Run each swarm contributor's harness headless and send every refusal back into the same session, reading outcomes only from status
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Drivers (`scripts/lib/swarm/harnesses/`), each pure (`start`, `resume`, `parse`, `files`), flags read from the installed `--help` on 2026-10-08: `claude --version` 2.1.293 (Claude Code), `opencode --version` v2.0.7, `amp --version` 0.0.1789750518-g64beac, `pi --version` 1.1.0. - Claude Code: `claude -p --output-format stream-json --verbose --permission-mode bypassPermissions --model <m> <brief>`, resumed with `--resume <id>`; the `system`/`init` line names the session, the `result` line settles it with its usage (the plan's dry-run argv, unchanged). - OpenCode: `opencode run --standalone --format json --auto -m <m> <brief>`, resumed with `-s <id>`. `--standalone` runs a private server in the contributor's env, not the user's background service. Its last step prints no `step_finish`, so a run settles when the process exits; an `error` event fails it. - Amp: `amp -x <brief> --stream-json -m <mode> --settings-file <dir>/amp-settings.json --no-archive-after-execute`, resumed with `amp threads continue <id> -x <prompt> …`. The workspace's own settings file allows every tool (`amp.dangerouslyAllowAll`; the workspace's `XDG_CONFIG_HOME` hides the user's). Without `--no-archive-after-execute` the first resume failed live: "This thread is archived and cannot be continued". - pi: `pi -p --mode json --session-dir <dir>/sessions --session-id <handle> --model <m> [-e apps/cli/src/pi.ts] <brief>`; a resume is the same command with `--session-id <id>` and the new prompt, and the adapter's agent loads `-e` on every resume too (so `ResumeInput` gained `adapter`). The header names the session, `agent_settled` settles it, and a `message_end` with `stopReason` `error` or `aborted` fails it (JSON mode exits 0 on provider failure). No `--approve`: burrow has no project-local pi files. - `parse` returns a list per line, not an Option: a Claude Code `result` line carries usage, the failure and the settling at once. Events: `SessionStarted{id}`, `Usage{input, output, stopReason}`, `Settled{stopReason}`, `Failed{reason}`. - The shared pieces live in `harnesses/event.ts`, a sixth file beyond the issue's list: the drivers import it and `index.ts` gathers the drivers, so no import cycle (a cycle left `Tokens` undefined at load). - `outcome.ts`: `readStatus` runs the workspace's `bin/<cli> status [--project <p>] --json` in the clone with the workspace's env, decodes protocol's `Envelope`, and gives the claim on the ask and the latest answer to it (by `at`); `readOutcome` is the issue's `{head, outcome}` view of it. `awaitSettledOutcome` repeats every 5 s while the latest answer is `Checking`; the run's timeout bounds it (no timeout of its own). - `loop.ts`: `runAgent` writes the driver's files, starts the harness with `extendEnv: false` (the env is a list of non-secret names kept from the swarm's: HOME, USER, SHELL, TERM, locale, XDG data/cache/state/runtime, proxies, certificates; then the workspace's env), `stdin` ignored, and reads stdout until `Settled` or its end, writing each line to `<run>/<handle>/attempt-<n>.jsonl` with the token blanked. So `SESSION_TOKENS`, cloud tokens and a parent harness's session never reach a harness (they did with `extendEnv: true`: a swarm run under varlock would have handed every person's token to every harness). A settled harness gets 10 s to exit; then its process group is killed (SIGKILL 5 s later). - `afterSettle`, pure: `Landed` → landed; `AwaitingFinish`, `AwaitingDecision` and `WaitingOnParent` → waiting; `Refused` → counted by tag, then resumed with `explain(refusals)` and `Next: <first next>`, unless a tag is in `endsClaim` or three continuations ran; no new answer → one nudge naming the claim's remote and git's `remote:` lines, then `noAnswer` (or `refused` when an earlier answer was refused). An answer whose request was already acted on is no new answer. A harness that failed (a `Failed` event or a nonzero exit) with no new answer ends `failed`, without a pointless nudge. - `attempts` counts sessions started or resumed: an attempt counts once its output names the session, so a harness that exits before that is `failed` with 0 attempts (702's run test, which expects 0 for every harness the fake spawner fails, holds). - The run's `timeoutMs` bounds everything (`Effect.timeoutOption`): a stalled harness or an answer checked past it ends `timedOut`, with the attempts so far. - `RunAgent` gained an optional `project`; without it status lists every project and the ask is found by name (swarm.ts does not pass it yet: a one-line follow-up outside this territory). - `startCommand` stays (the dry run prints it) and is now `drivers[h].start`. - Token usage is logged per attempt; `AgentRun` (702's `results.ts`) has no field for it. - Live (one real headless start and one resume per harness, through the drivers' argv, in a scratch clone with the swarm's env shape, no platform; a dev-stage start would claim burrow's children that 804 needs): Claude Code session 0786f808-…, resumed in the same session; OpenCode on `openai/gpt-5.5` ses_ee4ae93d…, same session on resume; Amp T-01a11b51-…, continued twice in the probes; pi on `opencode-go/kimi-k3` (`marisol`), `opencode-go/glm-5.3` (`dagny`) and `opencode-go/qwen3.8-flash` with the adapter (`pell`). Each harness's tool printed the env var the probe set, so tools run in the workspace's env. Recorded into `packages/config/test/fixtures/swarm/harness-output/` with local paths replaced and the user's tool, MCP, plugin and skill lists and pi's system prompt left out. - Failures recorded, with their fallbacks: the roster's OpenCode model `openai/gpt-6.1-sol` is refused here ("not supported when using Codex with a ChatGPT account", as are `gpt-6-sol` and `gpt-5.6-sol`); `openai/gpt-5.5` works (a `roster.ts` swap for 799). pell's `opencode/gemini-3.8-flash` exits 1 ("No API key found for opencode"); `opencode-go/qwen3.8-flash` runs with the adapter, or the user adds OpenCode Zen's key to pi. The loop records both as `failed` with the reason. - Tests (`packages/config/test/swarm-loop.test.ts`, 15, red by assertion against 702's stub first): OutOfScope, StaleBase, Landed → 3 attempts, landed, both resumes `--resume <the first run's id>` with the rendered refusal; four refusals → three continuations, refused; ClaimLapsed → no continuation; a stalled run → timedOut at 600 000 ms on the TestClock; polling every 5 s while Checking; waiting outcomes; one nudge then noAnswer; an old answer is no new answer; a harness that never starts → failed with 0 attempts; a provider-refused model → failed, saying why; the harness's cwd, `extendEnv: false`, env (HOME only from the swarm's) and the attempt file with the token blanked; Amp's settings file; each driver's start and resume against a golden argv; the plan's `startCommand` equals each driver's `start`; each harness's recorded output parses to a session, settling (none for OpenCode) and tokens, the same session on resume. - ASSUMPTION: a push refused at stage 1 (`OutOfScope`, `Weakened{marker}` …) is not an answer in `status` (spec §8.6, "stage-1 refusals unrecorded"), so the loop sees no new answer and nudges; such refusals reach the agent only in git's `remote:` lines and are not counted by tag. - ASSUMPTION: the swarm claims fresh asks, so no answer predates the run; an answer already in status before the first start would be acted on as new.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+2429 added−83 removed
- tests:+1088 added−0 removed
- other:+1341 added−83 removed
Provenance
- Commit
bd4a3c9- Tree
abf2471- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
5060ac3
18 files changed+2429 added−83 removed
added:packages/config/test/fixtures/swarm/harness-output/amp/resume.jsonl+4 added
1+{"type":"system","subtype":"init","cwd":"/work/.swarm/r1/ivo/clone","session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412","agent_mode":"medium"}2+{"type":"user","message":{"role":"user","content":[{"type":"text","text":"What word did you reply with? Reply with that word again."}]},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}3+{"type":"assistant","message":{"type":"message","role":"assistant","content":[{"type":"text","text":"ready"}],"stop_reason":"end_turn","usage":{"input_tokens":4,"cache_creation_input_tokens":50914,"cache_read_input_tokens":0,"output_tokens":4,"service_tier":"standard"}},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}4+{"type":"result","subtype":"success","duration_ms":4026,"is_error":false,"num_turns":1,"result":"ready","session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}added:packages/config/test/fixtures/swarm/harness-output/amp/start.jsonl+6 added
1+{"type":"system","subtype":"init","cwd":"/work/.swarm/r1/ivo/clone","session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412","agent_mode":"medium"}2+{"type":"user","message":{"role":"user","content":[{"type":"text","text":"This is a probe of a headless run. Run the shell command `echo probe=$SWARM_PROBE`, then reply with the single word: ready."}]},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}3+{"type":"assistant","message":{"type":"message","role":"assistant","content":[{"type":"tool_use","id":"TU-034cKkt0kjURKzOomADMjG","name":"shell_command","input":{"command":"echo probe=$SWARM_PROBE","workdir":"/work/.swarm/r1/ivo/clone"}}],"stop_reason":"tool_use","usage":{"input_tokens":4,"cache_creation_input_tokens":50632,"cache_read_input_tokens":0,"output_tokens":157,"service_tier":"standard"}},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}4+{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"TU-034cKkt0kjURKzOomADMjG","content":"{\"output\":\"probe=ivo-env-ok\\n\",\"exitCode\":0}","is_error":false}]},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}5+{"type":"assistant","message":{"type":"message","role":"assistant","content":[{"type":"text","text":"ready"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"cache_creation_input_tokens":1134,"cache_read_input_tokens":49694,"output_tokens":4,"service_tier":"standard"}},"parent_tool_use_id":null,"session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}6+{"type":"result","subtype":"success","duration_ms":22369,"is_error":false,"num_turns":2,"result":"ready","session_id":"T-01a11b51-90f5-7698-8967-0e0ffb165412"}added:packages/config/test/fixtures/swarm/harness-output/claude-code/resume.jsonl+5 added
1+{"type":"system","subtype":"hook_started","hook_id":"1bd84849-cd43-4971-8e80-b384a9b88726","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"87564778-ef2c-4f50-8a1c-f0b2b7b2246b","session_id":"0786f808-2228-498f-8e09-77d859095d18"}2+{"type":"system","subtype":"hook_response","hook_id":"1bd84849-cd43-4971-8e80-b384a9b88726","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"34d3e001-d915-4e41-92af-d4419cbbf3fa","session_id":"0786f808-2228-498f-8e09-77d859095d18"}3+{"type":"system","subtype":"init","cwd":"/work/.swarm/r1/wren/clone","session_id":"0786f808-2228-498f-8e09-77d859095d18","model":"claude-opus-5-5","permissionMode":"bypassPermissions","apiKeySource":"none","claude_code_version":"2.1.293","output_style":"default","analytics_disabled":false,"product_feedback_disabled":false,"uuid":"7cd12027-fd99-4237-bf62-f8bc0ed0c313","per_turn_effort_active":true,"view_mode":"default"}4+{"type":"assistant","message":{"model":"claude-opus-5-5","id":"msg_011Cfpi2KtexdbH7A5WPj38H","type":"message","role":"assistant","content":[{"type":"text","text":"ready"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":47,"cache_read_input_tokens":25621,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":47},"output_tokens":4,"service_tier":"standard","inference_geo":"not_available"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"0786f808-2228-498f-8e09-77d859095d18","uuid":"d7bb49b4-7413-4c5e-bff6-bf56b60b48b4","timestamp":"2026-10-08T11:41:19.704Z","request_id":"req_011Cfpi2KdHVucs1pMRcnjds"}5+{"duration_api_ms":4004,"stop_reason":"end_turn","session_id":"0786f808-2228-498f-8e09-77d859095d18","total_cost_usd":0.12808819999999999,"usage":{"input_tokens":2,"cache_creation_input_tokens":47,"cache_read_input_tokens":25621,"output_tokens":4,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":47,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","speed":"standard","fallback_credit":null},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","safety_stops":0,"is_error":false,"num_turns":1,"subtype":"success","api_error_status":null,"result":"ready","ttft_ms":1342,"type":"result","duration_ms":1356,"uuid":"ee11acdf-527b-4294-9f49-e766c857a82c","ttft_stream_ms":1341,"time_to_request_ms":67,"first_content_frame_ms":1342,"queued_turn_count":0,"result_index":0}added:packages/config/test/fixtures/swarm/harness-output/claude-code/start.jsonl+7 added
1+{"type":"system","subtype":"hook_started","hook_id":"f7d0db64-163f-4032-ab18-7722f85c7a1e","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"cfafe047-ebdf-4a2d-85fb-cc31b516e59d","session_id":"0786f808-2228-498f-8e09-77d859095d18"}2+{"type":"system","subtype":"hook_response","hook_id":"f7d0db64-163f-4032-ab18-7722f85c7a1e","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"ebfd9505-98c5-487b-b878-dd603537729e","session_id":"0786f808-2228-498f-8e09-77d859095d18"}3+{"type":"system","subtype":"init","cwd":"/work/.swarm/r1/wren/clone","session_id":"0786f808-2228-498f-8e09-77d859095d18","model":"claude-opus-5-5","permissionMode":"bypassPermissions","apiKeySource":"none","claude_code_version":"2.1.293","output_style":"default","analytics_disabled":false,"product_feedback_disabled":false,"uuid":"b9ccd2e6-a8a6-4f8e-b250-b2394198ec42","per_turn_effort_active":true,"view_mode":"default"}4+{"type":"assistant","message":{"model":"claude-opus-5-5","id":"msg_011Cfpi2218dy4QqWmjQiTwQ","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01GQhd88U3hqv5MuFMGiqEKJ","name":"Bash","input":{"command":"echo probe=$SWARM_PROBE","description":"Print probe environment variable"},"caller":{"type":"direct"}}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":14026,"cache_read_input_tokens":11467,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":14026},"output_tokens":16,"service_tier":"standard","inference_geo":"not_available"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"0786f808-2228-498f-8e09-77d859095d18","uuid":"75394980-6814-46cb-9ff6-413022929601","timestamp":"2026-10-08T11:41:16.120Z","request_id":"req_011Cfpi21bpbSiLEQMfAcstR","wire_tool_inputs":{"toolu_01GQhd88U3hqv5MuFMGiqEKJ":{"command":"echo probe=$SWARM_PROBE","description":"Print probe environment variable"}}}5+{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01GQhd88U3hqv5MuFMGiqEKJ","type":"tool_result","content":"probe=wren-env-ok","is_error":false}]},"parent_tool_use_id":null,"session_id":"0786f808-2228-498f-8e09-77d859095d18","uuid":"73a966fa-7072-4f5c-856b-533990937cd0","timestamp":"2026-10-08T11:41:16.240Z","tool_use_result":{"stdout":"probe=wren-env-ok","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_result_meta":[{"id":"toolu_01GQhd88U3hqv5MuFMGiqEKJ","permission_decision":{"decision":"accept","source":"config","reason_type":"mode"}}]}6+{"type":"assistant","message":{"model":"claude-opus-5-5","id":"msg_011Cfpi2Ab4RJyY8Mby7EKAD","type":"message","role":"assistant","content":[{"type":"text","text":"ready"}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":128,"cache_read_input_tokens":25493,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":128},"output_tokens":4,"service_tier":"standard","inference_geo":"not_available"},"input_transformations":[],"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"0786f808-2228-498f-8e09-77d859095d18","uuid":"2cfe1bf3-db3f-4a07-b0c4-8a017b273dab","timestamp":"2026-10-08T11:41:17.009Z","request_id":"req_011Cfpi2AJTJetmj9CVnFyZq"}7+{"duration_api_ms":2712,"stop_reason":"end_turn","session_id":"0786f808-2228-498f-8e09-77d859095d18","total_cost_usd":0.1225,"usage":{"input_tokens":4,"cache_creation_input_tokens":14154,"cache_read_input_tokens":36960,"output_tokens":93,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":14154,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","speed":"standard","fallback_credit":null},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","safety_stops":0,"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"ready","ttft_ms":1980,"type":"result","duration_ms":2883,"uuid":"b8d374a9-6cfc-4c77-bf17-a01ee5a83968","ttft_stream_ms":1009,"time_to_request_ms":56,"first_content_frame_ms":1010,"queued_turn_count":0,"result_index":0}added:packages/config/test/fixtures/swarm/harness-output/opencode/refused-model.jsonl+2 added
1+{"type":"step_start","timestamp":1791459681667,"sessionID":"ses_ee4ae9e95ffehty1k3fLpMFlH3","part":{"id":"prt_11b516583001j0731LRAm8aoey","sessionID":"ses_ee4ae9e95ffehty1k3fLpMFlH3","messageID":"msg_11b51633e0012hHj2Hi8WtjPzj","type":"step-start","snapshot":"1766483793937eed1e3b0926a5a74633da742b85"}}2+{"type":"error","timestamp":1791459681678,"sessionID":"ses_ee4ae9e95ffehty1k3fLpMFlH3","error":{"type":"provider.invalid-request","message":"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account."}}added:packages/config/test/fixtures/swarm/harness-output/opencode/resume.jsonl+2 added
1+{"type":"step_start","timestamp":1791459691311,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b518b2f001BJtsWnqgI63KWP","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b517e72001WqGDajkQWSfUcU","type":"step-start","snapshot":"1766483793937eed1e3b0926a5a74633da742b85"}}2+{"type":"text","timestamp":1791459691318,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b518b32001APOE6etAwrjOAy","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b517e72001WqGDajkQWSfUcU","type":"text","text":"ready","time":{"start":1791459691314,"end":1791459691318}}}added:packages/config/test/fixtures/swarm/harness-output/opencode/start.jsonl+5 added
1+{"type":"step_start","timestamp":1791459685388,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b51740c001Wc3ki36zIiOFcu","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b516e46001R5F44jFtE0WdKA","type":"step-start","snapshot":"1766483793937eed1e3b0926a5a74633da742b85"}}2+{"type":"tool_use","timestamp":1791459685721,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"partID":"prt_11b51740e001HqeVu6GYu3xmYH","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b516e46001R5F44jFtE0WdKA","type":"tool","id":"call_f5bed68f7d16440f8c45502011d9e5a9","tool":"shell","state":{"status":"completed","input":{"command":"echo probe=$SWARM_PROBE"},"output":"probe=tamsin-env-ok\n","title":"shell","metadata":{"metadata":{"status":"completed","truncated":false,"exit":0},"content":[{"type":"text","text":"probe=tamsin-env-ok\n"},{"type":"text","text":"Command exited with code 0."}],"providerCall":{"executed":false,"state":{"itemId":"fc_0e973434d32ab579016ac781655a3881989eaf52f74c72bd9c"}},"providerResult":{"executed":false},"rawInput":"{\"command\":\"echo probe=$SWARM_PROBE\"}"},"time":{"start":1791459685390,"end":1791459685721}}}}3+{"type":"step_finish","timestamp":1791459685831,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b5175c7001PWDPvE8UOe9pCB","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b516e46001R5F44jFtE0WdKA","type":"step-finish","reason":"tool-calls","snapshot":"1766483793937eed1e3b0926a5a74633da742b85","cost":0,"tokens":{"input":18888,"output":23,"reasoning":0,"cache":{"read":0,"write":0}}}}4+{"type":"step_start","timestamp":1791459687068,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b517a9c001gsd7lLfx2MGl3u","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b5175d0001NpKzNO5sWhmSwT","type":"step-start","snapshot":"1766483793937eed1e3b0926a5a74633da742b85"}}5+{"type":"text","timestamp":1791459687073,"sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","part":{"id":"prt_11b517a9f001w247TbTgskIkoe","sessionID":"ses_ee4ae93d8ffecveCAQ20H606pZ","messageID":"msg_11b5175d0001NpKzNO5sWhmSwT","type":"text","text":"ready","time":{"start":1791459687071,"end":1791459687073}}}added:packages/config/test/fixtures/swarm/harness-output/pi/resume.jsonl+21 added
1+{"type":"session","version":3,"id":"marisol","timestamp":"2026-10-08T11:42:05.467Z","cwd":"/work/.swarm/r1/marisol/clone"}2+{"type":"agent_start"}3+{"type":"turn_start"}4+{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"What word did you reply with? Reply with that word again."}],"timestamp":1791459731404}}5+{"type":"message_end","message":{"role":"user","content":[{"type":"text","text":"What word did you reply with? Reply with that word again."}],"timestamp":1791459731404}}6+{"type":"message_start","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The","thinkingSignature":"reasoning_content"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"pending","timestamp":1791459731415}}7+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_start","contentIndex":0}}8+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"The"}}9+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" user asks"}}10+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" what word I"}}11+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" replied with. I replied with"}}12+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" \"ready\". Reply"}}13+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" with that word again."}}14+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"text_start","contentIndex":1}}15+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"text_delta","contentIndex":1,"delta":"ready"}}16+{"type":"message_update","usage":{"input":10974,"output":35,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":11009,"cost":{"input":0.032922,"output":0.000525,"cacheRead":0,"cacheWrite":0,"total":0.033447}},"assistantMessageEvent":{"type":"thinking_end","contentIndex":0,"content":"The user asks what word I replied with. I replied with \"ready\". Reply with that word again."}}17+{"type":"message_update","usage":{"input":10974,"output":35,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":11009,"cost":{"input":0.032922,"output":0.000525,"cacheRead":0,"cacheWrite":0,"total":0.033447}},"assistantMessageEvent":{"type":"text_end","contentIndex":1,"content":"ready"}}18+{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user asks what word I replied with. I replied with \"ready\". Reply with that word again.","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user asks what word I replied with. I replied with \\\"ready\\\". Reply with that word again.\",\"format\":\"unknown\",\"index\":0}]"},{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10974,"output":35,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":11009,"cost":{"input":0.032922,"output":0.000525,"cacheRead":0,"cacheWrite":0,"total":0.033447}},"stopReason":"stop","timestamp":1791459731415,"responseId":"876e0d6e-9173-4a3c-a7a5-105e99ace8f5","rawStopReason":"stop","durationMs":23484,"thinkingLevel":"max"}}19+{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user asks what word I replied with. I replied with \"ready\". Reply with that word again.","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user asks what word I replied with. I replied with \\\"ready\\\". Reply with that word again.\",\"format\":\"unknown\",\"index\":0}]"},{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10974,"output":35,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":11009,"cost":{"input":0.032922,"output":0.000525,"cacheRead":0,"cacheWrite":0,"total":0.033447}},"stopReason":"stop","timestamp":1791459731415,"responseId":"876e0d6e-9173-4a3c-a7a5-105e99ace8f5","rawStopReason":"stop","durationMs":23484,"thinkingLevel":"max"},"toolResults":[]}20+{"type":"agent_end","messages":[{"role":"user","content":[{"type":"text","text":"What word did you reply with? Reply with that word again."}],"timestamp":1791459731404},{"role":"assistant","content":[{"type":"thinking","thinking":"The user asks what word I replied with. I replied with \"ready\". Reply with that word again.","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user asks what word I replied with. I replied with \\\"ready\\\". Reply with that word again.\",\"format\":\"unknown\",\"index\":0}]"},{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10974,"output":35,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":11009,"cost":{"input":0.032922,"output":0.000525,"cacheRead":0,"cacheWrite":0,"total":0.033447}},"stopReason":"stop","timestamp":1791459731415,"responseId":"876e0d6e-9173-4a3c-a7a5-105e99ace8f5","rawStopReason":"stop","durationMs":23484,"thinkingLevel":"max"}],"willRetry":false}21+{"type":"agent_settled","aborted":false}added:packages/config/test/fixtures/swarm/harness-output/pi/start.jsonl+37 added
1+{"type":"session","version":3,"id":"marisol","timestamp":"2026-10-08T11:42:05.467Z","cwd":"/work/.swarm/r1/marisol/clone"}2+{"type":"agent_start"}3+{"type":"turn_start"}4+{"type":"message_start","message":{"role":"system","content":"(the harness's system prompt, omitted from the recording)","sections":[],"timestamp":1791459726064,"toolsAdded":[]}}5+{"type":"message_end","message":{"role":"system","content":"(the harness's system prompt, omitted from the recording)","sections":[],"timestamp":1791459726064,"toolsAdded":[]}}6+{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"This is a probe of a headless run. Run the shell command `echo probe=$SWARM_PROBE`, then reply with the single word: ready."}],"timestamp":1791459726063}}7+{"type":"message_end","message":{"role":"user","content":[{"type":"text","text":"This is a probe of a headless run. Run the shell command `echo probe=$SWARM_PROBE`, then reply with the single word: ready."}],"timestamp":1791459726063}}8+{"type":"message_start","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The","thinkingSignature":"reasoning_content"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"pending","timestamp":1791459726073}}9+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_start","contentIndex":0}}10+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"The"}}11+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" user wants me"}}12+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" to run `"}}13+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"echo probe=$SWARM_PROBE` and"}}14+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":" then reply with the single word \"ready"}}15+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"thinking_delta","contentIndex":0,"delta":"\"."}}16+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"toolcall_start","contentIndex":1,"id":"bash:0","toolName":"bash"}}17+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"toolcall_delta","contentIndex":1,"delta":""}}18+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"toolcall_delta","contentIndex":1,"delta":"{\"command\": \"echo probe=$SWARM_PROBE\", \"timeout\": 10}"}}19+{"type":"message_update","usage":{"input":10797,"output":92,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":10889,"cost":{"input":0.032391,"output":0.00138,"cacheRead":0,"cacheWrite":0,"total":0.033771}},"assistantMessageEvent":{"type":"thinking_end","contentIndex":0,"content":"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \"ready\"."}}20+{"type":"message_update","usage":{"input":10797,"output":92,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":10889,"cost":{"input":0.032391,"output":0.00138,"cacheRead":0,"cacheWrite":0,"total":0.033771}},"assistantMessageEvent":{"type":"toolcall_end","contentIndex":1,"toolCall":{"type":"toolCall","id":"bash:0","name":"bash","arguments":{"command":"echo probe=$SWARM_PROBE","timeout":10}}}}21+{"type":"message_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \"ready\".","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \\\"ready\\\".\",\"format\":\"unknown\",\"index\":0}]"},{"type":"toolCall","id":"bash:0","name":"bash","arguments":{"command":"echo probe=$SWARM_PROBE","timeout":10}}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10797,"output":92,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":10889,"cost":{"input":0.032391,"output":0.00138,"cacheRead":0,"cacheWrite":0,"total":0.033771}},"stopReason":"toolUse","timestamp":1791459726073,"responseId":"2c74654e-1bc5-42b5-862f-0f8cc20372b7","rawStopReason":"tool_calls","durationMs":1704,"thinkingLevel":"max"}}22+{"type":"tool_execution_start","toolCallId":"bash:0","toolName":"bash","args":{"command":"echo probe=$SWARM_PROBE","timeout":10}}23+{"type":"tool_execution_update","toolCallId":"bash:0","toolName":"bash","args":{"command":"echo probe=$SWARM_PROBE","timeout":10},"partialResult":{"content":[]}}24+{"type":"tool_execution_update","toolCallId":"bash:0","toolName":"bash","args":{"command":"echo probe=$SWARM_PROBE","timeout":10},"partialResult":{"content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"details":{}}}25+{"type":"tool_execution_end","toolCallId":"bash:0","toolName":"bash","result":{"content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"structuredContent":{"output":"probe=marisol-env-ok\n","truncated":false,"exit_code":0,"wall_time_seconds":0}},"isError":false,"durationMs":6}26+{"type":"message_start","message":{"role":"toolResult","toolCallId":"bash:0","toolName":"bash","content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"isError":false,"durationMs":6,"timestamp":1791459727788}}27+{"type":"message_end","message":{"role":"toolResult","toolCallId":"bash:0","toolName":"bash","content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"isError":false,"durationMs":6,"timestamp":1791459727788}}28+{"type":"turn_end","message":{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \"ready\".","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \\\"ready\\\".\",\"format\":\"unknown\",\"index\":0}]"},{"type":"toolCall","id":"bash:0","name":"bash","arguments":{"command":"echo probe=$SWARM_PROBE","timeout":10}}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10797,"output":92,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":10889,"cost":{"input":0.032391,"output":0.00138,"cacheRead":0,"cacheWrite":0,"total":0.033771}},"stopReason":"toolUse","timestamp":1791459726073,"responseId":"2c74654e-1bc5-42b5-862f-0f8cc20372b7","rawStopReason":"tool_calls","durationMs":1704,"thinkingLevel":"max"},"toolResults":[{"role":"toolResult","toolCallId":"bash:0","toolName":"bash","content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"isError":false,"durationMs":6,"timestamp":1791459727788}]}29+{"type":"turn_start"}30+{"type":"message_start","message":{"role":"assistant","content":[{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"stopReason":"pending","timestamp":1791459727790}}31+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"text_start","contentIndex":0}}32+{"type":"message_update","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"total":0}},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"ready"}}33+{"type":"message_update","usage":{"input":174,"output":14,"cacheRead":10752,"cacheWrite":0,"reasoning":0,"totalTokens":10940,"cost":{"input":0.000522,"output":0.00021,"cacheRead":0.0032256,"cacheWrite":0,"total":0.0039576}},"assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"ready"}}34+{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":174,"output":14,"cacheRead":10752,"cacheWrite":0,"reasoning":0,"totalTokens":10940,"cost":{"input":0.000522,"output":0.00021,"cacheRead":0.0032256,"cacheWrite":0,"total":0.0039576}},"stopReason":"stop","timestamp":1791459727790,"responseId":"3cd57e89-caf8-4a8c-9f8b-d91fd00c8920","rawStopReason":"stop","durationMs":2798,"thinkingLevel":"max"}}35+{"type":"turn_end","message":{"role":"assistant","content":[{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":174,"output":14,"cacheRead":10752,"cacheWrite":0,"reasoning":0,"totalTokens":10940,"cost":{"input":0.000522,"output":0.00021,"cacheRead":0.0032256,"cacheWrite":0,"total":0.0039576}},"stopReason":"stop","timestamp":1791459727790,"responseId":"3cd57e89-caf8-4a8c-9f8b-d91fd00c8920","rawStopReason":"stop","durationMs":2798,"thinkingLevel":"max"},"toolResults":[]}36+{"type":"agent_end","messages":[{"role":"system","content":"(the harness's system prompt, omitted from the recording)","sections":[],"timestamp":1791459726064,"toolsAdded":[]},{"role":"user","content":[{"type":"text","text":"This is a probe of a headless run. Run the shell command `echo probe=$SWARM_PROBE`, then reply with the single word: ready."}],"timestamp":1791459726063},{"role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \"ready\".","thinkingSignature":"[{\"type\":\"reasoning.text\",\"text\":\"The user wants me to run `echo probe=$SWARM_PROBE` and then reply with the single word \\\"ready\\\".\",\"format\":\"unknown\",\"index\":0}]"},{"type":"toolCall","id":"bash:0","name":"bash","arguments":{"command":"echo probe=$SWARM_PROBE","timeout":10}}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":10797,"output":92,"cacheRead":0,"cacheWrite":0,"reasoning":24,"totalTokens":10889,"cost":{"input":0.032391,"output":0.00138,"cacheRead":0,"cacheWrite":0,"total":0.033771}},"stopReason":"toolUse","timestamp":1791459726073,"responseId":"2c74654e-1bc5-42b5-862f-0f8cc20372b7","rawStopReason":"tool_calls","durationMs":1704,"thinkingLevel":"max"},{"role":"toolResult","toolCallId":"bash:0","toolName":"bash","content":[{"type":"text","text":"probe=marisol-env-ok\n"}],"isError":false,"durationMs":6,"timestamp":1791459727788},{"role":"assistant","content":[{"type":"text","text":"ready"}],"api":"openai-completions","provider":"opencode-go","model":"kimi-k3","usage":{"input":174,"output":14,"cacheRead":10752,"cacheWrite":0,"reasoning":0,"totalTokens":10940,"cost":{"input":0.000522,"output":0.00021,"cacheRead":0.0032256,"cacheWrite":0,"total":0.0039576}},"stopReason":"stop","timestamp":1791459727790,"responseId":"3cd57e89-caf8-4a8c-9f8b-d91fd00c8920","rawStopReason":"stop","durationMs":2798,"thinkingLevel":"max"}],"willRetry":false}37+{"type":"agent_settled","aborted":false}added:packages/config/test/swarm-loop.test.ts+999 added
1+/**2+ * The swarm's verdict loop (issue 711): each contributor's harness started3+ * headless on the brief, and every refusal their answer meets sent back into4+ * the same session, at most three times. The loop reads outcomes only from5+ * the contributor's `<cli> status --json`; a harness's output gives it the6+ * session id, that the session settled, and the tokens it used.7+ *8+ * The harness output under `fixtures/swarm/harness-output/<harness>/` is9+ * what each installed harness printed for one headless start and one resume10+ * on 2026-10-08, its local paths replaced and the user's own setup (tool,11+ * MCP, plugin and skill lists, pi's system prompt) left out.12+ */13+import { NodeServices } from "@effect/platform-node";14+import { describe, expect, it } from "@effect/vitest";15+import { AnswerView } from "@repo/protocol/domain/answer";16+import { ClaimView } from "@repo/protocol/domain/claim";17+import { Outcome } from "@repo/protocol/domain/outcome";18+import { Envelope } from "@repo/protocol/envelope";19+import {20+ AskId,21+ CommitSha,22+ DecisionId,23+ Handle,24+ LandedSha,25+ RepoPath,26+ RequestId,27+} from "@repo/protocol/ids";28+import {29+ ChecksFailed,30+ ClaimLapsed,31+ OutOfScope,32+ StaleBase,33+} from "@repo/protocol/refusal";34+import type { Refusal } from "@repo/protocol/refusal";35+import { explain } from "@repo/protocol/render";36+import {37+ ConfigProvider,38+ Console,39+ DateTime,40+ Effect,41+ Fiber,42+ FileSystem,43+ Layer,44+ Path,45+ Ref,46+ Schema,47+ Sink,48+ Stream,49+} from "effect";50+import type { Array } from "effect";51+import { ChildProcess, ChildProcessSpawner } from "effect/process";52+import { TestClock } from "effect/testing";53+54+import {55+ drivers,56+ HarnessEvent,57+} from "../../../scripts/lib/swarm/harnesses/index.ts";58+import type { HarnessDriver } from "../../../scripts/lib/swarm/harnesses/index.ts";59+import { runAgent, startCommand } from "../../../scripts/lib/swarm/loop.ts";60+import type { Assignment } from "../../../scripts/lib/swarm/plan.ts";61+import type { Harness } from "../../../scripts/lib/swarm/results.ts";62+import { roster } from "../../../scripts/lib/swarm/roster.ts";63+import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";64+import { Brand } from "../../brand/src/index.ts";65+import { repoRoot } from "./root.ts";66+67+/** The env names the CLI reads, spelled from the brand. */68+const SLUG = Brand.slug.toUpperCase();69+70+const token = "wren-token-0123456789abcdef0123456789abcdef";71+72+const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";73+74+const ask = AskId.make("drop-legacy-fetch-burrow-auth");75+76+/** A harness's recorded output: `start`, `resume`, or OpenCode's `refused-model`. */77+const recorded = (78+ harness: Harness,79+ run: "start" | "resume" | "refused-model"80+) =>81+ Effect.gen(function* () {82+ const fs = yield* FileSystem.FileSystem;83+ const path = yield* Path.Path;84+85+ const text = yield* fs.readFileString(86+ path.join(87+ "test",88+ "fixtures",89+ "swarm",90+ "harness-output",91+ harness,92+ `${run}.jsonl`93+ )94+ );95+96+ return text.split("\n").filter((line) => line !== "");97+ }).pipe(Effect.provide(NodeServices.layer));98+99+/** Everything one recorded run's lines say, in order. */100+const heard = (driver: HarnessDriver, lines: readonly string[]) =>101+ lines.flatMap(driver.parse);102+103+const sessionsIn = (events: readonly HarnessEvent[]) =>104+ events.flatMap((event) =>105+ HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []106+ );107+108+// The commits of four answers, and the landing of the last.109+const heads = ["1", "2", "3", "4"].map((digit) =>110+ CommitSha.make(digit.repeat(40))111+);112+113+const landing = LandedSha.make(CommitSha.make("a".repeat(40)));114+115+/** One answer to the ask, `n` seconds after noon, with its outcome. */116+const answer = (n: number, outcome: Outcome): AnswerView => ({117+ ask,118+ at: DateTime.makeUnsafe(`2026-10-08T12:00:0${n}.000Z`),119+ head: heads[n] ?? CommitSha.make("f".repeat(40)),120+ outcome,121+ requestId: RequestId.make(`push-${heads[n] ?? "f".repeat(40)}-wren`),122+});123+124+const refused = (...refusals: Array.NonEmptyReadonlyArray<Refusal>) =>125+ Outcome.cases.Refused.make({ refusals });126+127+const outOfScope = new OutOfScope({128+ paths: [RepoPath.make("packages/billing/src/index.ts")],129+});130+131+const staleBase = new StaleBase({132+ base: CommitSha.make("b".repeat(40)),133+ conflicts: [],134+ main: CommitSha.make("c".repeat(40)),135+});136+137+const checksFailed = new ChecksFailed({138+ lane: "test",139+ logRef: "log-0001",140+ next: `${Brand.cli} evidence log-0001`,141+});142+143+const wrensClaim: ClaimView = Schema.decodeSync(ClaimView)({144+ ask,145+ base: "9998ebe62c2f282d148b1d806372484916cc2548",146+ checkCommand: `${Brand.cli} check`,147+ claimant: "wren",148+ fork: "burrow--drop-legacy-fetch-burrow-auth--wren",149+ lapsesAt: "2026-10-09T05:00:00.000Z",150+ openedAt: "2026-10-08T05:00:00.000Z",151+ project: "burrow",152+ remote: `${platformUrl}/burrow--drop-legacy-fetch-burrow-auth--wren.git`,153+ state: "live",154+ warnsAt: "2026-10-08T17:00:00.000Z",155+});156+157+const StatusJson = Schema.fromJsonString(158+ Envelope(159+ Schema.Struct({160+ answers: Schema.Array(AnswerView),161+ claims: Schema.Array(ClaimView),162+ handle: Handle,163+ })164+ )165+);166+167+/** What `<cli> status --json` prints for wren with these answers. */168+const status = (...answers: readonly AnswerView[]) =>169+ Schema.encodeSync(StatusJson)({170+ command: "status",171+ data: { answers, claims: [wrensClaim], handle: Handle.make("wren") },172+ ok: true,173+ v: 1,174+ });175+176+/** One command the fake spawner was asked to run. */177+interface Spawned {178+ readonly command: string;179+ readonly args: readonly string[];180+ readonly cwd: string | undefined;181+ readonly env: Readonly<Record<string, string | undefined>>;182+ readonly extendEnv: boolean | undefined;183+}184+185+/** How a scripted harness run goes: its stdout lines and exit code, or it never ends. */186+type HarnessRun =187+ | { readonly lines: readonly string[]; readonly code?: number }188+ | { readonly stalls: readonly string[] };189+190+const bytes = (text: string) => new TextEncoder().encode(text);191+192+/** A process handle that prints `stdout` and ends with `exitCode`. */193+const handleOf = (input: {194+ readonly stdout: Stream.Stream<Uint8Array>;195+ readonly exitCode: Effect.Effect<number>;196+}) =>197+ ChildProcessSpawner.makeHandle({198+ all: input.stdout,199+ exitCode: Effect.map(input.exitCode, ChildProcessSpawner.ExitCode),200+ getInputFd: () => Sink.drain,201+ getOutputFd: () => Stream.empty,202+ isRunning: Effect.succeed(false),203+ kill: () => Effect.void,204+ pid: ChildProcessSpawner.ProcessId(1),205+ stderr: Stream.empty,206+ stdin: Sink.drain,207+ stdout: input.stdout,208+ unref: Effect.succeed(Effect.void),209+ });210+211+/**212+ * A `ChildProcessSpawner` that runs nothing. The workspace's CLI answers213+ * `status` with the next of `statuses` (the last one again once they run214+ * out); any other command is a harness, and plays the next of `harness`.215+ */216+const fakeWorld = (script: {217+ readonly harness: readonly HarnessRun[];218+ readonly statuses: readonly string[];219+}) =>220+ Effect.gen(function* () {221+ const spawned = yield* Ref.make<readonly Spawned[]>([]);222+ const runs = yield* Ref.make(script.harness);223+ const statuses = yield* Ref.make(script.statuses);224+225+ const spawner = ChildProcessSpawner.make((command) =>226+ Effect.gen(function* () {227+ if (!ChildProcess.isStandardCommand(command)) {228+ return yield* Effect.die("the swarm pipes no commands");229+ }230+231+ yield* Ref.update(spawned, (calls) => [232+ ...calls,233+ {234+ args: command.args,235+ command: command.command,236+ cwd: command.options.cwd,237+ env: command.options.env ?? {},238+ extendEnv: command.options.extendEnv,239+ },240+ ]);241+242+ if (command.command.endsWith(`/bin/${Brand.cli}`)) {243+ const [next = "", ...rest] = yield* Ref.get(statuses);244+245+ if (rest.length > 0) {246+ yield* Ref.set(statuses, rest);247+ }248+249+ return handleOf({250+ exitCode: Effect.succeed(0),251+ stdout: Stream.make(bytes(`${next}\n`)),252+ });253+ }254+255+ const [next, ...rest] = yield* Ref.get(runs);256+257+ yield* Ref.set(runs, rest);258+259+ if (next === undefined) {260+ return yield* Effect.die(261+ `no harness run scripted for ${command.command}`262+ );263+ }264+265+ return "stalls" in next266+ ? handleOf({267+ exitCode: Effect.never,268+ stdout: Stream.make(bytes(`${next.stalls.join("\n")}\n`)).pipe(269+ Stream.concat(Stream.never)270+ ),271+ })272+ : handleOf({273+ exitCode: Effect.succeed(next.code ?? 0),274+ stdout: Stream.make(bytes(`${next.lines.join("\n")}\n`)),275+ });276+ })277+ );278+279+ return {280+ harnessRuns: Effect.map(Ref.get(spawned), (calls) =>281+ calls.filter(({ command }) => !command.endsWith(`/bin/${Brand.cli}`))282+ ),283+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),284+ spawned: Ref.get(spawned),285+ };286+ });287+288+/**289+ * A file system in memory: directories always exist, and a write (or an290+ * append, with flag `a`) lands in `files`. The loop's writes are then as291+ * synchronous as the fake processes, so the TestClock moves deterministically.292+ */293+const memoryFs = (files: Map<string, string>) =>294+ FileSystem.makeNoop({295+ makeDirectory: () => Effect.void,296+ writeFileString: (path, data, options) =>297+ Effect.sync(() => {298+ files.set(299+ path,300+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data301+ );302+ }),303+ });304+305+/** wren's workspace for run `r1`. */306+const dir = "/work/.swarm/r1/wren";307+308+const wrensWorkspace: AgentWorkspace = {309+ clone: `${dir}/clone`,310+ dir,311+ env: {312+ GIT_TERMINAL_PROMPT: "0",313+ PATH: `${dir}/bin:/usr/bin`,314+ [`${SLUG}_TOKEN`]: token,315+ [`${SLUG}_URL`]: platformUrl,316+ XDG_CONFIG_HOME: `${dir}/config`,317+ },318+ redacted: [`${SLUG}_TOKEN`],319+};320+321+/** The swarm's own env: the user's HOME, and secrets no harness may see. */322+const swarmEnv = ConfigProvider.fromEnv({323+ env: {324+ CLAUDECODE: "1",325+ CLOUDFLARE_API_TOKEN: "cf-secret",326+ HOME: "/home/user",327+ SESSION_TOKENS: JSON.stringify({ [token]: "wren" }),328+ },329+});330+331+const [wren, tamsin, ivo] = roster;332+333+/**334+ * `runAgent` for `contributor` on burrow's auth child, over a fake world and335+ * a file system in memory. It runs forked, so `clock` can move the TestClock336+ * while it runs.337+ */338+const agentRun = (input: {339+ readonly harness: readonly HarnessRun[];340+ readonly statuses: readonly string[];341+ readonly contributor?: Assignment["contributor"];342+ readonly timeoutMs?: number;343+ readonly clock?: Effect.Effect<void>;344+}) =>345+ Effect.gen(function* () {346+ const world = yield* fakeWorld(input);347+ const files = new Map<string, string>();348+ const said: string[] = [];349+350+ const captured: Console.Console = {351+ ...console,352+ error: (...args: readonly unknown[]) => {353+ said.push(args.map(String).join(" "));354+ },355+ log: (...args: readonly unknown[]) => {356+ said.push(args.map(String).join(" "));357+ },358+ };359+360+ const fiber = yield* runAgent({361+ assignment: {362+ ask,363+ contributor: input.contributor ?? wren,364+ territory: "@burrow/auth",365+ },366+ brief: "Answer the ask.",367+ maxContinuations: 3,368+ timeoutMs: input.timeoutMs ?? 1_200_000,369+ workspace: wrensWorkspace,370+ }).pipe(371+ Effect.provide(world.layer),372+ Effect.provideService(FileSystem.FileSystem, memoryFs(files)),373+ Effect.provideService(Console.Console, captured),374+ Effect.provideService(ConfigProvider.ConfigProvider, swarmEnv),375+ Effect.forkChild376+ );377+378+ yield* input.clock ?? Effect.void;379+380+ const result = yield* Fiber.join(fiber);381+382+ return {383+ files,384+ harnessRuns: yield* world.harnessRuns,385+ result,386+ said,387+ spawned: yield* world.spawned,388+ };389+ });390+391+/** The prompt a harness run carried: its last argument. */392+const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";393+394+describe("the verdict loop", () => {395+ it.effect(396+ "resumes the same session on OutOfScope, then on StaleBase, and stops when the answer lands",397+ () =>398+ Effect.gen(function* () {399+ const start = yield* recorded("claude-code", "start");400+ const resume = yield* recorded("claude-code", "resume");401+ const [session] = sessionsIn(heard(drivers["claude-code"], start));402+403+ const first = answer(1, refused(outOfScope));404+ const second = answer(2, refused(staleBase));405+ const third = answer(3, Outcome.cases.Landed.make({ sha: landing }));406+407+ const { harnessRuns, result } = yield* agentRun({408+ harness: [{ lines: start }, { lines: resume }, { lines: resume }],409+ statuses: [410+ status(first),411+ status(first, second),412+ status(first, second, third),413+ ],414+ });415+416+ expect(result).toStrictEqual({417+ adapter: false,418+ ask,419+ attempts: 3,420+ durationMs: 0,421+ handle: "wren",422+ harness: "claude-code",423+ landed: landing,424+ model: "claude-opus-5-5",425+ outcome: "landed",426+ refusals: { OutOfScope: 1, StaleBase: 1 },427+ });428+429+ const [, afterOutOfScope, afterStaleBase] = harnessRuns;430+431+ expect(432+ [afterOutOfScope, afterStaleBase].map(433+ (run) => run?.args.slice(-3, -1) ?? []434+ )435+ ).toStrictEqual([436+ ["--resume", session],437+ ["--resume", session],438+ ]);439+ expect(promptOf(afterOutOfScope)).toContain(440+ [...explain([outOfScope]), "", `Next: ${outOfScope.next}`].join("\n")441+ );442+ expect(promptOf(afterStaleBase)).toContain(`Next: ${staleBase.next}`);443+ })444+ );445+446+ it.effect(447+ "gives up as refused after three continuations when a fourth refusal comes back",448+ () =>449+ Effect.gen(function* () {450+ const start = yield* recorded("claude-code", "start");451+ const resume = yield* recorded("claude-code", "resume");452+453+ const answers = [1, 2, 3, 4].map((n) =>454+ answer(n, refused(checksFailed))455+ );456+457+ const { harnessRuns, result } = yield* agentRun({458+ harness: [459+ { lines: start },460+ { lines: resume },461+ { lines: resume },462+ { lines: resume },463+ { lines: resume },464+ ],465+ statuses: answers.map((_, n) => status(...answers.slice(0, n + 1))),466+ });467+468+ expect([469+ result.outcome,470+ result.attempts,471+ result.refusals,472+ ]).toStrictEqual(["refused", 4, { ChecksFailed: 4 }]);473+ expect(harnessRuns).toHaveLength(4);474+ })475+ );476+477+ it.effect("stops at once on a refusal that ends the claim", () =>478+ Effect.gen(function* () {479+ const start = yield* recorded("claude-code", "start");480+481+ const { harnessRuns, result } = yield* agentRun({482+ harness: [{ lines: start }],483+ statuses: [status(answer(1, refused(ClaimLapsed.of(ask))))],484+ });485+486+ expect([result.outcome, result.attempts, result.refusals]).toStrictEqual([487+ "refused",488+ 1,489+ { ClaimLapsed: 1 },490+ ]);491+ expect(harnessRuns).toHaveLength(1);492+ })493+ );494+495+ it.effect(496+ "records a run that never settles as timedOut when its timeout passes on the clock",497+ () =>498+ Effect.gen(function* () {499+ const start = yield* recorded("claude-code", "start");500+501+ const { result } = yield* agentRun({502+ clock: TestClock.adjust("10 minutes"),503+ harness: [{ stalls: start.slice(0, 3) }],504+ statuses: [status()],505+ timeoutMs: 600_000,506+ });507+508+ expect([509+ result.outcome,510+ result.attempts,511+ result.durationMs,512+ ]).toStrictEqual(["timedOut", 1, 600_000]);513+ })514+ );515+516+ it.effect(517+ "asks status again every five seconds while the answer is being checked",518+ () =>519+ Effect.gen(function* () {520+ const start = yield* recorded("claude-code", "start");521+ const checking = Outcome.cases.Checking.make({ stage: "checks" });522+523+ const { result, spawned } = yield* agentRun({524+ clock: Effect.gen(function* () {525+ yield* TestClock.adjust("5 seconds");526+ yield* TestClock.adjust("5 seconds");527+ }),528+ harness: [{ lines: start }],529+ statuses: [530+ status(answer(1, checking)),531+ status(answer(1, checking)),532+ status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),533+ ],534+ });535+536+ expect([result.outcome, result.attempts, result.landed]).toStrictEqual([537+ "landed",538+ 1,539+ landing,540+ ]);541+ expect(542+ spawned.filter(({ command }) => command.endsWith(`/bin/${Brand.cli}`))543+ ).toHaveLength(3);544+ })545+ );546+547+ it.effect(548+ "records an answer waiting on a decision or a finish as waiting, without a continuation",549+ () =>550+ Effect.gen(function* () {551+ const start = yield* recorded("claude-code", "start");552+553+ const waits = [554+ Outcome.cases.AwaitingDecision.make({555+ decision: DecisionId.make("dec-000001"),556+ }),557+ Outcome.cases.AwaitingFinish.make({}),558+ ];559+560+ const results = yield* Effect.forEach(waits, (waiting) =>561+ agentRun({562+ harness: [{ lines: start }],563+ statuses: [status(answer(1, waiting))],564+ })565+ );566+567+ expect(568+ results.map(({ harnessRuns, result }) => [569+ result.outcome,570+ result.attempts,571+ harnessRuns.length,572+ ])573+ ).toStrictEqual([574+ ["waiting", 1, 1],575+ ["waiting", 1, 1],576+ ]);577+ })578+ );579+580+ it.effect(581+ "nudges once, naming the claim's remote, when no answer was pushed, then records noAnswer",582+ () =>583+ Effect.gen(function* () {584+ const start = yield* recorded("claude-code", "start");585+ const resume = yield* recorded("claude-code", "resume");586+587+ const { harnessRuns, result } = yield* agentRun({588+ harness: [{ lines: start }, { lines: resume }, { lines: resume }],589+ statuses: [status()],590+ });591+592+ expect([result.outcome, result.attempts]).toStrictEqual([593+ "noAnswer",594+ 2,595+ ]);596+ expect(promptOf(harnessRuns[1])).toContain(wrensClaim.remote);597+ })598+ );599+600+ it.effect(601+ "takes an old answer status still shows after a continuation as no new answer",602+ () =>603+ Effect.gen(function* () {604+ const start = yield* recorded("claude-code", "start");605+ const resume = yield* recorded("claude-code", "resume");606+ const first = answer(1, refused(checksFailed));607+608+ const { result } = yield* agentRun({609+ harness: [{ lines: start }, { lines: resume }, { lines: resume }],610+ statuses: [status(first)],611+ });612+613+ expect([614+ result.outcome,615+ result.attempts,616+ result.refusals,617+ ]).toStrictEqual(["refused", 3, { ChecksFailed: 1 }]);618+ })619+ );620+621+ it.effect(622+ "records a harness that exits before it starts a session as failed",623+ () =>624+ Effect.gen(function* () {625+ const { result, spawned } = yield* agentRun({626+ harness: [{ code: 1, lines: [] }],627+ statuses: [status()],628+ });629+630+ expect([result.outcome, result.attempts]).toStrictEqual(["failed", 0]);631+ expect(spawned).toHaveLength(1);632+ })633+ );634+635+ it.effect(636+ "records a harness whose provider refused the model as failed, without a nudge, saying why",637+ () =>638+ Effect.gen(function* () {639+ const refusedModel = yield* recorded("opencode", "refused-model");640+641+ const { harnessRuns, result, said } = yield* agentRun({642+ contributor: tamsin,643+ harness: [{ code: 1, lines: refusedModel }, { lines: [] }],644+ statuses: [status()],645+ });646+647+ expect([648+ result.outcome,649+ result.attempts,650+ harnessRuns.length,651+ ]).toStrictEqual(["failed", 1, 1]);652+ expect(said).toContainEqual(653+ expect.stringContaining(654+ "tamsin: opencode failed: provider.invalid-request: The 'gpt-6.1-sol' model is not supported"655+ )656+ );657+ })658+ );659+660+ it.effect(661+ "runs the harness in the clone with the workspace's env and only the user's HOME from the swarm's, and keeps each attempt's output, the token blanked",662+ () =>663+ Effect.gen(function* () {664+ const start = yield* recorded("claude-code", "start");665+666+ // A tool's output that printed the token, before the run's result.667+ const leaky = [668+ ...start.slice(0, -1),669+ `{"type":"note","text":"${token}"}`,670+ ...start.slice(-1),671+ ];672+673+ const { files, harnessRuns } = yield* agentRun({674+ harness: [{ lines: leaky }],675+ statuses: [676+ status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),677+ ],678+ });679+680+ const [run] = harnessRuns;681+682+ expect([run?.cwd, run?.extendEnv, run?.env]).toStrictEqual([683+ wrensWorkspace.clone,684+ false,685+ { ...wrensWorkspace.env, HOME: "/home/user" },686+ ]);687+ expect(files.get(`${dir}/attempt-1.jsonl`)).toBe(688+ `${[...start.slice(0, -1), '{"type":"note","text":"<redacted>"}', ...start.slice(-1)].join("\n")}\n`689+ );690+ })691+ );692+693+ it.effect(694+ "writes Amp's settings into the workspace before Amp starts, and starts it there",695+ () =>696+ Effect.gen(function* () {697+ const start = yield* recorded("amp", "start");698+699+ const { files, harnessRuns } = yield* agentRun({700+ contributor: ivo,701+ harness: [{ lines: start }],702+ statuses: [703+ status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),704+ ],705+ });706+707+ expect(harnessRuns[0]?.args).toContain(`${dir}/amp-settings.json`);708+ expect(709+ JSON.parse(files.get(`${dir}/amp-settings.json`) ?? "{}")710+ ).toStrictEqual({ "amp.dangerouslyAllowAll": true });711+ })712+ );713+});714+715+/** A workspace for the golden argv: `/work/.swarm/r1/<handle>`. */716+const goldenWorkspace = (handle: string): AgentWorkspace => ({717+ clone: `/work/.swarm/r1/${handle}/clone`,718+ dir: `/work/.swarm/r1/${handle}`,719+ env: {},720+ redacted: [],721+});722+723+describe("the harness drivers", () => {724+ it.effect(725+ "start and resume each harness with the flags its --help lists",726+ () =>727+ Effect.gen(function* () {728+ const root = yield* repoRoot;729+ const adapter = `${root}/apps/cli/src/pi.ts`;730+731+ const argv = roster.map(732+ ({ adapter: withAdapter, handle, harness, model }) => {733+ const workspace = goldenWorkspace(handle);734+ const driver = drivers[harness];735+736+ return {737+ resume: driver.resume({738+ adapter: withAdapter,739+ model,740+ prompt: "Fix it.",741+ session: "S-1",742+ workspace,743+ }),744+ start: driver.start({745+ adapter: withAdapter,746+ brief: "Answer it.",747+ model,748+ sessionDir: `${workspace.dir}/sessions`,749+ sessionKey: handle,750+ workspace,751+ }),752+ };753+ }754+ );755+756+ expect(argv).toStrictEqual([757+ {758+ resume: [759+ "claude",760+ "-p",761+ "--output-format",762+ "stream-json",763+ "--verbose",764+ "--permission-mode",765+ "bypassPermissions",766+ "--model",767+ "claude-opus-5-5",768+ "--resume",769+ "S-1",770+ "Fix it.",771+ ],772+ start: [773+ "claude",774+ "-p",775+ "--output-format",776+ "stream-json",777+ "--verbose",778+ "--permission-mode",779+ "bypassPermissions",780+ "--model",781+ "claude-opus-5-5",782+ "Answer it.",783+ ],784+ },785+ {786+ resume: [787+ "opencode",788+ "run",789+ "--standalone",790+ "--format",791+ "json",792+ "--auto",793+ "-m",794+ "openai/gpt-6.1-sol",795+ "-s",796+ "S-1",797+ "Fix it.",798+ ],799+ start: [800+ "opencode",801+ "run",802+ "--standalone",803+ "--format",804+ "json",805+ "--auto",806+ "-m",807+ "openai/gpt-6.1-sol",808+ "Answer it.",809+ ],810+ },811+ {812+ resume: [813+ "amp",814+ "threads",815+ "continue",816+ "S-1",817+ "-x",818+ "Fix it.",819+ "--stream-json",820+ "-m",821+ "medium",822+ "--settings-file",823+ "/work/.swarm/r1/ivo/amp-settings.json",824+ "--no-archive-after-execute",825+ ],826+ start: [827+ "amp",828+ "-x",829+ "Answer it.",830+ "--stream-json",831+ "-m",832+ "medium",833+ "--settings-file",834+ "/work/.swarm/r1/ivo/amp-settings.json",835+ "--no-archive-after-execute",836+ ],837+ },838+ ...[839+ ["marisol", "opencode-go/kimi-k3"],840+ ["dagny", "opencode-go/glm-5.3"],841+ ].map(([handle = "", model = ""]) => ({842+ resume: [843+ "pi",844+ "-p",845+ "--mode",846+ "json",847+ "--session-dir",848+ `/work/.swarm/r1/${handle}/sessions`,849+ "--session-id",850+ "S-1",851+ "--model",852+ model,853+ "Fix it.",854+ ],855+ start: [856+ "pi",857+ "-p",858+ "--mode",859+ "json",860+ "--session-dir",861+ `/work/.swarm/r1/${handle}/sessions`,862+ "--session-id",863+ handle,864+ "--model",865+ model,866+ "Answer it.",867+ ],868+ })),869+ {870+ resume: [871+ "pi",872+ "-p",873+ "--mode",874+ "json",875+ "--session-dir",876+ "/work/.swarm/r1/pell/sessions",877+ "--session-id",878+ "S-1",879+ "--model",880+ "opencode/gemini-3.8-flash",881+ "-e",882+ adapter,883+ "Fix it.",884+ ],885+ start: [886+ "pi",887+ "-p",888+ "--mode",889+ "json",890+ "--session-dir",891+ "/work/.swarm/r1/pell/sessions",892+ "--session-id",893+ "pell",894+ "--model",895+ "opencode/gemini-3.8-flash",896+ "-e",897+ adapter,898+ "Answer it.",899+ ],900+ },901+ ]);902+ }).pipe(Effect.provide(NodeServices.layer))903+ );904+905+ it("prints the same start command in the plan as each driver's start", () => {906+ expect(907+ roster.map((contributor) =>908+ startCommand({909+ brief: "Answer it.",910+ contributor,911+ dir: `/work/.swarm/r1/${contributor.handle}`,912+ })913+ )914+ ).toStrictEqual(915+ roster.map(({ adapter, handle, harness, model }) =>916+ drivers[harness].start({917+ adapter,918+ brief: "Answer it.",919+ model,920+ sessionDir: `/work/.swarm/r1/${handle}/sessions`,921+ sessionKey: handle,922+ workspace: goldenWorkspace(handle),923+ })924+ )925+ );926+ });927+928+ it.effect(929+ "reads the session id, the settling and the tokens from each harness's recorded output, the same session on resume",930+ () =>931+ Effect.gen(function* () {932+ const harnesses = ["claude-code", "opencode", "amp", "pi"] as const;933+934+ const read = yield* Effect.forEach(harnesses, (harness) =>935+ Effect.gen(function* () {936+ const driver = drivers[harness];937+ const start = heard(driver, yield* recorded(harness, "start"));938+ const resume = heard(driver, yield* recorded(harness, "resume"));939+940+ const settled = start.filter(HarnessEvent.$is("Settled"));941+942+ return {943+ harness,944+ resumedSame:945+ new Set([...sessionsIn(start), ...sessionsIn(resume)]).size ===946+ 1,947+ sessions: sessionsIn(start).length > 0,948+ settled: settled.length,949+ tokens: start.some(950+ (event) =>951+ HarnessEvent.$is("Usage")(event) &&952+ event.input > 0 &&953+ event.output > 0954+ ),955+ };956+ })957+ );958+959+ expect(960+ heard(drivers.opencode, yield* recorded("opencode", "refused-model"))961+ .filter(HarnessEvent.$is("Failed"))962+ .map(({ reason }) => reason)963+ ).toStrictEqual([964+ "provider.invalid-request: The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.",965+ ]);966+ expect(read).toStrictEqual([967+ {968+ harness: "claude-code",969+ resumedSame: true,970+ sessions: true,971+ settled: 1,972+ tokens: true,973+ },974+ // OpenCode prints no event when its run ends: the process exiting settles it.975+ {976+ harness: "opencode",977+ resumedSame: true,978+ sessions: true,979+ settled: 0,980+ tokens: true,981+ },982+ {983+ harness: "amp",984+ resumedSame: true,985+ sessions: true,986+ settled: 1,987+ tokens: true,988+ },989+ {990+ harness: "pi",991+ resumedSame: true,992+ sessions: true,993+ settled: 1,994+ tokens: true,995+ },996+ ]);997+ }).pipe(Effect.provide(NodeServices.layer))998+ );999+});added:scripts/lib/swarm/harnesses/amp.ts+51 added
1+/**2+ * Amp, headless: execute mode (`-x`) with Claude Code-compatible stream JSON,3+ * in an agent mode (`-m`, the contributor's "model"). Amp asks before it4+ * runs a command unless its settings say `amp.dangerouslyAllowAll`, so the5+ * workspace gets a settings file of its own (`--settings-file`; the6+ * workspace's `XDG_CONFIG_HOME` hides the user's). A thread that execute7+ * mode archives cannot be continued ("This thread is archived and cannot be8+ * continued", found on the first resume), so every run passes9+ * `--no-archive-after-execute`; `amp threads continue <id> -x` resumes it.10+ */11+import { streamJsonEvents } from "./claude-code.ts";12+import type { HarnessDriver } from "./event.ts";13+14+/** The workspace's Amp settings: `<dir>/amp-settings.json`. */15+export const ampSettingsFile = (dir: string) => `${dir}/amp-settings.json`;16+17+/** The flags every run shares: stream JSON, the mode, the settings, and a thread kept open. */18+const headless = (model: string, dir: string) => [19+ "--stream-json",20+ "-m",21+ model,22+ "--settings-file",23+ ampSettingsFile(dir),24+ "--no-archive-after-execute",25+];26+27+export const amp: HarnessDriver = {28+ files: ({ dir }) => [29+ {30+ content: `${JSON.stringify({ "amp.dangerouslyAllowAll": true }, null, 2)}\n`,31+ path: ampSettingsFile(dir),32+ },33+ ],34+ harness: "amp",35+ parse: streamJsonEvents("assistant"),36+ resume: ({ model, prompt, session, workspace }) => [37+ "amp",38+ "threads",39+ "continue",40+ session,41+ "-x",42+ prompt,43+ ...headless(model, workspace.dir),44+ ],45+ start: ({ brief, model, workspace }) => [46+ "amp",47+ "-x",48+ brief,49+ ...headless(model, workspace.dir),50+ ],51+};added:scripts/lib/swarm/harnesses/claude-code.ts+131 added
1+/**2+ * Claude Code, headless: `claude -p` with stream JSON, every tool allowed3+ * (`--permission-mode bypassPermissions`: no one is there to approve), and4+ * `--resume <id>` to continue the same session. The `system`/`init` line5+ * names the session; the `result` line closes the run with its usage.6+ *7+ * Amp's `--stream-json` is "Claude Code-compatible", so `streamJsonEvents`8+ * reads both.9+ */10+import { Option, Schema } from "effect";11+12+import { HarnessEvent, lineAs, Tokens } from "./event.ts";13+import type { HarnessDriver } from "./event.ts";14+15+/** The `system`/`init` line: the session's id. */16+const Init = Schema.Struct({17+ session_id: Schema.NonEmptyString,18+ subtype: Schema.Literal("init"),19+ type: Schema.Literal("system"),20+});21+22+/** A model response's usage, as Anthropic's API reports it. */23+const ApiUsage = Schema.Struct({24+ cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),25+ cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),26+ input_tokens: Tokens,27+ output_tokens: Tokens,28+});29+30+/** One assistant message, with its stop reason and usage (Amp prints usage here). */31+const Assistant = Schema.Struct({32+ message: Schema.Struct({33+ stop_reason: Schema.optionalKey(Schema.NullOr(Schema.String)),34+ usage: Schema.optionalKey(ApiUsage),35+ }),36+ type: Schema.Literal("assistant"),37+});38+39+/** The `result` line: the run is over (`subtype` says how), with its usage (Claude Code). */40+const Result = Schema.Struct({41+ /** Whether the run failed; `subtype` then says how (`error_during_execution`). */42+ is_error: Schema.optionalKey(Schema.Boolean),43+ subtype: Schema.NonEmptyString,44+ type: Schema.Literal("result"),45+ usage: Schema.optionalKey(ApiUsage),46+});47+48+const initOf = lineAs(Init);49+50+const assistantOf = lineAs(Assistant);51+52+const resultOf = lineAs(Result);53+54+/** Tokens in and out, counting cached input as input. */55+const usageOf = (56+ usage: typeof ApiUsage.Type,57+ stopReason: Option.Option<string>58+) =>59+ HarnessEvent.Usage({60+ input:61+ usage.input_tokens +62+ (usage.cache_creation_input_tokens ?? 0) +63+ (usage.cache_read_input_tokens ?? 0),64+ output: usage.output_tokens,65+ stopReason,66+ });67+68+/**69+ * What one line of Claude Code-style stream JSON says. Usage is read where70+ * the harness totals it: the `result` line (Claude Code, whose assistant71+ * lines repeat what the result sums) or each assistant message (Amp, whose72+ * result carries none).73+ */74+export const streamJsonEvents =75+ (usageFrom: "result" | "assistant") =>76+ (line: string): readonly HarnessEvent[] => {77+ const init = initOf(line);78+79+ if (Option.isSome(init)) {80+ return [HarnessEvent.SessionStarted({ id: init.value.session_id })];81+ }82+83+ const assistant = assistantOf(line);84+85+ if (Option.isSome(assistant)) {86+ const { stop_reason: stopReason, usage } = assistant.value.message;87+88+ return usageFrom === "assistant" && usage !== undefined89+ ? [usageOf(usage, Option.fromNullishOr(stopReason))]90+ : [];91+ }92+93+ return Option.match(resultOf(line), {94+ onNone: () => [],95+ onSome: ({ is_error: isError, subtype, usage }) => [96+ ...(usageFrom === "result" && usage !== undefined97+ ? [usageOf(usage, Option.none())]98+ : []),99+ ...(isError === true || subtype.startsWith("error")100+ ? [HarnessEvent.Failed({ reason: subtype })]101+ : []),102+ HarnessEvent.Settled({ stopReason: Option.some(subtype) }),103+ ],104+ });105+ };106+107+/** The flags every run shares: print mode, stream JSON, no one to ask, the model. */108+const headless = (model: string) => [109+ "-p",110+ "--output-format",111+ "stream-json",112+ "--verbose",113+ "--permission-mode",114+ "bypassPermissions",115+ "--model",116+ model,117+];118+119+export const claudeCode: HarnessDriver = {120+ files: () => [],121+ harness: "claude-code",122+ parse: streamJsonEvents("result"),123+ resume: ({ model, prompt, session }) => [124+ "claude",125+ ...headless(model),126+ "--resume",127+ session,128+ prompt,129+ ],130+ start: ({ brief, model }) => ["claude", ...headless(model), brief],131+};added:scripts/lib/swarm/harnesses/event.ts+96 added
1+/**2+ * What every harness driver shares: the events a harness's output carries,3+ * the driver's shape, and the helpers that read one JSON line. The drivers4+ * (`claude-code.ts`, `opencode.ts`, `amp.ts`, `pi.ts`) import it, and5+ * `index.ts` gathers them, so no module imports the one that imports it.6+ */7+import type { Option } from "effect";8+import { Data, Schema } from "effect";9+10+import type { Harness } from "../results.ts";11+import type { AgentWorkspace } from "../workspace.ts";12+13+/** What one line of a harness's output tells the swarm. */14+export type HarnessEvent = Data.TaggedEnum<{15+ /** The session the harness runs: the id a resume names. */16+ SessionStarted: { readonly id: string };17+ /**18+ * Tokens one model response used (pi, OpenCode and Amp report each19+ * response; Claude Code the whole run), counting cached input as input,20+ * and why the response stopped when the harness says.21+ */22+ Usage: {23+ readonly input: number;24+ readonly output: number;25+ readonly stopReason: Option.Option<string>;26+ };27+ /**28+ * The session will do nothing more on its own (pi's `agent_settled`, the29+ * `result` line of Claude Code and Amp, OpenCode's `error`), with why it30+ * stopped when the line says.31+ */32+ Settled: { readonly stopReason: Option.Option<string> };33+ /**34+ * The run failed on the harness's side: a provider error or an abort, a35+ * model the provider refused. A model response after it (`Usage`) means36+ * the harness recovered (pi retries on its own).37+ */38+ Failed: { readonly reason: string };39+}>;40+41+export const HarnessEvent = Data.taggedEnum<HarnessEvent>();42+43+/** A file a harness reads, written into the workspace before its first start. */44+export interface WorkspaceFile {45+ readonly path: string;46+ readonly content: string;47+}48+49+/** How a harness is started on a contributor's brief. */50+export interface StartInput {51+ readonly workspace: AgentWorkspace;52+ readonly brief: string;53+ readonly model: string;54+ /** Load the CLI's pi adapter (pi only). */55+ readonly adapter: boolean;56+ /** Where a harness that takes one keeps its sessions (pi). */57+ readonly sessionDir: string;58+ /** The session id a harness that takes one opens or creates (pi). */59+ readonly sessionKey: string;60+}61+62+/** How a harness's session is resumed with a new prompt. */63+export interface ResumeInput {64+ /** The id the session's first run gave (`SessionStarted`). */65+ readonly session: string;66+ readonly prompt: string;67+ readonly model: string;68+ readonly workspace: AgentWorkspace;69+ /** Load the CLI's pi adapter again (pi only): a resume is a new process. */70+ readonly adapter: boolean;71+}72+73+/** One harness, driven headless. Every function is pure. */74+export interface HarnessDriver {75+ readonly harness: Harness;76+ /** The argv that starts the harness on the brief, in the workspace's clone. */77+ readonly start: (input: StartInput) => readonly string[];78+ /** The argv that resumes the session with `prompt`. */79+ readonly resume: (input: ResumeInput) => readonly string[];80+ /** What one stdout line says; most lines say nothing the swarm reads. */81+ readonly parse: (line: string) => readonly HarnessEvent[];82+ /** Files the harness needs in the workspace before it starts (Amp's settings). */83+ readonly files: (workspace: AgentWorkspace) => readonly WorkspaceFile[];84+}85+86+/** Where a contributor's harness keeps its sessions: `<dir>/sessions`. */87+export const sessionDirOf = (dir: string) => `${dir}/sessions`;88+89+/** One stdout line decoded as `schema`, or nothing when it is not that. */90+export const lineAs =91+ <A, I>(schema: Schema.Codec<A, I>) =>92+ (line: string): Option.Option<A> =>93+ Schema.decodeOption(Schema.fromJsonString(schema))(line);94+95+/** A token count as a harness prints it: a whole number, never negative. */96+export const Tokens = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));added:scripts/lib/swarm/harnesses/index.ts+37 added
1+/**2+ * The four harnesses a swarm contributor runs, each driven headless: how to3+ * start one on a brief, how to resume its session with a new prompt, and4+ * what one line of its JSON output says. A harness's output gives only its5+ * session's id, that the session settled, and the tokens it used; where the6+ * answer stands comes from `<cli> status` (`../outcome.ts`), never from7+ * what a harness printed.8+ *9+ * Every flag here was read from the installed harness's `--help` on10+ * 2026-10-08 (Claude Code 2.1.293, OpenCode 2.0.7, Amp 0.0.1789750518, pi11+ * 1.1.0), and each start and resume was run once headless against a12+ * scratch clone; `packages/config/test/fixtures/swarm/harness-output/` holds13+ * what they printed.14+ */15+import type { Harness } from "../results.ts";16+import { amp } from "./amp.ts";17+import { claudeCode } from "./claude-code.ts";18+import type { HarnessDriver } from "./event.ts";19+import { opencode } from "./opencode.ts";20+import { pi } from "./pi.ts";21+22+export { HarnessEvent, lineAs, sessionDirOf, Tokens } from "./event.ts";23+24+export type {25+ HarnessDriver,26+ ResumeInput,27+ StartInput,28+ WorkspaceFile,29+} from "./event.ts";30+31+/** Each harness's driver. */32+export const drivers = {33+ amp,34+ "claude-code": claudeCode,35+ opencode,36+ pi,37+} as const satisfies Readonly<Record<Harness, HarnessDriver>>;added:scripts/lib/swarm/harnesses/opencode.ts+111 added
1+/**2+ * OpenCode, headless: `opencode run` with JSON events, permissions approved3+ * (`--auto`), and `-s <id>` to continue a session. `--standalone` runs a4+ * private server in the contributor's env instead of the user's background5+ * service, so the agent's tools see the workspace's env and nobody else's.6+ *7+ * Every event names its session (`sessionID`); a `step_start` opens each8+ * step, and a `step_finish` closes it with its tokens. The run's last step9+ * prints no `step_finish` before the process exits (seen on 2.0.7), so the10+ * run settles when the process exits; an `error` event settles it at once.11+ */12+import { Option, Schema } from "effect";13+14+import { HarnessEvent, lineAs, Tokens } from "./event.ts";15+import type { HarnessDriver } from "./event.ts";16+17+/** A step's first event: names the session. */18+const StepStart = Schema.Struct({19+ sessionID: Schema.NonEmptyString,20+ type: Schema.Literal("step_start"),21+});22+23+/** A step's last event: why it stopped, and its tokens. */24+const StepFinish = Schema.Struct({25+ part: Schema.Struct({26+ reason: Schema.optionalKey(Schema.String),27+ tokens: Schema.Struct({28+ cache: Schema.optionalKey(Schema.Struct({ read: Tokens, write: Tokens })),29+ input: Tokens,30+ output: Tokens,31+ reasoning: Schema.optionalKey(Tokens),32+ }),33+ }),34+ type: Schema.Literal("step_finish"),35+});36+37+/** The run failed: the provider refused the model, say. */38+const ErrorEvent = Schema.Struct({39+ error: Schema.Struct({40+ message: Schema.optionalKey(Schema.String),41+ type: Schema.String,42+ }),43+ type: Schema.Literal("error"),44+});45+46+const stepStartOf = lineAs(StepStart);47+48+const stepFinishOf = lineAs(StepFinish);49+50+const errorOf = lineAs(ErrorEvent);51+52+const parse = (line: string): readonly HarnessEvent[] => {53+ const start = stepStartOf(line);54+55+ if (Option.isSome(start)) {56+ return [HarnessEvent.SessionStarted({ id: start.value.sessionID })];57+ }58+59+ const finish = stepFinishOf(line);60+61+ if (Option.isSome(finish)) {62+ const { reason, tokens } = finish.value.part;63+64+ return [65+ HarnessEvent.Usage({66+ input:67+ tokens.input + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0),68+ output: tokens.output + (tokens.reasoning ?? 0),69+ stopReason: Option.fromUndefinedOr(reason),70+ }),71+ ];72+ }73+74+ return Option.match(errorOf(line), {75+ onNone: () => [],76+ onSome: ({ error }) => [77+ HarnessEvent.Failed({78+ reason:79+ error.message === undefined80+ ? error.type81+ : `${error.type}: ${error.message}`,82+ }),83+ HarnessEvent.Settled({ stopReason: Option.some(error.type) }),84+ ],85+ });86+};87+88+/** The flags every run shares: a private server, JSON events, approvals, the model. */89+const headless = (model: string) => [90+ "run",91+ "--standalone",92+ "--format",93+ "json",94+ "--auto",95+ "-m",96+ model,97+];98+99+export const opencode: HarnessDriver = {100+ files: () => [],101+ harness: "opencode",102+ parse,103+ resume: ({ model, prompt, session }) => [104+ "opencode",105+ ...headless(model),106+ "-s",107+ session,108+ prompt,109+ ],110+ start: ({ brief, model }) => ["opencode", ...headless(model), brief],111+};added:scripts/lib/swarm/harnesses/pi.ts+134 added
1+/**2+ * pi, headless: print mode with JSON events (`-p --mode json`), sessions3+ * kept in the workspace (`--session-dir`) under an id the swarm picks4+ * (`--session-id`, which opens the session or creates it), so a resume is5+ * the same command with a new prompt. pi asks no approvals, so it needs no6+ * permission flag. The adapter's contributor loads the CLI's pi adapter7+ * (issue 706) with `-e`, on the start and on every resume.8+ *9+ * The header line names the session; `agent_settled` says pi will not10+ * continue on its own. JSON mode exits 0 when the provider fails, so the11+ * stop reason comes from each assistant `message_end` (`stopReason`), never12+ * from the exit code (PI §7).13+ */14+import { Option, Schema } from "effect";15+16+import { HarnessEvent, lineAs, sessionDirOf, Tokens } from "./event.ts";17+import type { HarnessDriver } from "./event.ts";18+19+/** The CLI's pi adapter in this repo (issue 706), loaded with `-e`. */20+export const piAdapter = decodeURIComponent(21+ new URL("../../../../apps/cli/src/pi.ts", import.meta.url).pathname22+);23+24+/** The session header, JSON mode's first line. */25+const Header = Schema.Struct({26+ id: Schema.NonEmptyString,27+ type: Schema.Literal("session"),28+});29+30+/** An assistant message, finished: why it stopped, and its usage. */31+const MessageEnd = Schema.Struct({32+ message: Schema.Struct({33+ /** Set when the response failed (`stopReason` `error` or `aborted`). */34+ errorMessage: Schema.optionalKey(Schema.String),35+ role: Schema.Literal("assistant"),36+ stopReason: Schema.optionalKey(Schema.String),37+ usage: Schema.optionalKey(38+ Schema.Struct({39+ cacheRead: Schema.optionalKey(Tokens),40+ cacheWrite: Schema.optionalKey(Tokens),41+ input: Tokens,42+ output: Tokens,43+ })44+ ),45+ }),46+ type: Schema.Literal("message_end"),47+});48+49+const Settled = Schema.Struct({ type: Schema.Literal("agent_settled") });50+51+const headerOf = lineAs(Header);52+53+const messageEndOf = lineAs(MessageEnd);54+55+const settledOf = lineAs(Settled);56+57+const parse = (line: string): readonly HarnessEvent[] => {58+ const header = headerOf(line);59+60+ if (Option.isSome(header)) {61+ return [HarnessEvent.SessionStarted({ id: header.value.id })];62+ }63+64+ const end = messageEndOf(line);65+66+ if (Option.isSome(end)) {67+ const { errorMessage, stopReason, usage } = end.value.message;68+69+ return [70+ HarnessEvent.Usage({71+ input:72+ (usage?.input ?? 0) +73+ (usage?.cacheRead ?? 0) +74+ (usage?.cacheWrite ?? 0),75+ output: usage?.output ?? 0,76+ stopReason: Option.fromUndefinedOr(stopReason),77+ }),78+ ...(stopReason === "error" || stopReason === "aborted"79+ ? [80+ HarnessEvent.Failed({81+ reason:82+ errorMessage === undefined83+ ? stopReason84+ : `${stopReason}: ${errorMessage}`,85+ }),86+ ]87+ : []),88+ ];89+ }90+91+ return Option.isSome(settledOf(line))92+ ? [HarnessEvent.Settled({ stopReason: Option.none() })]93+ : [];94+};95+96+/** The flags every run shares: print mode, JSON events, the session, the model, the adapter. */97+const headless = (input: {98+ readonly sessionDir: string;99+ readonly session: string;100+ readonly model: string;101+ readonly adapter: boolean;102+}) => [103+ "-p",104+ "--mode",105+ "json",106+ "--session-dir",107+ input.sessionDir,108+ "--session-id",109+ input.session,110+ "--model",111+ input.model,112+ ...(input.adapter ? ["-e", piAdapter] : []),113+];114+115+export const pi: HarnessDriver = {116+ files: () => [],117+ harness: "pi",118+ parse,119+ resume: ({ adapter, model, prompt, session, workspace }) => [120+ "pi",121+ ...headless({122+ adapter,123+ model,124+ session,125+ sessionDir: sessionDirOf(workspace.dir),126+ }),127+ prompt,128+ ],129+ start: ({ adapter, brief, model, sessionDir, sessionKey }) => [130+ "pi",131+ ...headless({ adapter, model, session: sessionKey, sessionDir }),132+ brief,133+ ],134+};modified:scripts/lib/swarm/loop.ts+619 added-83 removed
1 /**2- * The seam to issue 711, which replaces this file: each contributor's3- * harness started headless in their workspace, and the verdict loop that4- * resumes the same session on a refusal. Until 711, `runAgent` starts5- * nothing and records the run as `failed`, so the swarm runs end to end.2+ * The verdict loop: one contributor's harness, started headless on the brief3+ * in their workspace, and every refusal their answer meets sent back into4+ * the same session, at most `maxContinuations` times.5+ *6+ * Each attempt runs the harness until its session settles (or the process7+ * ends), its output kept in `<run>/<handle>/attempt-<n>.jsonl` with the8+ * token blanked. Then `<cli> status` says where the answer stands9+ * (`outcome.ts`), never the harness's output:10+ *11+ * - `Landed`: the contributor is done;12+ * - `AwaitingFinish`, `AwaitingDecision`, `WaitingOnParent`: waiting on a13+ * person or another ask, recorded as `waiting` (the swarm decides nothing);14+ * - `Refused`: the refusals, rendered by protocol's `explain`, go back into15+ * the same session with the first one's `next`, unless one of them ends16+ * the claim (`endsClaim`) or the continuations ran out;17+ * - no new answer: one nudge to push, then `noAnswer` (or `refused`, when an18+ * earlier answer was refused and nothing new came).19+ *20+ * The run's timeout bounds everything: a harness that never settles, or an21+ * answer checked past it, ends the run as `timedOut`, and the harness's22+ * process group is killed.23 */7-import { Console, Effect, Match } from "effect";8-import type { FileSystem } from "effect";9-import type { ChildProcessSpawner } from "effect/process";24+import { Brand } from "@repo/brand";25+import type { AnswerView } from "@repo/protocol/domain/answer";26+import { Outcome } from "@repo/protocol/domain/outcome";27+import type { ProjectName } from "@repo/protocol/ids";28+import type { Refusal } from "@repo/protocol/refusal";29+import { explain } from "@repo/protocol/render";30+import {31+ Array,32+ Clock,33+ Config,34+ Console,35+ Data,36+ Duration,37+ Effect,38+ FileSystem,39+ Fiber,40+ Option,41+ Ref,42+ Stream,43+} from "effect";44+import { ChildProcess, ChildProcessSpawner } from "effect/process";45 46+import { drivers, HarnessEvent, sessionDirOf } from "./harnesses/index.ts";47+import type { HarnessDriver } from "./harnesses/index.ts";48+import { awaitSettledOutcome } from "./outcome.ts";49+import type { AskStatus } from "./outcome.ts";50+import { endsClaim } from "./plan.ts";51 import type { Assignment } from "./plan.ts";12-import type { AgentRun } from "./results.ts";52+import type { AgentOutcome, AgentRun } from "./results.ts";53 import type { Contributor } from "./roster.ts";54+import { scrubbed, SwarmFailed } from "./workspace.ts";55 import type { AgentWorkspace } from "./workspace.ts";56 57 /** One contributor's run: their harness on the brief, then the verdict loop. */58 export type RunAgent = (input: {1 unmodified line60 readonly workspace: AgentWorkspace;61 readonly brief: string;62 readonly maxContinuations: 3;63 readonly timeoutMs: number;64+ /**65+ * The ask's project, so `status` reads only it. Without one, `status`66+ * lists every project's claims and answers and the ask is found by name.67+ */68+ readonly project?: ProjectName;69 }) => Effect.Effect<70 AgentRun,71 never,72 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem73 >;74 29-/** Not built (711): says so, starts nothing, and records the run as `failed`. */30-export const runAgent: RunAgent = ({ assignment }) =>31- Effect.gen(function* () {32- const { adapter, handle, harness, model } = assignment.contributor;33-34- yield* Console.error(`${handle}: not built: 711`);35-36- return {37- adapter,38- ask: assignment.ask,39- attempts: 0,40- durationMs: 0,41- handle,42- harness,43- model,44- outcome: "failed",45- refusals: {},46- };47- });48-49-/** The CLI's pi adapter (issue 706), which the adapter's agent loads with `-e`. */50-const piAdapter = decodeURIComponent(51- new URL("../../../apps/cli/src/pi.ts", import.meta.url).pathname52-);53-75 /**76 * The argv that starts `contributor`'s harness headless on `brief`, in their56- * workspace `dir` (the plan prints it; nothing runs it until 711). These are57- * the headless invocations each harness's `--help` lists on this machine;58- * 711 replaces this with its drivers' `start`, which also allow every tool59- * where a harness needs a setting for it (Amp).77+ * workspace `dir`: the plan prints it, and `runAgent` runs the same one.78 */79 export const startCommand = (input: {80 readonly contributor: Contributor;81 readonly brief: string;82 readonly dir: string;83 }): readonly string[] => {84 const { adapter, handle, harness, model } = input.contributor;85 68- return Match.value(harness).pipe(69- Match.when("claude-code", () => [70- "claude",71- "-p",72- "--output-format",73- "stream-json",74- "--verbose",75- "--permission-mode",76- "bypassPermissions",77- "--model",78- model,79- input.brief,80- ]),81- Match.when("opencode", () => [82- "opencode",83- "run",84- "--format",85- "json",86- "--auto",87- "-m",88- model,89- input.brief,90- ]),91- Match.when("amp", () => [92- "amp",93- "-x",94- input.brief,95- "--stream-json",96- "-m",97- model,98- ]),99- Match.when("pi", () => [100- "pi",101- "-p",102- "--mode",103- "json",104- "--session-dir",105- `${input.dir}/sessions`,106- "--session-id",107- handle,108- "--model",109- model,110- ...(adapter ? ["-e", piAdapter] : []),111- input.brief,112- ]),113- Match.exhaustive86+ return drivers[harness].start({87+ adapter,88+ brief: input.brief,89+ model,90+ sessionDir: sessionDirOf(input.dir),91+ sessionKey: handle,92+ workspace: {93+ clone: `${input.dir}/clone`,94+ dir: input.dir,95+ env: {},96+ redacted: [],97+ },98+ });99+};100+101+/**102+ * What a harness keeps of the swarm's own env: where the user's harness103+ * sign-ins and caches live, the terminal and locale, and the network's104+ * proxy and certificates. Nothing secret: the run's `SESSION_TOKENS`, cloud105+ * tokens and any parent harness's session never reach a contributor's106+ * harness, whose only credential is the person's token in the workspace's107+ * env (PI §7: a harness runs with the user's OS permissions).108+ */109+const KEPT_FROM_SWARM = [110+ "HOME",111+ "USER",112+ "LOGNAME",113+ "SHELL",114+ "TERM",115+ "COLORTERM",116+ "LANG",117+ "LANGUAGE",118+ "LC_ALL",119+ "LC_CTYPE",120+ "TZ",121+ "TMPDIR",122+ "XDG_CACHE_HOME",123+ "XDG_DATA_HOME",124+ "XDG_RUNTIME_DIR",125+ "XDG_STATE_HOME",126+ "HTTP_PROXY",127+ "HTTPS_PROXY",128+ "NO_PROXY",129+ "http_proxy",130+ "https_proxy",131+ "no_proxy",132+ "SSL_CERT_DIR",133+ "SSL_CERT_FILE",134+ "NODE_EXTRA_CA_CERTS",135+] as const;136+137+/** The env a contributor's harness runs in: `KEPT_FROM_SWARM`, then the workspace's. */138+const harnessEnv = (workspace: AgentWorkspace) =>139+ Effect.gen(function* () {140+ const kept = yield* Effect.forEach(KEPT_FROM_SWARM, (name) =>141+ Config.option(Config.String(name)).pipe(142+ Effect.map(Option.map((value) => [name, value] as const)),143+ Effect.orElseSucceed(() => Option.none())144+ )145+ );146+147+ return {148+ ...Object.fromEntries(Array.getSomes(kept)),149+ ...workspace.env,150+ };151+ });152+153+/** What one attempt's output said, and how its process ended. */154+interface Heard {155+ readonly session: Option.Option<string>;156+ readonly settled: boolean;157+ readonly stopReason: Option.Option<string>;158+ /** Why the run failed on the harness's side, unless a response came after. */159+ readonly failure: Option.Option<string>;160+ readonly input: number;161+ readonly output: number;162+}163+164+const nothingHeard: Heard = {165+ failure: Option.none(),166+ input: 0,167+ output: 0,168+ session: Option.none(),169+ settled: false,170+ stopReason: Option.none(),171+};172+173+const hear = (heard: Heard, event: HarnessEvent): Heard =>174+ HarnessEvent.$match(event, {175+ Failed: ({ reason }) => ({ ...heard, failure: Option.some(reason) }),176+ SessionStarted: ({ id }) => ({ ...heard, session: Option.some(id) }),177+ Settled: ({ stopReason }) => ({178+ ...heard,179+ settled: true,180+ stopReason: Option.orElse(stopReason, () => heard.stopReason),181+ }),182+ Usage: ({ input, output, stopReason }) => ({183+ ...heard,184+ failure: Option.none(),185+ input: heard.input + input,186+ output: heard.output + output,187+ stopReason: Option.orElse(stopReason, () => heard.stopReason),188+ }),189+ });190+191+/** How long a settled harness gets to exit on its own before it is killed. */192+const EXIT_GRACE = Duration.seconds(10);193+194+/** How long a killed harness gets before `SIGKILL`. */195+const KILL_GRACE = Duration.seconds(5);196+197+/** The last characters of a harness's stderr kept, to say why it failed. */198+const STDERR_TAIL = 2000;199+200+/**201+ * One harness process: `argv` in the clone with `env`. Every stdout line202+ * goes to `file`, scrubbed of the token, and is read for events until the203+ * session settles or the output ends. A settled harness gets `EXIT_GRACE`204+ * to exit; then it is killed with its process group.205+ */206+const attempt = (input: {207+ readonly argv: readonly string[];208+ readonly driver: HarnessDriver;209+ readonly env: Readonly<Record<string, string>>;210+ readonly file: string;211+ readonly workspace: AgentWorkspace;212+ /** Runs when the output first names the session: the attempt counts from then. */213+ readonly onSession: Effect.Effect<void>;214+}) =>215+ Effect.scoped(216+ Effect.gen(function* () {217+ const fs = yield* FileSystem.FileSystem;218+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;219+ const [command = "", ...args] = input.argv;220+ const scrub = (text: string) => scrubbed(text, input.workspace);221+222+ yield* fs.writeFileString(input.file, "");223+224+ const child = yield* spawner.spawn(225+ ChildProcess.make(command, args, {226+ cwd: input.workspace.clone,227+ env: { ...input.env },228+ extendEnv: false,229+ forceKillAfter: KILL_GRACE,230+ stdin: "ignore",231+ })232+ );233+234+ const stderr = yield* child.stderr.pipe(235+ Stream.decodeText(),236+ Stream.runFold(237+ () => "",238+ (tail, text) => `${tail}${text}`.slice(-STDERR_TAIL)239+ ),240+ Effect.forkScoped241+ );242+243+ const heard = yield* child.stdout.pipe(244+ Stream.decodeText(),245+ Stream.splitLines,246+ Stream.tap((line) =>247+ fs.writeFileString(input.file, `${scrub(line)}\n`, { flag: "a" })248+ ),249+ Stream.flatMap((line) => Stream.fromIterable(input.driver.parse(line))),250+ Stream.tap((event) =>251+ HarnessEvent.$is("SessionStarted")(event)252+ ? input.onSession253+ : Effect.void254+ ),255+ Stream.takeUntil(HarnessEvent.$is("Settled")),256+ Stream.runFold(() => nothingHeard, hear)257+ );258+259+ const code = yield* child.exitCode.pipe(260+ Effect.timeoutOption(EXIT_GRACE),261+ Effect.map(Option.map(Number))262+ );263+264+ // A harness still running after its grace keeps its stderr open:265+ // its tail is then not waited for.266+ const tail = yield* Fiber.join(stderr).pipe(267+ Effect.timeoutOption(Duration.seconds(1)),268+ Effect.map(Option.getOrElse(() => ""))269+ );270+271+ return { code, heard, stderr: scrub(tail).trim() };272+ })273+ ).pipe(274+ Effect.mapError(275+ ({ message }) =>276+ new SwarmFailed({277+ reason: `${input.argv[0] ?? "the harness"} didn't run: ${message}`,278+ })279+ )280 );281+282+/** What the loop does once an attempt's answer is known. */283+export type Next = Data.TaggedEnum<{284+ /** Resume the session with this prompt. */285+ Resume: { readonly prompt: string; readonly nudge: boolean };286+ /** The run ends with this outcome. */287+ Done: {288+ readonly outcome: AgentOutcome;289+ readonly landed: Option.Option<string>;290+ };291+}>;292+293+export const Next = Data.taggedEnum<Next>();294+295+/** Where the loop stands between attempts. */296+export interface Progress {297+ readonly attempts: number;298+ readonly continuations: number;299+ readonly nudged: boolean;300+ /** The requests of answers already acted on: status shows them until a new one comes. */301+ readonly judged: readonly string[];302+ readonly refusals: Readonly<Record<string, number>>;303+ readonly landed: Option.Option<string>;304+}305+306+const started: Progress = {307+ attempts: 0,308+ continuations: 0,309+ judged: [],310+ landed: Option.none(),311+ nudged: false,312+ refusals: {},313 };314+315+/** What the loop does next, and where it then stands. */316+export interface Step {317+ readonly next: Next;318+ readonly progress: Progress;319+}320+321+/** `prior` with each refusal's tag counted once more. */322+const tally = (323+ prior: Readonly<Record<string, number>>,324+ refusals: readonly Refusal[]325+) => {326+ const counts = new Map(Object.entries(prior));327+328+ for (const { _tag } of refusals) {329+ counts.set(_tag, (counts.get(_tag) ?? 0) + 1);330+ }331+332+ return Object.fromEntries(counts);333+};334+335+const short = (sha: string) => sha.slice(0, 7);336+337+/** The prompt that resumes a session after its answer was refused. */338+export const refusalPrompt = (input: {339+ readonly answer: Pick<AnswerView, "ask" | "head">;340+ readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;341+ readonly project: string;342+}) =>343+ [344+ `Your answer to ${input.answer.ask} at ${short(input.answer.head)} was refused:`,345+ "",346+ ...explain(input.refusals),347+ "",348+ `Next: ${Array.headNonEmpty(input.refusals).next}`,349+ "",350+ `Fix what the refusal names, commit, and push again; then run \`${Brand.cli} status --project ${input.project}\` for the new verdict.`,351+ ].join("\n");352+353+/** The prompt that resumes a session that pushed no answer. */354+export const nudgePrompt = (input: {355+ readonly ask: string;356+ readonly remote: string;357+ readonly project: string;358+}) =>359+ [360+ `No answer of yours to ${input.ask} has reached the platform yet.`,361+ `Commit your change and push it to ${input.remote} with \`git push\`. If git printed refusals in its \`remote:\` lines, fix what they name first, then push again.`,362+ `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,363+ ].join("\n");364+365+/**366+ * What to do with what status says after an attempt: pure, over the367+ * loop's progress. An answer status showed before (its request already368+ * judged) is no new answer.369+ */370+export const afterSettle = (input: {371+ readonly status: AskStatus;372+ readonly progress: Progress;373+ readonly maxContinuations: number;374+ readonly ask: string;375+ /** The ask's project, when the run was told it; else the claim's. */376+ readonly project: Option.Option<string>;377+ /**378+ * Why the attempt's harness failed (a provider error, a nonzero exit), if379+ * it did: with no new answer, a nudge cannot help, so the run failed.380+ */381+ readonly broke: Option.Option<string>;382+}): Step => {383+ const { maxContinuations, progress } = input;384+385+ const project = Option.getOrElse(386+ Option.orElse(input.project, () =>387+ Option.map(input.status.claim, (claim) => claim.project)388+ ),389+ () => "<project>"390+ );391+392+ const canContinue = progress.continuations < maxContinuations;393+394+ const fresh = Option.filter(395+ input.status.answer,396+ ({ requestId }) => !progress.judged.includes(requestId)397+ );398+399+ const done = (outcome: AgentOutcome, at: Progress = progress) => ({400+ next: Next.Done({ landed: at.landed, outcome }),401+ progress: at,402+ });403+404+ if (Option.isNone(fresh)) {405+ if (Option.isSome(input.broke)) {406+ return done("failed");407+ }408+409+ if (!progress.nudged && canContinue) {410+ return {411+ next: Next.Resume({412+ nudge: true,413+ prompt: nudgePrompt({414+ ask: input.ask,415+ project,416+ remote: Option.match(input.status.claim, {417+ onNone: () => "origin",418+ onSome: ({ remote }) => remote,419+ }),420+ }),421+ }),422+ progress: {423+ ...progress,424+ continuations: progress.continuations + 1,425+ nudged: true,426+ },427+ };428+ }429+430+ return done(progress.judged.length === 0 ? "noAnswer" : "refused");431+ }432+433+ const answer = fresh.value;434+435+ const judged = {436+ ...progress,437+ judged: [...progress.judged, answer.requestId],438+ };439+440+ return Outcome.match(answer.outcome, {441+ AwaitingDecision: () => done("waiting", judged),442+ AwaitingFinish: () => done("waiting", judged),443+ // `awaitSettledOutcome` reads past every `Checking` until the run's444+ // timeout ends it, so an answer still checking here ran out of time.445+ Checking: () => done("timedOut", judged),446+ Landed: ({ sha }) =>447+ done("landed", { ...judged, landed: Option.some(sha) }),448+ Refused: ({ refusals }) => {449+ const counted = {450+ ...judged,451+ refusals: tally(progress.refusals, refusals),452+ };453+454+ if (refusals.some(({ _tag }) => endsClaim.has(_tag)) || !canContinue) {455+ return done("refused", counted);456+ }457+458+ return {459+ next: Next.Resume({460+ nudge: false,461+ prompt: refusalPrompt({ answer, project, refusals }),462+ }),463+ progress: { ...counted, continuations: progress.continuations + 1 },464+ };465+ },466+ WaitingOnParent: () => done("waiting", judged),467+ });468+};469+470+/** The tags of the refusals status shows for the ask's latest answer. */471+const tagsOf = ({ answer }: AskStatus) =>472+ Option.match(answer, {473+ onNone: () => "",474+ onSome: ({ outcome }) =>475+ Outcome.guards.Refused(outcome)476+ ? outcome.refusals.map(({ _tag }) => _tag).join(", ")477+ : "",478+ });479+480+/** A count of tokens, in thousands when large. */481+const tokens = (count: number) =>482+ count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;483+484+export const runAgent: RunAgent = (input) =>485+ Effect.gen(function* () {486+ const { assignment, workspace } = input;487+ const { adapter, handle, harness, model } = assignment.contributor;488+ const driver = drivers[harness];489+ const project = Option.fromUndefinedOr(input.project);490+ const begun = yield* Clock.currentTimeMillis;491+ const progress = yield* Ref.make(started);492+493+ const say = (line: string) =>494+ Console.error(scrubbed(`${handle}: ${line}`, workspace));495+496+ /**497+ * One harness session (the start, or a continuation with `argv`), then498+ * what status says; it calls itself for each continuation, until499+ * `afterSettle` says the run is done.500+ */501+ const pass = (502+ argv: readonly string[],503+ env: Readonly<Record<string, string>>504+ ): Effect.Effect<505+ AgentOutcome,506+ SwarmFailed,507+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem508+ > =>509+ Effect.gen(function* () {510+ const attempts = (yield* Ref.get(progress)).attempts + 1;511+512+ const ran = yield* attempt({513+ argv,514+ driver,515+ env,516+ file: `${workspace.dir}/attempt-${attempts}.jsonl`,517+ onSession: Ref.update(progress, (now) => ({518+ ...now,519+ attempts: Math.max(now.attempts, attempts),520+ })),521+ workspace,522+ });523+524+ const { session } = ran.heard;525+526+ const ended = Option.match(ran.code, {527+ onNone: () => "still running",528+ onSome: (code) => `exit ${code}`,529+ });530+531+ if (Option.isNone(session)) {532+ return yield* new SwarmFailed({533+ reason: `${harness} ended (${ended}) before it started a session${ran.stderr === "" ? "" : `: ${ran.stderr}`}`,534+ });535+ }536+537+ yield* say(538+ `attempt ${attempts} ${ran.heard.settled ? "settled" : "ended"} (${Option.getOrElse(ran.heard.stopReason, () => ended)}), ${tokens(ran.heard.input)} tokens in, ${tokens(ran.heard.output)} out`539+ );540+541+ const status = yield* awaitSettledOutcome({542+ ask: assignment.ask,543+ project,544+ workspace,545+ });546+547+ const broke = Option.orElse(ran.heard.failure, () =>548+ Option.filter(ran.code, (code) => code !== 0).pipe(549+ Option.map((code) =>550+ ran.stderr === "" ? `exit ${code}` : `exit ${code}: ${ran.stderr}`551+ )552+ )553+ );554+555+ const step = afterSettle({556+ ask: assignment.ask,557+ broke,558+ maxContinuations: input.maxContinuations,559+ progress: yield* Ref.get(progress),560+ project,561+ status,562+ });563+564+ yield* Ref.set(progress, step.progress);565+566+ if (Next.$is("Done")(step.next)) {567+ if (step.next.outcome === "failed") {568+ yield* say(569+ `${harness} failed: ${Option.getOrElse(broke, () => "no reason given")}`570+ );571+ }572+573+ return step.next.outcome;574+ }575+576+ yield* say(577+ `${step.next.nudge ? "no new answer, so a nudge" : `refused ${tagsOf(status)}, so the refusal`} goes back into the session (continuation ${step.progress.continuations} of ${input.maxContinuations})`578+ );579+580+ return yield* pass(581+ driver.resume({582+ adapter,583+ model,584+ prompt: step.next.prompt,585+ session: session.value,586+ workspace,587+ }),588+ env589+ );590+ });591+592+ const loop = Effect.gen(function* () {593+ const fs = yield* FileSystem.FileSystem;594+595+ yield* Effect.forEach(596+ driver.files(workspace),597+ ({ content, path }) => fs.writeFileString(path, content),598+ { discard: true }599+ ).pipe(600+ Effect.mapError(601+ ({ message }) =>602+ new SwarmFailed({603+ reason: `${harness}'s settings: ${message}`,604+ })605+ )606+ );607+608+ return yield* pass(609+ driver.start({610+ adapter,611+ brief: input.brief,612+ model,613+ sessionDir: sessionDirOf(workspace.dir),614+ sessionKey: handle,615+ workspace,616+ }),617+ yield* harnessEnv(workspace)618+ );619+ });620+621+ const outcome = yield* loop.pipe(622+ Effect.timeoutOption(Duration.millis(input.timeoutMs)),623+ Effect.map(Option.getOrElse((): AgentOutcome => "timedOut")),624+ Effect.catchTag(625+ "SwarmFailed",626+ ({ reason }): Effect.Effect<AgentOutcome> =>627+ Effect.as(say(reason), "failed")628+ )629+ );630+631+ const finished = yield* Clock.currentTimeMillis;632+ const at = yield* Ref.get(progress);633+634+ yield* say(`${outcome} after ${at.attempts} attempts`);635+636+ return {637+ adapter,638+ ask: assignment.ask,639+ attempts: at.attempts,640+ durationMs: finished - begun,641+ handle,642+ harness,643+ model,644+ outcome,645+ refusals: at.refusals,646+ ...Option.match(at.landed, {647+ onNone: () => ({}),648+ onSome: (landed) => ({ landed }),649+ }),650+ };651+ });added:scripts/lib/swarm/outcome.ts+162 added
1+/**2+ * Where a contributor's answer stands, as the platform says it: their3+ * `<cli> status --json`, run in their workspace as them, decoded with4+ * protocol's `Envelope`. The verdict loop (`loop.ts`) reads outcomes only5+ * here, never from what a harness printed.6+ */7+import { Brand } from "@repo/brand";8+import { AnswerView } from "@repo/protocol/domain/answer";9+import { ClaimView } from "@repo/protocol/domain/claim";10+import { Outcome } from "@repo/protocol/domain/outcome";11+import { Envelope } from "@repo/protocol/envelope";12+import type { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";13+import {14+ Array,15+ Duration,16+ Effect,17+ Option,18+ Order,19+ Schedule,20+ Schema,21+} from "effect";22+import type { ChildProcessSpawner } from "effect/process";23+24+import { run, scrubbed, SwarmFailed } from "./workspace.ts";25+import type { AgentWorkspace } from "./workspace.ts";26+27+/** What the swarm reads of `status`: the caller's claims and answers. */28+const StatusData = Schema.Struct({29+ answers: Schema.Array(AnswerView),30+ claims: Schema.Array(ClaimView),31+});32+33+const decodeStatus = Schema.decodeEffect(34+ Schema.fromJsonString(Envelope(StatusData))35+);36+37+/** One ask, as the contributor's status shows it. */38+export interface AskStatus {39+ /** Their claim on the ask, while status lists it. */40+ readonly claim: Option.Option<ClaimView>;41+ /** Their latest answer to the ask. */42+ readonly answer: Option.Option<AnswerView>;43+}44+45+/** The CLI in the workspace's `bin/`: the shim the contributor's harness runs too. */46+export const workspaceCli = (workspace: Pick<AgentWorkspace, "dir">) =>47+ `${workspace.dir}/bin/${Brand.cli}`;48+49+/** The latest of `answers`, by `at`; of two at the same instant, the one listed last. */50+const latest = (answers: readonly AnswerView[]) =>51+ Array.last(52+ Array.sort(53+ answers,54+ Order.mapInput(Order.Number, ({ at }: AnswerView) => at.epochMilliseconds)55+ )56+ );57+58+/** How one status read is asked: whose workspace, and which ask (in which project, when known). */59+export interface StatusQuery {60+ readonly workspace: AgentWorkspace;61+ /** Without one, status lists every project's claims and answers. */62+ readonly project: Option.Option<ProjectName>;63+ readonly ask: AskId;64+}65+66+/**67+ * The contributor's claim on `ask` and their latest answer to it, from68+ * `<cli> status [--project <p>] --json` run in their clone with their env.69+ * A status that refuses, or prints no envelope, fails `SwarmFailed`, its70+ * text scrubbed of the token.71+ */72+export const readStatus = (73+ query: StatusQuery74+): Effect.Effect<75+ AskStatus,76+ SwarmFailed,77+ ChildProcessSpawner.ChildProcessSpawner78+> =>79+ Effect.gen(function* () {80+ const { ask, workspace } = query;81+82+ const ran = yield* run({83+ args: [84+ "status",85+ ...Option.match(query.project, {86+ onNone: () => [],87+ onSome: (project) => ["--project", project],88+ }),89+ "--json",90+ ],91+ command: workspaceCli(workspace),92+ cwd: workspace.clone,93+ env: workspace.env,94+ });95+96+ const envelope = yield* decodeStatus(ran.stdout).pipe(97+ Effect.mapError(98+ () =>99+ new SwarmFailed({100+ reason: scrubbed(101+ `status exited ${ran.code} without its JSON: ${(ran.stderr.trim() === "" ? ran.stdout : ran.stderr).trim().slice(0, 500)}`,102+ workspace103+ ),104+ })105+ )106+ );107+108+ if (!envelope.ok) {109+ return yield* new SwarmFailed({110+ reason: `status refused: ${envelope.refusals.map(({ _tag }) => _tag).join(", ")}`,111+ });112+ }113+114+ return {115+ answer: latest(116+ envelope.data.answers.filter((answer) => answer.ask === ask)117+ ),118+ claim: Array.findLast(envelope.data.claims, (claim) => claim.ask === ask),119+ };120+ });121+122+/**123+ * The contributor's latest answer to `ask`, with its head and outcome: the124+ * outcome the verdict loop acts on.125+ */126+export const readOutcome = (127+ query: StatusQuery128+): Effect.Effect<129+ Option.Option<{ readonly head: CommitSha; readonly outcome: Outcome }>,130+ SwarmFailed,131+ ChildProcessSpawner.ChildProcessSpawner132+> =>133+ Effect.map(readStatus(query), ({ answer }) =>134+ Option.map(answer, ({ head, outcome }) => ({ head, outcome }))135+ );136+137+/** How often a run that is still being checked is asked again. */138+export const POLL_MS = 5000;139+140+/**141+ * Reads the ask's status until its latest answer is no longer `Checking`:142+ * landed, refused or waiting on someone, or no answer at all. It asks143+ * every `pollMs`, and never gives up on its own: the run's timeout144+ * (`loop.ts`) bounds it.145+ */146+export const awaitSettledOutcome = (147+ query: StatusQuery & { readonly pollMs?: number }148+): Effect.Effect<149+ AskStatus,150+ SwarmFailed,151+ ChildProcessSpawner.ChildProcessSpawner152+> => {153+ const checking = ({ answer }: AskStatus) =>154+ Option.exists(answer, ({ outcome }) => Outcome.guards.Checking(outcome));155+156+ return readStatus(query).pipe(157+ Effect.repeat({158+ schedule: Schedule.spaced(Duration.millis(query.pollMs ?? POLL_MS)),159+ while: checking,160+ })161+ );162+};