Run the swarm in herdr's panes for the video, with a live counter of claims, pushes and landings
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- `--view herdr` (herdr 0.9.3; subcommands and flags read from `herdr --help`, `herdr agent --help` and the binary's usage lines) opens a workspace of its own in the herdr session the swarm runs in, lays out up to six contributor panes (two rows of three, equal widths) over a counter strip, and starts each harness interactively with `herdr agent start <handle> --kind <k> --pane <id> --timeout 120000 -- <flags>`. Every prompt (the brief, each refusal, the nudge) goes in with `herdr agent prompt <handle> <text> --wait`. Outcomes still come only from `<cli> status --json`; `--view headless` is unchanged. - `--wait` alone, not the issue's `--until done --until blocked`: it already matches idle, done and blocked, and a Claude Code turn ended `idle` live, which the ASSUMPTION's form would never have matched. - The loop's one seam (issue 717's allowance): `RunAgent` takes an optional `view: SwarmView`, headless by default, and hands it a `Turn` (start on the brief, or resume a session with a prompt) instead of argv. The headless process runner moved verbatim from `loop.ts` into `views/headless.ts` with the view contract; 711's tests pass unchanged. - A harness's interactive flags are its driver's start argv less what only headless mode needs (Claude Code `-p --verbose --output-format`, OpenCode `run --format -m`, Amp `-x --stream-json --no-archive-after-execute`, pi `-p --mode`), so the safety flags (bypass permissions, `--strict-mcp-config`, `--no-mcp`, the workspace's sessions and Amp settings) stay the headless run's. OpenCode's interface takes no model flag: `OPENCODE_CONFIG_CONTENT` carries it. - Each pane gets its contributor's env through a pipe (`mkfifo -m 600`): the pane runs a script that clears its env to the terminal's and herdr's own names, sources the harness env from the pipe and execs a shell without rc files in the clone. No token is in a file, an argv or on screen; panes do not inherit the herdr CLI's env (probed). - Claude Code asks two questions at startup in a new folder: folder trust ("No, exit" first; the swarm answers yes, the clone is its own) and CLAUDE.md imports from above the clone (the swarm keeps the default, no). The view recognises only these from herdr's detection text and answers each once; any other startup question waits for the person at the panes, and fails the run after 3 minutes. - The counter follows the project's public `watch` over the platform's framed `/rpc` through curl (scripts may use only `effect/process`), from the last event the project held when the run began (one plain JSON replay), and appends a line per claim, push and landing; the counter pane tails it. It follows again from its last event when the stream ends. - `--view herdr` refuses outside a herdr pane (no `HERDR_ENV=1` or `HERDR_SOCKET_PATH`), before any claim, rather than drive whichever session is focused. - Outside the territory, needed by the flag: `scripts/lib/swarm/args.ts` (swarm.ts's flag decoder) accepts `--view herdr` as `view`; 702's `swarm.test.ts` flag tests trade the "not built yet" case for an unknown view and expect `view: "headless"` by default. `infra/created.jsonl` gains the live run's fork, as the swarm records every fork for teardown. - Tests: `packages/config/test/swarm-herdr.test.ts` (14), red by assertion first: the counter line (`claims 6 · pushes 9 · landed 4`); the layout, interactive flags, start and prompt argv; a full `main --view herdr` run over a fake spawner (layout, one start per contributor, one prompt per brief, wren's refusal as a second prompt, outcomes from status, no token anywhere); Claude Code's two startup questions and an unknown one, on the TestClock; the counter's baseline and its framed stream from lines recorded off dev-oscabriel. The gate and de-duplication tests were each seen catching a planted bug. - Live, dev-oscabriel, `--only wren`, in a herdr test session of its own: Claude Code started in its pane, got past both startup questions, took the brief, pushed e79ba3d (the counter showed the claim and the push), and status refused it `VerifierBlocked`×2 (the platform could not run the checks); the refusal and then a nudge went into the same session, and the run ended `refused` after 3 attempts. The claim was released after; the fork is in the ledger.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+2600 added−180 removed
- tests:+1170 added−3 removed
- other:+1430 added−177 removed
Provenance
- Commit
a2ef0f8- Tree
ae2a893- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
2b7b80c
9 files changed+2600 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+1166 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.476+ */477+const herdrWorld = Effect.gen(function* () {478+ const panes = yield* Ref.make(1);479+ const reads = yield* Ref.make(new Map<string, number>());480+ const listed = yield* fixture("list-asks.json");481+482+ const shown = (yield* fixture("show-ask.json")).replaceAll(483+ "{configDir}",484+ Brand.configDir485+ );486+487+ const answer = (call: Spawned) =>488+ Effect.gen(function* () {489+ const { args, command, env } = call;490+ const [first = "", second = "", third = ""] = args;491+492+ if (command === "herdr") {493+ if (first === "workspace") {494+ return JSON.stringify({495+ id: "cli:workspace:create",496+ result: {497+ root_pane: { pane_id: "w9:p1", workspace_id: "w9" },498+ type: "workspace_created",499+ workspace: { workspace_id: "w9" },500+ },501+ });502+ }503+504+ if (second === "split") {505+ return paneJson(506+ `w9:p${yield* Ref.updateAndGet(panes, (n) => n + 1)}`507+ );508+ }509+510+ if (first === "agent") {511+ return agentJson(512+ third,513+ second === "start" ? "agent_started" : "agent_prompted"514+ );515+ }516+517+ return JSON.stringify({ id: "cli:pane", result: { type: "ok" } });518+ }519+520+ if (command === "git") {521+ return "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n";522+ }523+524+ if (command === "curl") {525+ return args.includes("content-type: application/json")526+ ? '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]'527+ : "";528+ }529+530+ if (first === "status") {531+ const handle = holderOf(env) ?? "nobody";532+533+ const count =534+ (yield* Ref.updateAndGet(reads, (seen) =>535+ new Map(seen).set(handle, (seen.get(handle) ?? 0) + 1)536+ )).get(handle) ?? 1;537+538+ return statusOf(handle, count);539+ }540+541+ return (542+ {543+ ask: shown,544+ asks: listed,545+ claim: claimOf(third, holderOf(env) ?? "nobody"),546+ }[second] ?? ""547+ );548+ });549+550+ return yield* fakeSpawner((call) =>551+ Effect.map(answer(call), (stdout) => ({ stdout }))552+ );553+});554+555+/** What herdr puts in the env of a process in one of its panes. */556+const inAPane = { HERDR_ENV: "1" };557+558+/**559+ * `main --view herdr` for every contributor over `herdrWorld`, from a herdr560+ * pane unless `herdrEnv` says otherwise, with `.swarm/` and the ledger in a561+ * temp dir.562+ */563+const herdrRunWith = (herdrEnv: Readonly<Record<string, string>>) =>564+ Effect.gen(function* () {565+ const fs = yield* FileSystem.FileSystem;566+ const swarm = yield* fs.makeTempDirectoryScoped();567+ const world = yield* herdrWorld;568+ const printed: string[] = [];569+570+ const captured: Console.Console = {571+ ...console,572+ error: (...args: readonly unknown[]) => {573+ printed.push(args.map(String).join(" "));574+ },575+ log: (...args: readonly unknown[]) => {576+ printed.push(args.map(String).join(" "));577+ },578+ };579+580+ const sessions = Object.fromEntries(581+ handles.map((handle) => [tokenOf(handle), handle])582+ );583+584+ const result = yield* main([585+ "--stage",586+ "dev-oscabriel",587+ "--url",588+ platformUrl,589+ "--view",590+ "herdr",591+ ]).pipe(592+ Effect.provide(world.layer),593+ Effect.provideService(SwarmDir, swarm),594+ Effect.provideService(LedgerFile, `${swarm}/created.jsonl`),595+ Effect.provideService(Console.Console, captured),596+ Effect.provideService(597+ ConfigProvider.ConfigProvider,598+ ConfigProvider.fromEnv({599+ env: {600+ ...herdrEnv,601+ HOME: "/home/user",602+ SESSION_TOKENS: JSON.stringify(sessions),603+ SHELL: "/usr/bin/zsh",604+ TERM: "xterm-256color",605+ },606+ })607+ ),608+ Effect.result609+ );610+611+ // The TestClock's epoch names the run.612+ const run = `${swarm}/19700101-000000`;613+ const summary = `${run}/agents.json`;614+ const wrensScript = `${run}/wren/pane-shell`;615+616+ return {617+ agents: (yield* fs.exists(summary))618+ ? Option.some(yield* fs.readFileString(summary))619+ : Option.none<string>(),620+ printed,621+ result,622+ root: (yield* repoRoot).replace(/\/$/u, ""),623+ run,624+ spawned: yield* world.spawned,625+ wrensScript: (yield* fs.exists(wrensScript))626+ ? yield* fs.readFileString(wrensScript)627+ : "",628+ };629+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));630+631+const herdrRun = herdrRunWith(inAPane);632+633+/** The herdr calls of a run, as argv. */634+const herdrCalls = (spawned: readonly Spawned[]) =>635+ spawned.flatMap(({ args, command }) => (command === "herdr" ? [args] : []));636+637+/** The `agent <verb>` calls among `calls`, by the agent's name. */638+const agentCalls = (calls: readonly (readonly string[])[], verb: string) =>639+ calls.flatMap((call) =>640+ call[0] === "agent" && call[1] === verb641+ ? [{ args: call, name: call[2] ?? "" }]642+ : []643+ );644+645+/** The pane each contributor's harness runs in: the layout's order over `w9:p1`, `w9:p2`, …. */646+const paneOf = new Map([647+ ["wren", "w9:p1"],648+ ["counter", "w9:p2"],649+ ["marisol", "w9:p3"],650+ ["tamsin", "w9:p4"],651+ ["ivo", "w9:p5"],652+ ["dagny", "w9:p6"],653+ ["pell", "w9:p7"],654+]);655+656+const byName = (657+ one: { readonly name: string },658+ other: { readonly name: string }659+) => one.name.localeCompare(other.name);660+661+describe("a run in herdr's panes", () => {662+ it.effect(663+ "lays the panes out in a workspace of their own, with a counter pane that shows the run's counter file",664+ () =>665+ Effect.gen(function* () {666+ const { result, root, run, spawned } = yield* herdrRun;667+ const calls = herdrCalls(spawned);668+669+ expect(Result.isSuccess(result)).toBeTruthy();670+ expect(calls.slice(0, 7)).toStrictEqual([671+ [672+ "workspace",673+ "create",674+ "--cwd",675+ root,676+ "--label",677+ "swarm burrow",678+ "--focus",679+ ],680+ ...[681+ ["w9:p1", "down", "0.85"],682+ ["w9:p1", "down", "0.5"],683+ ["w9:p1", "right", "0.333"],684+ ["w9:p4", "right", "0.5"],685+ ["w9:p3", "right", "0.333"],686+ ["w9:p6", "right", "0.5"],687+ ].map(([pane = "", direction = "", ratio = ""]) => [688+ "pane",689+ "split",690+ pane,691+ "--direction",692+ direction,693+ "--ratio",694+ ratio,695+ "--cwd",696+ root,697+ "--no-focus",698+ ]),699+ ]);700+ expect(calls).toContainEqual([701+ "pane",702+ "run",703+ "w9:p2",704+ `clear; tail -n +1 -F ${run}/counter.log`,705+ ]);706+ expect(calls).toContainEqual([707+ "pane",708+ "rename",709+ "w9:p1",710+ "wren · claude-code",711+ ]);712+ })713+ );714+715+ it.effect(716+ "starts each contributor's harness in their pane with their driver's flags",717+ () =>718+ Effect.gen(function* () {719+ const { run, spawned } = yield* herdrRun;720+ const starts = agentCalls(herdrCalls(spawned), "start");721+722+ expect(starts.toSorted(byName).map(({ args }) => args)).toStrictEqual(723+ roster724+ .map((contributor) => {725+ const { argv, kind } = interactiveLaunch({726+ contributor,727+ dir: `${run}/${contributor.handle}`,728+ });729+730+ return {731+ args: [732+ "agent",733+ "start",734+ contributor.handle,735+ "--kind",736+ kind,737+ "--pane",738+ paneOf.get(contributor.handle) ?? "",739+ "--timeout",740+ "120000",741+ "--",742+ ...argv,743+ ],744+ name: contributor.handle,745+ };746+ })747+ .toSorted(byName)748+ .map(({ args }) => args)749+ );750+ // wren's harness is Claude Code, started with the headless run's751+ // safety flags: every tool allowed, no MCP server of the user's.752+ expect(753+ starts.find(({ name }) => name === "wren")?.args.slice(9)754+ ).toStrictEqual([755+ "--",756+ "--permission-mode",757+ "bypassPermissions",758+ "--strict-mcp-config",759+ "--model",760+ "claude-opus-5-5",761+ ]);762+ })763+ );764+765+ it.effect(766+ "sends each contributor's brief into their pane's session and waits until it settles",767+ () =>768+ Effect.gen(function* () {769+ const { spawned } = yield* herdrRun;770+ const prompts = agentCalls(herdrCalls(spawned), "prompt");771+772+ const firsts = handles.map(773+ (handle) => prompts.find(({ name }) => name === handle)?.args ?? []774+ );775+776+ expect(777+ firsts.map((prompt) => [prompt[2], prompt[4], prompt.length])778+ ).toStrictEqual(handles.map((handle) => [handle, "--wait", 5]));779+ expect(780+ firsts.map((prompt, at) =>781+ (prompt[3] ?? "").includes(children[at] ?? "?")782+ )783+ ).toStrictEqual(handles.map(() => true));784+ })785+ );786+787+ it.effect(788+ "sends a refusal back into the same pane's session as a second prompt, and reads the outcome only from status",789+ () =>790+ Effect.gen(function* () {791+ const { agents, spawned } = yield* herdrRun;792+793+ const wrens = agentCalls(herdrCalls(spawned), "prompt").filter(794+ ({ name }) => name === "wren"795+ );796+797+ expect(wrens).toHaveLength(2);798+ expect(wrens[1]?.args[3]).toContain(799+ [...explain([outOfScope]), "", `Next: ${outOfScope.next}`].join("\n")800+ );801+802+ const summary = yield* Schema.decodeEffect(803+ Schema.fromJsonString(AgentsResult)804+ )(Option.getOrElse(agents, () => ""));805+806+ expect(807+ summary.runs.map(({ attempts, handle, outcome, refusals }) => [808+ handle,809+ outcome,810+ attempts,811+ refusals,812+ ])813+ ).toStrictEqual(814+ handles.map((handle) =>815+ handle === "wren"816+ ? [handle, "landed", 2, { OutOfScope: 1 }]817+ : [handle, "landed", 1, {}]818+ )819+ );820+ })821+ );822+823+ it.effect(824+ "refuses outside a herdr pane, before anything is claimed, rather than drive whichever session is focused",825+ () =>826+ Effect.gen(function* () {827+ const { result, spawned } = yield* herdrRunWith({});828+829+ expect(830+ Result.match(result, {831+ onFailure: ({ reason }) => reason,832+ onSuccess: () => "",833+ })834+ ).toContain("start the swarm from a herdr pane");835+ expect(836+ spawned.flatMap(({ args, command }) =>837+ command === "herdr" || args[1] === "claim" ? [args] : []838+ )839+ ).toStrictEqual([]);840+ })841+ );842+843+ it.effect(844+ "hands each pane its contributor's env through a pipe, so no token is in any argv, script or line",845+ () =>846+ Effect.gen(function* () {847+ const { printed, run, spawned, wrensScript } = yield* herdrRun;848+849+ expect(850+ spawned.flatMap(({ args, command }) =>851+ command === "mkfifo" ? [args] : []852+ )853+ ).toContainEqual(["-m", "600", `${run}/wren/pane-env`]);854+ expect(herdrCalls(spawned)).toContainEqual([855+ "pane",856+ "run",857+ "w9:p1",858+ `exec ${run}/wren/pane-shell`,859+ ]);860+ expect(wrensScript).toContain(`${run}/wren/pane-env`);861+ expect(862+ [863+ wrensScript,864+ ...printed,865+ ...spawned.flatMap(({ args }) => args),866+ ].filter((text) =>867+ handles.some((handle) => text.includes(tokenOf(handle)))868+ )869+ ).toStrictEqual([]);870+ })871+ );872+});873+874+/** What herdr's detection text shows while Claude Code 2.1.293 asks whether to trust a new folder. */875+const trustQuestion = [876+ " Accessing workspace:",877+ "",878+ " Quick safety check: Is this a project you created or one you trust?",879+ "",880+ " ❯ No, exit",881+ " Yes, I trust this folder",882+].join("\n");883+884+/** …and then whether to import the CLAUDE.md files above the clone. */885+const importsQuestion = [886+ " Allow external CLAUDE.md file imports?",887+ "",888+ " No, disable external imports",889+ " ❯ Yes, allow external imports",890+].join("\n");891+892+const [wren] = roster;893+894+/** wren's workspace for run `r1`. */895+const wrensWorkspace: AgentWorkspace = {896+ clone: "/work/.swarm/r1/wren/clone",897+ dir: "/work/.swarm/r1/wren",898+ env: { [`${SLUG}_TOKEN`]: tokenOf("wren") },899+ redacted: [`${SLUG}_TOKEN`],900+};901+902+/** The first of `queue`, taken off it unless it is the last. */903+const takeFrom = (queue: Ref.Ref<readonly string[]>) =>904+ Ref.modify(queue, (all) => [905+ all[0] ?? "",906+ all.length > 1 ? all.slice(1) : all,907+ ]);908+909+/**910+ * wren's first attempt in herdr's pane `w9:p1`, where herdr finds Claude911+ * Code blocked at startup: each `agent get` says the next of `states`912+ * (`blocked` until the last), and each `agent read` shows the next of913+ * `screens`. Files are kept in memory, so the TestClock moves as `clock`914+ * says, deterministically.915+ */916+const blockedStart = (input: {917+ readonly states: readonly string[];918+ readonly screens: readonly string[];919+ readonly clock: Effect.Effect<void>;920+}) =>921+ Effect.gen(function* () {922+ const states = yield* Ref.make(input.states);923+ const screens = yield* Ref.make(input.screens);924+925+ const world = yield* fakeSpawner(({ args, command }) =>926+ Effect.gen(function* () {927+ if (command !== "herdr" || args[0] !== "agent") {928+ return {};929+ }930+931+ if (args[1] === "start") {932+ return {933+ code: 1,934+ stderr: JSON.stringify({935+ error: {936+ code: "agent_not_ready",937+ message:938+ "agent wren is blocked during startup and is not ready for prompts",939+ },940+ id: "cli:agent:start",941+ }),942+ };943+ }944+945+ if (args[1] === "get") {946+ const status = yield* takeFrom(states);947+948+ return {949+ stdout: JSON.stringify({950+ result: {951+ agent: {952+ agent_status: status,953+ interactive_ready: status === "idle",954+ },955+ },956+ }),957+ };958+ }959+960+ if (args[1] === "read") {961+ return { stdout: yield* takeFrom(screens) };962+ }963+964+ return args[1] === "prompt"965+ ? { stdout: agentJson("wren", "agent_prompted") }966+ : {};967+ })968+ );969+970+ const files = new Map<string, string>();971+972+ const memoryFs = FileSystem.makeNoop({973+ chmod: () => Effect.void,974+ remove: () => Effect.void,975+ writeFileString: (path, data, options) =>976+ Effect.sync(() => {977+ files.set(978+ path,979+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data980+ );981+ }),982+ });983+984+ const fiber = yield* herdrView(new Map([["wren", "w9:p1"]]))985+ .attempt({986+ contributor: wren,987+ env: { HOME: "/home/user", ...wrensWorkspace.env },988+ file: `${wrensWorkspace.dir}/attempt-1.jsonl`,989+ onSession: Effect.void,990+ turn: Turn.Start({ brief: "Answer the ask." }),991+ workspace: wrensWorkspace,992+ })993+ .pipe(994+ Effect.provide(world.layer),995+ Effect.provideService(FileSystem.FileSystem, memoryFs),996+ Effect.result,997+ Effect.forkChild998+ );999+1000+ yield* input.clock;1001+1002+ return {1003+ calls: herdrCalls(yield* world.spawned),1004+ result: yield* Fiber.join(fiber),1005+ };1006+ });1007+1008+describe("a harness blocked at startup", () => {1009+ it.effect(1010+ "gets Claude Code past its folder-trust and CLAUDE.md-import questions as the swarm decides, then sends the brief",1011+ () =>1012+ Effect.gen(function* () {1013+ const { calls, result } = yield* blockedStart({1014+ clock: TestClock.adjust("10 seconds"),1015+ screens: [trustQuestion, trustQuestion, importsQuestion],1016+ states: ["blocked", "blocked", "blocked", "idle"],1017+ });1018+1019+ expect(1020+ agentCalls(calls, "send-keys").map(({ args }) => args)1021+ ).toStrictEqual([1022+ ["agent", "send-keys", "wren", "down", "enter"],1023+ ["agent", "send-keys", "wren", "enter"],1024+ ]);1025+ expect(1026+ agentCalls(calls, "prompt").map(({ args }) => args)1027+ ).toStrictEqual([1028+ ["agent", "prompt", "wren", "Answer the ask.", "--wait"],1029+ ]);1030+ expect(1031+ Result.map(result, ({ heard }) => [heard.session, heard.settled])1032+ ).toStrictEqual(Result.succeed([Option.some("wren"), true]));1033+ })1034+ );1035+1036+ it.effect(1037+ "leaves a question it doesn't know to the person at the panes, and fails the run when nobody answers it",1038+ () =>1039+ Effect.gen(function* () {1040+ const { calls, result } = yield* blockedStart({1041+ clock: TestClock.adjust("4 minutes"),1042+ screens: [" Do you want to enable telemetry?\n ❯ Yes\n No"],1043+ states: ["blocked"],1044+ });1045+1046+ expect(agentCalls(calls, "send-keys")).toStrictEqual([]);1047+ expect(1048+ Result.match(result, {1049+ onFailure: ({ reason }) => reason,1050+ onSuccess: () => "",1051+ })1052+ ).toBe(1053+ "claude-code is still blocked at startup in herdr pane w9:p1: answer it there, or run --view headless"1054+ );1055+ })1056+ );1057+});1058+1059+/**1060+ * What dev-oscabriel's `/rpc` answered `watch` for burrow over plain JSON1061+ * on 2026-10-08 (two of its eight events, the others cut): the frames at1062+ * once, then the exit.1063+ */1064+const replayed = [1065+ '[{"_tag":"Chunk","requestId":"1","values":[',1066+ '{"_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"}},',1067+ '{"_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"}}',1068+ ']},{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',1069+].join("");1070+1071+/**1072+ * The framed stream's lines, as dev-oscabriel sends them over NDJSON: one1073+ * frame per line. The first repeats an event the counter already heard1074+ * (a claim, so a counter that heard it twice would say so).1075+ */1076+const streamed = [1077+ '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:00:00.000Z","seq":8,"ask":"drop-legacy-fetch-burrow-billing","claimant":"tamsin"}]}',1078+ '{"_tag":"Chunk","requestId":"1","values":[{"_tag":"Claimed","at":"2026-10-08T12:05:00.000Z","seq":9,"ask":"drop-legacy-fetch-burrow-auth","claimant":"wren"}]}',1079+ `{"_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"}]}`,1080+ '{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}',1081+].join("\n");1082+1083+describe("the counter's watch", () => {1084+ it.effect(1085+ "starts after the last event the project holds, from watch's plain JSON replay",1086+ () =>1087+ Effect.gen(function* () {1088+ const world = yield* fakeSpawner(() =>1089+ Effect.succeed({ stdout: replayed })1090+ );1091+1092+ const from = yield* lastHeld(1093+ platformUrl,1094+ ProjectName.make("burrow")1095+ ).pipe(Effect.provide(world.layer));1096+1097+ expect(from).toBe(8);1098+ expect((yield* world.spawned).map(({ args }) => args)).toStrictEqual([1099+ [1100+ "--silent",1101+ "--show-error",1102+ "--no-buffer",1103+ "--request",1104+ "POST",1105+ "--header",1106+ "content-type: application/json",1107+ "--data-binary",1108+ '[{"_tag":"Request","headers":[],"id":"1","payload":{"project":"burrow"},"tag":"watch"}]',1109+ `${platformUrl}/rpc`,1110+ ],1111+ ]);1112+ })1113+ );1114+1115+ it.effect(1116+ "follows the framed stream after that event and writes a line per claim, push and landing",1117+ () =>1118+ Effect.gen(function* () {1119+ const world = yield* fakeSpawner(() =>1120+ Effect.succeed({ stdout: streamed })1121+ );1122+1123+ const files = new Map<string, string>();1124+1125+ const memoryFs = FileSystem.makeNoop({1126+ writeFileString: (path, data, options) =>1127+ Effect.sync(() => {1128+ files.set(1129+ path,1130+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data1131+ );1132+ }),1133+ });1134+1135+ const fiber = yield* followCounter({1136+ file: "/work/counter.log",1137+ from: 8,1138+ origin: platformUrl,1139+ project: ProjectName.make("burrow"),1140+ }).pipe(1141+ Effect.provide(world.layer),1142+ Effect.provideService(FileSystem.FileSystem, memoryFs),1143+ Effect.forkChild1144+ );1145+1146+ yield* TestClock.adjust("1 second");1147+ yield* Fiber.interrupt(fiber);1148+1149+ expect(files.get("/work/counter.log")?.split("\n")).toStrictEqual([1150+ "claims 0 · pushes 0 · landed 0 (burrow, after event 8)",1151+ "12:05:00 claims 1 · pushes 0 · landed 0 wren claimed drop-legacy-fetch-burrow-auth",1152+ "12:06:00 claims 1 · pushes 1 · landed 0 drop-legacy-fetch-burrow-auth pushed 1111111",1153+ "",1154+ ]);1155+ expect(1156+ (yield* world.spawned).map(({ args }) => args.slice(6, 9))1157+ ).toStrictEqual([1158+ [1159+ "content-type: application/ndjson",1160+ "--data-binary",1161+ '{"_tag":"Request","headers":[],"id":"1","payload":{"project":"burrow","since":8},"tag":"watch"}\n',1162+ ],1163+ ]);1164+ })1165+ );1166+});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+275 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 } 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+/** `curl`'s flags for one POST to the platform's `/rpc` with `contentType`. */142+const curlArgs = (input: {143+ readonly origin: string;144+ readonly contentType: string;145+ readonly body: string;146+}) => [147+ "--silent",148+ "--show-error",149+ "--no-buffer",150+ "--request",151+ "POST",152+ "--header",153+ `content-type: ${input.contentType}`,154+ "--data-binary",155+ input.body,156+ `${input.origin}/rpc`,157+];158+159+/**160+ * The last event `project` already holds, where a run's counter starts:161+ * `watch` over plain JSON replays what the project keeps and ends. 0 when162+ * it holds none, or the read fails.163+ */164+export const lastHeld = (origin: string, project: ProjectName) =>165+ run({166+ args: curlArgs({167+ body: `[${watchRequest(project, Option.none())}]`,168+ contentType: "application/json",169+ origin,170+ }),171+ command: "curl",172+ env: {},173+ }).pipe(174+ Effect.map(({ stdout }) =>175+ Option.getOrElse(decodeReplay(stdout), () => []).flatMap((frame) =>176+ isHeld(frame) ? frame.values.map(({ seq }) => seq) : []177+ )178+ ),179+ Effect.map((seqs) => Math.max(0, ...seqs)),180+ Effect.orElseSucceed(() => 0)181+ );182+183+/** Where the counter stands: the last event heard, and every counted one since the run began. */184+interface Tally {185+ readonly last: number;186+ readonly events: readonly ProjectEvent[];187+}188+189+/** How long the counter waits before it follows `watch` again. */190+const FOLLOW_AGAIN = Duration.seconds(2);191+192+/**193+ * Follows `project`'s `watch` at `origin` after event `from` (`lastHeld`,194+ * read before the run claims anything), appending a line to `file` for195+ * every claim, push and landing; it never ends on its own (interrupt it196+ * when the run is over).197+ */198+export const followCounter = (input: {199+ readonly origin: string;200+ readonly project: ProjectName;201+ readonly file: string;202+ readonly from: number;203+}) =>204+ Effect.gen(function* () {205+ const fs = yield* FileSystem.FileSystem;206+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;207+ const tally = yield* Ref.make<Tally>({ events: [], last: input.from });208+ const said = yield* Ref.make(false);209+210+ const append = (line: string) =>211+ fs.writeFileString(input.file, `${line}\n`, { flag: "a" });212+213+ const hear = (event: ProjectEvent) =>214+ Effect.gen(function* () {215+ const before = yield* Ref.get(tally);216+217+ if (event.seq <= before.last) {218+ return;219+ }220+221+ const events = counted(event)222+ ? [...before.events, event]223+ : before.events;224+225+ yield* Ref.set(tally, { events, last: event.seq });226+227+ if (counted(event)) {228+ yield* append(counterEntry(events, event));229+ }230+ });231+232+ const followOnce = Effect.scoped(233+ Effect.gen(function* () {234+ const { last } = yield* Ref.get(tally);235+236+ const child = yield* spawner.spawn(237+ ChildProcess.make(238+ "curl",239+ curlArgs({240+ body: `${watchRequest(input.project, Option.some(last))}\n`,241+ contentType: "application/ndjson",242+ origin: input.origin,243+ }),244+ { stderr: "ignore", stdin: "ignore" }245+ )246+ );247+248+ yield* child.stdout.pipe(249+ Stream.decodeText(),250+ Stream.splitLines,251+ Stream.flatMap((line) => Stream.fromIterable(eventsIn(line))),252+ Stream.runForEach(hear)253+ );254+ })255+ ).pipe(256+ // Said once, so a counter that cannot follow says why; it keeps trying.257+ Effect.tapError(({ message }) =>258+ Effect.gen(function* () {259+ if (!(yield* Ref.getAndSet(said, true))) {260+ yield* append(`counter: watch didn't run: ${message}`);261+ }262+ })263+ ),264+ Effect.ignore265+ );266+267+ yield* append(268+ `${counterLine([])} (${input.project}, after event ${input.from})`269+ );270+271+ return yield* followOnce.pipe(272+ Effect.repeat(Schedule.spaced(FOLLOW_AGAIN)),273+ Effect.andThen(Effect.never)274+ );275+ });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+837 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+import type { ProjectName } from "@repo/protocol/ids";18+import {19+ Config,20+ Duration,21+ Effect,22+ FileSystem,23+ Option,24+ Ref,25+ Result,26+ Schedule,27+ Schema,28+} from "effect";29+import type { Path, Scope } from "effect";30+import type { ChildProcessSpawner } from "effect/process";31+32+import { repoRoot } from "../../../../infra/stages.ts";33+import { drivers, sessionDirOf } from "../harnesses/index.ts";34+import type { Harness } from "../results.ts";35+import type { Contributor } from "../roster.ts";36+import { run, scrubbed, shellQuoted, SwarmFailed } from "../workspace.ts";37+import type { AgentWorkspace } from "../workspace.ts";38+import { followCounter, lastHeld } from "./counter.ts";39+import { nothingHeard, Turn } from "./headless.ts";40+import type { Attempted, SwarmView } from "./headless.ts";41+42+/** The counter's pane, below the contributors'. */43+export const COUNTER = "counter";44+45+/**46+ * One pane the layout makes: the pane `from` (already made) is split toward47+ * `direction`, keeping `ratio` of its space, and the new pane is `slot`.48+ */49+export interface Split {50+ readonly slot: string;51+ readonly from: string;52+ readonly direction: "right" | "down";53+ readonly ratio: number;54+}55+56+/** The share of the window the contributors keep above the counter strip. */57+const ABOVE_COUNTER = 0.85;58+59+/** `ratio` to three places, as herdr reads it. */60+const share = (ratio: number) => Math.round(ratio * 1000) / 1000;61+62+/**63+ * The panes for `handles`, as splits of the first one's pane (the64+ * workspace's own): a counter strip along the bottom, then up to three65+ * contributors to a row, two rows at most, each split keeping the share66+ * that leaves every pane of a row the same width. Pure.67+ */68+export const herdrLayout = (handles: readonly string[]): readonly Split[] => {69+ const [first] = handles;70+71+ if (first === undefined) {72+ return [];73+ }74+75+ const across =76+ handles.length <= 3 ? handles.length : Math.ceil(handles.length / 2);77+78+ const rows = [handles.slice(0, across), handles.slice(across)].filter(79+ (row) => row.length > 080+ );81+82+ const counter: Split = {83+ direction: "down",84+ from: first,85+ ratio: ABOVE_COUNTER,86+ slot: COUNTER,87+ };88+89+ const secondRow = rows.flatMap((row, at) => {90+ const [head] = row;91+92+ return at === 0 || head === undefined93+ ? []94+ : [{ direction: "down", from: first, ratio: 0.5, slot: head } as const];95+ });96+97+ const columns = rows.flatMap((row) =>98+ row.slice(1).map((slot, at): Split => ({99+ direction: "right",100+ from: row[at] ?? first,101+ ratio: share(1 / (row.length - at)),102+ slot,103+ }))104+ );105+106+ return [counter, ...secondRow, ...columns];107+};108+109+/** How long herdr waits for a harness to be ready for input when it starts one. */110+const START_TIMEOUT_MS = 120_000;111+112+/** `herdr agent start …`: the harness `kind`, named `handle`, in `pane`, with its own flags after `--`. Pure. */113+export const herdrStart = (input: {114+ readonly handle: string;115+ readonly kind: string;116+ readonly pane: string;117+ readonly argv: readonly string[];118+}): readonly string[] => [119+ "agent",120+ "start",121+ input.handle,122+ "--kind",123+ input.kind,124+ "--pane",125+ input.pane,126+ "--timeout",127+ String(START_TIMEOUT_MS),128+ "--",129+ ...input.argv,130+];131+132+/**133+ * `herdr agent prompt …`: `text` typed into the agent's session, then a134+ * wait until it settles. `--wait` alone matches `idle`, `done` and135+ * `blocked`: a turn that ends `idle` (seen on Claude Code) would never136+ * match `--until done --until blocked`. Pure.137+ */138+export const herdrPrompt = (input: {139+ readonly handle: string;140+ readonly text: string;141+}): readonly string[] => [142+ "agent",143+ "prompt",144+ input.handle,145+ input.text,146+ "--wait",147+];148+149+/**150+ * What only a headless run needs, per harness: the switches and the flags151+ * (with their values) the driver's start passes for print mode and JSON152+ * output, or for a prompt given on the command line. An interactive153+ * session gets its prompt from herdr instead.154+ */155+const HEADLESS_ONLY = {156+ amp: {157+ switches: ["--stream-json", "--no-archive-after-execute"],158+ valued: ["-x"],159+ },160+ "claude-code": { switches: ["-p", "--verbose"], valued: ["--output-format"] },161+ // `run` is OpenCode's headless subcommand; its interface takes no `-m`.162+ opencode: { switches: ["run"], valued: ["--format", "-m"] },163+ pi: { switches: ["-p"], valued: ["--mode"] },164+} as const satisfies Readonly<165+ Record<166+ Harness,167+ { readonly switches: readonly string[]; readonly valued: readonly string[] }168+ >169+>;170+171+/** Stands for the brief in a driver's argv, so the brief can be taken out. */172+const BRIEF = "\u0000brief";173+174+/** How a harness starts interactively: herdr's kind, its flags, and env it needs. */175+export interface Launch {176+ readonly kind: string;177+ readonly argv: readonly string[];178+ readonly env: Readonly<Record<string, string>>;179+}180+181+/**182+ * How `contributor`'s harness starts interactively in a pane: herdr's kind183+ * (the harness's executable, which herdr knows by the same name), and the184+ * driver's own start flags less `HEADLESS_ONLY` and the brief, so the185+ * settings that keep a contributor's session safe (every tool allowed, no186+ * MCP server of the user's, the workspace's sessions) are the headless187+ * run's. OpenCode's interface takes its model from inline config in the188+ * env. Pure.189+ */190+export const interactiveLaunch = (input: {191+ readonly contributor: Contributor;192+ readonly dir: string;193+}): Launch => {194+ const { adapter, handle, harness, model } = input.contributor;195+196+ const [kind = harness, ...flags] = drivers[harness].start({197+ adapter,198+ brief: BRIEF,199+ model,200+ sessionDir: sessionDirOf(input.dir),201+ sessionKey: handle,202+ workspace: {203+ clone: `${input.dir}/clone`,204+ dir: input.dir,205+ env: {},206+ redacted: [],207+ },208+ });209+210+ const { switches, valued } = HEADLESS_ONLY[harness];211+212+ const argv = flags.filter((flag, at) => {213+ const before = flags[at - 1] ?? "";214+215+ return (216+ flag !== BRIEF &&217+ !switches.some((one) => one === flag) &&218+ !valued.some((one) => one === flag || one === before)219+ );220+ });221+222+ return {223+ argv,224+ env:225+ harness === "opencode"226+ ? { OPENCODE_CONFIG_CONTENT: JSON.stringify({ model }) }227+ : {},228+ kind,229+ };230+};231+232+/** herdr refused a command: its error's code, and what it said. */233+class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {234+ code: Schema.String,235+ said: Schema.String,236+ verb: Schema.String,237+}) {238+ override get message() {239+ return `herdr ${this.verb}: ${this.code}: ${this.said}`;240+ }241+}242+243+const isRefused = Schema.is(HerdrRefused);244+245+/** What herdr prints on stderr when it refuses a command. */246+const decodeRefusal = Schema.decodeUnknownOption(247+ Schema.fromJsonString(248+ Schema.Struct({249+ error: Schema.Struct({ code: Schema.String, message: Schema.String }),250+ })251+ )252+);253+254+/**255+ * `herdr …` with the swarm's env, in the herdr session the swarm runs in:256+ * what it printed, or `HerdrRefused` with herdr's own error code.257+ */258+const herdr = (args: readonly string[]) =>259+ Effect.flatMap(run({ args, command: "herdr", env: {} }), (ran) => {260+ if (ran.code === 0) {261+ return Effect.succeed(ran.stdout);262+ }263+264+ const verb = args.slice(0, 2).join(" ");265+266+ return Effect.fail(267+ Option.match(decodeRefusal(ran.stderr), {268+ onNone: () =>269+ new HerdrRefused({270+ code: `exit ${ran.code}`,271+ said: ran.stderr.trim().slice(0, 500),272+ verb,273+ }),274+ onSome: ({ error }) =>275+ new HerdrRefused({ code: error.code, said: error.message, verb }),276+ })277+ );278+ });279+280+/** Ends a step on herdr's refusal, saying which. */281+const orFailed = <A, R>(282+ effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>283+): Effect.Effect<A, SwarmFailed, R> =>284+ effect.pipe(285+ Effect.catchTag("HerdrRefused", ({ message }) =>286+ Effect.fail(new SwarmFailed({ reason: message }))287+ )288+ );289+290+/** `printed` decoded as `schema`, or why herdr's answer was not what the step needs. */291+const answerOf =292+ <A, I>(schema: Schema.Codec<A, I>, what: string) =>293+ (printed: string) =>294+ Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(295+ Effect.mapError(296+ () =>297+ new SwarmFailed({298+ reason: `herdr ${what} answered without its JSON: ${printed.trim().slice(0, 300)}`,299+ })300+ )301+ );302+303+const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });304+305+/** `workspace create`: the workspace, and its first pane. */306+const WorkspaceMade = Schema.Struct({307+ result: Schema.Struct({308+ root_pane: PaneId,309+ workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),310+ }),311+});312+313+/** `pane split`: the new pane. */314+const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });315+316+/** An agent as herdr sees it: `idle`, `working`, `blocked`, `done` or `unknown`. */317+const AgentSeen = Schema.Struct({318+ result: Schema.Struct({319+ agent: Schema.Struct({320+ agent_status: Schema.String,321+ interactive_ready: Schema.optionalKey(Schema.Boolean),322+ }),323+ }),324+});325+326+/** A question a harness asks before it takes a prompt, and the keys that answer it as the swarm decides. */327+interface StartupQuestion {328+ /** Words only that question shows, in herdr's detection text. */329+ readonly asks: string;330+ readonly keys: readonly string[];331+}332+333+/**334+ * The questions each harness asks when it starts in a new folder (seen on335+ * Claude Code 2.1.293 and 2.1.294; OpenCode 2.0.7, Amp 0.0.1789750518 and336+ * pi 1.1.0 asked none):337+ *338+ * - Claude Code asks whether to trust the folder, "No, exit" first: the339+ * clone is the swarm's own, so it answers yes;340+ * - then whether to import the CLAUDE.md files above the clone (this341+ * repo's own, when `.swarm/` sits in the checkout), "No" first: it keeps342+ * the default, since they are not the contributor's project.343+ *344+ * Any other question is left for the person at the panes.345+ */346+const STARTUP_QUESTIONS = {347+ amp: [],348+ "claude-code": [349+ { asks: "Yes, I trust this folder", keys: ["down", "enter"] },350+ { asks: "Allow external CLAUDE.md file imports?", keys: ["enter"] },351+ ],352+ opencode: [],353+ pi: [],354+} as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;355+356+/** How long a harness gets to be ready for its brief once herdr says it is blocked at startup. */357+const STARTUP_WAIT = Duration.minutes(3);358+359+/** Whether herdr sees the agent ready for a prompt. */360+const readyIn = (printed: string) =>361+ Effect.map(362+ answerOf(AgentSeen, "agent get")(printed),363+ ({ result: { agent } }) =>364+ agent.interactive_ready === true &&365+ (agent.agent_status === "idle" || agent.agent_status === "done")366+ );367+368+/**369+ * A harness blocked at startup: each question it is known to ask is370+ * answered once, as `STARTUP_QUESTIONS` says, until herdr sees it ready.371+ * A question the table doesn't know waits for the person at the panes,372+ * until `STARTUP_WAIT` ends the run.373+ */374+const pastStartup = (input: {375+ readonly handle: string;376+ readonly harness: Harness;377+ readonly pane: string;378+}) =>379+ Effect.gen(function* () {380+ const answered = yield* Ref.make<readonly string[]>([]);381+382+ const look = Effect.gen(function* () {383+ const seen = yield* herdr(["agent", "get", input.handle]);384+385+ if (yield* readyIn(seen)) {386+ return true;387+ }388+389+ const shown = yield* herdr([390+ "agent",391+ "read",392+ input.handle,393+ "--source",394+ "detection",395+ ]);396+397+ const done = yield* Ref.get(answered);398+399+ const question = STARTUP_QUESTIONS[input.harness].find(400+ ({ asks }) => shown.includes(asks) && !done.includes(asks)401+ );402+403+ if (question !== undefined) {404+ yield* Ref.set(answered, [...done, question.asks]);405+ yield* herdr(["agent", "send-keys", input.handle, ...question.keys]);406+ }407+408+ return false;409+ });410+411+ const ready = yield* look.pipe(412+ Effect.repeat({413+ schedule: Schedule.spaced(Duration.seconds(1)),414+ until: (isReady: boolean) => isReady,415+ }),416+ Effect.timeoutOption(STARTUP_WAIT)417+ );418+419+ yield* Effect.fromOption(ready).pipe(420+ Effect.mapError(421+ () =>422+ new SwarmFailed({423+ reason: `${input.harness} is still blocked at startup in herdr pane ${input.pane}: answer it there, or run --view headless`,424+ })425+ )426+ );427+ });428+429+/** Names whose values the pane keeps from its own terminal, not the swarm's. */430+const PANE_OWNS = ["TERM", "COLORTERM"];431+432+/** herdr's names in a pane: its integrations report each agent's state with them. */433+const HERDR_NAMES = [434+ "HERDR_BIN_PATH",435+ "HERDR_ENV",436+ "HERDR_PANE_ID",437+ "HERDR_SOCKET_PATH",438+ "HERDR_TAB_ID",439+ "HERDR_WORKSPACE_ID",440+];441+442+/**443+ * The script a contributor's pane runs once: it clears the pane's env to444+ * its terminal and herdr's own names, reads the harness's env from the445+ * swarm through `fifo` (a pipe, so no token is ever in a file, an argv or446+ * on the screen), and leaves a shell without rc files (no user setup447+ * between the contributor and their env) in their clone, where herdr448+ * starts their harness. Pure.449+ */450+export const paneShell = (input: {451+ readonly fifo: string;452+ readonly clone: string;453+}) =>454+ [455+ "#!/bin/sh",456+ "# One swarm contributor's herdr pane (issue 717): their harness's env from the",457+ "# swarm through a pipe, then a shell in their clone for herdr to start it in.",458+ `exec env -i ${[...PANE_OWNS, ...HERDR_NAMES].map((name) => `${name}="\${${name}-}"`).join(" ")} /bin/sh -c '`,459+ "set -a",460+ '. "$1"',461+ "set +a",462+ 'cd "$2" || exit 1',463+ `case "\${SHELL##*/}" in`,464+ ' zsh) exec "$SHELL" -f ;;',465+ ' bash) exec "$SHELL" --noprofile --norc ;;',466+ ` *) exec "\${SHELL:-/bin/sh}" ;;`,467+ `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,468+ "",469+ ].join("\n");470+471+/** `env` as the lines a shell sources, less what the pane owns. Pure. */472+const envLines = (env: Readonly<Record<string, string>>) =>473+ Object.entries(env)474+ .filter(([name]) => !PANE_OWNS.includes(name))475+ .map(([name, value]) => `${name}=${shellQuoted(value)}\n`)476+ .join("");477+478+/** How long a pane gets to read its env from the pipe. */479+const ENV_READ_WAIT = Duration.seconds(30);480+481+/** How many times a pane whose shell is still starting is asked again, a second apart. */482+const BUSY_RETRIES = 10;483+484+/** A pane script runs only as its owner. */485+const SCRIPT_MODE = 0o700;486+487+/**488+ * Readies `pane` for `contributor` and starts their harness in it: the489+ * pane runs `paneShell`, reads `env` (with the launch's own) from a pipe,490+ * and herdr starts the harness with its interactive flags, getting past491+ * the startup questions it knows. herdr's answer goes to `log`.492+ */493+const startIn = (input: {494+ readonly contributor: Contributor;495+ readonly env: Readonly<Record<string, string>>;496+ readonly pane: string;497+ readonly workspace: AgentWorkspace;498+ readonly log: (text: string) => Effect.Effect<void, SwarmFailed>;499+}) =>500+ Effect.gen(function* () {501+ const fs = yield* FileSystem.FileSystem;502+ const { contributor, pane, workspace } = input;503+ const { handle, harness } = contributor;504+ const launch = interactiveLaunch({ contributor, dir: workspace.dir });505+ const fifo = `${workspace.dir}/pane-env`;506+ const script = `${workspace.dir}/pane-shell`;507+508+ const written = (what: string) =>509+ Effect.mapError(510+ ({ message }: { readonly message: string }) =>511+ new SwarmFailed({ reason: `${handle}'s ${what}: ${message}` })512+ );513+514+ yield* fs.remove(fifo, { force: true }).pipe(written("pipe"));515+516+ const made = yield* run({517+ args: ["-m", "600", fifo],518+ command: "mkfifo",519+ env: {},520+ });521+522+ if (made.code !== 0) {523+ return yield* new SwarmFailed({524+ reason: `${handle}'s pipe: mkfifo exited ${made.code}: ${made.stderr.trim()}`,525+ });526+ }527+528+ yield* fs529+ .writeFileString(script, paneShell({ clone: workspace.clone, fifo }), {530+ mode: SCRIPT_MODE,531+ })532+ .pipe(533+ Effect.andThen(fs.chmod(script, SCRIPT_MODE)),534+ written("pane script")535+ );536+537+ yield* orFailed(538+ herdr(["pane", "run", pane, `exec ${shellQuoted(script)}`])539+ );540+541+ // Opening the pipe waits for the pane's script to read it.542+ yield* fs543+ .writeFileString(fifo, envLines({ ...input.env, ...launch.env }))544+ .pipe(545+ written("env"),546+ Effect.timeoutOrElse({547+ duration: ENV_READ_WAIT,548+ orElse: () =>549+ Effect.fail(550+ new SwarmFailed({551+ reason: `${handle}'s herdr pane ${pane} didn't read its env: is it at a shell prompt?`,552+ })553+ ),554+ }),555+ Effect.ensuring(Effect.ignore(fs.remove(fifo, { force: true })))556+ );557+558+ const started = yield* herdr(559+ herdrStart({ argv: launch.argv, handle, kind: launch.kind, pane })560+ ).pipe(561+ // The pane's shell may still be starting.562+ Effect.retry({563+ schedule: Schedule.spaced(Duration.seconds(1)),564+ times: BUSY_RETRIES,565+ while: (error) => isRefused(error) && error.code === "agent_pane_busy",566+ }),567+ Effect.catchIf(568+ (error): error is HerdrRefused =>569+ isRefused(error) && error.code === "agent_not_ready",570+ (error) =>571+ Effect.as(572+ pastStartup({ handle, harness, pane }),573+ JSON.stringify({ startup: error.said })574+ )575+ ),576+ orFailed577+ );578+579+ return yield* input.log(started);580+ });581+582+/** What an attempt heard from herdr's answer to its prompt (or its refusal of it). */583+const promptHeard = (input: {584+ readonly name: string;585+ readonly pane: string;586+ readonly harness: Harness;587+ readonly answer: Result.Result<string, HerdrRefused>;588+}): Effect.Effect<Attempted, SwarmFailed> =>589+ Result.match(input.answer, {590+ onFailure: (refused) =>591+ Effect.succeed({592+ code: Option.some(1),593+ heard: {594+ ...nothingHeard,595+ failure: Option.some(refused.message),596+ session: Option.some(input.name),597+ },598+ stderr: refused.message,599+ }),600+ onSuccess: (printed) =>601+ Effect.map(602+ answerOf(AgentSeen, "agent prompt")(printed),603+ ({ result: { agent } }): Attempted => {604+ const blocked = agent.agent_status === "blocked";605+606+ return {607+ code: Option.some(0),608+ heard: {609+ ...nothingHeard,610+ failure: blocked611+ ? Option.some(612+ `${input.harness} is blocked on a question in herdr pane ${input.pane}`613+ )614+ : Option.none(),615+ session: Option.some(input.name),616+ settled: !blocked,617+ stopReason: Option.some(agent.agent_status),618+ },619+ stderr: "",620+ };621+ }622+ ),623+ });624+625+/**626+ * The herdr view over `panes` (each contributor's pane, by handle): an627+ * attempt starts the harness in its pane on the brief, or types the628+ * continuation's prompt into the same session, and waits until herdr sees629+ * it settle. The session a resume names is the agent's herdr name.630+ */631+export const herdrView = (panes: ReadonlyMap<string, string>): SwarmView => ({632+ attempt: ({ contributor, env, file, onSession, turn, workspace }) =>633+ Effect.gen(function* () {634+ const fs = yield* FileSystem.FileSystem;635+ const { handle, harness } = contributor;636+637+ const pane = yield* Effect.fromNullishOr(panes.get(handle)).pipe(638+ Effect.mapError(639+ () => new SwarmFailed({ reason: `${handle} has no herdr pane` })640+ )641+ );642+643+ const logged = Effect.mapError(644+ ({ message }: { readonly message: string }) =>645+ new SwarmFailed({ reason: `${handle}'s attempt log: ${message}` })646+ );647+648+ const log = (text: string) =>649+ fs650+ .writeFileString(file, `${scrubbed(text, workspace).trim()}\n`, {651+ flag: "a",652+ })653+ .pipe(logged);654+655+ yield* fs.writeFileString(file, "").pipe(logged);656+657+ const name = yield* Turn.$match(turn, {658+ Resume: ({ session }) => Effect.succeed(session),659+ Start: () =>660+ Effect.as(661+ startIn({ contributor, env, log, pane, workspace }),662+ handle663+ ),664+ });665+666+ yield* onSession;667+668+ const text = Turn.$match(turn, {669+ Resume: ({ prompt }) => prompt,670+ Start: ({ brief }) => brief,671+ });672+673+ const answer = yield* herdr(herdrPrompt({ handle: name, text })).pipe(674+ Effect.map(Result.succeed),675+ Effect.catchIf(isRefused, (refused) =>676+ Effect.succeed(Result.fail(refused))677+ )678+ );679+680+ yield* log(681+ Result.match(answer, {682+ onFailure: ({ message }) => message,683+ onSuccess: (printed) => printed,684+ })685+ );686+687+ return yield* promptHeard({ answer, harness, name, pane });688+ }),689+});690+691+/** A pane's title: who works in it, and on which harness. */692+const titleOf = ({693+ handle,694+ harness,695+}: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;696+697+/**698+ * Opens the herdr view for `contributors`, in the herdr session the swarm699+ * runs in: a workspace of its own (focused, for the person recording), one700+ * pane per contributor laid out by `herdrLayout`, and a counter pane that701+ * shows `counterFile`, which a fiber in the run's scope keeps writing from702+ * the project's `watch`. Outside a herdr pane it refuses: herdr's skill703+ * says not to drive a session from outside it.704+ */705+export const openHerdrView = (input: {706+ readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];707+ readonly project: ProjectName;708+ readonly origin: string;709+ readonly runDir: string;710+}): Effect.Effect<711+ { readonly view: SwarmView; readonly workspace: string },712+ SwarmFailed,713+ | ChildProcessSpawner.ChildProcessSpawner714+ | FileSystem.FileSystem715+ | Path.Path716+ | Scope.Scope717+> =>718+ Effect.gen(function* () {719+ const fs = yield* FileSystem.FileSystem;720+721+ const inHerdr = yield* Config.all({722+ env: Config.option(Config.String("HERDR_ENV")),723+ socket: Config.option(Config.String("HERDR_SOCKET_PATH")),724+ }).pipe(725+ Effect.map(726+ ({ env, socket }) => Option.contains(env, "1") || Option.isSome(socket)727+ ),728+ Effect.orElseSucceed(() => false)729+ );730+731+ if (!inHerdr) {732+ return yield* new SwarmFailed({733+ reason:734+ "--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",735+ });736+ }737+738+ const root = (yield* repoRoot).replace(/\/$/u, "");739+ const counterFile = `${input.runDir}/counter.log`;740+ const handles = input.contributors.map(({ handle }) => handle);741+742+ yield* fs743+ .makeDirectory(input.runDir, { recursive: true })744+ .pipe(745+ Effect.mapError(746+ ({ message }) =>747+ new SwarmFailed({ reason: `the run's folder: ${message}` })748+ )749+ );750+751+ const made = yield* herdr([752+ "workspace",753+ "create",754+ "--cwd",755+ root,756+ "--label",757+ `swarm ${input.project}`,758+ "--focus",759+ ]).pipe(760+ orFailed,761+ Effect.flatMap(answerOf(WorkspaceMade, "workspace create"))762+ );763+764+ const first = handles[0] ?? COUNTER;765+766+ const panes = yield* Effect.reduce(767+ herdrLayout(handles),768+ () => new Map([[first, made.result.root_pane.pane_id]]),769+ (known, split) =>770+ herdr([771+ "pane",772+ "split",773+ known.get(split.from) ?? made.result.root_pane.pane_id,774+ "--direction",775+ split.direction,776+ "--ratio",777+ String(split.ratio),778+ "--cwd",779+ root,780+ "--no-focus",781+ ]).pipe(782+ orFailed,783+ Effect.flatMap(answerOf(PaneMade, "pane split")),784+ Effect.map(({ result }) =>785+ new Map(known).set(split.slot, result.pane.pane_id)786+ )787+ )788+ );789+790+ const titles = [791+ ...input.contributors.map((one) => [one.handle, titleOf(one)] as const),792+ [COUNTER, `counter · ${input.project}`] as const,793+ ];794+795+ yield* Effect.forEach(796+ titles.flatMap(([slot, title]) =>797+ Option.toArray(798+ Option.map(Option.fromUndefinedOr(panes.get(slot)), (pane) => ({799+ pane,800+ title,801+ }))802+ )803+ ),804+ ({ pane, title }) => orFailed(herdr(["pane", "rename", pane, title])),805+ { discard: true }806+ );807+808+ const from = yield* lastHeld(input.origin, input.project);809+810+ yield* Effect.forkScoped(811+ followCounter({812+ file: counterFile,813+ from,814+ origin: input.origin,815+ project: input.project,816+ }).pipe(Effect.ignore)817+ );818+819+ yield* Effect.forEach(820+ Option.toArray(Option.fromUndefinedOr(panes.get(COUNTER))),821+ (pane) =>822+ orFailed(823+ herdr([824+ "pane",825+ "run",826+ pane,827+ `clear; tail -n +1 -F ${shellQuoted(counterFile)}`,828+ ])829+ ),830+ { discard: true }831+ );832+833+ return {834+ view: herdrView(panes),835+ workspace: made.result.workspace.workspace_id,836+ };837+ });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