Skip to content
Myr

Merge branch 'build/711-swarm-drivers-and-verdict-loop'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 5060ac3, b46c422 · Browse files · 19 files+2555 added−85 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

19 files+2555 added−85 removed

  • tests:+1186 added−2 removed
  • other:+1369 added−83 removed

19 files+2555 added−85 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+1095 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 */13import { NodeServices } from "@effect/platform-node";14import { describe, expect, it } from "@effect/vitest";15import { AnswerView } from "@repo/protocol/domain/answer";16import { ClaimView } from "@repo/protocol/domain/claim";17import { Outcome } from "@repo/protocol/domain/outcome";18import { Envelope } from "@repo/protocol/envelope";19import {20 AskId,21 CommitSha,22 DecisionId,23 Handle,24 LandedSha,25 RepoPath,26 RequestId,27} from "@repo/protocol/ids";28import {29 ChecksFailed,30 ClaimLapsed,31 OutOfScope,32 StaleBase,33} from "@repo/protocol/refusal";34import type { Refusal } from "@repo/protocol/refusal";35import { explain } from "@repo/protocol/render";36import {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";50import type { Array } from "effect";51import { ChildProcess, ChildProcessSpawner } from "effect/process";52import { TestClock } from "effect/testing";5354import {55 drivers,56 HarnessEvent,57} from "../../../scripts/lib/swarm/harnesses/index.ts";58import type { HarnessDriver } from "../../../scripts/lib/swarm/harnesses/index.ts";59import { runAgent, startCommand } from "../../../scripts/lib/swarm/loop.ts";60import type { Assignment } from "../../../scripts/lib/swarm/plan.ts";61import type { Harness } from "../../../scripts/lib/swarm/results.ts";62import { roster } from "../../../scripts/lib/swarm/roster.ts";63import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";64import { Brand } from "../../brand/src/index.ts";65import { repoRoot } from "./root.ts";6667/** The env names the CLI reads, spelled from the brand. */68const SLUG = Brand.slug.toUpperCase();6970const token = "wren-token-0123456789abcdef0123456789abcdef";7172const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";7374const ask = AskId.make("drop-legacy-fetch-burrow-auth");7576/** A harness's recorded output: `start`, `resume`, or OpenCode's `refused-model`. */77const 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;8485 const text = yield* fs.readFileString(86 path.join(87 "test",88 "fixtures",89 "swarm",90 "harness-output",91 harness,92 `${run}.jsonl`93 )94 );9596 return text.split("\n").filter((line) => line !== "");97 }).pipe(Effect.provide(NodeServices.layer));9899/** Everything one recorded run's lines say, in order. */100const heard = (driver: HarnessDriver, lines: readonly string[]) =>101 lines.flatMap(driver.parse);102103const sessionsIn = (events: readonly HarnessEvent[]) =>104 events.flatMap((event) =>105 HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []106 );107108// The commits of four answers, and the landing of the last.109const heads = ["1", "2", "3", "4"].map((digit) =>110 CommitSha.make(digit.repeat(40))111);112113const landing = LandedSha.make(CommitSha.make("a".repeat(40)));114115/** One answer to the ask, `n` seconds after noon, with its outcome. */116const 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});123124const refused = (...refusals: Array.NonEmptyReadonlyArray<Refusal>) =>125 Outcome.cases.Refused.make({ refusals });126127const outOfScope = new OutOfScope({128 paths: [RepoPath.make("packages/billing/src/index.ts")],129});130131const staleBase = new StaleBase({132 base: CommitSha.make("b".repeat(40)),133 conflicts: [],134 main: CommitSha.make("c".repeat(40)),135});136137const checksFailed = new ChecksFailed({138 lane: "test",139 logRef: "log-0001",140 next: `${Brand.cli} evidence log-0001`,141});142143const 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});156157const StatusJson = Schema.fromJsonString(158 Envelope(159 Schema.Struct({160 answers: Schema.Array(AnswerView),161 claims: Schema.Array(ClaimView),162 handle: Handle,163 })164 )165);166167/** What `<cli> status --json` prints for wren with these answers. */168const 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 });175176/** One command the fake spawner was asked to run. */177interface 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}184185/** How a scripted harness run goes: its stdout lines and exit code, or it never ends. */186type HarnessRun =187 | { readonly lines: readonly string[]; readonly code?: number }188 | { readonly stalls: readonly string[] };189190const bytes = (text: string) => new TextEncoder().encode(text);191192/** A process handle that prints `stdout` and ends with `exitCode`. */193const 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 });210211/**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 */216const 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);224225 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 }230231 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 ]);241242 if (command.command.endsWith(`/bin/${Brand.cli}`)) {243 const [next = "", ...rest] = yield* Ref.get(statuses);244245 if (rest.length > 0) {246 yield* Ref.set(statuses, rest);247 }248249 return handleOf({250 exitCode: Effect.succeed(0),251 stdout: Stream.make(bytes(`${next}\n`)),252 });253 }254255 const [next, ...rest] = yield* Ref.get(runs);256257 yield* Ref.set(runs, rest);258259 if (next === undefined) {260 return yield* Effect.die(261 `no harness run scripted for ${command.command}`262 );263 }264265 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 );278279 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 });287288/**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 */293const 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 });304305/** wren's workspace for run `r1`. */306const dir = "/work/.swarm/r1/wren";307308const 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};320321/** The swarm's own env: the user's HOME, and secrets no harness may see. */322const 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});330331const [wren, tamsin, ivo] = roster;332333/**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 */338const 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[] = [];349350 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 };359360 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 );377378 yield* input.clock ?? Effect.void;379380 const result = yield* Fiber.join(fiber);381382 return {383 files,384 harnessRuns: yield* world.harnessRuns,385 result,386 said,387 spawned: yield* world.spawned,388 };389 });390391/** The prompt a harness run carried: its last argument. */392const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";393394describe("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));402403 const first = answer(1, refused(outOfScope));404 const second = answer(2, refused(staleBase));405 const third = answer(3, Outcome.cases.Landed.make({ sha: landing }));406407 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 });415416 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 });428429 const [, afterOutOfScope, afterStaleBase] = harnessRuns;430431 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 );445446 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");452453 const answers = [1, 2, 3, 4].map((n) =>454 answer(n, refused(checksFailed))455 );456457 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 });467468 expect([469 result.outcome,470 result.attempts,471 result.refusals,472 ]).toStrictEqual(["refused", 4, { ChecksFailed: 4 }]);473 expect(harnessRuns).toHaveLength(4);474 })475 );476477 it.effect("stops at once on a refusal that ends the claim", () =>478 Effect.gen(function* () {479 const start = yield* recorded("claude-code", "start");480481 const { harnessRuns, result } = yield* agentRun({482 harness: [{ lines: start }],483 statuses: [status(answer(1, refused(ClaimLapsed.of(ask))))],484 });485486 expect([result.outcome, result.attempts, result.refusals]).toStrictEqual([487 "refused",488 1,489 { ClaimLapsed: 1 },490 ]);491 expect(harnessRuns).toHaveLength(1);492 })493 );494495 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");500501 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 });507508 expect([509 result.outcome,510 result.attempts,511 result.durationMs,512 ]).toStrictEqual(["timedOut", 1, 600_000]);513 })514 );515516 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" });522523 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 });535536 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 );546547 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");552553 const waits = [554 Outcome.cases.AwaitingDecision.make({555 decision: DecisionId.make("dec-000001"),556 }),557 Outcome.cases.AwaitingFinish.make({}),558 ];559560 const results = yield* Effect.forEach(waits, (waiting) =>561 agentRun({562 harness: [{ lines: start }],563 statuses: [status(answer(1, waiting))],564 })565 );566567 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 );579580 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");586587 const { harnessRuns, result } = yield* agentRun({588 harness: [{ lines: start }, { lines: resume }, { lines: resume }],589 statuses: [status()],590 });591592 expect([result.outcome, result.attempts]).toStrictEqual([593 "noAnswer",594 2,595 ]);596 expect(promptOf(harnessRuns[1])).toContain(wrensClaim.remote);597 })598 );599600 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));607608 const { result } = yield* agentRun({609 harness: [{ lines: start }, { lines: resume }, { lines: resume }],610 statuses: [status(first)],611 });612613 expect([614 result.outcome,615 result.attempts,616 result.refusals,617 ]).toStrictEqual(["refused", 3, { ChecksFailed: 1 }]);618 })619 );620621 it.effect(622 "counts the refusals of every answer one session pushed, not only its last",623 () =>624 Effect.gen(function* () {625 const start = yield* recorded("claude-code", "start");626627 // The brief tells the agent to read status and push again, so one628 // session can push several answers before it settles.629 const { harnessRuns, result } = yield* agentRun({630 harness: [{ lines: start }],631 statuses: [632 status(633 answer(1, refused(outOfScope)),634 answer(2, refused(staleBase)),635 answer(3, Outcome.cases.Landed.make({ sha: landing }))636 ),637 ],638 });639640 expect([641 result.outcome,642 result.attempts,643 result.refusals,644 ]).toStrictEqual(["landed", 1, { OutOfScope: 1, StaleBase: 1 }]);645 expect(harnessRuns).toHaveLength(1);646 })647 );648649 it.effect(650 "asks status again when a read fails, rather than ending the run",651 () =>652 Effect.gen(function* () {653 const start = yield* recorded("claude-code", "start");654655 const { result, spawned } = yield* agentRun({656 clock: TestClock.adjust("5 seconds"),657 harness: [{ lines: start }],658 statuses: [659 "error: fetch failed",660 status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),661 ],662 });663664 expect([result.outcome, result.attempts]).toStrictEqual(["landed", 1]);665 expect(666 spawned.filter(({ command }) => command.endsWith(`/bin/${Brand.cli}`))667 ).toHaveLength(2);668 })669 );670671 it.effect(672 "records a pi run whose provider failed as failed, though pi exits 0",673 () =>674 Effect.gen(function* () {675 const start = yield* recorded("pi", "start");676677 const finalResponse = start.findLastIndex((line) =>678 line.startsWith('{"type":"message_end","message":{"role":"assistant"')679 );680681 // pi's last response as JSON mode prints it when the provider fails.682 const failing = start.map((line, index) =>683 index === finalResponse684 ? line.replace(685 '"stopReason":"stop"',686 '"stopReason":"error","errorMessage":"429 Too Many Requests"'687 )688 : line689 );690691 const { harnessRuns, result, said } = yield* agentRun({692 contributor: roster[3],693 harness: [{ code: 0, lines: failing }, { lines: [] }],694 statuses: [status()],695 });696697 expect(failing[finalResponse]).toContain('"stopReason":"error"');698 expect([699 result.outcome,700 result.attempts,701 harnessRuns.length,702 ]).toStrictEqual(["failed", 1, 1]);703 expect(said).toContainEqual(704 expect.stringContaining(705 "marisol: pi failed: error: 429 Too Many Requests"706 )707 );708 })709 );710711 it.effect(712 "records a harness that exits before it starts a session as failed",713 () =>714 Effect.gen(function* () {715 const { result, spawned } = yield* agentRun({716 harness: [{ code: 1, lines: [] }],717 statuses: [status()],718 });719720 expect([result.outcome, result.attempts]).toStrictEqual(["failed", 0]);721 expect(spawned).toHaveLength(1);722 })723 );724725 it.effect(726 "records a harness whose provider refused the model as failed, without a nudge, saying why",727 () =>728 Effect.gen(function* () {729 const refusedModel = yield* recorded("opencode", "refused-model");730731 const { harnessRuns, result, said } = yield* agentRun({732 contributor: tamsin,733 harness: [{ code: 1, lines: refusedModel }, { lines: [] }],734 statuses: [status()],735 });736737 expect([738 result.outcome,739 result.attempts,740 harnessRuns.length,741 ]).toStrictEqual(["failed", 1, 1]);742 expect(said).toContainEqual(743 expect.stringContaining(744 "tamsin: opencode failed: provider.invalid-request: The 'gpt-6.1-sol' model is not supported"745 )746 );747 })748 );749750 it.effect(751 "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",752 () =>753 Effect.gen(function* () {754 const start = yield* recorded("claude-code", "start");755756 // A tool's output that printed the token, before the run's result.757 const leaky = [758 ...start.slice(0, -1),759 `{"type":"note","text":"${token}"}`,760 ...start.slice(-1),761 ];762763 const { files, harnessRuns } = yield* agentRun({764 harness: [{ lines: leaky }],765 statuses: [766 status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),767 ],768 });769770 const [run] = harnessRuns;771772 expect([run?.cwd, run?.extendEnv, run?.env]).toStrictEqual([773 wrensWorkspace.clone,774 false,775 { ...wrensWorkspace.env, HOME: "/home/user" },776 ]);777 expect(files.get(`${dir}/attempt-1.jsonl`)).toBe(778 `${[...start.slice(0, -1), '{"type":"note","text":"<redacted>"}', ...start.slice(-1)].join("\n")}\n`779 );780 })781 );782783 it.effect(784 "writes Amp's settings into the workspace before Amp starts, and starts it there",785 () =>786 Effect.gen(function* () {787 const start = yield* recorded("amp", "start");788789 const { files, harnessRuns } = yield* agentRun({790 contributor: ivo,791 harness: [{ lines: start }],792 statuses: [793 status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),794 ],795 });796797 expect(harnessRuns[0]?.args).toContain(`${dir}/amp-settings.json`);798 expect(799 JSON.parse(files.get(`${dir}/amp-settings.json`) ?? "{}")800 ).toStrictEqual({ "amp.dangerouslyAllowAll": true });801 })802 );803});804805/** A workspace for the golden argv: `/work/.swarm/r1/<handle>`. */806const goldenWorkspace = (handle: string): AgentWorkspace => ({807 clone: `/work/.swarm/r1/${handle}/clone`,808 dir: `/work/.swarm/r1/${handle}`,809 env: {},810 redacted: [],811});812813describe("the harness drivers", () => {814 it.effect(815 "start and resume each harness with the flags its --help lists",816 () =>817 Effect.gen(function* () {818 const root = yield* repoRoot;819 const adapter = `${root}/apps/cli/src/pi.ts`;820821 const argv = roster.map(822 ({ adapter: withAdapter, handle, harness, model }) => {823 const workspace = goldenWorkspace(handle);824 const driver = drivers[harness];825826 return {827 resume: driver.resume({828 adapter: withAdapter,829 model,830 prompt: "Fix it.",831 session: "S-1",832 workspace,833 }),834 start: driver.start({835 adapter: withAdapter,836 brief: "Answer it.",837 model,838 sessionDir: `${workspace.dir}/sessions`,839 sessionKey: handle,840 workspace,841 }),842 };843 }844 );845846 expect(argv).toStrictEqual([847 {848 resume: [849 "claude",850 "-p",851 "--output-format",852 "stream-json",853 "--verbose",854 "--permission-mode",855 "bypassPermissions",856 "--strict-mcp-config",857 "--model",858 "claude-opus-5-5",859 "--resume",860 "S-1",861 "Fix it.",862 ],863 start: [864 "claude",865 "-p",866 "--output-format",867 "stream-json",868 "--verbose",869 "--permission-mode",870 "bypassPermissions",871 "--strict-mcp-config",872 "--model",873 "claude-opus-5-5",874 "Answer it.",875 ],876 },877 {878 resume: [879 "opencode",880 "run",881 "--standalone",882 "--format",883 "json",884 "--auto",885 "-m",886 "openai/gpt-6.1-sol",887 "-s",888 "S-1",889 "Fix it.",890 ],891 start: [892 "opencode",893 "run",894 "--standalone",895 "--format",896 "json",897 "--auto",898 "-m",899 "openai/gpt-6.1-sol",900 "Answer it.",901 ],902 },903 {904 resume: [905 "amp",906 "threads",907 "continue",908 "S-1",909 "-x",910 "Fix it.",911 "--stream-json",912 "-m",913 "medium",914 "--settings-file",915 "/work/.swarm/r1/ivo/amp-settings.json",916 "--no-archive-after-execute",917 ],918 start: [919 "amp",920 "-x",921 "Answer it.",922 "--stream-json",923 "-m",924 "medium",925 "--settings-file",926 "/work/.swarm/r1/ivo/amp-settings.json",927 "--no-archive-after-execute",928 ],929 },930 ...[931 ["marisol", "opencode-go/kimi-k3"],932 ["dagny", "opencode-go/glm-5.3"],933 ].map(([handle = "", model = ""]) => ({934 resume: [935 "pi",936 "-p",937 "--mode",938 "json",939 "--no-mcp",940 "--session-dir",941 `/work/.swarm/r1/${handle}/sessions`,942 "--session-id",943 "S-1",944 "--model",945 model,946 "Fix it.",947 ],948 start: [949 "pi",950 "-p",951 "--mode",952 "json",953 "--no-mcp",954 "--session-dir",955 `/work/.swarm/r1/${handle}/sessions`,956 "--session-id",957 handle,958 "--model",959 model,960 "Answer it.",961 ],962 })),963 {964 resume: [965 "pi",966 "-p",967 "--mode",968 "json",969 "--no-mcp",970 "--session-dir",971 "/work/.swarm/r1/pell/sessions",972 "--session-id",973 "S-1",974 "--model",975 "opencode/gemini-3.8-flash",976 "-e",977 adapter,978 "Fix it.",979 ],980 start: [981 "pi",982 "-p",983 "--mode",984 "json",985 "--no-mcp",986 "--session-dir",987 "/work/.swarm/r1/pell/sessions",988 "--session-id",989 "pell",990 "--model",991 "opencode/gemini-3.8-flash",992 "-e",993 adapter,994 "Answer it.",995 ],996 },997 ]);998 }).pipe(Effect.provide(NodeServices.layer))999 );10001001 it("prints the same start command in the plan as each driver's start", () => {1002 expect(1003 roster.map((contributor) =>1004 startCommand({1005 brief: "Answer it.",1006 contributor,1007 dir: `/work/.swarm/r1/${contributor.handle}`,1008 })1009 )1010 ).toStrictEqual(1011 roster.map(({ adapter, handle, harness, model }) =>1012 drivers[harness].start({1013 adapter,1014 brief: "Answer it.",1015 model,1016 sessionDir: `/work/.swarm/r1/${handle}/sessions`,1017 sessionKey: handle,1018 workspace: goldenWorkspace(handle),1019 })1020 )1021 );1022 });10231024 it.effect(1025 "reads the session id, the settling and the tokens from each harness's recorded output, the same session on resume",1026 () =>1027 Effect.gen(function* () {1028 const harnesses = ["claude-code", "opencode", "amp", "pi"] as const;10291030 const read = yield* Effect.forEach(harnesses, (harness) =>1031 Effect.gen(function* () {1032 const driver = drivers[harness];1033 const start = heard(driver, yield* recorded(harness, "start"));1034 const resume = heard(driver, yield* recorded(harness, "resume"));10351036 const settled = start.filter(HarnessEvent.$is("Settled"));10371038 return {1039 harness,1040 resumedSame:1041 new Set([...sessionsIn(start), ...sessionsIn(resume)]).size ===1042 1,1043 sessions: sessionsIn(start).length > 0,1044 settled: settled.length,1045 tokens: start.some(1046 (event) =>1047 HarnessEvent.$is("Usage")(event) &&1048 event.input > 0 &&1049 event.output > 01050 ),1051 };1052 })1053 );10541055 expect(1056 heard(drivers.opencode, yield* recorded("opencode", "refused-model"))1057 .filter(HarnessEvent.$is("Failed"))1058 .map(({ reason }) => reason)1059 ).toStrictEqual([1060 "provider.invalid-request: The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.",1061 ]);1062 expect(read).toStrictEqual([1063 {1064 harness: "claude-code",1065 resumedSame: true,1066 sessions: true,1067 settled: 1,1068 tokens: true,1069 },1070 // OpenCode prints no event when its run ends: the process exiting settles it.1071 {1072 harness: "opencode",1073 resumedSame: true,1074 sessions: true,1075 settled: 0,1076 tokens: true,1077 },1078 {1079 harness: "amp",1080 resumedSame: true,1081 sessions: true,1082 settled: 1,1083 tokens: true,1084 },1085 {1086 harness: "pi",1087 resumedSame: true,1088 sessions: true,1089 settled: 1,1090 tokens: true,1091 },1092 ]);1093 }).pipe(Effect.provide(NodeServices.layer))1094 );1095});
modified:packages/config/test/swarm.test.ts+2 added-2 removed
962 unmodified lines
963 ],964 ]);965 expect([rows[0], rows[5], ...printed.slice(8)]).toStrictEqual([966 expect.stringContaining(967 "/<run>/wren/clone' && claude -p --output-format stream-json --verbose --permission-mode bypassPermissions --model claude-opus-5-5 '<brief>'"967 "/<run>/wren/clone' && claude -p --output-format stream-json --verbose --permission-mode bypassPermissions --strict-mcp-config --model claude-opus-5-5 '<brief>'"968 ),969 expect.stringMatching(970 / pi -p --mode json .* -e \S+\/apps\/cli\/src\/pi\.ts '<brief>'$/u970 / pi -p --mode json --no-mcp .* -e \S+\/apps\/cli\/src\/pi\.ts '<brief>'$/u971 ),972 "held: drop-legacy-fetch, drop-legacy-fetch-delete",973 "dry run: nothing claimed, no harness started",974 ]);
328 unmodified lines
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 */11import { streamJsonEvents } from "./claude-code.ts";12import type { HarnessDriver } from "./event.ts";1314/** The workspace's Amp settings: `<dir>/amp-settings.json`. */15export const ampSettingsFile = (dir: string) => `${dir}/amp-settings.json`;1617/** The flags every run shares: stream JSON, the mode, the settings, and a thread kept open. */18const headless = (model: string, dir: string) => [19 "--stream-json",20 "-m",21 model,22 "--settings-file",23 ampSettingsFile(dir),24 "--no-archive-after-execute",25];2627export 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+135 added
1/**2 * Claude Code, headless: `claude -p` with stream JSON, every tool allowed3 * (`--permission-mode bypassPermissions`: no one is there to approve), no4 * MCP server (`--strict-mcp-config` with no `--mcp-config`: else the user's5 * own servers and claude.ai connectors load, with the user's accounts6 * behind them), and `--resume <id>` to continue the same session. The7 * `system`/`init` line names the session; the `result` line closes the run8 * with its usage.9 *10 * Amp's `--stream-json` is "Claude Code-compatible", so `streamJsonEvents`11 * reads both.12 */13import { Option, Schema } from "effect";1415import { HarnessEvent, lineAs, Tokens } from "./event.ts";16import type { HarnessDriver } from "./event.ts";1718/** The `system`/`init` line: the session's id. */19const Init = Schema.Struct({20 session_id: Schema.NonEmptyString,21 subtype: Schema.Literal("init"),22 type: Schema.Literal("system"),23});2425/** A model response's usage, as Anthropic's API reports it. */26const ApiUsage = Schema.Struct({27 cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),28 cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),29 input_tokens: Tokens,30 output_tokens: Tokens,31});3233/** One assistant message, with its stop reason and usage (Amp prints usage here). */34const Assistant = Schema.Struct({35 message: Schema.Struct({36 stop_reason: Schema.optionalKey(Schema.NullOr(Schema.String)),37 usage: Schema.optionalKey(ApiUsage),38 }),39 type: Schema.Literal("assistant"),40});4142/** The `result` line: the run is over (`subtype` says how), with its usage (Claude Code). */43const Result = Schema.Struct({44 /** Whether the run failed; `subtype` then says how (`error_during_execution`). */45 is_error: Schema.optionalKey(Schema.Boolean),46 subtype: Schema.NonEmptyString,47 type: Schema.Literal("result"),48 usage: Schema.optionalKey(ApiUsage),49});5051const initOf = lineAs(Init);5253const assistantOf = lineAs(Assistant);5455const resultOf = lineAs(Result);5657/** Tokens in and out, counting cached input as input. */58const usageOf = (59 usage: typeof ApiUsage.Type,60 stopReason: Option.Option<string>61) =>62 HarnessEvent.Usage({63 input:64 usage.input_tokens +65 (usage.cache_creation_input_tokens ?? 0) +66 (usage.cache_read_input_tokens ?? 0),67 output: usage.output_tokens,68 stopReason,69 });7071/**72 * What one line of Claude Code-style stream JSON says. Usage is read where73 * the harness totals it: the `result` line (Claude Code, whose assistant74 * lines repeat what the result sums) or each assistant message (Amp, whose75 * result carries none).76 */77export const streamJsonEvents =78 (usageFrom: "result" | "assistant") =>79 (line: string): readonly HarnessEvent[] => {80 const init = initOf(line);8182 if (Option.isSome(init)) {83 return [HarnessEvent.SessionStarted({ id: init.value.session_id })];84 }8586 const assistant = assistantOf(line);8788 if (Option.isSome(assistant)) {89 const { stop_reason: stopReason, usage } = assistant.value.message;9091 return usageFrom === "assistant" && usage !== undefined92 ? [usageOf(usage, Option.fromNullishOr(stopReason))]93 : [];94 }9596 return Option.match(resultOf(line), {97 onNone: () => [],98 onSome: ({ is_error: isError, subtype, usage }) => [99 ...(usageFrom === "result" && usage !== undefined100 ? [usageOf(usage, Option.none())]101 : []),102 ...(isError === true || subtype.startsWith("error")103 ? [HarnessEvent.Failed({ reason: subtype })]104 : []),105 HarnessEvent.Settled({ stopReason: Option.some(subtype) }),106 ],107 });108 };109110/** The flags every run shares: print mode, stream JSON, no one to ask, no MCP, the model. */111const headless = (model: string) => [112 "-p",113 "--output-format",114 "stream-json",115 "--verbose",116 "--permission-mode",117 "bypassPermissions",118 "--strict-mcp-config",119 "--model",120 model,121];122123export const claudeCode: HarnessDriver = {124 files: () => [],125 harness: "claude-code",126 parse: streamJsonEvents("result"),127 resume: ({ model, prompt, session }) => [128 "claude",129 ...headless(model),130 "--resume",131 session,132 prompt,133 ],134 start: ({ brief, model }) => ["claude", ...headless(model), brief],135};
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 */7import type { Option } from "effect";8import { Data, Schema } from "effect";910import type { Harness } from "../results.ts";11import type { AgentWorkspace } from "../workspace.ts";1213/** What one line of a harness's output tells the swarm. */14export 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}>;4041export const HarnessEvent = Data.taggedEnum<HarnessEvent>();4243/** A file a harness reads, written into the workspace before its first start. */44export interface WorkspaceFile {45 readonly path: string;46 readonly content: string;47}4849/** How a harness is started on a contributor's brief. */50export 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}6162/** How a harness's session is resumed with a new prompt. */63export 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}7273/** One harness, driven headless. Every function is pure. */74export 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}8586/** Where a contributor's harness keeps its sessions: `<dir>/sessions`. */87export const sessionDirOf = (dir: string) => `${dir}/sessions`;8889/** One stdout line decoded as `schema`, or nothing when it is not that. */90export const lineAs =91 <A, I>(schema: Schema.Codec<A, I>) =>92 (line: string): Option.Option<A> =>93 Schema.decodeOption(Schema.fromJsonString(schema))(line);9495/** A token count as a harness prints it: a whole number, never negative. */96export 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 */15import type { Harness } from "../results.ts";16import { amp } from "./amp.ts";17import { claudeCode } from "./claude-code.ts";18import type { HarnessDriver } from "./event.ts";19import { opencode } from "./opencode.ts";20import { pi } from "./pi.ts";2122export { HarnessEvent, lineAs, sessionDirOf, Tokens } from "./event.ts";2324export type {25 HarnessDriver,26 ResumeInput,27 StartInput,28 WorkspaceFile,29} from "./event.ts";3031/** Each harness's driver. */32export 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 */12import { Option, Schema } from "effect";1314import { HarnessEvent, lineAs, Tokens } from "./event.ts";15import type { HarnessDriver } from "./event.ts";1617/** A step's first event: names the session. */18const StepStart = Schema.Struct({19 sessionID: Schema.NonEmptyString,20 type: Schema.Literal("step_start"),21});2223/** A step's last event: why it stopped, and its tokens. */24const 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});3637/** The run failed: the provider refused the model, say. */38const ErrorEvent = Schema.Struct({39 error: Schema.Struct({40 message: Schema.optionalKey(Schema.String),41 type: Schema.String,42 }),43 type: Schema.Literal("error"),44});4546const stepStartOf = lineAs(StepStart);4748const stepFinishOf = lineAs(StepFinish);4950const errorOf = lineAs(ErrorEvent);5152const parse = (line: string): readonly HarnessEvent[] => {53 const start = stepStartOf(line);5455 if (Option.isSome(start)) {56 return [HarnessEvent.SessionStarted({ id: start.value.sessionID })];57 }5859 const finish = stepFinishOf(line);6061 if (Option.isSome(finish)) {62 const { reason, tokens } = finish.value.part;6364 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 }7374 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};8788/** The flags every run shares: a private server, JSON events, approvals, the model. */89const headless = (model: string) => [90 "run",91 "--standalone",92 "--format",93 "json",94 "--auto",95 "-m",96 model,97];9899export 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+137 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. `--no-mcp` keeps pi's built-in MCP off, so the user's7 * own servers (`~/.pi/agent/mcp.json`, with the user's accounts behind8 * them) never reach a contributor. The adapter's contributor loads the9 * CLI's pi adapter (issue 706) with `-e`, on the start and on every resume.10 *11 * The header line names the session; `agent_settled` says pi will not12 * continue on its own. JSON mode exits 0 when the provider fails, so the13 * stop reason comes from each assistant `message_end` (`stopReason`), never14 * from the exit code (PI §7).15 */16import { Option, Schema } from "effect";1718import { HarnessEvent, lineAs, sessionDirOf, Tokens } from "./event.ts";19import type { HarnessDriver } from "./event.ts";2021/** The CLI's pi adapter in this repo (issue 706), loaded with `-e`. */22export const piAdapter = decodeURIComponent(23 new URL("../../../../apps/cli/src/pi.ts", import.meta.url).pathname24);2526/** The session header, JSON mode's first line. */27const Header = Schema.Struct({28 id: Schema.NonEmptyString,29 type: Schema.Literal("session"),30});3132/** An assistant message, finished: why it stopped, and its usage. */33const MessageEnd = Schema.Struct({34 message: Schema.Struct({35 /** Set when the response failed (`stopReason` `error` or `aborted`). */36 errorMessage: Schema.optionalKey(Schema.String),37 role: Schema.Literal("assistant"),38 stopReason: Schema.optionalKey(Schema.String),39 usage: Schema.optionalKey(40 Schema.Struct({41 cacheRead: Schema.optionalKey(Tokens),42 cacheWrite: Schema.optionalKey(Tokens),43 input: Tokens,44 output: Tokens,45 })46 ),47 }),48 type: Schema.Literal("message_end"),49});5051const Settled = Schema.Struct({ type: Schema.Literal("agent_settled") });5253const headerOf = lineAs(Header);5455const messageEndOf = lineAs(MessageEnd);5657const settledOf = lineAs(Settled);5859const parse = (line: string): readonly HarnessEvent[] => {60 const header = headerOf(line);6162 if (Option.isSome(header)) {63 return [HarnessEvent.SessionStarted({ id: header.value.id })];64 }6566 const end = messageEndOf(line);6768 if (Option.isSome(end)) {69 const { errorMessage, stopReason, usage } = end.value.message;7071 return [72 HarnessEvent.Usage({73 input:74 (usage?.input ?? 0) +75 (usage?.cacheRead ?? 0) +76 (usage?.cacheWrite ?? 0),77 output: usage?.output ?? 0,78 stopReason: Option.fromUndefinedOr(stopReason),79 }),80 ...(stopReason === "error" || stopReason === "aborted"81 ? [82 HarnessEvent.Failed({83 reason:84 errorMessage === undefined85 ? stopReason86 : `${stopReason}: ${errorMessage}`,87 }),88 ]89 : []),90 ];91 }9293 return Option.isSome(settledOf(line))94 ? [HarnessEvent.Settled({ stopReason: Option.none() })]95 : [];96};9798/** The flags every run shares: print mode, JSON events, no MCP, the session, the model, the adapter. */99const headless = (input: {100 readonly sessionDir: string;101 readonly session: string;102 readonly model: string;103 readonly adapter: boolean;104}) => [105 "-p",106 "--mode",107 "json",108 "--no-mcp",109 "--session-dir",110 input.sessionDir,111 "--session-id",112 input.session,113 "--model",114 input.model,115 ...(input.adapter ? ["-e", piAdapter] : []),116];117118export const pi: HarnessDriver = {119 files: () => [],120 harness: "pi",121 parse,122 resume: ({ adapter, model, prompt, session, workspace }) => [123 "pi",124 ...headless({125 adapter,126 model,127 session,128 sessionDir: sessionDirOf(workspace.dir),129 }),130 prompt,131 ],132 start: ({ adapter, brief, model, sessionDir, sessionKey }) => [133 "pi",134 ...headless({ adapter, model, session: sessionKey, sessionDir }),135 brief,136 ],137};
modified:scripts/lib/swarm/loop.ts+626 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 */7import { Console, Effect, Match } from "effect";8import type { FileSystem } from "effect";9import type { ChildProcessSpawner } from "effect/process";24import { Brand } from "@repo/brand";25import type { AnswerView } from "@repo/protocol/domain/answer";26import { Outcome } from "@repo/protocol/domain/outcome";27import type { ProjectName } from "@repo/protocol/ids";28import type { Refusal } from "@repo/protocol/refusal";29import { explain } from "@repo/protocol/render";30import {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";44import { ChildProcess, ChildProcessSpawner } from "effect/process";4546import { drivers, HarnessEvent, sessionDirOf } from "./harnesses/index.ts";47import type { HarnessDriver } from "./harnesses/index.ts";48import { awaitSettledOutcome } from "./outcome.ts";49import type { AskStatus } from "./outcome.ts";50import { endsClaim } from "./plan.ts";51import type { Assignment } from "./plan.ts";12import type { AgentRun } from "./results.ts";52import type { AgentOutcome, AgentRun } from "./results.ts";53import type { Contributor } from "./roster.ts";54import { scrubbed, SwarmFailed } from "./workspace.ts";55import type { AgentWorkspace } from "./workspace.ts";5657/** One contributor's run: their harness on the brief, then the verdict loop. */58export type RunAgent = (input: {
1 unmodified line
60 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>;7429/** Not built (711): says so, starts nothing, and records the run as `failed`. */30export const runAgent: RunAgent = ({ assignment }) =>31 Effect.gen(function* () {32 const { adapter, handle, harness, model } = assignment.contributor;3334 yield* Console.error(`${handle}: not built: 711`);3536 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 });4849/** The CLI's pi adapter (issue 706), which the adapter's agent loads with `-e`. */50const piAdapter = decodeURIComponent(51 new URL("../../../apps/cli/src/pi.ts", import.meta.url).pathname52);5375/**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 */79export 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;8568 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};100101/**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 */109const 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;136137/** The env a contributor's harness runs in: `KEPT_FROM_SWARM`, then the workspace's. */138const 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 );146147 return {148 ...Object.fromEntries(Array.getSomes(kept)),149 ...workspace.env,150 };151 });152153/** What one attempt's output said, and how its process ended. */154interface 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}163164const nothingHeard: Heard = {165 failure: Option.none(),166 input: 0,167 output: 0,168 session: Option.none(),169 settled: false,170 stopReason: Option.none(),171};172173const 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 });190191/** How long a settled harness gets to exit on its own before it is killed. */192const EXIT_GRACE = Duration.seconds(10);193194/** How long a killed harness gets before `SIGKILL`. */195const KILL_GRACE = Duration.seconds(5);196197/** The last characters of a harness's stderr kept, to say why it failed. */198const STDERR_TAIL = 2000;199200/**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 */206const 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);221222 yield* fs.writeFileString(input.file, "");223224 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 );233234 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 );242243 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 );258259 const code = yield* child.exitCode.pipe(260 Effect.timeoutOption(EXIT_GRACE),261 Effect.map(Option.map(Number))262 );263264 // 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 );270271 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 );281282/** What the loop does once an attempt's answer is known. */283export 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}>;292293export const Next = Data.taggedEnum<Next>();294295/** Where the loop stands between attempts. */296export 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}305306const started: Progress = {307 attempts: 0,308 continuations: 0,309 judged: [],310 landed: Option.none(),311 nudged: false,312 refusals: {},313};314315/** What the loop does next, and where it then stands. */316export interface Step {317 readonly next: Next;318 readonly progress: Progress;319}320321/** `prior` with each refusal's tag counted once more. */322const tally = (323 prior: Readonly<Record<string, number>>,324 refusals: readonly Refusal[]325) => {326 const counts = new Map(Object.entries(prior));327328 for (const { _tag } of refusals) {329 counts.set(_tag, (counts.get(_tag) ?? 0) + 1);330 }331332 return Object.fromEntries(counts);333};334335const short = (sha: string) => sha.slice(0, 7);336337/** The prompt that resumes a session after its answer was refused. */338export 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");352353/** The prompt that resumes a session that pushed no answer. */354export 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");364365/**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. The loop acts on the latest new answer, and369 * counts the refusals of every new one: an agent that read its verdict370 * and pushed again in the same session met each of them.371 */372export const afterSettle = (input: {373 readonly status: AskStatus;374 readonly progress: Progress;375 readonly maxContinuations: number;376 readonly ask: string;377 /** The ask's project, when the run was told it; else the claim's. */378 readonly project: Option.Option<string>;379 /**380 * Why the attempt's harness failed (a provider error, a nonzero exit), if381 * it did: with no new answer, a nudge cannot help, so the run failed.382 */383 readonly broke: Option.Option<string>;384}): Step => {385 const { maxContinuations, progress } = input;386387 const project = Option.getOrElse(388 Option.orElse(input.project, () =>389 Option.map(input.status.claim, (claim) => claim.project)390 ),391 () => "<project>"392 );393394 const canContinue = progress.continuations < maxContinuations;395396 const fresh = Option.filter(397 input.status.answer,398 ({ requestId }) => !progress.judged.includes(requestId)399 );400401 const done = (outcome: AgentOutcome, at: Progress = progress) => ({402 next: Next.Done({ landed: at.landed, outcome }),403 progress: at,404 });405406 if (Option.isNone(fresh)) {407 if (Option.isSome(input.broke)) {408 return done("failed");409 }410411 if (!progress.nudged && canContinue) {412 return {413 next: Next.Resume({414 nudge: true,415 prompt: nudgePrompt({416 ask: input.ask,417 project,418 remote: Option.match(input.status.claim, {419 onNone: () => "origin",420 onSome: ({ remote }) => remote,421 }),422 }),423 }),424 progress: {425 ...progress,426 continuations: progress.continuations + 1,427 nudged: true,428 },429 };430 }431432 return done(progress.judged.length === 0 ? "noAnswer" : "refused");433 }434435 const answer = fresh.value;436437 const unjudged = input.status.answers.filter(438 ({ requestId }) => !progress.judged.includes(requestId)439 );440441 const judged = {442 ...progress,443 judged: [...progress.judged, ...unjudged.map(({ requestId }) => requestId)],444 refusals: tally(445 progress.refusals,446 unjudged.flatMap(({ outcome }) =>447 Outcome.guards.Refused(outcome) ? outcome.refusals : []448 )449 ),450 };451452 return Outcome.match(answer.outcome, {453 AwaitingDecision: () => done("waiting", judged),454 AwaitingFinish: () => done("waiting", judged),455 // `awaitSettledOutcome` reads past every `Checking` until the run's456 // timeout ends it, so an answer still checking here ran out of time.457 Checking: () => done("timedOut", judged),458 Landed: ({ sha }) =>459 done("landed", { ...judged, landed: Option.some(sha) }),460 Refused: ({ refusals }) => {461 if (refusals.some(({ _tag }) => endsClaim.has(_tag)) || !canContinue) {462 return done("refused", judged);463 }464465 return {466 next: Next.Resume({467 nudge: false,468 prompt: refusalPrompt({ answer, project, refusals }),469 }),470 progress: { ...judged, continuations: progress.continuations + 1 },471 };472 },473 WaitingOnParent: () => done("waiting", judged),474 });475};476477/** The tags of the refusals status shows for the ask's latest answer. */478const tagsOf = ({ answer }: AskStatus) =>479 Option.match(answer, {480 onNone: () => "",481 onSome: ({ outcome }) =>482 Outcome.guards.Refused(outcome)483 ? outcome.refusals.map(({ _tag }) => _tag).join(", ")484 : "",485 });486487/** A count of tokens, in thousands when large. */488const tokens = (count: number) =>489 count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;490491export const runAgent: RunAgent = (input) =>492 Effect.gen(function* () {493 const { assignment, workspace } = input;494 const { adapter, handle, harness, model } = assignment.contributor;495 const driver = drivers[harness];496 const project = Option.fromUndefinedOr(input.project);497 const begun = yield* Clock.currentTimeMillis;498 const progress = yield* Ref.make(started);499500 const say = (line: string) =>501 Console.error(scrubbed(`${handle}: ${line}`, workspace));502503 /**504 * One harness session (the start, or a continuation with `argv`), then505 * what status says; it calls itself for each continuation, until506 * `afterSettle` says the run is done.507 */508 const pass = (509 argv: readonly string[],510 env: Readonly<Record<string, string>>511 ): Effect.Effect<512 AgentOutcome,513 SwarmFailed,514 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem515 > =>516 Effect.gen(function* () {517 const attempts = (yield* Ref.get(progress)).attempts + 1;518519 const ran = yield* attempt({520 argv,521 driver,522 env,523 file: `${workspace.dir}/attempt-${attempts}.jsonl`,524 onSession: Ref.update(progress, (now) => ({525 ...now,526 attempts: Math.max(now.attempts, attempts),527 })),528 workspace,529 });530531 const { session } = ran.heard;532533 const ended = Option.match(ran.code, {534 onNone: () => "still running",535 onSome: (code) => `exit ${code}`,536 });537538 if (Option.isNone(session)) {539 return yield* new SwarmFailed({540 reason: `${harness} ended (${ended}) before it started a session${ran.stderr === "" ? "" : `: ${ran.stderr}`}`,541 });542 }543544 yield* say(545 `attempt ${attempts} ${ran.heard.settled ? "settled" : "ended"} (${Option.getOrElse(ran.heard.stopReason, () => ended)}), ${tokens(ran.heard.input)} tokens in, ${tokens(ran.heard.output)} out`546 );547548 const status = yield* awaitSettledOutcome({549 ask: assignment.ask,550 project,551 workspace,552 });553554 const broke = Option.orElse(ran.heard.failure, () =>555 Option.filter(ran.code, (code) => code !== 0).pipe(556 Option.map((code) =>557 ran.stderr === "" ? `exit ${code}` : `exit ${code}: ${ran.stderr}`558 )559 )560 );561562 const step = afterSettle({563 ask: assignment.ask,564 broke,565 maxContinuations: input.maxContinuations,566 progress: yield* Ref.get(progress),567 project,568 status,569 });570571 yield* Ref.set(progress, step.progress);572573 if (Next.$is("Done")(step.next)) {574 if (step.next.outcome === "failed") {575 yield* say(576 `${harness} failed: ${Option.getOrElse(broke, () => "no reason given")}`577 );578 }579580 return step.next.outcome;581 }582583 yield* say(584 `${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})`585 );586587 return yield* pass(588 driver.resume({589 adapter,590 model,591 prompt: step.next.prompt,592 session: session.value,593 workspace,594 }),595 env596 );597 });598599 const loop = Effect.gen(function* () {600 const fs = yield* FileSystem.FileSystem;601602 yield* Effect.forEach(603 driver.files(workspace),604 ({ content, path }) => fs.writeFileString(path, content),605 { discard: true }606 ).pipe(607 Effect.mapError(608 ({ message }) =>609 new SwarmFailed({610 reason: `${harness}'s settings: ${message}`,611 })612 )613 );614615 return yield* pass(616 driver.start({617 adapter,618 brief: input.brief,619 model,620 sessionDir: sessionDirOf(workspace.dir),621 sessionKey: handle,622 workspace,623 }),624 yield* harnessEnv(workspace)625 );626 });627628 const outcome = yield* loop.pipe(629 Effect.timeoutOption(Duration.millis(input.timeoutMs)),630 Effect.map(Option.getOrElse((): AgentOutcome => "timedOut")),631 Effect.catchTag(632 "SwarmFailed",633 ({ reason }): Effect.Effect<AgentOutcome> =>634 Effect.as(say(reason), "failed")635 )636 );637638 const finished = yield* Clock.currentTimeMillis;639 const at = yield* Ref.get(progress);640641 yield* say(`${outcome} after ${at.attempts} attempts`);642643 return {644 adapter,645 ask: assignment.ask,646 attempts: at.attempts,647 durationMs: finished - begun,648 handle,649 harness,650 model,651 outcome,652 refusals: at.refusals,653 ...Option.match(at.landed, {654 onNone: () => ({}),655 onSome: (landed) => ({ landed }),656 }),657 };658 });
added:scripts/lib/swarm/outcome.ts+176 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 */7import { Brand } from "@repo/brand";8import { AnswerView } from "@repo/protocol/domain/answer";9import { ClaimView } from "@repo/protocol/domain/claim";10import { Outcome } from "@repo/protocol/domain/outcome";11import { Envelope } from "@repo/protocol/envelope";12import type { AskId, CommitSha, ProjectName } from "@repo/protocol/ids";13import {14 Array,15 Duration,16 Effect,17 Option,18 Order,19 Schedule,20 Schema,21} from "effect";22import type { ChildProcessSpawner } from "effect/process";2324import { run, scrubbed, SwarmFailed } from "./workspace.ts";25import type { AgentWorkspace } from "./workspace.ts";2627/** What the swarm reads of `status`: the caller's claims and answers. */28const StatusData = Schema.Struct({29 answers: Schema.Array(AnswerView),30 claims: Schema.Array(ClaimView),31});3233const decodeStatus = Schema.decodeEffect(34 Schema.fromJsonString(Envelope(StatusData))35);3637/** One ask, as the contributor's status shows it. */38export interface AskStatus {39 /** Their claim on the ask, while status lists it. */40 readonly claim: Option.Option<ClaimView>;41 /**42 * Every answer of theirs to the ask, oldest first: one session can push43 * several before it settles.44 */45 readonly answers: readonly AnswerView[];46 /** Their latest answer to the ask: the last of `answers`. */47 readonly answer: Option.Option<AnswerView>;48}4950/** The CLI in the workspace's `bin/`: the shim the contributor's harness runs too. */51export const workspaceCli = (workspace: Pick<AgentWorkspace, "dir">) =>52 `${workspace.dir}/bin/${Brand.cli}`;5354/** `answers` oldest first, by `at`; of two at the same instant, the one listed first. */55const oldestFirst = (answers: readonly AnswerView[]) =>56 Array.sort(57 answers,58 Order.mapInput(Order.Number, ({ at }: AnswerView) => at.epochMilliseconds)59 );6061/** How one status read is asked: whose workspace, and which ask (in which project, when known). */62export interface StatusQuery {63 readonly workspace: AgentWorkspace;64 /** Without one, status lists every project's claims and answers. */65 readonly project: Option.Option<ProjectName>;66 readonly ask: AskId;67}6869/**70 * The contributor's claim on `ask` and their latest answer to it, from71 * `<cli> status [--project <p>] --json` run in their clone with their env.72 * A status that refuses, or prints no envelope, fails `SwarmFailed`, its73 * text scrubbed of the token.74 */75export const readStatus = (76 query: StatusQuery77): Effect.Effect<78 AskStatus,79 SwarmFailed,80 ChildProcessSpawner.ChildProcessSpawner81> =>82 Effect.gen(function* () {83 const { ask, workspace } = query;8485 const ran = yield* run({86 args: [87 "status",88 ...Option.match(query.project, {89 onNone: () => [],90 onSome: (project) => ["--project", project],91 }),92 "--json",93 ],94 command: workspaceCli(workspace),95 cwd: workspace.clone,96 env: workspace.env,97 });9899 const envelope = yield* decodeStatus(ran.stdout).pipe(100 Effect.mapError(101 () =>102 new SwarmFailed({103 reason: scrubbed(104 `status exited ${ran.code} without its JSON: ${(ran.stderr.trim() === "" ? ran.stdout : ran.stderr).trim().slice(0, 500)}`,105 workspace106 ),107 })108 )109 );110111 if (!envelope.ok) {112 return yield* new SwarmFailed({113 reason: `status refused: ${envelope.refusals.map(({ _tag }) => _tag).join(", ")}`,114 });115 }116117 const answers = oldestFirst(118 envelope.data.answers.filter((answer) => answer.ask === ask)119 );120121 return {122 answer: Array.last(answers),123 answers,124 claim: Array.findLast(envelope.data.claims, (claim) => claim.ask === ask),125 };126 });127128/**129 * The contributor's latest answer to `ask`, with its head and outcome: the130 * outcome the verdict loop acts on.131 */132export const readOutcome = (133 query: StatusQuery134): Effect.Effect<135 Option.Option<{ readonly head: CommitSha; readonly outcome: Outcome }>,136 SwarmFailed,137 ChildProcessSpawner.ChildProcessSpawner138> =>139 Effect.map(readStatus(query), ({ answer }) =>140 Option.map(answer, ({ head, outcome }) => ({ head, outcome }))141 );142143/** How often a run that is still being checked is asked again. */144export const POLL_MS = 5000;145146/**147 * How many times a status read that fails (the platform briefly down, a148 * request dropped) is asked again, `pollMs` apart, before the run fails:149 * one bad read in a run of hundreds should not end a contributor's run.150 */151export const STATUS_RETRIES = 5;152153/**154 * Reads the ask's status until its latest answer is no longer `Checking`:155 * landed, refused or waiting on someone, or no answer at all. It asks156 * every `pollMs`, asks again up to `STATUS_RETRIES` times when a read157 * fails, and never gives up on its own: the run's timeout (`loop.ts`)158 * bounds it.159 */160export const awaitSettledOutcome = (161 query: StatusQuery & { readonly pollMs?: number }162): Effect.Effect<163 AskStatus,164 SwarmFailed,165 ChildProcessSpawner.ChildProcessSpawner166> => {167 const checking = ({ answer }: AskStatus) =>168 Option.exists(answer, ({ outcome }) => Outcome.guards.Checking(outcome));169170 const every = Schedule.spaced(Duration.millis(query.pollMs ?? POLL_MS));171172 return readStatus(query).pipe(173 Effect.retry({ schedule: every, times: STATUS_RETRIES }),174 Effect.repeat({ schedule: every, while: checking })175 );176};