Merge branch 'build/717-swarm-herdr-view'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 2b7b80c, cdfa9e6 · Browse files · 9 files·+2764 added−180 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+2764 added−180 removed
- tests:+1292 added−3 removed
- other:+1472 added−177 removed
Provenance
- Commit
b2e66c8- Tree
8ad40cf- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
2b7b80c- Parent 2
cdfa9e6
9 files changed+2764 added−180 removed
added:infra/created.jsonl+1 added
1+{"at":"2026-10-08T12:37:07.103Z","by":"swarm","kind":"repo","name":"burrow--drop-legacy-fetch-burrow-auth--wren","namespace":"projects-dev-oscabriel","stage":"dev-oscabriel"}added:packages/config/test/swarm-herdr.test.ts+1288 added
1+/**2+ * The swarm's herdr view (issue 717): six contributors in six herdr panes3+ * and a counter pane, for the video. The view decides only where a harness4+ * runs and how a prompt reaches it; the verdict loop and its outcomes (from5+ * `<cli> status --json`, never pane text) are 711's. The counter follows6+ * the project's `watch` and counts claims, pushes and landings.7+ */8+import { NodeServices } from "@effect/platform-node";9+import { describe, expect, it } from "@effect/vitest";10+import { AnswerView } from "@repo/protocol/domain/answer";11+import { ClaimView } from "@repo/protocol/domain/claim";12+import { ProjectEvent } from "@repo/protocol/domain/event";13+import { Outcome } from "@repo/protocol/domain/outcome";14+import { Envelope } from "@repo/protocol/envelope";15+import {16+ AskId,17+ CommitSha,18+ Handle,19+ LandedSha,20+ ProjectName,21+ RepoPath,22+ RequestId,23+} from "@repo/protocol/ids";24+import { OutOfScope } from "@repo/protocol/refusal";25+import { explain } from "@repo/protocol/render";26+import {27+ ConfigProvider,28+ Console,29+ DateTime,30+ Effect,31+ Fiber,32+ FileSystem,33+ Layer,34+ Option,35+ Path,36+ Ref,37+ Result,38+ Schema,39+ Sink,40+ Stream,41+} from "effect";42+import { ChildProcess, ChildProcessSpawner } from "effect/process";43+import { TestClock } from "effect/testing";44+45+import { LedgerFile } from "../../../infra/created.ts";46+import { repoRoot } from "../../../infra/stages.ts";47+import { piAdapter } from "../../../scripts/lib/swarm/harnesses/pi.ts";48+import { AgentsResult, SwarmDir } from "../../../scripts/lib/swarm/results.ts";49+import { roster } from "../../../scripts/lib/swarm/roster.ts";50+import {51+ counterLine,52+ followCounter,53+ lastHeld,54+} from "../../../scripts/lib/swarm/views/counter.ts";55+import { Turn } from "../../../scripts/lib/swarm/views/headless.ts";56+import {57+ herdrLayout,58+ herdrPrompt,59+ herdrStart,60+ herdrView,61+ interactiveLaunch,62+} from "../../../scripts/lib/swarm/views/herdr.ts";63+import type { AgentWorkspace } from "../../../scripts/lib/swarm/workspace.ts";64+import { main } from "../../../scripts/swarm.ts";65+import { Brand } from "../../brand/src/index.ts";66+67+const handles = ["wren", "tamsin", "ivo", "marisol", "dagny", "pell"];68+69+const children = ["auth", "billing", "catalog", "kit", "notify", "search"].map(70+ (module) => AskId.make(`drop-legacy-fetch-burrow-${module}`)71+);72+73+const sha = (digit: number) => CommitSha.make(String(digit).repeat(40));74+75+/** The `n`th event's place in the project's sequence, and its time. */76+const stamp = (n: number) => ({77+ at: DateTime.makeUnsafe(78+ `2026-10-08T12:${String(10 + n).padStart(2, "0")}:00.000Z`79+ ),80+ seq: 100 + n,81+});82+83+/**84+ * A take's events: six claims, nine pushes (three agents pushed twice), four85+ * landings, and events the counter does not count (a verdict, a released86+ * claim, an ask that opened).87+ */88+const takeEvents: readonly ProjectEvent[] = [89+ ...children.map((ask, at) =>90+ ProjectEvent.cases.Claimed.make({91+ ...stamp(at),92+ ask,93+ claimant: Handle.make(handles[at] ?? "wren"),94+ })95+ ),96+ ...[...children, ...children.slice(0, 3)].map((ask, at) =>97+ ProjectEvent.cases.Pushed.make({ ...stamp(6 + at), ask, head: sha(at) })98+ ),99+ ProjectEvent.cases.Judged.make({100+ ...stamp(15),101+ ask: AskId.make("drop-legacy-fetch-burrow-auth"),102+ head: sha(0),103+ outcome: Outcome.cases.Checking.make({ stage: "shape" }),104+ }),105+ ...children.slice(0, 4).map((ask, at) =>106+ ProjectEvent.cases.Landed.make({107+ ...stamp(16 + at),108+ landing: {109+ ask,110+ assisted: [],111+ author: Handle.make(handles[at] ?? "wren"),112+ credits: [],113+ landedAt: DateTime.makeUnsafe("2026-10-08T12:40:00.000Z"),114+ project: ProjectName.make("burrow"),115+ sha: LandedSha.make(sha(at + 5)),116+ },117+ })118+ ),119+ ProjectEvent.cases.Released.make({120+ ...stamp(20),121+ ask: AskId.make("drop-legacy-fetch-burrow-search"),122+ }),123+];124+125+describe("the counter", () => {126+ it.effect("reads a take's events as claims, pushes and landings", () =>127+ Effect.sync(() => {128+ expect(counterLine(takeEvents)).toBe("claims 6 · pushes 9 · landed 4");129+ expect(counterLine([])).toBe("claims 0 · pushes 0 · landed 0");130+ })131+ );132+});133+134+describe("the panes", () => {135+ it.effect(136+ "lay six contributors out in two rows of three over a counter strip, each split keeping its share",137+ () =>138+ Effect.sync(() => {139+ expect(herdrLayout(handles)).toStrictEqual([140+ { direction: "down", from: "wren", ratio: 0.85, slot: "counter" },141+ { direction: "down", from: "wren", ratio: 0.5, slot: "marisol" },142+ { direction: "right", from: "wren", ratio: 0.333, slot: "tamsin" },143+ { direction: "right", from: "tamsin", ratio: 0.5, slot: "ivo" },144+ { direction: "right", from: "marisol", ratio: 0.333, slot: "dagny" },145+ { direction: "right", from: "dagny", ratio: 0.5, slot: "pell" },146+ ]);147+ expect(herdrLayout(["wren"])).toStrictEqual([148+ { direction: "down", from: "wren", ratio: 0.85, slot: "counter" },149+ ]);150+ expect(151+ herdrLayout(handles.slice(0, 5)).map(({ slot }) => slot)152+ ).toStrictEqual(["counter", "marisol", "tamsin", "ivo", "dagny"]);153+ })154+ );155+156+ it.effect(157+ "start each harness interactively with its driver's flags, less what only headless mode needs",158+ () =>159+ Effect.sync(() => {160+ const launches = roster.map((contributor) =>161+ interactiveLaunch({162+ contributor,163+ dir: `/work/.swarm/r1/${contributor.handle}`,164+ })165+ );166+167+ expect(launches).toStrictEqual([168+ {169+ argv: [170+ "--permission-mode",171+ "bypassPermissions",172+ "--strict-mcp-config",173+ "--model",174+ "claude-opus-5-5",175+ ],176+ env: {},177+ kind: "claude",178+ },179+ {180+ argv: ["--standalone", "--auto"],181+ // OpenCode's interface takes no model flag: its inline config does.182+ env: { OPENCODE_CONFIG_CONTENT: '{"model":"openai/gpt-6.1-sol"}' },183+ kind: "opencode",184+ },185+ {186+ argv: [187+ "-m",188+ "medium",189+ "--settings-file",190+ "/work/.swarm/r1/ivo/amp-settings.json",191+ ],192+ env: {},193+ kind: "amp",194+ },195+ {196+ argv: [197+ "--no-mcp",198+ "--session-dir",199+ "/work/.swarm/r1/marisol/sessions",200+ "--session-id",201+ "marisol",202+ "--model",203+ "opencode-go/kimi-k3",204+ ],205+ env: {},206+ kind: "pi",207+ },208+ {209+ argv: [210+ "--no-mcp",211+ "--session-dir",212+ "/work/.swarm/r1/dagny/sessions",213+ "--session-id",214+ "dagny",215+ "--model",216+ "opencode-go/glm-5.3",217+ ],218+ env: {},219+ kind: "pi",220+ },221+ {222+ argv: [223+ "--no-mcp",224+ "--session-dir",225+ "/work/.swarm/r1/pell/sessions",226+ "--session-id",227+ "pell",228+ "--model",229+ "opencode/gemini-3.8-flash",230+ "-e",231+ piAdapter,232+ ],233+ env: {},234+ kind: "pi",235+ },236+ ]);237+ })238+ );239+240+ it.effect(241+ "start an agent in its pane by name, and prompt it by name, waiting until it settles",242+ () =>243+ Effect.sync(() => {244+ expect(245+ herdrStart({246+ argv: ["--model", "claude-opus-5-5"],247+ handle: "wren",248+ kind: "claude",249+ pane: "w9:p1",250+ })251+ ).toStrictEqual([252+ "agent",253+ "start",254+ "wren",255+ "--kind",256+ "claude",257+ "--pane",258+ "w9:p1",259+ "--timeout",260+ "120000",261+ "--",262+ "--model",263+ "claude-opus-5-5",264+ ]);265+ expect(266+ herdrPrompt({ handle: "wren", text: "Answer the ask." })267+ ).toStrictEqual([268+ "agent",269+ "prompt",270+ "wren",271+ "Answer the ask.",272+ "--wait",273+ ]);274+ })275+ );276+});277+278+/** The env names the CLI reads, spelled from the brand. */279+const SLUG = Brand.slug.toUpperCase();280+281+const platformUrl = "https://platform-dev-oscabriel.example.workers.dev";282+283+const tokenOf = (handle: string) =>284+ `${handle}-token-0123456789abcdef0123456789ab`;285+286+/** Whose token `env` carries, if anyone's. */287+const holderOf = (env: Readonly<Record<string, string | undefined>>) =>288+ handles.find((handle) => env[`${SLUG}_TOKEN`] === tokenOf(handle));289+290+/** One command the fake world was asked to run. */291+interface Spawned {292+ readonly command: string;293+ readonly args: readonly string[];294+ readonly env: Readonly<Record<string, string | undefined>>;295+}296+297+/** How a faked command ends: its exit code and what it printed. */298+interface Ending {299+ readonly code?: number;300+ readonly stdout?: string;301+ readonly stderr?: string;302+}303+304+const bytes = (text: string) => Stream.make(new TextEncoder().encode(text));305+306+/**307+ * A `ChildProcessSpawner` that runs nothing: it records each command and308+ * ends it as `answer` says.309+ */310+const fakeSpawner = (answer: (call: Spawned) => Effect.Effect<Ending>) =>311+ Effect.gen(function* () {312+ const spawned = yield* Ref.make<readonly Spawned[]>([]);313+314+ const spawner = ChildProcessSpawner.make((command) =>315+ Effect.gen(function* () {316+ if (!ChildProcess.isStandardCommand(command)) {317+ return yield* Effect.die("the swarm pipes no commands");318+ }319+320+ const call: Spawned = {321+ args: command.args,322+ command: command.command,323+ env: command.options.env ?? {},324+ };325+326+ yield* Ref.update(spawned, (calls) => [...calls, call]);327+328+ const { code = 0, stderr = "", stdout = "" } = yield* answer(call);329+330+ return ChildProcessSpawner.makeHandle({331+ all: bytes(stdout),332+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),333+ getInputFd: () => Sink.drain,334+ getOutputFd: () => Stream.empty,335+ isRunning: Effect.succeed(false),336+ kill: () => Effect.void,337+ pid: ChildProcessSpawner.ProcessId(1),338+ stderr: bytes(stderr),339+ stdin: Sink.drain,340+ stdout: bytes(stdout),341+ unref: Effect.succeed(Effect.void),342+ });343+ })344+ );345+346+ return {347+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),348+ spawned: Ref.get(spawned),349+ };350+ });351+352+/** A swarm fixture's text. */353+const fixture = (name: string) =>354+ Effect.gen(function* () {355+ const fs = yield* FileSystem.FileSystem;356+ const path = yield* Path.Path;357+358+ return yield* fs.readFileString(359+ path.join("test", "fixtures", "swarm", name)360+ );361+ });362+363+const outOfScope = new OutOfScope({364+ paths: [RepoPath.make("packages/billing/src/index.ts")],365+});366+367+const StatusJson = Schema.fromJsonString(368+ Envelope(369+ Schema.Struct({370+ answers: Schema.Array(AnswerView),371+ claims: Schema.Array(ClaimView),372+ handle: Handle,373+ })374+ )375+);376+377+/** `handle`'s answer to `ask`, the `n`th they pushed, with its outcome. */378+const answerOf = (379+ handle: string,380+ ask: AskId,381+ n: number,382+ outcome: Outcome383+): AnswerView => ({384+ ask,385+ at: DateTime.makeUnsafe(`2026-10-08T12:00:0${n}.000Z`),386+ head: sha(n),387+ outcome,388+ requestId: RequestId.make(`push-${sha(n)}-${handle}`),389+});390+391+const landed = Outcome.cases.Landed.make({ sha: LandedSha.make(sha(9)) });392+393+/**394+ * What `handle`'s `<cli> status --json` prints on its `call`th read: wren's395+ * first answer is refused for leaving its territory and the next one lands;396+ * everyone else's first answer lands.397+ */398+const statusOf = (handle: string, call: number) => {399+ const ask = children[handles.indexOf(handle)] ?? AskId.make("unknown");400+401+ const refused = answerOf(402+ handle,403+ ask,404+ 1,405+ Outcome.cases.Refused.make({ refusals: [outOfScope] })406+ );407+408+ const answers =409+ handle === "wren"410+ ? [refused, ...(call > 1 ? [answerOf(handle, ask, 2, landed)] : [])]411+ : [answerOf(handle, ask, 1, landed)];412+413+ return Schema.encodeSync(StatusJson)({414+ command: "status",415+ data: { answers, claims: [], handle: Handle.make(handle) },416+ ok: true,417+ v: 1,418+ });419+};420+421+/** herdr's answer for a pane it made. */422+const paneJson = (pane: string) =>423+ JSON.stringify({424+ id: "cli:pane:split",425+ result: { pane: { pane_id: pane, workspace_id: "w9" }, type: "pane_info" },426+ });427+428+/** herdr's answer for an agent that is idle and ready for input. */429+const agentJson = (name: string, type: string) =>430+ JSON.stringify({431+ id: `cli:agent:${type}`,432+ result: {433+ agent: {434+ agent: "claude",435+ agent_status: "idle",436+ interactive_ready: true,437+ name,438+ pane_id: "w9:p1",439+ },440+ type,441+ },442+ });443+444+/** What `<cli> claim <ask> --json` prints for `handle`. */445+const claimOf = (ask: string, handle: string) => {446+ const fork = `burrow--${ask}--${handle}`;447+448+ return JSON.stringify({449+ command: "claim",450+ data: {451+ claim: {452+ ask,453+ base: "9998ebe62c2f282d148b1d806372484916cc2548",454+ checkCommand: `${Brand.cli} check`,455+ claimant: handle,456+ fork,457+ lapsesAt: "2026-10-09T05:00:00.000Z",458+ openedAt: "2026-10-08T05:00:00.000Z",459+ project: "burrow",460+ remote: `${platformUrl}/${fork}.git`,461+ state: "live",462+ warnsAt: "2026-10-08T17:00:00.000Z",463+ },464+ },465+ ok: true,466+ v: 1,467+ });468+};469+470+/**471+ * The platform, git and herdr, faked for a whole `--view herdr` run: the472+ * CLI's `asks`, `ask` and `claim` answer from the fixtures, each473+ * contributor's `status` from `statusOf`, git and `mkfifo` succeed, herdr474+ * makes panes `w9:p1`, `w9:p2`, … and every agent settles idle, and the475+ * counter's `watch` hears nothing new. `replay` is how the counter's read476+ * of where the project stands ends: an empty replay unless a test says.477+ */478+const herdrWorld = (replay: Ending) =>479+ Effect.gen(function* () {480+ const panes = yield* Ref.make(1);481+ const reads = yield* Ref.make(new Map<string, number>());482+ const listed = yield* fixture("list-asks.json");483+484+ const shown = (yield* fixture("show-ask.json")).replaceAll(485+ "{configDir}",486+ Brand.configDir487+ );488+489+ const answer = (call: Spawned) =>490+ Effect.gen(function* () {491+ const { args, command, env } = call;492+ const [first = "", second = "", third = ""] = args;493+494+ if (command === "herdr") {495+ if (first === "workspace") {496+ return JSON.stringify({497+ id: "cli:workspace:create",498+ result: {499+ root_pane: { pane_id: "w9:p1", workspace_id: "w9" },500+ type: "workspace_created",501+ workspace: { workspace_id: "w9" },502+ },503+ });504+ }505+506+ if (second === "split") {507+ return paneJson(508+ `w9:p${yield* Ref.updateAndGet(panes, (n) => n + 1)}`509+ );510+ }511+512+ if (first === "agent") {513+ return agentJson(514+ third,515+ second === "start" ? "agent_started" : "agent_prompted"516+ );517+ }518+519+ return JSON.stringify({ id: "cli:pane", result: { type: "ok" } });520+ }521+522+ if (command === "git") {523+ return "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n";524+ }525+526+ if (first === "status") {527+ const handle = holderOf(env) ?? "nobody";528+529+ const count =530+ (yield* Ref.updateAndGet(reads, (seen) =>531+ new Map(seen).set(handle, (seen.get(handle) ?? 0) + 1)532+ )).get(handle) ?? 1;533+534+ return statusOf(handle, count);535+ }536+537+ return (538+ {539+ ask: shown,540+ asks: listed,541+ claim: claimOf(third, holderOf(env) ?? "nobody"),542+ }[second] ?? ""543+ );544+ });545+546+ return yield* fakeSpawner((call) => {547+ if (call.command !== "curl") {548+ return Effect.map(answer(call), (stdout) => ({ stdout }));549+ }550+551+ // The read of where the project stands is plain JSON; the follow hears nothing.552+ return Effect.succeed(553+ call.args.includes("content-type: application/json") ? replay : {}554+ );555+ });556+ });557+558+/** `watch`'s plain JSON replay of a project that holds no event yet. */559+const emptyReplay: Ending = {560+ stdout:561+ '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',562+};563+564+/** What herdr puts in the env of a process in one of its panes. */565+const inAPane = { HERDR_ENV: "1" };566+567+/**568+ * `main --view herdr` for every contributor over `herdrWorld`, from a herdr569+ * pane unless `herdrEnv` says otherwise, the counter's read of the project570+ * ending as `replay`, with `.swarm/` and the ledger in a temp dir.571+ */572+const herdrRunWith = (573+ herdrEnv: Readonly<Record<string, string>>,574+ replay: Ending = emptyReplay575+) =>576+ Effect.gen(function* () {577+ const fs = yield* FileSystem.FileSystem;578+ const swarm = yield* fs.makeTempDirectoryScoped();579+ const world = yield* herdrWorld(replay);580+ const printed: string[] = [];581+582+ const captured: Console.Console = {583+ ...console,584+ error: (...args: readonly unknown[]) => {585+ printed.push(args.map(String).join(" "));586+ },587+ log: (...args: readonly unknown[]) => {588+ printed.push(args.map(String).join(" "));589+ },590+ };591+592+ const sessions = Object.fromEntries(593+ handles.map((handle) => [tokenOf(handle), handle])594+ );595+596+ const result = yield* main([597+ "--stage",598+ "dev-oscabriel",599+ "--url",600+ platformUrl,601+ "--view",602+ "herdr",603+ ]).pipe(604+ Effect.provide(world.layer),605+ Effect.provideService(SwarmDir, swarm),606+ Effect.provideService(LedgerFile, `${swarm}/created.jsonl`),607+ Effect.provideService(Console.Console, captured),608+ Effect.provideService(609+ ConfigProvider.ConfigProvider,610+ ConfigProvider.fromEnv({611+ env: {612+ ...herdrEnv,613+ HOME: "/home/user",614+ SESSION_TOKENS: JSON.stringify(sessions),615+ SHELL: "/usr/bin/zsh",616+ TERM: "xterm-256color",617+ },618+ })619+ ),620+ Effect.result621+ );622+623+ // The TestClock's epoch names the run.624+ const run = `${swarm}/19700101-000000`;625+ const summary = `${run}/agents.json`;626+ const wrensScript = `${run}/wren/pane-shell`;627+628+ return {629+ agents: (yield* fs.exists(summary))630+ ? Option.some(yield* fs.readFileString(summary))631+ : Option.none<string>(),632+ printed,633+ result,634+ root: (yield* repoRoot).replace(/\/$/u, ""),635+ run,636+ spawned: yield* world.spawned,637+ wrensScript: (yield* fs.exists(wrensScript))638+ ? yield* fs.readFileString(wrensScript)639+ : "",640+ };641+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));642+643+const herdrRun = herdrRunWith(inAPane);644+645+/** The herdr calls of a run, as argv. */646+const herdrCalls = (spawned: readonly Spawned[]) =>647+ spawned.flatMap(({ args, command }) => (command === "herdr" ? [args] : []));648+649+/** The `agent <verb>` calls among `calls`, by the agent's name. */650+const agentCalls = (calls: readonly (readonly string[])[], verb: string) =>651+ calls.flatMap((call) =>652+ call[0] === "agent" && call[1] === verb653+ ? [{ args: call, name: call[2] ?? "" }]654+ : []655+ );656+657+/** The pane each contributor's harness runs in: the layout's order over `w9:p1`, `w9:p2`, …. */658+const paneOf = new Map([659+ ["wren", "w9:p1"],660+ ["counter", "w9:p2"],661+ ["marisol", "w9:p3"],662+ ["tamsin", "w9:p4"],663+ ["ivo", "w9:p5"],664+ ["dagny", "w9:p6"],665+ ["pell", "w9:p7"],666+]);667+668+const byName = (669+ one: { readonly name: string },670+ other: { readonly name: string }671+) => one.name.localeCompare(other.name);672+673+describe("a run in herdr's panes", () => {674+ it.effect(675+ "lays the panes out in a workspace of their own, with a counter pane that shows the run's counter file",676+ () =>677+ Effect.gen(function* () {678+ const { result, root, run, spawned } = yield* herdrRun;679+ const calls = herdrCalls(spawned);680+681+ expect(Result.isSuccess(result)).toBeTruthy();682+ expect(calls.slice(0, 7)).toStrictEqual([683+ [684+ "workspace",685+ "create",686+ "--cwd",687+ root,688+ "--label",689+ "swarm burrow",690+ "--focus",691+ ],692+ ...[693+ ["w9:p1", "down", "0.85"],694+ ["w9:p1", "down", "0.5"],695+ ["w9:p1", "right", "0.333"],696+ ["w9:p4", "right", "0.5"],697+ ["w9:p3", "right", "0.333"],698+ ["w9:p6", "right", "0.5"],699+ ].map(([pane = "", direction = "", ratio = ""]) => [700+ "pane",701+ "split",702+ pane,703+ "--direction",704+ direction,705+ "--ratio",706+ ratio,707+ "--cwd",708+ root,709+ "--no-focus",710+ ]),711+ ]);712+ expect(calls).toContainEqual([713+ "pane",714+ "run",715+ "w9:p2",716+ `clear; tail -n +1 -F ${run}/counter.log`,717+ ]);718+ expect(calls).toContainEqual([719+ "pane",720+ "rename",721+ "w9:p1",722+ "wren · claude-code",723+ ]);724+ })725+ );726+727+ it.effect(728+ "starts each contributor's harness in their pane with their driver's flags",729+ () =>730+ Effect.gen(function* () {731+ const { run, spawned } = yield* herdrRun;732+ const starts = agentCalls(herdrCalls(spawned), "start");733+734+ expect(starts.toSorted(byName).map(({ args }) => args)).toStrictEqual(735+ roster736+ .map((contributor) => {737+ const { argv, kind } = interactiveLaunch({738+ contributor,739+ dir: `${run}/${contributor.handle}`,740+ });741+742+ return {743+ args: [744+ "agent",745+ "start",746+ contributor.handle,747+ "--kind",748+ kind,749+ "--pane",750+ paneOf.get(contributor.handle) ?? "",751+ "--timeout",752+ "120000",753+ "--",754+ ...argv,755+ ],756+ name: contributor.handle,757+ };758+ })759+ .toSorted(byName)760+ .map(({ args }) => args)761+ );762+ // wren's harness is Claude Code, started with the headless run's763+ // safety flags: every tool allowed, no MCP server of the user's.764+ expect(765+ starts.find(({ name }) => name === "wren")?.args.slice(9)766+ ).toStrictEqual([767+ "--",768+ "--permission-mode",769+ "bypassPermissions",770+ "--strict-mcp-config",771+ "--model",772+ "claude-opus-5-5",773+ ]);774+ })775+ );776+777+ it.effect(778+ "sends each contributor's brief into their pane's session and waits until it settles",779+ () =>780+ Effect.gen(function* () {781+ const { spawned } = yield* herdrRun;782+ const prompts = agentCalls(herdrCalls(spawned), "prompt");783+784+ const firsts = handles.map(785+ (handle) => prompts.find(({ name }) => name === handle)?.args ?? []786+ );787+788+ expect(789+ firsts.map((prompt) => [prompt[2], prompt[4], prompt.length])790+ ).toStrictEqual(handles.map((handle) => [handle, "--wait", 5]));791+ expect(792+ firsts.map((prompt, at) =>793+ (prompt[3] ?? "").includes(children[at] ?? "?")794+ )795+ ).toStrictEqual(handles.map(() => true));796+ })797+ );798+799+ it.effect(800+ "sends a refusal back into the same pane's session as a second prompt, and reads the outcome only from status",801+ () =>802+ Effect.gen(function* () {803+ const { agents, spawned } = yield* herdrRun;804+805+ const wrens = agentCalls(herdrCalls(spawned), "prompt").filter(806+ ({ name }) => name === "wren"807+ );808+809+ expect(wrens).toHaveLength(2);810+ expect(wrens[1]?.args[3]).toContain(811+ [...explain([outOfScope]), "", `Next: ${outOfScope.next}`].join("\n")812+ );813+814+ const summary = yield* Schema.decodeEffect(815+ Schema.fromJsonString(AgentsResult)816+ )(Option.getOrElse(agents, () => ""));817+818+ expect(819+ summary.runs.map(({ attempts, handle, outcome, refusals }) => [820+ handle,821+ outcome,822+ attempts,823+ refusals,824+ ])825+ ).toStrictEqual(826+ handles.map((handle) =>827+ handle === "wren"828+ ? [handle, "landed", 2, { OutOfScope: 1 }]829+ : [handle, "landed", 1, {}]830+ )831+ );832+ })833+ );834+835+ it.effect(836+ "refuses outside a herdr pane, before anything is claimed, rather than drive whichever session is focused",837+ () =>838+ Effect.gen(function* () {839+ const { result, spawned } = yield* herdrRunWith({});840+841+ expect(842+ Result.match(result, {843+ onFailure: ({ reason }) => reason,844+ onSuccess: () => "",845+ })846+ ).toContain("start the swarm from a herdr pane");847+ expect(848+ spawned.flatMap(({ args, command }) =>849+ command === "herdr" || args[1] === "claim" ? [args] : []850+ )851+ ).toStrictEqual([]);852+ })853+ );854+855+ it.effect(856+ "stops before it opens a pane or claims anything when the counter can't read where the project stands",857+ () =>858+ Effect.gen(function* () {859+ const { result, spawned } = yield* herdrRunWith(inAPane, {860+ code: 7,861+ stderr:862+ "curl: (7) Failed to connect to platform-dev-oscabriel.example.workers.dev port 443\n",863+ });864+865+ expect(866+ Result.match(result, {867+ onFailure: ({ reason }) => reason,868+ onSuccess: () => "",869+ })870+ ).toBe(871+ "the counter couldn't read burrow's events: curl exited 7: curl: (7) Failed to connect to platform-dev-oscabriel.example.workers.dev port 443"872+ );873+ expect(874+ spawned.flatMap(({ args, command }) =>875+ command === "herdr" || args[1] === "claim" ? [args] : []876+ )877+ ).toStrictEqual([]);878+ })879+ );880+881+ it.effect(882+ "hands each pane its contributor's env through a pipe, so no token is in any argv, script or line",883+ () =>884+ Effect.gen(function* () {885+ const { printed, run, spawned, wrensScript } = yield* herdrRun;886+887+ expect(888+ spawned.flatMap(({ args, command }) =>889+ command === "mkfifo" ? [args] : []890+ )891+ ).toContainEqual(["-m", "600", `${run}/wren/pane-env`]);892+ expect(herdrCalls(spawned)).toContainEqual([893+ "pane",894+ "run",895+ "w9:p1",896+ `exec ${run}/wren/pane-shell`,897+ ]);898+ expect(wrensScript).toContain(`${run}/wren/pane-env`);899+ expect(900+ [901+ wrensScript,902+ ...printed,903+ ...spawned.flatMap(({ args }) => args),904+ ].filter((text) =>905+ handles.some((handle) => text.includes(tokenOf(handle)))906+ )907+ ).toStrictEqual([]);908+ })909+ );910+});911+912+/** What herdr's detection text shows while Claude Code 2.1.293 asks whether to trust a new folder. */913+const trustQuestion = [914+ " Accessing workspace:",915+ "",916+ " Quick safety check: Is this a project you created or one you trust?",917+ "",918+ " ❯ No, exit",919+ " Yes, I trust this folder",920+].join("\n");921+922+/**923+ * …and then whether to import the CLAUDE.md files above the clone, "No"924+ * under the cursor (live, Enter left the clone's925+ * `hasClaudeMdExternalIncludesApproved` false).926+ */927+const importsQuestion = [928+ " Allow external CLAUDE.md file imports?",929+ "",930+ " ❯ No, disable external imports",931+ " Yes, allow external imports",932+].join("\n");933+934+const [wren] = roster;935+936+/** wren's workspace for run `r1`. */937+const wrensWorkspace: AgentWorkspace = {938+ clone: "/work/.swarm/r1/wren/clone",939+ dir: "/work/.swarm/r1/wren",940+ env: { [`${SLUG}_TOKEN`]: tokenOf("wren") },941+ redacted: [`${SLUG}_TOKEN`],942+};943+944+/** The first of `queue`, taken off it unless it is the last. */945+const takeFrom = (queue: Ref.Ref<readonly string[]>) =>946+ Ref.modify(queue, (all) => [947+ all[0] ?? "",948+ all.length > 1 ? all.slice(1) : all,949+ ]);950+951+/**952+ * wren's first attempt in herdr's pane `w9:p1`, where herdr finds Claude953+ * Code blocked at startup: each `agent get` says the next of `states`954+ * (`blocked` until the last), and each `agent read` shows the next of955+ * `screens`. Files are kept in memory, so the TestClock moves as `clock`956+ * says, deterministically.957+ */958+const blockedStart = (input: {959+ readonly states: readonly string[];960+ readonly screens: readonly string[];961+ readonly clock: Effect.Effect<void>;962+}) =>963+ Effect.gen(function* () {964+ const states = yield* Ref.make(input.states);965+ const screens = yield* Ref.make(input.screens);966+967+ const world = yield* fakeSpawner(({ args, command }) =>968+ Effect.gen(function* () {969+ if (command !== "herdr" || args[0] !== "agent") {970+ return {};971+ }972+973+ if (args[1] === "start") {974+ return {975+ code: 1,976+ stderr: JSON.stringify({977+ error: {978+ code: "agent_not_ready",979+ message:980+ "agent wren is blocked during startup and is not ready for prompts",981+ },982+ id: "cli:agent:start",983+ }),984+ };985+ }986+987+ if (args[1] === "get") {988+ const status = yield* takeFrom(states);989+990+ return {991+ stdout: JSON.stringify({992+ result: {993+ agent: {994+ agent_status: status,995+ interactive_ready: status === "idle",996+ },997+ },998+ }),999+ };1000+ }1001+1002+ if (args[1] === "read") {1003+ return { stdout: yield* takeFrom(screens) };1004+ }1005+1006+ return args[1] === "prompt"1007+ ? { stdout: agentJson("wren", "agent_prompted") }1008+ : {};1009+ })1010+ );1011+1012+ const files = new Map<string, string>();1013+1014+ const memoryFs = FileSystem.makeNoop({1015+ chmod: () => Effect.void,1016+ remove: () => Effect.void,1017+ writeFileString: (path, data, options) =>1018+ Effect.sync(() => {1019+ files.set(1020+ path,1021+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data1022+ );1023+ }),1024+ });1025+1026+ const fiber = yield* herdrView(new Map([["wren", "w9:p1"]]))1027+ .attempt({1028+ contributor: wren,1029+ env: { HOME: "/home/user", ...wrensWorkspace.env },1030+ file: `${wrensWorkspace.dir}/attempt-1.jsonl`,1031+ onSession: Effect.void,1032+ turn: Turn.Start({ brief: "Answer the ask." }),1033+ workspace: wrensWorkspace,1034+ })1035+ .pipe(1036+ Effect.provide(world.layer),1037+ Effect.provideService(FileSystem.FileSystem, memoryFs),1038+ Effect.result,1039+ Effect.forkChild1040+ );1041+1042+ yield* input.clock;1043+1044+ return {1045+ calls: herdrCalls(yield* world.spawned),1046+ result: yield* Fiber.join(fiber),1047+ };1048+ });1049+1050+describe("a harness blocked at startup", () => {1051+ it.effect(1052+ "gets Claude Code past its folder-trust and CLAUDE.md-import questions as the swarm decides, then sends the brief",1053+ () =>1054+ Effect.gen(function* () {1055+ const { calls, result } = yield* blockedStart({1056+ clock: TestClock.adjust("10 seconds"),1057+ screens: [trustQuestion, trustQuestion, importsQuestion],1058+ states: ["blocked", "blocked", "blocked", "idle"],1059+ });1060+1061+ expect(1062+ agentCalls(calls, "send-keys").map(({ args }) => args)1063+ ).toStrictEqual([1064+ ["agent", "send-keys", "wren", "down", "enter"],1065+ ["agent", "send-keys", "wren", "enter"],1066+ ]);1067+ expect(1068+ agentCalls(calls, "prompt").map(({ args }) => args)1069+ ).toStrictEqual([1070+ ["agent", "prompt", "wren", "Answer the ask.", "--wait"],1071+ ]);1072+ expect(1073+ Result.map(result, ({ heard }) => [heard.session, heard.settled])1074+ ).toStrictEqual(Result.succeed([Option.some("wren"), true]));1075+ })1076+ );1077+1078+ it.effect(1079+ "leaves a question it doesn't know to the person at the panes, and fails the run when nobody answers it",1080+ () =>1081+ Effect.gen(function* () {1082+ const { calls, result } = yield* blockedStart({1083+ clock: TestClock.adjust("4 minutes"),1084+ screens: [" Do you want to enable telemetry?\n ❯ Yes\n No"],1085+ states: ["blocked"],1086+ });1087+1088+ expect(agentCalls(calls, "send-keys")).toStrictEqual([]);1089+ expect(1090+ Result.match(result, {1091+ onFailure: ({ reason }) => reason,1092+ onSuccess: () => "",1093+ })1094+ ).toBe(1095+ "claude-code is still blocked at startup in herdr pane w9:p1: answer it there, or run --view headless"1096+ );1097+ })1098+ );1099+});1100+1101+/**1102+ * What dev-oscabriel's `/rpc` answered `watch` for burrow over plain JSON1103+ * on 2026-10-08 (two of its eight events, the others cut): the frames at1104+ * once, then the exit.1105+ */1106+const replayed = [1107+ '[{"_tag":"Chunk","requestId":"1","values":[',1108+ '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":7,"ask":{"ask":"drop-legacy-fetch-burrow-notify","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/notify","want":"@burrow/notify: 1 caller of legacyFetch → http.get"}},',1109+ '{"_tag":"AskOpened","at":"2026-10-08T05:21:35.148Z","seq":8,"ask":{"ask":"drop-legacy-fetch-burrow-search","blockedBy":[],"claimed":false,"kind":"migrate","territory":"@burrow/search","want":"@burrow/search: 1 caller of legacyFetch → http.get"}}',1110+ ']},{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',1111+].join("");1112+1113+/**1114+ * The framed stream's lines, as dev-oscabriel sends them over NDJSON: one1115+ * frame per line. The first repeats an event the counter already heard1116+ * (a claim, so a counter that heard it twice would say so).1117+ */1118+const streamed = [1119+ '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:00:00.000Z","seq":8,"ask":"drop-legacy-fetch-burrow-billing","claimant":"tamsin"}]}',1120+ '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:05:00.000Z","seq":9,"ask":"drop-legacy-fetch-burrow-auth","claimant":"wren"}]}',1121+ `{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Pushed","at":"2026-10-08T12:06:00.000Z","seq":10,"ask":"drop-legacy-fetch-burrow-auth","head":"${"1".repeat(40)}"},{"_tag":"Released","at":"2026-10-08T12:07:00.000Z","seq":11,"ask":"drop-legacy-fetch-burrow-kit"}]}`,1122+ '{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}',1123+].join("\n");1124+1125+describe("the counter's watch", () => {1126+ it.effect(1127+ "starts after the last event the project holds, from watch's plain JSON replay",1128+ () =>1129+ Effect.gen(function* () {1130+ const world = yield* fakeSpawner(() =>1131+ Effect.succeed({ stdout: replayed })1132+ );1133+1134+ const from = yield* lastHeld(1135+ platformUrl,1136+ ProjectName.make("burrow")1137+ ).pipe(Effect.provide(world.layer));1138+1139+ expect(from).toBe(8);1140+ expect((yield* world.spawned).map(({ args }) => args)).toStrictEqual([1141+ [1142+ "--silent",1143+ "--show-error",1144+ "--fail",1145+ "--no-buffer",1146+ "--request",1147+ "POST",1148+ "--header",1149+ "content-type: application/json",1150+ "--data-binary",1151+ '[{"_tag":"Request","headers":[],"id":"1","payload":{"project":"burrow"},"tag":"watch"}]',1152+ `${platformUrl}/rpc`,1153+ ],1154+ ]);1155+ })1156+ );1157+1158+ it.effect(1159+ "refuses to guess where to start when the project's events can't be read, rather than count its whole history",1160+ () =>1161+ Effect.gen(function* () {1162+ const reasons = yield* Effect.forEach(1163+ [1164+ {1165+ code: 22,1166+ stderr: "curl: (22) The requested URL returned error: 502\n",1167+ },1168+ { stdout: "<html>502 Bad Gateway</html>" },1169+ ],1170+ (ending) =>1171+ Effect.gen(function* () {1172+ const world = yield* fakeSpawner(() => Effect.succeed(ending));1173+1174+ const read = yield* lastHeld(1175+ platformUrl,1176+ ProjectName.make("burrow")1177+ ).pipe(Effect.provide(world.layer), Effect.result);1178+1179+ return Result.match(read, {1180+ onFailure: ({ reason }) => reason,1181+ onSuccess: (from) => `counts from event ${from}`,1182+ });1183+ })1184+ );1185+1186+ expect(reasons).toStrictEqual([1187+ "the counter couldn't read burrow's events: curl exited 22: curl: (22) The requested URL returned error: 502",1188+ "the counter couldn't read burrow's events: <html>502 Bad Gateway</html>",1189+ ]);1190+ })1191+ );1192+1193+ it.effect("says once why it can't follow watch, and keeps trying", () =>1194+ Effect.gen(function* () {1195+ const world = yield* fakeSpawner(() =>1196+ Effect.succeed({1197+ code: 22,1198+ stderr: "curl: (22) The requested URL returned error: 503\n",1199+ })1200+ );1201+1202+ const files = new Map<string, string>();1203+1204+ const memoryFs = FileSystem.makeNoop({1205+ writeFileString: (path, data, options) =>1206+ Effect.sync(() => {1207+ files.set(1208+ path,1209+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data1210+ );1211+ }),1212+ });1213+1214+ const fiber = yield* followCounter({1215+ file: "/work/counter.log",1216+ from: 8,1217+ origin: platformUrl,1218+ project: ProjectName.make("burrow"),1219+ }).pipe(1220+ Effect.provide(world.layer),1221+ Effect.provideService(FileSystem.FileSystem, memoryFs),1222+ Effect.forkChild1223+ );1224+1225+ yield* TestClock.adjust("5 seconds");1226+ yield* Fiber.interrupt(fiber);1227+1228+ expect(files.get("/work/counter.log")?.split("\n")).toStrictEqual([1229+ "claims 0 · pushes 0 · landed 0 (burrow, after event 8)",1230+ "counter: watch didn't run: curl exited 22: curl: (22) The requested URL returned error: 503",1231+ "",1232+ ]);1233+ expect((yield* world.spawned).length).toBeGreaterThan(1);1234+ })1235+ );1236+1237+ it.effect(1238+ "follows the framed stream after that event and writes a line per claim, push and landing",1239+ () =>1240+ Effect.gen(function* () {1241+ const world = yield* fakeSpawner(() =>1242+ Effect.succeed({ stdout: streamed })1243+ );1244+1245+ const files = new Map<string, string>();1246+1247+ const memoryFs = FileSystem.makeNoop({1248+ writeFileString: (path, data, options) =>1249+ Effect.sync(() => {1250+ files.set(1251+ path,1252+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data1253+ );1254+ }),1255+ });1256+1257+ const fiber = yield* followCounter({1258+ file: "/work/counter.log",1259+ from: 8,1260+ origin: platformUrl,1261+ project: ProjectName.make("burrow"),1262+ }).pipe(1263+ Effect.provide(world.layer),1264+ Effect.provideService(FileSystem.FileSystem, memoryFs),1265+ Effect.forkChild1266+ );1267+1268+ yield* TestClock.adjust("1 second");1269+ yield* Fiber.interrupt(fiber);1270+1271+ expect(files.get("/work/counter.log")?.split("\n")).toStrictEqual([1272+ "claims 0 · pushes 0 · landed 0 (burrow, after event 8)",1273+ "12:05:00 claims 1 · pushes 0 · landed 0 wren claimed drop-legacy-fetch-burrow-auth",1274+ "12:06:00 claims 1 · pushes 1 · landed 0 drop-legacy-fetch-burrow-auth pushed 1111111",1275+ "",1276+ ]);1277+ expect(1278+ (yield* world.spawned).map(({ args }) => args.slice(7, 10))1279+ ).toStrictEqual([1280+ [1281+ "content-type: application/ndjson",1282+ "--data-binary",1283+ '{"_tag":"Request","headers":[],"id":"1","payload":{"project":"burrow","since":8},"tag":"watch"}\n',1284+ ],1285+ ]);1286+ })1287+ );1288+});modified:packages/config/test/swarm.test.ts+4 added-3 removed
766 unmodified lines767 scenario: "plain",768 stage: "dev-oscabriel",769 timeoutMin: 20,770 url: Option.none(),771+ view: "headless",772 });773 })774 );775 24 unmodified lines800 })801 );802 803 it.effect(803- "refuses demo without --allow-demo, the herdr view until 717, no stage, and a flag it doesn't know",804+ "refuses demo without --allow-demo, a view it doesn't have, no stage, and a flag it doesn't know",805 () =>806 Effect.gen(function* () {807 const reasons = yield* Effect.forEach(808 [809 ["--stage", "demo", "--dry-run"],809- ["--stage", "dev-oscabriel", "--view", "herdr"],810+ ["--stage", "dev-oscabriel", "--view", "tmux"],811 ["--dry-run"],812 ["--stage", "dev-oscabriel", "--yes"],813 ["--stage", "dev-oscabriel", "--timeout-min", "0"],814 ],4 unmodified lines819 reasons.map((reason, at) =>820 reason.includes(821 [822 "--allow-demo",822- "717",823+ "--view tmux: headless or herdr",824 "no --stage",825 "unknown flag --yes",826 "--timeout-min 0",827 ][at] ?? "?"535 unmodified linesadded:scripts/lib/swarm/views/counter.ts+310 added
1+/**2+ * The herdr view's counter: claims, pushes and landings in the swarm's3+ * project as they happen, for the video's live tally (SYN §7.3, beat4+ * 2:15–3:45). It follows the project's public `watch`, so it counts what5+ * the platform recorded, never what a pane printed.6+ *7+ * `watch` streams over the platform's framed `/rpc` (NDJSON, issue 510).8+ * The swarm's scripts reach the network only through processes (their9+ * allow-list grants `effect/process`), so `curl` carries the call, as the10+ * swarm's other steps run git, the CLI and herdr. A run counts from the last11+ * event the project already holds (`lastHeld`), appends one line to the12+ * counter file per claim, push and landing, and follows again from the13+ * last event it heard whenever the stream ends (a held stream does end:14+ * Bun's `fetch` at 361 s, spec §7.4).15+ */16+import { ProjectEvent } from "@repo/protocol/domain/event";17+import type { ProjectName } from "@repo/protocol/ids";18+import {19+ Array,20+ DateTime,21+ Duration,22+ Effect,23+ FileSystem,24+ Option,25+ Ref,26+ Schedule,27+ Schema,28+ Stream,29+} from "effect";30+import { ChildProcess, ChildProcessSpawner } from "effect/process";31+32+import { run, SwarmFailed } from "../workspace.ts";33+34+/** The events the counter counts. */35+const counted = (event: ProjectEvent) =>36+ ProjectEvent.guards.Claimed(event) ||37+ ProjectEvent.guards.Pushed(event) ||38+ ProjectEvent.guards.Landed(event);39+40+/** The counter's line for `events`: `claims 6 · pushes 9 · landed 4`. Pure. */41+export const counterLine = (events: readonly ProjectEvent[]): string => {42+ const claims = events.filter(ProjectEvent.guards.Claimed).length;43+ const pushes = events.filter(ProjectEvent.guards.Pushed).length;44+ const landings = events.filter(ProjectEvent.guards.Landed).length;45+46+ return `claims ${claims} · pushes ${pushes} · landed ${landings}`;47+};48+49+const short = (sha: string) => sha.slice(0, 7);50+51+/** What one counted event says, in a few words; the others say nothing. */52+const happening = (event: ProjectEvent) =>53+ ProjectEvent.match(event, {54+ AskClosed: () => "",55+ AskOpened: () => "",56+ Claimed: ({ ask, claimant }) => `${claimant} claimed ${ask}`,57+ Decided: () => "",58+ Judged: () => "",59+ Landed: ({ landing }) =>60+ `${landing.ask ?? "main"} landed as ${short(landing.sha)}`,61+ Lapsed: () => "",62+ LedgerAppended: () => "",63+ ProposalOpened: () => "",64+ Pushed: ({ ask, head }) => `${ask} pushed ${short(head)}`,65+ Released: () => "",66+ Warned: () => "",67+ });68+69+/**70+ * The counter file's line for `event`, the last of `events`: when it71+ * happened (UTC), the tally so far, and what happened. Pure.72+ */73+export const counterEntry = (74+ events: readonly ProjectEvent[],75+ event: ProjectEvent76+) =>77+ `${DateTime.formatIso(event.at).slice(11, 19)} ${counterLine(events)} ${happening(event)}`;78+79+/** One call as effect/rpc's protocol frames it (as `infra/smoke.ts` sends one). */80+const WatchCall = Schema.TaggedStruct("Request", {81+ headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),82+ id: Schema.String,83+ payload: Schema.Struct({84+ project: Schema.String,85+ since: Schema.optionalKey(Schema.Int),86+ }),87+ tag: Schema.Literal("watch"),88+});89+90+const encodeCall = Schema.encodeSync(Schema.fromJsonString(WatchCall));91+92+/** `watch` for `project`, after event `since` when given one, as JSON. */93+const watchRequest = (project: ProjectName, since: Option.Option<number>) =>94+ encodeCall(95+ WatchCall.make({96+ headers: [],97+ id: "1",98+ payload: Option.match(since, {99+ onNone: () => ({ project }),100+ onSome: (after) => ({ project, since: after }),101+ }),102+ tag: "watch",103+ })104+ );105+106+/** A frame of a stream's values, as the platform's `/rpc` sends one. */107+const ChunkOf = <S extends Schema.Top>(value: S) =>108+ Schema.TaggedStruct("Chunk", { values: Schema.Array(value) });109+110+/** A frame of events, read only for where each stands in the project's sequence. */111+const Held = ChunkOf(Schema.Struct({ seq: Schema.Int }));112+113+const isHeld = Schema.is(Held);114+115+/** What `watch` answers over plain JSON: every frame at once (any other is its exit). */116+const decodeReplay = Schema.decodeUnknownOption(117+ Schema.fromJsonString(118+ Schema.Array(Schema.Union([Held, Schema.Struct({ _tag: Schema.String })]))119+ )120+);121+122+/** One line of the framed stream, when it is a frame of values. */123+const decodeLine = Schema.decodeUnknownOption(124+ Schema.fromJsonString(ChunkOf(Schema.Unknown))125+);126+127+const eventOf = Schema.decodeUnknownOption(ProjectEvent);128+129+/**130+ * The events one line of the stream carries. A line that is no chunk (the131+ * stream's exit) carries none, and an event this build cannot read is132+ * skipped.133+ */134+export const eventsIn = (line: string): readonly ProjectEvent[] =>135+ Option.match(decodeLine(line), {136+ onNone: () => [],137+ onSome: ({ values }) =>138+ Array.getSomes(values.map((value) => eventOf(value))),139+ });140+141+/**142+ * `curl`'s flags for one POST to the platform's `/rpc` with `contentType`:143+ * an HTTP error fails it (`--fail`), and only its errors reach stderr.144+ */145+const curlArgs = (input: {146+ readonly origin: string;147+ readonly contentType: string;148+ readonly body: string;149+}) => [150+ "--silent",151+ "--show-error",152+ "--fail",153+ "--no-buffer",154+ "--request",155+ "POST",156+ "--header",157+ `content-type: ${input.contentType}`,158+ "--data-binary",159+ input.body,160+ `${input.origin}/rpc`,161+];162+163+/** Why the counter can't say where `project` stands: what curl or the platform said. */164+const unread = (project: ProjectName, said: string) =>165+ new SwarmFailed({166+ reason: `the counter couldn't read ${project}'s events: ${said.trim().slice(0, 300)}`,167+ });168+169+/**170+ * The last event `project` already holds, where a run's counter starts:171+ * `watch` over plain JSON replays what the project keeps and ends; 0 when172+ * it holds none. A read that fails is the run's failure, not 0: a counter173+ * that started from 0 would count the project's whole history as the run's.174+ */175+export const lastHeld = (origin: string, project: ProjectName) =>176+ Effect.gen(function* () {177+ const ran = yield* run({178+ args: curlArgs({179+ body: `[${watchRequest(project, Option.none())}]`,180+ contentType: "application/json",181+ origin,182+ }),183+ command: "curl",184+ env: {},185+ }).pipe(Effect.mapError(({ reason }) => unread(project, reason)));186+187+ if (ran.code !== 0) {188+ return yield* unread(project, `curl exited ${ran.code}: ${ran.stderr}`);189+ }190+191+ const frames = yield* Effect.fromOption(decodeReplay(ran.stdout)).pipe(192+ Effect.mapError(() => unread(project, ran.stdout))193+ );194+195+ return Math.max(196+ 0,197+ ...frames.flatMap((frame) =>198+ isHeld(frame) ? frame.values.map(({ seq }) => seq) : []199+ )200+ );201+ });202+203+/** Where the counter stands: the last event heard, and every counted one since the run began. */204+interface Tally {205+ readonly last: number;206+ readonly events: readonly ProjectEvent[];207+}208+209+/** How long the counter waits before it follows `watch` again. */210+const FOLLOW_AGAIN = Duration.seconds(2);211+212+/**213+ * Follows `project`'s `watch` at `origin` after event `from` (`lastHeld`,214+ * read before the run claims anything), appending a line to `file` for215+ * every claim, push and landing; it never ends on its own (interrupt it216+ * when the run is over).217+ */218+export const followCounter = (input: {219+ readonly origin: string;220+ readonly project: ProjectName;221+ readonly file: string;222+ readonly from: number;223+}) =>224+ Effect.gen(function* () {225+ const fs = yield* FileSystem.FileSystem;226+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;227+ const tally = yield* Ref.make<Tally>({ events: [], last: input.from });228+ const said = yield* Ref.make(false);229+230+ const append = (line: string) =>231+ fs.writeFileString(input.file, `${line}\n`, { flag: "a" });232+233+ const hear = (event: ProjectEvent) =>234+ Effect.gen(function* () {235+ const before = yield* Ref.get(tally);236+237+ if (event.seq <= before.last) {238+ return;239+ }240+241+ const events = counted(event)242+ ? [...before.events, event]243+ : before.events;244+245+ yield* Ref.set(tally, { events, last: event.seq });246+247+ if (counted(event)) {248+ yield* append(counterEntry(events, event));249+ }250+ });251+252+ const followOnce = Effect.scoped(253+ Effect.gen(function* () {254+ const { last } = yield* Ref.get(tally);255+256+ const child = yield* spawner.spawn(257+ ChildProcess.make(258+ "curl",259+ curlArgs({260+ body: `${watchRequest(input.project, Option.some(last))}\n`,261+ contentType: "application/ndjson",262+ origin: input.origin,263+ }),264+ { stdin: "ignore" }265+ )266+ );267+268+ // curl's exit says whether the stream ended or the call failed.269+ const [stderr, code] = yield* Effect.all(270+ [271+ child.stderr.pipe(Stream.decodeText(), Stream.mkString),272+ child.exitCode,273+ child.stdout.pipe(274+ Stream.decodeText(),275+ Stream.splitLines,276+ Stream.flatMap((line) => Stream.fromIterable(eventsIn(line))),277+ Stream.runForEach(hear)278+ ),279+ ],280+ { concurrency: "unbounded" }281+ );282+283+ yield* Effect.when(284+ Effect.fail(285+ new SwarmFailed({ reason: `curl exited ${code}: ${stderr.trim()}` })286+ ),287+ Effect.succeed(code !== 0)288+ );289+ })290+ ).pipe(291+ // Said once, so a counter that cannot follow says why; it keeps trying.292+ Effect.tapError(({ message }) =>293+ Effect.gen(function* () {294+ if (!(yield* Ref.getAndSet(said, true))) {295+ yield* append(`counter: watch didn't run: ${message}`);296+ }297+ })298+ ),299+ Effect.ignore300+ );301+302+ yield* append(303+ `${counterLine([])} (${input.project}, after event ${input.from})`304+ );305+306+ return yield* followOnce.pipe(307+ Effect.repeat(Schedule.spaced(FOLLOW_AGAIN)),308+ Effect.andThen(Effect.never)309+ );310+ });added:scripts/lib/swarm/views/headless.ts+226 added
1+/**2+ * Where a contributor's harness runs, and how a prompt reaches it: the3+ * swarm's views. A view runs one attempt of a session, its start on the4+ * brief or a turn that resumes it, and says what it heard; the verdict loop5+ * (`../loop.ts`) decides everything else, from `<cli> status` alone.6+ *7+ * This file holds the contract every view keeps (`SwarmView`) and the8+ * default, headless view: the harness's own process, started with its9+ * driver's argv (`../harnesses/`), its stdout read for the session's id,10+ * that it settled, and the tokens it used. `herdr.ts` is the other view.11+ */12+import {13+ Data,14+ Duration,15+ Effect,16+ FileSystem,17+ Fiber,18+ Option,19+ Stream,20+} from "effect";21+import { ChildProcess, ChildProcessSpawner } from "effect/process";22+23+import { drivers, HarnessEvent, sessionDirOf } from "../harnesses/index.ts";24+import type { HarnessDriver } from "../harnesses/index.ts";25+import type { Contributor } from "../roster.ts";26+import { scrubbed, SwarmFailed } from "../workspace.ts";27+import type { AgentWorkspace } from "../workspace.ts";28+29+/** One attempt of a contributor's session: its start, or a turn that resumes it. */30+export type Turn = Data.TaggedEnum<{31+ /** The session's first run, on the brief. */32+ Start: { readonly brief: string };33+ /** The session `session` (what an earlier attempt heard) goes on with `prompt`. */34+ Resume: { readonly session: string; readonly prompt: string };35+}>;36+37+export const Turn = Data.taggedEnum<Turn>();38+39+/** What one attempt said about its session. */40+export interface Heard {41+ /** The id a resume names: the harness's session, or the view's own name for it. */42+ readonly session: Option.Option<string>;43+ readonly settled: boolean;44+ readonly stopReason: Option.Option<string>;45+ /** Why the run failed on the harness's side, unless a response came after. */46+ readonly failure: Option.Option<string>;47+ readonly input: number;48+ readonly output: number;49+}50+51+export const nothingHeard: Heard = {52+ failure: Option.none(),53+ input: 0,54+ output: 0,55+ session: Option.none(),56+ settled: false,57+ stopReason: Option.none(),58+};59+60+/** What one attempt heard, and how it ended. */61+export interface Attempted {62+ /** The exit code, unless the process was still running when it was let go. */63+ readonly code: Option.Option<number>;64+ readonly heard: Heard;65+ /** The end of what it said on stderr, scrubbed of the token. */66+ readonly stderr: string;67+}68+69+/** One attempt, as the loop hands it to a view. */70+export interface ViewAttempt {71+ readonly contributor: Contributor;72+ readonly workspace: AgentWorkspace;73+ /** The env the harness runs in: the swarm's non-secret names, then the workspace's. */74+ readonly env: Readonly<Record<string, string>>;75+ /** Where the attempt's output is kept, scrubbed of the token. */76+ readonly file: string;77+ readonly turn: Turn;78+ /** Runs once the attempt has a session: the attempt counts from then. */79+ readonly onSession: Effect.Effect<void>;80+}81+82+/** Where a contributor's harness runs, and how each prompt reaches it. */83+export interface SwarmView {84+ readonly attempt: (85+ input: ViewAttempt86+ ) => Effect.Effect<87+ Attempted,88+ SwarmFailed,89+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem90+ >;91+}92+93+const hear = (heard: Heard, event: HarnessEvent): Heard =>94+ HarnessEvent.$match(event, {95+ Failed: ({ reason }) => ({ ...heard, failure: Option.some(reason) }),96+ SessionStarted: ({ id }) => ({ ...heard, session: Option.some(id) }),97+ Settled: ({ stopReason }) => ({98+ ...heard,99+ settled: true,100+ stopReason: Option.orElse(stopReason, () => heard.stopReason),101+ }),102+ Usage: ({ input, output, stopReason }) => ({103+ ...heard,104+ failure: Option.none(),105+ input: heard.input + input,106+ output: heard.output + output,107+ stopReason: Option.orElse(stopReason, () => heard.stopReason),108+ }),109+ });110+111+/** How long a settled harness gets to exit on its own before it is killed. */112+const EXIT_GRACE = Duration.seconds(10);113+114+/** How long a killed harness gets before `SIGKILL`. */115+const KILL_GRACE = Duration.seconds(5);116+117+/** The last characters of a harness's stderr kept, to say why it failed. */118+const STDERR_TAIL = 2000;119+120+/**121+ * One harness process: `argv` in the clone with `env`. Every stdout line122+ * goes to `file`, scrubbed of the token, and is read for events until the123+ * session settles or the output ends. A settled harness gets `EXIT_GRACE`124+ * to exit; then it is killed with its process group.125+ */126+const attempt = (input: {127+ readonly argv: readonly string[];128+ readonly driver: HarnessDriver;129+ readonly env: Readonly<Record<string, string>>;130+ readonly file: string;131+ readonly workspace: AgentWorkspace;132+ readonly onSession: Effect.Effect<void>;133+}) =>134+ Effect.scoped(135+ Effect.gen(function* () {136+ const fs = yield* FileSystem.FileSystem;137+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;138+ const [command = "", ...args] = input.argv;139+ const scrub = (text: string) => scrubbed(text, input.workspace);140+141+ yield* fs.writeFileString(input.file, "");142+143+ const child = yield* spawner.spawn(144+ ChildProcess.make(command, args, {145+ cwd: input.workspace.clone,146+ env: { ...input.env },147+ extendEnv: false,148+ forceKillAfter: KILL_GRACE,149+ stdin: "ignore",150+ })151+ );152+153+ const stderr = yield* child.stderr.pipe(154+ Stream.decodeText(),155+ Stream.runFold(156+ () => "",157+ (tail, text) => `${tail}${text}`.slice(-STDERR_TAIL)158+ ),159+ Effect.forkScoped160+ );161+162+ const heard = yield* child.stdout.pipe(163+ Stream.decodeText(),164+ Stream.splitLines,165+ Stream.tap((line) =>166+ fs.writeFileString(input.file, `${scrub(line)}\n`, { flag: "a" })167+ ),168+ Stream.flatMap((line) => Stream.fromIterable(input.driver.parse(line))),169+ Stream.tap((event) =>170+ HarnessEvent.$is("SessionStarted")(event)171+ ? input.onSession172+ : Effect.void173+ ),174+ Stream.takeUntil(HarnessEvent.$is("Settled")),175+ Stream.runFold(() => nothingHeard, hear)176+ );177+178+ const code = yield* child.exitCode.pipe(179+ Effect.timeoutOption(EXIT_GRACE),180+ Effect.map(Option.map(Number))181+ );182+183+ // A harness still running after its grace keeps its stderr open:184+ // its tail is then not waited for.185+ const tail = yield* Fiber.join(stderr).pipe(186+ Effect.timeoutOption(Duration.seconds(1)),187+ Effect.map(Option.getOrElse(() => ""))188+ );189+190+ return { code, heard, stderr: scrub(tail).trim() };191+ })192+ ).pipe(193+ Effect.mapError(194+ ({ message }) =>195+ new SwarmFailed({196+ reason: `${input.argv[0] ?? "the harness"} didn't run: ${message}`,197+ })198+ )199+ );200+201+/**202+ * The swarm's default view: each attempt is the harness's own process,203+ * headless, started (or resumed) with its driver's argv in the clone.204+ */205+export const headlessView: SwarmView = {206+ attempt: ({ contributor, env, file, onSession, turn, workspace }) => {207+ const { adapter, handle, harness, model } = contributor;208+ const driver = drivers[harness];209+210+ const argv = Turn.$match(turn, {211+ Resume: ({ prompt, session }) =>212+ driver.resume({ adapter, model, prompt, session, workspace }),213+ Start: ({ brief }) =>214+ driver.start({215+ adapter,216+ brief,217+ model,218+ sessionDir: sessionDirOf(workspace.dir),219+ sessionKey: handle,220+ workspace,221+ }),222+ });223+224+ return attempt({ argv, driver, env, file, onSession, workspace });225+ },226+};added:scripts/lib/swarm/views/herdr.ts+844 added
1+/**2+ * The herdr view (`--view herdr`, issue 717): for the video, each3+ * contributor's harness runs interactively in a herdr pane of its own, six4+ * tiled over a counter strip, and every prompt (the brief, each refusal,5+ * the nudge) is typed into that pane's session through herdr's CLI. The6+ * verdict loop is the headless one: outcomes still come only from the7+ * contributor's `<cli> status --json`, never from pane text.8+ *9+ * herdr is driven as a process (`herdr …`, read from `herdr --help` and10+ * `herdr agent --help` on herdr 0.9.3), never through an SDK. It runs in the11+ * herdr session the swarm itself runs in (`herdr --session demo`), so the12+ * panes open where the person recording is looking. Pane text is read for13+ * one thing only: to recognise a question a harness asks at startup, before14+ * it takes its brief (`STARTUP_QUESTIONS`). Where an answer stands comes15+ * from status alone.16+ *17+ * Unlike a headless harness, an agent in a pane outlives its run: a run that18+ * times out (or a swarm that is stopped) leaves it working in its pane,19+ * claim and all, until the person closes the workspace the swarm names20+ * (`herdr workspace close <id>`).21+ */22+import type { ProjectName } from "@repo/protocol/ids";23+import {24+ Config,25+ Duration,26+ Effect,27+ FileSystem,28+ Option,29+ Ref,30+ Result,31+ Schedule,32+ Schema,33+} from "effect";34+import type { Path, Scope } from "effect";35+import type { ChildProcessSpawner } from "effect/process";36+37+import { repoRoot } from "../../../../infra/stages.ts";38+import { drivers, sessionDirOf } from "../harnesses/index.ts";39+import type { Harness } from "../results.ts";40+import type { Contributor } from "../roster.ts";41+import { run, scrubbed, shellQuoted, SwarmFailed } from "../workspace.ts";42+import type { AgentWorkspace } from "../workspace.ts";43+import { followCounter, lastHeld } from "./counter.ts";44+import { nothingHeard, Turn } from "./headless.ts";45+import type { Attempted, SwarmView } from "./headless.ts";46+47+/** The counter's pane, below the contributors'. */48+export const COUNTER = "counter";49+50+/**51+ * One pane the layout makes: the pane `from` (already made) is split toward52+ * `direction`, keeping `ratio` of its space, and the new pane is `slot`.53+ */54+export interface Split {55+ readonly slot: string;56+ readonly from: string;57+ readonly direction: "right" | "down";58+ readonly ratio: number;59+}60+61+/** The share of the window the contributors keep above the counter strip. */62+const ABOVE_COUNTER = 0.85;63+64+/** `ratio` to three places, as herdr reads it. */65+const share = (ratio: number) => Math.round(ratio * 1000) / 1000;66+67+/**68+ * The panes for `handles`, as splits of the first one's pane (the69+ * workspace's own): a counter strip along the bottom, then up to three70+ * contributors to a row, two rows at most, each split keeping the share71+ * that leaves every pane of a row the same width. Pure.72+ */73+export const herdrLayout = (handles: readonly string[]): readonly Split[] => {74+ const [first] = handles;75+76+ if (first === undefined) {77+ return [];78+ }79+80+ const across =81+ handles.length <= 3 ? handles.length : Math.ceil(handles.length / 2);82+83+ const rows = [handles.slice(0, across), handles.slice(across)].filter(84+ (row) => row.length > 085+ );86+87+ const counter: Split = {88+ direction: "down",89+ from: first,90+ ratio: ABOVE_COUNTER,91+ slot: COUNTER,92+ };93+94+ const secondRow = rows.flatMap((row, at) => {95+ const [head] = row;96+97+ return at === 0 || head === undefined98+ ? []99+ : [{ direction: "down", from: first, ratio: 0.5, slot: head } as const];100+ });101+102+ const columns = rows.flatMap((row) =>103+ row.slice(1).map((slot, at): Split => ({104+ direction: "right",105+ from: row[at] ?? first,106+ ratio: share(1 / (row.length - at)),107+ slot,108+ }))109+ );110+111+ return [counter, ...secondRow, ...columns];112+};113+114+/** How long herdr waits for a harness to be ready for input when it starts one. */115+const START_TIMEOUT_MS = 120_000;116+117+/** `herdr agent start …`: the harness `kind`, named `handle`, in `pane`, with its own flags after `--`. Pure. */118+export const herdrStart = (input: {119+ readonly handle: string;120+ readonly kind: string;121+ readonly pane: string;122+ readonly argv: readonly string[];123+}): readonly string[] => [124+ "agent",125+ "start",126+ input.handle,127+ "--kind",128+ input.kind,129+ "--pane",130+ input.pane,131+ "--timeout",132+ String(START_TIMEOUT_MS),133+ "--",134+ ...input.argv,135+];136+137+/**138+ * `herdr agent prompt …`: `text` typed into the agent's session, then a139+ * wait until it settles. `--wait` alone matches `idle`, `done` and140+ * `blocked`: a turn that ends `idle` (seen on Claude Code) would never141+ * match `--until done --until blocked`. Pure.142+ */143+export const herdrPrompt = (input: {144+ readonly handle: string;145+ readonly text: string;146+}): readonly string[] => [147+ "agent",148+ "prompt",149+ input.handle,150+ input.text,151+ "--wait",152+];153+154+/**155+ * What only a headless run needs, per harness: the switches and the flags156+ * (with their values) the driver's start passes for print mode and JSON157+ * output, or for a prompt given on the command line. An interactive158+ * session gets its prompt from herdr instead.159+ */160+const HEADLESS_ONLY = {161+ amp: {162+ switches: ["--stream-json", "--no-archive-after-execute"],163+ valued: ["-x"],164+ },165+ "claude-code": { switches: ["-p", "--verbose"], valued: ["--output-format"] },166+ // `run` is OpenCode's headless subcommand; its interface takes no `-m`.167+ opencode: { switches: ["run"], valued: ["--format", "-m"] },168+ pi: { switches: ["-p"], valued: ["--mode"] },169+} as const satisfies Readonly<170+ Record<171+ Harness,172+ { readonly switches: readonly string[]; readonly valued: readonly string[] }173+ >174+>;175+176+/** Stands for the brief in a driver's argv, so the brief can be taken out. */177+const BRIEF = "\u0000brief";178+179+/** How a harness starts interactively: herdr's kind, its flags, and env it needs. */180+export interface Launch {181+ readonly kind: string;182+ readonly argv: readonly string[];183+ readonly env: Readonly<Record<string, string>>;184+}185+186+/**187+ * How `contributor`'s harness starts interactively in a pane: herdr's kind188+ * (the harness's executable, which herdr knows by the same name), and the189+ * driver's own start flags less `HEADLESS_ONLY` and the brief, so the190+ * settings that keep a contributor's session safe (every tool allowed, no191+ * MCP server of the user's, the workspace's sessions) are the headless192+ * run's. OpenCode's interface takes its model from inline config in the193+ * env. Pure.194+ */195+export const interactiveLaunch = (input: {196+ readonly contributor: Contributor;197+ readonly dir: string;198+}): Launch => {199+ const { adapter, handle, harness, model } = input.contributor;200+201+ const [kind = harness, ...flags] = drivers[harness].start({202+ adapter,203+ brief: BRIEF,204+ model,205+ sessionDir: sessionDirOf(input.dir),206+ sessionKey: handle,207+ workspace: {208+ clone: `${input.dir}/clone`,209+ dir: input.dir,210+ env: {},211+ redacted: [],212+ },213+ });214+215+ const { switches, valued } = HEADLESS_ONLY[harness];216+217+ const argv = flags.filter((flag, at) => {218+ const before = flags[at - 1] ?? "";219+220+ return (221+ flag !== BRIEF &&222+ !switches.some((one) => one === flag) &&223+ !valued.some((one) => one === flag || one === before)224+ );225+ });226+227+ return {228+ argv,229+ env:230+ harness === "opencode"231+ ? { OPENCODE_CONFIG_CONTENT: JSON.stringify({ model }) }232+ : {},233+ kind,234+ };235+};236+237+/** herdr refused a command: its error's code, and what it said. */238+class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {239+ code: Schema.String,240+ said: Schema.String,241+ verb: Schema.String,242+}) {243+ override get message() {244+ return `herdr ${this.verb}: ${this.code}: ${this.said}`;245+ }246+}247+248+const isRefused = Schema.is(HerdrRefused);249+250+/** What herdr prints on stderr when it refuses a command. */251+const decodeRefusal = Schema.decodeUnknownOption(252+ Schema.fromJsonString(253+ Schema.Struct({254+ error: Schema.Struct({ code: Schema.String, message: Schema.String }),255+ })256+ )257+);258+259+/**260+ * `herdr …` with the swarm's env, in the herdr session the swarm runs in:261+ * what it printed, or `HerdrRefused` with herdr's own error code.262+ */263+const herdr = (args: readonly string[]) =>264+ Effect.flatMap(run({ args, command: "herdr", env: {} }), (ran) => {265+ if (ran.code === 0) {266+ return Effect.succeed(ran.stdout);267+ }268+269+ const verb = args.slice(0, 2).join(" ");270+271+ return Effect.fail(272+ Option.match(decodeRefusal(ran.stderr), {273+ onNone: () =>274+ new HerdrRefused({275+ code: `exit ${ran.code}`,276+ said: ran.stderr.trim().slice(0, 500),277+ verb,278+ }),279+ onSome: ({ error }) =>280+ new HerdrRefused({ code: error.code, said: error.message, verb }),281+ })282+ );283+ });284+285+/** Ends a step on herdr's refusal, saying which. */286+const orFailed = <A, R>(287+ effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>288+): Effect.Effect<A, SwarmFailed, R> =>289+ effect.pipe(290+ Effect.catchTag("HerdrRefused", ({ message }) =>291+ Effect.fail(new SwarmFailed({ reason: message }))292+ )293+ );294+295+/** `printed` decoded as `schema`, or why herdr's answer was not what the step needs. */296+const answerOf =297+ <A, I>(schema: Schema.Codec<A, I>, what: string) =>298+ (printed: string) =>299+ Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(300+ Effect.mapError(301+ () =>302+ new SwarmFailed({303+ reason: `herdr ${what} answered without its JSON: ${printed.trim().slice(0, 300)}`,304+ })305+ )306+ );307+308+const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });309+310+/** `workspace create`: the workspace, and its first pane. */311+const WorkspaceMade = Schema.Struct({312+ result: Schema.Struct({313+ root_pane: PaneId,314+ workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),315+ }),316+});317+318+/** `pane split`: the new pane. */319+const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });320+321+/** An agent as herdr sees it: `idle`, `working`, `blocked`, `done` or `unknown`. */322+const AgentSeen = Schema.Struct({323+ result: Schema.Struct({324+ agent: Schema.Struct({325+ agent_status: Schema.String,326+ interactive_ready: Schema.optionalKey(Schema.Boolean),327+ }),328+ }),329+});330+331+/** A question a harness asks before it takes a prompt, and the keys that answer it as the swarm decides. */332+interface StartupQuestion {333+ /** Words only that question shows, in herdr's detection text. */334+ readonly asks: string;335+ readonly keys: readonly string[];336+}337+338+/**339+ * The questions each harness asks when it starts in a new folder (seen on340+ * Claude Code 2.1.293 and 2.1.294; OpenCode 2.0.7, Amp 0.0.1789750518 and341+ * pi 1.1.0 asked none):342+ *343+ * - Claude Code asks whether to trust the folder, "No, exit" first: the344+ * clone is the swarm's own, so it answers yes;345+ * - then whether to import the CLAUDE.md files above the clone (this346+ * repo's own, when `.swarm/` sits in the checkout), "No" first: it keeps347+ * the default, since they are not the contributor's project.348+ *349+ * Any other question is left for the person at the panes.350+ */351+const STARTUP_QUESTIONS = {352+ amp: [],353+ "claude-code": [354+ { asks: "Yes, I trust this folder", keys: ["down", "enter"] },355+ { asks: "Allow external CLAUDE.md file imports?", keys: ["enter"] },356+ ],357+ opencode: [],358+ pi: [],359+} as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;360+361+/** How long a harness gets to be ready for its brief once herdr says it is blocked at startup. */362+const STARTUP_WAIT = Duration.minutes(3);363+364+/** Whether herdr sees the agent ready for a prompt. */365+const readyIn = (printed: string) =>366+ Effect.map(367+ answerOf(AgentSeen, "agent get")(printed),368+ ({ result: { agent } }) =>369+ agent.interactive_ready === true &&370+ (agent.agent_status === "idle" || agent.agent_status === "done")371+ );372+373+/**374+ * A harness blocked at startup: each question it is known to ask is375+ * answered once, as `STARTUP_QUESTIONS` says, until herdr sees it ready.376+ * A question the table doesn't know waits for the person at the panes,377+ * until `STARTUP_WAIT` ends the run.378+ */379+const pastStartup = (input: {380+ readonly handle: string;381+ readonly harness: Harness;382+ readonly pane: string;383+}) =>384+ Effect.gen(function* () {385+ const answered = yield* Ref.make<readonly string[]>([]);386+387+ const look = Effect.gen(function* () {388+ const seen = yield* herdr(["agent", "get", input.handle]);389+390+ if (yield* readyIn(seen)) {391+ return true;392+ }393+394+ const shown = yield* herdr([395+ "agent",396+ "read",397+ input.handle,398+ "--source",399+ "detection",400+ ]);401+402+ const done = yield* Ref.get(answered);403+404+ const question = STARTUP_QUESTIONS[input.harness].find(405+ ({ asks }) => shown.includes(asks) && !done.includes(asks)406+ );407+408+ if (question !== undefined) {409+ yield* Ref.set(answered, [...done, question.asks]);410+ yield* herdr(["agent", "send-keys", input.handle, ...question.keys]);411+ }412+413+ return false;414+ });415+416+ const ready = yield* look.pipe(417+ Effect.repeat({418+ schedule: Schedule.spaced(Duration.seconds(1)),419+ until: (isReady: boolean) => isReady,420+ }),421+ Effect.timeoutOption(STARTUP_WAIT)422+ );423+424+ yield* Effect.fromOption(ready).pipe(425+ Effect.mapError(426+ () =>427+ new SwarmFailed({428+ reason: `${input.harness} is still blocked at startup in herdr pane ${input.pane}: answer it there, or run --view headless`,429+ })430+ )431+ );432+ });433+434+/** Names whose values the pane keeps from its own terminal, not the swarm's. */435+const PANE_OWNS = ["TERM", "COLORTERM"];436+437+/** herdr's names in a pane: its integrations report each agent's state with them. */438+const HERDR_NAMES = [439+ "HERDR_BIN_PATH",440+ "HERDR_ENV",441+ "HERDR_PANE_ID",442+ "HERDR_SOCKET_PATH",443+ "HERDR_TAB_ID",444+ "HERDR_WORKSPACE_ID",445+];446+447+/**448+ * The script a contributor's pane runs once: it clears the pane's env to449+ * its terminal and herdr's own names, reads the harness's env from the450+ * swarm through `fifo` (a pipe, so no token is ever in a file, an argv or451+ * on the screen), and leaves a shell without rc files (no user setup452+ * between the contributor and their env) in their clone, where herdr453+ * starts their harness. Pure.454+ */455+export const paneShell = (input: {456+ readonly fifo: string;457+ readonly clone: string;458+}) =>459+ [460+ "#!/bin/sh",461+ "# One swarm contributor's herdr pane (issue 717): their harness's env from the",462+ "# swarm through a pipe, then a shell in their clone for herdr to start it in.",463+ `exec env -i ${[...PANE_OWNS, ...HERDR_NAMES].map((name) => `${name}="\${${name}-}"`).join(" ")} /bin/sh -c '`,464+ "set -a",465+ '. "$1"',466+ "set +a",467+ 'cd "$2" || exit 1',468+ `case "\${SHELL##*/}" in`,469+ ' zsh) exec "$SHELL" -f ;;',470+ ' bash) exec "$SHELL" --noprofile --norc ;;',471+ ` *) exec "\${SHELL:-/bin/sh}" ;;`,472+ `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,473+ "",474+ ].join("\n");475+476+/** `env` as the lines a shell sources, less what the pane owns. Pure. */477+const envLines = (env: Readonly<Record<string, string>>) =>478+ Object.entries(env)479+ .filter(([name]) => !PANE_OWNS.includes(name))480+ .map(([name, value]) => `${name}=${shellQuoted(value)}\n`)481+ .join("");482+483+/** How long a pane gets to read its env from the pipe. */484+const ENV_READ_WAIT = Duration.seconds(30);485+486+/** How many times a pane whose shell is still starting is asked again, a second apart. */487+const BUSY_RETRIES = 10;488+489+/** A pane script runs only as its owner. */490+const SCRIPT_MODE = 0o700;491+492+/**493+ * Readies `pane` for `contributor` and starts their harness in it: the494+ * pane runs `paneShell`, reads `env` (with the launch's own) from a pipe,495+ * and herdr starts the harness with its interactive flags, getting past496+ * the startup questions it knows. herdr's answer goes to `log`.497+ */498+const startIn = (input: {499+ readonly contributor: Contributor;500+ readonly env: Readonly<Record<string, string>>;501+ readonly pane: string;502+ readonly workspace: AgentWorkspace;503+ readonly log: (text: string) => Effect.Effect<void, SwarmFailed>;504+}) =>505+ Effect.gen(function* () {506+ const fs = yield* FileSystem.FileSystem;507+ const { contributor, pane, workspace } = input;508+ const { handle, harness } = contributor;509+ const launch = interactiveLaunch({ contributor, dir: workspace.dir });510+ const fifo = `${workspace.dir}/pane-env`;511+ const script = `${workspace.dir}/pane-shell`;512+513+ const written = (what: string) =>514+ Effect.mapError(515+ ({ message }: { readonly message: string }) =>516+ new SwarmFailed({ reason: `${handle}'s ${what}: ${message}` })517+ );518+519+ yield* fs.remove(fifo, { force: true }).pipe(written("pipe"));520+521+ const made = yield* run({522+ args: ["-m", "600", fifo],523+ command: "mkfifo",524+ env: {},525+ });526+527+ if (made.code !== 0) {528+ return yield* new SwarmFailed({529+ reason: `${handle}'s pipe: mkfifo exited ${made.code}: ${made.stderr.trim()}`,530+ });531+ }532+533+ yield* fs534+ .writeFileString(script, paneShell({ clone: workspace.clone, fifo }), {535+ mode: SCRIPT_MODE,536+ })537+ .pipe(538+ Effect.andThen(fs.chmod(script, SCRIPT_MODE)),539+ written("pane script")540+ );541+542+ yield* orFailed(543+ herdr(["pane", "run", pane, `exec ${shellQuoted(script)}`])544+ );545+546+ // Opening the pipe waits for the pane's script to read it.547+ yield* fs548+ .writeFileString(fifo, envLines({ ...input.env, ...launch.env }))549+ .pipe(550+ written("env"),551+ Effect.timeoutOrElse({552+ duration: ENV_READ_WAIT,553+ orElse: () =>554+ Effect.fail(555+ new SwarmFailed({556+ reason: `${handle}'s herdr pane ${pane} didn't read its env: is it at a shell prompt?`,557+ })558+ ),559+ }),560+ Effect.ensuring(Effect.ignore(fs.remove(fifo, { force: true })))561+ );562+563+ const started = yield* herdr(564+ herdrStart({ argv: launch.argv, handle, kind: launch.kind, pane })565+ ).pipe(566+ // The pane's shell may still be starting.567+ Effect.retry({568+ schedule: Schedule.spaced(Duration.seconds(1)),569+ times: BUSY_RETRIES,570+ while: (error) => isRefused(error) && error.code === "agent_pane_busy",571+ }),572+ Effect.catchIf(573+ (error): error is HerdrRefused =>574+ isRefused(error) && error.code === "agent_not_ready",575+ (error) =>576+ Effect.as(577+ pastStartup({ handle, harness, pane }),578+ JSON.stringify({ startup: error.said })579+ )580+ ),581+ orFailed582+ );583+584+ return yield* input.log(started);585+ });586+587+/** What an attempt heard from herdr's answer to its prompt (or its refusal of it). */588+const promptHeard = (input: {589+ readonly name: string;590+ readonly pane: string;591+ readonly harness: Harness;592+ readonly answer: Result.Result<string, HerdrRefused>;593+}): Effect.Effect<Attempted, SwarmFailed> =>594+ Result.match(input.answer, {595+ onFailure: (refused) =>596+ Effect.succeed({597+ code: Option.some(1),598+ heard: {599+ ...nothingHeard,600+ failure: Option.some(refused.message),601+ session: Option.some(input.name),602+ },603+ stderr: refused.message,604+ }),605+ onSuccess: (printed) =>606+ Effect.map(607+ answerOf(AgentSeen, "agent prompt")(printed),608+ ({ result: { agent } }): Attempted => {609+ const blocked = agent.agent_status === "blocked";610+611+ return {612+ code: Option.some(0),613+ heard: {614+ ...nothingHeard,615+ failure: blocked616+ ? Option.some(617+ `${input.harness} is blocked on a question in herdr pane ${input.pane}`618+ )619+ : Option.none(),620+ session: Option.some(input.name),621+ settled: !blocked,622+ stopReason: Option.some(agent.agent_status),623+ },624+ stderr: "",625+ };626+ }627+ ),628+ });629+630+/**631+ * The herdr view over `panes` (each contributor's pane, by handle): an632+ * attempt starts the harness in its pane on the brief, or types the633+ * continuation's prompt into the same session, and waits until herdr sees634+ * it settle. The session a resume names is the agent's herdr name.635+ */636+export const herdrView = (panes: ReadonlyMap<string, string>): SwarmView => ({637+ attempt: ({ contributor, env, file, onSession, turn, workspace }) =>638+ Effect.gen(function* () {639+ const fs = yield* FileSystem.FileSystem;640+ const { handle, harness } = contributor;641+642+ const pane = yield* Effect.fromNullishOr(panes.get(handle)).pipe(643+ Effect.mapError(644+ () => new SwarmFailed({ reason: `${handle} has no herdr pane` })645+ )646+ );647+648+ const logged = Effect.mapError(649+ ({ message }: { readonly message: string }) =>650+ new SwarmFailed({ reason: `${handle}'s attempt log: ${message}` })651+ );652+653+ const log = (text: string) =>654+ fs655+ .writeFileString(file, `${scrubbed(text, workspace).trim()}\n`, {656+ flag: "a",657+ })658+ .pipe(logged);659+660+ yield* fs.writeFileString(file, "").pipe(logged);661+662+ const name = yield* Turn.$match(turn, {663+ Resume: ({ session }) => Effect.succeed(session),664+ Start: () =>665+ Effect.as(666+ startIn({ contributor, env, log, pane, workspace }),667+ handle668+ ),669+ });670+671+ yield* onSession;672+673+ const text = Turn.$match(turn, {674+ Resume: ({ prompt }) => prompt,675+ Start: ({ brief }) => brief,676+ });677+678+ const answer = yield* herdr(herdrPrompt({ handle: name, text })).pipe(679+ Effect.map(Result.succeed),680+ Effect.catchIf(isRefused, (refused) =>681+ Effect.succeed(Result.fail(refused))682+ )683+ );684+685+ yield* log(686+ Result.match(answer, {687+ onFailure: ({ message }) => message,688+ onSuccess: (printed) => printed,689+ })690+ );691+692+ return yield* promptHeard({ answer, harness, name, pane });693+ }),694+});695+696+/** A pane's title: who works in it, and on which harness. */697+const titleOf = ({698+ handle,699+ harness,700+}: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;701+702+/**703+ * Opens the herdr view for `contributors`, in the herdr session the swarm704+ * runs in: a workspace of its own (focused, for the person recording), one705+ * pane per contributor laid out by `herdrLayout`, and a counter pane that706+ * shows `counterFile`, which a fiber in the run's scope keeps writing from707+ * the project's `watch`. Outside a herdr pane it refuses: herdr's skill708+ * says not to drive a session from outside it. It refuses too when it can't709+ * read where the project stands (`lastHeld`), before any pane is made.710+ */711+export const openHerdrView = (input: {712+ readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];713+ readonly project: ProjectName;714+ readonly origin: string;715+ readonly runDir: string;716+}): Effect.Effect<717+ { readonly view: SwarmView; readonly workspace: string },718+ SwarmFailed,719+ | ChildProcessSpawner.ChildProcessSpawner720+ | FileSystem.FileSystem721+ | Path.Path722+ | Scope.Scope723+> =>724+ Effect.gen(function* () {725+ const fs = yield* FileSystem.FileSystem;726+727+ const inHerdr = yield* Config.all({728+ env: Config.option(Config.String("HERDR_ENV")),729+ socket: Config.option(Config.String("HERDR_SOCKET_PATH")),730+ }).pipe(731+ Effect.map(732+ ({ env, socket }) => Option.contains(env, "1") || Option.isSome(socket)733+ ),734+ Effect.orElseSucceed(() => false)735+ );736+737+ if (!inHerdr) {738+ return yield* new SwarmFailed({739+ reason:740+ "--view herdr opens its panes in the herdr session it runs in: start the swarm from a herdr pane (herdr --session demo), or name the session's socket in HERDR_SOCKET_PATH",741+ });742+ }743+744+ // Where the counter starts, read before any pane or claim: a run that745+ // can't say where the project stands stops here.746+ const from = yield* lastHeld(input.origin, input.project);747+ const root = (yield* repoRoot).replace(/\/$/u, "");748+ const counterFile = `${input.runDir}/counter.log`;749+ const handles = input.contributors.map(({ handle }) => handle);750+751+ yield* fs752+ .makeDirectory(input.runDir, { recursive: true })753+ .pipe(754+ Effect.mapError(755+ ({ message }) =>756+ new SwarmFailed({ reason: `the run's folder: ${message}` })757+ )758+ );759+760+ const made = yield* herdr([761+ "workspace",762+ "create",763+ "--cwd",764+ root,765+ "--label",766+ `swarm ${input.project}`,767+ "--focus",768+ ]).pipe(769+ orFailed,770+ Effect.flatMap(answerOf(WorkspaceMade, "workspace create"))771+ );772+773+ const first = handles[0] ?? COUNTER;774+775+ const panes = yield* Effect.reduce(776+ herdrLayout(handles),777+ () => new Map([[first, made.result.root_pane.pane_id]]),778+ (known, split) =>779+ herdr([780+ "pane",781+ "split",782+ known.get(split.from) ?? made.result.root_pane.pane_id,783+ "--direction",784+ split.direction,785+ "--ratio",786+ String(split.ratio),787+ "--cwd",788+ root,789+ "--no-focus",790+ ]).pipe(791+ orFailed,792+ Effect.flatMap(answerOf(PaneMade, "pane split")),793+ Effect.map(({ result }) =>794+ new Map(known).set(split.slot, result.pane.pane_id)795+ )796+ )797+ );798+799+ const titles = [800+ ...input.contributors.map((one) => [one.handle, titleOf(one)] as const),801+ [COUNTER, `counter · ${input.project}`] as const,802+ ];803+804+ yield* Effect.forEach(805+ titles.flatMap(([slot, title]) =>806+ Option.toArray(807+ Option.map(Option.fromUndefinedOr(panes.get(slot)), (pane) => ({808+ pane,809+ title,810+ }))811+ )812+ ),813+ ({ pane, title }) => orFailed(herdr(["pane", "rename", pane, title])),814+ { discard: true }815+ );816+817+ yield* Effect.forkScoped(818+ followCounter({819+ file: counterFile,820+ from,821+ origin: input.origin,822+ project: input.project,823+ }).pipe(Effect.ignore)824+ );825+826+ yield* Effect.forEach(827+ Option.toArray(Option.fromUndefinedOr(panes.get(COUNTER))),828+ (pane) =>829+ orFailed(830+ herdr([831+ "pane",832+ "run",833+ pane,834+ `clear; tail -n +1 -F ${shellQuoted(counterFile)}`,835+ ])836+ ),837+ { discard: true }838+ );839+840+ return {841+ view: herdrView(panes),842+ workspace: made.result.workspace.workspace_id,843+ };844+ });modified:scripts/lib/swarm/args.ts+19 added-12 removed
8 unmodified lines9 * --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 then13+ * --view headless|herdr default headless; herdr runs each harness in a herdr pane (issue 717)14 * --url <origin> the platform, when not the stage's workers.dev origin15 */16 import { Handle, ProjectName } from "@repo/protocol/ids";17 import { Effect, Option, Schema } from "effect";13 unmodified lines31 readonly json: boolean;32 /** The contributors to run; every one when `--only` names none. */33 readonly only: readonly Handle[];34 readonly timeoutMin: number;35+ /** Where the harnesses run: their own processes, or herdr's panes (`views/`). */36+ readonly view: ViewName;37 /** The platform's origin, when `--url` names it. */38 readonly url: Option.Option<string>;39 }40 41 export const USAGE =40- "bun scripts/swarm.ts --stage <dev-…|demo> [--project burrow] [--scenario plain|video] [--dry-run] [--json] [--allow-demo] [--only <handle>…] [--timeout-min 20] [--view headless] [--url <origin>]";42+ "bun scripts/swarm.ts --stage <dev-…|demo> [--project burrow] [--scenario plain|video] [--dry-run] [--json] [--allow-demo] [--only <handle>…] [--timeout-min 20] [--view headless|herdr] [--url <origin>]";43 44+/** The views a run can take. */45+export const ViewName = Schema.Literals(["headless", "herdr"]);46+47+export type ViewName = typeof ViewName.Type;48+49+const decodeView = Schema.decodeUnknownOption(ViewName);50+51 /** The flags that take a value. */52 const VALUED = [53 "--project",54 "--scenario",124 unmodified lines179 "--stage demo: its burrow family is for the recorded take (804); run it there only with --allow-demo"180 );181 }182 174- const view = Option.getOrElse(flagValue(argv, "--view"), () => "headless");183+ const rawView = Option.getOrElse(184+ flagValue(argv, "--view"),185+ () => "headless"186+ );187 176- if (view === "herdr") {177- return yield* failed(178- "--view herdr is not built yet (issue 717): run --view headless"179- );180- }188+ const view = yield* Effect.fromOption(decodeView(rawView)).pipe(189+ Effect.mapError(() => failed(`--view ${rawView}: headless or herdr`))190+ );191 182- if (view !== "headless") {183- return yield* failed(`--view ${view}: headless or herdr`);184- }185-192 const rawProject = Option.getOrElse(193 flagValue(argv, "--project"),194 () => "burrow"195 );66 unmodified lines262 scenario,263 stage,264 timeoutMin,265 url,266+ view,267 };268 });modified:scripts/lib/swarm/loop.ts+22 added-155 removed
18 unmodified lines19 *20 * The run's timeout bounds everything: a harness that never settles, or an21 * answer checked past it, ends the run as `timedOut`, and the harness's22 * process group is killed.23+ *24+ * Where the harness runs, and how a prompt reaches it, is the run's view25+ * (`views/`): its own headless process by default, or a herdr pane26+ * (`--view herdr`, issue 717). The loop is the same in both.27 */28 import { Brand } from "@repo/brand";29 import type { AnswerView } from "@repo/protocol/domain/answer";30 import { Outcome } from "@repo/protocol/domain/outcome";8 unmodified lines39 Data,40 Duration,41 Effect,42 FileSystem,39- Fiber,43 Option,44 Ref,42- Stream,45 } from "effect";44-import { ChildProcess, ChildProcessSpawner } from "effect/process";46+import type { ChildProcessSpawner } from "effect/process";47 46-import { drivers, HarnessEvent, sessionDirOf } from "./harnesses/index.ts";47-import type { HarnessDriver } from "./harnesses/index.ts";48+import { drivers, sessionDirOf } from "./harnesses/index.ts";49 import { awaitSettledOutcome } from "./outcome.ts";50 import type { AskStatus } from "./outcome.ts";51 import { endsClaim } from "./plan.ts";52 import type { Assignment } from "./plan.ts";53 import type { AgentOutcome, AgentRun } from "./results.ts";54 import type { Contributor } from "./roster.ts";55+import { headlessView, Turn } from "./views/headless.ts";56+import type { SwarmView } from "./views/headless.ts";57 import { scrubbed, SwarmFailed } from "./workspace.ts";58 import type { AgentWorkspace } from "./workspace.ts";59 60 /** One contributor's run: their harness on the brief, then the verdict loop. */7 unmodified lines68 * The ask's project, so `status` reads only it. Without one, `status`69 * lists every project's claims and answers and the ask is found by name.70 */71 readonly project?: ProjectName;72+ /**73+ * Where the harness runs and how each prompt reaches it: its own74+ * headless process unless a view (herdr's panes) says otherwise.75+ */76+ readonly view?: SwarmView;77 }) => Effect.Effect<78 AgentRun,79 never,80 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem76 unmodified lines157 ...workspace.env,158 };159 });160 153-/** What one attempt's output said, and how its process ended. */154-interface Heard {155- readonly session: Option.Option<string>;156- readonly settled: boolean;157- readonly stopReason: Option.Option<string>;158- /** Why the run failed on the harness's side, unless a response came after. */159- readonly failure: Option.Option<string>;160- readonly input: number;161- readonly output: number;162-}163-164-const nothingHeard: Heard = {165- failure: Option.none(),166- input: 0,167- output: 0,168- session: Option.none(),169- settled: false,170- stopReason: Option.none(),171-};172-173-const hear = (heard: Heard, event: HarnessEvent): Heard =>174- HarnessEvent.$match(event, {175- Failed: ({ reason }) => ({ ...heard, failure: Option.some(reason) }),176- SessionStarted: ({ id }) => ({ ...heard, session: Option.some(id) }),177- Settled: ({ stopReason }) => ({178- ...heard,179- settled: true,180- stopReason: Option.orElse(stopReason, () => heard.stopReason),181- }),182- Usage: ({ input, output, stopReason }) => ({183- ...heard,184- failure: Option.none(),185- input: heard.input + input,186- output: heard.output + output,187- stopReason: Option.orElse(stopReason, () => heard.stopReason),188- }),189- });190-191-/** How long a settled harness gets to exit on its own before it is killed. */192-const EXIT_GRACE = Duration.seconds(10);193-194-/** How long a killed harness gets before `SIGKILL`. */195-const KILL_GRACE = Duration.seconds(5);196-197-/** The last characters of a harness's stderr kept, to say why it failed. */198-const STDERR_TAIL = 2000;199-200-/**201- * One harness process: `argv` in the clone with `env`. Every stdout line202- * goes to `file`, scrubbed of the token, and is read for events until the203- * session settles or the output ends. A settled harness gets `EXIT_GRACE`204- * to exit; then it is killed with its process group.205- */206-const attempt = (input: {207- readonly argv: readonly string[];208- readonly driver: HarnessDriver;209- readonly env: Readonly<Record<string, string>>;210- readonly file: string;211- readonly workspace: AgentWorkspace;212- /** Runs when the output first names the session: the attempt counts from then. */213- readonly onSession: Effect.Effect<void>;214-}) =>215- Effect.scoped(216- Effect.gen(function* () {217- const fs = yield* FileSystem.FileSystem;218- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;219- const [command = "", ...args] = input.argv;220- const scrub = (text: string) => scrubbed(text, input.workspace);221-222- yield* fs.writeFileString(input.file, "");223-224- const child = yield* spawner.spawn(225- ChildProcess.make(command, args, {226- cwd: input.workspace.clone,227- env: { ...input.env },228- extendEnv: false,229- forceKillAfter: KILL_GRACE,230- stdin: "ignore",231- })232- );233-234- const stderr = yield* child.stderr.pipe(235- Stream.decodeText(),236- Stream.runFold(237- () => "",238- (tail, text) => `${tail}${text}`.slice(-STDERR_TAIL)239- ),240- Effect.forkScoped241- );242-243- const heard = yield* child.stdout.pipe(244- Stream.decodeText(),245- Stream.splitLines,246- Stream.tap((line) =>247- fs.writeFileString(input.file, `${scrub(line)}\n`, { flag: "a" })248- ),249- Stream.flatMap((line) => Stream.fromIterable(input.driver.parse(line))),250- Stream.tap((event) =>251- HarnessEvent.$is("SessionStarted")(event)252- ? input.onSession253- : Effect.void254- ),255- Stream.takeUntil(HarnessEvent.$is("Settled")),256- Stream.runFold(() => nothingHeard, hear)257- );258-259- const code = yield* child.exitCode.pipe(260- Effect.timeoutOption(EXIT_GRACE),261- Effect.map(Option.map(Number))262- );263-264- // A harness still running after its grace keeps its stderr open:265- // its tail is then not waited for.266- const tail = yield* Fiber.join(stderr).pipe(267- Effect.timeoutOption(Duration.seconds(1)),268- Effect.map(Option.getOrElse(() => ""))269- );270-271- return { code, heard, stderr: scrub(tail).trim() };272- })273- ).pipe(274- Effect.mapError(275- ({ message }) =>276- new SwarmFailed({277- reason: `${input.argv[0] ?? "the harness"} didn't run: ${message}`,278- })279- )280- );281-161 /** What the loop does once an attempt's answer is known. */162 export type Next = Data.TaggedEnum<{163 /** Resume the session with this prompt. */164 Resume: { readonly prompt: string; readonly nudge: boolean };206 unmodified lines371 Effect.gen(function* () {372 const { assignment, workspace } = input;373 const { adapter, handle, harness, model } = assignment.contributor;374 const driver = drivers[harness];375+ const view = input.view ?? headlessView;376 const project = Option.fromUndefinedOr(input.project);377 const begun = yield* Clock.currentTimeMillis;378 const progress = yield* Ref.make(started);379 380 const say = (line: string) =>381 Console.error(scrubbed(`${handle}: ${line}`, workspace));382 383 /**504- * One harness session (the start, or a continuation with `argv`), then505- * what status says; it calls itself for each continuation, until384+ * One harness session (the start, or a continuation: `turn`), then what385+ * status says; it calls itself for each continuation, until386 * `afterSettle` says the run is done.387 */388 const pass = (509- argv: readonly string[],389+ turn: Turn,390 env: Readonly<Record<string, string>>391 ): Effect.Effect<392 AgentOutcome,393 SwarmFailed,1 unmodified line395 > =>396 Effect.gen(function* () {397 const attempts = (yield* Ref.get(progress)).attempts + 1;398 519- const ran = yield* attempt({520- argv,521- driver,399+ const ran = yield* view.attempt({400+ contributor: assignment.contributor,401 env,402 file: `${workspace.dir}/attempt-${attempts}.jsonl`,403 onSession: Ref.update(progress, (now) => ({404 ...now,405 attempts: Math.max(now.attempts, attempts),406 })),407+ turn,408 workspace,409 });410 411 const { session } = ran.heard;52 unmodified lines464 `${step.next.nudge ? "no new answer, so a nudge" : `refused ${tagsOf(status)}, so the refusal`} goes back into the session (continuation ${step.progress.continuations} of ${input.maxContinuations})`465 );466 467 return yield* pass(588- driver.resume({589- adapter,590- model,591- prompt: step.next.prompt,592- session: session.value,593- workspace,594- }),468+ Turn.Resume({ prompt: step.next.prompt, session: session.value }),469 env470 );471 });472 13 unmodified lines486 )487 );488 489 return yield* pass(616- driver.start({617- adapter,618- brief: input.brief,619- model,620- sessionDir: sessionDirOf(workspace.dir),621- sessionKey: handle,622- workspace,623- }),490+ Turn.Start({ brief: input.brief }),491 yield* harnessEnv(workspace)492 );493 });494 31 unmodified linesmodified:scripts/swarm.ts+50 added-10 removed
16 unmodified lines17 * 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+ *22+ * `--view herdr` (issue 717, for the video) runs from a herdr pane: each23+ * harness runs interactively in a pane of its own, with a counter pane of24+ * claims, pushes and landings (`lib/swarm/views/herdr.ts`). The loop and25+ * its outcomes are the same.26 */27 import { BunRuntime, BunServices } from "@effect/platform-bun";28 import { AskListing } from "@repo/protocol/domain/ask";29 import { ClaimView } from "@repo/protocol/domain/claim";39 unmodified lines69 writeAgentsResult,70 } from "./lib/swarm/results.ts";71 import type { AgentRun } from "./lib/swarm/results.ts";72 import { roster } from "./lib/swarm/roster.ts";73+import { headlessView } from "./lib/swarm/views/headless.ts";74+import type { SwarmView } from "./lib/swarm/views/headless.ts";75+import { openHerdrView } from "./lib/swarm/views/herdr.ts";76 import {77 anonymousEnv,78 cliEntry,79 personEnv,281 unmodified lines361 readonly options: SwarmOptions;362 readonly origin: string;363 readonly run: string;364 readonly token: Redacted.Redacted;365+ readonly view: SwarmView;366 }) =>367 Effect.gen(function* () {368 const { assignment, options, origin, token } = input;369 const { contributor } = assignment;78 unmodified lines448 brief: ready.success.text,449 maxContinuations: 3,450 project: options.project,451 timeoutMs: options.timeoutMin * 60_000,452+ view: input.view,453 workspace: ready.success.workspace,454 });455 });456 69 unmodified lines526 const name = yield* runName;527 const commit = yield* headCommit;528 const at = yield* DateTime.now;529 520- const runs = yield* Effect.forEach(521- plan.assignments,522- (assignment) =>523- Effect.flatMap(524- Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),525- (token) =>526- contributorRun({ assignment, options, origin, run: name, token })527- ),528- { concurrency: 6 }529- ).pipe(Effect.mapError(() => failed("a contributor lost their token")));530+ const runs = yield* Effect.scoped(531+ Effect.gen(function* () {532+ const view =533+ options.view === "herdr"534+ ? yield* openHerdrView({535+ contributors: plan.assignments.map(536+ ({ contributor }) => contributor537+ ),538+ origin,539+ project: options.project,540+ runDir: yield* runDir(name),541+ }).pipe(542+ Effect.tap(({ workspace }) =>543+ say(544+ `herdr: workspace ${workspace} holds the panes; close it with herdr workspace close ${workspace}`545+ )546+ ),547+ Effect.map(({ view: panes }) => panes)548+ )549+ : headlessView;550 551+ return yield* Effect.forEach(552+ plan.assignments,553+ (assignment) =>554+ Effect.flatMap(555+ Effect.fromNullishOr(tokens.get(assignment.contributor.handle)),556+ (token) =>557+ contributorRun({558+ assignment,559+ options,560+ origin,561+ run: name,562+ token,563+ view,564+ })565+ ),566+ { concurrency: 6 }567+ ).pipe(Effect.mapError(() => failed("a contributor lost their token")));568+ })569+ );570+571 const result: AgentsResult = {572 at,573 commit,574 project: options.project,27 unmodified lines