Skip to content
Myr

swarm-loop.test.ts

This file

Path

packages/config/test/swarm-loop.test.ts

1,096 lines · 31.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1// `fixtures/swarm/harness-output/<harness>/` is what each harness printed for2// one headless start and one resume, its local paths replaced and the3// machine's own setup (tool, MCP, plugin and skill lists) left out.4import { NodeServices } from "@effect/platform-node";5import { describe, expect, it } from "@effect/vitest";6import { AnswerView } from "@repo/protocol/domain/answer";7import { ClaimView } from "@repo/protocol/domain/claim";8import { Outcome } from "@repo/protocol/domain/outcome";9import { Envelope } from "@repo/protocol/envelope";10import {11  AskId,12  CommitSha,13  DecisionId,14  Handle,15  LandedSha,16  RepoPath,17  RequestId,18} from "@repo/protocol/ids";19import {20  ChecksFailed,21  ClaimLapsed,22  OutOfScope,23  StaleBase,24  VerifierBlocked,25} from "@repo/protocol/refusal";26import type { Refusal } from "@repo/protocol/refusal";27import { explain } from "@repo/protocol/render";28import {29  ConfigProvider,30  Console,31  DateTime,32  Effect,33  Fiber,34  FileSystem,35  Layer,36  Path,37  Ref,38  Schema,39  Sink,40  Stream,41} from "effect";42import type { Array } from "effect";43import { ChildProcess, ChildProcessSpawner } from "effect/process";44import { TestClock } from "effect/testing";4546import {47  drivers,48  HarnessEvent,49} from "../../../scripts/lib/swarm/harnesses/index.ts";50import type { HarnessDriver } from "../../../scripts/lib/swarm/harnesses/index.ts";51import { runAgent, startCommand } from "../../../scripts/lib/swarm/loop.ts";52import type { Assignment } from "../../../scripts/lib/swarm/plan.ts";53import type { Harness } from "../../../scripts/lib/swarm/results.ts";54import { roster } from "../../../scripts/lib/swarm/roster.ts";55import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";56import { Brand } from "../../brand/src/index.ts";57import { repoRoot } from "./root.ts";5859const SLUG = Brand.slug.toUpperCase();6061const token = "wren-token-0123456789abcdef0123456789abcdef";6263const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";6465const ask = AskId.make("drop-legacy-fetch-burrow-auth");6667const recorded = (68  harness: Harness,69  run: "start" | "resume" | "refused-model"70) =>71  Effect.gen(function* () {72    const fs = yield* FileSystem.FileSystem;73    const path = yield* Path.Path;7475    const text = yield* fs.readFileString(76      path.join(77        "test",78        "fixtures",79        "swarm",80        "harness-output",81        harness,82        `${run}.jsonl`83      )84    );8586    return text.split("\n").filter((line) => line !== "");87  }).pipe(Effect.provide(NodeServices.layer));8889const heard = (driver: HarnessDriver, lines: readonly string[]) =>90  lines.flatMap(driver.parse);9192const sessionsIn = (events: readonly HarnessEvent[]) =>93  events.flatMap((event) =>94    HarnessEvent.$is("SessionStarted")(event) ? [event.id] : []95  );9697const heads = ["1", "2", "3", "4"].map((digit) =>98  CommitSha.make(digit.repeat(40))99);100101const landing = LandedSha.make(CommitSha.make("a".repeat(40)));102103const answer = (n: number, outcome: Outcome): AnswerView => ({104  ask,105  at: DateTime.makeUnsafe(`2026-10-08T12:00:0${n}.000Z`),106  head: heads[n] ?? CommitSha.make("f".repeat(40)),107  outcome,108  requestId: RequestId.make(`push-${heads[n] ?? "f".repeat(40)}-wren`),109});110111const refused = (...refusals: Array.NonEmptyReadonlyArray<Refusal>) =>112  Outcome.cases.Refused.make({ refusals });113114const outOfScope = new OutOfScope({115  paths: [RepoPath.make("packages/billing/src/index.ts")],116});117118const staleBase = new StaleBase({119  base: CommitSha.make("b".repeat(40)),120  conflicts: [],121  main: CommitSha.make("c".repeat(40)),122});123124const checksFailed = new ChecksFailed({125  lane: "test",126  logRef: "log-0001",127  next: `${Brand.cli} evidence log-0001`,128});129130const wrensClaim: ClaimView = Schema.decodeSync(ClaimView)({131  ask,132  base: "9998ebe62c2f282d148b1d806372484916cc2548",133  checkCommand: `${Brand.cli} check`,134  claimant: "wren",135  fork: "burrow--drop-legacy-fetch-burrow-auth--wren",136  lapsesAt: "2026-10-09T05:00:00.000Z",137  openedAt: "2026-10-08T05:00:00.000Z",138  project: "burrow",139  remote: `${platformUrl}/burrow--drop-legacy-fetch-burrow-auth--wren.git`,140  state: "live",141  warnsAt: "2026-10-08T17:00:00.000Z",142});143144const StatusJson = Schema.fromJsonString(145  Envelope(146    Schema.Struct({147      answers: Schema.Array(AnswerView),148      claims: Schema.Array(ClaimView),149      handle: Handle,150    })151  )152);153154const status = (...answers: readonly AnswerView[]) =>155  Schema.encodeSync(StatusJson)({156    command: "status",157    data: { answers, claims: [wrensClaim], handle: Handle.make("wren") },158    ok: true,159    v: 1,160  });161162interface Spawned {163  readonly command: string;164  readonly args: readonly string[];165  readonly cwd: string | undefined;166  readonly env: Readonly<Record<string, string | undefined>>;167  readonly extendEnv: boolean | undefined;168}169170type HarnessRun =171  | { readonly lines: readonly string[]; readonly code?: number }172  | { readonly stalls: readonly string[] };173174const bytes = (text: string) => new TextEncoder().encode(text);175176const handleOf = (input: {177  readonly stdout: Stream.Stream<Uint8Array>;178  readonly exitCode: Effect.Effect<number>;179}) =>180  ChildProcessSpawner.makeHandle({181    all: input.stdout,182    exitCode: Effect.map(input.exitCode, ChildProcessSpawner.ExitCode),183    getInputFd: () => Sink.drain,184    getOutputFd: () => Stream.empty,185    isRunning: Effect.succeed(false),186    kill: () => Effect.void,187    pid: ChildProcessSpawner.ProcessId(1),188    stderr: Stream.empty,189    stdin: Sink.drain,190    stdout: input.stdout,191    unref: Effect.succeed(Effect.void),192  });193194const fakeWorld = (script: {195  readonly harness: readonly HarnessRun[];196  readonly statuses: readonly string[];197}) =>198  Effect.gen(function* () {199    const spawned = yield* Ref.make<readonly Spawned[]>([]);200    const runs = yield* Ref.make(script.harness);201    const statuses = yield* Ref.make(script.statuses);202203    const spawner = ChildProcessSpawner.make((command) =>204      Effect.gen(function* () {205        if (!ChildProcess.isStandardCommand(command)) {206          return yield* Effect.die("the swarm pipes no commands");207        }208209        yield* Ref.update(spawned, (calls) => [210          ...calls,211          {212            args: command.args,213            command: command.command,214            cwd: command.options.cwd,215            env: command.options.env ?? {},216            extendEnv: command.options.extendEnv,217          },218        ]);219220        if (command.command.endsWith(`/bin/${Brand.cli}`)) {221          const [next = "", ...rest] = yield* Ref.get(statuses);222223          if (rest.length > 0) {224            yield* Ref.set(statuses, rest);225          }226227          return handleOf({228            exitCode: Effect.succeed(0),229            stdout: Stream.make(bytes(`${next}\n`)),230          });231        }232233        const [next, ...rest] = yield* Ref.get(runs);234235        yield* Ref.set(runs, rest);236237        if (next === undefined) {238          return yield* Effect.die(239            `no harness run scripted for ${command.command}`240          );241        }242243        return "stalls" in next244          ? handleOf({245              exitCode: Effect.never,246              stdout: Stream.make(bytes(`${next.stalls.join("\n")}\n`)).pipe(247                Stream.concat(Stream.never)248              ),249            })250          : handleOf({251              exitCode: Effect.succeed(next.code ?? 0),252              stdout: Stream.make(bytes(`${next.lines.join("\n")}\n`)),253            });254      })255    );256257    return {258      harnessRuns: Effect.map(Ref.get(spawned), (calls) =>259        calls.filter(({ command }) => !command.endsWith(`/bin/${Brand.cli}`))260      ),261      layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),262      spawned: Ref.get(spawned),263    };264  });265266/**267 * A file system in memory: directories always exist, and a write (or an268 * append, with flag `a`) lands in `files`. The loop's writes are then as269 * synchronous as the fake processes, so the TestClock moves deterministically.270 */271const memoryFs = (files: Map<string, string>) =>272  FileSystem.makeNoop({273    makeDirectory: () => Effect.void,274    writeFileString: (path, data, options) =>275      Effect.sync(() => {276        files.set(277          path,278          options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data279        );280      }),281  });282283const dir = "/work/.swarm/r1/wren";284285const wrensWorkspace: AgentWorkspace = {286  clone: `${dir}/clone`,287  dir,288  env: {289    GIT_TERMINAL_PROMPT: "0",290    PATH: `${dir}/bin:/usr/bin`,291    [`${SLUG}_TOKEN`]: token,292    [`${SLUG}_URL`]: platformUrl,293    XDG_CONFIG_HOME: `${dir}/config`,294  },295  redacted: [`${SLUG}_TOKEN`],296};297298const swarmEnv = ConfigProvider.fromEnv({299  env: {300    CLAUDECODE: "1",301    CLOUDFLARE_API_TOKEN: "cf-secret",302    HOME: "/home/user",303    SESSION_TOKENS: JSON.stringify({ [token]: "wren" }),304  },305});306307const [wren, tamsin, ivo] = roster;308309const agentRun = (input: {310  readonly harness: readonly HarnessRun[];311  readonly statuses: readonly string[];312  readonly contributor?: Assignment["contributor"];313  readonly timeoutMs?: number;314  readonly clock?: Effect.Effect<void>;315}) =>316  Effect.gen(function* () {317    const world = yield* fakeWorld(input);318    const files = new Map<string, string>();319    const said: string[] = [];320321    const captured: Console.Console = {322      ...console,323      error: (...args: readonly unknown[]) => {324        said.push(args.map(String).join(" "));325      },326      log: (...args: readonly unknown[]) => {327        said.push(args.map(String).join(" "));328      },329    };330331    const fiber = yield* runAgent({332      assignment: {333        ask,334        contributor: input.contributor ?? wren,335        territory: "@burrow/auth",336      },337      brief: "Answer the ask.",338      maxContinuations: 3,339      timeoutMs: input.timeoutMs ?? 1_200_000,340      workspace: wrensWorkspace,341    }).pipe(342      Effect.provide(world.layer),343      Effect.provideService(FileSystem.FileSystem, memoryFs(files)),344      Effect.provideService(Console.Console, captured),345      Effect.provideService(ConfigProvider.ConfigProvider, swarmEnv),346      Effect.forkChild347    );348349    yield* input.clock ?? Effect.void;350351    const result = yield* Fiber.join(fiber);352353    return {354      files,355      harnessRuns: yield* world.harnessRuns,356      result,357      said,358      spawned: yield* world.spawned,359    };360  });361362const promptOf = (run: Spawned | undefined) => run?.args.at(-1) ?? "";363364describe("the verdict loop", () => {365  it.effect(366    "resumes the same session on OutOfScope, then on StaleBase, and stops when the answer lands",367    () =>368      Effect.gen(function* () {369        const start = yield* recorded("claude-code", "start");370        const resume = yield* recorded("claude-code", "resume");371        const [session] = sessionsIn(heard(drivers["claude-code"], start));372373        const first = answer(1, refused(outOfScope));374        const second = answer(2, refused(staleBase));375        const third = answer(3, Outcome.cases.Landed.make({ sha: landing }));376377        const { harnessRuns, result } = yield* agentRun({378          harness: [{ lines: start }, { lines: resume }, { lines: resume }],379          statuses: [380            status(first),381            status(first, second),382            status(first, second, third),383          ],384        });385386        expect(result).toStrictEqual({387          adapter: false,388          ask,389          attempts: 3,390          durationMs: 0,391          handle: "wren",392          harness: "claude-code",393          landed: landing,394          model: "claude-opus-5-5",395          outcome: "landed",396          refusals: { OutOfScope: 1, StaleBase: 1 },397        });398399        const [, afterOutOfScope, afterStaleBase] = harnessRuns;400401        expect(402          [afterOutOfScope, afterStaleBase].map(403            (run) => run?.args.slice(-3, -1) ?? []404          )405        ).toStrictEqual([406          ["--resume", session],407          ["--resume", session],408        ]);409        expect(promptOf(afterOutOfScope)).toContain(410          [...explain([outOfScope]), "", `Next: ${outOfScope.next}`].join("\n")411        );412        expect(promptOf(afterStaleBase)).toContain(`Next: ${staleBase.next}`);413      })414  );415416  it.effect(417    "gives up as refused after three continuations when a fourth refusal comes back",418    () =>419      Effect.gen(function* () {420        const start = yield* recorded("claude-code", "start");421        const resume = yield* recorded("claude-code", "resume");422423        const answers = [1, 2, 3, 4].map((n) =>424          answer(n, refused(checksFailed))425        );426427        const { harnessRuns, result } = yield* agentRun({428          harness: [429            { lines: start },430            { lines: resume },431            { lines: resume },432            { lines: resume },433            { lines: resume },434          ],435          statuses: answers.map((_, n) => status(...answers.slice(0, n + 1))),436        });437438        expect([439          result.outcome,440          result.attempts,441          result.refusals,442        ]).toStrictEqual(["refused", 4, { ChecksFailed: 4 }]);443        expect(harnessRuns).toHaveLength(4);444      })445  );446447  it.effect("stops at once on a refusal that ends the claim", () =>448    Effect.gen(function* () {449      const start = yield* recorded("claude-code", "start");450451      const { harnessRuns, result } = yield* agentRun({452        harness: [{ lines: start }],453        statuses: [status(answer(1, refused(ClaimLapsed.of(ask))))],454      });455456      expect([result.outcome, result.attempts, result.refusals]).toStrictEqual([457        "refused",458        1,459        { ClaimLapsed: 1 },460      ]);461      expect(harnessRuns).toHaveLength(1);462    })463  );464465  it.effect(466    "records a run that never settles as timedOut when its timeout passes on the clock",467    () =>468      Effect.gen(function* () {469        const start = yield* recorded("claude-code", "start");470471        const { result } = yield* agentRun({472          clock: TestClock.adjust("10 minutes"),473          harness: [{ stalls: start.slice(0, 3) }],474          statuses: [status()],475          timeoutMs: 600_000,476        });477478        expect([479          result.outcome,480          result.attempts,481          result.durationMs,482        ]).toStrictEqual(["timedOut", 1, 600_000]);483      })484  );485486  it.effect(487    "asks status again every five seconds while the answer is being checked",488    () =>489      Effect.gen(function* () {490        const start = yield* recorded("claude-code", "start");491        const checking = Outcome.cases.Checking.make({ stage: "checks" });492493        const { result, spawned } = yield* agentRun({494          clock: Effect.gen(function* () {495            yield* TestClock.adjust("5 seconds");496            yield* TestClock.adjust("5 seconds");497          }),498          harness: [{ lines: start }],499          statuses: [500            status(answer(1, checking)),501            status(answer(1, checking)),502            status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),503          ],504        });505506        expect([result.outcome, result.attempts, result.landed]).toStrictEqual([507          "landed",508          1,509          landing,510        ]);511        expect(512          spawned.filter(({ command }) => command.endsWith(`/bin/${Brand.cli}`))513        ).toHaveLength(3);514      })515  );516517  it.effect(518    "records an answer waiting on a decision or a finish as waiting, without a continuation",519    () =>520      Effect.gen(function* () {521        const start = yield* recorded("claude-code", "start");522523        const waits = [524          Outcome.cases.AwaitingDecision.make({525            decision: DecisionId.make("dec-000001"),526          }),527          Outcome.cases.AwaitingFinish.make({}),528        ];529530        const results = yield* Effect.forEach(waits, (waiting) =>531          agentRun({532            harness: [{ lines: start }],533            statuses: [status(answer(1, waiting))],534          })535        );536537        expect(538          results.map(({ harnessRuns, result }) => [539            result.outcome,540            result.attempts,541            harnessRuns.length,542          ])543        ).toStrictEqual([544          ["waiting", 1, 1],545          ["waiting", 1, 1],546        ]);547      })548  );549550  it.effect(551    "nudges once, naming the claim's remote, when no answer was pushed, then records noAnswer",552    () =>553      Effect.gen(function* () {554        const start = yield* recorded("claude-code", "start");555        const resume = yield* recorded("claude-code", "resume");556557        const { harnessRuns, result } = yield* agentRun({558          harness: [{ lines: start }, { lines: resume }, { lines: resume }],559          statuses: [status()],560        });561562        expect([result.outcome, result.attempts]).toStrictEqual([563          "noAnswer",564          2,565        ]);566        expect(promptOf(harnessRuns[1])).toContain(wrensClaim.remote);567      })568  );569570  it.effect(571    "takes an old answer status still shows after a continuation as no new answer, and nudges with the head it last saw",572    () =>573      Effect.gen(function* () {574        const start = yield* recorded("claude-code", "start");575        const resume = yield* recorded("claude-code", "resume");576        const first = answer(1, refused(checksFailed));577578        const { harnessRuns, result } = yield* agentRun({579          harness: [{ lines: start }, { lines: resume }, { lines: resume }],580          statuses: [status(first)],581        });582583        expect([584          result.outcome,585          result.attempts,586          result.refusals,587        ]).toStrictEqual(["refused", 3, { ChecksFailed: 1 }]);588589        // An answer did arrive: the nudge must not say none ever did.590        const nudge = promptOf(harnessRuns[2]);591592        expect(nudge).toContain(`since ${first.head.slice(0, 7)}`);593        expect(nudge).not.toContain("yet");594      })595  );596597  it.effect(598    "sends a refusal on the platform's side back as a wait, not as something to fix",599    () =>600      Effect.gen(function* () {601        const start = yield* recorded("claude-code", "start");602        const resume = yield* recorded("claude-code", "resume");603        const blocked = answer(1, refused(new VerifierBlocked({})));604        const landed = answer(2, Outcome.cases.Landed.make({ sha: landing }));605606        const { harnessRuns, result } = yield* agentRun({607          harness: [{ lines: start }, { lines: resume }],608          statuses: [status(blocked), status(blocked, landed)],609        });610611        expect([612          result.outcome,613          result.attempts,614          result.refusals,615        ]).toStrictEqual(["landed", 2, { VerifierBlocked: 1 }]);616617        const prompt = promptOf(harnessRuns[1]);618619        expect(prompt).toContain("not a fault in your change");620        expect(prompt).toContain("git commit --allow-empty");621        expect(prompt).not.toContain("Fix what the refusal names");622      })623  );624625  it.effect(626    "counts the refusals of every answer one session pushed, not only its last",627    () =>628      Effect.gen(function* () {629        const start = yield* recorded("claude-code", "start");630631        const { harnessRuns, result } = yield* agentRun({632          harness: [{ lines: start }],633          statuses: [634            status(635              answer(1, refused(outOfScope)),636              answer(2, refused(staleBase)),637              answer(3, Outcome.cases.Landed.make({ sha: landing }))638            ),639          ],640        });641642        expect([643          result.outcome,644          result.attempts,645          result.refusals,646        ]).toStrictEqual(["landed", 1, { OutOfScope: 1, StaleBase: 1 }]);647        expect(harnessRuns).toHaveLength(1);648      })649  );650651  it.effect(652    "asks status again when a read fails, rather than ending the run",653    () =>654      Effect.gen(function* () {655        const start = yield* recorded("claude-code", "start");656657        const { result, spawned } = yield* agentRun({658          clock: TestClock.adjust("5 seconds"),659          harness: [{ lines: start }],660          statuses: [661            "error: fetch failed",662            status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),663          ],664        });665666        expect([result.outcome, result.attempts]).toStrictEqual(["landed", 1]);667        expect(668          spawned.filter(({ command }) => command.endsWith(`/bin/${Brand.cli}`))669        ).toHaveLength(2);670      })671  );672673  it.effect(674    "records a pi run whose provider failed as failed, though pi exits 0",675    () =>676      Effect.gen(function* () {677        const start = yield* recorded("pi", "start");678679        const finalResponse = start.findLastIndex((line) =>680          line.startsWith('{"type":"message_end","message":{"role":"assistant"')681        );682683        // pi's last response as JSON mode prints it when the provider fails.684        const failing = start.map((line, index) =>685          index === finalResponse686            ? line.replace(687                '"stopReason":"stop"',688                '"stopReason":"error","errorMessage":"429 Too Many Requests"'689              )690            : line691        );692693        const { harnessRuns, result, said } = yield* agentRun({694          contributor: roster[3],695          harness: [{ code: 0, lines: failing }, { lines: [] }],696          statuses: [status()],697        });698699        expect(failing[finalResponse]).toContain('"stopReason":"error"');700        expect([701          result.outcome,702          result.attempts,703          harnessRuns.length,704        ]).toStrictEqual(["failed", 1, 1]);705        expect(said).toContainEqual(706          expect.stringContaining(707            "marisol: pi failed: error: 429 Too Many Requests"708          )709        );710      })711  );712713  it.effect(714    "records a harness that exits before it starts a session as failed",715    () =>716      Effect.gen(function* () {717        const { result, spawned } = yield* agentRun({718          harness: [{ code: 1, lines: [] }],719          statuses: [status()],720        });721722        expect([result.outcome, result.attempts]).toStrictEqual(["failed", 0]);723        expect(spawned).toHaveLength(1);724      })725  );726727  it.effect(728    "records a harness whose provider refused the model as failed, without a nudge, saying why",729    () =>730      Effect.gen(function* () {731        const refusedModel = yield* recorded("opencode", "refused-model");732733        const { harnessRuns, result, said } = yield* agentRun({734          contributor: tamsin,735          harness: [{ code: 1, lines: refusedModel }, { lines: [] }],736          statuses: [status()],737        });738739        expect([740          result.outcome,741          result.attempts,742          harnessRuns.length,743        ]).toStrictEqual(["failed", 1, 1]);744        expect(said).toContainEqual(745          expect.stringContaining(746            "tamsin: opencode failed: provider.invalid-request: The 'gpt-6.1-sol' model is not supported"747          )748        );749      })750  );751752  it.effect(753    "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",754    () =>755      Effect.gen(function* () {756        const start = yield* recorded("claude-code", "start");757758        // A tool's output that printed the token, before the run's result.759        const leaky = [760          ...start.slice(0, -1),761          `{"type":"note","text":"${token}"}`,762          ...start.slice(-1),763        ];764765        const { files, harnessRuns } = yield* agentRun({766          harness: [{ lines: leaky }],767          statuses: [768            status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),769          ],770        });771772        const [run] = harnessRuns;773774        expect([run?.cwd, run?.extendEnv, run?.env]).toStrictEqual([775          wrensWorkspace.clone,776          false,777          { ...wrensWorkspace.env, HOME: "/home/user" },778        ]);779        expect(files.get(`${dir}/attempt-1.jsonl`)).toBe(780          `${[...start.slice(0, -1), '{"type":"note","text":"<redacted>"}', ...start.slice(-1)].join("\n")}\n`781        );782      })783  );784785  it.effect(786    "writes Amp's settings into the workspace before Amp starts, and starts it there",787    () =>788      Effect.gen(function* () {789        const start = yield* recorded("amp", "start");790791        const { files, harnessRuns } = yield* agentRun({792          contributor: ivo,793          harness: [{ lines: start }],794          statuses: [795            status(answer(1, Outcome.cases.Landed.make({ sha: landing }))),796          ],797        });798799        expect(harnessRuns[0]?.args).toContain(`${dir}/amp-settings.json`);800        expect(801          JSON.parse(files.get(`${dir}/amp-settings.json`) ?? "{}")802        ).toStrictEqual({ "amp.dangerouslyAllowAll": true });803      })804  );805});806807const goldenWorkspace = (handle: string): AgentWorkspace => ({808  clone: `/work/.swarm/r1/${handle}/clone`,809  dir: `/work/.swarm/r1/${handle}`,810  env: {},811  redacted: [],812});813814describe("the harness drivers", () => {815  it.effect(816    "start and resume each harness with the flags its --help lists",817    () =>818      Effect.gen(function* () {819        const root = yield* repoRoot;820        const adapter = `${root}/apps/cli/src/pi.ts`;821822        const argv = roster.map(823          ({ adapter: withAdapter, handle, harness, model }) => {824            const workspace = goldenWorkspace(handle);825            const driver = drivers[harness];826827            return {828              resume: driver.resume({829                adapter: withAdapter,830                model,831                prompt: "Fix it.",832                session: "S-1",833                workspace,834              }),835              start: driver.start({836                adapter: withAdapter,837                brief: "Answer it.",838                model,839                sessionDir: `${workspace.dir}/sessions`,840                sessionKey: handle,841                workspace,842              }),843            };844          }845        );846847        expect(argv).toStrictEqual([848          {849            resume: [850              "claude",851              "-p",852              "--output-format",853              "stream-json",854              "--verbose",855              "--permission-mode",856              "bypassPermissions",857              "--strict-mcp-config",858              "--model",859              "claude-opus-5-5",860              "--resume",861              "S-1",862              "Fix it.",863            ],864            start: [865              "claude",866              "-p",867              "--output-format",868              "stream-json",869              "--verbose",870              "--permission-mode",871              "bypassPermissions",872              "--strict-mcp-config",873              "--model",874              "claude-opus-5-5",875              "Answer it.",876            ],877          },878          {879            resume: [880              "opencode",881              "run",882              "--standalone",883              "--format",884              "json",885              "--auto",886              "-m",887              "opencode-go/gpt-6-luna",888              "-s",889              "S-1",890              "Fix it.",891            ],892            start: [893              "opencode",894              "run",895              "--standalone",896              "--format",897              "json",898              "--auto",899              "-m",900              "opencode-go/gpt-6-luna",901              "Answer it.",902            ],903          },904          {905            resume: [906              "amp",907              "threads",908              "continue",909              "S-1",910              "-x",911              "Fix it.",912              "--stream-json",913              "-m",914              "medium",915              "--settings-file",916              "/work/.swarm/r1/ivo/amp-settings.json",917              "--no-archive-after-execute",918            ],919            start: [920              "amp",921              "-x",922              "Answer it.",923              "--stream-json",924              "-m",925              "medium",926              "--settings-file",927              "/work/.swarm/r1/ivo/amp-settings.json",928              "--no-archive-after-execute",929            ],930          },931          ...[932            ["marisol", "opencode-go/kimi-k3"],933            ["dagny", "opencode-go/glm-5.3"],934          ].map(([handle = "", model = ""]) => ({935            resume: [936              "pi",937              "-p",938              "--mode",939              "json",940              "--no-mcp",941              "--session-dir",942              `/work/.swarm/r1/${handle}/sessions`,943              "--session-id",944              "S-1",945              "--model",946              model,947              "Fix it.",948            ],949            start: [950              "pi",951              "-p",952              "--mode",953              "json",954              "--no-mcp",955              "--session-dir",956              `/work/.swarm/r1/${handle}/sessions`,957              "--session-id",958              handle,959              "--model",960              model,961              "Answer it.",962            ],963          })),964          {965            resume: [966              "pi",967              "-p",968              "--mode",969              "json",970              "--no-mcp",971              "--session-dir",972              "/work/.swarm/r1/pell/sessions",973              "--session-id",974              "S-1",975              "--model",976              "opencode-go/qwen3.8-flash",977              "-e",978              adapter,979              "Fix it.",980            ],981            start: [982              "pi",983              "-p",984              "--mode",985              "json",986              "--no-mcp",987              "--session-dir",988              "/work/.swarm/r1/pell/sessions",989              "--session-id",990              "pell",991              "--model",992              "opencode-go/qwen3.8-flash",993              "-e",994              adapter,995              "Answer it.",996            ],997          },998        ]);999      }).pipe(Effect.provide(NodeServices.layer))1000  );10011002  it("prints the same start command in the plan as each driver's start", () => {1003    expect(1004      roster.map((contributor) =>1005        startCommand({1006          brief: "Answer it.",1007          contributor,1008          dir: `/work/.swarm/r1/${contributor.handle}`,1009        })1010      )1011    ).toStrictEqual(1012      roster.map(({ adapter, handle, harness, model }) =>1013        drivers[harness].start({1014          adapter,1015          brief: "Answer it.",1016          model,1017          sessionDir: `/work/.swarm/r1/${handle}/sessions`,1018          sessionKey: handle,1019          workspace: goldenWorkspace(handle),1020        })1021      )1022    );1023  });10241025  it.effect(1026    "reads the session id, the settling and the tokens from each harness's recorded output, the same session on resume",1027    () =>1028      Effect.gen(function* () {1029        const harnesses = ["claude-code", "opencode", "amp", "pi"] as const;10301031        const read = yield* Effect.forEach(harnesses, (harness) =>1032          Effect.gen(function* () {1033            const driver = drivers[harness];1034            const start = heard(driver, yield* recorded(harness, "start"));1035            const resume = heard(driver, yield* recorded(harness, "resume"));10361037            const settled = start.filter(HarnessEvent.$is("Settled"));10381039            return {1040              harness,1041              resumedSame:1042                new Set([...sessionsIn(start), ...sessionsIn(resume)]).size ===1043                1,1044              sessions: sessionsIn(start).length > 0,1045              settled: settled.length,1046              tokens: start.some(1047                (event) =>1048                  HarnessEvent.$is("Usage")(event) &&1049                  event.input > 0 &&1050                  event.output > 01051              ),1052            };1053          })1054        );10551056        expect(1057          heard(drivers.opencode, yield* recorded("opencode", "refused-model"))1058            .filter(HarnessEvent.$is("Failed"))1059            .map(({ reason }) => reason)1060        ).toStrictEqual([1061          "provider.invalid-request: The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account.",1062        ]);1063        expect(read).toStrictEqual([1064          {1065            harness: "claude-code",1066            resumedSame: true,1067            sessions: true,1068            settled: 1,1069            tokens: true,1070          },1071          // OpenCode prints no event when its run ends: the process exiting settles it.1072          {1073            harness: "opencode",1074            resumedSame: true,1075            sessions: true,1076            settled: 0,1077            tokens: true,1078          },1079          {1080            harness: "amp",1081            resumedSame: true,1082            sessions: true,1083            settled: 1,1084            tokens: true,1085          },1086          {1087            harness: "pi",1088            resumedSame: true,1089            sessions: true,1090            settled: 1,1091            tokens: true,1092          },1093        ]);1094      }).pipe(Effect.provide(NodeServices.layer))1095  );1096});