Skip to content
Myr

swarm.ts

This file

Path

scripts/swarm.ts

588 lines · 17.6 KiB · TypeScript

Last changed by

Merge build/agents-private into mainoscabrielbefore adoptionb1f69d8

History of this file

Take it

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

lines 1–2why, one step back
1/**
2 * swarm: six fictional contributors, on four harnesses, each answer one child

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

lines 3–4why, one step back
3 * of a project's split family on a stage: it plans them, prepares each
4 * one's workspace and runs their harnesses.

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

line 5why, one step back
5 *

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 6why, one step back
6 * bun scripts/swarm.ts --stage dev-oscabriel --project oscabriel/burrow --dry-run

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 7–15why, one step back
7 * bunx varlock run --path apps/platform/ -- bun scripts/swarm.ts --stage dev-oscabriel
8 *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 of

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 16why, one step back
16 * the claim's fork, and is handed to the run loop, six at once. The

Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042

lines 17–18why, one step back
17 * run's summary goes to `<swarm>/<run>/agents.json` (`SwarmDir`: the state
18 * home's `<slug>/swarm/`, outside every checkout), and each claim's fork to

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 19–21why, one step back
19 * the throwaway ledger (`infra/created.ts`). Tokens reach a contributor's
20 * processes only through their env, and no line or JSON this prints holds21 * one. Flags: `lib/swarm/args.ts`.

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

line 22why, one step back
22 *

Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6

line 23why, one step back
23 * `--view herdr` (for the video) runs from a herdr pane: each

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 24–26why, one step back
24 * harness runs interactively in a pane of its own, with a counter pane of
25 * claims, pushes and landings (`lib/swarm/views/herdr.ts`). The loop and26 * its outcomes are the same.

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

line 27why, one step back
27 */

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 28–46why, one step back
28import { BunRuntime, BunServices } from "@effect/platform-bun";
29import { AskListing } from "@repo/protocol/domain/ask";30import { ClaimView } from "@repo/protocol/domain/claim";31import { Envelope } from "@repo/protocol/envelope";32import { Handle, sameHandle } from "@repo/protocol/ids";33import type { ProjectName } from "@repo/protocol/ids";34import type { Refusal } from "@repo/protocol/refusal";35import {36 Clock,37 Config,38 Console,39 DateTime,40 Effect,41 Option,42 Redacted,43 Result,44 Schema,45 Stdio,46} from "effect";

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

line 47why, one step back
47

Add bun infra/teardown.ts: it prints which of the ledger's throwaways still exist, and deletes exactly those only with --applyoscabrielbefore adoptionf2215bd

