Compare commits

..
1 Commits
Author SHA1 Message Date
kosmos c89c18db0c fix(daemon): run the long lanes off the tick path
android / release (pull_request) Skipped
android / debug (pull_request) Successful in 2m17s
ci / checks (pull_request) Successful in 1m3s
ci / test (pull_request) Successful in 39s
ci / chart (pull_request) Successful in 6s
ci / docker (pull_request) Successful in 1m30s
ci / web (pull_request) Successful in 13s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (pull_request) Skipped
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
`tick` awaited `forge_driver.run_once()` (and the jobs one before it), and
`Driver::run_once` awaits every run it admits. So while a turn was under
way the loop stopped doing everything else: no forge poll, no watch
health, no due task, no calendar reminder, no phone delivery. With a 60s
poll interval and a ten-minute turn, the daemon polled once per turn —
which is why `last_ok_at` sat frozen at 00:35:02 while the turn that
started at 00:35:03 ran. Not a network problem, and not the watch.

Worse in combination with a longer lease: an hour-long turn would freeze
detection for an hour.

Split the pass. The resident loop (`run`) now uses `resident_tick`, which
detects and then hands the forge and jobs passes to their own tasks; the
interactive drain stays inline, since its runs are the chat itself. One
pass per lane at a time — a tick that fires mid-pass leaves its events in
the dispatcher's inbox for the next one, which is the queue the
dispatcher already is; a second concurrent pass would only lose lease
acquisitions to the first. The in-flight flag is cleared by a drop guard,
so a panicking pass cannot strand its lane permanently.

`tick` keeps its exact shape and semantics: `--once` and the tests still
mean "the work happened" when a pass returns, and the forge-line log
(`[claw] pass: N detected, H handled, F failed`) is unchanged there. The
detached passes log without the detected count, which they do not own.
2026-11-22 01:14:52 +00:00
29 changed files with 149 additions and 929 deletions

No files matched your search

