Skip to content
Myr

Merge branch 'build/702-swarm-plan'

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

authored by oscabriel · committed by oscabriel · parents d7064cb, 03d4540 · Browse files · 12 files+3057 added−13 removed
This commit

State

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

Diff stats

12 files+3057 added−13 removed

  • tests:+1424 added−0 removed
  • other:+1633 added−13 removed

12 files+3057 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
added:packages/config/test/swarm.test.ts+1302 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 */7import { NodeServices } from "@effect/platform-node";8import { describe, expect, it } from "@effect/vitest";9import { Ask, AskListing } from "@repo/protocol/domain/ask";10import { ClaimView } from "@repo/protocol/domain/claim";11import { Envelope } from "@repo/protocol/envelope";12import { AskId, KindName, ProjectName } from "@repo/protocol/ids";13import { AskFull } from "@repo/protocol/refusal";14import {15 Array,16 ConfigProvider,17 Console,18 Effect,19 FileSystem,20 Layer,21 Option,22 Path,23 Redacted,24 Ref,25 Result,26 Schema,27 Sink,28 Stream,29} from "effect";30import { ChildProcess, ChildProcessSpawner } from "effect/process";3132import { LedgerFile, readLedger } from "../../../infra/created.ts";33import { optionsOf } from "../../../scripts/lib/swarm/args.ts";34import {35 NotEnoughAsks,36 planSwarm,37 SwarmPlan,38} from "../../../scripts/lib/swarm/plan.ts";39import { brief } from "../../../scripts/lib/swarm/prompt.ts";40import {41 AgentsResult,42 SwarmDir,43 writeAgentsResult,44} from "../../../scripts/lib/swarm/results.ts";45import { roster } from "../../../scripts/lib/swarm/roster.ts";46import type { Contributor } from "../../../scripts/lib/swarm/roster.ts";47import { nudges } from "../../../scripts/lib/swarm/scenario.ts";48import { prepareWorkspace } from "../../../scripts/lib/swarm/workspace.ts";49import { main } from "../../../scripts/swarm.ts";50import { Brand } from "../../brand/src/index.ts";51import { repoRoot } from "./root.ts";5253const burrow = ProjectName.make("burrow");5455const ListedAsks = Envelope(Schema.Struct({ asks: Schema.Array(AskListing) }));5657/** What `<cli> claim <ask> --json` prints. */58const Claimed = Envelope(Schema.Struct({ claim: ClaimView }));5960/** What `<cli> ask <ask> --json` prints, when it shows the ask. */61const ShownAsk = Schema.Struct({62 command: Schema.Literal("ask"),63 data: Schema.Struct({ ask: Ask, brief: Schema.NonEmptyString }),64 ok: Schema.Literal(true),65 v: Schema.Literal(1),66});6768/** A fixture's text. */69const fixture = (name: string) =>70 Effect.gen(function* () {71 const fs = yield* FileSystem.FileSystem;72 const path = yield* Path.Path;7374 return yield* fs.readFileString(75 path.join("test", "fixtures", "swarm", name)76 );77 });7879/** burrow's open asks, as `<cli> asks --project burrow --json` listed them. */80const burrowAsks = Effect.gen(function* () {81 const envelope = yield* Schema.decodeEffect(82 Schema.fromJsonString(ListedAsks)83 )(yield* fixture("list-asks.json"));8485 return envelope.ok ? envelope.data.asks : [];86});8788const child = (module: string) => AskId.make(`drop-legacy-fetch-${module}`);8990const children = [91 "burrow-auth",92 "burrow-billing",93 "burrow-catalog",94 "burrow-kit",95 "burrow-notify",96 "burrow-search",97].map(child);9899const plan = (100 asks: readonly AskListing[],101 people: readonly Contributor[] = roster102) =>103 planSwarm({104 asks,105 project: burrow,106 roster: people,107 scenario: "plain",108 stage: "dev-oscabriel",109 });110111describe("the plan", () => {112 it.effect(113 "hands burrow's six children to the six contributors in order, on four harnesses and six models, and holds the delete child",114 () =>115 Effect.gen(function* () {116 const { assignments, held } = Result.getOrThrow(117 plan(yield* burrowAsks)118 );119120 expect(121 assignments.map(({ ask, contributor, territory }) => [122 contributor.handle,123 ask,124 territory,125 ])126 ).toStrictEqual([127 ["wren", children[0], "@burrow/auth"],128 ["tamsin", children[1], "@burrow/billing"],129 ["ivo", children[2], "@burrow/catalog"],130 ["marisol", children[3], "@burrow/kit"],131 ["dagny", children[4], "@burrow/notify"],132 ["pell", children[5], "@burrow/search"],133 ]);134135 expect({136 harnesses: new Set(137 assignments.map(({ contributor }) => contributor.harness)138 ).size,139 models: new Set(140 assignments.map(({ contributor }) => contributor.model)141 ).size,142 }).toStrictEqual({ harnesses: 4, models: 6 });143 expect(held).toStrictEqual([144 "drop-legacy-fetch",145 "drop-legacy-fetch-delete",146 ]);147 expect(assignments.map(({ ask }) => ask)).not.toContain(148 "drop-legacy-fetch-delete"149 );150 }).pipe(Effect.provide(NodeServices.layer))151 );152153 it.effect("gives no two contributors overlapping territories", () =>154 Effect.gen(function* () {155 const { assignments } = Result.getOrThrow(plan(yield* burrowAsks));156157 const territories = assignments.map(({ territory }) => territory);158159 expect(territories).toHaveLength(6);160 expect(new Set(territories).size).toBe(6);161 expect(territories).not.toContain(".");162 }).pipe(Effect.provide(NodeServices.layer))163 );164165 it.effect(166 "plans the same for the same asks, in whatever order they are listed",167 () =>168 Effect.gen(function* () {169 const asks = yield* burrowAsks;170 const first = Result.getOrThrow(plan(asks));171172 expect(Result.getOrThrow(plan(asks))).toStrictEqual(first);173 expect(Result.getOrThrow(plan(Array.reverse(asks)))).toStrictEqual(174 first175 );176 expect(177 yield* Schema.decodeEffect(SwarmPlan)(178 yield* Schema.encodeEffect(SwarmPlan)(first)179 )180 ).toStrictEqual(first);181 }).pipe(Effect.provide(NodeServices.layer))182 );183184 it.effect(185 "carries the video scenario's nudges in the plan, by each contributor's place in the roster even when planned alone",186 () =>187 Effect.gen(function* () {188 const asks = yield* burrowAsks;189190 const nudged = (people: readonly Contributor[]) =>191 Result.getOrThrow(192 planSwarm({193 asks,194 project: burrow,195 roster: people,196 scenario: "video",197 stage: "dev-oscabriel",198 })199 ).assignments.map(({ contributor, nudge }) => [200 contributor.handle,201 nudge,202 ]);203204 expect(nudged(roster)).toStrictEqual([205 ["wren", undefined],206 [207 "tamsin",208 "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.",209 ],210 [211 "ivo",212 "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>`.",213 ],214 ["marisol", undefined],215 ["dagny", undefined],216 ["pell", undefined],217 ]);218 expect(nudged(roster.slice(2, 3))).toStrictEqual([219 [220 "ivo",221 "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>`.",222 ],223 ]);224 expect(225 Result.getOrThrow(plan(asks)).assignments.filter(226 (assignment) => "nudge" in assignment227 )228 ).toStrictEqual([]);229 }).pipe(Effect.provide(NodeServices.layer))230 );231232 it.effect(233 "fails NotEnoughAsks{wanted: 6, open: 5} with five open children",234 () =>235 Effect.gen(function* () {236 const asks = (yield* burrowAsks).filter(237 ({ ask }) => ask !== children[5]238 );239240 expect(plan(asks)).toStrictEqual(241 Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))242 );243 }).pipe(Effect.provide(NodeServices.layer))244 );245246 it.effect("skips a child someone already claimed", () =>247 Effect.gen(function* () {248 const asks = (yield* burrowAsks).map((listed) =>249 listed.ask === children[1] ? { ...listed, claimed: true } : listed250 );251252 const five = roster.slice(0, 5);253 const { assignments } = Result.getOrThrow(plan(asks, five));254255 expect(assignments.map(({ ask }) => ask)).toStrictEqual([256 children[0],257 children[2],258 children[3],259 children[4],260 children[5],261 ]);262 expect(plan(asks)).toStrictEqual(263 Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))264 );265 }).pipe(Effect.provide(NodeServices.layer))266 );267268 it.effect(269 "hands out only one of two asks on the same module, and nothing beside a whole-repo ask",270 () =>271 Effect.gen(function* () {272 const asks = yield* burrowAsks;273274 const same = asks.map((listed) =>275 listed.ask === children[1]276 ? { ...listed, territory: "@burrow/auth" }277 : listed278 );279280 expect(plan(same)).toStrictEqual(281 Result.fail(new NotEnoughAsks({ open: 5, wanted: 6 }))282 );283 expect(284 Result.getOrThrow(plan(same, roster.slice(0, 5))).assignments.map(285 ({ ask }) => ask286 )287 ).toStrictEqual([288 children[0],289 children[2],290 children[3],291 children[4],292 children[5],293 ]);294295 const whole: AskListing = {296 ask: AskId.make("aaa-whole-repo"),297 blockedBy: [],298 claimed: false,299 kind: KindName.make("fix"),300 territory: ".",301 want: "Touch everything",302 };303304 const first = Result.getOrThrow(305 plan([whole, ...asks], roster.slice(0, 1))306 );307308 expect(first.assignments.map(({ ask }) => ask)).toStrictEqual([309 "aaa-whole-repo",310 ]);311 expect(plan([whole, ...asks], roster.slice(0, 2))).toStrictEqual(312 Result.fail(new NotEnoughAsks({ open: 1, wanted: 2 }))313 );314 }).pipe(Effect.provide(NodeServices.layer))315 );316});317318describe("the roster", () => {319 it.effect(320 "is six people burrow vouches for, on four harnesses and six models, with the pi adapter on one pi agent only",321 () =>322 Effect.gen(function* () {323 const fs = yield* FileSystem.FileSystem;324 const path = yield* Path.Path;325 const root = yield* repoRoot;326327 const vouched = new Set(328 (yield* fs.readFileString(329 path.join(root, "examples", "burrow", Brand.configDir, "vouched.td")330 ))331 .split("\n")332 .map((line) => line.split(" ")[0] ?? "")333 .filter((handle) => /^[a-z]/u.test(handle))334 );335336 expect(roster.map(({ handle }) => handle)).toStrictEqual([337 "wren",338 "tamsin",339 "ivo",340 "marisol",341 "dagny",342 "pell",343 ]);344345 expect(346 roster.filter(({ handle }) => !vouched.has(handle))347 ).toStrictEqual([]);348 expect(roster.map(({ harness }) => harness)).toStrictEqual([349 "claude-code",350 "opencode",351 "amp",352 "pi",353 "pi",354 "pi",355 ]);356 expect(357 roster.flatMap(({ adapter, handle }) => (adapter ? [handle] : []))358 ).toStrictEqual(["pell"]);359360 // An Anthropic id, OpenCode's GPT, an Amp mode, then pi's three.361 const models = [362 /^claude-/u,363 /^openai\/gpt-/u,364 /^(?:low|medium|high|ultra)$/u,365 /\/kimi-k3$/u,366 /\/glm-5\.3$/u,367 /\/gemini-[\d.]+-flash$/u,368 ];369370 expect(371 roster.map(({ model }, at) => models[at]?.test(model))372 ).toStrictEqual([true, true, true, true, true, true]);373 }).pipe(Effect.provide(NodeServices.layer))374 );375});376377describe("the scenarios' nudges", () => {378 it("adds nothing to anyone's brief in the plain scenario", () => {379 expect(roster.map((_, index) => nudges("plain", index))).toStrictEqual(380 roster.map(() => Option.none())381 );382 });383384 it("tells contributor 2 a disable comment is fine, and contributor 3 that it needs its reason, in the video scenario", () => {385 const told = roster.map((_, index) => nudges("video", index));386387 expect(told.map(Option.isSome)).toStrictEqual([388 false,389 true,390 true,391 false,392 false,393 false,394 ]);395 expect(Option.getOrThrow(told[1] ?? Option.none())).toContain(396 "disable comment"397 );398 expect(Option.getOrThrow(told[1] ?? Option.none())).not.toContain(" -- ");399 expect(Option.getOrThrow(told[2] ?? Option.none())).toContain(400 "reason after ` -- `"401 );402 });403});404405/** The ask page `<cli> ask` printed for burrow's auth child. */406const authPage = Effect.gen(function* () {407 const text = (yield* fixture("show-ask.json")).replaceAll(408 "{configDir}",409 Brand.configDir410 );411412 const shown = yield* Schema.decodeEffect(Schema.fromJsonString(ShownAsk))(413 text414 );415416 return shown.data;417});418419describe("the brief", () => {420 const remote =421 "https://platform-dev-oscabriel.example.workers.dev/burrow--drop-legacy-fetch-burrow-auth--wren.git";422423 it.effect(424 "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",425 () =>426 Effect.gen(function* () {427 const page = yield* authPage;428429 const text = brief({430 ask: children[0] ?? AskId.make("x"),431 askMarkdown: page.brief,432 nudge: Option.none(),433 project: burrow,434 remote,435 });436437 expect(text).toContain(page.brief);438 expect(439 [440 remote,441 "AGENTS.md",442 `${Brand.cli} check`,443 "git push",444 `${Brand.cli} status --project burrow`,445 ].filter((said) => !text.includes(said))446 ).toStrictEqual([]);447 expect(text).not.toMatch(448 /\bgate\b|\bstage\b|held-back|sealed|Workflow|Note:/iu449 );450 }).pipe(Effect.provide(NodeServices.layer))451 );452453 it("adds a scenario's nudge, in plain sight, at the end", () => {454 const text = brief({455 ask: AskId.make("drop-legacy-fetch-burrow-billing"),456 askMarkdown: "# @burrow/billing: 2 callers\n",457 nudge: Option.some("A disable comment is acceptable."),458 project: burrow,459 remote,460 });461462 expect(text.trimEnd().split("\n").at(-1)).toBe(463 "Note: A disable comment is acceptable."464 );465 });466});467468/** One command a fake spawner was asked to run. */469interface Spawned {470 readonly command: string;471 readonly args: readonly string[];472 readonly cwd: string | undefined;473 readonly env: Readonly<Record<string, string | undefined>>;474}475476/**477 * A `ChildProcessSpawner` that runs nothing: it records each command and478 * answers with what `answer` gives it (exit 0 and no output by default).479 */480const fakeSpawner = (481 answer: (spawned: Spawned) => {482 readonly code?: number;483 readonly stdout?: string;484 } = () => ({})485) =>486 Effect.gen(function* () {487 const spawned = yield* Ref.make<readonly Spawned[]>([]);488489 const spawner = ChildProcessSpawner.make((command) =>490 Effect.gen(function* () {491 if (!ChildProcess.isStandardCommand(command)) {492 return yield* Effect.die("the swarm pipes no commands");493 }494495 const call: Spawned = {496 args: command.args,497 command: command.command,498 cwd: command.options.cwd,499 env: command.options.env ?? {},500 };501502 yield* Ref.update(spawned, (calls) => [...calls, call]);503504 const { code = 0, stdout = "" } = answer(call);505 const out = Stream.make(new TextEncoder().encode(stdout));506507 return ChildProcessSpawner.makeHandle({508 all: out,509 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),510 getInputFd: () => Sink.drain,511 getOutputFd: () => Stream.empty,512 isRunning: Effect.succeed(false),513 kill: () => Effect.void,514 pid: ChildProcessSpawner.ProcessId(1),515 stderr: Stream.empty,516 stdin: Sink.drain,517 stdout: out,518 unref: Effect.succeed(Effect.void),519 });520 })521 );522523 return {524 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),525 spawned: Ref.get(spawned),526 };527 });528529/** The env names the CLI reads, spelled from the brand. */530const SLUG = Brand.slug.toUpperCase();531532const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";533534/** wren's claim of burrow's auth child, as `<cli> claim --json` gives it. */535const wrensClaim = Schema.decodeSync(ClaimView)({536 ask: "drop-legacy-fetch-burrow-auth",537 base: "9998ebe62c2f282d148b1d806372484916cc2548",538 checkCommand: `${Brand.cli} check`,539 claimant: "wren",540 fork: "burrow--drop-legacy-fetch-burrow-auth--wren",541 lapsesAt: "2026-10-09T05:00:00.000Z",542 openedAt: "2026-10-08T05:00:00.000Z",543 project: "burrow",544 remote: `${platformUrl}/burrow--drop-legacy-fetch-burrow-auth--wren.git`,545 state: "live",546 warnsAt: "2026-10-08T17:00:00.000Z",547});548549const wrensToken = "wren-token-0123456789abcdef0123456789abcdef";550551/** wren's workspace for run `r1`, below a temp dir, over a fake spawner. */552const wrensWorkspace = (code = 0) =>553 Effect.gen(function* () {554 const fs = yield* FileSystem.FileSystem;555 const swarm = yield* fs.makeTempDirectoryScoped();556 const fake = yield* fakeSpawner(() => ({ code }));557558 const [wren] = roster;559560 const workspace = yield* prepareWorkspace({561 claim: wrensClaim,562 contributor: wren,563 platformUrl,564 run: "r1",565 token: Redacted.make(wrensToken),566 }).pipe(567 Effect.provide(fake.layer),568 Effect.provideService(SwarmDir, swarm),569 Effect.provideService(570 ConfigProvider.ConfigProvider,571 ConfigProvider.fromEnv({ env: { PATH: "/usr/local/bin:/usr/bin" } })572 ),573 Effect.result574 );575576 return { spawned: yield* fake.spawned, swarm, workspace };577 });578579describe("a contributor's workspace", () => {580 it.effect(581 "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",582 () =>583 Effect.gen(function* () {584 const fs = yield* FileSystem.FileSystem;585 const { spawned, swarm, workspace } = yield* wrensWorkspace();586587 const dir = `${swarm}/r1/wren`;588 const bin = `${dir}/bin`;589 const helper = `${bin}/${Brand.gitCredentialHelper}`;590 const made = Result.getOrThrow(workspace);591592 expect(made).toStrictEqual({593 clone: `${dir}/clone`,594 dir,595 env: {596 GIT_EDITOR: ":",597 GIT_MERGE_AUTOEDIT: "no",598 GIT_SEQUENCE_EDITOR: ":",599 GIT_TERMINAL_PROMPT: "0",600 PATH: `${bin}:/usr/local/bin:/usr/bin`,601 [`${SLUG}_TOKEN`]: wrensToken,602 [`${SLUG}_URL`]: platformUrl,603 XDG_CONFIG_HOME: `${dir}/config`,604 },605 redacted: [`${SLUG}_TOKEN`],606 });607608 const cli = yield* fs.readFileString(`${bin}/${Brand.cli}`);609 const credential = yield* fs.readFileString(helper);610611 const modes = yield* Effect.forEach(612 [`${bin}/${Brand.cli}`, helper],613 (shim) =>614 Effect.map(fs.stat(shim), ({ mode }) => (mode % 0o1000).toString(8))615 );616617 expect({618 cli: /^#!\/bin\/sh\n(?:#.*\n)?exec bun '[^']+\/apps\/cli\/src\/bin\.ts' "\$@"\n$/u.test(619 cli620 ),621 config: (yield* fs.stat(`${dir}/config`)).type,622 credential:623 /^#!\/bin\/sh\n(?:#.*\n)?exec bun '[^']+\/apps\/cli\/src\/bin\.ts' credential "\$@"\n$/u.test(624 credential625 ),626 modes,627 }).toStrictEqual({628 cli: true,629 config: "Directory",630 credential: true,631 modes: ["755", "755"],632 });633634 expect(spawned).toStrictEqual([635 {636 args: [637 "clone",638 "--config",639 `credential.${platformUrl}.helper=`,640 "--config",641 `credential.${platformUrl}.helper=${helper}`,642 "--config",643 `credential.${platformUrl}.useHttpPath=true`,644 "--config",645 "user.name=wren",646 "--config",647 "user.email=wren@example.com",648 "--config",649 "commit.gpgsign=false",650 "--",651 wrensClaim.remote,652 `${dir}/clone`,653 ],654 command: "git",655 cwd: dir,656 env: made.env,657 },658 ]);659 expect(660 [cli, credential, ...spawned.flatMap(({ args }) => args)].filter(661 (text) => text.includes(wrensToken)662 )663 ).toStrictEqual([]);664 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))665 );666667 it.effect(668 "fails SwarmFailed when the clone fails, naming the fork and never the token",669 () =>670 Effect.gen(function* () {671 const { workspace } = yield* wrensWorkspace(128);672673 const { _tag, reason } = Option.getOrThrow(674 Result.getFailure(workspace)675 );676677 expect(_tag).toBe("SwarmFailed");678 expect(reason).toContain(wrensClaim.remote);679 expect(reason).not.toContain(wrensToken);680 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))681 );682});683684describe("the run's summary", () => {685 it.effect(686 "writes the run's summary to <run>/agents.json, and it decodes as AgentsResult",687 () =>688 Effect.gen(function* () {689 const fs = yield* FileSystem.FileSystem;690 const swarm = yield* fs.makeTempDirectoryScoped();691692 const result = yield* Schema.decodeEffect(AgentsResult)({693 at: "2026-10-08T12:00:00.000Z",694 commit: "d7064cb0000000000000000000000000000000000",695 project: "burrow",696 runs: [697 {698 adapter: false,699 ask: "drop-legacy-fetch-burrow-auth",700 attempts: 3,701 durationMs: 412_000,702 handle: "wren",703 harness: "claude-code",704 landed: "9998ebe62c2f282d148b1d806372484916cc2548",705 model: "claude-opus-5-5",706 outcome: "landed",707 refusals: { OutOfScope: 1, StaleBase: 1 },708 },709 {710 adapter: true,711 ask: "drop-legacy-fetch-burrow-search",712 attempts: 0,713 durationMs: 0,714 handle: "pell",715 harness: "pi",716 model: "opencode/gemini-3.8-flash",717 outcome: "failed",718 refusals: {},719 },720 ],721 scenario: "plain",722 stage: "dev-oscabriel",723 v: 1,724 });725726 yield* writeAgentsResult({ result, run: "r1" }).pipe(727 Effect.provideService(SwarmDir, swarm)728 );729730 const written = yield* fs.readFileString(`${swarm}/r1/agents.json`);731732 expect(733 yield* Schema.decodeEffect(Schema.fromJsonString(AgentsResult))(734 written735 )736 ).toStrictEqual(result);737 expect(written.at(-1)).toBe("\n");738 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))739 );740});741742/** Why the flags `argv` make no run, or `accepted` when they make one. */743const reasonOf = (argv: readonly string[]) =>744 optionsOf(argv).pipe(745 Effect.match({746 onFailure: ({ reason }) => reason,747 onSuccess: () => "accepted",748 })749 );750751describe("the swarm's flags", () => {752 it.effect(753 "takes burrow, plain, headless and 20 minutes when nothing else is named",754 () =>755 Effect.gen(function* () {756 const options = yield* optionsOf([757 "--stage",758 "dev-oscabriel",759 "--dry-run",760 ]);761762 expect(options).toStrictEqual({763 dryRun: true,764 json: false,765 only: [],766 project: "burrow",767 scenario: "plain",768 stage: "dev-oscabriel",769 timeoutMin: 20,770 url: Option.none(),771 });772 })773 );774775 it.effect(776 "reads --only as one or more handles from the roster, repeated or comma-separated",777 () =>778 Effect.gen(function* () {779 const options = yield* optionsOf([780 "--stage=dev-oscabriel",781 "--only",782 "wren",783 "pell",784 "--only=ivo,tamsin",785 "--scenario",786 "video",787 "--timeout-min",788 "5",789 ]);790791 expect([792 options.only,793 options.scenario,794 options.timeoutMin,795 ]).toStrictEqual([["wren", "pell", "ivo", "tamsin"], "video", 5]);796 expect(797 yield* reasonOf(["--stage", "dev-oscabriel", "--only", "quickclaim"])798 ).toContain("not in the roster");799 })800 );801802 it.effect(803 "refuses demo without --allow-demo, the herdr view until 717, no stage, and a flag it doesn't know",804 () =>805 Effect.gen(function* () {806 const reasons = yield* Effect.forEach(807 [808 ["--stage", "demo", "--dry-run"],809 ["--stage", "dev-oscabriel", "--view", "herdr"],810 ["--dry-run"],811 ["--stage", "dev-oscabriel", "--yes"],812 ["--stage", "dev-oscabriel", "--timeout-min", "0"],813 ],814 reasonOf815 );816817 expect(818 reasons.map((reason, at) =>819 reason.includes(820 [821 "--allow-demo",822 "717",823 "no --stage",824 "unknown flag --yes",825 "--timeout-min 0",826 ][at] ?? "?"827 )828 )829 ).toStrictEqual([true, true, true, true, true]);830 expect(831 (yield* optionsOf(["--stage", "demo", "--allow-demo"])).stage832 ).toBe("demo");833 })834 );835836 it.effect(837 "refuses a switch given a value, a flag missing its value, an empty --only, a --url that is no http(s) origin, and a word no flag takes",838 () =>839 Effect.gen(function* () {840 const reasons = yield* Effect.forEach(841 [842 // Read as a plain `--dry-run`, it would claim six asks.843 ["--stage", "dev-oscabriel", "--dry-run=yes"],844 ["--stage", "dev-oscabriel", "--url", "--dry-run"],845 ["--stage", "dev-oscabriel", "--only=", "--dry-run"],846 ["--stage", "dev-oscabriel", "--url", "platform.example"],847 ["--stage", "dev-oscabriel", "--dry-run", "burrow"],848 ],849 reasonOf850 );851852 expect(reasons).toStrictEqual([853 expect.stringContaining("--dry-run takes no value"),854 expect.stringContaining("--url needs a value"),855 expect.stringContaining("--only names no contributor"),856 expect.stringContaining("--url platform.example: an http(s) origin"),857 expect.stringContaining("unexpected argument burrow"),858 ]);859 expect(860 (yield* optionsOf([861 "--stage",862 "dev-oscabriel",863 "--url",864 "https://platform.example/",865 "--only",866 "wren",867 "pell",868 ])).url869 ).toStrictEqual(Option.some("https://platform.example"));870 })871 );872});873874/** What `main` prints, line by line, over a spawner that answers `asks` with the fixture. */875const dryRun = (argv: readonly string[]) =>876 Effect.gen(function* () {877 const fs = yield* FileSystem.FileSystem;878 const swarm = yield* fs.makeTempDirectoryScoped();879 const listed = yield* fixture("list-asks.json");880881 const fake = yield* fakeSpawner(({ args }) =>882 args[1] === "asks" ? { stdout: listed } : { code: 1 }883 );884885 const printed: string[] = [];886887 const captured: Console.Console = {888 ...console,889 error: () => {},890 log: (...args: readonly unknown[]) => {891 printed.push(args.map(String).join(" "));892 },893 };894895 yield* main(argv).pipe(896 Effect.provide(fake.layer),897 Effect.provideService(SwarmDir, swarm),898 Effect.provideService(Console.Console, captured),899 // No SESSION_TOKENS, nor any token: a dry run needs none.900 Effect.provideService(901 ConfigProvider.ConfigProvider,902 ConfigProvider.fromEnv({ env: {} })903 )904 );905906 return {907 made: yield* fs.readDirectory(swarm),908 printed,909 spawned: yield* fake.spawned,910 };911 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));912913describe("the dry run", () => {914 const url = platformUrl;915916 it.effect(917 "prints the plan as a table, each row ending in the command that would start that contributor, and only lists asks, anonymously",918 () =>919 Effect.gen(function* () {920 const { made, printed, spawned } = yield* dryRun([921 "--stage",922 "dev-oscabriel",923 "--project",924 "burrow",925 "--dry-run",926 "--url",927 url,928 ]);929930 expect(printed.slice(0, 2)).toStrictEqual([931 `swarm: burrow on dev-oscabriel (${url}), scenario plain, 6 contributors`,932 expect.stringMatching(933 /^handle +harness +model +ask +territory +command$/u934 ),935 ]);936937 const rows = printed.slice(2, 8);938939 expect(rows.map((row) => row.split(/ +/u).slice(0, 5))).toStrictEqual([940 [941 "wren",942 "claude-code",943 "claude-opus-5-5",944 children[0],945 "@burrow/auth",946 ],947 [948 "tamsin",949 "opencode",950 "openai/gpt-6.1-sol",951 children[1],952 "@burrow/billing",953 ],954 ["ivo", "amp", "medium", children[2], "@burrow/catalog"],955 ["marisol", "pi", "opencode-go/kimi-k3", children[3], "@burrow/kit"],956 ["dagny", "pi", "opencode-go/glm-5.3", children[4], "@burrow/notify"],957 [958 "pell",959 "pi",960 "opencode/gemini-3.8-flash",961 children[5],962 "@burrow/search",963 ],964 ]);965 expect([rows[0], rows[5], ...printed.slice(8)]).toStrictEqual([966 expect.stringContaining(967 "/<run>/wren/clone' && claude -p --output-format stream-json --verbose --permission-mode bypassPermissions --model claude-opus-5-5 '<brief>'"968 ),969 expect.stringMatching(970 / pi -p --mode json .* -e \S+\/apps\/cli\/src\/pi\.ts '<brief>'$/u971 ),972 "held: drop-legacy-fetch, drop-legacy-fetch-delete",973 "dry run: nothing claimed, no harness started",974 ]);975 expect(976 spawned.map(({ args, env }) => ({977 args: args.slice(1),978 token: Object.hasOwn(env, `${SLUG}_TOKEN`)979 ? env[`${SLUG}_TOKEN`]980 : "inherited",981 url: env[`${SLUG}_URL`],982 }))983 ).toStrictEqual([984 {985 args: ["asks", "--project", "burrow", "--json"],986 token: undefined,987 url,988 },989 ]);990 expect(made).toStrictEqual([]);991 })992 );993994 it.effect(995 "prints one decodable SwarmPlan with --json, and the video scenario's nudges in plain sight without it",996 () =>997 Effect.gen(function* () {998 const { printed } = yield* dryRun([999 "--stage",1000 "dev-oscabriel",1001 "--dry-run",1002 "--json",1003 "--url",1004 url,1005 ]);10061007 expect(printed).toHaveLength(1);10081009 const decoded = yield* Schema.decodeEffect(1010 Schema.fromJsonString(SwarmPlan)1011 )(printed[0] ?? "");10121013 expect(decoded.assignments.map(({ ask }) => ask)).toStrictEqual(1014 children1015 );10161017 const video = yield* dryRun([1018 "--stage",1019 "dev-oscabriel",1020 "--dry-run",1021 "--scenario",1022 "video",1023 "--url",1024 url,1025 ]);10261027 expect(1028 video.printed.filter((line) => line.startsWith("nudge for "))1029 ).toStrictEqual([1030 `nudge for tamsin (video): ${Option.getOrThrow(nudges("video", 1))}`,1031 `nudge for ivo (video): ${Option.getOrThrow(nudges("video", 2))}`,1032 ]);10331034 const videoJson = yield* dryRun([1035 "--stage",1036 "dev-oscabriel",1037 "--dry-run",1038 "--json",1039 "--scenario",1040 "video",1041 "--url",1042 url,1043 ]);10441045 const videoPlan = yield* Schema.decodeEffect(1046 Schema.fromJsonString(SwarmPlan)1047 )(videoJson.printed[0] ?? "");10481049 expect(1050 videoPlan.assignments.flatMap(({ contributor, nudge }) =>1051 nudge === undefined ? [] : [[contributor.handle, nudge]]1052 )1053 ).toStrictEqual([1054 ["tamsin", Option.getOrThrow(nudges("video", 1))],1055 ["ivo", Option.getOrThrow(nudges("video", 2))],1056 ]);1057 })1058 );1059});10601061/** A fictional person's token on the fake platform: never printed, never in an argv. */1062const tokenOf = (handle: string) =>1063 `${handle}-token-0123456789abcdef0123456789ab`;10641065/**1066 * `main` without `--dry-run`, over a fake platform: the CLI's `asks`, `ask`1067 * and `claim` answer from the fixtures, git succeeds, and `SESSION_TOKENS`1068 * holds `people`. The ledger and `.swarm/` are temp files.1069 */1070const fullRun = (1071 people: readonly string[],1072 /** The contributor whose claim the platform refuses with `AskFull`, if any. */1073 refused?: string1074) =>1075 Effect.gen(function* () {1076 const fs = yield* FileSystem.FileSystem;1077 const swarm = yield* fs.makeTempDirectoryScoped();1078 const ledger = `${swarm}/created.jsonl`;1079 const listed = yield* fixture("list-asks.json");10801081 const shown = (yield* fixture("show-ask.json")).replaceAll(1082 "{configDir}",1083 Brand.configDir1084 );10851086 const claimFor = (ask: string, token: string | undefined) => {1087 const handle = roster.find(1088 (one) => tokenOf(one.handle) === token1089 )?.handle;10901091 const fork = `burrow--${ask}--${handle ?? "nobody"}`;10921093 if (handle !== undefined && handle === refused) {1094 return Schema.encodeSync(Schema.fromJsonString(Claimed))({1095 command: "claim",1096 ok: false,1097 refusals: [new AskFull({ ask: AskId.make(ask) })],1098 v: 1,1099 });1100 }11011102 return JSON.stringify({1103 command: "claim",1104 data: {1105 claim: {1106 ask,1107 base: "9998ebe62c2f282d148b1d806372484916cc2548",1108 checkCommand: `${Brand.cli} check`,1109 claimant: handle,1110 fork,1111 lapsesAt: "2026-10-09T05:00:00.000Z",1112 openedAt: "2026-10-08T05:00:00.000Z",1113 project: "burrow",1114 remote: `${platformUrl}/${fork}.git`,1115 state: "live",1116 warnsAt: "2026-10-08T17:00:00.000Z",1117 },1118 },1119 ok: true,1120 v: 1,1121 });1122 };11231124 const fake = yield* fakeSpawner(({ args, command, env }) => {1125 if (command === "git") {1126 return args.includes("rev-parse")1127 ? { stdout: "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n" }1128 : {};1129 }11301131 const [, verb = "", ask = ""] = args;11321133 return (1134 {1135 ask: { stdout: shown },1136 asks: { stdout: listed },1137 claim: { stdout: claimFor(ask, env[`${SLUG}_TOKEN`]) },1138 }[verb] ?? { code: 1 }1139 );1140 });11411142 const printed: string[] = [];11431144 const captured: Console.Console = {1145 ...console,1146 error: (...args: readonly unknown[]) => {1147 printed.push(args.map(String).join(" "));1148 },1149 log: (...args: readonly unknown[]) => {1150 printed.push(args.map(String).join(" "));1151 },1152 };11531154 const sessions = Object.fromEntries(1155 people.map((handle) => [tokenOf(handle), handle])1156 );11571158 const result = yield* main([1159 "--stage",1160 "dev-oscabriel",1161 "--url",1162 platformUrl,1163 ]).pipe(1164 Effect.provide(fake.layer),1165 Effect.provideService(SwarmDir, swarm),1166 Effect.provideService(LedgerFile, ledger),1167 Effect.provideService(Console.Console, captured),1168 Effect.provideService(1169 ConfigProvider.ConfigProvider,1170 ConfigProvider.fromEnv({1171 env: { SESSION_TOKENS: JSON.stringify(sessions) },1172 })1173 ),1174 Effect.result1175 );11761177 // The TestClock's epoch names the run.1178 const summary = `${swarm}/19700101-000000/agents.json`;11791180 return {1181 agents: (yield* fs.exists(summary))1182 ? Option.some(yield* fs.readFileString(summary))1183 : Option.none<string>(),1184 ledger: yield* readLedger.pipe(Effect.provideService(LedgerFile, ledger)),1185 printed,1186 result,1187 spawned: yield* fake.spawned,1188 };1189 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));11901191describe("a run", () => {1192 it.effect(1193 "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",1194 () =>1195 Effect.gen(function* () {1196 const handles = roster.map(({ handle }) => handle);11971198 const { agents, ledger, printed, result, spawned } =1199 yield* fullRun(handles);12001201 expect(Result.isSuccess(result)).toBeTruthy();12021203 const claims = spawned.filter(({ args }) => args[1] === "claim");12041205 // Six at once: in whatever order they ran.1206 expect(1207 claims1208 .map(({ args, env }) => [args[2], env[`${SLUG}_TOKEN`]])1209 .toSorted(([one = ""], [other = ""]) => one.localeCompare(other))1210 ).toStrictEqual(1211 handles.map((handle, at) => [children[at], tokenOf(handle)])1212 );1213 expect(1214 ledger1215 .map(({ by, kind, name, namespace, stage }) => ({1216 by,1217 kind,1218 name,1219 namespace,1220 stage,1221 }))1222 .toSorted((one, other) => one.name.localeCompare(other.name))1223 ).toStrictEqual(1224 handles.map((handle, at) => ({1225 by: "swarm",1226 kind: "repo",1227 name: `burrow--${children[at] ?? ""}--${handle}`,1228 namespace: "projects-dev-oscabriel",1229 stage: "dev-oscabriel",1230 }))1231 );12321233 const summary = yield* Schema.decodeEffect(1234 Schema.fromJsonString(AgentsResult)1235 )(Option.getOrElse(agents, () => ""));12361237 expect(1238 summary.runs.map(({ handle, outcome }) => [handle, outcome])1239 ).toStrictEqual(handles.map((handle) => [handle, "failed"]));1240 expect(1241 [...printed, ...spawned.flatMap(({ args }) => args)].filter((text) =>1242 handles.some((handle) => text.includes(tokenOf(handle)))1243 )1244 ).toStrictEqual([]);1245 })1246 );12471248 it.effect(1249 "ends only the refused contributor's run, as failed with its refusal, and runs the other five",1250 () =>1251 Effect.gen(function* () {1252 const handles = roster.map(({ handle }) => handle);1253 const { agents, ledger, result } = yield* fullRun(handles, "ivo");12541255 expect(Result.isSuccess(result)).toBeTruthy();12561257 const summary = yield* Schema.decodeEffect(1258 Schema.fromJsonString(AgentsResult)1259 )(Option.getOrElse(agents, () => ""));12601261 expect(1262 summary.runs.map(({ attempts, handle, refusals }) => [1263 handle,1264 attempts,1265 refusals,1266 ])1267 ).toStrictEqual([1268 ["wren", 0, {}],1269 ["tamsin", 0, {}],1270 ["ivo", 0, { AskFull: 1 }],1271 ["marisol", 0, {}],1272 ["dagny", 0, {}],1273 ["pell", 0, {}],1274 ]);1275 // No claim, no fork: ivo's is never recorded for teardown.1276 expect(1277 ledger1278 .map(({ name }) => name.split("--").at(-1) ?? "")1279 .toSorted((one, other) => one.localeCompare(other))1280 ).toStrictEqual(["dagny", "marisol", "pell", "tamsin", "wren"]);1281 })1282 );12831284 it.effect(1285 "stops before any claim when SESSION_TOKENS has no session for a contributor, naming them",1286 () =>1287 Effect.gen(function* () {1288 const { result, spawned } = yield* fullRun(1289 roster.slice(0, 5).map(({ handle }) => handle)1290 );12911292 expect(1293 Option.map(Result.getFailure(result), ({ reason }) => reason)1294 ).toStrictEqual(1295 Option.some(1296 "SESSION_TOKENS has no session for pell: add each on the stage (human step H5 on demo), then run the swarm again"1297 )1298 );1299 expect(spawned.map(({ args }) => args[1])).toStrictEqual(["asks"]);1300 })1301 );1302});
added:scripts/lib/swarm/args.ts+261 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 */16import { Handle, ProjectName } from "@repo/protocol/ids";17import { Effect, Option, Schema } from "effect";1819import { flagValue, stageOf } from "../../../infra/stages.ts";20import type { Stage } from "../../../infra/stages.ts";21import { roster } from "./roster.ts";22import { ScenarioName } from "./scenario.ts";23import { SwarmFailed } from "./workspace.ts";2425/** What `bun scripts/swarm.ts` was asked to do. */26export 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}3839export 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>]";4142/** The flags that take a value. */43const VALUED = [44 "--project",45 "--scenario",46 "--stage",47 "--timeout-min",48 "--url",49 "--view",50] as const;5152/** The flags that stand alone. */53const SWITCHES = ["--allow-demo", "--dry-run", "--json"] as const;5455const failed = (reason: string) => new SwarmFailed({ reason });5657/** The handles `--only` names: each value after each `--only`, comma-separated or not. */58const onlyOf = (argv: readonly string[]) =>59 argv.flatMap((arg, at) => {60 if (arg.startsWith("--only=")) {61 return arg.slice("--only=".length).split(",");62 }6364 if (arg !== "--only") {65 return [];66 }6768 const rest = argv.slice(at + 1);69 const end = rest.findIndex((value) => value.startsWith("--"));7071 return (end === -1 ? rest : rest.slice(0, end)).flatMap((value) =>72 value.split(",")73 );74 });7576/** The arguments that are flags, with any `=value` cut off. */77const flagsIn = (argv: readonly string[]) =>78 argv.flatMap((arg) =>79 arg.startsWith("--") ? [arg.split("=")[0] ?? arg] : []80 );8182const isValued = (flag: string): flag is (typeof VALUED)[number] =>83 VALUED.some((valued) => valued === flag);8485/**86 * The words no flag takes: each valued flag takes the word after it (unless87 * it wrote `=value`), and `--only` every word up to the next flag.88 */89const straysIn = (argv: readonly string[]) => {90 const strays: string[] = [];91 let takes: "none" | "one" | "many" = "none";9293 for (const arg of argv) {94 if (arg.startsWith("--")) {95 const bare = !arg.includes("=");9697 if (bare && isValued(arg)) {98 takes = "one";99 } else {100 takes = bare && arg === "--only" ? "many" : "none";101 }102 } else if (takes === "none") {103 strays.push(arg);104 } else if (takes === "one") {105 takes = "none";106 }107 }108109 return strays;110};111112/** `raw` as the platform's origin, without a trailing `/`, if it is an http(s) URL. */113const originOf = (raw: string) =>114 Option.filter(115 Option.liftThrowable((url: string) => new URL(url))(raw),116 ({ protocol }) => protocol === "https:" || protocol === "http:"117 ).pipe(Option.as(raw.replace(/\/+$/u, "")));118119const decodeProject = Schema.decodeUnknownOption(ProjectName);120121const decodeScenario = Schema.decodeUnknownOption(ScenarioName);122123/** The swarm's options from its arguments, or why they don't make a run. */124export const optionsOf = (125 argv: readonly string[]126): Effect.Effect<SwarmOptions, SwarmFailed> =>127 Effect.gen(function* () {128 const known = new Set<string>([...VALUED, ...SWITCHES, "--only"]);129 const strange = flagsIn(argv).filter((flag) => !known.has(flag));130131 if (strange.length > 0) {132 return yield* failed(`unknown flag ${strange.join(", ")}: ${USAGE}`);133 }134135 // A switch read only by its bare spelling: `--dry-run=yes` would136 // otherwise pass as a known flag and leave the run live.137 const switchValue = argv.find((arg) =>138 SWITCHES.some((flag) => arg.startsWith(`${flag}=`))139 );140141 if (switchValue !== undefined) {142 return yield* failed(143 `${switchValue.split("=")[0] ?? switchValue} takes no value: ${USAGE}`144 );145 }146147 const valueless = VALUED.find(148 (flag) => argv.includes(flag) && Option.isNone(flagValue(argv, flag))149 );150151 if (valueless !== undefined) {152 return yield* failed(`${valueless} needs a value: ${USAGE}`);153 }154155 const strays = straysIn(argv);156157 if (strays.length > 0) {158 return yield* failed(159 `unexpected argument ${strays.join(", ")}: ${USAGE}`160 );161 }162163 // infra's own reading of `--stage`, and its words when it names none.164 const stage = yield* stageOf(argv).pipe(165 Effect.mapError(({ message }) => failed(`${message}. ${USAGE}`))166 );167168 if (stage === "demo" && !argv.includes("--allow-demo")) {169 return yield* failed(170 "--stage demo: its burrow family is for the recorded take (804); run it there only with --allow-demo"171 );172 }173174 const view = Option.getOrElse(flagValue(argv, "--view"), () => "headless");175176 if (view === "herdr") {177 return yield* failed(178 "--view herdr is not built yet (issue 717): run --view headless"179 );180 }181182 if (view !== "headless") {183 return yield* failed(`--view ${view}: headless or herdr`);184 }185186 const rawProject = Option.getOrElse(187 flagValue(argv, "--project"),188 () => "burrow"189 );190191 const project = yield* Effect.fromOption(decodeProject(rawProject)).pipe(192 Effect.mapError(() => failed(`--project ${rawProject} names no project`))193 );194195 const rawScenario = Option.getOrElse(196 flagValue(argv, "--scenario"),197 () => "plain"198 );199200 const scenario = yield* Effect.fromOption(decodeScenario(rawScenario)).pipe(201 Effect.mapError(() => failed(`--scenario ${rawScenario}: plain or video`))202 );203204 const rawTimeout = Option.getOrElse(205 flagValue(argv, "--timeout-min"),206 () => "20"207 );208209 const timeoutMin = Number(rawTimeout);210211 if (!Number.isInteger(timeoutMin) || timeoutMin < 1) {212 return yield* failed(213 `--timeout-min ${rawTimeout}: a whole number of minutes, 1 or more`214 );215 }216217 const named = onlyOf(argv).filter((handle) => handle !== "");218219 const only = yield* Effect.forEach(named, (handle) =>220 Effect.fromNullishOr(221 roster.find((contributor) => contributor.handle === handle)?.handle222 ).pipe(223 Effect.mapError(() =>224 failed(225 `--only ${handle} is not in the roster: ${roster.map((contributor) => contributor.handle).join(", ")}`226 )227 )228 )229 );230231 const onlyGiven = argv.some(232 (arg) => arg === "--only" || arg.startsWith("--only=")233 );234235 if (onlyGiven && only.length === 0) {236 return yield* failed("--only names no contributor");237 }238239 const url = yield* Effect.transposeOption(240 Option.map(flagValue(argv, "--url"), (raw) =>241 Effect.fromOption(originOf(raw)).pipe(242 Effect.mapError(() =>243 failed(244 `--url ${raw}: an http(s) origin, such as https://platform.example`245 )246 )247 )248 )249 );250251 return {252 dryRun: argv.includes("--dry-run"),253 json: argv.includes("--json"),254 only: [...new Set(only)].map((handle) => Handle.make(handle)),255 project,256 scenario,257 stage,258 timeoutMin,259 url,260 };261 });
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 */7import { Console, Effect, Match } from "effect";8import type { FileSystem } from "effect";9import type { ChildProcessSpawner } from "effect/process";1011import type { Assignment } from "./plan.ts";12import type { AgentRun } from "./results.ts";13import type { Contributor } from "./roster.ts";14import type { AgentWorkspace } from "./workspace.ts";1516/** One contributor's run: their harness on the brief, then the verdict loop. */17export 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>;2829/** Not built (711): says so, starts nothing, and records the run as `failed`. */30export const runAgent: RunAgent = ({ assignment }) =>31 Effect.gen(function* () {32 const { adapter, handle, harness, model } = assignment.contributor;3334 yield* Console.error(`${handle}: not built: 711`);3536 return {37 adapter,38 ask: assignment.ask,39 attempts: 0,40 durationMs: 0,41 handle,42 harness,43 model,44 outcome: "failed",45 refusals: {},46 };47 });4849/** The CLI's pi adapter (issue 706), which the adapter's agent loads with `-e`. */50const piAdapter = decodeURIComponent(51 new URL("../../../apps/cli/src/pi.ts", import.meta.url).pathname52);5354/**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 */61export 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;6768 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+158 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 */8import type { AskListing } from "@repo/protocol/domain/ask";9import { AskId, ProjectName } from "@repo/protocol/ids";10import type { Refusal } from "@repo/protocol/refusal";11import { Array, Option, Order, Result, Schema } from "effect";1213import { Contributor, roster } from "./roster.ts";14import { nudges, ScenarioName } from "./scenario.ts";1516/** One contributor's ask, and the territory (module) it may change. */17export const Assignment = Schema.Struct({18 ask: AskId,19 contributor: Contributor,20 /**21 * What the run's scenario adds to this contributor's brief. The plan22 * carries it, so the table and `--json` both show it: staging is never23 * hidden.24 */25 nudge: Schema.optionalKey(Schema.NonEmptyString),26 territory: Schema.NonEmptyString,27});2829export type Assignment = typeof Assignment.Type;3031/** The plan for one run: its assignments, and the asks it holds back. */32export const SwarmPlan = Schema.Struct({33 assignments: Schema.Array(Assignment),34 /** Open asks still blocked by others: a migrate family's delete child, say. */35 held: Schema.Array(AskId),36 project: ProjectName,37 scenario: ScenarioName,38 stage: Schema.NonEmptyString,39});4041export type SwarmPlan = typeof SwarmPlan.Type;4243/** Fewer asks can be handed out than the roster has contributors. */44export class NotEnoughAsks extends Schema.TaggedError<NotEnoughAsks>()(45 "NotEnoughAsks",46 { open: Schema.Int, wanted: Schema.Int }47) {48 override get message() {49 return `${this.wanted} contributors, but only ${this.open} open, unclaimed, unblocked asks on disjoint territories`;50 }51}5253/**54 * The refusals that end a contributor's claim, so the verdict loop (711)55 * stops on them. It bounces every other refusal back into the same session:56 * `retryable: true` means only that the same push may pass if sent again57 * (`StaleBase`, `RepoBusy`, `Flake`), while `OutOfScope`, `Weakened` and58 * `ChecksFailed` (`retryable: false`) are exactly what an agent fixes.59 */60export const endsClaim: ReadonlySet<Refusal["_tag"]> = new Set([61 "AskFull",62 "AttemptsExhausted",63 "ClaimLapsed",64 "Denounced",65 "NotClaimed",66 "NotVouched",67] as const satisfies readonly Refusal["_tag"][]);6869/** The whole repo as a territory: it overlaps every other one. */70const WHOLE_REPO = ".";7172/**73 * Whether two asks' territories overlap: the same module, or either one74 * the whole repo. A listing names only the module, so two modules that are75 * not the same are taken as disjoint (each is one workspace package).76 */77const overlaps = (one: string, other: string) =>78 one === other || one === WHOLE_REPO || other === WHOLE_REPO;7980/**81 * The nudge `scenario` gives `contributor`, by their place in the whole82 * roster, so a contributor planned alone (`--only`) is told what the full83 * run would tell them.84 */85const nudgeFor = (scenario: ScenarioName, contributor: Contributor) =>86 Option.match(87 nudges(88 scenario,89 roster.findIndex(({ handle }) => handle === contributor.handle)90 ),91 {92 onNone: () => ({}),93 onSome: (nudge) => ({ nudge }),94 }95 );9697/**98 * Plans a run: each contributor in `roster`, in roster order, gets one open,99 * unclaimed and unblocked ask, taken in `AskId` order, whose territory100 * overlaps no ask already handed out, and the nudge the scenario gives them.101 * An ask is blocked while any ask it waits on is still listed (`listAsks`102 * lists every ask not closed); blocked asks are held. With fewer asks to103 * hand out than contributors, the plan fails `NotEnoughAsks`, counting the104 * asks it could hand out.105 */106export const planSwarm = (input: {107 readonly roster: readonly Contributor[];108 readonly asks: readonly AskListing[];109 readonly stage: string;110 readonly project: ProjectName;111 readonly scenario: ScenarioName;112}): Result.Result<SwarmPlan, NotEnoughAsks> => {113 const listed = new Set<string>(input.asks.map(({ ask }) => ask));114115 const blocked = ({ blockedBy }: AskListing) =>116 blockedBy.some((waitsOn) => listed.has(waitsOn));117118 const unclaimed = Array.sort(119 input.asks.filter(({ claimed }) => !claimed),120 Order.mapInput(Order.String, ({ ask }: AskListing) => ask)121 );122123 const held = unclaimed.filter(blocked);124 const open = unclaimed.filter((listing) => !blocked(listing));125126 const disjoint: AskListing[] = [];127128 for (const listing of open) {129 if (130 !disjoint.some(({ territory }) => overlaps(territory, listing.territory))131 ) {132 disjoint.push(listing);133 }134 }135136 const wanted = input.roster.length;137138 if (disjoint.length < wanted) {139 return Result.fail(new NotEnoughAsks({ open: disjoint.length, wanted }));140 }141142 return Result.succeed({143 assignments: Array.zipWith(144 input.roster,145 disjoint,146 (contributor, { ask, territory }) => ({147 ask,148 contributor,149 territory,150 ...nudgeFor(input.scenario, contributor),151 })152 ),153 held: held.map(({ ask }) => ask),154 project: input.project,155 scenario: input.scenario,156 stage: input.stage,157 });158};
added:scripts/lib/swarm/prompt.ts+42 added
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 */9import { Context, Effect, FileSystem, Schema } from "effect";10import type { PlatformError } from "effect";1112/**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 */17export const SwarmDir = Context.Reference<string>("swarm/SwarmDir", {18 defaultValue: () =>19 decodeURIComponent(new URL("../../../.swarm", import.meta.url).pathname),20});2122/** A run's own folder: `.swarm/<run>`. */23export const runDir = (run: string) =>24 Effect.map(SwarmDir, (dir) => `${dir}/${run}`);2526/** The four harnesses a swarm contributor may run. */27export const Harness = Schema.Literals([28 "claude-code",29 "opencode",30 "amp",31 "pi",32]);3334export type Harness = typeof Harness.Type;3536/**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 */42export const AgentOutcome = Schema.Literals([43 "landed",44 "refused",45 "waiting",46 "noAnswer",47 "timedOut",48 "failed",49]);5051export type AgentOutcome = typeof AgentOutcome.Type;5253/** One contributor's run. */54export 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});6970export type AgentRun = typeof AgentRun.Type;7172/** A whole run: where it ran, from which commit, and each contributor's run. */73export 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});8384export type AgentsResult = typeof AgentsResult.Type;8586/** The file a run's summary is written to, below the swarm's folder. */87export const agentsFile = (dir: string) => `${dir}/agents.json`;8889/** Writes `result` to `.swarm/<run>/agents.json`, as indented JSON. */90export 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);9798 // An `AgentsResult` value always encodes: strings, numbers and a DateTime.99 const encoded = yield* Schema.encodeEffect(AgentsResult)(input.result).pipe(100 Effect.orDie101 );102103 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 */12import { Handle } from "@repo/protocol/ids";13import { Schema } from "effect";1415import { Harness } from "./results.ts";1617/** One contributor: a person, the harness they run, and its model. */18export 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});3031export type Contributor = typeof Contributor.Type;3233/**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 */37export 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
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 */8import { Brand } from "@repo/brand";9import type { ClaimView } from "@repo/protocol/domain/claim";10import { Config, Effect, FileSystem, Redacted, Schema, Stream } from "effect";11import { ChildProcess, ChildProcessSpawner } from "effect/process";1213import { runDir } from "./results.ts";14import type { Contributor } from "./roster.ts";1516/** The swarm could not do a step; the reason says which, and never holds a token. */17export class SwarmFailed extends Schema.TaggedError<SwarmFailed>()(18 "SwarmFailed",19 { reason: Schema.String }20) {21 override get message() {22 return this.reason;23 }24}2526/** Where one contributor works, and the env their harness runs in. */27export 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}3637/** The env names the CLI reads, spelled from the brand (`apps/cli/src/credentials.ts`). */38const SLUG = Brand.slug.toUpperCase();3940/** The person's platform token: the only identity the CLI and git present. */41export const TOKEN_VARIABLE = `${SLUG}_TOKEN`;4243/** The platform the CLI calls, with the token or, without one, as anyone. */44export const URL_VARIABLE = `${SLUG}_URL`;4546/** The profile the CLI would read instead of the env's token. */47const PROFILE_VARIABLE = `${SLUG}_PROFILE`;4849/** The CLI's process entry in this repo, run from source with Bun. */50export const cliEntry = decodeURIComponent(51 new URL("../../../apps/cli/src/bin.ts", import.meta.url).pathname52);5354/** A one-word shell argument: `'…'`, with any `'` inside closed and escaped. */55export const shellQuoted = (word: string) =>56 /^[\w./:@%+=,-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;5758/** A shim in `bin/`: a shell script that runs the CLI from source with `args` first. */59const 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");6667/** Owner, group and everyone may run a shim; only the owner writes it. */68const SHIM_MODE = 0o755;6970/** The workspace's config folder holds the CLI's credentials: owner only. */71const CONFIG_MODE = 0o700;7273/**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 */78export 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});8788/**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 */92export 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});101102/** `text` with every secret value of `env` (the names in `redacted`) blanked out. */103export const scrubbed = (104 text: string,105 workspace: Pick<AgentWorkspace, "env" | "redacted">106) => {107 let clean = text;108109 for (const name of workspace.redacted) {110 const secret = workspace.env[name];111112 if (secret !== undefined && secret !== "") {113 clean = clean.replaceAll(secret, "<redacted>");114 }115 }116117 return clean;118};119120/** All a byte stream says, as text. */121const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>122 bytes.pipe(Stream.decodeText(), Stream.mkString);123124/** How a process ended, and what it printed. */125export interface Ran {126 readonly code: number;127 readonly stdout: string;128 readonly stderr: string;129}130131/** `command args` in `cwd` with `env` over the swarm's own: how it ended, and what it printed. */132export 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;141142 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 );149150 const [stdout, stderr, code] = yield* Effect.all(151 [streamText(child.stdout), streamText(child.stderr), child.exitCode],152 { concurrency: "unbounded" }153 );154155 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 );163164/**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 */178export 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}`;198199 const path = yield* Config.String("PATH").pipe(200 Config.withDefault(""),201 Effect.orElseSucceed(() => "")202 );203204 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 );221222 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 };237238 const workspace: AgentWorkspace = {239 clone,240 dir,241 env,242 redacted: [TOKEN_VARIABLE],243 };244245 const credential = `credential.${input.platformUrl}`;246247 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 });266267 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 }275276 return workspace;277 });
modified:scripts/swarm.ts+549 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 */7import { BunRuntime } from "@effect/platform-bun";8import { Console, Effect, Runtime, Schema } from "effect";22import { BunRuntime, BunServices } from "@effect/platform-bun";23import { AskListing } from "@repo/protocol/domain/ask";24import { ClaimView } from "@repo/protocol/domain/claim";25import { Envelope } from "@repo/protocol/envelope";26import { Handle, sameHandle } from "@repo/protocol/ids";27import type { ProjectName } from "@repo/protocol/ids";28import type { Refusal } from "@repo/protocol/refusal";29import {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";4310/** The script is not built yet: the line it printed says where it will be. */11class NotBuilt extends Schema.TaggedError<NotBuilt>()("NotBuilt", {}) {12 override readonly [Runtime.errorExitCode] = 1;13 override readonly [Runtime.errorReported] = false;44import { readLedger, recordCreated } from "../infra/created.ts";45import {46 platformOrigin,47 repoRoot,48 resources,49 subdomainFile,50 WorkersDev,51} from "../infra/stages.ts";52import type { Stage } from "../infra/stages.ts";53import { optionsOf } from "./lib/swarm/args.ts";54import type { SwarmOptions } from "./lib/swarm/args.ts";55import { runAgent, startCommand } from "./lib/swarm/loop.ts";56import { planSwarm, SwarmPlan } from "./lib/swarm/plan.ts";57import type { Assignment } from "./lib/swarm/plan.ts";58import { brief } from "./lib/swarm/prompt.ts";59import {60 agentsFile,61 AgentsResult,62 runDir,63 SwarmDir,64 writeAgentsResult,65} from "./lib/swarm/results.ts";66import type { AgentRun } from "./lib/swarm/results.ts";67import { roster } from "./lib/swarm/roster.ts";68import {69 anonymousEnv,70 cliEntry,71 personEnv,72 prepareWorkspace,73 run,74 scrubbed,75 shellQuoted,76 SwarmFailed,77 TOKEN_VARIABLE,78} from "./lib/swarm/workspace.ts";79import type { Ran } from "./lib/swarm/workspace.ts";8081const failed = (reason: string) => new SwarmFailed({ reason });8283/** The env var that holds the stage's people: a JSON object from token to handle. */84const SESSIONS_VARIABLE = "SESSION_TOKENS";8586/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */87const originOf = (options: SwarmOptions) =>88 Option.match(options.url, {89 onNone: () =>90 Effect.gen(function* () {91 const fs = yield* FileSystem.FileSystem;92 const path = yield* Path.Path;93 const root = yield* repoRoot;9495 const recorded = yield* fs96 .readFileString(path.join(root, subdomainFile))97 .pipe(98 Effect.flatMap(99 Schema.decodeEffect(Schema.fromJsonString(WorkersDev))100 ),101 Effect.mapError(() =>102 failed(103 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`104 )105 )106 );107108 return platformOrigin(options.stage, recorded.subdomain);109 }),110 onSome: Effect.succeed,111 });112113/** One CLI command, run from this repo's source with Bun. */114const cli = (115 args: readonly string[],116 env: Readonly<Record<string, string | undefined>>117) => run({ args: [cliEntry, ...args], command: "bun", env });118119/** A refusal list in one line: `NotVouched, AskFull`. */120const tagsOf = (refusals: readonly Refusal[]) =>121 refusals.map(({ _tag }) => _tag).join(", ");122123/** The CLI refused the command: its refusals, for the run's summary. */124class Refused extends Schema.TaggedError<Refused>()("Refused", {125 reason: Schema.String,126 tags: Schema.Array(Schema.String),127}) {128 override get message() {129 return this.reason;130 }131}13216const main = Effect.gen(function* () {17 yield* Console.error(18 "not built: see .scratch/build/issues/702-swarm-plan.md"133/**134 * What one CLI command printed under `--json`, decoded as its envelope: its135 * data, or `Refused` with its refusals. Output that is no envelope fails136 * with what the command printed, `scrub`bed of any secret.137 */138const envelopeOf =139 <A, I>(140 data: Schema.Codec<A, I>,141 what: string,142 scrub: (text: string) => string143 ) =>144 (ran: Ran): Effect.Effect<A, SwarmFailed | Refused> =>145 Effect.gen(function* () {146 const printed = ran.stderr.trim() === "" ? ran.stdout : ran.stderr;147148 const envelope: Envelope<A> = yield* Schema.decodeEffect(149 Schema.fromJsonString(Envelope(data))150 )(ran.stdout).pipe(151 Effect.mapError(() =>152 failed(153 scrub(154 `${what} exited ${ran.code} without its JSON: ${printed.trim().slice(0, 500)}`155 )156 )157 )158 );159160 if (envelope.ok) {161 return envelope.data;162 }163164 return yield* new Refused({165 reason: `${what}: refused ${tagsOf(envelope.refusals)}`,166 tags: envelope.refusals.map(({ _tag }) => _tag),167 });168 });169170const isRefused = Schema.is(Refused);171172const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });173174/** The project's open asks, read anonymously: no token, and no stored login of the user's. */175const listAsks = (origin: string, project: ProjectName) =>176 Effect.gen(function* () {177 const home = `${yield* SwarmDir}/anonymous`;178179 const listed = yield* cli(180 ["asks", "--project", project, "--json"],181 anonymousEnv({ configHome: home, platformUrl: origin })182 ).pipe(183 Effect.flatMap(184 envelopeOf(Listed, `asks --project ${project}`, (text) => text)185 ),186 Effect.mapError(({ reason }) => failed(reason))187 );188189 return listed.asks;190 });191192/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */193const planLines = (194 plan: SwarmPlan,195 origin: string,196 swarm: string197): readonly string[] => {198 const rows = plan.assignments.map(({ ask, contributor, territory }) => {199 const dir = `${swarm}/<run>/${contributor.handle}`;200201 const command = startCommand({ brief: "<brief>", contributor, dir })202 .map(shellQuoted)203 .join(" ");204205 return [206 contributor.handle,207 contributor.harness,208 contributor.model,209 ask,210 territory,211 `cd ${shellQuoted(`${dir}/clone`)} && ${command}`,212 ];213 });214215 const header = ["handle", "harness", "model", "ask", "territory", "command"];216217 const widths = header.map((title, column) =>218 Math.max(title.length, ...rows.map((row) => row[column]?.length ?? 0))219 );22021 return yield* new NotBuilt();221 const line = (cells: readonly string[]) =>222 cells223 .map((cell, column) =>224 column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)225 )226 .join(" ");227228 const nudged = plan.assignments.flatMap(({ contributor, nudge }) =>229 nudge === undefined230 ? []231 : [`nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`]232 );233234 return [235 `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,236 line(header),237 ...rows.map(line),238 `held: ${plan.held.length === 0 ? "none" : plan.held.join(", ")}`,239 ...nudged,240 ];241};242243/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */244const runName = Effect.map(DateTime.now, (now) =>245 DateTime.formatIso(now)246 .slice(0, 19)247 .replaceAll(/[-:]/gu, "")248 .replace("T", "-")249);250251/** The commit of this repo the swarm runs from. */252const headCommit = Effect.gen(function* () {253 const root = yield* repoRoot;254255 const head = yield* run({256 args: ["-C", root, "rev-parse", "HEAD"],257 command: "git",258 env: {},259 });260261 return head.code === 0 && head.stdout.trim() !== ""262 ? head.stdout.trim()263 : yield* failed(`git rev-parse HEAD exited ${head.code}`);264});265266const decodeSessions = Schema.decodeUnknownEffect(267 Schema.fromJsonString(Schema.Record(Schema.String, Handle))268);269270/**271 * Each contributor's token, by handle, from `SESSION_TOKENS`; a missing272 * person fails before anything is claimed, naming them and never a token.273 */274const tokensFor = (handles: readonly Handle[]) =>275 Effect.gen(function* () {276 const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(277 Effect.mapError(() =>278 failed(279 `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`280 )281 )282 );283284 const sessions = yield* decodeSessions(raw).pipe(285 Effect.mapError(() =>286 failed(`${SESSIONS_VARIABLE} is not a JSON object from token to handle`)287 )288 );289290 const tokens = new Map(291 handles.flatMap((handle) => {292 const token = Object.entries(sessions).find(([, person]) =>293 sameHandle(person, handle)294 )?.[0];295296 return token === undefined297 ? []298 : [[handle, Redacted.make(token)] as const];299 })300 );301302 const missing = handles.filter((handle) => !tokens.has(handle));303304 return missing.length === 0305 ? tokens306 : yield* failed(307 `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each on the stage (human step H5 on demo), then run the swarm again`308 );309 });310311/** Records a claim's fork in the throwaway ledger, once. */312const recordFork = (stage: Stage, claim: ClaimView) =>313 Effect.gen(function* () {314 const namespace = resources(stage).projects;315316 const known = (yield* readLedger).some(317 (entry) =>318 entry.kind === "repo" &&319 entry.name === claim.fork &&320 entry.namespace === namespace &&321 entry.stage === stage322 );323324 if (!known) {325 yield* recordCreated({326 at: yield* DateTime.now,327 by: "swarm",328 kind: "repo",329 name: claim.fork,330 namespace,331 stage,332 });333 }334 }).pipe(335 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))336 );337338const Claimed = Schema.Struct({ claim: ClaimView });339340const Shown = Schema.Struct({341 ask: Schema.Struct({ id: Schema.NonEmptyString }),342 brief: Schema.NonEmptyString,343});344345/**346 * One contributor, from claim to the run loop: claims their ask as347 * themselves, reads its page, makes their workspace and hands it to348 * `runAgent`. A step that fails ends their run as `failed`, with any349 * refusals the claim met; it never stops the others.350 */351const contributorRun = (input: {352 readonly assignment: Assignment;353 readonly options: SwarmOptions;354 readonly origin: string;355 readonly run: string;356 readonly token: Redacted.Redacted;357}) =>358 Effect.gen(function* () {359 const { assignment, options, origin, token } = input;360 const { contributor } = assignment;361 const { handle } = contributor;362 const started = yield* Clock.currentTimeMillis;363 const configHome = `${yield* runDir(input.run)}/${handle}/config`;364 const env = personEnv({ configHome, platformUrl: origin, token });365366 const scrub = (text: string) =>367 scrubbed(text, { env, redacted: [TOKEN_VARIABLE] });368369 const setup = Effect.gen(function* () {370 const { claim } = yield* cli(371 ["claim", assignment.ask, "--project", options.project, "--json"],372 env373 ).pipe(374 Effect.flatMap(375 envelopeOf(Claimed, `${handle}: claim ${assignment.ask}`, scrub)376 )377 );378379 yield* recordFork(options.stage, claim);380381 const page = yield* cli(382 ["ask", assignment.ask, "--project", options.project, "--json"],383 env384 ).pipe(385 Effect.flatMap(386 envelopeOf(Shown, `${handle}: ask ${assignment.ask}`, scrub)387 )388 );389390 const workspace = yield* prepareWorkspace({391 claim,392 contributor,393 platformUrl: origin,394 run: input.run,395 token,396 });397398 return {399 text: brief({400 ask: assignment.ask,401 askMarkdown: page.brief,402 nudge: Option.fromUndefinedOr(assignment.nudge),403 project: options.project,404 remote: claim.remote,405 }),406 workspace,407 };408 });409410 const ready = yield* Effect.result(setup);411412 if (Result.isFailure(ready)) {413 const { failure } = ready;414 const ended = yield* Clock.currentTimeMillis;415416 yield* Console.error(`${handle}: ${scrub(failure.reason)}`);417418 return {419 adapter: contributor.adapter,420 ask: assignment.ask,421 attempts: 0,422 durationMs: ended - started,423 handle,424 harness: contributor.harness,425 model: contributor.model,426 outcome: "failed",427 refusals: Object.fromEntries(428 (isRefused(failure) ? failure.tags : []).map((tag) => [tag, 1])429 ),430 } satisfies AgentRun;431 }432433 yield* Console.error(434 `${handle}: claimed ${assignment.ask}; workspace ${ready.success.workspace.dir}`435 );436437 return yield* runAgent({438 assignment,439 brief: ready.success.text,440 maxContinuations: 3,441 timeoutMs: options.timeoutMin * 60_000,442 workspace: ready.success.workspace,443 });444 });445446/** One contributor's run as the summary prints it. */447const runLine = ({448 ask,449 attempts,450 handle,451 harness,452 outcome,453 refusals,454}: AgentRun) => {455 const met = Object.entries(refusals)456 .map(([tag, count]) => `${tag}×${count}`)457 .join(", ");458459 return `${handle} (${harness}) ${ask}: ${outcome}, ${attempts} attempts${met === "" ? "" : `, refused ${met}`}`;460};461462const printJson = <S extends Schema.Top>(schema: S, value: S["Type"]) =>463 Effect.flatMap(464 Schema.encodeEffect(Schema.fromJsonString(schema))(value),465 Console.log466 ).pipe(Effect.orDie);467468/**469 * `bun scripts/swarm.ts …`: plans the run from the project's open asks; with470 * `--dry-run`, prints the plan (or, with `--json`, the `SwarmPlan`) and471 * stops. Otherwise runs every contributor at once and writes the summary.472 */473export const main = (argv: readonly string[]) =>474 Effect.gen(function* () {475 const options = yield* optionsOf(argv);476 const origin = yield* originOf(options);477 const asks = yield* listAsks(origin, options.project);478479 const people =480 options.only.length === 0481 ? roster482 : roster.filter(({ handle }) => options.only.includes(handle));483484 const plan = yield* Effect.fromResult(485 planSwarm({486 asks,487 project: options.project,488 roster: people,489 scenario: options.scenario,490 stage: options.stage,491 })492 ).pipe(Effect.mapError(({ message }) => failed(message)));493494 const say = (line: string) =>495 options.json ? Effect.void : Console.log(line);496497 yield* Effect.forEach(planLines(plan, origin, yield* SwarmDir), say, {498 discard: true,499 });500501 if (options.dryRun) {502 yield* say("dry run: nothing claimed, no harness started");503504 if (options.json) {505 yield* printJson(SwarmPlan, plan);506 }507508 return;509 }510511 const tokens = yield* tokensFor(512 plan.assignments.map(({ contributor }) => contributor.handle)513 );514515 const name = yield* runName;516 const commit = yield* headCommit;517 const at = yield* DateTime.now;518519 const runs = yield* Effect.forEach(520 plan.assignments,521 (assignment) =>522 Effect.flatMap(523 Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),524 (token) =>525 contributorRun({ assignment, options, origin, run: name, token })526 ),527 { concurrency: 6 }528 ).pipe(Effect.mapError(() => failed("a contributor lost their token")));529530 const result: AgentsResult = {531 at,532 commit,533 project: options.project,534 runs,535 scenario: options.scenario,536 stage: options.stage,537 v: 1,538 };539540 yield* writeAgentsResult({ result, run: name }).pipe(541 Effect.mapError(({ message }) => failed(`agents.json: ${message}`))542 );543544 yield* Effect.forEach(runs.map(runLine), say, { discard: true });545 yield* say(`summary: ${agentsFile(yield* runDir(name))}`);546547 if (options.json) {548 yield* printJson(AgentsResult, result);549 }550 });551552if (import.meta.main) {24BunRuntime.runMain(main);553 BunRuntime.runMain(554 Effect.gen(function* () {555 const args = yield* (yield* Stdio.Stdio).args;556557 return yield* main(args);558 }).pipe(Effect.provide(BunServices.layer))559 );560}