line 48why, one step back
48import { isRecorded, readLedger, recordCreated } from "../infra/created.ts";

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 49–50why, one step back
49import {
50 platformOrigin,

Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042

line 51why, one step back
51 recordedSubdomain,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 52–71why, one step back
52 repoRoot,
53 resources,54 subdomainFile,55} from "../infra/stages.ts";56import type { Stage } from "../infra/stages.ts";57import { optionsOf } from "./lib/swarm/args.ts";58import type { SwarmOptions } from "./lib/swarm/args.ts";59import { runAgent, startCommand } from "./lib/swarm/loop.ts";60import { planSwarm, SwarmPlan } from "./lib/swarm/plan.ts";61import type { Assignment } from "./lib/swarm/plan.ts";62import { brief } from "./lib/swarm/prompt.ts";63import {64 agentsFile,65 AgentsResult,66 runDir,67 SwarmDir,68 writeAgentsResult,69} from "./lib/swarm/results.ts";70import type { AgentRun } from "./lib/swarm/results.ts";71import { roster } from "./lib/swarm/roster.ts";

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 72–74why, one step back
72import { headlessView } from "./lib/swarm/views/headless.ts";
73import type { SwarmView } from "./lib/swarm/views/headless.ts";74import { openHerdrView } from "./lib/swarm/views/herdr.ts";

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 75–96why, one step back
75import {
76 anonymousEnv,77 cliEntry,78 personEnv,79 prepareWorkspace,80 run,81 scrubbed,82 shellQuoted,83 SwarmFailed,84 TOKEN_VARIABLE,85} from "./lib/swarm/workspace.ts";86import type { Ran } from "./lib/swarm/workspace.ts";8788const failed = (reason: string) => new SwarmFailed({ reason });8990/** The env var that holds the stage's people: a JSON object from token to handle. */91const SESSIONS_VARIABLE = "SESSION_TOKENS";9293/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */94const originOf = (options: SwarmOptions) =>95 Option.match(options.url, {96 onNone: () =>

Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkoutoscabrielbefore adoption842f042

lines 97–105why, one step back
97 recordedSubdomain.pipe(
98 Effect.flatMap(Effect.fromOption),99 Effect.mapError(() =>100 failed(101 `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`102 )103 ),104 Effect.map((subdomain) => platformOrigin(options.stage, subdomain))105 ),

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 106–126why, one step back
106 onSome: Effect.succeed,
107 });108109/** One CLI command, run from this repo's source with Bun. */110const cli = (111 args: readonly string[],112 env: Readonly<Record<string, string | undefined>>113) => run({ args: [cliEntry, ...args], command: "bun", env });114115/** A refusal list in one line: `NotVouched, AskFull`. */116const tagsOf = (refusals: readonly Refusal[]) =>117 refusals.map(({ _tag }) => _tag).join(", ");118119/** The CLI refused the command: its refusals, for the run's summary. */120class Refused extends Schema.TaggedError<Refused>()("Refused", {121 reason: Schema.String,122 tags: Schema.Array(Schema.String),123}) {124 override get message() {125 return this.reason;126 }

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

lines 127–128why, one step back
127}
128

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 129–214why, one step back
129/**
130 * What one CLI command printed under `--json`, decoded as its envelope: its131 * data, or `Refused` with its refusals. Output that is no envelope fails132 * with what the command printed, `scrub`bed of any secret.133 */134const envelopeOf =135 <A, I>(136 data: Schema.Codec<A, I>,137 what: string,138 scrub: (text: string) => string139 ) =>140 (ran: Ran): Effect.Effect<A, SwarmFailed | Refused> =>141 Effect.gen(function* () {142 const printed = ran.stderr.trim() === "" ? ran.stdout : ran.stderr;143144 const envelope: Envelope<A> = yield* Schema.decodeEffect(145 Schema.fromJsonString(Envelope(data))146 )(ran.stdout).pipe(147 Effect.mapError(() =>148 failed(149 scrub(150 `${what} exited ${ran.code} without its JSON: ${printed.trim().slice(0, 500)}`151 )152 )153 )154 );155156 if (envelope.ok) {157 return envelope.data;158 }159160 return yield* new Refused({161 reason: `${what}: refused ${tagsOf(envelope.refusals)}`,162 tags: envelope.refusals.map(({ _tag }) => _tag),163 });164 });165166const isRefused = Schema.is(Refused);167168const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });169170/** The project's open asks, read anonymously: no token, and no stored login of the user's. */171const listAsks = (origin: string, project: ProjectName) =>172 Effect.gen(function* () {173 const home = `${yield* SwarmDir}/anonymous`;174175 const listed = yield* cli(176 ["asks", "--project", project, "--json"],177 anonymousEnv({ configHome: home, platformUrl: origin })178 ).pipe(179 Effect.flatMap(180 envelopeOf(Listed, `asks --project ${project}`, (text) => text)181 ),182 Effect.mapError(({ reason }) => failed(reason))183 );184185 return listed.asks;186 });187188/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */189const planLines = (190 plan: SwarmPlan,191 origin: string,192 swarm: string193): readonly string[] => {194 const rows = plan.assignments.map(({ ask, contributor, territory }) => {195 const dir = `${swarm}/<run>/${contributor.handle}`;196197 const command = startCommand({ brief: "<brief>", contributor, dir })198 .map(shellQuoted)199 .join(" ");200201 return [202 contributor.handle,203 contributor.harness,204 contributor.model,205 ask,206 territory,207 `cd ${shellQuoted(`${dir}/clone`)} && ${command}`,208 ];209 });210211 const header = ["handle", "harness", "model", "ask", "territory", "command"];212213 const widths = header.map((title, column) =>214 Math.max(title.length, ...rows.map((row) => row[column]?.length ?? 0))

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

lines 215–216why, one step back
215 );
216

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 217–259why, one step back
217 const line = (cells: readonly string[]) =>
218 cells219 .map((cell, column) =>220 column === cells.length - 1 ? cell : cell.padEnd(widths[column] ?? 0)221 )222 .join(" ");223224 const nudged = plan.assignments.flatMap(({ contributor, nudge }) =>225 nudge === undefined226 ? []227 : [`nudge for ${contributor.handle} (${plan.scenario}): ${nudge}`]228 );229230 return [231 `swarm: ${plan.project} on ${plan.stage} (${origin}), scenario ${plan.scenario}, ${plan.assignments.length} contributors`,232 line(header),233 ...rows.map(line),234 `held: ${plan.held.length === 0 ? "none" : plan.held.join(", ")}`,235 ...nudged,236 ];237};238239/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */240const runName = Effect.map(DateTime.now, (now) =>241 DateTime.formatIso(now)242 .slice(0, 19)243 .replaceAll(/[-:]/gu, "")244 .replace("T", "-")245);246247/** The commit of this repo the swarm runs from. */248const headCommit = Effect.gen(function* () {249 const root = yield* repoRoot;250251 const head = yield* run({252 args: ["-C", root, "rev-parse", "HEAD"],253 command: "git",254 env: {},255 });256257 return head.code === 0 && head.stdout.trim() !== ""258 ? head.stdout.trim()259 : yield* failed(`git rev-parse HEAD exited ${head.code}`);

Name the swarm, seed and release scripts, and record every throwaway resource a live run makes in one ledgeroscabrielbefore adoptiond7064cb

lines 260–261why, one step back
260});
261

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 262–302why, one step back
262const decodeSessions = Schema.decodeUnknownEffect(
263 Schema.fromJsonString(Schema.Record(Schema.String, Handle))264);265266/**267 * Each contributor's token, by handle, from `SESSION_TOKENS`; a missing268 * person fails before anything is claimed, naming them and never a token.269 */270const tokensFor = (handles: readonly Handle[]) =>271 Effect.gen(function* () {272 const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(273 Effect.mapError(() =>274 failed(275 `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`276 )277 )278 );279280 const sessions = yield* decodeSessions(raw).pipe(281 Effect.mapError(() =>282 failed(`${SESSIONS_VARIABLE} is not a JSON object from token to handle`)283 )284 );285286 const tokens = new Map(287 handles.flatMap((handle) => {288 const token = Object.entries(sessions).find(([, person]) =>289 sameHandle(person, handle)290 )?.[0];291292 return token === undefined293 ? []294 : [[handle, Redacted.make(token)] as const];295 })296 );297298 const missing = handles.filter((handle) => !tokens.has(handle));299300 return missing.length === 0301 ? tokens302 : yield* failed(

Merge build/agents-private into mainoscabrielbefore adoptionb1f69d8

line 303why, one step back
303 `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each to the stage's ${SESSIONS_VARIABLE} secret (in the stage's secrets file, STAGE_SECRETS_FILE), and to the env the swarm runs in, then run the swarm again`

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 304–311why, one step back
304 );
305 });306307/** Records a claim's fork in the throwaway ledger, once. */308const recordFork = (stage: Stage, claim: ClaimView) =>309 Effect.gen(function* () {310 const namespace = resources(stage).projects;311

Add bun infra/teardown.ts: it prints which of the ledger's throwaways still exist, and deletes exactly those only with --applyoscabrielbefore adoptionf2215bd

lines 312–317why, one step back
312 const known = isRecorded(yield* readLedger, {
313 kind: "repo",314 name: claim.fork,315 namespace,316 stage,317 });

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 318–351why, one step back
318
319 if (!known) {320 yield* recordCreated({321 at: yield* DateTime.now,322 by: "swarm",323 kind: "repo",324 name: claim.fork,325 namespace,326 stage,327 });328 }329 }).pipe(330 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))331 );332333const Claimed = Schema.Struct({ claim: ClaimView });334335const Shown = Schema.Struct({336 ask: Schema.Struct({ id: Schema.NonEmptyString }),337 brief: Schema.NonEmptyString,338});339340/**341 * One contributor, from claim to the run loop: claims their ask as342 * themselves, reads its page, makes their workspace and hands it to343 * `runAgent`. A step that fails ends their run as `failed`, with any344 * refusals the claim met; it never stops the others.345 */346const contributorRun = (input: {347 readonly assignment: Assignment;348 readonly options: SwarmOptions;349 readonly origin: string;350 readonly run: string;351 readonly token: Redacted.Redacted;

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

line 352why, one step back
352 readonly view: SwarmView;

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 353–436why, one step back
353}) =>
354 Effect.gen(function* () {355 const { assignment, options, origin, token } = input;356 const { contributor } = assignment;357 const { handle } = contributor;358 const started = yield* Clock.currentTimeMillis;359 const configHome = `${yield* runDir(input.run)}/${handle}/config`;360 const env = personEnv({ configHome, platformUrl: origin, token });361362 const scrub = (text: string) =>363 scrubbed(text, { env, redacted: [TOKEN_VARIABLE] });364365 const setup = Effect.gen(function* () {366 const { claim } = yield* cli(367 ["claim", assignment.ask, "--project", options.project, "--json"],368 env369 ).pipe(370 Effect.flatMap(371 envelopeOf(Claimed, `${handle}: claim ${assignment.ask}`, scrub)372 )373 );374375 yield* recordFork(options.stage, claim);376377 const page = yield* cli(378 ["ask", assignment.ask, "--project", options.project, "--json"],379 env380 ).pipe(381 Effect.flatMap(382 envelopeOf(Shown, `${handle}: ask ${assignment.ask}`, scrub)383 )384 );385386 const workspace = yield* prepareWorkspace({387 claim,388 contributor,389 platformUrl: origin,390 run: input.run,391 token,392 });393394 return {395 text: brief({396 ask: assignment.ask,397 askMarkdown: page.brief,398 nudge: Option.fromUndefinedOr(assignment.nudge),399 project: options.project,400 remote: claim.remote,401 }),402 workspace,403 };404 });405406 const ready = yield* Effect.result(setup);407408 if (Result.isFailure(ready)) {409 const { failure } = ready;410 const ended = yield* Clock.currentTimeMillis;411412 yield* Console.error(`${handle}: ${scrub(failure.reason)}`);413414 return {415 adapter: contributor.adapter,416 ask: assignment.ask,417 attempts: 0,418 durationMs: ended - started,419 handle,420 harness: contributor.harness,421 model: contributor.model,422 outcome: "failed",423 refusals: Object.fromEntries(424 (isRefused(failure) ? failure.tags : []).map((tag) => [tag, 1])425 ),426 } satisfies AgentRun;427 }428429 yield* Console.error(430 `${handle}: claimed ${assignment.ask}; workspace ${ready.success.workspace.dir}`431 );432433 return yield* runAgent({434 assignment,435 brief: ready.success.text,436 maxContinuations: 3,

Read each swarm contributor's status for the swarm's project onlyoscabrielbefore adoption2b7b80c

line 437why, one step back
437 project: options.project,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

line 438why, one step back
438 timeoutMs: options.timeoutMin * 60_000,

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

line 439why, one step back
439 view: input.view,

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 440–516why, one step back
440 workspace: ready.success.workspace,
441 });442 });443444/** One contributor's run as the summary prints it. */445const runLine = ({446 ask,447 attempts,448 handle,449 harness,450 outcome,451 refusals,452}: AgentRun) => {453 const met = Object.entries(refusals)454 .map(([tag, count]) => `${tag}×${count}`)455 .join(", ");456457 return `${handle} (${harness}) ${ask}: ${outcome}, ${attempts} attempts${met === "" ? "" : `, refused ${met}`}`;458};459460const printJson = <S extends Schema.Top>(schema: S, value: S["Type"]) =>461 Effect.flatMap(462 Schema.encodeEffect(Schema.fromJsonString(schema))(value),463 Console.log464 ).pipe(Effect.orDie);465466/**467 * `bun scripts/swarm.ts …`: plans the run from the project's open asks; with468 * `--dry-run`, prints the plan (or, with `--json`, the `SwarmPlan`) and469 * stops. Otherwise runs every contributor at once and writes the summary.470 */471export const main = (argv: readonly string[]) =>472 Effect.gen(function* () {473 const options = yield* optionsOf(argv);474 const origin = yield* originOf(options);475 const asks = yield* listAsks(origin, options.project);476477 const people =478 options.only.length === 0479 ? roster480 : roster.filter(({ handle }) => options.only.includes(handle));481482 const plan = yield* Effect.fromResult(483 planSwarm({484 asks,485 project: options.project,486 roster: people,487 scenario: options.scenario,488 stage: options.stage,489 })490 ).pipe(Effect.mapError(({ message }) => failed(message)));491492 const say = (line: string) =>493 options.json ? Effect.void : Console.log(line);494495 yield* Effect.forEach(planLines(plan, origin, yield* SwarmDir), say, {496 discard: true,497 });498499 if (options.dryRun) {500 yield* say("dry run: nothing claimed, no harness started");501502 if (options.json) {503 yield* printJson(SwarmPlan, plan);504 }505506 return;507 }508509 const tokens = yield* tokensFor(510 plan.assignments.map(({ contributor }) => contributor.handle)511 );512513 const name = yield* runName;514 const commit = yield* headCommit;515 const at = yield* DateTime.now;516

Merge branch 'build/717-swarm-herdr-view'oscabrielbefore adoptionb2e66c8

lines 517–556why, one step back
517 const runs = yield* Effect.scoped(
518 Effect.gen(function* () {519 const view =520 options.view === "herdr"521 ? yield* openHerdrView({522 contributors: plan.assignments.map(523 ({ contributor }) => contributor524 ),525 origin,526 project: options.project,527 runDir: yield* runDir(name),528 }).pipe(529 Effect.tap(({ workspace }) =>530 say(531 `herdr: workspace ${workspace} holds the panes; close it with herdr workspace close ${workspace}`532 )533 ),534 Effect.map(({ view: panes }) => panes)535 )536 : headlessView;537538 return yield* Effect.forEach(539 plan.assignments,540 (assignment) =>541 Effect.flatMap(542 Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),543 (token) =>544 contributorRun({545 assignment,546 options,547 origin,548 run: name,549 token,550 view,551 })552 ),553 { concurrency: 6 }554 ).pipe(Effect.mapError(() => failed("a contributor lost their token")));555 })556 );

Merge branch 'build/702-swarm-plan'oscabrielbefore adoption8496778

lines 557–588why, one step back
557
558 const result: AgentsResult = {559 at,560 commit,561 project: options.project,562 runs,563 scenario: options.scenario,564 stage: options.stage,565 v: 1,566 };567568 yield* writeAgentsResult({ result, run: name }).pipe(569 Effect.mapError(({ message }) => failed(`agents.json: ${message}`))570 );571572 yield* Effect.forEach(runs.map(runLine), say, { discard: true });573 yield* say(`summary: ${agentsFile(yield* runDir(name))}`);574575 if (options.json) {576 yield* printJson(AgentsResult, result);577 }578 });579580if (import.meta.main) {581 BunRuntime.runMain(582 Effect.gen(function* () {583 const args = yield* (yield* Stdio.Stdio).args;584585 return yield* main(args);586 }).pipe(Effect.provide(BunServices.layer))587 );588}