Skip to content
Myr

Keep the user's MCP servers away from swarm harnesses, count every refusal a session met, and ask status again when a read fails

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

Review of 711 against its issue (Spec) and AGENTS.md with spec §7 (Standards). - Claude Code now runs with `--strict-mcp-config` and pi with `--no-mcp` (both in the installed `--help`: Claude Code 2.1.293, pi 1.1.0). Without them, a live probe showed wren's Claude Code loading the user's `playwright` and `claude.ai Claude Docs` servers, and pi offering the user's `mcp__convex` tool: the user's accounts in a fictional contributor's harness, against the issue's anti-jobs (no credential beyond the person's token; the zero-install path is git plus the CLI). With the flags, the init line lists no MCP server and pi's tools list no MCP tool; both still print a session id and settle. Amp's own settings file and OpenCode's hidden config folder already keep the user's servers out. - `packages/config/test/swarm.test.ts` (702's dry-run row) gains the two flags: its golden string is the plan's printed start command, which these drivers produce. - The loop counted only the latest answer's refusals, but the brief tells the agent to read status and push again, so one session can push several answers before it settles. `readStatus` now returns every answer to the ask, oldest first, and `afterSettle` counts the refusals of every answer not yet judged and marks them all judged, while it still acts on the latest. - `awaitSettledOutcome` asks a failing status read again up to five times, `pollMs` apart, before the run fails (`STATUS_RETRIES`): one dropped request among a run's hundreds of reads no longer ends a contributor's run as `failed`. - Tests (`swarm-loop.test.ts`, 15 to 18): one session that pushed a refused, a refused and a landed answer gives `landed`, 1 attempt, `{OutOfScope: 1, StaleBase: 1}`; a status read that prints no envelope is asked again 5 s later and the run lands; a pi run whose last response failed (`stopReason` `error`) while pi exits 0 is `failed` with no nudge, saying why. The first two and the golden argv failed by assertion first; the pi case passed at once and was seen to fail by assertion with the `error` stop reason planted out of the parser. - Left for 799, as the builder wrote under the issue's Comments: `scripts/swarm.ts` should pass `project: options.project` to `runAgent`.

authored by oscabriel · committed by oscabriel · parent bd4a3c9 · Browse files · 6 files+159 added−35 removed
This commit

State

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

Diff stats

6 files+159 added−35 removed

  • tests:+98 added−2 removed
  • other:+61 added−33 removed

6 files+159 added−35 removed

modified:packages/config/test/swarm-loop.test.ts+96 added
617 unmodified lines
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({
136 unmodified lines
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",
6 unmodified lines
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 ],
59 unmodified lines
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",
5 unmodified lines
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,
7 unmodified lines
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",
7 unmodified lines
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",
106 unmodified lines
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
modified:scripts/lib/swarm/harnesses/claude-code.ts+8 added-4 removed
modified:scripts/lib/swarm/harnesses/pi.ts+6 added-3 removed
1 unmodified line
2 * pi, headless: print mode with JSON events (`-p --mode json`), sessions3 * kept in the workspace (`--session-dir`) under an id the swarm picks4 * (`--session-id`, which opens the session or creates it), so a resume is5 * the same command with a new prompt. pi asks no approvals, so it needs no6 * permission flag. The adapter's contributor loads the CLI's pi adapter7 * (issue 706) with `-e`, on the start and on every resume.6 * 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`), never
80 unmodified lines
94 ? [HarnessEvent.Settled({ stopReason: Option.none() })]95 : [];96};9796/** The flags every run shares: print mode, JSON events, the session, the model, the adapter. */98/** 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;
1 unmodified line
104}) => [105 "-p",106 "--mode",107 "json",108 "--no-mcp",109 "--session-dir",110 input.sessionDir,111 "--session-id",112 input.session,
25 unmodified lines
modified:scripts/lib/swarm/loop.ts+16 added-9 removed
363 unmodified lines
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.368 * 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;
58 unmodified lines
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,437 judged: [...progress.judged, answer.requestId],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),
3 unmodified lines
457 Checking: () => done("timedOut", judged),458 Landed: ({ sha }) =>459 done("landed", { ...judged, landed: Option.some(sha) }),460 Refused: ({ refusals }) => {449 const counted = {450 ...judged,451 refusals: tally(progress.refusals, refusals),452 };453461 if (refusals.some(({ _tag }) => endsClaim.has(_tag)) || !canContinue) {455 return done("refused", counted);462 return done("refused", judged);463 }464465 return {466 next: Next.Resume({467 nudge: false,468 prompt: refusalPrompt({ answer, project, refusals }),469 }),463 progress: { ...counted, continuations: progress.continuations + 1 },470 progress: { ...judged, continuations: progress.continuations + 1 },471 };472 },473 WaitingOnParent: () => done("waiting", judged),474 });
184 unmodified lines
modified:scripts/lib/swarm/outcome.ts+31 added-17 removed
36 unmodified lines
37/** 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[];41 /** Their latest answer to the ask. */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}`;5349/** The latest of `answers`, by `at`; of two at the same instant, the one listed last. */50const latest = (answers: readonly AnswerView[]) =>51 Array.last(52 Array.sort(53 answers,54 Order.mapInput(Order.Number, ({ at }: AnswerView) => at.epochMilliseconds)55 )54/** `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 {
50 unmodified lines
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 {115 answer: latest(116 envelope.data.answers.filter((answer) => answer.ask === ask)117 ),122 answer: Array.last(answers),123 answers,124 claim: Array.findLast(envelope.data.claims, (claim) => claim.ask === ask),125 };126 });127
15 unmodified lines
143/** 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 asks143 * every `pollMs`, and never gives up on its own: the run's timeout144 * (`loop.ts`) bounds it.156 * 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<
3 unmodified lines
166> => {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(157 Effect.repeat({158 schedule: Schedule.spaced(Duration.millis(query.pollMs ?? POLL_MS)),159 while: checking,160 })173 Effect.retry({ schedule: every, times: STATUS_RETRIES }),174 Effect.repeat({ schedule: every, while: checking })175 );176};