@ours.network/fleet 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -865,6 +865,60 @@ still up after 2 minutes the monitor gives up on that wake and records
865
865
  queued and its cursor is not committed until a later delivery is accepted). The
866
866
  agent's briefing tells it **not** to arm a native harness Monitor.
867
867
 
868
+ Managed ACP sessions can opt into bounded stall recovery independently of mail delivery:
869
+
870
+ ```yaml
871
+ monitor:
872
+ mode: fleet
873
+ stall_recovery: true # omitted/false preserves existing behavior
874
+ stall_timeout_ms: 900000 # 15 minutes; integer 60000–86400000
875
+ ```
876
+
877
+ The ACP session measures silence from its last live reasoning, output, plan, or tool
878
+ update, excluding replay and retry/status chatter. It requires observable progress
879
+ before detecting a stall. Repeated structured Codex response-stream retry errors
880
+ can confirm a stall after one window; generic silence requires two windows (30
881
+ minutes by default). Codex ACP 1.1.7 exposes no native-turn mapping, so strong retry
882
+ evidence is used only on the first fresh, unsteered managed turn. Later and resumed
883
+ turns use the generic path. Assistant text and stderr never authenticate a retry.
884
+
885
+ Active tools, pending permissions, modal/unknown adapter status, unknown tool
886
+ boundaries, in-flight steering, human cancellation, and shutdown prevent automatic
887
+ interruption. Tool IDs are stored as a bounded set of hashes before the watchdog relies on their
888
+ boundaries. Reuse across any ordinary or diagnostic turn, including after resume,
889
+ makes the boundary uncertain; delayed terminal events cannot authorize cancellation.
890
+ Missing, damaged, or exhausted history disables automatic cancellation and reports
891
+ `blocked_evidence` after the conservative silence window.
892
+ An untracked steering-started turn is left alone. A tracked turn with no meaningful
893
+ event reports `blocked_evidence` after two windows from admission; turn age alone
894
+ never authorizes cancellation.
895
+ Native monitoring and non-ACP backends do not run this watchdog.
896
+
897
+ Recovery sends one explicit ACP cancel, waits at most 15 seconds for settlement,
898
+ and submits a diagnostic continuation in the same session and queue slot. Startup
899
+ and queued prompts remain behind that continuation. It instructs the agent to check
900
+ recorded terminal events and never replay ambiguous or completed side effects.
901
+ The watchdog never kills, restarts, or respawns the adapter. Error/refusal settlement of cancellation reports a blocker without failing startup.
902
+ A refused/failed or re-stalled continuation emits an actionable blocker without another cancellation;
903
+ startup remains supervised when diagnostic recovery reports a blocker.
904
+
905
+ The durable claim is deliberately stricter than one attempt per turn: at most one
906
+ automatic recovery per ACP session ID, including after a supervisor restart. No
907
+ claim is automatically cleared, even if incomplete. Its queue-only monitor policy
908
+ is restored before admission on supervisor restart. During and after that attempt,
909
+ mail wakes use queued delivery for all `monitor.interrupt` policies; explicit human
910
+ interrupts retain their existing authority and supersede pending recovery. The
911
+ `after_tool` timeout alone never authorizes watchdog cancellation. The feature must
912
+ be enabled explicitly even when mail uses `interrupt: true` or `after_tool`.
913
+
914
+ Body-free claim and audit records live under `<agentDir>/.stall-recovery/`; typed
915
+ `stall_recovery` events and fixed supervisor log messages expose outcomes. Session
916
+ and turn identifiers are hashed; prompt bodies, tool outputs, credentials, and
917
+ workspace paths are excluded. On `blocked_*`, inspect the structured session events,
918
+ verify completed actions, then continue manually if safe or report the remaining
919
+ blocker. Do not clear a claim to retry an uncertain interruption. No room integration
920
+ or identity binding is needed.
921
+
868
922
  With `monitor.mode: native`, ours-fleet does not start its supervisor monitor;
869
923
  the generated briefing instead instructs the harness to arm its own wake