-1
View File
@@ -1,2 +1 @@
/target/
.rhema/
Generated
+54 -69
View File
@@ -1906,9 +1906,9 @@ dependencies = [
[[package]]
name = "rhema-autonomous-agent"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46677fb855ebb628da602111fa2595ad363401c7101c07f07a602dbc86a1dd8a"
checksum = "08fd6d5fe5f9551226d322491d03b14d5e42ac2ff73544c15a555fb97a04bbfd"
dependencies = [
"async-trait",
"rhema-core",
@@ -1922,9 +1922,9 @@ dependencies = [
[[package]]
name = "rhema-bash"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0aacc9aac461f674ec7f72dc321b11edc4c7868d3c635c2b1c58dbd9256c80"
checksum = "cf9ae34e5c556e0abdf279dd7d0aa08632bdcd68cff965bce2b81c226ada8f1e"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -1982,7 +1982,6 @@ dependencies = [
"rhema-rsd",
"rhema-sandbox",
"rhema-sandbox-http",
"rhema-sandbox-ssh",
"rhema-transcript",
"rusqlite",
"serde",
@@ -2007,9 +2006,9 @@ dependencies = [
[[package]]
name = "rhema-config"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a05d1d30472d7ea03685806b69e0e9984744b0349cc7c7ad53497916b6c2be1"
checksum = "a0bbfb885f219272d24534c004819db377cf5370de0f82a851f9329466a5349c"
dependencies = [
"keyring",
"rhema-core",
@@ -2021,9 +2020,9 @@ dependencies = [
[[package]]
name = "rhema-core"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de9d3c12019209170cbf82fa75dcad4ec10c3c712f7235d9f9a60f165cab5d8c"
checksum = "c3cd4c7a28b121243a2e26371e53750f28368e96c1a1629f021847c717e1cd55"
dependencies = [
"async-trait",
"serde",
@@ -2047,9 +2046,9 @@ dependencies = [
[[package]]
name = "rhema-host-agent"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "973dc8ee54a24065c7996b23e0cfd2eba715687394a248583582faca3d7a5c4c"
checksum = "3c10a82a420f1ea5ad1e68cabf0da67e6d05f18ec9e6fa02993969c2dcc53a68"
dependencies = [
"minijinja",
"rhema-bash",
@@ -2067,9 +2066,9 @@ dependencies = [
[[package]]
name = "rhema-identity"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3188f0fec1338df315c76034909e8ff7c1314a84ff6dd0ac11793d605d655b5b"
checksum = "f1bb799ae7395c647577b9cf26208d81c2913d893db050adc82976e88436226c"
dependencies = [
"rusqlite",
"serde",
@@ -2078,9 +2077,9 @@ dependencies = [
[[package]]
name = "rhema-mcp"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dd8f9ee0b0699c09efb303dfc17ed3049aabc8a7b3e01d211de283c43c8c19b"
checksum = "6ed674931827b5b5e3130b376bda837cf49bda6ca6c94392430b74e292b6f516"
dependencies = [
"async-stream",
"axum",
@@ -2105,9 +2104,9 @@ dependencies = [
[[package]]
name = "rhema-memory"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abdfee3e709305e86cedc3e60ca59776af512b2bf520ab87d7da1d184f01d560"
checksum = "34d3b6763b7c567849b6f1787bae7152ce92ec38bdbe2ec27691d4ef2596c259"
dependencies = [
"async-trait",
"rhema-core",
@@ -2119,9 +2118,9 @@ dependencies = [
[[package]]
name = "rhema-prompt"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ecbf1ae5d134d110c8f3b4c47ad2331f703bd7bb1ad6d53b4108787d894c8bd"
checksum = "b70bba0a045879067817db80fcaa7578dc32ef699786cc004b8fdb73bccc47e4"
dependencies = [
"minijinja",
"rhema-core",
@@ -2132,9 +2131,9 @@ dependencies = [
[[package]]
name = "rhema-provider"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15855c3fa2d858622cd55bd6323d4a7533066e52a74e3dc440ffe69c12ed1263"
checksum = "c400c1ac8430f78184ecc12024605686a988ada7a3ee30dd67a4ce12114ccb9e"
dependencies = [
"async-trait",
"futures-core",
@@ -2148,9 +2147,9 @@ dependencies = [
[[package]]
name = "rhema-provider-anthropic"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "223a60c52ce2e548f72a9f2cce6f7a48be954bd3e5b959ff70d308b3d42d6425"
checksum = "a57458493f5b1fb540fa47f558f7743094dc123d2c06815d2078f9303d9df22f"
dependencies = [
"async-trait",
"futures-util",
@@ -2164,9 +2163,9 @@ dependencies = [
[[package]]
name = "rhema-provider-chatgpt"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec84f3f5601e8ca6e69f92a291480842058352bb580b985ec23db713505b8f5d"
checksum = "7642b1e0bc194cc81d7f347182eecd6702a04a85de41912bd2d34b2cdf41ca7b"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2183,16 +2182,15 @@ dependencies = [
[[package]]
name = "rhema-provider-copilot"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6685a56017c7de21d17384d25f941f2733526d581dfafc5cd7371d4f6e82096"
checksum = "eb39fa7f059df415bdef2453e58ad5359fd74eeb39f7981179f03c78ffb5af7d"
dependencies = [
"async-trait",
"futures-util",
"reqwest",
"rhema-core",
"rhema-provider",
"rhema-provider-anthropic",
"rhema-provider-openai-compatible",
"serde",
"serde_json",
@@ -2202,9 +2200,9 @@ dependencies = [
[[package]]
name = "rhema-provider-google"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "749f27fcf2ad1c7745cabc85e56d05e116bce30b6be317910f0c455ba4147ff9"
checksum = "7dda76eea354cfbdfd4a2dfa1fc1ce8da823675699cf2bf4d3ace8560fec2cd7"
dependencies = [
"async-trait",
"futures-util",
@@ -2218,9 +2216,9 @@ dependencies = [
[[package]]
name = "rhema-provider-llama-cpp"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf5d26ec681baac6b8c6fc752470a78205acb11f763987bf571fa54be1195e2a"
checksum = "953181611b909688db511f891e8c59e034b90bd798034f1afef36cac05409566"
dependencies = [
"async-trait",
"futures-util",
@@ -2235,9 +2233,9 @@ dependencies = [
[[package]]
name = "rhema-provider-mistral"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d8ae3c2c924202d3614987b6b7c4930d84a19ebb2264747bb5100f1f67db7ff"
checksum = "1f657297d7d617a14b10bb6248e944d053d73a536d3b6ae4ee4cc8acabcb4a57"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2254,9 +2252,9 @@ dependencies = [
[[package]]
name = "rhema-provider-openai-compatible"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aab0c24d2d558d66de1f002c250d05c25d9c52038e4fa1890f6c40644c4f9702"
checksum = "a90f1620882b2a3dbdb00065b29c329622c5596f582027b29130fbd40003b450"
dependencies = [
"async-trait",
"futures-util",
@@ -2270,9 +2268,9 @@ dependencies = [
[[package]]
name = "rhema-provider-opencode"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eb4c641b7997ba5cab41bede6c4b7331baa9a9b2298d5bb0ffbc8844df6dbf3"
checksum = "2068c980362fe3d4f7876e5e842f51c0719626449afac64192592865e11a0108"
dependencies = [
"async-trait",
"reqwest",
@@ -2285,9 +2283,9 @@ dependencies = [
[[package]]
name = "rhema-provider-openrouter"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7170cef8b456c8f1df1b565d16ad3c61c4b252e521fff16718eacca5d7d98605"
checksum = "c2025f84d6a1fd1e513ffad4b374d280f0db600ffac635dfe08a58d04b03e91d"
dependencies = [
"async-trait",
"futures-util",
@@ -2301,9 +2299,9 @@ dependencies = [
[[package]]
name = "rhema-provider-registry"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c93ceacbe2332f122b23a11de11ddf4a502a96baaa8c95f33882c5c589581dce"
checksum = "be5ed790e3dc4fc3a42bd9b1a633ef72204c519810ce03dafb2792a8ff0b6bf8"
dependencies = [
"rhema-core",
"rhema-provider",
@@ -2321,9 +2319,9 @@ dependencies = [
[[package]]
name = "rhema-rsd"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e97a9d363b432147220a0646a158ea7a08d6012efa1bedf169fd973721dd745"
checksum = "3a4bd0555ff3720c0501187f5e9c6ee19ebebb95c1ecdb296c509c2e2dd971ce"
dependencies = [
"rhema-core",
"rusqlite",
@@ -2334,9 +2332,9 @@ dependencies = [
[[package]]
name = "rhema-sandbox"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d5aaa76f2400989439f325754a29593669c1275485796150e19b04277ea54fb"
checksum = "7030dbd46aa8a2398452dcf86b6b39d13b82909b9fdc654c49e1374183594779"
dependencies = [
"async-trait",
"rhema-bash",
@@ -2344,14 +2342,13 @@ dependencies = [
"serde",
"serde_json",
"thiserror",
"tokio",
]
[[package]]
name = "rhema-sandbox-http"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f4cbb9f2238961082a8b406da460c84ced75f4d6bb9e52a79b41dc17065b601"
checksum = "b5171470a8a56246e036aa10fc63e641ae7907a3ce70ac8f4816f3c9499eb75b"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2361,23 +2358,11 @@ dependencies = [
"serde_json",
]
[[package]]
name = "rhema-sandbox-ssh"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578252c65b6e8047b8f013d2d0a0bd867991b50ed31a530cdfa1304d158a6e65"
dependencies = [
"async-trait",
"base64 0.22.1",
"rhema-sandbox",
"tokio",
]
[[package]]
name = "rhema-session-store"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00548f40bf2ec40381d4f9d60a1e136c66d7c4c334097a5eebafe21169915f5c"
checksum = "ef2dd4aca030a56e438c136099d3f07d6fd4649a3db1be6c9838a68a6530cbf6"
dependencies = [
"rhema-core",
"serde",
@@ -2387,9 +2372,9 @@ dependencies = [
[[package]]
name = "rhema-session-store-file"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df75d21d1ad25b16cb72fc3747d435415e7423872b51fa3751094a5a6e380543"
checksum = "e5ff65f110123026ae79679572b084c517693f81e0d464897e580b64985a9507"
dependencies = [
"rhema-config",
"rhema-core",
@@ -2399,9 +2384,9 @@ dependencies = [
[[package]]
name = "rhema-submissions"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dba11599010c7537800bee275dd9d414162dd57806b1d75c54ef98f126eb9f65"
checksum = "d054ba904c324ef057c8fb4b9c88a40703496c8b621768844af56a8893d3fb99"
dependencies = [
"rhema-core",
"rhema-session-store",
@@ -2412,9 +2397,9 @@ dependencies = [
[[package]]
name = "rhema-transcript"
version = "0.4.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "592b80da0bf1c84e4da814639383dc33c5d2eeee522db5bd93bb779bf0e34e10"
checksum = "800261e8c1f29e6ceee48769bba2aaea19ccd3496ff8c6c76c617aa7d53ec2db"
dependencies = [
"async-trait",
"rhema-core",
+18 -19
View File
@@ -29,34 +29,33 @@ mock = ["rhema-core/mock"]
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.1"
rhema-prompt = "0.4.1"
rhema-host-agent = "0.4.1"
rhema-autonomous-agent = "0.4.1"
rhema-config = "0.4.1"
rhema-core = "0.4.1"
rhema-bash = "0.4.0"
rhema-prompt = "0.4.0"
rhema-host-agent = "0.4.0"
rhema-autonomous-agent = "0.4.0"
rhema-config = "0.4.0"
rhema-core = "0.4.0"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.1"
rhema-transcript = "0.4.0"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = "0.4.1"
rhema-rsd = "0.4.1"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box
rhema-sandbox = "0.4.1"
rhema-sandbox-http = "0.4.1"
rhema-sandbox-ssh = "0.4.1"
rhema-identity = "0.4.0"
rhema-rsd = "0.4.0"
# The sandbox seam: where `bash` runs, local process or a daemon speaking
# the wire protocol over HTTP
rhema-sandbox = "0.4.0"
rhema-sandbox-http = "0.4.0"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.4.1"
rhema-memory = "0.4.0"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.1"
rhema-provider-registry = "0.4.1"
rhema-provider = "0.4.0"
rhema-provider-registry = "0.4.0"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -81,7 +80,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.22"
rhema-mcp = "0.4.1"
rhema-mcp = "0.4.0"
[dev-dependencies]
tempfile = "3"
@@ -93,7 +92,7 @@ reqwest = { version = "0.12", features = ["json", "stream"] }
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.4.1", features = ["mock"] }
rhema-core = { version = "0.4.0", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+6 -13
View File
@@ -70,11 +70,9 @@ token: change-me # optional; when set, /v1/* requires it
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
sandbox: # where bash runs; omit for this host
kind: ssh # local (default), http, or ssh
host: me@box.example # the ssh destination: an alias or user@host
workspace: /srv/claw # ssh only: the workspace base, default /root
# http instead speaks the sandbox protocol (rhema-sandboxd):
# kind: http, url: https://box.example:7600, token: sandbox-secret
kind: http # local (default) or http
url: https://box.example:7600 # the sandboxd base URL
token: sandbox-secret # the daemon's shared secret, if it has one
poll_interval_secs: 120
max_turn_steps: 2048 # tool rounds one chat turn may run
watches: # a seed: imported while the table is empty
@@ -105,15 +103,10 @@ conversation intact; a follow-up message keeps going.
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
keeps the daemon's own processes. `kind: http` sends commands to a host
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
optional `token`. `kind: ssh` runs commands on a login the local `ssh`
config resolves (`host`, any alias or `user@host`), nothing installed
on the far end; `workspace` names the remote directory the claw's
workspaces live under, `/root` by default, one directory per claw
workspace under it. The settings screen writes the same choice to the
optional `token`. The settings screen writes the same choice to the
settings table, and the next turn reads it; no restart is needed. On
first use the claw copies the local workspace into the sandbox's
workspace root. Later edits stay there; the claw does not copy them
back.
`/workspace`. Later edits stay there; the claw does not copy them back.
The surface refuses to start on a non-loopback `listen` with no
`token`: anything beyond loopback can reach the port, and the bearer
@@ -157,7 +150,7 @@ GET /v1/attachments/{id} an attached file's bytes
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
GET /v1/sandbox where the agent's bash runs
PUT /v1/sandbox {"kind","url"?,"token"?,"host"?,"workspace"?}, switch and persist
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
GET /v1/providers the backend instances + the active pair
PUT /v1/providers/active {"provider","model"?} — switch, persisted
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
+2 -35
View File
@@ -464,15 +464,6 @@ sandbox:
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
let config: ClawConfig = serde_yaml::from_str(
"sandbox:\n kind: ssh\n host: me@box.example\n workspace: /srv/claw\n",
)
.expect("the ssh sandbox parses");
let sandbox = config.sandbox.expect("the sandbox parses");
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Ssh);
assert_eq!(sandbox.host.as_deref(), Some("me@box.example"));
assert_eq!(sandbox.workspace.as_deref(), Some("/srv/claw"));
}
#[test]
@@ -481,7 +472,7 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: None,
..crate::sandbox::SandboxChoice::default()
token: None,
}),
..ClawConfig::default()
};
@@ -493,37 +484,13 @@ sandbox:
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Http,
url: Some("https://box.example:7600".to_owned()),
..crate::sandbox::SandboxChoice::default()
token: None,
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a complete remote choice passes");
}
#[test]
fn an_ssh_sandbox_needs_a_host_at_boot() {
let missing = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
"an ssh sandbox without a host is refused at boot"
);
let valid = ClawConfig {
sandbox: Some(crate::sandbox::SandboxChoice {
kind: crate::sandbox::SandboxKind::Ssh,
host: Some("me@box.example".to_owned()),
..crate::sandbox::SandboxChoice::default()
}),
..ClawConfig::default()
};
assert!(valid.validate().is_ok(), "a bare login is all ssh needs");
}
#[test]
fn an_unknown_key_is_rejected_and_named() {
let err = serde_yaml::from_str::<ClawConfig>("listne: 127.0.0.1:7799\n")
+3 -41
View File
@@ -127,30 +127,6 @@ fn interactive_dispatch() -> DispatcherConfig {
}
}
/// The forge dispatcher's timing: the library defaults, except the lease
/// TTL.
///
/// A forge turn is not a chat step. The handler clones a repository,
/// reads it, and may build and test a fix — tens of minutes of wall
/// clock — and nothing renews the lease once the turn is under way:
/// `SessionContext::poll_inbox` renews, and the handler calls it once, at
/// the start; the commit hook that runs between tool calls *checkpoints*,
/// which fails on a lapsed lease instead of extending one. So the TTL is
/// a hard ceiling on a whole turn: cross it and the turn dies on its next
/// tool call, after which the driver's own checkpoint and release both
/// report `Expired` and the key ends with no outcome recorded — a silent
/// kill, indistinguishable from a pass that found nothing.
///
/// `DispatcherConfig::default`'s ten minutes are the spec's example
/// values, sized for a single agent step. An hour matches the
/// interactive lane's choice for the same reason: the work is long.
pub fn forge_dispatch() -> DispatcherConfig {
DispatcherConfig {
lease_ttl_millis: 3_600_000,
..DispatcherConfig::default()
}
}
/// Hands one driver pass to its own task, so a turn does not stop the
/// clock.
///
@@ -236,8 +212,8 @@ impl Daemon {
/// Assembles the daemon over `config`: the shared SQLite store, one
/// source per forge kind reading the watch table, the interactive
/// dispatcher, and both handlers running `provider`. `dispatch` is
/// the forge dispatcher's timing — [`forge_dispatch`] in both shapes,
/// with `--once` zeroing the debounce.
/// the forge dispatcher's timing — the resident loop uses the
/// defaults, `--once` zeroes the debounce.
pub fn build(
config: &ClawConfig,
backends: Arc<BackendRegistry>,
@@ -705,7 +681,7 @@ pub async fn run_once(
) -> Result<TickReport, ClawError> {
let dispatch = DispatcherConfig {
debounce_window_millis: 0,
..forge_dispatch()
..DispatcherConfig::default()
};
let daemon = Daemon::build(config, backends, dispatch)?;
daemon.bootstrap().await?;
@@ -798,20 +774,6 @@ mod tests {
assert_eq!(handler.runs.load(Ordering::SeqCst), 1, "one pass, not two");
}
#[test]
fn the_forge_dispatcher_leases_for_a_turn_not_a_step() {
let dispatch = forge_dispatch();
assert_eq!(
dispatch.lease_ttl_millis, 3_600_000,
"an hour: a turn clones, reads, builds and tests"
);
assert_eq!(
dispatch.debounce_window_millis,
DispatcherConfig::default().debounce_window_millis,
"the rest stays the library's defaults"
);
}
#[test]
fn the_interactive_dispatcher_dispatches_now_and_leases_long() {
let dispatch = interactive_dispatch();
-77
View File
@@ -565,22 +565,6 @@ impl ForgeSource {
fed += 1;
}
}
// The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning
// it. Deciding without consuming is a loop: the poll's cursor
// never passes a row the forge still considers unread, so
// every pass re-decides it and re-dispatches a turn for a
// thread that already has one, and a restart (the cursor is
// in memory) replays the whole unread feed.
//
// Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on.
if let Err(err) = client.mark_read(notification).await {
eprintln!(
"[claw] warning: mark-read of {} failed: {err}",
notification.id
);
}
}
if let Some(cursor) = page.cursor {
self.account_cursors
@@ -705,65 +689,6 @@ mod tests {
);
}
/// The account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still
/// considers unread, and a restart asks for the whole unread feed
/// again — so a row that is triaged but not marked read comes back
/// with the same dedup id on the next pass, and every pass dispatches
/// a fresh turn for a thread that already has one.
#[tokio::test]
async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
{
"id": 42188,
"unread": true,
"reason": "mention",
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": "https://api.github.com/repos/acme/widgets/pulls/142",
"type": "PullRequest"
},
"repository": { "full_name": "acme/widgets" }
}
])))
.mount(&server)
.await;
let store = Arc::new(ClawStore::in_memory().expect("store opens"));
let (dispatcher, accounts, notifications) = test_parts(store.clone());
// The store mints the id; the watch row is what names it.
let account = accounts
.put(rhema_identity::AccountDraft::new(
"forge bot",
"github",
rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"),
))
.expect("account lands");
store
.add_account_watch("github", Some(&server.uri()), &account.id)
.expect("account watch lands");
let source = ForgeSource::new(&dispatcher, "github", store, accounts, notifications);
assert_eq!(
source.detect().await.expect("the pass runs"),
1,
"a mention dispatches a turn"
);
// The read route keys on the notification, not the thread.
let requests = server.received_requests().await.expect("recording is on");
let reads: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(reads.len(), 1, "one mark-read per triaged row");
assert_eq!(reads[0].url.path(), "/notifications/threads/42188");
}
/// The parts a test source polls through, all in memory.
fn test_parts(
store: Arc<ClawStore>,
@@ -1047,7 +972,6 @@ mod tests {
title: Some("Add the flange".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
};
let payload = |notification: &Notification| {
@@ -1092,7 +1016,6 @@ mod tests {
title: Some("a title".to_owned()),
url: None,
timestamp: Timestamp::parse("2026-11-21T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
-1
View File
@@ -977,7 +977,6 @@ mod tests {
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-03T09:00:00Z",
"read_key": "42188",
"raw": {},
}))
.expect("notification fixture parses")
-10
View File
@@ -2016,8 +2016,6 @@ fn sandbox_json(state: &ClawState) -> Value {
"kind": choice.kind.as_str(),
"url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"host": choice.host,
"ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(),
"local_workspace": state.sandbox().local_workspace().display().to_string(),
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
@@ -2053,14 +2051,6 @@ async fn sandbox_put(
.map(str::to_owned)
.or_else(|| current.url.clone()),
token,
host: body["host"]
.as_str()
.map(str::to_owned)
.or_else(|| current.host.clone()),
workspace: body["workspace"]
.as_str()
.map(str::to_owned)
.or_else(|| current.workspace.clone()),
};
state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
+1 -1
View File
@@ -108,7 +108,7 @@ pub use bootstrap::{
render_system,
};
pub use config::{ClawConfig, ConfigError};
pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once};
pub use daemon::{ClawError, Daemon, TickReport, run_once};
pub use environment::write_report;
pub use extension::{ClawExtension, ExtensionDeps, Extensions, Lanes};
pub use forge::ForgeSource;
+3 -3
View File
@@ -8,8 +8,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use rhema_claw::{ClawConfig, ClawError, Daemon, forge_dispatch, run_once};
use rhema_rsd::Outcome;
use rhema_claw::{ClawConfig, ClawError, Daemon, run_once};
use rhema_rsd::{DispatcherConfig, Outcome};
/// `rhema-claw` — the resident forge-watching agent daemon.
#[derive(Debug, Parser)]
@@ -135,7 +135,7 @@ async fn run(args: Args) -> Result<(), ClawError> {
// reads it next to the config that turns it on.
config.validate_surface()?;
eprintln!("[claw] note: resident sessions run tool calls without approval prompts");
let daemon = Daemon::build(&config, backends, forge_dispatch())?;
let daemon = Daemon::build(&config, backends, DispatcherConfig::default())?;
daemon.run().await
}
}
+43 -240
View File
@@ -1,18 +1,16 @@
//! Where the claw's `bash` runs: this host's processes, a daemon
//! speaking the sandbox protocol over HTTP, or an ssh login on a far
//! box.
//! Where the claw's `bash` runs: this host's processes, or a daemon
//! speaking the sandbox protocol over HTTP.
//!
//! The choice is deployment state, persisted in the settings table and
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end. The tool spec, approval gate,
//! output caps, and error shaping stay in `ShellTools`; only the
//! machine changes.
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
//! and gives the handlers a `ShellSandbox` executor over it. The tool
//! spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//!
//! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes the workspace root and, when it is
//! empty, sends the host workspace as a tarball through the seed
//! workspace, the executor probes `/workspace` and, when it is empty,
//! sends the host workspace as a tarball through the protocol's seed
//! route. Later edits stay in the sandbox; the claw does not copy them
//! back.
@@ -27,7 +25,6 @@ use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
use crate::settings::SettingsStore;
@@ -35,15 +32,10 @@ use crate::settings::SettingsStore;
/// The settings key the chosen sandbox is persisted under.
pub const SANDBOX_KEY: &str = "sandbox";
/// The workspace path the http sandbox exposes: one root per session,
/// The workspace path a remote sandbox exposes: one root per session,
/// fixed by the protocol.
pub const REMOTE_WORKSPACE: &str = "/workspace";
/// The ssh sandbox's default workspace base: the remote login's own
/// home, the ssh backend's documented default. One directory per claw
/// workspace lands under it, named by the session hash.
pub const SSH_WORKSPACE_ROOT: &str = "/root";
/// The per-command budget of the emptiness probe before a seed: long
/// enough for a fresh sandbox, short enough that an unreachable daemon
/// fails the turn rather than stalling it.
@@ -58,8 +50,6 @@ pub enum SandboxKind {
Local,
/// A host speaking the sandbox protocol over HTTP.
Http,
/// A remote login reached with `ssh`, no daemon on the far end.
Ssh,
}
impl SandboxKind {
@@ -68,7 +58,6 @@ impl SandboxKind {
match self {
Self::Local => "local",
Self::Http => "http",
Self::Ssh => "ssh",
}
}
@@ -78,7 +67,6 @@ impl SandboxKind {
match value {
"local" => Some(Self::Local),
"http" => Some(Self::Http),
"ssh" => Some(Self::Ssh),
_ => None,
}
}
@@ -98,14 +86,6 @@ pub struct SandboxChoice {
/// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// The `ssh` sandbox's destination, passed to `ssh` as-is: any
/// alias or `user@host` the local config resolves.
#[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
}
impl SandboxChoice {
@@ -121,32 +101,6 @@ impl SandboxChoice {
.token
.map(|token| token.trim().to_owned())
.filter(|token| !token.is_empty());
self.host = self
.host
.map(|host| host.trim().to_owned())
.filter(|host| !host.is_empty());
self.workspace = self
.workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty());
if self.kind == SandboxKind::Ssh {
let host = self
.host
.as_deref()
.ok_or_else(|| SandboxError::Invalid("the ssh sandbox needs a host".to_owned()))?;
if host.contains(char::is_whitespace) {
return Err(SandboxError::Invalid(
"the ssh sandbox host is one destination, no spaces".to_owned(),
));
}
if let Some(workspace) = self.workspace.as_deref()
&& !workspace.starts_with('/')
{
return Err(SandboxError::Invalid(
"the ssh sandbox workspace must be an absolute path".to_owned(),
));
}
}
if self.kind == SandboxKind::Http {
let url = self
.url
@@ -163,22 +117,7 @@ impl SandboxChoice {
/// Whether commands leave this host.
pub fn is_remote(&self) -> bool {
self.kind != SandboxKind::Local
}
/// The remote directory one workspace's commands run in: the
/// protocol root for `http`, a directory per host workspace under
/// the configured base for `ssh`.
pub fn remote_root(&self, host: &Path) -> PathBuf {
match self.kind {
SandboxKind::Http => PathBuf::from(REMOTE_WORKSPACE),
SandboxKind::Ssh => PathBuf::from(format!(
"{}/{}",
self.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT),
session_name(host)
)),
SandboxKind::Local => host.to_path_buf(),
}
self.kind == SandboxKind::Http
}
}
@@ -200,7 +139,7 @@ pub struct SandboxState {
settings: Arc<SettingsStore>,
local_workspace: PathBuf,
local: Arc<dyn ShellExecutor>,
remote: Mutex<HashMap<String, Arc<dyn Sandbox>>>,
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
}
impl SandboxState {
@@ -265,9 +204,13 @@ impl SandboxState {
}
/// The workspace a handler should name and start commands in: the
/// host path locally, the choice's remote root otherwise.
/// host path locally, `/workspace` on a remote sandbox.
pub fn workspace_for(&self, host: &Path) -> PathBuf {
self.choice().remote_root(host)
if self.is_remote() {
PathBuf::from(REMOTE_WORKSPACE)
} else {
host.to_path_buf()
}
}
/// The chat workspace under the current choice, for the settings
@@ -296,14 +239,18 @@ impl SandboxState {
})
}
/// The cached sandbox for one session. The map is cleared whenever
/// the choice changes, so a new URL, token, host, or base builds a
/// new client.
/// The cached HTTP client for one session. The map is cleared
/// whenever the choice changes, so a new URL or token builds a new
/// client.
fn remote_sandbox(
&self,
choice: &SandboxChoice,
host: &Path,
) -> Result<Arc<dyn Sandbox>, ShellError> {
) -> Result<Arc<HttpSandbox>, ShellError> {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let session = session_name(host);
{
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
@@ -311,31 +258,8 @@ impl SandboxState {
return Ok(sandbox.clone());
}
}
let sandbox: Arc<dyn Sandbox> = match choice.kind {
SandboxKind::Http => {
let url = choice
.url
.as_deref()
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
}
SandboxKind::Ssh => {
let dest = choice
.host
.as_deref()
.ok_or_else(|| ShellError::Failed("the ssh sandbox has no host".to_owned()))?;
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
Arc::new(
SshSandbox::new(dest.to_owned()).with_workspace(format!("{base}/{session}")),
)
}
SandboxKind::Local => {
return Err(ShellError::Failed(
"the local sandbox needs no remote client".to_owned(),
));
}
};
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
self.remote
.lock()
.unwrap_or_else(PoisonError::into_inner)
@@ -356,32 +280,20 @@ struct ClawShell {
}
impl ClawShell {
/// Seeds the sandbox once per choice. An empty workspace root gets
/// Seeds the sandbox once per choice. An empty `/workspace` gets
/// the host workspace as a tarball; a non-empty one is left alone
/// so a restart never overwrites work done in the sandbox. The
/// probe makes the root first: the http daemon keeps one, the ssh
/// far end has none until something makes it, and the unpack's
/// `tar -C` would fail on a missing directory.
/// so a restart never overwrites work done in the sandbox.
async fn seed(
&self,
sandbox: &Arc<dyn Sandbox>,
sandbox: &Arc<HttpSandbox>,
cancelled: &AtomicBool,
) -> Result<(), ShellError> {
let root = self
.state
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = |_line: &str| {};
let probe = sandbox
.exec(
ExecRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone(),
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
cwd: REMOTE_WORKSPACE.to_owned(),
timeout: PROBE_TIMEOUT,
},
cancelled,
@@ -441,9 +353,15 @@ impl ShellExecutor for ClawShell {
self.seed(&sandbox, cancelled).await?;
self.seeded.store(true, Ordering::Relaxed);
}
let root = choice.remote_root(&self.host_workspace);
let sandbox: Arc<dyn Sandbox> = sandbox;
ShellSandbox::new(sandbox)
.run(command, &root, timeout, cancelled, progress)
.run(
command,
Path::new(REMOTE_WORKSPACE),
timeout,
cancelled,
progress,
)
.await
}
}
@@ -461,13 +379,6 @@ fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
}
}
/// One path quoted for the remote `bash -c`: single quotes, the
/// closing quote spliced, good for every path a workspace root can
/// have.
fn shquote(path: &str) -> String {
format!("'{}'", path.replace('\'', "'\\''"))
}
/// The sandbox session name for one host workspace: a stable FNV-1a
/// hash of the path, so the daemon can multiplex one root per session
/// and a restart finds the same root.
@@ -547,7 +458,7 @@ mod tests {
let missing = SandboxChoice {
kind: SandboxKind::Http,
url: None,
..SandboxChoice::default()
token: None,
}
.normalized();
assert!(missing.is_err(), "a URL is required");
@@ -555,63 +466,18 @@ mod tests {
let relative = SandboxChoice {
kind: SandboxKind::Http,
url: Some("box.example:7600".to_owned()),
..SandboxChoice::default()
token: None,
}
.normalized();
assert!(relative.is_err(), "a bare host is not a URL");
}
#[test]
fn an_ssh_choice_needs_a_host_and_an_absolute_base() {
let missing = SandboxChoice {
kind: SandboxKind::Ssh,
..SandboxChoice::default()
}
.normalized();
assert!(missing.is_err(), "a host is required");
let spaced = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me @box".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(spaced.is_err(), "a destination is one word");
let relative = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("srv/claw".to_owned()),
..SandboxChoice::default()
}
.normalized();
assert!(relative.is_err(), "the base is an absolute path");
let good = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some(" me@box ".to_owned()),
workspace: Some("/srv/claw/".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(good.host.as_deref(), Some("me@box"));
assert_eq!(good.workspace.as_deref(), Some("/srv/claw"));
assert!(good.is_remote());
assert_eq!(good.kind.as_str(), "ssh");
assert_eq!(
SandboxKind::parse("ssh"),
Some(SandboxKind::Ssh),
"the stored spelling round-trips"
);
}
#[test]
fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some("http://box:7600/".to_owned()),
..SandboxChoice::default()
token: None,
});
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
assert_eq!(
@@ -621,36 +487,6 @@ mod tests {
);
}
#[test]
fn an_ssh_workspace_is_one_directory_per_host_workspace() {
let host = PathBuf::from("/state/claw/workspaces/interactive");
let choice = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
};
let root = choice.remote_root(&host);
let root = root.to_string_lossy().to_string();
assert!(
root.starts_with("/srv/claw/rhema-claw-"),
"the root lives under the configured base: {root}"
);
assert_eq!(root.len(), "/srv/claw/rhema-claw-".len() + 16);
let default_root = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
..SandboxChoice::default()
}
.remote_root(&host);
assert_eq!(
default_root.to_string_lossy(),
format!("/root/{}", session_name(&host)),
"the base defaults to the login's home"
);
}
#[test]
fn a_choice_persists_and_reloads() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
@@ -668,7 +504,6 @@ mod tests {
kind: SandboxKind::Http,
url: Some("https://box:7600".to_owned()),
token: Some("secret".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
@@ -680,38 +515,6 @@ mod tests {
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
}
#[test]
fn an_ssh_choice_persists_with_its_host_and_base() {
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
let state = SandboxState::load(
settings.clone(),
None,
PathBuf::from("/tmp/ws"),
&BTreeMap::new(),
)
.expect("the state loads");
state
.set(SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
workspace: Some("/srv/claw".to_owned()),
..SandboxChoice::default()
})
.expect("the choice saves");
let reloaded =
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
.expect("the state reloads");
assert_eq!(reloaded.choice().kind, SandboxKind::Ssh);
assert_eq!(reloaded.choice().host.as_deref(), Some("me@box"));
assert_eq!(reloaded.choice().workspace.as_deref(), Some("/srv/claw"));
assert_eq!(
reloaded.workspace().to_string_lossy(),
format!("/srv/claw/{}", session_name(Path::new("/tmp/ws"))),
"the settings surface reports the session root"
);
}
#[tokio::test]
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
let server = MockServer::start().await;
@@ -753,7 +556,7 @@ mod tests {
let state = state(SandboxChoice {
kind: SandboxKind::Http,
url: Some(server.uri()),
..SandboxChoice::default()
token: None,
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
-60
View File
@@ -2431,66 +2431,6 @@ async fn the_sandbox_choice_is_listed_and_switchable() {
assert_eq!(cleared["url"], "https://box.example:7600");
}
/// The ssh sandbox over the surface: a choice without a host is a 400,
/// a complete one lists its host and reports the workspace under the
/// configured base, and switching back to this host keeps the ssh
/// fields staged for the next switch.
#[tokio::test]
async fn the_ssh_sandbox_is_switchable_over_the_surface() {
let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build(
&config(&dir, None),
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
rhema_rsd::DispatcherConfig::default(),
)
.expect("the daemon assembles");
let base = serve(&daemon).await;
let client = reqwest::Client::new();
let refused = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh"}))
.send()
.await
.expect("the refusal posts");
assert_eq!(refused.status(), 400, "an ssh choice without a host");
let switched: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "workspace": "/srv/claw"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(switched["kind"], "ssh");
assert_eq!(switched["host"], "me@box.example");
let workspace = switched["workspace"].as_str().expect("the workspace reads");
assert!(
workspace.starts_with("/srv/claw/rhema-claw-"),
"the workspace sits under the configured base: {workspace}"
);
// Back to this host: the workspace flips, the ssh fields stay
// staged for the next switch.
let local: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "local"}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(local["kind"], "local");
assert_eq!(local["host"], "me@box.example");
assert!(
local["workspace"].as_str().expect("the workspace reads") != workspace,
"the workspace path follows the choice"
);
}
/// The agent identity surface: the text fields round-trip with
/// partial-save semantics (an absent field is left alone, an empty one
/// clears), the avatar uploads and serves back with its content type,
+1 -1
View File
@@ -48,7 +48,7 @@ FROM debian:stable-slim
# bash and git are load-bearing, not conveniences: the coding agent shells
# out via `bash -c` and clones/fetches in its per-thread workspaces.
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
+1 -1
View File
@@ -67,7 +67,7 @@ FROM debian:stable-slim
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
# neither).
RUN apt-get update \
&& apt-get install -y --no-install-recommends bash curl git tar ca-certificates \
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
@@ -15,10 +15,10 @@ publish = false
rusqlite = { version = "0.40", features = ["bundled"] }
# The reminder source: one `Source` over the feeds, detect-pass shaped
# like the task scheduler's
rhema-autonomous-agent = "0.4.1"
rhema-autonomous-agent = "0.4.0"
# The reminder source ingests its slots into a `Dispatcher`; the event
# and key-function shapes are the dispatcher's
rhema-rsd = "0.4.1"
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -13,7 +13,7 @@ publish = false
[dependencies]
# The dispatch seam: watches ingest into a Dispatcher
rhema-rsd = "0.4.1"
rhema-rsd = "0.4.0"
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -230,17 +230,6 @@ pub struct Notification {
/// When the notification row was last touched. The poll cursor
/// advances to the newest of these.
pub timestamp: Timestamp,
/// What the backend's read-marking route keys on, when it has one —
/// GitHub's `PUT /notifications/threads/{id}` takes the numeric
/// notification id, which [`Notification::id`] embeds only as text
/// (its suffix is the dedup timestamp, not the row's identity).
/// `None` on a backend with no read route.
///
/// Defaulted on deserialize: rows already in a dispatcher inbox were
/// written before this field existed, and a replay must not fail on
/// one.
#[serde(default)]
pub read_key: Option<String>,
/// The untouched wire row, minus the keys the notification lifts.
pub raw: serde_json::Value,
}
@@ -16,9 +16,7 @@
use async_trait::async_trait;
use crate::error::ForgeError;
use crate::event::{
ForgeEvent, ForgeThreadKind, Notification, NotificationPage, RepoRef, Snapshot, Timestamp,
};
use crate::event::{ForgeEvent, ForgeThreadKind, NotificationPage, RepoRef, Snapshot, Timestamp};
/// One poll's worth of activity, with the cursor to continue from.
#[derive(Debug, Clone, PartialEq)]
@@ -102,25 +100,6 @@ pub trait Forge: Send + Sync {
since: Option<&Timestamp>,
) -> Result<NotificationPage, ForgeError>;
/// Marks `notification` read on the forge, so the account's feed
/// stops returning it.
///
/// The feed is at-least-once: `since` is inclusive at the boundary
/// and the cursor only ever advances to the newest row seen, so a row
/// that the poll cannot get past — anything at or before the cursor,
/// every poll — comes back for as long as the forge considers it
/// unread. Dedup ids absorb a repeat *within* one pass, but a row
/// re-read on the next pass is a fresh event with the same id, and a
/// restart drops the in-memory cursor entirely and asks for the whole
/// unread feed again. Deciding a row is therefore not the same as
/// consuming it; this is the call that consumes it.
///
/// The default is a no-op: a backend with no read route repeats its
/// rows, which its dedup ids absorb — noisier, never wrong.
async fn mark_read(&self, _notification: &Notification) -> Result<(), ForgeError> {
Ok(())
}
/// The login this client authenticates as — the backend's own answer
/// to "who am I".
///
@@ -585,9 +585,6 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -120,17 +120,6 @@ impl GitHubForge {
}
}
/// A PUT builder for `path` with auth applied.
fn put(&self, path: &str) -> reqwest::RequestBuilder {
let base = &self.base_url;
let request = self.http.put(format!("{base}{path}"));
if self.token.is_empty() {
request
} else {
request.bearer_auth(&self.token)
}
}
/// Follows `per_page`/`page` pagination until a short page.
async fn paged<T: DeserializeOwned>(
&self,
@@ -520,9 +509,6 @@ fn notification_event(row: &WireNotification) -> Result<Option<Notification>, Fo
title: subject.title.clone(),
url: None,
timestamp: updated,
// `PUT /notifications/threads/{id}` is keyed on this same id:
// the notification, not the thread's number.
read_key: Some(id.to_string()),
raw: Value::Object(row.raw.clone()),
}))
}
@@ -750,22 +736,6 @@ impl Forge for GitHubForge {
}
Ok(NotificationPage::finish(notifications, since))
}
async fn mark_read(&self, notification: &Notification) -> Result<(), ForgeError> {
let Some(read_key) = notification.read_key.as_deref() else {
// A row built without one is a shape break, not a forge
// outage: say so instead of silently re-reading it forever.
return Err(ForgeError::Parse(format!(
"notification {} carries no read key",
notification.id
)));
};
let path = format!("/notifications/threads/{read_key}");
let response = self.put(&path).send().await.map_err(ForgeError::network)?;
// 205 Reset Content: marked, nothing to decode.
ensure_success(response).await?;
Ok(())
}
}
#[cfg(test)]
@@ -957,7 +927,6 @@ mod tests {
notification.id,
"github:notification:27210544329@2026-11-21T22:33:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("27210544329"));
}
#[test]
@@ -978,7 +947,6 @@ mod tests {
notification.id,
"github:notification:42188@2026-10-08T12:00:00Z"
);
assert_eq!(notification.read_key.as_deref(), Some("42188"));
}
#[test]
@@ -331,9 +331,6 @@ fn todo_notification(row: &WireTodo) -> Result<Option<Notification>, ForgeError>
title: target.title.clone(),
url: row.target_url.clone(),
timestamp: updated,
// No read-marking route in this backend yet; the feed's repeat is
// absorbed by the dedup id.
read_key: None,
raw: Value::Object(row.raw.clone()),
}))
}
@@ -97,7 +97,6 @@ mod tests {
title: None,
url: None,
timestamp: Timestamp::parse("2026-10-08T00:00:00Z").expect("parses"),
read_key: Some("1".to_owned()),
raw: serde_json::json!({}),
}
}
@@ -2,8 +2,8 @@
//! wiremock server. Zero network.
use rhema_forge_integration::{
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, Notification, NotificationReason,
RepoRef, Timestamp,
EventKind, Forge, ForgeError, ForgeThreadKind, GitHubForge, NotificationReason, RepoRef,
Timestamp,
};
use serde_json::{Value, json};
use wiremock::matchers::{header, method, path, query_param};
@@ -533,89 +533,6 @@ async fn notifications_without_a_cursor_still_return_the_newest_seen() {
);
}
/// A notification row, as the account's feed sends it.
fn notification_row(id: i64, reason: &str, number: u64) -> Value {
json!({
"id": id,
"unread": true,
"reason": reason,
"updated_at": "2026-10-05T12:00:00Z",
"subject": {
"title": "Add the widget flange",
"url": format!("https://api.github.com/repos/acme/widgets/issues/{number}"),
"type": "Issue"
},
"repository": { "full_name": "acme/widgets" }
})
}
/// Deciding a row is not consuming it: the feed keeps returning anything
/// the account still has unread, so the read route is what ends the
/// repeat. It keys on the notification's own id, not the thread number —
/// the dedup id keeps that integer only as text.
#[tokio::test]
async fn marking_a_notification_read_puts_its_thread() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/notifications"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!([notification_row(
42188,
"review_requested",
142
)])),
)
.mount(&server)
.await;
Mock::given(method("PUT"))
.and(path("/notifications/threads/42188"))
.and(header("authorization", "Bearer tok"))
.respond_with(ResponseTemplate::new(205))
.mount(&server)
.await;
let forge = forge(&server);
let page = forge.notifications(None).await.expect("poll succeeds");
let notification = &page.notifications[0];
forge.mark_read(notification).await.expect("marks read");
let requests = server.received_requests().await.expect("recording is on");
let puts: Vec<_> = requests
.iter()
.filter(|request| request.method.as_str() == "PUT")
.collect();
assert_eq!(puts.len(), 1, "one read call, on the row's id");
assert_eq!(puts[0].url.path(), "/notifications/threads/42188");
}
/// A row that reaches the caller with no read key is a shape break, not a
/// silent no-op: re-reading the same thread forever is the failure this
/// whole route exists to stop.
#[tokio::test]
async fn a_notification_without_a_read_key_fails_loudly() {
// Defaulted on deserialize, so this is also the row an inbox written
// before the field existed decodes to.
let notification: Notification = serde_json::from_value(json!({
"id": "github:notification:42188@2026-10-05T12:00:00Z",
"reason": "review_requested",
"repo": { "owner": "acme", "name": "widgets" },
"number": 142,
"is_pr": false,
"actor": null,
"title": "Add the widget flange",
"url": null,
"timestamp": "2026-10-05T12:00:00Z",
"raw": {}
}))
.expect("a read-key-less row parses");
let err = GitHubForge::new("tok")
.mark_read(&notification)
.await
.expect_err("loud failure");
assert!(matches!(err, ForgeError::Parse(_)), "got: {err:?}");
}
/// The mention gate asks the forge who the credential is, because a token
/// read from a watch row names nobody.
#[tokio::test]
+1 -5
View File
@@ -523,11 +523,7 @@ async function saveSandbox(choice: SandboxSelection): Promise<void> {
try {
sandboxState.value = await claw.setSandbox(choice)
pushNotice(
choice.kind === 'http'
? 'sandbox: remote host'
: choice.kind === 'ssh'
? 'sandbox: ssh host'
: 'sandbox: this machine',
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
)
apiError.value = null
} catch (err) {
-40
View File
@@ -519,10 +519,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
@download-attachment="(id, name) => emit('downloadAttachment', id, name)"
/>
<AppMarkdown v-if="live.reply" :text="live.reply" streaming class="reply" />
<p v-if="!live.reply" class="working" role="status">
<span class="spinner" aria-hidden="true" />
{{ agentName }} is working…
</p>
</div>
</div>
</div>
@@ -759,42 +755,6 @@ function streamTone(status: StreamStatus): 'ok' | 'warn' | 'error' {
color: var(--accent-text);
}
/* While the turn runs but no reply text has landed yet. Tool rows and
the thinking trace never render on this surface, so this line is the
turn's only pulse between its first event and its first delta — the
streaming cursor takes over once text arrives, and the line goes.
Reduced motion gets the static ring. */
.working {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0 0;
color: var(--text3);
font-size: 12.5px;
}
.spinner {
flex: none;
width: 12px;
height: 12px;
border: 2px solid var(--border-strong);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
/* A consent card: the agent asking its human something — distinct
from a tool row, toned by its resolution. */
.consent-card {
+3 -64
View File
@@ -7,10 +7,6 @@
// new key lands in the inventory. The delete button asks nothing itself
// — the confirmation, which names the transcript that goes with the
// session, is the shell's.
//
// The non-interactive keys fold under *others*: folded (the default),
// the group shows only how many of them hold a lease, plus the
// more/less toggle; unfolded it lists every row.
import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw'
import type { ClawSession } from '~/composables/useClaw'
@@ -32,10 +28,6 @@ const emit = defineEmits<{
interface Group {
label: string
rows: { key: string; name: string; session: ClawSession }[]
/** How many rows hold a lease; the others' header shows the count. */
working: number
/** Whether the rows fold away until the toggle says otherwise. */
collapsible: boolean
}
const groups = computed<Group[]>(() => {
@@ -60,29 +52,13 @@ const groups = computed<Group[]>(() => {
name: session.key.replace(/^interactive:/, ''),
session,
})
const working = (sessions: ClawSession[]) =>
sessions.filter((session) => session.state === 'leased').length
const groups: Group[] = []
if (interactive.length > 0)
groups.push({
label: 'interactive',
rows: interactive.map(row),
working: working(interactive),
collapsible: false,
})
if (others.length > 0)
groups.push({
label: 'others',
rows: others.map(row),
working: working(others),
collapsible: true,
})
groups.push({ label: 'interactive', rows: interactive.map(row) })
if (others.length > 0) groups.push({ label: 'other keys', rows: others.map(row) })
return groups
})
/** Whether the others group is folded out; it starts folded. */
const othersOpen = ref(false)
const shownCount = computed(() =>
groups.value.reduce((total, group) => total + group.rows.length, 0),
)
@@ -183,21 +159,7 @@ watch(
</p>
<div v-for="group in groups" :key="group.label" class="group">
<div class="group-head">
<span class="label">{{ group.label }}</span>
<span v-if="group.collapsible" class="working" :class="{ live: group.working > 0 }">
{{ group.working }} working
</span>
<button
v-if="group.collapsible"
class="ghost toggle"
:title="othersOpen ? 'fold the other keys away' : 'show every other key'"
@click="othersOpen = !othersOpen"
>
{{ othersOpen ? 'less' : 'more' }}
</button>
</div>
<template v-if="!group.collapsible || othersOpen">
<div
v-for="row in group.rows"
:key="row.key"
@@ -221,7 +183,6 @@ watch(
×
</button>
</div>
</template>
</div>
</aside>
</template>
@@ -326,32 +287,10 @@ watch(
margin-bottom: 14px;
}
.group-head {
display: flex;
align-items: center;
gap: 8px;
.group .label {
padding: 0 8px 4px;
}
.group-head .working {
flex: 1;
min-width: 0;
text-align: right;
font-family: var(--mono);
font-size: 11px;
color: var(--text3);
}
.group-head .working.live {
color: var(--ok);
}
.group-head .toggle {
flex: none;
padding: 0 6px;
font-size: 11px;
}
/* The row owns the hover and active surface: the select button fills it
and the delete button sits beside it, so neither has to nest in the
other. */
@@ -18,36 +18,20 @@ const kind = ref<SandboxKind>('local')
const url = ref('')
const token = ref('')
const clearToken = ref(false)
const host = ref('')
const workspace = ref('')
const dirty = computed(() => {
const state = props.state
if (!state) return false
if (kind.value !== state.kind) return true
if (kind.value === 'http') {
if (kind.value !== 'http') return false
const normalized = url.value.trim().replace(/\/+$/, '')
if (normalized !== (state.url ?? '')) return true
return token.value.trim() !== '' || clearToken.value
}
if (kind.value === 'ssh') {
if (host.value.trim() !== (state.host ?? '')) return true
if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true
}
return false
})
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
const hostValid = computed(
() => host.value.trim() !== '' && !host.value.trim().includes(' '),
)
const ready = computed(() => {
if (kind.value === 'http') return urlValid.value
if (kind.value === 'ssh') return hostValid.value
return true
})
const ready = computed(() => kind.value !== 'http' || urlValid.value)
const urlHint = computed(() =>
url.value.trim() && !urlValid.value
@@ -55,12 +39,6 @@ const urlHint = computed(() =>
: 'The sandboxd base URL, for example https://box.example:7600.',
)
const hostHint = computed(() =>
host.value.trim() && !hostValid.value
? 'One destination, no spaces: an alias or user@host your ssh config resolves.'
: 'An alias or user@host your ssh config resolves.',
)
function sync(): void {
const state = props.state
if (!state) return
@@ -68,8 +46,6 @@ function sync(): void {
url.value = state.url ?? ''
token.value = ''
clearToken.value = false
host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? ''
}
watch(
@@ -95,10 +71,6 @@ function save(): void {
choice.clear_token = true
}
}
if (kind.value === 'ssh') {
choice.host = host.value.trim()
choice.workspace = workspace.value.trim()
}
emit('save', choice)
}
@@ -106,9 +78,7 @@ function save(): void {
const workspacePath = computed(() => {
const state = props.state
if (!state) return ''
if (kind.value === 'local') return state.local_workspace
if (kind.value === 'http') return state.remote_workspace
return state.workspace
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
})
</script>
@@ -153,47 +123,6 @@ const workspacePath = computed(() => {
</span>
</span>
</label>
<label class="option" :class="{ selected: kind === 'ssh' }">
<input v-model="kind" type="radio" value="ssh" :disabled="saving" />
<span class="option-text">
<span class="option-title">
SSH host
<span v-if="state.kind === 'ssh'" class="current">current</span>
</span>
<span class="option-detail">
Commands run on a box the claw reaches with ssh, nothing installed on the far end.
</span>
</span>
</label>
</SettingCard>
<SettingCard v-if="kind === 'ssh'" title="SSH host">
<SettingRow title="Destination" :description="hostHint">
<input
v-model="host"
type="text"
class="mono"
placeholder="me@box.example"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
<SettingRow
title="Workspace base"
description="The remote directory the claw's workspaces live under. Defaults to /root."
>
<input
v-model="workspace"
type="text"
class="mono"
placeholder="/root"
autocomplete="off"
spellcheck="false"
:disabled="saving"
/>
</SettingRow>
</SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
@@ -238,7 +167,7 @@ const workspacePath = computed(() => {
</SettingRow>
</SettingCard>
<AppCallout v-if="kind !== 'local'" variant="info" title="Remote commands start from a copy">
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
On first use the claw sends the local workspace to the sandbox as a tarball.
Later edits stay in the sandbox; the claw does not copy them back.
</AppCallout>
+3 -13
View File
@@ -231,9 +231,9 @@ export interface ActiveBackend {
active: { provider: string; model: string }
}
/** Where the agent's `bash` runs: this host, a daemon speaking the
* sandbox protocol over HTTP, or an ssh login on a far box. */
export type SandboxKind = 'local' | 'http' | 'ssh'
/** Where the agent's `bash` runs: this host or a daemon speaking the
* sandbox protocol over HTTP. */
export type SandboxKind = 'local' | 'http'
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
* the wire; `token_set` says whether one is stored. */
@@ -241,12 +241,6 @@ export interface SandboxState {
kind: SandboxKind
url: string | null
token_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */
host: string | null
/** The ssh workspace base the workspaces sit under, `null` for the
* default. */
ssh_workspace: string | null
/** Where `bash` starts under the current choice. */
workspace: string
/** The daemon's chat workspace, whatever the choice. */
@@ -263,10 +257,6 @@ export interface SandboxSelection {
url?: string
token?: string
clear_token?: boolean
host?: string
/** The ssh workspace base; the per-workspace directories land under
* it. An omitted value keeps the current one. */
workspace?: string
}
/** A failed API call: the status plus the claw's `error` string when it sent one. */