Stop the herdr view's counter from counting a project's history as the run's, and say why it can't follow
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Review of 717 (code-review, Spec and Standards against the issue and AGENTS.md). - `lastHeld` fails the run, before any pane or claim, when it can't read where the project stands (curl's failure, an HTTP error, a body that isn't watch's replay). It used to fall back to 0, so a counter started from a failed read would follow from event 0 and show the project's whole history (a rehearsal's claims and landings) as the take's. `openHerdrView` now reads it first, before the workspace is made. - `followCounter` reads curl's exit and stderr: a call that fails (connection refused, or an HTTP error now that every call passes `--fail`) is said once in the counter pane, as its comment promised; before, curl's stderr was ignored and its exit never read, so a counter that couldn't follow sat at 0 without a word. - The Claude Code imports-question fixture had the cursor on "Yes" while the view presses Enter to keep "No"; it now shows "No" under the cursor, as live (the wren clone's `hasClaudeMdExternalIncludesApproved` is false). - herdr.ts says that an agent in a pane outlives a run that times out, until the workspace is closed (the loop's "the harness's process group is killed" holds for the headless view only). - Tests (red by assertion first): a herdr run stops before any herdr call or claim when the read fails; `lastHeld` refuses a curl failure and a non-replay body; `followCounter` says curl's failure once and keeps trying. The two curl argv expectations gain `--fail`.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+261 added−97 removed
- tests:+191 added−69 removed
- other:+70 added−28 removed
Provenance
- Commit
cdfa9e6- Tree
8ad40cf- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
a2ef0f8
3 files changed+261 added−97 removed
modified:packages/config/test/swarm-herdr.test.ts+191 added-69 removed
470 unmodified lines471 * 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.475+ * counter's `watch` hears nothing new. `replay` is how the counter's read476+ * of where the project stands ends: an empty replay unless a test says.477 */478+const herdrWorld = (replay: Ending) =>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");479+ Effect.gen(function* () {480+ const panes = yield* Ref.make(1);481+ const reads = yield* Ref.make(new Map<string, number>());482+ const listed = yield* fixture("list-asks.json");483 482- const shown = (yield* fixture("show-ask.json")).replaceAll(483- "{configDir}",484- Brand.configDir485- );484+ const shown = (yield* fixture("show-ask.json")).replaceAll(485+ "{configDir}",486+ Brand.configDir487+ );488 487- const answer = (call: Spawned) =>488- Effect.gen(function* () {489- const { args, command, env } = call;490- const [first = "", second = "", third = ""] = args;489+ const answer = (call: Spawned) =>490+ Effect.gen(function* () {491+ const { args, command, env } = call;492+ const [first = "", second = "", third = ""] = args;493 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- }494+ if (command === "herdr") {495+ if (first === "workspace") {496+ return JSON.stringify({497+ id: "cli:workspace:create",498+ result: {499+ root_pane: { pane_id: "w9:p1", workspace_id: "w9" },500+ type: "workspace_created",501+ workspace: { workspace_id: "w9" },502+ },503+ });504+ }505 504- if (second === "split") {505- return paneJson(506- `w9:p${yield* Ref.updateAndGet(panes, (n) => n + 1)}`507- );506+ if (second === "split") {507+ return paneJson(508+ `w9:p${yield* Ref.updateAndGet(panes, (n) => n + 1)}`509+ );510+ }511+512+ if (first === "agent") {513+ return agentJson(514+ third,515+ second === "start" ? "agent_started" : "agent_prompted"516+ );517+ }518+519+ return JSON.stringify({ id: "cli:pane", result: { type: "ok" } });520 }521 510- if (first === "agent") {511- return agentJson(512- third,513- second === "start" ? "agent_started" : "agent_prompted"514- );522+ if (command === "git") {523+ return "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n";524 }525 517- return JSON.stringify({ id: "cli:pane", result: { type: "ok" } });518- }526+ if (first === "status") {527+ const handle = holderOf(env) ?? "nobody";528 520- if (command === "git") {521- return "d7064cb4f9f0f0e0d0c0b0a090807060504030201\n";522- }529+ const count =530+ (yield* Ref.updateAndGet(reads, (seen) =>531+ new Map(seen).set(handle, (seen.get(handle) ?? 0) + 1)532+ )).get(handle) ?? 1;533 524- if (command === "curl") {525- return args.includes("content-type: application/json")526- ? '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]'527- : "";528- }534+ return statusOf(handle, count);535+ }536 530- if (first === "status") {531- const handle = holderOf(env) ?? "nobody";537+ return (538+ {539+ ask: shown,540+ asks: listed,541+ claim: claimOf(third, holderOf(env) ?? "nobody"),542+ }[second] ?? ""543+ );544+ });545 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);546+ return yield* fakeSpawner((call) => {547+ if (call.command !== "curl") {548+ return Effect.map(answer(call), (stdout) => ({ stdout }));549 }550 541- return (542- {543- ask: shown,544- asks: listed,545- claim: claimOf(third, holderOf(env) ?? "nobody"),546- }[second] ?? ""551+ // The read of where the project stands is plain JSON; the follow hears nothing.552+ return Effect.succeed(553+ call.args.includes("content-type: application/json") ? replay : {}554 );555 });556+ });557 550- return yield* fakeSpawner((call) =>551- Effect.map(answer(call), (stdout) => ({ stdout }))552- );553-});558+/** `watch`'s plain JSON replay of a project that holds no event yet. */559+const emptyReplay: Ending = {560+ stdout:561+ '[{"_tag":"Exit","requestId":"1","exit":{"_tag":"Success","value":null}}]',562+};563 564 /** What herdr puts in the env of a process in one of its panes. */565 const inAPane = { HERDR_ENV: "1" };566 567 /**568 * `main --view herdr` for every contributor over `herdrWorld`, from a herdr560- * pane unless `herdrEnv` says otherwise, with `.swarm/` and the ledger in a561- * temp dir.569+ * pane unless `herdrEnv` says otherwise, the counter's read of the project570+ * ending as `replay`, with `.swarm/` and the ledger in a temp dir.571 */563-const herdrRunWith = (herdrEnv: Readonly<Record<string, string>>) =>572+const herdrRunWith = (573+ herdrEnv: Readonly<Record<string, string>>,574+ replay: Ending = emptyReplay575+) =>576 Effect.gen(function* () {577 const fs = yield* FileSystem.FileSystem;578 const swarm = yield* fs.makeTempDirectoryScoped();567- const world = yield* herdrWorld;579+ const world = yield* herdrWorld(replay);580 const printed: string[] = [];581 582 const captured: Console.Console = {583 ...console,268 unmodified lines852 })853 );854 855 it.effect(856+ "stops before it opens a pane or claims anything when the counter can't read where the project stands",857+ () =>858+ Effect.gen(function* () {859+ const { result, spawned } = yield* herdrRunWith(inAPane, {860+ code: 7,861+ stderr:862+ "curl: (7) Failed to connect to platform-dev-oscabriel.example.workers.dev port 443\n",863+ });864+865+ expect(866+ Result.match(result, {867+ onFailure: ({ reason }) => reason,868+ onSuccess: () => "",869+ })870+ ).toBe(871+ "the counter couldn't read burrow's events: curl exited 7: curl: (7) Failed to connect to platform-dev-oscabriel.example.workers.dev port 443"872+ );873+ expect(874+ spawned.flatMap(({ args, command }) =>875+ command === "herdr" || args[1] === "claim" ? [args] : []876+ )877+ ).toStrictEqual([]);878+ })879+ );880+881+ it.effect(882 "hands each pane its contributor's env through a pipe, so no token is in any argv, script or line",883 () =>884 Effect.gen(function* () {885 const { printed, run, spawned, wrensScript } = yield* herdrRun;32 unmodified lines918 " ❯ No, exit",919 " Yes, I trust this folder",920 ].join("\n");921 884-/** …and then whether to import the CLAUDE.md files above the clone. */922+/**923+ * …and then whether to import the CLAUDE.md files above the clone, "No"924+ * under the cursor (live, Enter left the clone's925+ * `hasClaudeMdExternalIncludesApproved` false).926+ */927 const importsQuestion = [928 " Allow external CLAUDE.md file imports?",929 "",888- " No, disable external imports",889- " ❯ Yes, allow external imports",930+ " ❯ No, disable external imports",931+ " Yes, allow external imports",932 ].join("\n");933 934 const [wren] = roster;935 204 unmodified lines1140 expect((yield* world.spawned).map(({ args }) => args)).toStrictEqual([1141 [1142 "--silent",1143 "--show-error",1144+ "--fail",1145 "--no-buffer",1146 "--request",1147 "POST",1148 "--header",6 unmodified lines1155 })1156 );1157 1158 it.effect(1159+ "refuses to guess where to start when the project's events can't be read, rather than count its whole history",1160+ () =>1161+ Effect.gen(function* () {1162+ const reasons = yield* Effect.forEach(1163+ [1164+ {1165+ code: 22,1166+ stderr: "curl: (22) The requested URL returned error: 502\n",1167+ },1168+ { stdout: "<html>502 Bad Gateway</html>" },1169+ ],1170+ (ending) =>1171+ Effect.gen(function* () {1172+ const world = yield* fakeSpawner(() => Effect.succeed(ending));1173+1174+ const read = yield* lastHeld(1175+ platformUrl,1176+ ProjectName.make("burrow")1177+ ).pipe(Effect.provide(world.layer), Effect.result);1178+1179+ return Result.match(read, {1180+ onFailure: ({ reason }) => reason,1181+ onSuccess: (from) => `counts from event ${from}`,1182+ });1183+ })1184+ );1185+1186+ expect(reasons).toStrictEqual([1187+ "the counter couldn't read burrow's events: curl exited 22: curl: (22) The requested URL returned error: 502",1188+ "the counter couldn't read burrow's events: <html>502 Bad Gateway</html>",1189+ ]);1190+ })1191+ );1192+1193+ it.effect("says once why it can't follow watch, and keeps trying", () =>1194+ Effect.gen(function* () {1195+ const world = yield* fakeSpawner(() =>1196+ Effect.succeed({1197+ code: 22,1198+ stderr: "curl: (22) The requested URL returned error: 503\n",1199+ })1200+ );1201+1202+ const files = new Map<string, string>();1203+1204+ const memoryFs = FileSystem.makeNoop({1205+ writeFileString: (path, data, options) =>1206+ Effect.sync(() => {1207+ files.set(1208+ path,1209+ options?.flag === "a" ? `${files.get(path) ?? ""}${data}` : data1210+ );1211+ }),1212+ });1213+1214+ const fiber = yield* followCounter({1215+ file: "/work/counter.log",1216+ from: 8,1217+ origin: platformUrl,1218+ project: ProjectName.make("burrow"),1219+ }).pipe(1220+ Effect.provide(world.layer),1221+ Effect.provideService(FileSystem.FileSystem, memoryFs),1222+ Effect.forkChild1223+ );1224+1225+ yield* TestClock.adjust("5 seconds");1226+ yield* Fiber.interrupt(fiber);1227+1228+ expect(files.get("/work/counter.log")?.split("\n")).toStrictEqual([1229+ "claims 0 · pushes 0 · landed 0 (burrow, after event 8)",1230+ "counter: watch didn't run: curl exited 22: curl: (22) The requested URL returned error: 503",1231+ "",1232+ ]);1233+ expect((yield* world.spawned).length).toBeGreaterThan(1);1234+ })1235+ );1236+1237+ it.effect(1238 "follows the framed stream after that event and writes a line per claim, push and landing",1239 () =>1240 Effect.gen(function* () {1241 const world = yield* fakeSpawner(() =>32 unmodified lines1274 "12:06:00 claims 1 · pushes 1 · landed 0 drop-legacy-fetch-burrow-auth pushed 1111111",1275 "",1276 ]);1277 expect(1156- (yield* world.spawned).map(({ args }) => args.slice(6, 9))1278+ (yield* world.spawned).map(({ args }) => args.slice(7, 10))1279 ).toStrictEqual([1280 [1281 "content-type: application/ndjson",1282 "--data-binary",6 unmodified linesmodified:scripts/lib/swarm/views/counter.ts+60 added-25 removed
27 unmodified lines28 Stream,29 } from "effect";30 import { ChildProcess, ChildProcessSpawner } from "effect/process";31 32-import { run } from "../workspace.ts";32+import { run, SwarmFailed } from "../workspace.ts";33 34 /** The events the counter counts. */35 const counted = (event: ProjectEvent) =>36 ProjectEvent.guards.Claimed(event) ||100 unmodified lines137 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`. */141+/**142+ * `curl`'s flags for one POST to the platform's `/rpc` with `contentType`:143+ * an HTTP error fails it (`--fail`), and only its errors reach stderr.144+ */145 const curlArgs = (input: {146 readonly origin: string;147 readonly contentType: string;148 readonly body: string;149 }) => [150 "--silent",151 "--show-error",152+ "--fail",153 "--no-buffer",154 "--request",155 "POST",156 "--header",2 unmodified lines159 input.body,160 `${input.origin}/rpc`,161 ];162 163+/** Why the counter can't say where `project` stands: what curl or the platform said. */164+const unread = (project: ProjectName, said: string) =>165+ new SwarmFailed({166+ reason: `the counter couldn't read ${project}'s events: ${said.trim().slice(0, 300)}`,167+ });168+169 /**170 * The last event `project` already holds, where a run's counter starts:161- * `watch` over plain JSON replays what the project keeps and ends. 0 when162- * it holds none, or the read fails.171+ * `watch` over plain JSON replays what the project keeps and ends; 0 when172+ * it holds none. A read that fails is the run's failure, not 0: a counter173+ * that started from 0 would count the project's whole history as the run's.174 */175 export const lastHeld = (origin: string, project: ProjectName) =>176+ Effect.gen(function* () {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) =>177+ const ran = yield* run({178+ args: curlArgs({179+ body: `[${watchRequest(project, Option.none())}]`,180+ contentType: "application/json",181+ origin,182+ }),183+ command: "curl",184+ env: {},185+ }).pipe(Effect.mapError(({ reason }) => unread(project, reason)));186+187+ if (ran.code !== 0) {188+ return yield* unread(project, `curl exited ${ran.code}: ${ran.stderr}`);189+ }190+191+ const frames = yield* Effect.fromOption(decodeReplay(ran.stdout)).pipe(192+ Effect.mapError(() => unread(project, ran.stdout))193+ );194+195+ return Math.max(196+ 0,197+ ...frames.flatMap((frame) =>198 isHeld(frame) ? frame.values.map(({ seq }) => seq) : []199 )178- ),179- Effect.map((seqs) => Math.max(0, ...seqs)),180- Effect.orElseSucceed(() => 0)181- );200+ );201+ });202 203 /** Where the counter stands: the last event heard, and every counted one since the run began. */204 interface Tally {205 readonly last: number;54 unmodified lines260 body: `${watchRequest(input.project, Option.some(last))}\n`,261 contentType: "application/ndjson",262 origin: input.origin,263 }),244- { stderr: "ignore", stdin: "ignore" }264+ { stdin: "ignore" }265 )266 );267 268+ // curl's exit says whether the stream ended or the call failed.269+ const [stderr, code] = yield* Effect.all(270+ [271+ child.stderr.pipe(Stream.decodeText(), Stream.mkString),272+ child.exitCode,248- yield* child.stdout.pipe(249- Stream.decodeText(),250- Stream.splitLines,251- Stream.flatMap((line) => Stream.fromIterable(eventsIn(line))),252- Stream.runForEach(hear)273+ child.stdout.pipe(274+ Stream.decodeText(),275+ Stream.splitLines,276+ Stream.flatMap((line) => Stream.fromIterable(eventsIn(line))),277+ Stream.runForEach(hear)278+ ),279+ ],280+ { concurrency: "unbounded" }281 );282+283+ yield* Effect.when(284+ Effect.fail(285+ new SwarmFailed({ reason: `curl exited ${code}: ${stderr.trim()}` })286+ ),287+ Effect.succeed(code !== 0)288+ );289 })290 ).pipe(291 // Said once, so a counter that cannot follow says why; it keeps trying.292 Effect.tapError(({ message }) =>18 unmodified linesmodified:scripts/lib/swarm/views/herdr.ts+10 added-3 removed
11 unmodified lines12 * panes open where the person recording is looking. Pane text is read for13 * one thing only: to recognise a question a harness asks at startup, before14 * it takes its brief (`STARTUP_QUESTIONS`). Where an answer stands comes15 * from status alone.16+ *17+ * Unlike a headless harness, an agent in a pane outlives its run: a run that18+ * times out (or a swarm that is stopped) leaves it working in its pane,19+ * claim and all, until the person closes the workspace the swarm names20+ * (`herdr workspace close <id>`).21 */22 import type { ProjectName } from "@repo/protocol/ids";23 import {24 Config,679 unmodified lines704 * runs in: a workspace of its own (focused, for the person recording), one705 * pane per contributor laid out by `herdrLayout`, and a counter pane that706 * shows `counterFile`, which a fiber in the run's scope keeps writing from707 * the project's `watch`. Outside a herdr pane it refuses: herdr's skill703- * says not to drive a session from outside it.708+ * says not to drive a session from outside it. It refuses too when it can't709+ * read where the project stands (`lastHeld`), before any pane is made.710 */711 export const openHerdrView = (input: {712 readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];713 readonly project: ProjectName;26 unmodified lines740 "--view herdr opens its panes in the herdr session it runs in: start the swarm from a herdr pane (herdr --session demo), or name the session's socket in HERDR_SOCKET_PATH",741 });742 }743 744+ // Where the counter starts, read before any pane or claim: a run that745+ // can't say where the project stands stops here.746+ const from = yield* lastHeld(input.origin, input.project);747 const root = (yield* repoRoot).replace(/\/$/u, "");748 const counterFile = `${input.runDir}/counter.log`;749 const handles = input.contributors.map(({ handle }) => handle);750 62 unmodified lines813 ({ pane, title }) => orFailed(herdr(["pane", "rename", pane, title])),814 { discard: true }815 );816 808- const from = yield* lastHeld(input.origin, input.project);809-817 yield* Effect.forkScoped(818 followCounter({819 file: counterFile,820 from,24 unmodified lines