870
924
  mechanism (the structured `ours api watch-notifications` JSONL stream for Claude Code,
@@ -1,9 +1,9 @@
1
1
  {
2
- "version": "1.1.0",
3
- "buildId": "6a76080fd007",
4
- "commit": "818954bbd80a4eb2c184af8cc784b98cc214c0e9",
2
+ "version": "1.1.1",
3
+ "buildId": "24bc68cc8165",
4
+ "commit": "f146310c646c05b381b1bada8d782fcfd3c47b25",
5
5
  "dirty": false,
6
- "builtAt": "2026-09-05T14:01:06.755Z",
6
+ "builtAt": "2026-09-05T20:37:21.457Z",
7
7
  "capabilities": [
8
8
  "monitor.interrupt.after_tool"
9
9
  ]
package/dist/config.d.ts CHANGED
@@ -68,6 +68,10 @@ export interface MonitorConfig {
68
68
  * a positive integer; resolved default is 3. Optional so old snapshots resolve.
69
69
  */
70
70
  turn_fail_threshold?: number;
71
+ /** Opt-in bounded ACP no-progress recovery; independent of mail interruption policy. */
72
+ stall_recovery?: boolean;
73
+ /** Progress silence window; default 15 minutes. Generic silence requires two windows. */
74
+ stall_timeout_ms?: number;
71
75
  }
72
76
  /** A trusted, fleet-owned ours mailbox which is never bound inside the agent. */
73
77
  export interface OwnerChannelConfig {
package/dist/config.js CHANGED
@@ -27,7 +27,7 @@ export const NOTIFY_EVENT_TYPES = [
27
27
  /** Default wake sources when a role does not list its own. */
28
28
  export const DEFAULT_WAKE_SOURCES = ['message_received', 'file_received', 'local_contact_request', 'pending_message'];
29
29
  const MONITOR_KEYS = [
30
- 'mode', 'enabled', 'wake_sources', 'batch_ms', 'inject', 'interrupt', 'turn_fail_threshold',
30
+ 'mode', 'enabled', 'wake_sources', 'batch_ms', 'inject', 'interrupt', 'turn_fail_threshold', 'stall_recovery', 'stall_timeout_ms',
31
31
  ];
32
32
  const INJECT_MODES = ['notification', 'full'];
33
33
  const MONITOR_MODES = ['fleet', 'native'];
@@ -74,6 +74,12 @@ export function validateMonitorConfig(raw, capabilities = CAPABILITIES) {
74
74
  && (typeof m.turn_fail_threshold !== 'number' || !Number.isInteger(m.turn_fail_threshold)
75
75
  || m.turn_fail_threshold < 1))
76
76
  problems.push('monitor.turn_fail_threshold: must be a positive integer');
77
+ if (m.stall_recovery !== undefined && typeof m.stall_recovery !== 'boolean')
78
+ problems.push('monitor.stall_recovery: must be true or false');
79
+ if (m.stall_timeout_ms !== undefined
80
+ && (typeof m.stall_timeout_ms !== 'number' || !Number.isSafeInteger(m.stall_timeout_ms)
81
+ || m.stall_timeout_ms < 60_000 || m.stall_timeout_ms > 86_400_000))
82
+ problems.push('monitor.stall_timeout_ms: must be an integer between 60000 and 86400000');
77
83
  if (m.wake_sources !== undefined) {
78
84
  if (!Array.isArray(m.wake_sources))
79
85
  problems.push('monitor.wake_sources: must be a list');
@@ -1164,6 +1170,8 @@ export function resolveMonitorConfig(defMonitor, roleMonitor, labels = {}) {
1164
1170
  batch_ms: merged.batch_ms ?? MONITOR_DEFAULT_BATCH_MS,
1165
1171
  inject: merged.inject ?? 'notification',
1166
1172
  interrupt: merged.interrupt ?? false,
1173
+ ...(merged.stall_recovery !== undefined ? { stall_recovery: merged.stall_recovery } : {}),
1174
+ ...(merged.stall_timeout_ms !== undefined ? { stall_timeout_ms: merged.stall_timeout_ms } : {}),
1167
1175
  turn_fail_threshold: merged.turn_fail_threshold ?? MONITOR_DEFAULT_TURN_FAIL_THRESHOLD,
1168
1176
  };
1169
1177
  }
package/dist/docs.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Keep this concise enough to place directly in an agent context. Unlike
5
5
  * Commander's per-command help, this describes how the pieces compose.
6
6
  */
7
- export declare const AI_DOCS = "# ours-fleet reference\n\nours-fleet runs persistent or temporary, identity-bound AI roles through a\nprovider-neutral managed-session interface:\n\n- harness: `claude-code` or `codex`\n- session: `acp` (default) or `codex-app-server` (Codex only)\n- lifetime: permanent (supervised, restartable) or `spawn --temp`\n\n## Discover and validate\n\n```sh\nours-fleet docs # this complete reference (`man` is an alias)\nours-fleet help <command> # exact flags for one command\nours-fleet config [-c FILE] # validate and print the merged plan; no changes\nours-fleet doctor [-c FILE] [--harness codex|claude-code]\nours-fleet version [--json] # build identity, capabilities, every install on PATH\n```\n\nConfiguration v2 is `~/fleet.yaml` plus typed bare documents under the exact\nstem directories `~/fleet/agents`, `~/fleet/agent_templates`, `~/fleet/roles`, `~/fleet/brains`, and\n`~/fleet/room_templates`.\nThe manifest owns fleet-wide operational defaults and automation; each Agent\nselects one inline/ref Role and Brain and carries its operational fields.\nAgent Templates under `~/fleet/agent_templates` are inert reusable launch definitions;\nonly explicit files under `~/fleet/agents` are persistent lifecycle instances.\nRoom members use `agent_template` and receive immutable content-addressed snapshots.\nAn Agent Template may declare up to 64 temporary-only named `loops`; persistent Agent\ninstances reject them. Each loop requires `interval` (1m..30d) and bounded\nnonblank `prompt`, with optional `enabled` (default true), `initial_delay`\n(default interval, 0s..30d), and `jitter` (default 0s, < interval, <=1h).\nExecution is fixed skip-if-busy with no ordinary missed-tick backlog/replay;\nrestart recovery may preserve at most one recent late occurrence.\nLegacy top-level `roles:` and `fleet.d` are rejected. Validate the complete\ntrusted source set with `config` and `doctor` before starting or restarting.\n\nPermanent `spawn` writes `~/fleet/agents/Name.yaml`. The web console edits an\nexplicit `{manifest, agents, agent_templates}` model while Role/Brain presets remain read-only.\nIts aggregate revision includes every Agent/Role/Brain/Room-template source, previews a\nredacted per-document diff in an exact-stem private staging tree, and saves under\none root lock with a private multi-file backup and full rollback. A no-op is\nbyte-identical and creates no backup.\n\n## Build identity and install provenance\n\n`--version` prints a semver and nothing else, and a semver does NOT identify an\nartifact. Version bumps land in a release commit of their own, so every build cut\nbetween two releases carries the PREVIOUS version while already containing new\nbehaviour. One host ran two installs that both reported 0.16.0 \u2014 same version,\ndifferent build. One accepted `monitor.interrupt: after_tool`, the other\nrejected it as invalid. Their\n`dist/cli.js` were byte-identical \u2014 the divergence was in other modules.\n\nEvery build therefore stamps `dist/build-info.json` with a build id (first 12 hex\nof a sha256 over the rest of `dist/`), the commit it was cut from, and the\ncapability tokens the shipped code declares \u2014 for example\n`monitor.interrupt.after_tool`. Ask any executable what it is:\n\n```sh\nours-fleet version # ours-fleet 0.17.0+9f1c2a3b4d5e, capabilities, PATH installs\nours-fleet version --json # the same as machine-readable JSON, no environment values\n```\n\nRead a capability, never a version number, to decide whether a setting is\nsupported. When a build rejects a value it knows the name of, it says which\ncapability is missing and which build rejected it, because another install on the\nsame host may accept the identical file. `config` prints the build that resolved\nthe plan; `status <Name>` says so when the build reporting on a role is not the\none that created it (roles record their creating build in `creation.json`).\n\n`ours-fleet doctor` runs an `install` check that lists every `ours-fleet` on\nPATH plus the one executing, and FAILS when two installs share a semver but are\ndifferent builds, or when the running artifact is a DIFFERENT artifact from the\none PATH resolves to. A second prefix holding identical content is not a skew\nand is not reported. A PATH entry the shell would not execute \u2014 a directory, or\na file without its execute bit \u2014 is not counted as an install at all.\nInstalls built before this stamp existed report `+unknown`; they are compared by\nhashing their `dist/` instead, so two pre-provenance installs are still told\napart. To fix a flagged host, remove or update the stale install \u2014 do not rely on\nPATH order.\n\n## Lifecycle and console commands\n\n```sh\nours-fleet init [-c FILE] # interactive missing-default seed; TTY required\nours-fleet up|down [Name...]\nours-fleet restart [Name...] # preserve/resume harness context\nours-fleet force-restart [Name...] # fresh context; briefing is reloaded\nours-fleet ls\nours-fleet status|peek|attach|logs Name\nours-fleet logs -f Name\nours-fleet send Name \"prompt\"\nours-fleet rm Name\nours-fleet watchdog-report <name> [run-id] [--list] [--json]\nours-fleet watchdog-run <name>\n```\n\n`init` is an interactive missing-default workflow that preserves existing files byte-for-byte.\nIt names the resolved manifest and split directory, asks a default-No confirmation,\nthen subscriptions (Codex, Claude, or both), model assignment (one explicit model for\nevery job or explicit development/review/coordination choices), one reasoning level,\nand a final default-No review. Quick/Balanced/Thorough generate low/medium/high.\nModel pickers show packaged supported IDs; catalog membership is not a recommendation\nor entitlement claim. Run `ours-fleet doctor` for local Codex availability; Claude\nentitlement is checked when a role launches. The generated brains contain no\n`model_chain`, so Fleet never silently substitutes another model.\n\nAt either confirmation, N, Enter, Escape, Ctrl-C, Ctrl-D, or EOF cancels. In a picker,\nEscape, Ctrl-C, Ctrl-D, or EOF cancels; Enter records the highlight or continues a\nnon-empty multi-select, N is ignored, and an empty subscription selection remains blocked.\nEvery cancellation before final approval performs no host or configuration mutation.\nRedirected/non-TTY invocation is refused with the same guarantee. After the final Yes,\nhost setup precedes publication. Path ownership/type/mode/symlink and\nsame-filesystem checks run before host setup and again under a per-setup lock. Publication\nstages and validates the complete combined setup, backs up whichever old target(s) exist,\nand retains a private recovery record. A hard process/host termination cannot promise\nrollback; inspect host integration and private init stage/recovery evidence.\n\n`peek`, `attach`, and text `send` use the structured agent session.\nAttachment also accepts `/permit <permission-id> <option-id>`, `/interrupt`,\nand `/detach`.\n\n## Local web console\n\nThe npm package includes the web console; installed users do not clone the repo\nor run `npm run build`:\n\n```sh\nnpm i -g @ours.network/fleet\nours-fleet init\nours-fleet doctor\nours-fleet web # install/update service, start, pair browser\n```\n\nThe normal command uses stable `http://127.0.0.1:49271/`, installs an\nowner-level systemd user service (Linux) or LaunchAgent (macOS), and opens a\nfive-minute one-use pairing link in the local browser. After pairing, bookmark\nthe plain URL or install the PWA. To pair a new, signed-out, or revoked browser,\nrun `ours-fleet web open`.\n\n```sh\nours-fleet web status\nours-fleet web start|stop|restart\nours-fleet web open\nours-fleet web revoke-all # revoke every browser and active session\nours-fleet web uninstall\nours-fleet web serve --port 0 --no-open # isolated foreground/testing mode\n```\n\nThe console is IPv4-loopback-only by default. Both `localhost` and\n`127.0.0.1` are accepted locally. For an nginx/TLS reverse proxy, keep the\ndefault bind and declare the exact browser origin:\n\n`ours-fleet web install --public-origin https://fleet.example.com --password-file /secure/fleet-password`\n\nFleet reads the password file during setup and persists only a salted scrypt\nverifier. New browsers authenticate and retain rotating HttpOnly/SameSite\ntrusted-device credentials. If nginx already authenticates, the operator may\ndeliberately select `--no-password`; the CLI and browser warn that anyone\nreaching the origin can control the fleet. First setup requires an explicit\nchoice: `--password-file` or `--pairing` for protected access, or\n`--no-password` for intentional unprotected access.\n\nUse `--bind ADDRESS` only for an intentional direct listen. A non-loopback\nbind is rejected unless `--public-origin` is also present. Host/Origin checks\nuse the declaration and do not trust forwarded headers. Configure nginx to\nproxy HTTP and WebSocket upgrades to `127.0.0.1:49271` and terminate TLS;\nfleet accepts nginx's loopback upstream Host, so no Host rewrite is required.\nBrowser credentials add Secure for HTTPS, and `revoke-all` invalidates all\ntrusted devices. Role creation offers harness-scoped known-model choices\nwhile still accepting a typed model ID; blank explicitly uses the selected\nharness's own default.\n\n## Spawn\n\n```sh\nours-fleet spawn [--temp] [Name | --name Name] \\\n --brain BRAIN_ID --role ROLE_ID \\\n --cwd /absolute/path --identity Identity --coordinator Coordinator \\\n --approval ask|auto|allow \\\n --filesystem read-only|workspace|unrestricted \\\n --unattended deny|wait --isolation-file /path/isolation.yaml\n```\n\nPermanent spawn writes `~/fleet/agents/Name.yaml` and starts a supervised role.\n`--temp` writes active state under `~/.ours-fleet/tmp` and starts an independent\ntransient supervisor (a collected systemd unit or submitted launchd job). It is\nnot enabled across reboot and does not die when the role that spawned it restarts.\nBrain definitions own the managed session backend. When a temporary role's bound identity\ncloses or its session ends, the supervisor, monitor and live roster entry retire\ntogether; state moves intact to `~/.ours-fleet/recovery/temporary` with a\ntermination record. Failed launches use the same archive rather than deleting\ntheir briefing, provenance, logs or partial supervisor metadata.\n\nNamed `down` and `rm` commands can target an exact state-backed temporary role\neven though it is absent from merged fleet YAML. The recorded transient unit/job\nis authoritative. Missing/incomplete ownership metadata is reconciled only from\nan exact `_run-temp <role>` process-table match: one match may be adopted, zero\nsettles as stopped, and ambiguity or an unreadable table fails closed. Launching\nrecords receive a bounded grace so a not-yet-registered transient unit cannot be\nmistaken for a stopped one. Stale recorded supervisors are reclaimed in bounded\nbatches by moving their state to the same recovery archive, never by blind deletion.\n\nEvery temporary role creates a new session-owned identity by calling ours MCP\n`create_temporary_identity` with its exact assigned name. It never binds a\npre-existing identity and never falls back to permanent `create_identity`.\nFleet does not inspect, preserve, or provision an ours identity for temporary\nspawn; creation belongs exclusively to the launched temporary agent session.\nCollisions, missing tool support, and creation errors stop safely without\nforce-adopting or deleting identity state. Permanent roles\nare provisioned by fleet before launch and never delegate normal identity\ncreation to the harness.\n\nThe temporary supervisor treats its first positive identity observation as the\nlifecycle readiness gate: a cold harness may take as long as needed to read its\nbriefing and bind, without a fixed first-bind retirement timer. After readiness,\nonly sustained authoritative absence closes the role. Unreachable, malformed, or\nvalid-but-empty daemon indexes are ambiguous and reset closure debounce rather\nthan becoming cleanup authority.\n\nInside a managed role, public `ours-fleet` commands cross an authenticated\nsupervisor attribution boundary before Commander parsing. The original CLI remains\nthe executor inside the role's existing OS sandbox, and ordinary CLI validation is\nthe source of truth. Hidden worker entry points remain internal; public lifecycle and\noperator commands are not restricted by the proxy.\n\nCommand invocation, raw argv, read-only work, validation failures, and generic\noutcomes are never forwarded to the Owner-visible channel. Fleet announces only\nconfirmed Agent, Task, and Room lifecycle changes. Local diagnostics retain\nstructurally redacted command metadata. Lifecycle delivery uncertainty is logged,\nnever recursively announced, and never reruns or blindly retries an effect.\nRoom participant summaries describe creation and activation. Fleet has no public\npost-create Room membership mutation, so it does not claim a separate membership event.\n\nOmitted Brain and Role selections, working directory, coordinator, neutral permissions,\nand fleet monitor policy inherit from the calling Agent. Explicit options always win.\nIdentity, mission/profile text, environment, owner routing, auth proxy, room startup,\nisolation, worklog, and sensitive inline Brain values never inherit implicitly.\nThis automatic proxy is a convenience and\nattribution mechanism, not an isolation boundary: an unrestricted role can still\ninvoke another binary path directly. Host/operator shells keep the ordinary direct\nCLI behavior.\n\nBrain owns harness, session, model, reasoning effort, token limits, and native harness\noptions. Removed runtime flags are rejected with migration guidance rather than silently\nreinterpreted. A selection is a stable ID or an explicit `inline:{...}` mapping.\n\nPackaged Developer, Critic, and LocalCoordinator Agent Templates set\n`monitor: { mode: fleet, interrupt: after_tool }`. Every member of the standard\n`single`, `pair`, and `team` Room Templates therefore resolves to fleet-owned,\nafter-tool delivery. Explicit per-member and custom Agent Template values remain\nauthoritative and merge key by key.\n\n## fleet.yaml\n\n```yaml\napi_version: ours.network/fleet/v2\nvars:\n work_root: /home/me/work\nstart_stagger_ms: 0\ndefaults:\n permissions:\n approval: ask\n filesystem: workspace\n unattended: deny\n monitor:\n mode: fleet # fleet (default) | native\nwatchdogs:\n nightwatch: # [A-Za-z0-9_-], must not collide with a role name\n coordinator: FleetCoordinator # required \u2014 where alerts go\n # everything below is optional\n enabled: true # default true; false = configured but never scheduled\n interval: 10m # default 10m; 30s | 10m | 2h, minimum 1m\n watch: [Alice, CodexReviewer] # explicit lists are exact; omit for configured + live temp roles\n agent: { ref: WatchdogAgent } # required: declared Agent ID, or canonical inline Agent definition\n identity: Watchdog-nightwatch # default: Watchdog-<name>\n timeout: 5m # default 5m; a run past this is killed and recorded as error\n keep_reports: 50 # default 50 reports retained per watchdog\n alert_cooldown: 60m # default 60m before the same finding alerts again\n prompt_file: /abs/extra.md # optional extra focus, APPENDED to the fixed contract\n```\n\nAn Agent is a separate bare document under `~/fleet/agents/<ID>.yaml`:\n\n```yaml\nrole: { inline: { mission: Coordinate work and delegate implementation. } }\nbrain: { inline: { harness: codex, session: codex-app-server, model: gpt-model-id } }\nidentity: Coordinator\ncwd: ${work_root}/project\noversee: [{ agent: Worker, interval: 5m }]\n```\n\nA watchdog observes and reports; it never restarts, stops, spawns, or removes a\nrole, answers a pending permission, edits a workspace, or approves anything on\nthe owner's behalf. `watchdogs:` may appear only in the base config\n(`~/fleet.yaml` or `-c FILE`); Agent/Role/Brain documents never own it.\nThe selected Agent owns Brain, Role, permissions, isolation, and every other\nagent setting. Legacy watchdog `harness`, `model`, `session`, and\n`isolation` fields fail with migration guidance.\nWhen `watch:` is omitted, each run watches the configured roles plus temporary\nfleet roles that are live when the run starts. An explicit `watch:` list is\nnever augmented.\n\nAgent operational values override manifest operational defaults. Role and Brain\nownership never cross-merges. `${name}` substitutes entries from `vars`.\nBrain fields include `max_tokens` and `autocompact_pct`; isolation is Agent-owned.\nUse README.md for the complete isolation policy and resource-cap schema.\n\nSupervised roles connect to the operator-configured ours daemon; they do not own its\nlifecycle. Fleet strips the obsolete, presence-sensitive `OURS_AUTOSTART` variable from\nagent-session children; `ours-mcp proxy` is client-only and never starts a daemon. Start\nthe shared daemon only through an explicit operator or installer/setup flow.\n\n## Rooms and tasks\n\n`init` materializes editable `single`, `pair`, and `team` Room templates plus\ntheir exact-cased Agent, Role, and Brain presets. The command prints the packaged\npreset revision and source directory. Inspect provenance and content before use:\n\n```sh\nours-fleet config [-c FILE]\nours-fleet template list [-c FILE]\nours-fleet template show team [-c FILE]\nours-fleet task create --title \"Solo task\" --template single [-c FILE]\nours-fleet task create --title \"Reviewed change\" --template pair [-c FILE]\nours-fleet task create --title \"Phased delivery\" --template team [-c FILE]\nours-fleet spawn --temp Scout --role SELECTION --brain SELECTION --loops-file PRIVATE.yaml\nours-fleet task start TASK --member developer --loops-file PRIVATE.yaml\nours-fleet task start TASK --member critic --no-loops\n```\n\n`--loops-file` must be an owner-only, non-symlink regular file <=1 MB containing\nexactly one top-level non-empty `loops:` mapping. `--no-loops` explicitly\ndisables loops. They are mutually exclusive and rejected for permanent spawn.\nFor a grouped room member the whole CLI block overrides its Agent Template;\nthe template overrides omission. Omission preserves historical no-loop behavior\nand never inherits manifest wildcard loops. Fleet validates before side effects,\nseals normalized timings plus exact private prompts, and reuses that snapshot for\nidempotent start, retry, recovery, and replacement. Trusted authoring and the\nprivate sealed runtime retain exact prompts; resolved launch, task, room,\nprovenance, and audit presentations show source, policy, timing, prompt bytes,\nand prompt SHA-256 instead of prompt text.\n\nAn alternate manifest `-c /path/custom.yaml` uses `/path/custom/` as its split\nroot. Repeated init only fills missing files and never adopts a newer default.\nExact known revision-3 through revision-5 packaged-bootstrap and generated role defaults have an exact-semantic,\nfail-closed migration (dry-run by default):\n\n`ours-fleet migrate-role-defaults [-c FILE]`\n`ours-fleet migrate-role-defaults [-c FILE] --write`\n\nReview removals, replacements, additions, preserved custom files, staging path,\nand recovery path. Same-named custom files stay byte-identical; dangling custom\nreferences refuse publication, and a successful rerun is a no-op. For explicit\nsingle-file adoption, copy from init's reported packaged source beside the target\nas `.new-default`, inspect `diff -u TARGET TARGET.new-default`, then replace it.\n\nThe exact generated six-worker legacy starter Agent set has its own fail-closed\nmigration (dry-run by default):\n\n`ours-fleet migrate-agent-templates [-c FILE]`\n`ours-fleet migrate-agent-templates [-c FILE] --write`\n\nReview the dry-run moves, addition, staging path, and retained recovery-backup path\nbefore `--write`. Customized/partial known starters and unsafe trees refuse without\nmutation; unrelated custom persistent Agents remain persistent. A manifest-level template\nmay shadow a same-named file only with `override_builtin: true` and a higher\nversion; this compatibility marker is deprecated and reported as a diagnostic.\n\nRooms always use `ours-cowork`; there is no room-provider selector. Configure\nthe cowork daemon connection and room owner directly:\n\n```yaml\nrooms:\n cowork:\n config: /home/me/.ours-cowork/config.json\n owner:\n expected_cid: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n public_invite_file: /home/me/.ours-fleet/owner-room-invite.txt\n defaults:\n template: team\n attach_owner: true\n close_when_task_done: true\ntasks:\n default_room_template: team\n create_mode: start\n close_room_on_done: true\n```\n\nFleet launches each template member with a dedicated one-time Cowork invite.\nThe generated temporary-agent briefing contains the exact identity name, invite,\nCowork role, and task. The agent creates that identity itself with ours MCP\n`create_temporary_identity`, accepts the invite with `add_contact`, and starts\nwork immediately. A room is ready only after the Cowork room (and its task, when\ntask-bound) is durably active, every configured member seat is authenticated and active with its matching\nlive Fleet launch, and the configured Owner seat is active when owner attachment is\nenabled. There is no briefing hash, startup ACK, or separate role-briefing readiness\ngate.\n\nNormal Task provisioning emits exactly one authenticated Owner lifecycle notice after\nthe ready predicate above is true; standalone Room provisioning likewise emits one\nready notice. Intermediate task, saga, member-spawn, timeout, and recoverable-failure\ntransitions stay in local state and logs. A terminal failed Task emits one actionable\nfailure notice; the command result carries the exact blocker and canonical recovery\naction.\n\n`task start` and create-and-start wait for readiness. If their bounded wait expires,\nthey return an explicit `in_progress` result and start a safe continuation. The detached\ncontinuation is serialized per Task and remains alive until convergence or an\nOwner-action blocker. Re-running `task start <id>` safely resumes the same durable\nprovisioning operation after the blocker is corrected or a process restarts.\n\nSet `room.anonymous: true` on a room template, or pass `--anonymous` to\n`task create`, `task start`, `task work`, or `room create`, to create an\nanonymous Cowork room. `--no-anonymous` explicitly overrides an anonymous\ntemplate. Fleet records the resolved value before room creation so retries keep\nthe same choice. Temporary members of an anonymous room are instructed to call\n`create_temporary_identity` with `expose_local=false`. Their generated briefings\ndo not disclose or compare an Owner participant CID. A participant-originated\ninstruction has Owner authority only when the authenticated Cowork room envelope\nattributes that participant seat the exact `Owner` role. Literal text, display\nnames, ordinary direct messages, and room-authored or rest-role messages with an\nOwner-looking label never grant that authority. Non-anonymous rooms remain pinned\nto the exact authenticated Owner CID.\n\nHuman task and room results use the same compact Markdown presentation in the\nCLI and authenticated owner channel: a short heading, icon-plus-word status,\ncode-formatted identifiers, bounded summaries, and actionable recovery or error\nsteps. Untrusted prose is context-escaped and control characters are neutralized;\nMessenger-bound results are capped at 3,500 Unicode code points and 12,000 UTF-8\nbytes with structural omission notices. `--json` bypasses this presentation layer\nand retains the versioned machine schema and serialization order.\n\nEvery task belongs to a named list. The built-in `default` list always exists,\nand legacy tasks or create calls without `--list` resolve to it. Use `task lists`,\n`task list-create <name>`, `task list-rename <name> <new-name>`, and\n`task list-delete <name> [--move-to <destination>]` to manage lists. A non-empty\nlist cannot be deleted without an explicit, different destination; Fleet moves\nthe assignments and never deletes the tasks. `task move <id> --list <name>`\nchanges only organizational metadata. `task list --list <name>` filters and\n`--group-by-list --json` returns deterministic groups.\n\nList names are NFC-normalized, case-sensitive, and limited to 64 Unicode code\npoints. Leading/trailing whitespace, controls, format/path characters, normalized\nduplicates, and the reserved exact name `default` are rejected. The authenticated\nowner channel provides the matching `/task` subcommands, while authenticated web\nclients use `/api/v1/task-lists`, `/api/v1/tasks`, and\n`/api/v1/tasks/:id/list`; every adapter delegates to the same application service.\nMessenger's multiline command grammar treats surrounding whitespace on each\nvalue line as transport framing; the canonical value passed to the shared service\nis the trimmed line. CLI arguments and REST strings are passed verbatim.\n\nOlder prerelease files with the exact legacy `provider: cowork` key under\n`rooms:` still load, but the key is ignored and omitted from resolved\nconfiguration. Remove it when editing the file. Any other legacy value is an\nerror. The optional `rooms.owner.provider` setting is separate and defaults to\n`messenger-server`.\n\nFinish and Delete are distinct terminal task actions:\n\n`ours-fleet task finish <id>` moves an active or review task to `done` and\ndeletes its associated Cowork room after retiring its members. The room then\ndisappears from normal Fleet and Cowork views; its brief, messages, repository\nreferences, and attachments are not retained as an inspectable archive.\nThe prerelease configuration names `tasks.close_room_on_done` and\n`rooms.defaults.close_when_task_done` are retained for compatibility, but\n`true` now means this close-then-delete behavior.\n\n`ours-fleet room delete <id> <id>` is the canonical destructive room command.\n`room close <id> <id>` remains a deprecated alias with identical deletion\nsemantics. Older prerelease `closed` room records are deleted directly the next\ntime `room list` reconciles Fleet with Cowork.\n\n`ours-fleet task delete <id> <id>` permanently deletes a task in ANY lifecycle\nstate \u2014 backlog, provisioning, active, blocked, review, done, cancelled, failed,\nor partially settled. The exact task ID is required twice for confirmation. A\ndurable deletion intent is persisted before any side effect; the cleanup worker\nthen retires managed room members with evidence, closes and deletes an attached\nroom (tolerating already-missing remote rooms), releases the sealed launch\nsnapshot, and unlinks the task record last. While cleanup settles the task is\nhidden from normal listings and every lifecycle mutation is rejected; if\ncleanup cannot complete (for example Cowork is unreachable), the deletion stays\nin a precise resumable state \u2014 repeat the identical delete command to converge\nafter outages, crashes, or restarts. Deletion\nnever fabricates a `done` transition. A metadata-only deletion receipt\n(acceptance actor, original state, timestamps, completion) is retained under\n`deletion-receipts/` as durable audit evidence. An already-missing task is an\nidempotent no-op. The Owner-channel equivalent is `/task delete <id> <id>`; the\nmanagement API equivalent is `DELETE /api/v1/tasks/<id>?confirm=<id>` (200 when\nsettled, 202 while pending; `GET /api/v1/tasks?includeDeleting=true` exposes\ndeletion-pending tasks to operators).\n\n## Permissions\n\nPrefer the harness-neutral `permissions` block:\n\n- `approval: ask|auto|allow`: portable permission policy. `deny` remains a\n deprecated, fail-closed compatibility alias for existing fleet files.\n- `filesystem: read-only|workspace|unrestricted`: filesystem intent\n- `unattended: deny|wait`: what a managed session does when no console can\n answer a request\n\nThe backend translates this common intent. Native Codex app-server roles reject\npermission aliases in `harness_options`; Codex ACP and Claude retain their\nlegacy native-override compatibility. Do not choose `allow`/`unrestricted`\nor Claude `bypassPermissions` without explicit authorization.\n\n### Creation-time isolation\n\n`ours-fleet spawn --isolation-file <path>` supplies a role's sandbox policy at\ncreation, so the FIRST launch is already confined \u2014 a role that only gains\n`isolation:` on a later `up` ran unsandboxed until then.\n\nThe file holds exactly the `isolation:` mapping documented above and nothing\nelse \u2014 the same schema, validated by the same code, so a policy written here\ncannot mean something different from the identical block in fleet.yaml:\n\n```yaml\nnetwork: deny\nfs:\n read: [/opt/reference]\nresources:\n mem: 2G\n```\n\nInvalid files are rejected before anything is created: no config, no state\ndirectory, no identity reservation. Works for both permanent and `--temp` roles.\n\n### Never-prompt failure\n\nThe failure this section exists to prevent leaves no error message anywhere.\n\nAn unattended role has no console. When the harness needs a permission decision\nthere is nobody to ask, so the request is refused INSIDE the harness \u2014 no\nprompt, no error, no log line. The agent simply does less than its briefing told\nit to, reports success, and nothing distinguishes that from having done the\nwork. Two settings produce it:\n\n1. a permission mode that suppresses the prompt without granting the action\n (Claude `dontAsk`, which is why neutral `allow` maps to\n `bypassPermissions` instead); and\n2. `unattended: deny`, which refuses every request that reaches it.\n\n**Automatic decisions are now recorded.** Every permission request decided\nwithout a human emits a completed event into\n`~/.ours-fleet/agents/<Name>/.session-events.jsonl` carrying the decision,\nwhether policy or a person made it, the policy that produced it\n(`permissions.unattended=deny` vs `permissions.approval=deny`/`=allow`),\nthe reason, and the option selected. `ours-fleet peek` and `attach` render\nthem. Automatic denial asks for a one-shot rejection, never a standing one, so a\nsingle unattended refusal cannot disable a tool for the rest of the session.\n\nA role that can auto-deny logs one line at startup saying so.\n\nTo detect an under-permissioned role BEFORE it runs, use the capability floor\nbelow: `ours-fleet doctor` fails such a role rather than letting it discover\nthe problem silently at work.\n\n### The unattended capability floor\n\nAn unattended role has no console, so a permission request cannot be answered \u2014\nit is refused, silently, inside the harness. The agent then does less than it\nwas told to and reports no error. To make that visible before launch,\n`ours-fleet config` and `ours-fleet doctor` resolve each role's neutral\npermissions through its harness and check the result against a fixed floor:\n\n- `read-state` \u2014 read its briefing, ROUTINES.md, and WORKLOG.md\n- `write-state` \u2014 append its WORKLOG and its own state files\n- `messaging` \u2014 bind its identity, send and receive ours mail\n- `monitor` \u2014 arm and observe its mail monitor\n- `workspace-edit` \u2014 edit and test files in its working directory\n- `status-commands` \u2014 run the inspection commands its briefing prescribes\n\n`doctor` reports this per role as `unattended floor: <Role>`. A role with\n`unattended: deny` that cannot meet the floor FAILS doctor, because it will\ndeny those requests with nobody to see it; with `unattended: wait` it warns,\nbecause a human can still attach and answer.\n\nSecurity meaning: native Codex maps `ask` \u2192 `untrusted`, `auto` \u2192\n`on-request`, and `allow` \u2192 `never`; its independent filesystem mapping is\n`read-only` \u2192 `read-only`, `workspace` \u2192 `workspace-write`, and\n`unrestricted` \u2192 `danger-full-access`. Users configure only the Fleet names.\nClaude maps `ask` to `default`, `auto` to `acceptEdits`, and `allow` to\n`bypassPermissions`. Codex ACP retains its adapter-specific coupled modes:\n`auto` selects `agent`, while `allow` selects `agent-full-access`. These\nmodes genuinely permit the actions the role was authorized to take \u2014\n`dontAsk` only suppresses the prompt while still refusing the action. Nothing\nother than an explicit `allow` becomes non-interactive. Legacy `deny` keeps\nits conservative Codex `on-request` / Claude `plan` translation. `allow` is therefore a real grant and\nrequires explicit authorization; per-role `isolation:` remains the outer\nboundary that a permission mode cannot cross.\n\nACP carries agent-advertised session mode IDs and `session/set_mode`, but those\nIDs are agent-specific and ACP defines no portable permission-policy capability.\nFleet therefore uses the ACP primitive where an adapter exposes a matching mode\nand otherwise performs the harness translation above. The bundled Codex ACP\nadapter couples approval and sandboxing in its advertised mode IDs. Neutral\n`allow` therefore selects `agent-full-access` and widens `filesystem:\nworkspace` or `read-only` to `danger-full-access`; neutral `auto` selects\n`agent` and `workspace-write` even when the neutral filesystem value differs.\nAn explicit `harness_options.sandbox` selects its corresponding ACP preset and\nstill wins, as does an explicit native approval override. `config` and\n`doctor` report a coupled-mode mismatch as approximate. Use per-role\n`isolation:` as the outer boundary for an `allow` ACP role. The live session\nreports both its effective normalized mode and the exact native mode selected.\n\nSee also: `spawn --approval/--filesystem/--unattended` set this intent at\ncreation, and `ours-fleet config` prints each role's neutral settings, their\nnative translation, and any warning \u2014 the same text `doctor` reports.\n\nClaude `harness_options`: `permission_mode` (default, acceptEdits, plan,\ndontAsk, bypassPermissions), `plugins`, `mem_palace`,\n`mem_palace_midsession_autosave`, `mcp_servers` and `mcp_servers_only`.\n\n`mcp_servers` declares MCP servers for the role, in `.mcp.json`'s own shape\n(a map of name to `{ command, args, env }`, or `{ type: http|sse, url,\nheaders }`). By default they are ADDED to whatever the OS user running the role\nalready has configured. The Claude Code adapter sends them in `session/new`.\n\nWhen `mcp_servers` is absent, Fleet sends ACP's protocol-required empty\n`mcpServers` array without an exclusive override, so the agent keeps its inherited\nservers. An explicitly empty configured set is different: Fleet preserves that intent\nthrough the bundled adapter's compatibility path and disables every inherited server.\n\n`mcp_servers_only: true` makes the declared set EXCLUSIVE through\n`strictMcpConfig`. It is all-or-nothing and it ignores every\nother MCP configuration: project `.mcp.json`, user settings, and **plugins**.\nThe ours connector is normally installed as a plugin, so a strict role that does\nnot re-declare it has no `send_message` and no `get_messages` \u2014 it cannot even\nreport that it has gone mute. Fleet therefore refuses a strict role whose\n`mcp_servers` does not name the connector; declare it explicitly, e.g.\n`ours: { command: ours-mcp, args: [proxy] }`.\n\nBoth options, and `plugins`, reach an ACP session through the bundled Claude ACP\nagent's `_meta` vocabulary. A role that sets `session_options.acp.command` runs\nan agent fleet did not choose and cannot be promised them, so that combination is\nrefused at validation rather than accepted and dropped. This narrows a role's\ntool surface; it does not stop the harness deferring tool schemas, which is the\nharness's own decision.\n\nCodex `harness_options`: `launcher` (auto, ours-codex, codex), `search`,\n`config`, `add_dirs`, and `monitor`; Codex ACP additionally supports\n`profile`. Native app-server roles reject `profile` because Codex does not\naccept `--profile` for `app-server`. They\nmust express approval and filesystem authority through the shared\n`permissions:` block, never through harness options. The adapter translates\n`ask|auto|allow` to Codex `untrusted|on-request|never` and translates\n`read-only|workspace|unrestricted` to Codex\n`read-only|workspace-write|danger-full-access`. Native `config` currently\nallows only `model_reasoning_effort`; ACP retains the broader Codex config surface.\n\nFor Codex, the opt-in `session: codex-app-server` directly runs Codex's native\nJSONL app server behind Fleet's provider-neutral session contract. It supports native item\nstreaming, commentary/final phases, prompt admission, steering, interruption,\npermission requests, durable conversation projection, and thread resume. Packaged\nCodex brains and the init wizard continue to select `session: acp` for compatibility;\nClaude Code also uses ACP. Native Codex defaults to `codex app-server` (or `ours-codex app-server`\nwhen launcher auto finds it). Override the exact command when necessary:\n\n`session_options: { codex_app_server: { command: [codex, app-server] } }`\n\nAn exact command override receives no appended profile, search, or subcommand\narguments. Native sessions persist their Codex thread in Fleet's `.session-id`\nand participate in its bounded fresh/resume recovery; cross-provider conversation\nportability is never assumed.\n\n## ACP adapters\n\nThe maintained `@agentclientprotocol/codex-acp` and\n`@agentclientprotocol/claude-agent-acp` runtimes are bundled automatically as\noptional ours-fleet dependencies. The supervisor resolves their executable\nentrypoints internally, so default ACP roles do not depend on global PATH.\nours-fleet and both maintained adapters require Node 22 or newer.\n\nOverride an adapter only when necessary with `session_options.acp.command`\n(string or argv list). If optional dependencies were deliberately omitted,\nours-fleet falls back to a compatible globally installed `codex-acp` or\n`claude-agent-acp`. `ours-fleet doctor -c FILE` verifies the resolved adapter.\n\n## Reliable mail wake\n\n`monitor.mode` selects exactly one wake owner:\n\n- `fleet` (default): the ours-fleet supervisor consumes body-free daemon\n events and advances its durable cursor only after delivery is accepted. ACP\n uses live steering when supported and falls back to structured\n `session/prompt`.\n- `native`: ours-fleet starts no supervisor monitor; the generated briefing\n instructs Claude Code or Codex to arm its harness-native wake mechanism.\n\nSet `monitor.interrupt: true` in fleet mode to cancel active work before every\nconfigured wake. Set it to `after_tool` to preserve an active ACP tool (and any\npending permission), then steer the wake at the first tool-terminal boundary\nwithout cancellation. A hung boundary is bounded at 120 seconds and falls back\nto non-cancelling steering/queueing; adapters without authenticated tool events\nuse the same conservative fallback. Explicit human/control interrupts remain\nimmediate. The policy is content-blind because the supervisor cannot inspect\nencrypted message bodies. Message bodies are released only when the role calls\nthe ours `get_messages` tool.\n\nThe default is `false`. For a temporary role whose mission intentionally arrives\nafter its readiness announcement, set `mode: fleet` and `interrupt: true`\nexplicitly. The readiness announcement does not change the transport: the\nmission remains ordinary ours mail, fleet injects only the body-free wake, and\nthe role calls `get_messages` before acting. Every later configured wake uses\nthe same interruption policy.\n\nLegacy `monitor.enabled: true|false` remains accepted as an alias for\n`mode: fleet|native`; use `mode` in new configuration. Codex's separate\n`harness_options.monitor: true` is native-monitor consent, not monitor-owner\nselection.\nInspect `ours-fleet status Name`, `peek Name`, role logs, and\n`~/.ours-fleet/agents/Name/.monitor-status` when diagnosing delivery.\n\n## Trusted owner channel\n\nAny managed role may declare a separate ours identity which fleet \u2014 never the agent \u2014\ncreates when missing and binds:\n\n```yaml\nowner_channel:\n identity: Coordinator Owner Channel\n owners: [authenticated-owner-contact-cid]\n agent: authenticated-managed-agent-cid\n interrupt: false\n progress_interval_ms: 30000\n comments: true\n attachments:\n enabled: true\n max_files_per_request: 4\n max_file_bytes: 10485760\n max_request_bytes: 20971520\n retention_ms: 86400000\n```\n\nPermanent role identities are also reconciled before launch. Fleet creates a\nmissing role identity with local exposure and local auto-accept enabled. A\nmissing owner-channel identity uses the safer inverse policy: both are disabled.\nThe short provisioning lease is released before the agent or channel binds.\nTemporary role identities remain connector-owned because their creating lease\ndefines their cleanup lifetime.\n\nThis does not replace the role identity. Normal identity mail remains untrusted\npeer input: the agent reads it through `get_messages` and replies through\n`send_message`. Mail arriving on the dedicated channel from a CID in `owners`\nis injected as a direct `[fleet-owner]` prompt. Mail from the exact `agent`\nCID is forwarded as a new message to the latest authenticated owner conversation;\nits files may also be relayed through this channel. A reply reference selects the\nowner of that authenticated source wire instead of the latest conversation.\nEvery other CID is rejected and warned about without reflecting its body. Fleet sends\naccepted/queued/progress/interrupted/failure notices and routes the ACP turn's\nfinal assistant text back to the authenticated sender with its source wire ID.\nFor file replies of every kind \u2014 a response artifact, a proactive note, or an\nin-turn attachment \u2014 the agent calls ours `send_file` to the channel identity\nand may pair it with a reply-linked caption; fleet, not the agent, chooses the\nowner. That is the only delivery route an agent is given: a tool call either\ndelivers or reports an error, where a file written to disk does neither.\nOwner messages whose trimmed text starts with `/` are deterministic\nsupervisor commands and never enter the model: `/help` (alias `/commands`),\n`/status`, `/comments [status|on|off]`, `/interrupt`, `/clear`,\n`/compact`, `/model <model-id>`, `/restart`, `/force-restart`, `/ls`,\n`/peek`, `/worklog`, and\n`/version`. Unknown or malformed commands answer with the help text instead of\nbeing forwarded; plain messages reach the agent unchanged. `/clear`,\n`/compact`, and `/model` are forwarded only when the role's bundled ACP\nadapter executes them locally (claude-code: all three; codex: `/compact`\nonly) and are otherwise refused with a notice, so slash text never reaches the\nmodel as a prompt.\n\nThe supervisor advertises the same primary registry entries as recipient-scoped\nours typed commands. Their single arguments field is converted back to the text\nafter the slash command name and enters the same dispatcher; aliases stay\nslash-only. Typed handlers repeat the live authenticated Owner-CID check before\ndispatch and return a null protocol completion because the existing correlated\nowner-channel reply remains the result.\n\nWhile a request runs, the agent's live ACP commentary is relayed as messages\nprefixed with the single stable label `\uD83D\uDFE1 Live update:`, so an owner can see\nexactly which messages the setting controls. `owner_channel.comments`\n(default `true`, so existing channels keep their current behavior) is the\nRESTART BASELINE; `/comments on|off` changes only the running session and is\ndeliberately not persisted, so a restart always returns to the checked-in\nconfiguration. `/comments status` reports the live value, the baseline, and\nwhether the backend emits live comments at all. Suppressing live comments never\nsuppresses receipts, progress notices, or the final answer.\n\nOwner documents, images, and voice messages use the same authenticated sender\nand source-wire boundary. Fleet inspects body-free metadata first and rejects\ndisabled, over-count, or over-size requests before selective\nretrieval. Unauthorized CIDs are never retrieved or answered. Reply-linked text\nand files from the same sender become one ordered request; a file-only wake also\nstarts a turn. Retrieved bytes must match their structured size and SHA-256,\nwhile MIME values, extensions, file categories, and declared-versus-detected mismatches\nremain report-only metadata. Symlinks or non-regular paths fail closed. Sanitized copies live only in a mode-0700 request directory as\nmode-0600 files and are removed after completion or bounded stale retention.\n\nThe legacy `attachments.allowed_mime` key is accepted and ignored so existing\nconfigurations keep loading; it is omitted from resolved configuration and cannot\naffect admission.\n\nVoice prompts include a bounded transcript only when typed daemon metadata reports success.\nFailure or unavailability is explicit and preserves the private audio path as the\ninput for direct review. Run `ours config show --json` and inspect `sttConfigured` without\nrevealing provider credentials.\nA mode-0600 message claim journal stores only wire ID, persistent-history\nsequence, and claim time. Fleet journals the exact body-free oldest-first slice\nbefore calling `getMessages` with that slice length, rejects a returned set\nmismatch, and loads a crash-recovered body only through `getHistoryItem`.\nThe attachment crash journal contains only authenticated CID and wire routing\ndata; it never stores captions, filenames, paths, transcript text, or bytes.\nJournaled read files resume through `getFileInfo` and `fetchFile`. A claimed\nagent caption is loaded from history and rejoined before the group is admitted. Fleet\nresolves one authenticated owner route before retrieving bytes, admits every file\nbefore emitting the caption or any file, and sends every part to that same route.\nUnknown correlated routes remain queued without retrieval and receive one bounded\ncorrelated notice. Admission rejection consumes the whole group with one NACK;\nonce emission starts, a transport error becomes terminal uncertain delivery and\nthe group is never blind-retried. Bounded v2 source-wire routing state is migrated\nfrom v1 on read. Corrupt state disables attachment admission rather than weakening\nprovenance checks.\n\nThe channel identity must be unique and must not be a role identity. The bridge\npersists bounded wire IDs only, never message/reply plaintext, and requeues input\nbefore starting its turn for at-least-once crash recovery. It currently requires\nthe structured agent-session interface so correlated final replies retain their\ndelivery guarantee.\n\n### Live contact and owner administration\n\nThe supervisor which is already running the managed role remains the sole binder of\n`owner_channel.identity`. The CLI reaches that exact live `OwnerChannel`\nthrough the role's token-authenticated, mode-0600 Unix control socket for contact\ninspection and setup; it never starts another ours client and never force-binds:\n\nRapid supervised restart is serialized by a role-scoped single-binder lease.\nThe predecessor closes its authenticated control socket and MCP proxy before\nreleasing ownership. The replacement waits at most five seconds and retries the\ndaemon bind only when PID/start-marker metadata proves the holder was the same\nrole and owner-channel identity. Foreign, live, corrupt, or otherwise\nunverifiable ownership remains fail-closed; fleet never uses `force=true`.\n\nIf that matching predecessor misses the bound, its still-authenticated control\nroute may send one fixed, digest-deduplicated recovery notice through the latest\nauthenticated owner conversation (or the sole configured owner). Notice\nplaintext is never persisted. With no safe deterministic route fleet guesses no\nrecipient and leaves the actionable failure in the web console and role logs.\nThe remote recovery action is `/restart`; inspect repeated failures with\n`ours-fleet logs <Role>` or the web console.\n\n```sh\nours-fleet owner-channel contact list <Role>\nours-fleet owner-channel contact invite <Role> [--name <label>]\nours-fleet owner-channel contact add <Role> (--invite-file <path> | --invite-stdin) [--name <label>]\nours-fleet owner-channel owner list <Role>\nours-fleet owner-channel owner authorize <Role> <exact-64-hex-contact-cid>\nours-fleet owner-channel owner revoke <Role> <exact-64-hex-contact-cid>\n```\n\nContact establishment and owner authorization are separate security steps.\n`contact add` never authorizes: invite redemption is pending until the peer\nverifies it. Once `contact list` reports the established contact, authorize\nits exact immutable CID explicitly. Invite creation emits invite material only\non stdout; acceptance reads it from a file or stdin, not argv.\n\nConfigured `owners` remain the baseline. On legacy channels without `agent`,\nlive authorizations/revocations are an immediately effective, restart-persistent\noverlay. Managed-agent CID gating makes fleet configuration authoritative and\ndisables live owner mutation and direct control-socket sends. `owner list` labels\nbaseline versus dynamic entries and effective status. The atomic mode-0600 file\ncontains bounded CIDs and audit actions only. Corruption disables all effective\nowners and refuses mutation rather than resurrecting authority; revoking the\nlast effective owner is always refused.\n\nA missing/stopped role, role without `owner_channel`, unavailable\nMCP client, or a role entering shutdown returns an actionable error with no\nside effects. Management uses no network listener and never logs or persists\ninvite material.\n\nFor any non-final message\u2014progress, blocker, suggestion, or later proactive note\u2014\nthe managed agent calls ordinary ours `send_message` to the channel identity.\nFleet checks only that the authenticated sender CID exactly equals `agent`, then\nforwards the text as a new message. There is no task/request/update type, phase,\nreply correlation, or owner recipient argument. A sole owner is the safe fallback;\nwith multiple owners and no inbound route history the relay fails closed. Devices\nsharing one identity share its CID; separate owner identities hand off the route\nwhen either sends channel mail. The ACP final is separate: fleet extracts it from\nthe completed turn and deterministically replies to the initiating owner wire.\n\nThe bounded mode-0600 route state stores CIDs, wire IDs, timestamps, delivery state,\nand hashes but never message plaintext. Unauthorized attempts produce a bounded\nCID-only owner warning; attempted bodies are neither reflected nor persisted.\n\nFor a mobile owner, establish the contact first, wait for peer verification,\nauthorize its exact CID, and revoke that same CID when access ends. The bounded\nmode-0600 CID overlay survives supervisor restart and remains fail-closed on\ncorruption. Update bodies remain memory-only. After a crash/restart, unfinished\ndeferred owner input follows the existing at-least-once replay path; the restarted\nsupervisor remains the sole binder.\n\n## Stable config and YAML migration\n\n`ours-fleet config --json` emits schemaVersion 1 resolved plans. Environment\nvalues and mission/persona/bio bodies are withheld; environment keys are sorted\nand values are marked redacted. Additive fields may appear in schema 1, while a\nremoval or semantic reuse requires a new schema version.\n\nYAML parsing always rejects duplicate keys. The current default\n`--yaml-mode compat` warns with file/line/column for anchors, aliases, explicit\ntags, non-scalar keys, and multiple documents. Use `--yaml-mode strict` in CI\nnow; strict becomes the next-major default and compat is the temporary migration\nescape hatch.\n\n## Bounded worklogs, auth proxy, and model recovery\n\nWORKLOG rotation is enabled by default with\n`worklog: { max_kb: 1024, keep_tail_kb: 256, max_archives: 12 }`. Maps may\noverride individual values; `worklog: false` on a role or in defaults opts out.\nFleet rotates only at that role's launch/resume lifecycle boundary. Concurrent\nchanges defer rotation. The active file keeps a bounded UTF-8 tail and advances\nto a line boundary when a complete line fits. If one logical line alone exceeds\nthe budget, its newest suffix remains and the rotation manifest records the\nmid-line start and omitted byte count. The complete prior inode receives a\ncollision-safe UTC archive name, and\n`.worklog-rotation.json` records restart provenance. `max_archives` bounds\nrecent archives beside WORKLOG.md; older complete archives move to\n`WORKLOG.archives/` without deletion. All archives share the role's sensitive\nstate boundary. Fleet refuses a symlinked/non-regular live log or a symlinked\ncold-archive boundary before replacing the live path and best-effort removes a\nduplicate publication left by a detected failure while the original inode is\nstill available. The manifest records SHA-256 digests for the archive and live\nbytes observed when it is written. These checks address ordinary path hazards,\nnot intentional path mutation by a malicious concurrent process with the same\nUnix authority; that is outside the threat model and requires OS-level isolation.\n\nACP tool diffs are bounded before entering web conversation events. Existing\nsmall before/after diffs are unchanged. Oversized whole-file snapshots are\nreduced to the actual changed region plus path, operation, original byte counts,\ndigest, and omission metadata. Each retained side is a newest-content UTF-8 tail\nof at most 64 KiB, advanced to a line boundary when a complete line fits. An\noverlong single line keeps its newest suffix and explicitly records a mid-line\nstart. Paths retain at most a 4 KiB suffix with byte count, digest, and omitted\nprefix metadata; the complete normalized update is capped at 320 KiB. A large\nappend therefore retains current appended content, not the historical prefix.\nThe live web-console transcript includes only the current runner generation and\nexcludes adapter session/load replay. Replayed events remain durable with\nagent_replay provenance for diagnosis and recovery.\n\n`auth_proxy: { kind: anthropic, base_url, required, health_url }` is Claude-only\nand loopback-only. Fleet injects only ANTHROPIC_BASE_URL and doctor rejects\ncredential env keys. The privileged reference companion is\n`contrib/anthropic-auth-proxy.mjs`; deploy it separately as a dedicated account\nwith a 0600 token file and per-role listener access. Fleet never installs it or\nreads its credential.\n\n`model_chain` is an ordered authorization list and its first entry must equal\n`model`. Only sustained high-confidence entitlement/quota 429 evidence advances\none entry. Transient 429, overload, auth, policy, and unknown errors never\ndown-shift. Runtime state is atomic in .model-recovery.json; exhaustion is\nfail-closed and held down. Change the declared chain/model and restart to\nreconcile explicitly; no chain preserves detection-only behavior.\n";
7
+ export declare const AI_DOCS = "# ours-fleet reference\n\nours-fleet runs persistent or temporary, identity-bound AI roles through a\nprovider-neutral managed-session interface:\n\n- harness: `claude-code` or `codex`\n- session: `acp` (default) or `codex-app-server` (Codex only)\n- lifetime: permanent (supervised, restartable) or `spawn --temp`\n\n## Discover and validate\n\n```sh\nours-fleet docs # this complete reference (`man` is an alias)\nours-fleet help <command> # exact flags for one command\nours-fleet config [-c FILE] # validate and print the merged plan; no changes\nours-fleet doctor [-c FILE] [--harness codex|claude-code]\nours-fleet version [--json] # build identity, capabilities, every install on PATH\n```\n\nConfiguration v2 is `~/fleet.yaml` plus typed bare documents under the exact\nstem directories `~/fleet/agents`, `~/fleet/agent_templates`, `~/fleet/roles`, `~/fleet/brains`, and\n`~/fleet/room_templates`.\nThe manifest owns fleet-wide operational defaults and automation; each Agent\nselects one inline/ref Role and Brain and carries its operational fields.\nAgent Templates under `~/fleet/agent_templates` are inert reusable launch definitions;\nonly explicit files under `~/fleet/agents` are persistent lifecycle instances.\nRoom members use `agent_template` and receive immutable content-addressed snapshots.\nAn Agent Template may declare up to 64 temporary-only named `loops`; persistent Agent\ninstances reject them. Each loop requires `interval` (1m..30d) and bounded\nnonblank `prompt`, with optional `enabled` (default true), `initial_delay`\n(default interval, 0s..30d), and `jitter` (default 0s, < interval, <=1h).\nExecution is fixed skip-if-busy with no ordinary missed-tick backlog/replay;\nrestart recovery may preserve at most one recent late occurrence.\nLegacy top-level `roles:` and `fleet.d` are rejected. Validate the complete\ntrusted source set with `config` and `doctor` before starting or restarting.\n\nPermanent `spawn` writes `~/fleet/agents/Name.yaml`. The web console edits an\nexplicit `{manifest, agents, agent_templates}` model while Role/Brain presets remain read-only.\nIts aggregate revision includes every Agent/Role/Brain/Room-template source, previews a\nredacted per-document diff in an exact-stem private staging tree, and saves under\none root lock with a private multi-file backup and full rollback. A no-op is\nbyte-identical and creates no backup.\n\n## Build identity and install provenance\n\n`--version` prints a semver and nothing else, and a semver does NOT identify an\nartifact. Version bumps land in a release commit of their own, so every build cut\nbetween two releases carries the PREVIOUS version while already containing new\nbehaviour. One host ran two installs that both reported 0.16.0 \u2014 same version,\ndifferent build. One accepted `monitor.interrupt: after_tool`, the other\nrejected it as invalid. Their\n`dist/cli.js` were byte-identical \u2014 the divergence was in other modules.\n\nEvery build therefore stamps `dist/build-info.json` with a build id (first 12 hex\nof a sha256 over the rest of `dist/`), the commit it was cut from, and the\ncapability tokens the shipped code declares \u2014 for example\n`monitor.interrupt.after_tool`. Ask any executable what it is:\n\n```sh\nours-fleet version # ours-fleet 0.17.0+9f1c2a3b4d5e, capabilities, PATH installs\nours-fleet version --json # the same as machine-readable JSON, no environment values\n```\n\nRead a capability, never a version number, to decide whether a setting is\nsupported. When a build rejects a value it knows the name of, it says which\ncapability is missing and which build rejected it, because another install on the\nsame host may accept the identical file. `config` prints the build that resolved\nthe plan; `status <Name>` says so when the build reporting on a role is not the\none that created it (roles record their creating build in `creation.json`).\n\n`ours-fleet doctor` runs an `install` check that lists every `ours-fleet` on\nPATH plus the one executing, and FAILS when two installs share a semver but are\ndifferent builds, or when the running artifact is a DIFFERENT artifact from the\none PATH resolves to. A second prefix holding identical content is not a skew\nand is not reported. A PATH entry the shell would not execute \u2014 a directory, or\na file without its execute bit \u2014 is not counted as an install at all.\nInstalls built before this stamp existed report `+unknown`; they are compared by\nhashing their `dist/` instead, so two pre-provenance installs are still told\napart. To fix a flagged host, remove or update the stale install \u2014 do not rely on\nPATH order.\n\n## Lifecycle and console commands\n\n```sh\nours-fleet init [-c FILE] # interactive missing-default seed; TTY required\nours-fleet up|down [Name...]\nours-fleet restart [Name...] # preserve/resume harness context\nours-fleet force-restart [Name...] # fresh context; briefing is reloaded\nours-fleet ls\nours-fleet status|peek|attach|logs Name\nours-fleet logs -f Name\nours-fleet send Name \"prompt\"\nours-fleet rm Name\nours-fleet watchdog-report <name> [run-id] [--list] [--json]\nours-fleet watchdog-run <name>\n```\n\n`init` is an interactive missing-default workflow that preserves existing files byte-for-byte.\nIt names the resolved manifest and split directory, asks a default-No confirmation,\nthen subscriptions (Codex, Claude, or both), model assignment (one explicit model for\nevery job or explicit development/review/coordination choices), one reasoning level,\nand a final default-No review. Quick/Balanced/Thorough generate low/medium/high.\nModel pickers show packaged supported IDs; catalog membership is not a recommendation\nor entitlement claim. Run `ours-fleet doctor` for local Codex availability; Claude\nentitlement is checked when a role launches. The generated brains contain no\n`model_chain`, so Fleet never silently substitutes another model.\n\nAt either confirmation, N, Enter, Escape, Ctrl-C, Ctrl-D, or EOF cancels. In a picker,\nEscape, Ctrl-C, Ctrl-D, or EOF cancels; Enter records the highlight or continues a\nnon-empty multi-select, N is ignored, and an empty subscription selection remains blocked.\nEvery cancellation before final approval performs no host or configuration mutation.\nRedirected/non-TTY invocation is refused with the same guarantee. After the final Yes,\nhost setup precedes publication. Path ownership/type/mode/symlink and\nsame-filesystem checks run before host setup and again under a per-setup lock. Publication\nstages and validates the complete combined setup, backs up whichever old target(s) exist,\nand retains a private recovery record. A hard process/host termination cannot promise\nrollback; inspect host integration and private init stage/recovery evidence.\n\n`peek`, `attach`, and text `send` use the structured agent session.\nAttachment also accepts `/permit <permission-id> <option-id>`, `/interrupt`,\nand `/detach`.\n\n## Local web console\n\nThe npm package includes the web console; installed users do not clone the repo\nor run `npm run build`:\n\n```sh\nnpm i -g @ours.network/fleet\nours-fleet init\nours-fleet doctor\nours-fleet web # install/update service, start, pair browser\n```\n\nThe normal command uses stable `http://127.0.0.1:49271/`, installs an\nowner-level systemd user service (Linux) or LaunchAgent (macOS), and opens a\nfive-minute one-use pairing link in the local browser. After pairing, bookmark\nthe plain URL or install the PWA. To pair a new, signed-out, or revoked browser,\nrun `ours-fleet web open`.\n\n```sh\nours-fleet web status\nours-fleet web start|stop|restart\nours-fleet web open\nours-fleet web revoke-all # revoke every browser and active session\nours-fleet web uninstall\nours-fleet web serve --port 0 --no-open # isolated foreground/testing mode\n```\n\nThe console is IPv4-loopback-only by default. Both `localhost` and\n`127.0.0.1` are accepted locally. For an nginx/TLS reverse proxy, keep the\ndefault bind and declare the exact browser origin:\n\n`ours-fleet web install --public-origin https://fleet.example.com --password-file /secure/fleet-password`\n\nFleet reads the password file during setup and persists only a salted scrypt\nverifier. New browsers authenticate and retain rotating HttpOnly/SameSite\ntrusted-device credentials. If nginx already authenticates, the operator may\ndeliberately select `--no-password`; the CLI and browser warn that anyone\nreaching the origin can control the fleet. First setup requires an explicit\nchoice: `--password-file` or `--pairing` for protected access, or\n`--no-password` for intentional unprotected access.\n\nUse `--bind ADDRESS` only for an intentional direct listen. A non-loopback\nbind is rejected unless `--public-origin` is also present. Host/Origin checks\nuse the declaration and do not trust forwarded headers. Configure nginx to\nproxy HTTP and WebSocket upgrades to `127.0.0.1:49271` and terminate TLS;\nfleet accepts nginx's loopback upstream Host, so no Host rewrite is required.\nBrowser credentials add Secure for HTTPS, and `revoke-all` invalidates all\ntrusted devices. Role creation offers harness-scoped known-model choices\nwhile still accepting a typed model ID; blank explicitly uses the selected\nharness's own default.\n\n## Spawn\n\n```sh\nours-fleet spawn [--temp] [Name | --name Name] \\\n --brain BRAIN_ID --role ROLE_ID \\\n --cwd /absolute/path --identity Identity --coordinator Coordinator \\\n --approval ask|auto|allow \\\n --filesystem read-only|workspace|unrestricted \\\n --unattended deny|wait --isolation-file /path/isolation.yaml\n```\n\nPermanent spawn writes `~/fleet/agents/Name.yaml` and starts a supervised role.\n`--temp` writes active state under `~/.ours-fleet/tmp` and starts an independent\ntransient supervisor (a collected systemd unit or submitted launchd job). It is\nnot enabled across reboot and does not die when the role that spawned it restarts.\nBrain definitions own the managed session backend. When a temporary role's bound identity\ncloses or its session ends, the supervisor, monitor and live roster entry retire\ntogether; state moves intact to `~/.ours-fleet/recovery/temporary` with a\ntermination record. Failed launches use the same archive rather than deleting\ntheir briefing, provenance, logs or partial supervisor metadata.\n\nNamed `down` and `rm` commands can target an exact state-backed temporary role\neven though it is absent from merged fleet YAML. The recorded transient unit/job\nis authoritative. Missing/incomplete ownership metadata is reconciled only from\nan exact `_run-temp <role>` process-table match: one match may be adopted, zero\nsettles as stopped, and ambiguity or an unreadable table fails closed. Launching\nrecords receive a bounded grace so a not-yet-registered transient unit cannot be\nmistaken for a stopped one. Stale recorded supervisors are reclaimed in bounded\nbatches by moving their state to the same recovery archive, never by blind deletion.\n\nEvery temporary role creates a new session-owned identity by calling ours MCP\n`create_temporary_identity` with its exact assigned name. It never binds a\npre-existing identity and never falls back to permanent `create_identity`.\nFleet does not inspect, preserve, or provision an ours identity for temporary\nspawn; creation belongs exclusively to the launched temporary agent session.\nCollisions, missing tool support, and creation errors stop safely without\nforce-adopting or deleting identity state. Permanent roles\nare provisioned by fleet before launch and never delegate normal identity\ncreation to the harness.\n\nThe temporary supervisor treats its first positive identity observation as the\nlifecycle readiness gate: a cold harness may take as long as needed to read its\nbriefing and bind, without a fixed first-bind retirement timer. After readiness,\nonly sustained authoritative absence closes the role. Unreachable, malformed, or\nvalid-but-empty daemon indexes are ambiguous and reset closure debounce rather\nthan becoming cleanup authority.\n\nInside a managed role, public `ours-fleet` commands cross an authenticated\nsupervisor attribution boundary before Commander parsing. The original CLI remains\nthe executor inside the role's existing OS sandbox, and ordinary CLI validation is\nthe source of truth. Hidden worker entry points remain internal; public lifecycle and\noperator commands are not restricted by the proxy.\n\nCommand invocation, raw argv, read-only work, validation failures, and generic\noutcomes are never forwarded to the Owner-visible channel. Fleet announces only\nconfirmed Agent, Task, and Room lifecycle changes. Local diagnostics retain\nstructurally redacted command metadata. Lifecycle delivery uncertainty is logged,\nnever recursively announced, and never reruns or blindly retries an effect.\nRoom participant summaries describe creation and activation. Fleet has no public\npost-create Room membership mutation, so it does not claim a separate membership event.\n\nOmitted Brain and Role selections, working directory, coordinator, neutral permissions,\nand fleet monitor policy inherit from the calling Agent. Explicit options always win.\nIdentity, mission/profile text, environment, owner routing, auth proxy, room startup,\nisolation, worklog, and sensitive inline Brain values never inherit implicitly.\nThis automatic proxy is a convenience and\nattribution mechanism, not an isolation boundary: an unrestricted role can still\ninvoke another binary path directly. Host/operator shells keep the ordinary direct\nCLI behavior.\n\nBrain owns harness, session, model, reasoning effort, token limits, and native harness\noptions. Removed runtime flags are rejected with migration guidance rather than silently\nreinterpreted. A selection is a stable ID or an explicit `inline:{...}` mapping.\n\nPackaged Developer, Critic, and LocalCoordinator Agent Templates set\n`monitor: { mode: fleet, interrupt: after_tool }`. Every member of the standard\n`single`, `pair`, and `team` Room Templates therefore resolves to fleet-owned,\nafter-tool delivery. Explicit per-member and custom Agent Template values remain\nauthoritative and merge key by key.\n\nManaged ACP stall recovery is opt-in: `monitor: { mode: fleet, stall_recovery: true,\n stall_timeout_ms: 900000 }`. The validated timeout is 60000\u201386400000 milliseconds.\nOmitted/false preserves existing behavior. Silence is measured from meaningful live\nprogress; replay and retry chatter do not reset it. Strong authenticated retry\nevidence requires one window, generic silence two. Tools, permissions, modal or\nunknown boundaries, steering and human cancellation protect the turn. Recovery\nuses one bounded cancel and diagnostic continuation in the same ACP session/queue\nslot; it never restarts the adapter. Startup and queued mail wait behind recovery.\nA durable claim permits at most one automatic attempt per ACP session ID, including\nacross supervisor restarts; later mail is non-cancelling. Failed or re-stalled\nrecovery reports a blocker. Inspect `.stall-recovery/audit.jsonl` and recorded\nterminal events before continuing; never replay ambiguous or completed mutations.\nNative monitoring/non-ACP sessions are unchanged. No room or identity coupling.\n\n## fleet.yaml\n\n```yaml\napi_version: ours.network/fleet/v2\nvars:\n work_root: /home/me/work\nstart_stagger_ms: 0\ndefaults:\n permissions:\n approval: ask\n filesystem: workspace\n unattended: deny\n monitor:\n mode: fleet # fleet (default) | native\nwatchdogs:\n nightwatch: # [A-Za-z0-9_-], must not collide with a role name\n coordinator: FleetCoordinator # required \u2014 where alerts go\n # everything below is optional\n enabled: true # default true; false = configured but never scheduled\n interval: 10m # default 10m; 30s | 10m | 2h, minimum 1m\n watch: [Alice, CodexReviewer] # explicit lists are exact; omit for configured + live temp roles\n agent: { ref: WatchdogAgent } # required: declared Agent ID, or canonical inline Agent definition\n identity: Watchdog-nightwatch # default: Watchdog-<name>\n timeout: 5m # default 5m; a run past this is killed and recorded as error\n keep_reports: 50 # default 50 reports retained per watchdog\n alert_cooldown: 60m # default 60m before the same finding alerts again\n prompt_file: /abs/extra.md # optional extra focus, APPENDED to the fixed contract\n```\n\nAn Agent is a separate bare document under `~/fleet/agents/<ID>.yaml`:\n\n```yaml\nrole: { inline: { mission: Coordinate work and delegate implementation. } }\nbrain: { inline: { harness: codex, session: codex-app-server, model: gpt-model-id } }\nidentity: Coordinator\ncwd: ${work_root}/project\noversee: [{ agent: Worker, interval: 5m }]\n```\n\nA watchdog observes and reports; it never restarts, stops, spawns, or removes a\nrole, answers a pending permission, edits a workspace, or approves anything on\nthe owner's behalf. `watchdogs:` may appear only in the base config\n(`~/fleet.yaml` or `-c FILE`); Agent/Role/Brain documents never own it.\nThe selected Agent owns Brain, Role, permissions, isolation, and every other\nagent setting. Legacy watchdog `harness`, `model`, `session`, and\n`isolation` fields fail with migration guidance.\nWhen `watch:` is omitted, each run watches the configured roles plus temporary\nfleet roles that are live when the run starts. An explicit `watch:` list is\nnever augmented.\n\nAgent operational values override manifest operational defaults. Role and Brain\nownership never cross-merges. `${name}` substitutes entries from `vars`.\nBrain fields include `max_tokens` and `autocompact_pct`; isolation is Agent-owned.\nUse README.md for the complete isolation policy and resource-cap schema.\n\nSupervised roles connect to the operator-configured ours daemon; they do not own its\nlifecycle. Fleet strips the obsolete, presence-sensitive `OURS_AUTOSTART` variable from\nagent-session children; `ours-mcp proxy` is client-only and never starts a daemon. Start\nthe shared daemon only through an explicit operator or installer/setup flow.\n\n## Rooms and tasks\n\n`init` materializes editable `single`, `pair`, and `team` Room templates plus\ntheir exact-cased Agent, Role, and Brain presets. The command prints the packaged\npreset revision and source directory. Inspect provenance and content before use:\n\n```sh\nours-fleet config [-c FILE]\nours-fleet template list [-c FILE]\nours-fleet template show team [-c FILE]\nours-fleet task create --title \"Solo task\" --template single [-c FILE]\nours-fleet task create --title \"Reviewed change\" --template pair [-c FILE]\nours-fleet task create --title \"Phased delivery\" --template team [-c FILE]\nours-fleet spawn --temp Scout --role SELECTION --brain SELECTION --loops-file PRIVATE.yaml\nours-fleet task start TASK --member developer --loops-file PRIVATE.yaml\nours-fleet task start TASK --member critic --no-loops\n```\n\n`--loops-file` must be an owner-only, non-symlink regular file <=1 MB containing\nexactly one top-level non-empty `loops:` mapping. `--no-loops` explicitly\ndisables loops. They are mutually exclusive and rejected for permanent spawn.\nFor a grouped room member the whole CLI block overrides its Agent Template;\nthe template overrides omission. Omission preserves historical no-loop behavior\nand never inherits manifest wildcard loops. Fleet validates before side effects,\nseals normalized timings plus exact private prompts, and reuses that snapshot for\nidempotent start, retry, recovery, and replacement. Trusted authoring and the\nprivate sealed runtime retain exact prompts; resolved launch, task, room,\nprovenance, and audit presentations show source, policy, timing, prompt bytes,\nand prompt SHA-256 instead of prompt text.\n\nAn alternate manifest `-c /path/custom.yaml` uses `/path/custom/` as its split\nroot. Repeated init only fills missing files and never adopts a newer default.\nExact known revision-3 through revision-5 packaged-bootstrap and generated role defaults have an exact-semantic,\nfail-closed migration (dry-run by default):\n\n`ours-fleet migrate-role-defaults [-c FILE]`\n`ours-fleet migrate-role-defaults [-c FILE] --write`\n\nReview removals, replacements, additions, preserved custom files, staging path,\nand recovery path. Same-named custom files stay byte-identical; dangling custom\nreferences refuse publication, and a successful rerun is a no-op. For explicit\nsingle-file adoption, copy from init's reported packaged source beside the target\nas `.new-default`, inspect `diff -u TARGET TARGET.new-default`, then replace it.\n\nThe exact generated six-worker legacy starter Agent set has its own fail-closed\nmigration (dry-run by default):\n\n`ours-fleet migrate-agent-templates [-c FILE]`\n`ours-fleet migrate-agent-templates [-c FILE] --write`\n\nReview the dry-run moves, addition, staging path, and retained recovery-backup path\nbefore `--write`. Customized/partial known starters and unsafe trees refuse without\nmutation; unrelated custom persistent Agents remain persistent. A manifest-level template\nmay shadow a same-named file only with `override_builtin: true` and a higher\nversion; this compatibility marker is deprecated and reported as a diagnostic.\n\nRooms always use `ours-cowork`; there is no room-provider selector. Configure\nthe cowork daemon connection and room owner directly:\n\n```yaml\nrooms:\n cowork:\n config: /home/me/.ours-cowork/config.json\n owner:\n expected_cid: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n public_invite_file: /home/me/.ours-fleet/owner-room-invite.txt\n defaults:\n template: team\n attach_owner: true\n close_when_task_done: true\ntasks:\n default_room_template: team\n create_mode: start\n close_room_on_done: true\n```\n\nFleet launches each template member with a dedicated one-time Cowork invite.\nThe generated temporary-agent briefing contains the exact identity name, invite,\nCowork role, and task. The agent creates that identity itself with ours MCP\n`create_temporary_identity`, accepts the invite with `add_contact`, and starts\nwork immediately. A room is ready only after the Cowork room (and its task, when\ntask-bound) is durably active, every configured member seat is authenticated and active with its matching\nlive Fleet launch, and the configured Owner seat is active when owner attachment is\nenabled. There is no briefing hash, startup ACK, or separate role-briefing readiness\ngate.\n\nNormal Task provisioning emits exactly one authenticated Owner lifecycle notice after\nthe ready predicate above is true; standalone Room provisioning likewise emits one\nready notice. Intermediate task, saga, member-spawn, timeout, and recoverable-failure\ntransitions stay in local state and logs. A terminal failed Task emits one actionable\nfailure notice; the command result carries the exact blocker and canonical recovery\naction.\n\n`task start` and create-and-start wait for readiness. If their bounded wait expires,\nthey return an explicit `in_progress` result and start a safe continuation. The detached\ncontinuation is serialized per Task and remains alive until convergence or an\nOwner-action blocker. Re-running `task start <id>` safely resumes the same durable\nprovisioning operation after the blocker is corrected or a process restarts.\n\nSet `room.anonymous: true` on a room template, or pass `--anonymous` to\n`task create`, `task start`, `task work`, or `room create`, to create an\nanonymous Cowork room. `--no-anonymous` explicitly overrides an anonymous\ntemplate. Fleet records the resolved value before room creation so retries keep\nthe same choice. Temporary members of an anonymous room are instructed to call\n`create_temporary_identity` with `expose_local=false`. Their generated briefings\ndo not disclose or compare an Owner participant CID. A participant-originated\ninstruction has Owner authority only when the authenticated Cowork room envelope\nattributes that participant seat the exact `Owner` role. Literal text, display\nnames, ordinary direct messages, and room-authored or rest-role messages with an\nOwner-looking label never grant that authority. Non-anonymous rooms remain pinned\nto the exact authenticated Owner CID.\n\nHuman task and room results use the same compact Markdown presentation in the\nCLI and authenticated owner channel: a short heading, icon-plus-word status,\ncode-formatted identifiers, bounded summaries, and actionable recovery or error\nsteps. Untrusted prose is context-escaped and control characters are neutralized;\nMessenger-bound results are capped at 3,500 Unicode code points and 12,000 UTF-8\nbytes with structural omission notices. `--json` bypasses this presentation layer\nand retains the versioned machine schema and serialization order.\n\nEvery task belongs to a named list. The built-in `default` list always exists,\nand legacy tasks or create calls without `--list` resolve to it. Use `task lists`,\n`task list-create <name>`, `task list-rename <name> <new-name>`, and\n`task list-delete <name> [--move-to <destination>]` to manage lists. A non-empty\nlist cannot be deleted without an explicit, different destination; Fleet moves\nthe assignments and never deletes the tasks. `task move <id> --list <name>`\nchanges only organizational metadata. `task list --list <name>` filters and\n`--group-by-list --json` returns deterministic groups.\n\nList names are NFC-normalized, case-sensitive, and limited to 64 Unicode code\npoints. Leading/trailing whitespace, controls, format/path characters, normalized\nduplicates, and the reserved exact name `default` are rejected. The authenticated\nowner channel provides the matching `/task` subcommands, while authenticated web\nclients use `/api/v1/task-lists`, `/api/v1/tasks`, and\n`/api/v1/tasks/:id/list`; every adapter delegates to the same application service.\nMessenger's multiline command grammar treats surrounding whitespace on each\nvalue line as transport framing; the canonical value passed to the shared service\nis the trimmed line. CLI arguments and REST strings are passed verbatim.\n\nOlder prerelease files with the exact legacy `provider: cowork` key under\n`rooms:` still load, but the key is ignored and omitted from resolved\nconfiguration. Remove it when editing the file. Any other legacy value is an\nerror. The optional `rooms.owner.provider` setting is separate and defaults to\n`messenger-server`.\n\nFinish and Delete are distinct terminal task actions:\n\n`ours-fleet task finish <id>` moves an active or review task to `done` and\ndeletes its associated Cowork room after retiring its members. The room then\ndisappears from normal Fleet and Cowork views; its brief, messages, repository\nreferences, and attachments are not retained as an inspectable archive.\nThe prerelease configuration names `tasks.close_room_on_done` and\n`rooms.defaults.close_when_task_done` are retained for compatibility, but\n`true` now means this close-then-delete behavior.\n\n`ours-fleet room delete <id> <id>` is the canonical destructive room command.\n`room close <id> <id>` remains a deprecated alias with identical deletion\nsemantics. Older prerelease `closed` room records are deleted directly the next\ntime `room list` reconciles Fleet with Cowork.\n\n`ours-fleet task delete <id> <id>` permanently deletes a task in ANY lifecycle\nstate \u2014 backlog, provisioning, active, blocked, review, done, cancelled, failed,\nor partially settled. The exact task ID is required twice for confirmation. A\ndurable deletion intent is persisted before any side effect; the cleanup worker\nthen retires managed room members with evidence, closes and deletes an attached\nroom (tolerating already-missing remote rooms), releases the sealed launch\nsnapshot, and unlinks the task record last. While cleanup settles the task is\nhidden from normal listings and every lifecycle mutation is rejected; if\ncleanup cannot complete (for example Cowork is unreachable), the deletion stays\nin a precise resumable state \u2014 repeat the identical delete command to converge\nafter outages, crashes, or restarts. Deletion\nnever fabricates a `done` transition. A metadata-only deletion receipt\n(acceptance actor, original state, timestamps, completion) is retained under\n`deletion-receipts/` as durable audit evidence. An already-missing task is an\nidempotent no-op. The Owner-channel equivalent is `/task delete <id> <id>`; the\nmanagement API equivalent is `DELETE /api/v1/tasks/<id>?confirm=<id>` (200 when\nsettled, 202 while pending; `GET /api/v1/tasks?includeDeleting=true` exposes\ndeletion-pending tasks to operators).\n\n## Permissions\n\nPrefer the harness-neutral `permissions` block:\n\n- `approval: ask|auto|allow`: portable permission policy. `deny` remains a\n deprecated, fail-closed compatibility alias for existing fleet files.\n- `filesystem: read-only|workspace|unrestricted`: filesystem intent\n- `unattended: deny|wait`: what a managed session does when no console can\n answer a request\n\nThe backend translates this common intent. Native Codex app-server roles reject\npermission aliases in `harness_options`; Codex ACP and Claude retain their\nlegacy native-override compatibility. Do not choose `allow`/`unrestricted`\nor Claude `bypassPermissions` without explicit authorization.\n\n### Creation-time isolation\n\n`ours-fleet spawn --isolation-file <path>` supplies a role's sandbox policy at\ncreation, so the FIRST launch is already confined \u2014 a role that only gains\n`isolation:` on a later `up` ran unsandboxed until then.\n\nThe file holds exactly the `isolation:` mapping documented above and nothing\nelse \u2014 the same schema, validated by the same code, so a policy written here\ncannot mean something different from the identical block in fleet.yaml:\n\n```yaml\nnetwork: deny\nfs:\n read: [/opt/reference]\nresources:\n mem: 2G\n```\n\nInvalid files are rejected before anything is created: no config, no state\ndirectory, no identity reservation. Works for both permanent and `--temp` roles.\n\n### Never-prompt failure\n\nThe failure this section exists to prevent leaves no error message anywhere.\n\nAn unattended role has no console. When the harness needs a permission decision\nthere is nobody to ask, so the request is refused INSIDE the harness \u2014 no\nprompt, no error, no log line. The agent simply does less than its briefing told\nit to, reports success, and nothing distinguishes that from having done the\nwork. Two settings produce it:\n\n1. a permission mode that suppresses the prompt without granting the action\n (Claude `dontAsk`, which is why neutral `allow` maps to\n `bypassPermissions` instead); and\n2. `unattended: deny`, which refuses every request that reaches it.\n\n**Automatic decisions are now recorded.** Every permission request decided\nwithout a human emits a completed event into\n`~/.ours-fleet/agents/<Name>/.session-events.jsonl` carrying the decision,\nwhether policy or a person made it, the policy that produced it\n(`permissions.unattended=deny` vs `permissions.approval=deny`/`=allow`),\nthe reason, and the option selected. `ours-fleet peek` and `attach` render\nthem. Automatic denial asks for a one-shot rejection, never a standing one, so a\nsingle unattended refusal cannot disable a tool for the rest of the session.\n\nA role that can auto-deny logs one line at startup saying so.\n\nTo detect an under-permissioned role BEFORE it runs, use the capability floor\nbelow: `ours-fleet doctor` fails such a role rather than letting it discover\nthe problem silently at work.\n\n### The unattended capability floor\n\nAn unattended role has no console, so a permission request cannot be answered \u2014\nit is refused, silently, inside the harness. The agent then does less than it\nwas told to and reports no error. To make that visible before launch,\n`ours-fleet config` and `ours-fleet doctor` resolve each role's neutral\npermissions through its harness and check the result against a fixed floor:\n\n- `read-state` \u2014 read its briefing, ROUTINES.md, and WORKLOG.md\n- `write-state` \u2014 append its WORKLOG and its own state files\n- `messaging` \u2014 bind its identity, send and receive ours mail\n- `monitor` \u2014 arm and observe its mail monitor\n- `workspace-edit` \u2014 edit and test files in its working directory\n- `status-commands` \u2014 run the inspection commands its briefing prescribes\n\n`doctor` reports this per role as `unattended floor: <Role>`. A role with\n`unattended: deny` that cannot meet the floor FAILS doctor, because it will\ndeny those requests with nobody to see it; with `unattended: wait` it warns,\nbecause a human can still attach and answer.\n\nSecurity meaning: native Codex maps `ask` \u2192 `untrusted`, `auto` \u2192\n`on-request`, and `allow` \u2192 `never`; its independent filesystem mapping is\n`read-only` \u2192 `read-only`, `workspace` \u2192 `workspace-write`, and\n`unrestricted` \u2192 `danger-full-access`. Users configure only the Fleet names.\nClaude maps `ask` to `default`, `auto` to `acceptEdits`, and `allow` to\n`bypassPermissions`. Codex ACP retains its adapter-specific coupled modes:\n`auto` selects `agent`, while `allow` selects `agent-full-access`. These\nmodes genuinely permit the actions the role was authorized to take \u2014\n`dontAsk` only suppresses the prompt while still refusing the action. Nothing\nother than an explicit `allow` becomes non-interactive. Legacy `deny` keeps\nits conservative Codex `on-request` / Claude `plan` translation. `allow` is therefore a real grant and\nrequires explicit authorization; per-role `isolation:` remains the outer\nboundary that a permission mode cannot cross.\n\nACP carries agent-advertised session mode IDs and `session/set_mode`, but those\nIDs are agent-specific and ACP defines no portable permission-policy capability.\nFleet therefore uses the ACP primitive where an adapter exposes a matching mode\nand otherwise performs the harness translation above. The bundled Codex ACP\nadapter couples approval and sandboxing in its advertised mode IDs. Neutral\n`allow` therefore selects `agent-full-access` and widens `filesystem:\nworkspace` or `read-only` to `danger-full-access`; neutral `auto` selects\n`agent` and `workspace-write` even when the neutral filesystem value differs.\nAn explicit `harness_options.sandbox` selects its corresponding ACP preset and\nstill wins, as does an explicit native approval override. `config` and\n`doctor` report a coupled-mode mismatch as approximate. Use per-role\n`isolation:` as the outer boundary for an `allow` ACP role. The live session\nreports both its effective normalized mode and the exact native mode selected.\n\nSee also: `spawn --approval/--filesystem/--unattended` set this intent at\ncreation, and `ours-fleet config` prints each role's neutral settings, their\nnative translation, and any warning \u2014 the same text `doctor` reports.\n\nClaude `harness_options`: `permission_mode` (default, acceptEdits, plan,\ndontAsk, bypassPermissions), `plugins`, `mem_palace`,\n`mem_palace_midsession_autosave`, `mcp_servers` and `mcp_servers_only`.\n\n`mcp_servers` declares MCP servers for the role, in `.mcp.json`'s own shape\n(a map of name to `{ command, args, env }`, or `{ type: http|sse, url,\nheaders }`). By default they are ADDED to whatever the OS user running the role\nalready has configured. The Claude Code adapter sends them in `session/new`.\n\nWhen `mcp_servers` is absent, Fleet sends ACP's protocol-required empty\n`mcpServers` array without an exclusive override, so the agent keeps its inherited\nservers. An explicitly empty configured set is different: Fleet preserves that intent\nthrough the bundled adapter's compatibility path and disables every inherited server.\n\n`mcp_servers_only: true` makes the declared set EXCLUSIVE through\n`strictMcpConfig`. It is all-or-nothing and it ignores every\nother MCP configuration: project `.mcp.json`, user settings, and **plugins**.\nThe ours connector is normally installed as a plugin, so a strict role that does\nnot re-declare it has no `send_message` and no `get_messages` \u2014 it cannot even\nreport that it has gone mute. Fleet therefore refuses a strict role whose\n`mcp_servers` does not name the connector; declare it explicitly, e.g.\n`ours: { command: ours-mcp, args: [proxy] }`.\n\nBoth options, and `plugins`, reach an ACP session through the bundled Claude ACP\nagent's `_meta` vocabulary. A role that sets `session_options.acp.command` runs\nan agent fleet did not choose and cannot be promised them, so that combination is\nrefused at validation rather than accepted and dropped. This narrows a role's\ntool surface; it does not stop the harness deferring tool schemas, which is the\nharness's own decision.\n\nCodex `harness_options`: `launcher` (auto, ours-codex, codex), `search`,\n`config`, `add_dirs`, and `monitor`; Codex ACP additionally supports\n`profile`. Native app-server roles reject `profile` because Codex does not\naccept `--profile` for `app-server`. They\nmust express approval and filesystem authority through the shared\n`permissions:` block, never through harness options. The adapter translates\n`ask|auto|allow` to Codex `untrusted|on-request|never` and translates\n`read-only|workspace|unrestricted` to Codex\n`read-only|workspace-write|danger-full-access`. Native `config` currently\nallows only `model_reasoning_effort`; ACP retains the broader Codex config surface.\n\nFor Codex, the opt-in `session: codex-app-server` directly runs Codex's native\nJSONL app server behind Fleet's provider-neutral session contract. It supports native item\nstreaming, commentary/final phases, prompt admission, steering, interruption,\npermission requests, durable conversation projection, and thread resume. Packaged\nCodex brains and the init wizard continue to select `session: acp` for compatibility;\nClaude Code also uses ACP. Native Codex defaults to `codex app-server` (or `ours-codex app-server`\nwhen launcher auto finds it). Override the exact command when necessary:\n\n`session_options: { codex_app_server: { command: [codex, app-server] } }`\n\nAn exact command override receives no appended profile, search, or subcommand\narguments. Native sessions persist their Codex thread in Fleet's `.session-id`\nand participate in its bounded fresh/resume recovery; cross-provider conversation\nportability is never assumed.\n\n## ACP adapters\n\nThe maintained `@agentclientprotocol/codex-acp` and\n`@agentclientprotocol/claude-agent-acp` runtimes are bundled automatically as\noptional ours-fleet dependencies. The supervisor resolves their executable\nentrypoints internally, so default ACP roles do not depend on global PATH.\nours-fleet and both maintained adapters require Node 22 or newer.\n\nOverride an adapter only when necessary with `session_options.acp.command`\n(string or argv list). If optional dependencies were deliberately omitted,\nours-fleet falls back to a compatible globally installed `codex-acp` or\n`claude-agent-acp`. `ours-fleet doctor -c FILE` verifies the resolved adapter.\n\n## Reliable mail wake\n\n`monitor.mode` selects exactly one wake owner:\n\n- `fleet` (default): the ours-fleet supervisor consumes body-free daemon\n events and advances its durable cursor only after delivery is accepted. ACP\n uses live steering when supported and falls back to structured\n `session/prompt`.\n- `native`: ours-fleet starts no supervisor monitor; the generated briefing\n instructs Claude Code or Codex to arm its harness-native wake mechanism.\n\nSet `monitor.interrupt: true` in fleet mode to cancel active work before every\nconfigured wake. Set it to `after_tool` to preserve an active ACP tool (and any\npending permission), then steer the wake at the first tool-terminal boundary\nwithout cancellation. A hung boundary is bounded at 120 seconds and falls back\nto non-cancelling steering/queueing; adapters without authenticated tool events\nuse the same conservative fallback. Explicit human/control interrupts remain\nimmediate. The policy is content-blind because the supervisor cannot inspect\nencrypted message bodies. Message bodies are released only when the role calls\nthe ours `get_messages` tool.\n\nThe default is `false`. For a temporary role whose mission intentionally arrives\nafter its readiness announcement, set `mode: fleet` and `interrupt: true`\nexplicitly. The readiness announcement does not change the transport: the\nmission remains ordinary ours mail, fleet injects only the body-free wake, and\nthe role calls `get_messages` before acting. Every later configured wake uses\nthe same interruption policy.\n\nLegacy `monitor.enabled: true|false` remains accepted as an alias for\n`mode: fleet|native`; use `mode` in new configuration. Codex's separate\n`harness_options.monitor: true` is native-monitor consent, not monitor-owner\nselection.\nInspect `ours-fleet status Name`, `peek Name`, role logs, and\n`~/.ours-fleet/agents/Name/.monitor-status` when diagnosing delivery.\n\n## Trusted owner channel\n\nAny managed role may declare a separate ours identity which fleet \u2014 never the agent \u2014\ncreates when missing and binds:\n\n```yaml\nowner_channel:\n identity: Coordinator Owner Channel\n owners: [authenticated-owner-contact-cid]\n agent: authenticated-managed-agent-cid\n interrupt: false\n progress_interval_ms: 30000\n comments: true\n attachments:\n enabled: true\n max_files_per_request: 4\n max_file_bytes: 10485760\n max_request_bytes: 20971520\n retention_ms: 86400000\n```\n\nPermanent role identities are also reconciled before launch. Fleet creates a\nmissing role identity with local exposure and local auto-accept enabled. A\nmissing owner-channel identity uses the safer inverse policy: both are disabled.\nThe short provisioning lease is released before the agent or channel binds.\nTemporary role identities remain connector-owned because their creating lease\ndefines their cleanup lifetime.\n\nThis does not replace the role identity. Normal identity mail remains untrusted\npeer input: the agent reads it through `get_messages` and replies through\n`send_message`. Mail arriving on the dedicated channel from a CID in `owners`\nis injected as a direct `[fleet-owner]` prompt. Mail from the exact `agent`\nCID is forwarded as a new message to the latest authenticated owner conversation;\nits files may also be relayed through this channel. A reply reference selects the\nowner of that authenticated source wire instead of the latest conversation.\nEvery other CID is rejected and warned about without reflecting its body. Fleet sends\naccepted/queued/progress/interrupted/failure notices and routes the ACP turn's\nfinal assistant text back to the authenticated sender with its source wire ID.\nFor file replies of every kind \u2014 a response artifact, a proactive note, or an\nin-turn attachment \u2014 the agent calls ours `send_file` to the channel identity\nand may pair it with a reply-linked caption; fleet, not the agent, chooses the\nowner. That is the only delivery route an agent is given: a tool call either\ndelivers or reports an error, where a file written to disk does neither.\nOwner messages whose trimmed text starts with `/` are deterministic\nsupervisor commands and never enter the model: `/help` (alias `/commands`),\n`/status`, `/comments [status|on|off]`, `/interrupt`, `/clear`,\n`/compact`, `/model <model-id>`, `/restart`, `/force-restart`, `/ls`,\n`/peek`, `/worklog`, and\n`/version`. Unknown or malformed commands answer with the help text instead of\nbeing forwarded; plain messages reach the agent unchanged. `/clear`,\n`/compact`, and `/model` are forwarded only when the role's bundled ACP\nadapter executes them locally (claude-code: all three; codex: `/compact`\nonly) and are otherwise refused with a notice, so slash text never reaches the\nmodel as a prompt.\n\nThe supervisor advertises the same primary registry entries as recipient-scoped\nours typed commands. Their single arguments field is converted back to the text\nafter the slash command name and enters the same dispatcher; aliases stay\nslash-only. Typed handlers repeat the live authenticated Owner-CID check before\ndispatch and return a null protocol completion because the existing correlated\nowner-channel reply remains the result.\n\nWhile a request runs, the agent's live ACP commentary is relayed as messages\nprefixed with the single stable label `\uD83D\uDFE1 Live update:`, so an owner can see\nexactly which messages the setting controls. `owner_channel.comments`\n(default `true`, so existing channels keep their current behavior) is the\nRESTART BASELINE; `/comments on|off` changes only the running session and is\ndeliberately not persisted, so a restart always returns to the checked-in\nconfiguration. `/comments status` reports the live value, the baseline, and\nwhether the backend emits live comments at all. Suppressing live comments never\nsuppresses receipts, progress notices, or the final answer.\n\nOwner documents, images, and voice messages use the same authenticated sender\nand source-wire boundary. Fleet inspects body-free metadata first and rejects\ndisabled, over-count, or over-size requests before selective\nretrieval. Unauthorized CIDs are never retrieved or answered. Reply-linked text\nand files from the same sender become one ordered request; a file-only wake also\nstarts a turn. Retrieved bytes must match their structured size and SHA-256,\nwhile MIME values, extensions, file categories, and declared-versus-detected mismatches\nremain report-only metadata. Symlinks or non-regular paths fail closed. Sanitized copies live only in a mode-0700 request directory as\nmode-0600 files and are removed after completion or bounded stale retention.\n\nThe legacy `attachments.allowed_mime` key is accepted and ignored so existing\nconfigurations keep loading; it is omitted from resolved configuration and cannot\naffect admission.\n\nVoice prompts include a bounded transcript only when typed daemon metadata reports success.\nFailure or unavailability is explicit and preserves the private audio path as the\ninput for direct review. Run `ours config show --json` and inspect `sttConfigured` without\nrevealing provider credentials.\nA mode-0600 message claim journal stores only wire ID, persistent-history\nsequence, and claim time. Fleet journals the exact body-free oldest-first slice\nbefore calling `getMessages` with that slice length, rejects a returned set\nmismatch, and loads a crash-recovered body only through `getHistoryItem`.\nThe attachment crash journal contains only authenticated CID and wire routing\ndata; it never stores captions, filenames, paths, transcript text, or bytes.\nJournaled read files resume through `getFileInfo` and `fetchFile`. A claimed\nagent caption is loaded from history and rejoined before the group is admitted. Fleet\nresolves one authenticated owner route before retrieving bytes, admits every file\nbefore emitting the caption or any file, and sends every part to that same route.\nUnknown correlated routes remain queued without retrieval and receive one bounded\ncorrelated notice. Admission rejection consumes the whole group with one NACK;\nonce emission starts, a transport error becomes terminal uncertain delivery and\nthe group is never blind-retried. Bounded v2 source-wire routing state is migrated\nfrom v1 on read. Corrupt state disables attachment admission rather than weakening\nprovenance checks.\n\nThe channel identity must be unique and must not be a role identity. The bridge\npersists bounded wire IDs only, never message/reply plaintext, and requeues input\nbefore starting its turn for at-least-once crash recovery. It currently requires\nthe structured agent-session interface so correlated final replies retain their\ndelivery guarantee.\n\n### Live contact and owner administration\n\nThe supervisor which is already running the managed role remains the sole binder of\n`owner_channel.identity`. The CLI reaches that exact live `OwnerChannel`\nthrough the role's token-authenticated, mode-0600 Unix control socket for contact\ninspection and setup; it never starts another ours client and never force-binds:\n\nRapid supervised restart is serialized by a role-scoped single-binder lease.\nThe predecessor closes its authenticated control socket and MCP proxy before\nreleasing ownership. The replacement waits at most five seconds and retries the\ndaemon bind only when PID/start-marker metadata proves the holder was the same\nrole and owner-channel identity. Foreign, live, corrupt, or otherwise\nunverifiable ownership remains fail-closed; fleet never uses `force=true`.\n\nIf that matching predecessor misses the bound, its still-authenticated control\nroute may send one fixed, digest-deduplicated recovery notice through the latest\nauthenticated owner conversation (or the sole configured owner). Notice\nplaintext is never persisted. With no safe deterministic route fleet guesses no\nrecipient and leaves the actionable failure in the web console and role logs.\nThe remote recovery action is `/restart`; inspect repeated failures with\n`ours-fleet logs <Role>` or the web console.\n\n```sh\nours-fleet owner-channel contact list <Role>\nours-fleet owner-channel contact invite <Role> [--name <label>]\nours-fleet owner-channel contact add <Role> (--invite-file <path> | --invite-stdin) [--name <label>]\nours-fleet owner-channel owner list <Role>\nours-fleet owner-channel owner authorize <Role> <exact-64-hex-contact-cid>\nours-fleet owner-channel owner revoke <Role> <exact-64-hex-contact-cid>\n```\n\nContact establishment and owner authorization are separate security steps.\n`contact add` never authorizes: invite redemption is pending until the peer\nverifies it. Once `contact list` reports the established contact, authorize\nits exact immutable CID explicitly. Invite creation emits invite material only\non stdout; acceptance reads it from a file or stdin, not argv.\n\nConfigured `owners` remain the baseline. On legacy channels without `agent`,\nlive authorizations/revocations are an immediately effective, restart-persistent\noverlay. Managed-agent CID gating makes fleet configuration authoritative and\ndisables live owner mutation and direct control-socket sends. `owner list` labels\nbaseline versus dynamic entries and effective status. The atomic mode-0600 file\ncontains bounded CIDs and audit actions only. Corruption disables all effective\nowners and refuses mutation rather than resurrecting authority; revoking the\nlast effective owner is always refused.\n\nA missing/stopped role, role without `owner_channel`, unavailable\nMCP client, or a role entering shutdown returns an actionable error with no\nside effects. Management uses no network listener and never logs or persists\ninvite material.\n\nFor any non-final message\u2014progress, blocker, suggestion, or later proactive note\u2014\nthe managed agent calls ordinary ours `send_message` to the channel identity.\nFleet checks only that the authenticated sender CID exactly equals `agent`, then\nforwards the text as a new message. There is no task/request/update type, phase,\nreply correlation, or owner recipient argument. A sole owner is the safe fallback;\nwith multiple owners and no inbound route history the relay fails closed. Devices\nsharing one identity share its CID; separate owner identities hand off the route\nwhen either sends channel mail. The ACP final is separate: fleet extracts it from\nthe completed turn and deterministically replies to the initiating owner wire.\n\nThe bounded mode-0600 route state stores CIDs, wire IDs, timestamps, delivery state,\nand hashes but never message plaintext. Unauthorized attempts produce a bounded\nCID-only owner warning; attempted bodies are neither reflected nor persisted.\n\nFor a mobile owner, establish the contact first, wait for peer verification,\nauthorize its exact CID, and revoke that same CID when access ends. The bounded\nmode-0600 CID overlay survives supervisor restart and remains fail-closed on\ncorruption. Update bodies remain memory-only. After a crash/restart, unfinished\ndeferred owner input follows the existing at-least-once replay path; the restarted\nsupervisor remains the sole binder.\n\n## Stable config and YAML migration\n\n`ours-fleet config --json` emits schemaVersion 1 resolved plans. Environment\nvalues and mission/persona/bio bodies are withheld; environment keys are sorted\nand values are marked redacted. Additive fields may appear in schema 1, while a\nremoval or semantic reuse requires a new schema version.\n\nYAML parsing always rejects duplicate keys. The current default\n`--yaml-mode compat` warns with file/line/column for anchors, aliases, explicit\ntags, non-scalar keys, and multiple documents. Use `--yaml-mode strict` in CI\nnow; strict becomes the next-major default and compat is the temporary migration\nescape hatch.\n\n## Bounded worklogs, auth proxy, and model recovery\n\nWORKLOG rotation is enabled by default with\n`worklog: { max_kb: 1024, keep_tail_kb: 256, max_archives: 12 }`. Maps may\noverride individual values; `worklog: false` on a role or in defaults opts out.\nFleet rotates only at that role's launch/resume lifecycle boundary. Concurrent\nchanges defer rotation. The active file keeps a bounded UTF-8 tail and advances\nto a line boundary when a complete line fits. If one logical line alone exceeds\nthe budget, its newest suffix remains and the rotation manifest records the\nmid-line start and omitted byte count. The complete prior inode receives a\ncollision-safe UTC archive name, and\n`.worklog-rotation.json` records restart provenance. `max_archives` bounds\nrecent archives beside WORKLOG.md; older complete archives move to\n`WORKLOG.archives/` without deletion. All archives share the role's sensitive\nstate boundary. Fleet refuses a symlinked/non-regular live log or a symlinked\ncold-archive boundary before replacing the live path and best-effort removes a\nduplicate publication left by a detected failure while the original inode is\nstill available. The manifest records SHA-256 digests for the archive and live\nbytes observed when it is written. These checks address ordinary path hazards,\nnot intentional path mutation by a malicious concurrent process with the same\nUnix authority; that is outside the threat model and requires OS-level isolation.\n\nACP tool diffs are bounded before entering web conversation events. Existing\nsmall before/after diffs are unchanged. Oversized whole-file snapshots are\nreduced to the actual changed region plus path, operation, original byte counts,\ndigest, and omission metadata. Each retained side is a newest-content UTF-8 tail\nof at most 64 KiB, advanced to a line boundary when a complete line fits. An\noverlong single line keeps its newest suffix and explicitly records a mid-line\nstart. Paths retain at most a 4 KiB suffix with byte count, digest, and omitted\nprefix metadata; the complete normalized update is capped at 320 KiB. A large\nappend therefore retains current appended content, not the historical prefix.\nThe live web-console transcript includes only the current runner generation and\nexcludes adapter session/load replay. Replayed events remain durable with\nagent_replay provenance for diagnosis and recovery.\n\n`auth_proxy: { kind: anthropic, base_url, required, health_url }` is Claude-only\nand loopback-only. Fleet injects only ANTHROPIC_BASE_URL and doctor rejects\ncredential env keys. The privileged reference companion is\n`contrib/anthropic-auth-proxy.mjs`; deploy it separately as a dedicated account\nwith a 0600 token file and per-role listener access. Fleet never installs it or\nreads its credential.\n\n`model_chain` is an ordered authorization list and its first entry must equal\n`model`. Only sustained high-confidence entitlement/quota 429 evidence advances\none entry. Transient 429, overload, auth, policy, and unknown errors never\ndown-shift. Runtime state is atomic in .model-recovery.json; exhaustion is\nfail-closed and held down. Change the declared chain/model and restart to\nreconcile explicitly; no chain preserves detection-only behavior.\n";
8
8
  /**
9
9
  * What every shipped spawn-skill variant must say, and must not say.
10
10
  *
package/dist/docs.js CHANGED
@@ -257,6 +257,20 @@ Packaged Developer, Critic, and LocalCoordinator Agent Templates set
257
257
  after-tool delivery. Explicit per-member and custom Agent Template values remain
258
258
  authoritative and merge key by key.
259
259
 
260
+ Managed ACP stall recovery is opt-in: \`monitor: { mode: fleet, stall_recovery: true,
261
+ stall_timeout_ms: 900000 }\`. The validated timeout is 60000–86400000 milliseconds.
262
+ Omitted/false preserves existing behavior. Silence is measured from meaningful live
263
+ progress; replay and retry chatter do not reset it. Strong authenticated retry
264
+ evidence requires one window, generic silence two. Tools, permissions, modal or
265
+ unknown boundaries, steering and human cancellation protect the turn. Recovery
266
+ uses one bounded cancel and diagnostic continuation in the same ACP session/queue
267
+ slot; it never restarts the adapter. Startup and queued mail wait behind recovery.
268
+ A durable claim permits at most one automatic attempt per ACP session ID, including
269
+ across supervisor restarts; later mail is non-cancelling. Failed or re-stalled
270
+ recovery reports a blocker. Inspect \`.stall-recovery/audit.jsonl\` and recorded
271
+ terminal events before continuing; never replay ambiguous or completed mutations.
272
+ Native monitoring/non-ACP sessions are unchanged. No room or identity coupling.
273
+
260
274
  ## fleet.yaml
261
275
 
262
276
  \`\`\`yaml
@@ -31,6 +31,9 @@ export class ClaudeCodeAgentSessionAdapter {
31
31
  permissionMode: options.permissionMode,
32
32
  permissionMetadataSource: acpAdapterState(launch.adapterState).permissionMetadataSource,
33
33
  scrubObsoleteOursAutostart: true,
34
+ ...(role.monitor?.mode === 'fleet' && role.monitor.stall_recovery ? {
35
+ stallRecovery: { timeoutMs: role.monitor.stall_timeout_ms },
36
+ } : {}),
34
37
  log: options.log,
35
38
  });
36
39
  }
@@ -46,6 +46,9 @@ export class CodexAgentSessionAdapter {
46
46
  permissionMode: options.permissionMode,
47
47
  permissionMetadataSource: acpAdapterState(launch.adapterState).permissionMetadataSource,
48
48
  scrubObsoleteOursAutostart: true,
49
+ ...(role.monitor?.mode === 'fleet' && role.monitor.stall_recovery ? {
50
+ stallRecovery: { timeoutMs: role.monitor.stall_timeout_ms },
51
+ } : {}),
49
52
  log: options.log,
50
53
  });
51
54
  }
package/dist/runner.js CHANGED
@@ -612,7 +612,7 @@ export async function runOnce(name, opts = {}, partialDeps = {}) {
612
612
  arbiter = new RoleTurnArbiter(agentSession);
613
613
  sessionHandle = arbiter;
614
614
  unsubscribeRecovery = agentSession.subscribe(event => {
615
- if (event.kind !== 'error' || !event.text)
615
+ if (event.kind !== 'error' || !event.text || event.origin?.kind === 'stall-watchdog')
616
616
  return;
617
617
  const evidence = classifyFailureText(event.text, sessionBackend, new Date(deps.now()).toISOString());
618
618
  if (evidence)
@@ -747,7 +747,8 @@ export async function runOnce(name, opts = {}, partialDeps = {}) {
747
747
  // valid. Keep every unproven cancellation, refusal, shutdown, and genuine
748
748
  // failure terminal so a role that never accepted its briefing is not
749
749
  // silently reported as healthy.
750
- const interruptedForWake = isRecoverableTempStartupCancellation(temp, started);
750
+ const interruptedForWake = isRecoverableTempStartupCancellation(temp, started)
751
+ || (started.outcome === 'cancelled' && started.cancellationSource === 'stall-watchdog');
751
752
  if (!started.succeeded && !interruptedForWake) {
752
753
  monitor?.stop();
753
754
  await control.close();
@@ -772,7 +773,9 @@ export async function runOnce(name, opts = {}, partialDeps = {}) {
772
773
  throw new Error(`[${name}] ${sessionLabel} startup prompt ${started.outcome}` +
773
774
  `${started.detail ? `: ${started.detail}` : ''}`);
774
775
  }
775
- if (interruptedForWake)
776
+ if (started.cancellationSource === 'stall-watchdog')
777
+ deps.log(`[${name}] ${sessionLabel} startup diagnostic recovery requires operator attention; keeping supervisor alive`);
778
+ else if (interruptedForWake)
776
779
  deps.log(`[${name}] ${sessionLabel} startup prompt cancelled by ${started.cancellationSource}; `
777
780
  + 'keeping temporary supervisor alive');
778
781
  sessionStartupComplete = true;
@@ -27,6 +27,12 @@ export declare const CODEX_DISABLE_INHERITED_MCP_ENV = "OURS_FLEET_CODEX_DISABLE
27
27
  export declare function promptContentBlocks(text: string, origin?: PromptOrigin): acp.ContentBlock[];
28
28
  export declare function runtimeSelector(options: acp.SessionConfigOption[] | null | undefined, category: string): RuntimeSelectorMetadata | undefined;
29
29
  export interface AcpSessionOptions {
30
+ /** Opt-in Fleet watchdog, owned by this ACP session, never a process restart. */
31
+ stallRecovery?: {
32
+ timeoutMs?: number;
33
+ tickMs?: number;
34
+ cancelWaitMs?: number;
35
+ };
30
36
  name: string;
31
37
  /** Harness identity used only for honest optional capability reporting. */
32
38
  harness?: string;
@@ -144,6 +150,15 @@ export declare class AcpSession implements AgentSession {
144
150
  private terminate;
145
151
  /** ACP-authenticated in-flight calls, including independently reserved permissions. */
146
152
  private readonly activeToolCalls;
153
+ private stallWatchdog?;
154
+ private stallToolHistory?;
155
+ private stallRecoveryClaimed;
156
+ private managedTurnCount;
157
+ private steeringWasUsed;
158
+ private steeringRequests;
159
+ private retryNativeTurnId?;
160
+ private stallTimer?;
161
+ private stallAttempt?;
147
162
  private readonly toolBoundaryWaiters;
148
163
  private activeTurn?;
149
164
  private constructor();
@@ -275,7 +290,13 @@ export declare class AcpSession implements AgentSession {
275
290
  private declaredMcpServers;
276
291
  private initialize;
277
292
  private captureRuntimeMetadata;
293
+ private startStallWatchdog;
294
+ private checkStallWatchdog;
295
+ private stallObservation;
296
+ private recoverStall;
297
+ /** Keep the original queue slot (including startup) until recovery finishes. */
278
298
  private runPrompt;
299
+ private runSinglePrompt;
279
300
  private steerPrompt;
280
301
  private requestPermission;
281
302
  /**
@@ -294,6 +315,8 @@ export declare class AcpSession implements AgentSession {
294
315
  * malformed requests on the ordinary fail-closed path.
295
316
  */
296
317
  private isEffectiveCodexProtectedMcpApproval;
318
+ /** Pinned codex-acp 1.1.7 structured metadata, never stderr or assistant text. */
319
+ private recordStallMetadata;
297
320
  private recordUpdate;
298
321
  /**
299
322
  * Codex ACP's phase extension is the only currently supported visibility
@@ -1,5 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { randomUUID } from 'node:crypto';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
3
  import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, writeFileSync, } from 'node:fs';
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
5
  import { Readable, Writable } from 'node:stream';
@@ -7,6 +7,7 @@ import * as acp from '@agentclientprotocol/sdk';
7
7
  import { normalizeSessionUpdate } from './conversation-normalizer.js';
8
8
  import { ConversationEventStore } from './conversation-store.js';
9
9
  import { SessionEvents } from './events.js';
10
+ import { DEFAULT_STALL_TIMEOUT_MS, STALL_RECOVERY_PROMPT, StallWatchdog, StallToolHistory, hasStallRecoveryClaim } from './stall-watchdog.js';
10
11
  import { ACP_CANCEL_DEADLINE_EXCEEDED, SessionControlError, classifyChildExit, sessionBackendCapabilities, turnResult, } from './types.js';
11
12
  const CANCEL_SETTLE_GRACE_MS = 15_000;
12
13
  const CANCEL_TERMINATE_GRACE_MS = 5_000;
@@ -158,6 +159,7 @@ function canonicallyWithin(root, candidates) {
158
159
  function conversationSource(origin) {
159
160
  switch (origin?.kind) {
160
161
  case 'owner-admin-console': return { source: 'owner_admin_console', persistBody: true };
162
+ case 'stall-watchdog': return { source: 'fleet_monitor', persistBody: false };
161
163
  case 'startup': return { source: 'startup', persistBody: true };
162
164
  case 'owner': return { source: 'owner_channel', persistBody: false };
163
165
  case 'fleet-monitor': return { source: 'fleet_monitor', persistBody: false };
@@ -265,6 +267,15 @@ export class AcpSession {
265
267
  terminate;
266
268
  /** ACP-authenticated in-flight calls, including independently reserved permissions. */
267
269
  activeToolCalls = new Map();
270
+ stallWatchdog;
271
+ stallToolHistory;
272
+ stallRecoveryClaimed = false;
273
+ managedTurnCount = 0;
274
+ steeringWasUsed = false;
275
+ steeringRequests = 0;
276
+ retryNativeTurnId;
277
+ stallTimer;
278
+ stallAttempt;
268
279
  toolBoundaryWaiters = new Set();
269
280
  activeTurn;
270
281
  constructor(options, child, connection) {
@@ -285,6 +296,9 @@ export class AcpSession {
285
296
  this.terminated.catch(() => undefined);
286
297
  child.stderr.on('data', chunk => options.log(`[${options.name}] acp: ${String(chunk).trimEnd()}`));
287
298
  child.once('exit', (code, signal) => {
299
+ if (this.stallTimer)
300
+ clearInterval(this.stallTimer);
301
+ this.stallTimer = undefined;
288
302
  if (this.cancelForceKill)
289
303
  clearTimeout(this.cancelForceKill);
290
304
  this.cancelForceKill = undefined;
@@ -341,7 +355,8 @@ export class AcpSession {
341
355
  let instance;
342
356
  const app = acp.client({ name: 'ours-fleet' })
343
357
  .onNotification(acp.methods.client.session.update, ({ params }) => {
344
- instance?.recordUpdate(params.update);
358
+ if (instance && (!instance.sessionId || params.sessionId === instance.sessionId))
359
+ instance.recordUpdate(params.update);
345
360
  })
346
361
  .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
347
362
  if (!instance)
@@ -353,6 +368,7 @@ export class AcpSession {
353
368
  instance = new AcpSession(options, child, connection);
354
369
  try {
355
370
  await instance.initialize();
371
+ instance.startStallWatchdog();
356
372
  instance.recoverOpenPrompts();
357
373
  return instance;
358
374
  }
@@ -471,10 +487,14 @@ export class AcpSession {
471
487
  reserveTool(toolCallId) {
472
488
  if (toolCallId)
473
489
  this.toolCall(toolCallId).lifecycle = true;
490
+ else if (this.activeTurn)
491
+ this.activeTurn.boundaryUnknown = true;
474
492
  }
475
493
  reservePermission(toolCallId, permissionId) {
476
494
  if (toolCallId)
477
495
  this.toolCall(toolCallId).permissions.set(permissionId, 'pending');
496
+ else if (this.activeTurn)
497
+ this.activeTurn.boundaryUnknown = true;
478
498
  }
479
499
  allowPermission(toolCallId, permissionId) {
480
500
  if (!toolCallId)
@@ -559,6 +579,8 @@ export class AcpSession {
559
579
  * steering response from becoming a tight replay loop.
560
580
  */
561
581
  async steerOrQueueWake(text, options) {
582
+ if (this.stallRecoveryClaimed)
583
+ return this.submitPrompt(text, { ...options, interrupt: false, steer: false });
562
584
  const steered = await this.steerPrompt(text);
563
585
  if (steered.accepted || steered.detail !== 'ACP steering failed'
564
586
  || this.closing || !this.isAlive())
@@ -622,6 +644,8 @@ export class AcpSession {
622
644
  * for it is what turned a busy agent into a timeout and then into "dead".
623
645
  */
624
646
  async queuePrompt(text, options = {}) {
647
+ if (this.stallRecoveryClaimed && options.origin?.kind === 'fleet-monitor')
648
+ options = { ...options, interrupt: false, steer: false };
625
649
  if (this.cancelRecoveryReason)
626
650
  throw new SessionControlError('control-unavailable', 'ACP adapter restart is in progress after the cancellation deadline', ACP_CANCEL_DEADLINE_EXCEEDED);
627
651
  if (this.closing || !this.sessionId || !this.isAlive())
@@ -781,6 +805,8 @@ export class AcpSession {
781
805
  }
782
806
  }
783
807
  async cancelActive(source) {
808
+ if (this.stallAttempt && source !== 'stall-watchdog' && source !== 'fleet-monitor')
809
+ this.stallAttempt.superseded = true;
784
810
  if (!this.sessionId)
785
811
  return;
786
812
  const active = this.activeTurn;
@@ -989,6 +1015,11 @@ export class AcpSession {
989
1015
  }
990
1016
  async close() {
991
1017
  this.closing = true;
1018
+ if (this.stallTimer)
1019
+ clearInterval(this.stallTimer);
1020
+ this.stallTimer = undefined;
1021
+ if (this.stallAttempt)
1022
+ this.stallAttempt.superseded = true;
992
1023
  if (this.cancelEscalation)
993
1024
  clearTimeout(this.cancelEscalation);
994
1025
  this.cancelEscalation = undefined;
@@ -1130,13 +1161,158 @@ export class AcpSession {
1130
1161
  this.runtimeModel = runtimeSelector(options, 'model');
1131
1162
  this.reasoningEffort = runtimeSelector(options, 'thought_level') ?? reasoningFromModelId(modelId);
1132
1163
  }
1164
+ startStallWatchdog() {
1165
+ if (!this.options.stallRecovery)
1166
+ return;
1167
+ const timeoutMs = this.options.stallRecovery.timeoutMs ?? DEFAULT_STALL_TIMEOUT_MS;
1168
+ this.stallRecoveryClaimed = hasStallRecoveryClaim(this.options.stateDir, this.sessionId);
1169
+ this.stallToolHistory = new StallToolHistory(this.options.stateDir, this.sessionId, this.options.mode === 'resume');
1170
+ this.stallWatchdog = new StallWatchdog({
1171
+ stateDir: this.options.stateDir, timeoutMs, previouslyClaimed: this.stallRecoveryClaimed, now: () => Date.now(),
1172
+ observe: () => this.stallObservation(),
1173
+ recover: (observed, report) => this.recoverStall(observed, report),
1174
+ diagnostic: diagnostic => {
1175
+ if (['interrupt_requested', 'blocked_previous_attempt', 'blocked_persistence'].includes(diagnostic.status))
1176
+ this.stallRecoveryClaimed = true;
1177
+ this.events.emit('stall_recovery', { status: diagnostic.status, stallDiagnostic: diagnostic });
1178
+ this.options.log(`[${this.options.name}] ACP stall recovery: ${diagnostic.status}; `
1179
+ + 'inspect structured session events before continuing; never replay uncertain side effects');
1180
+ },
1181
+ });
1182
+ this.stallTimer = setInterval(() => this.checkStallWatchdog(), this.options.stallRecovery.tickMs ?? Math.min(10_000, timeoutMs));
1183
+ this.stallTimer.unref?.();
1184
+ }
1185
+ checkStallWatchdog() {
1186
+ void this.stallWatchdog?.tick();
1187
+ const attempt = this.stallAttempt;
1188
+ if (attempt?.recoveryStartedAt === undefined || attempt.blocked || attempt.superseded)
1189
+ return;
1190
+ const observed = this.stallObservation();
1191
+ if (!observed?.safe || observed.turnId !== attempt.recoveryId)
1192
+ return;
1193
+ const last = observed.lastProgressAt || attempt.recoveryStartedAt;
1194
+ const timeoutMs = this.options.stallRecovery?.timeoutMs ?? DEFAULT_STALL_TIMEOUT_MS;
1195
+ if (Date.now() - last >= timeoutMs * 2) {
1196
+ attempt.blocked = true;
1197
+ try {
1198
+ attempt.report('blocked_restall');
1199
+ }
1200
+ catch { /* durable claim already prevents retry */ }
1201
+ }
1202
+ }
1203
+ stallObservation() {
1204
+ const active = this.activeTurn;
1205
+ if (!active || !this.sessionId)
1206
+ return undefined;
1207
+ return {
1208
+ sessionId: this.sessionId, generation: this.sessionGeneration, turnId: active.id,
1209
+ startedAt: active.startedAt, lastProgressAt: active.lastProgressAt, progressCount: active.progressCount,
1210
+ transportFailures: active.transportFailures,
1211
+ boundaryEvidenceAvailable: this.stallToolHistory?.available() !== false,
1212
+ safe: this.isAlive() && !this.closing && this.readiness === 'running'
1213
+ && !active.cancellationSource && !active.boundaryUnknown && !this.steeringOccupied
1214
+ && this.steeringRequests === 0 && this.stallToolHistory?.available() !== false
1215
+ && this.activeToolCalls.size === 0 && this.pendingPermissions.size === 0,
1216
+ };
1217
+ }
1218
+ async recoverStall(observed, report) {
1219
+ const current = this.stallObservation();
1220
+ if (!current?.safe || current.turnId !== observed.turnId
1221
+ || current.lastProgressAt !== observed.lastProgressAt || current.progressCount !== observed.progressCount) {
1222
+ report('superseded');
1223
+ return;
1224
+ }
1225
+ const active = this.activeTurn;
1226
+ let resolveReady;
1227
+ const ready = new Promise(resolve => { resolveReady = resolve; });
1228
+ const attempt = this.stallAttempt = {
1229
+ turnId: active.id, recoveryId: randomUUID(), ready, superseded: false,
1230
+ report, resumed: false, blocked: false,
1231
+ };
1232
+ active.cancellationSource = 'stall-watchdog';
1233
+ // This intentionally does not use cancelActive: automatic recovery may
1234
+ // never enter its SIGTERM/SIGKILL escalation or settle a permission.
1235
+ let timer;
1236
+ try {
1237
+ const completed = await Promise.race([
1238
+ (async () => {
1239
+ await this.connection.agent.notify(acp.methods.agent.session.cancel, { sessionId: this.sessionId });
1240
+ await active.settled;
1241
+ return true;
1242
+ })(),
1243
+ new Promise(resolve => {
1244
+ timer = setTimeout(() => resolve(false), this.options.stallRecovery?.cancelWaitMs ?? CANCEL_SETTLE_GRACE_MS);
1245
+ timer.unref?.();
1246
+ }),
1247
+ ]);
1248
+ if (!completed || attempt.superseded || this.closing || !this.isAlive()) {
1249
+ attempt.blocked = true;
1250
+ report(attempt.superseded || this.closing ? 'superseded' : 'blocked_cancel');
1251
+ resolveReady(false);
1252
+ }
1253
+ else
1254
+ resolveReady(true);
1255
+ }
1256
+ catch {
1257
+ attempt.blocked = true;
1258
+ try {
1259
+ report('blocked_cancel');
1260
+ }
1261
+ finally {
1262
+ resolveReady(false);
1263
+ }
1264
+ }
1265
+ finally {
1266
+ if (timer)
1267
+ clearTimeout(timer);
1268
+ }
1269
+ }
1270
+ /** Keep the original queue slot (including startup) until recovery finishes. */
1133
1271
  async runPrompt(text, turnId = randomUUID(), origin) {
1272
+ const result = await this.runSinglePrompt(text, turnId, origin);
1273
+ const attempt = this.stallAttempt;
1274
+ if (!attempt || attempt.turnId !== turnId)
1275
+ return result;
1276
+ const ready = await attempt.ready;
1277
+ if (attempt.superseded || this.closing)
1278
+ return result;
1279
+ if (!ready || result.outcome !== 'cancelled' || result.cancellationSource !== 'stall-watchdog') {
1280
+ // An RPC error/refusal/ambiguous terminal answer to cancellation is not
1281
+ // permission to replay work or to fail startup and restart the process.
1282
+ if (!attempt.blocked) {
1283
+ attempt.blocked = true;
1284
+ try {
1285
+ attempt.report('blocked_cancel');
1286
+ }
1287
+ catch { /* claim remains durable */ }
1288
+ }
1289
+ return turnResult(true, 'cancelled', 'diagnostic cancellation requires operator attention', undefined, 'stall-watchdog');
1290
+ }
1291
+ try {
1292
+ attempt.report('recovery_started');
1293
+ attempt.recoveryStartedAt = Date.now();
1294
+ const recoveryOrigin = origin?.kind === 'scheduled-loop'
1295
+ ? origin : { kind: 'stall-watchdog' };
1296
+ this.admitToLedger(attempt.recoveryId, STALL_RECOVERY_PROMPT, 0, { origin: recoveryOrigin });
1297
+ const recovered = await this.runSinglePrompt(STALL_RECOVERY_PROMPT, attempt.recoveryId, recoveryOrigin);
1298
+ attempt.report(attempt.superseded ? 'superseded'
1299
+ : recovered.succeeded && attempt.resumed ? 'recovery_completed' : 'blocked_recovery');
1300
+ // A failed diagnostic turn must not make startup tear down the session.
1301
+ return recovered.succeeded && attempt.resumed ? recovered : turnResult(true, 'cancelled', 'diagnostic recovery requires operator attention', undefined, 'stall-watchdog');
1302
+ }
1303
+ catch {
1304
+ return turnResult(true, 'cancelled', 'diagnostic recovery requires operator attention', undefined, 'stall-watchdog');
1305
+ }
1306
+ }
1307
+ async runSinglePrompt(text, turnId = randomUUID(), origin) {
1134
1308
  if (!this.sessionId || !this.isAlive())
1135
1309
  return turnResult(false, 'failed', this.lastError ?? 'ACP session is offline');
1136
1310
  this.readiness = 'running';
1311
+ this.managedTurnCount++;
1312
+ this.retryNativeTurnId = undefined;
1137
1313
  let settle;
1138
1314
  const settled = new Promise(resolve => { settle = resolve; });
1139
- this.activeTurn = { id: turnId, output: '', origin, settled, settle };
1315
+ this.activeTurn = { toolEvidence: new Map(), startedAt: Date.now(), toolIds: new Set(), lastProgressAt: 0, progressCount: 0, transportFailures: 0, boundaryUnknown: false, id: turnId, output: '', origin, settled, settle };
1140
1316
  this.events.emit('state', { turnId, status: 'running', origin });
1141
1317
  this.conversation.appendSafe({
1142
1318
  kind: 'prompt.started', sessionGeneration: this.sessionGeneration,
@@ -1180,7 +1356,8 @@ export class AcpSession {
1180
1356
  this.lastError = origin?.kind === 'scheduled-loop' ? 'scheduled-loop turn failed' : detail;
1181
1357
  this.readiness = this.isAlive() ? 'idle' : 'failed';
1182
1358
  this.events.emit('error', {
1183
- turnId, origin,
1359
+ turnId, origin: this.activeTurn?.cancellationSource === 'stall-watchdog'
1360
+ ? { kind: 'stall-watchdog' } : origin,
1184
1361
  text: origin?.kind === 'scheduled-loop' ? 'scheduled-loop turn failed' : this.lastError,
1185
1362
  });
1186
1363
  if (this.isAlive())
@@ -1208,8 +1385,10 @@ export class AcpSession {
1208
1385
  }
1209
1386
  }
1210
1387
  async steerPrompt(text) {
1388
+ this.steeringWasUsed = true;
1211
1389
  if (!this.sessionId || !this.isAlive())
1212
1390
  return turnResult(false, 'failed', this.lastError ?? 'ACP session is offline');
1391
+ this.steeringRequests++;
1213
1392
  try {
1214
1393
  const response = await Promise.race([
1215
1394
  this.connection.agent.request('_session/steering', {
@@ -1234,6 +1413,9 @@ export class AcpSession {
1234
1413
  this.events.emit('error', { text: detail });
1235
1414
  return turnResult(false, 'failed', detail);
1236
1415
  }
1416
+ finally {
1417
+ this.steeringRequests--;
1418
+ }
1237
1419
  }
1238
1420
  requestPermission(params) {
1239
1421
  // `kinds` is a PRIORITY order. Scanning the agent's option array instead
@@ -1409,6 +1591,48 @@ export class AcpSession {
1409
1591
  && params.options.some(option => option.optionId === 'allow_once' && option.kind === 'allow_once')
1410
1592
  && params.options.some(option => option.optionId === 'decline' && option.kind === 'reject_once');
1411
1593
  }
1594
+ /** Pinned codex-acp 1.1.7 structured metadata, never stderr or assistant text. */
1595
+ recordStallMetadata(update) {
1596
+ if (this.options.permissionMetadataSource !== 'codex-acp'
1597
+ || update.sessionUpdate !== 'session_info_update' || !this.activeTurn)
1598
+ return;
1599
+ const meta = update._meta?.codex;
1600
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta))
1601
+ return;
1602
+ const codex = meta;
1603
+ const status = codex.threadStatus;
1604
+ if (Object.prototype.hasOwnProperty.call(codex, 'threadStatus')) {
1605
+ const value = status && typeof status === 'object' && !Array.isArray(status)
1606
+ ? status : {};
1607
+ // Unknown or modal thread status is a permanent conservative fence for
1608
+ // this turn. A later delayed idle/active status must not clear it.
1609
+ if (value.type !== 'active' || !Array.isArray(value.activeFlags)
1610
+ || value.activeFlags.length > 0)
1611
+ this.activeTurn.boundaryUnknown = true;
1612
+ }
1613
+ const error = codex.error;
1614
+ if (!error || typeof error !== 'object' || Array.isArray(error))
1615
+ return;
1616
+ const value = error;
1617
+ const info = value.codexErrorInfo;
1618
+ if (value.willRetry !== true || typeof value.turnId !== 'string' || !value.turnId
1619
+ || !info || typeof info !== 'object' || Array.isArray(info))
1620
+ return;
1621
+ if (!['responseStreamConnectionFailed', 'responseStreamDisconnected']
1622
+ .some(key => Object.prototype.hasOwnProperty.call(info, key)))
1623
+ return;
1624
+ // ACP 1.1.7 does not expose a native-turn-to-prompt mapping. Only the first
1625
+ // fresh managed turn with no steering can be correlated without guessing;
1626
+ // later/resumed turns retain the conservative generic no-progress path.
1627
+ if (this.options.mode !== 'fresh' || this.managedTurnCount !== 1 || this.steeringWasUsed)
1628
+ return;
1629
+ if (this.retryNativeTurnId && this.retryNativeTurnId !== value.turnId) {
1630
+ this.activeTurn.boundaryUnknown = true;
1631
+ return;
1632
+ }
1633
+ this.retryNativeTurnId = value.turnId;
1634
+ this.activeTurn.transportFailures++;
1635
+ }
1412
1636
  recordUpdate(update) {
1413
1637
  // Replayed history is not current activity: `session/load` would otherwise
1414
1638
  // make a cold session look like it had just been working. The same reason
@@ -1418,6 +1642,53 @@ export class AcpSession {
1418
1642
  this.lastUpdateAt = new Date().toISOString();
1419
1643
  this.refreshSteeringOccupancy();
1420
1644
  }
1645
+ if (!this.replaying && this.activeTurn) {
1646
+ this.recordStallMetadata(update);
1647
+ const active = this.activeTurn;
1648
+ const kind = update.sessionUpdate;
1649
+ if (this.options.stallRecovery && (kind === 'tool_call' || kind === 'tool_call_update')) {
1650
+ if (!update.toolCallId || active.toolIds.size >= 4096)
1651
+ active.boundaryUnknown = true;
1652
+ else
1653
+ active.toolIds.add(update.toolCallId);
1654
+ if (this.stallToolHistory?.observe(update.toolCallId, active.id) === false)
1655
+ active.boundaryUnknown = true;
1656
+ }
1657
+ let meaningful = ((kind === 'agent_message_chunk' || kind === 'agent_thought_chunk')
1658
+ && (update.content.type !== 'text' || update.content.text.length > 0))
1659
+ || kind === 'tool_call' || kind === 'tool_call_update' || kind === 'plan';
1660
+ if (this.options.stallRecovery && (kind === 'tool_call' || kind === 'tool_call_update' || kind === 'plan')) {
1661
+ const fingerprint = createHash('sha256').update(JSON.stringify(update)).digest('hex');
1662
+ if (kind === 'plan') {
1663
+ meaningful = fingerprint !== active.planEvidence;
1664
+ active.planEvidence = fingerprint;
1665
+ }
1666
+ else if (active.toolEvidence.size < 4096 || active.toolEvidence.has(update.toolCallId)) {
1667
+ meaningful = fingerprint !== active.toolEvidence.get(update.toolCallId);
1668
+ active.toolEvidence.set(update.toolCallId, fingerprint);
1669
+ }
1670
+ }
1671
+ if (this.options.stallRecovery && ![
1672
+ 'agent_message_chunk', 'agent_thought_chunk', 'tool_call', 'tool_call_update', 'plan',
1673
+ 'available_commands_update', 'current_mode_update', 'config_option_update', 'session_info_update', 'usage_update',
1674
+ ].includes(kind))
1675
+ active.boundaryUnknown = true;
1676
+ if (meaningful) {
1677
+ active.lastProgressAt = Date.now();
1678
+ active.progressCount++;
1679
+ active.transportFailures = 0;
1680
+ const attempt = this.stallAttempt;
1681
+ if (attempt?.recoveryId === active.id && !attempt.resumed) {
1682
+ attempt.resumed = true;
1683
+ try {
1684
+ attempt.report('progress_resumed');
1685
+ }
1686
+ catch {
1687
+ attempt.blocked = true;
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1421
1692
  const scheduled = this.activeTurn?.origin?.kind === 'scheduled-loop';
1422
1693
  const messagePhase = update.sessionUpdate === 'agent_message_chunk'
1423
1694
  ? this.codexMessagePhase(update) : undefined;
@@ -1475,6 +1746,9 @@ export class AcpSession {
1475
1746
  this.releaseTool(update.toolCallId);
1476
1747
  else if (update.status !== undefined)
1477
1748
  this.reserveTool(update.toolCallId);
1749
+ else if (this.options.stallRecovery && this.activeTurn
1750
+ && !this.activeToolCalls.has(update.toolCallId))
1751
+ this.activeTurn.boundaryUnknown = true;
1478
1752
  break;
1479
1753
  default:
1480
1754
  break;
@@ -0,0 +1,60 @@
1
+ export declare const DEFAULT_STALL_TIMEOUT_MS: number;
2
+ export declare const STALL_RECOVERY_PROMPT: string;
3
+ export type StallStatus = 'interrupt_requested' | 'recovery_started' | 'progress_resumed' | 'recovery_completed' | 'blocked_cancel' | 'blocked_recovery' | 'blocked_restall' | 'blocked_persistence' | 'blocked_previous_attempt' | 'blocked_evidence' | 'superseded';
4
+ export interface StallDiagnostic {
5
+ version: 1;
6
+ kind: 'stall_recovery';
7
+ eventId: string;
8
+ session: string;
9
+ turn: string;
10
+ status: StallStatus;
11
+ evidence: 'adapter_transport' | 'no_progress';
12
+ idleMs: number;
13
+ }
14
+ export interface StallObservation {
15
+ sessionId: string;
16
+ generation: string;
17
+ turnId: string;
18
+ startedAt: number;
19
+ lastProgressAt: number;
20
+ progressCount: number;
21
+ transportFailures: number;
22
+ safe: boolean;
23
+ boundaryEvidenceAvailable?: boolean;
24
+ }
25
+ /** Presence, including an incomplete claim, restores conservative mail policy. */
26
+ export declare function hasStallRecoveryClaim(stateDir: string, sessionId: string): boolean;
27
+ /** ACP has no turn IDs on tool updates. Reuse across turns is ambiguous. */
28
+ export declare class StallToolHistory {
29
+ private readonly turns;
30
+ private healthy;
31
+ private readonly directory;
32
+ private readonly path;
33
+ private readonly session;
34
+ constructor(stateDir: string, sessionId: string, resume: boolean);
35
+ available(): boolean;
36
+ /** Record before relying on a tool event. False means cancellation is unsafe. */
37
+ observe(toolId: string, turnId: string): boolean;
38
+ private persist;
39
+ }
40
+ /**
41
+ * One durable attempt per ACP session, deliberately stricter than one per turn.
42
+ * A restarted supervisor never guesses whether cancellation or recovery ran.
43
+ * Claim files are never reclaimed automatically, including malformed/empty ones.
44
+ */
45
+ export declare class StallWatchdog {
46
+ private readonly options;
47
+ private checking;
48
+ private disabled;
49
+ private unavailableTurn?;
50
+ constructor(options: {
51
+ stateDir: string;
52
+ timeoutMs: number;
53
+ previouslyClaimed?: boolean;
54
+ now(): number;
55
+ observe(): StallObservation | undefined;
56
+ recover(observed: StallObservation, report: (status: StallStatus) => void): Promise<void>;
57
+ diagnostic(event: StallDiagnostic): void;
58
+ });
59
+ tick(): Promise<void>;
60
+ }
@@ -0,0 +1,210 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { replaceFileAtomically } from '../atomic-file.js';
5
+ export const DEFAULT_STALL_TIMEOUT_MS = 15 * 60_000;
6
+ export const STALL_RECOVERY_PROMPT = 'This is a diagnostic interruption. The previous turn showed no progress. '
7
+ + 'Inspect recorded terminal events and re-check completed actions before continuing. '
8
+ + 'Never assume an issued side effect failed: do not replay ambiguous or already-completed mutations. '
9
+ + 'Continue the previous task if safe; otherwise report an actionable blocker.';
10
+ const digest = (text) => createHash('sha256').update(text).digest('hex');
11
+ /** Presence, including an incomplete claim, restores conservative mail policy. */
12
+ export function hasStallRecoveryClaim(stateDir, sessionId) {
13
+ try {
14
+ lstatSync(join(stateDir, '.stall-recovery', `${digest(sessionId)}.claim`));
15
+ return true;
16
+ }
17
+ catch (error) {
18
+ return error.code !== 'ENOENT';
19
+ }
20
+ }
21
+ /** ACP has no turn IDs on tool updates. Reuse across turns is ambiguous. */
22
+ export class StallToolHistory {
23
+ turns = new Map();
24
+ healthy = true;
25
+ directory;
26
+ path;
27
+ session;
28
+ constructor(stateDir, sessionId, resume) {
29
+ this.session = digest(sessionId);
30
+ this.directory = join(stateDir, '.stall-recovery');
31
+ this.path = join(this.directory, `${this.session}.tools.json`);
32
+ try {
33
+ const stored = JSON.parse(readFileSync(this.path, 'utf8'));
34
+ if (stored.version !== 1 || stored.session !== this.session || !Array.isArray(stored.tools)
35
+ || stored.tools.length > 4096 || !stored.tools.every((id) => typeof id === 'string' && /^[a-f0-9]{64}$/.test(id)))
36
+ throw new Error('invalid history');
37
+ for (const id of stored.tools)
38
+ this.turns.set(id, 'previous-generation');
39
+ }
40
+ catch (error) {
41
+ if (error.code !== 'ENOENT' || resume)
42
+ this.healthy = false;
43
+ else {
44
+ try {
45
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 });
46
+ this.persist();
47
+ const fd = openSync(stateDir, 'r');
48
+ try {
49
+ fsyncSync(fd);
50
+ }
51
+ finally {
52
+ closeSync(fd);
53
+ }
54
+ }
55
+ catch {
56
+ this.healthy = false;
57
+ }
58
+ }
59
+ }
60
+ }
61
+ available() { return this.healthy; }
62
+ /** Record before relying on a tool event. False means cancellation is unsafe. */
63
+ observe(toolId, turnId) {
64
+ if (!this.healthy || !toolId)
65
+ return false;
66
+ const id = digest(toolId);
67
+ const previous = this.turns.get(id);
68
+ if (previous !== undefined)
69
+ return previous === turnId;
70
+ if (this.turns.size >= 4096) {
71
+ this.healthy = false;
72
+ return false;
73
+ }
74
+ this.turns.set(id, turnId);
75
+ try {
76
+ this.persist();
77
+ }
78
+ catch {
79
+ this.healthy = false;
80
+ }
81
+ return this.healthy;
82
+ }
83
+ persist() {
84
+ replaceFileAtomically(this.path, JSON.stringify({ version: 1, session: this.session,
85
+ tools: [...this.turns.keys()] }) + '\n');
86
+ const fd = openSync(this.directory, 'r');
87
+ try {
88
+ fsyncSync(fd);
89
+ }
90
+ finally {
91
+ closeSync(fd);
92
+ }
93
+ }
94
+ }
95
+ /**
96
+ * One durable attempt per ACP session, deliberately stricter than one per turn.
97
+ * A restarted supervisor never guesses whether cancellation or recovery ran.
98
+ * Claim files are never reclaimed automatically, including malformed/empty ones.
99
+ */
100
+ export class StallWatchdog {
101
+ options;
102
+ checking = false;
103
+ disabled = false;
104
+ unavailableTurn;
105
+ constructor(options) {
106
+ this.options = options;
107
+ }
108
+ async tick() {
109
+ if (this.checking || this.disabled)
110
+ return;
111
+ const observed = this.options.observe();
112
+ if (!observed)
113
+ return;
114
+ const missingBoundary = observed.boundaryEvidenceAvailable === false;
115
+ if (!observed.safe && !missingBoundary && !this.options.previouslyClaimed)
116
+ return;
117
+ const missingEvidence = observed.progressCount === 0 || missingBoundary;
118
+ // Turn age can only produce an informational blocker, never cancellation.
119
+ const idleMs = this.options.now() - (observed.progressCount === 0 ? observed.startedAt : observed.lastProgressAt);
120
+ // Generic silence needs two full windows. Authenticated repeated transport
121
+ // failures strengthen evidence, but never bypass protected-operation checks.
122
+ const threshold = this.options.timeoutMs * (!missingEvidence && observed.transportFailures >= 2 ? 1 : 2);
123
+ if (!Number.isFinite(idleMs) || (idleMs < threshold && !this.options.previouslyClaimed))
124
+ return;
125
+ this.checking = true;
126
+ const session = digest(observed.sessionId);
127
+ const turn = digest(observed.generation + '\0' + observed.turnId);
128
+ const directory = join(this.options.stateDir, '.stall-recovery');
129
+ const report = (status) => {
130
+ const event = {
131
+ version: 1, kind: 'stall_recovery', eventId: `${turn}:${status}`,
132
+ session, turn, status, idleMs: Math.floor(idleMs),
133
+ evidence: observed.transportFailures >= 2 ? 'adapter_transport' : 'no_progress',
134
+ };
135
+ const fd = openSync(join(directory, 'audit.jsonl'), 'a', 0o600);
136
+ try {
137
+ writeFileSync(fd, JSON.stringify(event) + '\n');
138
+ fsyncSync(fd);
139
+ }
140
+ finally {
141
+ closeSync(fd);
142
+ }
143
+ this.options.diagnostic(event);
144
+ };
145
+ try {
146
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
147
+ const parentFd = openSync(this.options.stateDir, 'r');
148
+ try {
149
+ fsyncSync(parentFd);
150
+ }
151
+ finally {
152
+ closeSync(parentFd);
153
+ }
154
+ if (this.options.previouslyClaimed) {
155
+ this.disabled = true;
156
+ report('blocked_previous_attempt');
157
+ return;
158
+ }
159
+ if (missingEvidence) {
160
+ if (this.unavailableTurn !== turn) {
161
+ this.unavailableTurn = turn;
162
+ report('blocked_evidence');
163
+ }
164
+ return;
165
+ }
166
+ let fd;
167
+ try {
168
+ fd = openSync(join(directory, `${session}.claim`), 'wx', 0o600);
169
+ }
170
+ catch (error) {
171
+ this.disabled = true;
172
+ if (error.code === 'EEXIST') {
173
+ report('blocked_previous_attempt');
174
+ return;
175
+ }
176
+ throw error;
177
+ }
178
+ // Even a crash before this write leaves a permanent conservative fence.
179
+ try {
180
+ writeFileSync(fd, JSON.stringify({ version: 1, session, turn }) + '\n');
181
+ fsyncSync(fd);
182
+ }
183
+ finally {
184
+ closeSync(fd);
185
+ }
186
+ const dirFd = openSync(directory, 'r');
187
+ try {
188
+ fsyncSync(dirFd);
189
+ }
190
+ finally {
191
+ closeSync(dirFd);
192
+ }
193
+ this.disabled = true;
194
+ report('interrupt_requested');
195
+ // No await between the durable claim and the adapter's final atomic
196
+ // observation check. Recovery itself must re-check before session/cancel.
197
+ await this.options.recover(observed, report);
198
+ }
199
+ catch {
200
+ this.disabled = true;
201
+ // Never include an exception string: it may contain paths or wire data.
202
+ this.options.diagnostic({ version: 1, kind: 'stall_recovery',
203
+ eventId: `${turn}:blocked_persistence`, session, turn,
204
+ status: 'blocked_persistence', evidence: 'no_progress', idleMs: Math.floor(idleMs) });
205
+ }
206
+ finally {
207
+ this.checking = false;
208
+ }
209
+ }
210
+ }
@@ -13,9 +13,11 @@ import type { ConversationEventV1, ConversationSnapshot, PromptReceipt, SubmitPr
13
13
  */
14
14
  export type SessionReadiness = 'starting' | 'idle' | 'running' | 'awaiting_permission' | 'failed';
15
15
  export type TurnOutcome = 'completed' | 'refused' | 'cancelled' | 'failed' | 'inconclusive';
16
- export type TurnCancellationSource = 'owner' | 'local-console' | 'fleet-monitor' | 'scheduled-loop' | 'shutdown';
16
+ export type TurnCancellationSource = 'owner' | 'local-console' | 'fleet-monitor' | 'scheduled-loop' | 'shutdown' | 'stall-watchdog';
17
17
  export type PromptOrigin = {
18
18
  kind: 'startup';
19
+ } | {
20
+ kind: 'stall-watchdog';
19
21
  } | {
20
22
  kind: 'local-console';
21
23
  } | {
@@ -221,7 +223,7 @@ export interface AgentSessionCapabilities {
221
223
  }
222
224
  /** Conservative static capabilities used before a live session is reachable. */
223
225
  export declare function sessionBackendCapabilities(backend: SessionBackendId, harness?: string): AgentSessionCapabilities;
224
- export type SessionEventKind = 'state' | 'agent_text' | 'thought' | 'tool_call' | 'tool_update' | 'permission' | 'monitor_delivery' | 'turn_stop' | 'error';
226
+ export type SessionEventKind = 'state' | 'agent_text' | 'thought' | 'tool_call' | 'tool_update' | 'permission' | 'stall_recovery' | 'monitor_delivery' | 'turn_stop' | 'error';
225
227
  /** What a settled permission request resolved to. */
226
228
  export type PermissionDecision = 'allowed' | 'denied' | 'cancelled';
227
229
  export interface SessionEvent {
@@ -263,6 +265,7 @@ export interface SessionEvent {
263
265
  /** The option actually selected, when one was. */
264
266
  optionId?: string;
265
267
  /** Body-free evidence for monitor safe-boundary delivery. */
268
+ stallDiagnostic?: import('./stall-watchdog.js').StallDiagnostic;
266
269
  monitorPolicy?: 'after_tool';
267
270
  activeToolCount?: number;
268
271
  waitedMs?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ours.network/fleet",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Harness-agnostic fleet of persistent, identity-bound AI agents. Declarative fleet.yaml, managed native/ACP sessions, supervision, and ours.network messaging.",
5
5
  "type": "module",
6
6
  "license": "FSL-1.1-Apache-2.0",