Plan the swarm: six vouched contributors on four harnesses, each claiming one child of a split family in a workspace of their own
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- `bun run swarm -- --stage dev-oscabriel --project burrow --dry-run` reads burrow's open asks anonymously (the CLI from source with `<SLUG>_URL`, no token, `XDG_CONFIG_HOME` at an empty `.swarm/anonymous`) and prints one row per contributor ending in the command that would start their harness, the held asks and any scenario nudge; `--json` prints one `SwarmPlan`. It claims nothing, starts nothing, writes nothing and needs no token (run live against dev-oscabriel: six rows, held `drop-legacy-fetch`, `drop-legacy-fetch-delete`). - `planSwarm` takes open, unclaimed, unblocked asks in `AskId` order and hands them out in roster order, skipping any ask whose territory overlaps one already handed out (same module, or `.`, the whole repo). An ask is blocked while any ask in its `blockedBy` is still listed (`listAsks` lists everything not closed), so the delete child and the parent are `held`. `NotEnoughAsks.open` counts the asks it could hand out; `wanted` is the roster's length (`--only` plans for the named people only). - What the verdict loop bounces (spec §6.8 "retryable refusals go back into the same session"): every refusal except those that end the claim. `retryable: true` means only that the same push may pass if sent again (`StaleBase`, `RepoBusy`, `Flake`), while `retryable: false` tags such as `OutOfScope`, `Weakened` and `ChecksFailed` are exactly what an agent fixes, and agents are meant to act on verdicts. `endsClaim` in `scripts/lib/swarm/plan.ts` holds the stop list for 711: `NotClaimed`, `ClaimLapsed`, `AskFull`, `Denounced`, `NotVouched`, `AttemptsExhausted`. - Roster: burrow's vouched six (`wren`, `tamsin`, `ivo`, `marisol`, `dagny`, `pell`; 599's note), so no claim is `NotVouched`. Models as this machine lists them (2026-10-08): Claude Code 2.1.293 on `claude-opus-5-5`; OpenCode 2.0.7 on `openai/gpt-6.1-sol` (`opencode models`); Amp in mode `medium` (`amp --help`: low, medium, high, ultra); pi 1.1.0 on `opencode-go/kimi-k3` and `opencode-go/glm-5.3` (`pi --offline --list-models`: its ready provider is `opencode-go`, not `opencode`), and `opencode/gemini-3.8-flash` with the adapter (OpenCode Zen's newest flash; `opencode-go` has no Gemini). - ASSUMPTION: the pi Gemini agent runs once pi has OpenCode Zen's key: `pi auth check --provider opencode` says `credentials_not_configured` here. A human step; the fallback is one line in `roster.ts` (`opencode-go/qwen3.8-flash`). - Workspace (`.swarm/<run>/<handle>/`): `bin/<Brand.cli>` and `bin/<Brand.gitCredentialHelper>` shims run `apps/cli/src/bin.ts` with Bun (the issue named `main.ts`, which exports the program but runs nothing; the helper shim runs `<cli> credential`, since `bin.ts` picks the helper role by its own name); `config/` (0700) as `XDG_CONFIG_HOME`; the env is PATH, `GIT_TERMINAL_PROMPT=0`, Rat Stack's editor env (credited beside it), `<SLUG>_TOKEN` and `<SLUG>_URL`. The CLI reads `<SLUG>_URL`, not `<SLUG>_PLATFORM` (`apps/cli/src/credentials.ts`, `remote.ts`), so the env uses it. - `prepareWorkspace` makes the clone itself, with `git clone --config …`: the clone's own config gets `credential.<platform>.helper` (empty, then the shim's absolute path, as `login` sets it globally), `useHttpPath`, and the person as `user.name`/`user.email` (`<handle>@example.com`) with `commit.gpgsign=false`, so the helper answers from the first fetch and no fictional person's commit carries the user's own name or signature. No token in any URL, argv or file. - A run: tokens from `SESSION_TOKENS` (token to handle, as the platform's own; a missing person stops the run before any claim, named, never a token); each contributor claims as themselves (`<cli> claim --json` with their env), the claim's fork goes to the throwaway ledger (`recordCreated`, `by: "swarm"`, once), `<cli> ask --json` gives the page, `brief` wraps it, and `runAgent` takes over, six at once; `.swarm/<run>/agents.json` holds the `AgentsResult`. A step that fails ends that contributor's run as `failed` (with the claim's refusal tags), never the others'. - `scripts/lib/swarm/loop.ts` is 711's stub: `runAgent` logs `not built: 711` and returns `failed`. It also exports `startCommand`, the headless argv the plan prints per harness (flags read from each `--help` here); 711 replaces it with its drivers' `start`. - Tests (`packages/config/test/swarm.test.ts`, 21; fixtures recorded from dev-oscabriel's `asks` and `ask` for burrow): the plan (six on four harnesses and six models, delete child held, disjoint, deterministic under reordering, `NotEnoughAsks{wanted: 6, open: 5}`, a claimed child skipped, overlapping and whole-repo territories), the roster against burrow's `vouched.td`, the nudges, the brief, the workspace over a temp dir and a fake spawner (shims, modes, env, the clone's argv, no token anywhere), `writeAgentsResult` decoding back, the flags (demo without `--allow-demo`, herdr until 717), the dry run (table, `--json`, one anonymous `asks` call, nothing written) and a full run over a fake platform (claims per person, ledger entries, summary, no token printed; a missing session stops before any claim). The plan's check was red by assertion first.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+2795 added−13 removed
- tests:+1260 added−0 removed
- other:+1535 added−13 removed
Provenance
- Commit
9bc6d53- Tree
f778b54- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
d7064cb
12 files changed+2795 added−13 removed
added:packages/config/test/fixtures/swarm/list-asks.json+88 added
1+{2+ "command": "asks",3+ "data": {4+ "asks": [5+ {6+ "ask": "drop-legacy-fetch",7+ "blockedBy": [8+ "drop-legacy-fetch-burrow-auth",9+ "drop-legacy-fetch-burrow-billing",10+ "drop-legacy-fetch-burrow-catalog",11+ "drop-legacy-fetch-burrow-kit",12+ "drop-legacy-fetch-burrow-notify",13+ "drop-legacy-fetch-burrow-search",14+ "drop-legacy-fetch-delete"15+ ],16+ "claimed": false,17+ "kind": "migrate",18+ "territory": ".",19+ "want": "Replace every call to legacyFetch with http.get, then delete legacyFetch"20+ },21+ {22+ "ask": "drop-legacy-fetch-burrow-auth",23+ "blockedBy": [],24+ "claimed": false,25+ "kind": "migrate",26+ "territory": "@burrow/auth",27+ "want": "@burrow/auth: 2 callers of legacyFetch → http.get"28+ },29+ {30+ "ask": "drop-legacy-fetch-burrow-billing",31+ "blockedBy": [],32+ "claimed": false,33+ "kind": "migrate",34+ "territory": "@burrow/billing",35+ "want": "@burrow/billing: 2 callers of legacyFetch → http.get"36+ },37+ {38+ "ask": "drop-legacy-fetch-burrow-catalog",39+ "blockedBy": [],40+ "claimed": false,41+ "kind": "migrate",42+ "territory": "@burrow/catalog",43+ "want": "@burrow/catalog: 2 callers of legacyFetch → http.get"44+ },45+ {46+ "ask": "drop-legacy-fetch-burrow-kit",47+ "blockedBy": [],48+ "claimed": false,49+ "kind": "migrate",50+ "territory": "@burrow/kit",51+ "want": "@burrow/kit: 1 caller of legacyFetch → http.get"52+ },53+ {54+ "ask": "drop-legacy-fetch-burrow-notify",55+ "blockedBy": [],56+ "claimed": false,57+ "kind": "migrate",58+ "territory": "@burrow/notify",59+ "want": "@burrow/notify: 1 caller of legacyFetch → http.get"60+ },61+ {62+ "ask": "drop-legacy-fetch-burrow-search",63+ "blockedBy": [],64+ "claimed": false,65+ "kind": "migrate",66+ "territory": "@burrow/search",67+ "want": "@burrow/search: 1 caller of legacyFetch → http.get"68+ },69+ {70+ "ask": "drop-legacy-fetch-delete",71+ "blockedBy": [72+ "drop-legacy-fetch-burrow-auth",73+ "drop-legacy-fetch-burrow-billing",74+ "drop-legacy-fetch-burrow-catalog",75+ "drop-legacy-fetch-burrow-kit",76+ "drop-legacy-fetch-burrow-notify",77+ "drop-legacy-fetch-burrow-search"78+ ],79+ "claimed": false,80+ "kind": "migrate",81+ "territory": ".",82+ "want": "Delete legacyFetch: nothing calls it any more"83+ }84+ ]85+ },86+ "ok": true,87+ "v": 188+}added:packages/config/test/fixtures/swarm/show-ask.json+34 added
12345678910111213141516171819202122232425262728293031323334{ "command": "ask", "data": { "ask": { "askedBy": "okafor", "blockedBy": [], "brief": { "want": "@burrow/auth: 2 callers of legacyFetch → http.get" }, "check": { "_tag": "Migrate", "count": "bun scripts/count-callers.ts legacyFetch --json", "from": "legacyFetch", "to": "http.get" }, "file": "{configDir}/asks/drop-legacy-fetch-burrow-auth.ask.ts", "id": "drop-legacy-fetch-burrow-auth", "kind": "migrate", "openedAt": "2026-10-08T05:21:35.148Z", "openedIn": "9998ebe62c2f282d148b1d806372484916cc2548", "parent": "drop-legacy-fetch", "project": "burrow", "state": "open", "territory": { "module": "@burrow/auth", "paths": ["packages/auth/**"], "publicFiles": ["packages/auth/src/index.ts"] } }, "brief": "# @burrow/auth: 2 callers of legacyFetch → http.get\n\nAsk `drop-legacy-fetch-burrow-auth` in burrow, a `migrate` ask from okafor.\n\n## Territory\n\nThe module `@burrow/auth`: `packages/auth/**`.\n\n## Check\n\nNo caller uses `legacyFetch`; they use `http.get`.\n" }, "ok": true, "v": 1}added:packages/config/test/swarm.test.ts+1138 added
1+/**2+ * The swarm (issue 702): its plan for a split family, its people, each3+ * contributor's brief and workspace, and the run's summary file. The burrow4+ * fixtures are what `<cli> asks` and `<cli> ask` printed for burrow's5+ * `drop-legacy-fetch` family on the dev stage (2026-10-08).6+ */7+import { NodeServices } from "@effect/platform-node";8+import { describe, expect, it } from "@effect/vitest";9+import { Ask, AskListing } from "@repo/protocol/domain/ask";10+import { ClaimView } from "@repo/protocol/domain/claim";11+import { Envelope } from "@repo/protocol/envelope";12+import { AskId, KindName, ProjectName } from "@repo/protocol/ids";13+import {14+ Array,15+ ConfigProvider,16+ Console,17+ Effect,18+ FileSystem,19+ Layer,20+ Option,21+ Path,22+ Redacted,23+ Ref,24+ Result,25+ Schema,26+ Sink,27+ Stream,28+} from "effect";29+import { ChildProcess, ChildProcessSpawner } from "effect/process";30+31+import { LedgerFile, readLedger } from "../../../infra/created.ts";32+import { optionsOf } from "../../../scripts/lib/swarm/args.ts";33+import {34+ NotEnoughAsks,35+ planSwarm,36+ SwarmPlan,37+} from "../../../scripts/lib/swarm/plan.ts";38+import { brief } from "../../../scripts/lib/swarm/prompt.ts";39+import {40+ AgentsResult,41+ SwarmDir,42+ writeAgentsResult,43+} from "../../../scripts/lib/swarm/results.ts";44+import { roster } from "../../../scripts/lib/swarm/roster.ts";45+import type { Contributor } from "../../../scripts/lib/swarm/roster.ts";46+import { nudges } from "../../../scripts/lib/swarm/scenario.ts";47+import { prepareWorkspace } from "../../../scripts/lib/swarm/workspace.ts";48+import { main } from "../../../scripts/swarm.ts";49+import { Brand } from "../../brand/src/index.ts";50+import { repoRoot } from "./root.ts";51+52+const burrow = ProjectName.make("burrow");53+54+const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));55+56+/** What `<cli> ask <ask> --json` prints, when it shows the ask. */57+const ShownAsk = Schema.Struct({58+ command: Schema.Literal("ask"),59+ data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),60+ ok: Schema.Literal(true),61+ v: Schema.Literal(1),62+});63+64+/** A fixture's text. */65+const fixture = (name: string) =>66+ Effect.gen(function* () {67+ const fs = yield* FileSystem.FileSystem;68+ const path = yield* Path.Path;69+70+ return yield* fs.readFileString(71+ path.join("test", "fixtures", "swarm", name)72+ );73+ });74+75+/** burrow's open asks, as `<cli> asks --project burrow --json` listed them. */76+const burrowAsks = Effect.gen(function* () {77+ const envelope = yield* Schema.decodeEffect(78+ Schema.fromJsonString(ListedAsks)79+ )(yield* fixture("list-asks.json"));80+81+ return envelope.ok ? envelope.data.asks : [];82+});83+84+const child = (module: string) => AskId.make(`drop-legacy-fetch-${module}`);85+86+const children = [87+ "burrow-auth",88+ "burrow-billing",89+ "burrow-catalog",90+ "burrow-kit",91+ "burrow-notify",92+ "burrow-search",93+].map(child);94+95+const plan = (96+ asks: readonly AskListing[],97+ people: readonly Contributor[] = roster98+) =>99+ planSwarm({100+ asks,101+ project: burrow,102+ roster: people,103+ scenario: "plain",104+ stage: "dev-oscabriel",105+ });106+107+describe("the plan", () => {108+ it.effect(109+ "hands burrow's six children to the six contributors in order, on four harnesses and six models, and holds the delete child",110+ () =>111+ Effect.gen(function* () {112+ const { assignments, held } = Result.getOrThrow(113+ plan(yield* burrowAsks)114+ );115+116+ expect(117+ assignments.map(({ ask, contributor, territory }) => [118+ contributor.handle,119+ ask,120+ territory,121+ ])122+ ).toStrictEqual([123+ ["wren", children[0], "@burrow/auth"],124+ ["tamsin", children[1], "@burrow/billing"],125+ ["ivo", children[2], "@burrow/catalog"],126+ ["marisol", children[3], "@burrow/kit"],127+ ["dagny", children[4], "@burrow/notify"],128+ ["pell", children[5], "@burrow/search"],129+ ]);130+131+ expect({132+ harnesses: new Set(133+ assignments.map(({ contributor }) => contributor.harness)134+ ).size,135+ models: new Set(136+ assignments.map(({ contributor }) => contributor.model)137+ ).size,138+ }).toStrictEqual({ harnesses: 4, models: 6 });139+ expect(held).toStrictEqual([140+ "drop-legacy-fetch",141+ "drop-legacy-fetch-delete",142+ ]);143+ expect(assignments.map(({ ask }) => ask)).not.toContain(144+ "drop-legacy-fetch-delete"145+ );146+ }).pipe(Effect.provide(NodeServices.layer))147+ );148+149+ it.effect("gives no two contributors overlapping territories", () =>150+ Effect.gen(function* () {151+ const { assignments } = Result.getOrThrow(plan(yield* burrowAsks));152+153+ const territories = assignments.map(({ territory }) => territory);154+155+ expect(territories).toHaveLength(6);156+ expect(new Set(territories).size).toBe(6);157+ expect(territories).not.toContain(".");158+ }).pipe(Effect.provide(NodeServices.layer))159+ );160+161+ it.effect(162+ "plans the same for the same asks, in whatever order they are listed",163+ () =>164+ Effect.gen(function* () {165+ const asks = yield* burrowAsks;166+ const first = Result.getOrThrow(plan(asks));167+168+ expect(Result.getOrThrow(plan(asks))).toStrictEqual(first);169+ expect(Result.getOrThrow(plan(Array.reverse(asks)))).toStrictEqual(170+ first171+ );172+ expect(173+ yield* Schema.decodeEffect(SwarmPlan)(174+ yield* Schema.encodeEffect(SwarmPlan)(first)175+ )176+ ).toStrictEqual(first);177+ }).pipe(Effect.provide(NodeServices.layer))178+ );179+180+ it.effect(181+ "fails NotEnoughAsks{wanted: 6, open: 5} with five open children",182+ () =>183+ Effect.gen(function* () {184+ const asks = (yield* burrowAsks).filter(185+ ({ ask }) => ask !== children[5]186+ );187+188+ expect(plan(asks)).toStrictEqual(189+ Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))190+ );191+ }).pipe(Effect.provide(NodeServices.layer))192+ );193+194+ it.effect("skips a child someone already claimed", () =>195+ Effect.gen(function* () {196+ const asks = (yield* burrowAsks).map((listed) =>197+ listed.ask === children[1] ? { ...listed, claimed: true } : listed198+ );199+200+ const five = roster.slice(0, 5);201+ const { assignments } = Result.getOrThrow(plan(asks, five));202+203+ expect(assignments.map(({ ask }) => ask)).toStrictEqual([204+ children[0],205+ children[2],206+ children[3],207+ children[4],208+ children[5],209+ ]);210+ expect(plan(asks)).toStrictEqual(211+ Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))212+ );213+ }).pipe(Effect.provide(NodeServices.layer))214+ );215+216+ it.effect(217+ "hands out only one of two asks on the same module, and nothing beside a whole-repo ask",218+ () =>219+ Effect.gen(function* () {220+ const asks = yield* burrowAsks;221+222+ const same = asks.map((listed) =>223+ listed.ask === children[1]224+ ? { ...listed, territory: "@burrow/auth" }225+ : listed226+ );227+228+ expect(plan(same)).toStrictEqual(229+ Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))230+ );231+ expect(232+ Result.getOrThrow(plan(same, roster.slice(0, 5))).assignments.map(233+ ({ ask }) => ask234+ )235+ ).toStrictEqual([236+ children[0],237+ children[2],238+ children[3],239+ children[4],240+ children[5],241+ ]);242+243+ const whole: AskListing = {244+ ask: AskId.make("aaa-whole-repo"),245+ blockedBy: [],246+ claimed: false,247+ kind: KindName.make("fix"),248+ territory: ".",249+ want: "Touch everything",250+ };251+252+ const first = Result.getOrThrow(253+ plan([whole, ...asks], roster.slice(0, 1))254+ );255+256+ expect(first.assignments.map(({ ask }) => ask)).toStrictEqual([257+ "aaa-whole-repo",258+ ]);259+ expect(plan([whole, ...asks], roster.slice(0, 2))).toStrictEqual(260+ Result.fail(new NotEnoughAsks({ open: 1, wanted: 2 }))261+ );262+ }).pipe(Effect.provide(NodeServices.layer))263+ );264+});265+266+describe("the roster", () => {267+ it.effect(268+ "is six people burrow vouches for, on four harnesses and six models, with the pi adapter on one pi agent only",269+ () =>270+ Effect.gen(function* () {271+ const fs = yield* FileSystem.FileSystem;272+ const path = yield* Path.Path;273+ const root = yield* repoRoot;274+275+ const vouched = new Set(276+ (yield* fs.readFileString(277+ path.join(root, "examples", "burrow", Brand.configDir, "vouched.td")278+ ))279+ .split("\n")280+ .map((line) => line.split(" ")[0] ?? "")281+ .filter((handle) => /^[a-z]/u.test(handle))282+ );283+284+ expect(roster.map(({ handle }) => handle)).toStrictEqual([285+ "wren",286+ "tamsin",287+ "ivo",288+ "marisol",289+ "dagny",290+ "pell",291+ ]);292+293+ expect(294+ roster.filter(({ handle }) => !vouched.has(handle))295+ ).toStrictEqual([]);296+ expect(roster.map(({ harness }) => harness)).toStrictEqual([297+ "claude-code",298+ "opencode",299+ "amp",300+ "pi",301+ "pi",302+ "pi",303+ ]);304+ expect(305+ roster.flatMap(({ adapter, handle }) => (adapter ? [handle] : []))306+ ).toStrictEqual(["pell"]);307+308+ // An Anthropic id, OpenCode's GPT, an Amp mode, then pi's three.309+ const models = [310+ /^claude-/u,311+ /^openai\/gpt-/u,312+ /^(?:low|medium|high|ultra)$/u,313+ /\/kimi-k3$/u,314+ /\/glm-5\.3$/u,315+ /\/gemini-[\d.]+-flash$/u,316+ ];317+318+ expect(319+ roster.map(({ model }, at) => models[at]?.test(model))320+ ).toStrictEqual([true, true, true, true, true, true]);321+ }).pipe(Effect.provide(NodeServices.layer))322+ );323+});324+325+describe("the scenarios' nudges", () => {326+ it("adds nothing to anyone's brief in the plain scenario", () => {327+ expect(roster.map((_, index) => nudges("plain", index))).toStrictEqual(328+ roster.map(() => Option.none())329+ );330+ });331+332+ it("tells contributor 2 a disable comment is fine, and contributor 3 that it needs its reason, in the video scenario", () => {333+ const told = roster.map((_, index) => nudges("video", index));334+335+ expect(told.map(Option.isSome)).toStrictEqual([336+ false,337+ true,338+ true,339+ false,340+ false,341+ false,342+ ]);343+ expect(Option.getOrThrow(told[1] ?? Option.none())).toContain(344+ "disable comment"345+ );346+ expect(Option.getOrThrow(told[1] ?? Option.none())).not.toContain(" -- ");347+ expect(Option.getOrThrow(told[2] ?? Option.none())).toContain(348+ "reason after ` -- `"349+ );350+ });351+});352+353+/** The ask page `<cli> ask` printed for burrow's auth child. */354+const authPage = Effect.gen(function* () {355+ const text = (yield* fixture("show-ask.json")).replaceAll(356+ "{configDir}",357+ Brand.configDir358+ );359+360+ const shown = yield* Schema.decodeEffect(Schema.fromJsonString(ShownAsk))(361+ text362+ );363+364+ return shown.data;365+});366+367+describe("the brief", () => {368+ const remote =369+ "https://platform-dev-oscabriel.example.workers.dev/burrow--drop-legacy-fetch-burrow-auth--wren.git";370+371+ it.effect(372+ "gives the ask's page, the clone's remote and the four steps a contributor reads in AGENTS.md, and nothing about how answers are judged",373+ () =>374+ Effect.gen(function* () {375+ const page = yield* authPage;376+377+ const text = brief({378+ ask: children[0] ?? AskId.make("x"),379+ askMarkdown: page.brief,380+ nudge: Option.none(),381+ project: burrow,382+ remote,383+ });384+385+ expect(text).toContain(page.brief);386+ expect(387+ [388+ remote,389+ "AGENTS.md",390+ `${Brand.cli} check`,391+ "git push",392+ `${Brand.cli} status --project burrow`,393+ ].filter((said) => !text.includes(said))394+ ).toStrictEqual([]);395+ expect(text).not.toMatch(396+ /\bgate\b|\bstage\b|held-back|sealed|Workflow|Note:/iu397+ );398+ }).pipe(Effect.provide(NodeServices.layer))399+ );400+401+ it("adds a scenario's nudge, in plain sight, at the end", () => {402+ const text = brief({403+ ask: AskId.make("drop-legacy-fetch-burrow-billing"),404+ askMarkdown: "# @burrow/billing: 2 callers\n",405+ nudge: Option.some("A disable comment is acceptable."),406+ project: burrow,407+ remote,408+ });409+410+ expect(text.trimEnd().split("\n").at(-1)).toBe(411+ "Note: A disable comment is acceptable."412+ );413+ });414+});415+416+/** One command a fake spawner was asked to run. */417+interface Spawned {418+ readonly command: string;419+ readonly args: readonly string[];420+ readonly cwd: string | undefined;421+ readonly env: Readonly<Record<string, string | undefined>>;422+}423+424+/**425+ * A `ChildProcessSpawner` that runs nothing: it records each command and426+ * answers with what `answer` gives it (exit 0 and no output by default).427+ */428+const fakeSpawner = (429+ answer: (spawned: Spawned) => {430+ readonly code?: number;431+ readonly stdout?: string;432+ } = () => ({})433+) =>434+ Effect.gen(function* () {435+ const spawned = yield* Ref.make<readonly Spawned[]>([]);436+437+ const spawner = ChildProcessSpawner.make((command) =>438+ Effect.gen(function* () {439+ if (!ChildProcess.isStandardCommand(command)) {440+ return yield* Effect.die("the swarm pipes no commands");441+ }442+443+ const call: Spawned = {444+ args: command.args,445+ command: command.command,446+ cwd: command.options.cwd,447+ env: command.options.env ?? {},448+ };449+450+ yield* Ref.update(spawned, (calls) => [...calls, call]);451+452+ const { code = 0, stdout = "" } = answer(call);453+ const out = Stream.make(new TextEncoder().encode(stdout));454+455+ return ChildProcessSpawner.makeHandle({456+ all: out,457+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),458+ getInputFd: () => Sink.drain,459+ getOutputFd: () => Stream.empty,460+ isRunning: Effect.succeed(false),461+ kill: () => Effect.void,462+ pid: ChildProcessSpawner.ProcessId(1),463+ stderr: Stream.empty,464+ stdin: Sink.drain,465+ stdout: out,466+ unref: Effect.succeed(Effect.void),467+ });468+ })469+ );470+471+ return {472+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),473+ spawned: Ref.get(spawned),474+ };475+ });476+477+/** The env names the CLI reads, spelled from the brand. */478+const SLUG = Brand.slug.toUpperCase();479+480+const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";481+482+/** wren's claim of burrow's auth child, as `<cli> claim --json` gives it. */483+const wrensClaim = Schema.decodeSync(ClaimView)({484+ ask: "drop-legacy-fetch-burrow-auth",485+ base: "9998ebe62c2f282d148b1d806372484916cc2548",486+ checkCommand: `${Brand.cli} check`,487+ claimant: "wren",488+ fork: "burrow--drop-legacy-fetch-burrow-auth--wren",489+ lapsesAt: "2026-10-09T05:00:00.000Z",490+ openedAt: "2026-10-08T05:00:00.000Z",491+ project: "burrow",492+ remote: `${platformUrl}/burrow--drop-legacy-fetch-burrow-auth--wren.git`,493+ state: "live",494+ warnsAt: "2026-10-08T17:00:00.000Z",495+});496+497+const wrensToken = "wren-token-0123456789abcdef0123456789abcdef";498+499+/** wren's workspace for run `r1`, below a temp dir, over a fake spawner. */500+const wrensWorkspace = (code = 0) =>501+ Effect.gen(function* () {502+ const fs = yield* FileSystem.FileSystem;503+ const swarm = yield* fs.makeTempDirectoryScoped();504+ const fake = yield* fakeSpawner(() => ({ code }));505+506+ const [wren] = roster;507+508+ const workspace = yield* prepareWorkspace({509+ claim: wrensClaim,510+ contributor: wren,511+ platformUrl,512+ run: "r1",513+ token: Redacted.make(wrensToken),514+ }).pipe(515+ Effect.provide(fake.layer),516+ Effect.provideService(SwarmDir, swarm),517+ Effect.provideService(518+ ConfigProvider.ConfigProvider,519+ ConfigProvider.fromEnv({ env: { PATH: "/usr/local/bin:/usr/bin" } })520+ ),521+ Effect.result522+ );523+524+ return { spawned: yield* fake.spawned, swarm, workspace };525+ });526+527+describe("a contributor's workspace", () => {528+ it.effect(529+ "writes the CLI and the credential helper as shims in bin/, gives the harness its env, and clones the fork with the helper in the clone's config",530+ () =>531+ Effect.gen(function* () {532+ const fs = yield* FileSystem.FileSystem;533+ const { spawned, swarm, workspace } = yield* wrensWorkspace();534+535+ const dir = `${swarm}/r1/wren`;536+ const bin = `${dir}/bin`;537+ const helper = `${bin}/${Brand.gitCredentialHelper}`;538+ const made = Result.getOrThrow(workspace);539+540+ expect(made).toStrictEqual({541+ clone: `${dir}/clone`,542+ dir,543+ env: {544+ GIT_EDITOR: ":",545+ GIT_MERGE_AUTOEDIT: "no",546+ GIT_SEQUENCE_EDITOR: ":",547+ GIT_TERMINAL_PROMPT: "0",548+ PATH: `${bin}:/usr/local/bin:/usr/bin`,549+ [`${SLUG}_TOKEN`]: wrensToken,550+ [`${SLUG}_URL`]: platformUrl,551+ XDG_CONFIG_HOME: `${dir}/config`,552+ },553+ redacted: [`${SLUG}_TOKEN`],554+ });555+556+ const cli = yield* fs.readFileString(`${bin}/${Brand.cli}`);557+ const credential = yield* fs.readFileString(helper);558+559+ const modes = yield* Effect.forEach(560+ [`${bin}/${Brand.cli}`, helper],561+ (shim) =>562+ Effect.map(fs.stat(shim), ({ mode }) => (mode % 0o1000).toString(8))563+ );564+565+ expect({566+ cli: /^#!\/bin\/sh\n(?:#.*\n)?exec bun '[^']+\/apps\/cli\/src\/bin\.ts' "\$@"\n$/u.test(567+ cli568+ ),569+ config: (yield* fs.stat(`${dir}/config`)).type,570+ credential:571+ /^#!\/bin\/sh\n(?:#.*\n)?exec bun '[^']+\/apps\/cli\/src\/bin\.ts' credential "\$@"\n$/u.test(572+ credential573+ ),574+ modes,575+ }).toStrictEqual({576+ cli: true,577+ config: "Directory",578+ credential: true,579+ modes: ["755", "755"],580+ });581+582+ expect(spawned).toStrictEqual([583+ {584+ args: [585+ "clone",586+ "--config",587+ `credential.${platformUrl}.helper=`,588+ "--config",589+ `credential.${platformUrl}.helper=${helper}`,590+ "--config",591+ `credential.${platformUrl}.useHttpPath=true`,592+ "--config",593+ "user.name=wren",594+ "--config",595+ "user.email=wren@example.com",596+ "--config",597+ "commit.gpgsign=false",598+ "--",599+ wrensClaim.remote,600+ `${dir}/clone`,601+ ],602+ command: "git",603+ cwd: dir,604+ env: made.env,605+ },606+ ]);607+ expect(608+ [cli, credential, ...spawned.flatMap(({ args }) => args)].filter(609+ (text) => text.includes(wrensToken)610+ )611+ ).toStrictEqual([]);612+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))613+ );614+615+ it.effect(616+ "fails SwarmFailed when the clone fails, naming the fork and never the token",617+ () =>618+ Effect.gen(function* () {619+ const { workspace } = yield* wrensWorkspace(128);620+621+ const { _tag, reason } = Option.getOrThrow(622+ Result.getFailure(workspace)623+ );624+625+ expect(_tag).toBe("SwarmFailed");626+ expect(reason).toContain(wrensClaim.remote);627+ expect(reason).not.toContain(wrensToken);628+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))629+ );630+});631+632+describe("the run's summary", () => {633+ it.effect(634+ "writes the run's summary to <run>/agents.json, and it decodes as AgentsResult",635+ () =>636+ Effect.gen(function* () {637+ const fs = yield* FileSystem.FileSystem;638+ const swarm = yield* fs.makeTempDirectoryScoped();639+640+ const result = yield* Schema.decodeEffect(AgentsResult)({641+ at: "2026-10-08T12:00:00.000Z",642+ commit: "d7064cb0000000000000000000000000000000000",643+ project: "burrow",644+ runs: [645+ {646+ adapter: false,647+ ask: "drop-legacy-fetch-burrow-auth",648+ attempts: 3,649+ durationMs: 412_000,650+ handle: "wren",651+ harness: "claude-code",652+ landed: "9998ebe62c2f282d148b1d806372484916cc2548",653+ model: "claude-opus-5-5",654+ outcome: "landed",655+ refusals: { OutOfScope: 1, StaleBase: 1 },656+ },657+ {658+ adapter: true,659+ ask: "drop-legacy-fetch-burrow-search",660+ attempts: 0,661+ durationMs: 0,662+ handle: "pell",663+ harness: "pi",664+ model: "opencode/gemini-3.8-flash",665+ outcome: "failed",666+ refusals: {},667+ },668+ ],669+ scenario: "plain",670+ stage: "dev-oscabriel",671+ v: 1,672+ });673+674+ yield* writeAgentsResult({ result, run: "r1" }).pipe(675+ Effect.provideService(SwarmDir, swarm)676+ );677+678+ const written = yield* fs.readFileString(`${swarm}/r1/agents.json`);679+680+ expect(681+ yield* Schema.decodeEffect(Schema.fromJsonString(AgentsResult))(682+ written683+ )684+ ).toStrictEqual(result);685+ expect(written.at(-1)).toBe("\n");686+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))687+ );688+});689+690+/** Why the flags `argv` make no run. */691+const reasonOf = (argv: readonly string[]) =>692+ optionsOf(argv).pipe(693+ Effect.flip,694+ Effect.map(({ reason }) => reason)695+ );696+697+describe("the swarm's flags", () => {698+ it.effect(699+ "takes burrow, plain, headless and 20 minutes when nothing else is named",700+ () =>701+ Effect.gen(function* () {702+ const options = yield* optionsOf([703+ "--stage",704+ "dev-oscabriel",705+ "--dry-run",706+ ]);707+708+ expect(options).toStrictEqual({709+ dryRun: true,710+ json: false,711+ only: [],712+ project: "burrow",713+ scenario: "plain",714+ stage: "dev-oscabriel",715+ timeoutMin: 20,716+ url: Option.none(),717+ });718+ })719+ );720+721+ it.effect(722+ "reads --only as one or more handles from the roster, repeated or comma-separated",723+ () =>724+ Effect.gen(function* () {725+ const options = yield* optionsOf([726+ "--stage=dev-oscabriel",727+ "--only",728+ "wren",729+ "pell",730+ "--only=ivo,tamsin",731+ "--scenario",732+ "video",733+ "--timeout-min",734+ "5",735+ ]);736+737+ expect([738+ options.only,739+ options.scenario,740+ options.timeoutMin,741+ ]).toStrictEqual([["wren", "pell", "ivo", "tamsin"], "video", 5]);742+ expect(743+ yield* reasonOf(["--stage", "dev-oscabriel", "--only", "quickclaim"])744+ ).toContain("not in the roster");745+ })746+ );747+748+ it.effect(749+ "refuses demo without --allow-demo, the herdr view until 717, no stage, and a flag it doesn't know",750+ () =>751+ Effect.gen(function* () {752+ const reasons = yield* Effect.forEach(753+ [754+ ["--stage", "demo", "--dry-run"],755+ ["--stage", "dev-oscabriel", "--view", "herdr"],756+ ["--dry-run"],757+ ["--stage", "dev-oscabriel", "--yes"],758+ ["--stage", "dev-oscabriel", "--timeout-min", "0"],759+ ],760+ reasonOf761+ );762+763+ expect(764+ reasons.map((reason, at) =>765+ reason.includes(766+ [767+ "--allow-demo",768+ "717",769+ "no --stage",770+ "unknown flag --yes",771+ "--timeout-min 0",772+ ][at] ?? "?"773+ )774+ )775+ ).toStrictEqual([true, true, true, true, true]);776+ expect(777+ (yield* optionsOf(["--stage", "demo", "--allow-demo"])).stage778+ ).toBe("demo");779+ })780+ );781+});782+783+/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */784+const dryRun = (argv: readonly string[]) =>785+ Effect.gen(function* () {786+ const fs = yield* FileSystem.FileSystem;787+ const swarm = yield* fs.makeTempDirectoryScoped();788+ const listed = yield* fixture("list-asks.json");789+790+ const fake = yield* fakeSpawner(({ args }) =>791+ args[1] === "asks" ? { stdout: listed } : { code: 1 }792+ );793+794+ const printed: string[] = [];795+796+ const captured: Console.Console = {797+ ...console,798+ error: () => {},799+ log: (...args: readonly unknown[]) => {800+ printed.push(args.map(String).join(" "));801+ },802+ };803+804+ yield* main(argv).pipe(805+ Effect.provide(fake.layer),806+ Effect.provideService(SwarmDir, swarm),807+ Effect.provideService(Console.Console, captured),808+ // No SESSION_TOKENS, nor any token: a dry run needs none.809+ Effect.provideService(810+ ConfigProvider.ConfigProvider,811+ ConfigProvider.fromEnv({ env: {} })812+ )813+ );814+815+ return {816+ made: yield* fs.readDirectory(swarm),817+ printed,818+ spawned: yield* fake.spawned,819+ };820+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));821+822+describe("the dry run", () => {823+ const url = platformUrl;824+825+ it.effect(826+ "prints the plan as a table, each row ending in the command that would start that contributor, and only lists asks, anonymously",827+ () =>828+ Effect.gen(function* () {829+ const { made, printed, spawned } = yield* dryRun([830+ "--stage",831+ "dev-oscabriel",832+ "--project",833+ "burrow",834+ "--dry-run",835+ "--url",836+ url,837+ ]);838+839+ expect(printed.slice(0, 2)).toStrictEqual([840+ `swarm: burrow on dev-oscabriel (${url}), scenario plain, 6 contributors`,841+ expect.stringMatching(842+ /^handle +harness +model +ask +territory +command$/u843+ ),844+ ]);845+846+ const rows = printed.slice(2, 8);847+848+ expect(rows.map((row) => row.split(/ +/u).slice(0, 5))).toStrictEqual([849+ [850+ "wren",851+ "claude-code",852+ "claude-opus-5-5",853+ children[0],854+ "@burrow/auth",855+ ],856+ [857+ "tamsin",858+ "opencode",859+ "openai/gpt-6.1-sol",860+ children[1],861+ "@burrow/billing",862+ ],863+ ["ivo", "amp", "medium", children[2], "@burrow/catalog"],864+ ["marisol", "pi", "opencode-go/kimi-k3", children[3], "@burrow/kit"],865+ ["dagny", "pi", "opencode-go/glm-5.3", children[4], "@burrow/notify"],866+ [867+ "pell",868+ "pi",869+ "opencode/gemini-3.8-flash",870+ children[5],871+ "@burrow/search",872+ ],873+ ]);874+ expect([rows[0], rows[5], ...printed.slice(8)]).toStrictEqual([875+ expect.stringContaining(876+ "/<run>/wren/clone' && claude -p --output-format stream-json --verbose --permission-mode bypassPermissions --model claude-opus-5-5 '<brief>'"877+ ),878+ expect.stringMatching(879+ / pi -p --mode json .* -e \S+\/apps\/cli\/src\/pi\.ts '<brief>'$/u880+ ),881+ "held: drop-legacy-fetch, drop-legacy-fetch-delete",882+ "dry run: nothing claimed, no harness started",883+ ]);884+ expect(885+ spawned.map(({ args, env }) => ({886+ args: args.slice(1),887+ token: Object.hasOwn(env, `${SLUG}_TOKEN`)888+ ? env[`${SLUG}_TOKEN`]889+ : "inherited",890+ url: env[`${SLUG}_URL`],891+ }))892+ ).toStrictEqual([893+ {894+ args: ["asks", "--project", "burrow", "--json"],895+ token: undefined,896+ url,897+ },898+ ]);899+ expect(made).toStrictEqual([]);900+ })901+ );902+903+ it.effect(904+ "prints one decodable SwarmPlan with --json, and the video scenario's nudges in plain sight without it",905+ () =>906+ Effect.gen(function* () {907+ const { printed } = yield* dryRun([908+ "--stage",909+ "dev-oscabriel",910+ "--dry-run",911+ "--json",912+ "--url",913+ url,914+ ]);915+916+ expect(printed).toHaveLength(1);917+918+ const decoded = yield* Schema.decodeEffect(919+ Schema.fromJsonString(SwarmPlan)920+ )(printed[0] ?? "");921+922+ expect(decoded.assignments.map(({ ask }) => ask)).toStrictEqual(923+ children924+ );925+926+ const video = yield* dryRun([927+ "--stage",928+ "dev-oscabriel",929+ "--dry-run",930+ "--scenario",931+ "video",932+ "--url",933+ url,934+ ]);935+936+ expect(937+ video.printed.filter((line) => line.startsWith("nudge for "))938+ ).toStrictEqual([939+ `nudge for tamsin (video): ${Option.getOrThrow(nudges("video", 1))}`,940+ `nudge for ivo (video): ${Option.getOrThrow(nudges("video", 2))}`,941+ ]);942+ })943+ );944+});945+946+/** A fictional person's token on the fake platform: never printed, never in an argv. */947+const tokenOf = (handle: string) =>948+ `${handle}-token-0123456789abcdef0123456789ab`;949+950+/**951+ * `main` without `--dry-run`, over a fake platform: the CLI's `asks`, `ask`952+ * and `claim` answer from the fixtures, git succeeds, and `SESSION_TOKENS`953+ * holds `people`. The ledger and `.swarm/` are temp files.954+ */955+const fullRun = (people: readonly string[]) =>956+ Effect.gen(function* () {957+ const fs = yield* FileSystem.FileSystem;958+ const swarm = yield* fs.makeTempDirectoryScoped();959+ const ledger = `${swarm}/created.jsonl`;960+ const listed = yield* fixture("list-asks.json");961+962+ const shown = (yield* fixture("show-ask.json")).replaceAll(963+ "{configDir}",964+ Brand.configDir965+ );966+967+ const claimFor = (ask: string, token: string | undefined) => {968+ const handle = roster.find(969+ (one) => tokenOf(one.handle) === token970+ )?.handle;971+972+ const fork = `burrow--${ask}--${handle ?? "nobody"}`;973+974+ return JSON.stringify({975+ command: "claim",976+ data: {977+ claim: {978+ ask,979+ base: "9998ebe62c2f282d148b1d806372484916cc2548",980+ checkCommand: `${Brand.cli} check`,981+ claimant: handle,982+ fork,983+ lapsesAt: "2026-10-09T05:00:00.000Z",984+ openedAt: "2026-10-08T05:00:00.000Z",985+ project: "burrow",986+ remote: `${platformUrl}/${fork}.git`,987+ state: "live",988+ warnsAt: "2026-10-08T17:00:00.000Z",989+ },990+ },991+ ok: true,992+ v: 1,993+ });994+ };995+996+ const fake = yield* fakeSpawner(({ args, command, env }) => {997+ if (command === "git") {998+ return args.includes("rev-parse")999+ ? { stdout: "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n" }1000+ : {};1001+ }1002+1003+ const [, verb = "", ask = ""] = args;1004+1005+ return (1006+ {1007+ ask: { stdout: shown },1008+ asks: { stdout: listed },1009+ claim: { stdout: claimFor(ask, env[`${SLUG}_TOKEN`]) },1010+ }[verb] ?? { code: 1 }1011+ );1012+ });1013+1014+ const printed: string[] = [];1015+1016+ const captured: Console.Console = {1017+ ...console,1018+ error: (...args: readonly unknown[]) => {1019+ printed.push(args.map(String).join(" "));1020+ },1021+ log: (...args: readonly unknown[]) => {1022+ printed.push(args.map(String).join(" "));1023+ },1024+ };1025+1026+ const sessions = Object.fromEntries(1027+ people.map((handle) => [tokenOf(handle), handle])1028+ );1029+1030+ const result = yield* main([1031+ "--stage",1032+ "dev-oscabriel",1033+ "--url",1034+ platformUrl,1035+ ]).pipe(1036+ Effect.provide(fake.layer),1037+ Effect.provideService(SwarmDir, swarm),1038+ Effect.provideService(LedgerFile, ledger),1039+ Effect.provideService(Console.Console, captured),1040+ Effect.provideService(1041+ ConfigProvider.ConfigProvider,1042+ ConfigProvider.fromEnv({1043+ env: { SESSION_TOKENS: JSON.stringify(sessions) },1044+ })1045+ ),1046+ Effect.result1047+ );1048+1049+ // The TestClock's epoch names the run.1050+ const summary = `${swarm}/19700101-000000/agents.json`;1051+1052+ return {1053+ agents: (yield* fs.exists(summary))1054+ ? Option.some(yield* fs.readFileString(summary))1055+ : Option.none<string>(),1056+ ledger: yield* readLedger.pipe(Effect.provideService(LedgerFile, ledger)),1057+ printed,1058+ result,1059+ spawned: yield* fake.spawned,1060+ };1061+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));1062+1063+describe("a run", () => {1064+ it.effect(1065+ "claims each ask as its contributor, records each fork for teardown, prepares six workspaces and writes the summary, with no token in any argv or line",1066+ () =>1067+ Effect.gen(function* () {1068+ const handles = roster.map(({ handle }) => handle);1069+1070+ const { agents, ledger, printed, result, spawned } =1071+ yield* fullRun(handles);1072+1073+ expect(Result.isSuccess(result)).toBeTruthy();1074+1075+ const claims = spawned.filter(({ args }) => args[1] === "claim");1076+1077+ // Six at once: in whatever order they ran.1078+ expect(1079+ claims1080+ .map(({ args, env }) => [args[2], env[`${SLUG}_TOKEN`]])1081+ .toSorted(([one = ""], [other = ""]) => one.localeCompare(other))1082+ ).toStrictEqual(1083+ handles.map((handle, at) => [children[at], tokenOf(handle)])1084+ );1085+ expect(1086+ ledger1087+ .map(({ by, kind, name, namespace, stage }) => ({1088+ by,1089+ kind,1090+ name,1091+ namespace,1092+ stage,1093+ }))1094+ .toSorted((one, other) => one.name.localeCompare(other.name))1095+ ).toStrictEqual(1096+ handles.map((handle, at) => ({1097+ by: "swarm",1098+ kind: "repo",1099+ name: `burrow--${children[at] ?? ""}--${handle}`,1100+ namespace: "projects-dev-oscabriel",1101+ stage: "dev-oscabriel",1102+ }))1103+ );1104+1105+ const summary = yield* Schema.decodeEffect(1106+ Schema.fromJsonString(AgentsResult)1107+ )(Option.getOrElse(agents, () => ""));1108+1109+ expect(1110+ summary.runs.map(({ handle, outcome }) => [handle, outcome])1111+ ).toStrictEqual(handles.map((handle) => [handle, "failed"]));1112+ expect(1113+ [...printed, ...spawned.flatMap(({ args }) => args)].filter((text) =>1114+ handles.some((handle) => text.includes(tokenOf(handle)))1115+ )1116+ ).toStrictEqual([]);1117+ })1118+ );1119+1120+ it.effect(1121+ "stops before any claim when SESSION_TOKENS has no session for a contributor, naming them",1122+ () =>1123+ Effect.gen(function* () {1124+ const { result, spawned } = yield* fullRun(1125+ roster.slice(0, 5).map(({ handle }) => handle)1126+ );1127+1128+ expect(1129+ Option.map(Result.getFailure(result), ({ reason }) => reason)1130+ ).toStrictEqual(1131+ Option.some(1132+ "SESSION_TOKENS has no session for pell: add each on the stage (human step H5 on demo), then run the swarm again"1133+ )1134+ );1135+ expect(spawned.map(({ args }) => args[1])).toStrictEqual(["asks"]);1136+ })1137+ );1138+});added:scripts/lib/swarm/args.ts+182 added
1+/**2+ * The swarm's flags, read by a small decoder (the scripts' allow-list grants3+ * `effect/process` only, so no `effect/cli`):4+ *5+ * --stage <s> required: a stage `infra/stages.ts` declares6+ * --project <name> default burrow7+ * --scenario plain|video default plain8+ * --dry-run print the plan; claim nothing, start nothing9+ * --json print JSON: the plan (dry run) or the run's summary10+ * --allow-demo required with --stage demo: its burrow family is the recorded take's11+ * --only <handle>… run only these contributors (repeat, or comma-separate)12+ * --timeout-min <n> each agent's run timeout, default 2013+ * --view headless|herdr default headless; herdr is issue 717's, refused until then14+ * --url <origin> the platform, when not the stage's workers.dev origin15+ */16+import { Handle, ProjectName } from "@repo/protocol/ids";17+import { Effect, Option, Schema } from "effect";18+19+import { flagValue, stageOf } from "../../../infra/stages.ts";20+import type { Stage } from "../../../infra/stages.ts";21+import { roster } from "./roster.ts";22+import { ScenarioName } from "./scenario.ts";23+import { SwarmFailed } from "./workspace.ts";24+25+/** What `bun scripts/swarm.ts` was asked to do. */26+export interface SwarmOptions {27+ readonly stage: Stage;28+ readonly project: ProjectName;29+ readonly scenario: ScenarioName;30+ readonly dryRun: boolean;31+ readonly json: boolean;32+ /** The contributors to run; every one when `--only` names none. */33+ readonly only: readonly Handle[];34+ readonly timeoutMin: number;35+ /** The platform's origin, when `--url` names it. */36+ readonly url: Option.Option<string>;37+}38+39+export const USAGE =40+ "bun scripts/swarm.ts --stage <dev-…|demo> [--project burrow] [--scenario plain|video] [--dry-run] [--json] [--allow-demo] [--only <handle>…] [--timeout-min 20] [--view headless] [--url <origin>]";41+42+/** The flags that take a value. */43+const VALUED = [44+ "--project",45+ "--scenario",46+ "--stage",47+ "--timeout-min",48+ "--url",49+ "--view",50+] as const;51+52+/** The flags that stand alone. */53+const SWITCHES = ["--allow-demo", "--dry-run", "--json"] as const;54+55+const failed = (reason: string) => new SwarmFailed({ reason });56+57+/** The handles `--only` names: each value after each `--only`, comma-separated or not. */58+const onlyOf = (argv: readonly string[]) =>59+ argv.flatMap((arg, at) => {60+ if (arg.startsWith("--only=")) {61+ return arg.slice("--only=".length).split(",");62+ }63+64+ if (arg !== "--only") {65+ return [];66+ }67+68+ const rest = argv.slice(at + 1);69+ const end = rest.findIndex((value) => value.startsWith("--"));70+71+ return (end === -1 ? rest : rest.slice(0, end)).flatMap((value) =>72+ value.split(",")73+ );74+ });75+76+/** The arguments that are flags, with any `=value` cut off. */77+const flagsIn = (argv: readonly string[]) =>78+ argv.flatMap((arg) =>79+ arg.startsWith("--") ? [arg.split("=")[0] ?? arg] : []80+ );81+82+const decodeProject = Schema.decodeUnknownOption(ProjectName);83+84+const decodeScenario = Schema.decodeUnknownOption(ScenarioName);85+86+/** The swarm's options from its arguments, or why they don't make a run. */87+export const optionsOf = (88+ argv: readonly string[]89+): Effect.Effect<SwarmOptions, SwarmFailed> =>90+ Effect.gen(function* () {91+ const known = new Set<string>([...VALUED, ...SWITCHES, "--only"]);92+ const strange = flagsIn(argv).filter((flag) => !known.has(flag));93+94+ if (strange.length > 0) {95+ return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);96+ }97+98+ // infra's own reading of `--stage`, and its words when it names none.99+ const stage = yield* stageOf(argv).pipe(100+ Effect.mapError(({ message }) => failed(`${message}. ${USAGE}`))101+ );102+103+ if (stage === "demo" && !argv.includes("--allow-demo")) {104+ return yield* failed(105+ "--stage demo: its burrow family is for the recorded take (804); run it there only with --allow-demo"106+ );107+ }108+109+ const view = Option.getOrElse(flagValue(argv, "--view"), () => "headless");110+111+ if (view === "herdr") {112+ return yield* failed(113+ "--view herdr is not built yet (issue 717): run --view headless"114+ );115+ }116+117+ if (view !== "headless") {118+ return yield* failed(`--view ${view}: headless or herdr`);119+ }120+121+ const rawProject = Option.getOrElse(122+ flagValue(argv, "--project"),123+ () => "burrow"124+ );125+126+ const project = yield* Effect.fromOption(decodeProject(rawProject)).pipe(127+ Effect.mapError(() => failed(`--project ${rawProject} names no project`))128+ );129+130+ const rawScenario = Option.getOrElse(131+ flagValue(argv, "--scenario"),132+ () => "plain"133+ );134+135+ const scenario = yield* Effect.fromOption(decodeScenario(rawScenario)).pipe(136+ Effect.mapError(() => failed(`--scenario ${rawScenario}: plain or video`))137+ );138+139+ const rawTimeout = Option.getOrElse(140+ flagValue(argv, "--timeout-min"),141+ () => "20"142+ );143+144+ const timeoutMin = Number(rawTimeout);145+146+ if (!Number.isInteger(timeoutMin) || timeoutMin < 1) {147+ return yield* failed(148+ `--timeout-min ${rawTimeout}: a whole number of minutes, 1 or more`149+ );150+ }151+152+ const named = onlyOf(argv).filter((handle) => handle !== "");153+154+ const only = yield* Effect.forEach(named, (handle) =>155+ Effect.fromNullishOr(156+ roster.find((contributor) => contributor.handle === handle)?.handle157+ ).pipe(158+ Effect.mapError(() =>159+ failed(160+ `--only ${handle} is not in the roster: ${roster.map((contributor) => contributor.handle).join(", ")}`161+ )162+ )163+ )164+ );165+166+ if (argv.includes("--only") && only.length === 0) {167+ return yield* failed("--only names no contributor");168+ }169+170+ return {171+ dryRun: argv.includes("--dry-run"),172+ json: argv.includes("--json"),173+ only: [...new Set(only)].map((handle) => Handle.make(handle)),174+ project,175+ scenario,176+ stage,177+ timeoutMin,178+ url: Option.map(flagValue(argv, "--url"), (url) =>179+ url.replace(/\/+$/u, "")180+ ),181+ };182+ });added:scripts/lib/swarm/loop.ts+115 added
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.6+ */7+import { Console, Effect, Match } from "effect";8+import type { FileSystem } from "effect";9+import type { ChildProcessSpawner } from "effect/process";10+11+import type { Assignment } from "./plan.ts";12+import type { AgentRun } from "./results.ts";13+import type { Contributor } from "./roster.ts";14+import type { AgentWorkspace } from "./workspace.ts";15+16+/** One contributor's run: their harness on the brief, then the verdict loop. */17+export type RunAgent = (input: {18+ readonly assignment: Assignment;19+ readonly workspace: AgentWorkspace;20+ readonly brief: string;21+ readonly maxContinuations: 3;22+ readonly timeoutMs: number;23+}) => Effect.Effect<24+ AgentRun,25+ never,26+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem27+>;28+29+/** Not built (711): says so, starts nothing, and records the run as `failed`. */30+export const runAgent: RunAgent = ({ assignment }) =>31+ Effect.gen(function* () {32+ const { adapter, handle, harness, model } = assignment.contributor;33+34+ yield* Console.error(`${handle}: not built: 711`);35+36+ return {37+ adapter,38+ ask: assignment.ask,39+ attempts: 0,40+ durationMs: 0,41+ handle,42+ harness,43+ model,44+ outcome: "failed",45+ refusals: {},46+ };47+ });48+49+/** The CLI's pi adapter (issue 706), which the adapter's agent loads with `-e`. */50+const piAdapter = decodeURIComponent(51+ new URL("../../../apps/cli/src/pi.ts", import.meta.url).pathname52+);53+54+/**55+ * 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).60+ */61+export const startCommand = (input: {62+ readonly contributor: Contributor;63+ readonly brief: string;64+ readonly dir: string;65+}): readonly string[] => {66+ const { adapter, handle, harness, model } = input.contributor;67+68+ return Match.value(harness).pipe(69+ Match.when("claude-code", () => [70+ "claude",71+ "-p",72+ "--output-format",73+ "stream-json",74+ "--verbose",75+ "--permission-mode",76+ "bypassPermissions",77+ "--model",78+ model,79+ input.brief,80+ ]),81+ Match.when("opencode", () => [82+ "opencode",83+ "run",84+ "--format",85+ "json",86+ "--auto",87+ "-m",88+ model,89+ input.brief,90+ ]),91+ Match.when("amp", () => [92+ "amp",93+ "-x",94+ input.brief,95+ "--stream-json",96+ "-m",97+ model,98+ ]),99+ Match.when("pi", () => [100+ "pi",101+ "-p",102+ "--mode",103+ "json",104+ "--session-dir",105+ `${input.dir}/sessions`,106+ "--session-id",107+ handle,108+ "--model",109+ model,110+ ...(adapter ? ["-e", piAdapter] : []),111+ input.brief,112+ ]),113+ Match.exhaustive114+ );115+};added:scripts/lib/swarm/plan.ts+129 added
1+/**2+ * The swarm's plan: which contributor answers which ask. It takes a3+ * project's open asks as `listAsks` shows them, and hands each contributor,4+ * in roster order, one open, unclaimed, unblocked ask, in `AskId` order, on5+ * a territory no other assignment shares. Asks still blocked (a migrate6+ * family's delete child, and its parent) are held.7+ */8+import type { AskListing } from "@repo/protocol/domain/ask";9+import { AskId, ProjectName } from "@repo/protocol/ids";10+import type { Refusal } from "@repo/protocol/refusal";11+import { Array, Order, Result, Schema } from "effect";12+13+import { Contributor } from "./roster.ts";14+import { ScenarioName } from "./scenario.ts";15+16+/** One contributor's ask, and the territory (module) it may change. */17+export const Assignment = Schema.Struct({18+ ask: AskId,19+ contributor: Contributor,20+ territory: Schema.NonEmptyString,21+});22+23+export type Assignment = typeof Assignment.Type;24+25+/** The plan for one run: its assignments, and the asks it holds back. */26+export const SwarmPlan = Schema.Struct({27+ assignments: Schema.Array(Assignment),28+ /** Open asks still blocked by others: a migrate family's delete child, say. */29+ held: Schema.Array(AskId),30+ project: ProjectName,31+ scenario: ScenarioName,32+ stage: Schema.NonEmptyString,33+});34+35+export type SwarmPlan = typeof SwarmPlan.Type;36+37+/** Fewer asks can be handed out than the roster has contributors. */38+export class NotEnoughAsks extends Schema.TaggedError<NotEnoughAsks>()(39+ "NotEnoughAsks",40+ { open: Schema.Int, wanted: Schema.Int }41+) {42+ override get message() {43+ return `${this.wanted} contributors, but only ${this.open} open, unclaimed, unblocked asks on disjoint territories`;44+ }45+}46+47+/**48+ * The refusals that end a contributor's claim, so the verdict loop (711)49+ * stops on them. It bounces every other refusal back into the same session:50+ * `retryable: true` means only that the same push may pass if sent again51+ * (`StaleBase`, `RepoBusy`, `Flake`), while `OutOfScope`, `Weakened` and52+ * `ChecksFailed` (`retryable: false`) are exactly what an agent fixes.53+ */54+export const endsClaim: ReadonlySet<Refusal["_tag"]> = new Set([55+ "AskFull",56+ "AttemptsExhausted",57+ "ClaimLapsed",58+ "Denounced",59+ "NotClaimed",60+ "NotVouched",61+] as const satisfies readonly Refusal["_tag"][]);62+63+/** The whole repo as a territory: it overlaps every other one. */64+const WHOLE_REPO = ".";65+66+/**67+ * Whether two asks' territories overlap: the same module, or either one68+ * the whole repo. A listing names only the module, so two modules that are69+ * not the same are taken as disjoint (each is one workspace package).70+ */71+const overlaps = (one: string, other: string) =>72+ one === other || one === WHOLE_REPO || other === WHOLE_REPO;73+74+/**75+ * Plans a run: each contributor in `roster`, in roster order, gets one open,76+ * unclaimed and unblocked ask, taken in `AskId` order, whose territory77+ * overlaps no ask already handed out. An ask is blocked while any ask it78+ * waits on is still listed (`listAsks` lists every ask not closed); blocked79+ * asks are held. With fewer asks to hand out than contributors, the plan80+ * fails `NotEnoughAsks`, counting the asks it could hand out.81+ */82+export const planSwarm = (input: {83+ readonly roster: readonly Contributor[];84+ readonly asks: readonly AskListing[];85+ readonly stage: string;86+ readonly project: ProjectName;87+ readonly scenario: ScenarioName;88+}): Result.Result<SwarmPlan, NotEnoughAsks> => {89+ const listed = new Set<string>(input.asks.map(({ ask }) => ask));90+91+ const blocked = ({ blockedBy }: AskListing) =>92+ blockedBy.some((waitsOn) => listed.has(waitsOn));93+94+ const unclaimed = Array.sort(95+ input.asks.filter(({ claimed }) => !claimed),96+ Order.mapInput(Order.String, ({ ask }: AskListing) => ask)97+ );98+99+ const held = unclaimed.filter(blocked);100+ const open = unclaimed.filter((listing) => !blocked(listing));101+102+ const disjoint: AskListing[] = [];103+104+ for (const listing of open) {105+ if (106+ !disjoint.some(({ territory }) => overlaps(territory, listing.territory))107+ ) {108+ disjoint.push(listing);109+ }110+ }111+112+ const wanted = input.roster.length;113+114+ if (disjoint.length < wanted) {115+ return Result.fail(new NotEnoughAsks({ open: disjoint.length, wanted }));116+ }117+118+ return Result.succeed({119+ assignments: Array.zipWith(120+ input.roster,121+ disjoint,122+ (contributor, { ask, territory }) => ({ ask, contributor, territory })123+ ),124+ held: held.map(({ ask }) => ask),125+ project: input.project,126+ scenario: input.scenario,127+ stage: input.stage,128+ });129+};added:scripts/lib/swarm/prompt.ts+42 added
123456789101112131415161718192021222324252627282930313233343536373839404142/** * The brief each contributor's harness starts with. It is zero-install: it * says only what a contributor gets from the ask's page and the project's * AGENTS.md (where their clone is, make the check pass, push, read the * verdict with `<cli> status`), and nothing about how the platform judges * an answer. */import { Brand } from "@repo/brand";import type { AskId, ProjectName } from "@repo/protocol/ids";import { Option } from "effect";
/** The brief for one contributor's ask: the ask's page between what to do. */export const brief = (input: { readonly ask: AskId; readonly project: ProjectName; readonly remote: string; readonly askMarkdown: string; readonly nudge: Option.Option<string>;}): string => [ `You have claimed the ask \`${input.ask}\` in the project ${input.project}. Answer it.`, "", `The current directory is your clone of ${input.remote}, the fork your claim gave you. Push your answer there.`, "", "---", "", input.askMarkdown.trimEnd(), "", "---", "", "How to answer:", "", "1. Read the project's AGENTS.md, then the ask above.", `2. Change only files in the ask's territory, and make its check pass: \`${Brand.cli} check\` runs the project's checks here, before you push.`, "3. Commit, then `git push` to origin.", `4. Run \`${Brand.cli} status --project ${input.project}\` for the verdict. A refusal says what is wrong and what to run next: fix it, commit and push again.`, ...Option.match(input.nudge, { onNone: () => [], onSome: (nudge) => ["", `Note: ${nudge}`], }), "", ].join("\n");added:scripts/lib/swarm/results.ts+108 added
1+/**2+ * The swarm run's summary: one `AgentRun` per contributor, written to3+ * `.swarm/<run>/agents.json` (gitignored). A live issue records what a run4+ * shows in its own notes; nothing here is committed.5+ *6+ * Every field follows the wire rule (AGENTS.md "Effect traps"): `Schema.Int`7+ * or `Schema.Finite` for numbers, `Schema.optionalKey` for optional keys.8+ */9+import { Context, Effect, FileSystem, Schema } from "effect";10+import type { PlatformError } from "effect";11+12+/**13+ * The swarm's folder, `.swarm/` at the repo root (beside `scripts/`), unless14+ * a test points it elsewhere. Each run writes below it: `<run>/agents.json`15+ * and one workspace per contributor, `<run>/<handle>/`.16+ */17+export const SwarmDir = Context.Reference<string>("swarm/SwarmDir", {18+ defaultValue: () =>19+ decodeURIComponent(new URL("../../../.swarm", import.meta.url).pathname),20+});21+22+/** A run's own folder: `.swarm/<run>`. */23+export const runDir = (run: string) =>24+ Effect.map(SwarmDir, (dir) => `${dir}/${run}`);25+26+/** The four harnesses a swarm contributor may run. */27+export const Harness = Schema.Literals([28+ "claude-code",29+ "opencode",30+ "amp",31+ "pi",32+]);33+34+export type Harness = typeof Harness.Type;35+36+/**37+ * How one contributor's run ended: its answer landed, was refused (and the38+ * continuations ran out), waits on a person (`AwaitingFinish`,39+ * `AwaitingDecision`), was never pushed, ran past its timeout, or the run40+ * itself failed (a claim refused, a harness that did not start).41+ */42+export const AgentOutcome = Schema.Literals([43+ "landed",44+ "refused",45+ "waiting",46+ "noAnswer",47+ "timedOut",48+ "failed",49+]);50+51+export type AgentOutcome = typeof AgentOutcome.Type;52+53+/** One contributor's run. */54+export const AgentRun = Schema.Struct({55+ adapter: Schema.Boolean,56+ ask: Schema.NonEmptyString,57+ /** Harness sessions started or resumed: the first run and each continuation. */58+ attempts: Schema.Int,59+ durationMs: Schema.Int,60+ handle: Schema.NonEmptyString,61+ harness: Harness,62+ /** The landing commit, when the answer landed. */63+ landed: Schema.optionalKey(Schema.NonEmptyString),64+ model: Schema.NonEmptyString,65+ outcome: AgentOutcome,66+ /** Each refusal's `_tag`, with how often it came back across the attempts. */67+ refusals: Schema.Record(Schema.String, Schema.Int),68+});69+70+export type AgentRun = typeof AgentRun.Type;71+72+/** A whole run: where it ran, from which commit, and each contributor's run. */73+export const AgentsResult = Schema.Struct({74+ at: Schema.DateTimeUtcFromString,75+ /** The commit of this repo the swarm ran from. */76+ commit: Schema.NonEmptyString,77+ project: Schema.NonEmptyString,78+ runs: Schema.Array(AgentRun),79+ scenario: Schema.NonEmptyString,80+ stage: Schema.NonEmptyString,81+ v: Schema.Literal(1),82+});83+84+export type AgentsResult = typeof AgentsResult.Type;85+86+/** The file a run's summary is written to, below the swarm's folder. */87+export const agentsFile = (dir: string) => `${dir}/agents.json`;88+89+/** Writes `result` to `.swarm/<run>/agents.json`, as indented JSON. */90+export const writeAgentsResult = (input: {91+ readonly run: string;92+ readonly result: AgentsResult;93+}): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> =>94+ Effect.gen(function* () {95+ const fs = yield* FileSystem.FileSystem;96+ const dir = yield* runDir(input.run);97+98+ // An `AgentsResult` value always encodes: strings, numbers and a DateTime.99+ const encoded = yield* Schema.encodeEffect(AgentsResult)(input.result).pipe(100+ Effect.orDie101+ );102+103+ yield* fs.makeDirectory(dir, { recursive: true });104+ yield* fs.writeFileString(105+ agentsFile(dir),106+ `${JSON.stringify(encoded, null, 2)}\n`107+ );108+ });added:scripts/lib/swarm/roster.ts+85 added
1+/**2+ * The swarm's six fictional contributors: "4 harnesses, 6 models" (SYN Q28).3+ * Each is one person (a `SESSION_TOKENS` entry on the stage, spec D9) with4+ * one harness and one model, vouched in burrow's `vouched.td`, so their5+ * claims are not `NotVouched`.6+ *7+ * The model ids are what this machine's harnesses list (2026-10-08):8+ * `opencode models` for OpenCode's GPT model and OpenCode Zen's Gemini flash,9+ * `pi --offline --list-models` for pi's (its ready provider is `opencode-go`),10+ * `amp --help` for Amp's modes.11+ */12+import { Handle } from "@repo/protocol/ids";13+import { Schema } from "effect";14+15+import { Harness } from "./results.ts";16+17+/** One contributor: a person, the harness they run, and its model. */18+export const Contributor = Schema.Struct({19+ /** True only for the pi agent that loads the CLI's pi adapter (`-e`). */20+ adapter: Schema.Boolean,21+ /** A fictional person: a key of the stage's `SESSION_TOKENS` (human step H5 on demo). */22+ handle: Handle,23+ harness: Harness,24+ /**25+ * Claude Code: an Anthropic model id. OpenCode: `openai/<gpt id>`. Amp: its26+ * mode. pi: `<provider>/<id>`.27+ */28+ model: Schema.NonEmptyString,29+});30+31+export type Contributor = typeof Contributor.Type;32+33+/**34+ * The six, in the order the plan hands them asks. Contributor 2 (tamsin)35+ * and 3 (ivo) are the ones the `video` scenario nudges (`scenario.ts`).36+ */37+export const roster: readonly [38+ Contributor,39+ Contributor,40+ Contributor,41+ Contributor,42+ Contributor,43+ Contributor,44+] = [45+ // The "stock harness, nothing installed" beat.46+ {47+ adapter: false,48+ handle: Handle.make("wren"),49+ harness: "claude-code",50+ model: "claude-opus-5-5",51+ },52+ {53+ adapter: false,54+ handle: Handle.make("tamsin"),55+ harness: "opencode",56+ model: "openai/gpt-6.1-sol",57+ },58+ {59+ adapter: false,60+ handle: Handle.make("ivo"),61+ harness: "amp",62+ model: "medium",63+ },64+ {65+ adapter: false,66+ handle: Handle.make("marisol"),67+ harness: "pi",68+ model: "opencode-go/kimi-k3",69+ },70+ {71+ adapter: false,72+ handle: Handle.make("dagny"),73+ harness: "pi",74+ model: "opencode-go/glm-5.3",75+ },76+ // The tier-2 beat: the pi adapter's brief, scope guard and verdict gate.77+ // OpenCode Zen's provider (`opencode/…`) needs its key in pi on the78+ // machine that runs it (pi reports it not configured here).79+ {80+ adapter: true,81+ handle: Handle.make("pell"),82+ harness: "pi",83+ model: "opencode/gemini-3.8-flash",84+ },85+];added:scripts/lib/swarm/scenario.ts+38 added
1234567891011121314151617181920212223242526272829303132333435363738/** * Scenarios: the nudges the swarm adds to some contributors' briefs, so a * recorded take shows the refusals the video's beat names (1:30–2:15; 713 * documents them). `plain` nudges nobody. Every nudge is printed in the * plan: staging is never hidden. */import { Option, Schema } from "effect";
/** The swarm's scenarios. */export const ScenarioName = Schema.Literals(["plain", "video"]);
export type ScenarioName = typeof ScenarioName.Type;
/** * The `video` scenario's nudges, by roster position (0-based): contributor * 2 is told a disable comment is fine (expect `Weakened{marker}` for one with * no reason); contributor 3 is told a disable comment carries its reason * after ` -- ` (expect `AwaitingDecision`). */const videoNudges: ReadonlyMap<number, string> = new Map([ [ 1, "The project's lint rule against module-level mutable state is noisy. If it gets in your way, a lint disable comment on the line is acceptable.", ], [ 2, "If you need a lint disable comment, it must carry its reason after ` -- ` on the same line, for example `// oxlint-disable-next-line <rule> -- <why>`.", ],]);
/** The nudge `scenario` adds to the brief of the contributor at roster position `index`, if any. */export const nudges = ( scenario: ScenarioName, index: number): Option.Option<string> => scenario === "video" ? Option.fromUndefinedOr(videoNudges.get(index)) : Option.none();added:scripts/lib/swarm/workspace.ts+277 added
1+/**2+ * One contributor's workspace: `.swarm/<run>/<handle>/`, with their clone of3+ * the claim's fork, a `bin/` that puts this repo's CLI (and git's credential4+ * helper) on `PATH`, their own config folder, and the env their harness runs5+ * in. The person's platform token reaches the harness only through that env,6+ * as `<SLUG>_TOKEN`, never in a file, an argv or a URL.7+ */8+import { Brand } from "@repo/brand";9+import type { ClaimView } from "@repo/protocol/domain/claim";10+import { Config, Effect, FileSystem, Redacted, Schema, Stream } from "effect";11+import { ChildProcess, ChildProcessSpawner } from "effect/process";12+13+import { runDir } from "./results.ts";14+import type { Contributor } from "./roster.ts";15+16+/** The swarm could not do a step; the reason says which, and never holds a token. */17+export class SwarmFailed extends Schema.TaggedError<SwarmFailed>()(18+ "SwarmFailed",19+ { reason: Schema.String }20+) {21+ override get message() {22+ return this.reason;23+ }24+}25+26+/** Where one contributor works, and the env their harness runs in. */27+export interface AgentWorkspace {28+ /** `.swarm/<run>/<handle>`. */29+ readonly dir: string;30+ /** Their clone of the claim's fork: the harness's working directory. */31+ readonly clone: string;32+ readonly env: Readonly<Record<string, string>>;33+ /** The env names whose values are secret: never logged, never printed. */34+ readonly redacted: readonly string[];35+}36+37+/** The env names the CLI reads, spelled from the brand (`apps/cli/src/credentials.ts`). */38+const SLUG = Brand.slug.toUpperCase();39+40+/** The person's platform token: the only identity the CLI and git present. */41+export const TOKEN_VARIABLE = `${SLUG}_TOKEN`;42+43+/** The platform the CLI calls, with the token or, without one, as anyone. */44+export const URL_VARIABLE = `${SLUG}_URL`;45+46+/** The profile the CLI would read instead of the env's token. */47+const PROFILE_VARIABLE = `${SLUG}_PROFILE`;48+49+/** The CLI's process entry in this repo, run from source with Bun. */50+export const cliEntry = decodeURIComponent(51+ new URL("../../../apps/cli/src/bin.ts", import.meta.url).pathname52+);53+54+/** A one-word shell argument: `'…'`, with any `'` inside closed and escaped. */55+export const shellQuoted = (word: string) =>56+ /^[\w./:@%+=,-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;57+58+/** A shim in `bin/`: a shell script that runs the CLI from source with `args` first. */59+const shim = (what: string, args: readonly string[]) =>60+ [61+ "#!/bin/sh",62+ `# ${what} for one swarm contributor: this repo's CLI from source, under Bun.`,63+ `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' ${[...args.map(shellQuoted), '"$@"'].join(" ")}`,64+ "",65+ ].join("\n");66+67+/** Owner, group and everyone may run a shim; only the owner writes it. */68+const SHIM_MODE = 0o755;69+70+/** The workspace's config folder holds the CLI's credentials: owner only. */71+const CONFIG_MODE = 0o700;72+73+/**74+ * The env a CLI call runs in as a person: their token and the platform, and75+ * a config folder of their own, so no stored profile of the user's answers76+ * instead.77+ */78+export const personEnv = (input: {79+ readonly configHome: string;80+ readonly platformUrl: string;81+ readonly token: Redacted.Redacted;82+}) => ({83+ [TOKEN_VARIABLE]: Redacted.value(input.token),84+ [URL_VARIABLE]: input.platformUrl,85+ XDG_CONFIG_HOME: input.configHome,86+});87+88+/**89+ * The env a CLI call runs in as anyone: the platform, a config folder that90+ * holds no profile, and no token or profile from the shell the swarm runs in.91+ */92+export const anonymousEnv = (input: {93+ readonly configHome: string;94+ readonly platformUrl: string;95+}) => ({96+ [PROFILE_VARIABLE]: undefined,97+ [TOKEN_VARIABLE]: undefined,98+ [URL_VARIABLE]: input.platformUrl,99+ XDG_CONFIG_HOME: input.configHome,100+});101+102+/** `text` with every secret value of `env` (the names in `redacted`) blanked out. */103+export const scrubbed = (104+ text: string,105+ workspace: Pick<AgentWorkspace, "env" | "redacted">106+) => {107+ let clean = text;108+109+ for (const name of workspace.redacted) {110+ const secret = workspace.env[name];111+112+ if (secret !== undefined && secret !== "") {113+ clean = clean.replaceAll(secret, "<redacted>");114+ }115+ }116+117+ return clean;118+};119+120+/** All a byte stream says, as text. */121+const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>122+ bytes.pipe(Stream.decodeText(), Stream.mkString);123+124+/** How a process ended, and what it printed. */125+export interface Ran {126+ readonly code: number;127+ readonly stdout: string;128+ readonly stderr: string;129+}130+131+/** `command args` in `cwd` with `env` over the swarm's own: how it ended, and what it printed. */132+export const run = (input: {133+ readonly command: string;134+ readonly args: readonly string[];135+ readonly cwd?: string;136+ readonly env: Readonly<Record<string, string | undefined>>;137+}): Effect.Effect<Ran, SwarmFailed, ChildProcessSpawner.ChildProcessSpawner> =>138+ Effect.scoped(139+ Effect.gen(function* () {140+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;141+142+ const child = yield* spawner.spawn(143+ ChildProcess.make(input.command, input.args, {144+ cwd: input.cwd,145+ env: { ...input.env },146+ extendEnv: true,147+ })148+ );149+150+ const [stdout, stderr, code] = yield* Effect.all(151+ [streamText(child.stdout), streamText(child.stderr), child.exitCode],152+ { concurrency: "unbounded" }153+ );154+155+ return { code: Number(code), stderr, stdout };156+ })157+ ).pipe(158+ Effect.mapError(159+ ({ message }) =>160+ new SwarmFailed({ reason: `${input.command} didn't run: ${message}` })161+ )162+ );163+164+/**165+ * Makes one contributor's workspace for their claim, below `.swarm/<run>/`:166+ *167+ * - `bin/<cli>` and `bin/git-credential-<slug>`, shims that run this repo's168+ * CLI from source (the helper as `<cli> credential`), first on `PATH`;169+ * - `config/`, the CLI's `XDG_CONFIG_HOME`, so neither the CLI nor git's170+ * helper reads the user's own login (HOME stays the user's: the171+ * harnesses' own sign-ins live there);172+ * - `clone/`, the claim's fork, cloned with the helper in its config for173+ * the platform (after an empty helper that drops any other, as `login`174+ * sets it globally), and the person as its author;175+ * - the env: `PATH`, git's non-interactive settings, `XDG_CONFIG_HOME`, and176+ * the person's token and platform as `<SLUG>_TOKEN` and `<SLUG>_URL`.177+ */178+export const prepareWorkspace = (input: {179+ readonly run: string;180+ readonly contributor: Contributor;181+ readonly claim: ClaimView;182+ readonly platformUrl: string;183+ readonly token: Redacted.Redacted;184+}): Effect.Effect<185+ AgentWorkspace,186+ SwarmFailed,187+ FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner188+> =>189+ Effect.gen(function* () {190+ const fs = yield* FileSystem.FileSystem;191+ const { handle } = input.contributor;192+ const dir = `${yield* runDir(input.run)}/${handle}`;193+ const bin = `${dir}/bin`;194+ const config = `${dir}/config`;195+ const clone = `${dir}/clone`;196+ const helper = `${bin}/${Brand.gitCredentialHelper}`;197+ const cli = `${bin}/${Brand.cli}`;198+199+ const path = yield* Config.String("PATH").pipe(200+ Config.withDefault(""),201+ Effect.orElseSucceed(() => "")202+ );203+204+ yield* Effect.gen(function* () {205+ yield* fs.makeDirectory(bin, { recursive: true });206+ yield* fs.makeDirectory(config, { mode: CONFIG_MODE, recursive: true });207+ yield* fs.writeFileString(cli, shim(Brand.cli, []), { mode: SHIM_MODE });208+ yield* fs.writeFileString(209+ helper,210+ shim(Brand.gitCredentialHelper, ["credential"]),211+ { mode: SHIM_MODE }212+ );213+ yield* fs.chmod(cli, SHIM_MODE);214+ yield* fs.chmod(helper, SHIM_MODE);215+ }).pipe(216+ Effect.mapError(217+ ({ message }) =>218+ new SwarmFailed({ reason: `${handle}'s workspace: ${message}` })219+ )220+ );221+222+ const env = {223+ // Rat Stack's editor env (joelhooks/rat-stack, MIT, after its224+ // `scripts/vcs-command-policy.js`): no git command waits in an editor.225+ GIT_EDITOR: ":",226+ GIT_MERGE_AUTOEDIT: "no",227+ GIT_SEQUENCE_EDITOR: ":",228+ // …nor at a prompt for a password.229+ GIT_TERMINAL_PROMPT: "0",230+ PATH: path === "" ? bin : `${bin}:${path}`,231+ ...personEnv({232+ configHome: config,233+ platformUrl: input.platformUrl,234+ token: input.token,235+ }),236+ };237+238+ const workspace: AgentWorkspace = {239+ clone,240+ dir,241+ env,242+ redacted: [TOKEN_VARIABLE],243+ };244+245+ const credential = `credential.${input.platformUrl}`;246+247+ const cloned = yield* run({248+ args: [249+ "clone",250+ ...[251+ `${credential}.helper=`,252+ `${credential}.helper=${helper}`,253+ `${credential}.useHttpPath=true`,254+ `user.name=${handle}`,255+ `user.email=${handle}@example.com`,256+ "commit.gpgsign=false",257+ ].flatMap((setting) => ["--config", setting]),258+ "--",259+ input.claim.remote,260+ clone,261+ ],262+ command: "git",263+ cwd: dir,264+ env,265+ });266+267+ if (cloned.code !== 0) {268+ return yield* new SwarmFailed({269+ reason: scrubbed(270+ `${handle}: git clone ${input.claim.remote} exited ${cloned.code}: ${cloned.stderr.trim()}`,271+ workspace272+ ),273+ });274+ }275+276+ return workspace;277+ });modified:scripts/swarm.ts+559 added-13 removed
1 /**2 * swarm: six fictional contributors, on four harnesses, each answer one child3- * of a project's split family on a stage (issue 702 plans them, 711 runs them).3+ * of a project's split family on a stage (issue 702 plans them and prepares4+ * each one's workspace; issue 711 runs their harnesses).5 *5- * A stub until 702 builds it: it says so in one line and exits 1.6+ * bun scripts/swarm.ts --stage dev-oscabriel --project burrow --dry-run7+ * bunx varlock run --path apps/platform/ -- bun scripts/swarm.ts --stage dev-oscabriel8+ *9+ * `--dry-run` reads the project's open asks anonymously and prints the plan:10+ * who answers which ask, on which territory, and the command that would11+ * start their harness. It claims nothing, starts nothing and needs no token.12+ *13+ * Without it, each contributor claims their ask as themselves (their token14+ * from `SESSION_TOKENS`, a JSON object from token to handle, as the15+ * platform's own), reads the ask's page, gets a workspace with a clone of16+ * the claim's fork, and is handed to the run loop (711), six at once. The17+ * run's summary goes to `.swarm/<run>/agents.json`, and each claim's fork to18+ * the throwaway ledger (`infra/created.ts`). Tokens reach a contributor's19+ * processes only through their env, and no line or JSON this prints holds20+ * one. Flags: `lib/swarm/args.ts`.21 */7-import { BunRuntime } from "@effect/platform-bun";8-import { Console, Effect, Runtime, Schema } from "effect";22+import { BunRuntime, BunServices } from "@effect/platform-bun";23+import { AskListing } from "@repo/protocol/domain/ask";24+import { ClaimView } from "@repo/protocol/domain/claim";25+import { Envelope } from "@repo/protocol/envelope";26+import { Handle, sameHandle } from "@repo/protocol/ids";27+import type { ProjectName } from "@repo/protocol/ids";28+import type { Refusal } from "@repo/protocol/refusal";29+import {30+ Clock,31+ Config,32+ Console,33+ DateTime,34+ Effect,35+ FileSystem,36+ Option,37+ Path,38+ Redacted,39+ Result,40+ Schema,41+ Stdio,42+} from "effect";43 10-/** The script is not built yet: the line it printed says where it will be. */11-class NotBuilt extends Schema.TaggedError<NotBuilt>()("NotBuilt", {}) {12- override readonly [Runtime.errorExitCode] = 1;13- override readonly [Runtime.errorReported] = false;44+import { readLedger, recordCreated } from "../infra/created.ts";45+import {46+ platformOrigin,47+ repoRoot,48+ resources,49+ subdomainFile,50+ WorkersDev,51+} from "../infra/stages.ts";52+import type { Stage } from "../infra/stages.ts";53+import { optionsOf } from "./lib/swarm/args.ts";54+import type { SwarmOptions } from "./lib/swarm/args.ts";55+import { runAgent, startCommand } from "./lib/swarm/loop.ts";56+import { planSwarm, SwarmPlan } from "./lib/swarm/plan.ts";57+import type { Assignment } from "./lib/swarm/plan.ts";58+import { brief } from "./lib/swarm/prompt.ts";59+import {60+ agentsFile,61+ AgentsResult,62+ runDir,63+ SwarmDir,64+ writeAgentsResult,65+} from "./lib/swarm/results.ts";66+import type { AgentRun } from "./lib/swarm/results.ts";67+import { roster } from "./lib/swarm/roster.ts";68+import type { Contributor } from "./lib/swarm/roster.ts";69+import { nudges } from "./lib/swarm/scenario.ts";70+import {71+ anonymousEnv,72+ cliEntry,73+ personEnv,74+ prepareWorkspace,75+ run,76+ scrubbed,77+ shellQuoted,78+ SwarmFailed,79+ TOKEN_VARIABLE,80+} from "./lib/swarm/workspace.ts";81+import type { Ran } from "./lib/swarm/workspace.ts";82+83+const failed = (reason: string) => new SwarmFailed({ reason });84+85+/** The env var that holds the stage's people: a JSON object from token to handle. */86+const SESSIONS_VARIABLE = "SESSION_TOKENS";87+88+/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */89+const originOf = (options: SwarmOptions) =>90+ Option.match(options.url, {91+ onNone: () =>92+ Effect.gen(function* () {93+ const fs = yield* FileSystem.FileSystem;94+ const path = yield* Path.Path;95+ const root = yield* repoRoot;96+97+ const recorded = yield* fs98+ .readFileString(path.join(root, subdomainFile))99+ .pipe(100+ Effect.flatMap(101+ Schema.decodeEffect(Schema.fromJsonString(WorkersDev))102+ ),103+ Effect.mapError(() =>104+ failed(105+ `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`106+ )107+ )108+ );109+110+ return platformOrigin(options.stage, recorded.subdomain);111+ }),112+ onSome: Effect.succeed,113+ });114+115+/** One CLI command, run from this repo's source with Bun. */116+const cli = (117+ args: readonly string[],118+ env: Readonly<Record<string, string | undefined>>119+) => run({ args: [cliEntry, ...args], command: "bun", env });120+121+/** A refusal list in one line: `NotVouched, AskFull`. */122+const tagsOf = (refusals: readonly Refusal[]) =>123+ refusals.map(({ _tag }) => _tag).join(", ");124+125+/** The CLI refused the command: its refusals, for the run's summary. */126+class Refused extends Schema.TaggedError<Refused>()("Refused", {127+ reason: Schema.String,128+ tags: Schema.Array(Schema.String),129+}) {130+ override get message() {131+ return this.reason;132+ }133 }134 16-const main = Effect.gen(function* () {17- yield* Console.error(18- "not built: see .scratch/build/issues/702-swarm-plan.md"135+/**136+ * What one CLI command printed under `--json`, decoded as its envelope: its137+ * data, or `Refused` with its refusals. Output that is no envelope fails138+ * with what the command printed, `scrub`bed of any secret.139+ */140+const envelopeOf =141+ <A, I>(142+ data: Schema.Codec<A, I>,143+ what: string,144+ scrub: (text: string) => string145+ ) =>146+ (ran: Ran): Effect.Effect<A, SwarmFailed | Refused> =>147+ Effect.gen(function* () {148+ const printed = ran.stderr.trim() === "" ? ran.stdout : ran.stderr;149+150+ const envelope: Envelope<A> = yield* Schema.decodeEffect(151+ Schema.fromJsonString(Envelope(data))152+ )(ran.stdout).pipe(153+ Effect.mapError(() =>154+ failed(155+ scrub(156+ `${what} exited ${ran.code} without its JSON: ${printed.trim().slice(0, 500)}`157+ )158+ )159+ )160+ );161+162+ if (envelope.ok) {163+ return envelope.data;164+ }165+166+ return yield* new Refused({167+ reason: `${what}: refused ${tagsOf(envelope.refusals)}`,168+ tags: envelope.refusals.map(({ _tag }) => _tag),169+ });170+ });171+172+const isRefused = Schema.is(Refused);173+174+const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });175+176+/** The project's open asks, read anonymously: no token, and no stored login of the user's. */177+const listAsks = (origin: string, project: ProjectName) =>178+ Effect.gen(function* () {179+ const home = `${yield* SwarmDir}/anonymous`;180+181+ const listed = yield* cli(182+ ["asks", "--project", project, "--json"],183+ anonymousEnv({ configHome: home, platformUrl: origin })184+ ).pipe(185+ Effect.flatMap(186+ envelopeOf(Listed, `asks --project ${project}`, (text) => text)187+ ),188+ Effect.mapError(({ reason }) => failed(reason))189+ );190+191+ return listed.asks;192+ });193+194+/** A contributor's position in the whole roster, which the scenarios' nudges go by. */195+const rosterIndex = ({ handle }: Contributor) =>196+ roster.findIndex((one) => one.handle === handle);197+198+/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */199+const planLines = (200+ plan: SwarmPlan,201+ origin: string,202+ swarm: string203+): readonly string[] => {204+ const rows = plan.assignments.map(({ ask, contributor, territory }) => {205+ const dir = `${swarm}/<run>/${contributor.handle}`;206+207+ const command = startCommand({ brief: "<brief>", contributor, dir })208+ .map(shellQuoted)209+ .join(" ");210+211+ return [212+ contributor.handle,213+ contributor.harness,214+ contributor.model,215+ ask,216+ territory,217+ `cd ${shellQuoted(`${dir}/clone`)} && ${command}`,218+ ];219+ });220+221+ const header = ["handle", "harness", "model", "ask", "territory", "command"];222+223+ const widths = header.map((title, column) =>224+ Math.max(title.length, ...rows.map((row) => row[column]?.length ?? 0))225 );226 21- return yield* new NotBuilt();227+ const line = (cells: readonly string[]) =>228+ cells229+ .map((cell, column) =>230+ column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)231+ )232+ .join(" ");233+234+ const nudged = plan.assignments.flatMap(({ contributor }) =>235+ Option.toArray(236+ Option.map(237+ nudges(plan.scenario, rosterIndex(contributor)),238+ (nudge) =>239+ `nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`240+ )241+ )242+ );243+244+ return [245+ `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,246+ line(header),247+ ...rows.map(line),248+ `held: ${plan.held.length === 0 ? "none" : plan.held.join(", ")}`,249+ ...nudged,250+ ];251+};252+253+/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */254+const runName = Effect.map(DateTime.now, (now) =>255+ DateTime.formatIso(now)256+ .slice(0, 19)257+ .replaceAll(/[-:]/gu, "")258+ .replace("T", "-")259+);260+261+/** The commit of this repo the swarm runs from. */262+const headCommit = Effect.gen(function* () {263+ const root = yield* repoRoot;264+265+ const head = yield* run({266+ args: ["-C", root, "rev-parse", "HEAD"],267+ command: "git",268+ env: {},269+ });270+271+ return head.code === 0 && head.stdout.trim() !== ""272+ ? head.stdout.trim()273+ : yield* failed(`git rev-parse HEAD exited ${head.code}`);274 });275 276+const decodeSessions = Schema.decodeUnknownEffect(277+ Schema.fromJsonString(Schema.Record(Schema.String, Handle))278+);279+280+/**281+ * Each contributor's token, by handle, from `SESSION_TOKENS`; a missing282+ * person fails before anything is claimed, naming them and never a token.283+ */284+const tokensFor = (handles: readonly Handle[]) =>285+ Effect.gen(function* () {286+ const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(287+ Effect.mapError(() =>288+ failed(289+ `no ${SESSIONS_VARIABLE} in the environment: run the swarm under \`bunx varlock run --path apps/platform/ --\`, or with the stage's secrets in the env`290+ )291+ )292+ );293+294+ const sessions = yield* decodeSessions(raw).pipe(295+ Effect.mapError(() =>296+ failed(`${SESSIONS_VARIABLE} is not a JSON object from token to handle`)297+ )298+ );299+300+ const tokens = new Map(301+ handles.flatMap((handle) => {302+ const token = Object.entries(sessions).find(([, person]) =>303+ sameHandle(person, handle)304+ )?.[0];305+306+ return token === undefined307+ ? []308+ : [[handle, Redacted.make(token)] as const];309+ })310+ );311+312+ const missing = handles.filter((handle) => !tokens.has(handle));313+314+ return missing.length === 0315+ ? tokens316+ : yield* failed(317+ `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each on the stage (human step H5 on demo), then run the swarm again`318+ );319+ });320+321+/** Records a claim's fork in the throwaway ledger, once. */322+const recordFork = (stage: Stage, claim: ClaimView) =>323+ Effect.gen(function* () {324+ const namespace = resources(stage).projects;325+326+ const known = (yield* readLedger).some(327+ (entry) =>328+ entry.kind === "repo" &&329+ entry.name === claim.fork &&330+ entry.namespace === namespace &&331+ entry.stage === stage332+ );333+334+ if (!known) {335+ yield* recordCreated({336+ at: yield* DateTime.now,337+ by: "swarm",338+ kind: "repo",339+ name: claim.fork,340+ namespace,341+ stage,342+ });343+ }344+ }).pipe(345+ Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))346+ );347+348+const Claimed = Schema.Struct({ claim: ClaimView });349+350+const Shown = Schema.Struct({351+ ask: Schema.Struct({ id: Schema.NonEmptyString }),352+ brief: Schema.NonEmptyString,353+});354+355+/**356+ * One contributor, from claim to the run loop: claims their ask as357+ * themselves, reads its page, makes their workspace and hands it to358+ * `runAgent`. A step that fails ends their run as `failed`, with any359+ * refusals the claim met; it never stops the others.360+ */361+const contributorRun = (input: {362+ readonly assignment: Assignment;363+ readonly options: SwarmOptions;364+ readonly origin: string;365+ readonly run: string;366+ readonly token: Redacted.Redacted;367+}) =>368+ Effect.gen(function* () {369+ const { assignment, options, origin, token } = input;370+ const { contributor } = assignment;371+ const { handle } = contributor;372+ const started = yield* Clock.currentTimeMillis;373+ const configHome = `${yield* runDir(input.run)}/${handle}/config`;374+ const env = personEnv({ configHome, platformUrl: origin, token });375+376+ const scrub = (text: string) =>377+ scrubbed(text, { env, redacted: [TOKEN_VARIABLE] });378+379+ const setup = Effect.gen(function* () {380+ const { claim } = yield* cli(381+ ["claim", assignment.ask, "--project", options.project, "--json"],382+ env383+ ).pipe(384+ Effect.flatMap(385+ envelopeOf(Claimed, `${handle}: claim ${assignment.ask}`, scrub)386+ )387+ );388+389+ yield* recordFork(options.stage, claim);390+391+ const page = yield* cli(392+ ["ask", assignment.ask, "--project", options.project, "--json"],393+ env394+ ).pipe(395+ Effect.flatMap(396+ envelopeOf(Shown, `${handle}: ask ${assignment.ask}`, scrub)397+ )398+ );399+400+ const workspace = yield* prepareWorkspace({401+ claim,402+ contributor,403+ platformUrl: origin,404+ run: input.run,405+ token,406+ });407+408+ return {409+ text: brief({410+ ask: assignment.ask,411+ askMarkdown: page.brief,412+ nudge: nudges(options.scenario, rosterIndex(contributor)),413+ project: options.project,414+ remote: claim.remote,415+ }),416+ workspace,417+ };418+ });419+420+ const ready = yield* Effect.result(setup);421+422+ if (Result.isFailure(ready)) {423+ const { failure } = ready;424+ const ended = yield* Clock.currentTimeMillis;425+426+ yield* Console.error(`${handle}: ${scrub(failure.reason)}`);427+428+ return {429+ adapter: contributor.adapter,430+ ask: assignment.ask,431+ attempts: 0,432+ durationMs: ended - started,433+ handle,434+ harness: contributor.harness,435+ model: contributor.model,436+ outcome: "failed",437+ refusals: Object.fromEntries(438+ (isRefused(failure) ? failure.tags : []).map((tag) => [tag, 1])439+ ),440+ } satisfies AgentRun;441+ }442+443+ yield* Console.error(444+ `${handle}: claimed ${assignment.ask}; workspace ${ready.success.workspace.dir}`445+ );446+447+ return yield* runAgent({448+ assignment,449+ brief: ready.success.text,450+ maxContinuations: 3,451+ timeoutMs: options.timeoutMin * 60_000,452+ workspace: ready.success.workspace,453+ });454+ });455+456+/** One contributor's run as the summary prints it. */457+const runLine = ({458+ ask,459+ attempts,460+ handle,461+ harness,462+ outcome,463+ refusals,464+}: AgentRun) => {465+ const met = Object.entries(refusals)466+ .map(([tag, count]) => `${tag}×${count}`)467+ .join(", ");468+469+ return `${handle} (${harness}) ${ask}: ${outcome}, ${attempts} attempts${met === "" ? "" : `, refused ${met}`}`;470+};471+472+const printJson = <S extends Schema.Top>(schema: S, value: S["Type"]) =>473+ Effect.flatMap(474+ Schema.encodeEffect(Schema.fromJsonString(schema))(value),475+ Console.log476+ ).pipe(Effect.orDie);477+478+/**479+ * `bun scripts/swarm.ts …`: plans the run from the project's open asks; with480+ * `--dry-run`, prints the plan (or, with `--json`, the `SwarmPlan`) and481+ * stops. Otherwise runs every contributor at once and writes the summary.482+ */483+export const main = (argv: readonly string[]) =>484+ Effect.gen(function* () {485+ const options = yield* optionsOf(argv);486+ const origin = yield* originOf(options);487+ const asks = yield* listAsks(origin, options.project);488+489+ const people =490+ options.only.length === 0491+ ? roster492+ : roster.filter(({ handle }) => options.only.includes(handle));493+494+ const plan = yield* Effect.fromResult(495+ planSwarm({496+ asks,497+ project: options.project,498+ roster: people,499+ scenario: options.scenario,500+ stage: options.stage,501+ })502+ ).pipe(Effect.mapError(({ message }) => failed(message)));503+504+ const say = (line: string) =>505+ options.json ? Effect.void : Console.log(line);506+507+ yield* Effect.forEach(planLines(plan, origin, yield* SwarmDir), say, {508+ discard: true,509+ });510+511+ if (options.dryRun) {512+ yield* say("dry run: nothing claimed, no harness started");513+514+ if (options.json) {515+ yield* printJson(SwarmPlan, plan);516+ }517+518+ return;519+ }520+521+ const tokens = yield* tokensFor(522+ plan.assignments.map(({ contributor }) => contributor.handle)523+ );524+525+ const name = yield* runName;526+ const commit = yield* headCommit;527+ const at = yield* DateTime.now;528+529+ const runs = yield* Effect.forEach(530+ plan.assignments,531+ (assignment) =>532+ Effect.flatMap(533+ Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),534+ (token) =>535+ contributorRun({ assignment, options, origin, run: name, token })536+ ),537+ { concurrency: 6 }538+ ).pipe(Effect.mapError(() => failed("a contributor lost their token")));539+540+ const result: AgentsResult = {541+ at,542+ commit,543+ project: options.project,544+ runs,545+ scenario: options.scenario,546+ stage: options.stage,547+ v: 1,548+ };549+550+ yield* writeAgentsResult({ result, run: name }).pipe(551+ Effect.mapError(({ message }) => failed(`agents.json: ${message}`))552+ );553+554+ yield* Effect.forEach(runs.map(runLine), say, { discard: true });555+ yield* say(`summary: ${agentsFile(yield* runDir(name))}`);556+557+ if (options.json) {558+ yield* printJson(AgentsResult, result);559+ }560+ });561+562+if (import.meta.main) {24-BunRuntime.runMain(main);563+ BunRuntime.runMain(564+ Effect.gen(function* () {565+ const args = yield* (yield* Stdio.Stdio).args;566+567+ return yield* main(args);568+ }).pipe(Effect.provide(BunServices.layer))569+ );570+}