fanout-cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../daemon/src/workspace/git.ts", "../src/main.ts", "../../adapters/claude/src/index.ts", "../../core/src/schema/common.ts", "../../core/src/schema/scope.ts", "../../core/src/schema/plan.ts", "../../core/src/schema/events.ts", "../../core/src/schema/manifest.ts", "../../core/src/schema/policy.ts", "../../core/src/ledger/ledger.ts", "../../core/src/projections/state.ts", "../../core/src/format/run.ts", "../../core/src/gate/readiness.ts", "../../core/src/gate/routing.ts", "../../core/src/version.ts", "../../adapters/claude/manifest.json", "../../adapters/claude/src/protocol.ts", "../../adapters/codex/src/index.ts", "../../adapters/codex/manifest.json", "../../adapters/codex/src/protocol.ts", "../../adapters/grok/src/index.ts", "../../adapters/grok/manifest.json", "../../adapters/grok/src/protocol.ts", "../../daemon/src/supervisor/supervise.ts", "../../daemon/src/env.ts", "../../daemon/src/run.ts", "../../daemon/src/workspace/manager.ts", "../../daemon/src/workspace/deny.ts", "../../daemon/src/index.ts", "../../daemon/src/safety/report.ts", "../../daemon/src/safety/dependencies.ts", "../../daemon/src/detector/detect.ts", "../../daemon/src/detector/version.ts", "../../daemon/src/mission/runner.ts", "../../daemon/src/api/server.ts", "../../daemon/src/api/token.ts", "../../daemon/src/policy/seats.ts", "../../daemon/src/policy/route.ts", "../../daemon/src/gate/revision.ts", "../../daemon/src/gate/isolate.ts", "../../daemon/src/gate/run-seat.ts", "../../daemon/src/gate/buddy.ts", "../../daemon/src/gate/claims.ts", "../../daemon/src/api/view.ts", "../../daemon/src/gate/checks.ts", "../../daemon/src/gate/proof.ts", "../../daemon/src/gate/merge.ts", "../../daemon/src/gate/rework.ts", "../../mcp/src/server.ts", "../../adapters/fake/src/index.ts", "../../adapters/fake/src/protocol.ts", "../../adapters/fake/src/scenario.ts", "../src/home.ts", "../src/live.ts", "../src/demo.ts", "../src/format.ts", "../src/unfinished.ts", "../src/cli.ts"],
4
- "sourcesContent": ["import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\n/*\n * Every git call the daemon makes. No shell, so a path can never become an argument list; a closed environment, so\n * git cannot prompt for credentials or pick up a helper we did not choose; and a timeout, so a hung git cannot hang\n * a mission.\n */\n\nconst run = promisify(execFile);\n\nexport class GitError extends Error {\n override name = \"GitError\";\n readonly args: readonly string[];\n readonly stderr: string;\n readonly exitCode: number | null;\n\n constructor(args: readonly string[], stderr: string, exitCode: number | null) {\n super(`git ${args.join(\" \")} failed${exitCode === null ? \"\" : ` (exit ${exitCode})`}: ${stderr.trim()}`);\n this.args = args;\n this.stderr = stderr;\n this.exitCode = exitCode;\n }\n}\n\nexport interface GitOptions {\n cwd: string;\n timeoutMs?: number;\n /** Diffs and file lists can be large; the default holds a very big patch. */\n maxBuffer?: number;\n}\n\nexport function gitEnv(): Record<string, string> {\n const path = process.env[\"PATH\"];\n const home = process.env[\"HOME\"];\n return {\n ...(path === undefined ? {} : { PATH: path }),\n ...(home === undefined ? {} : { HOME: home }),\n // Never ask a human, never touch a credential helper, never take a lock we don't need, and speak English so\n // that parsing never depends on the user's locale.\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_ASKPASS: \"\",\n GIT_OPTIONAL_LOCKS: \"0\",\n GIT_CONFIG_NOSYSTEM: \"1\",\n LC_ALL: \"C\",\n };\n}\n\nexport async function git(args: readonly string[], options: GitOptions): Promise<string> {\n try {\n const { stdout } = await run(\"git\", [...args], {\n cwd: options.cwd,\n timeout: options.timeoutMs ?? 60_000,\n maxBuffer: options.maxBuffer ?? 256 * 1024 * 1024,\n env: gitEnv(),\n windowsHide: true,\n });\n return stdout;\n } catch (cause) {\n const detail = cause as { stderr?: string; code?: number | null; message?: string };\n throw new GitError(args, detail.stderr ?? detail.message ?? \"\", detail.code ?? null);\n }\n}\n\n/** Lines of output, without the trailing empty one. */\nexport function lines(output: string): string[] {\n return output.split(\"\\n\").filter((line) => line !== \"\");\n}\n\n/** Entries of a `-z` listing, which is the only safe way to read paths that contain spaces or newlines. */\nexport function zeroSeparated(output: string): string[] {\n return output.split(\"\\0\").filter((entry) => entry !== \"\");\n}\n", "import { existsSync, realpathSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createClaudeAdapter, manifest as claude } from \"fanout-adapter-claude\";\nimport { createCodexAdapter, manifest as codex } from \"fanout-adapter-codex\";\nimport { createGrokAdapter, manifest as grok } from \"fanout-adapter-grok\";\nimport {\n Ledger,\n elapsedMs,\n PlanGraph,\n project,\n SeatPosture,\n stanceFor,\n type AdapterManifest,\n type EventOf,\n type SeatAdapter,\n routeLine,\n versionOf,\n EMPTY_POLICY,\n type PlanLine,\n type RunView,\n type SeatInfo,\n type StoredEvent,\n} from \"fanout-core\";\nimport {\n detectSeats,\n git,\n lines,\n buddyReview,\n checkClaims,\n createMissionRunner,\n createWorkspaceManager,\n missionViewHtml,\n readOrCreateToken,\n readSeatPolicy,\n setPosture,\n startApi,\n workSnapshot,\n writeSeatPolicy,\n type CommandResult,\n type RunLimits,\n} from \"fanout-daemon\";\nimport { createFanoutServer } from \"fanout-mcp\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createFakeAdapter } from \"fanout-adapter-fake\";\nimport { fanoutHome, type FanoutHome } from \"./home.ts\";\nimport { createLive, type LiveRow } from \"./live.ts\";\nimport { buildDemoRepo, demoClaims, demoLines, demoScenario, DEMO_GOAL } from \"./demo.ts\";\nimport { crewTable, missionLines } from \"./format.ts\";\nimport { ownWorkOwed, unfinishedReport, whatIsOwed } from \"./unfinished.ts\";\n\n/*\n * `fanout` is the terminal half of the product: the daemon the lead talks to, and a straight answer about the crew\n * and the missions. It prints what it knows and says plainly what it doesn't \u2014 a CLI that guesses is worse than one\n * that shrugs.\n */\n\nexport const SEATS: readonly AdapterManifest[] = [codex, claude, grok];\n\n/** Every seat we can drive today. A plan naming anything else is dropped with the reason, never guessed at. */\nexport function adapters(): ReadonlyMap<string, SeatAdapter> {\n return new Map([\n [\"codex\", createCodexAdapter()],\n [\"claude\", createClaudeAdapter()],\n [\"grok\", createGrokAdapter()],\n ]);\n}\n\n/** What a run is allowed before the supervisor stops it. Generous: a real agent thinks for minutes. */\nexport const DEFAULT_LIMITS: RunLimits = {\n startTimeoutMs: 90_000,\n timeoutMs: 30 * 60_000,\n killGraceMs: 5_000,\n maxLogBytes: 16 * 1024 * 1024,\n maxLineBytes: 200_000,\n};\n\nconst HELP = `fanout \u2014 Claude Code leads, your other agents build\n\n fanout demo watch a whole mission run, offline, with no accounts at all (--once to exit at the end)\n fanout status the crew on this machine, and any missions on the go\n fanout seat how freely to spend a seat: preferred | normal | sparing | off\n fanout owed what is waiting on you before anything can merge (the Stop hook runs this)\n fanout review ask a second vendor to read your own uncommitted changes\n fanout check state what you believe; a cold reader tries to disprove each claim\n fanout daemon run the daemon the lead and the mission view talk to\n fanout clean remove the worktrees and branches finished missions left behind\n fanout mcp speak MCP on stdin/stdout, for Claude Code to drive (the plugin runs this)\n fanout version what you are running\n fanout help this\n\nEverything lives in ~/.fanout (move it with FANOUT_HOME). Nothing leaves your machine.\n`;\n\nexport interface Io {\n out: (text: string) => void;\n err: (text: string) => void;\n /** Injected so tests never need the real CLIs installed. */\n execute?: (binary: string, args: readonly string[]) => Promise<CommandResult>;\n env?: Readonly<Record<string, string | undefined>>;\n /** Resolves when the daemon should stop; without it, `daemon` runs until interrupted. */\n until?: Promise<void>;\n /** Where the command was run; tests point it at a temporary repository. */\n cwd?: string;\n /**\n * Whether `out` is going to a terminal a person is watching.\n *\n * Injected rather than read from `process.stdout` here so a test can render both ways, and so a pipe never\n * gets cursor-movement codes it would print as garbage.\n */\n tty?: boolean;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const [command = \"help\"] = argv;\n const home = fanoutHome(io.env ?? process.env);\n\n switch (command) {\n case \"demo\":\n return demo(home, io, argv.slice(1));\n case \"status\":\n return status(home, io);\n case \"seat\":\n return seat(home, argv.slice(1), io);\n case \"owed\":\n return owed(home, io);\n case \"review\":\n return buddy(home, io);\n case \"check\":\n return check(home, argv.slice(1), io);\n case \"daemon\":\n return daemon(home, io);\n case \"clean\":\n return clean(home, io);\n case \"mcp\":\n return mcp(home, io);\n case \"version\":\n io.out(`fanout ${versionOf(import.meta.url)}\\n`);\n return 0;\n case \"help\":\n case \"--help\":\n case \"-h\":\n io.out(HELP);\n return 0;\n default:\n io.err(`fanout: there is no \"${command}\" command.\\n\\n${HELP}`);\n return 64;\n }\n}\n\n/**\n * One agent, described the way someone watching would describe it.\n *\n * `doing` is the agent's own last words \u2014 the file it opened, the edit it made, the command it ran \u2014 because a\n * phase name (\"coding\") says less than the thing being coded. When it has nothing to say yet, the phase is the\n * honest fallback rather than an invented action.\n */\nfunction demoRow(run: RunView, line: PlanLine, who: string, now: Date): LiveRow {\n const elapsed = elapsedMs(run, now);\n const finished = run.status === \"done\";\n const failed = run.status === \"failed\" || run.status === \"killed\" || run.status === \"timeout\";\n\n const doing =\n run.lastTool === null\n ? (run.phase ?? \"starting up\")\n : run.lastTool.summary === null\n ? run.lastTool.tool\n : `${run.lastTool.tool} ${run.lastTool.summary}`;\n\n const stat = run.diffStat;\n const result =\n stat === null\n ? run.files.length === 0\n ? \"no changes\"\n : `${String(run.files.length)} file${run.files.length === 1 ? \"\" : \"s\"}`\n : `+${String(stat.insertions)} \u2212${String(stat.deletions)}`;\n\n return {\n who,\n task: line.title,\n doing,\n ...(finished || failed ? { result } : {}),\n state: failed ? \"failed\" : finished ? \"done\" : run.status === \"queued\" ? \"waiting\" : \"working\",\n elapsedMs: elapsed,\n };\n}\n\n/**\n * The demo's crew: the simulated seat, said plainly, and nothing else.\n *\n * One list, used both by the page that shows the crew and by the router that decides on it. Two copies would let\n * the screen say one thing while the routing did another, which on this particular screen is the whole product.\n *\n * Reporting the machine's real CLIs here would make the demo look like it was using them, and reporting nothing\n * makes a working demo look broken.\n */\nconst DEMO_CREW: readonly SeatInfo[] = [\n {\n id: \"fake\",\n displayName: \"Simulated agent\",\n binary: \"fake\",\n version: \"demo\",\n supported: true,\n signedIn: \"yes\",\n models: [\"demo\"],\n efforts: [],\n billing: \"unknown\",\n plan: { name: \"no account needed\", source: \"detected\" },\n },\n];\n\n/**\n * `fanout demo` \u2014 the whole thing, on a machine with nothing signed in.\n *\n * Real worktrees, the real safety gate, the real ledger, real diffs from real files. Only the agents are\n * simulated, by the `fake` seat: a genuine CLI speaking the genuine protocol from a script. Nothing inside the\n * daemon takes a special path, because a demo of a special path is a demo of something nobody ships.\n */\nasync function demo(home: FanoutHome, io: Io, argv: readonly string[] = []): Promise<number> {\n const root = join(home.root, \"demo\");\n const repo = buildDemoRepo(join(root, \"shop\"));\n const ledgerPath = join(root, \"ledger.db\");\n rmSync(ledgerPath, { force: true });\n\n // The feed exists only once the API is listening, and the ledger is open before that; this holder is the join.\n const feed: { publish?: (event: StoredEvent) => void } = {};\n const ledger = Ledger.open(ledgerPath, {\n onAppend: (event) => {\n feed.publish?.(event);\n },\n });\n const adapter = createFakeAdapter({ scenarioFor: demoScenario });\n const workspaces = createWorkspaceManager({ repoRoot: repo, workspaceRoot: join(root, \"workspaces\") });\n const runner = createMissionRunner({\n ledger,\n workspaces,\n adapters: new Map([[\"fake\", adapter]]),\n runsRoot: join(root, \"runs\"),\n limits: DEFAULT_LIMITS,\n /*\n * The real router, over the demo's real crew \u2014 which is the simulated seat and nothing else. The `ui` line\n * asks for Codex, so it is moved and the reason on screen is the router's own sentence rather than a caption\n * we wrote. A demo that faked this would be demonstrating a code path nobody ships.\n */\n route: (line) =>\n routeLine({\n wanted: line.seat.id,\n seats: DEMO_CREW,\n policy: EMPTY_POLICY,\n headroom: {},\n now: new Date(),\n }),\n });\n\n const api = await startApi({\n ledger,\n token: readOrCreateToken(home.token),\n view: missionViewHtml,\n /*\n * The demo's crew is the simulated seat, said plainly. Reporting the machine's real CLIs here would make the\n * demo look like it was using them, and reporting nothing makes a working demo look broken.\n */\n crew: () => Promise.resolve(DEMO_CREW),\n });\n feed.publish = (event) => {\n api.publish(event);\n };\n\n const plan = PlanGraph.parse({ lines: demoLines() });\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: repo })).trim();\n const missionId = \"demo-csv-export\";\n ledger.appendAll([\n {\n type: \"mission.created\",\n missionId,\n goal: DEMO_GOAL,\n repo: { root: repo, baseCommit: head },\n limits: { maxParallel: 3, timeoutMinutes: 10 },\n },\n { type: \"plan.proposed\", missionId, plan, by: \"lead\" },\n ]);\n\n /*\n * The opening. Short, because nobody reads a paragraph before the thing they ran starts moving, and the crew\n * below is the actual answer to \"what is this\".\n */\n io.out(`\\n \\u001B[1mFanout\\u001B[0m \\u001B[2m\u00B7 a crew of coding agents, led by Claude Code\\u001B[0m\\n\\n`);\n io.out(` \\u001B[2mGoal\\u001B[0m ${DEMO_GOAL}\\n`);\n io.out(` \\u001B[2mCrew\\u001B[0m 3 simulated agents \u2014 nothing to sign into, nothing to pay for\\n`);\n io.out(` \\u001B[2mRepo\\u001B[0m ${repo} \\u001B[2m(throwaway)\\u001B[0m\\n\\n`);\n\n const handle = runner.launch({ missionId, plan, baseCommit: head, maxParallel: 3 });\n\n /*\n * The crew, live. Each line of the plan is one agent, named the way a person would name them, and the mission\n * is watched through the same projection every other surface reads \u2014 so this can never show a state the\n * mission view and the ledger disagree with.\n */\n const names = new Map(plan.lines.map((line, index) => [line.id, `Agent ${String(index + 1)}`]));\n const live = createLive({\n write: io.out,\n tty: io.tty ?? process.stdout.isTTY,\n });\n const draw = (): void => {\n const current = project(ledger.read({ missionId })).missions[missionId];\n if (current === undefined) return;\n live.render(\n current.runOrder.flatMap((runId) => {\n const run = current.runs[runId];\n const line = plan.lines.find((entry) => entry.id === run?.lineId);\n if (run === undefined || line === undefined) return [];\n return [demoRow(run, line, names.get(line.id) ?? run.seat.id, new Date())];\n }),\n );\n };\n\n const ticking = setInterval(draw, 90);\n try {\n await handle.finished;\n } finally {\n clearInterval(ticking);\n draw();\n live.stop();\n }\n\n /*\n * The claim check the demo shows is written, not read: real verdicts need a real second vendor. It is recorded\n * with `simulated: true` so every surface says so, because inventing a second opinion and presenting it as one\n * would fake the only thing this product claims to do.\n */\n ledger.appendAll([\n {\n type: \"claims.checked\",\n repoRoot: repo,\n revision: \"d3\".repeat(32),\n by: { id: \"fake\", model: \"demo\" },\n claims: demoClaims(),\n ran: true,\n simulated: true,\n },\n ]);\n\n /*\n * The ending, which the demo never had. Three diffs arrive and none of them merge, and that is the product\n * rather than a shortcoming \u2014 so it is said plainly instead of being left for the viewer to notice.\n */\n const state = project(ledger.read({ missionId }));\n const mission = state.missions[missionId];\n if (mission !== undefined) {\n const runs = mission.runOrder.flatMap((id) => (mission.runs[id] === undefined ? [] : [mission.runs[id]]));\n const written = runs.reduce((total, run) => total + (run.diffStat?.insertions ?? 0), 0);\n const refuted = demoClaims().filter((claim) => claim.verdict === \"refuted\").length;\n\n io.out(`\\n \\u001B[2m${\"\u2500\".repeat(62)}\\u001B[0m\\n\\n`);\n io.out(\n ` ${String(runs.length)} agents wrote ${String(written)} lines, each in its own worktree. ` +\n `\\u001B[1mNone of it is merged.\\u001B[0m\\n\\n`,\n );\n io.out(` \\u001B[2mThat is the point. Before anything reaches your branch:\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 a reader who did not write it reviews the diff\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 your own checks run against that exact revision\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 a bug fix ships with a test proven to fail on the old code\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 and you say yes\\u001B[0m\\n\\n`);\n if (refuted > 0) {\n io.out(\n ` A second agent read the work cold and \\u001B[1mrefuted ${String(refuted)} of their claims\\u001B[0m.\\n` +\n ` \\u001B[2mSimulated here; real the moment you have a second CLI signed in.\\u001B[0m\\n\\n`,\n );\n }\n io.out(` \\u001B[2mThe whole run, diff by diff:\\u001B[0m ${api.url}/\\n`);\n }\n /*\n * `--once` exits when the mission does, instead of holding the view open. It is what a script wants: the\n * packaging check runs this to prove an installed Fanout actually works, and a command that never returns\n * cannot be checked by anything.\n */\n if (argv.includes(\"--once\")) {\n await api.close();\n ledger.close();\n return 0;\n }\n\n io.out(` \\u001B[2mStill watching \u2014 Ctrl-C when you have seen enough.\\u001B[0m\\n`);\n\n await (io.until ?? new Promise<void>(() => undefined));\n await api.close();\n ledger.close();\n return 0;\n}\n\nasync function status(home: FanoutHome, io: Io): Promise<number> {\n const seats = await detectSeats({\n manifests: SEATS,\n ...(io.execute === undefined ? {} : { execute: io.execute }),\n });\n const { policy, problem } = readSeatPolicy(home.root);\n // A policy we could not read is not the same as no policy, and the difference is whose money it is.\n if (problem !== null)\n io.err(`fanout: ${problem}\\n Until it is fixed, every seat falls back to its default.\\n\\n`);\n io.out(crewTable(seats, policy));\n\n if (!existsSync(home.ledger)) {\n io.out(\"\\nNo missions yet. The ledger appears the first time the lead plans one.\\n\");\n return 0;\n }\n\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n io.out(`\\n${missionLines(state)}`);\n } finally {\n ledger.close();\n }\n return 0;\n}\n\n/**\n * `fanout check` \u2014 the lead writes down what it believes; a cold reader tries to disprove each claim.\n *\n * Sharper and far cheaper than a broad review, because the value was never the volume of reading. The lead\n * carries the plan and the reasoning, and that is exactly what hides its mistakes from it; a reader with only the\n * diff is not smarter, it is differently placed. Three specific claims buy that difference for almost nothing.\n *\n * Exits non-zero when a claim is refuted, so this can sit in a script or a hook.\n */\nasync function check(home: FanoutHome, claims: readonly string[], io: Io): Promise<number> {\n if (claims.length === 0) {\n io.err(`fanout: check needs something to check.\\n\\n${CHECK_HELP}`);\n return 64;\n }\n\n const ready = await reviewerFor(home, io);\n if (typeof ready === \"number\") return ready;\n\n const { event, refuted } = await checkClaims({\n repoRoot: io.cwd ?? process.cwd(),\n claims,\n manifest: ready.manifest,\n ...(io.execute === undefined ? {} : { execute: reviewWith(io.execute) }),\n });\n\n const ledger = Ledger.open(home.ledger);\n try {\n ledger.appendAll([event]);\n } finally {\n ledger.close();\n }\n\n if (!event.ran) {\n // Never let \"we could not ask\" read as \"nothing was refuted\".\n io.err(\n `fanout: ${ready.manifest.displayName} did not check your claims.\\n ${event.claims[0]?.evidence ?? \"\"}\\n`,\n );\n return 69;\n }\n\n const mark = { confirmed: \"\u2713\", refuted: \"\u2717\", unclear: \"?\" } as const;\n io.out(`${ready.manifest.displayName} read your changes cold:\\n\\n`);\n for (const claim of event.claims) {\n io.out(` ${mark[claim.verdict]} ${claim.claim}\\n ${claim.evidence}\\n`);\n }\n io.out(`\\n${summarise(event.claims)}\\n`);\n\n // A refuted claim is the only outcome worth interrupting someone for.\n return refuted.length > 0 ? 1 : 0;\n}\n\nfunction summarise(claims: EventOf<\"claims.checked\">[\"claims\"]): string {\n const count = (verdict: string): number => claims.filter((claim) => claim.verdict === verdict).length;\n const refuted = count(\"refuted\");\n const unclear = count(\"unclear\");\n if (refuted > 0) return `${String(refuted)} refuted. Nothing here is settled until those are.`;\n if (unclear > 0)\n return `Nothing refuted, but ${String(unclear)} could not be checked \u2014 that is not the same as fine.`;\n return \"All confirmed.\";\n}\n\nconst CHECK_HELP = ` fanout check \"<claim>\" [\"<claim>\" ...]\n\n Write claims a reader could disprove. \"It works\" cannot be checked; \"no caller of\n total() passes fewer than two arguments\" can.\n`;\n\n/**\n * `fanout review` \u2014 a second vendor reads the lead's own uncommitted work.\n *\n * The one command that earns its keep in a session where no agent ran at all. Most of the code in a Claude Code\n * session is written by the lead and reviewed by the lead, which is how a confident mistake ships; this is the\n * call that breaks that loop. The findings are printed verbatim, because a second opinion summarised by the\n * author it is about is not a second opinion.\n */\nasync function buddy(home: FanoutHome, io: Io): Promise<number> {\n const ready = await reviewerFor(home, io);\n if (typeof ready === \"number\") return ready;\n\n const { snapshot, event } = await buddyReview({\n repoRoot: io.cwd ?? process.cwd(),\n manifest: ready.manifest,\n ...(io.execute === undefined ? {} : { execute: reviewWith(io.execute) }),\n });\n\n const ledger = Ledger.open(home.ledger);\n try {\n ledger.appendAll([event]);\n } finally {\n ledger.close();\n }\n\n if (snapshot.clean) {\n io.out(\"Nothing uncommitted to review.\\n\");\n return 0;\n }\n if (!event.ran) {\n // Never let \"the reviewer broke\" read as \"the reviewer found nothing\".\n io.err(`fanout: ${ready.manifest.displayName} could not review your changes.\\n ${event.findings}\\n`);\n return 69;\n }\n\n const files = `${String(snapshot.files.length)} file${snapshot.files.length === 1 ? \"\" : \"s\"}`;\n io.out(\n event.findings.trim() === \"\"\n ? `${ready.manifest.displayName} read ${files} and had nothing to say.\\n`\n : `${ready.manifest.displayName} read ${files}:\\n\\n${event.findings.trim()}\\n`,\n );\n return 0;\n}\n\n/**\n * The seat that will read your work, or the exit code explaining why nobody will.\n *\n * Every check here is about not spending someone's subscription behind their back \u2014 a posture they set, a version\n * this adapter was never verified against, a policy file we could not read. Shared by both readers so that the\n * next one cannot forget any of them, which is exactly how `fanout review` shipped ignoring the seat policy.\n */\nasync function reviewerFor(home: FanoutHome, io: Io): Promise<{ manifest: AdapterManifest } | number> {\n const manifest = SEATS.find((seat) => seat.id === \"codex\");\n if (manifest?.capabilities.review == null) {\n io.err(\"fanout: no seat on this machine has a non-interactive review command.\\n\");\n return 69;\n }\n\n const { policy, problem } = readSeatPolicy(home.root);\n if (problem !== null) {\n io.err(`fanout: ${problem}\\n Fix or delete that file before spending a seat.\\n`);\n return 65;\n }\n\n const [detected] = await detectSeats({\n manifests: [manifest],\n ...(io.execute === undefined ? {} : { execute: io.execute }),\n });\n if (detected === undefined) {\n io.err(\"fanout: could not detect the reviewing seat.\\n\");\n return 69;\n }\n\n const stance = stanceFor(detected, policy);\n if (stance.posture === \"off\") {\n io.err(`fanout: ${manifest.displayName} is off (${stance.reason}). Turn it on with:\\n`);\n io.err(` fanout seat ${manifest.id} normal\\n`);\n return 69;\n }\n if (!detected.supported) {\n // An unverified build would be driven with flags we have not confirmed and read as a stream we have not seen.\n io.err(\n `fanout: ${manifest.displayName} ${detected.version ?? \"is not installed\"} is outside the versions this ` +\n `adapter was verified against (${manifest.supportedVersions}).\\n`,\n );\n return 69;\n }\n if (detected.signedIn !== \"yes\") {\n io.err(\n `fanout: ${manifest.displayName} is ${detected.signedIn === \"no\" ? \"not signed in\" : \"unknown\"}.\\n`,\n );\n return 69;\n }\n if (stance.posture === \"sparing\") {\n // Sparing means \"only when nothing else fits, and say so first\". This is the saying so.\n io.out(\n `Using ${manifest.displayName}, which you marked sparing${stance.note === undefined ? \"\" : ` \u2014 ${stance.note}`}.\\n`,\n );\n }\n return { manifest };\n}\n\n/** The CLI's injected executor takes no options; the buddy's takes cwd and a deadline. Bridge them for tests. */\nfunction reviewWith(\n execute: NonNullable<Io[\"execute\"]>,\n): (binary: string, args: readonly string[]) => Promise<CommandResult> {\n return (binary, args) => execute(binary, args);\n}\n\n/**\n * `fanout owed` \u2014 what the lead still owes before anything can merge.\n *\n * Run by the Stop hook on every turn, which is the point: a tool the lead chooses to call cannot catch a lead who\n * believes the work is already finished. Prints nothing and exits 0 when there is nothing owed, so a quiet session\n * stays quiet, and it never blocks \u2014 walking away from unfinished work is allowed, doing it unknowingly is not.\n */\nasync function owed(home: FanoutHome, io: Io): Promise<number> {\n const repoRoot = io.cwd ?? process.cwd();\n\n // The working tree is asked about first, because that is where the lead's own unread code lives.\n let own = \"\";\n try {\n const snapshot = await workSnapshot({ cwd: repoRoot });\n if (!existsSync(home.ledger)) {\n own = ownWorkOwed({ revision: snapshot.revision, files: snapshot.files.length, checked: undefined });\n } else {\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n own = ownWorkOwed({\n revision: snapshot.revision,\n files: snapshot.files.length,\n checked: state.claims[snapshot.repoRoot],\n });\n } finally {\n ledger.close();\n }\n }\n } catch {\n // Not a repository, or git is unhappy. A hook that runs every turn must never be the reason a turn fails.\n }\n\n if (!existsSync(home.ledger)) {\n if (own !== \"\") io.out(unfinishedReport([], own));\n return 0;\n }\n\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n const report = unfinishedReport(whatIsOwed(Object.values(state.missions)), own);\n if (report !== \"\") io.out(report);\n } finally {\n ledger.close();\n }\n return 0;\n}\n\n/** `fanout seat <id> <posture> [note]` \u2014 the one setting, and it is always the owner's to make. */\nfunction seat(home: FanoutHome, args: readonly string[], io: Io): number {\n const [seatId, posture, ...rest] = args;\n if (seatId === undefined || posture === undefined) {\n io.err(`fanout: seat needs which seat and how freely to spend it.\\n\\n${SEAT_HELP}`);\n return 64;\n }\n\n const wanted = SeatPosture.safeParse(posture);\n if (!wanted.success) {\n io.err(`fanout: \"${posture}\" is not a posture.\\n\\n${SEAT_HELP}`);\n return 64;\n }\n if (!SEATS.some((manifest) => manifest.id === seatId)) {\n const known = SEATS.map((manifest) => manifest.id).join(\", \");\n io.err(`fanout: there is no seat called \"${seatId}\". Seats: ${known}.\\n`);\n return 64;\n }\n\n const { policy, problem } = readSeatPolicy(home.root);\n if (problem !== null) {\n // Writing on top of a file we could not read would silently discard preferences the owner did set.\n io.err(`fanout: ${problem}\\n Fix or delete that file before changing a seat.\\n`);\n return 65;\n }\n\n const note = rest.join(\" \");\n writeSeatPolicy(home.root, setPosture(policy, seatId, wanted.data, note));\n io.out(`${seatId} is now ${wanted.data}${note === \"\" ? \"\" : ` \u2014 ${note}`}.\\n`);\n return 0;\n}\n\nconst SEAT_HELP = ` fanout seat <id> <preferred|normal|sparing|off> [why]\n\n preferred reach for this one first\n normal use it when the plan calls for it\n sparing only when nothing else fits, and say so first\n off never, until you say otherwise\n`;\n\nasync function daemon(home: FanoutHome, io: Io): Promise<number> {\n const ledger = Ledger.open(home.ledger);\n const token = readOrCreateToken(home.token);\n const api = await startApi({\n ledger,\n token,\n crew: () =>\n detectSeats({ manifests: SEATS, ...(io.execute === undefined ? {} : { execute: io.execute }) }),\n view: missionViewHtml,\n });\n\n io.out(\n `fanout daemon listening on ${api.url}\\n` +\n ` token ${home.token} (read by the plugin and the CLI; keep it to yourself)\\n` +\n ` ledger ${home.ledger}\\n` +\n ` live ${api.url.replace(\"http\", \"ws\")}/events?for=lead\\n\\nStop it with Ctrl-C.\\n`,\n );\n\n await (io.until ?? interrupted());\n await api.close();\n ledger.close();\n io.out(\"fanout daemon stopped.\\n\");\n return 0;\n}\n\n/**\n * Removes what a run leaves on disk: its worktree and its throwaway branch. It only ever touches workspaces under\n * FANOUT_HOME and branches under `fanout/`, so a clean can never take the user's own work with it.\n */\nasync function clean(home: FanoutHome, io: Io): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n let repoRoot: string;\n try {\n repoRoot = (await git([\"rev-parse\", \"--show-toplevel\"], { cwd })).trim();\n } catch {\n io.err(\"fanout clean: run this inside the repository whose missions you want to clean up.\\n\");\n return 64;\n }\n\n // git reports resolved paths (/private/var/\u2026 on macOS) while FANOUT_HOME may be the symlinked form (/var/\u2026),\n // so compare both spellings; otherwise a clean silently removes nothing and then fails to delete the branch.\n const roots = [\n home.workspaces,\n existsSync(home.workspaces) ? realpathSync(home.workspaces) : home.workspaces,\n ];\n const worktrees = lines(await git([\"worktree\", \"list\", \"--porcelain\"], { cwd: repoRoot }))\n .filter((line) => line.startsWith(\"worktree \"))\n .map((line) => line.slice(\"worktree \".length))\n .filter((path) => roots.some((root) => path.startsWith(root)));\n const branches = lines(\n await git([\"for-each-ref\", \"--format=%(refname:short)\", \"refs/heads/fanout/\"], { cwd: repoRoot }),\n );\n\n if (worktrees.length === 0 && branches.length === 0) {\n io.out(\"Nothing to clean: no Fanout worktrees or branches in this repository.\\n\");\n return 0;\n }\n\n for (const path of worktrees) await git([\"worktree\", \"remove\", \"--force\", path], { cwd: repoRoot });\n await git([\"worktree\", \"prune\"], { cwd: repoRoot });\n\n const kept: string[] = [];\n for (const branch of branches) {\n try {\n await git([\"branch\", \"-D\", branch], { cwd: repoRoot });\n } catch {\n kept.push(branch); // still checked out somewhere: say so rather than pretending it is gone\n }\n }\n rmSync(home.workspaces, { recursive: true, force: true });\n\n const removed = branches.length - kept.length;\n io.out(\n `Cleaned ${worktrees.length} worktree${worktrees.length === 1 ? \"\" : \"s\"} and ` +\n `${removed} branch${removed === 1 ? \"\" : \"es\"}. Your own branches were not touched.\\n`,\n );\n if (kept.length > 0) {\n io.err(`Still in use elsewhere, so left alone: ${kept.join(\", \")}.\\n`);\n }\n return kept.length === 0 ? 0 : 1;\n}\n\n/**\n * Speaks MCP on stdin and stdout so Claude Code can drive the crew, and runs the daemon in the same process so the\n * mission view and the lead's live feed have something to subscribe to.\n *\n * Nothing but MCP may touch stdout here: a stray line would corrupt the protocol, which is why every message this\n * command prints goes to stderr.\n */\nasync function mcp(home: FanoutHome, io: Io): Promise<number> {\n // The feed exists only once the API is listening, and the ledger is open before that; this holder is the join.\n const feed: { publish?: (event: StoredEvent) => void } = {};\n const ledger = Ledger.open(home.ledger, {\n onAppend: (event) => {\n feed.publish?.(event);\n },\n });\n const token = readOrCreateToken(home.token);\n const api = await startApi({\n ledger,\n token,\n crew: () =>\n detectSeats({ manifests: SEATS, ...(io.execute === undefined ? {} : { execute: io.execute }) }),\n view: missionViewHtml,\n });\n feed.publish = (event) => {\n api.publish(event);\n };\n\n // Where the daemon is, for the mission view and any other client. Private, like everything else here.\n writeFileSync(join(home.root, \"daemon.json\"), `${JSON.stringify({ url: api.url, pid: process.pid })}\\n`, {\n mode: 0o600,\n });\n\n const server = createFanoutServer({\n ledger,\n repoRoot: io.cwd ?? process.cwd(),\n paths: { runs: home.runs, workspaces: home.workspaces, home: home.root },\n adapters: adapters(),\n manifests: SEATS,\n limits: DEFAULT_LIMITS,\n });\n\n io.err(`fanout mcp ready. Live feed: ${api.url.replace(\"http\", \"ws\")}/events?for=lead\\n`);\n await server.connect(new StdioServerTransport());\n await (io.until ?? interrupted());\n\n await server.close();\n await api.close();\n ledger.close();\n return 0;\n}\n\nfunction interrupted(): Promise<void> {\n return new Promise<void>((resolve) => {\n const stop = (): void => {\n resolve();\n };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n });\n}\n\nexport type { SeatInfo };\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type AdapterSignal,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { ClaudeLine, ToolUse } from \"./protocol.ts\";\n\n/*\n * The Claude Code seat, as a worker. It is opt-in (DECISIONS 0009): the lead already spends this subscription on\n * planning and reviewing, and the point of a crew is to put the other subscriptions to work.\n *\n * Driven through `claude -p`, the documented non-interactive mode. Permission prompts are denied rather than\n * bypassed: a run that would need a human is refused, never waved through.\n *\n * Its stream is the only one that reports a real quota window (how full the five-hour and seven-day windows are,\n * and when they reset), which is exactly what routing needs and what every other seat makes us estimate.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst WRITING = /^(write|edit|multiedit|notebookedit|update)$/i;\nconst READING = /^(read|grep|glob|ls|search|webfetch|websearch)$/i;\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\n\nexport function createClaudeAdapter(): SeatAdapter {\n return {\n id: manifest.id,\n\n command(context: AdapterContext): LaunchSpec {\n const readOnly = context.line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{prompt}\", context.line.prompt)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit),\n );\n if (context.line.seat.model !== undefined) args.push(\"--model\", context.line.seat.model);\n if (context.line.seat.effort !== undefined) args.push(\"--effort\", context.line.seat.effort);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n },\n\n parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = ClaudeLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n\n if (line.type === \"system\" && line.subtype === \"init\" && line.session_id !== undefined) {\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reading\" }],\n signals: [{ kind: \"session\", id: line.session_id }],\n };\n }\n\n if (\n line.type === \"system\" &&\n line.subtype === \"thinking_tokens\" &&\n line.estimated_tokens_delta !== undefined\n ) {\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: Math.max(0, line.estimated_tokens_delta),\n unit: \"tokens\",\n estimated: true,\n },\n ],\n signals: [],\n };\n }\n\n if (line.type === \"rate_limit_event\")\n return { events: [], signals: quotaSignals(line.rate_limit_info) };\n\n if (line.type === \"assistant\") {\n const events: FanoutEventInput[] = [];\n for (const raw of line.message.content) {\n const parsedBlock = ToolUse.safeParse(raw);\n if (!parsedBlock.success) continue; // thinking and text blocks say nothing about what the run did\n const block = parsedBlock.data;\n const input = block.input;\n const command = input?.command ?? \"\";\n const files = [input?.file_path, input?.path, input?.notebook_path]\n .filter((path): path is string => path !== undefined && path !== \"\")\n .map((path) => repoRelative(path, context.workdir));\n\n events.push({ type: \"run.progress\", ...run, phase: phaseOf(block.name, command) });\n events.push({\n type: \"run.tool\",\n ...run,\n tool: block.name,\n ...(command === \"\" ? {} : { summary: command.slice(0, 500) }),\n files,\n });\n }\n return { events, signals: [] };\n }\n\n if (line.type === \"result\") {\n const usage = line.usage;\n const tokens = (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0);\n return {\n events: [\n ...(tokens > 0\n ? [\n {\n type: \"run.usage\" as const,\n ...run,\n seat: context.line.seat.id,\n amount: tokens,\n unit: \"tokens\" as const,\n estimated: false,\n },\n ]\n : []),\n { type: \"run.progress\", ...run, phase: \"reporting\" },\n ],\n signals: [\n ...(line.result === undefined || line.result === \"\"\n ? []\n : [{ kind: \"report\" as const, text: line.result }]),\n ...(line.is_error === true\n ? [{ kind: \"error\" as const, message: line.result ?? \"the run ended with an error\" }]\n : []),\n ],\n };\n }\n\n // \"user\" lines carry tool results, which the tool call already told us about.\n return { events: [], signals: [] };\n },\n };\n}\n\n/** Claude reports how full each window is, and when it resets: real numbers the crew never has to estimate. */\nfunction quotaSignals(info: {\n status: string;\n rateLimitType?: string | undefined;\n resetsAt?: number | undefined;\n unifiedWindows?: Record<string, { utilization: number; resetsAt?: number | undefined }> | undefined;\n}): AdapterSignal[] {\n const signals: AdapterSignal[] = Object.entries(info.unifiedWindows ?? {}).map(([window, value]) => ({\n kind: \"quota\",\n window,\n utilization: value.utilization,\n ...(value.resetsAt === undefined ? {} : { resetsAt: asIso(value.resetsAt) }),\n }));\n\n if (info.status !== \"allowed\") {\n signals.push({\n kind: \"limit\",\n message: `Claude reported the ${info.rateLimitType ?? \"usage\"} window as ${info.status}`,\n ...(info.resetsAt === undefined ? {} : { resetsAt: asIso(info.resetsAt) }),\n });\n }\n return signals;\n}\n\n/** The CLI counts in seconds since the epoch; events speak ISO. */\nfunction asIso(seconds: number): string {\n return new Date(seconds * 1000).toISOString();\n}\n\nfunction phaseOf(tool: string, command: string): \"reading\" | \"coding\" | \"testing\" {\n if (TEST_COMMAND.test(command)) return \"testing\";\n if (WRITING.test(tool)) return \"coding\";\n if (READING.test(tool)) return \"reading\";\n return \"coding\";\n}\n\n/** Claude reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "import { z } from \"zod\";\n\n/** Identifiers people read: mission, line, run and seat ids (\"csv-export\", \"api-builder-1\", \"codex\"). */\nexport const Slug = z\n .string()\n .regex(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/, \"use lowercase letters, digits and inner dashes (max 64)\");\n\nexport const MissionId = Slug;\nexport const LineId = Slug;\nexport const RunId = Slug;\nexport const SeatId = Slug;\n\n/** A full commit id: 40 hex characters (SHA-1 repositories) or 64 (SHA-256 repositories). */\nexport const GitSha = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/, \"a full commit sha\");\n\n/**\n * The identity of one piece of work: a hash of exactly what a run changed, at the moment we looked.\n *\n * An agent never commits, so its work has no commit id to name it by, and \"the diff in that worktree\" is not an\n * identity \u2014 it is a thing that can change between the moment it is reviewed and the moment it is merged. Every\n * step of the gate records the revision it judged, and a merge applies only a revision that every step agreed on.\n * Without that, \"reviewed and checked\" means \"reviewed and checked something, once\".\n */\nexport const WorkRevision = z.string().regex(/^[0-9a-f]{64}$/, \"a work revision (sha-256 of the diff)\");\n\n/** Which seat runs a line, and optionally with which model and effort. */\nexport const SeatRef = z.strictObject({\n id: SeatId,\n model: z.string().min(1).max(100).optional(),\n effort: z.string().min(1).max(40).optional(),\n});\nexport type SeatRef = z.infer<typeof SeatRef>;\n\n/** What the detector knows about an installed agent CLI. Unknown facts say \"unknown\" or null, never a guess. */\nexport const SeatInfo = z.strictObject({\n id: SeatId,\n displayName: z.string().min(1).max(80),\n binary: z.string().min(1).max(200),\n version: z.string().min(1).max(100).nullable(),\n supported: z.boolean(),\n signedIn: z.enum([\"yes\", \"no\", \"unknown\"]),\n models: z.array(z.string().min(1).max(100)).max(100),\n efforts: z.array(z.string().min(1).max(40)).max(20),\n billing: z.enum([\"subscription\", \"credit\", \"api\", \"unknown\"]),\n /**\n * The subscription tier this seat is on, and where that answer came from \u2014 `null` when the CLI does not report\n * one, which is most of them. The source travels with the value on purpose: \"detected\" is a fact the CLI told us\n * this run, \"declared\" is something the owner typed once and may since have outgrown, and a reader deciding how\n * much to trust a routing decision deserves to know which it is looking at.\n */\n plan: z\n .strictObject({\n name: z.string().min(1).max(100),\n source: z.enum([\"detected\", \"declared\"]),\n })\n .nullable(),\n});\nexport type SeatInfo = z.infer<typeof SeatInfo>;\n\nexport const DiffStat = z.strictObject({\n files: z.int().nonnegative(),\n insertions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n});\nexport type DiffStat = z.infer<typeof DiffStat>;\n\nexport const MissionLimits = z.strictObject({\n maxParallel: z.int().min(1).max(32),\n timeoutMinutes: z\n .int()\n .min(1)\n .max(24 * 60),\n});\nexport type MissionLimits = z.infer<typeof MissionLimits>;\n\n/** One line of the safety report. A failed \"block\" check stops the launch; a failed \"warn\" check is shown. */\nexport const SafetyCheck = z.strictObject({\n id: z.string().min(1).max(64),\n ok: z.boolean(),\n severity: z.enum([\"block\", \"warn\"]),\n message: z.string().min(1).max(2000),\n lineIds: z.array(LineId).max(32).optional(),\n});\nexport type SafetyCheck = z.infer<typeof SafetyCheck>;\n", "import { z } from \"zod\";\n\n/*\n * Write scopes are repo-relative POSIX globs with a deliberately small syntax:\n * `*` and `?` match within one path segment, `**` (a whole segment) matches zero or more segments.\n * Every pattern also covers everything below what it matches, so `src/api` and `src/api/**` are the same scope.\n * Braces, character classes and negation are not supported: a scope must be obvious to the person approving it.\n *\n * Every other character is literal, so ordinary filenames work: spaces, parentheses, accents, CJK, emoji.\n * Only `*` and `?` are special, and there is no escape for them; a file whose name really contains one is covered\n * by a scope that ends in `**`. Separators, empty segments, `.` and `..` are refused, as are control characters.\n *\n * Matching is deliberately hand-written rather than translated to regular expressions: a pattern like `a*a*a*\u2026z`\n * makes a backtracking engine take exponential time, and scopes come from plans we must be able to check quickly.\n */\n\n// eslint-disable-next-line no-control-regex -- control characters are exactly what a path segment must not contain\nconst SEGMENT = /^(?:\\*\\*|[^/\u0000-\u001F\u007F]+)$/;\nconst WILDCARD = /[*?]/;\n\nexport function isValidScopeGlob(glob: string): boolean {\n if (glob.length === 0 || glob.startsWith(\"/\") || glob.endsWith(\"/\")) return false;\n return glob\n .split(\"/\")\n .every(\n (segment) =>\n SEGMENT.test(segment) &&\n segment !== \".\" &&\n segment !== \"..\" &&\n (segment === \"**\" || !segment.includes(\"**\")),\n );\n}\n\nexport const ScopeGlob = z.string().max(300).refine(isValidScopeGlob, {\n message: \"use a repo-relative path or glob (`*`, `?`, `**`), without `..`, leading or trailing `/`\",\n});\n\n/**\n * A plain repo-relative path: no leading slash, no `.` or `..`, no empty segments. Anything else (a path that still\n * needs resolving, or one from outside the repository) is not inside any scope, whatever it looks like.\n */\nexport function isRepoPath(path: string): boolean {\n if (path.length === 0 || path.startsWith(\"/\") || path.endsWith(\"/\")) return false;\n return path.split(\"/\").every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/** Segments of a pattern, with the implicit \"and everything below\" made explicit. */\nfunction scopeSegments(glob: string): string[] {\n const segments = glob.split(\"/\");\n return segments.at(-1) === \"**\" ? segments : [...segments, \"**\"];\n}\n\n/**\n * Matches one segment pattern (`*`, `?`) against one name, in linear time: on a mismatch it returns to the last `*`\n * and gives it one more character, so no input can make it backtrack exponentially.\n */\nfunction segmentMatches(pattern: string, text: string): boolean {\n let p = 0;\n let t = 0;\n let starAt = -1;\n let matchedAt = 0;\n\n while (t < text.length) {\n const token = pattern[p];\n if (token === \"?\" || (token !== undefined && token !== \"*\" && token === text[t])) {\n p += 1;\n t += 1;\n } else if (token === \"*\") {\n starAt = p;\n matchedAt = t;\n p += 1;\n } else if (starAt >= 0) {\n matchedAt += 1;\n p = starAt + 1;\n t = matchedAt;\n } else {\n return false;\n }\n }\n while (pattern[p] === \"*\") p += 1;\n return p === pattern.length;\n}\n\n/** The literal text before the first wildcard and after the last one. */\nfunction literalEnds(segment: string): [prefix: string, suffix: string] {\n const first = segment.search(WILDCARD);\n let last = segment.length - 1;\n while (last >= 0 && !WILDCARD.test(segment.charAt(last))) last -= 1;\n return [segment.slice(0, first), segment.slice(last + 1)];\n}\n\n/**\n * Whether two single-segment patterns can match a common name. Exact when at least one side is literal; when both\n * have wildcards it compares their literal ends, which can only err towards \"yes\" (the safe side for scopes).\n */\nfunction segmentsMayOverlap(a: string, b: string): boolean {\n const aWild = WILDCARD.test(a);\n const bWild = WILDCARD.test(b);\n if (!aWild && !bWild) return a === b;\n if (!aWild) return segmentMatches(b, a);\n if (!bWild) return segmentMatches(a, b);\n const [aPrefix, aSuffix] = literalEnds(a);\n const [bPrefix, bSuffix] = literalEnds(b);\n return (\n (aPrefix.startsWith(bPrefix) || bPrefix.startsWith(aPrefix)) &&\n (aSuffix.endsWith(bSuffix) || bSuffix.endsWith(aSuffix))\n );\n}\n\n/**\n * Whether some file path could fall inside both scopes. Sound: it never answers \"no\" when a common path exists.\n * It may answer \"yes\" for exotic wildcard pairs that cannot actually meet; the plan then asks for narrower scopes.\n */\nexport function scopesMayOverlap(a: string, b: string): boolean {\n const left = scopeSegments(a);\n const right = scopeSegments(b);\n const memo = new Map<number, boolean>();\n const width = right.length + 1;\n\n const from = (i: number, j: number): boolean => {\n const key = i * width + j;\n const known = memo.get(key);\n if (known !== undefined) return known;\n let result: boolean;\n const l = left[i];\n const r = right[j];\n if (l === undefined && r === undefined) result = true;\n else if (l === \"**\") result = from(i + 1, j) || (r !== undefined && from(i, j + 1));\n else if (r === \"**\") result = from(i, j + 1) || (l !== undefined && from(i + 1, j));\n else if (l === undefined || r === undefined) result = false;\n else result = segmentsMayOverlap(l, r) && from(i + 1, j + 1);\n memo.set(key, result);\n return result;\n };\n\n return from(0, 0);\n}\n\n/** Whether a repo-relative file path falls inside a scope. */\nexport function pathInScope(path: string, glob: string): boolean {\n if (!isRepoPath(path)) return false;\n const parts = path.split(\"/\");\n const pattern = scopeSegments(glob);\n const memo = new Map<number, boolean>();\n const width = pattern.length + 1;\n\n const from = (i: number, j: number): boolean => {\n const key = i * width + j;\n const known = memo.get(key);\n if (known !== undefined) return known;\n const segment = pattern[j];\n const part = parts[i];\n let result: boolean;\n if (segment === undefined) result = i === parts.length;\n else if (segment === \"**\") result = from(i, j + 1) || (i < parts.length && from(i + 1, j));\n else result = part !== undefined && segmentMatches(segment, part) && from(i + 1, j + 1);\n memo.set(key, result);\n return result;\n };\n\n return from(0, 0);\n}\n", "import { z } from \"zod\";\nimport { LineId, SeatRef } from \"./common.ts\";\nimport { ScopeGlob, scopesMayOverlap } from \"./scope.ts\";\n\nexport const LineRole = z.enum([\"auditor\", \"builder\", \"tester\"]);\nexport type LineRole = z.infer<typeof LineRole>;\n\n/** One task in a mission. Auditors are read-only; builders and testers declare where they may write. */\nexport const PlanLine = z.strictObject({\n id: LineId,\n title: z.string().trim().min(1).max(120),\n role: LineRole,\n prompt: z.string().min(1).max(100_000),\n seat: SeatRef,\n scope: z.strictObject({ write: z.array(ScopeGlob).max(64) }),\n dependsOn: z.array(LineId).max(32).default([]),\n checks: z.array(z.string().min(1).max(500)).max(16).default([]),\n timeoutMinutes: z.int().min(1).max(240).optional(),\n /**\n * This line fixes a bug, so the gate will not merge it without a test proven to fail on the old code.\n *\n * Declared when the mission is planned rather than judged afterwards, because the moment to decide whether\n * something is a fix is before an agent has written a persuasive explanation of why its change is fine.\n */\n fixesBug: z.boolean().default(false),\n});\nexport type PlanLine = z.infer<typeof PlanLine>;\n\nexport const PlanGraph = z.strictObject({\n lines: z.array(PlanLine).min(1).max(32),\n});\nexport type PlanGraph = z.infer<typeof PlanGraph>;\n\nexport type PlanIssueCode =\n | \"duplicate_line\"\n | \"unknown_dependency\"\n | \"self_dependency\"\n | \"dependency_cycle\"\n | \"auditor_writes\"\n | \"missing_write_scope\"\n | \"scope_overlap\";\n\nexport interface PlanIssue {\n code: PlanIssueCode;\n message: string;\n lineIds: string[];\n}\n\n/**\n * Checks the rules a schema can't express: the dependency graph and the write scopes of lines that may run at the\n * same time. Returns every issue found, in a stable order; an empty list means the plan is launchable.\n */\nexport function validatePlan(plan: PlanGraph): PlanIssue[] {\n const issues: PlanIssue[] = [];\n const { lines } = plan;\n\n const indexById = new Map<string, number>();\n lines.forEach((line, index) => {\n if (indexById.has(line.id)) {\n issues.push({\n code: \"duplicate_line\",\n message: `Line id \"${line.id}\" is used more than once.`,\n lineIds: [line.id],\n });\n } else {\n indexById.set(line.id, index);\n }\n });\n\n const edges: number[][] = lines.map((line) => {\n const targets: number[] = [];\n for (const dependency of line.dependsOn) {\n if (dependency === line.id) {\n issues.push({\n code: \"self_dependency\",\n message: `Line \"${line.id}\" depends on itself.`,\n lineIds: [line.id],\n });\n continue;\n }\n const target = indexById.get(dependency);\n if (target === undefined) {\n issues.push({\n code: \"unknown_dependency\",\n message: `Line \"${line.id}\" depends on \"${dependency}\", which is not in the plan.`,\n lineIds: [line.id],\n });\n } else {\n targets.push(target);\n }\n }\n return targets;\n });\n\n for (const cycle of findCycles(edges)) {\n const ids = cycle.map((index) => lines[index]?.id ?? \"?\");\n issues.push({\n code: \"dependency_cycle\",\n message: `Dependencies form a cycle: ${[...ids, ids[0]].join(\" \u2192 \")}.`,\n lineIds: ids,\n });\n }\n\n for (const line of lines) {\n if (line.role === \"auditor\" && line.scope.write.length > 0) {\n issues.push({\n code: \"auditor_writes\",\n message: `Line \"${line.id}\" is an auditor, so it is read-only; remove its write scope or make it a builder.`,\n lineIds: [line.id],\n });\n }\n if (line.role !== \"auditor\" && line.scope.write.length === 0) {\n issues.push({\n code: \"missing_write_scope\",\n message: `Line \"${line.id}\" is a ${line.role} but declares no write scope.`,\n lineIds: [line.id],\n });\n }\n }\n\n const reaches = reachability(edges);\n for (let i = 0; i < lines.length; i += 1) {\n for (let j = i + 1; j < lines.length; j += 1) {\n const a = lines[i];\n const b = lines[j];\n if (a === undefined || b === undefined) continue;\n if (reaches[i]?.has(j) === true || reaches[j]?.has(i) === true) continue;\n const clash = firstOverlap(a.scope.write, b.scope.write);\n if (clash !== undefined) {\n issues.push({\n code: \"scope_overlap\",\n message:\n `Lines \"${a.id}\" and \"${b.id}\" can run at the same time and may both write ` +\n `\"${clash[0]}\" / \"${clash[1]}\". Make one depend on the other, or narrow the scopes.`,\n lineIds: [a.id, b.id],\n });\n }\n }\n }\n\n return issues;\n}\n\nfunction firstOverlap(left: string[], right: string[]): [string, string] | undefined {\n for (const a of left) {\n for (const b of right) {\n if (scopesMayOverlap(a, b)) return [a, b];\n }\n }\n return undefined;\n}\n\n/** For each node, every node it can reach by following edges (its transitive dependencies). */\nfunction reachability(edges: number[][]): Set<number>[] {\n return edges.map((_, start) => {\n const seen = new Set<number>();\n const stack = [...(edges[start] ?? [])];\n for (let next = stack.pop(); next !== undefined; next = stack.pop()) {\n if (seen.has(next)) continue;\n seen.add(next);\n stack.push(...(edges[next] ?? []));\n }\n return seen;\n });\n}\n\n/** One cycle per back edge found by a depth-first search, each listed from its first node in plan order. */\nfunction findCycles(edges: number[][]): number[][] {\n const state = new Array<\"new\" | \"open\" | \"done\">(edges.length).fill(\"new\");\n const path: number[] = [];\n const cycles: number[][] = [];\n\n const visit = (node: number): void => {\n state[node] = \"open\";\n path.push(node);\n for (const next of edges[node] ?? []) {\n if (state[next] === \"open\") {\n cycles.push(path.slice(path.indexOf(next)));\n } else if (state[next] === \"new\") {\n visit(next);\n }\n }\n path.pop();\n state[node] = \"done\";\n };\n\n edges.forEach((_, node) => {\n if (state[node] === \"new\") visit(node);\n });\n return cycles;\n}\n", "import { z } from \"zod\";\nimport {\n DiffStat,\n GitSha,\n LineId,\n MissionId,\n MissionLimits,\n RunId,\n SafetyCheck,\n SeatId,\n SeatInfo,\n SeatRef,\n WorkRevision,\n} from \"./common.ts\";\nimport { PlanGraph } from \"./plan.ts\";\n\n/*\n * Every fact the daemon records is one of these events. Rules for changing this file:\n * - Adding a new event type is additive: old ledgers stay valid.\n * - Changing the shape of an existing type needs a new EVENT_VERSION and an upgrade path for stored events.\n * - Events carry no secrets and no raw logs: summaries, paths and numbers only.\n */\n\nexport const EVENT_VERSION = 1 as const;\n\nconst mission = { missionId: MissionId };\nconst run = { missionId: MissionId, runId: RunId };\n\nconst PlanAuthor = z.enum([\"lead\", \"user\"]);\nconst Phase = z.enum([\"reading\", \"coding\", \"testing\", \"reporting\"]);\nconst RepoPaths = z.array(z.string().min(1).max(1000)).max(1000);\n\nexport const SeatDetected = z.strictObject({\n type: z.literal(\"seat.detected\"),\n seat: SeatInfo,\n});\n\nexport const MissionCreated = z.strictObject({\n type: z.literal(\"mission.created\"),\n ...mission,\n goal: z.string().trim().min(1).max(4000),\n repo: z.strictObject({ root: z.string().min(1).max(1000), baseCommit: GitSha }),\n limits: MissionLimits,\n});\n\nexport const PlanProposed = z.strictObject({\n type: z.literal(\"plan.proposed\"),\n ...mission,\n plan: PlanGraph,\n by: PlanAuthor,\n note: z.string().max(2000).optional(),\n});\n\nexport const PlanRevised = z.strictObject({\n type: z.literal(\"plan.revised\"),\n ...mission,\n plan: PlanGraph,\n by: PlanAuthor,\n note: z.string().max(2000).optional(),\n});\n\nexport const SafetyReported = z\n .strictObject({\n type: z.literal(\"safety.report\"),\n ...mission,\n /** Which plan revision this report describes. A newer plan makes it stale, never current. */\n planRevision: z.int().positive(),\n ok: z.boolean(),\n checks: z.array(SafetyCheck).max(200),\n })\n .refine((report) => report.ok === report.checks.every((check) => check.ok || check.severity === \"warn\"), {\n message: \"ok must be true exactly when no blocking check failed\",\n path: [\"ok\"],\n });\n\nexport const RunQueued = z.strictObject({\n type: z.literal(\"run.queued\"),\n ...run,\n lineId: LineId,\n seat: SeatRef,\n attempt: z.int().min(1).max(3),\n});\n\nexport const RunStarted = z.strictObject({\n type: z.literal(\"run.started\"),\n ...run,\n workdir: z.string().min(1).max(1000),\n argv: z.array(z.string().max(200_000)).min(1).max(200),\n});\n\n/**\n * The agent's own name for this conversation, learned as soon as we have it.\n *\n * Recorded because rework depends on it: replying into the session that wrote a diff is worth far more than\n * re-explaining the work to a stranger who happens to share its model. Some CLIs let us choose the id before\n * launch and some announce it in their stream (ADR 0018); either way it is written down the moment it is known,\n * because the run most likely to need rework is the one that ended badly.\n */\nexport const RunSession = z.strictObject({\n type: z.literal(\"run.session\"),\n ...run,\n sessionId: z.string().trim().min(1).max(200),\n});\n\nexport const RunProgress = z.strictObject({\n type: z.literal(\"run.progress\"),\n ...run,\n phase: Phase,\n detail: z.string().max(500).optional(),\n});\n\nexport const RunTool = z.strictObject({\n type: z.literal(\"run.tool\"),\n ...run,\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n files: RepoPaths.default([]),\n});\n\nexport const RunUsage = z.strictObject({\n type: z.literal(\"run.usage\"),\n ...run,\n seat: SeatId,\n amount: z.number().nonnegative(),\n unit: z.enum([\"messages\", \"tokens\", \"minutes\"]),\n estimated: z.boolean(),\n});\n\nexport const RunFinished = z.strictObject({\n type: z.literal(\"run.finished\"),\n ...run,\n status: z.enum([\"done\", \"failed\", \"killed\", \"timeout\"]),\n exitCode: z.int().nullable(),\n reportPath: z.string().min(1).max(1000).optional(),\n diffStat: DiffStat.optional(),\n});\n\n/*\n * The merge gate, in events. Every one of them names the `revision` it judged, because each is a statement about a\n * specific diff and not about a worktree that may since have moved. A merge applies a revision only when review,\n * checks, proof and approval all named that same one; anything else is a claim about work nobody looked at.\n */\n\nexport const ReviewDone = z.strictObject({\n type: z.literal(\"review.done\"),\n ...run,\n revision: WorkRevision,\n verdict: z.enum([\"accept\", \"rework\", \"reject\"]),\n notes: z.string().max(20_000),\n by: SeatRef,\n});\n\nexport const ChecksDone = z.strictObject({\n type: z.literal(\"checks.done\"),\n ...run,\n revision: WorkRevision,\n ok: z.boolean(),\n summary: z.string().max(4000),\n /** What actually ran, so \"checks pass\" can be read as a claim about specific commands. */\n commands: z.array(z.string().min(1).max(500)).max(50),\n});\n\n/** Proof of a fix: the new tests that fail on the old code (and pass on the new). */\nexport const ProofDone = z\n .strictObject({\n type: z.literal(\"proof.done\"),\n ...run,\n revision: WorkRevision,\n ok: z.boolean(),\n failedOnOld: z.array(z.string().min(1).max(500)).max(500),\n })\n .refine((proof) => !proof.ok || proof.failedOnOld.length > 0, {\n message: \"a passing proof names at least one test that failed on the old code\",\n path: [\"failedOnOld\"],\n });\n\n/**\n * Someone said yes. Recorded separately from the merge itself so a replay can answer \"who authorised this?\" \u2014\n * a question a diff in the history cannot answer on its own.\n */\nexport const MergeApproved = z.strictObject({\n type: z.literal(\"merge.approved\"),\n ...run,\n revision: WorkRevision,\n /**\n * A person, or a policy the person wrote down in advance. A policy must name itself: \"it was pre-approved\" is\n * not an answer anyone can audit, and \"which rule, written when\" is.\n */\n by: z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"user\"),\n /**\n * How we know. This is the difference between a fact and an agent's account of one.\n *\n * `direct` \u2014 the daemon received the click itself, from the mission view, on this machine. Nothing in\n * between could have invented it.\n *\n * `relayed` \u2014 the lead says it asked and quoted the answer in `note`. That is a claim by a language model\n * about a conversation, and an agent that skipped the asking writes a byte-identical event. It is worth\n * recording and it is not worth confusing with the first one.\n *\n * Absent on events written before Fanout drew the distinction; read those as `relayed`.\n */\n via: z.enum([\"direct\", \"relayed\"]).optional(),\n }),\n z.strictObject({ kind: z.literal(\"policy\"), name: z.string().trim().min(1).max(200) }),\n ]),\n note: z.string().max(2000).optional(),\n});\n\nexport const MergeApplied = z.strictObject({\n type: z.literal(\"merge.applied\"),\n ...run,\n revision: WorkRevision,\n files: RepoPaths.min(1),\n /** Where the work landed, so a dependent line can start from it rather than from a guess. */\n commit: GitSha,\n});\n\nexport const MergeConflict = z.strictObject({\n type: z.literal(\"merge.conflict\"),\n ...run,\n revision: WorkRevision,\n files: RepoPaths.min(1),\n});\n\nexport const RunDropped = z.strictObject({\n type: z.literal(\"run.dropped\"),\n ...run,\n reason: z.string().trim().min(1).max(2000),\n});\n\n/**\n * A second vendor read the lead's own uncommitted work.\n *\n * Not a mission and not a run: no agent worked in a worktree, and forcing this into the mission machinery would\n * put a fake mission in front of the user for every review. It carries no `missionId` for the same reason\n * `seat.detected` does not \u2014 it is a fact about this machine at a moment, not about a mission.\n *\n * This is the event that answers the product's only real question: was anything other than the author's own\n * judgement applied to this code before it was called done?\n */\nexport const BuddyReviewed = z.strictObject({\n type: z.literal(\"buddy.reviewed\"),\n /** Which working tree, so a review of one repository is never read as covering another. */\n repoRoot: z.string().min(1).max(1000),\n revision: WorkRevision,\n by: SeatRef,\n /** What it said, verbatim. A second opinion summarised by the author is not a second opinion. */\n findings: z.string().max(100_000),\n /** False when the reviewer could not be run at all, so \"no findings\" never stands in for \"never asked\". */\n ran: z.boolean(),\n files: RepoPaths.max(1000),\n});\n\n/**\n * The lead wrote down what it believes, and a cold reader checked each belief against the code.\n *\n * This is the sharpest thing a second vendor can do, and the cheapest. The lead carries the whole session \u2014 the\n * plan, the reasoning, the justification \u2014 and that context is precisely what makes its own mistakes invisible to\n * it: it knows why the code is right, so the code looks right. A reader arriving with only the diff is not\n * smarter, it is differently placed, which is why even a small model reading cold can refute a large one reading\n * warm. Asking it to review everything spends tokens on that asymmetry. Asking it to falsify three specific\n * claims spends almost none.\n *\n * Recording the claims, not only the verdicts, is the point. A replay shows what the lead asserted as well as\n * what turned out to be true, and an author who must write down falsifiable claims notices the weak ones while\n * writing them.\n */\nexport const ClaimsChecked = z.strictObject({\n type: z.literal(\"claims.checked\"),\n repoRoot: z.string().min(1).max(1000),\n revision: WorkRevision,\n by: SeatRef,\n claims: z\n .array(\n z.strictObject({\n /** What the lead asserted, in its own words. */\n claim: z.string().trim().min(1).max(500),\n /**\n * `unclear` is the default and the only safe absence. A verdict we could not read is not a pass, and a\n * claim the reader ignored has not been checked \u2014 treating either as confirmed would make this theatre.\n */\n verdict: z.enum([\"confirmed\", \"refuted\", \"unclear\"]),\n /** Why, in the reader's own words. Required for a refusal; a bare \"no\" helps nobody. */\n evidence: z.string().max(4000),\n }),\n )\n .min(1)\n .max(20),\n /** False when the reader could not be run at all, so \"nothing refuted\" never stands in for \"never asked\". */\n ran: z.boolean(),\n /**\n * True when these verdicts were written by us rather than read by anyone \u2014 the offline demo, and nothing else.\n *\n * It exists so that the one thing the demo cannot do honestly is labelled everywhere it appears instead of\n * being quietly indistinguishable from a real answer. Inventing a second opinion and presenting it as read\n * would be faking the only claim this product makes.\n */\n simulated: z.boolean().default(false),\n});\n\n/**\n * A seat said it has run out, in its own words.\n *\n * Not mission-scoped: a limit belongs to the account, not to whatever happened to be running when it was hit.\n * The message is kept verbatim because \"you have reached your usage limit\" and \"rate limited, retry in 30s\" are\n * different problems and only the vendor knows which one this is.\n */\nexport const SeatLimited = z.strictObject({\n type: z.literal(\"seat.limited\"),\n seat: SeatId,\n message: z.string().trim().min(1).max(500),\n /** When the seat says it will work again. Absent when it did not say, which is usually. */\n resetsAt: z.iso.datetime().optional(),\n});\n\n/**\n * How full one of a seat's quota windows is, when the CLI reports it rather than us guessing.\n *\n * Claude Code is the only seat that says this today, per turn, for its five-hour and seven-day windows. It is the\n * difference between routing on facts and routing on arithmetic we made up, so it is recorded as what it is \u2014\n * real, and belonging to a named window \u2014 rather than flattened into a token count that would read as estimated.\n */\nexport const SeatQuota = z.strictObject({\n type: z.literal(\"seat.quota\"),\n seat: SeatId,\n window: z.string().min(1).max(50),\n /** 0.28 means 28% of that window is used. */\n utilization: z.number().min(0).max(1),\n resetsAt: z.iso.datetime().optional(),\n});\n\nexport const RouteChanged = z.strictObject({\n type: z.literal(\"route.changed\"),\n ...mission,\n lineId: LineId,\n from: SeatRef,\n to: SeatRef,\n reason: z.string().trim().min(1).max(500),\n});\n\nexport const PolicyBreach = z.strictObject({\n type: z.literal(\"policy.breach\"),\n ...run,\n limit: z.string().min(1).max(100),\n action: z.enum([\"killed\", \"paused\", \"asked\"]),\n});\n\nexport const MissionFinished = z.strictObject({\n type: z.literal(\"mission.finished\"),\n ...mission,\n outcome: z.enum([\"completed\", \"aborted\"]),\n summary: z.string().max(8000),\n});\n\nexport const FanoutEvent = z.discriminatedUnion(\"type\", [\n SeatDetected,\n MissionCreated,\n PlanProposed,\n PlanRevised,\n SafetyReported,\n RunQueued,\n RunStarted,\n RunSession,\n RunProgress,\n RunTool,\n RunUsage,\n RunFinished,\n ReviewDone,\n ChecksDone,\n ProofDone,\n BuddyReviewed,\n ClaimsChecked,\n MergeApproved,\n MergeApplied,\n MergeConflict,\n RunDropped,\n SeatLimited,\n SeatQuota,\n RouteChanged,\n PolicyBreach,\n MissionFinished,\n]);\n\n/** An event as validated (defaults applied). */\nexport type FanoutEvent = z.infer<typeof FanoutEvent>;\n/** An event as written by a producer (defaults may be omitted). */\nexport type FanoutEventInput = z.input<typeof FanoutEvent>;\nexport type EventType = FanoutEvent[\"type\"];\nexport type EventOf<T extends EventType> = Extract<FanoutEvent, { type: T }>;\n\n/** What the ledger adds when it records an event. */\nexport const EventStamp = z.strictObject({\n v: z.literal(EVENT_VERSION),\n id: z.uuid(),\n seq: z.int().positive(),\n ts: z.iso.datetime(),\n});\nexport type EventStamp = z.infer<typeof EventStamp>;\n\n/** An event as stored in and read from the ledger. */\nexport type StoredEvent = FanoutEvent & EventStamp;\n", "import { z } from \"zod\";\nimport { SeatId } from \"./common.ts\";\n\n/*\n * What an adapter declares about its CLI, as data rather than code: the versions it was verified against, the exact\n * non-interactive invocation, how to read its output, the safest modes it offers, how to ask it whether it is signed\n * in, and when its vendor's terms were last reviewed.\n *\n * A manifest is a promise we can check. A CLI outside `supportedVersions` is reported as an unsupported version\n * rather than driven on a guess, because a stream we have not seen is a stream we cannot parse honestly.\n */\n\n/** A placeholder the supervisor fills in: {workdir}, {prompt}, {report}, {sandbox}, {model}, {effort}, {session}. */\nconst ArgTemplate = z.string().min(1).max(500);\n\n/**\n * A regular expression a manifest asks us to run, checked at parse time rather than at the moment we need it.\n *\n * A pattern that does not compile throws from `new RegExp`, and that throw would happen deep inside detection,\n * where it takes down the whole crew's result and not just the seat that declared it. Refusing the manifest is\n * both earlier and louder. (This does not make a pattern *fast*: see `matches` in the detector for that half.)\n */\nconst SafePattern = z.string().max(200).refine(compiles, { message: \"must be a valid regular expression\" });\n\nfunction compiles(pattern: string): boolean {\n try {\n new RegExp(pattern, \"i\");\n return true;\n } catch {\n return false;\n }\n}\n\nexport const AdapterManifest = z.strictObject({\n id: SeatId,\n displayName: z.string().min(1).max(80),\n binary: z.string().min(1).max(200),\n /** A semver range, e.g. \">=0.150 <1.0\". Outside it, the seat is unsupported, never guessed at. */\n supportedVersions: z.string().min(1).max(100),\n /** What we promise about this seat, never a judgment of the CLI's quality. */\n tier: z.enum([\"supported\", \"community\", \"reference\"]),\n\n /** Null means no such mode or none verified: the merge gate must never act on a guess. */\n capabilities: z.strictObject({\n resume: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n fork: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n review: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n /**\n * An allowlist keeps account identity out of storage. A privacy promise that is data can be reviewed in a pull\n * request; a promise in adapter code has to be re-read every time.\n */\n plan: z\n .strictObject({\n probe: z.array(z.string().min(1).max(100)).min(1).max(10),\n format: z.literal(\"json\"),\n keep: z.array(z.string().min(1).max(100)).min(1).max(5),\n planField: z.string().min(1).max(100),\n })\n .refine((plan) => plan.keep.includes(plan.planField), {\n message: \"planField must be one of keep\",\n path: [\"planField\"],\n })\n .nullable(),\n }),\n\n headless: z.strictObject({\n args: z.array(ArgTemplate).min(1).max(50),\n /** Always closed: a CLI waiting on stdin is the most common way a run hangs forever. */\n stdin: z.literal(\"closed\"),\n }),\n\n stream: z.strictObject({\n /** The flag that turns on machine-readable output, or null when the CLI has none. */\n flag: z.string().max(100).nullable(),\n format: z.enum([\"jsonl\", \"text\"]),\n }),\n\n models: z.array(z.string().min(1).max(100)).max(100),\n efforts: z.array(z.string().min(1).max(40)).max(20),\n\n /** The flag value for each mode we use. Auditors get the read-only one; nothing else is ever passed. */\n permissionModes: z.strictObject({\n readOnly: z.string().min(1).max(100),\n edit: z.string().min(1).max(100),\n }),\n\n network: z.strictObject({\n canDisable: z.boolean(),\n flag: z.string().max(100).nullable(),\n }),\n\n /**\n * How to ask the CLI itself whether it is signed in. We never read credential files.\n *\n * Both answers are named, because only one of them can be inferred from the other's absence and neither\n * actually is: a probe that fails, times out or answers something unforeseen has told us nothing, and\n * \"nothing\" must stay \"unknown\" rather than becoming a \"no\" that quietly reroutes someone's work.\n */\n signIn: z.strictObject({\n probe: z.array(z.string().min(1).max(100)).max(10).nullable(),\n /** A pattern the probe's output must match to count as signed in. */\n okPattern: SafePattern.nullable(),\n /** A pattern that positively means signed out. Checked first, so \"Not logged in\" cannot match \"Logged in\". */\n noPattern: SafePattern.nullable(),\n }),\n\n /** Real usage when the CLI reports it; otherwise we estimate and say so. */\n usage: z.strictObject({\n probe: z.array(z.string().min(1).max(100)).max(10).nullable(),\n window: z.string().max(100),\n }),\n\n /** Which pool this seat's headless use bills against, so a vendor's policy change is a manifest change. */\n billing: z.enum([\"subscription\", \"credit\", \"api\", \"unknown\"]),\n\n terms: z.strictObject({\n reviewedAt: z.iso.date().nullable(),\n notes: z.string().max(2000),\n }),\n\n status: z.enum([\"planned\", \"research\", \"alpha\", \"stable\"]),\n});\nexport type AdapterManifest = z.infer<typeof AdapterManifest>;\n", "import { z } from \"zod\";\nimport { SeatId, type SeatInfo } from \"./common.ts\";\n\n/*\n * What the owner wants done with each seat, kept apart from what is true of it today.\n *\n * Posture is a preference and availability is a fact, and mixing them produces a interface that lies in both\n * directions: a seat you rely on looks disabled the morning its CLI fails to start, and a seat you asked us never\n * to touch looks ready the moment it signs in. They are resolved together only at the point of use, in `stanceFor`.\n *\n * This file holds only what the owner declared. It is never a cache of anything detected: a subscription tier\n * written down in June and read back in September is a stale answer presented as a current fact, and the whole\n * point of the `source` on a plan is that a reader can tell those apart.\n */\n\n/**\n * How willingly Fanout should spend a seat.\n *\n * - `preferred` \u2014 reach for this first when several seats could do the line.\n * - `normal` \u2014 use it when the plan calls for it.\n * - `sparing` \u2014 only when nothing else fits, and say so before launching. For the subscription you pay least for.\n * - `off` \u2014 never, until the owner says otherwise.\n */\nexport const SeatPosture = z.enum([\"preferred\", \"normal\", \"sparing\", \"off\"]);\nexport type SeatPosture = z.infer<typeof SeatPosture>;\n\nexport const SeatPolicy = z.strictObject({\n version: z.literal(1),\n seats: z.record(\n SeatId,\n z.strictObject({\n posture: SeatPosture,\n /** The owner's own words about why, shown back to them so a past decision explains itself. */\n note: z.string().max(200).optional(),\n }),\n ),\n});\nexport type SeatPolicy = z.infer<typeof SeatPolicy>;\n\nexport const EMPTY_POLICY: SeatPolicy = { version: 1, seats: {} };\n\n/**\n * Claude is the only seat that is off until asked for.\n *\n * The lead already runs on this subscription, so a Claude worker spends the same window the session you are sitting\n * in is spending. That is a decision about someone's money, and it is theirs to make deliberately rather than to\n * discover afterwards (DECISIONS 0009).\n */\nconst OPT_IN_SEATS: ReadonlySet<string> = new Set([\"claude\"]);\n\nexport interface SeatStance {\n posture: SeatPosture;\n /** `declared` when the owner set it; `default` when nobody has, and `reason` says why that default. */\n source: \"declared\" | \"default\";\n reason: string;\n /** Willing *and* able: the posture allows it and the CLI is actually there and signed in. */\n usable: boolean;\n note?: string;\n}\n\n/**\n * What we should do with one seat right now, given what the owner declared and what detection found.\n *\n * Deliberately not clever. We know a plan's *name*, never its price, so nothing here infers that \"pro\" is cheaper\n * than \"max\" or that an unknown plan is a small one \u2014 the one fact only the owner has is which subscription they\n * would rather not spend, and the only honest way to learn it is to be told.\n */\nexport function stanceFor(seat: SeatInfo, policy: SeatPolicy): SeatStance {\n const declared = Object.hasOwn(policy.seats, seat.id) ? policy.seats[seat.id] : undefined;\n const posture: SeatPosture = declared?.posture ?? (OPT_IN_SEATS.has(seat.id) ? \"off\" : \"normal\");\n\n const reason =\n declared !== undefined\n ? \"you set this\"\n : OPT_IN_SEATS.has(seat.id)\n ? \"opt-in: a worker here spends the same subscription your session is running on\"\n : \"nobody has said otherwise\";\n\n return {\n posture,\n source: declared === undefined ? \"default\" : \"declared\",\n reason,\n usable: posture !== \"off\" && seat.supported && seat.signedIn === \"yes\",\n ...(declared?.note === undefined ? {} : { note: declared.note }),\n };\n}\n\n/** The seats a mission may draw on, most willing first, so a planner can take the head of the list. */\nexport function usableSeats(seats: readonly SeatInfo[], policy: SeatPolicy): SeatInfo[] {\n const rank: Record<SeatPosture, number> = { preferred: 0, normal: 1, sparing: 2, off: 3 };\n return seats\n .filter((seat) => stanceFor(seat, policy).usable)\n .sort((a, b) => rank[stanceFor(a, policy).posture] - rank[stanceFor(b, policy).posture]);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { chmodSync, closeSync, mkdirSync, openSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { DatabaseSync, type StatementSync } from \"node:sqlite\";\nimport { z } from \"zod\";\nimport {\n EVENT_VERSION,\n EventStamp,\n FanoutEvent,\n type FanoutEventInput,\n type StoredEvent,\n} from \"../schema/events.ts\";\n\n/*\n * The ledger is the single source of truth: an append-only SQLite table of validated events.\n * Append-only is enforced by the database, not just by this API: triggers abort any UPDATE, any DELETE, and any\n * INSERT that would replace an existing row (INSERT OR REPLACE deletes the old row without firing DELETE triggers).\n * This guards against rewriting history with ordinary SQL. It is not a defense against someone with raw access to\n * the file: they own it, and `DROP TABLE` or replacing a trigger would still succeed. Opening checks the guards exist.\n * Every row is validated on the way in and again on the way out, so a damaged ledger fails loudly.\n */\n\nconst SCHEMA_VERSION = 1;\n\nconst SCHEMA_V1 = `\nCREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n ts TEXT NOT NULL,\n v INTEGER NOT NULL,\n type TEXT NOT NULL,\n mission_id TEXT,\n run_id TEXT,\n body TEXT NOT NULL CHECK (json_valid(body))\n) STRICT;\nCREATE INDEX IF NOT EXISTS events_by_mission ON events (mission_id, seq);\nCREATE TRIGGER IF NOT EXISTS events_no_update BEFORE UPDATE ON events\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\nCREATE TRIGGER IF NOT EXISTS events_no_delete BEFORE DELETE ON events\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\nCREATE TRIGGER IF NOT EXISTS events_no_replace BEFORE INSERT ON events\n WHEN EXISTS (SELECT 1 FROM events WHERE seq = NEW.seq OR id = NEW.id)\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\n`;\n\nconst GUARD_TRIGGERS = [\"events_no_update\", \"events_no_delete\", \"events_no_replace\"] as const;\n\nexport class LedgerError extends Error {\n override name = \"LedgerError\";\n}\n\n/** An event that does not match the schema. Nothing was written. */\nexport class InvalidEventError extends LedgerError {\n override name = \"InvalidEventError\";\n readonly index: number;\n\n constructor(index: number, detail: string) {\n super(`Event ${index} is invalid, nothing was written:\\n${detail}`);\n this.index = index;\n }\n}\n\n/** A ledger or an event written by a newer Fanout. We refuse to guess at it. */\nexport class UnsupportedLedgerError extends LedgerError {\n override name = \"UnsupportedLedgerError\";\n}\n\nexport interface LedgerOptions {\n /** Clock for event timestamps (tests inject a fixed one). */\n now?: () => Date;\n /** Event id generator; must return UUIDs. */\n newId?: () => string;\n /**\n * Called once per event, after it is committed, so a live feed never shows something the ledger might roll back.\n * Whatever it throws is ignored: a listener must not be able to break the record.\n */\n onAppend?: (event: StoredEvent) => void;\n}\n\nexport interface ReadOptions {\n /** Only events with a larger sequence number. */\n afterSeq?: number;\n /** Only events of this mission. */\n missionId?: string;\n /** At most this many events. */\n limit?: number;\n}\n\nconst Row = z.object({\n seq: z.number(),\n id: z.string(),\n ts: z.string(),\n v: z.number(),\n type: z.string(),\n mission_id: z.string().nullable(),\n run_id: z.string().nullable(),\n body: z.string(),\n});\n\nexport class Ledger {\n readonly #db: DatabaseSync;\n readonly #now: () => Date;\n readonly #newId: () => string;\n readonly #onAppend: ((event: StoredEvent) => void) | undefined;\n readonly #insert: StatementSync;\n readonly #readAll: StatementSync;\n readonly #readMission: StatementSync;\n readonly #lastSeq: StatementSync;\n\n private constructor(db: DatabaseSync, options: LedgerOptions) {\n this.#db = db;\n this.#now = options.now ?? (() => new Date());\n this.#newId = options.newId ?? randomUUID;\n this.#onAppend = options.onAppend;\n this.#insert = db.prepare(\n \"INSERT INTO events (id, ts, v, type, mission_id, run_id, body) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n );\n this.#readAll = db.prepare(\n \"SELECT seq, id, ts, v, type, mission_id, run_id, body FROM events WHERE seq > ? ORDER BY seq LIMIT ?\",\n );\n this.#readMission = db.prepare(\n \"SELECT seq, id, ts, v, type, mission_id, run_id, body FROM events \" +\n \"WHERE seq > ? AND mission_id = ? ORDER BY seq LIMIT ?\",\n );\n this.#lastSeq = db.prepare(\"SELECT COALESCE(MAX(seq), 0) AS seq FROM events\");\n }\n\n /**\n * Opens (or creates) a ledger. Use \":memory:\" for a throwaway one. On disk, the file is private to the user\n * (mode 600, directory 700).\n */\n static open(path: string, options: LedgerOptions = {}): Ledger {\n const onDisk = path !== \":memory:\";\n if (onDisk) {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n closeSync(openSync(path, \"a\", 0o600));\n chmodSync(path, 0o600);\n }\n const db = new DatabaseSync(path);\n try {\n db.exec(\"PRAGMA busy_timeout = 5000\");\n if (onDisk) db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA synchronous = FULL\");\n migrate(db);\n return new Ledger(db, options);\n } catch (error) {\n db.close();\n throw error;\n }\n }\n\n /** Validates and records one event; returns it with its stamp. */\n append(input: FanoutEventInput): StoredEvent {\n const [stored] = this.appendAll([input]);\n if (stored === undefined) throw new LedgerError(\"append recorded nothing\");\n return stored;\n }\n\n /** Validates every event first, then records them all in one transaction, or none of them. */\n appendAll(inputs: readonly FanoutEventInput[]): StoredEvent[] {\n const events = inputs.map((input, index) => {\n const result = FanoutEvent.safeParse(input);\n if (!result.success) throw new InvalidEventError(index, z.prettifyError(result.error));\n return result.data;\n });\n\n this.#db.exec(\"BEGIN IMMEDIATE\");\n try {\n const stored = events.map((event): StoredEvent => {\n const stamp = EventStamp.omit({ seq: true }).parse({\n v: EVENT_VERSION,\n id: this.#newId(),\n ts: this.#now().toISOString(),\n });\n const result = this.#insert.run(\n stamp.id,\n stamp.ts,\n stamp.v,\n event.type,\n \"missionId\" in event ? event.missionId : null,\n \"runId\" in event ? event.runId : null,\n JSON.stringify(event),\n );\n return { ...event, ...stamp, seq: Number(result.lastInsertRowid) };\n });\n this.#db.exec(\"COMMIT\");\n for (const event of stored) {\n try {\n this.#onAppend?.(event);\n } catch {\n // A listener that throws has a problem of its own; the record is already safe.\n }\n }\n return stored;\n } catch (error) {\n this.#db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n /** Events in sequence order. */\n read(options: ReadOptions = {}): StoredEvent[] {\n const afterSeq = options.afterSeq ?? 0;\n const limit = options.limit ?? -1;\n const rows =\n options.missionId === undefined\n ? this.#readAll.all(afterSeq, limit)\n : this.#readMission.all(afterSeq, options.missionId, limit);\n return rows.map(decode);\n }\n\n /** The sequence number of the last event, or 0 for an empty ledger. */\n lastSeq(): number {\n const row = this.#lastSeq.get();\n return Number(row?.[\"seq\"] ?? 0);\n }\n\n /**\n * Whether this ledger can still be written to.\n *\n * A daemon shutting down closes the ledger while runs may still be in flight, and a process that exits a moment\n * later tries to record how it ended. That is expected, not exceptional, and a caller needs to be able to tell\n * it apart from a ledger that has actually broken \u2014 one means \"we are going away\", the other means \"stop the\n * run, we can no longer record what it is doing\".\n */\n get isOpen(): boolean {\n return this.#db.isOpen;\n }\n\n /** Idempotent: closing twice is what happens when shutdown and a test's cleanup both do the right thing. */\n close(): void {\n if (this.#db.isOpen) this.#db.close();\n }\n}\n\nfunction migrate(db: DatabaseSync): void {\n const version = userVersion(db);\n if (version > SCHEMA_VERSION) {\n throw new UnsupportedLedgerError(\n `This ledger was written by a newer Fanout (schema ${version}; this one reads ${SCHEMA_VERSION}). ` +\n \"Update Fanout to open it.\",\n );\n }\n if (version < SCHEMA_VERSION) {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n if (userVersion(db) < SCHEMA_VERSION) {\n db.exec(SCHEMA_V1);\n db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);\n }\n db.exec(\"COMMIT\");\n } catch (error) {\n db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n const triggers = new Set(\n db\n .prepare(\"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'events'\")\n .all()\n .map((row) => String(row[\"name\"])),\n );\n const missing = GUARD_TRIGGERS.filter((name) => !triggers.has(name));\n if (missing.length > 0) {\n throw new LedgerError(\n `This ledger lost its append-only guard (${missing.join(\", \")}); refusing to use it.`,\n );\n }\n}\n\nfunction userVersion(db: DatabaseSync): number {\n return Number(db.prepare(\"PRAGMA user_version\").get()?.[\"user_version\"] ?? 0);\n}\n\nfunction decode(raw: unknown): StoredEvent {\n const row = Row.parse(raw);\n if (row.v !== EVENT_VERSION) {\n throw new UnsupportedLedgerError(\n `Event ${row.seq} has version ${row.v}; this Fanout reads version ${EVENT_VERSION}. Update Fanout to read it.`,\n );\n }\n let body: unknown;\n try {\n body = JSON.parse(row.body);\n } catch {\n throw new LedgerError(`Event ${row.seq} is not valid JSON; the ledger is damaged.`);\n }\n const event = FanoutEvent.safeParse(body);\n const stamp = EventStamp.safeParse({ v: row.v, id: row.id, seq: row.seq, ts: row.ts });\n if (!event.success || !stamp.success) {\n const detail = event.error ?? stamp.error;\n throw new LedgerError(\n `Event ${row.seq} does not match the schema; the ledger is damaged.` +\n (detail === undefined ? \"\" : `\\n${z.prettifyError(detail)}`),\n );\n }\n\n // The indexed columns are how events are found; if they disagree with the body, queries would silently lie.\n const routed =\n row.type === event.data.type &&\n row.mission_id === (\"missionId\" in event.data ? event.data.missionId : null) &&\n row.run_id === (\"runId\" in event.data ? event.data.runId : null);\n if (!routed) {\n throw new LedgerError(\n `Event ${row.seq} is indexed as ${row.type} (mission ${row.mission_id ?? \"none\"}, ` +\n `run ${row.run_id ?? \"none\"}) but its body says otherwise; the ledger is damaged.`,\n );\n }\n\n return { ...event.data, ...stamp.data };\n}\n", "import type { DiffStat, MissionLimits, SafetyCheck, SeatInfo, SeatRef } from \"../schema/common.ts\";\nimport type { EventOf, StoredEvent } from \"../schema/events.ts\";\nimport type { PlanGraph } from \"../schema/plan.ts\";\n\n/*\n * Projections are pure folds over the ledger: state(n + 1) = applyEvent(state(n), event n + 1).\n * They never mutate their input, so any intermediate state can be kept, compared or sent to a client.\n * An event that doesn't fit (an unknown mission or run, a duplicate, a sequence out of order) is recorded as an\n * anomaly instead of being silently dropped or crashing the view.\n */\n\nexport type RunPhase = EventOf<\"run.progress\">[\"phase\"];\nexport type UsageUnit = EventOf<\"run.usage\">[\"unit\"];\nexport type RunStatus =\n \"queued\" | \"running\" | \"done\" | \"failed\" | \"killed\" | \"timeout\" | \"merged\" | \"conflict\" | \"dropped\";\n\nexport interface UsageMeter {\n amount: number;\n /** True when any part of the amount is an estimate. */\n estimated: boolean;\n}\nexport type UsageMeters = Partial<Record<UsageUnit, UsageMeter>>;\n\nexport interface RunView {\n runId: string;\n lineId: string;\n seat: SeatRef;\n attempt: number;\n status: RunStatus;\n phase: RunPhase | null;\n /** The agent's own name for this conversation, once it is known. Rework resumes it rather than starting over. */\n sessionId: string | null;\n /**\n * Where the run actually worked, as it reported when it started.\n *\n * Kept rather than derived from the run id, because a reworked run continues in the worktree of the attempt\n * before it \u2014 so the convention `workspaces/<mission>/<runId>` is wrong for exactly the runs that most need\n * finding. A recorded fact beats a naming rule the moment anything reuses anything.\n */\n workdir: string | null;\n /**\n * The seat the plan asked for, when it is not the seat that ran \u2014 with the reason in the words the router used.\n *\n * Carried on the run rather than left on the mission because everything that shows a run needs it. A row saying\n * `claude` under a plan that said `codex`, with nothing to explain the difference, is the kind of silent\n * substitution that makes someone stop trusting the whole screen.\n */\n movedFrom: { seat: string; reason: string } | null;\n lastTool: { tool: string; summary: string | null } | null;\n /** Files the run touched, sorted, without duplicates. */\n files: string[];\n diffStat: DiffStat | null;\n exitCode: number | null;\n usage: UsageMeters;\n /*\n * Each step of the gate remembers the revision it judged. A merge that applies a different one is applying work\n * nobody in this list actually looked at, which is the single failure the gate exists to prevent.\n */\n review: { verdict: EventOf<\"review.done\">[\"verdict\"]; notes: string; by: SeatRef; revision: string } | null;\n checks: { ok: boolean; summary: string; commands: string[]; revision: string } | null;\n proof: { ok: boolean; failedOnOld: string[]; revision: string } | null;\n approval: { by: EventOf<\"merge.approved\">[\"by\"]; revision: string; note: string | null } | null;\n /** What was merged, and where it landed, so a dependent line can start from a fact. */\n merged: { revision: string; commit: string } | null;\n mergedFiles: string[];\n conflictFiles: string[];\n dropReason: string | null;\n breaches: { limit: string; action: EventOf<\"policy.breach\">[\"action\"] }[];\n queuedSeq: number;\n startedSeq: number | null;\n updatedSeq: number;\n /* The three moments a watcher asks about. Stamped by the ledger, never computed here: see `elapsedMs`. */\n queuedAt: string;\n startedAt: string | null;\n /** When the agent's own work stopped. Review, merge and drop happen after this and do not move it. */\n endedAt: string | null;\n /** The last time this run produced any event at all: its most recent sign of life. */\n updatedAt: string;\n}\n\n/**\n * How long a run has been working, in milliseconds, or `null` if it has not started \u2014 never `0`, because\n * \"not started\" and \"started a moment ago\" are different facts and a watcher deserves to know which.\n *\n * A finished run is measured between its own two stamps, so its duration never changes after the fact. A running\n * one is measured against `now`, so a slow run is visibly slow rather than indistinguishable from a stuck one.\n * That is why the projection stores stamps and not a duration: a stored elapsed time is stale the moment it is read.\n *\n * A clock that has moved backwards (an NTP correction, a laptop waking) clamps to 0 rather than showing a negative\n * age, since a run cannot have started in the future.\n */\nexport function elapsedMs(run: RunView, now: Date): number | null {\n if (run.startedAt === null) return null;\n const from = Date.parse(run.startedAt);\n const to = run.endedAt === null ? now.getTime() : Date.parse(run.endedAt);\n return Math.max(0, to - from);\n}\n\n/**\n * How long a still-running run has said nothing, in milliseconds, or `null` once it has ended \u2014 a finished run is\n * not silent, it is simply over.\n *\n * Elapsed time alone cannot tell a thinking agent from a dead one: both counters climb. The gap since the last\n * event can, which makes this the number worth putting in front of someone deciding whether to wait or to kill.\n *\n * Only a run that is actually working can be silent. A queued run has not been launched and a finished one is\n * simply over; reporting either as \"quiet for 30 minutes\" would raise an alarm about the scheduler doing its job.\n */\nexport function silentMs(run: RunView, now: Date): number | null {\n if (run.startedAt === null || run.endedAt !== null) return null;\n return Math.max(0, now.getTime() - Date.parse(run.updatedAt));\n}\n\nexport interface RouteChange {\n lineId: string;\n from: SeatRef;\n to: SeatRef;\n reason: string;\n seq: number;\n}\n\nexport interface MissionView {\n missionId: string;\n goal: string;\n repo: { root: string; baseCommit: string };\n limits: MissionLimits;\n status: \"planning\" | \"running\" | \"finished\" | \"aborted\";\n plan: PlanGraph | null;\n /** 0 before any plan, then 1, 2, \u2026 for each proposal or revision. */\n planRevision: number;\n /** The safety report for the current plan revision; a new plan clears it, a stale one is refused. */\n safety: { ok: boolean; checks: SafetyCheck[]; planRevision: number } | null;\n runs: Record<string, RunView>;\n runOrder: string[];\n routes: RouteChange[];\n summary: string | null;\n createdSeq: number;\n updatedSeq: number;\n}\n\nexport interface Anomaly {\n seq: number;\n type: string;\n message: string;\n}\n\nexport interface BuddyReview {\n revision: string;\n by: SeatRef;\n findings: string;\n ran: boolean;\n files: string[];\n at: string;\n}\n\nexport interface ClaimCheck {\n revision: string;\n by: SeatRef;\n claims: EventOf<\"claims.checked\">[\"claims\"];\n ran: boolean;\n /** These verdicts were written, not read: the offline demo. Every surface that shows them must say so. */\n simulated: boolean;\n at: string;\n}\n\n/**\n * What a seat has said about its own capacity.\n *\n * `limited` is the seat refusing work; `windows` is how full its named quota windows are when it reports them.\n * Both are the vendor's words, never our arithmetic \u2014 a number we estimated and a number Claude Code measured\n * should never be mistaken for each other in a routing decision.\n */\nexport interface SeatHeadroom {\n limited: { message: string; at: string; resetsAt: string | null } | null;\n windows: Record<string, { utilization: number; resetsAt: string | null }>;\n}\n\nexport interface ProjectionState {\n lastSeq: number;\n crew: Record<string, SeatInfo>;\n /** Per seat, what it last said about running out. Empty for a seat that has never said anything. */\n headroom: Record<string, SeatHeadroom>;\n /** The most recent second-vendor review of the lead's own work, per repository root. */\n buddy: Record<string, BuddyReview>;\n /** The most recent claim check of the lead's own work, per repository root. */\n claims: Record<string, ClaimCheck>;\n usage: Record<string, UsageMeters>;\n missions: Record<string, MissionView>;\n anomalies: Anomaly[];\n}\n\nexport function initialState(): ProjectionState {\n return {\n lastSeq: 0,\n crew: {},\n headroom: {},\n buddy: {},\n claims: {},\n usage: {},\n missions: {},\n anomalies: [],\n };\n}\n\n/** Folds events into a state, starting from an empty one or from a state already projected. */\nexport function project(\n events: Iterable<StoredEvent>,\n from: ProjectionState = initialState(),\n): ProjectionState {\n let state = from;\n for (const event of events) state = applyEvent(state, event);\n return state;\n}\n\nexport function applyEvent(state: ProjectionState, event: StoredEvent): ProjectionState {\n if (event.seq <= state.lastSeq) {\n return withAnomaly(state, event, `sequence ${event.seq} arrived after ${state.lastSeq}; ignored`);\n }\n return { ...reduce(state, event), lastSeq: event.seq };\n}\n\nfunction reduce(state: ProjectionState, event: StoredEvent): ProjectionState {\n switch (event.type) {\n case \"seat.detected\":\n return { ...state, crew: { ...state.crew, [event.seat.id]: event.seat } };\n\n /*\n * Kept per repository and per revision rather than as a list. The only question anyone asks of it is \"has\n * *this* work been read by someone other than its author\", and a history of reviews of older work answers a\n * question nobody is asking while making the answer to this one harder to find.\n */\n /*\n * Kept per repository and per revision, like the buddy review, and for the same reason: the only question\n * anyone asks is what was checked about *this* work, and a history of verdicts on older work buries it.\n */\n case \"claims.checked\":\n return {\n ...state,\n claims: {\n ...state.claims,\n [event.repoRoot]: {\n revision: event.revision,\n by: event.by,\n claims: event.claims,\n ran: event.ran,\n simulated: event.simulated,\n at: event.ts,\n },\n },\n };\n\n /*\n * A seat's own account of its headroom, kept per seat rather than as a history. The only question anyone asks\n * is whether this seat can be used right now; a list of every limit it ever hit answers a different one and\n * buries this.\n */\n case \"seat.limited\":\n return {\n ...state,\n headroom: {\n ...state.headroom,\n [event.seat]: {\n ...(state.headroom[event.seat] ?? { windows: {} }),\n limited: { message: event.message, at: event.ts, resetsAt: event.resetsAt ?? null },\n },\n },\n };\n\n case \"seat.quota\":\n return {\n ...state,\n headroom: {\n ...state.headroom,\n [event.seat]: {\n ...(state.headroom[event.seat] ?? { limited: null }),\n windows: {\n ...(state.headroom[event.seat]?.windows ?? {}),\n [event.window]: { utilization: event.utilization, resetsAt: event.resetsAt ?? null },\n },\n },\n },\n };\n\n case \"buddy.reviewed\":\n return {\n ...state,\n buddy: {\n ...state.buddy,\n [event.repoRoot]: {\n revision: event.revision,\n by: event.by,\n findings: event.findings,\n ran: event.ran,\n files: event.files,\n at: event.ts,\n },\n },\n };\n\n case \"mission.created\": {\n if (Object.hasOwn(state.missions, event.missionId)) {\n return withAnomaly(state, event, `mission \"${event.missionId}\" already exists`);\n }\n const mission: MissionView = {\n missionId: event.missionId,\n goal: event.goal,\n repo: event.repo,\n limits: event.limits,\n status: \"planning\",\n plan: null,\n planRevision: 0,\n safety: null,\n runs: {},\n runOrder: [],\n routes: [],\n summary: null,\n createdSeq: event.seq,\n updatedSeq: event.seq,\n };\n return { ...state, missions: { ...state.missions, [event.missionId]: mission } };\n }\n\n case \"plan.proposed\":\n case \"plan.revised\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n plan: event.plan,\n planRevision: mission.planRevision + 1,\n safety: null,\n }));\n\n case \"safety.report\":\n return updateMission(state, event, (mission) =>\n event.planRevision === mission.planRevision\n ? { ...mission, safety: { ok: event.ok, checks: event.checks, planRevision: event.planRevision } }\n : `safety report is for plan revision ${event.planRevision}, ` +\n `but the mission is at revision ${mission.planRevision}`,\n );\n\n case \"route.changed\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n routes: [\n ...mission.routes,\n { lineId: event.lineId, from: event.from, to: event.to, reason: event.reason, seq: event.seq },\n ],\n }));\n\n case \"mission.finished\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n status: event.outcome === \"completed\" ? \"finished\" : \"aborted\",\n summary: event.summary,\n }));\n\n case \"run.queued\":\n return updateMission(state, event, (mission) => {\n if (Object.hasOwn(mission.runs, event.runId)) return `run \"${event.runId}\" already exists`;\n /*\n * The router records its decision before the run is queued, so the move for this line is already here.\n * The last one wins: a line reworked onto a third seat was moved twice, and the move that explains the\n * seat in front of you is the most recent one.\n */\n const moved = mission.routes.filter((change) => change.lineId === event.lineId).at(-1);\n const run: RunView = {\n runId: event.runId,\n lineId: event.lineId,\n seat: event.seat,\n attempt: event.attempt,\n status: \"queued\",\n phase: null,\n sessionId: null,\n workdir: null,\n movedFrom: moved?.to.id === event.seat.id ? { seat: moved.from.id, reason: moved.reason } : null,\n lastTool: null,\n files: [],\n diffStat: null,\n exitCode: null,\n usage: {},\n review: null,\n checks: null,\n proof: null,\n approval: null,\n merged: null,\n mergedFiles: [],\n conflictFiles: [],\n dropReason: null,\n breaches: [],\n queuedSeq: event.seq,\n startedSeq: null,\n updatedSeq: event.seq,\n queuedAt: event.ts,\n startedAt: null,\n endedAt: null,\n updatedAt: event.ts,\n };\n return {\n ...mission,\n status: mission.status === \"planning\" ? \"running\" : mission.status,\n runs: { ...mission.runs, [event.runId]: run },\n runOrder: [...mission.runOrder, event.runId],\n };\n });\n\n case \"run.started\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: \"running\",\n startedSeq: event.seq,\n startedAt: event.ts,\n workdir: event.workdir,\n }));\n\n case \"run.session\":\n return updateRun(state, event, (run) => ({ ...run, sessionId: event.sessionId }));\n\n case \"run.progress\":\n return updateRun(state, event, (run) => ({ ...run, phase: event.phase }));\n\n case \"run.tool\":\n return updateRun(state, event, (run) => ({\n ...run,\n lastTool: { tool: event.tool, summary: event.summary ?? null },\n files: sortedUnion(run.files, event.files),\n }));\n\n case \"run.usage\": {\n const next = updateRun(state, event, (run) =>\n run.seat.id === event.seat\n ? { ...run, usage: addUsage(run.usage, event) }\n : `usage is charged to seat \"${event.seat}\" but run \"${event.runId}\" is on \"${run.seat.id}\"`,\n );\n if (next.anomalies.length > state.anomalies.length) return next;\n return {\n ...next,\n usage: { ...next.usage, [event.seat]: addUsage(next.usage[event.seat] ?? {}, event) },\n };\n }\n\n case \"run.finished\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: event.status,\n exitCode: event.exitCode,\n diffStat: event.diffStat ?? run.diffStat,\n endedAt: event.ts,\n }));\n\n case \"review.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n review: { verdict: event.verdict, notes: event.notes, by: event.by, revision: event.revision },\n }));\n\n case \"checks.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n checks: {\n ok: event.ok,\n summary: event.summary,\n commands: event.commands,\n revision: event.revision,\n },\n }));\n\n case \"proof.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n proof: { ok: event.ok, failedOnOld: event.failedOnOld, revision: event.revision },\n }));\n\n case \"merge.approved\":\n return updateRun(state, event, (run) => ({\n ...run,\n approval: { by: event.by, revision: event.revision, note: event.note ?? null },\n }));\n\n case \"merge.applied\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: \"merged\",\n mergedFiles: event.files,\n merged: { revision: event.revision, commit: event.commit },\n }));\n\n case \"merge.conflict\":\n return updateRun(state, event, (run) => ({ ...run, status: \"conflict\", conflictFiles: event.files }));\n\n case \"run.dropped\":\n return updateRun(state, event, (run) => ({ ...run, status: \"dropped\", dropReason: event.reason }));\n\n case \"policy.breach\":\n return updateRun(state, event, (run) => ({\n ...run,\n breaches: [...run.breaches, { limit: event.limit, action: event.action }],\n }));\n }\n}\n\n/** Applies `change` to the event's mission; a returned string is recorded as an anomaly instead. */\nfunction updateMission(\n state: ProjectionState,\n event: StoredEvent & { missionId: string },\n change: (mission: MissionView) => MissionView | string,\n): ProjectionState {\n const mission = Object.hasOwn(state.missions, event.missionId)\n ? state.missions[event.missionId]\n : undefined;\n if (mission === undefined) return withAnomaly(state, event, `unknown mission \"${event.missionId}\"`);\n const next = change(mission);\n if (typeof next === \"string\") return withAnomaly(state, event, next);\n return { ...state, missions: { ...state.missions, [event.missionId]: { ...next, updatedSeq: event.seq } } };\n}\n\n/** A run that merged or was dropped is finished for good; later run events are anomalies, not a second life. */\nconst TERMINAL: ReadonlySet<RunStatus> = new Set<RunStatus>([\"merged\", \"dropped\"]);\n\nfunction updateRun(\n state: ProjectionState,\n event: StoredEvent & { missionId: string; runId: string },\n change: (run: RunView) => RunView | string,\n): ProjectionState {\n return updateMission(state, event, (mission) => {\n const run = Object.hasOwn(mission.runs, event.runId) ? mission.runs[event.runId] : undefined;\n if (run === undefined) return `unknown run \"${event.runId}\" in mission \"${event.missionId}\"`;\n if (TERMINAL.has(run.status)) {\n return `run \"${event.runId}\" is already ${run.status}; \"${event.type}\" cannot change it`;\n }\n const next = change(run);\n if (typeof next === \"string\") return next;\n return {\n ...mission,\n runs: { ...mission.runs, [event.runId]: { ...next, updatedSeq: event.seq, updatedAt: event.ts } },\n };\n });\n}\n\nfunction withAnomaly(state: ProjectionState, event: StoredEvent, message: string): ProjectionState {\n return { ...state, anomalies: [...state.anomalies, { seq: event.seq, type: event.type, message }] };\n}\n\nfunction addUsage(meters: UsageMeters, event: EventOf<\"run.usage\">): UsageMeters {\n const previous = meters[event.unit];\n return {\n ...meters,\n [event.unit]: {\n amount: (previous?.amount ?? 0) + event.amount,\n estimated: (previous?.estimated ?? false) || event.estimated,\n },\n };\n}\n\nfunction sortedUnion(left: string[], right: string[]): string[] {\n return [...new Set([...left, ...right])].sort();\n}\n", "import { elapsedMs, silentMs, type MissionView, type RunPhase, type RunView } from \"../projections/state.ts\";\n\n/*\n * How a crew reads to a human, in one place.\n *\n * The lead reads this in a chat, the owner reads it in a terminal, and later a browser will draw the same facts.\n * They share this module so the three can never disagree: a mission that looks stalled in one surface and healthy\n * in another is worse than either answer alone.\n *\n * The rule these functions follow is the project's sixth non-negotiable. Every number here is measured, never\n * guessed; what is unknown prints as \"\u2014\" rather than as a zero that reads like a fact; and nothing implies we know\n * how much work is left, because we do not.\n */\n\n/** Below this, an agent that has not spoken is simply thinking, and saying \"quiet\" would cry wolf. */\nconst QUIET_AFTER_MS = 60_000;\n\nconst PHASES: readonly RunPhase[] = [\"reading\", \"coding\", \"testing\", \"reporting\"];\n\nconst DASH = \"\u2014\";\n\n/**\n * A duration a person can read at a glance: `9s`, `6m 38s`, `2h 05m`.\n *\n * Always rounds down. A run that has been going 119 seconds is in its first minute and fifty-ninth second, not its\n * second minute, and rounding up would make every run look slightly further along than it is.\n */\nexport function formatDuration(ms: number): string {\n const total = Math.max(0, Math.floor(ms / 1000));\n const seconds = total % 60;\n const minutes = Math.floor(total / 60) % 60;\n const hours = Math.floor(total / 3600);\n\n if (hours > 0) return `${String(hours)}h ${String(minutes).padStart(2, \"0\")}m`;\n if (minutes > 0) return `${String(minutes)}m ${String(seconds).padStart(2, \"0\")}s`;\n return `${String(seconds)}s`;\n}\n\n/**\n * Which of the four named phases a run is in \u2014 `\u25AA\u25AA\u25AB\u25AB` is \"coding\", the second of four.\n *\n * This is deliberately not a progress bar. We know the phase a run reported; we do not know how much of it is left,\n * and an agent can sit in one phase for a minute or for twenty. A bar that filled with time would be inventing\n * information, which is the one thing these surfaces may never do.\n */\nexport function phaseBar(phase: RunPhase | null): string {\n const reached = phase === null ? 0 : PHASES.indexOf(phase) + 1;\n return \"\u25AA\".repeat(reached) + \"\u25AB\".repeat(PHASES.length - reached);\n}\n\n/** One aligned row per run: what it is, where it is, how long it has been there, and what it has produced. */\nexport function runTable(runs: readonly RunView[], now: Date): string {\n if (runs.length === 0) return ` No runs yet.\\n`;\n\n const rows = runs.map((run) => {\n const elapsed = elapsedMs(run, now);\n const silent = silentMs(run, now);\n const diff =\n run.diffStat === null\n ? run.files.length === 0\n ? \"\"\n : `${String(run.files.length)} file${run.files.length === 1 ? \"\" : \"s\"}`\n : `+${String(run.diffStat.insertions)} \u2212${String(run.diffStat.deletions)}`;\n\n return {\n mark: MARKS[run.status],\n runId: run.runId,\n seat: run.seat.id,\n status: run.status,\n bar: phaseBar(run.phase),\n phase: run.phase ?? \"\",\n elapsed: elapsed === null ? DASH : formatDuration(elapsed),\n diff,\n // A finished run is never \"quiet\": it is not waiting for anything.\n quiet: silent !== null && silent >= QUIET_AFTER_MS ? `quiet ${formatDuration(silent)}` : \"\",\n };\n });\n\n const width = (pick: (row: (typeof rows)[number]) => string): number =>\n Math.max(...rows.map((row) => pick(row).length));\n const w = {\n runId: width((row) => row.runId),\n seat: width((row) => row.seat),\n status: width((row) => row.status),\n elapsed: width((row) => row.elapsed),\n phase: width((row) => row.phase),\n };\n\n return (\n rows\n .map((row) =>\n [\n ` ${row.mark} ${row.runId.padEnd(w.runId)}`,\n row.seat.padEnd(w.seat),\n row.status.padEnd(w.status),\n `${row.bar} ${row.phase.padEnd(w.phase)}`,\n row.elapsed.padStart(w.elapsed),\n row.diff,\n row.quiet,\n ]\n .filter((cell) => cell !== \"\")\n .join(\" \")\n .trimEnd(),\n )\n .join(\"\\n\") + \"\\n\"\n );\n}\n\n/** The whole mission as a watcher wants it: the headline first, then a row per run. */\nexport function missionReport(mission: MissionView, now: Date): string {\n const runs = mission.runOrder.flatMap((runId) => {\n const run = mission.runs[runId];\n return run === undefined ? [] : [run];\n });\n\n const count = (predicate: (run: RunView) => boolean): number => runs.filter(predicate).length;\n const tallies = [\n [count((run) => run.status === \"running\"), \"running\"],\n [count((run) => run.status === \"queued\"), \"queued\"],\n [count((run) => run.status === \"done\"), \"done\"],\n [count((run) => run.status === \"merged\"), \"merged\"],\n [count((run) => run.status === \"dropped\"), \"dropped\"],\n [\n count((run) => run.status === \"failed\" || run.status === \"killed\" || run.status === \"timeout\"),\n \"ended badly\",\n ],\n ] as const;\n\n const headline = [\n mission.missionId,\n mission.status,\n ...tallies.filter(([n]) => n > 0).map(([n, label]) => `${String(n)} ${label}`),\n ].join(\" \u00B7 \");\n\n return `${headline}\\n${runTable(runs, now)}`;\n}\n\nconst MARKS: Record<RunView[\"status\"], string> = {\n queued: \"\u25CC\",\n running: \"\u25CF\",\n done: \"\u2713\",\n merged: \"\u2713\",\n failed: \"\u2717\",\n killed: \"\u2717\",\n timeout: \"\u2717\",\n conflict: \"!\",\n dropped: \"\u00B7\",\n};\n", "import type { PlanLine } from \"../schema/plan.ts\";\nimport type { RunView } from \"../projections/state.ts\";\n\n/*\n * Whether a piece of work may be merged, and if not, exactly what is missing.\n *\n * This is the smallest and most important function in the product. Everything else \u2014 worktrees, adapters, the\n * ledger, the mission view \u2014 exists so that this can be asked honestly about a specific diff. It is a pure\n * function of recorded facts on purpose: it cannot read a file, run a command, or be talked round by an agent's\n * account of its own work, and a replay of the ledger reaches the same verdict months later.\n *\n * The rule it enforces is one sentence: nothing merges that review, checks, proof and a person did not all agree\n * on, about the *same revision*. Each of those is easy alone. Tying them to one revision is the part that makes\n * \"reviewed and checked\" mean something, because a worktree can change between being judged and being applied.\n */\n\nexport type BlockerCode =\n | \"not-finished\"\n | \"already-settled\"\n | \"no-review\"\n | \"review-rejected\"\n | \"review-asked-for-rework\"\n | \"review-stale\"\n | \"no-checks\"\n | \"checks-failed\"\n | \"checks-stale\"\n | \"no-proof\"\n | \"proof-failed\"\n | \"proof-stale\"\n | \"not-approved\"\n | \"approval-stale\";\n\nexport interface Blocker {\n code: BlockerCode;\n /** Written for the person who has to do something about it, not for a log. */\n message: string;\n}\n\nexport interface Readiness {\n ready: boolean;\n /** Empty when ready. Ordered the way a person would work through them. */\n blockers: Blocker[];\n}\n\n/**\n * Can `run`'s work at `revision` be merged?\n *\n * `line` is the plan line the run came from: it says whether a proof is required, which is a decision made when\n * the mission was planned rather than after an agent has explained why its change is obviously fine.\n */\nexport function mergeReadiness(run: RunView, line: PlanLine, revision: string): Readiness {\n const blockers: Blocker[] = [];\n const add = (code: BlockerCode, message: string): void => {\n blockers.push({ code, message });\n };\n\n // A run that is already merged or dropped is not a candidate; a second merge would double-apply its diff.\n if (run.status === \"merged\" || run.status === \"dropped\" || run.status === \"conflict\") {\n add(\"already-settled\", `This run is already ${run.status}.`);\n return { ready: false, blockers };\n }\n if (run.status !== \"done\") {\n add(\"not-finished\", `The agent has not finished: the run is ${run.status}.`);\n }\n\n if (run.review === null) {\n add(\"no-review\", \"Nobody has reviewed this diff.\");\n } else if (run.review.verdict === \"reject\") {\n add(\"review-rejected\", \"Review rejected this work.\");\n } else if (run.review.verdict === \"rework\") {\n add(\"review-asked-for-rework\", \"Review asked for changes, which have not come back.\");\n } else if (run.review.revision !== revision) {\n add(\"review-stale\", staleMessage(\"review\"));\n }\n\n if (run.checks === null) {\n add(\"no-checks\", \"The project's checks have not been run against this diff.\");\n } else if (!run.checks.ok) {\n add(\"checks-failed\", `The project's checks failed: ${run.checks.summary}`);\n } else if (run.checks.revision !== revision) {\n add(\"checks-stale\", staleMessage(\"checks\"));\n }\n\n /*\n * The fourth non-negotiable, in code. A fix without a test that fails on the old code is a claim that something\n * is fixed, and a claim is exactly what this gate exists not to accept. Only lines the plan marked as fixes are\n * held to it: demanding a failing-first test of a new feature would teach everyone to lie about the flag.\n */\n if (line.fixesBug) {\n if (run.proof === null) {\n add(\"no-proof\", \"This line fixes a bug, so it needs a test proven to fail on the old code.\");\n } else if (!run.proof.ok) {\n add(\"proof-failed\", \"The new test did not fail on the old code, so it does not prove the fix.\");\n } else if (run.proof.revision !== revision) {\n add(\"proof-stale\", staleMessage(\"proof\"));\n }\n }\n\n if (run.approval === null) {\n add(\"not-approved\", \"Nobody has approved this merge.\");\n } else if (run.approval.revision !== revision) {\n add(\"approval-stale\", staleMessage(\"approval\"));\n }\n\n return { ready: blockers.length === 0, blockers };\n}\n\n/**\n * A stale step is not a failure, and saying \"review failed\" about one would send someone hunting for a problem\n * that is not there. The work moved after it was judged; it has to be judged again.\n */\nfunction staleMessage(step: string): string {\n return `The work changed after ${step}, so ${step} was about a different diff. Run it again.`;\n}\n\n/** The two blockers that are the person's own yes, rather than something they are waiting on. */\nconst APPROVAL_CODES: ReadonlySet<BlockerCode> = new Set([\"not-approved\", \"approval-stale\"]);\n\n/**\n * What stands between this work and someone being *able* to approve it.\n *\n * Approval is the one blocker a person clears by deciding, so asking `mergeReadiness` whether work may be approved\n * answers \"no\" forever: the missing approval is itself a blocker. This removes that circle and nothing else.\n *\n * It exists so an approve button can refuse honestly. A button that recorded a yes for work nobody had reviewed\n * would put a real approval \u2014 the strongest evidence in the ledger \u2014 behind a diff that had earned none of it, and\n * the merge would then refuse for reasons the person had already been told did not apply.\n */\nexport function blocksApproval(readiness: Readiness): Blocker[] {\n return readiness.blockers.filter((blocker) => !APPROVAL_CODES.has(blocker.code));\n}\n\n/** One line a person can read, for when the whole list is too much: the first thing standing in the way. */\nexport function firstBlocker(readiness: Readiness): string | null {\n return readiness.blockers[0]?.message ?? null;\n}\n", "import type { SeatInfo } from \"../schema/common.ts\";\nimport type { SeatPolicy } from \"../schema/policy.ts\";\nimport { stanceFor } from \"../schema/policy.ts\";\nimport type { SeatHeadroom } from \"../projections/state.ts\";\n\n/*\n * Choosing which seat does a line, and being able to say why.\n *\n * A pure function over recorded facts, like the merge gate's judgement and for the same reason: a routing\n * decision that cannot be replayed is a decision nobody can argue with later. Every answer carries its reason in\n * words, because \"moved to claude\" is not something a person can act on and \"codex reached its usage limit, and\n * you marked grok sparing\" is.\n *\n * Three things decide it, in this order:\n *\n * 1. Can the seat work at all \u2014 installed, a version we verified, signed in, and not currently refusing?\n * 2. Did the owner say anything about spending it? A seat marked `off` is never chosen, however free it is.\n * 3. Of what is left, the plan's own choice first, then the owner's preference.\n *\n * Nothing here guesses at cost. We know a plan's name, not its price, and inventing an ordering from that would\n * be exactly the kind of confident arithmetic this project refuses elsewhere.\n */\n\nexport interface RoutingInput {\n /** The seat the plan asked for. */\n wanted: string;\n seats: readonly SeatInfo[];\n policy: SeatPolicy;\n headroom: Readonly<Record<string, SeatHeadroom>>;\n /** Now, for deciding whether a limit has since reset. */\n now: Date;\n}\n\nexport type Routing =\n | { kind: \"keep\"; seat: string }\n | { kind: \"move\"; seat: string; from: string; reason: string }\n | { kind: \"stuck\"; from: string; reason: string };\n\n/**\n * Why a seat cannot take work right now, or null when it can.\n *\n * `asFallback` is stricter, and the difference matters. When the plan named a seat, the person writing the plan\n * chose it and a CLI that simply cannot report its own sign-in \u2014 Grok and Kimi have no status command at all \u2014 is\n * not a reason to overrule them; we find out by running it. Moving work *onto* a seat is our decision rather than\n * theirs, and spending someone's subscription on a guess about whether it will even answer is not a decision to\n * make on their behalf.\n */\nexport function unavailable(\n seat: SeatInfo,\n policy: SeatPolicy,\n headroom: SeatHeadroom | undefined,\n now: Date,\n asFallback = false,\n): string | null {\n const stance = stanceFor(seat, policy);\n if (stance.posture === \"off\") return `you set it to off (${stance.reason})`;\n if (seat.version === null) return \"it is not installed\";\n if (!seat.supported) return `version ${seat.version} is outside what its adapter was verified against`;\n if (seat.signedIn === \"no\") return \"it is not signed in\";\n if (asFallback && seat.signedIn === \"unknown\") {\n return \"its CLI cannot tell us whether it is signed in, and this is not the seat you asked for\";\n }\n\n const limited = headroom?.limited;\n if (limited != null) {\n /*\n * A limit that has passed its reset is not a limit. Believing an expired one forever would strand a seat\n * that came back an hour ago, and the reset time is the seat's own word rather than our guess.\n */\n if (limited.resetsAt === null || Date.parse(limited.resetsAt) > now.getTime()) {\n return `it said: ${limited.message}`;\n }\n }\n return null;\n}\n\n/**\n * Where this line should run.\n *\n * Keeps the plan's choice whenever it can, because the plan was written by someone who knew what the line needed\n * \u2014 a different model is a different result, not a free substitution, and moving work silently would hide that.\n */\nexport function routeLine(input: RoutingInput): Routing {\n const byId = new Map(input.seats.map((seat) => [seat.id, seat]));\n const asked = byId.get(input.wanted);\n\n const why = (seat: SeatInfo, asFallback: boolean): string | null =>\n unavailable(seat, input.policy, input.headroom[seat.id], input.now, asFallback);\n\n if (asked !== undefined && why(asked, false) === null) return { kind: \"keep\", seat: asked.id };\n\n const blocked =\n asked === undefined\n ? `${input.wanted} is not a seat on this machine`\n : `${input.wanted}: ${why(asked, false) ?? \"unavailable\"}`;\n\n /*\n * Ordered by what the owner said, then by name so the same crew always routes the same way. A stable answer\n * matters more than a clever one: a mission that picks a different seat on every run is a mission whose\n * results cannot be compared.\n */\n const rank = { preferred: 0, normal: 1, sparing: 2, off: 3 };\n const candidates = input.seats\n .filter((seat) => seat.id !== input.wanted && why(seat, true) === null)\n .sort((a, b) => {\n const order = rank[stanceFor(a, input.policy).posture] - rank[stanceFor(b, input.policy).posture];\n return order !== 0 ? order : a.id.localeCompare(b.id);\n });\n\n const chosen = candidates[0];\n if (chosen === undefined) {\n return { kind: \"stuck\", from: input.wanted, reason: `${blocked}, and no other seat can take it` };\n }\n\n const stance = stanceFor(chosen, input.policy);\n const note =\n stance.posture === \"sparing\"\n ? ` \u2014 ${chosen.id} is marked sparing${stance.note === undefined ? \"\" : `: ${stance.note}`}`\n : \"\";\n return { kind: \"move\", seat: chosen.id, from: input.wanted, reason: `${blocked}${note}` };\n}\n", "import { readFileSync } from \"node:fs\";\n\n/*\n * What version of Fanout this actually is.\n *\n * Read from the package that is running, never written down twice. Two hand-maintained strings had already drifted\n * apart from the packages they named and from each other \u2014 the CLI said 0.5.0-dev and the MCP server said\n * 0.6.0-dev while both shipped from 0.7.0 \u2014 which is a small lie until someone reports a bug against a version\n * that never existed.\n */\n\n/**\n * The version in a package's own `package.json`, given any file inside that package.\n *\n * Pass `import.meta.url` from the caller. It walks up looking for the manifest, which is what makes it work\n * identically from `src/main.ts` in a checkout and from `dist/main.js` inside `node_modules`.\n */\nexport function versionOf(fromUrl: string): string {\n let directory = new URL(\".\", fromUrl);\n for (let depth = 0; depth < 8; depth++) {\n try {\n const text = readFileSync(new URL(\"package.json\", directory), \"utf8\");\n const parsed: unknown = JSON.parse(text);\n const version = (parsed as { version?: unknown }).version;\n if (typeof version === \"string\") return version;\n } catch {\n // Not this directory. Keep walking up until the package root or we run out of patience.\n }\n const parent = new URL(\"..\", directory);\n if (parent.href === directory.href) break;\n directory = parent;\n }\n // Saying so beats inventing a number: an unknown version is a fact, and a wrong one sends someone hunting.\n return \"unknown\";\n}\n", "{\n \"id\": \"claude\",\n \"displayName\": \"Claude Code\",\n \"binary\": \"claude\",\n \"supportedVersions\": \">=2.0 <3\",\n \"tier\": \"supported\",\n \"capabilities\": {\n \"resume\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--resume\",\n \"{session}\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ]\n },\n \"fork\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--resume\",\n \"{session}\",\n \"--fork-session\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ]\n },\n \"review\": null,\n \"plan\": {\n \"probe\": [\"auth\", \"status\", \"--json\"],\n \"format\": \"json\",\n \"keep\": [\"loggedIn\", \"subscriptionType\"],\n \"planField\": \"subscriptionType\"\n }\n },\n \"headless\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--output-format stream-json\",\n \"format\": \"jsonl\"\n },\n \"models\": [\"fable\", \"opus\", \"sonnet\", \"haiku\"],\n \"efforts\": [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n \"permissionModes\": {\n \"readOnly\": \"plan\",\n \"edit\": \"acceptEdits\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": [\"auth\", \"status\"],\n \"okPattern\": \"\\\"loggedIn\\\"\\\\s*:\\\\s*true\",\n \"noPattern\": \"\\\"loggedIn\\\"\\\\s*:\\\\s*false\"\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"5h\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through `claude -p`, the documented non-interactive mode, with permission prompts denied rather than bypassed. No credential handling: sign-in state comes from `claude auth status`. Claude is an opt-in worker (DECISIONS 0009) because the lead already spends this subscription on planning and review. Billing to watch: Anthropic announced moving headless use to a separate Agent SDK credit on 2026-06-15 and then paused it, so today it draws from subscription limits; if that changes, this field becomes \\\"credit\\\".\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Claude Code's stream-json feed, as recorded from version 2.1.269 (fixtures/basic.jsonl).\n *\n * It is the most generous of the streams we drive: an init line naming the session, a rate-limit line with real\n * window utilization, thinking-token estimates as the turn goes, assistant messages whose content blocks carry the\n * tool calls, and a final result line with the answer and the turn's token usage.\n *\n * Only the fields we use are described and unknown extras are allowed, so a new field never breaks a run. The\n * union is discriminated on `type` so that narrowing one line tells us exactly what we may read from it; the\n * several kinds of `system` line differ by `subtype`, which is why its fields are optional here.\n */\n\nexport const ToolUse = z.looseObject({\n type: z.literal(\"tool_use\"),\n name: z.string(),\n input: z\n .looseObject({\n file_path: z.string().optional(),\n path: z.string().optional(),\n notebook_path: z.string().optional(),\n command: z.string().optional(),\n })\n .optional(),\n});\nexport type ToolUse = z.infer<typeof ToolUse>;\n\nconst Window = z.looseObject({ utilization: z.number(), resetsAt: z.number().optional() });\n\nexport const ClaudeLine = z.discriminatedUnion(\"type\", [\n z.looseObject({\n type: z.literal(\"system\"),\n subtype: z.string(),\n session_id: z.string().optional(),\n estimated_tokens_delta: z.number().optional(),\n }),\n z.looseObject({\n type: z.literal(\"rate_limit_event\"),\n rate_limit_info: z.looseObject({\n status: z.string(),\n rateLimitType: z.string().optional(),\n resetsAt: z.number().optional(),\n unifiedWindows: z.record(z.string(), Window).optional(),\n }),\n }),\n z.looseObject({\n type: z.literal(\"assistant\"),\n message: z.looseObject({ content: z.array(z.looseObject({ type: z.string() })) }),\n }),\n z.looseObject({ type: z.literal(\"user\") }),\n z.looseObject({\n type: z.literal(\"result\"),\n subtype: z.string().optional(),\n is_error: z.boolean().optional(),\n result: z.string().optional(),\n usage: z\n .looseObject({ input_tokens: z.number().optional(), output_tokens: z.number().optional() })\n .optional(),\n }),\n]);\nexport type ClaudeLine = z.infer<typeof ClaudeLine>;\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type AdapterSignal,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { CodexLine, type CodexItem } from \"./protocol.ts\";\n\n/*\n * The OpenAI Codex seat, driven through `codex exec` \u2014 the mode its own documentation describes for\n * non-interactive use. Nothing here touches credentials: sign-in belongs to the CLI, and we only ever ask it.\n *\n * Its stream (verified against 0.154.0, recorded in fixtures/basic.jsonl) is JSONL:\n * thread.started the session id\n * item.started/completed with an item of type command_execution | file_change | agent_message | error\n * turn.completed token usage for the turn\n *\n * Two details a hand-written parser would get wrong, both found by recording a real run: file changes carry\n * absolute paths, which we make repo-relative; and Codex emits non-fatal `error` items that must reach the lead\n * rather than being swallowed.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst LIMIT = /usage limit|rate limit|quota|too many requests/i;\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\n\nexport function createCodexAdapter(): SeatAdapter {\n return { id: manifest.id, command, parse, resume };\n}\n\n/**\n * Continues the thread that produced the diff, with the reviewer's notes as the next turn.\n *\n * Verified against codex 0.154.0 on a throwaway repository: the resumed run keeps the same thread id and answered\n * a follow-up that said \"the file you just created\" correctly, which is the whole reason to resume rather than\n * re-explain. The argv is the manifest's, so a change to what was verified is a change to data.\n */\nfunction resume(context: AdapterContext & { sessionId: string }): LaunchSpec {\n const template = manifest.capabilities.resume;\n if (template === null) throw new Error(\"this codex manifest declares no resume command\");\n\n const args = fill(template.args, {\n \"{workdir}\": context.workdir,\n \"{sandbox}\": manifest.permissionModes.edit,\n \"{session}\": context.sessionId,\n \"{prompt}\": context.line.prompt,\n ...(context.line.seat.model === undefined ? {} : { \"{model}\": context.line.seat.model }),\n });\n return {\n argv: [manifest.binary, ...args] as [string, ...string[]],\n cwd: context.workdir,\n env: context.baseEnv,\n };\n}\n\n/**\n * Fills the manifest's template, dropping a placeholder nobody supplied along with the flag in front of it.\n *\n * Without this, no model chosen means `-m \"\"`, and Codex answers `The '' model is not supported`. Found by running\n * it rather than by reading it.\n */\nfunction fill(template: readonly string[], values: Readonly<Record<string, string>>): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n if (/^\\{[a-z]+\\}$/.test(argument) && !Object.hasOwn(values, argument)) {\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction command(context: AdapterContext): LaunchSpec {\n const { line } = context;\n const readOnly = line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{workdir}\", context.workdir)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit)\n .replace(\"{report}\", context.reportPath)\n .replace(\"{prompt}\", line.prompt),\n );\n\n // An auditor works on an export with no .git, which `codex exec` otherwise refuses to run in.\n if (readOnly) args.splice(args.length - 1, 0, \"--skip-git-repo-check\");\n if (line.seat.model !== undefined) args.splice(1, 0, \"-m\", line.seat.model);\n if (line.seat.effort !== undefined) args.splice(1, 0, \"-c\", `model_reasoning_effort=\"${line.seat.effort}\"`);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n}\n\nfunction parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = CodexLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const run = { missionId: context.missionId, runId: context.runId };\n const line = parsed.data;\n\n switch (line.type) {\n case \"thread.started\":\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reading\" }],\n signals: [{ kind: \"session\", id: line.thread_id }],\n };\n\n case \"turn.started\":\n return { events: [], signals: [] };\n\n case \"turn.completed\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.usage.input_tokens + line.usage.output_tokens,\n unit: \"tokens\",\n estimated: false,\n },\n { type: \"run.progress\", ...run, phase: \"reporting\" },\n ],\n signals: [],\n };\n\n case \"item.started\":\n case \"item.completed\":\n return item(line.type, line.item, context, run);\n }\n}\n\nfunction item(\n lineType: \"item.started\" | \"item.completed\",\n value: CodexItem,\n context: AdapterContext,\n run: { missionId: string; runId: string },\n): ParseResult {\n const completed = lineType === \"item.completed\";\n\n switch (value.type) {\n case \"error\": {\n const signal: AdapterSignal = LIMIT.test(value.message)\n ? { kind: \"limit\", message: value.message }\n : { kind: \"error\", message: value.message };\n return { events: [], signals: [signal] };\n }\n\n case \"agent_message\":\n // Every agent message is a report; the last one before the run ends is the run's report.\n return completed\n ? { events: [], signals: [{ kind: \"report\", text: value.text }] }\n : { events: [], signals: [] };\n\n case \"file_change\": {\n if (!completed) return { events: [], signals: [] };\n const files = value.changes.map((change) => repoRelative(change.path, context.workdir));\n const kinds = [...new Set(value.changes.map((change) => change.kind))].join(\", \");\n const events: FanoutEventInput[] = [\n { type: \"run.progress\", ...run, phase: \"coding\" },\n { type: \"run.tool\", ...run, tool: \"edit\", summary: kinds, files },\n ];\n return { events, signals: [] };\n }\n\n case \"command_execution\": {\n if (!completed) return { events: [], signals: [] };\n const summary = value.command.slice(0, 500);\n const events: FanoutEventInput[] = [\n ...(TEST_COMMAND.test(value.command)\n ? [{ type: \"run.progress\" as const, ...run, phase: \"testing\" as const }]\n : []),\n { type: \"run.tool\", ...run, tool: \"shell\", summary, files: [] },\n ];\n return { events, signals: [] };\n }\n }\n}\n\n/** Codex reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "{\n \"id\": \"codex\",\n \"displayName\": \"OpenAI Codex\",\n \"binary\": \"codex\",\n \"supportedVersions\": \">=0.150.0 <1.0.0\",\n \"tier\": \"supported\",\n \"capabilities\": {\n \"resume\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"resume\",\n \"{session}\",\n \"--json\",\n \"-m\",\n \"{model}\",\n \"{prompt}\"\n ]\n },\n \"fork\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"fork\",\n \"{session}\",\n \"--json\",\n \"-m\",\n \"{model}\",\n \"{prompt}\"\n ]\n },\n \"review\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"review\",\n \"--uncommitted\",\n \"--json\",\n \"-m\",\n \"{model}\"\n ]\n },\n \"plan\": null\n },\n \"headless\": {\n \"args\": [\"exec\", \"--json\", \"-C\", \"{workdir}\", \"-s\", \"{sandbox}\", \"-o\", \"{report}\", \"{prompt}\"],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--json\",\n \"format\": \"jsonl\"\n },\n \"models\": [\"gpt-6-astra\", \"gpt-5.6-sol\", \"gpt-5.6-terra\", \"gpt-5.6-luna\", \"gpt-5.5\", \"gpt-5.3-codex-spark\"],\n \"efforts\": [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n \"permissionModes\": {\n \"readOnly\": \"read-only\",\n \"edit\": \"workspace-write\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": [\"login\", \"status\"],\n \"okPattern\": \"^\\\\s*Logged in\\\\b\",\n \"noPattern\": \"^\\\\s*Not logged in\\\\b\"\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"unknown\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through `codex exec`, the documented non-interactive mode. No credential handling: sign-in state is read with `codex login status`. Network behaviour inside the sandbox is the CLI's own and we do not claim to control it, so the safety report warns rather than promising isolation.\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Codex's own JSONL stream, as recorded from version 0.154.0 (fixtures/basic.jsonl). Only the fields we use are\n * described, and unknown extras are allowed: a vendor adding a field must never break a run. A line that does not\n * match at all becomes an `unparsed` signal rather than a guess.\n */\n\nconst FileChange = z.object({\n id: z.string(),\n type: z.literal(\"file_change\"),\n changes: z.array(z.object({ path: z.string(), kind: z.string() })),\n status: z.string().optional(),\n});\n\nconst CommandExecution = z.object({\n id: z.string(),\n type: z.literal(\"command_execution\"),\n command: z.string(),\n aggregated_output: z.string().optional(),\n exit_code: z.number().nullable().optional(),\n status: z.string().optional(),\n});\n\nconst AgentMessage = z.object({ id: z.string(), type: z.literal(\"agent_message\"), text: z.string() });\n\nconst ErrorItem = z.object({ id: z.string(), type: z.literal(\"error\"), message: z.string() });\n\nconst Item = z.discriminatedUnion(\"type\", [FileChange, CommandExecution, AgentMessage, ErrorItem]);\n\nexport const CodexLine = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"thread.started\"), thread_id: z.string() }),\n z.object({ type: z.literal(\"turn.started\") }),\n z.object({\n type: z.literal(\"turn.completed\"),\n usage: z.object({ input_tokens: z.number(), output_tokens: z.number() }),\n }),\n z.object({ type: z.literal(\"item.started\"), item: Item }),\n z.object({ type: z.literal(\"item.completed\"), item: Item }),\n]);\nexport type CodexLine = z.infer<typeof CodexLine>;\nexport type CodexItem = z.infer<typeof Item>;\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { GrokLine } from \"./protocol.ts\";\n\n/*\n * The Grok Build seat, driven through its documented single-turn mode (`grok -p`) with structured output.\n *\n * Its stream (verified against 1.0.13, recorded in fixtures/basic.jsonl) differs from Codex's in two ways that\n * shape this adapter. Prose arrives as a stream of one-word deltas, so the run's report has to be assembled here\n * rather than read from a file \u2014 Grok writes none. And the session id arrives only in the final `end` line, so a\n * run is half over before we can name its session.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\nconst WRITING = /write|edit|replace|create|patch/i;\n\nexport function createGrokAdapter(): SeatAdapter {\n /** Grok streams its prose in pieces; a run's report is all of them, in order, joined. */\n const spoken = new Map<string, string>();\n /*\n * Runs that have already seen the tool-list handshake.\n *\n * Grok announces its available commands several times in one run \u2014 four, in the stream we recorded \u2014 and each\n * announcement is the CLI listing what it can do, not a statement about what it is doing. Treating every one of\n * them as \"reading\" walked the phase backwards from `coding` mid-run, which on the mission view looks exactly\n * like an agent that gave up and started over.\n */\n const greeted = new Set<string>();\n\n return {\n id: manifest.id,\n\n command(context: AdapterContext): LaunchSpec {\n const readOnly = context.line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{prompt}\", context.line.prompt)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit)\n .replace(\"{workdir}\", context.workdir),\n );\n if (context.line.seat.model !== undefined) args.push(\"-m\", context.line.seat.model);\n if (context.line.seat.effort !== undefined) args.push(\"--reasoning-effort\", context.line.seat.effort);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n },\n\n parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = GrokLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n\n switch (line.type) {\n case \"available_commands\": {\n // The first one is genuine news: the run is up and reading. The rest are the same handshake repeated.\n if (greeted.has(context.runId)) return { events: [], signals: [] };\n greeted.add(context.runId);\n return { events: [{ type: \"run.progress\", ...run, phase: \"reading\" }], signals: [] };\n }\n\n case \"thought\":\n return { events: [], signals: [] };\n\n case \"text\":\n spoken.set(context.runId, (spoken.get(context.runId) ?? \"\") + line.data);\n return { events: [], signals: [] };\n\n case \"tool_call\": {\n const tool = line.toolName ?? line.kind ?? \"tool\";\n const files = toolFiles(line.rawInput, line.locations, context.workdir);\n const command = line.rawInput?.command ?? \"\";\n const events: FanoutEventInput[] = [\n {\n type: \"run.progress\",\n ...run,\n phase: TEST_COMMAND.test(command) ? \"testing\" : WRITING.test(tool) ? \"coding\" : \"reading\",\n },\n {\n type: \"run.tool\",\n ...run,\n tool,\n ...(command === \"\" ? {} : { summary: command.slice(0, 500) }),\n files,\n },\n ];\n return { events, signals: [] };\n }\n\n case \"tool_call_update\":\n return { events: [], signals: [] };\n\n case \"usage\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.usage.input_tokens + line.usage.output_tokens,\n unit: \"tokens\",\n estimated: false,\n },\n ],\n signals: [],\n };\n\n case \"end\": {\n const report = spoken.get(context.runId) ?? \"\";\n spoken.delete(context.runId);\n greeted.delete(context.runId);\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reporting\" }],\n signals: [\n ...(line.sessionId === undefined ? [] : [{ kind: \"session\" as const, id: line.sessionId }]),\n ...(report === \"\" ? [] : [{ kind: \"report\" as const, text: report }]),\n ],\n };\n }\n }\n },\n };\n}\n\nfunction toolFiles(\n rawInput: { file_path?: string | undefined; path?: string | undefined } | undefined,\n locations: { path: string }[] | undefined,\n workdir: string,\n): string[] {\n const paths = [rawInput?.file_path, rawInput?.path, ...(locations ?? []).map((location) => location.path)];\n const seen = new Set<string>();\n for (const path of paths) {\n if (path !== undefined && path !== \"\") seen.add(repoRelative(path, workdir));\n }\n return [...seen];\n}\n\n/** Grok reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "{\n \"id\": \"grok\",\n \"displayName\": \"Grok Build\",\n \"binary\": \"grok\",\n \"supportedVersions\": \">=1.0 <2\",\n \"tier\": \"community\",\n \"capabilities\": {\n \"resume\": null,\n \"fork\": null,\n \"review\": null,\n \"plan\": null\n },\n \"headless\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--output-format\",\n \"streaming-json\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--cwd\",\n \"{workdir}\"\n ],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--output-format streaming-json\",\n \"format\": \"jsonl\"\n },\n \"models\": [],\n \"efforts\": [\"low\", \"medium\", \"high\"],\n \"permissionModes\": {\n \"readOnly\": \"plan\",\n \"edit\": \"acceptEdits\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": null,\n \"okPattern\": null,\n \"noPattern\": null\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"unknown\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through the documented single-turn mode (-p) with structured output. No credential handling: sign-in belongs to `grok login`, and the CLI offers no status command, so the crew reports sign-in as unknown rather than guessing. It writes no report file of its own, so the run's report is the text it streamed.\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Grok Build's streaming-json feed, as recorded from version 1.0.13 (fixtures/basic.jsonl). It is a session-update\n * stream: prose and reasoning arrive as many small deltas, tools as a call and later updates, usage once per turn,\n * and the session id only at the very end.\n *\n * Only the fields we use are described and unknown extras are allowed: a vendor adding a field must not break a run.\n */\n\nconst Location = z.looseObject({ path: z.string() });\n\nconst RawInput = z.looseObject({\n file_path: z.string().optional(),\n path: z.string().optional(),\n command: z.string().optional(),\n});\n\nexport const GrokLine = z.discriminatedUnion(\"type\", [\n z.looseObject({ type: z.literal(\"available_commands\") }),\n z.looseObject({ type: z.literal(\"thought\"), data: z.string() }),\n z.looseObject({ type: z.literal(\"text\"), data: z.string() }),\n z.looseObject({\n type: z.literal(\"tool_call\"),\n toolCallId: z.string(),\n toolName: z.string().optional(),\n kind: z.string().optional(),\n rawInput: RawInput.optional(),\n locations: z.array(Location).optional(),\n }),\n z.looseObject({\n type: z.literal(\"tool_call_update\"),\n toolCallId: z.string(),\n status: z.string().nullable().optional(),\n locations: z.array(Location).optional(),\n }),\n z.looseObject({\n type: z.literal(\"usage\"),\n usage: z.looseObject({ input_tokens: z.number(), output_tokens: z.number() }),\n }),\n z.looseObject({\n type: z.literal(\"end\"),\n stopReason: z.string().optional(),\n sessionId: z.string().optional(),\n }),\n]);\nexport type GrokLine = z.infer<typeof GrokLine>;\n", "import { spawn, type ChildProcess } from \"node:child_process\";\nimport { closeSync, openSync, writeSync } from \"node:fs\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport type { OutputStream, RunExit, RunHandle, SuperviseOptions } from \"./types.ts\";\n\nexport function supervise(options: SuperviseOptions): RunHandle {\n const began = performance.now();\n let resolveDone: ((result: RunExit) => void) | undefined;\n const done = new Promise<RunExit>((resolve) => {\n resolveDone = resolve;\n });\n let child: ChildProcess | undefined;\n let log: number | undefined;\n let logBytes = 0;\n let logTruncated = false;\n let startDetected = false;\n let settled = false;\n let closed = false;\n let exitCode: number | null = null;\n let signal: NodeJS.Signals | null = null;\n let stopping: \"failed\" | \"killed\" | \"timeout\" | undefined;\n let error: string | undefined;\n let startTimer: NodeJS.Timeout | undefined = undefined;\n let timeoutTimer: NodeJS.Timeout | undefined = undefined;\n let killTimer: NodeJS.Timeout | undefined;\n\n function clearDeadlines(): void {\n clearTimeout(startTimer);\n clearTimeout(timeoutTimer);\n }\n\n function finish(): void {\n if (settled) return;\n settled = true;\n clearDeadlines();\n clearTimeout(killTimer);\n if (log !== undefined) {\n try {\n closeSync(log);\n } catch (cause) {\n error ??= message(cause);\n stopping ??= \"failed\";\n }\n log = undefined;\n }\n resolveDone?.({\n status: stopping ?? (exitCode === 0 ? \"done\" : \"failed\"),\n exitCode,\n signal,\n startDetected,\n durationMs: performance.now() - began,\n ...(error === undefined ? {} : { error }),\n });\n }\n\n function signalGroup(nextSignal: NodeJS.Signals | 0): boolean {\n if (child?.pid === undefined) return false;\n try {\n process.kill(-child.pid, nextSignal);\n return true;\n } catch (cause) {\n if (!(cause instanceof Error && \"code\" in cause && cause.code === \"ESRCH\")) {\n error ??= message(cause);\n }\n return false;\n }\n }\n\n function stop(status: \"failed\" | \"killed\" | \"timeout\", reason?: string): void {\n if (settled || stopping !== undefined) return;\n stopping = status;\n if (reason !== undefined) error ??= reason;\n clearDeadlines();\n signalGroup(\"SIGTERM\");\n // Keep escalation alive even if the group leader exits before its descendants.\n killTimer = setTimeout(() => {\n if (signalGroup(0)) signalGroup(\"SIGKILL\");\n killTimer = undefined;\n if (closed) finish();\n }, options.killGraceMs);\n }\n\n function fail(cause: unknown): void {\n error ??= message(cause);\n stop(\"failed\");\n }\n\n function writeLog(text: string): void {\n if (log === undefined) return;\n const bytes = Buffer.from(text);\n let offset = 0;\n while (offset < bytes.length) {\n offset += writeSync(log, bytes, offset, bytes.length - offset);\n }\n }\n\n function line(text: string, stream: OutputStream): void {\n try {\n if (!logTruncated) {\n const entry = `${stream === \"stderr\" ? \"[stderr] \" : \"\"}${text}\\n`;\n const size = Buffer.byteLength(entry);\n if (logBytes + size <= options.maxLogBytes) {\n writeLog(entry);\n logBytes += size;\n } else {\n // Keep complete log lines; the single marker is metadata beyond the payload cap.\n logTruncated = true;\n writeLog(`[log truncated at ${options.maxLogBytes} bytes]\\n`);\n }\n }\n } catch (cause) {\n fail(cause);\n }\n try {\n options.onLine(text, stream);\n } catch (cause) {\n fail(cause);\n }\n }\n\n const handle: RunHandle = {\n runId: options.runId,\n get pid() {\n return child?.pid;\n },\n done,\n kill(reason: string) {\n stop(\"killed\", reason);\n return done;\n },\n };\n\n try {\n log = openSync(options.logPath, \"a\", 0o600);\n child = spawn(options.spec.argv[0], options.spec.argv.slice(1), {\n cwd: options.spec.cwd,\n env: { ...options.spec.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: true,\n });\n } catch (cause) {\n error = message(cause);\n stopping = \"failed\";\n finish();\n return handle;\n }\n\n startTimer = setTimeout(() => {\n error = `No stdout received within ${options.startTimeoutMs} ms`;\n stop(\"failed\");\n }, options.startTimeoutMs);\n timeoutTimer = setTimeout(() => {\n stop(\"timeout\");\n }, options.timeoutMs);\n\n const stdout = splitLines(options.maxLineBytes, (text) => {\n line(text, \"stdout\");\n });\n const stderr = splitLines(options.maxLineBytes, (text) => {\n line(text, \"stderr\");\n });\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n if (chunk.length > 0 && !startDetected && stopping === undefined) {\n startDetected = true;\n clearTimeout(startTimer);\n try {\n options.onStarted();\n } catch (cause) {\n fail(cause);\n }\n }\n stdout.push(chunk);\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr.push(chunk);\n });\n child.stdout?.on(\"error\", fail);\n child.stderr?.on(\"error\", fail);\n child.once(\"error\", fail);\n child.once(\"exit\", (code, exitSignal) => {\n exitCode = code;\n signal = exitSignal;\n });\n child.once(\"close\", (code, exitSignal) => {\n closed = true;\n exitCode = child.pid === undefined ? null : code;\n signal = exitSignal;\n stdout.end();\n stderr.end();\n if (stopping === undefined || killTimer === undefined || !signalGroup(0)) finish();\n });\n return handle;\n}\n\nfunction message(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n\n/** Retain only the bounded prefix, even for an arbitrarily long unterminated line. */\nfunction splitLines(limit: number, emit: (line: string) => void) {\n let parts: Buffer[] = [];\n let retained = 0;\n let length = 0;\n let lastByte: number | undefined;\n\n function append(bytes: Buffer): void {\n if (bytes.length === 0) return;\n lastByte = bytes[bytes.length - 1];\n length = Math.min(limit + 2, length + bytes.length);\n const keep = Math.min(bytes.length, Math.max(0, limit - retained));\n if (keep > 0) {\n parts.push(Buffer.from(bytes.subarray(0, keep)));\n retained += keep;\n }\n }\n\n function flush(newline: boolean): void {\n const size = length - (newline && lastByte === 13 ? 1 : 0);\n const prefix = Buffer.concat(parts, retained).subarray(0, size);\n const truncated = size > limit;\n const text = truncated ? new StringDecoder(\"utf8\").write(prefix) : prefix.toString(\"utf8\");\n parts = [];\n retained = 0;\n length = 0;\n lastByte = undefined;\n emit(`${text}${truncated ? \" \u2026[truncated]\" : \"\"}`);\n }\n\n return {\n push(chunk: Buffer): void {\n let offset = 0;\n let newline = chunk.indexOf(10, offset);\n while (newline !== -1) {\n append(chunk.subarray(offset, newline));\n flush(true);\n offset = newline + 1;\n newline = chunk.indexOf(10, offset);\n }\n append(chunk.subarray(offset));\n },\n end(): void {\n if (length > 0) flush(false);\n },\n };\n}\n", "/*\n * The environment an agent CLI receives. It needs enough to run and to find its own sign-in (PATH, HOME, locale),\n * and nothing else: API keys, tokens and cloud credentials in the user's shell never reach an agent.\n * A CLI that needs a vendor variable (for example CODEX_HOME) gets it from its adapter, by name.\n */\n\nexport const ALLOWED_ENV = [\n \"PATH\",\n \"HOME\",\n \"USER\",\n \"LOGNAME\",\n \"SHELL\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"TMPDIR\",\n \"TZ\",\n \"XDG_CONFIG_HOME\",\n \"XDG_DATA_HOME\",\n \"XDG_CACHE_HOME\",\n \"XDG_STATE_HOME\",\n] as const;\n\nexport function baseEnv(\n source: Readonly<Record<string, string | undefined>> = process.env,\n): Record<string, string> {\n const env: Record<string, string> = {};\n for (const name of ALLOWED_ENV) {\n const value = source[name];\n if (value !== undefined && value !== \"\") env[name] = value;\n }\n return env;\n}\n", "import { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport {\n InvalidEventError,\n type AdapterContext,\n type AdapterSignal,\n type DiffStat,\n type FanoutEventInput,\n type Ledger,\n type SeatAdapter,\n} from \"fanout-core\";\nimport { supervise } from \"./supervisor/supervise.ts\";\nimport type { RunExit, RunHandle, SuperviseOptions } from \"./supervisor/types.ts\";\n\n/*\n * One run, end to end: the adapter builds the command, the supervisor runs it, the adapter reads its output, and the\n * ledger records what happened. Adapters may only report what their agent is doing (progress, tools, usage) for\n * their own run; anything else they emit is refused and surfaced as an `unparsed` signal.\n * If the ledger itself cannot record an event, the run is stopped: nothing runs unrecorded.\n */\n\nexport type RunLimits = Pick<\n SuperviseOptions,\n \"startTimeoutMs\" | \"timeoutMs\" | \"killGraceMs\" | \"maxLogBytes\" | \"maxLineBytes\"\n>;\n\nexport interface StartRunOptions {\n ledger: Ledger;\n adapter: SeatAdapter;\n context: AdapterContext;\n logPath: string;\n limits: RunLimits;\n /** The adapter's hints (session id, limit reached, final report, unparsed lines), in order. */\n onSignal?: (signal: AdapterSignal) => void;\n /**\n * Read from the run's workspace once it has stopped, so `run.finished` carries what actually changed rather\n * than what the agent said it changed. Failing to read it never fails the run.\n */\n collectDiff?: () => Promise<DiffStat | undefined>;\n /**\n * Continue an earlier conversation instead of starting one.\n *\n * The run keeps the same worktree, so the agent sees the code it wrote and the notes about it together. Set\n * only when the seat can resume at all; `startRun` refuses rather than quietly starting over, because a rework\n * that silently forgot everything would spend a subscription to lose the context it was spent on.\n */\n resumeSession?: string;\n}\n\n/**\n * How this run is started: fresh, or as the next turn of a conversation that already exists.\n *\n * A seat asked to resume that cannot is an error rather than a fresh run. Rework's whole value is that the agent\n * still holds its own reasoning about the code, and silently discarding that while still charging for it is the\n * worst of both outcomes.\n */\nfunction specFor(adapter: SeatAdapter, context: AdapterContext, sessionId?: string) {\n if (sessionId === undefined) return adapter.command(context);\n if (adapter.resume === undefined) {\n throw new Error(`${adapter.id} cannot resume a session, so this work cannot be reworked in place`);\n }\n return adapter.resume({ ...context, sessionId });\n}\n\nexport interface ActiveRun {\n readonly handle: RunHandle;\n /** Resolves once `run.finished` is recorded; rejects only if the ledger failed. */\n readonly finished: Promise<RunExit>;\n}\n\nconst ADAPTER_EVENT_TYPES: ReadonlySet<string> = new Set([\"run.progress\", \"run.tool\", \"run.usage\"]);\n\nexport function startRun(options: StartRunOptions): ActiveRun {\n const { ledger, adapter, context } = options;\n const ids = { missionId: context.missionId, runId: context.runId };\n const spec = specFor(adapter, context, options.resumeSession);\n\n // The run's own directories are the daemon's to make: the supervisor opens the log before it spawns anything,\n // and an agent should never have to create the place its report goes. Private to the user, like the ledger.\n mkdirSync(dirname(options.logPath), { recursive: true, mode: 0o700 });\n mkdirSync(dirname(context.reportPath), { recursive: true, mode: 0o700 });\n // Callbacks may fire before `supervise` returns, so they reach the handle through this holder.\n const control: { handle?: RunHandle } = {};\n let ledgerFailure: Error | undefined;\n\n const signal = (value: AdapterSignal): void => {\n /*\n * Written down the moment the agent names its conversation. Rework replies into the session that wrote the\n * diff rather than re-explaining the work to a stranger, and the run most likely to need rework is the one\n * that ended badly \u2014 so this cannot wait until the run finishes tidily.\n */\n if (value.kind === \"session\") {\n record({ type: \"run.session\", missionId: ids.missionId, runId: ids.runId, sessionId: value.id });\n }\n /*\n * A seat running out belongs to the account, not to this mission \u2014 the next mission needs to know as much as\n * this one does. Recorded here rather than left as a hint the runner may or may not act on, because a limit\n * nobody wrote down is a limit the crew rediscovers by spending on it again.\n */\n if (value.kind === \"limit\") {\n record({\n type: \"seat.limited\",\n seat: context.line.seat.id,\n message: value.message,\n ...(value.resetsAt === undefined ? {} : { resetsAt: value.resetsAt }),\n });\n }\n if (value.kind === \"quota\") {\n record({\n type: \"seat.quota\",\n seat: context.line.seat.id,\n window: value.window,\n utilization: value.utilization,\n ...(value.resetsAt === undefined ? {} : { resetsAt: value.resetsAt }),\n });\n }\n options.onSignal?.(value);\n };\n\n const record = (event: FanoutEventInput): boolean => {\n if (ledgerFailure !== undefined) return false;\n try {\n ledger.append(event);\n return true;\n } catch (error) {\n if (error instanceof InvalidEventError) return false;\n ledgerFailure = error instanceof Error ? error : new Error(String(error));\n void control.handle?.kill(\"the ledger could not record an event\");\n return false;\n }\n };\n\n /** What went wrong with the ledger, if anything. A function so a caller's narrowing cannot go stale. */\n const ledgerBroke = (): Error | undefined => ledgerFailure;\n\n const belongsToRun = (event: FanoutEventInput): boolean =>\n ADAPTER_EVENT_TYPES.has(event.type) &&\n \"runId\" in event &&\n event.missionId === ids.missionId &&\n event.runId === ids.runId;\n\n const handle = supervise({\n runId: context.runId,\n spec,\n logPath: options.logPath,\n ...options.limits,\n onStarted: () => {\n record({ type: \"run.started\", ...ids, workdir: spec.cwd, argv: spec.argv });\n },\n onLine: (line, stream) => {\n const result =\n stream === \"stdout\" ? adapter.parse(line, context) : adapter.parseStderr?.(line, context);\n if (result === undefined) return;\n for (const event of result.events) {\n if (!belongsToRun(event) || !record(event)) {\n if (ledgerFailure === undefined) signal({ kind: \"unparsed\", line });\n break;\n }\n }\n result.signals.forEach(signal);\n },\n });\n\n control.handle = handle;\n\n const finished = handle.done.then(async (exit) => {\n if (ledgerFailure !== undefined) throw ledgerFailure;\n const diffStat = await options.collectDiff?.().catch(() => undefined);\n /*\n * The last event, and the only one recorded after the run is already over. That distinction is the whole\n * reason it is handled separately from `record`: a ledger that closes while a run is *working* must stop it \u2014\n * work nobody can record is a subscription being spent into the void \u2014 but a ledger that closes between the\n * agent exiting and this line has nothing left to stop. The daemon is shutting down and the run is finished.\n *\n * This used to be a bare `ledger.append`, which made the single most important event a run produces the only\n * one with no handling at all. It threw out of this promise with nobody holding it. CI found it on macOS as\n * two errors printed beside 695 passing tests \u2014 the shape of a bug a green suite hides.\n */\n if (ledger.isOpen) {\n record({\n type: \"run.finished\",\n ...ids,\n status: exit.status,\n exitCode: exit.exitCode,\n ...(existsSync(context.reportPath) ? { reportPath: context.reportPath } : {}),\n ...(diffStat === undefined ? {} : { diffStat }),\n });\n /*\n * Read through a call rather than the variable: `record` assigns it from inside a closure, and narrowing\n * from the check at the top of this promise would otherwise make the line below dead code to the compiler\n * and live code at runtime \u2014 which lint caught, correctly.\n */\n const broke = ledgerBroke();\n if (broke !== undefined) throw broke;\n }\n return exit;\n });\n\n return { handle, finished };\n}\n", "import { execFile } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { mkdir, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { pathInScope, type DiffStat, type PlanLine } from \"fanout-core\";\nimport { deniedFiles, DenyListError } from \"./deny.ts\";\nimport { git, lines, zeroSeparated, GitError } from \"./git.ts\";\nimport type {\n RunDiff,\n Workspace,\n WorkspaceManager,\n WorkspaceManagerOptions,\n WorkspaceRequest,\n} from \"./types.ts\";\n\n/*\n * Isolation, done by the daemon so that no agent has to be trusted with it.\n *\n * An editing run gets `git worktree add` on a throwaway branch from the mission's base commit: its own working\n * directory, its own branch, nothing of the user's. An auditor gets an export of the same commit with no `.git`,\n * so it cannot commit, switch branch, read history or reach another run. Ignored files are in neither, because\n * neither is a copy of the user's working tree.\n *\n * What git ignores is not enough on its own: a repository can track a `.env` or a private key. Those are checked\n * for before anything is created, and a workspace is refused rather than quietly exposing them.\n */\n\nconst runProcess = promisify(execFile);\n\nexport { DEFAULT_DENY_LIST, DenyListError } from \"./deny.ts\";\n\nexport function createWorkspaceManager(options: WorkspaceManagerOptions): WorkspaceManager {\n const { repoRoot, workspaceRoot } = options;\n const inRepo = { cwd: repoRoot };\n\n const missionDir = (missionId: string): string => join(workspaceRoot, missionId);\n const runDir = (missionId: string, runId: string): string => join(missionDir(missionId), runId);\n\n const create = async (request: WorkspaceRequest): Promise<Workspace> => {\n const { missionId, runId, baseCommit, line } = request;\n const denied = await deniedFiles(repoRoot, baseCommit, options.denyList);\n if (denied.length > 0) throw new DenyListError(denied);\n\n const path = runDir(missionId, runId);\n await rm(path, { recursive: true, force: true });\n await mkdir(missionDir(missionId), { recursive: true, mode: 0o700 });\n\n if (line.role === \"auditor\") {\n // An export, not a clone: no .git, so nothing to commit into and no history to read.\n await mkdir(path, { recursive: true, mode: 0o700 });\n await git(\n [\"archive\", \"--format=tar\", `--output=${join(missionDir(missionId), `${runId}.tar`)}`, baseCommit],\n inRepo,\n );\n await extractTar(join(missionDir(missionId), `${runId}.tar`), path);\n await rm(join(missionDir(missionId), `${runId}.tar`), { force: true });\n return { missionId, runId, kind: \"archive\", path, branch: null, baseCommit };\n }\n\n const branch = `fanout/${missionId}/${runId}`;\n await git([\"worktree\", \"add\", \"--quiet\", \"-b\", branch, path, baseCommit], inRepo);\n return { missionId, runId, kind: \"worktree\", path, branch, baseCommit };\n };\n\n const collect = async (workspace: Workspace, line: PlanLine): Promise<RunDiff> => {\n if (workspace.kind === \"archive\") {\n return { stat: { files: 0, insertions: 0, deletions: 0 }, patch: \"\", newFiles: [], outsideScope: [] };\n }\n const inWorkspace = { cwd: workspace.path };\n // Against the base commit, not the index: this stays true even if the agent staged or committed, which it\n // must not do but might. `-z` is the only safe listing for paths with spaces or newlines in them.\n const base = workspace.baseCommit;\n const numstat = lines(\n (await git([\"diff\", \"--numstat\", \"-z\", base, \"--\"], inWorkspace)).replaceAll(\"\\0\", \"\\n\"),\n );\n const newFiles = zeroSeparated(\n await git([\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], inWorkspace),\n ).sort();\n const patch = await git([\"diff\", \"--binary\", base, \"--\"], inWorkspace);\n\n const changed = numstat.map((entry) => entry.split(\"\\t\")[2] ?? \"\");\n const stat = numstat.reduce<DiffStat>(\n (total, entry) => {\n const [added, removed] = entry.split(\"\\t\");\n return {\n files: total.files + 1,\n insertions: total.insertions + count(added),\n deletions: total.deletions + count(removed),\n };\n },\n { files: 0, insertions: 0, deletions: 0 },\n );\n\n const touched = [...changed, ...newFiles].filter((file) => file !== \"\");\n const outsideScope = touched\n .filter((file) => !line.scope.write.some((pattern) => pathInScope(file, pattern)))\n .sort();\n\n /*\n * A new file has no tracked diff, so `git diff` says nothing about it at all. Counting it towards the file\n * total while leaving its lines at zero is how a run that wrote a whole file came to report \"+0 \u22120\" \u2014 which\n * reads as a run that did nothing, in the one number a person glances at.\n */\n const added = newFiles.reduce((total, file) => total + linesIn(join(workspace.path, file)), 0);\n\n return {\n stat: {\n files: stat.files + newFiles.length,\n insertions: stat.insertions + added,\n deletions: stat.deletions,\n },\n patch,\n newFiles,\n outsideScope,\n };\n };\n\n /**\n * How many lines a new file adds.\n *\n * Read rather than asked of git, because asking would mean a subprocess per file or writing to the index of a\n * worktree we are only inspecting. Binary files count as nothing: git itself reports `-` instead of a number\n * for them, and turning bytes into a line count would be inventing a figure to put in front of someone.\n */\n const linesIn = (path: string): number => {\n let contents: Buffer;\n try {\n contents = readFileSync(path);\n } catch {\n // Listed a moment ago and gone now: report nothing rather than guess at what it held.\n return 0;\n }\n if (contents.includes(0)) return 0;\n if (contents.length === 0) return 0;\n const newlines = contents.filter((byte) => byte === 0x0a).length;\n // A file that does not end in a newline still ends in a line.\n return contents.at(-1) === 0x0a ? newlines : newlines + 1;\n };\n\n const remove = async (workspace: Workspace): Promise<void> => {\n if (workspace.kind === \"worktree\") {\n await ignoreMissing(git([\"worktree\", \"remove\", \"--force\", workspace.path], inRepo));\n if (workspace.branch !== null) await ignoreMissing(git([\"branch\", \"-D\", workspace.branch], inRepo));\n }\n await rm(workspace.path, { recursive: true, force: true });\n };\n\n const removeAll = async (missionId: string): Promise<void> => {\n const prefix = `fanout/${missionId}/`;\n const branches = lines(\n await git([\"for-each-ref\", \"--format=%(refname:short)\", `refs/heads/${prefix}`], inRepo),\n );\n await rm(missionDir(missionId), { recursive: true, force: true });\n await ignoreMissing(git([\"worktree\", \"prune\"], inRepo));\n for (const branch of branches) await ignoreMissing(git([\"branch\", \"-D\", branch], inRepo));\n };\n\n return { create, collect, remove, removeAll };\n}\n\nfunction count(value: string | undefined): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : 0; // git writes \"-\" for a binary file\n}\n\nasync function extractTar(archive: string, into: string): Promise<void> {\n await runProcess(\"tar\", [\"-x\", \"-f\", archive, \"-C\", into], { windowsHide: true });\n}\n\nasync function ignoreMissing(work: Promise<unknown>): Promise<void> {\n try {\n await work;\n } catch (error) {\n if (!(error instanceof GitError)) throw error;\n }\n}\n", "import { pathInScope } from \"fanout-core\";\nimport { git, zeroSeparated } from \"./git.ts\";\n\n/*\n * What an agent must never receive. Git ignoring a file is not enough on its own: a repository can track a `.env`\n * or a private key, and a worktree of that commit would hand it over. This is checked against the commit itself,\n * before any workspace exists, and it is the same list the safety report shows the user.\n */\n\nexport const DEFAULT_DENY_LIST: readonly string[] = [\n \"**/.env\",\n \"**/.env.*\",\n \"**/*.pem\",\n \"**/*.key\",\n \"**/*.p12\",\n \"**/*.pfx\",\n \"**/*.keystore\",\n \"**/id_rsa*\",\n \"**/id_ed25519*\",\n \"**/.npmrc\",\n \"**/.netrc\",\n \"**/.pgpass\",\n \"**/.ssh/**\",\n \"**/.aws/**\",\n \"**/.gnupg/**\",\n \"**/secrets.*\",\n \"**/credentials\",\n \"**/credentials.*\",\n \"**/service-account*.json\",\n];\n\n/** A workspace was not created because the repository holds something an agent must not see. */\nexport class DenyListError extends Error {\n override name = \"DenyListError\";\n readonly files: readonly string[];\n\n constructor(files: readonly string[]) {\n super(\n `The repository tracks ${files.length} file(s) an agent must never receive: ${files.slice(0, 5).join(\", \")}` +\n `${files.length > 5 ? \", \u2026\" : \"\"}. Remove them from the commit, or narrow the deny-list on purpose.`,\n );\n this.files = files;\n }\n}\n\n/** Tracked files at a commit that the deny-list covers, in the repository's own order. */\nexport async function deniedFiles(\n repoRoot: string,\n baseCommit: string,\n denyList: readonly string[] = DEFAULT_DENY_LIST,\n): Promise<string[]> {\n const tracked = zeroSeparated(\n await git([\"ls-tree\", \"-r\", \"-z\", \"--name-only\", baseCommit], { cwd: repoRoot }),\n );\n return tracked.filter((file) => denyList.some((pattern) => pathInScope(file, pattern)));\n}\n", "export type * from \"./supervisor/types.ts\";\nexport { supervise } from \"./supervisor/supervise.ts\";\nexport { ALLOWED_ENV, baseEnv } from \"./env.ts\";\nexport { startRun, type ActiveRun, type RunLimits, type StartRunOptions } from \"./run.ts\";\n\nexport type * from \"./workspace/types.ts\";\nexport { createWorkspaceManager } from \"./workspace/manager.ts\";\nexport { DEFAULT_DENY_LIST, DenyListError, deniedFiles } from \"./workspace/deny.ts\";\nexport { git, GitError, lines, zeroSeparated, type GitOptions } from \"./workspace/git.ts\";\n\nexport type * from \"./safety/types.ts\";\nexport { safetyReport, type RepositoryState, type SafetyDependencies } from \"./safety/report.ts\";\nexport { createSafetyDependencies, type SafetyDependencyOptions } from \"./safety/dependencies.ts\";\n\nexport { detectSeats, type CommandResult, type DetectOptions } from \"./detector/detect.ts\";\nexport { compareVersions, parseVersion, satisfies, type Version } from \"./detector/version.ts\";\n\nexport {\n createMissionRunner,\n PlanRefused,\n type LaunchRequest,\n type MissionHandle,\n type MissionOutcome,\n type MissionRunnerOptions,\n type RunOutcome,\n} from \"./mission/runner.ts\";\n\nexport { startApi, LEAD_EVENTS, type ApiOptions, type ApiServer } from \"./api/server.ts\";\nexport { originAllowed, readOrCreateToken, tokenMatches } from \"./api/token.ts\";\nexport * from \"./policy/route.ts\";\nexport * from \"./policy/seats.ts\";\nexport * from \"./gate/revision.ts\";\nexport * from \"./gate/buddy.ts\";\nexport * from \"./gate/claims.ts\";\nexport * from \"./gate/run-seat.ts\";\nexport { missionViewHtml } from \"./api/view.ts\";\nexport * from \"./gate/checks.ts\";\nexport * from \"./gate/proof.ts\";\nexport * from \"./gate/merge.ts\";\nexport * from \"./gate/rework.ts\";\n", "import { pathInScope, validatePlan, type LaunchSpec, type PlanGraph, type SafetyCheck } from \"fanout-core\";\nimport type { SafetyCheckId, SafetyInput, SafetyReport } from \"./types.ts\";\n\n/*\n * The gate between a plan and running it.\n *\n * Every check is computed here from the plan, the repository and the seats as detected \u2014 never from an agent's\n * word \u2014 and every one names the lines it concerns, so \"why can't I launch?\" always has a specific answer.\n * A check that cannot be evaluated says so and warns; it never passes quietly, because a gate that looks green\n * when it is not is worse than no gate.\n */\n\n/** Flags that hand an agent the machine. A command carrying one never launches. */\nconst FORBIDDEN_FLAGS: readonly { flag: string; why: string }[] = [\n { flag: \"--dangerously-bypass-approvals-and-sandbox\", why: \"it turns off the sandbox and every approval\" },\n { flag: \"--dangerously-skip-permissions\", why: \"it bypasses every permission check\" },\n { flag: \"--dangerously-bypass-hook-trust\", why: \"it runs untrusted hooks\" },\n { flag: \"danger-full-access\", why: \"it gives the run full access to the machine\" },\n { flag: \"bypassPermissions\", why: \"it bypasses every permission check\" },\n { flag: \"--always-approve\", why: \"it approves whatever the agent asks for\" },\n { flag: \"--yolo\", why: \"it auto-approves tool calls\" },\n { flag: \"--approve-for-me\", why: \"it approves the agent's requests automatically\" },\n];\n\nexport interface RepositoryState {\n /** Where the repository is now. */\n head: string;\n /** Paths with uncommitted changes, relative to the repository root. */\n dirty: readonly string[];\n}\n\nexport interface SafetyDependencies {\n /** Tracked files at the base commit that the deny-list covers. */\n deniedFiles: (baseCommit: string) => Promise<readonly string[]>;\n /** The repository as it is right now. */\n repositoryState: () => Promise<RepositoryState>;\n}\n\nexport async function safetyReport(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyReport> {\n const checks: SafetyCheck[] = [\n ...planChecks(input.plan),\n await secretsCheck(input, deps),\n ...seatChecks(input),\n ...commandChecks(input),\n concurrencyCheck(input),\n await baseCommitCheck(input, deps),\n ];\n\n return {\n ok: checks.every((check) => check.ok || check.severity === \"warn\"),\n planRevision: input.planRevision,\n checks,\n dryRun: input.plan.lines.map((line) => ({\n lineId: line.id,\n seat: line.seat.id,\n argv: input.commands[line.id]?.argv ?? [],\n cwd: input.commands[line.id]?.cwd ?? \"\",\n })),\n };\n}\n\nfunction check(\n id: SafetyCheckId,\n ok: boolean,\n severity: SafetyCheck[\"severity\"],\n message: string,\n lineIds?: string[],\n): SafetyCheck {\n return { id, ok, severity, message, ...(lineIds === undefined ? {} : { lineIds }) };\n}\n\n/** Two of the eight come straight from the plan schema: scopes must be declared, and must not overlap. */\nfunction planChecks(plan: PlanGraph): SafetyCheck[] {\n const issues = validatePlan(plan);\n const overlaps = issues.filter((issue) => issue.code === \"scope_overlap\");\n const structural = issues.filter((issue) => issue.code !== \"scope_overlap\");\n\n return [\n check(\n \"scopes-disjoint\",\n overlaps.length === 0,\n \"block\",\n overlaps.length === 0\n ? \"No two lines that can run at the same time write the same path.\"\n : overlaps.map((issue) => issue.message).join(\" \"),\n overlaps.flatMap((issue) => issue.lineIds),\n ),\n check(\n \"scopes-declared\",\n structural.length === 0,\n \"block\",\n structural.length === 0\n ? \"Every line declares where it may write, and the plan's dependencies make sense.\"\n : structural.map((issue) => issue.message).join(\" \"),\n structural.flatMap((issue) => issue.lineIds),\n ),\n ];\n}\n\nasync function secretsCheck(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyCheck> {\n const denied = await deps.deniedFiles(input.repo.baseCommit);\n return check(\n \"secrets-excluded\",\n denied.length === 0,\n \"block\",\n denied.length === 0\n ? \"Nothing the deny-list covers is tracked at the base commit; ignored files are in no workspace.\"\n : `The repository tracks ${denied.length} file(s) an agent must never receive: ${denied\n .slice(0, 5)\n .join(\", \")}${denied.length > 5 ? \", \u2026\" : \"\"}.`,\n );\n}\n\nfunction seatChecks(input: SafetyInput): SafetyCheck[] {\n const missing: string[] = [];\n const unsupported: string[] = [];\n const signedOut: string[] = [];\n const unknown: string[] = [];\n\n for (const line of input.plan.lines) {\n const seat = input.seats[line.seat.id];\n if (seat === undefined) missing.push(line.id);\n else if (!seat.supported) unsupported.push(line.id);\n else if (seat.signedIn === \"no\") signedOut.push(line.id);\n else if (seat.signedIn === \"unknown\") unknown.push(line.id);\n }\n\n const blocked = [...missing, ...unsupported, ...signedOut];\n const reasons = [\n missing.length > 0 ? `not installed (${missing.join(\", \")})` : \"\",\n unsupported.length > 0 ? `an unsupported version (${unsupported.join(\", \")})` : \"\",\n signedOut.length > 0 ? `not signed in (${signedOut.join(\", \")})` : \"\",\n ].filter((reason) => reason !== \"\");\n\n return [\n check(\n \"seat-available\",\n blocked.length === 0,\n \"block\",\n blocked.length === 0\n ? \"Every line's seat is installed, signed in and a version we support.\"\n : `Some lines have no usable seat: ${reasons.join(\"; \")}.`,\n blocked,\n ),\n ...(unknown.length === 0\n ? []\n : [\n check(\n \"seat-available\",\n false,\n \"warn\",\n `Sign-in state is unknown for ${unknown.length} line(s); the seat's CLI has no status command, ` +\n \"so a run may fail at launch.\",\n unknown,\n ),\n ]),\n ];\n}\n\nfunction commandChecks(input: SafetyInput): SafetyCheck[] {\n const missing = input.plan.lines\n .filter((line) => input.commands[line.id] === undefined)\n .map((line) => line.id);\n const dangerous: { lineId: string; why: string }[] = [];\n\n for (const line of input.plan.lines) {\n const spec: LaunchSpec | undefined = input.commands[line.id];\n if (spec === undefined) continue;\n const argv = spec.argv.join(\" \");\n for (const { flag, why } of FORBIDDEN_FLAGS) {\n if (argv.includes(flag)) dangerous.push({ lineId: line.id, why: `${flag}: ${why}` });\n }\n }\n\n return [\n check(\n \"permission-mode\",\n missing.length === 0 && dangerous.length === 0,\n \"block\",\n missing.length > 0\n ? `No command was built for ${missing.join(\", \")}, so there is nothing to show you before launch.`\n : dangerous.length === 0\n ? \"Every seat runs in the safest mode that can still do its work.\"\n : dangerous.map((entry) => `${entry.lineId} would run with ${entry.why}`).join(\"; \"),\n [...missing, ...dangerous.map((entry) => entry.lineId)],\n ),\n check(\n \"network\",\n true,\n \"warn\",\n \"Network isolation is the CLI's own: we select the safest mode each seat offers and cannot verify more \" +\n \"than that. Treat a run as able to reach the network unless its vendor documents otherwise.\",\n ),\n ];\n}\n\nfunction concurrencyCheck(input: SafetyInput): SafetyCheck {\n const starting = input.plan.lines.filter((line) => line.dependsOn.length === 0);\n const perSeat = new Map<string, number>();\n for (const line of starting) perSeat.set(line.seat.id, (perSeat.get(line.seat.id) ?? 0) + 1);\n\n const overSeat = [...perSeat.entries()].filter(([seat, count]) => {\n const cap = input.limits.perSeat[seat];\n return cap !== undefined && count > cap;\n });\n const overall = starting.length > input.limits.maxParallel;\n\n return check(\n \"concurrency\",\n !overall && overSeat.length === 0,\n \"block\",\n overall\n ? `${starting.length} lines would start at once but the mission allows ${input.limits.maxParallel}.`\n : overSeat.length > 0\n ? overSeat\n .map(\n ([seat, count]) =>\n `${count} lines would start on ${seat}, which allows ${input.limits.perSeat[seat] ?? 0}`,\n )\n .join(\"; \")\n : `${starting.length} line(s) start at once, within the mission's limit of ${input.limits.maxParallel}.`,\n starting.map((line) => line.id),\n );\n}\n\nasync function baseCommitCheck(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyCheck> {\n const state = await deps.repositoryState();\n if (state.head !== input.repo.baseCommit) {\n return check(\n \"base-commit\",\n false,\n \"block\",\n `The repository is at ${state.head.slice(0, 7)} but the mission plans from ` +\n `${input.repo.baseCommit.slice(0, 7)}. Re-plan from where you are, or check out that commit.`,\n );\n }\n\n const conflicts = state.dirty.filter((path) =>\n input.plan.lines.some((line) => line.scope.write.some((pattern) => pathInScope(path, pattern))),\n );\n return check(\n \"base-commit\",\n conflicts.length === 0,\n \"block\",\n conflicts.length === 0\n ? \"The repository is at the mission's base commit, with nothing uncommitted inside any line's scope.\"\n : `Uncommitted changes sit inside a line's scope (${conflicts.slice(0, 5).join(\", \")}); commit or stash ` +\n \"them, or the merge will fight you later.\",\n );\n}\n", "import { deniedFiles } from \"../workspace/deny.ts\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\nimport type { RepositoryState, SafetyDependencies } from \"./report.ts\";\n\n/*\n * What the safety gate needs from the repository itself. Keeping it here means the report stays a pure function of\n * facts, and these two calls are the only place those facts come from.\n */\n\nexport interface SafetyDependencyOptions {\n repoRoot: string;\n denyList?: readonly string[];\n}\n\nexport function createSafetyDependencies(options: SafetyDependencyOptions): SafetyDependencies {\n const inRepo = { cwd: options.repoRoot };\n\n return {\n deniedFiles: (baseCommit) => deniedFiles(options.repoRoot, baseCommit, options.denyList),\n\n repositoryState: async (): Promise<RepositoryState> => {\n const head = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n const entries = zeroSeparated(await git([\"status\", \"--porcelain=v1\", \"-z\"], inRepo));\n const dirty: string[] = [];\n\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined) continue;\n const status = entry.slice(0, 2);\n const path = entry.slice(3);\n if (path !== \"\") dirty.push(path);\n // A rename or copy carries its source as the next entry; both paths count as touched.\n if (status.startsWith(\"R\") || status.startsWith(\"C\")) {\n const source = entries[index + 1];\n if (source !== undefined) {\n dirty.push(source);\n index += 1;\n }\n }\n }\n\n return { head, dirty };\n },\n };\n}\n", "import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { SeatInfo, type AdapterManifest } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { parseVersion, satisfies } from \"./version.ts\";\n\n/*\n * Who is on the crew. For each adapter we ask the CLI itself three things: are you here, which version are you, and\n * are you signed in \u2014 the last one through the CLI's own status command. We never read a credential file, never\n * parse a token, and never guess: a CLI we cannot find, cannot read a version from, or whose version is outside the\n * range its adapter was verified against is reported as unsupported, and one that cannot tell us its sign-in state\n * says \"unknown\" rather than \"yes\".\n */\n\nconst run = promisify(execFile);\n\nexport interface CommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\nexport interface DetectOptions {\n manifests: readonly AdapterManifest[];\n /** Runs a CLI. Injected in tests so detection needs no CLIs installed. */\n execute?: (binary: string, args: readonly string[]) => Promise<CommandResult>;\n /** How long any single probe may take before it counts as not answering. */\n timeoutMs?: number;\n}\n\nexport async function detectSeats(options: DetectOptions): Promise<SeatInfo[]> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const execute = options.execute ?? defaultExecute(timeoutMs);\n // Every probe gets its own deadline, and so does the seat as a whole: a CLI can hang between probes as easily\n // as during one, and `execFile`'s own timeout does not exist at all when a caller injects an executor.\n const bounded = (binary: string, args: readonly string[]): Promise<CommandResult> =>\n within(execute(binary, args), timeoutMs, null).then((result) => result ?? NO_ANSWER);\n\n return Promise.all(\n options.manifests.map(async (manifest) =>\n // Detection is the first thing a session does, so it must always finish. One CLI that never answers must\n // not hide the seats that did: an unfinished probe becomes \"unknown\" for that seat and nothing more.\n within(detectSeat(manifest, bounded), timeoutMs * 3, unknownSeat(manifest)),\n ),\n );\n}\n\n/** What a probe that never answered \"said\". Not an error: we simply do not know, which is a valid answer here. */\nconst NO_ANSWER: CommandResult = { stdout: \"\", stderr: \"\", exitCode: -1 };\n\n/**\n * Resolves with `whenLate` if `work` has not settled in time.\n *\n * A promise cannot be cancelled, so this stops *waiting*; it does not stop the work. That is the honest\n * description and also the safe one: for the real executor the child already carries its own kill timeout, and\n * for an injected one there is nothing to kill. The timer is unref'd so a straggler cannot hold the process open.\n */\nfunction within<T>(work: Promise<T>, ms: number, whenLate: T): Promise<T> {\n return new Promise<T>((resolve) => {\n const timer = setTimeout(() => {\n resolve(whenLate);\n }, ms);\n timer.unref();\n work.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(whenLate);\n },\n );\n });\n}\n\nfunction unknownSeat(manifest: AdapterManifest): SeatInfo {\n return {\n id: manifest.id,\n displayName: manifest.displayName,\n binary: manifest.binary,\n models: manifest.models,\n efforts: manifest.efforts,\n billing: manifest.billing,\n version: null,\n supported: false,\n signedIn: \"unknown\",\n plan: null,\n };\n}\n\nasync function detectSeat(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo> {\n const base = {\n id: manifest.id,\n displayName: manifest.displayName,\n binary: manifest.binary,\n models: manifest.models,\n efforts: manifest.efforts,\n billing: manifest.billing,\n };\n\n const versionResult = await attempt(() => execute(manifest.binary, [\"--version\"]));\n if (versionResult?.exitCode !== 0) {\n return { ...base, version: null, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const version = parseVersion(`${versionResult.stdout} ${versionResult.stderr}`);\n if (version === null) {\n return { ...base, version: null, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const printed = `${version.major}.${version.minor}.${version.patch}`;\n const supported = satisfies(version, manifest.supportedVersions);\n if (!supported) {\n // A stream we have not seen is a stream we cannot parse honestly, so we stop at the version \u2014 and in\n // particular we do not send an unverified build a probe whose answer we would not know how to read.\n return { ...base, version: printed, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const [signedIn, plan] = await Promise.all([signInState(manifest, execute), planState(manifest, execute)]);\n return { ...base, version: printed, supported: true, signedIn, plan };\n}\n\n/**\n * Keep only the fields the manifest allows, and drop everything else before it can travel any further.\n *\n * This is the whole of the privacy control, and it is deliberately four lines in one place. The probe that reports\n * Claude's subscription tier answers with the user's email address and organisation id in the same object; those\n * must never reach the ledger, a log, a projection or a prompt. Filtering at the moment of reading \u2014 rather than\n * remembering not to use the extra fields later \u2014 is what makes that a property of the code instead of a habit.\n */\nfunction keepAllowed(parsed: Record<string, unknown>, keep: readonly string[]): Record<string, unknown> {\n return Object.fromEntries(\n keep.filter((field) => Object.hasOwn(parsed, field)).map((field) => [field, parsed[field]]),\n );\n}\n\nasync function planState(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo[\"plan\"]> {\n const { plan } = manifest.capabilities;\n if (plan === null) return null;\n\n const result = await attempt(() => execute(manifest.binary, plan.probe));\n if (result?.exitCode !== 0) return null;\n\n const parsed = parseJsonObject(result.stdout);\n if (parsed === null) return null;\n\n const kept = keepAllowed(parsed, plan.keep);\n\n // A tier belongs to an account, so a signed-out answer carries no current plan \u2014 only, at best, the last one\n // this machine happened to see. `loggedIn` is on the allowlist precisely so this question can be asked.\n if (Object.hasOwn(kept, \"loggedIn\") && kept[\"loggedIn\"] !== true) return null;\n\n const name = kept[plan.planField];\n // A CLI that answers in a shape we did not expect has told us nothing, and a guess here would be recorded as a\n // fact and routed on. The schema has the final say, so detection cannot return a seat it could not itself store.\n const candidate = typeof name === \"string\" ? { name, source: \"detected\" as const } : null;\n const checked = SeatInfo.shape.plan.safeParse(candidate);\n return checked.success ? checked.data : null;\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> | null {\n try {\n const value: unknown = JSON.parse(text);\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nasync function signInState(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo[\"signedIn\"]> {\n const { probe, okPattern, noPattern } = manifest.signIn;\n if (probe === null) return \"unknown\";\n\n const result = await attempt(() => execute(manifest.binary, probe));\n if (result === null) return \"unknown\";\n\n const answer = `${result.stdout}\\n${result.stderr}`;\n // Signed out is checked first and on its own terms. \"Not logged in\" contains \"Logged in\", so a positive\n // pattern asked first will happily read a refusal as an approval \u2014 which is exactly what this code used to do.\n if (noPattern !== null && matches(noPattern, answer)) return \"no\";\n if (okPattern !== null && matches(okPattern, answer)) return \"yes\";\n\n // Neither shape. A non-zero exit with nothing we recognise is a failure to answer, not an answer of \"no\":\n // reporting \"no\" would route someone's work away from a seat that may be perfectly fine.\n return \"unknown\";\n}\n\n/**\n * Runs a manifest's pattern against a bounded prefix of the CLI's output.\n *\n * The bound is the point. A pattern is compiled when the manifest is parsed, so it is valid, but validity says\n * nothing about cost: `^(a+)+$` against a long line backtracks for effectively ever, and a regular expression is\n * synchronous, so no timeout anywhere else in this file can interrupt it. Sign-in answers are short; anything\n * past a couple of kilobytes is not the answer we are looking for.\n */\nfunction matches(pattern: string, text: string): boolean {\n return new RegExp(pattern, \"i\").test(text.slice(0, 2_000));\n}\n\n/** A probe that throws, hangs or cannot start tells us nothing; it must never take the daemon down with it. */\nasync function attempt(work: () => Promise<CommandResult>): Promise<CommandResult | null> {\n try {\n return await work();\n } catch {\n return null;\n }\n}\n\nfunction defaultExecute(timeoutMs: number) {\n return async (binary: string, args: readonly string[]): Promise<CommandResult> => {\n try {\n const { stdout, stderr } = await run(binary, [...args], {\n timeout: timeoutMs,\n env: baseEnv(),\n windowsHide: true,\n });\n return { stdout, stderr, exitCode: 0 };\n } catch (cause) {\n const detail = cause as { stdout?: string; stderr?: string; code?: number };\n // A CLI that answers \"not signed in\" with a non-zero exit is answering, not failing.\n if (typeof detail.code === \"number\") {\n return { stdout: detail.stdout ?? \"\", stderr: detail.stderr ?? \"\", exitCode: detail.code };\n }\n throw cause;\n }\n };\n}\n", "/*\n * Just enough semantic versioning to answer one question: is this CLI inside the range its adapter was verified\n * against? A whole dependency for that would be a dependency to keep current, and the answer has to be boring.\n *\n * A range is a space-separated list of comparators that must all hold, for example \">=0.150.0 <1.0.0\".\n * Anything we cannot read is not a match, because \"unsupported\" is the honest answer to a version we don't know.\n */\n\nexport interface Version {\n major: number;\n minor: number;\n patch: number;\n}\n\nconst VERSION = /(\\d+)\\.(\\d+)(?:\\.(\\d+))?/;\n// A bound may name as much as it likes: \">=0.150.0\", \">=1.0\" and \"<2\" are all ordinary ways to write a range.\nconst COMPARATOR = /^(>=|<=|>|<|=)?\\s*(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/;\n\n/** The first version in a CLI's `--version` output, whatever else it prints around it. */\nexport function parseVersion(text: string): Version | null {\n const found = VERSION.exec(text);\n if (found === null) return null;\n return {\n major: Number(found[1]),\n minor: Number(found[2]),\n patch: Number(found[3] ?? 0),\n };\n}\n\nexport function compareVersions(a: Version, b: Version): number {\n return a.major - b.major || a.minor - b.minor || a.patch - b.patch;\n}\n\nexport function satisfies(version: Version, range: string): boolean {\n const comparators = range.trim().split(/\\s+/).filter(Boolean);\n if (comparators.length === 0) return false;\n\n return comparators.every((text) => {\n const found = COMPARATOR.exec(text);\n if (found === null) return false;\n const bound: Version = {\n major: Number(found[2]),\n minor: Number(found[3] ?? 0),\n patch: Number(found[4] ?? 0),\n };\n const order = compareVersions(version, bound);\n switch (found[1] ?? \"=\") {\n case \">=\":\n return order >= 0;\n case \"<=\":\n return order <= 0;\n case \">\":\n return order > 0;\n case \"<\":\n return order < 0;\n default:\n return order === 0;\n }\n });\n}\n", "import { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n validatePlan,\n type AdapterSignal,\n type Ledger,\n type PlanGraph,\n type PlanLine,\n type SeatAdapter,\n} from \"fanout-core\";\nimport type { Routing } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { startRun, type RunLimits } from \"../run.ts\";\nimport type { RunExitStatus } from \"../supervisor/types.ts\";\nimport type { Workspace, WorkspaceManager } from \"../workspace/types.ts\";\n\n/*\n * A plan becomes runs here. The rules it keeps are the ones a person would expect and a machine forgets:\n *\n * - a line starts only when every line it depends on has finished well;\n * - a line whose dependency failed is dropped with the reason, never started hopefully;\n * - no more lines run at once than the mission allows;\n * - every run gets its own workspace, and the workspace stays afterwards so the diff can be reviewed;\n * - an invalid plan never runs at all.\n *\n * It records what happens as events. It does not review, merge or reroute: those are the gate's job, and a runner\n * that quietly merged would be the most dangerous code in the project.\n */\n\nexport interface MissionRunnerOptions {\n /**\n * Where each line should actually run, asked as the line starts.\n *\n * Injected rather than worked out here: the runner has a ledger and a set of adapters, not the crew's sign-in\n * state or the owner's posture, and giving it those would put three more reasons to change into the one place\n * that must not be wrong. Omitted, every line runs on the seat the plan named.\n */\n route?: (line: PlanLine) => Routing;\n ledger: Ledger;\n workspaces: WorkspaceManager;\n /** Seat id to the adapter that drives it. A line whose seat is missing is dropped, not guessed at. */\n adapters: ReadonlyMap<string, SeatAdapter>;\n /** Run logs and reports live under `<runsRoot>/<missionId>/<runId>/`. */\n runsRoot: string;\n limits: RunLimits;\n onSignal?: (runId: string, signal: AdapterSignal) => void;\n}\n\nexport interface LaunchRequest {\n missionId: string;\n plan: PlanGraph;\n baseCommit: string;\n maxParallel: number;\n}\n\nexport interface RunOutcome {\n runId: string;\n lineId: string;\n status: RunExitStatus | \"dropped\";\n workspace: Workspace | null;\n reason?: string;\n}\n\nexport interface MissionOutcome {\n missionId: string;\n runs: RunOutcome[];\n done: number;\n failed: number;\n dropped: number;\n}\n\nexport interface MissionHandle {\n readonly missionId: string;\n readonly finished: Promise<MissionOutcome>;\n /** Stops everything still running. The mission finishes with those runs marked killed. */\n cancel(reason: string): Promise<void>;\n}\n\n/** A plan that does not pass its own validation never becomes runs. */\nexport class PlanRefused extends Error {\n override name = \"PlanRefused\";\n readonly issues: readonly { code: string; message: string; lineIds: string[] }[];\n\n constructor(issues: readonly { code: string; message: string; lineIds: string[] }[]) {\n super(`This plan cannot run:\\n${issues.map((issue) => ` - ${issue.message}`).join(\"\\n\")}`);\n this.issues = issues;\n }\n}\n\nexport function createMissionRunner(options: MissionRunnerOptions) {\n return {\n launch(request: LaunchRequest): MissionHandle {\n const issues = validatePlan(request.plan);\n if (issues.length > 0) throw new PlanRefused(issues);\n return run(options, request);\n },\n };\n}\n\nfunction run(options: MissionRunnerOptions, request: LaunchRequest): MissionHandle {\n const { ledger, workspaces, adapters, limits } = options;\n const byId = new Map(request.plan.lines.map((line) => [line.id, line]));\n const waiting = new Set(byId.keys());\n const outcomes = new Map<string, RunOutcome>();\n const active = new Map<string, { kill: (reason: string) => Promise<unknown>; settled: Promise<void> }>();\n let cancelling: string | undefined;\n\n const finishedWell = (lineId: string): boolean => outcomes.get(lineId)?.status === \"done\";\n const finishedBadly = (lineId: string): boolean => {\n const status = outcomes.get(lineId)?.status;\n return status !== undefined && status !== \"done\";\n };\n\n const drop = (line: PlanLine, reason: string): void => {\n const runId = runIdFor(line);\n ledger.append({\n type: \"run.queued\",\n missionId: request.missionId,\n runId,\n lineId: line.id,\n seat: line.seat,\n attempt: 1,\n });\n ledger.append({ type: \"run.dropped\", missionId: request.missionId, runId, reason });\n outcomes.set(line.id, { runId, lineId: line.id, status: \"dropped\", workspace: null, reason });\n waiting.delete(line.id);\n };\n\n const start = async (line: PlanLine): Promise<void> => {\n /*\n * Decided at the moment the line starts, not when the mission was planned: a seat that was fine an hour ago\n * may have run out since, and the line after this one may be the one that finds out. A move is recorded\n * before anything runs, so the reason is in the history whatever happens next.\n */\n const routing = options.route?.(line) ?? { kind: \"keep\" as const, seat: line.seat.id };\n if (routing.kind === \"stuck\") {\n drop(line, routing.reason);\n return;\n }\n if (routing.kind === \"move\") {\n ledger.append({\n type: \"route.changed\",\n missionId: request.missionId,\n lineId: line.id,\n from: { id: routing.from },\n to: { id: routing.seat },\n reason: routing.reason,\n });\n /*\n * The id moves and the model does not. `gpt-5-codex` means nothing to Claude's CLI, and a model string a\n * seat does not recognise is how we already lost twenty minutes once \u2014 Codex answered \"The '' model is not\n * supported\" and sat there. The new seat gets its own default, which is the only model we know it has.\n */\n line = { ...line, seat: { id: routing.seat } };\n }\n\n const runId = runIdFor(line);\n const adapter = adapters.get(line.seat.id);\n if (adapter === undefined) {\n drop(line, `no adapter is installed for the seat \"${line.seat.id}\"`);\n return;\n }\n\n waiting.delete(line.id);\n ledger.append({\n type: \"run.queued\",\n missionId: request.missionId,\n runId,\n lineId: line.id,\n seat: line.seat,\n attempt: 1,\n });\n\n const directory = join(options.runsRoot, request.missionId, runId);\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n const workspace = await workspaces.create({\n missionId: request.missionId,\n runId,\n baseCommit: request.baseCommit,\n line,\n });\n\n const started = startRun({\n ledger,\n adapter,\n context: {\n missionId: request.missionId,\n runId,\n line,\n workdir: workspace.path,\n reportPath: join(directory, \"report.md\"),\n baseEnv: baseEnv(),\n },\n logPath: join(directory, \"run.log\"),\n limits,\n collectDiff: async () => (await workspaces.collect(workspace, line)).stat,\n ...(options.onSignal === undefined\n ? {}\n : { onSignal: (signal: AdapterSignal) => options.onSignal?.(runId, signal) }),\n });\n\n const settled = started.finished\n .then((exit) => {\n outcomes.set(line.id, { runId, lineId: line.id, status: exit.status, workspace });\n })\n .catch((error: unknown) => {\n outcomes.set(line.id, {\n runId,\n lineId: line.id,\n status: \"failed\",\n workspace,\n reason: error instanceof Error ? error.message : \"the run could not be recorded\",\n });\n })\n .finally(() => {\n active.delete(line.id);\n });\n\n active.set(line.id, { kill: (reason) => started.handle.kill(reason), settled });\n };\n\n const finished = (async (): Promise<MissionOutcome> => {\n while (waiting.size > 0 || active.size > 0) {\n for (const lineId of [...waiting]) {\n const line = byId.get(lineId);\n if (line === undefined) continue;\n if (cancelling !== undefined) {\n drop(line, cancelling);\n continue;\n }\n if (line.dependsOn.some(finishedBadly)) {\n const blocker = line.dependsOn.find(finishedBadly) ?? \"a line it depends on\";\n drop(line, `\"${blocker}\" did not finish, so this line was not started`);\n continue;\n }\n if (active.size >= request.maxParallel) break;\n if (line.dependsOn.every(finishedWell)) await start(line);\n }\n\n if (active.size > 0) await Promise.race([...active.values()].map((entry) => entry.settled));\n else if (waiting.size > 0 && [...waiting].every((id) => !ready(id, byId, finishedWell))) {\n // Nothing can start and nothing is running: whatever is left is waiting on something that never happened.\n for (const lineId of [...waiting]) {\n const line = byId.get(lineId);\n if (line !== undefined) drop(line, \"the lines it depends on never finished\");\n }\n }\n }\n\n const runs = [...outcomes.values()];\n return {\n missionId: request.missionId,\n runs,\n done: runs.filter((outcome) => outcome.status === \"done\").length,\n failed: runs.filter((outcome) => outcome.status !== \"done\" && outcome.status !== \"dropped\").length,\n dropped: runs.filter((outcome) => outcome.status === \"dropped\").length,\n };\n })();\n\n return {\n missionId: request.missionId,\n finished,\n async cancel(reason: string): Promise<void> {\n cancelling = reason;\n await Promise.all([...active.values()].map((entry) => entry.kill(reason)));\n },\n };\n}\n\nfunction ready(lineId: string, byId: Map<string, PlanLine>, finishedWell: (id: string) => boolean): boolean {\n return byId.get(lineId)?.dependsOn.every(finishedWell) ?? false;\n}\n\n/** One attempt per line for now; rework (attempt 2 and 3) arrives with the merge gate. */\nfunction runIdFor(line: PlanLine): string {\n return `${line.id}-1`;\n}\n", "import { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { Socket } from \"node:net\";\nimport {\n blocksApproval,\n mergeReadiness,\n project,\n type EventType,\n type Ledger,\n type ProjectionState,\n type SeatInfo,\n type StoredEvent,\n} from \"fanout-core\";\nimport { WebSocketServer, type WebSocket } from \"ws\";\nimport { originAllowed, tokenMatches } from \"./token.ts\";\n\n/*\n * The daemon's only door. It binds to 127.0.0.1, never to an interface anyone else can reach, and every request\n * carries the daemon's token \u2014 \"local\" is not the same as \"yours\" on a shared machine. Requests that arrive with a\n * browser's Origin are refused before a handler sees them, so a web page cannot drive your crew.\n *\n * Two ways to read: ask for what is there now over HTTP, or subscribe over a WebSocket and be told as it happens.\n * The subscription is what the lead's Monitor listens to, which is why it can be narrowed to the events a lead\n * actually acts on: a feed that repeats everything is a feed nobody reads.\n */\n\n/** The events a lead acts on. Everything else is for the mission view, which asks for the lot. */\nexport const LEAD_EVENTS: readonly EventType[] = [\n \"run.finished\",\n \"merge.conflict\",\n \"policy.breach\",\n \"route.changed\",\n \"safety.report\",\n \"mission.finished\",\n];\n\nexport interface ApiOptions {\n ledger: Ledger;\n token: string;\n /** The crew as last detected. Async because asking the CLIs takes a moment. */\n crew?: () => Promise<readonly SeatInfo[]>;\n /** 0 asks the operating system for a free port, which is what tests want. */\n port?: number;\n /**\n * The mission view's HTML, with `{{TOKEN}}` wherever the page needs this daemon's token.\n *\n * Passed in rather than read from disk here so the daemon has no opinion about where the page lives, and so a\n * test can serve a one-line page without a file.\n */\n view?: () => string;\n}\n\nexport interface ApiServer {\n readonly port: number;\n readonly url: string;\n /** Tells every subscriber about an event that was just recorded. */\n publish(event: StoredEvent): void;\n close(): Promise<void>;\n}\n\ninterface Subscriber {\n socket: WebSocket;\n types: ReadonlySet<EventType> | null;\n missionId: string | null;\n}\n\nexport async function startApi(options: ApiOptions): Promise<ApiServer> {\n const subscribers = new Set<Subscriber>();\n const sockets = new Set<Socket>();\n\n const server = createServer((request, response) => {\n handle(request, response, options).catch((error: unknown) => {\n send(response, 500, { error: error instanceof Error ? error.message : \"unknown error\" });\n });\n });\n server.on(\"connection\", (socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n });\n\n const websockets = new WebSocketServer({ noServer: true });\n server.on(\"upgrade\", (request, socket, head) => {\n const url = parseUrl(request);\n const port = (server.address() as { port: number } | null)?.port ?? 0;\n const authorized =\n originAllowed(request.headers.origin, port) &&\n tokenMatches(\n options.token,\n request.headers.authorization ?? url.searchParams.get(\"token\") ?? undefined,\n );\n\n if (!authorized || url.pathname !== \"/events\") {\n socket.write(`HTTP/1.1 ${authorized ? 404 : 401} ${authorized ? \"Not Found\" : \"Unauthorized\"}\\r\\n\\r\\n`);\n socket.destroy();\n return;\n }\n\n websockets.handleUpgrade(request, socket, head, (ws) => {\n const subscriber: Subscriber = {\n socket: ws,\n types: typesFrom(url),\n missionId: url.searchParams.get(\"missionId\"),\n };\n subscribers.add(subscriber);\n ws.on(\"close\", () => subscribers.delete(subscriber));\n\n // Replay first, then live: a subscriber that joins mid-mission still sees how it got here.\n const afterSeq = Number(url.searchParams.get(\"afterSeq\") ?? 0);\n for (const event of options.ledger.read({ afterSeq })) {\n if (wanted(subscriber, event)) ws.send(JSON.stringify(event));\n }\n });\n });\n\n await new Promise<void>((resolve) => {\n server.listen(options.port ?? 0, \"127.0.0.1\", resolve);\n });\n const port = (server.address() as { port: number } | null)?.port ?? 0;\n\n return {\n port,\n url: `http://127.0.0.1:${port}`,\n publish(event) {\n for (const subscriber of subscribers) {\n if (wanted(subscriber, event)) subscriber.socket.send(JSON.stringify(event));\n }\n },\n close: () => close(server, websockets, sockets, subscribers),\n };\n}\n\nasync function handle(\n request: IncomingMessage,\n response: ServerResponse,\n options: ApiOptions,\n): Promise<void> {\n const url = parseUrl(request);\n const port = Number(request.headers.host?.split(\":\")[1] ?? 0);\n\n // Health says nothing about you, so it needs no token: it is how a client knows a daemon is there at all.\n if (url.pathname === \"/health\") {\n send(response, 200, { ok: true, name: \"fanout\" });\n return;\n }\n\n /*\n * The mission view itself, and the only route that answers a browser.\n *\n * It carries no data \u2014 the page asks for that with the token it is handed below \u2014 so serving it before the\n * Origin and token checks gives away nothing except that a daemon is running, which `/health` already says.\n * A browser cannot send an Authorization header on a plain navigation, which is why the token is stamped into\n * the page rather than demanded from it.\n */\n if (url.pathname === \"/\" && options.view !== undefined) {\n const page = options.view().replaceAll(\"{{TOKEN}}\", options.token);\n response.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n // It shows your source code: nothing about it may be cached, framed, or fetched from anywhere else.\n \"cache-control\": \"no-store\",\n \"content-security-policy\":\n \"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n });\n response.end(page);\n return;\n }\n\n if (!originAllowed(request.headers.origin, port)) {\n send(response, 403, { error: \"a page in a browser cannot drive the daemon\" });\n return;\n }\n if (!tokenMatches(options.token, request.headers.authorization)) {\n send(response, 401, { error: \"this daemon needs its token; it is in ~/.fanout/token\" });\n return;\n }\n /*\n * The one thing this daemon lets a person do rather than read, and the reason it is worth the write route.\n *\n * An approval recorded through the lead's tool is a language model's account of a conversation: `via: relayed`,\n * and an agent that never asked writes a byte-identical event. This one is `via: direct` \u2014 the daemon received\n * the click itself, over loopback, with its own token, from the page it served. Nothing in between could have\n * invented it, and the ledger can finally tell the two apart.\n *\n * It approves and stops there. Merging needs a commit message in the repository's own convention, which the\n * lead writes; and leaving the apply to the gate means this route can never touch the user's tree.\n */\n if (request.method === \"POST\" && url.pathname === \"/approve\") {\n await approve(request, response, options);\n return;\n }\n if (request.method !== \"GET\") {\n send(response, 405, { error: `${request.method ?? \"that\"} is not something this daemon does yet` });\n return;\n }\n\n /*\n * Everything the view draws, in one answer. The page redraws from a whole snapshot rather than stitching\n * together deltas, because a view that can drift from the ledger is a view that will eventually lie about it.\n */\n if (url.pathname === \"/state\") {\n const state = project(options.ledger.read());\n const seats = options.crew === undefined ? [] : await options.crew();\n send(response, 200, { state, seats, waiting: waitingOnYou(state), now: new Date().toISOString() });\n return;\n }\n\n if (url.pathname === \"/crew\") {\n const seats = options.crew === undefined ? [] : await options.crew();\n send(response, 200, { seats });\n return;\n }\n\n if (url.pathname === \"/events\") {\n const afterSeq = Number(url.searchParams.get(\"afterSeq\") ?? 0);\n const limit = Number(url.searchParams.get(\"limit\") ?? 500);\n const missionId = url.searchParams.get(\"missionId\");\n const events = options.ledger.read({\n afterSeq: Number.isFinite(afterSeq) ? afterSeq : 0,\n limit: Number.isFinite(limit) ? Math.min(limit, 5000) : 500,\n ...(missionId === null ? {} : { missionId }),\n });\n send(response, 200, { events, lastSeq: options.ledger.lastSeq() });\n return;\n }\n\n send(response, 404, { error: `nothing lives at ${url.pathname}` });\n}\n\n/**\n * Records a person's yes, or explains why it cannot be given yet.\n *\n * The revision is the one review judged, never one the caller chose: an approval is consent to a specific diff,\n * and letting the page name it would let a stale page approve work it had not seen. If the worktree has moved\n * since, `mergeRun` collects the diff again, finds a revision the approval does not match, and refuses \u2014 which is\n * the same protection the lead's tool has, arrived at the same way.\n */\nasync function approve(\n request: IncomingMessage,\n response: ServerResponse,\n options: ApiOptions,\n): Promise<void> {\n let body: { missionId?: unknown; runId?: unknown; note?: unknown };\n try {\n body = JSON.parse(await readBody(request)) as typeof body;\n } catch {\n send(response, 400, { error: \"that was not JSON this daemon could read\" });\n return;\n }\n const missionId = typeof body.missionId === \"string\" ? body.missionId : \"\";\n const runId = typeof body.runId === \"string\" ? body.runId : \"\";\n const note = typeof body.note === \"string\" ? body.note.slice(0, 2000) : \"approved in the mission view\";\n if (missionId === \"\" || runId === \"\") {\n send(response, 400, { error: \"an approval needs a missionId and a runId\" });\n return;\n }\n\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n const run = mission?.runs[runId];\n const line = (mission?.plan?.lines ?? []).find((candidate) => candidate.id === run?.lineId);\n if (mission === undefined || run === undefined || line === undefined) {\n send(response, 404, { error: `no run ${runId} in ${missionId}` });\n return;\n }\n\n const revision = run.review?.revision ?? run.checks?.revision ?? \"\";\n if (revision === \"\") {\n send(response, 409, { error: \"nothing has judged this diff yet, so there is no revision to approve\" });\n return;\n }\n\n /*\n * Everything except the approval itself must already be satisfied. Recording a yes for work nobody reviewed\n * would put the strongest evidence in the ledger behind a diff that had earned none of it.\n */\n const standing = blocksApproval(mergeReadiness(run, line, revision));\n if (standing.length > 0) {\n send(response, 409, {\n error: \"this is not ready for your approval yet\",\n blockers: standing.map((blocker) => blocker.message),\n });\n return;\n }\n\n options.ledger.append({\n type: \"merge.approved\",\n missionId,\n runId,\n revision,\n by: { kind: \"user\", via: \"direct\" },\n note,\n });\n send(response, 200, { ok: true, runId, revision });\n}\n\n/** The request's body, refusing anything large enough to be an attempt at exhausting the daemon. */\nasync function readBody(request: IncomingMessage, limit = 8 * 1024): Promise<string> {\n let body = \"\";\n for await (const chunk of request) {\n body += (chunk as Buffer).toString(\"utf8\");\n if (body.length > limit) throw new Error(\"body too large\");\n }\n return body;\n}\n\n/**\n * What each finished run still needs before it can merge, computed here rather than in the page.\n *\n * `mergeReadiness` is the gate's judgement and there is exactly one of it. A page that worked out its own answer\n * would eventually disagree with the tool that actually refuses, and the screen saying \"ready\" while the merge\n * says \"no\" is worse than the screen saying nothing \u2014 this repository has spent a day proving that a rule with\n * two implementations ends up with two behaviours.\n */\nfunction waitingOnYou(state: ProjectionState): {\n missionId: string;\n runId: string;\n task: string;\n seat: string;\n ready: boolean;\n /**\n * Your yes is the only thing missing.\n *\n * Distinct from `ready`, which means the gate would merge this now \u2014 and which can only become true *after*\n * someone approves, since a missing approval is itself a blocker. Without this flag the page could never tell\n * the one state where a person actually has something to do.\n */\n approvable: boolean;\n blockers: string[];\n}[] {\n const waiting = [];\n for (const mission of Object.values(state.missions)) {\n const lines = new Map((mission.plan?.lines ?? []).map((line) => [line.id, line]));\n for (const runId of mission.runOrder) {\n const run = mission.runs[runId];\n if (run?.status !== \"done\") continue;\n const line = lines.get(run.lineId);\n if (line === undefined) continue;\n\n // Judged against the revision the review saw: the page cannot read a worktree, and the merge tool\n // re-collects the diff and refuses for itself if the work has moved since.\n const judged = run.review?.revision ?? run.checks?.revision ?? \"\";\n const readiness = mergeReadiness(run, line, judged);\n waiting.push({\n missionId: mission.missionId,\n runId,\n // What the work was, not just which run it was. A row that says `api-1` makes a person go and look it up.\n task: line.title,\n seat: run.seat.id,\n ready: readiness.ready,\n approvable: !readiness.ready && blocksApproval(readiness).length === 0,\n blockers: readiness.blockers.map((blocker) => blocker.message),\n });\n }\n }\n return waiting;\n}\n\nfunction wanted(subscriber: Subscriber, event: StoredEvent): boolean {\n if (subscriber.types !== null && !subscriber.types.has(event.type)) return false;\n if (subscriber.missionId === null) return true;\n return \"missionId\" in event && event.missionId === subscriber.missionId;\n}\n\nfunction typesFrom(url: URL): ReadonlySet<EventType> | null {\n if (url.searchParams.get(\"for\") === \"lead\") return new Set(LEAD_EVENTS);\n const types = url.searchParams.get(\"types\");\n if (types === null || types === \"\") return null;\n return new Set(types.split(\",\").filter(Boolean) as EventType[]);\n}\n\nfunction parseUrl(request: IncomingMessage): URL {\n return new URL(request.url ?? \"/\", `http://127.0.0.1`);\n}\n\nfunction send(response: ServerResponse, status: number, body: unknown): void {\n const text = JSON.stringify(body);\n response.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(text),\n // Nothing here is for a browser to keep.\n \"cache-control\": \"no-store\",\n });\n response.end(text);\n}\n\nasync function close(\n server: Server,\n websockets: WebSocketServer,\n sockets: Set<Socket>,\n subscribers: Set<Subscriber>,\n): Promise<void> {\n for (const subscriber of subscribers) subscriber.socket.close();\n subscribers.clear();\n await new Promise<void>((resolve) => {\n websockets.close(() => {\n resolve();\n });\n });\n for (const socket of sockets) socket.destroy();\n sockets.clear();\n await new Promise<void>((resolve) => {\n server.close(() => {\n resolve();\n });\n });\n}\n", "import { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/*\n * The daemon answers on 127.0.0.1 only, but \"local\" is not the same as \"yours\": anything running on the machine,\n * including a web page in your browser, can reach a local port. So every request carries a token that lives in a\n * file only you can read, and comparisons are constant-time so a wrong guess teaches an attacker nothing.\n */\n\nconst TOKEN_BYTES = 32;\n\n/** Reads the daemon's token, creating one the first time. The file is yours alone (mode 600). */\nexport function readOrCreateToken(path: string): string {\n if (existsSync(path)) {\n const existing = readFileSync(path, \"utf8\").trim();\n if (existing.length >= 32) {\n chmodSync(path, 0o600);\n return existing;\n }\n }\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const token = randomBytes(TOKEN_BYTES).toString(\"base64url\");\n writeFileSync(path, `${token}\\n`, { encoding: \"utf8\", mode: 0o600 });\n chmodSync(path, 0o600);\n return token;\n}\n\n/** Whether a request carries the daemon's token. Constant-time, and never true for a missing or empty header. */\nexport function tokenMatches(expected: string, authorization: string | undefined): boolean {\n if (authorization === undefined) return false;\n const offered = authorization.startsWith(\"Bearer \") ? authorization.slice(7).trim() : authorization.trim();\n if (offered === \"\" || expected === \"\") return false;\n\n const a = Buffer.from(offered, \"utf8\");\n const b = Buffer.from(expected, \"utf8\");\n // timingSafeEqual needs equal lengths; compare a fixed-size digest of each instead of leaking the length.\n if (a.length !== b.length) {\n timingSafeEqual(b, b); // keep the work the same whatever the input looks like\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\n/**\n * Whether a browser page is trying to drive the daemon. A request from a page carries an Origin; ours never do,\n * so anything with an Origin that is not our own loopback address is refused before it reaches a handler.\n */\nexport function originAllowed(origin: string | undefined, port: number): boolean {\n if (origin === undefined || origin === \"\" || origin === \"null\") return true;\n return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;\n}\n", "import { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { EMPTY_POLICY, SeatPolicy, type SeatPosture } from \"fanout-core\";\n\n/*\n * Where the owner's seat preferences live, and \u2014 more importantly \u2014 what happens when that file is unreadable.\n *\n * The failure mode is the whole design here. \"No preferences\" and \"I could not read your preferences\" look\n * identical if you return an empty policy for both, and they are not the same at all: the first means use the\n * defaults, the second means a seat the owner switched off may be about to be spent. So a damaged file yields the\n * defaults *and* a problem, and any caller about to spend money on a seat must treat a problem as a refusal rather\n * than as a shrug.\n */\n\nexport const POLICY_FILE = \"seats.json\";\n\nexport interface PolicyRead {\n policy: SeatPolicy;\n /**\n * Null when the file was read or was simply absent. A string when something is wrong with it, in which case\n * `policy` holds the defaults and is **not** safe to act on: see the note above.\n */\n problem: string | null;\n}\n\nexport function policyPath(home: string): string {\n return join(home, POLICY_FILE);\n}\n\n/** Reads the owner's seat preferences. An absent file is not a problem; an unreadable one is. */\nexport function readSeatPolicy(home: string): PolicyRead {\n const path = policyPath(home);\n\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch (cause) {\n // Never having set a preference is the normal case, not an error.\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") return { policy: EMPTY_POLICY, problem: null };\n return { policy: EMPTY_POLICY, problem: `${path} could not be read: ${describe(cause)}` };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { policy: EMPTY_POLICY, problem: `${path} is not valid JSON` };\n }\n\n const result = SeatPolicy.safeParse(parsed);\n if (!result.success) {\n const first = result.error.issues[0];\n const where = first === undefined ? \"\" : ` (${first.path.join(\".\")}: ${first.message})`;\n return { policy: EMPTY_POLICY, problem: `${path} is not a seat policy we understand${where}` };\n }\n\n return { policy: result.data, problem: null };\n}\n\n/**\n * Writes the preferences, replacing the file atomically.\n *\n * A half-written policy is the worst outcome available: it reads as damaged, which blocks work, and it does so at\n * the moment the owner was trying to change something. Writing beside the file and renaming means a reader sees\n * either the old policy or the new one, never a torn one.\n */\nexport function writeSeatPolicy(home: string, policy: SeatPolicy): void {\n const path = policyPath(home);\n mkdirSync(dirname(path), { recursive: true });\n\n const temporary = `${path}.${String(process.pid)}.tmp`;\n writeFileSync(temporary, `${JSON.stringify(SeatPolicy.parse(policy), null, 2)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n renameSync(temporary, path);\n}\n\n/** Sets one seat's posture, leaving every other seat's preference exactly as it was. */\nexport function setPosture(\n policy: SeatPolicy,\n seatId: string,\n posture: SeatPosture,\n note?: string,\n): SeatPolicy {\n return SeatPolicy.parse({\n version: 1,\n seats: {\n ...policy.seats,\n [seatId]: { posture, ...(note === undefined || note === \"\" ? {} : { note }) },\n },\n });\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import { routeLine, type Routing, type SeatHeadroom, type SeatInfo } from \"fanout-core\";\nimport { readSeatPolicy } from \"./seats.ts\";\n\n/*\n * Where a line runs, given what is actually on this machine.\n *\n * `routeLine` in core decides it from facts; this decides which facts we are entitled to use. The two are separate\n * because the interesting failures here are not about choosing badly, they are about choosing at all on top of\n * something we did not really read \u2014 and that question has nothing to do with the ordering rules in core.\n *\n * Every refusal below resolves the same way: keep the seat the plan named. That is the choice that can only fail\n * loudly. A line kept on a seat that has run out stops with the seat's own message on screen; a line moved onto a\n * seat the owner switched off spends their subscription and tells them afterwards.\n */\n\nexport interface RouteContext {\n /** The owner's fanout home, where seat preferences live. */\n home: string;\n /** What detection found. Empty means it has not answered yet. */\n crew: readonly SeatInfo[];\n headroom: Readonly<Record<string, SeatHeadroom>>;\n now: Date;\n}\n\n/**\n * Decides where a line runs, or declines to decide.\n *\n * The policy read is the reason this function exists. `readSeatPolicy` hands back defaults *and* a problem when\n * the file is damaged, and says in its own documentation that the defaults are not safe to act on \u2014 a caller that\n * destructures `policy` and drops `problem` gets code that looks right, passes, and one day moves work onto a\n * seat the owner had turned off. So a problem here means we route nothing.\n */\nexport function chooseSeat(wanted: string, context: RouteContext): Routing {\n // Detection has not answered. The safety report has already told the user which seats it could not see.\n if (context.crew.length === 0) return { kind: \"keep\", seat: wanted };\n\n const { policy, problem } = readSeatPolicy(context.home);\n if (problem !== null) return { kind: \"keep\", seat: wanted };\n\n return routeLine({ wanted, seats: context.crew, policy, headroom: context.headroom, now: context.now });\n}\n", "import { createHash } from \"node:crypto\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * The identity of a working tree's uncommitted work.\n *\n * The gate's every claim \u2014 reviewed, checked, proven, approved \u2014 is about a specific diff, and a working tree is\n * not a specific anything: it changes under you. Hashing what is actually there turns \"the current changes\" into a\n * name that two steps can be compared against, which is the difference between \"this was reviewed\" and \"something\n * was reviewed once\".\n *\n * The hash covers tracked modifications *and* new files, because a change that only adds files has an empty\n * `git diff` and would otherwise share a revision with a clean tree \u2014 the most dangerous collision available here.\n */\n\nexport interface RevisionOptions {\n cwd: string;\n /** Untracked files to include. Defaults to everything git would show as untracked and not ignored. */\n timeoutMs?: number;\n}\n\nexport interface WorkSnapshot {\n /** sha-256 over the diff and the new files, or the hash of \"nothing\" when the tree is clean. */\n revision: string;\n /** Repo-relative paths this work touches, sorted. Empty when the tree is clean. */\n files: string[];\n /** The new files among them: they are copied into an isolated review rather than patched into it. */\n newFiles: string[];\n clean: boolean;\n /** The repository root, resolved from whatever directory we were pointed at. */\n repoRoot: string;\n}\n\n/** The sha-256 of an empty snapshot: a clean tree always has this revision, on every machine. */\nexport const CLEAN_REVISION = createHash(\"sha256\")\n .update(\"fanout/work/v1\\n\")\n .update(\"\\0staged\\0\")\n .digest(\"hex\");\n\n/**\n * What the working tree currently holds, and its name.\n *\n * Deliberately not `git stash create` or `write-tree`: both write objects into the repository, and a tool that\n * inspects your work must not change it. This only reads.\n */\nexport async function workSnapshot(options: RevisionOptions): Promise<WorkSnapshot> {\n const at =\n (cwd: string) =>\n (args: readonly string[]): Promise<string> =>\n git(args, { cwd, ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) });\n\n /*\n * Everything is asked of the repository root, never of whatever directory we happened to be started in.\n * `git ls-files --others` lists only files beneath its working directory and names them relative to it, so\n * running from a package subdirectory would silently miss new files elsewhere and mix two kinds of path.\n */\n const repoRoot = (await at(options.cwd)([\"rev-parse\", \"--show-toplevel\"])).trim();\n const run = at(repoRoot);\n\n // `--no-ext-diff` and `--no-color` so a user's own diff settings cannot change the identity of their work.\n const tracked = await run([\"diff\", \"HEAD\", \"--no-ext-diff\", \"--no-color\"]);\n /*\n * Staged work is hashed separately. `git diff HEAD` compares the working tree with HEAD, so a change that was\n * staged and then reverted in the working tree is invisible to it while still sitting in the index, ready to be\n * committed \u2014 a clean-looking tree that is not clean.\n */\n const staged = await run([\"diff\", \"--cached\", \"HEAD\", \"--no-ext-diff\", \"--no-color\"]);\n const untracked = zeroSeparated(await run([\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"])).sort();\n\n const hash = createHash(\"sha256\").update(\"fanout/work/v1\\n\");\n hash.update(tracked);\n hash.update(\"\\0staged\\0\");\n hash.update(staged);\n for (const path of untracked) {\n // The path goes in as well as the bytes: moving a new file is a change, even when its contents are identical.\n hash.update(`\\0new\\0${path}\\0`);\n hash.update(await run([\"hash-object\", \"--\", path]));\n }\n\n const changed = zeroSeparated(await run([\"diff\", \"HEAD\", \"--name-only\", \"-z\"]));\n const stagedNames = zeroSeparated(await run([\"diff\", \"--cached\", \"HEAD\", \"--name-only\", \"-z\"]));\n const files = [...new Set([...changed, ...stagedNames, ...untracked])].sort();\n\n return {\n revision: hash.digest(\"hex\"),\n files,\n newFiles: [...untracked],\n clean: files.length === 0,\n repoRoot,\n };\n}\n", "import {\n copyFileSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n realpathSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\nimport { pathInScope } from \"fanout-core\";\nimport { DEFAULT_DENY_LIST } from \"../workspace/deny.ts\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * A copy of the lead's uncommitted work, with nothing else in it.\n *\n * Isolation is the third non-negotiable and it is not satisfied by a read-only sandbox: read-only stops a reviewer\n * writing, not reading, so a reviewer launched in the repository can open `.env`, a private key, or any other\n * ignored file that happens to be lying there. Filtering which paths we *tell* it about changes nothing, because\n * its tools can look anywhere.\n *\n * So the reviewer never sees the repository. It sees a fresh worktree at HEAD with exactly the changes applied \u2014\n * ignored files do not exist in a worktree, which makes that half of the guarantee structural rather than a\n * promise about behaviour.\n *\n * Three ways secrets got in anyway, all found by a second vendor reviewing this file, all now closed: a `.env`\n * that HEAD *tracks* lands in the worktree and has to be deleted from the copy (the deny-list, the same one the\n * mission workspaces use); an untracked symlink with an innocent name dereferences to whatever it points at, so\n * links are refused rather than followed; and work that is staged but reverted in the working tree is invisible\n * to `git diff HEAD`, so the reviewer would have read a copy missing the very change being reviewed.\n */\n\nexport interface IsolatedWork {\n /** Where the reviewer should run. Contains the repository at HEAD plus the uncommitted changes. */\n path: string;\n /** Files deliberately kept out of the copy. The caller tells the user, so nobody wonders why a file is missing. */\n refused: Refused[];\n /** Removes the copy. Safe to call twice. */\n dispose: () => Promise<void>;\n}\n\nexport interface IsolateOptions {\n repoRoot: string;\n /** Repo-relative paths that are new files, from the snapshot; they are copied in, not patched. */\n newFiles: readonly string[];\n timeoutMs?: number;\n denyList?: readonly string[];\n}\n\n/** A file the copy refused to include, and why \u2014 reported, never silently dropped. */\nexport interface Refused {\n path: string;\n reason: \"deny-list\" | \"symlink\";\n}\n\n/**\n * Removes every symbolic link in the copy that points outside it.\n *\n * Found by a cold reader refuting the claim that this could not happen: the earlier guard only covered untracked\n * files copied in, while `git worktree add` faithfully checks out symlinks that HEAD already tracks \u2014 and a\n * tracked link may point at an ignored `.env`, at `~/.ssh/id_rsa`, or anywhere else on the machine. The copy is\n * supposed to be the only thing a reviewer can read; a link out of it is a hole in exactly that.\n *\n * Links that stay inside the copy are left alone: they are part of the repository's own shape, and a reviewer\n * following one reads only what it was already shown.\n *\n * Containment is decided by asking the filesystem, never by reading the path. A cold reader refuted the lexical\n * version of this check with a two-link chain \u2014 `a -> .` beside `leak -> a/../secret` \u2014 where `path.resolve`\n * folds `a/..` away textually and calls the target contained, while the kernel follows `a` to the root first and\n * lands `..` in the parent. Only `realpath`, which walks every link, knows where a path actually goes.\n */\nfunction cutEscapingLinks(root: string): Refused[] {\n /*\n * Walked from the resolved root, not the given one. On macOS a temporary directory is handed out as `/var/...`\n * and resolves to `/private/var/...`; comparing one against the other makes every link inside the copy look\n * like an escape, and this cut all of them until a test said so.\n */\n const inside = realpathSync.native(root);\n const cut: Refused[] = [];\n\n const walk = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const full = join(directory, entry.name);\n // `.git` in a linked worktree is a file pointing at the real repository, which is not ours to rewrite.\n if (entry.name === \".git\") continue;\n\n if (entry.isSymbolicLink()) {\n if (!staysInside(inside, full)) {\n rmSync(full, { force: true });\n cut.push({ path: relative(inside, full), reason: \"symlink\" });\n }\n continue;\n }\n if (entry.isDirectory()) walk(full);\n }\n };\n\n walk(inside);\n return cut;\n}\n\n/**\n * Does following this link, all the way, land inside `root`?\n *\n * `realpath` resolves every link in the chain, which is the only answer that matches what a reader actually gets.\n * A link we cannot resolve at all \u2014 dangling, or a loop \u2014 is cut: it shows a reviewer nothing, and a path the\n * filesystem will not explain is not one we can promise anything about.\n */\nexport function staysInside(root: string, link: string): boolean {\n let real: string;\n let inside: string;\n try {\n // Both sides resolved the same way, or a macOS `/var` against a `/private/var` makes everything look outside.\n inside = realpathSync.native(root);\n /*\n * `.native` is not an optimisation here, it is the correctness. Node's JavaScript `realpathSync` folds `..`\n * segments lexically as it goes, so a chain like `a -> .` beside `leak -> a/a/../../etc/passwd` resolves to a\n * path *inside* the copy while opening it reaches the real `/etc/passwd`. Measured on this machine: the JS\n * version answered `<copy>/etc/passwd`, the native one `/private/etc/passwd`, and reading the link returned\n * the system file. Only the operating system's own resolver is a security boundary.\n */\n real = realpathSync.native(link);\n } catch {\n return false;\n }\n // An empty result means the link resolves to the copy's own root, which is inside it. The chain that made that\n // dangerous is dead anyway: every link is now followed to where it really goes before this is asked.\n const stepsOut = relative(inside, real);\n return !stepsOut.startsWith(\"..\") && !isAbsolute(stepsOut);\n}\n\n/** Builds a throwaway worktree holding HEAD plus whatever is currently uncommitted. */\nexport async function isolateWork(options: IsolateOptions): Promise<IsolatedWork> {\n const run = (args: readonly string[], cwd: string = options.repoRoot): Promise<string> =>\n git(args, { cwd, ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) });\n\n const root = mkdtempSync(join(tmpdir(), \"fanout-review-\"));\n const patches = mkdtempSync(join(tmpdir(), \"fanout-patch-\"));\n const path = join(root, \"work\");\n let created = false;\n\n /*\n * Patches are written beside the copy and applied by file, so that every git call in this module goes through\n * the one helper that closes the environment. There used to be a second, bespoke invocation here that piped the\n * patch to stdin and inherited the shell's \u2014 which in an editor's integrated terminal means its GIT_ASKPASS,\n * its IPC auth token, and the user's system git config. Deleting the second path is a better guarantee than\n * testing it, because there is now nothing left to drift.\n */\n const applyPatch = async (patch: string, name: string): Promise<void> => {\n // Written outside the copy's own parent and removed immediately: `..` from the copy should hold nothing\n // worth reaching, so that a link we failed to catch has less to find.\n const file = join(patches, name);\n writeFileSync(file, patch, \"utf8\");\n try {\n await run([\"apply\", \"--whitespace=nowarn\", file], path);\n } finally {\n rmSync(file, { force: true });\n }\n };\n\n const dispose = async (): Promise<void> => {\n if (created) {\n // `git worktree remove` first so the repository's administrative files are updated, not orphaned.\n try {\n await run([\"worktree\", \"remove\", \"--force\", path]);\n } catch {\n // A worktree we cannot unregister still must not be left on disk.\n }\n }\n rmSync(root, { recursive: true, force: true });\n rmSync(patches, { recursive: true, force: true });\n };\n\n try {\n await run([\"worktree\", \"add\", \"--detach\", \"--quiet\", path, \"HEAD\"]);\n created = true;\n\n const denyList = options.denyList ?? DEFAULT_DENY_LIST;\n const refused: Refused[] = [];\n\n /*\n * A secret that HEAD tracks is already in this worktree, because a worktree is a checkout of HEAD. Ignored\n * files never arrive, but a committed `.env` does, so it is removed from the copy before anything runs.\n */\n for (const file of zeroSeparated(await run([\"ls-tree\", \"-r\", \"-z\", \"--name-only\", \"HEAD\"], path))) {\n if (denyList.some((pattern) => pathInScope(file, pattern))) {\n rmSync(join(path, file), { force: true });\n refused.push({ path: file, reason: \"deny-list\" });\n }\n }\n\n // The working tree as it stands.\n const patch = await run([\"diff\", \"HEAD\", \"--no-ext-diff\", \"--no-color\", \"--binary\"]);\n if (patch.trim() !== \"\") await applyPatch(patch, \"worktree.patch\");\n\n /*\n * Then any file whose *index* differs from HEAD but whose working tree does not: staged, then reverted. It is\n * invisible to the patch above, and a reviewer given a copy without it would be reviewing different work from\n * the one whose revision we record.\n */\n const inWorktree = new Set(zeroSeparated(await run([\"diff\", \"HEAD\", \"--name-only\", \"-z\"])));\n const stagedOnly = zeroSeparated(await run([\"diff\", \"--cached\", \"HEAD\", \"--name-only\", \"-z\"])).filter(\n (file) => !inWorktree.has(file),\n );\n if (stagedOnly.length > 0) {\n const staged = await run([\n \"diff\",\n \"--cached\",\n \"HEAD\",\n \"--no-ext-diff\",\n \"--no-color\",\n \"--binary\",\n \"--\",\n ...stagedOnly,\n ]);\n if (staged.trim() !== \"\") await applyPatch(staged, \"staged.patch\");\n }\n\n /*\n * New files are copied rather than patched. They come from the snapshot, which asks git for untracked files\n * excluding standard ignores \u2014 but \"not ignored\" is not the same as \"safe to show\", so each one is checked\n * again here.\n */\n for (const file of options.newFiles) {\n if (denyList.some((pattern) => pathInScope(file, pattern))) {\n refused.push({ path: file, reason: \"deny-list\" });\n continue;\n }\n const source = join(options.repoRoot, file);\n /*\n * `copyFileSync` follows symlinks, so an untracked link innocently named `notes.txt` and pointing at an\n * ignored `.env` \u2014 or anywhere outside the repository at all \u2014 would materialise that file's contents in\n * the copy. Links are refused rather than resolved: a reviewer has no need of one.\n */\n if (lstatSync(source).isSymbolicLink()) {\n refused.push({ path: file, reason: \"symlink\" });\n continue;\n }\n const destination = join(path, file);\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(source, destination);\n }\n\n // Last, because a link can arrive three ways \u2014 checked out from HEAD, added by a patch, or copied in \u2014 and\n // only a sweep of what is actually on disk catches all three.\n refused.push(...cutEscapingLinks(path));\n\n return { path, refused, dispose };\n } catch (cause) {\n await dispose();\n throw cause;\n }\n}\n", "import type { AdapterManifest } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\n\n/*\n * Running a seat's CLI once, read-only, and getting back what it said.\n *\n * Shared by everything that asks another vendor a question about code it did not write. The environment is an\n * allowlist (see `env.ts`), the mode is the read-only one the seat's own manifest names, and an unsupplied\n * placeholder is removed along with its flag rather than becoming an empty string \u2014 a CLI is entitled to reject\n * `-m \"\"`, and one of them does.\n */\n\nexport type SeatExecute = (\n binary: string,\n args: readonly string[],\n options: { cwd: string; timeoutMs: number },\n) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n\nexport interface RunSeatOptions {\n manifest: AdapterManifest;\n cwd: string;\n prompt: string;\n model?: string;\n timeoutMs?: number;\n execute?: SeatExecute;\n}\n\nexport interface SeatAnswer {\n /** False when the CLI could not run, exited non-zero, or said nothing we could read. */\n ok: boolean;\n /** Everything the agent said, joined. Empty when `ok` is false. */\n text: string;\n /** Why it failed, when it did. */\n problem: string;\n}\n\n/** Asks a seat a question about the code in `cwd`, read-only, and returns its answer. */\nexport async function runSeat(options: RunSeatOptions): Promise<SeatAnswer> {\n const { manifest } = options;\n const args = fillTemplate(manifest.headless.args, {\n \"{workdir}\": options.cwd,\n \"{sandbox}\": manifest.permissionModes.readOnly,\n \"{prompt}\": options.prompt,\n ...(options.model === undefined ? {} : { \"{model}\": options.model }),\n });\n\n const execute = options.execute ?? runCliOnce;\n let stdout: string;\n try {\n const result = await execute(manifest.binary, args, {\n cwd: options.cwd,\n timeoutMs: options.timeoutMs ?? 10 * 60_000,\n });\n if (result.exitCode !== 0) {\n return { ok: false, text: \"\", problem: firstLines(result.stderr || result.stdout) };\n }\n stdout = result.stdout;\n } catch (cause) {\n return { ok: false, text: \"\", problem: cause instanceof Error ? cause.message : String(cause) };\n }\n\n const text = agentText(stdout);\n // An exit code of zero is not an answer. A CLI that printed nothing we recognise has told us nothing.\n if (text === null) {\n return { ok: false, text: \"\", problem: \"the seat exited cleanly but said nothing we could read\" };\n }\n return { ok: true, text, problem: \"\" };\n}\n\n/**\n * What the agent actually said, out of its stream.\n *\n * Null when the stream held no agent message at all \u2014 different from an agent that said nothing, and never to be\n * reported as one.\n */\nexport function agentText(stream: string): string | null {\n const messages: string[] = [];\n for (const line of stream.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n try {\n const parsed: unknown = JSON.parse(line);\n const item = (parsed as { item?: { type?: string; text?: string } }).item;\n if (item?.type === \"agent_message\" && typeof item.text === \"string\") messages.push(item.text);\n } catch {\n // A line that is not JSON is the CLI talking to a human; the answer is in the ones that are.\n }\n }\n return messages.length === 0 ? null : messages.join(\"\\n\\n\");\n}\n\n/**\n * Fills an argument template, dropping any placeholder nobody supplied and the flag in front of it.\n *\n * Found by running this for real: with no model chosen, `[\"-m\", \"{model}\"]` became `[\"-m\", \"\"]` and Codex answered\n * `The '' model is not supported`. An unsupplied option must vanish, not become an empty value.\n */\nexport function fillTemplate(\n template: readonly string[],\n values: Readonly<Record<string, string>>,\n): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n const placeholder = /^\\{[a-z]+\\}$/.test(argument) ? argument : null;\n if (placeholder !== null && !Object.hasOwn(values, placeholder)) {\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction firstLines(text: string, count = 5): string {\n return text.split(\"\\n\").slice(0, count).join(\"\\n\").trim();\n}\n\n/**\n * Runs the CLI with its standard input closed.\n *\n * Every manifest declares `stdin: \"closed\"` and this is where that is honoured. Without a terminal, `codex exec`\n * waits on \"Reading additional input from stdin\u2026\" and never returns \u2014 a pipe nobody writes to is not the same as\n * no input at all. It cost an hour of a run that looked busy and was blocked, in code whose own manifest says the\n * rule out loud, which is the argument for honouring declarations rather than remembering them.\n */\nexport const runCliOnce: SeatExecute = async (binary, args, options) => {\n const { execFile } = await import(\"node:child_process\");\n\n // Resolved either way; the caller turns a failure into an answer of \"we could not ask\", never into a verdict.\n const outcome = await new Promise<\n { stdout: string; stderr: string; exitCode: number } | { failure: Error }\n >((settle) => {\n const child = execFile(\n binary,\n [...args],\n {\n cwd: options.cwd,\n timeout: options.timeoutMs,\n env: baseEnv(),\n maxBuffer: 64 * 1024 * 1024,\n windowsHide: true,\n },\n (error, stdout, stderr) => {\n if (error === null) {\n settle({ stdout, stderr, exitCode: 0 });\n return;\n }\n const code = (error as { code?: number }).code;\n // A CLI that answers with a non-zero exit is answering, not failing to run.\n if (typeof code === \"number\") settle({ stdout, stderr, exitCode: code });\n else settle({ failure: error });\n },\n );\n child.stdin?.end();\n });\n\n if (\"failure\" in outcome) throw outcome.failure;\n return outcome;\n};\n", "import type { AdapterManifest, FanoutEventInput, SeatRef } from \"fanout-core\";\nimport { isolateWork } from \"./isolate.ts\";\nimport { runCliOnce } from \"./run-seat.ts\";\nimport { workSnapshot, type WorkSnapshot } from \"./revision.ts\";\n\n/*\n * A second vendor, reading the lead's own uncommitted work.\n *\n * This is the part of Fanout that earns its place in a session where no agent ran at all. Most of the code in a\n * Claude Code session is written by the lead, and the lead is the one reviewer it gets \u2014 which is exactly how a\n * confident mistake ships. Pointing another vendor's own review command at the working tree costs one call and\n * breaks that loop, because a different model does not share the author's blind spots.\n *\n * It reads, and it reads a copy. A read-only sandbox stops a reviewer writing, not reading, so a reviewer\n * launched in the repository could open `.env` or a private key that happens to be lying there \u2014 which is why the\n * work is rebuilt in a throwaway worktree first, where ignored files simply do not exist. Its answer is recorded\n * verbatim rather than summarised by the author it is about.\n */\n\nexport interface BuddyOptions {\n repoRoot: string;\n /** The seat doing the reading. Must declare a `review` capability; nothing is guessed if it does not. */\n manifest: AdapterManifest;\n model?: string;\n timeoutMs?: number;\n /** Injected in tests so nothing needs a CLI installed. */\n execute?: (\n binary: string,\n args: readonly string[],\n options: { cwd: string; timeoutMs: number },\n ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n}\n\nexport interface BuddyResult {\n snapshot: WorkSnapshot;\n /** The event to record. Always produced, including when the reviewer could not run. */\n event: Extract<FanoutEventInput, { type: \"buddy.reviewed\" }>;\n}\n\nexport class BuddyUnavailable extends Error {\n readonly seat: string;\n\n constructor(seat: string, reason: string) {\n super(`${seat} cannot review: ${reason}`);\n this.name = \"BuddyUnavailable\";\n this.seat = seat;\n }\n}\n\n/** Asks the seat to review whatever is currently uncommitted, and returns what it said. */\nexport async function buddyReview(options: BuddyOptions): Promise<BuddyResult> {\n const { manifest } = options;\n const review = manifest.capabilities.review;\n if (review === null) {\n throw new BuddyUnavailable(manifest.id, \"its CLI has no non-interactive review command\");\n }\n\n const snapshot = await workSnapshot({ cwd: options.repoRoot });\n const by: SeatRef = { id: manifest.id, ...(options.model === undefined ? {} : { model: options.model }) };\n\n const base = {\n type: \"buddy.reviewed\" as const,\n repoRoot: options.repoRoot,\n revision: snapshot.revision,\n by,\n files: snapshot.files,\n };\n\n // Nothing to read is not a finding, and asking anyway would spend a subscription to be told so.\n if (snapshot.clean) {\n return { snapshot, event: { ...base, findings: \"\", ran: true } };\n }\n\n const isolated = await isolateWork({\n repoRoot: snapshot.repoRoot,\n newFiles: snapshot.newFiles,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n /*\n * Building the copy takes a moment, and an editor saving in that moment would leave us reviewing one set of\n * bytes while recording the revision of another \u2014 a review that certifies work nobody read. Cheaper to look\n * again than to reason about the window: if the work moved, say so and let the caller ask again.\n */\n const after = await workSnapshot({ cwd: snapshot.repoRoot });\n if (after.revision !== snapshot.revision) {\n await isolated.dispose();\n return {\n snapshot: after,\n event: {\n ...base,\n revision: after.revision,\n files: after.files,\n findings: \"your files changed while the review copy was being made; nothing was reviewed\",\n ran: false,\n },\n };\n }\n\n const args = fill(review.args, {\n \"{workdir}\": isolated.path,\n // A reviewer reads; it is given the read-only mode its own manifest names, never the editing one.\n \"{sandbox}\": manifest.permissionModes.readOnly,\n ...(options.model === undefined ? {} : { \"{model}\": options.model }),\n });\n\n const execute = options.execute ?? runCliOnce;\n let stdout: string;\n try {\n const result = await execute(manifest.binary, args, {\n cwd: isolated.path,\n timeoutMs: options.timeoutMs ?? 10 * 60_000,\n });\n if (result.exitCode !== 0) {\n /*\n * A reviewer that failed has not approved anything. Recording `ran: false` with the reason keeps \"we asked\n * and it broke\" distinguishable from \"it found nothing\" \u2014 which would otherwise read as a clean bill.\n */\n return {\n snapshot,\n event: { ...base, findings: firstLines(result.stderr || result.stdout), ran: false },\n };\n }\n stdout = result.stdout;\n } catch (cause) {\n return { snapshot, event: { ...base, findings: describe(cause), ran: false } };\n } finally {\n await isolated.dispose();\n }\n\n const findings = findingsFrom(stdout, isolated.path);\n const refused = isolated.refused;\n /*\n * An exit code of zero is not a review. A CLI that printed nothing we recognise has not told us the code is\n * fine, and recording that as a completed review with no findings would turn silence into a clean bill of\n * health \u2014 the exact shape of dishonesty this project refuses.\n */\n if (findings === null) {\n return {\n snapshot,\n event: { ...base, findings: \"the reviewer exited cleanly but said nothing we could read\", ran: false },\n };\n }\n\n /*\n * A file kept out of the copy is said out loud. A reviewer that never saw a file has not approved it, and a\n * silent omission is the difference between \"reviewed\" and \"reviewed most of it\".\n */\n const note =\n refused.length === 0\n ? \"\"\n : `\\n\\nNot shown to the reviewer: ${refused.map((item) => `${item.path} (${item.reason})`).join(\", \")}`;\n\n return { snapshot, event: { ...base, findings: `${findings}${note}`, ran: true } };\n}\n\n/**\n * The reviewer's own words, pulled out of its stream.\n *\n * Codex reports a review as prose inside an `agent_message`, with a `- [P1] title \u2014 path:lines` convention and no\n * severity or file field to read (verified 2026-09-12). So this deliberately does not parse findings into\n * structure: inventing a schema over a convention would produce confident, wrong severities the moment the\n * convention shifts. The lead reads the prose, which is what a second opinion is for.\n *\n * Returns null when the stream held no reviewer message at all, which is a different thing from a review with\n * nothing to say and must never be reported as one.\n */\nfunction findingsFrom(stream: string, repoRoot: string): string | null {\n const messages: string[] = [];\n for (const line of stream.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n try {\n const parsed: unknown = JSON.parse(line);\n const item = (parsed as { item?: { type?: string; text?: string } }).item;\n if (item?.type === \"agent_message\" && typeof item.text === \"string\") messages.push(item.text);\n } catch {\n // An unparsable line is the CLI talking to a human, not to us; the findings are in the parsed ones.\n }\n }\n if (messages.length === 0) return null;\n // Reviewers report absolute paths \u2014 here, paths inside the throwaway copy. Making them repo-relative is the\n // difference between a clickable finding and a line naming a directory that no longer exists.\n return messages.join(\"\\n\\n\").split(`${repoRoot}/`).join(\"\");\n}\n\n/**\n * Fills a manifest's argument template, dropping any placeholder nobody supplied \u2014 and the flag in front of it.\n *\n * Found by running this for real: with no model chosen, `[\"-m\", \"{model}\"]` became `[\"-m\", \"\"]`, and Codex\n * answered `The '' model is not supported`. An unsupplied option must vanish, not become an empty string, because\n * an empty string is a value and CLIs are entitled to reject it.\n */\nfunction fill(template: readonly string[], values: Readonly<Record<string, string>>): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n const placeholder = /^\\{[a-z]+\\}$/.test(argument) ? argument : null;\n if (placeholder !== null && !Object.hasOwn(values, placeholder)) {\n // Drop the flag this value belonged to, so `-m` does not survive without its model.\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction firstLines(text: string, count = 5): string {\n return text.split(\"\\n\").slice(0, count).join(\"\\n\").trim();\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import type { AdapterManifest, FanoutEventInput, SeatRef } from \"fanout-core\";\nimport { isolateWork } from \"./isolate.ts\";\nimport { CLEAN_REVISION, workSnapshot, type WorkSnapshot } from \"./revision.ts\";\nimport { runSeat, type SeatExecute } from \"./run-seat.ts\";\n\n/*\n * Asking a cold reader to falsify what the lead believes.\n *\n * The lead carries the plan, the reasoning and the justification for every line it wrote, and that context is\n * exactly what hides its mistakes from it: knowing why the code is right makes the code look right. A reader with\n * only the diff is not smarter, it is differently placed. Broad review pays for that asymmetry by the token;\n * three specific claims get it for almost nothing.\n *\n * Every rule here bends one way. A verdict we cannot read is `unclear`, a claim the reader skipped is `unclear`,\n * and a reader that never ran refutes nothing and confirms nothing. Confirmation has to be said out loud, because\n * the whole value of this is that it cannot be satisfied by silence.\n */\n\nexport type Verdict = \"confirmed\" | \"refuted\" | \"unclear\";\n\nexport interface CheckedClaim {\n claim: string;\n verdict: Verdict;\n evidence: string;\n}\n\nexport interface ClaimsOptions {\n repoRoot: string;\n claims: readonly string[];\n manifest: AdapterManifest;\n model?: string;\n timeoutMs?: number;\n execute?: SeatExecute;\n}\n\nexport interface ClaimsResult {\n event: Extract<FanoutEventInput, { type: \"claims.checked\" }>;\n /** Claims the reader actively refuted. The only reason to stop and look. */\n refuted: CheckedClaim[];\n}\n\n/** The verdict line we ask for, and the only one we will read as an answer. */\nconst VERDICT_LINE = /^\\s*CLAIM\\s+(\\d+)\\s*:\\s*(CONFIRMED|REFUTED|UNCLEAR)\\b\\s*[-\u2014:]?\\s*(.*)$/i;\n\nexport async function checkClaims(options: ClaimsOptions): Promise<ClaimsResult> {\n /*\n * A session started outside a repository is an ordinary thing, not an exception. Throwing here would make the\n * tool look broken to whoever called it; answering \"there is nothing here to check\" is both true and useful.\n */\n let snapshot: WorkSnapshot;\n try {\n snapshot = await workSnapshot({ cwd: options.repoRoot });\n } catch {\n return {\n event: {\n type: \"claims.checked\",\n repoRoot: options.repoRoot,\n revision: CLEAN_REVISION,\n by: { id: options.manifest.id },\n claims: options.claims.map((claim) =>\n unclear(claim, `${options.repoRoot} is not a git repository, so there are no changes to check`),\n ),\n ran: false,\n },\n refuted: [],\n };\n }\n const by: SeatRef = {\n id: options.manifest.id,\n ...(options.model === undefined ? {} : { model: options.model }),\n };\n\n const base = {\n type: \"claims.checked\" as const,\n repoRoot: snapshot.repoRoot,\n revision: snapshot.revision,\n by,\n };\n\n /*\n * Only uncommitted work, and the message has to say so. This reads what is in the tree right now because the\n * point is to catch a belief before it lands \u2014 the reader gets the diff and nothing else, which is what makes\n * it differently placed. Saying merely \"no changes\" reads as \"nothing is wrong\" to whoever asked, when the\n * truth is that nothing was looked at: the two are opposite answers and the caller cannot tell them apart.\n */\n if (snapshot.clean) {\n return {\n event: {\n ...base,\n claims: options.claims.map((c) =>\n unclear(\n c,\n \"the working tree is clean, and this checks uncommitted work only \u2014 nothing was read, which is \" +\n \"not the same as nothing being wrong. State your claims before you commit.\",\n ),\n ),\n ran: false,\n },\n refuted: [],\n };\n }\n\n const isolated = await isolateWork({\n repoRoot: snapshot.repoRoot,\n newFiles: snapshot.newFiles,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n try {\n const result = await runSeat({\n manifest: options.manifest,\n cwd: isolated.path,\n prompt: promptFor(options.claims),\n ...(options.model === undefined ? {} : { model: options.model }),\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n\n if (!result.ok) {\n /*\n * The reason travels with the verdict. An earlier version returned a flat \"not checked\" here, which is true\n * and useless: it told the owner nothing and told me nothing when this failed on its first real run.\n */\n return {\n event: {\n ...base,\n claims: options.claims.map((claim) => unclear(claim, result.problem)),\n ran: false,\n },\n refuted: [],\n };\n }\n\n const claims = readVerdicts(options.claims, result.text);\n return { event: { ...base, claims, ran: true }, refuted: claims.filter((c) => c.verdict === \"refuted\") };\n } finally {\n await isolated.dispose();\n }\n}\n\n/**\n * What we ask the reader.\n *\n * It is told to try to falsify, not to agree, and told that saying \"I cannot tell\" is a real answer. A reader\n * nudged toward confirmation will confirm, which would make every run of this worthless and expensive at once.\n */\nfunction promptFor(claims: readonly string[]): string {\n const numbered = claims.map((claim, index) => `${String(index + 1)}. ${claim}`).join(\"\\n\");\n return [\n \"You are reading a diff you did not write, with no knowledge of why it was written.\",\n \"Below are claims its author makes about it. Your job is to try to FALSIFY each one by reading the code.\",\n \"\",\n \"Rules:\",\n \"- Answer every claim, in order, one line each, in exactly this format:\",\n \" CLAIM <n>: CONFIRMED|REFUTED|UNCLEAR - <one sentence of evidence, naming a file and line where you can>\",\n \"- REFUTED means you found a concrete case where the claim does not hold. Name it.\",\n \"- UNCLEAR is a real answer. Use it when the diff does not let you tell. Do not guess, and do not\",\n \" confirm something you merely failed to disprove.\",\n \"- CONFIRMED means you actively checked and it holds.\",\n \"- Say nothing else before or after the CLAIM lines.\",\n \"\",\n \"Claims:\",\n numbered,\n ].join(\"\\n\");\n}\n\n/**\n * Reads the reader's verdicts, and refuses to invent any it did not give.\n *\n * A missing line, an unparsable line, or a line for a claim that does not exist all leave that claim `unclear`.\n * The failure mode this protects against is the one that matters: a checker that quietly reports everything fine\n * whenever the output format drifts is worse than no checker, because it is trusted.\n */\nexport function readVerdicts(claims: readonly string[], text: string): CheckedClaim[] {\n const found = new Map<number, { verdict: Verdict; evidence: string }>();\n\n for (const line of text.split(\"\\n\")) {\n const match = VERDICT_LINE.exec(line);\n if (match === null) continue;\n const index = Number(match[1]) - 1;\n const word = (match[2] ?? \"\").toLowerCase();\n if (index < 0 || index >= claims.length) continue;\n if (word !== \"confirmed\" && word !== \"refuted\" && word !== \"unclear\") continue;\n // First answer wins: a reader that contradicts itself later has not confirmed anything.\n if (!found.has(index)) found.set(index, { verdict: word, evidence: (match[3] ?? \"\").trim() });\n }\n\n return claims.map((claim, index) => {\n const answer = found.get(index);\n if (answer === undefined) return unclear(claim, \"the reader did not answer this claim\");\n // A refusal with no reason is not actionable, but it is still a refusal \u2014 we keep it and say the reason is missing.\n return {\n claim,\n verdict: answer.verdict,\n evidence: answer.evidence === \"\" ? \"(no reason given)\" : answer.evidence,\n };\n });\n}\n\nfunction unclear(claim: string, evidence: string): CheckedClaim {\n return { claim, verdict: \"unclear\", evidence };\n}\n", "import { readFileSync } from \"node:fs\";\n\n/*\n * The mission view's page, read from disk beside this file.\n *\n * It is one self-contained HTML file with no framework, no bundler and no dependencies (ADR 0019), because this\n * page renders your private source code and every dependency it carried would be one more thing that could read\n * it. Kept as `.html` rather than a template string so it stays a file a person can open, lint and read.\n *\n * Read on every request rather than cached. It is a few kilobytes off a local disk for a page only this machine\n * can reach, and caching it meant an edit did nothing until the daemon was restarted \u2014 which is how the first\n * version of this was reviewed against a screen that had not changed.\n */\n\n/** The page, with `{{TOKEN}}` still in it: the daemon stamps its own token in as it serves. */\nexport function missionViewHtml(): string {\n return readFileSync(new URL(\"./view.html\", import.meta.url), \"utf8\");\n}\n", "import { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readdirSync, rmSync, symlinkSync, type Dirent } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport { baseEnv } from \"../env.ts\";\nimport { workSnapshot } from \"./revision.ts\";\n\n/*\n * Running the project's own checks against what an agent actually wrote.\n *\n * The agent already told us its tests pass. That is not evidence: it is the account of the only party with an\n * interest in the answer, produced inside a sandbox that could not open a port or reach a toolchain. So the gate\n * runs the commands itself, in the run's own worktree, and believes the exit codes.\n *\n * The commands come from the plan \u2014 which the safety report showed the user before anything launched \u2014 and never\n * from an agent. A check an agent could choose is a check an agent can pass.\n */\n\nexport interface ChecksOptions {\n /** The worktree holding the agent's changes. */\n cwd: string;\n /** Exactly the commands the plan declared for this line, in order. */\n commands: readonly string[];\n /**\n * The repository the worktree came from. When given, its dependency directories are linked in for the length\n * of the check and removed afterwards \u2014 see `withDependencies`.\n */\n repoRoot?: string;\n timeoutMs?: number;\n /** Injected in tests so nothing needs a real toolchain. */\n run?: (command: string, cwd: string, timeoutMs: number) => Promise<CommandOutcome>;\n}\n\n/**\n * Directories a project keeps its installed dependencies in.\n *\n * A git worktree contains the tracked files and nothing else, so `npm run test` in one reports\n * `vitest: command not found` \u2014 which the gate would otherwise record as the project's checks failing. Found by\n * running the gate against a real agent's work rather than against a fixture.\n *\n * They are lent only while the check runs, never while the agent works. The agent's sandbox can write anywhere in\n * its worktree, and a link to the real `node_modules` would put the developer's installed packages inside the one\n * place an agent is allowed to write. An agent that cannot run the full suite is the expected case, and the\n * reason this gate runs it afterwards.\n */\nconst DEPENDENCY_NAMES = new Set([\"node_modules\", \".venv\", \"vendor\"]);\n\n/**\n * Every dependency directory in the repository, not only the one at the top.\n *\n * A workspace puts a package's links inside that package: without `packages/daemon/node_modules`, a test there\n * cannot resolve `fanout-core` however complete the root is. Lending only the root ran 90 of 656 tests \u2014 a\n * suite that looks like it ran and did not, which is the most expensive kind of green there is.\n *\n * The depth is generous rather than tight because the first attempt stopped at three and missed\n * `packages/adapters/codex/node_modules` at four, leaving that package's tests unable to import anything. It\n * costs a bounded directory walk that never descends into a dependency directory, and guessing how deeply\n * someone nests their packages is not a guess worth making.\n */\nfunction dependencyDirectories(root: string, depth = 6): string[] {\n if (depth === 0) return [];\n const found: string[] = [];\n let entries: Dirent[];\n try {\n entries = readdirSync(root, { withFileTypes: true });\n } catch {\n return found;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".git\")) continue;\n if (DEPENDENCY_NAMES.has(entry.name)) {\n found.push(join(root, entry.name));\n continue; // Never descend into one: its own node_modules are its business.\n }\n found.push(...dependencyDirectories(join(root, entry.name), depth - 1));\n }\n return found;\n}\n\nexport interface CommandOutcome {\n exitCode: number | null;\n /** Combined output, newest-relevant last, capped. */\n output: string;\n timedOut: boolean;\n}\n\nexport interface ChecksResult {\n ok: boolean;\n /** What the work looked like when these commands ran, so a merge can refuse a diff that has moved since. */\n revision: string;\n commands: string[];\n summary: string;\n /** Per command, so a person can see which one broke without reading everything. */\n outcomes: { command: string; exitCode: number | null; timedOut: boolean; tail: string }[];\n}\n\nconst MAX_OUTPUT = 64 * 1024;\n\n/**\n * Runs every declared check, stopping at the first failure.\n *\n * Stopping early is deliberate: the second command's output after the first has failed is noise, and the answer\n * to \"may this merge\" was already settled by the first. Nothing is \"ok\" by default \u2014 a line with no checks\n * declared is reported as exactly that, not as a pass, because \"nothing failed\" and \"nothing ran\" are different\n * facts and only one of them is evidence.\n */\nexport async function runChecks(options: ChecksOptions): Promise<ChecksResult> {\n const snapshot = await workSnapshot({ cwd: options.cwd });\n const run = options.run ?? runCommand;\n const commands = [...options.commands];\n const outcomes: ChecksResult[\"outcomes\"] = [];\n\n if (commands.length === 0) {\n return {\n ok: false,\n revision: snapshot.revision,\n commands,\n summary: \"no checks were declared for this line, so nothing was verified\",\n outcomes,\n };\n }\n\n const unlink =\n options.repoRoot === undefined ? () => undefined : lendDependencies(options.repoRoot, options.cwd);\n try {\n for (const command of commands) {\n const outcome = await run(command, options.cwd, options.timeoutMs ?? 10 * 60_000);\n outcomes.push({\n command,\n exitCode: outcome.exitCode,\n timedOut: outcome.timedOut,\n tail: lastLines(outcome.output),\n });\n if (outcome.timedOut || outcome.exitCode !== 0) {\n return {\n ok: false,\n revision: snapshot.revision,\n commands,\n summary: outcome.timedOut\n ? `\\`${command}\\` did not finish in time`\n : `\\`${command}\\` exited ${String(outcome.exitCode)}`,\n outcomes,\n };\n }\n }\n\n return {\n ok: true,\n revision: snapshot.revision,\n commands,\n summary: `${String(commands.length)} check${commands.length === 1 ? \"\" : \"s\"} passed`,\n outcomes,\n };\n } finally {\n unlink();\n }\n}\n\n/**\n * Links a repository's dependency directories into a worktree, and returns how to take them away again.\n *\n * A link rather than a copy, because `node_modules` is enormous and this happens on every check. Removed in a\n * `finally` so a failing check does not leave the developer's installed packages reachable from a directory an\n * agent may later be allowed to write to.\n */\nfunction lendDependencies(repoRoot: string, worktree: string): () => void {\n const lent: string[] = [];\n for (const source of dependencyDirectories(repoRoot)) {\n const destination = join(worktree, relative(repoRoot, source));\n if (existsSync(destination)) continue;\n try {\n mkdirSync(dirname(destination), { recursive: true });\n symlinkSync(source, destination, \"dir\");\n lent.push(destination);\n } catch {\n // Nothing lent and nothing to clean up: the check will say what it could not find.\n }\n }\n return () => {\n for (const path of lent) rmSync(path, { force: true });\n };\n}\n\n/**\n * Runs one command the way a person would, and kills it if it will not stop.\n *\n * A shell, because the checks people write are shell (`npm run check && npm run lint`), and the user saw the\n * exact strings in the safety report before any of this started. The environment is the same allowlist agents\n * get, so a check cannot quietly depend on a secret in the developer's shell and then fail on someone else's\n * machine. Output is capped: a check that prints a hundred megabytes should not be able to exhaust the daemon.\n *\n * It runs in its own process group, and the deadline kills the group rather than the shell. Found by CI on Linux\n * while macOS passed: `sh -c \"sleep 30\"` leaves `sleep` as a child of the shell, so killing the shell leaves a\n * grandchild alive holding the pipes open and the promise never settles. A check that spawns anything \u2014 and every\n * real one does, that is what `npm test` is \u2014 could have hung the gate forever.\n */\nasync function runCommand(command: string, cwd: string, timeoutMs: number): Promise<CommandOutcome> {\n return new Promise<CommandOutcome>((resolve) => {\n const child = spawn(command, {\n cwd,\n shell: true,\n env: { ...baseEnv(), CI: \"1\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n // Its own process group, so the whole tree can be signalled and not just the shell at the top of it.\n detached: true,\n });\n\n let output = \"\";\n let timedOut = false;\n\n /** Signals every descendant. A check's children are the check. */\n const signalGroup = (signal: NodeJS.Signals): void => {\n if (child.pid === undefined) return;\n try {\n process.kill(-child.pid, signal);\n } catch {\n // Already gone: nothing to signal and nothing to report.\n }\n };\n const keep = (chunk: Buffer): void => {\n if (output.length < MAX_OUTPUT) output += chunk.toString().slice(0, MAX_OUTPUT - output.length);\n };\n child.stdout.on(\"data\", keep);\n child.stderr.on(\"data\", keep);\n\n const deadline = setTimeout(() => {\n timedOut = true;\n signalGroup(\"SIGTERM\");\n // A check that ignores SIGTERM is a check that has stopped being one.\n const escalate = setTimeout(() => {\n signalGroup(\"SIGKILL\");\n }, 5_000);\n escalate.unref();\n }, timeoutMs);\n deadline.unref();\n\n child.on(\"error\", (error) => {\n clearTimeout(deadline);\n resolve({ exitCode: null, output: `${output}\\n${error.message}`, timedOut });\n });\n /*\n * `exit` rather than `close`: close waits for every pipe to end, and an orphan holding stdout open would make\n * a killed command look like a running one forever. The output we have when it exits is the output there is.\n */\n child.on(\"exit\", (code) => {\n clearTimeout(deadline);\n resolve({ exitCode: code, output, timedOut });\n });\n });\n}\n\n/** The end of the output, which is where a failing command says why. */\nfunction lastLines(output: string, count = 20): string {\n return output.split(\"\\n\").filter(Boolean).slice(-count).join(\"\\n\");\n}\n", "import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { runChecks, type ChecksOptions, type ChecksResult } from \"./checks.ts\";\nimport { git } from \"../workspace/git.ts\";\n\n/*\n * Proving that a fix fixes something.\n *\n * The fourth non-negotiable says a bug fix ships with a test that fails on the old code, and this is the only\n * part of the gate that cannot be satisfied by an agent being persuasive. A test that passes on the new code\n * proves the new code passes its own test. A test that *fails on the old code* proves the test is about the bug.\n *\n * So: build the old code again from the base commit, put only the run's new and changed tests on top of it, and\n * run the check. It has to fail. If it passes, the test would have passed before the fix, and whatever it is\n * testing is not what was broken.\n *\n * Everything here bends towards refusing. A proof we could not run is not a proof; a test file we could not\n * identify is not a proof; a check that errored for some unrelated reason is not a proof.\n */\n\n/** Paths that look like tests. Documented rather than clever: a person has to be able to predict this. */\nconst TEST_PATH =\n /(^|\\/)(tests?|__tests__|spec)\\/|\\.(test|spec)\\.[cm]?[jt]sx?$|_test\\.(py|go|rb)$|(^|\\/)test_[^/]+\\.py$/;\n\nexport function looksLikeATest(path: string): boolean {\n return TEST_PATH.test(path);\n}\n\nexport interface ProofOptions {\n /** The repository the run started from. */\n repoRoot: string;\n /** The worktree holding the agent's changes. */\n workspacePath: string;\n /** The commit the run started from: the old code. */\n baseCommit: string;\n /** Every path the run touched, repo-relative. */\n touched: readonly string[];\n /** The line's own checks. A proof runs the project's real command, not one we invent. */\n commands: readonly string[];\n timeoutMs?: number;\n runChecksImpl?: (options: ChecksOptions) => Promise<ChecksResult>;\n}\n\nexport interface ProofResult {\n ok: boolean;\n /** The tests that were put on the old code. Empty when none could be identified. */\n tests: string[];\n /** Named so a reader knows what was proven, and so `proof.done` can carry them. */\n failedOnOld: string[];\n why: string;\n}\n\n/**\n * Runs the run's new tests against the old code and insists they fail.\n *\n * The old code is a fresh worktree at the base commit \u2014 not the agent's worktree with changes reverted, because\n * \"reverted\" is a thing we would have to get exactly right and a checkout is a thing git gets right for us.\n */\nexport async function proveFix(options: ProofOptions): Promise<ProofResult> {\n const tests = options.touched.filter(looksLikeATest).sort();\n if (tests.length === 0) {\n return {\n ok: false,\n tests: [],\n failedOnOld: [],\n why: \"this line is a fix but changed no file that looks like a test, so there is nothing to prove it with\",\n };\n }\n if (options.commands.length === 0) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"this line declares no checks, so there is no command that could run the test\",\n };\n }\n\n const root = mkdtempSync(join(tmpdir(), \"fanout-proof-\"));\n const oldCode = join(root, \"old\");\n\n try {\n await git([\"worktree\", \"add\", \"--detach\", \"--quiet\", oldCode, options.baseCommit], {\n cwd: options.repoRoot,\n });\n\n // Only the tests travel. Bringing anything else would be bringing the fix, which is the whole point.\n for (const test of tests) {\n const destination = join(oldCode, test);\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(join(options.workspacePath, test), destination);\n }\n\n const run = options.runChecksImpl ?? runChecks;\n const result = await run({\n cwd: oldCode,\n repoRoot: options.repoRoot,\n commands: options.commands,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n /*\n * Failing is the passing outcome here, and it has to fail for the right reason. A command that could not\n * start at all tells us nothing about the bug: it is a broken proof, not a proven fix.\n */\n const couldNotRun = result.outcomes.some((outcome) => outcome.exitCode === null && !outcome.timedOut);\n if (couldNotRun) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"the check could not run against the old code at all, so nothing was proven either way\",\n };\n }\n\n if (result.ok) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"the new tests pass on the old code, so they do not test what was broken\",\n };\n }\n\n return {\n ok: true,\n tests,\n failedOnOld: tests,\n why: `the new tests fail on ${options.baseCommit.slice(0, 7)} and pass on this work`,\n };\n } catch (cause) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: `the old code could not be rebuilt to test against: ${cause instanceof Error ? cause.message : String(cause)}`,\n };\n } finally {\n await git([\"worktree\", \"remove\", \"--force\", oldCode], { cwd: options.repoRoot }).catch(() => undefined);\n rmSync(root, { recursive: true, force: true });\n }\n}\n", "import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { mergeReadiness, pathInScope, type PlanLine, type RunView } from \"fanout-core\";\nimport { git, lines, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * Putting a run's work into the repository, and refusing to in every other case.\n *\n * This is the most dangerous function in the product: everything else can be wrong and leave your code alone.\n * So it asks permission from a pure judgement it cannot influence (`mergeReadiness`, over recorded facts), it\n * applies with a three-way merge so a conflict is a conflict rather than a silent overwrite, and it never forces\n * anything. A conflict is reported and the repository is left exactly as it was found.\n *\n * It also refuses to merge a diff that is not the one everybody looked at. Review, checks, proof and approval each\n * recorded the revision they judged; if the worktree has moved since, all four were about a different piece of\n * work and none of them is evidence about this one.\n */\n\nexport interface MergeOptions {\n repoRoot: string;\n /** The worktree holding the agent's changes. */\n workspacePath: string;\n run: RunView;\n line: PlanLine;\n /** What the work is right now, freshly collected \u2014 not what anyone remembers it being. */\n revision: string;\n patch: string;\n /** Files the run created, which a patch does not carry. */\n newFiles: readonly string[];\n /**\n * The commit's subject and body, written by the lead.\n *\n * Every project has its own convention and some enforce it with a hook; ours rejected the gate's own first\n * attempt. Guessing a format is not possible and bypassing the hook is out of the question \u2014 a tool that\n * merged past the rules a repository set for itself would be the least trustworthy thing here. So the lead,\n * which can read the repository's standard, supplies this. The trailers below it are the gate's and are not\n * the caller's to write.\n */\n message?: string;\n /**\n * Files this merge may apply even though the plan did not grant them, each named in full.\n *\n * The plan's write scope is what the safety report showed the user before anything launched, and until this\n * existed it was decoration at merge time: `collect` worked out what a run had written outside its scope and\n * the only thing that ever happened to that list was being printed. A run could write anywhere in its worktree\n * and the gate would apply it, provided nobody read one line of prose.\n *\n * Widening it is sometimes right \u2014 the lead's own prompt asks for an export the plan forgot to grant, which is\n * how this was found \u2014 so the answer is not to forbid it but to make it deliberate. Naming each path means a\n * lead cannot wave through a file it has not looked at, and the paths are recorded in the commit.\n */\n allowOutsideScope?: readonly string[];\n timeoutMs?: number;\n}\n\nexport type MergeOutcome =\n | { kind: \"merged\"; files: string[]; commit: string }\n | { kind: \"conflict\"; files: string[]; why: string }\n | { kind: \"refused\"; why: string[] };\n\n/**\n * Merges a run's work, or explains why it will not.\n *\n * Nothing is committed unless every file applied. A partial merge is the worst outcome available here \u2014 half a\n * change in your working tree, with the other half in a report \u2014 so a conflict rolls the whole attempt back.\n */\nexport async function mergeRun(options: MergeOptions): Promise<MergeOutcome> {\n const readiness = mergeReadiness(options.run, options.line, options.revision);\n if (!readiness.ready) {\n return { kind: \"refused\", why: readiness.blockers.map((blocker) => blocker.message) };\n }\n\n /*\n * The plan's write scope, enforced rather than reported. Checked against what is about to be applied \u2014 the\n * patch and the new files \u2014 rather than against anything recorded earlier, for the same reason the revision is\n * re-collected: the question is what this merge would do to your repository now.\n */\n const allowed = new Set(options.allowOutsideScope ?? []);\n const ungranted = [...new Set([...filesInPatch(options.patch), ...options.newFiles])]\n .filter((file) => !options.line.scope.write.some((pattern) => pathInScope(file, pattern)))\n .filter((file) => !allowed.has(file))\n .sort();\n if (ungranted.length > 0) {\n return {\n kind: \"refused\",\n why: [\n `${options.run.runId} wrote outside the scope its plan declared: ${ungranted.join(\", \")}. ` +\n \"Send it back, or name those paths in allowOutsideScope if you have read them and want them.\",\n ],\n };\n }\n\n const inRepo = {\n cwd: options.repoRoot,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n };\n\n /*\n * A dirty repository is refused rather than merged into. The three-way apply would probably work, and\n * \"probably\" is not a word that belongs anywhere near someone else's uncommitted work.\n */\n const dirty = zeroSeparated(await git([\"status\", \"--porcelain\", \"-z\"], inRepo))\n .map((entry) => entry.slice(3))\n .filter((path) => path !== \"\");\n const wouldTouch = new Set([...filesInPatch(options.patch), ...options.newFiles]);\n const clash = dirty.filter((path) => wouldTouch.has(path)).sort();\n if (clash.length > 0) {\n return {\n kind: \"refused\",\n why: [\n `You have uncommitted changes in ${clash.join(\", \")}, which this merge would touch. ` +\n \"Commit or stash them first.\",\n ],\n };\n }\n\n const before = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n const applied: string[] = [];\n\n try {\n if (options.patch.trim() !== \"\") {\n /*\n * `-3` so git can use the blobs both sides came from: it turns \"this hunk does not apply\" into a real\n * three-way merge, and into honest conflict markers when the two changes genuinely disagree.\n */\n await applyPatch(options.patch, options.repoRoot, options.timeoutMs);\n applied.push(...filesInPatch(options.patch));\n }\n\n for (const file of options.newFiles) {\n const destination = join(options.repoRoot, file);\n // A \"new\" file that already exists is not new: someone else created it while this run was working.\n if (existsSync(destination)) {\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"conflict\",\n files: [file],\n why: `${file} was created here while the run was working, so this would overwrite it`,\n };\n }\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(join(options.workspacePath, file), destination);\n applied.push(file);\n }\n } catch (cause) {\n const conflicted = await conflictedFiles(options.repoRoot, options.timeoutMs);\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"conflict\",\n files: conflicted.length > 0 ? conflicted : [...wouldTouch].sort(),\n why: conflicted.length > 0 ? \"the work disagrees with what is here now\" : describe(cause),\n };\n }\n\n const files = [...new Set(applied)].sort();\n try {\n await git([\"add\", \"--\", ...files], inRepo);\n await git(\n [\n \"commit\",\n \"--quiet\",\n \"-m\",\n commitMessage(options),\n \"--author\",\n `${options.run.seat.id} via fanout <noreply@fanout.invalid>`,\n \"--\",\n ...files,\n ],\n inRepo,\n );\n } catch (cause) {\n /*\n * A repository may refuse its own commit \u2014 ours does, through a commit-msg hook, and said so the first time\n * the gate tried. Rolling back here is the difference between \"not merged\" and the thing this function\n * promises never to leave behind: the work applied, staged, and uncommitted, with the report saying it\n * failed. `--no-verify` is never the answer; a tool that merged past the rules a repository set for itself\n * would be the least trustworthy thing in it.\n */\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"refused\",\n why: [`The repository refused the commit, and nothing was changed: ${describe(cause)}`],\n };\n }\n\n const commit = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n return { kind: \"merged\", files, commit };\n}\n\n/**\n * Who wrote this, in the history itself.\n *\n * The author is the seat, because it wrote the code, and the trailer names the person or policy that approved it,\n * because someone authorised it. A repository whose history cannot answer \"who decided this\" is a repository\n * where nobody decided.\n */\nfunction commitMessage(options: MergeOptions): string {\n const { line, run } = options;\n const approval = run.approval;\n const by =\n approval === null\n ? \"unknown\"\n : approval.by.kind === \"user\"\n ? \"the repository's owner\"\n : `policy \"${approval.by.name}\"`;\n return [\n options.message ?? `${line.title} (${line.id})\\n\\n${line.prompt.split(\"\\n\")[0] ?? \"\"}`,\n \"\",\n `Built-by: ${run.seat.id}${run.seat.model === undefined ? \"\" : ` (${run.seat.model})`} via fanout`,\n `Approved-by: ${by}`,\n // Only when the plan's scope was widened. A silent override would be no override at all.\n ...(options.allowOutsideScope === undefined || options.allowOutsideScope.length === 0\n ? []\n : [`Outside-scope: ${[...options.allowOutsideScope].sort().join(\", \")}`]),\n `Fanout-run: ${run.runId}`,\n ].join(\"\\n\");\n}\n\n/** Every path a patch claims to change, read from the patch rather than from anyone's account of it. */\nexport function filesInPatch(patch: string): string[] {\n const paths = new Set<string>();\n for (const line of patch.split(\"\\n\")) {\n const match = /^\\+\\+\\+ b\\/(.+)$/.exec(line);\n if (match?.[1] !== undefined && match[1] !== \"/dev/null\") paths.add(match[1]);\n }\n return [...paths].sort();\n}\n\nasync function applyPatch(patch: string, cwd: string, timeoutMs?: number): Promise<void> {\n const { execFile } = await import(\"node:child_process\");\n const { gitEnv } = await import(\"../workspace/git.ts\");\n const failure = await new Promise<Error | null>((resolve) => {\n const child = execFile(\n \"git\",\n [\"apply\", \"-3\", \"--whitespace=nowarn\", \"-\"],\n { cwd, timeout: timeoutMs ?? 60_000, env: gitEnv() },\n (error) => {\n resolve(error);\n },\n );\n child.stdin?.end(patch);\n });\n if (failure !== null) throw failure;\n}\n\nasync function conflictedFiles(repoRoot: string, timeoutMs?: number): Promise<string[]> {\n try {\n return lines(\n await git([\"diff\", \"--name-only\", \"--diff-filter=U\"], {\n cwd: repoRoot,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n }),\n );\n } catch {\n return [];\n }\n}\n\n/** Back to exactly where we started. A half-applied merge is worse than a refused one. */\nasync function rollback(repoRoot: string, commit: string, timeoutMs?: number): Promise<void> {\n const inRepo = { cwd: repoRoot, ...(timeoutMs === undefined ? {} : { timeoutMs }) };\n await git([\"reset\", \"--hard\", \"--quiet\", commit], inRepo).catch(() => undefined);\n await git([\"clean\", \"-fdq\"], inRepo).catch(() => undefined);\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import { join } from \"node:path\";\nimport type { Ledger, PlanLine, RunView, SeatAdapter } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { startRun, type ActiveRun, type RunLimits } from \"../run.ts\";\n\n/*\n * Sending a diff back to the agent that wrote it.\n *\n * The whole value is in the word \"back\". The agent still holds its own reasoning about this code, so a note\n * saying \"escape the quotes in the header row too\" lands on someone who knows which header row, what it was\n * weighed against, and why the first attempt looked right. A fresh run handed a summary of that reasoning is a\n * stranger reading a description of a conversation it was not in \u2014 and it is charged at the same rate.\n *\n * It is also the same worktree, so the agent sees the code it wrote and the notes about it together rather than\n * being asked to imagine both.\n */\n\n/** Two rounds, then a person decides. */\nexport const MAX_REWORKS = 2;\n\nexport interface ReworkOptions {\n ledger: Ledger;\n adapter: SeatAdapter;\n missionId: string;\n line: PlanLine;\n run: RunView;\n /** The worktree the run already has. Rework never creates a new one. */\n workspacePath: string;\n runsRoot: string;\n limits: RunLimits;\n}\n\nexport type ReworkOutcome =\n { kind: \"started\"; runId: string; active: ActiveRun } | { kind: \"refused\"; why: string };\n\n/**\n * Starts the next turn of the conversation that produced this diff, with the reviewer's notes as the instruction.\n *\n * Every refusal here is a case where continuing would look like rework and not be one. The most important is a\n * seat that cannot resume: starting fresh while calling it rework would spend a subscription to discard exactly\n * the context the subscription was spent building, with nothing on screen to say so.\n */\nexport function reworkRun(options: ReworkOptions): ReworkOutcome {\n const { run, line } = options;\n\n const review = run.review;\n if (review?.verdict !== \"rework\") {\n return { kind: \"refused\", why: \"rework needs a review that asked for it, with the notes to send back\" };\n }\n if (run.status === \"merged\" || run.status === \"dropped\") {\n return { kind: \"refused\", why: `this run is already ${run.status}` };\n }\n if (run.sessionId === null) {\n return {\n kind: \"refused\",\n why: \"this run never told us its session, so there is no conversation to continue\",\n };\n }\n if (options.adapter.resume === undefined) {\n return {\n kind: \"refused\",\n why: `${options.adapter.id} cannot resume a session, so this work cannot be sent back to the agent that wrote it`,\n };\n }\n if (run.attempt > MAX_REWORKS) {\n /*\n * A third attempt is a signal about the task, not about the agent. Rework is for a diff that is nearly right;\n * work that has come back twice needs a person to look at the plan rather than another round of notes.\n */\n return {\n kind: \"refused\",\n why: `this line has already been reworked ${String(run.attempt - 1)} times; decide what to do with it instead`,\n };\n }\n\n const attempt = run.attempt + 1;\n const runId = `${line.id}-${String(attempt)}`;\n const directory = join(options.runsRoot, options.missionId, runId);\n\n options.ledger.appendAll([\n { type: \"run.queued\", missionId: options.missionId, runId, lineId: line.id, seat: run.seat, attempt },\n ]);\n\n const active = startRun({\n ledger: options.ledger,\n adapter: options.adapter,\n context: {\n missionId: options.missionId,\n runId,\n /*\n * The notes are the instruction, not the original task. The session already holds the task; repeating it\n * would invite the agent to start again instead of reading what it got wrong.\n */\n line: { ...line, prompt: reworkPrompt(review.notes) },\n workdir: options.workspacePath,\n reportPath: join(directory, \"report.md\"),\n baseEnv: baseEnv(),\n sessionId: run.sessionId,\n },\n logPath: join(directory, \"run.log\"),\n limits: options.limits,\n resumeSession: run.sessionId,\n });\n\n return { kind: \"started\", runId, active };\n}\n\n/**\n * What the agent is told.\n *\n * Short on purpose. It is already in the conversation and already has the code in front of it; the one thing it\n * does not have is what a reader thought when they read it.\n */\nexport function reworkPrompt(notes: string): string {\n return [\n \"Your work was reviewed and needs changes. The notes are below.\",\n \"\",\n \"Change only what they ask for, in the same files you already have open. Do not start over, do not commit,\",\n \"and do not widen the scope you were given.\",\n \"\",\n notes,\n ].join(\"\\n\");\n}\n", "import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n missionReport,\n PlanGraph,\n PlanLine,\n project,\n validatePlan,\n versionOf,\n type AdapterManifest,\n type Ledger,\n type SeatAdapter,\n type SeatInfo,\n} from \"fanout-core\";\nimport {\n checkClaims,\n chooseSeat,\n createSafetyDependencies,\n filesInPatch,\n mergeRun,\n proveFix,\n reworkRun,\n runChecks,\n workSnapshot,\n createMissionRunner,\n createWorkspaceManager,\n detectSeats,\n git,\n lines as splitLines,\n safetyReport,\n zeroSeparated,\n type MissionHandle,\n type RunLimits,\n} from \"fanout-daemon\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\n/*\n * The lead's tools. Claude Code is the brain; this is the hand it works with.\n *\n * Every tool answers in plain words as well as data, because the lead reads them and so does the person watching.\n * Two rules shape the surface:\n *\n * - Nothing runs that has not passed the gate. `launch` refuses a red safety report unless the user says\n * otherwise in so many words, and that override is recorded.\n * - Nothing merges here at all. Review and merge arrive with the gate; a tool that quietly merged would be the\n * most dangerous thing in the product.\n */\n\nexport interface FanoutMcpOptions {\n ledger: Ledger;\n /** The repository the session is working in. */\n repoRoot: string;\n /** Where run logs, reports and workspaces live, and where the owner's seat preferences are kept. */\n paths: { runs: string; workspaces: string; home?: string };\n /** Seat id to adapter, and the manifests behind them. */\n adapters: ReadonlyMap<string, SeatAdapter>;\n manifests: readonly AdapterManifest[];\n limits: RunLimits;\n /** Injected in tests so nothing needs a CLI installed. */\n execute?: (\n binary: string,\n args: readonly string[],\n ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n /** The clock elapsed and quiet times are measured against; injected so tests are not timing-dependent. */\n now?: () => Date;\n}\n\nconst MissionLimits = { maxParallel: z.int().min(1).max(16).default(3) };\n\nexport function createFanoutServer(options: FanoutMcpOptions): McpServer {\n const server = new McpServer(\n { name: \"fanout\", version: versionOf(import.meta.url) },\n {\n instructions:\n \"Fanout runs the other coding-agent CLIs on this machine as a crew. Plan with `plan_check`, start with \" +\n \"`launch`, watch with `mission_status`, and read a run's work with `run_diff`. Nothing merges here: review \" +\n \"the diff yourself and apply it, or wait for the merge gate.\",\n },\n );\n\n const workspaces = createWorkspaceManager({\n repoRoot: options.repoRoot,\n workspaceRoot: options.paths.workspaces,\n });\n /*\n * Detection spawns processes, so a line uses the crew last reported at startup or by the seats tool rather\n * than waiting on four CLIs before it can begin. Headroom still comes from the ledger every time: a seat\n * running out is exactly the thing that changes between one line and the next.\n */\n let crew: readonly SeatInfo[] = [];\n void detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n }).then((seats) => {\n crew = seats;\n });\n\n const runner = createMissionRunner({\n ledger: options.ledger,\n workspaces,\n adapters: options.adapters,\n runsRoot: options.paths.runs,\n limits: options.limits,\n route: (line) => {\n const home = options.paths.home;\n // Without a home there are no seat preferences to honour, and routing without them could spend a seat the\n // owner switched off. The plan's own seat is the choice that can only fail loudly.\n if (home === undefined) return { kind: \"keep\", seat: line.seat.id };\n return chooseSeat(line.seat.id, {\n home,\n crew,\n headroom: project(options.ledger.read()).headroom,\n now: new Date(),\n });\n },\n });\n const missions = new Map<string, MissionHandle>();\n\n server.registerTool(\n \"seats\",\n {\n title: \"The crew on this machine\",\n description:\n \"Which agent CLIs are installed, which version, and whether each is signed in. A seat whose CLI cannot \" +\n \"tell us is reported as unknown, never as ready.\",\n inputSchema: {},\n },\n async () => {\n const seats = await detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n crew = seats;\n const ready = seats.filter((seat) => seat.supported && seat.signedIn === \"yes\");\n return text(\n `${ready.length} of ${seats.length} seats are ready.\\n` +\n seats\n .map(\n (seat) =>\n `- ${seat.id}: ${seat.version ?? \"not installed\"}, ` +\n (seat.supported ? seat.signedIn : \"unsupported version\"),\n )\n .join(\"\\n\"),\n { seats },\n );\n },\n );\n\n server.registerTool(\n \"repo_overview\",\n {\n title: \"A map of this repository\",\n description:\n \"What is here and where, so a plan can be written without reading every file: the commit the mission \" +\n \"would start from, whether the tree is clean, the top-level areas by size, and the checks the project runs.\",\n inputSchema: {},\n },\n async () => {\n const overview = await repoOverview(options.repoRoot);\n return text(\n `On ${overview.head.slice(0, 7)}${overview.dirty.length > 0 ? ` with ${overview.dirty.length} uncommitted file(s)` : \", clean\"}.\\n` +\n `Areas: ${overview.areas.map((area) => `${area.path} (${area.files})`).join(\", \")}\\n` +\n `Checks: ${overview.checks.length > 0 ? overview.checks.join(\", \") : \"none found\"}`,\n overview,\n );\n },\n );\n\n server.registerTool(\n \"plan_check\",\n {\n title: \"Check a plan before anything runs\",\n description:\n \"Validates a plan and returns the safety report: overlapping write scopes, anything deny-listed in the \" +\n \"repository, seats that are missing or signed out, the concurrency limits, and the exact commands that \" +\n \"would run. Records nothing, so iterate freely.\",\n inputSchema: { lines: z.array(PlanLine), ...MissionLimits },\n },\n async ({ lines, maxParallel }) => {\n const plan = PlanGraph.parse({ lines });\n const report = await gate(options, plan, maxParallel);\n const blocking = report.checks.filter((check) => !check.ok && check.severity === \"block\");\n return text(\n blocking.length === 0\n ? `The plan is ready to launch. ${report.checks.filter((check) => !check.ok).length} warning(s).`\n : `This plan cannot launch yet:\\n${blocking.map((check) => `- ${check.message}`).join(\"\\n\")}`,\n report,\n );\n },\n );\n\n server.registerTool(\n \"launch\",\n {\n title: \"Start a mission\",\n description:\n \"Runs a plan: each line in its own git worktree, in dependency order, never more at once than allowed. \" +\n \"Refuses a plan whose safety report has a blocking failure unless `override` explains why, which is \" +\n \"recorded. Returns as soon as the runs are under way; watch with mission_status.\",\n inputSchema: {\n goal: z.string().min(1).max(4000),\n lines: z.array(PlanLine),\n ...MissionLimits,\n override: z.string().min(10).max(500).optional(),\n },\n },\n async ({ goal, lines, maxParallel, override }) => {\n const plan = PlanGraph.parse({ lines });\n const issues = validatePlan(plan);\n if (issues.length > 0) {\n return text(`This plan cannot run:\\n${issues.map((issue) => `- ${issue.message}`).join(\"\\n\")}`, {\n issues,\n });\n }\n\n const report = await gate(options, plan, maxParallel);\n const blocking = report.checks.filter((check) => !check.ok && check.severity === \"block\");\n if (blocking.length > 0 && override === undefined) {\n return text(\n `Not launching. The safety report has ${blocking.length} blocking failure(s):\\n` +\n `${blocking.map((check) => `- ${check.message}`).join(\"\\n\")}\\n` +\n \"Fix the plan, or pass `override` with the reason if the user has decided to go ahead anyway.\",\n report,\n );\n }\n\n const missionId = missionIdFor(goal);\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: options.repoRoot })).trim();\n options.ledger.appendAll([\n {\n type: \"mission.created\",\n missionId,\n goal,\n repo: { root: options.repoRoot, baseCommit: head },\n limits: { maxParallel, timeoutMinutes: Math.ceil(options.limits.timeoutMs / 60_000) },\n },\n { type: \"plan.proposed\", missionId, plan, by: \"lead\" },\n { type: \"safety.report\", missionId, planRevision: 1, ok: report.ok, checks: report.checks },\n ]);\n\n const handle = runner.launch({ missionId, plan, baseCommit: head, maxParallel });\n missions.set(missionId, handle);\n void handle.finished.then((outcome) => {\n options.ledger.append({\n type: \"mission.finished\",\n missionId,\n outcome: outcome.failed === 0 && outcome.dropped === 0 ? \"completed\" : \"aborted\",\n summary: `${outcome.done} done, ${outcome.failed} failed, ${outcome.dropped} dropped`,\n });\n });\n\n return text(\n `Mission ${missionId} is running ${plan.lines.length} line(s) from ${head.slice(0, 7)}` +\n `${override === undefined ? \"\" : `, with the safety report overridden: ${override}`}.`,\n { missionId, baseCommit: head, lines: plan.lines.map((line) => line.id) },\n );\n },\n );\n\n server.registerTool(\n \"mission_status\",\n {\n title: \"How a mission is going\",\n description:\n \"Every run of a mission: how long it has been going, which phase it reported, what it touched and how \" +\n \"it ended. A run still working that has said nothing for a while is marked quiet, which is the \" +\n \"difference between an agent thinking and an agent that has stopped.\",\n inputSchema: { missionId: z.string().min(1) },\n },\n ({ missionId }) => {\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n if (mission === undefined) return text(`No mission called ${missionId}.`, { missionId });\n\n return text(missionReport(mission, (options.now ?? (() => new Date()))()), { mission });\n },\n );\n\n server.registerTool(\n \"run_diff\",\n {\n title: \"What a run actually changed\",\n description:\n \"The diff read from the run's own workspace, not the agent's account of it, plus anything it wrote \" +\n \"outside its declared scope and the report it left.\",\n inputSchema: {\n missionId: z.string().min(1),\n runId: z.string().min(1),\n patch: z.boolean().default(false),\n },\n },\n async ({ missionId, runId, patch }) => {\n /*\n * Through `locate`, like every other tool here. This used to derive the path from the run id, which is the\n * one thing that is wrong for a reworked run: it continues in the worktree of the attempt before it. So the\n * diff was unreadable for exactly the runs a lead most needs to read \u2014 found by running a real mission and\n * being unable to see what came back. `locate` had already been fixed; this was a second copy of the rule.\n */\n const found = locate(missionId, runId);\n if (found === null) return text(`No run called ${runId} in ${missionId}.`, { missionId, runId });\n if (!found.exists) {\n return text(`The workspace for ${runId} is gone, so there is nothing left to read.`, { runId });\n }\n const { line, workspace } = found;\n\n const diff = await workspaces.collect(workspace, line);\n const reportPath = join(options.paths.runs, missionId, runId, \"report.md\");\n const report = existsSync(reportPath) ? readFileSync(reportPath, \"utf8\").slice(0, 20_000) : null;\n\n return text(\n `${runId}: ${diff.stat.files} file(s), +${diff.stat.insertions} \u2212${diff.stat.deletions}.` +\n (diff.outsideScope.length > 0 ? `\\nOutside its scope: ${diff.outsideScope.join(\", \")}` : \"\") +\n (report === null ? \"\" : `\\n\\nIts report:\\n${report}`),\n {\n stat: diff.stat,\n newFiles: diff.newFiles,\n outsideScope: diff.outsideScope,\n report,\n ...(patch ? { patch: diff.patch.slice(0, 200_000) } : {}),\n },\n );\n },\n );\n\n server.registerTool(\n \"cancel_mission\",\n {\n title: \"Stop a mission\",\n description: \"Stops every run still going and drops the lines that had not started, with the reason.\",\n inputSchema: { missionId: z.string().min(1), reason: z.string().min(1).max(500) },\n },\n async ({ missionId, reason }) => {\n const handle = missions.get(missionId);\n if (handle === undefined) return text(`Mission ${missionId} is not running here.`, { missionId });\n await handle.cancel(reason);\n return text(`Stopped ${missionId}: ${reason}`, { missionId });\n },\n );\n\n /*\n * The tool this whole product exists for.\n *\n * Most of the code in a Claude Code session is written by the lead and reviewed by the lead, and the lead's own\n * context \u2014 the plan, the reasoning, the justification \u2014 is exactly what hides its mistakes from it. A reader\n * holding only the diff is not smarter, it is differently placed. This is here rather than only in the terminal\n * because a check the lead has to remember to leave the session for is a check the lead will not run.\n */\n server.registerTool(\n \"check_claims\",\n {\n title: \"Have a second vendor try to disprove what you believe\",\n description:\n \"State what you believe about your own uncommitted changes; another vendor's CLI reads them cold, with \" +\n \"no knowledge of why you wrote them, and tries to falsify each claim. Run this before telling anyone \" +\n 'work is done. Write claims that could be proven false \u2014 \"it works\" cannot be checked, \"no caller of ' +\n 'total() passes fewer than two arguments\" can. A claim is only ever reported confirmed when the reader ' +\n \"said so explicitly: anything it skipped or garbled comes back unclear, never as a pass.\",\n inputSchema: {\n claims: z.array(z.string().trim().min(1).max(500)).min(1).max(10),\n },\n },\n async ({ claims }) => {\n const manifest = options.manifests.find((seat) => seat.capabilities.review !== null);\n if (manifest === undefined) {\n return text(\"No seat on this machine can read code it did not write.\", { ran: false });\n }\n\n const { event, refuted } = await checkClaims({\n repoRoot: options.repoRoot,\n claims,\n manifest,\n ...(options.execute === undefined ? {} : { execute: seatExecute(options.execute) }),\n });\n options.ledger.appendAll([event]);\n\n if (!event.ran) {\n // \"We could not ask\" must never read as \"nothing was refuted\".\n return text(\n `${manifest.displayName} did not check these claims: ${event.claims[0]?.evidence ?? \"unknown\"}`,\n { ran: false, claims: event.claims },\n );\n }\n\n const lines = event.claims.map(\n (claim) =>\n `${{ confirmed: \"\u2713\", refuted: \"\u2717\", unclear: \"?\" }[claim.verdict]} ${claim.claim}\\n ${claim.evidence}`,\n );\n const verdict =\n refuted.length > 0\n ? `\\n${String(refuted.length)} refuted. Fix these before saying the work is done.`\n : event.claims.some((claim) => claim.verdict === \"unclear\")\n ? \"\\nNothing refuted, but some claims could not be checked \u2014 that is not the same as fine.\"\n : \"\\nAll confirmed.\";\n\n return text(`${manifest.displayName} read your changes cold:\\n\\n${lines.join(\"\\n\")}\\n${verdict}`, {\n ran: true,\n refuted: refuted.length,\n claims: event.claims,\n });\n },\n );\n\n /*\n * The merge gate, as four tools the lead drives in order.\n *\n * They are deliberately separate. Each records the revision it judged, and `merge_run` refuses unless review,\n * checks, proof and approval all named the same one \u2014 so a single tool that \"reviewed and merged\" would be a\n * tool that could skip its own gate. Splitting them is what makes the refusal possible.\n */\n\n /** Finds a run and its worktree, or explains which part is missing. */\n const locate = (missionId: string, runId: string) => {\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n const run = mission?.runs[runId];\n const line = mission?.plan?.lines.find((entry) => entry.id === run?.lineId);\n /*\n * Where the run said it worked, falling back to the convention only for a run that never started. A reworked\n * run continues in the worktree of the attempt before it, so deriving the path from the run id finds nothing\n * for exactly the runs that most need finding.\n */\n if (mission === undefined || run === undefined || line === undefined) return null;\n const path = run.workdir ?? join(options.paths.workspaces, missionId, runId);\n return {\n run,\n line,\n workspace: {\n missionId,\n runId,\n kind: \"worktree\" as const,\n path,\n branch: `fanout/${missionId}/${runId}`,\n baseCommit: mission.repo.baseCommit,\n },\n exists: existsSync(path),\n };\n };\n\n const RUN = { missionId: z.string().min(1), runId: z.string().min(1) };\n\n server.registerTool(\n \"review_run\",\n {\n title: \"Record your verdict on a run's diff\",\n description:\n \"Records what you decided after reading the diff yourself with `run_diff`. Say what you actually \" +\n \"checked, not that it looks fine. `rework` sends it back; `reject` ends it. The verdict is tied to the \" +\n \"diff as it is right now, so if the work changes afterwards this review no longer counts for it.\",\n inputSchema: {\n ...RUN,\n verdict: z.enum([\"accept\", \"rework\", \"reject\"]),\n notes: z.string().trim().min(1).max(20_000),\n },\n },\n async ({ missionId, runId, verdict, notes }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to review.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n options.ledger.appendAll([\n { type: \"review.done\", missionId, runId, revision, verdict, notes, by: { id: \"claude\" } },\n ]);\n return text(\n `Recorded: ${verdict} for ${runId} (${String(diff.stat.files)} file(s) changed).` +\n (verdict === \"accept\" ? \" Next: run_checks.\" : \"\"),\n { revision, verdict },\n );\n },\n );\n\n server.registerTool(\n \"run_checks\",\n {\n title: \"Run the project's own checks against a run's work\",\n description:\n \"Runs the commands the plan declared for this line, in the run's worktree, and believes the exit codes. \" +\n \"The agent's own claim that its tests pass is not evidence: it was made by the only party with an \" +\n \"interest in the answer, inside a sandbox that could not run them properly. A line that declared no \" +\n \"checks is reported as unverified, never as passing.\",\n inputSchema: RUN,\n },\n async ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to check.`, { runId });\n\n // A worktree holds tracked files and nothing else, so the repository lends it node_modules for the length\n // of the check and takes them back afterwards.\n const result = await runChecks({\n cwd: found.workspace.path,\n repoRoot: options.repoRoot,\n commands: found.line.checks,\n });\n options.ledger.appendAll([\n {\n type: \"checks.done\",\n missionId,\n runId,\n revision: result.revision,\n ok: result.ok,\n summary: result.summary,\n commands: result.commands,\n },\n ]);\n const failing = result.outcomes.find((outcome) => outcome.exitCode !== 0);\n return text(\n `${result.ok ? \"\u2713\" : \"\u2717\"} ${result.summary}` +\n (failing === undefined ? \"\" : `\\n\\n${failing.command}:\\n${failing.tail}`),\n { ok: result.ok, revision: result.revision, outcomes: result.outcomes },\n );\n },\n );\n\n server.registerTool(\n \"prove_fix\",\n {\n title: \"Prove a bug fix by failing its test on the old code\",\n description:\n \"For a line the plan marked as a bug fix. Checks out the code as it was, copies only this run's tests \" +\n \"on top of it, and runs them: they must fail. A test that passes on the old code would have passed \" +\n \"before the fix, so it does not test what was broken. Required before such a line can merge.\",\n inputSchema: RUN,\n },\n async ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to prove.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n const result = await proveFix({\n repoRoot: options.repoRoot,\n workspacePath: found.workspace.path,\n baseCommit: found.workspace.baseCommit,\n touched: [...diff.newFiles, ...filesInPatch(diff.patch)],\n commands: found.line.checks,\n });\n\n options.ledger.appendAll([\n { type: \"proof.done\", missionId, runId, revision, ok: result.ok, failedOnOld: result.failedOnOld },\n ]);\n return text(`${result.ok ? \"\u2713 proven\" : \"\u2717 not proven\"}: ${result.why}`, {\n ok: result.ok,\n revision,\n tests: result.tests,\n });\n },\n );\n\n server.registerTool(\n \"rework_run\",\n {\n title: \"Send a diff back to the agent that wrote it\",\n description:\n \"Continues the conversation that produced this diff, with your review notes as the instruction, in the \" +\n \"same worktree. Use it after `review_run` with a `rework` verdict. This is worth far more than running \" +\n \"the line again: the agent still holds its own reasoning about the code, so a note about the header row \" +\n \"lands on someone who knows which header row. Two rounds, then decide instead of asking a third time.\",\n inputSchema: RUN,\n },\n ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to rework.`, { runId });\n\n const adapter = options.adapters.get(found.run.seat.id);\n if (adapter === undefined) {\n return text(`No adapter for ${found.run.seat.id} on this machine.`, { runId });\n }\n\n const outcome = reworkRun({\n ledger: options.ledger,\n adapter,\n missionId,\n line: found.line,\n run: found.run,\n workspacePath: found.workspace.path,\n runsRoot: options.paths.runs,\n limits: options.limits,\n });\n if (outcome.kind === \"refused\") return text(`Not reworked: ${outcome.why}`, { started: false });\n\n // Returns as soon as it is under way, like `launch`: watch it with mission_status.\n return text(\n `${outcome.runId} is picking the work back up where it left off. Watch it with mission_status.`,\n { started: true, runId: outcome.runId },\n );\n },\n );\n\n server.registerTool(\n \"merge_run\",\n {\n title: \"Merge a run's work into the repository\",\n description:\n \"The only tool that changes the user's repository, and it refuses unless review, checks, proof and the \" +\n \"user's approval all judged this exact diff. **Ask the user first, in the chat, and quote their answer \" +\n \"in `approvedBy`.** Applies with a three-way merge; a conflict is reported and rolled back, never \" +\n \"forced. Nothing is merged into a tree with uncommitted changes it would touch.\",\n inputSchema: {\n ...RUN,\n approvedBy: z\n .string()\n .trim()\n .min(1)\n .max(2000)\n .describe(\"What the user actually said when they approved this merge, in their own words.\"),\n allowOutsideScope: z\n .array(z.string().trim().min(1).max(400))\n .max(50)\n .optional()\n .describe(\n \"Paths this run wrote that its plan did not grant, which you have read and want anyway. The merge \" +\n \"refuses otherwise, and names them. Copy them from `run_diff`'s 'Outside its scope' line only \" +\n \"after looking at each one \u2014 they are recorded in the commit as Outside-scope.\",\n ),\n message: z\n .string()\n .trim()\n .min(1)\n .max(4000)\n .optional()\n .describe(\n \"The commit subject and body, in this repository's own convention \u2014 read docs/COMMITS.md or the \" +\n \"recent log before writing it. A project that enforces a format with a hook will refuse anything \" +\n \"else, and the gate will not bypass that hook. Trailers naming the seat and the approver are \" +\n \"added by the gate and are not yours to write.\",\n ),\n },\n },\n async ({ missionId, runId, approvedBy, message, allowOutsideScope }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to merge.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n\n /*\n * The approval is recorded before the attempt, so a replay shows the authority even when the merge then\n * hits a conflict. It is recorded as the user's because the user is who this tool asks the lead to ask.\n */\n options.ledger.appendAll([\n {\n type: \"merge.approved\",\n missionId,\n runId,\n revision,\n // Relayed, not direct: this is the lead's account of what the user said, and the ledger should say so.\n by: { kind: \"user\", via: \"relayed\" },\n note: approvedBy,\n },\n ]);\n\n const fresh = project(options.ledger.read({ missionId })).missions[missionId]?.runs[runId];\n if (fresh === undefined) return text(`${runId} vanished between reading and merging.`, { runId });\n\n const outcome = await mergeRun({\n repoRoot: options.repoRoot,\n workspacePath: found.workspace.path,\n run: fresh,\n line: found.line,\n revision,\n patch: diff.patch,\n newFiles: diff.newFiles,\n ...(allowOutsideScope === undefined ? {} : { allowOutsideScope }),\n ...(message === undefined ? {} : { message }),\n });\n\n if (outcome.kind === \"refused\") {\n return text(`Not merged:\\n${outcome.why.map((why) => `- ${why}`).join(\"\\n\")}`, { merged: false });\n }\n if (outcome.kind === \"conflict\") {\n options.ledger.appendAll([\n { type: \"merge.conflict\", missionId, runId, revision, files: outcome.files },\n ]);\n return text(\n `Conflict in ${outcome.files.join(\", \")}: ${outcome.why}. Your repository is untouched.`,\n { merged: false, files: outcome.files },\n );\n }\n\n options.ledger.appendAll([\n { type: \"merge.applied\", missionId, runId, revision, files: outcome.files, commit: outcome.commit },\n ]);\n return text(`Merged ${runId} as ${outcome.commit.slice(0, 7)}: ${outcome.files.join(\", \")}`, {\n merged: true,\n commit: outcome.commit,\n files: outcome.files,\n });\n },\n );\n\n return server;\n}\n\n/** The daemon's seat runner takes a working directory and a deadline; the injected test executor takes neither. */\nfunction seatExecute(execute: NonNullable<FanoutMcpOptions[\"execute\"]>) {\n return (binary: string, args: readonly string[]) => execute(binary, args);\n}\n\n/** Every tool answers twice: words for whoever is reading, and data for whatever is next. */\nfunction text(message: string, data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: message }],\n structuredContent: data as Record<string, unknown>,\n };\n}\n\nasync function gate(options: FanoutMcpOptions, plan: PlanGraph, maxParallel: number) {\n const seats = await detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: options.repoRoot })).trim();\n const commands = Object.fromEntries(\n plan.lines.flatMap((line) => {\n const adapter = options.adapters.get(line.seat.id);\n if (adapter === undefined) return [];\n return [\n [\n line.id,\n adapter.command({\n missionId: \"preview\",\n runId: `${line.id}-1`,\n line,\n workdir: join(options.paths.workspaces, \"preview\", line.id),\n reportPath: join(options.paths.runs, \"preview\", line.id, \"report.md\"),\n baseEnv: {},\n }),\n ],\n ];\n }),\n );\n\n return safetyReport(\n {\n plan,\n planRevision: 1,\n repo: { root: options.repoRoot, baseCommit: head },\n seats: Object.fromEntries(seats.map((seat) => [seat.id, seat])),\n commands,\n denyList: [],\n limits: { maxParallel, perSeat: {} },\n },\n createSafetyDependencies({ repoRoot: options.repoRoot }),\n );\n}\n\nasync function repoOverview(repoRoot: string) {\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: repoRoot })).trim();\n const dirty = splitLines(await git([\"status\", \"--porcelain\"], { cwd: repoRoot })).map((entry) =>\n entry.slice(3),\n );\n const files = zeroSeparated(await git([\"ls-files\", \"-z\"], { cwd: repoRoot }));\n\n const counts = new Map<string, number>();\n for (const file of files) {\n const area = file.includes(\"/\") ? `${file.slice(0, file.indexOf(\"/\"))}/` : \"(root)\";\n counts.set(area, (counts.get(area) ?? 0) + 1);\n }\n const areas = [...counts.entries()]\n .map(([path, count]) => ({ path, files: count }))\n .sort((a, b) => b.files - a.files)\n .slice(0, 12);\n\n return { head, dirty, files: files.length, areas, checks: projectChecks(repoRoot) };\n}\n\n/** The commands this project runs to know it is well, read from where they are declared. */\nfunction projectChecks(repoRoot: string): string[] {\n const manifest = join(repoRoot, \"package.json\");\n if (!existsSync(manifest)) return [];\n try {\n const parsed = JSON.parse(readFileSync(manifest, \"utf8\")) as { scripts?: Record<string, string> };\n return Object.keys(parsed.scripts ?? {})\n .filter((name) => [\"check\", \"test\", \"lint\", \"typecheck\", \"build\"].includes(name))\n .map((name) => `npm run ${name}`);\n } catch {\n return [];\n }\n}\n\nfunction missionIdFor(goal: string): string {\n const slug = goal\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 40);\n return `${slug === \"\" ? \"mission\" : slug}-${randomBytes(2).toString(\"hex\")}`;\n}\n", "import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { AdapterContext, ParseResult, SeatAdapter } from \"fanout-core\";\nimport { OutputLine } from \"./protocol.ts\";\nimport { Scenario, type ScenarioInput } from \"./scenario.ts\";\n\n/*\n * The fake seat: a deterministic simulated agent for the offline demo and for every test that needs an agent without\n * an account. It is a seat like any other: `command()` starts its CLI, `parse()` reads its stream.\n */\n\n/**\n * The simulated agent's own executable, wherever this module happens to be running from.\n *\n * Three places, and each one is a lesson rather than a configuration:\n *\n * 1. `fake-agent.js` beside us means we are inside the published bundle, where every workspace package has been\n * compiled into one file. `./cli.js` there is the *lead's* CLI \u2014 spawning it would make the demo run itself.\n * 2. `./cli.ts` is a checkout, where Node runs our TypeScript directly.\n * 3. `./cli.js` is the unbundled compiled layout.\n *\n * A path built as a string is the one import a compiler cannot rewrite, which is why this is worked out at\n * runtime: an earlier version wrote `./cli.ts` into `dist`, and all three demo agents died on the first spawn.\n */\nexport const FAKE_CLI_PATH = resolveFakeCli();\n\nfunction resolveFakeCli(): string {\n const bundled = fileURLToPath(new URL(\"./fake-agent.js\", import.meta.url));\n if (existsSync(bundled)) return bundled;\n return fileURLToPath(new URL(import.meta.url.endsWith(\".ts\") ? \"./cli.ts\" : \"./cli.js\", import.meta.url));\n}\n\nexport interface FakeAdapterOptions {\n /** The scenario a plan line plays. */\n scenarioFor: (line: AdapterContext[\"line\"]) => ScenarioInput;\n}\n\nexport function createFakeAdapter(options: FakeAdapterOptions): SeatAdapter {\n return {\n id: \"fake\",\n command: (context) => ({\n argv: [\n process.execPath,\n FAKE_CLI_PATH,\n \"--scenario-json\",\n JSON.stringify(Scenario.parse(options.scenarioFor(context.line))),\n \"--report\",\n context.reportPath,\n \"--\",\n context.line.prompt,\n ],\n cwd: context.workdir,\n env: { ...context.baseEnv },\n }),\n parse: parseLine,\n };\n}\n\n/** Maps one line of the fake agent's stdout. Never throws: anything unexpected is an `unparsed` signal. */\nexport function parseLine(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = OutputLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n switch (line.kind) {\n case \"phase\":\n return {\n events: [\n {\n type: \"run.progress\",\n ...run,\n phase: line.phase,\n ...(line.detail === undefined ? {} : { detail: line.detail }),\n },\n ],\n signals: [],\n };\n case \"tool\":\n return {\n events: [\n {\n type: \"run.tool\",\n ...run,\n tool: line.tool,\n ...(line.summary === undefined ? {} : { summary: line.summary }),\n files: line.files,\n },\n ],\n signals: [],\n };\n case \"usage\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.amount,\n unit: line.unit,\n estimated: false,\n },\n ],\n signals: [],\n };\n case \"limit\":\n return { events: [], signals: [{ kind: \"limit\", message: line.message }] };\n case \"sleep\":\n return { events: [], signals: [] };\n case \"report\":\n return { events: [], signals: [{ kind: \"report\", text: line.text }] };\n }\n}\n\nexport { EXIT, OutputLine } from \"./protocol.ts\";\nexport { Scenario, ScenarioStep, type ScenarioInput } from \"./scenario.ts\";\n", "import { RunProgress } from \"fanout-core\";\nimport { z } from \"zod\";\n\n/*\n * The fake agent's stdout: one JSON object per line. It stands in for a vendor CLI's stream, so the adapter parses it\n * the same way a real adapter parses Codex's or Kimi's output. The CLI writes it and the adapter reads it with this\n * one schema.\n */\nexport const OutputLine = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"phase\"),\n phase: RunProgress.shape.phase,\n detail: z.string().max(500).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"tool\"),\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n files: z.array(z.string().min(1).max(1000)).max(200),\n }),\n z.strictObject({ kind: z.literal(\"usage\"), amount: z.int().nonnegative(), unit: z.literal(\"messages\") }),\n z.strictObject({ kind: z.literal(\"limit\"), message: z.string().min(1).max(500) }),\n z.strictObject({ kind: z.literal(\"sleep\"), ms: z.int().nonnegative() }),\n z.strictObject({ kind: z.literal(\"report\"), text: z.string().max(20_000) }),\n]);\nexport type OutputLine = z.infer<typeof OutputLine>;\n\n/** Exit codes besides the scenario's own. */\nexport const EXIT = {\n /** A limit step was played: the simulated seat ran out of usage. */\n limit: 2,\n /** Bad arguments or an invalid scenario (EX_USAGE). */\n usage: 64,\n /** The scenario tried to write outside the working directory (EX_DATAERR). */\n unsafeWrite: 65,\n /** Anything unexpected (EX_SOFTWARE). */\n internal: 70,\n} as const;\n", "import { RunProgress } from \"fanout-core\";\nimport { z } from \"zod\";\n\n/*\n * What the fake agent does, step by step. Deterministic by design: no randomness, no clock in the output.\n * Example:\n * { \"steps\": [ { \"phase\": \"reading\", \"delayMs\": 300 },\n * { \"tool\": \"edit\", \"summary\": \"add csv writer\", \"write\": { \"src/api/csv.ts\": \"export \u2026\" } },\n * { \"usage\": 2 }, { \"limit\": \"usage limit reached\" } ],\n * \"report\": \"Added the endpoint.\", \"exitCode\": 0, \"timeScale\": 0.2 }\n */\n\nconst Delay = z.int().nonnegative().max(60_000).optional();\n\nconst PhaseStep = z.strictObject({\n phase: RunProgress.shape.phase,\n detail: z.string().max(500).optional(),\n delayMs: Delay,\n});\n\nconst ToolStep = z.strictObject({\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n /** Files to really write, relative to the working directory, with their content. */\n write: z.record(z.string().min(1).max(1000), z.string().max(1_000_000)).optional(),\n delayMs: Delay,\n});\n\nconst UsageStep = z.strictObject({ usage: z.int().nonnegative().max(1_000_000), delayMs: Delay });\n\n/** The seat runs out of usage: the agent prints the message, writes its report and exits with code 2. */\nconst LimitStep = z.strictObject({ limit: z.string().min(1).max(500), delayMs: Delay });\n\nconst SleepStep = z.strictObject({ sleep: z.int().nonnegative().max(60_000) });\n\nexport const ScenarioStep = z.union([PhaseStep, ToolStep, UsageStep, LimitStep, SleepStep]);\nexport type ScenarioStep = z.infer<typeof ScenarioStep>;\n\nexport const Scenario = z.strictObject({\n steps: z.array(ScenarioStep).max(1000),\n report: z.string().max(20_000),\n exitCode: z.int().min(0).max(255).default(0),\n /** Keep running after the last step, until killed (to exercise timeouts). */\n hang: z.boolean().default(false),\n /** Multiplies every delay: 0.2 plays five times faster (the demo), 0 plays instantly (tests). */\n timeScale: z.number().nonnegative().max(100).default(1),\n});\nexport type Scenario = z.infer<typeof Scenario>;\nexport type ScenarioInput = z.input<typeof Scenario>;\n", "import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/*\n * Everything Fanout keeps lives in one directory, and only there: the ledger, the token, run logs and workspaces.\n * `FANOUT_HOME` moves the lot, which is how tests get their own and how someone can keep it off a synced folder.\n */\n\nexport interface FanoutHome {\n root: string;\n ledger: string;\n token: string;\n workspaces: string;\n runs: string;\n}\n\nexport function fanoutHome(env: Readonly<Record<string, string | undefined>> = process.env): FanoutHome {\n const root = env[\"FANOUT_HOME\"] ?? join(env[\"HOME\"] ?? homedir(), \".fanout\");\n return {\n root,\n ledger: join(root, \"ledger.db\"),\n token: join(root, \"token\"),\n workspaces: join(root, \"workspaces\"),\n runs: join(root, \"runs\"),\n };\n}\n", "/*\n * A terminal that keeps up with the crew.\n *\n * `fanout demo` used to print a header, go silent for half a minute while three agents worked, and then drop a\n * table of run ids on the floor. Everything interesting happened somewhere the viewer could not see, and the\n * first impression of the product was a frozen screen.\n *\n * Two rules shape this file.\n *\n * **The agent is the subject.** A row says who is working and what they are doing right now, in the words the\n * agent used \u2014 `reading src/api/orders.ts`, not `api-1 \u00B7 fake \u00B7 \u25AA\u25AA\u25AB\u25AB`. Ids and phase glyphs are a debugging view\n * of a mission; they are not what a person wants to know while it runs.\n *\n * **A pipe is not a terminal.** Redrawing in place needs a TTY and a person watching. Piped into a file, a CI log\n * or `verify:pack`, the same render appends one line per real change instead \u2014 no escape codes, no rewritten\n * history, and every state a reader might grep for still shown exactly once.\n */\n\n/** One agent, as a person watching would describe it. */\nexport interface LiveRow {\n /** Who is working. The demo's simulated crew are Agent 1, 2, 3; a real mission names the seat. */\n who: string;\n /** What they were asked for, in the plan's own words. */\n task: string;\n /** What they are doing at this moment, from their own output. Empty while queued. */\n doing: string;\n /** Finished rows keep their result here instead of a live action. */\n result?: string;\n state: \"waiting\" | \"working\" | \"done\" | \"failed\";\n /** Milliseconds since the agent started, or null before it did. */\n elapsedMs: number | null;\n}\n\nconst FRAMES = [\"\u280B\", \"\u2819\", \"\u2839\", \"\u2838\", \"\u283C\", \"\u2834\", \"\u2826\", \"\u2827\", \"\u2807\", \"\u280F\"];\nconst MARK = { waiting: \"\u00B7\", working: \"\", done: \"\u2713\", failed: \"\u2717\" } as const;\n\n/* Dim and green only. A demo that reaches for six colours looks like a toy; restraint reads as confidence. */\nconst DIM = \"\u001B[2m\";\nconst GREEN = \"\u001B[32m\";\nconst RED = \"\u001B[31m\";\nconst RESET = \"\u001B[0m\";\nconst HIDE_CURSOR = \"\u001B[?25l\";\nconst SHOW_CURSOR = \"\u001B[?25h\";\n\nexport interface LiveOptions {\n write: (text: string) => void;\n /** False for a pipe or a CI log, where cursor movement is noise rather than motion. */\n tty: boolean;\n /** How wide the terminal is. Defaults to the real one, or 80 where nothing says. */\n columns?: number;\n}\n\n/**\n * Draws the crew, over and over, without the screen ever flickering or scrolling away.\n *\n * It redraws only the rows it printed last time, so anything already above \u2014 the goal, the header \u2014 stays put and\n * the block never scrolls. A row is written once and then rewritten in place, which is what makes a terminal feel\n * alive rather than chatty.\n */\nexport function createLive(options: LiveOptions) {\n const write = options.write;\n let printed = 0;\n let frame = 0;\n /** What each row last said, so a pipe can print a line only when something actually changed. */\n const said = new Map<string, string>();\n /** The widest each column has ever been, so it never narrows again mid-mission. */\n const widest = new Map<string, number>();\n let cursorHidden = false;\n\n const render = (rows: readonly LiveRow[]): void => {\n if (!options.tty) {\n for (const row of rows) {\n /*\n * The clock is deliberately not part of what counts as a change. Including it printed a line per agent\n * per second \u2014 a log where the interesting moments are buried under a stopwatch. What changed is the\n * state and the action; the time is just stamped on whichever line reports it.\n */\n const key = `${row.state}|${row.result ?? row.doing}`;\n if (said.get(row.who) === key) continue;\n said.set(row.who, key);\n write(`${plainLine(row)}\\n`);\n }\n return;\n }\n\n if (!cursorHidden) {\n write(HIDE_CURSOR);\n cursorHidden = true;\n }\n // Back to the top of the block we drew last time, so this frame replaces it rather than following it.\n if (printed > 0) write(`\u001B[${String(printed)}A`);\n\n /*\n * Column widths only ever grow.\n *\n * Measuring each frame afresh made the layout twitch: `shell npm run check` is wide, the `+8 \u22122` that\n * replaces it is narrow, and the clock jumped left the moment an agent finished. A table that rearranges\n * itself while you read it is the thing that makes a terminal feel cheap, and it costs a few trailing\n * spaces to hold still.\n */\n const widthOf = (key: string, pick: (row: LiveRow) => string): number => {\n const wanted = rows.reduce((wide, row) => Math.max(wide, pick(row).length), 0);\n const held = Math.max(widest.get(key) ?? 0, wanted);\n widest.set(key, held);\n return held;\n };\n const whoWidth = widthOf(\"who\", (row) => row.who);\n const taskWidth = widthOf(\"task\", (row) => row.task);\n /*\n * The action is the column that gives way when the terminal is narrow. A wrapped row breaks the redraw\n * outright \u2014 the cursor moves back by lines, not by rows, so one wrap leaves the block drawing over itself.\n * Truncating is the difference between a tight layout and a corrupted screen.\n */\n /*\n * `process.stdout.columns` is declared as a number and is genuinely `undefined` when stdout is not a\n * terminal \u2014 which is precisely when this code runs in CI. Read it as it really is; taking the declaration\n * at its word makes the budget `NaN` and every row collapses to the minimum.\n */\n const real = process.stdout.columns as number | undefined;\n const budget = (options.columns ?? real ?? 80) - (whoWidth + taskWidth + 16);\n const saidWidth = Math.max(\n 8,\n Math.min(\n widthOf(\"said\", (row) => row.result ?? row.doing),\n budget,\n ),\n );\n\n frame = (frame + 1) % FRAMES.length;\n for (const row of rows) {\n const spinner = row.state === \"working\" ? FRAMES[frame] : MARK[row.state];\n const colour = row.state === \"done\" ? GREEN : row.state === \"failed\" ? RED : \"\";\n const said = fit(row.result ?? row.doing, saidWidth);\n const time = row.elapsedMs === null ? \"\" : clock(row.elapsedMs);\n\n // `\u001B[K` clears to the end of the line: a shorter action must not leave the tail of a longer one.\n write(\n ` ${colour}${spinner}${RESET} ` +\n `${row.who.padEnd(whoWidth)} ` +\n `${row.task.padEnd(taskWidth)} ` +\n `${DIM}${said.padEnd(saidWidth)}${RESET}` +\n (time === \"\" ? \"\" : ` ${DIM}${time}${RESET}`) +\n `\u001B[K\\n`,\n );\n }\n printed = rows.length;\n };\n\n /** Gives the terminal back. A demo that leaves the cursor hidden has broken the shell it was showing off in. */\n const stop = (): void => {\n if (cursorHidden) {\n write(SHOW_CURSOR);\n cursorHidden = false;\n }\n };\n\n return { render, stop };\n}\n\n/** Shortened to fit, with an ellipsis so a reader knows something was cut rather than missing. */\nfunction fit(text: string, width: number): string {\n return text.length <= width ? text : `${text.slice(0, Math.max(1, width - 1))}\u2026`;\n}\n\n/** `0:04`, `1:12`, `11:30` \u2014 a clock, because that is how people read a stopwatch. */\nfunction clock(ms: number): string {\n const total = Math.max(0, Math.floor(ms / 1000));\n return `${String(Math.floor(total / 60))}:${String(total % 60).padStart(2, \"0\")}`;\n}\n\n/** One line for a log: no colour, no spinner, and only when something changed. */\nfunction plainLine(row: LiveRow): string {\n const said = row.result ?? row.doing;\n const time = row.elapsedMs === null ? \"\" : ` (${clock(row.elapsedMs)})`;\n return ` ${row.who} \u00B7 ${row.task} \u00B7 ${row.state}${said === \"\" ? \"\" : ` \u2014 ${said}`}${time}`;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { PlanLine } from \"fanout-core\";\nimport type { ScenarioInput } from \"fanout-adapter-fake\";\n\n/*\n * A whole mission, on a machine with no accounts on it.\n *\n * Everything here is the real thing except the thinking. Real git worktrees, the real safety gate, the real\n * append-only ledger, real diffs collected from real files \u2014 driven by the `fake` seat, which is a genuine CLI\n * speaking the genuine protocol and taking a script instead of a model. Nothing is stubbed out inside the daemon,\n * because a demo that exercised a special path would be a demo of something nobody ships.\n *\n * It is honest about the one thing it cannot do. A cold reader's verdicts need a real second vendor; the demo's\n * are written here, and every surface that shows them says `simulated` out loud. Faking the one claim the product\n * makes would be the single most dishonest thing this repository could contain.\n */\n\n/** A small repository worth changing: three areas, one seeded bug, one commit. */\nexport function buildDemoRepo(root: string): string {\n rmSync(root, { recursive: true, force: true });\n mkdirSync(join(root, \"src\", \"api\"), { recursive: true });\n mkdirSync(join(root, \"src\", \"ui\"), { recursive: true });\n mkdirSync(join(root, \"docs\"), { recursive: true });\n\n writeFileSync(\n join(root, \"src\", \"api\", \"orders.ts\"),\n \"export interface Order {\\n id: string;\\n total: number;\\n}\\n\\n\" +\n \"export function ordersFor(customer: string): Order[] {\\n return [];\\n}\\n\",\n );\n writeFileSync(\n join(root, \"src\", \"api\", \"dates.ts\"),\n \"/** Formats a day. Off by one in December: the bug this demo fixes. */\\n\" +\n \"export function monthOf(date: Date): number {\\n return date.getMonth();\\n}\\n\",\n );\n writeFileSync(join(root, \"src\", \"ui\", \"table.ts\"), \"export const columns = ['id', 'total'];\\n\");\n writeFileSync(join(root, \"docs\", \"orders.md\"), \"# Orders\\n\\nThe orders API.\\n\");\n writeFileSync(\n join(root, \"package.json\"),\n `${JSON.stringify({ name: \"demo-shop\", private: true, scripts: { check: \"echo ok\" } }, null, 2)}\\n`,\n );\n\n const git = (args: string[]): void => {\n execFileSync(\"git\", args, {\n cwd: root,\n stdio: \"ignore\",\n env: { PATH: process.env[\"PATH\"] ?? \"\", HOME: process.env[\"HOME\"] ?? \"\", GIT_CONFIG_NOSYSTEM: \"1\" },\n });\n };\n git([\"init\", \"--quiet\", \"-b\", \"main\"]);\n git([\"config\", \"user.email\", \"demo@example.invalid\"]);\n git([\"config\", \"user.name\", \"Fanout demo\"]);\n git([\"add\", \"-A\"]);\n git([\"commit\", \"--quiet\", \"-m\", \"the shop, before the crew arrives\"]);\n return root;\n}\n\nexport const DEMO_GOAL = \"Add CSV export and fix the December date bug\";\n\n/**\n * Three lines that touch three different areas.\n *\n * One of them is marked `fixesBug`, which is the flag the merge gate holds to the fourth non-negotiable: that\n * line cannot merge without a test proven to fail on the old code. The demo exists partly to show that refusal.\n */\nexport function demoLines(): PlanLine[] {\n return [\n {\n id: \"api\",\n title: \"CSV export endpoint\",\n role: \"builder\",\n prompt: \"Add GET /orders.csv, streaming rows and escaping quotes.\",\n seat: { id: \"fake\", model: \"demo\" },\n // Narrowed to the file it writes. `src/api/**` swallowed the dates line's scope, and the safety gate\n // refused the plan \u2014 on the product's own demo, which is the best argument for the check there is.\n scope: { write: [\"src/api/csv.ts\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: false,\n },\n {\n id: \"dates\",\n title: \"Fix the December month bug\",\n role: \"builder\",\n prompt: \"monthOf() is off by one in December. Fix it and prove it with a test.\",\n seat: { id: \"fake\", model: \"demo\" },\n scope: { write: [\"src/api/dates.ts\", \"src/api/dates.test.ts\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: true,\n },\n {\n id: \"ui\",\n title: \"Export button\",\n role: \"builder\",\n /*\n * The one line that asks for a seat this machine does not have. Nothing here fakes the consequence: the\n * demo's crew really is the simulated seat alone, so the router really does move this line and really does\n * say why \u2014 which is the behaviour worth showing, and the only honest way to show it offline.\n */\n prompt: \"Add the export column and a button that hits the new endpoint.\",\n seat: { id: \"codex\", model: \"gpt-5-codex\" },\n scope: { write: [\"src/ui/**\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: false,\n },\n ];\n}\n\n/**\n * What each simulated agent does, second by second.\n *\n * `timeScale` is the only dishonesty about time and it is the useful kind: a real run takes minutes and nobody\n * watches a demo for minutes. The phases, the tool calls and the files are what a real run of this shape does.\n */\nexport function demoScenario(line: PlanLine): ScenarioInput {\n const scenarios: Record<string, ScenarioInput> = {\n api: {\n steps: [\n { phase: \"reading\", delayMs: 900 },\n { tool: \"read\", summary: \"src/api/orders.ts\", delayMs: 700 },\n { phase: \"coding\", delayMs: 600 },\n {\n tool: \"edit\",\n summary: \"add the csv writer\",\n delayMs: 1400,\n write: {\n \"src/api/csv.ts\":\n \"import type { Order } from './orders.ts';\\n\\n\" +\n \"/** One row per order. A quote inside a field is doubled, per RFC 4180. */\\n\" +\n \"export function toCsv(orders: Order[]): string {\\n\" +\n \" const rows = orders.map((order) => `${quote(order.id)},${order.total}`);\\n\" +\n \" return ['id,total', ...rows].join('\\\\n');\\n}\\n\\n\" +\n \"function quote(value: string): string {\\n\" +\n \" return value.includes(',') || value.includes('\\\"')\\n\" +\n ' ? `\"${value.split(\\'\"\\').join(\\'\"\"\\')}\"`\\n : value;\\n}\\n',\n },\n },\n { phase: \"testing\", delayMs: 900 },\n { tool: \"shell\", summary: \"npm run check\", delayMs: 1100 },\n { usage: 3 },\n { phase: \"reporting\", delayMs: 400 },\n ],\n report: \"Added toCsv() with RFC 4180 quoting. Streaming is left for a follow-up.\",\n timeScale: 1,\n },\n dates: {\n steps: [\n { phase: \"reading\", delayMs: 800 },\n { phase: \"coding\", delayMs: 900 },\n {\n tool: \"edit\",\n summary: \"months are zero-based\",\n delayMs: 1200,\n write: {\n \"src/api/dates.ts\":\n \"/** Formats a day. getMonth() is zero-based, which is where December went wrong. */\\n\" +\n \"export function monthOf(date: Date): number {\\n return date.getMonth() + 1;\\n}\\n\",\n \"src/api/dates.test.ts\":\n \"import { monthOf } from './dates.ts';\\n\\n\" +\n \"// Fails on the old code: it returned 11 for December.\\n\" +\n \"test('December is the twelfth month', () => {\\n\" +\n \" expect(monthOf(new Date('2026-12-01'))).toBe(12);\\n});\\n\",\n },\n },\n { phase: \"testing\", delayMs: 1000 },\n { tool: \"shell\", summary: \"npm run check\", delayMs: 900 },\n { usage: 2 },\n { phase: \"reporting\", delayMs: 400 },\n ],\n report: \"monthOf() was zero-based. Fixed, with a test that fails on the old code.\",\n timeScale: 1,\n },\n ui: {\n steps: [\n { phase: \"reading\", delayMs: 1000 },\n { phase: \"coding\", delayMs: 1500 },\n {\n tool: \"edit\",\n summary: \"export column and button\",\n delayMs: 1600,\n write: {\n \"src/ui/table.ts\": \"export const columns = ['id', 'total', 'export'];\\n\",\n \"src/ui/export-button.ts\":\n \"export function exportButton(): string {\\n\" +\n \" return '<button data-href=\\\"/orders.csv\\\">Export CSV</button>';\\n}\\n\",\n },\n },\n { usage: 4 },\n { phase: \"reporting\", delayMs: 600 },\n ],\n report: \"Added the column and the button.\",\n timeScale: 1,\n },\n };\n\n const scenario = scenarios[line.id];\n if (scenario === undefined) throw new Error(`the demo has no script for line \"${line.id}\"`);\n return scenario;\n}\n\n/**\n * The claim check the demo shows, written here rather than asked of anyone.\n *\n * Marked `simulated` all the way through to the screen. A real check needs a real second vendor and a\n * subscription; inventing one and presenting it as read would be faking the single thing this product claims to\n * do, which is worse than having no demo at all.\n */\nexport function demoClaims(): {\n claim: string;\n verdict: \"confirmed\" | \"refuted\" | \"unclear\";\n evidence: string;\n}[] {\n return [\n {\n claim: \"The December fix comes with a test that fails on the old code\",\n verdict: \"confirmed\",\n evidence: \"dates.test.ts expects 12; the old monthOf returned 11 \u00B7 src/api/dates.ts:3\",\n },\n {\n claim: \"Nothing outside the three declared scopes was touched\",\n verdict: \"confirmed\",\n evidence: \"every changed path falls inside a declared write scope\",\n },\n {\n claim: \"toCsv escapes every field that needs it\",\n verdict: \"refuted\",\n evidence: \"a field containing a newline is not quoted \u00B7 src/api/csv.ts:10\",\n },\n ];\n}\n", "import {\n elapsedMs,\n EMPTY_POLICY,\n formatDuration,\n silentMs,\n stanceFor,\n type ProjectionState,\n type SeatInfo,\n type SeatPolicy,\n} from \"fanout-core\";\n\n/*\n * How the crew reads in a terminal. The rule everywhere: say what is known, say plainly what is not, and never let\n * an unknown look like a yes.\n */\n\nconst SIGN_IN: Record<SeatInfo[\"signedIn\"], string> = {\n yes: \"signed in\",\n no: \"not signed in\",\n unknown: \"unknown\",\n};\n\nexport function crewTable(seats: readonly SeatInfo[], policy: SeatPolicy = EMPTY_POLICY): string {\n if (seats.length === 0) return \"No agent CLIs found on this machine.\\n\";\n\n const rows = seats.map((seat) => ({\n name: seat.displayName,\n version: seat.version ?? \"not installed\",\n state: seat.supported ? SIGN_IN[seat.signedIn] : seat.version === null ? \"\u2014\" : \"unsupported version\",\n ready: stanceFor(seat, policy).usable,\n // \"normal\" is what a seat is when nobody has said anything, and printing it down every row would bury the\n // one or two the owner actually decided about.\n posture: stanceFor(seat, policy).posture === \"normal\" ? \"\" : stanceFor(seat, policy).posture,\n // Most CLIs do not report a tier. An empty column says that better than a word like \"unknown\" repeated\n // down the table, and the source travels with the value so nobody has to wonder who said it.\n plan: seat.plan === null ? \"\" : `${seat.plan.name} (${seat.plan.source})`,\n }));\n const width = {\n name: Math.max(...rows.map((row) => row.name.length)),\n version: Math.max(...rows.map((row) => row.version.length)),\n state: Math.max(...rows.map((row) => row.state.length)),\n plan: Math.max(...rows.map((row) => row.plan.length)),\n };\n\n const lines = rows.map((row) =>\n (\n ` ${row.ready ? \"\u2022\" : \" \"} ${row.name.padEnd(width.name)} ${row.version.padEnd(width.version)} ` +\n `${row.state.padEnd(width.state)} ${row.plan.padEnd(width.plan)} ${row.posture}`\n ).trimEnd(),\n );\n const ready = rows.filter((row) => row.ready).length;\n\n return `Crew on this machine (${ready} ready)\\n${lines.join(\"\\n\")}\\n`;\n}\n\nexport function missionLines(state: ProjectionState, now: Date = new Date()): string {\n const missions = Object.values(state.missions);\n if (missions.length === 0) return \"No missions yet.\\n\";\n\n const lines = missions.map((mission) => {\n const runs = Object.values(mission.runs);\n const running = runs.filter((run) => run.status === \"running\" || run.status === \"queued\").length;\n const merged = runs.filter((run) => run.status === \"merged\").length;\n const waiting = runs.filter((run) => run.status === \"done\" && run.review === null).length;\n // A mission where every working run has gone silent is the one worth walking back to the terminal for.\n const quiet = runs.filter((run) => (silentMs(run, now) ?? 0) >= 60_000).length;\n const longest = runs.reduce((most, run) => Math.max(most, elapsedMs(run, now) ?? 0), 0);\n const parts = [\n `${runs.length} run${runs.length === 1 ? \"\" : \"s\"}`,\n running > 0 ? `${running} running` : \"\",\n waiting > 0 ? `${waiting} waiting for review` : \"\",\n merged > 0 ? `${merged} merged` : \"\",\n longest > 0 ? formatDuration(longest) : \"\",\n quiet > 0 ? `${quiet} quiet` : \"\",\n ].filter((part) => part !== \"\");\n return ` ${mission.missionId.padEnd(16)} ${mission.status.padEnd(9)} ${parts.join(\" \u00B7 \")}`;\n });\n\n const anomalies =\n state.anomalies.length === 0\n ? \"\"\n : `\\n ${state.anomalies.length} event(s) did not fit the story and were kept as anomalies.\\n`;\n\n return `Missions\\n${lines.join(\"\\n\")}\\n${anomalies}`;\n}\n", "import { mergeReadiness, type ClaimCheck, type MissionView, type PlanLine, type RunView } from \"fanout-core\";\n\n/*\n * What is still owed, for the Stop hook.\n *\n * Everything else in Fanout is a tool the lead chooses to call, and that is the weakness: the failure mode is not\n * \"the gate said no\", it is \"nobody asked the gate\", or a lead that believes its own work is finished. A hook runs\n * whether or not anyone remembered it, which makes \"done\" a claim the session can check rather than one it asserts.\n *\n * It reports; it does not block. A hook that refused to let a session end would be a hostage-taker the first time\n * someone legitimately wanted to stop \u2014 and a person who wants to walk away from unfinished work is allowed to.\n * The point is that they do it knowingly.\n */\n\n/** What the lead's own uncommitted work still owes, if anything. */\nexport interface OwnWork {\n /** The revision the working tree is at now. */\n revision: string;\n files: number;\n /** The most recent claim check, if any, whatever revision it was about. */\n checked: ClaimCheck | undefined;\n}\n\n/**\n * What to say about the lead's own changes.\n *\n * The runs a crew produced are the obvious thing to guard, and they are not where most of a session's code comes\n * from: the lead writes it, and the lead is its only reader. A check nobody is reminded of is a check nobody runs,\n * which is why this asks about the working tree and not only about the mission.\n */\nexport function ownWorkOwed(work: OwnWork): string {\n if (work.files === 0) return \"\";\n\n const changed = `${String(work.files)} changed file${work.files === 1 ? \"\" : \"s\"}`;\n if (work.checked === undefined) {\n return ` ${changed}, and nobody but you has read them. Try: fanout check \"<something you believe>\"`;\n }\n if (work.checked.revision !== work.revision) {\n // A check of older bytes is not a check of these ones, and saying \"checked\" here would be the lie.\n return ` ${changed}, and they have moved since the last check. Run it again.`;\n }\n if (!work.checked.ran) {\n return ` ${changed}, and the last check could not run at all.`;\n }\n\n const refuted = work.checked.claims.filter((claim) => claim.verdict === \"refuted\");\n if (refuted.length > 0) {\n return [\n ` ${String(refuted.length)} of your own claims was refuted and is not fixed:`,\n ...refuted.map((claim) => ` \u2717 ${claim.claim}\\n ${claim.evidence}`),\n ].join(\"\\n\");\n }\n return \"\";\n}\n\nexport interface Owed {\n missionId: string;\n runId: string;\n /** One line, written for someone about to close their laptop. */\n what: string;\n}\n\n/**\n * Every run that is waiting on the lead: finished agents nobody has reviewed, checks nobody has run, fixes with\n * no proof, work reviewed at a revision that has since moved.\n *\n * Runs still working are deliberately not here. They are not owed by anyone; they are simply not done, and the\n * mission view says so already.\n */\nexport function whatIsOwed(missions: readonly MissionView[]): Owed[] {\n const owed: Owed[] = [];\n\n for (const mission of missions) {\n const lines = new Map<string, PlanLine>((mission.plan?.lines ?? []).map((line) => [line.id, line]));\n\n for (const runId of mission.runOrder) {\n const run = mission.runs[runId];\n if (run === undefined || !waitingOnTheLead(run)) continue;\n\n const line = lines.get(run.lineId);\n if (line === undefined) {\n owed.push({ missionId: mission.missionId, runId, what: \"finished, but its plan line is missing\" });\n continue;\n }\n\n /*\n * The run's own recorded revision is the best we can do from the ledger alone: a hook must not go and read\n * the worktree, because it runs on every turn and must stay fast. Asking readiness about the revision the\n * review saw answers \"is anything missing\", which is the hook's question \u2014 \"has the work moved since\" is\n * the merge tool's, and it recollects the diff to find out.\n */\n const judged = run.review?.revision ?? run.checks?.revision ?? run.approval?.revision ?? \"\";\n const { blockers } = mergeReadiness(run, line, judged);\n const first = blockers[0];\n if (first !== undefined) owed.push({ missionId: mission.missionId, runId, what: first.message });\n }\n }\n\n return owed;\n}\n\n/** A run the agent has finished with, that has not yet been merged, dropped or run into a conflict. */\nfunction waitingOnTheLead(run: RunView): boolean {\n return run.status === \"done\";\n}\n\n/** The hook's whole output. Empty string when nothing is owed, so a quiet session stays quiet. */\nexport function unfinishedReport(owed: readonly Owed[], own = \"\"): string {\n const parts: string[] = [];\n\n if (owed.length > 0) {\n const lines = owed.map((item) => ` ${item.missionId} \u00B7 ${item.runId}: ${item.what}`);\n const count = `${String(owed.length)} run${owed.length === 1 ? \"\" : \"s\"}`;\n parts.push(\n `${count} still waiting on you before anything can merge.\\n${lines.join(\"\\n\")}\\n` +\n `Nothing has been merged. Review them, or drop them on purpose.`,\n );\n }\n if (own !== \"\") parts.push(`Your own changes:\\n${own}`);\n\n return parts.length === 0 ? \"\" : `Fanout: ${parts.join(\"\\n\\n\")}\\n`;\n}\n", "#!/usr/bin/env node\nimport { main } from \"./main.ts\";\n\n/* The thin edge of the CLI: everything testable lives in main.ts, which takes its output as an argument. */\n\nconst code = await main(process.argv.slice(2), {\n out: (text) => process.stdout.write(text),\n err: (text) => process.stderr.write(text),\n});\nprocess.exitCode = code;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AA+BnB,SAAS,SAAiC;AAC/C,QAAM,OAAO,QAAQ,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IAAI,CAAC,CAAC;AAAA,GAAM;AAAA,IACvG,MAAM;AAAA,EACR,CAAC;AAED,QAAM,SAAS,mBAAmB;AAAA,IAChC;AAAA,IACA,UAAU,GAAG,OAAO,QAAQ,IAAI;AAAA,IAChC,OAAO,EAAE,MAAM,KAAK,MAAM,YAAY,KAAK,YAAY,MAAM,KAAK,KAAK;AAAA,IACvE,UAAU,SAAS;AAAA,IACnB,WAAW;AAAA,IACX,QAAQ;AAAA,EACV,CAAC;AAED,KAAG,IAAI,gCAAgC,IAAI,IAAI,QAAQ,QAAQ,IAAI,CAAC;AAAA,CAAoB;AACxF,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,SAAO,GAAG,SAAS,YAAY;AAE/B,QAAM,OAAO,MAAM;AACnB,QAAM,IAAI,MAAM;AAChB,SAAO,MAAM;AACb,SAAO;AACT;AAEA,SAAS,cAA6B;AACpC,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,UAAM,OAAO,MAAY;AACvB,cAAQ;AAAA,IACV;AACA,YAAQ,KAAK,UAAU,IAAI;AAC3B,YAAQ,KAAK,WAAW,IAAI;AAAA,EAC9B,CAAC;AACH;;;AwDhzBA,IAAM,OAAO,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EAC7C,KAAK,CAACa,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EACxC,KAAK,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAC1C,CAAC;AACD,QAAQ,WAAW;",
6
- "names": ["run", "existsSync", "realpathSync", "rmSync", "writeFileSync", "join", "z", "text", "z", "z", "lines", "z", "z", "check", "z", "z", "z", "z", "seat", "z", "z", "run", "mission", "message", "run", "mission", "count", "run", "code", "message", "seat", "text", "z", "text", "run", "command", "isAbsolute", "relative", "manifest_default", "z", "manifest", "manifest_default", "TEST_COMMAND", "text", "run", "repoRelative", "isAbsolute", "relative", "isAbsolute", "relative", "manifest_default", "z", "manifest", "manifest_default", "TEST_COMMAND", "WRITING", "text", "run", "command", "repoRelative", "isAbsolute", "relative", "closeSync", "openSync", "status", "text", "handle", "code", "mkdirSync", "dirname", "mkdirSync", "dirname", "handle", "execFile", "readFileSync", "promisify", "promisify", "execFile", "added", "readFileSync", "check", "message", "seat", "count", "status", "execFile", "promisify", "text", "run", "promisify", "execFile", "manifest", "text", "mkdirSync", "join", "run", "adapters", "status", "join", "mkdirSync", "chmodSync", "existsSync", "mkdirSync", "readFileSync", "dirname", "port", "mission", "run", "lines", "status", "text", "mkdirSync", "readFileSync", "writeFileSync", "dirname", "join", "join", "text", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "wanted", "run", "mkdirSync", "writeFileSync", "dirname", "isAbsolute", "join", "relative", "join", "relative", "isAbsolute", "run", "applyPatch", "writeFileSync", "mkdirSync", "dirname", "manifest", "text", "item", "count", "execFile", "code", "seat", "manifest", "fill", "firstLines", "describe", "item", "text", "count", "text", "readFileSync", "spawn", "existsSync", "mkdirSync", "readdirSync", "rmSync", "dirname", "join", "relative", "readdirSync", "join", "run", "command", "relative", "existsSync", "mkdirSync", "dirname", "rmSync", "spawn", "code", "count", "copyFileSync", "mkdirSync", "mkdtempSync", "rmSync", "tmpdir", "dirname", "join", "mkdtempSync", "join", "tmpdir", "mkdirSync", "dirname", "copyFileSync", "run", "rmSync", "copyFileSync", "existsSync", "mkdirSync", "dirname", "join", "join", "existsSync", "mkdirSync", "dirname", "copyFileSync", "describe", "run", "execFile", "gitEnv", "join", "run", "attempt", "join", "randomBytes", "existsSync", "readFileSync", "join", "z", "MissionLimits", "ready", "seat", "lines", "check", "handle", "mission", "join", "existsSync", "readFileSync", "manifest", "run", "message", "count", "randomBytes", "existsSync", "z", "z", "existsSync", "text", "run", "join", "wanted", "said", "text", "mkdirSync", "rmSync", "writeFileSync", "join", "git", "seat", "lines", "ready", "mission", "run", "owed", "mission", "lines", "run", "item", "count", "manifest", "command", "check", "run", "join", "rmSync", "handle", "mission", "existsSync", "ready", "count", "unclear", "seat", "ledger", "wanted", "realpathSync", "writeFileSync", "text"]
3
+ "sources": ["../../daemon/src/workspace/git.ts", "../src/quiet.ts", "../src/main.ts", "../../adapters/claude/src/index.ts", "../../core/src/schema/common.ts", "../../core/src/schema/scope.ts", "../../core/src/schema/plan.ts", "../../core/src/schema/events.ts", "../../core/src/schema/manifest.ts", "../../core/src/schema/policy.ts", "../../core/src/ledger/ledger.ts", "../../core/src/projections/state.ts", "../../core/src/format/run.ts", "../../core/src/gate/readiness.ts", "../../core/src/gate/routing.ts", "../../core/src/version.ts", "../../adapters/claude/manifest.json", "../../adapters/claude/src/protocol.ts", "../../adapters/codex/src/index.ts", "../../adapters/codex/manifest.json", "../../adapters/codex/src/protocol.ts", "../../adapters/grok/src/index.ts", "../../adapters/grok/manifest.json", "../../adapters/grok/src/protocol.ts", "../../daemon/src/supervisor/supervise.ts", "../../daemon/src/env.ts", "../../daemon/src/run.ts", "../../daemon/src/workspace/manager.ts", "../../daemon/src/workspace/deny.ts", "../../daemon/src/index.ts", "../../daemon/src/safety/report.ts", "../../daemon/src/safety/dependencies.ts", "../../daemon/src/detector/detect.ts", "../../daemon/src/detector/version.ts", "../../daemon/src/mission/runner.ts", "../../daemon/src/api/link.ts", "../../daemon/src/api/server.ts", "../../daemon/src/api/token.ts", "../../daemon/src/mission/reconcile.ts", "../../daemon/src/policy/seats.ts", "../../daemon/src/policy/route.ts", "../../daemon/src/gate/revision.ts", "../../daemon/src/gate/isolate.ts", "../../daemon/src/gate/run-seat.ts", "../../daemon/src/gate/buddy.ts", "../../daemon/src/gate/claims.ts", "../../daemon/src/api/view.ts", "../../daemon/src/gate/checks.ts", "../../daemon/src/gate/proof.ts", "../../daemon/src/gate/merge.ts", "../../daemon/src/gate/rework.ts", "../../mcp/src/server.ts", "../../adapters/fake/src/index.ts", "../../adapters/fake/src/protocol.ts", "../../adapters/fake/src/scenario.ts", "../src/home.ts", "../src/live.ts", "../src/demo.ts", "../src/format.ts", "../src/unfinished.ts", "../src/cli.ts"],
4
+ "sourcesContent": ["import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\n/*\n * Every git call the daemon makes. No shell, so a path can never become an argument list; a closed environment, so\n * git cannot prompt for credentials or pick up a helper we did not choose; and a timeout, so a hung git cannot hang\n * a mission.\n */\n\nconst run = promisify(execFile);\n\nexport class GitError extends Error {\n override name = \"GitError\";\n readonly args: readonly string[];\n readonly stderr: string;\n readonly exitCode: number | null;\n\n constructor(args: readonly string[], stderr: string, exitCode: number | null) {\n super(`git ${args.join(\" \")} failed${exitCode === null ? \"\" : ` (exit ${exitCode})`}: ${stderr.trim()}`);\n this.args = args;\n this.stderr = stderr;\n this.exitCode = exitCode;\n }\n}\n\nexport interface GitOptions {\n cwd: string;\n timeoutMs?: number;\n /** Diffs and file lists can be large; the default holds a very big patch. */\n maxBuffer?: number;\n}\n\nexport function gitEnv(): Record<string, string> {\n const path = process.env[\"PATH\"];\n const home = process.env[\"HOME\"];\n return {\n ...(path === undefined ? {} : { PATH: path }),\n ...(home === undefined ? {} : { HOME: home }),\n // Never ask a human, never touch a credential helper, never take a lock we don't need, and speak English so\n // that parsing never depends on the user's locale.\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_ASKPASS: \"\",\n GIT_OPTIONAL_LOCKS: \"0\",\n GIT_CONFIG_NOSYSTEM: \"1\",\n LC_ALL: \"C\",\n };\n}\n\nexport async function git(args: readonly string[], options: GitOptions): Promise<string> {\n try {\n const { stdout } = await run(\"git\", [...args], {\n cwd: options.cwd,\n timeout: options.timeoutMs ?? 60_000,\n maxBuffer: options.maxBuffer ?? 256 * 1024 * 1024,\n env: gitEnv(),\n windowsHide: true,\n });\n return stdout;\n } catch (cause) {\n const detail = cause as { stderr?: string; code?: number | null; message?: string };\n throw new GitError(args, detail.stderr ?? detail.message ?? \"\", detail.code ?? null);\n }\n}\n\n/** Lines of output, without the trailing empty one. */\nexport function lines(output: string): string[] {\n return output.split(\"\\n\").filter((line) => line !== \"\");\n}\n\n/** Entries of a `-z` listing, which is the only safe way to read paths that contain spaces or newlines. */\nexport function zeroSeparated(output: string): string[] {\n return output.split(\"\\0\").filter((entry) => entry !== \"\");\n}\n", "/*\n * Swallowing one warning, and only one.\n *\n * The ledger is Node's built-in SQLite, so every `fanout` command opened with two lines nobody asked for:\n *\n * (node:38137) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n * (Use `node --trace-warnings ...` to show where the warning was created)\n *\n * That is the first thing a person ever sees of this product, before a single word of our own, and it reads as\n * something going wrong. It is not news to them: the choice was ours, it is written down (ADR 0002), and the\n * minimum Node version in `engines` is the promise that it works. A warning the user can do nothing about, on\n * every invocation, is noise pretending to be information.\n *\n * Narrow on purpose. `process.removeAllListeners(\"warning\")` would have been one line and would have hidden\n * every future deprecation from us as well \u2014 the sort of silence that is discovered two majors late. This keeps\n * Node's own printer and gives it back everything except the one warning we already know about.\n *\n * Imported before anything else in `cli.ts`: ESM evaluates imports in order, and the warning fires the moment\n * `node:sqlite` is first loaded, which happens while the modules below are still being evaluated.\n */\n\nconst printers = process.listeners(\"warning\");\nprocess.removeAllListeners(\"warning\");\n\nprocess.on(\"warning\", (warning) => {\n const ours = warning.name === \"ExperimentalWarning\" && warning.message.includes(\"SQLite\");\n if (ours) return;\n for (const printer of printers) printer(warning);\n});\n", "import { existsSync, realpathSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createClaudeAdapter, manifest as claude } from \"fanout-adapter-claude\";\nimport { createCodexAdapter, manifest as codex } from \"fanout-adapter-codex\";\nimport { createGrokAdapter, manifest as grok } from \"fanout-adapter-grok\";\nimport {\n Ledger,\n elapsedMs,\n PlanGraph,\n project,\n SeatPosture,\n stanceFor,\n type AdapterManifest,\n type EventOf,\n type SeatAdapter,\n routeLine,\n versionOf,\n EMPTY_POLICY,\n type PlanLine,\n type RunView,\n type SeatInfo,\n type StoredEvent,\n} from \"fanout-core\";\nimport {\n detectSeats,\n git,\n lines,\n buddyReview,\n checkClaims,\n createMissionRunner,\n createWorkspaceManager,\n missionViewHtml,\n readOrCreateToken,\n reconcile,\n readSeatPolicy,\n setPosture,\n startApi,\n workSnapshot,\n writeSeatPolicy,\n type CommandResult,\n type RunLimits,\n} from \"fanout-daemon\";\nimport { createFanoutServer } from \"fanout-mcp\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { createFakeAdapter } from \"fanout-adapter-fake\";\nimport { fanoutHome, type FanoutHome } from \"./home.ts\";\nimport { createLive, type LiveRow } from \"./live.ts\";\nimport { buildDemoRepo, demoClaims, demoLines, demoScenario, DEMO_GOAL } from \"./demo.ts\";\nimport { crewTable, missionLines } from \"./format.ts\";\nimport { ownWorkOwed, unfinishedReport, whatIsOwed } from \"./unfinished.ts\";\n\n/*\n * `fanout` is the terminal half of the product: the daemon the lead talks to, and a straight answer about the crew\n * and the missions. It prints what it knows and says plainly what it doesn't \u2014 a CLI that guesses is worse than one\n * that shrugs.\n */\n\nexport const SEATS: readonly AdapterManifest[] = [codex, claude, grok];\n\n/** Every seat we can drive today. A plan naming anything else is dropped with the reason, never guessed at. */\nexport function adapters(): ReadonlyMap<string, SeatAdapter> {\n return new Map([\n [\"codex\", createCodexAdapter()],\n [\"claude\", createClaudeAdapter()],\n [\"grok\", createGrokAdapter()],\n ]);\n}\n\n/** What a run is allowed before the supervisor stops it. Generous: a real agent thinks for minutes. */\nexport const DEFAULT_LIMITS: RunLimits = {\n startTimeoutMs: 90_000,\n timeoutMs: 30 * 60_000,\n killGraceMs: 5_000,\n maxLogBytes: 16 * 1024 * 1024,\n maxLineBytes: 200_000,\n};\n\nconst HELP = `fanout \u2014 Claude Code leads, your other agents build\n\n fanout demo watch a whole mission run, offline, with no accounts at all (--once to exit at the end)\n fanout status the crew on this machine, and any missions on the go\n fanout seat how freely to spend a seat: preferred | normal | sparing | off\n fanout owed what is waiting on you before anything can merge (the Stop hook runs this)\n fanout review ask a second vendor to read your own uncommitted changes\n fanout check state what you believe; a cold reader tries to disprove each claim\n fanout daemon run the daemon the lead and the mission view talk to\n fanout clean remove the worktrees and branches finished missions left behind\n fanout mcp speak MCP on stdin/stdout, for Claude Code to drive (the plugin runs this)\n fanout version what you are running\n fanout help this\n\nEverything lives in ~/.fanout (move it with FANOUT_HOME). Nothing leaves your machine.\n`;\n\nexport interface Io {\n out: (text: string) => void;\n err: (text: string) => void;\n /** Injected so tests never need the real CLIs installed. */\n execute?: (binary: string, args: readonly string[]) => Promise<CommandResult>;\n env?: Readonly<Record<string, string | undefined>>;\n /** Resolves when the daemon should stop; without it, `daemon` runs until interrupted. */\n until?: Promise<void>;\n /** Where the command was run; tests point it at a temporary repository. */\n cwd?: string;\n /**\n * Whether `out` is going to a terminal a person is watching.\n *\n * Injected rather than read from `process.stdout` here so a test can render both ways, and so a pipe never\n * gets cursor-movement codes it would print as garbage.\n */\n tty?: boolean;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const [command = \"help\"] = argv;\n const home = fanoutHome(io.env ?? process.env);\n\n switch (command) {\n case \"demo\":\n return demo(home, io, argv.slice(1));\n case \"status\":\n return status(home, io);\n case \"seat\":\n return seat(home, argv.slice(1), io);\n case \"owed\":\n return owed(home, io);\n case \"review\":\n return buddy(home, io);\n case \"check\":\n return check(home, argv.slice(1), io);\n case \"daemon\":\n return daemon(home, io);\n case \"clean\":\n return clean(home, io);\n case \"mcp\":\n return mcp(home, io);\n case \"version\":\n io.out(`fanout ${versionOf(import.meta.url)}\\n`);\n return 0;\n case \"help\":\n case \"--help\":\n case \"-h\":\n io.out(HELP);\n return 0;\n default:\n io.err(`fanout: there is no \"${command}\" command.\\n\\n${HELP}`);\n return 64;\n }\n}\n\n/**\n * A path with the home directory written as `~`.\n *\n * The demo is the thing people record and paste into issues, and an absolute path puts their account name in\n * every frame of it. `~` is also simply how a person would say it.\n */\nfunction tilde(path: string, io: Io): string {\n const home = (io.env ?? process.env)[\"HOME\"] ?? \"\";\n return home !== \"\" && path.startsWith(home) ? `~${path.slice(home.length)}` : path;\n}\n\n/**\n * One agent, described the way someone watching would describe it.\n *\n * `doing` is the agent's own last words \u2014 the file it opened, the edit it made, the command it ran \u2014 because a\n * phase name (\"coding\") says less than the thing being coded. When it has nothing to say yet, the phase is the\n * honest fallback rather than an invented action.\n */\nfunction demoRow(run: RunView, line: PlanLine, who: string, now: Date): LiveRow {\n const elapsed = elapsedMs(run, now);\n const finished = run.status === \"done\";\n const failed = run.status === \"failed\" || run.status === \"killed\" || run.status === \"timeout\";\n\n const doing =\n run.lastTool === null\n ? (run.phase ?? \"starting up\")\n : run.lastTool.summary === null\n ? run.lastTool.tool\n : `${run.lastTool.tool} ${run.lastTool.summary}`;\n\n const stat = run.diffStat;\n const result =\n stat === null\n ? run.files.length === 0\n ? \"no changes\"\n : `${String(run.files.length)} file${run.files.length === 1 ? \"\" : \"s\"}`\n : `+${String(stat.insertions)} \u2212${String(stat.deletions)}`;\n\n return {\n who,\n task: line.title,\n doing,\n ...(finished || failed ? { result } : {}),\n state: failed ? \"failed\" : finished ? \"done\" : run.status === \"queued\" ? \"waiting\" : \"working\",\n elapsedMs: elapsed,\n };\n}\n\n/**\n * The demo's crew: the simulated seat, said plainly, and nothing else.\n *\n * One list, used both by the page that shows the crew and by the router that decides on it. Two copies would let\n * the screen say one thing while the routing did another, which on this particular screen is the whole product.\n *\n * Reporting the machine's real CLIs here would make the demo look like it was using them, and reporting nothing\n * makes a working demo look broken.\n */\nconst DEMO_CREW: readonly SeatInfo[] = [\n {\n id: \"fake\",\n displayName: \"Simulated agent\",\n binary: \"fake\",\n version: \"demo\",\n supported: true,\n signedIn: \"yes\",\n models: [\"demo\"],\n efforts: [],\n billing: \"unknown\",\n plan: { name: \"no account needed\", source: \"detected\" },\n },\n];\n\n/**\n * `fanout demo` \u2014 the whole thing, on a machine with nothing signed in.\n *\n * Real worktrees, the real safety gate, the real ledger, real diffs from real files. Only the agents are\n * simulated, by the `fake` seat: a genuine CLI speaking the genuine protocol from a script. Nothing inside the\n * daemon takes a special path, because a demo of a special path is a demo of something nobody ships.\n */\nasync function demo(home: FanoutHome, io: Io, argv: readonly string[] = []): Promise<number> {\n const root = join(home.root, \"demo\");\n const repo = buildDemoRepo(join(root, \"shop\"));\n const ledgerPath = join(root, \"ledger.db\");\n rmSync(ledgerPath, { force: true });\n\n // The feed exists only once the API is listening, and the ledger is open before that; this holder is the join.\n const feed: { publish?: (event: StoredEvent) => void } = {};\n const ledger = Ledger.open(ledgerPath, {\n onAppend: (event) => {\n feed.publish?.(event);\n },\n });\n const adapter = createFakeAdapter({ scenarioFor: demoScenario });\n const workspaces = createWorkspaceManager({ repoRoot: repo, workspaceRoot: join(root, \"workspaces\") });\n const runner = createMissionRunner({\n ledger,\n workspaces,\n adapters: new Map([[\"fake\", adapter]]),\n runsRoot: join(root, \"runs\"),\n limits: DEFAULT_LIMITS,\n /*\n * The real router, over the demo's real crew \u2014 which is the simulated seat and nothing else. The `ui` line\n * asks for Codex, so it is moved and the reason on screen is the router's own sentence rather than a caption\n * we wrote. A demo that faked this would be demonstrating a code path nobody ships.\n */\n route: (line) =>\n routeLine({\n wanted: line.seat.id,\n seats: DEMO_CREW,\n policy: EMPTY_POLICY,\n headroom: {},\n now: new Date(),\n }),\n });\n\n const api = await startApi({\n ledger,\n token: readOrCreateToken(home.token),\n view: missionViewHtml,\n /*\n * The demo's crew is the simulated seat, said plainly. Reporting the machine's real CLIs here would make the\n * demo look like it was using them, and reporting nothing makes a working demo look broken.\n */\n crew: () => Promise.resolve(DEMO_CREW),\n });\n feed.publish = (event) => {\n api.publish(event);\n };\n\n const plan = PlanGraph.parse({ lines: demoLines() });\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: repo })).trim();\n const missionId = \"demo-csv-export\";\n ledger.appendAll([\n {\n type: \"mission.created\",\n missionId,\n goal: DEMO_GOAL,\n repo: { root: repo, baseCommit: head },\n limits: { maxParallel: 3, timeoutMinutes: 10 },\n },\n { type: \"plan.proposed\", missionId, plan, by: \"lead\" },\n ]);\n\n /*\n * The opening. Short, because nobody reads a paragraph before the thing they ran starts moving, and the crew\n * below is the actual answer to \"what is this\".\n */\n io.out(`\\n \\u001B[1mFanout\\u001B[0m \\u001B[2m\u00B7 a crew of coding agents, led by Claude Code\\u001B[0m\\n\\n`);\n io.out(` \\u001B[2mGoal\\u001B[0m ${DEMO_GOAL}\\n`);\n io.out(` \\u001B[2mCrew\\u001B[0m 3 simulated agents \u2014 nothing to sign into, nothing to pay for\\n`);\n io.out(` \\u001B[2mRepo\\u001B[0m ${tilde(repo, io)} \\u001B[2m(throwaway)\\u001B[0m\\n\\n`);\n\n const handle = runner.launch({ missionId, plan, baseCommit: head, maxParallel: 3 });\n\n /*\n * The crew, live. Each line of the plan is one agent, named the way a person would name them, and the mission\n * is watched through the same projection every other surface reads \u2014 so this can never show a state the\n * mission view and the ledger disagree with.\n */\n const names = new Map(plan.lines.map((line, index) => [line.id, `Agent ${String(index + 1)}`]));\n const live = createLive({\n write: io.out,\n tty: io.tty ?? process.stdout.isTTY,\n });\n const draw = (): void => {\n const current = project(ledger.read({ missionId })).missions[missionId];\n if (current === undefined) return;\n live.render(\n current.runOrder.flatMap((runId) => {\n const run = current.runs[runId];\n const line = plan.lines.find((entry) => entry.id === run?.lineId);\n if (run === undefined || line === undefined) return [];\n return [demoRow(run, line, names.get(line.id) ?? run.seat.id, new Date())];\n }),\n );\n };\n\n const ticking = setInterval(draw, 90);\n try {\n await handle.finished;\n } finally {\n clearInterval(ticking);\n draw();\n live.stop();\n }\n\n /*\n * The claim check the demo shows is written, not read: real verdicts need a real second vendor. It is recorded\n * with `simulated: true` so every surface says so, because inventing a second opinion and presenting it as one\n * would fake the only thing this product claims to do.\n */\n ledger.appendAll([\n {\n type: \"claims.checked\",\n repoRoot: repo,\n revision: \"d3\".repeat(32),\n by: { id: \"fake\", model: \"demo\" },\n claims: demoClaims(),\n ran: true,\n simulated: true,\n },\n ]);\n\n /*\n * The ending, which the demo never had. Three diffs arrive and none of them merge, and that is the product\n * rather than a shortcoming \u2014 so it is said plainly instead of being left for the viewer to notice.\n */\n const state = project(ledger.read({ missionId }));\n const mission = state.missions[missionId];\n if (mission !== undefined) {\n const runs = mission.runOrder.flatMap((id) => (mission.runs[id] === undefined ? [] : [mission.runs[id]]));\n const written = runs.reduce((total, run) => total + (run.diffStat?.insertions ?? 0), 0);\n const refuted = demoClaims().filter((claim) => claim.verdict === \"refuted\").length;\n\n io.out(`\\n \\u001B[2m${\"\u2500\".repeat(62)}\\u001B[0m\\n\\n`);\n io.out(\n ` ${String(runs.length)} agents wrote ${String(written)} lines, each in its own worktree. ` +\n `\\u001B[1mNone of it is merged.\\u001B[0m\\n\\n`,\n );\n io.out(` \\u001B[2mThat is the point. Before anything reaches your branch:\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 a reader who did not write it reviews the diff\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 your own checks run against that exact revision\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 a bug fix ships with a test proven to fail on the old code\\u001B[0m\\n`);\n io.out(` \\u001B[2m \u00B7 and you say yes\\u001B[0m\\n\\n`);\n if (refuted > 0) {\n io.out(\n ` A second agent read the work cold and \\u001B[1mrefuted ${String(refuted)} of their claims\\u001B[0m.\\n` +\n ` \\u001B[2mSimulated here; real the moment you have a second CLI signed in.\\u001B[0m\\n\\n`,\n );\n }\n io.out(` \\u001B[2mThe whole run, diff by diff:\\u001B[0m ${api.url}/\\n`);\n }\n /*\n * `--once` exits when the mission does, instead of holding the view open. It is what a script wants: the\n * packaging check runs this to prove an installed Fanout actually works, and a command that never returns\n * cannot be checked by anything.\n */\n if (argv.includes(\"--once\")) {\n await api.close();\n ledger.close();\n return 0;\n }\n\n io.out(` \\u001B[2mStill watching \u2014 Ctrl-C when you have seen enough.\\u001B[0m\\n`);\n\n await (io.until ?? new Promise<void>(() => undefined));\n await api.close();\n ledger.close();\n return 0;\n}\n\n/** The repository a command was run in, or undefined outside one \u2014 which is not an error, just less context. */\nasync function repoRootOf(cwd: string): Promise<string | undefined> {\n try {\n return (await git([\"rev-parse\", \"--show-toplevel\"], { cwd })).trim();\n } catch {\n return undefined;\n }\n}\n\nasync function status(home: FanoutHome, io: Io): Promise<number> {\n const seats = await detectSeats({\n manifests: SEATS,\n ...(io.execute === undefined ? {} : { execute: io.execute }),\n });\n const { policy, problem } = readSeatPolicy(home.root);\n // A policy we could not read is not the same as no policy, and the difference is whose money it is.\n if (problem !== null)\n io.err(`fanout: ${problem}\\n Until it is fixed, every seat falls back to its default.\\n\\n`);\n io.out(crewTable(seats, policy));\n\n if (!existsSync(home.ledger)) {\n io.out(\"\\nNo missions yet. The ledger appears the first time the lead plans one.\\n\");\n return 0;\n }\n\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n /*\n * Scoped to the repository the person is standing in. The ledger is one file for the whole machine, and\n * without this `fanout status` in your own project lists work from every other project on it.\n */\n const here = await repoRootOf(io.cwd ?? process.cwd());\n io.out(`\\n${missionLines(state, new Date(), here)}`);\n } finally {\n ledger.close();\n }\n return 0;\n}\n\n/**\n * `fanout check` \u2014 the lead writes down what it believes; a cold reader tries to disprove each claim.\n *\n * Sharper and far cheaper than a broad review, because the value was never the volume of reading. The lead\n * carries the plan and the reasoning, and that is exactly what hides its mistakes from it; a reader with only the\n * diff is not smarter, it is differently placed. Three specific claims buy that difference for almost nothing.\n *\n * Exits non-zero when a claim is refuted, so this can sit in a script or a hook.\n */\nasync function check(home: FanoutHome, claims: readonly string[], io: Io): Promise<number> {\n if (claims.length === 0) {\n io.err(`fanout: check needs something to check.\\n\\n${CHECK_HELP}`);\n return 64;\n }\n\n const ready = await reviewerFor(home, io);\n if (typeof ready === \"number\") return ready;\n\n const { event, refuted } = await checkClaims({\n repoRoot: io.cwd ?? process.cwd(),\n claims,\n manifest: ready.manifest,\n ...(io.execute === undefined ? {} : { execute: reviewWith(io.execute) }),\n });\n\n const ledger = Ledger.open(home.ledger);\n try {\n ledger.appendAll([event]);\n } finally {\n ledger.close();\n }\n\n if (!event.ran) {\n // Never let \"we could not ask\" read as \"nothing was refuted\".\n io.err(\n `fanout: ${ready.manifest.displayName} did not check your claims.\\n ${event.claims[0]?.evidence ?? \"\"}\\n`,\n );\n return 69;\n }\n\n const mark = { confirmed: \"\u2713\", refuted: \"\u2717\", unclear: \"?\" } as const;\n io.out(`${ready.manifest.displayName} read your changes cold:\\n\\n`);\n for (const claim of event.claims) {\n io.out(` ${mark[claim.verdict]} ${claim.claim}\\n ${claim.evidence}\\n`);\n }\n io.out(`\\n${summarise(event.claims)}\\n`);\n\n // A refuted claim is the only outcome worth interrupting someone for.\n return refuted.length > 0 ? 1 : 0;\n}\n\nfunction summarise(claims: EventOf<\"claims.checked\">[\"claims\"]): string {\n const count = (verdict: string): number => claims.filter((claim) => claim.verdict === verdict).length;\n const refuted = count(\"refuted\");\n const unclear = count(\"unclear\");\n if (refuted > 0) return `${String(refuted)} refuted. Nothing here is settled until those are.`;\n if (unclear > 0)\n return `Nothing refuted, but ${String(unclear)} could not be checked \u2014 that is not the same as fine.`;\n return \"All confirmed.\";\n}\n\nconst CHECK_HELP = ` fanout check \"<claim>\" [\"<claim>\" ...]\n\n Write claims a reader could disprove. \"It works\" cannot be checked; \"no caller of\n total() passes fewer than two arguments\" can.\n`;\n\n/**\n * `fanout review` \u2014 a second vendor reads the lead's own uncommitted work.\n *\n * The one command that earns its keep in a session where no agent ran at all. Most of the code in a Claude Code\n * session is written by the lead and reviewed by the lead, which is how a confident mistake ships; this is the\n * call that breaks that loop. The findings are printed verbatim, because a second opinion summarised by the\n * author it is about is not a second opinion.\n */\nasync function buddy(home: FanoutHome, io: Io): Promise<number> {\n const ready = await reviewerFor(home, io);\n if (typeof ready === \"number\") return ready;\n\n const { snapshot, event } = await buddyReview({\n repoRoot: io.cwd ?? process.cwd(),\n manifest: ready.manifest,\n ...(io.execute === undefined ? {} : { execute: reviewWith(io.execute) }),\n });\n\n const ledger = Ledger.open(home.ledger);\n try {\n ledger.appendAll([event]);\n } finally {\n ledger.close();\n }\n\n if (snapshot.clean) {\n io.out(\"Nothing uncommitted to review.\\n\");\n return 0;\n }\n if (!event.ran) {\n // Never let \"the reviewer broke\" read as \"the reviewer found nothing\".\n io.err(`fanout: ${ready.manifest.displayName} could not review your changes.\\n ${event.findings}\\n`);\n return 69;\n }\n\n const files = `${String(snapshot.files.length)} file${snapshot.files.length === 1 ? \"\" : \"s\"}`;\n io.out(\n event.findings.trim() === \"\"\n ? `${ready.manifest.displayName} read ${files} and had nothing to say.\\n`\n : `${ready.manifest.displayName} read ${files}:\\n\\n${event.findings.trim()}\\n`,\n );\n return 0;\n}\n\n/**\n * The seat that will read your work, or the exit code explaining why nobody will.\n *\n * Every check here is about not spending someone's subscription behind their back \u2014 a posture they set, a version\n * this adapter was never verified against, a policy file we could not read. Shared by both readers so that the\n * next one cannot forget any of them, which is exactly how `fanout review` shipped ignoring the seat policy.\n */\nasync function reviewerFor(home: FanoutHome, io: Io): Promise<{ manifest: AdapterManifest } | number> {\n const manifest = SEATS.find((seat) => seat.id === \"codex\");\n if (manifest?.capabilities.review == null) {\n io.err(\"fanout: no seat on this machine has a non-interactive review command.\\n\");\n return 69;\n }\n\n const { policy, problem } = readSeatPolicy(home.root);\n if (problem !== null) {\n io.err(`fanout: ${problem}\\n Fix or delete that file before spending a seat.\\n`);\n return 65;\n }\n\n const [detected] = await detectSeats({\n manifests: [manifest],\n ...(io.execute === undefined ? {} : { execute: io.execute }),\n });\n if (detected === undefined) {\n io.err(\"fanout: could not detect the reviewing seat.\\n\");\n return 69;\n }\n\n const stance = stanceFor(detected, policy);\n if (stance.posture === \"off\") {\n io.err(`fanout: ${manifest.displayName} is off (${stance.reason}). Turn it on with:\\n`);\n io.err(` fanout seat ${manifest.id} normal\\n`);\n return 69;\n }\n if (!detected.supported) {\n // An unverified build would be driven with flags we have not confirmed and read as a stream we have not seen.\n io.err(\n `fanout: ${manifest.displayName} ${detected.version ?? \"is not installed\"} is outside the versions this ` +\n `adapter was verified against (${manifest.supportedVersions}).\\n`,\n );\n return 69;\n }\n if (detected.signedIn !== \"yes\") {\n io.err(\n `fanout: ${manifest.displayName} is ${detected.signedIn === \"no\" ? \"not signed in\" : \"unknown\"}.\\n`,\n );\n return 69;\n }\n if (stance.posture === \"sparing\") {\n // Sparing means \"only when nothing else fits, and say so first\". This is the saying so.\n io.out(\n `Using ${manifest.displayName}, which you marked sparing${stance.note === undefined ? \"\" : ` \u2014 ${stance.note}`}.\\n`,\n );\n }\n return { manifest };\n}\n\n/** The CLI's injected executor takes no options; the buddy's takes cwd and a deadline. Bridge them for tests. */\nfunction reviewWith(\n execute: NonNullable<Io[\"execute\"]>,\n): (binary: string, args: readonly string[]) => Promise<CommandResult> {\n return (binary, args) => execute(binary, args);\n}\n\n/**\n * `fanout owed` \u2014 what the lead still owes before anything can merge.\n *\n * Run by the Stop hook on every turn, which is the point: a tool the lead chooses to call cannot catch a lead who\n * believes the work is already finished. Prints nothing and exits 0 when there is nothing owed, so a quiet session\n * stays quiet, and it never blocks \u2014 walking away from unfinished work is allowed, doing it unknowingly is not.\n */\nasync function owed(home: FanoutHome, io: Io): Promise<number> {\n const repoRoot = io.cwd ?? process.cwd();\n\n // The working tree is asked about first, because that is where the lead's own unread code lives.\n let own = \"\";\n try {\n const snapshot = await workSnapshot({ cwd: repoRoot });\n if (!existsSync(home.ledger)) {\n own = ownWorkOwed({ revision: snapshot.revision, files: snapshot.files.length, checked: undefined });\n } else {\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n own = ownWorkOwed({\n revision: snapshot.revision,\n files: snapshot.files.length,\n checked: state.claims[snapshot.repoRoot],\n });\n } finally {\n ledger.close();\n }\n }\n } catch {\n // Not a repository, or git is unhappy. A hook that runs every turn must never be the reason a turn fails.\n }\n\n if (!existsSync(home.ledger)) {\n if (own !== \"\") io.out(unfinishedReport([], own));\n return 0;\n }\n\n const ledger = Ledger.open(home.ledger);\n try {\n const state = project(ledger.read());\n const report = unfinishedReport(whatIsOwed(Object.values(state.missions)), own);\n if (report !== \"\") io.out(report);\n } finally {\n ledger.close();\n }\n return 0;\n}\n\n/** `fanout seat <id> <posture> [note]` \u2014 the one setting, and it is always the owner's to make. */\nfunction seat(home: FanoutHome, args: readonly string[], io: Io): number {\n const [seatId, posture, ...rest] = args;\n if (seatId === undefined || posture === undefined) {\n io.err(`fanout: seat needs which seat and how freely to spend it.\\n\\n${SEAT_HELP}`);\n return 64;\n }\n\n const wanted = SeatPosture.safeParse(posture);\n if (!wanted.success) {\n io.err(`fanout: \"${posture}\" is not a posture.\\n\\n${SEAT_HELP}`);\n return 64;\n }\n if (!SEATS.some((manifest) => manifest.id === seatId)) {\n const known = SEATS.map((manifest) => manifest.id).join(\", \");\n io.err(`fanout: there is no seat called \"${seatId}\". Seats: ${known}.\\n`);\n return 64;\n }\n\n const { policy, problem } = readSeatPolicy(home.root);\n if (problem !== null) {\n // Writing on top of a file we could not read would silently discard preferences the owner did set.\n io.err(`fanout: ${problem}\\n Fix or delete that file before changing a seat.\\n`);\n return 65;\n }\n\n const note = rest.join(\" \");\n writeSeatPolicy(home.root, setPosture(policy, seatId, wanted.data, note));\n io.out(`${seatId} is now ${wanted.data}${note === \"\" ? \"\" : ` \u2014 ${note}`}.\\n`);\n return 0;\n}\n\nconst SEAT_HELP = ` fanout seat <id> <preferred|normal|sparing|off> [why]\n\n preferred reach for this one first\n normal use it when the plan calls for it\n sparing only when nothing else fits, and say so first\n off never, until you say otherwise\n`;\n\nasync function daemon(home: FanoutHome, io: Io): Promise<number> {\n const ledger = Ledger.open(home.ledger);\n const token = readOrCreateToken(home.token);\n\n // Runs left over from a session that ended: written off before anybody reads the ledger for an answer.\n reconcile(ledger);\n\n /*\n * One runner per repository, made when that repository first asks for one.\n *\n * A daemon serves the whole machine while a mission belongs to one checkout, so the worktrees and the base\n * commit differ per repository \u2014 one runner for all of them would put an agent's worktree under somebody\n * else's project.\n */\n const runners = new Map<string, ReturnType<typeof createMissionRunner>>();\n /** Missions this daemon is running, so a cancel can reach the one it names. */\n const running = new Map<string, ReturnType<ReturnType<typeof createMissionRunner>[\"launch\"]>>();\n const runnerFor = (repoRoot: string): ReturnType<typeof createMissionRunner> => {\n const existing = runners.get(repoRoot);\n if (existing !== undefined) return existing;\n const made = createMissionRunner({\n ledger,\n workspaces: createWorkspaceManager({ repoRoot, workspaceRoot: home.workspaces }),\n adapters: adapters(),\n runsRoot: home.runs,\n limits: DEFAULT_LIMITS,\n });\n runners.set(repoRoot, made);\n return made;\n };\n\n const api = await startApi({\n ledger,\n token,\n crew: () =>\n detectSeats({ manifests: SEATS, ...(io.execute === undefined ? {} : { execute: io.execute }) }),\n view: missionViewHtml,\n /*\n * Answering as soon as the runs are under way, not when they finish. The session that asked may be gone in\n * thirty seconds \u2014 that is the whole reason this daemon runs the mission instead of it.\n */\n /*\n * Stopping matters more than starting. The handles live here now, so this is the only process that can act\n * on one \u2014 a cancel that went to the session instead would find nothing and say so cheerfully.\n */\n cancel: async (missionId, reason) => {\n const handle = running.get(missionId);\n if (handle === undefined) return false;\n await handle.cancel(reason);\n return true;\n },\n launch: async (order) => {\n try {\n const plan = PlanGraph.parse(order.plan);\n const baseCommit = (await git([\"rev-parse\", \"HEAD\"], { cwd: order.repoRoot })).trim();\n const handle = runnerFor(order.repoRoot).launch({\n missionId: order.missionId,\n plan,\n baseCommit,\n maxParallel: order.maxParallel,\n });\n\n /*\n * Recording the end, because nobody else will.\n *\n * The session that asked for this is very likely gone by now \u2014 that is the point of running it here \u2014 so\n * there is no caller waiting on the handle to write the mission off. Without this the runs all finish\n * and the mission reads `running` for ever, which is the same lie reconciliation exists to prevent, one\n * level up.\n */\n running.set(order.missionId, handle);\n void handle.finished.then((outcome) => {\n running.delete(order.missionId);\n ledger.append({\n type: \"mission.finished\",\n missionId: order.missionId,\n outcome: outcome.failed === 0 && outcome.dropped === 0 ? \"completed\" : \"aborted\",\n summary: `${String(outcome.done)} done, ${String(outcome.failed)} failed, ${String(outcome.dropped)} dropped`,\n });\n });\n\n return { ok: true };\n } catch (cause) {\n return { ok: false, why: cause instanceof Error ? cause.message : String(cause) };\n }\n },\n });\n\n /*\n * Where this daemon is, so a session can find it.\n *\n * It was only ever written by `fanout demo`, which meant the real daemon never advertised itself and the file\n * held a stale entry from whenever somebody last ran the demo \u2014 pointing at a port nobody was listening on.\n * Discovery that answers with an old address is worse than none: the caller believes it.\n */\n const advert = join(home.root, \"daemon.json\");\n writeFileSync(advert, `${JSON.stringify({ url: api.url, pid: process.pid })}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n\n io.out(\n `fanout daemon listening on ${api.url}\\n` +\n ` token ${home.token} (read by the plugin and the CLI; keep it to yourself)\\n` +\n ` ledger ${home.ledger}\\n` +\n ` live ${api.url.replace(\"http\", \"ws\")}/events?for=lead\\n\\nStop it with Ctrl-C.\\n`,\n );\n\n await (io.until ?? interrupted());\n // Taken down with the daemon: an address that outlives the process it names is the bug this file just had.\n rmSync(advert, { force: true });\n await api.close();\n ledger.close();\n io.out(\"fanout daemon stopped.\\n\");\n return 0;\n}\n\n/**\n * Removes what a run leaves on disk: its worktree and its throwaway branch. It only ever touches workspaces under\n * FANOUT_HOME and branches under `fanout/`, so a clean can never take the user's own work with it.\n */\nasync function clean(home: FanoutHome, io: Io): Promise<number> {\n const cwd = io.cwd ?? process.cwd();\n let repoRoot: string;\n try {\n repoRoot = (await git([\"rev-parse\", \"--show-toplevel\"], { cwd })).trim();\n } catch {\n io.err(\"fanout clean: run this inside the repository whose missions you want to clean up.\\n\");\n return 64;\n }\n\n // git reports resolved paths (/private/var/\u2026 on macOS) while FANOUT_HOME may be the symlinked form (/var/\u2026),\n // so compare both spellings; otherwise a clean silently removes nothing and then fails to delete the branch.\n const roots = [\n home.workspaces,\n existsSync(home.workspaces) ? realpathSync(home.workspaces) : home.workspaces,\n ];\n const worktrees = lines(await git([\"worktree\", \"list\", \"--porcelain\"], { cwd: repoRoot }))\n .filter((line) => line.startsWith(\"worktree \"))\n .map((line) => line.slice(\"worktree \".length))\n .filter((path) => roots.some((root) => path.startsWith(root)));\n const branches = lines(\n await git([\"for-each-ref\", \"--format=%(refname:short)\", \"refs/heads/fanout/\"], { cwd: repoRoot }),\n );\n\n if (worktrees.length === 0 && branches.length === 0) {\n io.out(\"Nothing to clean: no Fanout worktrees or branches in this repository.\\n\");\n return 0;\n }\n\n for (const path of worktrees) await git([\"worktree\", \"remove\", \"--force\", path], { cwd: repoRoot });\n await git([\"worktree\", \"prune\"], { cwd: repoRoot });\n\n const kept: string[] = [];\n for (const branch of branches) {\n try {\n await git([\"branch\", \"-D\", branch], { cwd: repoRoot });\n } catch {\n kept.push(branch); // still checked out somewhere: say so rather than pretending it is gone\n }\n }\n rmSync(home.workspaces, { recursive: true, force: true });\n\n const removed = branches.length - kept.length;\n io.out(\n `Cleaned ${worktrees.length} worktree${worktrees.length === 1 ? \"\" : \"s\"} and ` +\n `${removed} branch${removed === 1 ? \"\" : \"es\"}. Your own branches were not touched.\\n`,\n );\n if (kept.length > 0) {\n io.err(`Still in use elsewhere, so left alone: ${kept.join(\", \")}.\\n`);\n }\n return kept.length === 0 ? 0 : 1;\n}\n\n/**\n * Speaks MCP on stdin and stdout so Claude Code can drive the crew, and runs the daemon in the same process so the\n * mission view and the lead's live feed have something to subscribe to.\n *\n * Nothing but MCP may touch stdout here: a stray line would corrupt the protocol, which is why every message this\n * command prints goes to stderr.\n */\nasync function mcp(home: FanoutHome, io: Io): Promise<number> {\n // The feed exists only once the API is listening, and the ledger is open before that; this holder is the join.\n const feed: { publish?: (event: StoredEvent) => void } = {};\n const ledger = Ledger.open(home.ledger, {\n onAppend: (event) => {\n feed.publish?.(event);\n },\n });\n const token = readOrCreateToken(home.token);\n const api = await startApi({\n ledger,\n token,\n crew: () =>\n detectSeats({ manifests: SEATS, ...(io.execute === undefined ? {} : { execute: io.execute }) }),\n view: missionViewHtml,\n });\n feed.publish = (event) => {\n api.publish(event);\n };\n\n /*\n * This server does not advertise itself, and that is the fix for a real failure.\n *\n * `daemon.json` is the machine's one answer to \"where is the daemon\". This API belongs to a single Claude Code\n * session and dies with it, so writing the address here overwrote the long-running daemon's \u2014 and the very\n * next thing this process did was read that file, find itself, and hand its own mission to an API with no\n * runner behind it. The mission sat in planning and never started.\n *\n * The url is printed instead. A session that wants a durable mission runs `fanout daemon`, which is the thing\n * that actually owns the advert.\n */\n\n const server = createFanoutServer({\n ledger,\n repoRoot: io.cwd ?? process.cwd(),\n paths: { runs: home.runs, workspaces: home.workspaces, home: home.root },\n adapters: adapters(),\n manifests: SEATS,\n limits: DEFAULT_LIMITS,\n });\n\n io.err(`fanout mcp ready. Live feed: ${api.url.replace(\"http\", \"ws\")}/events?for=lead\\n`);\n await server.connect(new StdioServerTransport());\n await (io.until ?? interrupted());\n\n await server.close();\n await api.close();\n ledger.close();\n return 0;\n}\n\nfunction interrupted(): Promise<void> {\n return new Promise<void>((resolve) => {\n const stop = (): void => {\n resolve();\n };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n });\n}\n\nexport type { SeatInfo };\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type AdapterSignal,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { ClaudeLine, ToolUse } from \"./protocol.ts\";\n\n/*\n * The Claude Code seat, as a worker. It is opt-in (DECISIONS 0009): the lead already spends this subscription on\n * planning and reviewing, and the point of a crew is to put the other subscriptions to work.\n *\n * Driven through `claude -p`, the documented non-interactive mode. Permission prompts are denied rather than\n * bypassed: a run that would need a human is refused, never waved through.\n *\n * Its stream is the only one that reports a real quota window (how full the five-hour and seven-day windows are,\n * and when they reset), which is exactly what routing needs and what every other seat makes us estimate.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst WRITING = /^(write|edit|multiedit|notebookedit|update)$/i;\nconst READING = /^(read|grep|glob|ls|search|webfetch|websearch)$/i;\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\n\nexport function createClaudeAdapter(): SeatAdapter {\n return {\n id: manifest.id,\n\n command(context: AdapterContext): LaunchSpec {\n const readOnly = context.line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{prompt}\", context.line.prompt)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit),\n );\n if (context.line.seat.model !== undefined) args.push(\"--model\", context.line.seat.model);\n if (context.line.seat.effort !== undefined) args.push(\"--effort\", context.line.seat.effort);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n },\n\n parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = ClaudeLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n\n if (line.type === \"system\" && line.subtype === \"init\" && line.session_id !== undefined) {\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reading\" }],\n signals: [{ kind: \"session\", id: line.session_id }],\n };\n }\n\n if (\n line.type === \"system\" &&\n line.subtype === \"thinking_tokens\" &&\n line.estimated_tokens_delta !== undefined\n ) {\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: Math.max(0, line.estimated_tokens_delta),\n unit: \"tokens\",\n estimated: true,\n },\n ],\n signals: [],\n };\n }\n\n if (line.type === \"rate_limit_event\")\n return { events: [], signals: quotaSignals(line.rate_limit_info) };\n\n if (line.type === \"assistant\") {\n const events: FanoutEventInput[] = [];\n for (const raw of line.message.content) {\n const parsedBlock = ToolUse.safeParse(raw);\n if (!parsedBlock.success) continue; // thinking and text blocks say nothing about what the run did\n const block = parsedBlock.data;\n const input = block.input;\n const command = input?.command ?? \"\";\n const files = [input?.file_path, input?.path, input?.notebook_path]\n .filter((path): path is string => path !== undefined && path !== \"\")\n .map((path) => repoRelative(path, context.workdir));\n\n events.push({ type: \"run.progress\", ...run, phase: phaseOf(block.name, command) });\n events.push({\n type: \"run.tool\",\n ...run,\n tool: block.name,\n ...(command === \"\" ? {} : { summary: command.slice(0, 500) }),\n files,\n });\n }\n return { events, signals: [] };\n }\n\n if (line.type === \"result\") {\n const usage = line.usage;\n const tokens = (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0);\n return {\n events: [\n ...(tokens > 0\n ? [\n {\n type: \"run.usage\" as const,\n ...run,\n seat: context.line.seat.id,\n amount: tokens,\n unit: \"tokens\" as const,\n estimated: false,\n },\n ]\n : []),\n { type: \"run.progress\", ...run, phase: \"reporting\" },\n ],\n signals: [\n ...(line.result === undefined || line.result === \"\"\n ? []\n : [{ kind: \"report\" as const, text: line.result }]),\n ...(line.is_error === true\n ? [{ kind: \"error\" as const, message: line.result ?? \"the run ended with an error\" }]\n : []),\n ],\n };\n }\n\n // \"user\" lines carry tool results, which the tool call already told us about.\n return { events: [], signals: [] };\n },\n };\n}\n\n/** Claude reports how full each window is, and when it resets: real numbers the crew never has to estimate. */\nfunction quotaSignals(info: {\n status: string;\n rateLimitType?: string | undefined;\n resetsAt?: number | undefined;\n unifiedWindows?: Record<string, { utilization: number; resetsAt?: number | undefined }> | undefined;\n}): AdapterSignal[] {\n const signals: AdapterSignal[] = Object.entries(info.unifiedWindows ?? {}).map(([window, value]) => ({\n kind: \"quota\",\n window,\n utilization: value.utilization,\n ...(value.resetsAt === undefined ? {} : { resetsAt: asIso(value.resetsAt) }),\n }));\n\n if (info.status !== \"allowed\") {\n signals.push({\n kind: \"limit\",\n message: `Claude reported the ${info.rateLimitType ?? \"usage\"} window as ${info.status}`,\n ...(info.resetsAt === undefined ? {} : { resetsAt: asIso(info.resetsAt) }),\n });\n }\n return signals;\n}\n\n/** The CLI counts in seconds since the epoch; events speak ISO. */\nfunction asIso(seconds: number): string {\n return new Date(seconds * 1000).toISOString();\n}\n\nfunction phaseOf(tool: string, command: string): \"reading\" | \"coding\" | \"testing\" {\n if (TEST_COMMAND.test(command)) return \"testing\";\n if (WRITING.test(tool)) return \"coding\";\n if (READING.test(tool)) return \"reading\";\n return \"coding\";\n}\n\n/** Claude reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "import { z } from \"zod\";\n\n/** Identifiers people read: mission, line, run and seat ids (\"csv-export\", \"api-builder-1\", \"codex\"). */\nexport const Slug = z\n .string()\n .regex(/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/, \"use lowercase letters, digits and inner dashes (max 64)\");\n\nexport const MissionId = Slug;\nexport const LineId = Slug;\nexport const RunId = Slug;\nexport const SeatId = Slug;\n\n/** A full commit id: 40 hex characters (SHA-1 repositories) or 64 (SHA-256 repositories). */\nexport const GitSha = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/, \"a full commit sha\");\n\n/**\n * The identity of one piece of work: a hash of exactly what a run changed, at the moment we looked.\n *\n * An agent never commits, so its work has no commit id to name it by, and \"the diff in that worktree\" is not an\n * identity \u2014 it is a thing that can change between the moment it is reviewed and the moment it is merged. Every\n * step of the gate records the revision it judged, and a merge applies only a revision that every step agreed on.\n * Without that, \"reviewed and checked\" means \"reviewed and checked something, once\".\n */\nexport const WorkRevision = z.string().regex(/^[0-9a-f]{64}$/, \"a work revision (sha-256 of the diff)\");\n\n/** Which seat runs a line, and optionally with which model and effort. */\nexport const SeatRef = z.strictObject({\n id: SeatId,\n model: z.string().min(1).max(100).optional(),\n effort: z.string().min(1).max(40).optional(),\n});\nexport type SeatRef = z.infer<typeof SeatRef>;\n\n/** What the detector knows about an installed agent CLI. Unknown facts say \"unknown\" or null, never a guess. */\nexport const SeatInfo = z.strictObject({\n id: SeatId,\n displayName: z.string().min(1).max(80),\n binary: z.string().min(1).max(200),\n version: z.string().min(1).max(100).nullable(),\n supported: z.boolean(),\n signedIn: z.enum([\"yes\", \"no\", \"unknown\"]),\n models: z.array(z.string().min(1).max(100)).max(100),\n efforts: z.array(z.string().min(1).max(40)).max(20),\n billing: z.enum([\"subscription\", \"credit\", \"api\", \"unknown\"]),\n /**\n * The subscription tier this seat is on, and where that answer came from \u2014 `null` when the CLI does not report\n * one, which is most of them. The source travels with the value on purpose: \"detected\" is a fact the CLI told us\n * this run, \"declared\" is something the owner typed once and may since have outgrown, and a reader deciding how\n * much to trust a routing decision deserves to know which it is looking at.\n */\n plan: z\n .strictObject({\n name: z.string().min(1).max(100),\n source: z.enum([\"detected\", \"declared\"]),\n })\n .nullable(),\n});\nexport type SeatInfo = z.infer<typeof SeatInfo>;\n\nexport const DiffStat = z.strictObject({\n files: z.int().nonnegative(),\n insertions: z.int().nonnegative(),\n deletions: z.int().nonnegative(),\n});\nexport type DiffStat = z.infer<typeof DiffStat>;\n\nexport const MissionLimits = z.strictObject({\n maxParallel: z.int().min(1).max(32),\n timeoutMinutes: z\n .int()\n .min(1)\n .max(24 * 60),\n});\nexport type MissionLimits = z.infer<typeof MissionLimits>;\n\n/** One line of the safety report. A failed \"block\" check stops the launch; a failed \"warn\" check is shown. */\nexport const SafetyCheck = z.strictObject({\n id: z.string().min(1).max(64),\n ok: z.boolean(),\n severity: z.enum([\"block\", \"warn\"]),\n message: z.string().min(1).max(2000),\n lineIds: z.array(LineId).max(32).optional(),\n});\nexport type SafetyCheck = z.infer<typeof SafetyCheck>;\n", "import { z } from \"zod\";\n\n/*\n * Write scopes are repo-relative POSIX globs with a deliberately small syntax:\n * `*` and `?` match within one path segment, `**` (a whole segment) matches zero or more segments.\n * Every pattern also covers everything below what it matches, so `src/api` and `src/api/**` are the same scope.\n * Braces, character classes and negation are not supported: a scope must be obvious to the person approving it.\n *\n * Every other character is literal, so ordinary filenames work: spaces, parentheses, accents, CJK, emoji.\n * Only `*` and `?` are special, and there is no escape for them; a file whose name really contains one is covered\n * by a scope that ends in `**`. Separators, empty segments, `.` and `..` are refused, as are control characters.\n *\n * Matching is deliberately hand-written rather than translated to regular expressions: a pattern like `a*a*a*\u2026z`\n * makes a backtracking engine take exponential time, and scopes come from plans we must be able to check quickly.\n */\n\n// eslint-disable-next-line no-control-regex -- control characters are exactly what a path segment must not contain\nconst SEGMENT = /^(?:\\*\\*|[^/\u0000-\u001F\u007F]+)$/;\nconst WILDCARD = /[*?]/;\n\nexport function isValidScopeGlob(glob: string): boolean {\n if (glob.length === 0 || glob.startsWith(\"/\") || glob.endsWith(\"/\")) return false;\n return glob\n .split(\"/\")\n .every(\n (segment) =>\n SEGMENT.test(segment) &&\n segment !== \".\" &&\n segment !== \"..\" &&\n (segment === \"**\" || !segment.includes(\"**\")),\n );\n}\n\nexport const ScopeGlob = z.string().max(300).refine(isValidScopeGlob, {\n message: \"use a repo-relative path or glob (`*`, `?`, `**`), without `..`, leading or trailing `/`\",\n});\n\n/**\n * A plain repo-relative path: no leading slash, no `.` or `..`, no empty segments. Anything else (a path that still\n * needs resolving, or one from outside the repository) is not inside any scope, whatever it looks like.\n */\nexport function isRepoPath(path: string): boolean {\n if (path.length === 0 || path.startsWith(\"/\") || path.endsWith(\"/\")) return false;\n return path.split(\"/\").every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/** Segments of a pattern, with the implicit \"and everything below\" made explicit. */\nfunction scopeSegments(glob: string): string[] {\n const segments = glob.split(\"/\");\n return segments.at(-1) === \"**\" ? segments : [...segments, \"**\"];\n}\n\n/**\n * Matches one segment pattern (`*`, `?`) against one name, in linear time: on a mismatch it returns to the last `*`\n * and gives it one more character, so no input can make it backtrack exponentially.\n */\nfunction segmentMatches(pattern: string, text: string): boolean {\n let p = 0;\n let t = 0;\n let starAt = -1;\n let matchedAt = 0;\n\n while (t < text.length) {\n const token = pattern[p];\n if (token === \"?\" || (token !== undefined && token !== \"*\" && token === text[t])) {\n p += 1;\n t += 1;\n } else if (token === \"*\") {\n starAt = p;\n matchedAt = t;\n p += 1;\n } else if (starAt >= 0) {\n matchedAt += 1;\n p = starAt + 1;\n t = matchedAt;\n } else {\n return false;\n }\n }\n while (pattern[p] === \"*\") p += 1;\n return p === pattern.length;\n}\n\n/** The literal text before the first wildcard and after the last one. */\nfunction literalEnds(segment: string): [prefix: string, suffix: string] {\n const first = segment.search(WILDCARD);\n let last = segment.length - 1;\n while (last >= 0 && !WILDCARD.test(segment.charAt(last))) last -= 1;\n return [segment.slice(0, first), segment.slice(last + 1)];\n}\n\n/**\n * Whether two single-segment patterns can match a common name. Exact when at least one side is literal; when both\n * have wildcards it compares their literal ends, which can only err towards \"yes\" (the safe side for scopes).\n */\nfunction segmentsMayOverlap(a: string, b: string): boolean {\n const aWild = WILDCARD.test(a);\n const bWild = WILDCARD.test(b);\n if (!aWild && !bWild) return a === b;\n if (!aWild) return segmentMatches(b, a);\n if (!bWild) return segmentMatches(a, b);\n const [aPrefix, aSuffix] = literalEnds(a);\n const [bPrefix, bSuffix] = literalEnds(b);\n return (\n (aPrefix.startsWith(bPrefix) || bPrefix.startsWith(aPrefix)) &&\n (aSuffix.endsWith(bSuffix) || bSuffix.endsWith(aSuffix))\n );\n}\n\n/**\n * Whether some file path could fall inside both scopes. Sound: it never answers \"no\" when a common path exists.\n * It may answer \"yes\" for exotic wildcard pairs that cannot actually meet; the plan then asks for narrower scopes.\n */\nexport function scopesMayOverlap(a: string, b: string): boolean {\n const left = scopeSegments(a);\n const right = scopeSegments(b);\n const memo = new Map<number, boolean>();\n const width = right.length + 1;\n\n const from = (i: number, j: number): boolean => {\n const key = i * width + j;\n const known = memo.get(key);\n if (known !== undefined) return known;\n let result: boolean;\n const l = left[i];\n const r = right[j];\n if (l === undefined && r === undefined) result = true;\n else if (l === \"**\") result = from(i + 1, j) || (r !== undefined && from(i, j + 1));\n else if (r === \"**\") result = from(i, j + 1) || (l !== undefined && from(i + 1, j));\n else if (l === undefined || r === undefined) result = false;\n else result = segmentsMayOverlap(l, r) && from(i + 1, j + 1);\n memo.set(key, result);\n return result;\n };\n\n return from(0, 0);\n}\n\n/** Whether a repo-relative file path falls inside a scope. */\nexport function pathInScope(path: string, glob: string): boolean {\n if (!isRepoPath(path)) return false;\n const parts = path.split(\"/\");\n const pattern = scopeSegments(glob);\n const memo = new Map<number, boolean>();\n const width = pattern.length + 1;\n\n const from = (i: number, j: number): boolean => {\n const key = i * width + j;\n const known = memo.get(key);\n if (known !== undefined) return known;\n const segment = pattern[j];\n const part = parts[i];\n let result: boolean;\n if (segment === undefined) result = i === parts.length;\n else if (segment === \"**\") result = from(i, j + 1) || (i < parts.length && from(i + 1, j));\n else result = part !== undefined && segmentMatches(segment, part) && from(i + 1, j + 1);\n memo.set(key, result);\n return result;\n };\n\n return from(0, 0);\n}\n", "import { z } from \"zod\";\nimport { LineId, SeatRef } from \"./common.ts\";\nimport { ScopeGlob, scopesMayOverlap } from \"./scope.ts\";\n\nexport const LineRole = z.enum([\"auditor\", \"builder\", \"tester\"]);\nexport type LineRole = z.infer<typeof LineRole>;\n\n/** One task in a mission. Auditors are read-only; builders and testers declare where they may write. */\nexport const PlanLine = z.strictObject({\n id: LineId,\n title: z.string().trim().min(1).max(120),\n role: LineRole,\n prompt: z.string().min(1).max(100_000),\n seat: SeatRef,\n scope: z.strictObject({ write: z.array(ScopeGlob).max(64) }),\n dependsOn: z.array(LineId).max(32).default([]),\n checks: z.array(z.string().min(1).max(500)).max(16).default([]),\n timeoutMinutes: z.int().min(1).max(240).optional(),\n /**\n * This line fixes a bug, so the gate will not merge it without a test proven to fail on the old code.\n *\n * Declared when the mission is planned rather than judged afterwards, because the moment to decide whether\n * something is a fix is before an agent has written a persuasive explanation of why its change is fine.\n */\n fixesBug: z.boolean().default(false),\n});\nexport type PlanLine = z.infer<typeof PlanLine>;\n\nexport const PlanGraph = z.strictObject({\n lines: z.array(PlanLine).min(1).max(32),\n});\nexport type PlanGraph = z.infer<typeof PlanGraph>;\n\nexport type PlanIssueCode =\n | \"duplicate_line\"\n | \"unknown_dependency\"\n | \"self_dependency\"\n | \"dependency_cycle\"\n | \"auditor_writes\"\n | \"missing_write_scope\"\n | \"scope_overlap\";\n\nexport interface PlanIssue {\n code: PlanIssueCode;\n message: string;\n lineIds: string[];\n}\n\n/**\n * Checks the rules a schema can't express: the dependency graph and the write scopes of lines that may run at the\n * same time. Returns every issue found, in a stable order; an empty list means the plan is launchable.\n */\nexport function validatePlan(plan: PlanGraph): PlanIssue[] {\n const issues: PlanIssue[] = [];\n const { lines } = plan;\n\n const indexById = new Map<string, number>();\n lines.forEach((line, index) => {\n if (indexById.has(line.id)) {\n issues.push({\n code: \"duplicate_line\",\n message: `Line id \"${line.id}\" is used more than once.`,\n lineIds: [line.id],\n });\n } else {\n indexById.set(line.id, index);\n }\n });\n\n const edges: number[][] = lines.map((line) => {\n const targets: number[] = [];\n for (const dependency of line.dependsOn) {\n if (dependency === line.id) {\n issues.push({\n code: \"self_dependency\",\n message: `Line \"${line.id}\" depends on itself.`,\n lineIds: [line.id],\n });\n continue;\n }\n const target = indexById.get(dependency);\n if (target === undefined) {\n issues.push({\n code: \"unknown_dependency\",\n message: `Line \"${line.id}\" depends on \"${dependency}\", which is not in the plan.`,\n lineIds: [line.id],\n });\n } else {\n targets.push(target);\n }\n }\n return targets;\n });\n\n for (const cycle of findCycles(edges)) {\n const ids = cycle.map((index) => lines[index]?.id ?? \"?\");\n issues.push({\n code: \"dependency_cycle\",\n message: `Dependencies form a cycle: ${[...ids, ids[0]].join(\" \u2192 \")}.`,\n lineIds: ids,\n });\n }\n\n for (const line of lines) {\n if (line.role === \"auditor\" && line.scope.write.length > 0) {\n issues.push({\n code: \"auditor_writes\",\n message: `Line \"${line.id}\" is an auditor, so it is read-only; remove its write scope or make it a builder.`,\n lineIds: [line.id],\n });\n }\n if (line.role !== \"auditor\" && line.scope.write.length === 0) {\n issues.push({\n code: \"missing_write_scope\",\n message: `Line \"${line.id}\" is a ${line.role} but declares no write scope.`,\n lineIds: [line.id],\n });\n }\n }\n\n const reaches = reachability(edges);\n for (let i = 0; i < lines.length; i += 1) {\n for (let j = i + 1; j < lines.length; j += 1) {\n const a = lines[i];\n const b = lines[j];\n if (a === undefined || b === undefined) continue;\n if (reaches[i]?.has(j) === true || reaches[j]?.has(i) === true) continue;\n const clash = firstOverlap(a.scope.write, b.scope.write);\n if (clash !== undefined) {\n issues.push({\n code: \"scope_overlap\",\n message:\n `Lines \"${a.id}\" and \"${b.id}\" can run at the same time and may both write ` +\n `\"${clash[0]}\" / \"${clash[1]}\". Make one depend on the other, or narrow the scopes.`,\n lineIds: [a.id, b.id],\n });\n }\n }\n }\n\n return issues;\n}\n\nfunction firstOverlap(left: string[], right: string[]): [string, string] | undefined {\n for (const a of left) {\n for (const b of right) {\n if (scopesMayOverlap(a, b)) return [a, b];\n }\n }\n return undefined;\n}\n\n/** For each node, every node it can reach by following edges (its transitive dependencies). */\nfunction reachability(edges: number[][]): Set<number>[] {\n return edges.map((_, start) => {\n const seen = new Set<number>();\n const stack = [...(edges[start] ?? [])];\n for (let next = stack.pop(); next !== undefined; next = stack.pop()) {\n if (seen.has(next)) continue;\n seen.add(next);\n stack.push(...(edges[next] ?? []));\n }\n return seen;\n });\n}\n\n/** One cycle per back edge found by a depth-first search, each listed from its first node in plan order. */\nfunction findCycles(edges: number[][]): number[][] {\n const state = new Array<\"new\" | \"open\" | \"done\">(edges.length).fill(\"new\");\n const path: number[] = [];\n const cycles: number[][] = [];\n\n const visit = (node: number): void => {\n state[node] = \"open\";\n path.push(node);\n for (const next of edges[node] ?? []) {\n if (state[next] === \"open\") {\n cycles.push(path.slice(path.indexOf(next)));\n } else if (state[next] === \"new\") {\n visit(next);\n }\n }\n path.pop();\n state[node] = \"done\";\n };\n\n edges.forEach((_, node) => {\n if (state[node] === \"new\") visit(node);\n });\n return cycles;\n}\n", "import { z } from \"zod\";\nimport {\n DiffStat,\n GitSha,\n LineId,\n MissionId,\n MissionLimits,\n RunId,\n SafetyCheck,\n SeatId,\n SeatInfo,\n SeatRef,\n WorkRevision,\n} from \"./common.ts\";\nimport { PlanGraph } from \"./plan.ts\";\n\n/*\n * Every fact the daemon records is one of these events. Rules for changing this file:\n * - Adding a new event type is additive: old ledgers stay valid.\n * - Changing the shape of an existing type needs a new EVENT_VERSION and an upgrade path for stored events.\n * - Events carry no secrets and no raw logs: summaries, paths and numbers only.\n */\n\nexport const EVENT_VERSION = 1 as const;\n\nconst mission = { missionId: MissionId };\nconst run = { missionId: MissionId, runId: RunId };\n\nconst PlanAuthor = z.enum([\"lead\", \"user\"]);\nconst Phase = z.enum([\"reading\", \"coding\", \"testing\", \"reporting\"]);\nconst RepoPaths = z.array(z.string().min(1).max(1000)).max(1000);\n\nexport const SeatDetected = z.strictObject({\n type: z.literal(\"seat.detected\"),\n seat: SeatInfo,\n});\n\nexport const MissionCreated = z.strictObject({\n type: z.literal(\"mission.created\"),\n ...mission,\n goal: z.string().trim().min(1).max(4000),\n repo: z.strictObject({ root: z.string().min(1).max(1000), baseCommit: GitSha }),\n limits: MissionLimits,\n});\n\nexport const PlanProposed = z.strictObject({\n type: z.literal(\"plan.proposed\"),\n ...mission,\n plan: PlanGraph,\n by: PlanAuthor,\n note: z.string().max(2000).optional(),\n});\n\nexport const PlanRevised = z.strictObject({\n type: z.literal(\"plan.revised\"),\n ...mission,\n plan: PlanGraph,\n by: PlanAuthor,\n note: z.string().max(2000).optional(),\n});\n\nexport const SafetyReported = z\n .strictObject({\n type: z.literal(\"safety.report\"),\n ...mission,\n /** Which plan revision this report describes. A newer plan makes it stale, never current. */\n planRevision: z.int().positive(),\n ok: z.boolean(),\n checks: z.array(SafetyCheck).max(200),\n })\n .refine((report) => report.ok === report.checks.every((check) => check.ok || check.severity === \"warn\"), {\n message: \"ok must be true exactly when no blocking check failed\",\n path: [\"ok\"],\n });\n\nexport const RunQueued = z.strictObject({\n type: z.literal(\"run.queued\"),\n ...run,\n lineId: LineId,\n seat: SeatRef,\n attempt: z.int().min(1).max(3),\n});\n\nexport const RunStarted = z.strictObject({\n type: z.literal(\"run.started\"),\n ...run,\n workdir: z.string().min(1).max(1000),\n argv: z.array(z.string().max(200_000)).min(1).max(200),\n /**\n * The process id of the daemon supervising this run \u2014 not the agent's own.\n *\n * It exists to answer one question later: is anybody still watching this? A run whose supervisor is gone\n * cannot still be running, however the ledger last left it. Without this a session that ends while a mission\n * is in flight leaves a run recorded as running forever, and nothing can tell that apart from one that\n * genuinely is.\n *\n * Absent on runs recorded before this existed; read those as unknown rather than as dead.\n */\n owner: z.int().positive().optional(),\n});\n\n/**\n * The agent's own name for this conversation, learned as soon as we have it.\n *\n * Recorded because rework depends on it: replying into the session that wrote a diff is worth far more than\n * re-explaining the work to a stranger who happens to share its model. Some CLIs let us choose the id before\n * launch and some announce it in their stream (ADR 0018); either way it is written down the moment it is known,\n * because the run most likely to need rework is the one that ended badly.\n */\nexport const RunSession = z.strictObject({\n type: z.literal(\"run.session\"),\n ...run,\n sessionId: z.string().trim().min(1).max(200),\n});\n\nexport const RunProgress = z.strictObject({\n type: z.literal(\"run.progress\"),\n ...run,\n phase: Phase,\n detail: z.string().max(500).optional(),\n});\n\nexport const RunTool = z.strictObject({\n type: z.literal(\"run.tool\"),\n ...run,\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n files: RepoPaths.default([]),\n});\n\nexport const RunUsage = z.strictObject({\n type: z.literal(\"run.usage\"),\n ...run,\n seat: SeatId,\n amount: z.number().nonnegative(),\n unit: z.enum([\"messages\", \"tokens\", \"minutes\"]),\n estimated: z.boolean(),\n});\n\nexport const RunFinished = z.strictObject({\n type: z.literal(\"run.finished\"),\n ...run,\n status: z.enum([\"done\", \"failed\", \"killed\", \"timeout\"]),\n exitCode: z.int().nullable(),\n reportPath: z.string().min(1).max(1000).optional(),\n diffStat: DiffStat.optional(),\n});\n\n/*\n * The merge gate, in events. Every one of them names the `revision` it judged, because each is a statement about a\n * specific diff and not about a worktree that may since have moved. A merge applies a revision only when review,\n * checks, proof and approval all named that same one; anything else is a claim about work nobody looked at.\n */\n\nexport const ReviewDone = z.strictObject({\n type: z.literal(\"review.done\"),\n ...run,\n revision: WorkRevision,\n verdict: z.enum([\"accept\", \"rework\", \"reject\"]),\n notes: z.string().max(20_000),\n by: SeatRef,\n});\n\nexport const ChecksDone = z.strictObject({\n type: z.literal(\"checks.done\"),\n ...run,\n revision: WorkRevision,\n ok: z.boolean(),\n summary: z.string().max(4000),\n /** What actually ran, so \"checks pass\" can be read as a claim about specific commands. */\n commands: z.array(z.string().min(1).max(500)).max(50),\n});\n\n/** Proof of a fix: the new tests that fail on the old code (and pass on the new). */\nexport const ProofDone = z\n .strictObject({\n type: z.literal(\"proof.done\"),\n ...run,\n revision: WorkRevision,\n ok: z.boolean(),\n failedOnOld: z.array(z.string().min(1).max(500)).max(500),\n })\n .refine((proof) => !proof.ok || proof.failedOnOld.length > 0, {\n message: \"a passing proof names at least one test that failed on the old code\",\n path: [\"failedOnOld\"],\n });\n\n/**\n * Someone said yes. Recorded separately from the merge itself so a replay can answer \"who authorised this?\" \u2014\n * a question a diff in the history cannot answer on its own.\n */\nexport const MergeApproved = z.strictObject({\n type: z.literal(\"merge.approved\"),\n ...run,\n revision: WorkRevision,\n /**\n * A person, or a policy the person wrote down in advance. A policy must name itself: \"it was pre-approved\" is\n * not an answer anyone can audit, and \"which rule, written when\" is.\n */\n by: z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"user\"),\n /**\n * How we know. This is the difference between a fact and an agent's account of one.\n *\n * `direct` \u2014 the daemon received the click itself, from the mission view, on this machine. Nothing in\n * between could have invented it.\n *\n * `relayed` \u2014 the lead says it asked and quoted the answer in `note`. That is a claim by a language model\n * about a conversation, and an agent that skipped the asking writes a byte-identical event. It is worth\n * recording and it is not worth confusing with the first one.\n *\n * Absent on events written before Fanout drew the distinction; read those as `relayed`.\n */\n via: z.enum([\"direct\", \"relayed\"]).optional(),\n }),\n z.strictObject({ kind: z.literal(\"policy\"), name: z.string().trim().min(1).max(200) }),\n ]),\n note: z.string().max(2000).optional(),\n});\n\nexport const MergeApplied = z.strictObject({\n type: z.literal(\"merge.applied\"),\n ...run,\n revision: WorkRevision,\n files: RepoPaths.min(1),\n /** Where the work landed, so a dependent line can start from it rather than from a guess. */\n commit: GitSha,\n});\n\nexport const MergeConflict = z.strictObject({\n type: z.literal(\"merge.conflict\"),\n ...run,\n revision: WorkRevision,\n files: RepoPaths.min(1),\n});\n\nexport const RunDropped = z.strictObject({\n type: z.literal(\"run.dropped\"),\n ...run,\n reason: z.string().trim().min(1).max(2000),\n});\n\n/**\n * A second vendor read the lead's own uncommitted work.\n *\n * Not a mission and not a run: no agent worked in a worktree, and forcing this into the mission machinery would\n * put a fake mission in front of the user for every review. It carries no `missionId` for the same reason\n * `seat.detected` does not \u2014 it is a fact about this machine at a moment, not about a mission.\n *\n * This is the event that answers the product's only real question: was anything other than the author's own\n * judgement applied to this code before it was called done?\n */\nexport const BuddyReviewed = z.strictObject({\n type: z.literal(\"buddy.reviewed\"),\n /** Which working tree, so a review of one repository is never read as covering another. */\n repoRoot: z.string().min(1).max(1000),\n revision: WorkRevision,\n by: SeatRef,\n /** What it said, verbatim. A second opinion summarised by the author is not a second opinion. */\n findings: z.string().max(100_000),\n /** False when the reviewer could not be run at all, so \"no findings\" never stands in for \"never asked\". */\n ran: z.boolean(),\n files: RepoPaths.max(1000),\n});\n\n/**\n * The lead wrote down what it believes, and a cold reader checked each belief against the code.\n *\n * This is the sharpest thing a second vendor can do, and the cheapest. The lead carries the whole session \u2014 the\n * plan, the reasoning, the justification \u2014 and that context is precisely what makes its own mistakes invisible to\n * it: it knows why the code is right, so the code looks right. A reader arriving with only the diff is not\n * smarter, it is differently placed, which is why even a small model reading cold can refute a large one reading\n * warm. Asking it to review everything spends tokens on that asymmetry. Asking it to falsify three specific\n * claims spends almost none.\n *\n * Recording the claims, not only the verdicts, is the point. A replay shows what the lead asserted as well as\n * what turned out to be true, and an author who must write down falsifiable claims notices the weak ones while\n * writing them.\n */\nexport const ClaimsChecked = z.strictObject({\n type: z.literal(\"claims.checked\"),\n repoRoot: z.string().min(1).max(1000),\n revision: WorkRevision,\n by: SeatRef,\n claims: z\n .array(\n z.strictObject({\n /** What the lead asserted, in its own words. */\n claim: z.string().trim().min(1).max(500),\n /**\n * `unclear` is the default and the only safe absence. A verdict we could not read is not a pass, and a\n * claim the reader ignored has not been checked \u2014 treating either as confirmed would make this theatre.\n */\n verdict: z.enum([\"confirmed\", \"refuted\", \"unclear\"]),\n /** Why, in the reader's own words. Required for a refusal; a bare \"no\" helps nobody. */\n evidence: z.string().max(4000),\n }),\n )\n .min(1)\n .max(20),\n /** False when the reader could not be run at all, so \"nothing refuted\" never stands in for \"never asked\". */\n ran: z.boolean(),\n /**\n * True when these verdicts were written by us rather than read by anyone \u2014 the offline demo, and nothing else.\n *\n * It exists so that the one thing the demo cannot do honestly is labelled everywhere it appears instead of\n * being quietly indistinguishable from a real answer. Inventing a second opinion and presenting it as read\n * would be faking the only claim this product makes.\n */\n simulated: z.boolean().default(false),\n});\n\n/**\n * A seat said it has run out, in its own words.\n *\n * Not mission-scoped: a limit belongs to the account, not to whatever happened to be running when it was hit.\n * The message is kept verbatim because \"you have reached your usage limit\" and \"rate limited, retry in 30s\" are\n * different problems and only the vendor knows which one this is.\n */\nexport const SeatLimited = z.strictObject({\n type: z.literal(\"seat.limited\"),\n seat: SeatId,\n message: z.string().trim().min(1).max(500),\n /** When the seat says it will work again. Absent when it did not say, which is usually. */\n resetsAt: z.iso.datetime().optional(),\n});\n\n/**\n * How full one of a seat's quota windows is, when the CLI reports it rather than us guessing.\n *\n * Claude Code is the only seat that says this today, per turn, for its five-hour and seven-day windows. It is the\n * difference between routing on facts and routing on arithmetic we made up, so it is recorded as what it is \u2014\n * real, and belonging to a named window \u2014 rather than flattened into a token count that would read as estimated.\n */\nexport const SeatQuota = z.strictObject({\n type: z.literal(\"seat.quota\"),\n seat: SeatId,\n window: z.string().min(1).max(50),\n /** 0.28 means 28% of that window is used. */\n utilization: z.number().min(0).max(1),\n resetsAt: z.iso.datetime().optional(),\n});\n\nexport const RouteChanged = z.strictObject({\n type: z.literal(\"route.changed\"),\n ...mission,\n lineId: LineId,\n from: SeatRef,\n to: SeatRef,\n reason: z.string().trim().min(1).max(500),\n});\n\nexport const PolicyBreach = z.strictObject({\n type: z.literal(\"policy.breach\"),\n ...run,\n limit: z.string().min(1).max(100),\n action: z.enum([\"killed\", \"paused\", \"asked\"]),\n});\n\nexport const MissionFinished = z.strictObject({\n type: z.literal(\"mission.finished\"),\n ...mission,\n outcome: z.enum([\"completed\", \"aborted\"]),\n summary: z.string().max(8000),\n});\n\nexport const FanoutEvent = z.discriminatedUnion(\"type\", [\n SeatDetected,\n MissionCreated,\n PlanProposed,\n PlanRevised,\n SafetyReported,\n RunQueued,\n RunStarted,\n RunSession,\n RunProgress,\n RunTool,\n RunUsage,\n RunFinished,\n ReviewDone,\n ChecksDone,\n ProofDone,\n BuddyReviewed,\n ClaimsChecked,\n MergeApproved,\n MergeApplied,\n MergeConflict,\n RunDropped,\n SeatLimited,\n SeatQuota,\n RouteChanged,\n PolicyBreach,\n MissionFinished,\n]);\n\n/** An event as validated (defaults applied). */\nexport type FanoutEvent = z.infer<typeof FanoutEvent>;\n/** An event as written by a producer (defaults may be omitted). */\nexport type FanoutEventInput = z.input<typeof FanoutEvent>;\nexport type EventType = FanoutEvent[\"type\"];\nexport type EventOf<T extends EventType> = Extract<FanoutEvent, { type: T }>;\n\n/** What the ledger adds when it records an event. */\nexport const EventStamp = z.strictObject({\n v: z.literal(EVENT_VERSION),\n id: z.uuid(),\n seq: z.int().positive(),\n ts: z.iso.datetime(),\n});\nexport type EventStamp = z.infer<typeof EventStamp>;\n\n/** An event as stored in and read from the ledger. */\nexport type StoredEvent = FanoutEvent & EventStamp;\n", "import { z } from \"zod\";\nimport { SeatId } from \"./common.ts\";\n\n/*\n * What an adapter declares about its CLI, as data rather than code: the versions it was verified against, the exact\n * non-interactive invocation, how to read its output, the safest modes it offers, how to ask it whether it is signed\n * in, and when its vendor's terms were last reviewed.\n *\n * A manifest is a promise we can check. A CLI outside `supportedVersions` is reported as an unsupported version\n * rather than driven on a guess, because a stream we have not seen is a stream we cannot parse honestly.\n */\n\n/** A placeholder the supervisor fills in: {workdir}, {prompt}, {report}, {sandbox}, {model}, {effort}, {session}. */\nconst ArgTemplate = z.string().min(1).max(500);\n\n/**\n * A regular expression a manifest asks us to run, checked at parse time rather than at the moment we need it.\n *\n * A pattern that does not compile throws from `new RegExp`, and that throw would happen deep inside detection,\n * where it takes down the whole crew's result and not just the seat that declared it. Refusing the manifest is\n * both earlier and louder. (This does not make a pattern *fast*: see `matches` in the detector for that half.)\n */\nconst SafePattern = z.string().max(200).refine(compiles, { message: \"must be a valid regular expression\" });\n\nfunction compiles(pattern: string): boolean {\n try {\n new RegExp(pattern, \"i\");\n return true;\n } catch {\n return false;\n }\n}\n\nexport const AdapterManifest = z.strictObject({\n id: SeatId,\n displayName: z.string().min(1).max(80),\n binary: z.string().min(1).max(200),\n /** A semver range, e.g. \">=0.150 <1.0\". Outside it, the seat is unsupported, never guessed at. */\n supportedVersions: z.string().min(1).max(100),\n /** What we promise about this seat, never a judgment of the CLI's quality. */\n tier: z.enum([\"supported\", \"community\", \"reference\"]),\n\n /** Null means no such mode or none verified: the merge gate must never act on a guess. */\n capabilities: z.strictObject({\n resume: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n fork: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n review: z.strictObject({ args: z.array(ArgTemplate).min(1).max(50) }).nullable(),\n /**\n * An allowlist keeps account identity out of storage. A privacy promise that is data can be reviewed in a pull\n * request; a promise in adapter code has to be re-read every time.\n */\n plan: z\n .strictObject({\n probe: z.array(z.string().min(1).max(100)).min(1).max(10),\n format: z.literal(\"json\"),\n keep: z.array(z.string().min(1).max(100)).min(1).max(5),\n planField: z.string().min(1).max(100),\n })\n .refine((plan) => plan.keep.includes(plan.planField), {\n message: \"planField must be one of keep\",\n path: [\"planField\"],\n })\n .nullable(),\n }),\n\n headless: z.strictObject({\n args: z.array(ArgTemplate).min(1).max(50),\n /** Always closed: a CLI waiting on stdin is the most common way a run hangs forever. */\n stdin: z.literal(\"closed\"),\n }),\n\n stream: z.strictObject({\n /** The flag that turns on machine-readable output, or null when the CLI has none. */\n flag: z.string().max(100).nullable(),\n format: z.enum([\"jsonl\", \"text\"]),\n }),\n\n models: z.array(z.string().min(1).max(100)).max(100),\n efforts: z.array(z.string().min(1).max(40)).max(20),\n\n /** The flag value for each mode we use. Auditors get the read-only one; nothing else is ever passed. */\n permissionModes: z.strictObject({\n readOnly: z.string().min(1).max(100),\n edit: z.string().min(1).max(100),\n }),\n\n network: z.strictObject({\n canDisable: z.boolean(),\n flag: z.string().max(100).nullable(),\n }),\n\n /**\n * How to ask the CLI itself whether it is signed in. We never read credential files.\n *\n * Both answers are named, because only one of them can be inferred from the other's absence and neither\n * actually is: a probe that fails, times out or answers something unforeseen has told us nothing, and\n * \"nothing\" must stay \"unknown\" rather than becoming a \"no\" that quietly reroutes someone's work.\n */\n signIn: z.strictObject({\n probe: z.array(z.string().min(1).max(100)).max(10).nullable(),\n /** A pattern the probe's output must match to count as signed in. */\n okPattern: SafePattern.nullable(),\n /** A pattern that positively means signed out. Checked first, so \"Not logged in\" cannot match \"Logged in\". */\n noPattern: SafePattern.nullable(),\n }),\n\n /** Real usage when the CLI reports it; otherwise we estimate and say so. */\n usage: z.strictObject({\n probe: z.array(z.string().min(1).max(100)).max(10).nullable(),\n window: z.string().max(100),\n }),\n\n /** Which pool this seat's headless use bills against, so a vendor's policy change is a manifest change. */\n billing: z.enum([\"subscription\", \"credit\", \"api\", \"unknown\"]),\n\n terms: z.strictObject({\n reviewedAt: z.iso.date().nullable(),\n notes: z.string().max(2000),\n }),\n\n status: z.enum([\"planned\", \"research\", \"alpha\", \"stable\"]),\n});\nexport type AdapterManifest = z.infer<typeof AdapterManifest>;\n", "import { z } from \"zod\";\nimport { SeatId, type SeatInfo } from \"./common.ts\";\n\n/*\n * What the owner wants done with each seat, kept apart from what is true of it today.\n *\n * Posture is a preference and availability is a fact, and mixing them produces a interface that lies in both\n * directions: a seat you rely on looks disabled the morning its CLI fails to start, and a seat you asked us never\n * to touch looks ready the moment it signs in. They are resolved together only at the point of use, in `stanceFor`.\n *\n * This file holds only what the owner declared. It is never a cache of anything detected: a subscription tier\n * written down in June and read back in September is a stale answer presented as a current fact, and the whole\n * point of the `source` on a plan is that a reader can tell those apart.\n */\n\n/**\n * How willingly Fanout should spend a seat.\n *\n * - `preferred` \u2014 reach for this first when several seats could do the line.\n * - `normal` \u2014 use it when the plan calls for it.\n * - `sparing` \u2014 only when nothing else fits, and say so before launching. For the subscription you pay least for.\n * - `off` \u2014 never, until the owner says otherwise.\n */\nexport const SeatPosture = z.enum([\"preferred\", \"normal\", \"sparing\", \"off\"]);\nexport type SeatPosture = z.infer<typeof SeatPosture>;\n\nexport const SeatPolicy = z.strictObject({\n version: z.literal(1),\n seats: z.record(\n SeatId,\n z.strictObject({\n posture: SeatPosture,\n /** The owner's own words about why, shown back to them so a past decision explains itself. */\n note: z.string().max(200).optional(),\n }),\n ),\n});\nexport type SeatPolicy = z.infer<typeof SeatPolicy>;\n\nexport const EMPTY_POLICY: SeatPolicy = { version: 1, seats: {} };\n\n/**\n * Claude is the only seat that is off until asked for.\n *\n * The lead already runs on this subscription, so a Claude worker spends the same window the session you are sitting\n * in is spending. That is a decision about someone's money, and it is theirs to make deliberately rather than to\n * discover afterwards (DECISIONS 0009).\n */\nconst OPT_IN_SEATS: ReadonlySet<string> = new Set([\"claude\"]);\n\nexport interface SeatStance {\n posture: SeatPosture;\n /** `declared` when the owner set it; `default` when nobody has, and `reason` says why that default. */\n source: \"declared\" | \"default\";\n reason: string;\n /** Willing *and* able: the posture allows it and the CLI is actually there and signed in. */\n usable: boolean;\n note?: string;\n}\n\n/**\n * What we should do with one seat right now, given what the owner declared and what detection found.\n *\n * Deliberately not clever. We know a plan's *name*, never its price, so nothing here infers that \"pro\" is cheaper\n * than \"max\" or that an unknown plan is a small one \u2014 the one fact only the owner has is which subscription they\n * would rather not spend, and the only honest way to learn it is to be told.\n */\nexport function stanceFor(seat: SeatInfo, policy: SeatPolicy): SeatStance {\n const declared = Object.hasOwn(policy.seats, seat.id) ? policy.seats[seat.id] : undefined;\n const posture: SeatPosture = declared?.posture ?? (OPT_IN_SEATS.has(seat.id) ? \"off\" : \"normal\");\n\n const reason =\n declared !== undefined\n ? \"you set this\"\n : OPT_IN_SEATS.has(seat.id)\n ? \"opt-in: a worker here spends the same subscription your session is running on\"\n : \"nobody has said otherwise\";\n\n return {\n posture,\n source: declared === undefined ? \"default\" : \"declared\",\n reason,\n usable: posture !== \"off\" && seat.supported && seat.signedIn === \"yes\",\n ...(declared?.note === undefined ? {} : { note: declared.note }),\n };\n}\n\n/** The seats a mission may draw on, most willing first, so a planner can take the head of the list. */\nexport function usableSeats(seats: readonly SeatInfo[], policy: SeatPolicy): SeatInfo[] {\n const rank: Record<SeatPosture, number> = { preferred: 0, normal: 1, sparing: 2, off: 3 };\n return seats\n .filter((seat) => stanceFor(seat, policy).usable)\n .sort((a, b) => rank[stanceFor(a, policy).posture] - rank[stanceFor(b, policy).posture]);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { chmodSync, closeSync, mkdirSync, openSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname } from \"node:path\";\nimport type * as Sqlite from \"node:sqlite\";\ntype Database = Sqlite.DatabaseSync;\ntype StatementSync = Sqlite.StatementSync;\nimport { z } from \"zod\";\n/*\n * Required at runtime rather than imported, for one reason: Node prints `ExperimentalWarning: SQLite is an\n * experimental feature` the moment this module is loaded, and ESM resolves every static import before any module\n * body runs. A static import here fires that warning before the CLI has executed a single line, so nothing the\n * CLI does could ever suppress it \u2014 and every `fanout` command opened with two lines of noise about a decision\n * the user did not make and cannot act on.\n *\n * A runtime require happens during evaluation instead, by which time `cli.ts` has installed its filter. The\n * types are the real ones; only the moment of loading changes. `packages/cli/test/quiet.test.ts` fails if this\n * becomes a static import again.\n */\nconst { DatabaseSync } = createRequire(import.meta.url)(\"node:sqlite\") as typeof Sqlite;\n\nimport {\n EVENT_VERSION,\n EventStamp,\n FanoutEvent,\n type FanoutEventInput,\n type StoredEvent,\n} from \"../schema/events.ts\";\n\n/*\n * The ledger is the single source of truth: an append-only SQLite table of validated events.\n * Append-only is enforced by the database, not just by this API: triggers abort any UPDATE, any DELETE, and any\n * INSERT that would replace an existing row (INSERT OR REPLACE deletes the old row without firing DELETE triggers).\n * This guards against rewriting history with ordinary SQL. It is not a defense against someone with raw access to\n * the file: they own it, and `DROP TABLE` or replacing a trigger would still succeed. Opening checks the guards exist.\n * Every row is validated on the way in and again on the way out, so a damaged ledger fails loudly.\n */\n\nconst SCHEMA_VERSION = 1;\n\nconst SCHEMA_V1 = `\nCREATE TABLE IF NOT EXISTS events (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n ts TEXT NOT NULL,\n v INTEGER NOT NULL,\n type TEXT NOT NULL,\n mission_id TEXT,\n run_id TEXT,\n body TEXT NOT NULL CHECK (json_valid(body))\n) STRICT;\nCREATE INDEX IF NOT EXISTS events_by_mission ON events (mission_id, seq);\nCREATE TRIGGER IF NOT EXISTS events_no_update BEFORE UPDATE ON events\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\nCREATE TRIGGER IF NOT EXISTS events_no_delete BEFORE DELETE ON events\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\nCREATE TRIGGER IF NOT EXISTS events_no_replace BEFORE INSERT ON events\n WHEN EXISTS (SELECT 1 FROM events WHERE seq = NEW.seq OR id = NEW.id)\n BEGIN SELECT RAISE(ABORT, 'ledger is append-only'); END;\n`;\n\nconst GUARD_TRIGGERS = [\"events_no_update\", \"events_no_delete\", \"events_no_replace\"] as const;\n\nexport class LedgerError extends Error {\n override name = \"LedgerError\";\n}\n\n/** An event that does not match the schema. Nothing was written. */\nexport class InvalidEventError extends LedgerError {\n override name = \"InvalidEventError\";\n readonly index: number;\n\n constructor(index: number, detail: string) {\n super(`Event ${index} is invalid, nothing was written:\\n${detail}`);\n this.index = index;\n }\n}\n\n/** A ledger or an event written by a newer Fanout. We refuse to guess at it. */\nexport class UnsupportedLedgerError extends LedgerError {\n override name = \"UnsupportedLedgerError\";\n}\n\nexport interface LedgerOptions {\n /** Clock for event timestamps (tests inject a fixed one). */\n now?: () => Date;\n /** Event id generator; must return UUIDs. */\n newId?: () => string;\n /**\n * Called once per event, after it is committed, so a live feed never shows something the ledger might roll back.\n * Whatever it throws is ignored: a listener must not be able to break the record.\n */\n onAppend?: (event: StoredEvent) => void;\n}\n\nexport interface ReadOptions {\n /** Only events with a larger sequence number. */\n afterSeq?: number;\n /** Only events of this mission. */\n missionId?: string;\n /** At most this many events. */\n limit?: number;\n}\n\nconst Row = z.object({\n seq: z.number(),\n id: z.string(),\n ts: z.string(),\n v: z.number(),\n type: z.string(),\n mission_id: z.string().nullable(),\n run_id: z.string().nullable(),\n body: z.string(),\n});\n\nexport class Ledger {\n readonly #db: Database;\n readonly #now: () => Date;\n readonly #newId: () => string;\n readonly #onAppend: ((event: StoredEvent) => void) | undefined;\n readonly #insert: StatementSync;\n readonly #readAll: StatementSync;\n readonly #readMission: StatementSync;\n readonly #lastSeq: StatementSync;\n\n private constructor(db: Database, options: LedgerOptions) {\n this.#db = db;\n this.#now = options.now ?? (() => new Date());\n this.#newId = options.newId ?? randomUUID;\n this.#onAppend = options.onAppend;\n this.#insert = db.prepare(\n \"INSERT INTO events (id, ts, v, type, mission_id, run_id, body) VALUES (?, ?, ?, ?, ?, ?, ?)\",\n );\n this.#readAll = db.prepare(\n \"SELECT seq, id, ts, v, type, mission_id, run_id, body FROM events WHERE seq > ? ORDER BY seq LIMIT ?\",\n );\n this.#readMission = db.prepare(\n \"SELECT seq, id, ts, v, type, mission_id, run_id, body FROM events \" +\n \"WHERE seq > ? AND mission_id = ? ORDER BY seq LIMIT ?\",\n );\n this.#lastSeq = db.prepare(\"SELECT COALESCE(MAX(seq), 0) AS seq FROM events\");\n }\n\n /**\n * Opens (or creates) a ledger. Use \":memory:\" for a throwaway one. On disk, the file is private to the user\n * (mode 600, directory 700).\n */\n static open(path: string, options: LedgerOptions = {}): Ledger {\n const onDisk = path !== \":memory:\";\n if (onDisk) {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n closeSync(openSync(path, \"a\", 0o600));\n chmodSync(path, 0o600);\n }\n const db = new DatabaseSync(path);\n try {\n db.exec(\"PRAGMA busy_timeout = 5000\");\n if (onDisk) db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA synchronous = FULL\");\n migrate(db);\n return new Ledger(db, options);\n } catch (error) {\n db.close();\n throw error;\n }\n }\n\n /** Validates and records one event; returns it with its stamp. */\n append(input: FanoutEventInput): StoredEvent {\n const [stored] = this.appendAll([input]);\n if (stored === undefined) throw new LedgerError(\"append recorded nothing\");\n return stored;\n }\n\n /** Validates every event first, then records them all in one transaction, or none of them. */\n appendAll(inputs: readonly FanoutEventInput[]): StoredEvent[] {\n const events = inputs.map((input, index) => {\n const result = FanoutEvent.safeParse(input);\n if (!result.success) throw new InvalidEventError(index, z.prettifyError(result.error));\n return result.data;\n });\n\n this.#db.exec(\"BEGIN IMMEDIATE\");\n try {\n const stored = events.map((event): StoredEvent => {\n const stamp = EventStamp.omit({ seq: true }).parse({\n v: EVENT_VERSION,\n id: this.#newId(),\n ts: this.#now().toISOString(),\n });\n const result = this.#insert.run(\n stamp.id,\n stamp.ts,\n stamp.v,\n event.type,\n \"missionId\" in event ? event.missionId : null,\n \"runId\" in event ? event.runId : null,\n JSON.stringify(event),\n );\n return { ...event, ...stamp, seq: Number(result.lastInsertRowid) };\n });\n this.#db.exec(\"COMMIT\");\n for (const event of stored) {\n try {\n this.#onAppend?.(event);\n } catch {\n // A listener that throws has a problem of its own; the record is already safe.\n }\n }\n return stored;\n } catch (error) {\n this.#db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n /** Events in sequence order. */\n read(options: ReadOptions = {}): StoredEvent[] {\n const afterSeq = options.afterSeq ?? 0;\n const limit = options.limit ?? -1;\n const rows =\n options.missionId === undefined\n ? this.#readAll.all(afterSeq, limit)\n : this.#readMission.all(afterSeq, options.missionId, limit);\n return rows.map(decode);\n }\n\n /** The sequence number of the last event, or 0 for an empty ledger. */\n lastSeq(): number {\n const row = this.#lastSeq.get();\n return Number(row?.[\"seq\"] ?? 0);\n }\n\n /**\n * Whether this ledger can still be written to.\n *\n * A daemon shutting down closes the ledger while runs may still be in flight, and a process that exits a moment\n * later tries to record how it ended. That is expected, not exceptional, and a caller needs to be able to tell\n * it apart from a ledger that has actually broken \u2014 one means \"we are going away\", the other means \"stop the\n * run, we can no longer record what it is doing\".\n */\n get isOpen(): boolean {\n return this.#db.isOpen;\n }\n\n /** Idempotent: closing twice is what happens when shutdown and a test's cleanup both do the right thing. */\n close(): void {\n if (this.#db.isOpen) this.#db.close();\n }\n}\n\nfunction migrate(db: Database): void {\n const version = userVersion(db);\n if (version > SCHEMA_VERSION) {\n throw new UnsupportedLedgerError(\n `This ledger was written by a newer Fanout (schema ${version}; this one reads ${SCHEMA_VERSION}). ` +\n \"Update Fanout to open it.\",\n );\n }\n if (version < SCHEMA_VERSION) {\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n if (userVersion(db) < SCHEMA_VERSION) {\n db.exec(SCHEMA_V1);\n db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);\n }\n db.exec(\"COMMIT\");\n } catch (error) {\n db.exec(\"ROLLBACK\");\n throw error;\n }\n }\n\n const triggers = new Set(\n db\n .prepare(\"SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'events'\")\n .all()\n .map((row: Record<string, unknown>) => String(row[\"name\"])),\n );\n const missing = GUARD_TRIGGERS.filter((name) => !triggers.has(name));\n if (missing.length > 0) {\n throw new LedgerError(\n `This ledger lost its append-only guard (${missing.join(\", \")}); refusing to use it.`,\n );\n }\n}\n\nfunction userVersion(db: Database): number {\n return Number(db.prepare(\"PRAGMA user_version\").get()?.[\"user_version\"] ?? 0);\n}\n\nfunction decode(raw: unknown): StoredEvent {\n const row = Row.parse(raw);\n if (row.v !== EVENT_VERSION) {\n throw new UnsupportedLedgerError(\n `Event ${row.seq} has version ${row.v}; this Fanout reads version ${EVENT_VERSION}. Update Fanout to read it.`,\n );\n }\n let body: unknown;\n try {\n body = JSON.parse(row.body);\n } catch {\n throw new LedgerError(`Event ${row.seq} is not valid JSON; the ledger is damaged.`);\n }\n const event = FanoutEvent.safeParse(body);\n const stamp = EventStamp.safeParse({ v: row.v, id: row.id, seq: row.seq, ts: row.ts });\n if (!event.success || !stamp.success) {\n const detail = event.error ?? stamp.error;\n throw new LedgerError(\n `Event ${row.seq} does not match the schema; the ledger is damaged.` +\n (detail === undefined ? \"\" : `\\n${z.prettifyError(detail)}`),\n );\n }\n\n // The indexed columns are how events are found; if they disagree with the body, queries would silently lie.\n const routed =\n row.type === event.data.type &&\n row.mission_id === (\"missionId\" in event.data ? event.data.missionId : null) &&\n row.run_id === (\"runId\" in event.data ? event.data.runId : null);\n if (!routed) {\n throw new LedgerError(\n `Event ${row.seq} is indexed as ${row.type} (mission ${row.mission_id ?? \"none\"}, ` +\n `run ${row.run_id ?? \"none\"}) but its body says otherwise; the ledger is damaged.`,\n );\n }\n\n return { ...event.data, ...stamp.data };\n}\n", "import type { DiffStat, MissionLimits, SafetyCheck, SeatInfo, SeatRef } from \"../schema/common.ts\";\nimport type { EventOf, StoredEvent } from \"../schema/events.ts\";\nimport type { PlanGraph } from \"../schema/plan.ts\";\n\n/*\n * Projections are pure folds over the ledger: state(n + 1) = applyEvent(state(n), event n + 1).\n * They never mutate their input, so any intermediate state can be kept, compared or sent to a client.\n * An event that doesn't fit (an unknown mission or run, a duplicate, a sequence out of order) is recorded as an\n * anomaly instead of being silently dropped or crashing the view.\n */\n\nexport type RunPhase = EventOf<\"run.progress\">[\"phase\"];\nexport type UsageUnit = EventOf<\"run.usage\">[\"unit\"];\nexport type RunStatus =\n \"queued\" | \"running\" | \"done\" | \"failed\" | \"killed\" | \"timeout\" | \"merged\" | \"conflict\" | \"dropped\";\n\nexport interface UsageMeter {\n amount: number;\n /** True when any part of the amount is an estimate. */\n estimated: boolean;\n}\nexport type UsageMeters = Partial<Record<UsageUnit, UsageMeter>>;\n\nexport interface RunView {\n runId: string;\n lineId: string;\n seat: SeatRef;\n attempt: number;\n status: RunStatus;\n phase: RunPhase | null;\n /** The agent's own name for this conversation, once it is known. Rework resumes it rather than starting over. */\n sessionId: string | null;\n /**\n * Where the run actually worked, as it reported when it started.\n *\n * Kept rather than derived from the run id, because a reworked run continues in the worktree of the attempt\n * before it \u2014 so the convention `workspaces/<mission>/<runId>` is wrong for exactly the runs that most need\n * finding. A recorded fact beats a naming rule the moment anything reuses anything.\n */\n workdir: string | null;\n /**\n * The process id of the daemon that started this run, or null when it never started or predates the field.\n *\n * Kept so a later reader can ask whether anybody is still watching. A run whose supervisor is gone cannot be\n * running, however the ledger last left it.\n */\n owner: number | null;\n /**\n * The seat the plan asked for, when it is not the seat that ran \u2014 with the reason in the words the router used.\n *\n * Carried on the run rather than left on the mission because everything that shows a run needs it. A row saying\n * `claude` under a plan that said `codex`, with nothing to explain the difference, is the kind of silent\n * substitution that makes someone stop trusting the whole screen.\n */\n movedFrom: { seat: string; reason: string } | null;\n lastTool: { tool: string; summary: string | null } | null;\n /** Files the run touched, sorted, without duplicates. */\n files: string[];\n diffStat: DiffStat | null;\n exitCode: number | null;\n usage: UsageMeters;\n /*\n * Each step of the gate remembers the revision it judged. A merge that applies a different one is applying work\n * nobody in this list actually looked at, which is the single failure the gate exists to prevent.\n */\n review: { verdict: EventOf<\"review.done\">[\"verdict\"]; notes: string; by: SeatRef; revision: string } | null;\n checks: { ok: boolean; summary: string; commands: string[]; revision: string } | null;\n proof: { ok: boolean; failedOnOld: string[]; revision: string } | null;\n approval: { by: EventOf<\"merge.approved\">[\"by\"]; revision: string; note: string | null } | null;\n /** What was merged, and where it landed, so a dependent line can start from a fact. */\n merged: { revision: string; commit: string } | null;\n mergedFiles: string[];\n conflictFiles: string[];\n dropReason: string | null;\n breaches: { limit: string; action: EventOf<\"policy.breach\">[\"action\"] }[];\n queuedSeq: number;\n startedSeq: number | null;\n updatedSeq: number;\n /* The three moments a watcher asks about. Stamped by the ledger, never computed here: see `elapsedMs`. */\n queuedAt: string;\n startedAt: string | null;\n /** When the agent's own work stopped. Review, merge and drop happen after this and do not move it. */\n endedAt: string | null;\n /** The last time this run produced any event at all: its most recent sign of life. */\n updatedAt: string;\n}\n\n/**\n * How long a run has been working, in milliseconds, or `null` if it has not started \u2014 never `0`, because\n * \"not started\" and \"started a moment ago\" are different facts and a watcher deserves to know which.\n *\n * A finished run is measured between its own two stamps, so its duration never changes after the fact. A running\n * one is measured against `now`, so a slow run is visibly slow rather than indistinguishable from a stuck one.\n * That is why the projection stores stamps and not a duration: a stored elapsed time is stale the moment it is read.\n *\n * A clock that has moved backwards (an NTP correction, a laptop waking) clamps to 0 rather than showing a negative\n * age, since a run cannot have started in the future.\n */\nexport function elapsedMs(run: RunView, now: Date): number | null {\n if (run.startedAt === null) return null;\n const from = Date.parse(run.startedAt);\n const to = run.endedAt === null ? now.getTime() : Date.parse(run.endedAt);\n return Math.max(0, to - from);\n}\n\n/**\n * How long a still-running run has said nothing, in milliseconds, or `null` once it has ended \u2014 a finished run is\n * not silent, it is simply over.\n *\n * Elapsed time alone cannot tell a thinking agent from a dead one: both counters climb. The gap since the last\n * event can, which makes this the number worth putting in front of someone deciding whether to wait or to kill.\n *\n * Only a run that is actually working can be silent. A queued run has not been launched and a finished one is\n * simply over; reporting either as \"quiet for 30 minutes\" would raise an alarm about the scheduler doing its job.\n */\nexport function silentMs(run: RunView, now: Date): number | null {\n if (run.startedAt === null || run.endedAt !== null) return null;\n return Math.max(0, now.getTime() - Date.parse(run.updatedAt));\n}\n\nexport interface RouteChange {\n lineId: string;\n from: SeatRef;\n to: SeatRef;\n reason: string;\n seq: number;\n}\n\nexport interface MissionView {\n missionId: string;\n goal: string;\n repo: { root: string; baseCommit: string };\n limits: MissionLimits;\n status: \"planning\" | \"running\" | \"finished\" | \"aborted\";\n plan: PlanGraph | null;\n /** 0 before any plan, then 1, 2, \u2026 for each proposal or revision. */\n planRevision: number;\n /** The safety report for the current plan revision; a new plan clears it, a stale one is refused. */\n safety: { ok: boolean; checks: SafetyCheck[]; planRevision: number } | null;\n runs: Record<string, RunView>;\n runOrder: string[];\n routes: RouteChange[];\n summary: string | null;\n createdSeq: number;\n updatedSeq: number;\n}\n\nexport interface Anomaly {\n seq: number;\n type: string;\n message: string;\n}\n\nexport interface BuddyReview {\n revision: string;\n by: SeatRef;\n findings: string;\n ran: boolean;\n files: string[];\n at: string;\n}\n\nexport interface ClaimCheck {\n revision: string;\n by: SeatRef;\n claims: EventOf<\"claims.checked\">[\"claims\"];\n ran: boolean;\n /** These verdicts were written, not read: the offline demo. Every surface that shows them must say so. */\n simulated: boolean;\n at: string;\n}\n\n/**\n * What a seat has said about its own capacity.\n *\n * `limited` is the seat refusing work; `windows` is how full its named quota windows are when it reports them.\n * Both are the vendor's words, never our arithmetic \u2014 a number we estimated and a number Claude Code measured\n * should never be mistaken for each other in a routing decision.\n */\nexport interface SeatHeadroom {\n limited: { message: string; at: string; resetsAt: string | null } | null;\n windows: Record<string, { utilization: number; resetsAt: string | null }>;\n}\n\nexport interface ProjectionState {\n lastSeq: number;\n crew: Record<string, SeatInfo>;\n /** Per seat, what it last said about running out. Empty for a seat that has never said anything. */\n headroom: Record<string, SeatHeadroom>;\n /** The most recent second-vendor review of the lead's own work, per repository root. */\n buddy: Record<string, BuddyReview>;\n /** The most recent claim check of the lead's own work, per repository root. */\n claims: Record<string, ClaimCheck>;\n usage: Record<string, UsageMeters>;\n missions: Record<string, MissionView>;\n anomalies: Anomaly[];\n}\n\nexport function initialState(): ProjectionState {\n return {\n lastSeq: 0,\n crew: {},\n headroom: {},\n buddy: {},\n claims: {},\n usage: {},\n missions: {},\n anomalies: [],\n };\n}\n\n/** Folds events into a state, starting from an empty one or from a state already projected. */\nexport function project(\n events: Iterable<StoredEvent>,\n from: ProjectionState = initialState(),\n): ProjectionState {\n let state = from;\n for (const event of events) state = applyEvent(state, event);\n return state;\n}\n\nexport function applyEvent(state: ProjectionState, event: StoredEvent): ProjectionState {\n if (event.seq <= state.lastSeq) {\n return withAnomaly(state, event, `sequence ${event.seq} arrived after ${state.lastSeq}; ignored`);\n }\n return { ...reduce(state, event), lastSeq: event.seq };\n}\n\nfunction reduce(state: ProjectionState, event: StoredEvent): ProjectionState {\n switch (event.type) {\n case \"seat.detected\":\n return { ...state, crew: { ...state.crew, [event.seat.id]: event.seat } };\n\n /*\n * Kept per repository and per revision rather than as a list. The only question anyone asks of it is \"has\n * *this* work been read by someone other than its author\", and a history of reviews of older work answers a\n * question nobody is asking while making the answer to this one harder to find.\n */\n /*\n * Kept per repository and per revision, like the buddy review, and for the same reason: the only question\n * anyone asks is what was checked about *this* work, and a history of verdicts on older work buries it.\n */\n case \"claims.checked\":\n return {\n ...state,\n claims: {\n ...state.claims,\n [event.repoRoot]: {\n revision: event.revision,\n by: event.by,\n claims: event.claims,\n ran: event.ran,\n simulated: event.simulated,\n at: event.ts,\n },\n },\n };\n\n /*\n * A seat's own account of its headroom, kept per seat rather than as a history. The only question anyone asks\n * is whether this seat can be used right now; a list of every limit it ever hit answers a different one and\n * buries this.\n */\n case \"seat.limited\":\n return {\n ...state,\n headroom: {\n ...state.headroom,\n [event.seat]: {\n ...(state.headroom[event.seat] ?? { windows: {} }),\n limited: { message: event.message, at: event.ts, resetsAt: event.resetsAt ?? null },\n },\n },\n };\n\n case \"seat.quota\":\n return {\n ...state,\n headroom: {\n ...state.headroom,\n [event.seat]: {\n ...(state.headroom[event.seat] ?? { limited: null }),\n windows: {\n ...(state.headroom[event.seat]?.windows ?? {}),\n [event.window]: { utilization: event.utilization, resetsAt: event.resetsAt ?? null },\n },\n },\n },\n };\n\n case \"buddy.reviewed\":\n return {\n ...state,\n buddy: {\n ...state.buddy,\n [event.repoRoot]: {\n revision: event.revision,\n by: event.by,\n findings: event.findings,\n ran: event.ran,\n files: event.files,\n at: event.ts,\n },\n },\n };\n\n case \"mission.created\": {\n if (Object.hasOwn(state.missions, event.missionId)) {\n return withAnomaly(state, event, `mission \"${event.missionId}\" already exists`);\n }\n const mission: MissionView = {\n missionId: event.missionId,\n goal: event.goal,\n repo: event.repo,\n limits: event.limits,\n status: \"planning\",\n plan: null,\n planRevision: 0,\n safety: null,\n runs: {},\n runOrder: [],\n routes: [],\n summary: null,\n createdSeq: event.seq,\n updatedSeq: event.seq,\n };\n return { ...state, missions: { ...state.missions, [event.missionId]: mission } };\n }\n\n case \"plan.proposed\":\n case \"plan.revised\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n plan: event.plan,\n planRevision: mission.planRevision + 1,\n safety: null,\n }));\n\n case \"safety.report\":\n return updateMission(state, event, (mission) =>\n event.planRevision === mission.planRevision\n ? { ...mission, safety: { ok: event.ok, checks: event.checks, planRevision: event.planRevision } }\n : `safety report is for plan revision ${event.planRevision}, ` +\n `but the mission is at revision ${mission.planRevision}`,\n );\n\n case \"route.changed\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n routes: [\n ...mission.routes,\n { lineId: event.lineId, from: event.from, to: event.to, reason: event.reason, seq: event.seq },\n ],\n }));\n\n case \"mission.finished\":\n return updateMission(state, event, (mission) => ({\n ...mission,\n status: event.outcome === \"completed\" ? \"finished\" : \"aborted\",\n summary: event.summary,\n }));\n\n case \"run.queued\":\n return updateMission(state, event, (mission) => {\n if (Object.hasOwn(mission.runs, event.runId)) return `run \"${event.runId}\" already exists`;\n /*\n * The router records its decision before the run is queued, so the move for this line is already here.\n * The last one wins: a line reworked onto a third seat was moved twice, and the move that explains the\n * seat in front of you is the most recent one.\n */\n const moved = mission.routes.filter((change) => change.lineId === event.lineId).at(-1);\n const run: RunView = {\n runId: event.runId,\n lineId: event.lineId,\n seat: event.seat,\n attempt: event.attempt,\n status: \"queued\",\n phase: null,\n sessionId: null,\n workdir: null,\n owner: null,\n movedFrom: moved?.to.id === event.seat.id ? { seat: moved.from.id, reason: moved.reason } : null,\n lastTool: null,\n files: [],\n diffStat: null,\n exitCode: null,\n usage: {},\n review: null,\n checks: null,\n proof: null,\n approval: null,\n merged: null,\n mergedFiles: [],\n conflictFiles: [],\n dropReason: null,\n breaches: [],\n queuedSeq: event.seq,\n startedSeq: null,\n updatedSeq: event.seq,\n queuedAt: event.ts,\n startedAt: null,\n endedAt: null,\n updatedAt: event.ts,\n };\n return {\n ...mission,\n status: mission.status === \"planning\" ? \"running\" : mission.status,\n runs: { ...mission.runs, [event.runId]: run },\n runOrder: [...mission.runOrder, event.runId],\n };\n });\n\n case \"run.started\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: \"running\",\n startedSeq: event.seq,\n startedAt: event.ts,\n workdir: event.workdir,\n owner: event.owner ?? null,\n }));\n\n case \"run.session\":\n return updateRun(state, event, (run) => ({ ...run, sessionId: event.sessionId }));\n\n case \"run.progress\":\n return updateRun(state, event, (run) => ({ ...run, phase: event.phase }));\n\n case \"run.tool\":\n return updateRun(state, event, (run) => ({\n ...run,\n lastTool: { tool: event.tool, summary: event.summary ?? null },\n files: sortedUnion(run.files, event.files),\n }));\n\n case \"run.usage\": {\n const next = updateRun(state, event, (run) =>\n run.seat.id === event.seat\n ? { ...run, usage: addUsage(run.usage, event) }\n : `usage is charged to seat \"${event.seat}\" but run \"${event.runId}\" is on \"${run.seat.id}\"`,\n );\n if (next.anomalies.length > state.anomalies.length) return next;\n return {\n ...next,\n usage: { ...next.usage, [event.seat]: addUsage(next.usage[event.seat] ?? {}, event) },\n };\n }\n\n case \"run.finished\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: event.status,\n exitCode: event.exitCode,\n diffStat: event.diffStat ?? run.diffStat,\n endedAt: event.ts,\n }));\n\n case \"review.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n review: { verdict: event.verdict, notes: event.notes, by: event.by, revision: event.revision },\n }));\n\n case \"checks.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n checks: {\n ok: event.ok,\n summary: event.summary,\n commands: event.commands,\n revision: event.revision,\n },\n }));\n\n case \"proof.done\":\n return updateRun(state, event, (run) => ({\n ...run,\n proof: { ok: event.ok, failedOnOld: event.failedOnOld, revision: event.revision },\n }));\n\n case \"merge.approved\":\n return updateRun(state, event, (run) => ({\n ...run,\n approval: { by: event.by, revision: event.revision, note: event.note ?? null },\n }));\n\n case \"merge.applied\":\n return updateRun(state, event, (run) => ({\n ...run,\n status: \"merged\",\n mergedFiles: event.files,\n merged: { revision: event.revision, commit: event.commit },\n }));\n\n case \"merge.conflict\":\n return updateRun(state, event, (run) => ({ ...run, status: \"conflict\", conflictFiles: event.files }));\n\n case \"run.dropped\":\n /*\n * `endedAt` matters as much as the status. Without it `silentMs` never stops counting, so a run that was\n * dropped an hour ago reports as quiet \u2014 a run nobody is waiting on, described as one that has gone\n * ominously silent \u2014 and its elapsed time climbs for ever. Seen on a real mission reading\n * `aborted \u00B7 1h 24m \u00B7 1 quiet`, where every part after \"aborted\" was untrue.\n */\n return updateRun(state, event, (run) => ({\n ...run,\n status: \"dropped\",\n dropReason: event.reason,\n endedAt: run.endedAt ?? event.ts,\n }));\n\n case \"policy.breach\":\n return updateRun(state, event, (run) => ({\n ...run,\n breaches: [...run.breaches, { limit: event.limit, action: event.action }],\n }));\n }\n}\n\n/** Applies `change` to the event's mission; a returned string is recorded as an anomaly instead. */\nfunction updateMission(\n state: ProjectionState,\n event: StoredEvent & { missionId: string },\n change: (mission: MissionView) => MissionView | string,\n): ProjectionState {\n const mission = Object.hasOwn(state.missions, event.missionId)\n ? state.missions[event.missionId]\n : undefined;\n if (mission === undefined) return withAnomaly(state, event, `unknown mission \"${event.missionId}\"`);\n const next = change(mission);\n if (typeof next === \"string\") return withAnomaly(state, event, next);\n return { ...state, missions: { ...state.missions, [event.missionId]: { ...next, updatedSeq: event.seq } } };\n}\n\n/** A run that merged or was dropped is finished for good; later run events are anomalies, not a second life. */\nconst TERMINAL: ReadonlySet<RunStatus> = new Set<RunStatus>([\"merged\", \"dropped\"]);\n\nfunction updateRun(\n state: ProjectionState,\n event: StoredEvent & { missionId: string; runId: string },\n change: (run: RunView) => RunView | string,\n): ProjectionState {\n return updateMission(state, event, (mission) => {\n const run = Object.hasOwn(mission.runs, event.runId) ? mission.runs[event.runId] : undefined;\n if (run === undefined) return `unknown run \"${event.runId}\" in mission \"${event.missionId}\"`;\n if (TERMINAL.has(run.status)) {\n return `run \"${event.runId}\" is already ${run.status}; \"${event.type}\" cannot change it`;\n }\n const next = change(run);\n if (typeof next === \"string\") return next;\n return {\n ...mission,\n runs: { ...mission.runs, [event.runId]: { ...next, updatedSeq: event.seq, updatedAt: event.ts } },\n };\n });\n}\n\nfunction withAnomaly(state: ProjectionState, event: StoredEvent, message: string): ProjectionState {\n return { ...state, anomalies: [...state.anomalies, { seq: event.seq, type: event.type, message }] };\n}\n\nfunction addUsage(meters: UsageMeters, event: EventOf<\"run.usage\">): UsageMeters {\n const previous = meters[event.unit];\n return {\n ...meters,\n [event.unit]: {\n amount: (previous?.amount ?? 0) + event.amount,\n estimated: (previous?.estimated ?? false) || event.estimated,\n },\n };\n}\n\nfunction sortedUnion(left: string[], right: string[]): string[] {\n return [...new Set([...left, ...right])].sort();\n}\n", "import { elapsedMs, silentMs, type MissionView, type RunPhase, type RunView } from \"../projections/state.ts\";\n\n/*\n * How a crew reads to a human, in one place.\n *\n * The lead reads this in a chat, the owner reads it in a terminal, and later a browser will draw the same facts.\n * They share this module so the three can never disagree: a mission that looks stalled in one surface and healthy\n * in another is worse than either answer alone.\n *\n * The rule these functions follow is the project's sixth non-negotiable. Every number here is measured, never\n * guessed; what is unknown prints as \"\u2014\" rather than as a zero that reads like a fact; and nothing implies we know\n * how much work is left, because we do not.\n */\n\n/** Below this, an agent that has not spoken is simply thinking, and saying \"quiet\" would cry wolf. */\nconst QUIET_AFTER_MS = 60_000;\n\nconst PHASES: readonly RunPhase[] = [\"reading\", \"coding\", \"testing\", \"reporting\"];\n\nconst DASH = \"\u2014\";\n\n/**\n * A duration a person can read at a glance: `9s`, `6m 38s`, `2h 05m`.\n *\n * Always rounds down. A run that has been going 119 seconds is in its first minute and fifty-ninth second, not its\n * second minute, and rounding up would make every run look slightly further along than it is.\n */\nexport function formatDuration(ms: number): string {\n const total = Math.max(0, Math.floor(ms / 1000));\n const seconds = total % 60;\n const minutes = Math.floor(total / 60) % 60;\n const hours = Math.floor(total / 3600);\n\n if (hours > 0) return `${String(hours)}h ${String(minutes).padStart(2, \"0\")}m`;\n if (minutes > 0) return `${String(minutes)}m ${String(seconds).padStart(2, \"0\")}s`;\n return `${String(seconds)}s`;\n}\n\n/**\n * Which of the four named phases a run is in \u2014 `\u25AA\u25AA\u25AB\u25AB` is \"coding\", the second of four.\n *\n * This is deliberately not a progress bar. We know the phase a run reported; we do not know how much of it is left,\n * and an agent can sit in one phase for a minute or for twenty. A bar that filled with time would be inventing\n * information, which is the one thing these surfaces may never do.\n */\nexport function phaseBar(phase: RunPhase | null): string {\n const reached = phase === null ? 0 : PHASES.indexOf(phase) + 1;\n return \"\u25AA\".repeat(reached) + \"\u25AB\".repeat(PHASES.length - reached);\n}\n\n/** One aligned row per run: what it is, where it is, how long it has been there, and what it has produced. */\nexport function runTable(runs: readonly RunView[], now: Date): string {\n if (runs.length === 0) return ` No runs yet.\\n`;\n\n const rows = runs.map((run) => {\n const elapsed = elapsedMs(run, now);\n const silent = silentMs(run, now);\n const diff =\n run.diffStat === null\n ? run.files.length === 0\n ? \"\"\n : `${String(run.files.length)} file${run.files.length === 1 ? \"\" : \"s\"}`\n : `+${String(run.diffStat.insertions)} \u2212${String(run.diffStat.deletions)}`;\n\n return {\n mark: MARKS[run.status],\n runId: run.runId,\n seat: run.seat.id,\n status: run.status,\n bar: phaseBar(run.phase),\n phase: run.phase ?? \"\",\n elapsed: elapsed === null ? DASH : formatDuration(elapsed),\n diff,\n // A finished run is never \"quiet\": it is not waiting for anything.\n quiet: silent !== null && silent >= QUIET_AFTER_MS ? `quiet ${formatDuration(silent)}` : \"\",\n };\n });\n\n const width = (pick: (row: (typeof rows)[number]) => string): number =>\n Math.max(...rows.map((row) => pick(row).length));\n const w = {\n runId: width((row) => row.runId),\n seat: width((row) => row.seat),\n status: width((row) => row.status),\n elapsed: width((row) => row.elapsed),\n phase: width((row) => row.phase),\n };\n\n return (\n rows\n .map((row) =>\n [\n ` ${row.mark} ${row.runId.padEnd(w.runId)}`,\n row.seat.padEnd(w.seat),\n row.status.padEnd(w.status),\n `${row.bar} ${row.phase.padEnd(w.phase)}`,\n row.elapsed.padStart(w.elapsed),\n row.diff,\n row.quiet,\n ]\n .filter((cell) => cell !== \"\")\n .join(\" \")\n .trimEnd(),\n )\n .join(\"\\n\") + \"\\n\"\n );\n}\n\n/** The whole mission as a watcher wants it: the headline first, then a row per run. */\nexport function missionReport(mission: MissionView, now: Date): string {\n const runs = mission.runOrder.flatMap((runId) => {\n const run = mission.runs[runId];\n return run === undefined ? [] : [run];\n });\n\n const count = (predicate: (run: RunView) => boolean): number => runs.filter(predicate).length;\n const tallies = [\n [count((run) => run.status === \"running\"), \"running\"],\n [count((run) => run.status === \"queued\"), \"queued\"],\n [count((run) => run.status === \"done\"), \"done\"],\n [count((run) => run.status === \"merged\"), \"merged\"],\n [count((run) => run.status === \"dropped\"), \"dropped\"],\n [\n count((run) => run.status === \"failed\" || run.status === \"killed\" || run.status === \"timeout\"),\n \"ended badly\",\n ],\n ] as const;\n\n const headline = [\n mission.missionId,\n mission.status,\n ...tallies.filter(([n]) => n > 0).map(([n, label]) => `${String(n)} ${label}`),\n ].join(\" \u00B7 \");\n\n return `${headline}\\n${runTable(runs, now)}`;\n}\n\nconst MARKS: Record<RunView[\"status\"], string> = {\n queued: \"\u25CC\",\n running: \"\u25CF\",\n done: \"\u2713\",\n merged: \"\u2713\",\n failed: \"\u2717\",\n killed: \"\u2717\",\n timeout: \"\u2717\",\n conflict: \"!\",\n dropped: \"\u00B7\",\n};\n", "import type { PlanLine } from \"../schema/plan.ts\";\nimport type { RunView } from \"../projections/state.ts\";\n\n/*\n * Whether a piece of work may be merged, and if not, exactly what is missing.\n *\n * This is the smallest and most important function in the product. Everything else \u2014 worktrees, adapters, the\n * ledger, the mission view \u2014 exists so that this can be asked honestly about a specific diff. It is a pure\n * function of recorded facts on purpose: it cannot read a file, run a command, or be talked round by an agent's\n * account of its own work, and a replay of the ledger reaches the same verdict months later.\n *\n * The rule it enforces is one sentence: nothing merges that review, checks, proof and a person did not all agree\n * on, about the *same revision*. Each of those is easy alone. Tying them to one revision is the part that makes\n * \"reviewed and checked\" mean something, because a worktree can change between being judged and being applied.\n */\n\nexport type BlockerCode =\n | \"not-finished\"\n | \"already-settled\"\n | \"no-review\"\n | \"review-rejected\"\n | \"review-asked-for-rework\"\n | \"review-stale\"\n | \"no-checks\"\n | \"checks-failed\"\n | \"checks-stale\"\n | \"no-proof\"\n | \"proof-failed\"\n | \"proof-stale\"\n | \"not-approved\"\n | \"approval-stale\";\n\nexport interface Blocker {\n code: BlockerCode;\n /** Written for the person who has to do something about it, not for a log. */\n message: string;\n}\n\nexport interface Readiness {\n ready: boolean;\n /** Empty when ready. Ordered the way a person would work through them. */\n blockers: Blocker[];\n}\n\n/**\n * Can `run`'s work at `revision` be merged?\n *\n * `line` is the plan line the run came from: it says whether a proof is required, which is a decision made when\n * the mission was planned rather than after an agent has explained why its change is obviously fine.\n */\nexport function mergeReadiness(run: RunView, line: PlanLine, revision: string): Readiness {\n const blockers: Blocker[] = [];\n const add = (code: BlockerCode, message: string): void => {\n blockers.push({ code, message });\n };\n\n // A run that is already merged or dropped is not a candidate; a second merge would double-apply its diff.\n if (run.status === \"merged\" || run.status === \"dropped\" || run.status === \"conflict\") {\n add(\"already-settled\", `This run is already ${run.status}.`);\n return { ready: false, blockers };\n }\n if (run.status !== \"done\") {\n add(\"not-finished\", `The agent has not finished: the run is ${run.status}.`);\n }\n\n if (run.review === null) {\n add(\"no-review\", \"Nobody has reviewed this diff.\");\n } else if (run.review.verdict === \"reject\") {\n add(\"review-rejected\", \"Review rejected this work.\");\n } else if (run.review.verdict === \"rework\") {\n add(\"review-asked-for-rework\", \"Review asked for changes, which have not come back.\");\n } else if (run.review.revision !== revision) {\n add(\"review-stale\", staleMessage(\"review\"));\n }\n\n if (run.checks === null) {\n add(\"no-checks\", \"The project's checks have not been run against this diff.\");\n } else if (!run.checks.ok) {\n add(\"checks-failed\", `The project's checks failed: ${run.checks.summary}`);\n } else if (run.checks.revision !== revision) {\n add(\"checks-stale\", staleMessage(\"checks\"));\n }\n\n /*\n * The fourth non-negotiable, in code. A fix without a test that fails on the old code is a claim that something\n * is fixed, and a claim is exactly what this gate exists not to accept. Only lines the plan marked as fixes are\n * held to it: demanding a failing-first test of a new feature would teach everyone to lie about the flag.\n */\n if (line.fixesBug) {\n if (run.proof === null) {\n add(\"no-proof\", \"This line fixes a bug, so it needs a test proven to fail on the old code.\");\n } else if (!run.proof.ok) {\n add(\"proof-failed\", \"The new test did not fail on the old code, so it does not prove the fix.\");\n } else if (run.proof.revision !== revision) {\n add(\"proof-stale\", staleMessage(\"proof\"));\n }\n }\n\n if (run.approval === null) {\n add(\"not-approved\", \"Nobody has approved this merge.\");\n } else if (run.approval.revision !== revision) {\n add(\"approval-stale\", staleMessage(\"approval\"));\n }\n\n return { ready: blockers.length === 0, blockers };\n}\n\n/**\n * A stale step is not a failure, and saying \"review failed\" about one would send someone hunting for a problem\n * that is not there. The work moved after it was judged; it has to be judged again.\n */\nfunction staleMessage(step: string): string {\n return `The work changed after ${step}, so ${step} was about a different diff. Run it again.`;\n}\n\n/** The two blockers that are the person's own yes, rather than something they are waiting on. */\nconst APPROVAL_CODES: ReadonlySet<BlockerCode> = new Set([\"not-approved\", \"approval-stale\"]);\n\n/**\n * What stands between this work and someone being *able* to approve it.\n *\n * Approval is the one blocker a person clears by deciding, so asking `mergeReadiness` whether work may be approved\n * answers \"no\" forever: the missing approval is itself a blocker. This removes that circle and nothing else.\n *\n * It exists so an approve button can refuse honestly. A button that recorded a yes for work nobody had reviewed\n * would put a real approval \u2014 the strongest evidence in the ledger \u2014 behind a diff that had earned none of it, and\n * the merge would then refuse for reasons the person had already been told did not apply.\n */\nexport function blocksApproval(readiness: Readiness): Blocker[] {\n return readiness.blockers.filter((blocker) => !APPROVAL_CODES.has(blocker.code));\n}\n\n/** One line a person can read, for when the whole list is too much: the first thing standing in the way. */\nexport function firstBlocker(readiness: Readiness): string | null {\n return readiness.blockers[0]?.message ?? null;\n}\n", "import type { SeatInfo } from \"../schema/common.ts\";\nimport type { SeatPolicy } from \"../schema/policy.ts\";\nimport { stanceFor } from \"../schema/policy.ts\";\nimport type { SeatHeadroom } from \"../projections/state.ts\";\n\n/*\n * Choosing which seat does a line, and being able to say why.\n *\n * A pure function over recorded facts, like the merge gate's judgement and for the same reason: a routing\n * decision that cannot be replayed is a decision nobody can argue with later. Every answer carries its reason in\n * words, because \"moved to claude\" is not something a person can act on and \"codex reached its usage limit, and\n * you marked grok sparing\" is.\n *\n * Three things decide it, in this order:\n *\n * 1. Can the seat work at all \u2014 installed, a version we verified, signed in, and not currently refusing?\n * 2. Did the owner say anything about spending it? A seat marked `off` is never chosen, however free it is.\n * 3. Of what is left, the plan's own choice first, then the owner's preference.\n *\n * Nothing here guesses at cost. We know a plan's name, not its price, and inventing an ordering from that would\n * be exactly the kind of confident arithmetic this project refuses elsewhere.\n */\n\nexport interface RoutingInput {\n /** The seat the plan asked for. */\n wanted: string;\n seats: readonly SeatInfo[];\n policy: SeatPolicy;\n headroom: Readonly<Record<string, SeatHeadroom>>;\n /** Now, for deciding whether a limit has since reset. */\n now: Date;\n}\n\nexport type Routing =\n | { kind: \"keep\"; seat: string }\n | { kind: \"move\"; seat: string; from: string; reason: string }\n | { kind: \"stuck\"; from: string; reason: string };\n\n/**\n * Why a seat cannot take work right now, or null when it can.\n *\n * `asFallback` is stricter, and the difference matters. When the plan named a seat, the person writing the plan\n * chose it and a CLI that simply cannot report its own sign-in \u2014 Grok and Kimi have no status command at all \u2014 is\n * not a reason to overrule them; we find out by running it. Moving work *onto* a seat is our decision rather than\n * theirs, and spending someone's subscription on a guess about whether it will even answer is not a decision to\n * make on their behalf.\n */\nexport function unavailable(\n seat: SeatInfo,\n policy: SeatPolicy,\n headroom: SeatHeadroom | undefined,\n now: Date,\n asFallback = false,\n): string | null {\n const stance = stanceFor(seat, policy);\n if (stance.posture === \"off\") return `you set it to off (${stance.reason})`;\n if (seat.version === null) return \"it is not installed\";\n if (!seat.supported) return `version ${seat.version} is outside what its adapter was verified against`;\n if (seat.signedIn === \"no\") return \"it is not signed in\";\n if (asFallback && seat.signedIn === \"unknown\") {\n return \"its CLI cannot tell us whether it is signed in, and this is not the seat you asked for\";\n }\n\n const limited = headroom?.limited;\n if (limited != null) {\n /*\n * A limit that has passed its reset is not a limit. Believing an expired one forever would strand a seat\n * that came back an hour ago, and the reset time is the seat's own word rather than our guess.\n */\n if (limited.resetsAt === null || Date.parse(limited.resetsAt) > now.getTime()) {\n return `it said: ${limited.message}`;\n }\n }\n return null;\n}\n\n/**\n * Where this line should run.\n *\n * Keeps the plan's choice whenever it can, because the plan was written by someone who knew what the line needed\n * \u2014 a different model is a different result, not a free substitution, and moving work silently would hide that.\n */\nexport function routeLine(input: RoutingInput): Routing {\n const byId = new Map(input.seats.map((seat) => [seat.id, seat]));\n const asked = byId.get(input.wanted);\n\n const why = (seat: SeatInfo, asFallback: boolean): string | null =>\n unavailable(seat, input.policy, input.headroom[seat.id], input.now, asFallback);\n\n if (asked !== undefined && why(asked, false) === null) return { kind: \"keep\", seat: asked.id };\n\n const blocked =\n asked === undefined\n ? `${input.wanted} is not a seat on this machine`\n : `${input.wanted}: ${why(asked, false) ?? \"unavailable\"}`;\n\n /*\n * Ordered by what the owner said, then by name so the same crew always routes the same way. A stable answer\n * matters more than a clever one: a mission that picks a different seat on every run is a mission whose\n * results cannot be compared.\n */\n const rank = { preferred: 0, normal: 1, sparing: 2, off: 3 };\n const candidates = input.seats\n .filter((seat) => seat.id !== input.wanted && why(seat, true) === null)\n .sort((a, b) => {\n const order = rank[stanceFor(a, input.policy).posture] - rank[stanceFor(b, input.policy).posture];\n return order !== 0 ? order : a.id.localeCompare(b.id);\n });\n\n const chosen = candidates[0];\n if (chosen === undefined) {\n return { kind: \"stuck\", from: input.wanted, reason: `${blocked}, and no other seat can take it` };\n }\n\n const stance = stanceFor(chosen, input.policy);\n const note =\n stance.posture === \"sparing\"\n ? ` \u2014 ${chosen.id} is marked sparing${stance.note === undefined ? \"\" : `: ${stance.note}`}`\n : \"\";\n return { kind: \"move\", seat: chosen.id, from: input.wanted, reason: `${blocked}${note}` };\n}\n", "import { readFileSync } from \"node:fs\";\n\n/*\n * What version of Fanout this actually is.\n *\n * Read from the package that is running, never written down twice. Two hand-maintained strings had already drifted\n * apart from the packages they named and from each other \u2014 the CLI said 0.5.0-dev and the MCP server said\n * 0.6.0-dev while both shipped from 0.7.0 \u2014 which is a small lie until someone reports a bug against a version\n * that never existed.\n */\n\n/**\n * The version in a package's own `package.json`, given any file inside that package.\n *\n * Pass `import.meta.url` from the caller. It walks up looking for the manifest, which is what makes it work\n * identically from `src/main.ts` in a checkout and from `dist/main.js` inside `node_modules`.\n */\nexport function versionOf(fromUrl: string): string {\n let directory = new URL(\".\", fromUrl);\n for (let depth = 0; depth < 8; depth++) {\n try {\n const text = readFileSync(new URL(\"package.json\", directory), \"utf8\");\n const parsed: unknown = JSON.parse(text);\n const version = (parsed as { version?: unknown }).version;\n if (typeof version === \"string\") return version;\n } catch {\n // Not this directory. Keep walking up until the package root or we run out of patience.\n }\n const parent = new URL(\"..\", directory);\n if (parent.href === directory.href) break;\n directory = parent;\n }\n // Saying so beats inventing a number: an unknown version is a fact, and a wrong one sends someone hunting.\n return \"unknown\";\n}\n", "{\n \"id\": \"claude\",\n \"displayName\": \"Claude Code\",\n \"binary\": \"claude\",\n \"supportedVersions\": \">=2.0 <3\",\n \"tier\": \"supported\",\n \"capabilities\": {\n \"resume\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--resume\",\n \"{session}\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ]\n },\n \"fork\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--resume\",\n \"{session}\",\n \"--fork-session\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ]\n },\n \"review\": null,\n \"plan\": {\n \"probe\": [\"auth\", \"status\", \"--json\"],\n \"format\": \"json\",\n \"keep\": [\"loggedIn\", \"subscriptionType\"],\n \"planField\": \"subscriptionType\"\n }\n },\n \"headless\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--permission-prompts\",\n \"none\"\n ],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--output-format stream-json\",\n \"format\": \"jsonl\"\n },\n \"models\": [\"fable\", \"opus\", \"sonnet\", \"haiku\"],\n \"efforts\": [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n \"permissionModes\": {\n \"readOnly\": \"plan\",\n \"edit\": \"acceptEdits\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": [\"auth\", \"status\"],\n \"okPattern\": \"\\\"loggedIn\\\"\\\\s*:\\\\s*true\",\n \"noPattern\": \"\\\"loggedIn\\\"\\\\s*:\\\\s*false\"\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"5h\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through `claude -p`, the documented non-interactive mode, with permission prompts denied rather than bypassed. No credential handling: sign-in state comes from `claude auth status`. Claude is an opt-in worker (DECISIONS 0009) because the lead already spends this subscription on planning and review. Billing to watch: Anthropic announced moving headless use to a separate Agent SDK credit on 2026-06-15 and then paused it, so today it draws from subscription limits; if that changes, this field becomes \\\"credit\\\".\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Claude Code's stream-json feed, as recorded from version 2.1.269 (fixtures/basic.jsonl).\n *\n * It is the most generous of the streams we drive: an init line naming the session, a rate-limit line with real\n * window utilization, thinking-token estimates as the turn goes, assistant messages whose content blocks carry the\n * tool calls, and a final result line with the answer and the turn's token usage.\n *\n * Only the fields we use are described and unknown extras are allowed, so a new field never breaks a run. The\n * union is discriminated on `type` so that narrowing one line tells us exactly what we may read from it; the\n * several kinds of `system` line differ by `subtype`, which is why its fields are optional here.\n */\n\nexport const ToolUse = z.looseObject({\n type: z.literal(\"tool_use\"),\n name: z.string(),\n input: z\n .looseObject({\n file_path: z.string().optional(),\n path: z.string().optional(),\n notebook_path: z.string().optional(),\n command: z.string().optional(),\n })\n .optional(),\n});\nexport type ToolUse = z.infer<typeof ToolUse>;\n\nconst Window = z.looseObject({ utilization: z.number(), resetsAt: z.number().optional() });\n\nexport const ClaudeLine = z.discriminatedUnion(\"type\", [\n z.looseObject({\n type: z.literal(\"system\"),\n subtype: z.string(),\n session_id: z.string().optional(),\n estimated_tokens_delta: z.number().optional(),\n }),\n z.looseObject({\n type: z.literal(\"rate_limit_event\"),\n rate_limit_info: z.looseObject({\n status: z.string(),\n rateLimitType: z.string().optional(),\n resetsAt: z.number().optional(),\n unifiedWindows: z.record(z.string(), Window).optional(),\n }),\n }),\n z.looseObject({\n type: z.literal(\"assistant\"),\n message: z.looseObject({ content: z.array(z.looseObject({ type: z.string() })) }),\n }),\n z.looseObject({ type: z.literal(\"user\") }),\n z.looseObject({\n type: z.literal(\"result\"),\n subtype: z.string().optional(),\n is_error: z.boolean().optional(),\n result: z.string().optional(),\n usage: z\n .looseObject({ input_tokens: z.number().optional(), output_tokens: z.number().optional() })\n .optional(),\n }),\n]);\nexport type ClaudeLine = z.infer<typeof ClaudeLine>;\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type AdapterSignal,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { CodexLine, type CodexItem } from \"./protocol.ts\";\n\n/*\n * The OpenAI Codex seat, driven through `codex exec` \u2014 the mode its own documentation describes for\n * non-interactive use. Nothing here touches credentials: sign-in belongs to the CLI, and we only ever ask it.\n *\n * Its stream (verified against 0.154.0, recorded in fixtures/basic.jsonl) is JSONL:\n * thread.started the session id\n * item.started/completed with an item of type command_execution | file_change | agent_message | error\n * turn.completed token usage for the turn\n *\n * Two details a hand-written parser would get wrong, both found by recording a real run: file changes carry\n * absolute paths, which we make repo-relative; and Codex emits non-fatal `error` items that must reach the lead\n * rather than being swallowed.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst LIMIT = /usage limit|rate limit|quota|too many requests/i;\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\n\nexport function createCodexAdapter(): SeatAdapter {\n return { id: manifest.id, command, parse, resume };\n}\n\n/**\n * Continues the thread that produced the diff, with the reviewer's notes as the next turn.\n *\n * Verified against codex 0.154.0 on a throwaway repository: the resumed run keeps the same thread id and answered\n * a follow-up that said \"the file you just created\" correctly, which is the whole reason to resume rather than\n * re-explain. The argv is the manifest's, so a change to what was verified is a change to data.\n */\nfunction resume(context: AdapterContext & { sessionId: string }): LaunchSpec {\n const template = manifest.capabilities.resume;\n if (template === null) throw new Error(\"this codex manifest declares no resume command\");\n\n const args = fill(template.args, {\n \"{workdir}\": context.workdir,\n \"{sandbox}\": manifest.permissionModes.edit,\n \"{session}\": context.sessionId,\n \"{prompt}\": context.line.prompt,\n ...(context.line.seat.model === undefined ? {} : { \"{model}\": context.line.seat.model }),\n });\n return {\n argv: [manifest.binary, ...args] as [string, ...string[]],\n cwd: context.workdir,\n env: context.baseEnv,\n };\n}\n\n/**\n * Fills the manifest's template, dropping a placeholder nobody supplied along with the flag in front of it.\n *\n * Without this, no model chosen means `-m \"\"`, and Codex answers `The '' model is not supported`. Found by running\n * it rather than by reading it.\n */\nfunction fill(template: readonly string[], values: Readonly<Record<string, string>>): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n if (/^\\{[a-z]+\\}$/.test(argument) && !Object.hasOwn(values, argument)) {\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction command(context: AdapterContext): LaunchSpec {\n const { line } = context;\n const readOnly = line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{workdir}\", context.workdir)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit)\n .replace(\"{report}\", context.reportPath)\n .replace(\"{prompt}\", line.prompt),\n );\n\n // An auditor works on an export with no .git, which `codex exec` otherwise refuses to run in.\n if (readOnly) args.splice(args.length - 1, 0, \"--skip-git-repo-check\");\n if (line.seat.model !== undefined) args.splice(1, 0, \"-m\", line.seat.model);\n if (line.seat.effort !== undefined) args.splice(1, 0, \"-c\", `model_reasoning_effort=\"${line.seat.effort}\"`);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n}\n\nfunction parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = CodexLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const run = { missionId: context.missionId, runId: context.runId };\n const line = parsed.data;\n\n switch (line.type) {\n case \"thread.started\":\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reading\" }],\n signals: [{ kind: \"session\", id: line.thread_id }],\n };\n\n case \"turn.started\":\n return { events: [], signals: [] };\n\n case \"turn.completed\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.usage.input_tokens + line.usage.output_tokens,\n unit: \"tokens\",\n estimated: false,\n },\n { type: \"run.progress\", ...run, phase: \"reporting\" },\n ],\n signals: [],\n };\n\n case \"item.started\":\n case \"item.completed\":\n return item(line.type, line.item, context, run);\n }\n}\n\nfunction item(\n lineType: \"item.started\" | \"item.completed\",\n value: CodexItem,\n context: AdapterContext,\n run: { missionId: string; runId: string },\n): ParseResult {\n const completed = lineType === \"item.completed\";\n\n switch (value.type) {\n case \"error\": {\n const signal: AdapterSignal = LIMIT.test(value.message)\n ? { kind: \"limit\", message: value.message }\n : { kind: \"error\", message: value.message };\n return { events: [], signals: [signal] };\n }\n\n case \"agent_message\":\n // Every agent message is a report; the last one before the run ends is the run's report.\n return completed\n ? { events: [], signals: [{ kind: \"report\", text: value.text }] }\n : { events: [], signals: [] };\n\n case \"file_change\": {\n if (!completed) return { events: [], signals: [] };\n const files = value.changes.map((change) => repoRelative(change.path, context.workdir));\n const kinds = [...new Set(value.changes.map((change) => change.kind))].join(\", \");\n const events: FanoutEventInput[] = [\n { type: \"run.progress\", ...run, phase: \"coding\" },\n { type: \"run.tool\", ...run, tool: \"edit\", summary: kinds, files },\n ];\n return { events, signals: [] };\n }\n\n case \"command_execution\": {\n if (!completed) return { events: [], signals: [] };\n const summary = value.command.slice(0, 500);\n const events: FanoutEventInput[] = [\n ...(TEST_COMMAND.test(value.command)\n ? [{ type: \"run.progress\" as const, ...run, phase: \"testing\" as const }]\n : []),\n { type: \"run.tool\", ...run, tool: \"shell\", summary, files: [] },\n ];\n return { events, signals: [] };\n }\n }\n}\n\n/** Codex reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "{\n \"id\": \"codex\",\n \"displayName\": \"OpenAI Codex\",\n \"binary\": \"codex\",\n \"supportedVersions\": \">=0.150.0 <1.0.0\",\n \"tier\": \"supported\",\n \"capabilities\": {\n \"resume\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"resume\",\n \"{session}\",\n \"--json\",\n \"-m\",\n \"{model}\",\n \"{prompt}\"\n ]\n },\n \"fork\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"fork\",\n \"{session}\",\n \"--json\",\n \"-m\",\n \"{model}\",\n \"{prompt}\"\n ]\n },\n \"review\": {\n \"args\": [\n \"exec\",\n \"-C\",\n \"{workdir}\",\n \"-s\",\n \"{sandbox}\",\n \"review\",\n \"--uncommitted\",\n \"--json\",\n \"-m\",\n \"{model}\"\n ]\n },\n \"plan\": null\n },\n \"headless\": {\n \"args\": [\"exec\", \"--json\", \"-C\", \"{workdir}\", \"-s\", \"{sandbox}\", \"-o\", \"{report}\", \"{prompt}\"],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--json\",\n \"format\": \"jsonl\"\n },\n \"models\": [\"gpt-6-astra\", \"gpt-5.6-sol\", \"gpt-5.6-terra\", \"gpt-5.6-luna\", \"gpt-5.5\", \"gpt-5.3-codex-spark\"],\n \"efforts\": [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n \"permissionModes\": {\n \"readOnly\": \"read-only\",\n \"edit\": \"workspace-write\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": [\"login\", \"status\"],\n \"okPattern\": \"^\\\\s*Logged in\\\\b\",\n \"noPattern\": \"^\\\\s*Not logged in\\\\b\"\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"unknown\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through `codex exec`, the documented non-interactive mode. No credential handling: sign-in state is read with `codex login status`. Network behaviour inside the sandbox is the CLI's own and we do not claim to control it, so the safety report warns rather than promising isolation.\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Codex's own JSONL stream, as recorded from version 0.154.0 (fixtures/basic.jsonl). Only the fields we use are\n * described, and unknown extras are allowed: a vendor adding a field must never break a run. A line that does not\n * match at all becomes an `unparsed` signal rather than a guess.\n */\n\nconst FileChange = z.object({\n id: z.string(),\n type: z.literal(\"file_change\"),\n changes: z.array(z.object({ path: z.string(), kind: z.string() })),\n status: z.string().optional(),\n});\n\nconst CommandExecution = z.object({\n id: z.string(),\n type: z.literal(\"command_execution\"),\n command: z.string(),\n aggregated_output: z.string().optional(),\n exit_code: z.number().nullable().optional(),\n status: z.string().optional(),\n});\n\nconst AgentMessage = z.object({ id: z.string(), type: z.literal(\"agent_message\"), text: z.string() });\n\nconst ErrorItem = z.object({ id: z.string(), type: z.literal(\"error\"), message: z.string() });\n\nconst Item = z.discriminatedUnion(\"type\", [FileChange, CommandExecution, AgentMessage, ErrorItem]);\n\nexport const CodexLine = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"thread.started\"), thread_id: z.string() }),\n z.object({ type: z.literal(\"turn.started\") }),\n z.object({\n type: z.literal(\"turn.completed\"),\n usage: z.object({ input_tokens: z.number(), output_tokens: z.number() }),\n }),\n z.object({ type: z.literal(\"item.started\"), item: Item }),\n z.object({ type: z.literal(\"item.completed\"), item: Item }),\n]);\nexport type CodexLine = z.infer<typeof CodexLine>;\nexport type CodexItem = z.infer<typeof Item>;\n", "import { isAbsolute, relative } from \"node:path\";\nimport {\n AdapterManifest,\n type AdapterContext,\n type FanoutEventInput,\n type LaunchSpec,\n type ParseResult,\n type SeatAdapter,\n} from \"fanout-core\";\nimport manifestJson from \"../manifest.json\" with { type: \"json\" };\nimport { GrokLine } from \"./protocol.ts\";\n\n/*\n * The Grok Build seat, driven through its documented single-turn mode (`grok -p`) with structured output.\n *\n * Its stream (verified against 1.0.13, recorded in fixtures/basic.jsonl) differs from Codex's in two ways that\n * shape this adapter. Prose arrives as a stream of one-word deltas, so the run's report has to be assembled here\n * rather than read from a file \u2014 Grok writes none. And the session id arrives only in the final `end` line, so a\n * run is half over before we can name its session.\n */\n\nexport const manifest: AdapterManifest = AdapterManifest.parse(manifestJson);\n\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|cargo test|go test|npm run|pnpm run)\\b/;\nconst WRITING = /write|edit|replace|create|patch/i;\n\nexport function createGrokAdapter(): SeatAdapter {\n /** Grok streams its prose in pieces; a run's report is all of them, in order, joined. */\n const spoken = new Map<string, string>();\n /*\n * Runs that have already seen the tool-list handshake.\n *\n * Grok announces its available commands several times in one run \u2014 four, in the stream we recorded \u2014 and each\n * announcement is the CLI listing what it can do, not a statement about what it is doing. Treating every one of\n * them as \"reading\" walked the phase backwards from `coding` mid-run, which on the mission view looks exactly\n * like an agent that gave up and started over.\n */\n const greeted = new Set<string>();\n\n return {\n id: manifest.id,\n\n command(context: AdapterContext): LaunchSpec {\n const readOnly = context.line.role === \"auditor\";\n const args = manifest.headless.args.map((argument) =>\n argument\n .replace(\"{prompt}\", context.line.prompt)\n .replace(\"{sandbox}\", readOnly ? manifest.permissionModes.readOnly : manifest.permissionModes.edit)\n .replace(\"{workdir}\", context.workdir),\n );\n if (context.line.seat.model !== undefined) args.push(\"-m\", context.line.seat.model);\n if (context.line.seat.effort !== undefined) args.push(\"--reasoning-effort\", context.line.seat.effort);\n\n return { argv: [manifest.binary, ...args], cwd: context.workdir, env: { ...context.baseEnv } };\n },\n\n parse(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = GrokLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n\n switch (line.type) {\n case \"available_commands\": {\n // The first one is genuine news: the run is up and reading. The rest are the same handshake repeated.\n if (greeted.has(context.runId)) return { events: [], signals: [] };\n greeted.add(context.runId);\n return { events: [{ type: \"run.progress\", ...run, phase: \"reading\" }], signals: [] };\n }\n\n case \"thought\":\n return { events: [], signals: [] };\n\n case \"text\":\n spoken.set(context.runId, (spoken.get(context.runId) ?? \"\") + line.data);\n return { events: [], signals: [] };\n\n case \"tool_call\": {\n const tool = line.toolName ?? line.kind ?? \"tool\";\n const files = toolFiles(line.rawInput, line.locations, context.workdir);\n const command = line.rawInput?.command ?? \"\";\n const events: FanoutEventInput[] = [\n {\n type: \"run.progress\",\n ...run,\n phase: TEST_COMMAND.test(command) ? \"testing\" : WRITING.test(tool) ? \"coding\" : \"reading\",\n },\n {\n type: \"run.tool\",\n ...run,\n tool,\n ...(command === \"\" ? {} : { summary: command.slice(0, 500) }),\n files,\n },\n ];\n return { events, signals: [] };\n }\n\n case \"tool_call_update\":\n return { events: [], signals: [] };\n\n case \"usage\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.usage.input_tokens + line.usage.output_tokens,\n unit: \"tokens\",\n estimated: false,\n },\n ],\n signals: [],\n };\n\n case \"end\": {\n const report = spoken.get(context.runId) ?? \"\";\n spoken.delete(context.runId);\n greeted.delete(context.runId);\n return {\n events: [{ type: \"run.progress\", ...run, phase: \"reporting\" }],\n signals: [\n ...(line.sessionId === undefined ? [] : [{ kind: \"session\" as const, id: line.sessionId }]),\n ...(report === \"\" ? [] : [{ kind: \"report\" as const, text: report }]),\n ],\n };\n }\n }\n },\n };\n}\n\nfunction toolFiles(\n rawInput: { file_path?: string | undefined; path?: string | undefined } | undefined,\n locations: { path: string }[] | undefined,\n workdir: string,\n): string[] {\n const paths = [rawInput?.file_path, rawInput?.path, ...(locations ?? []).map((location) => location.path)];\n const seen = new Set<string>();\n for (const path of paths) {\n if (path !== undefined && path !== \"\") seen.add(repoRelative(path, workdir));\n }\n return [...seen];\n}\n\n/** Grok reports absolute paths; our events speak in paths relative to the run's working directory. */\nfunction repoRelative(path: string, workdir: string): string {\n if (!isAbsolute(path)) return path;\n const inside = relative(workdir, path);\n return inside === \"\" || inside.startsWith(\"..\") ? path : inside;\n}\n", "{\n \"id\": \"grok\",\n \"displayName\": \"Grok Build\",\n \"binary\": \"grok\",\n \"supportedVersions\": \">=1.0 <2\",\n \"tier\": \"community\",\n \"capabilities\": {\n \"resume\": null,\n \"fork\": null,\n \"review\": null,\n \"plan\": null\n },\n \"headless\": {\n \"args\": [\n \"-p\",\n \"{prompt}\",\n \"--output-format\",\n \"streaming-json\",\n \"--permission-mode\",\n \"{sandbox}\",\n \"--cwd\",\n \"{workdir}\"\n ],\n \"stdin\": \"closed\"\n },\n \"stream\": {\n \"flag\": \"--output-format streaming-json\",\n \"format\": \"jsonl\"\n },\n \"models\": [],\n \"efforts\": [\"low\", \"medium\", \"high\"],\n \"permissionModes\": {\n \"readOnly\": \"plan\",\n \"edit\": \"acceptEdits\"\n },\n \"network\": {\n \"canDisable\": false,\n \"flag\": null\n },\n \"signIn\": {\n \"probe\": null,\n \"okPattern\": null,\n \"noPattern\": null\n },\n \"usage\": {\n \"probe\": null,\n \"window\": \"unknown\"\n },\n \"billing\": \"subscription\",\n \"terms\": {\n \"reviewedAt\": \"2026-09-11\",\n \"notes\": \"Driven only through the documented single-turn mode (-p) with structured output. No credential handling: sign-in belongs to `grok login`, and the CLI offers no status command, so the crew reports sign-in as unknown rather than guessing. It writes no report file of its own, so the run's report is the text it streamed.\"\n },\n \"status\": \"alpha\"\n}\n", "import { z } from \"zod\";\n\n/*\n * Grok Build's streaming-json feed, as recorded from version 1.0.13 (fixtures/basic.jsonl). It is a session-update\n * stream: prose and reasoning arrive as many small deltas, tools as a call and later updates, usage once per turn,\n * and the session id only at the very end.\n *\n * Only the fields we use are described and unknown extras are allowed: a vendor adding a field must not break a run.\n */\n\nconst Location = z.looseObject({ path: z.string() });\n\nconst RawInput = z.looseObject({\n file_path: z.string().optional(),\n path: z.string().optional(),\n command: z.string().optional(),\n});\n\nexport const GrokLine = z.discriminatedUnion(\"type\", [\n z.looseObject({ type: z.literal(\"available_commands\") }),\n z.looseObject({ type: z.literal(\"thought\"), data: z.string() }),\n z.looseObject({ type: z.literal(\"text\"), data: z.string() }),\n z.looseObject({\n type: z.literal(\"tool_call\"),\n toolCallId: z.string(),\n toolName: z.string().optional(),\n kind: z.string().optional(),\n rawInput: RawInput.optional(),\n locations: z.array(Location).optional(),\n }),\n z.looseObject({\n type: z.literal(\"tool_call_update\"),\n toolCallId: z.string(),\n status: z.string().nullable().optional(),\n locations: z.array(Location).optional(),\n }),\n z.looseObject({\n type: z.literal(\"usage\"),\n usage: z.looseObject({ input_tokens: z.number(), output_tokens: z.number() }),\n }),\n z.looseObject({\n type: z.literal(\"end\"),\n stopReason: z.string().optional(),\n sessionId: z.string().optional(),\n }),\n]);\nexport type GrokLine = z.infer<typeof GrokLine>;\n", "import { spawn, type ChildProcess } from \"node:child_process\";\nimport { closeSync, openSync, writeSync } from \"node:fs\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport type { OutputStream, RunExit, RunHandle, SuperviseOptions } from \"./types.ts\";\n\nexport function supervise(options: SuperviseOptions): RunHandle {\n const began = performance.now();\n let resolveDone: ((result: RunExit) => void) | undefined;\n const done = new Promise<RunExit>((resolve) => {\n resolveDone = resolve;\n });\n let child: ChildProcess | undefined;\n let log: number | undefined;\n let logBytes = 0;\n let logTruncated = false;\n let startDetected = false;\n let settled = false;\n let closed = false;\n let exitCode: number | null = null;\n let signal: NodeJS.Signals | null = null;\n let stopping: \"failed\" | \"killed\" | \"timeout\" | undefined;\n let error: string | undefined;\n let startTimer: NodeJS.Timeout | undefined = undefined;\n let timeoutTimer: NodeJS.Timeout | undefined = undefined;\n let killTimer: NodeJS.Timeout | undefined;\n\n function clearDeadlines(): void {\n clearTimeout(startTimer);\n clearTimeout(timeoutTimer);\n }\n\n function finish(): void {\n if (settled) return;\n settled = true;\n clearDeadlines();\n clearTimeout(killTimer);\n if (log !== undefined) {\n try {\n closeSync(log);\n } catch (cause) {\n error ??= message(cause);\n stopping ??= \"failed\";\n }\n log = undefined;\n }\n resolveDone?.({\n status: stopping ?? (exitCode === 0 ? \"done\" : \"failed\"),\n exitCode,\n signal,\n startDetected,\n durationMs: performance.now() - began,\n ...(error === undefined ? {} : { error }),\n });\n }\n\n function signalGroup(nextSignal: NodeJS.Signals | 0): boolean {\n if (child?.pid === undefined) return false;\n try {\n process.kill(-child.pid, nextSignal);\n return true;\n } catch (cause) {\n if (!(cause instanceof Error && \"code\" in cause && cause.code === \"ESRCH\")) {\n error ??= message(cause);\n }\n return false;\n }\n }\n\n function stop(status: \"failed\" | \"killed\" | \"timeout\", reason?: string): void {\n if (settled || stopping !== undefined) return;\n stopping = status;\n if (reason !== undefined) error ??= reason;\n clearDeadlines();\n signalGroup(\"SIGTERM\");\n // Keep escalation alive even if the group leader exits before its descendants.\n killTimer = setTimeout(() => {\n if (signalGroup(0)) signalGroup(\"SIGKILL\");\n killTimer = undefined;\n if (closed) finish();\n }, options.killGraceMs);\n }\n\n function fail(cause: unknown): void {\n error ??= message(cause);\n stop(\"failed\");\n }\n\n function writeLog(text: string): void {\n if (log === undefined) return;\n const bytes = Buffer.from(text);\n let offset = 0;\n while (offset < bytes.length) {\n offset += writeSync(log, bytes, offset, bytes.length - offset);\n }\n }\n\n function line(text: string, stream: OutputStream): void {\n try {\n if (!logTruncated) {\n const entry = `${stream === \"stderr\" ? \"[stderr] \" : \"\"}${text}\\n`;\n const size = Buffer.byteLength(entry);\n if (logBytes + size <= options.maxLogBytes) {\n writeLog(entry);\n logBytes += size;\n } else {\n // Keep complete log lines; the single marker is metadata beyond the payload cap.\n logTruncated = true;\n writeLog(`[log truncated at ${options.maxLogBytes} bytes]\\n`);\n }\n }\n } catch (cause) {\n fail(cause);\n }\n try {\n options.onLine(text, stream);\n } catch (cause) {\n fail(cause);\n }\n }\n\n const handle: RunHandle = {\n runId: options.runId,\n get pid() {\n return child?.pid;\n },\n done,\n kill(reason: string) {\n stop(\"killed\", reason);\n return done;\n },\n };\n\n try {\n log = openSync(options.logPath, \"a\", 0o600);\n child = spawn(options.spec.argv[0], options.spec.argv.slice(1), {\n cwd: options.spec.cwd,\n env: { ...options.spec.env },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: true,\n });\n } catch (cause) {\n error = message(cause);\n stopping = \"failed\";\n finish();\n return handle;\n }\n\n startTimer = setTimeout(() => {\n error = `No stdout received within ${options.startTimeoutMs} ms`;\n stop(\"failed\");\n }, options.startTimeoutMs);\n timeoutTimer = setTimeout(() => {\n stop(\"timeout\");\n }, options.timeoutMs);\n\n const stdout = splitLines(options.maxLineBytes, (text) => {\n line(text, \"stdout\");\n });\n const stderr = splitLines(options.maxLineBytes, (text) => {\n line(text, \"stderr\");\n });\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n if (chunk.length > 0 && !startDetected && stopping === undefined) {\n startDetected = true;\n clearTimeout(startTimer);\n try {\n options.onStarted();\n } catch (cause) {\n fail(cause);\n }\n }\n stdout.push(chunk);\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr.push(chunk);\n });\n child.stdout?.on(\"error\", fail);\n child.stderr?.on(\"error\", fail);\n child.once(\"error\", fail);\n child.once(\"exit\", (code, exitSignal) => {\n exitCode = code;\n signal = exitSignal;\n });\n child.once(\"close\", (code, exitSignal) => {\n closed = true;\n exitCode = child.pid === undefined ? null : code;\n signal = exitSignal;\n stdout.end();\n stderr.end();\n if (stopping === undefined || killTimer === undefined || !signalGroup(0)) finish();\n });\n return handle;\n}\n\nfunction message(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n\n/** Retain only the bounded prefix, even for an arbitrarily long unterminated line. */\nfunction splitLines(limit: number, emit: (line: string) => void) {\n let parts: Buffer[] = [];\n let retained = 0;\n let length = 0;\n let lastByte: number | undefined;\n\n function append(bytes: Buffer): void {\n if (bytes.length === 0) return;\n lastByte = bytes[bytes.length - 1];\n length = Math.min(limit + 2, length + bytes.length);\n const keep = Math.min(bytes.length, Math.max(0, limit - retained));\n if (keep > 0) {\n parts.push(Buffer.from(bytes.subarray(0, keep)));\n retained += keep;\n }\n }\n\n function flush(newline: boolean): void {\n const size = length - (newline && lastByte === 13 ? 1 : 0);\n const prefix = Buffer.concat(parts, retained).subarray(0, size);\n const truncated = size > limit;\n const text = truncated ? new StringDecoder(\"utf8\").write(prefix) : prefix.toString(\"utf8\");\n parts = [];\n retained = 0;\n length = 0;\n lastByte = undefined;\n emit(`${text}${truncated ? \" \u2026[truncated]\" : \"\"}`);\n }\n\n return {\n push(chunk: Buffer): void {\n let offset = 0;\n let newline = chunk.indexOf(10, offset);\n while (newline !== -1) {\n append(chunk.subarray(offset, newline));\n flush(true);\n offset = newline + 1;\n newline = chunk.indexOf(10, offset);\n }\n append(chunk.subarray(offset));\n },\n end(): void {\n if (length > 0) flush(false);\n },\n };\n}\n", "/*\n * The environment an agent CLI receives. It needs enough to run and to find its own sign-in (PATH, HOME, locale),\n * and nothing else: API keys, tokens and cloud credentials in the user's shell never reach an agent.\n * A CLI that needs a vendor variable (for example CODEX_HOME) gets it from its adapter, by name.\n */\n\nexport const ALLOWED_ENV = [\n \"PATH\",\n \"HOME\",\n \"USER\",\n \"LOGNAME\",\n \"SHELL\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"TMPDIR\",\n \"TZ\",\n \"XDG_CONFIG_HOME\",\n \"XDG_DATA_HOME\",\n \"XDG_CACHE_HOME\",\n \"XDG_STATE_HOME\",\n] as const;\n\nexport function baseEnv(\n source: Readonly<Record<string, string | undefined>> = process.env,\n): Record<string, string> {\n const env: Record<string, string> = {};\n for (const name of ALLOWED_ENV) {\n const value = source[name];\n if (value !== undefined && value !== \"\") env[name] = value;\n }\n return env;\n}\n", "import { existsSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport {\n InvalidEventError,\n type AdapterContext,\n type AdapterSignal,\n type DiffStat,\n type FanoutEventInput,\n type Ledger,\n type SeatAdapter,\n} from \"fanout-core\";\nimport { supervise } from \"./supervisor/supervise.ts\";\nimport type { RunExit, RunHandle, SuperviseOptions } from \"./supervisor/types.ts\";\n\n/*\n * One run, end to end: the adapter builds the command, the supervisor runs it, the adapter reads its output, and the\n * ledger records what happened. Adapters may only report what their agent is doing (progress, tools, usage) for\n * their own run; anything else they emit is refused and surfaced as an `unparsed` signal.\n * If the ledger itself cannot record an event, the run is stopped: nothing runs unrecorded.\n */\n\nexport type RunLimits = Pick<\n SuperviseOptions,\n \"startTimeoutMs\" | \"timeoutMs\" | \"killGraceMs\" | \"maxLogBytes\" | \"maxLineBytes\"\n>;\n\nexport interface StartRunOptions {\n ledger: Ledger;\n adapter: SeatAdapter;\n context: AdapterContext;\n logPath: string;\n limits: RunLimits;\n /** The adapter's hints (session id, limit reached, final report, unparsed lines), in order. */\n onSignal?: (signal: AdapterSignal) => void;\n /**\n * Read from the run's workspace once it has stopped, so `run.finished` carries what actually changed rather\n * than what the agent said it changed. Failing to read it never fails the run.\n */\n collectDiff?: () => Promise<DiffStat | undefined>;\n /**\n * Continue an earlier conversation instead of starting one.\n *\n * The run keeps the same worktree, so the agent sees the code it wrote and the notes about it together. Set\n * only when the seat can resume at all; `startRun` refuses rather than quietly starting over, because a rework\n * that silently forgot everything would spend a subscription to lose the context it was spent on.\n */\n resumeSession?: string;\n}\n\n/**\n * How this run is started: fresh, or as the next turn of a conversation that already exists.\n *\n * A seat asked to resume that cannot is an error rather than a fresh run. Rework's whole value is that the agent\n * still holds its own reasoning about the code, and silently discarding that while still charging for it is the\n * worst of both outcomes.\n */\nfunction specFor(adapter: SeatAdapter, context: AdapterContext, sessionId?: string) {\n if (sessionId === undefined) return adapter.command(context);\n if (adapter.resume === undefined) {\n throw new Error(`${adapter.id} cannot resume a session, so this work cannot be reworked in place`);\n }\n return adapter.resume({ ...context, sessionId });\n}\n\nexport interface ActiveRun {\n readonly handle: RunHandle;\n /** Resolves once `run.finished` is recorded; rejects only if the ledger failed. */\n readonly finished: Promise<RunExit>;\n}\n\nconst ADAPTER_EVENT_TYPES: ReadonlySet<string> = new Set([\"run.progress\", \"run.tool\", \"run.usage\"]);\n\nexport function startRun(options: StartRunOptions): ActiveRun {\n const { ledger, adapter, context } = options;\n const ids = { missionId: context.missionId, runId: context.runId };\n const spec = specFor(adapter, context, options.resumeSession);\n\n // The run's own directories are the daemon's to make: the supervisor opens the log before it spawns anything,\n // and an agent should never have to create the place its report goes. Private to the user, like the ledger.\n mkdirSync(dirname(options.logPath), { recursive: true, mode: 0o700 });\n mkdirSync(dirname(context.reportPath), { recursive: true, mode: 0o700 });\n // Callbacks may fire before `supervise` returns, so they reach the handle through this holder.\n const control: { handle?: RunHandle } = {};\n let ledgerFailure: Error | undefined;\n\n const signal = (value: AdapterSignal): void => {\n /*\n * Written down the moment the agent names its conversation. Rework replies into the session that wrote the\n * diff rather than re-explaining the work to a stranger, and the run most likely to need rework is the one\n * that ended badly \u2014 so this cannot wait until the run finishes tidily.\n */\n if (value.kind === \"session\") {\n record({ type: \"run.session\", missionId: ids.missionId, runId: ids.runId, sessionId: value.id });\n }\n /*\n * A seat running out belongs to the account, not to this mission \u2014 the next mission needs to know as much as\n * this one does. Recorded here rather than left as a hint the runner may or may not act on, because a limit\n * nobody wrote down is a limit the crew rediscovers by spending on it again.\n */\n if (value.kind === \"limit\") {\n record({\n type: \"seat.limited\",\n seat: context.line.seat.id,\n message: value.message,\n ...(value.resetsAt === undefined ? {} : { resetsAt: value.resetsAt }),\n });\n }\n if (value.kind === \"quota\") {\n record({\n type: \"seat.quota\",\n seat: context.line.seat.id,\n window: value.window,\n utilization: value.utilization,\n ...(value.resetsAt === undefined ? {} : { resetsAt: value.resetsAt }),\n });\n }\n options.onSignal?.(value);\n };\n\n const record = (event: FanoutEventInput): boolean => {\n if (ledgerFailure !== undefined) return false;\n try {\n ledger.append(event);\n return true;\n } catch (error) {\n if (error instanceof InvalidEventError) return false;\n ledgerFailure = error instanceof Error ? error : new Error(String(error));\n void control.handle?.kill(\"the ledger could not record an event\");\n return false;\n }\n };\n\n /** What went wrong with the ledger, if anything. A function so a caller's narrowing cannot go stale. */\n const ledgerBroke = (): Error | undefined => ledgerFailure;\n\n const belongsToRun = (event: FanoutEventInput): boolean =>\n ADAPTER_EVENT_TYPES.has(event.type) &&\n \"runId\" in event &&\n event.missionId === ids.missionId &&\n event.runId === ids.runId;\n\n const handle = supervise({\n runId: context.runId,\n spec,\n logPath: options.logPath,\n ...options.limits,\n onStarted: () => {\n // The owner is this daemon's pid: how a later reader tells a run that is still going from one whose\n // supervisor died with the session that started it.\n record({ type: \"run.started\", ...ids, workdir: spec.cwd, argv: spec.argv, owner: process.pid });\n },\n onLine: (line, stream) => {\n const result =\n stream === \"stdout\" ? adapter.parse(line, context) : adapter.parseStderr?.(line, context);\n if (result === undefined) return;\n for (const event of result.events) {\n if (!belongsToRun(event) || !record(event)) {\n if (ledgerFailure === undefined) signal({ kind: \"unparsed\", line });\n break;\n }\n }\n result.signals.forEach(signal);\n },\n });\n\n control.handle = handle;\n\n const finished = handle.done.then(async (exit) => {\n if (ledgerFailure !== undefined) throw ledgerFailure;\n const diffStat = await options.collectDiff?.().catch(() => undefined);\n /*\n * The last event, and the only one recorded after the run is already over. That distinction is the whole\n * reason it is handled separately from `record`: a ledger that closes while a run is *working* must stop it \u2014\n * work nobody can record is a subscription being spent into the void \u2014 but a ledger that closes between the\n * agent exiting and this line has nothing left to stop. The daemon is shutting down and the run is finished.\n *\n * This used to be a bare `ledger.append`, which made the single most important event a run produces the only\n * one with no handling at all. It threw out of this promise with nobody holding it. CI found it on macOS as\n * two errors printed beside 695 passing tests \u2014 the shape of a bug a green suite hides.\n */\n if (ledger.isOpen) {\n record({\n type: \"run.finished\",\n ...ids,\n status: exit.status,\n exitCode: exit.exitCode,\n ...(existsSync(context.reportPath) ? { reportPath: context.reportPath } : {}),\n ...(diffStat === undefined ? {} : { diffStat }),\n });\n /*\n * Read through a call rather than the variable: `record` assigns it from inside a closure, and narrowing\n * from the check at the top of this promise would otherwise make the line below dead code to the compiler\n * and live code at runtime \u2014 which lint caught, correctly.\n */\n const broke = ledgerBroke();\n if (broke !== undefined) throw broke;\n }\n return exit;\n });\n\n return { handle, finished };\n}\n", "import { execFile } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { mkdir, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { pathInScope, type DiffStat, type PlanLine } from \"fanout-core\";\nimport { deniedFiles, DenyListError } from \"./deny.ts\";\nimport { git, lines, zeroSeparated, GitError } from \"./git.ts\";\nimport type {\n RunDiff,\n Workspace,\n WorkspaceManager,\n WorkspaceManagerOptions,\n WorkspaceRequest,\n} from \"./types.ts\";\n\n/*\n * Isolation, done by the daemon so that no agent has to be trusted with it.\n *\n * An editing run gets `git worktree add` on a throwaway branch from the mission's base commit: its own working\n * directory, its own branch, nothing of the user's. An auditor gets an export of the same commit with no `.git`,\n * so it cannot commit, switch branch, read history or reach another run. Ignored files are in neither, because\n * neither is a copy of the user's working tree.\n *\n * What git ignores is not enough on its own: a repository can track a `.env` or a private key. Those are checked\n * for before anything is created, and a workspace is refused rather than quietly exposing them.\n */\n\nconst runProcess = promisify(execFile);\n\nexport { DEFAULT_DENY_LIST, DenyListError } from \"./deny.ts\";\n\nexport function createWorkspaceManager(options: WorkspaceManagerOptions): WorkspaceManager {\n const { repoRoot, workspaceRoot } = options;\n const inRepo = { cwd: repoRoot };\n\n const missionDir = (missionId: string): string => join(workspaceRoot, missionId);\n const runDir = (missionId: string, runId: string): string => join(missionDir(missionId), runId);\n\n const create = async (request: WorkspaceRequest): Promise<Workspace> => {\n const { missionId, runId, baseCommit, line } = request;\n const denied = await deniedFiles(repoRoot, baseCommit, options.denyList);\n if (denied.length > 0) throw new DenyListError(denied);\n\n const path = runDir(missionId, runId);\n await rm(path, { recursive: true, force: true });\n await mkdir(missionDir(missionId), { recursive: true, mode: 0o700 });\n\n if (line.role === \"auditor\") {\n // An export, not a clone: no .git, so nothing to commit into and no history to read.\n await mkdir(path, { recursive: true, mode: 0o700 });\n await git(\n [\"archive\", \"--format=tar\", `--output=${join(missionDir(missionId), `${runId}.tar`)}`, baseCommit],\n inRepo,\n );\n await extractTar(join(missionDir(missionId), `${runId}.tar`), path);\n await rm(join(missionDir(missionId), `${runId}.tar`), { force: true });\n return { missionId, runId, kind: \"archive\", path, branch: null, baseCommit };\n }\n\n const branch = `fanout/${missionId}/${runId}`;\n await git([\"worktree\", \"add\", \"--quiet\", \"-b\", branch, path, baseCommit], inRepo);\n return { missionId, runId, kind: \"worktree\", path, branch, baseCommit };\n };\n\n const collect = async (workspace: Workspace, line: PlanLine): Promise<RunDiff> => {\n if (workspace.kind === \"archive\") {\n return { stat: { files: 0, insertions: 0, deletions: 0 }, patch: \"\", newFiles: [], outsideScope: [] };\n }\n const inWorkspace = { cwd: workspace.path };\n // Against the base commit, not the index: this stays true even if the agent staged or committed, which it\n // must not do but might. `-z` is the only safe listing for paths with spaces or newlines in them.\n const base = workspace.baseCommit;\n const numstat = lines(\n (await git([\"diff\", \"--numstat\", \"-z\", base, \"--\"], inWorkspace)).replaceAll(\"\\0\", \"\\n\"),\n );\n const newFiles = zeroSeparated(\n await git([\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], inWorkspace),\n ).sort();\n const patch = await git([\"diff\", \"--binary\", base, \"--\"], inWorkspace);\n\n const changed = numstat.map((entry) => entry.split(\"\\t\")[2] ?? \"\");\n const stat = numstat.reduce<DiffStat>(\n (total, entry) => {\n const [added, removed] = entry.split(\"\\t\");\n return {\n files: total.files + 1,\n insertions: total.insertions + count(added),\n deletions: total.deletions + count(removed),\n };\n },\n { files: 0, insertions: 0, deletions: 0 },\n );\n\n const touched = [...changed, ...newFiles].filter((file) => file !== \"\");\n const outsideScope = touched\n .filter((file) => !line.scope.write.some((pattern) => pathInScope(file, pattern)))\n .sort();\n\n /*\n * A new file has no tracked diff, so `git diff` says nothing about it at all. Counting it towards the file\n * total while leaving its lines at zero is how a run that wrote a whole file came to report \"+0 \u22120\" \u2014 which\n * reads as a run that did nothing, in the one number a person glances at.\n */\n const added = newFiles.reduce((total, file) => total + linesIn(join(workspace.path, file)), 0);\n\n return {\n stat: {\n files: stat.files + newFiles.length,\n insertions: stat.insertions + added,\n deletions: stat.deletions,\n },\n patch,\n newFiles,\n outsideScope,\n };\n };\n\n /**\n * How many lines a new file adds.\n *\n * Read rather than asked of git, because asking would mean a subprocess per file or writing to the index of a\n * worktree we are only inspecting. Binary files count as nothing: git itself reports `-` instead of a number\n * for them, and turning bytes into a line count would be inventing a figure to put in front of someone.\n */\n const linesIn = (path: string): number => {\n let contents: Buffer;\n try {\n contents = readFileSync(path);\n } catch {\n // Listed a moment ago and gone now: report nothing rather than guess at what it held.\n return 0;\n }\n if (contents.includes(0)) return 0;\n if (contents.length === 0) return 0;\n const newlines = contents.filter((byte) => byte === 0x0a).length;\n // A file that does not end in a newline still ends in a line.\n return contents.at(-1) === 0x0a ? newlines : newlines + 1;\n };\n\n const remove = async (workspace: Workspace): Promise<void> => {\n if (workspace.kind === \"worktree\") {\n await ignoreMissing(git([\"worktree\", \"remove\", \"--force\", workspace.path], inRepo));\n if (workspace.branch !== null) await ignoreMissing(git([\"branch\", \"-D\", workspace.branch], inRepo));\n }\n await rm(workspace.path, { recursive: true, force: true });\n };\n\n const removeAll = async (missionId: string): Promise<void> => {\n const prefix = `fanout/${missionId}/`;\n const branches = lines(\n await git([\"for-each-ref\", \"--format=%(refname:short)\", `refs/heads/${prefix}`], inRepo),\n );\n await rm(missionDir(missionId), { recursive: true, force: true });\n await ignoreMissing(git([\"worktree\", \"prune\"], inRepo));\n for (const branch of branches) await ignoreMissing(git([\"branch\", \"-D\", branch], inRepo));\n };\n\n return { create, collect, remove, removeAll };\n}\n\nfunction count(value: string | undefined): number {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : 0; // git writes \"-\" for a binary file\n}\n\nasync function extractTar(archive: string, into: string): Promise<void> {\n await runProcess(\"tar\", [\"-x\", \"-f\", archive, \"-C\", into], { windowsHide: true });\n}\n\nasync function ignoreMissing(work: Promise<unknown>): Promise<void> {\n try {\n await work;\n } catch (error) {\n if (!(error instanceof GitError)) throw error;\n }\n}\n", "import { pathInScope } from \"fanout-core\";\nimport { git, zeroSeparated } from \"./git.ts\";\n\n/*\n * What an agent must never receive. Git ignoring a file is not enough on its own: a repository can track a `.env`\n * or a private key, and a worktree of that commit would hand it over. This is checked against the commit itself,\n * before any workspace exists, and it is the same list the safety report shows the user.\n */\n\nexport const DEFAULT_DENY_LIST: readonly string[] = [\n \"**/.env\",\n \"**/.env.*\",\n \"**/*.pem\",\n \"**/*.key\",\n \"**/*.p12\",\n \"**/*.pfx\",\n \"**/*.keystore\",\n \"**/id_rsa*\",\n \"**/id_ed25519*\",\n \"**/.npmrc\",\n \"**/.netrc\",\n \"**/.pgpass\",\n \"**/.ssh/**\",\n \"**/.aws/**\",\n \"**/.gnupg/**\",\n \"**/secrets.*\",\n \"**/credentials\",\n \"**/credentials.*\",\n \"**/service-account*.json\",\n];\n\n/** A workspace was not created because the repository holds something an agent must not see. */\nexport class DenyListError extends Error {\n override name = \"DenyListError\";\n readonly files: readonly string[];\n\n constructor(files: readonly string[]) {\n super(\n `The repository tracks ${files.length} file(s) an agent must never receive: ${files.slice(0, 5).join(\", \")}` +\n `${files.length > 5 ? \", \u2026\" : \"\"}. Remove them from the commit, or narrow the deny-list on purpose.`,\n );\n this.files = files;\n }\n}\n\n/** Tracked files at a commit that the deny-list covers, in the repository's own order. */\nexport async function deniedFiles(\n repoRoot: string,\n baseCommit: string,\n denyList: readonly string[] = DEFAULT_DENY_LIST,\n): Promise<string[]> {\n const tracked = zeroSeparated(\n await git([\"ls-tree\", \"-r\", \"-z\", \"--name-only\", baseCommit], { cwd: repoRoot }),\n );\n return tracked.filter((file) => denyList.some((pattern) => pathInScope(file, pattern)));\n}\n", "export type * from \"./supervisor/types.ts\";\nexport { supervise } from \"./supervisor/supervise.ts\";\nexport { ALLOWED_ENV, baseEnv } from \"./env.ts\";\nexport { startRun, type ActiveRun, type RunLimits, type StartRunOptions } from \"./run.ts\";\n\nexport type * from \"./workspace/types.ts\";\nexport { createWorkspaceManager } from \"./workspace/manager.ts\";\nexport { DEFAULT_DENY_LIST, DenyListError, deniedFiles } from \"./workspace/deny.ts\";\nexport { git, GitError, lines, zeroSeparated, type GitOptions } from \"./workspace/git.ts\";\n\nexport type * from \"./safety/types.ts\";\nexport { safetyReport, type RepositoryState, type SafetyDependencies } from \"./safety/report.ts\";\nexport { createSafetyDependencies, type SafetyDependencyOptions } from \"./safety/dependencies.ts\";\n\nexport { detectSeats, type CommandResult, type DetectOptions } from \"./detector/detect.ts\";\nexport { compareVersions, parseVersion, satisfies, type Version } from \"./detector/version.ts\";\n\nexport {\n createMissionRunner,\n PlanRefused,\n type LaunchRequest,\n type MissionHandle,\n type MissionOutcome,\n type MissionRunnerOptions,\n type RunOutcome,\n} from \"./mission/runner.ts\";\n\nexport * from \"./api/link.ts\";\nexport { startApi, LEAD_EVENTS, type ApiOptions, type ApiServer } from \"./api/server.ts\";\nexport { originAllowed, readOrCreateToken, tokenMatches } from \"./api/token.ts\";\nexport * from \"./mission/reconcile.ts\";\nexport * from \"./policy/route.ts\";\nexport * from \"./policy/seats.ts\";\nexport * from \"./gate/revision.ts\";\nexport * from \"./gate/buddy.ts\";\nexport * from \"./gate/claims.ts\";\nexport * from \"./gate/run-seat.ts\";\nexport { missionViewHtml } from \"./api/view.ts\";\nexport * from \"./gate/checks.ts\";\nexport * from \"./gate/proof.ts\";\nexport * from \"./gate/merge.ts\";\nexport * from \"./gate/rework.ts\";\n", "import { pathInScope, validatePlan, type LaunchSpec, type PlanGraph, type SafetyCheck } from \"fanout-core\";\nimport type { SafetyCheckId, SafetyInput, SafetyReport } from \"./types.ts\";\n\n/*\n * The gate between a plan and running it.\n *\n * Every check is computed here from the plan, the repository and the seats as detected \u2014 never from an agent's\n * word \u2014 and every one names the lines it concerns, so \"why can't I launch?\" always has a specific answer.\n * A check that cannot be evaluated says so and warns; it never passes quietly, because a gate that looks green\n * when it is not is worse than no gate.\n */\n\n/** Flags that hand an agent the machine. A command carrying one never launches. */\nconst FORBIDDEN_FLAGS: readonly { flag: string; why: string }[] = [\n { flag: \"--dangerously-bypass-approvals-and-sandbox\", why: \"it turns off the sandbox and every approval\" },\n { flag: \"--dangerously-skip-permissions\", why: \"it bypasses every permission check\" },\n { flag: \"--dangerously-bypass-hook-trust\", why: \"it runs untrusted hooks\" },\n { flag: \"danger-full-access\", why: \"it gives the run full access to the machine\" },\n { flag: \"bypassPermissions\", why: \"it bypasses every permission check\" },\n { flag: \"--always-approve\", why: \"it approves whatever the agent asks for\" },\n { flag: \"--yolo\", why: \"it auto-approves tool calls\" },\n { flag: \"--approve-for-me\", why: \"it approves the agent's requests automatically\" },\n];\n\nexport interface RepositoryState {\n /** Where the repository is now. */\n head: string;\n /** Paths with uncommitted changes, relative to the repository root. */\n dirty: readonly string[];\n}\n\nexport interface SafetyDependencies {\n /** Tracked files at the base commit that the deny-list covers. */\n deniedFiles: (baseCommit: string) => Promise<readonly string[]>;\n /** The repository as it is right now. */\n repositoryState: () => Promise<RepositoryState>;\n}\n\nexport async function safetyReport(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyReport> {\n const checks: SafetyCheck[] = [\n ...planChecks(input.plan),\n await secretsCheck(input, deps),\n ...seatChecks(input),\n ...commandChecks(input),\n concurrencyCheck(input),\n await baseCommitCheck(input, deps),\n ];\n\n return {\n ok: checks.every((check) => check.ok || check.severity === \"warn\"),\n planRevision: input.planRevision,\n checks,\n dryRun: input.plan.lines.map((line) => ({\n lineId: line.id,\n seat: line.seat.id,\n argv: input.commands[line.id]?.argv ?? [],\n cwd: input.commands[line.id]?.cwd ?? \"\",\n })),\n };\n}\n\nfunction check(\n id: SafetyCheckId,\n ok: boolean,\n severity: SafetyCheck[\"severity\"],\n message: string,\n lineIds?: string[],\n): SafetyCheck {\n return { id, ok, severity, message, ...(lineIds === undefined ? {} : { lineIds }) };\n}\n\n/** Two of the eight come straight from the plan schema: scopes must be declared, and must not overlap. */\nfunction planChecks(plan: PlanGraph): SafetyCheck[] {\n const issues = validatePlan(plan);\n const overlaps = issues.filter((issue) => issue.code === \"scope_overlap\");\n const structural = issues.filter((issue) => issue.code !== \"scope_overlap\");\n\n return [\n check(\n \"scopes-disjoint\",\n overlaps.length === 0,\n \"block\",\n overlaps.length === 0\n ? \"No two lines that can run at the same time write the same path.\"\n : overlaps.map((issue) => issue.message).join(\" \"),\n overlaps.flatMap((issue) => issue.lineIds),\n ),\n check(\n \"scopes-declared\",\n structural.length === 0,\n \"block\",\n structural.length === 0\n ? \"Every line declares where it may write, and the plan's dependencies make sense.\"\n : structural.map((issue) => issue.message).join(\" \"),\n structural.flatMap((issue) => issue.lineIds),\n ),\n ];\n}\n\nasync function secretsCheck(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyCheck> {\n const denied = await deps.deniedFiles(input.repo.baseCommit);\n return check(\n \"secrets-excluded\",\n denied.length === 0,\n \"block\",\n denied.length === 0\n ? \"Nothing the deny-list covers is tracked at the base commit; ignored files are in no workspace.\"\n : `The repository tracks ${denied.length} file(s) an agent must never receive: ${denied\n .slice(0, 5)\n .join(\", \")}${denied.length > 5 ? \", \u2026\" : \"\"}.`,\n );\n}\n\nfunction seatChecks(input: SafetyInput): SafetyCheck[] {\n const missing: string[] = [];\n const unsupported: string[] = [];\n const signedOut: string[] = [];\n const unknown: string[] = [];\n\n for (const line of input.plan.lines) {\n const seat = input.seats[line.seat.id];\n if (seat === undefined) missing.push(line.id);\n else if (!seat.supported) unsupported.push(line.id);\n else if (seat.signedIn === \"no\") signedOut.push(line.id);\n else if (seat.signedIn === \"unknown\") unknown.push(line.id);\n }\n\n const blocked = [...missing, ...unsupported, ...signedOut];\n const reasons = [\n missing.length > 0 ? `not installed (${missing.join(\", \")})` : \"\",\n unsupported.length > 0 ? `an unsupported version (${unsupported.join(\", \")})` : \"\",\n signedOut.length > 0 ? `not signed in (${signedOut.join(\", \")})` : \"\",\n ].filter((reason) => reason !== \"\");\n\n return [\n check(\n \"seat-available\",\n blocked.length === 0,\n \"block\",\n blocked.length === 0\n ? \"Every line's seat is installed, signed in and a version we support.\"\n : `Some lines have no usable seat: ${reasons.join(\"; \")}.`,\n blocked,\n ),\n ...(unknown.length === 0\n ? []\n : [\n check(\n \"seat-available\",\n false,\n \"warn\",\n `Sign-in state is unknown for ${unknown.length} line(s); the seat's CLI has no status command, ` +\n \"so a run may fail at launch.\",\n unknown,\n ),\n ]),\n ];\n}\n\nfunction commandChecks(input: SafetyInput): SafetyCheck[] {\n const missing = input.plan.lines\n .filter((line) => input.commands[line.id] === undefined)\n .map((line) => line.id);\n const dangerous: { lineId: string; why: string }[] = [];\n\n for (const line of input.plan.lines) {\n const spec: LaunchSpec | undefined = input.commands[line.id];\n if (spec === undefined) continue;\n const argv = spec.argv.join(\" \");\n for (const { flag, why } of FORBIDDEN_FLAGS) {\n if (argv.includes(flag)) dangerous.push({ lineId: line.id, why: `${flag}: ${why}` });\n }\n }\n\n return [\n check(\n \"permission-mode\",\n missing.length === 0 && dangerous.length === 0,\n \"block\",\n missing.length > 0\n ? `No command was built for ${missing.join(\", \")}, so there is nothing to show you before launch.`\n : dangerous.length === 0\n ? \"Every seat runs in the safest mode that can still do its work.\"\n : dangerous.map((entry) => `${entry.lineId} would run with ${entry.why}`).join(\"; \"),\n [...missing, ...dangerous.map((entry) => entry.lineId)],\n ),\n check(\n \"network\",\n true,\n \"warn\",\n \"Network isolation is the CLI's own: we select the safest mode each seat offers and cannot verify more \" +\n \"than that. Treat a run as able to reach the network unless its vendor documents otherwise.\",\n ),\n ];\n}\n\nfunction concurrencyCheck(input: SafetyInput): SafetyCheck {\n const starting = input.plan.lines.filter((line) => line.dependsOn.length === 0);\n const perSeat = new Map<string, number>();\n for (const line of starting) perSeat.set(line.seat.id, (perSeat.get(line.seat.id) ?? 0) + 1);\n\n const overSeat = [...perSeat.entries()].filter(([seat, count]) => {\n const cap = input.limits.perSeat[seat];\n return cap !== undefined && count > cap;\n });\n const overall = starting.length > input.limits.maxParallel;\n\n return check(\n \"concurrency\",\n !overall && overSeat.length === 0,\n \"block\",\n overall\n ? `${starting.length} lines would start at once but the mission allows ${input.limits.maxParallel}.`\n : overSeat.length > 0\n ? overSeat\n .map(\n ([seat, count]) =>\n `${count} lines would start on ${seat}, which allows ${input.limits.perSeat[seat] ?? 0}`,\n )\n .join(\"; \")\n : `${starting.length} line(s) start at once, within the mission's limit of ${input.limits.maxParallel}.`,\n starting.map((line) => line.id),\n );\n}\n\nasync function baseCommitCheck(input: SafetyInput, deps: SafetyDependencies): Promise<SafetyCheck> {\n const state = await deps.repositoryState();\n if (state.head !== input.repo.baseCommit) {\n return check(\n \"base-commit\",\n false,\n \"block\",\n `The repository is at ${state.head.slice(0, 7)} but the mission plans from ` +\n `${input.repo.baseCommit.slice(0, 7)}. Re-plan from where you are, or check out that commit.`,\n );\n }\n\n const conflicts = state.dirty.filter((path) =>\n input.plan.lines.some((line) => line.scope.write.some((pattern) => pathInScope(path, pattern))),\n );\n return check(\n \"base-commit\",\n conflicts.length === 0,\n \"block\",\n conflicts.length === 0\n ? \"The repository is at the mission's base commit, with nothing uncommitted inside any line's scope.\"\n : `Uncommitted changes sit inside a line's scope (${conflicts.slice(0, 5).join(\", \")}); commit or stash ` +\n \"them, or the merge will fight you later.\",\n );\n}\n", "import { deniedFiles } from \"../workspace/deny.ts\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\nimport type { RepositoryState, SafetyDependencies } from \"./report.ts\";\n\n/*\n * What the safety gate needs from the repository itself. Keeping it here means the report stays a pure function of\n * facts, and these two calls are the only place those facts come from.\n */\n\nexport interface SafetyDependencyOptions {\n repoRoot: string;\n denyList?: readonly string[];\n}\n\nexport function createSafetyDependencies(options: SafetyDependencyOptions): SafetyDependencies {\n const inRepo = { cwd: options.repoRoot };\n\n return {\n deniedFiles: (baseCommit) => deniedFiles(options.repoRoot, baseCommit, options.denyList),\n\n repositoryState: async (): Promise<RepositoryState> => {\n const head = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n const entries = zeroSeparated(await git([\"status\", \"--porcelain=v1\", \"-z\"], inRepo));\n const dirty: string[] = [];\n\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (entry === undefined) continue;\n const status = entry.slice(0, 2);\n const path = entry.slice(3);\n if (path !== \"\") dirty.push(path);\n // A rename or copy carries its source as the next entry; both paths count as touched.\n if (status.startsWith(\"R\") || status.startsWith(\"C\")) {\n const source = entries[index + 1];\n if (source !== undefined) {\n dirty.push(source);\n index += 1;\n }\n }\n }\n\n return { head, dirty };\n },\n };\n}\n", "import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { SeatInfo, type AdapterManifest } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { parseVersion, satisfies } from \"./version.ts\";\n\n/*\n * Who is on the crew. For each adapter we ask the CLI itself three things: are you here, which version are you, and\n * are you signed in \u2014 the last one through the CLI's own status command. We never read a credential file, never\n * parse a token, and never guess: a CLI we cannot find, cannot read a version from, or whose version is outside the\n * range its adapter was verified against is reported as unsupported, and one that cannot tell us its sign-in state\n * says \"unknown\" rather than \"yes\".\n */\n\nconst run = promisify(execFile);\n\nexport interface CommandResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\nexport interface DetectOptions {\n manifests: readonly AdapterManifest[];\n /** Runs a CLI. Injected in tests so detection needs no CLIs installed. */\n execute?: (binary: string, args: readonly string[]) => Promise<CommandResult>;\n /** How long any single probe may take before it counts as not answering. */\n timeoutMs?: number;\n}\n\nexport async function detectSeats(options: DetectOptions): Promise<SeatInfo[]> {\n const timeoutMs = options.timeoutMs ?? 10_000;\n const execute = options.execute ?? defaultExecute(timeoutMs);\n // Every probe gets its own deadline, and so does the seat as a whole: a CLI can hang between probes as easily\n // as during one, and `execFile`'s own timeout does not exist at all when a caller injects an executor.\n const bounded = (binary: string, args: readonly string[]): Promise<CommandResult> =>\n within(execute(binary, args), timeoutMs, null).then((result) => result ?? NO_ANSWER);\n\n return Promise.all(\n options.manifests.map(async (manifest) =>\n // Detection is the first thing a session does, so it must always finish. One CLI that never answers must\n // not hide the seats that did: an unfinished probe becomes \"unknown\" for that seat and nothing more.\n within(detectSeat(manifest, bounded), timeoutMs * 3, unknownSeat(manifest)),\n ),\n );\n}\n\n/** What a probe that never answered \"said\". Not an error: we simply do not know, which is a valid answer here. */\nconst NO_ANSWER: CommandResult = { stdout: \"\", stderr: \"\", exitCode: -1 };\n\n/**\n * Resolves with `whenLate` if `work` has not settled in time.\n *\n * A promise cannot be cancelled, so this stops *waiting*; it does not stop the work. That is the honest\n * description and also the safe one: for the real executor the child already carries its own kill timeout, and\n * for an injected one there is nothing to kill. The timer is unref'd so a straggler cannot hold the process open.\n */\nfunction within<T>(work: Promise<T>, ms: number, whenLate: T): Promise<T> {\n return new Promise<T>((resolve) => {\n const timer = setTimeout(() => {\n resolve(whenLate);\n }, ms);\n timer.unref();\n work.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(whenLate);\n },\n );\n });\n}\n\nfunction unknownSeat(manifest: AdapterManifest): SeatInfo {\n return {\n id: manifest.id,\n displayName: manifest.displayName,\n binary: manifest.binary,\n models: manifest.models,\n efforts: manifest.efforts,\n billing: manifest.billing,\n version: null,\n supported: false,\n signedIn: \"unknown\",\n plan: null,\n };\n}\n\nasync function detectSeat(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo> {\n const base = {\n id: manifest.id,\n displayName: manifest.displayName,\n binary: manifest.binary,\n models: manifest.models,\n efforts: manifest.efforts,\n billing: manifest.billing,\n };\n\n const versionResult = await attempt(() => execute(manifest.binary, [\"--version\"]));\n if (versionResult?.exitCode !== 0) {\n return { ...base, version: null, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const version = parseVersion(`${versionResult.stdout} ${versionResult.stderr}`);\n if (version === null) {\n return { ...base, version: null, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const printed = `${version.major}.${version.minor}.${version.patch}`;\n const supported = satisfies(version, manifest.supportedVersions);\n if (!supported) {\n // A stream we have not seen is a stream we cannot parse honestly, so we stop at the version \u2014 and in\n // particular we do not send an unverified build a probe whose answer we would not know how to read.\n return { ...base, version: printed, supported: false, signedIn: \"unknown\", plan: null };\n }\n\n const [signedIn, plan] = await Promise.all([signInState(manifest, execute), planState(manifest, execute)]);\n return { ...base, version: printed, supported: true, signedIn, plan };\n}\n\n/**\n * Keep only the fields the manifest allows, and drop everything else before it can travel any further.\n *\n * This is the whole of the privacy control, and it is deliberately four lines in one place. The probe that reports\n * Claude's subscription tier answers with the user's email address and organisation id in the same object; those\n * must never reach the ledger, a log, a projection or a prompt. Filtering at the moment of reading \u2014 rather than\n * remembering not to use the extra fields later \u2014 is what makes that a property of the code instead of a habit.\n */\nfunction keepAllowed(parsed: Record<string, unknown>, keep: readonly string[]): Record<string, unknown> {\n return Object.fromEntries(\n keep.filter((field) => Object.hasOwn(parsed, field)).map((field) => [field, parsed[field]]),\n );\n}\n\nasync function planState(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo[\"plan\"]> {\n const { plan } = manifest.capabilities;\n if (plan === null) return null;\n\n const result = await attempt(() => execute(manifest.binary, plan.probe));\n if (result?.exitCode !== 0) return null;\n\n const parsed = parseJsonObject(result.stdout);\n if (parsed === null) return null;\n\n const kept = keepAllowed(parsed, plan.keep);\n\n // A tier belongs to an account, so a signed-out answer carries no current plan \u2014 only, at best, the last one\n // this machine happened to see. `loggedIn` is on the allowlist precisely so this question can be asked.\n if (Object.hasOwn(kept, \"loggedIn\") && kept[\"loggedIn\"] !== true) return null;\n\n const name = kept[plan.planField];\n // A CLI that answers in a shape we did not expect has told us nothing, and a guess here would be recorded as a\n // fact and routed on. The schema has the final say, so detection cannot return a seat it could not itself store.\n const candidate = typeof name === \"string\" ? { name, source: \"detected\" as const } : null;\n const checked = SeatInfo.shape.plan.safeParse(candidate);\n return checked.success ? checked.data : null;\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> | null {\n try {\n const value: unknown = JSON.parse(text);\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nasync function signInState(\n manifest: AdapterManifest,\n execute: (binary: string, args: readonly string[]) => Promise<CommandResult>,\n): Promise<SeatInfo[\"signedIn\"]> {\n const { probe, okPattern, noPattern } = manifest.signIn;\n if (probe === null) return \"unknown\";\n\n const result = await attempt(() => execute(manifest.binary, probe));\n if (result === null) return \"unknown\";\n\n const answer = `${result.stdout}\\n${result.stderr}`;\n // Signed out is checked first and on its own terms. \"Not logged in\" contains \"Logged in\", so a positive\n // pattern asked first will happily read a refusal as an approval \u2014 which is exactly what this code used to do.\n if (noPattern !== null && matches(noPattern, answer)) return \"no\";\n if (okPattern !== null && matches(okPattern, answer)) return \"yes\";\n\n // Neither shape. A non-zero exit with nothing we recognise is a failure to answer, not an answer of \"no\":\n // reporting \"no\" would route someone's work away from a seat that may be perfectly fine.\n return \"unknown\";\n}\n\n/**\n * Runs a manifest's pattern against a bounded prefix of the CLI's output.\n *\n * The bound is the point. A pattern is compiled when the manifest is parsed, so it is valid, but validity says\n * nothing about cost: `^(a+)+$` against a long line backtracks for effectively ever, and a regular expression is\n * synchronous, so no timeout anywhere else in this file can interrupt it. Sign-in answers are short; anything\n * past a couple of kilobytes is not the answer we are looking for.\n */\nfunction matches(pattern: string, text: string): boolean {\n return new RegExp(pattern, \"i\").test(text.slice(0, 2_000));\n}\n\n/** A probe that throws, hangs or cannot start tells us nothing; it must never take the daemon down with it. */\nasync function attempt(work: () => Promise<CommandResult>): Promise<CommandResult | null> {\n try {\n return await work();\n } catch {\n return null;\n }\n}\n\nfunction defaultExecute(timeoutMs: number) {\n return async (binary: string, args: readonly string[]): Promise<CommandResult> => {\n try {\n const { stdout, stderr } = await run(binary, [...args], {\n timeout: timeoutMs,\n env: baseEnv(),\n windowsHide: true,\n });\n return { stdout, stderr, exitCode: 0 };\n } catch (cause) {\n const detail = cause as { stdout?: string; stderr?: string; code?: number };\n // A CLI that answers \"not signed in\" with a non-zero exit is answering, not failing.\n if (typeof detail.code === \"number\") {\n return { stdout: detail.stdout ?? \"\", stderr: detail.stderr ?? \"\", exitCode: detail.code };\n }\n throw cause;\n }\n };\n}\n", "/*\n * Just enough semantic versioning to answer one question: is this CLI inside the range its adapter was verified\n * against? A whole dependency for that would be a dependency to keep current, and the answer has to be boring.\n *\n * A range is a space-separated list of comparators that must all hold, for example \">=0.150.0 <1.0.0\".\n * Anything we cannot read is not a match, because \"unsupported\" is the honest answer to a version we don't know.\n */\n\nexport interface Version {\n major: number;\n minor: number;\n patch: number;\n}\n\nconst VERSION = /(\\d+)\\.(\\d+)(?:\\.(\\d+))?/;\n// A bound may name as much as it likes: \">=0.150.0\", \">=1.0\" and \"<2\" are all ordinary ways to write a range.\nconst COMPARATOR = /^(>=|<=|>|<|=)?\\s*(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/;\n\n/** The first version in a CLI's `--version` output, whatever else it prints around it. */\nexport function parseVersion(text: string): Version | null {\n const found = VERSION.exec(text);\n if (found === null) return null;\n return {\n major: Number(found[1]),\n minor: Number(found[2]),\n patch: Number(found[3] ?? 0),\n };\n}\n\nexport function compareVersions(a: Version, b: Version): number {\n return a.major - b.major || a.minor - b.minor || a.patch - b.patch;\n}\n\nexport function satisfies(version: Version, range: string): boolean {\n const comparators = range.trim().split(/\\s+/).filter(Boolean);\n if (comparators.length === 0) return false;\n\n return comparators.every((text) => {\n const found = COMPARATOR.exec(text);\n if (found === null) return false;\n const bound: Version = {\n major: Number(found[2]),\n minor: Number(found[3] ?? 0),\n patch: Number(found[4] ?? 0),\n };\n const order = compareVersions(version, bound);\n switch (found[1] ?? \"=\") {\n case \">=\":\n return order >= 0;\n case \"<=\":\n return order <= 0;\n case \">\":\n return order > 0;\n case \"<\":\n return order < 0;\n default:\n return order === 0;\n }\n });\n}\n", "import { mkdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n validatePlan,\n type AdapterSignal,\n type Ledger,\n type PlanGraph,\n type PlanLine,\n type SeatAdapter,\n} from \"fanout-core\";\nimport type { Routing } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { startRun, type RunLimits } from \"../run.ts\";\nimport type { RunExitStatus } from \"../supervisor/types.ts\";\nimport type { Workspace, WorkspaceManager } from \"../workspace/types.ts\";\n\n/*\n * A plan becomes runs here. The rules it keeps are the ones a person would expect and a machine forgets:\n *\n * - a line starts only when every line it depends on has finished well;\n * - a line whose dependency failed is dropped with the reason, never started hopefully;\n * - no more lines run at once than the mission allows;\n * - every run gets its own workspace, and the workspace stays afterwards so the diff can be reviewed;\n * - an invalid plan never runs at all.\n *\n * It records what happens as events. It does not review, merge or reroute: those are the gate's job, and a runner\n * that quietly merged would be the most dangerous code in the project.\n */\n\nexport interface MissionRunnerOptions {\n /**\n * Where each line should actually run, asked as the line starts.\n *\n * Injected rather than worked out here: the runner has a ledger and a set of adapters, not the crew's sign-in\n * state or the owner's posture, and giving it those would put three more reasons to change into the one place\n * that must not be wrong. Omitted, every line runs on the seat the plan named.\n */\n route?: (line: PlanLine) => Routing;\n ledger: Ledger;\n workspaces: WorkspaceManager;\n /** Seat id to the adapter that drives it. A line whose seat is missing is dropped, not guessed at. */\n adapters: ReadonlyMap<string, SeatAdapter>;\n /** Run logs and reports live under `<runsRoot>/<missionId>/<runId>/`. */\n runsRoot: string;\n limits: RunLimits;\n onSignal?: (runId: string, signal: AdapterSignal) => void;\n}\n\nexport interface LaunchRequest {\n missionId: string;\n plan: PlanGraph;\n baseCommit: string;\n maxParallel: number;\n}\n\nexport interface RunOutcome {\n runId: string;\n lineId: string;\n status: RunExitStatus | \"dropped\";\n workspace: Workspace | null;\n reason?: string;\n}\n\nexport interface MissionOutcome {\n missionId: string;\n runs: RunOutcome[];\n done: number;\n failed: number;\n dropped: number;\n}\n\nexport interface MissionHandle {\n readonly missionId: string;\n readonly finished: Promise<MissionOutcome>;\n /** Stops everything still running. The mission finishes with those runs marked killed. */\n cancel(reason: string): Promise<void>;\n}\n\n/** A plan that does not pass its own validation never becomes runs. */\nexport class PlanRefused extends Error {\n override name = \"PlanRefused\";\n readonly issues: readonly { code: string; message: string; lineIds: string[] }[];\n\n constructor(issues: readonly { code: string; message: string; lineIds: string[] }[]) {\n super(`This plan cannot run:\\n${issues.map((issue) => ` - ${issue.message}`).join(\"\\n\")}`);\n this.issues = issues;\n }\n}\n\nexport function createMissionRunner(options: MissionRunnerOptions) {\n return {\n launch(request: LaunchRequest): MissionHandle {\n const issues = validatePlan(request.plan);\n if (issues.length > 0) throw new PlanRefused(issues);\n return run(options, request);\n },\n };\n}\n\nfunction run(options: MissionRunnerOptions, request: LaunchRequest): MissionHandle {\n const { ledger, workspaces, adapters, limits } = options;\n const byId = new Map(request.plan.lines.map((line) => [line.id, line]));\n const waiting = new Set(byId.keys());\n const outcomes = new Map<string, RunOutcome>();\n const active = new Map<string, { kill: (reason: string) => Promise<unknown>; settled: Promise<void> }>();\n let cancelling: string | undefined;\n\n const finishedWell = (lineId: string): boolean => outcomes.get(lineId)?.status === \"done\";\n const finishedBadly = (lineId: string): boolean => {\n const status = outcomes.get(lineId)?.status;\n return status !== undefined && status !== \"done\";\n };\n\n const drop = (line: PlanLine, reason: string): void => {\n const runId = runIdFor(line);\n ledger.append({\n type: \"run.queued\",\n missionId: request.missionId,\n runId,\n lineId: line.id,\n seat: line.seat,\n attempt: 1,\n });\n ledger.append({ type: \"run.dropped\", missionId: request.missionId, runId, reason });\n outcomes.set(line.id, { runId, lineId: line.id, status: \"dropped\", workspace: null, reason });\n waiting.delete(line.id);\n };\n\n const start = async (line: PlanLine): Promise<void> => {\n /*\n * Decided at the moment the line starts, not when the mission was planned: a seat that was fine an hour ago\n * may have run out since, and the line after this one may be the one that finds out. A move is recorded\n * before anything runs, so the reason is in the history whatever happens next.\n */\n const routing = options.route?.(line) ?? { kind: \"keep\" as const, seat: line.seat.id };\n if (routing.kind === \"stuck\") {\n drop(line, routing.reason);\n return;\n }\n if (routing.kind === \"move\") {\n ledger.append({\n type: \"route.changed\",\n missionId: request.missionId,\n lineId: line.id,\n from: { id: routing.from },\n to: { id: routing.seat },\n reason: routing.reason,\n });\n /*\n * The id moves and the model does not. `gpt-5-codex` means nothing to Claude's CLI, and a model string a\n * seat does not recognise is how we already lost twenty minutes once \u2014 Codex answered \"The '' model is not\n * supported\" and sat there. The new seat gets its own default, which is the only model we know it has.\n */\n line = { ...line, seat: { id: routing.seat } };\n }\n\n const runId = runIdFor(line);\n const adapter = adapters.get(line.seat.id);\n if (adapter === undefined) {\n drop(line, `no adapter is installed for the seat \"${line.seat.id}\"`);\n return;\n }\n\n waiting.delete(line.id);\n ledger.append({\n type: \"run.queued\",\n missionId: request.missionId,\n runId,\n lineId: line.id,\n seat: line.seat,\n attempt: 1,\n });\n\n const directory = join(options.runsRoot, request.missionId, runId);\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n const workspace = await workspaces.create({\n missionId: request.missionId,\n runId,\n baseCommit: request.baseCommit,\n line,\n });\n\n const started = startRun({\n ledger,\n adapter,\n context: {\n missionId: request.missionId,\n runId,\n line,\n workdir: workspace.path,\n reportPath: join(directory, \"report.md\"),\n baseEnv: baseEnv(),\n },\n logPath: join(directory, \"run.log\"),\n limits,\n collectDiff: async () => (await workspaces.collect(workspace, line)).stat,\n ...(options.onSignal === undefined\n ? {}\n : { onSignal: (signal: AdapterSignal) => options.onSignal?.(runId, signal) }),\n });\n\n const settled = started.finished\n .then((exit) => {\n outcomes.set(line.id, { runId, lineId: line.id, status: exit.status, workspace });\n })\n .catch((error: unknown) => {\n outcomes.set(line.id, {\n runId,\n lineId: line.id,\n status: \"failed\",\n workspace,\n reason: error instanceof Error ? error.message : \"the run could not be recorded\",\n });\n })\n .finally(() => {\n active.delete(line.id);\n });\n\n active.set(line.id, { kill: (reason) => started.handle.kill(reason), settled });\n };\n\n const finished = (async (): Promise<MissionOutcome> => {\n while (waiting.size > 0 || active.size > 0) {\n for (const lineId of [...waiting]) {\n const line = byId.get(lineId);\n if (line === undefined) continue;\n if (cancelling !== undefined) {\n drop(line, cancelling);\n continue;\n }\n if (line.dependsOn.some(finishedBadly)) {\n const blocker = line.dependsOn.find(finishedBadly) ?? \"a line it depends on\";\n drop(line, `\"${blocker}\" did not finish, so this line was not started`);\n continue;\n }\n if (active.size >= request.maxParallel) break;\n if (line.dependsOn.every(finishedWell)) await start(line);\n }\n\n if (active.size > 0) await Promise.race([...active.values()].map((entry) => entry.settled));\n else if (waiting.size > 0 && [...waiting].every((id) => !ready(id, byId, finishedWell))) {\n // Nothing can start and nothing is running: whatever is left is waiting on something that never happened.\n for (const lineId of [...waiting]) {\n const line = byId.get(lineId);\n if (line !== undefined) drop(line, \"the lines it depends on never finished\");\n }\n }\n }\n\n const runs = [...outcomes.values()];\n return {\n missionId: request.missionId,\n runs,\n done: runs.filter((outcome) => outcome.status === \"done\").length,\n failed: runs.filter((outcome) => outcome.status !== \"done\" && outcome.status !== \"dropped\").length,\n dropped: runs.filter((outcome) => outcome.status === \"dropped\").length,\n };\n })();\n\n return {\n missionId: request.missionId,\n finished,\n async cancel(reason: string): Promise<void> {\n cancelling = reason;\n await Promise.all([...active.values()].map((entry) => entry.kill(reason)));\n },\n };\n}\n\nfunction ready(lineId: string, byId: Map<string, PlanLine>, finishedWell: (id: string) => boolean): boolean {\n return byId.get(lineId)?.dependsOn.every(finishedWell) ?? false;\n}\n\n/** One attempt per line for now; rework (attempt 2 and 3) arrives with the merge gate. */\nfunction runIdFor(line: PlanLine): string {\n return `${line.id}-1`;\n}\n", "import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/*\n * Finding the long-running daemon, if there is one.\n *\n * A mission launched from a Claude Code session dies with that session, because the runner lives inside the\n * session's MCP server (ADR 0024). The way out is for the runner to live somewhere that outlives a terminal \u2014\n * `fanout daemon`, which already runs for as long as you leave it \u2014 and for the session to ask it rather than do\n * the work itself.\n *\n * This is the asking half: where is it, and is it really there. Two checks, because either alone lies. The file\n * says where a daemon *was*: it survives a crash, a reboot and a kill -9, so a url alone is a guess. The process\n * says something is alive at that id, which after a reboot may be something else entirely. Together they are\n * good enough to try, and the request itself is the final word.\n */\n\nexport interface DaemonLink {\n url: string;\n /** The daemon's own token, which every request to it must carry. */\n token: string;\n pid: number;\n}\n\n/**\n * The daemon this machine is running, or null when there is none to talk to.\n *\n * Never throws. A missing file, a stale file, a file somebody edited by hand and a daemon that died an hour ago\n * are all the same answer to the caller \u2014 there is nobody to ask \u2014 and turning any of them into an exception\n * would make \"no daemon\" look like a failure rather than the ordinary case it is.\n */\nexport function findDaemon(home: string): DaemonLink | null {\n let advertised: unknown;\n try {\n advertised = JSON.parse(readFileSync(join(home, \"daemon.json\"), \"utf8\"));\n } catch {\n return null;\n }\n\n const { url, pid } = advertised as { url?: unknown; pid?: unknown };\n if (typeof url !== \"string\" || url === \"\" || typeof pid !== \"number\" || !Number.isInteger(pid)) return null;\n\n /*\n * `EPERM` means the process exists and belongs to somebody else \u2014 alive, and quite possibly another user's\n * daemon on a shared machine. Only `ESRCH` is proof that the id advertised in the file is nobody.\n */\n try {\n process.kill(pid, 0);\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== \"EPERM\") return null;\n }\n\n let token: string;\n try {\n token = readFileSync(join(home, \"token\"), \"utf8\").trim();\n } catch {\n return null;\n }\n if (token === \"\") return null;\n\n return { url, token, pid };\n}\n\n/** Whether the daemon at this link answers. The only check that proves anything; the rest is prologue. */\nexport async function daemonAnswers(link: DaemonLink, timeoutMs = 1500): Promise<boolean> {\n try {\n const response = await fetch(`${link.url}/health`, { signal: AbortSignal.timeout(timeoutMs) });\n return response.ok;\n } catch {\n return false;\n }\n}\n", "import { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport type { Socket } from \"node:net\";\nimport {\n blocksApproval,\n mergeReadiness,\n project,\n type EventType,\n type Ledger,\n type ProjectionState,\n type SeatInfo,\n type StoredEvent,\n} from \"fanout-core\";\nimport { WebSocketServer, type WebSocket } from \"ws\";\nimport { originAllowed, tokenMatches } from \"./token.ts\";\n\n/*\n * The daemon's only door. It binds to 127.0.0.1, never to an interface anyone else can reach, and every request\n * carries the daemon's token \u2014 \"local\" is not the same as \"yours\" on a shared machine. Requests that arrive with a\n * browser's Origin are refused before a handler sees them, so a web page cannot drive your crew.\n *\n * Two ways to read: ask for what is there now over HTTP, or subscribe over a WebSocket and be told as it happens.\n * The subscription is what the lead's Monitor listens to, which is why it can be narrowed to the events a lead\n * actually acts on: a feed that repeats everything is a feed nobody reads.\n */\n\n/** The events a lead acts on. Everything else is for the mission view, which asks for the lot. */\nexport const LEAD_EVENTS: readonly EventType[] = [\n \"run.finished\",\n \"merge.conflict\",\n \"policy.breach\",\n \"route.changed\",\n \"safety.report\",\n \"mission.finished\",\n];\n\nexport interface ApiOptions {\n ledger: Ledger;\n token: string;\n /** The crew as last detected. Async because asking the CLIs takes a moment. */\n crew?: () => Promise<readonly SeatInfo[]>;\n /** 0 asks the operating system for a free port, which is what tests want. */\n port?: number;\n /**\n * Starts a mission, when this daemon is one that can.\n *\n * Injected rather than built here, because running a mission needs adapters, manifests and limits \u2014 things the\n * API has no business knowing. Absent, the daemon is what it has always been: a window onto the ledger.\n *\n * It exists so a mission can outlive the session that asked for it. A runner inside a Claude Code session dies\n * with the terminal; one inside a daemon does not (ADR 0024).\n */\n launch?: (request: LaunchOrder) => Promise<{ ok: true } | { ok: false; why: string }>;\n\n /**\n * Stops a mission this daemon is running. Absent when the daemon cannot run one in the first place.\n *\n * It matters more than launching. Cancel is how somebody says \"stop spending my subscription\", and a cancel\n * that quietly does nothing because the mission is owned by a different process is the worst of both: the\n * agents keep working and the person believes they stopped.\n */\n cancel?: (missionId: string, reason: string) => Promise<boolean>;\n\n /**\n * The mission view's HTML, with `{{TOKEN}}` wherever the page needs this daemon's token.\n *\n * Passed in rather than read from disk here so the daemon has no opinion about where the page lives, and so a\n * test can serve a one-line page without a file.\n */\n view?: () => string;\n}\n\n/** What the daemon needs to start a mission on somebody else's behalf. */\nexport interface LaunchOrder {\n missionId: string;\n goal: string;\n /** The repository the work happens in. A daemon serves every repository on the machine, not one. */\n repoRoot: string;\n plan: unknown;\n maxParallel: number;\n}\n\nexport interface ApiServer {\n readonly port: number;\n readonly url: string;\n /** Tells every subscriber about an event that was just recorded. */\n publish(event: StoredEvent): void;\n close(): Promise<void>;\n}\n\ninterface Subscriber {\n socket: WebSocket;\n types: ReadonlySet<EventType> | null;\n missionId: string | null;\n}\n\nexport async function startApi(options: ApiOptions): Promise<ApiServer> {\n const subscribers = new Set<Subscriber>();\n const sockets = new Set<Socket>();\n\n const server = createServer((request, response) => {\n handle(request, response, options).catch((error: unknown) => {\n send(response, 500, { error: error instanceof Error ? error.message : \"unknown error\" });\n });\n });\n server.on(\"connection\", (socket) => {\n sockets.add(socket);\n socket.on(\"close\", () => sockets.delete(socket));\n });\n\n const websockets = new WebSocketServer({ noServer: true });\n server.on(\"upgrade\", (request, socket, head) => {\n const url = parseUrl(request);\n const port = (server.address() as { port: number } | null)?.port ?? 0;\n const authorized =\n originAllowed(request.headers.origin, port) &&\n tokenMatches(\n options.token,\n request.headers.authorization ?? url.searchParams.get(\"token\") ?? undefined,\n );\n\n if (!authorized || url.pathname !== \"/events\") {\n socket.write(`HTTP/1.1 ${authorized ? 404 : 401} ${authorized ? \"Not Found\" : \"Unauthorized\"}\\r\\n\\r\\n`);\n socket.destroy();\n return;\n }\n\n websockets.handleUpgrade(request, socket, head, (ws) => {\n const subscriber: Subscriber = {\n socket: ws,\n types: typesFrom(url),\n missionId: url.searchParams.get(\"missionId\"),\n };\n subscribers.add(subscriber);\n ws.on(\"close\", () => subscribers.delete(subscriber));\n\n // Replay first, then live: a subscriber that joins mid-mission still sees how it got here.\n const afterSeq = Number(url.searchParams.get(\"afterSeq\") ?? 0);\n for (const event of options.ledger.read({ afterSeq })) {\n if (wanted(subscriber, event)) ws.send(JSON.stringify(event));\n }\n });\n });\n\n await new Promise<void>((resolve) => {\n server.listen(options.port ?? 0, \"127.0.0.1\", resolve);\n });\n const port = (server.address() as { port: number } | null)?.port ?? 0;\n\n return {\n port,\n url: `http://127.0.0.1:${port}`,\n publish(event) {\n for (const subscriber of subscribers) {\n if (wanted(subscriber, event)) subscriber.socket.send(JSON.stringify(event));\n }\n },\n close: () => close(server, websockets, sockets, subscribers),\n };\n}\n\nasync function handle(\n request: IncomingMessage,\n response: ServerResponse,\n options: ApiOptions,\n): Promise<void> {\n const url = parseUrl(request);\n const port = Number(request.headers.host?.split(\":\")[1] ?? 0);\n\n // Health says nothing about you, so it needs no token: it is how a client knows a daemon is there at all.\n if (url.pathname === \"/health\") {\n send(response, 200, { ok: true, name: \"fanout\" });\n return;\n }\n\n /*\n * The mission view itself, and the only route that answers a browser.\n *\n * It carries no data \u2014 the page asks for that with the token it is handed below \u2014 so serving it before the\n * Origin and token checks gives away nothing except that a daemon is running, which `/health` already says.\n * A browser cannot send an Authorization header on a plain navigation, which is why the token is stamped into\n * the page rather than demanded from it.\n */\n if (url.pathname === \"/\" && options.view !== undefined) {\n const page = options.view().replaceAll(\"{{TOKEN}}\", options.token);\n response.writeHead(200, {\n \"content-type\": \"text/html; charset=utf-8\",\n // It shows your source code: nothing about it may be cached, framed, or fetched from anywhere else.\n \"cache-control\": \"no-store\",\n \"content-security-policy\":\n \"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'\",\n \"x-frame-options\": \"DENY\",\n \"referrer-policy\": \"no-referrer\",\n });\n response.end(page);\n return;\n }\n\n if (!originAllowed(request.headers.origin, port)) {\n send(response, 403, { error: \"a page in a browser cannot drive the daemon\" });\n return;\n }\n if (!tokenMatches(options.token, request.headers.authorization)) {\n send(response, 401, { error: \"this daemon needs its token; it is in ~/.fanout/token\" });\n return;\n }\n /*\n * The one thing this daemon lets a person do rather than read, and the reason it is worth the write route.\n *\n * An approval recorded through the lead's tool is a language model's account of a conversation: `via: relayed`,\n * and an agent that never asked writes a byte-identical event. This one is `via: direct` \u2014 the daemon received\n * the click itself, over loopback, with its own token, from the page it served. Nothing in between could have\n * invented it, and the ledger can finally tell the two apart.\n *\n * It approves and stops there. Merging needs a commit message in the repository's own convention, which the\n * lead writes; and leaving the apply to the gate means this route can never touch the user's tree.\n */\n if (request.method === \"POST\" && url.pathname === \"/approve\") {\n await approve(request, response, options);\n return;\n }\n\n /*\n * Handing a mission to something that will outlive the asker.\n *\n * The session that calls this may be gone in thirty seconds \u2014 that is the whole reason the route exists \u2014 so\n * it answers as soon as the runs are under way rather than when they finish, and everything after that is in\n * the ledger for whoever comes back.\n */\n if (request.method === \"POST\" && url.pathname === \"/cancel\") {\n let order: { missionId?: unknown; reason?: unknown };\n try {\n order = JSON.parse(await readBody(request)) as typeof order;\n } catch {\n send(response, 400, { error: \"that was not JSON this daemon could read\" });\n return;\n }\n const missionId = typeof order.missionId === \"string\" ? order.missionId : \"\";\n const reason = typeof order.reason === \"string\" ? order.reason : \"cancelled\";\n if (missionId === \"\" || options.cancel === undefined) {\n send(response, options.cancel === undefined ? 501 : 400, {\n error: options.cancel === undefined ? \"this daemon runs no missions\" : \"a cancel needs a missionId\",\n });\n return;\n }\n // `stopped: false` is a real answer, not a failure: this daemon is simply not the one running it.\n send(response, 200, { stopped: await options.cancel(missionId, reason) });\n return;\n }\n\n if (request.method === \"POST\" && url.pathname === \"/launch\") {\n if (options.launch === undefined) {\n send(response, 501, { error: \"this daemon only reads the ledger; it cannot run a mission\" });\n return;\n }\n await launch(request, response, {\n start: options.launch,\n knows: (missionId) => project(options.ledger.read({ missionId })).missions[missionId] !== undefined,\n });\n return;\n }\n if (request.method !== \"GET\") {\n send(response, 405, { error: `${request.method ?? \"that\"} is not something this daemon does yet` });\n return;\n }\n\n /*\n * Everything the view draws, in one answer. The page redraws from a whole snapshot rather than stitching\n * together deltas, because a view that can drift from the ledger is a view that will eventually lie about it.\n */\n if (url.pathname === \"/state\") {\n const state = project(options.ledger.read());\n const seats = options.crew === undefined ? [] : await options.crew();\n send(response, 200, { state, seats, waiting: waitingOnYou(state), now: new Date().toISOString() });\n return;\n }\n\n if (url.pathname === \"/crew\") {\n const seats = options.crew === undefined ? [] : await options.crew();\n send(response, 200, { seats });\n return;\n }\n\n if (url.pathname === \"/events\") {\n const afterSeq = Number(url.searchParams.get(\"afterSeq\") ?? 0);\n const limit = Number(url.searchParams.get(\"limit\") ?? 500);\n const missionId = url.searchParams.get(\"missionId\");\n const events = options.ledger.read({\n afterSeq: Number.isFinite(afterSeq) ? afterSeq : 0,\n limit: Number.isFinite(limit) ? Math.min(limit, 5000) : 500,\n ...(missionId === null ? {} : { missionId }),\n });\n send(response, 200, { events, lastSeq: options.ledger.lastSeq() });\n return;\n }\n\n send(response, 404, { error: `nothing lives at ${url.pathname}` });\n}\n\n/**\n * Records a person's yes, or explains why it cannot be given yet.\n *\n * The revision is the one review judged, never one the caller chose: an approval is consent to a specific diff,\n * and letting the page name it would let a stale page approve work it had not seen. If the worktree has moved\n * since, `mergeRun` collects the diff again, finds a revision the approval does not match, and refuses \u2014 which is\n * the same protection the lead's tool has, arrived at the same way.\n */\nasync function approve(\n request: IncomingMessage,\n response: ServerResponse,\n options: ApiOptions,\n): Promise<void> {\n let body: { missionId?: unknown; runId?: unknown; note?: unknown };\n try {\n body = JSON.parse(await readBody(request)) as typeof body;\n } catch {\n send(response, 400, { error: \"that was not JSON this daemon could read\" });\n return;\n }\n const missionId = typeof body.missionId === \"string\" ? body.missionId : \"\";\n const runId = typeof body.runId === \"string\" ? body.runId : \"\";\n const note = typeof body.note === \"string\" ? body.note.slice(0, 2000) : \"approved in the mission view\";\n if (missionId === \"\" || runId === \"\") {\n send(response, 400, { error: \"an approval needs a missionId and a runId\" });\n return;\n }\n\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n const run = mission?.runs[runId];\n const line = (mission?.plan?.lines ?? []).find((candidate) => candidate.id === run?.lineId);\n if (mission === undefined || run === undefined || line === undefined) {\n send(response, 404, { error: `no run ${runId} in ${missionId}` });\n return;\n }\n\n const revision = run.review?.revision ?? run.checks?.revision ?? \"\";\n if (revision === \"\") {\n send(response, 409, { error: \"nothing has judged this diff yet, so there is no revision to approve\" });\n return;\n }\n\n /*\n * Everything except the approval itself must already be satisfied. Recording a yes for work nobody reviewed\n * would put the strongest evidence in the ledger behind a diff that had earned none of it.\n */\n const standing = blocksApproval(mergeReadiness(run, line, revision));\n if (standing.length > 0) {\n send(response, 409, {\n error: \"this is not ready for your approval yet\",\n blockers: standing.map((blocker) => blocker.message),\n });\n return;\n }\n\n options.ledger.append({\n type: \"merge.approved\",\n missionId,\n runId,\n revision,\n by: { kind: \"user\", via: \"direct\" },\n note,\n });\n send(response, 200, { ok: true, runId, revision });\n}\n\n/** Reads a launch order and starts it, or says exactly which part it could not read. */\nasync function launch(\n request: IncomingMessage,\n response: ServerResponse,\n options: {\n start: (order: LaunchOrder) => Promise<{ ok: true } | { ok: false; why: string }>;\n knows: (missionId: string) => boolean;\n },\n): Promise<void> {\n const { start } = options;\n let body: Partial<LaunchOrder>;\n try {\n body = JSON.parse(await readBody(request, 2 * 1024 * 1024)) as Partial<LaunchOrder>;\n } catch {\n send(response, 400, { error: \"that was not JSON this daemon could read\" });\n return;\n }\n\n const { missionId, goal, repoRoot, plan } = body;\n if (\n typeof missionId !== \"string\" ||\n typeof goal !== \"string\" ||\n typeof repoRoot !== \"string\" ||\n plan === undefined\n ) {\n send(response, 400, { error: \"a launch needs a missionId, a goal, a repoRoot and a plan\" });\n return;\n }\n\n /*\n * The mission has to exist before it can be run.\n *\n * The caller records `mission.created` and the plan, then asks for it to be started; without that the runs\n * this queues belong to a mission the ledger has never heard of, and every one of them lands as an anomaly.\n * Found by calling this route by hand and watching a launch succeed into nothing.\n */\n if (!options.knows(missionId)) {\n send(response, 409, {\n error: `${missionId} has not been recorded yet \u2014 create the mission and its plan before launching it`,\n });\n return;\n }\n\n const outcome = await start({\n missionId,\n goal,\n repoRoot,\n plan,\n maxParallel: typeof body.maxParallel === \"number\" ? body.maxParallel : 3,\n });\n\n if (!outcome.ok) {\n send(response, 409, { error: outcome.why });\n return;\n }\n send(response, 202, { ok: true, missionId });\n}\n\n/** The request's body, refusing anything large enough to be an attempt at exhausting the daemon. */\nasync function readBody(request: IncomingMessage, limit = 8 * 1024): Promise<string> {\n let body = \"\";\n for await (const chunk of request) {\n body += (chunk as Buffer).toString(\"utf8\");\n if (body.length > limit) throw new Error(\"body too large\");\n }\n return body;\n}\n\n/**\n * What each finished run still needs before it can merge, computed here rather than in the page.\n *\n * `mergeReadiness` is the gate's judgement and there is exactly one of it. A page that worked out its own answer\n * would eventually disagree with the tool that actually refuses, and the screen saying \"ready\" while the merge\n * says \"no\" is worse than the screen saying nothing \u2014 this repository has spent a day proving that a rule with\n * two implementations ends up with two behaviours.\n */\nfunction waitingOnYou(state: ProjectionState): {\n missionId: string;\n runId: string;\n task: string;\n seat: string;\n ready: boolean;\n /**\n * Your yes is the only thing missing.\n *\n * Distinct from `ready`, which means the gate would merge this now \u2014 and which can only become true *after*\n * someone approves, since a missing approval is itself a blocker. Without this flag the page could never tell\n * the one state where a person actually has something to do.\n */\n approvable: boolean;\n blockers: string[];\n}[] {\n const waiting = [];\n for (const mission of Object.values(state.missions)) {\n const lines = new Map((mission.plan?.lines ?? []).map((line) => [line.id, line]));\n for (const runId of mission.runOrder) {\n const run = mission.runs[runId];\n if (run?.status !== \"done\") continue;\n const line = lines.get(run.lineId);\n if (line === undefined) continue;\n\n // Judged against the revision the review saw: the page cannot read a worktree, and the merge tool\n // re-collects the diff and refuses for itself if the work has moved since.\n const judged = run.review?.revision ?? run.checks?.revision ?? \"\";\n const readiness = mergeReadiness(run, line, judged);\n waiting.push({\n missionId: mission.missionId,\n runId,\n // What the work was, not just which run it was. A row that says `api-1` makes a person go and look it up.\n task: line.title,\n seat: run.seat.id,\n ready: readiness.ready,\n approvable: !readiness.ready && blocksApproval(readiness).length === 0,\n blockers: readiness.blockers.map((blocker) => blocker.message),\n });\n }\n }\n return waiting;\n}\n\nfunction wanted(subscriber: Subscriber, event: StoredEvent): boolean {\n if (subscriber.types !== null && !subscriber.types.has(event.type)) return false;\n if (subscriber.missionId === null) return true;\n return \"missionId\" in event && event.missionId === subscriber.missionId;\n}\n\nfunction typesFrom(url: URL): ReadonlySet<EventType> | null {\n if (url.searchParams.get(\"for\") === \"lead\") return new Set(LEAD_EVENTS);\n const types = url.searchParams.get(\"types\");\n if (types === null || types === \"\") return null;\n return new Set(types.split(\",\").filter(Boolean) as EventType[]);\n}\n\nfunction parseUrl(request: IncomingMessage): URL {\n return new URL(request.url ?? \"/\", `http://127.0.0.1`);\n}\n\nfunction send(response: ServerResponse, status: number, body: unknown): void {\n const text = JSON.stringify(body);\n response.writeHead(status, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"content-length\": Buffer.byteLength(text),\n // Nothing here is for a browser to keep.\n \"cache-control\": \"no-store\",\n });\n response.end(text);\n}\n\nasync function close(\n server: Server,\n websockets: WebSocketServer,\n sockets: Set<Socket>,\n subscribers: Set<Subscriber>,\n): Promise<void> {\n for (const subscriber of subscribers) subscriber.socket.close();\n subscribers.clear();\n await new Promise<void>((resolve) => {\n websockets.close(() => {\n resolve();\n });\n });\n for (const socket of sockets) socket.destroy();\n sockets.clear();\n await new Promise<void>((resolve) => {\n server.close(() => {\n resolve();\n });\n });\n}\n", "import { randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\n/*\n * The daemon answers on 127.0.0.1 only, but \"local\" is not the same as \"yours\": anything running on the machine,\n * including a web page in your browser, can reach a local port. So every request carries a token that lives in a\n * file only you can read, and comparisons are constant-time so a wrong guess teaches an attacker nothing.\n */\n\nconst TOKEN_BYTES = 32;\n\n/** Reads the daemon's token, creating one the first time. The file is yours alone (mode 600). */\nexport function readOrCreateToken(path: string): string {\n if (existsSync(path)) {\n const existing = readFileSync(path, \"utf8\").trim();\n if (existing.length >= 32) {\n chmodSync(path, 0o600);\n return existing;\n }\n }\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const token = randomBytes(TOKEN_BYTES).toString(\"base64url\");\n writeFileSync(path, `${token}\\n`, { encoding: \"utf8\", mode: 0o600 });\n chmodSync(path, 0o600);\n return token;\n}\n\n/** Whether a request carries the daemon's token. Constant-time, and never true for a missing or empty header. */\nexport function tokenMatches(expected: string, authorization: string | undefined): boolean {\n if (authorization === undefined) return false;\n const offered = authorization.startsWith(\"Bearer \") ? authorization.slice(7).trim() : authorization.trim();\n if (offered === \"\" || expected === \"\") return false;\n\n const a = Buffer.from(offered, \"utf8\");\n const b = Buffer.from(expected, \"utf8\");\n // timingSafeEqual needs equal lengths; compare a fixed-size digest of each instead of leaking the length.\n if (a.length !== b.length) {\n timingSafeEqual(b, b); // keep the work the same whatever the input looks like\n return false;\n }\n return timingSafeEqual(a, b);\n}\n\n/**\n * Whether a browser page is trying to drive the daemon. A request from a page carries an Origin; ours never do,\n * so anything with an Origin that is not our own loopback address is refused before it reaches a handler.\n */\nexport function originAllowed(origin: string | undefined, port: number): boolean {\n if (origin === undefined || origin === \"\" || origin === \"null\") return true;\n return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;\n}\n", "import { project, type Ledger } from \"fanout-core\";\n\n/*\n * Closing the books on runs whose supervisor is gone.\n *\n * Found by using the product the way a person will: a `/fanout` mission was launched from a Claude Code session,\n * the session ended while the agent was still working, and the run stayed recorded as `running` \u2014 eleven minutes,\n * then forever. Nothing was watching it, the process had died with its parent, and the ledger had no way to say\n * so. `fanout status` showed a mission in flight that had not existed for a quarter of an hour.\n *\n * The supervisor lives inside the session's MCP server, so this is not an edge case: it is what happens every\n * time somebody closes their terminal, and every time a print-mode session returns. The honest fix is not to\n * pretend those runs are alive, and not to guess in a projection either \u2014 a projection that invented a status\n * would be reading the ledger as a suggestion. It is to write down what is now known.\n *\n * A run is only ended here when we can prove nobody is watching: its supervisor's process id was recorded and\n * that process is gone. A run whose owner is still alive belongs to a session that is still going \u2014 a second\n * terminal, very possibly \u2014 and is left strictly alone.\n */\n\nexport interface ReconcileResult {\n /** Runs written off, by id, so a caller can say what it found rather than that it found something. */\n dropped: string[];\n}\n\n/** Whether a process exists. Signal 0 asks the kernel without disturbing it. */\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (cause) {\n /*\n * `EPERM` means the process exists and belongs to somebody else \u2014 alive, and not ours to judge. Only\n * `ESRCH`, no such process, is proof of death. Treating a permission error as death would end another\n * user's runs on a shared machine.\n */\n return (cause as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Ends every run this ledger still calls running whose supervisor has died.\n *\n * Called when a daemon starts, before anything reads the ledger for an answer \u2014 which is the first moment the\n * truth is knowable and the last moment it can be recorded without someone having already been misled.\n */\nexport function reconcile(ledger: Ledger, now = process.pid): ReconcileResult {\n const state = project(ledger.read());\n const dropped: string[] = [];\n\n for (const mission of Object.values(state.missions)) {\n for (const runId of mission.runOrder) {\n const run = mission.runs[runId];\n if (run?.status !== \"running\" && run?.status !== \"queued\") continue;\n\n /*\n * A queued run never started, so it has no owner to check: it was waiting for a slot in a mission that is\n * no longer being run by anybody, which is the same fate by a shorter road.\n */\n const owner = run.owner;\n if (owner !== null && (owner === now || alive(owner))) continue;\n\n ledger.append({\n type: \"run.dropped\",\n missionId: mission.missionId,\n runId,\n reason:\n owner === null\n ? \"the session that started this run ended, and nothing recorded how it finished\"\n : `the session supervising this run (process ${String(owner)}) is gone, so nothing was watching it`,\n });\n dropped.push(runId);\n }\n\n /*\n * A mission with nothing left running is over, whatever it was last called.\n *\n * Not only when this pass dropped something. A mission is also left open when the process that owned its\n * handle died between the last run finishing and the finish being written \u2014 every run settled, the mission\n * still reading `running`, and nothing that would ever say otherwise. Seen for real: a daemon restarted\n * after its runs had completed, and the mission showed `running \u00B7 1 waiting for review` indefinitely.\n */\n if (mission.status === \"running\" || mission.status === \"planning\") {\n const settled =\n mission.runOrder.length > 0 &&\n mission.runOrder.every((id) => {\n const status = mission.runs[id]?.status;\n return (status !== \"running\" && status !== \"queued\") || dropped.includes(id);\n });\n if (settled) {\n ledger.append({\n type: \"mission.finished\",\n missionId: mission.missionId,\n outcome: dropped.length > 0 ? \"aborted\" : \"completed\",\n summary:\n dropped.length > 0\n ? `${String(dropped.length)} run(s) ended when the session supervising them did`\n : \"every run had finished; nothing recorded the mission as over\",\n });\n }\n }\n }\n\n return { dropped };\n}\n", "import { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { EMPTY_POLICY, SeatPolicy, type SeatPosture } from \"fanout-core\";\n\n/*\n * Where the owner's seat preferences live, and \u2014 more importantly \u2014 what happens when that file is unreadable.\n *\n * The failure mode is the whole design here. \"No preferences\" and \"I could not read your preferences\" look\n * identical if you return an empty policy for both, and they are not the same at all: the first means use the\n * defaults, the second means a seat the owner switched off may be about to be spent. So a damaged file yields the\n * defaults *and* a problem, and any caller about to spend money on a seat must treat a problem as a refusal rather\n * than as a shrug.\n */\n\nexport const POLICY_FILE = \"seats.json\";\n\nexport interface PolicyRead {\n policy: SeatPolicy;\n /**\n * Null when the file was read or was simply absent. A string when something is wrong with it, in which case\n * `policy` holds the defaults and is **not** safe to act on: see the note above.\n */\n problem: string | null;\n}\n\nexport function policyPath(home: string): string {\n return join(home, POLICY_FILE);\n}\n\n/** Reads the owner's seat preferences. An absent file is not a problem; an unreadable one is. */\nexport function readSeatPolicy(home: string): PolicyRead {\n const path = policyPath(home);\n\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch (cause) {\n // Never having set a preference is the normal case, not an error.\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") return { policy: EMPTY_POLICY, problem: null };\n return { policy: EMPTY_POLICY, problem: `${path} could not be read: ${describe(cause)}` };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { policy: EMPTY_POLICY, problem: `${path} is not valid JSON` };\n }\n\n const result = SeatPolicy.safeParse(parsed);\n if (!result.success) {\n const first = result.error.issues[0];\n const where = first === undefined ? \"\" : ` (${first.path.join(\".\")}: ${first.message})`;\n return { policy: EMPTY_POLICY, problem: `${path} is not a seat policy we understand${where}` };\n }\n\n return { policy: result.data, problem: null };\n}\n\n/**\n * Writes the preferences, replacing the file atomically.\n *\n * A half-written policy is the worst outcome available: it reads as damaged, which blocks work, and it does so at\n * the moment the owner was trying to change something. Writing beside the file and renaming means a reader sees\n * either the old policy or the new one, never a torn one.\n */\nexport function writeSeatPolicy(home: string, policy: SeatPolicy): void {\n const path = policyPath(home);\n mkdirSync(dirname(path), { recursive: true });\n\n const temporary = `${path}.${String(process.pid)}.tmp`;\n writeFileSync(temporary, `${JSON.stringify(SeatPolicy.parse(policy), null, 2)}\\n`, {\n encoding: \"utf8\",\n mode: 0o600,\n });\n renameSync(temporary, path);\n}\n\n/** Sets one seat's posture, leaving every other seat's preference exactly as it was. */\nexport function setPosture(\n policy: SeatPolicy,\n seatId: string,\n posture: SeatPosture,\n note?: string,\n): SeatPolicy {\n return SeatPolicy.parse({\n version: 1,\n seats: {\n ...policy.seats,\n [seatId]: { posture, ...(note === undefined || note === \"\" ? {} : { note }) },\n },\n });\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import { routeLine, type Routing, type SeatHeadroom, type SeatInfo } from \"fanout-core\";\nimport { readSeatPolicy } from \"./seats.ts\";\n\n/*\n * Where a line runs, given what is actually on this machine.\n *\n * `routeLine` in core decides it from facts; this decides which facts we are entitled to use. The two are separate\n * because the interesting failures here are not about choosing badly, they are about choosing at all on top of\n * something we did not really read \u2014 and that question has nothing to do with the ordering rules in core.\n *\n * Every refusal below resolves the same way: keep the seat the plan named. That is the choice that can only fail\n * loudly. A line kept on a seat that has run out stops with the seat's own message on screen; a line moved onto a\n * seat the owner switched off spends their subscription and tells them afterwards.\n */\n\nexport interface RouteContext {\n /** The owner's fanout home, where seat preferences live. */\n home: string;\n /** What detection found. Empty means it has not answered yet. */\n crew: readonly SeatInfo[];\n headroom: Readonly<Record<string, SeatHeadroom>>;\n now: Date;\n}\n\n/**\n * Decides where a line runs, or declines to decide.\n *\n * The policy read is the reason this function exists. `readSeatPolicy` hands back defaults *and* a problem when\n * the file is damaged, and says in its own documentation that the defaults are not safe to act on \u2014 a caller that\n * destructures `policy` and drops `problem` gets code that looks right, passes, and one day moves work onto a\n * seat the owner had turned off. So a problem here means we route nothing.\n */\nexport function chooseSeat(wanted: string, context: RouteContext): Routing {\n // Detection has not answered. The safety report has already told the user which seats it could not see.\n if (context.crew.length === 0) return { kind: \"keep\", seat: wanted };\n\n const { policy, problem } = readSeatPolicy(context.home);\n if (problem !== null) return { kind: \"keep\", seat: wanted };\n\n return routeLine({ wanted, seats: context.crew, policy, headroom: context.headroom, now: context.now });\n}\n", "import { createHash } from \"node:crypto\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * The identity of a working tree's uncommitted work.\n *\n * The gate's every claim \u2014 reviewed, checked, proven, approved \u2014 is about a specific diff, and a working tree is\n * not a specific anything: it changes under you. Hashing what is actually there turns \"the current changes\" into a\n * name that two steps can be compared against, which is the difference between \"this was reviewed\" and \"something\n * was reviewed once\".\n *\n * The hash covers tracked modifications *and* new files, because a change that only adds files has an empty\n * `git diff` and would otherwise share a revision with a clean tree \u2014 the most dangerous collision available here.\n */\n\nexport interface RevisionOptions {\n cwd: string;\n /** Untracked files to include. Defaults to everything git would show as untracked and not ignored. */\n timeoutMs?: number;\n}\n\nexport interface WorkSnapshot {\n /** sha-256 over the diff and the new files, or the hash of \"nothing\" when the tree is clean. */\n revision: string;\n /** Repo-relative paths this work touches, sorted. Empty when the tree is clean. */\n files: string[];\n /** The new files among them: they are copied into an isolated review rather than patched into it. */\n newFiles: string[];\n clean: boolean;\n /** The repository root, resolved from whatever directory we were pointed at. */\n repoRoot: string;\n}\n\n/** The sha-256 of an empty snapshot: a clean tree always has this revision, on every machine. */\nexport const CLEAN_REVISION = createHash(\"sha256\")\n .update(\"fanout/work/v1\\n\")\n .update(\"\\0staged\\0\")\n .digest(\"hex\");\n\n/**\n * What the working tree currently holds, and its name.\n *\n * Deliberately not `git stash create` or `write-tree`: both write objects into the repository, and a tool that\n * inspects your work must not change it. This only reads.\n */\nexport async function workSnapshot(options: RevisionOptions): Promise<WorkSnapshot> {\n const at =\n (cwd: string) =>\n (args: readonly string[]): Promise<string> =>\n git(args, { cwd, ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) });\n\n /*\n * Everything is asked of the repository root, never of whatever directory we happened to be started in.\n * `git ls-files --others` lists only files beneath its working directory and names them relative to it, so\n * running from a package subdirectory would silently miss new files elsewhere and mix two kinds of path.\n */\n const repoRoot = (await at(options.cwd)([\"rev-parse\", \"--show-toplevel\"])).trim();\n const run = at(repoRoot);\n\n // `--no-ext-diff` and `--no-color` so a user's own diff settings cannot change the identity of their work.\n const tracked = await run([\"diff\", \"HEAD\", \"--no-ext-diff\", \"--no-color\"]);\n /*\n * Staged work is hashed separately. `git diff HEAD` compares the working tree with HEAD, so a change that was\n * staged and then reverted in the working tree is invisible to it while still sitting in the index, ready to be\n * committed \u2014 a clean-looking tree that is not clean.\n */\n const staged = await run([\"diff\", \"--cached\", \"HEAD\", \"--no-ext-diff\", \"--no-color\"]);\n const untracked = zeroSeparated(await run([\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"])).sort();\n\n const hash = createHash(\"sha256\").update(\"fanout/work/v1\\n\");\n hash.update(tracked);\n hash.update(\"\\0staged\\0\");\n hash.update(staged);\n for (const path of untracked) {\n // The path goes in as well as the bytes: moving a new file is a change, even when its contents are identical.\n hash.update(`\\0new\\0${path}\\0`);\n hash.update(await run([\"hash-object\", \"--\", path]));\n }\n\n const changed = zeroSeparated(await run([\"diff\", \"HEAD\", \"--name-only\", \"-z\"]));\n const stagedNames = zeroSeparated(await run([\"diff\", \"--cached\", \"HEAD\", \"--name-only\", \"-z\"]));\n const files = [...new Set([...changed, ...stagedNames, ...untracked])].sort();\n\n return {\n revision: hash.digest(\"hex\"),\n files,\n newFiles: [...untracked],\n clean: files.length === 0,\n repoRoot,\n };\n}\n", "import {\n copyFileSync,\n lstatSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n realpathSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative } from \"node:path\";\nimport { pathInScope } from \"fanout-core\";\nimport { DEFAULT_DENY_LIST } from \"../workspace/deny.ts\";\nimport { git, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * A copy of the lead's uncommitted work, with nothing else in it.\n *\n * Isolation is the third non-negotiable and it is not satisfied by a read-only sandbox: read-only stops a reviewer\n * writing, not reading, so a reviewer launched in the repository can open `.env`, a private key, or any other\n * ignored file that happens to be lying there. Filtering which paths we *tell* it about changes nothing, because\n * its tools can look anywhere.\n *\n * So the reviewer never sees the repository. It sees a fresh worktree at HEAD with exactly the changes applied \u2014\n * ignored files do not exist in a worktree, which makes that half of the guarantee structural rather than a\n * promise about behaviour.\n *\n * Three ways secrets got in anyway, all found by a second vendor reviewing this file, all now closed: a `.env`\n * that HEAD *tracks* lands in the worktree and has to be deleted from the copy (the deny-list, the same one the\n * mission workspaces use); an untracked symlink with an innocent name dereferences to whatever it points at, so\n * links are refused rather than followed; and work that is staged but reverted in the working tree is invisible\n * to `git diff HEAD`, so the reviewer would have read a copy missing the very change being reviewed.\n */\n\nexport interface IsolatedWork {\n /** Where the reviewer should run. Contains the repository at HEAD plus the uncommitted changes. */\n path: string;\n /** Files deliberately kept out of the copy. The caller tells the user, so nobody wonders why a file is missing. */\n refused: Refused[];\n /** Removes the copy. Safe to call twice. */\n dispose: () => Promise<void>;\n}\n\nexport interface IsolateOptions {\n repoRoot: string;\n /** Repo-relative paths that are new files, from the snapshot; they are copied in, not patched. */\n newFiles: readonly string[];\n timeoutMs?: number;\n denyList?: readonly string[];\n}\n\n/** A file the copy refused to include, and why \u2014 reported, never silently dropped. */\nexport interface Refused {\n path: string;\n reason: \"deny-list\" | \"symlink\";\n}\n\n/**\n * Removes every symbolic link in the copy that points outside it.\n *\n * Found by a cold reader refuting the claim that this could not happen: the earlier guard only covered untracked\n * files copied in, while `git worktree add` faithfully checks out symlinks that HEAD already tracks \u2014 and a\n * tracked link may point at an ignored `.env`, at `~/.ssh/id_rsa`, or anywhere else on the machine. The copy is\n * supposed to be the only thing a reviewer can read; a link out of it is a hole in exactly that.\n *\n * Links that stay inside the copy are left alone: they are part of the repository's own shape, and a reviewer\n * following one reads only what it was already shown.\n *\n * Containment is decided by asking the filesystem, never by reading the path. A cold reader refuted the lexical\n * version of this check with a two-link chain \u2014 `a -> .` beside `leak -> a/../secret` \u2014 where `path.resolve`\n * folds `a/..` away textually and calls the target contained, while the kernel follows `a` to the root first and\n * lands `..` in the parent. Only `realpath`, which walks every link, knows where a path actually goes.\n */\nfunction cutEscapingLinks(root: string): Refused[] {\n /*\n * Walked from the resolved root, not the given one. On macOS a temporary directory is handed out as `/var/...`\n * and resolves to `/private/var/...`; comparing one against the other makes every link inside the copy look\n * like an escape, and this cut all of them until a test said so.\n */\n const inside = realpathSync.native(root);\n const cut: Refused[] = [];\n\n const walk = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const full = join(directory, entry.name);\n // `.git` in a linked worktree is a file pointing at the real repository, which is not ours to rewrite.\n if (entry.name === \".git\") continue;\n\n if (entry.isSymbolicLink()) {\n if (!staysInside(inside, full)) {\n rmSync(full, { force: true });\n cut.push({ path: relative(inside, full), reason: \"symlink\" });\n }\n continue;\n }\n if (entry.isDirectory()) walk(full);\n }\n };\n\n walk(inside);\n return cut;\n}\n\n/**\n * Does following this link, all the way, land inside `root`?\n *\n * `realpath` resolves every link in the chain, which is the only answer that matches what a reader actually gets.\n * A link we cannot resolve at all \u2014 dangling, or a loop \u2014 is cut: it shows a reviewer nothing, and a path the\n * filesystem will not explain is not one we can promise anything about.\n */\nexport function staysInside(root: string, link: string): boolean {\n let real: string;\n let inside: string;\n try {\n // Both sides resolved the same way, or a macOS `/var` against a `/private/var` makes everything look outside.\n inside = realpathSync.native(root);\n /*\n * `.native` is not an optimisation here, it is the correctness. Node's JavaScript `realpathSync` folds `..`\n * segments lexically as it goes, so a chain like `a -> .` beside `leak -> a/a/../../etc/passwd` resolves to a\n * path *inside* the copy while opening it reaches the real `/etc/passwd`. Measured on this machine: the JS\n * version answered `<copy>/etc/passwd`, the native one `/private/etc/passwd`, and reading the link returned\n * the system file. Only the operating system's own resolver is a security boundary.\n */\n real = realpathSync.native(link);\n } catch {\n return false;\n }\n // An empty result means the link resolves to the copy's own root, which is inside it. The chain that made that\n // dangerous is dead anyway: every link is now followed to where it really goes before this is asked.\n const stepsOut = relative(inside, real);\n return !stepsOut.startsWith(\"..\") && !isAbsolute(stepsOut);\n}\n\n/** Builds a throwaway worktree holding HEAD plus whatever is currently uncommitted. */\nexport async function isolateWork(options: IsolateOptions): Promise<IsolatedWork> {\n const run = (args: readonly string[], cwd: string = options.repoRoot): Promise<string> =>\n git(args, { cwd, ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) });\n\n const root = mkdtempSync(join(tmpdir(), \"fanout-review-\"));\n const patches = mkdtempSync(join(tmpdir(), \"fanout-patch-\"));\n const path = join(root, \"work\");\n let created = false;\n\n /*\n * Patches are written beside the copy and applied by file, so that every git call in this module goes through\n * the one helper that closes the environment. There used to be a second, bespoke invocation here that piped the\n * patch to stdin and inherited the shell's \u2014 which in an editor's integrated terminal means its GIT_ASKPASS,\n * its IPC auth token, and the user's system git config. Deleting the second path is a better guarantee than\n * testing it, because there is now nothing left to drift.\n */\n const applyPatch = async (patch: string, name: string): Promise<void> => {\n // Written outside the copy's own parent and removed immediately: `..` from the copy should hold nothing\n // worth reaching, so that a link we failed to catch has less to find.\n const file = join(patches, name);\n writeFileSync(file, patch, \"utf8\");\n try {\n await run([\"apply\", \"--whitespace=nowarn\", file], path);\n } finally {\n rmSync(file, { force: true });\n }\n };\n\n const dispose = async (): Promise<void> => {\n if (created) {\n // `git worktree remove` first so the repository's administrative files are updated, not orphaned.\n try {\n await run([\"worktree\", \"remove\", \"--force\", path]);\n } catch {\n // A worktree we cannot unregister still must not be left on disk.\n }\n }\n rmSync(root, { recursive: true, force: true });\n rmSync(patches, { recursive: true, force: true });\n };\n\n try {\n await run([\"worktree\", \"add\", \"--detach\", \"--quiet\", path, \"HEAD\"]);\n created = true;\n\n const denyList = options.denyList ?? DEFAULT_DENY_LIST;\n const refused: Refused[] = [];\n\n /*\n * A secret that HEAD tracks is already in this worktree, because a worktree is a checkout of HEAD. Ignored\n * files never arrive, but a committed `.env` does, so it is removed from the copy before anything runs.\n */\n for (const file of zeroSeparated(await run([\"ls-tree\", \"-r\", \"-z\", \"--name-only\", \"HEAD\"], path))) {\n if (denyList.some((pattern) => pathInScope(file, pattern))) {\n rmSync(join(path, file), { force: true });\n refused.push({ path: file, reason: \"deny-list\" });\n }\n }\n\n // The working tree as it stands.\n const patch = await run([\"diff\", \"HEAD\", \"--no-ext-diff\", \"--no-color\", \"--binary\"]);\n if (patch.trim() !== \"\") await applyPatch(patch, \"worktree.patch\");\n\n /*\n * Then any file whose *index* differs from HEAD but whose working tree does not: staged, then reverted. It is\n * invisible to the patch above, and a reviewer given a copy without it would be reviewing different work from\n * the one whose revision we record.\n */\n const inWorktree = new Set(zeroSeparated(await run([\"diff\", \"HEAD\", \"--name-only\", \"-z\"])));\n const stagedOnly = zeroSeparated(await run([\"diff\", \"--cached\", \"HEAD\", \"--name-only\", \"-z\"])).filter(\n (file) => !inWorktree.has(file),\n );\n if (stagedOnly.length > 0) {\n const staged = await run([\n \"diff\",\n \"--cached\",\n \"HEAD\",\n \"--no-ext-diff\",\n \"--no-color\",\n \"--binary\",\n \"--\",\n ...stagedOnly,\n ]);\n if (staged.trim() !== \"\") await applyPatch(staged, \"staged.patch\");\n }\n\n /*\n * New files are copied rather than patched. They come from the snapshot, which asks git for untracked files\n * excluding standard ignores \u2014 but \"not ignored\" is not the same as \"safe to show\", so each one is checked\n * again here.\n */\n for (const file of options.newFiles) {\n if (denyList.some((pattern) => pathInScope(file, pattern))) {\n refused.push({ path: file, reason: \"deny-list\" });\n continue;\n }\n const source = join(options.repoRoot, file);\n /*\n * `copyFileSync` follows symlinks, so an untracked link innocently named `notes.txt` and pointing at an\n * ignored `.env` \u2014 or anywhere outside the repository at all \u2014 would materialise that file's contents in\n * the copy. Links are refused rather than resolved: a reviewer has no need of one.\n */\n if (lstatSync(source).isSymbolicLink()) {\n refused.push({ path: file, reason: \"symlink\" });\n continue;\n }\n const destination = join(path, file);\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(source, destination);\n }\n\n // Last, because a link can arrive three ways \u2014 checked out from HEAD, added by a patch, or copied in \u2014 and\n // only a sweep of what is actually on disk catches all three.\n refused.push(...cutEscapingLinks(path));\n\n return { path, refused, dispose };\n } catch (cause) {\n await dispose();\n throw cause;\n }\n}\n", "import type { AdapterManifest } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\n\n/*\n * Running a seat's CLI once, read-only, and getting back what it said.\n *\n * Shared by everything that asks another vendor a question about code it did not write. The environment is an\n * allowlist (see `env.ts`), the mode is the read-only one the seat's own manifest names, and an unsupplied\n * placeholder is removed along with its flag rather than becoming an empty string \u2014 a CLI is entitled to reject\n * `-m \"\"`, and one of them does.\n */\n\nexport type SeatExecute = (\n binary: string,\n args: readonly string[],\n options: { cwd: string; timeoutMs: number },\n) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n\nexport interface RunSeatOptions {\n manifest: AdapterManifest;\n cwd: string;\n prompt: string;\n model?: string;\n timeoutMs?: number;\n execute?: SeatExecute;\n}\n\nexport interface SeatAnswer {\n /** False when the CLI could not run, exited non-zero, or said nothing we could read. */\n ok: boolean;\n /** Everything the agent said, joined. Empty when `ok` is false. */\n text: string;\n /** Why it failed, when it did. */\n problem: string;\n}\n\n/** Asks a seat a question about the code in `cwd`, read-only, and returns its answer. */\nexport async function runSeat(options: RunSeatOptions): Promise<SeatAnswer> {\n const { manifest } = options;\n const args = fillTemplate(manifest.headless.args, {\n \"{workdir}\": options.cwd,\n \"{sandbox}\": manifest.permissionModes.readOnly,\n \"{prompt}\": options.prompt,\n ...(options.model === undefined ? {} : { \"{model}\": options.model }),\n });\n\n const execute = options.execute ?? runCliOnce;\n let stdout: string;\n try {\n const result = await execute(manifest.binary, args, {\n cwd: options.cwd,\n timeoutMs: options.timeoutMs ?? 10 * 60_000,\n });\n if (result.exitCode !== 0) {\n return { ok: false, text: \"\", problem: firstLines(result.stderr || result.stdout) };\n }\n stdout = result.stdout;\n } catch (cause) {\n return { ok: false, text: \"\", problem: cause instanceof Error ? cause.message : String(cause) };\n }\n\n const text = agentText(stdout);\n // An exit code of zero is not an answer. A CLI that printed nothing we recognise has told us nothing.\n if (text === null) {\n return { ok: false, text: \"\", problem: \"the seat exited cleanly but said nothing we could read\" };\n }\n return { ok: true, text, problem: \"\" };\n}\n\n/**\n * What the agent actually said, out of its stream.\n *\n * Null when the stream held no agent message at all \u2014 different from an agent that said nothing, and never to be\n * reported as one.\n */\nexport function agentText(stream: string): string | null {\n const messages: string[] = [];\n for (const line of stream.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n try {\n const parsed: unknown = JSON.parse(line);\n const item = (parsed as { item?: { type?: string; text?: string } }).item;\n if (item?.type === \"agent_message\" && typeof item.text === \"string\") messages.push(item.text);\n } catch {\n // A line that is not JSON is the CLI talking to a human; the answer is in the ones that are.\n }\n }\n return messages.length === 0 ? null : messages.join(\"\\n\\n\");\n}\n\n/**\n * Fills an argument template, dropping any placeholder nobody supplied and the flag in front of it.\n *\n * Found by running this for real: with no model chosen, `[\"-m\", \"{model}\"]` became `[\"-m\", \"\"]` and Codex answered\n * `The '' model is not supported`. An unsupplied option must vanish, not become an empty value.\n */\nexport function fillTemplate(\n template: readonly string[],\n values: Readonly<Record<string, string>>,\n): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n const placeholder = /^\\{[a-z]+\\}$/.test(argument) ? argument : null;\n if (placeholder !== null && !Object.hasOwn(values, placeholder)) {\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction firstLines(text: string, count = 5): string {\n return text.split(\"\\n\").slice(0, count).join(\"\\n\").trim();\n}\n\n/**\n * Runs the CLI with its standard input closed.\n *\n * Every manifest declares `stdin: \"closed\"` and this is where that is honoured. Without a terminal, `codex exec`\n * waits on \"Reading additional input from stdin\u2026\" and never returns \u2014 a pipe nobody writes to is not the same as\n * no input at all. It cost an hour of a run that looked busy and was blocked, in code whose own manifest says the\n * rule out loud, which is the argument for honouring declarations rather than remembering them.\n */\nexport const runCliOnce: SeatExecute = async (binary, args, options) => {\n const { execFile } = await import(\"node:child_process\");\n\n // Resolved either way; the caller turns a failure into an answer of \"we could not ask\", never into a verdict.\n const outcome = await new Promise<\n { stdout: string; stderr: string; exitCode: number } | { failure: Error }\n >((settle) => {\n const child = execFile(\n binary,\n [...args],\n {\n cwd: options.cwd,\n timeout: options.timeoutMs,\n env: baseEnv(),\n maxBuffer: 64 * 1024 * 1024,\n windowsHide: true,\n },\n (error, stdout, stderr) => {\n if (error === null) {\n settle({ stdout, stderr, exitCode: 0 });\n return;\n }\n const code = (error as { code?: number }).code;\n // A CLI that answers with a non-zero exit is answering, not failing to run.\n if (typeof code === \"number\") settle({ stdout, stderr, exitCode: code });\n else settle({ failure: error });\n },\n );\n child.stdin?.end();\n });\n\n if (\"failure\" in outcome) throw outcome.failure;\n return outcome;\n};\n", "import type { AdapterManifest, FanoutEventInput, SeatRef } from \"fanout-core\";\nimport { isolateWork } from \"./isolate.ts\";\nimport { runCliOnce } from \"./run-seat.ts\";\nimport { workSnapshot, type WorkSnapshot } from \"./revision.ts\";\n\n/*\n * A second vendor, reading the lead's own uncommitted work.\n *\n * This is the part of Fanout that earns its place in a session where no agent ran at all. Most of the code in a\n * Claude Code session is written by the lead, and the lead is the one reviewer it gets \u2014 which is exactly how a\n * confident mistake ships. Pointing another vendor's own review command at the working tree costs one call and\n * breaks that loop, because a different model does not share the author's blind spots.\n *\n * It reads, and it reads a copy. A read-only sandbox stops a reviewer writing, not reading, so a reviewer\n * launched in the repository could open `.env` or a private key that happens to be lying there \u2014 which is why the\n * work is rebuilt in a throwaway worktree first, where ignored files simply do not exist. Its answer is recorded\n * verbatim rather than summarised by the author it is about.\n */\n\nexport interface BuddyOptions {\n repoRoot: string;\n /** The seat doing the reading. Must declare a `review` capability; nothing is guessed if it does not. */\n manifest: AdapterManifest;\n model?: string;\n timeoutMs?: number;\n /** Injected in tests so nothing needs a CLI installed. */\n execute?: (\n binary: string,\n args: readonly string[],\n options: { cwd: string; timeoutMs: number },\n ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n}\n\nexport interface BuddyResult {\n snapshot: WorkSnapshot;\n /** The event to record. Always produced, including when the reviewer could not run. */\n event: Extract<FanoutEventInput, { type: \"buddy.reviewed\" }>;\n}\n\nexport class BuddyUnavailable extends Error {\n readonly seat: string;\n\n constructor(seat: string, reason: string) {\n super(`${seat} cannot review: ${reason}`);\n this.name = \"BuddyUnavailable\";\n this.seat = seat;\n }\n}\n\n/** Asks the seat to review whatever is currently uncommitted, and returns what it said. */\nexport async function buddyReview(options: BuddyOptions): Promise<BuddyResult> {\n const { manifest } = options;\n const review = manifest.capabilities.review;\n if (review === null) {\n throw new BuddyUnavailable(manifest.id, \"its CLI has no non-interactive review command\");\n }\n\n const snapshot = await workSnapshot({ cwd: options.repoRoot });\n const by: SeatRef = { id: manifest.id, ...(options.model === undefined ? {} : { model: options.model }) };\n\n const base = {\n type: \"buddy.reviewed\" as const,\n repoRoot: options.repoRoot,\n revision: snapshot.revision,\n by,\n files: snapshot.files,\n };\n\n // Nothing to read is not a finding, and asking anyway would spend a subscription to be told so.\n if (snapshot.clean) {\n return { snapshot, event: { ...base, findings: \"\", ran: true } };\n }\n\n const isolated = await isolateWork({\n repoRoot: snapshot.repoRoot,\n newFiles: snapshot.newFiles,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n /*\n * Building the copy takes a moment, and an editor saving in that moment would leave us reviewing one set of\n * bytes while recording the revision of another \u2014 a review that certifies work nobody read. Cheaper to look\n * again than to reason about the window: if the work moved, say so and let the caller ask again.\n */\n const after = await workSnapshot({ cwd: snapshot.repoRoot });\n if (after.revision !== snapshot.revision) {\n await isolated.dispose();\n return {\n snapshot: after,\n event: {\n ...base,\n revision: after.revision,\n files: after.files,\n findings: \"your files changed while the review copy was being made; nothing was reviewed\",\n ran: false,\n },\n };\n }\n\n const args = fill(review.args, {\n \"{workdir}\": isolated.path,\n // A reviewer reads; it is given the read-only mode its own manifest names, never the editing one.\n \"{sandbox}\": manifest.permissionModes.readOnly,\n ...(options.model === undefined ? {} : { \"{model}\": options.model }),\n });\n\n const execute = options.execute ?? runCliOnce;\n let stdout: string;\n try {\n const result = await execute(manifest.binary, args, {\n cwd: isolated.path,\n timeoutMs: options.timeoutMs ?? 10 * 60_000,\n });\n if (result.exitCode !== 0) {\n /*\n * A reviewer that failed has not approved anything. Recording `ran: false` with the reason keeps \"we asked\n * and it broke\" distinguishable from \"it found nothing\" \u2014 which would otherwise read as a clean bill.\n */\n return {\n snapshot,\n event: { ...base, findings: firstLines(result.stderr || result.stdout), ran: false },\n };\n }\n stdout = result.stdout;\n } catch (cause) {\n return { snapshot, event: { ...base, findings: describe(cause), ran: false } };\n } finally {\n await isolated.dispose();\n }\n\n const findings = findingsFrom(stdout, isolated.path);\n const refused = isolated.refused;\n /*\n * An exit code of zero is not a review. A CLI that printed nothing we recognise has not told us the code is\n * fine, and recording that as a completed review with no findings would turn silence into a clean bill of\n * health \u2014 the exact shape of dishonesty this project refuses.\n */\n if (findings === null) {\n return {\n snapshot,\n event: { ...base, findings: \"the reviewer exited cleanly but said nothing we could read\", ran: false },\n };\n }\n\n /*\n * A file kept out of the copy is said out loud. A reviewer that never saw a file has not approved it, and a\n * silent omission is the difference between \"reviewed\" and \"reviewed most of it\".\n */\n const note =\n refused.length === 0\n ? \"\"\n : `\\n\\nNot shown to the reviewer: ${refused.map((item) => `${item.path} (${item.reason})`).join(\", \")}`;\n\n return { snapshot, event: { ...base, findings: `${findings}${note}`, ran: true } };\n}\n\n/**\n * The reviewer's own words, pulled out of its stream.\n *\n * Codex reports a review as prose inside an `agent_message`, with a `- [P1] title \u2014 path:lines` convention and no\n * severity or file field to read (verified 2026-09-12). So this deliberately does not parse findings into\n * structure: inventing a schema over a convention would produce confident, wrong severities the moment the\n * convention shifts. The lead reads the prose, which is what a second opinion is for.\n *\n * Returns null when the stream held no reviewer message at all, which is a different thing from a review with\n * nothing to say and must never be reported as one.\n */\nfunction findingsFrom(stream: string, repoRoot: string): string | null {\n const messages: string[] = [];\n for (const line of stream.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n try {\n const parsed: unknown = JSON.parse(line);\n const item = (parsed as { item?: { type?: string; text?: string } }).item;\n if (item?.type === \"agent_message\" && typeof item.text === \"string\") messages.push(item.text);\n } catch {\n // An unparsable line is the CLI talking to a human, not to us; the findings are in the parsed ones.\n }\n }\n if (messages.length === 0) return null;\n // Reviewers report absolute paths \u2014 here, paths inside the throwaway copy. Making them repo-relative is the\n // difference between a clickable finding and a line naming a directory that no longer exists.\n return messages.join(\"\\n\\n\").split(`${repoRoot}/`).join(\"\");\n}\n\n/**\n * Fills a manifest's argument template, dropping any placeholder nobody supplied \u2014 and the flag in front of it.\n *\n * Found by running this for real: with no model chosen, `[\"-m\", \"{model}\"]` became `[\"-m\", \"\"]`, and Codex\n * answered `The '' model is not supported`. An unsupplied option must vanish, not become an empty string, because\n * an empty string is a value and CLIs are entitled to reject it.\n */\nfunction fill(template: readonly string[], values: Readonly<Record<string, string>>): string[] {\n const filled: string[] = [];\n for (const argument of template) {\n const placeholder = /^\\{[a-z]+\\}$/.test(argument) ? argument : null;\n if (placeholder !== null && !Object.hasOwn(values, placeholder)) {\n // Drop the flag this value belonged to, so `-m` does not survive without its model.\n if (filled[filled.length - 1]?.startsWith(\"-\") === true) filled.pop();\n continue;\n }\n filled.push(\n Object.entries(values).reduce((text, [name, value]) => text.split(name).join(value), argument),\n );\n }\n return filled;\n}\n\nfunction firstLines(text: string, count = 5): string {\n return text.split(\"\\n\").slice(0, count).join(\"\\n\").trim();\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import type { AdapterManifest, FanoutEventInput, SeatRef } from \"fanout-core\";\nimport { isolateWork } from \"./isolate.ts\";\nimport { CLEAN_REVISION, workSnapshot, type WorkSnapshot } from \"./revision.ts\";\nimport { runSeat, type SeatExecute } from \"./run-seat.ts\";\n\n/*\n * Asking a cold reader to falsify what the lead believes.\n *\n * The lead carries the plan, the reasoning and the justification for every line it wrote, and that context is\n * exactly what hides its mistakes from it: knowing why the code is right makes the code look right. A reader with\n * only the diff is not smarter, it is differently placed. Broad review pays for that asymmetry by the token;\n * three specific claims get it for almost nothing.\n *\n * Every rule here bends one way. A verdict we cannot read is `unclear`, a claim the reader skipped is `unclear`,\n * and a reader that never ran refutes nothing and confirms nothing. Confirmation has to be said out loud, because\n * the whole value of this is that it cannot be satisfied by silence.\n */\n\nexport type Verdict = \"confirmed\" | \"refuted\" | \"unclear\";\n\nexport interface CheckedClaim {\n claim: string;\n verdict: Verdict;\n evidence: string;\n}\n\nexport interface ClaimsOptions {\n repoRoot: string;\n claims: readonly string[];\n manifest: AdapterManifest;\n model?: string;\n timeoutMs?: number;\n execute?: SeatExecute;\n}\n\nexport interface ClaimsResult {\n event: Extract<FanoutEventInput, { type: \"claims.checked\" }>;\n /** Claims the reader actively refuted. The only reason to stop and look. */\n refuted: CheckedClaim[];\n}\n\n/** The verdict line we ask for, and the only one we will read as an answer. */\nconst VERDICT_LINE = /^\\s*CLAIM\\s+(\\d+)\\s*:\\s*(CONFIRMED|REFUTED|UNCLEAR)\\b\\s*[-\u2014:]?\\s*(.*)$/i;\n\nexport async function checkClaims(options: ClaimsOptions): Promise<ClaimsResult> {\n /*\n * A session started outside a repository is an ordinary thing, not an exception. Throwing here would make the\n * tool look broken to whoever called it; answering \"there is nothing here to check\" is both true and useful.\n */\n let snapshot: WorkSnapshot;\n try {\n snapshot = await workSnapshot({ cwd: options.repoRoot });\n } catch {\n return {\n event: {\n type: \"claims.checked\",\n repoRoot: options.repoRoot,\n revision: CLEAN_REVISION,\n by: { id: options.manifest.id },\n claims: options.claims.map((claim) =>\n unclear(claim, `${options.repoRoot} is not a git repository, so there are no changes to check`),\n ),\n ran: false,\n },\n refuted: [],\n };\n }\n const by: SeatRef = {\n id: options.manifest.id,\n ...(options.model === undefined ? {} : { model: options.model }),\n };\n\n const base = {\n type: \"claims.checked\" as const,\n repoRoot: snapshot.repoRoot,\n revision: snapshot.revision,\n by,\n };\n\n /*\n * Only uncommitted work, and the message has to say so. This reads what is in the tree right now because the\n * point is to catch a belief before it lands \u2014 the reader gets the diff and nothing else, which is what makes\n * it differently placed. Saying merely \"no changes\" reads as \"nothing is wrong\" to whoever asked, when the\n * truth is that nothing was looked at: the two are opposite answers and the caller cannot tell them apart.\n */\n if (snapshot.clean) {\n return {\n event: {\n ...base,\n claims: options.claims.map((c) =>\n unclear(\n c,\n \"the working tree is clean, and this checks uncommitted work only \u2014 nothing was read, which is \" +\n \"not the same as nothing being wrong. State your claims before you commit.\",\n ),\n ),\n ran: false,\n },\n refuted: [],\n };\n }\n\n const isolated = await isolateWork({\n repoRoot: snapshot.repoRoot,\n newFiles: snapshot.newFiles,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n try {\n const result = await runSeat({\n manifest: options.manifest,\n cwd: isolated.path,\n prompt: promptFor(options.claims),\n ...(options.model === undefined ? {} : { model: options.model }),\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n\n if (!result.ok) {\n /*\n * The reason travels with the verdict. An earlier version returned a flat \"not checked\" here, which is true\n * and useless: it told the owner nothing and told me nothing when this failed on its first real run.\n */\n return {\n event: {\n ...base,\n claims: options.claims.map((claim) => unclear(claim, result.problem)),\n ran: false,\n },\n refuted: [],\n };\n }\n\n const claims = readVerdicts(options.claims, result.text);\n return { event: { ...base, claims, ran: true }, refuted: claims.filter((c) => c.verdict === \"refuted\") };\n } finally {\n await isolated.dispose();\n }\n}\n\n/**\n * What we ask the reader.\n *\n * It is told to try to falsify, not to agree, and told that saying \"I cannot tell\" is a real answer. A reader\n * nudged toward confirmation will confirm, which would make every run of this worthless and expensive at once.\n */\nfunction promptFor(claims: readonly string[]): string {\n const numbered = claims.map((claim, index) => `${String(index + 1)}. ${claim}`).join(\"\\n\");\n return [\n \"You are reading a diff you did not write, with no knowledge of why it was written.\",\n \"Below are claims its author makes about it. Your job is to try to FALSIFY each one by reading the code.\",\n \"\",\n \"Rules:\",\n \"- Answer every claim, in order, one line each, in exactly this format:\",\n \" CLAIM <n>: CONFIRMED|REFUTED|UNCLEAR - <one sentence of evidence, naming a file and line where you can>\",\n \"- REFUTED means you found a concrete case where the claim does not hold. Name it.\",\n \"- UNCLEAR is a real answer. Use it when the diff does not let you tell. Do not guess, and do not\",\n \" confirm something you merely failed to disprove.\",\n \"- CONFIRMED means you actively checked and it holds.\",\n \"- Say nothing else before or after the CLAIM lines.\",\n \"\",\n \"Claims:\",\n numbered,\n ].join(\"\\n\");\n}\n\n/**\n * Reads the reader's verdicts, and refuses to invent any it did not give.\n *\n * A missing line, an unparsable line, or a line for a claim that does not exist all leave that claim `unclear`.\n * The failure mode this protects against is the one that matters: a checker that quietly reports everything fine\n * whenever the output format drifts is worse than no checker, because it is trusted.\n */\nexport function readVerdicts(claims: readonly string[], text: string): CheckedClaim[] {\n const found = new Map<number, { verdict: Verdict; evidence: string }>();\n\n for (const line of text.split(\"\\n\")) {\n const match = VERDICT_LINE.exec(line);\n if (match === null) continue;\n const index = Number(match[1]) - 1;\n const word = (match[2] ?? \"\").toLowerCase();\n if (index < 0 || index >= claims.length) continue;\n if (word !== \"confirmed\" && word !== \"refuted\" && word !== \"unclear\") continue;\n // First answer wins: a reader that contradicts itself later has not confirmed anything.\n if (!found.has(index)) found.set(index, { verdict: word, evidence: (match[3] ?? \"\").trim() });\n }\n\n return claims.map((claim, index) => {\n const answer = found.get(index);\n if (answer === undefined) return unclear(claim, \"the reader did not answer this claim\");\n // A refusal with no reason is not actionable, but it is still a refusal \u2014 we keep it and say the reason is missing.\n return {\n claim,\n verdict: answer.verdict,\n evidence: answer.evidence === \"\" ? \"(no reason given)\" : answer.evidence,\n };\n });\n}\n\nfunction unclear(claim: string, evidence: string): CheckedClaim {\n return { claim, verdict: \"unclear\", evidence };\n}\n", "import { readFileSync } from \"node:fs\";\n\n/*\n * The mission view's page, read from disk beside this file.\n *\n * It is one self-contained HTML file with no framework, no bundler and no dependencies (ADR 0019), because this\n * page renders your private source code and every dependency it carried would be one more thing that could read\n * it. Kept as `.html` rather than a template string so it stays a file a person can open, lint and read.\n *\n * Read on every request rather than cached. It is a few kilobytes off a local disk for a page only this machine\n * can reach, and caching it meant an edit did nothing until the daemon was restarted \u2014 which is how the first\n * version of this was reviewed against a screen that had not changed.\n */\n\n/** The page, with `{{TOKEN}}` still in it: the daemon stamps its own token in as it serves. */\nexport function missionViewHtml(): string {\n return readFileSync(new URL(\"./view.html\", import.meta.url), \"utf8\");\n}\n", "import { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readdirSync, renameSync, rmSync, symlinkSync, type Dirent } from \"node:fs\";\nimport { dirname, join, relative } from \"node:path\";\nimport { baseEnv } from \"../env.ts\";\nimport { workSnapshot } from \"./revision.ts\";\n\n/*\n * Running the project's own checks against what an agent actually wrote.\n *\n * The agent already told us its tests pass. That is not evidence: it is the account of the only party with an\n * interest in the answer, produced inside a sandbox that could not open a port or reach a toolchain. So the gate\n * runs the commands itself, in the run's own worktree, and believes the exit codes.\n *\n * The commands come from the plan \u2014 which the safety report showed the user before anything launched \u2014 and never\n * from an agent. A check an agent could choose is a check an agent can pass.\n */\n\nexport interface ChecksOptions {\n /** The worktree holding the agent's changes. */\n cwd: string;\n /** Exactly the commands the plan declared for this line, in order. */\n commands: readonly string[];\n /**\n * The repository the worktree came from. When given, its dependency directories are linked in for the length\n * of the check and removed afterwards \u2014 see `withDependencies`.\n */\n repoRoot?: string;\n timeoutMs?: number;\n /** Injected in tests so nothing needs a real toolchain. */\n run?: (command: string, cwd: string, timeoutMs: number) => Promise<CommandOutcome>;\n}\n\n/**\n * Directories a project keeps its installed dependencies in.\n *\n * A git worktree contains the tracked files and nothing else, so `npm run test` in one reports\n * `vitest: command not found` \u2014 which the gate would otherwise record as the project's checks failing. Found by\n * running the gate against a real agent's work rather than against a fixture.\n *\n * They are lent only while the check runs, never while the agent works. The agent's sandbox can write anywhere in\n * its worktree, and a link to the real `node_modules` would put the developer's installed packages inside the one\n * place an agent is allowed to write. An agent that cannot run the full suite is the expected case, and the\n * reason this gate runs it afterwards.\n */\nconst DEPENDENCY_NAMES = new Set([\"node_modules\", \".venv\", \"vendor\"]);\n\n/**\n * Every dependency directory in the repository, not only the one at the top.\n *\n * A workspace puts a package's links inside that package: without `packages/daemon/node_modules`, a test there\n * cannot resolve `fanout-core` however complete the root is. Lending only the root ran 90 of 656 tests \u2014 a\n * suite that looks like it ran and did not, which is the most expensive kind of green there is.\n *\n * The depth is generous rather than tight because the first attempt stopped at three and missed\n * `packages/adapters/codex/node_modules` at four, leaving that package's tests unable to import anything. It\n * costs a bounded directory walk that never descends into a dependency directory, and guessing how deeply\n * someone nests their packages is not a guess worth making.\n */\nfunction dependencyDirectories(root: string, depth = 6): string[] {\n if (depth === 0) return [];\n const found: string[] = [];\n let entries: Dirent[];\n try {\n entries = readdirSync(root, { withFileTypes: true });\n } catch {\n return found;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".git\")) continue;\n if (DEPENDENCY_NAMES.has(entry.name)) {\n found.push(join(root, entry.name));\n continue; // Never descend into one: its own node_modules are its business.\n }\n found.push(...dependencyDirectories(join(root, entry.name), depth - 1));\n }\n return found;\n}\n\nexport interface CommandOutcome {\n exitCode: number | null;\n /** Combined output, newest-relevant last, capped. */\n output: string;\n timedOut: boolean;\n}\n\nexport interface ChecksResult {\n ok: boolean;\n /** What the work looked like when these commands ran, so a merge can refuse a diff that has moved since. */\n revision: string;\n commands: string[];\n summary: string;\n /** Per command, so a person can see which one broke without reading everything. */\n outcomes: { command: string; exitCode: number | null; timedOut: boolean; tail: string }[];\n}\n\nconst MAX_OUTPUT = 64 * 1024;\n\n/**\n * Runs every declared check, stopping at the first failure.\n *\n * Stopping early is deliberate: the second command's output after the first has failed is noise, and the answer\n * to \"may this merge\" was already settled by the first. Nothing is \"ok\" by default \u2014 a line with no checks\n * declared is reported as exactly that, not as a pass, because \"nothing failed\" and \"nothing ran\" are different\n * facts and only one of them is evidence.\n */\nexport async function runChecks(options: ChecksOptions): Promise<ChecksResult> {\n const snapshot = await workSnapshot({ cwd: options.cwd });\n const run = options.run ?? runCommand;\n const commands = [...options.commands];\n const outcomes: ChecksResult[\"outcomes\"] = [];\n\n if (commands.length === 0) {\n return {\n ok: false,\n revision: snapshot.revision,\n commands,\n summary: \"no checks were declared for this line, so nothing was verified\",\n outcomes,\n };\n }\n\n const unlink =\n options.repoRoot === undefined ? () => undefined : lendDependencies(options.repoRoot, options.cwd);\n try {\n for (const command of commands) {\n const outcome = await run(command, options.cwd, options.timeoutMs ?? 10 * 60_000);\n outcomes.push({\n command,\n exitCode: outcome.exitCode,\n timedOut: outcome.timedOut,\n tail: lastLines(outcome.output),\n });\n if (outcome.timedOut || outcome.exitCode !== 0) {\n return {\n ok: false,\n revision: snapshot.revision,\n commands,\n summary: outcome.timedOut\n ? `\\`${command}\\` did not finish in time`\n : `\\`${command}\\` exited ${String(outcome.exitCode)}`,\n outcomes,\n };\n }\n }\n\n return {\n ok: true,\n revision: snapshot.revision,\n commands,\n summary: `${String(commands.length)} check${commands.length === 1 ? \"\" : \"s\"} passed`,\n outcomes,\n };\n } finally {\n unlink();\n }\n}\n\n/**\n * Links a repository's dependency directories into a worktree, and returns how to take them away again.\n *\n * A link rather than a copy, because `node_modules` is enormous and this happens on every check. Removed in a\n * `finally` so a failing check does not leave the developer's installed packages reachable from a directory an\n * agent may later be allowed to write to.\n */\nfunction lendDependencies(repoRoot: string, worktree: string): () => void {\n const lent: string[] = [];\n const setAside: { was: string; now: string }[] = [];\n\n for (const source of dependencyDirectories(repoRoot)) {\n const destination = join(worktree, relative(repoRoot, source));\n\n /*\n * A dependency directory already in the worktree is moved out of the way, not merged with and not skipped.\n *\n * Both of the gentler options were tried against a real mission and both were wrong. Skipping on \"it exists\"\n * lent nothing, and four agents who had written four good files were all reported as having written code\n * that does not build \u2014 a false failure, which is worse than no check, because it blames the one party that\n * did nothing wrong. Filling in the missing entries then failed differently: an agent's sandboxed\n * `pnpm install` leaves a `node_modules` holding a 262-entry `.pnpm` store and no `.bin` at all, so the\n * lent `.bin/astro` resolved back into the agent's own half-downloaded store and could not find itself.\n *\n * A partial install cannot be repaired by symlinking around it, and it is not the agent's work: it is\n * ignored by git, it is the residue of an install that failed, and the check is supposed to run against the\n * developer's real dependencies. So it is renamed for the length of the check and put back afterwards \u2014\n * nothing is deleted, and a crash mid-check leaves it recoverable beside where it was.\n */\n if (existsSync(destination)) {\n const parked = `${destination}.fanout-aside`;\n try {\n rmSync(parked, { recursive: true, force: true });\n renameSync(destination, parked);\n setAside.push({ was: destination, now: parked });\n } catch {\n // Could not move it, so leave it alone and let the check say what it could not find.\n continue;\n }\n }\n\n try {\n mkdirSync(dirname(destination), { recursive: true });\n symlinkSync(source, destination, \"dir\");\n lent.push(destination);\n } catch {\n // Nothing lent and nothing to clean up: the check will say what it could not find.\n }\n }\n\n return () => {\n for (const path of lent) rmSync(path, { force: true });\n for (const { was, now } of setAside) {\n try {\n rmSync(was, { recursive: true, force: true });\n renameSync(now, was);\n } catch {\n // It stays beside where it was, which is recoverable and visible, rather than silently gone.\n }\n }\n };\n}\n\n/**\n * Runs one command the way a person would, and kills it if it will not stop.\n *\n * A shell, because the checks people write are shell (`npm run check && npm run lint`), and the user saw the\n * exact strings in the safety report before any of this started. The environment is the same allowlist agents\n * get, so a check cannot quietly depend on a secret in the developer's shell and then fail on someone else's\n * machine. Output is capped: a check that prints a hundred megabytes should not be able to exhaust the daemon.\n *\n * It runs in its own process group, and the deadline kills the group rather than the shell. Found by CI on Linux\n * while macOS passed: `sh -c \"sleep 30\"` leaves `sleep` as a child of the shell, so killing the shell leaves a\n * grandchild alive holding the pipes open and the promise never settles. A check that spawns anything \u2014 and every\n * real one does, that is what `npm test` is \u2014 could have hung the gate forever.\n */\nasync function runCommand(command: string, cwd: string, timeoutMs: number): Promise<CommandOutcome> {\n return new Promise<CommandOutcome>((resolve) => {\n const child = spawn(command, {\n cwd,\n shell: true,\n env: { ...baseEnv(), CI: \"1\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n // Its own process group, so the whole tree can be signalled and not just the shell at the top of it.\n detached: true,\n });\n\n let output = \"\";\n let timedOut = false;\n\n /** Signals every descendant. A check's children are the check. */\n const signalGroup = (signal: NodeJS.Signals): void => {\n if (child.pid === undefined) return;\n try {\n process.kill(-child.pid, signal);\n } catch {\n // Already gone: nothing to signal and nothing to report.\n }\n };\n const keep = (chunk: Buffer): void => {\n if (output.length < MAX_OUTPUT) output += chunk.toString().slice(0, MAX_OUTPUT - output.length);\n };\n child.stdout.on(\"data\", keep);\n child.stderr.on(\"data\", keep);\n\n const deadline = setTimeout(() => {\n timedOut = true;\n signalGroup(\"SIGTERM\");\n // A check that ignores SIGTERM is a check that has stopped being one.\n const escalate = setTimeout(() => {\n signalGroup(\"SIGKILL\");\n }, 5_000);\n escalate.unref();\n }, timeoutMs);\n deadline.unref();\n\n child.on(\"error\", (error) => {\n clearTimeout(deadline);\n resolve({ exitCode: null, output: `${output}\\n${error.message}`, timedOut });\n });\n /*\n * `exit` rather than `close`: close waits for every pipe to end, and an orphan holding stdout open would make\n * a killed command look like a running one forever. The output we have when it exits is the output there is.\n */\n child.on(\"exit\", (code) => {\n clearTimeout(deadline);\n resolve({ exitCode: code, output, timedOut });\n });\n });\n}\n\n/** The end of the output, which is where a failing command says why. */\nfunction lastLines(output: string, count = 20): string {\n return output.split(\"\\n\").filter(Boolean).slice(-count).join(\"\\n\");\n}\n", "import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { runChecks, type ChecksOptions, type ChecksResult } from \"./checks.ts\";\nimport { git } from \"../workspace/git.ts\";\n\n/*\n * Proving that a fix fixes something.\n *\n * The fourth non-negotiable says a bug fix ships with a test that fails on the old code, and this is the only\n * part of the gate that cannot be satisfied by an agent being persuasive. A test that passes on the new code\n * proves the new code passes its own test. A test that *fails on the old code* proves the test is about the bug.\n *\n * So: build the old code again from the base commit, put only the run's new and changed tests on top of it, and\n * run the check. It has to fail. If it passes, the test would have passed before the fix, and whatever it is\n * testing is not what was broken.\n *\n * Everything here bends towards refusing. A proof we could not run is not a proof; a test file we could not\n * identify is not a proof; a check that errored for some unrelated reason is not a proof.\n */\n\n/** Paths that look like tests. Documented rather than clever: a person has to be able to predict this. */\nconst TEST_PATH =\n /(^|\\/)(tests?|__tests__|spec)\\/|\\.(test|spec)\\.[cm]?[jt]sx?$|_test\\.(py|go|rb)$|(^|\\/)test_[^/]+\\.py$/;\n\nexport function looksLikeATest(path: string): boolean {\n return TEST_PATH.test(path);\n}\n\nexport interface ProofOptions {\n /** The repository the run started from. */\n repoRoot: string;\n /** The worktree holding the agent's changes. */\n workspacePath: string;\n /** The commit the run started from: the old code. */\n baseCommit: string;\n /** Every path the run touched, repo-relative. */\n touched: readonly string[];\n /** The line's own checks. A proof runs the project's real command, not one we invent. */\n commands: readonly string[];\n timeoutMs?: number;\n runChecksImpl?: (options: ChecksOptions) => Promise<ChecksResult>;\n}\n\nexport interface ProofResult {\n ok: boolean;\n /** The tests that were put on the old code. Empty when none could be identified. */\n tests: string[];\n /** Named so a reader knows what was proven, and so `proof.done` can carry them. */\n failedOnOld: string[];\n why: string;\n}\n\n/**\n * Runs the run's new tests against the old code and insists they fail.\n *\n * The old code is a fresh worktree at the base commit \u2014 not the agent's worktree with changes reverted, because\n * \"reverted\" is a thing we would have to get exactly right and a checkout is a thing git gets right for us.\n */\nexport async function proveFix(options: ProofOptions): Promise<ProofResult> {\n const tests = options.touched.filter(looksLikeATest).sort();\n if (tests.length === 0) {\n return {\n ok: false,\n tests: [],\n failedOnOld: [],\n why: \"this line is a fix but changed no file that looks like a test, so there is nothing to prove it with\",\n };\n }\n if (options.commands.length === 0) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"this line declares no checks, so there is no command that could run the test\",\n };\n }\n\n const root = mkdtempSync(join(tmpdir(), \"fanout-proof-\"));\n const oldCode = join(root, \"old\");\n\n try {\n await git([\"worktree\", \"add\", \"--detach\", \"--quiet\", oldCode, options.baseCommit], {\n cwd: options.repoRoot,\n });\n\n // Only the tests travel. Bringing anything else would be bringing the fix, which is the whole point.\n for (const test of tests) {\n const destination = join(oldCode, test);\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(join(options.workspacePath, test), destination);\n }\n\n const run = options.runChecksImpl ?? runChecks;\n const result = await run({\n cwd: oldCode,\n repoRoot: options.repoRoot,\n commands: options.commands,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n\n /*\n * Failing is the passing outcome here, and it has to fail for the right reason. A command that could not\n * start at all tells us nothing about the bug: it is a broken proof, not a proven fix.\n */\n const couldNotRun = result.outcomes.some((outcome) => outcome.exitCode === null && !outcome.timedOut);\n if (couldNotRun) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"the check could not run against the old code at all, so nothing was proven either way\",\n };\n }\n\n if (result.ok) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: \"the new tests pass on the old code, so they do not test what was broken\",\n };\n }\n\n return {\n ok: true,\n tests,\n failedOnOld: tests,\n why: `the new tests fail on ${options.baseCommit.slice(0, 7)} and pass on this work`,\n };\n } catch (cause) {\n return {\n ok: false,\n tests,\n failedOnOld: [],\n why: `the old code could not be rebuilt to test against: ${cause instanceof Error ? cause.message : String(cause)}`,\n };\n } finally {\n await git([\"worktree\", \"remove\", \"--force\", oldCode], { cwd: options.repoRoot }).catch(() => undefined);\n rmSync(root, { recursive: true, force: true });\n }\n}\n", "import { copyFileSync, existsSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { mergeReadiness, pathInScope, type PlanLine, type RunView } from \"fanout-core\";\nimport { git, lines, zeroSeparated } from \"../workspace/git.ts\";\n\n/*\n * Putting a run's work into the repository, and refusing to in every other case.\n *\n * This is the most dangerous function in the product: everything else can be wrong and leave your code alone.\n * So it asks permission from a pure judgement it cannot influence (`mergeReadiness`, over recorded facts), it\n * applies with a three-way merge so a conflict is a conflict rather than a silent overwrite, and it never forces\n * anything. A conflict is reported and the repository is left exactly as it was found.\n *\n * It also refuses to merge a diff that is not the one everybody looked at. Review, checks, proof and approval each\n * recorded the revision they judged; if the worktree has moved since, all four were about a different piece of\n * work and none of them is evidence about this one.\n */\n\nexport interface MergeOptions {\n repoRoot: string;\n /** The worktree holding the agent's changes. */\n workspacePath: string;\n run: RunView;\n line: PlanLine;\n /** What the work is right now, freshly collected \u2014 not what anyone remembers it being. */\n revision: string;\n patch: string;\n /** Files the run created, which a patch does not carry. */\n newFiles: readonly string[];\n /**\n * The commit's subject and body, written by the lead.\n *\n * Every project has its own convention and some enforce it with a hook; ours rejected the gate's own first\n * attempt. Guessing a format is not possible and bypassing the hook is out of the question \u2014 a tool that\n * merged past the rules a repository set for itself would be the least trustworthy thing here. So the lead,\n * which can read the repository's standard, supplies this. The trailers below it are the gate's and are not\n * the caller's to write.\n */\n message?: string;\n /**\n * Files this merge may apply even though the plan did not grant them, each named in full.\n *\n * The plan's write scope is what the safety report showed the user before anything launched, and until this\n * existed it was decoration at merge time: `collect` worked out what a run had written outside its scope and\n * the only thing that ever happened to that list was being printed. A run could write anywhere in its worktree\n * and the gate would apply it, provided nobody read one line of prose.\n *\n * Widening it is sometimes right \u2014 the lead's own prompt asks for an export the plan forgot to grant, which is\n * how this was found \u2014 so the answer is not to forbid it but to make it deliberate. Naming each path means a\n * lead cannot wave through a file it has not looked at, and the paths are recorded in the commit.\n */\n allowOutsideScope?: readonly string[];\n timeoutMs?: number;\n}\n\nexport type MergeOutcome =\n | { kind: \"merged\"; files: string[]; commit: string }\n | { kind: \"conflict\"; files: string[]; why: string }\n | { kind: \"refused\"; why: string[] };\n\n/**\n * Merges a run's work, or explains why it will not.\n *\n * Nothing is committed unless every file applied. A partial merge is the worst outcome available here \u2014 half a\n * change in your working tree, with the other half in a report \u2014 so a conflict rolls the whole attempt back.\n */\nexport async function mergeRun(options: MergeOptions): Promise<MergeOutcome> {\n const readiness = mergeReadiness(options.run, options.line, options.revision);\n if (!readiness.ready) {\n return { kind: \"refused\", why: readiness.blockers.map((blocker) => blocker.message) };\n }\n\n /*\n * The plan's write scope, enforced rather than reported. Checked against what is about to be applied \u2014 the\n * patch and the new files \u2014 rather than against anything recorded earlier, for the same reason the revision is\n * re-collected: the question is what this merge would do to your repository now.\n */\n const allowed = new Set(options.allowOutsideScope ?? []);\n const ungranted = [...new Set([...filesInPatch(options.patch), ...options.newFiles])]\n .filter((file) => !options.line.scope.write.some((pattern) => pathInScope(file, pattern)))\n .filter((file) => !allowed.has(file))\n .sort();\n if (ungranted.length > 0) {\n return {\n kind: \"refused\",\n why: [\n `${options.run.runId} wrote outside the scope its plan declared: ${ungranted.join(\", \")}. ` +\n \"Send it back, or name those paths in allowOutsideScope if you have read them and want them.\",\n ],\n };\n }\n\n const inRepo = {\n cwd: options.repoRoot,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n };\n\n /*\n * A dirty repository is refused rather than merged into. The three-way apply would probably work, and\n * \"probably\" is not a word that belongs anywhere near someone else's uncommitted work.\n */\n const dirty = zeroSeparated(await git([\"status\", \"--porcelain\", \"-z\"], inRepo))\n .map((entry) => entry.slice(3))\n .filter((path) => path !== \"\");\n const wouldTouch = new Set([...filesInPatch(options.patch), ...options.newFiles]);\n const clash = dirty.filter((path) => wouldTouch.has(path)).sort();\n if (clash.length > 0) {\n return {\n kind: \"refused\",\n why: [\n `You have uncommitted changes in ${clash.join(\", \")}, which this merge would touch. ` +\n \"Commit or stash them first.\",\n ],\n };\n }\n\n const before = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n const applied: string[] = [];\n\n try {\n if (options.patch.trim() !== \"\") {\n /*\n * `-3` so git can use the blobs both sides came from: it turns \"this hunk does not apply\" into a real\n * three-way merge, and into honest conflict markers when the two changes genuinely disagree.\n */\n await applyPatch(options.patch, options.repoRoot, options.timeoutMs);\n applied.push(...filesInPatch(options.patch));\n }\n\n for (const file of options.newFiles) {\n const destination = join(options.repoRoot, file);\n // A \"new\" file that already exists is not new: someone else created it while this run was working.\n if (existsSync(destination)) {\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"conflict\",\n files: [file],\n why: `${file} was created here while the run was working, so this would overwrite it`,\n };\n }\n mkdirSync(dirname(destination), { recursive: true });\n copyFileSync(join(options.workspacePath, file), destination);\n applied.push(file);\n }\n } catch (cause) {\n const conflicted = await conflictedFiles(options.repoRoot, options.timeoutMs);\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"conflict\",\n files: conflicted.length > 0 ? conflicted : [...wouldTouch].sort(),\n why: conflicted.length > 0 ? \"the work disagrees with what is here now\" : describe(cause),\n };\n }\n\n const files = [...new Set(applied)].sort();\n try {\n await git([\"add\", \"--\", ...files], inRepo);\n await git(\n [\n \"commit\",\n \"--quiet\",\n \"-m\",\n commitMessage(options),\n \"--author\",\n `${options.run.seat.id} via fanout <noreply@fanout.invalid>`,\n \"--\",\n ...files,\n ],\n inRepo,\n );\n } catch (cause) {\n /*\n * A repository may refuse its own commit \u2014 ours does, through a commit-msg hook, and said so the first time\n * the gate tried. Rolling back here is the difference between \"not merged\" and the thing this function\n * promises never to leave behind: the work applied, staged, and uncommitted, with the report saying it\n * failed. `--no-verify` is never the answer; a tool that merged past the rules a repository set for itself\n * would be the least trustworthy thing in it.\n */\n await rollback(options.repoRoot, before, options.timeoutMs);\n return {\n kind: \"refused\",\n why: [`The repository refused the commit, and nothing was changed: ${describe(cause)}`],\n };\n }\n\n const commit = (await git([\"rev-parse\", \"HEAD\"], inRepo)).trim();\n return { kind: \"merged\", files, commit };\n}\n\n/**\n * Who wrote this, in the history itself.\n *\n * The author is the seat, because it wrote the code, and the trailer names the person or policy that approved it,\n * because someone authorised it. A repository whose history cannot answer \"who decided this\" is a repository\n * where nobody decided.\n */\nfunction commitMessage(options: MergeOptions): string {\n const { line, run } = options;\n const approval = run.approval;\n const by =\n approval === null\n ? \"unknown\"\n : approval.by.kind === \"user\"\n ? \"the repository's owner\"\n : `policy \"${approval.by.name}\"`;\n return [\n options.message ?? `${line.title} (${line.id})\\n\\n${line.prompt.split(\"\\n\")[0] ?? \"\"}`,\n \"\",\n `Built-by: ${run.seat.id}${run.seat.model === undefined ? \"\" : ` (${run.seat.model})`} via fanout`,\n `Approved-by: ${by}`,\n // Only when the plan's scope was widened. A silent override would be no override at all.\n ...(options.allowOutsideScope === undefined || options.allowOutsideScope.length === 0\n ? []\n : [`Outside-scope: ${[...options.allowOutsideScope].sort().join(\", \")}`]),\n `Fanout-run: ${run.runId}`,\n ].join(\"\\n\");\n}\n\n/** Every path a patch claims to change, read from the patch rather than from anyone's account of it. */\nexport function filesInPatch(patch: string): string[] {\n const paths = new Set<string>();\n for (const line of patch.split(\"\\n\")) {\n const match = /^\\+\\+\\+ b\\/(.+)$/.exec(line);\n if (match?.[1] !== undefined && match[1] !== \"/dev/null\") paths.add(match[1]);\n }\n return [...paths].sort();\n}\n\nasync function applyPatch(patch: string, cwd: string, timeoutMs?: number): Promise<void> {\n const { execFile } = await import(\"node:child_process\");\n const { gitEnv } = await import(\"../workspace/git.ts\");\n const failure = await new Promise<Error | null>((resolve) => {\n const child = execFile(\n \"git\",\n [\"apply\", \"-3\", \"--whitespace=nowarn\", \"-\"],\n { cwd, timeout: timeoutMs ?? 60_000, env: gitEnv() },\n (error) => {\n resolve(error);\n },\n );\n child.stdin?.end(patch);\n });\n if (failure !== null) throw failure;\n}\n\nasync function conflictedFiles(repoRoot: string, timeoutMs?: number): Promise<string[]> {\n try {\n return lines(\n await git([\"diff\", \"--name-only\", \"--diff-filter=U\"], {\n cwd: repoRoot,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n }),\n );\n } catch {\n return [];\n }\n}\n\n/** Back to exactly where we started. A half-applied merge is worse than a refused one. */\nasync function rollback(repoRoot: string, commit: string, timeoutMs?: number): Promise<void> {\n const inRepo = { cwd: repoRoot, ...(timeoutMs === undefined ? {} : { timeoutMs }) };\n await git([\"reset\", \"--hard\", \"--quiet\", commit], inRepo).catch(() => undefined);\n await git([\"clean\", \"-fdq\"], inRepo).catch(() => undefined);\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n", "import { join } from \"node:path\";\nimport type { Ledger, PlanLine, RunView, SeatAdapter } from \"fanout-core\";\nimport { baseEnv } from \"../env.ts\";\nimport { startRun, type ActiveRun, type RunLimits } from \"../run.ts\";\n\n/*\n * Sending a diff back to the agent that wrote it.\n *\n * The whole value is in the word \"back\". The agent still holds its own reasoning about this code, so a note\n * saying \"escape the quotes in the header row too\" lands on someone who knows which header row, what it was\n * weighed against, and why the first attempt looked right. A fresh run handed a summary of that reasoning is a\n * stranger reading a description of a conversation it was not in \u2014 and it is charged at the same rate.\n *\n * It is also the same worktree, so the agent sees the code it wrote and the notes about it together rather than\n * being asked to imagine both.\n */\n\n/** Two rounds, then a person decides. */\nexport const MAX_REWORKS = 2;\n\nexport interface ReworkOptions {\n ledger: Ledger;\n adapter: SeatAdapter;\n missionId: string;\n line: PlanLine;\n run: RunView;\n /** The worktree the run already has. Rework never creates a new one. */\n workspacePath: string;\n runsRoot: string;\n limits: RunLimits;\n}\n\nexport type ReworkOutcome =\n { kind: \"started\"; runId: string; active: ActiveRun } | { kind: \"refused\"; why: string };\n\n/**\n * Starts the next turn of the conversation that produced this diff, with the reviewer's notes as the instruction.\n *\n * Every refusal here is a case where continuing would look like rework and not be one. The most important is a\n * seat that cannot resume: starting fresh while calling it rework would spend a subscription to discard exactly\n * the context the subscription was spent building, with nothing on screen to say so.\n */\nexport function reworkRun(options: ReworkOptions): ReworkOutcome {\n const { run, line } = options;\n\n const review = run.review;\n if (review?.verdict !== \"rework\") {\n return { kind: \"refused\", why: \"rework needs a review that asked for it, with the notes to send back\" };\n }\n if (run.status === \"merged\" || run.status === \"dropped\") {\n return { kind: \"refused\", why: `this run is already ${run.status}` };\n }\n if (run.sessionId === null) {\n return {\n kind: \"refused\",\n why: \"this run never told us its session, so there is no conversation to continue\",\n };\n }\n if (options.adapter.resume === undefined) {\n return {\n kind: \"refused\",\n why: `${options.adapter.id} cannot resume a session, so this work cannot be sent back to the agent that wrote it`,\n };\n }\n if (run.attempt > MAX_REWORKS) {\n /*\n * A third attempt is a signal about the task, not about the agent. Rework is for a diff that is nearly right;\n * work that has come back twice needs a person to look at the plan rather than another round of notes.\n */\n return {\n kind: \"refused\",\n why: `this line has already been reworked ${String(run.attempt - 1)} times; decide what to do with it instead`,\n };\n }\n\n const attempt = run.attempt + 1;\n const runId = `${line.id}-${String(attempt)}`;\n const directory = join(options.runsRoot, options.missionId, runId);\n\n options.ledger.appendAll([\n { type: \"run.queued\", missionId: options.missionId, runId, lineId: line.id, seat: run.seat, attempt },\n ]);\n\n const active = startRun({\n ledger: options.ledger,\n adapter: options.adapter,\n context: {\n missionId: options.missionId,\n runId,\n /*\n * The notes are the instruction, not the original task. The session already holds the task; repeating it\n * would invite the agent to start again instead of reading what it got wrong.\n */\n line: { ...line, prompt: reworkPrompt(review.notes) },\n workdir: options.workspacePath,\n reportPath: join(directory, \"report.md\"),\n baseEnv: baseEnv(),\n sessionId: run.sessionId,\n },\n logPath: join(directory, \"run.log\"),\n limits: options.limits,\n resumeSession: run.sessionId,\n });\n\n return { kind: \"started\", runId, active };\n}\n\n/**\n * What the agent is told.\n *\n * Short on purpose. It is already in the conversation and already has the code in front of it; the one thing it\n * does not have is what a reader thought when they read it.\n */\nexport function reworkPrompt(notes: string): string {\n return [\n \"Your work was reviewed and needs changes. The notes are below.\",\n \"\",\n \"Change only what they ask for, in the same files you already have open. Do not start over, do not commit,\",\n \"and do not widen the scope you were given.\",\n \"\",\n notes,\n ].join(\"\\n\");\n}\n", "import { randomBytes } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n missionReport,\n PlanGraph,\n PlanLine,\n project,\n validatePlan,\n versionOf,\n type AdapterManifest,\n type Ledger,\n type SeatAdapter,\n type SeatInfo,\n} from \"fanout-core\";\nimport {\n checkClaims,\n chooseSeat,\n createSafetyDependencies,\n filesInPatch,\n mergeRun,\n proveFix,\n reworkRun,\n runChecks,\n workSnapshot,\n createMissionRunner,\n createWorkspaceManager,\n daemonAnswers,\n findDaemon,\n type DaemonLink,\n reconcile,\n detectSeats,\n git,\n lines as splitLines,\n safetyReport,\n zeroSeparated,\n type MissionHandle,\n type RunLimits,\n} from \"fanout-daemon\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\n/*\n * The lead's tools. Claude Code is the brain; this is the hand it works with.\n *\n * Every tool answers in plain words as well as data, because the lead reads them and so does the person watching.\n * Two rules shape the surface:\n *\n * - Nothing runs that has not passed the gate. `launch` refuses a red safety report unless the user says\n * otherwise in so many words, and that override is recorded.\n * - Nothing merges here at all. Review and merge arrive with the gate; a tool that quietly merged would be the\n * most dangerous thing in the product.\n */\n\nexport interface FanoutMcpOptions {\n ledger: Ledger;\n /** The repository the session is working in. */\n repoRoot: string;\n /** Where run logs, reports and workspaces live, and where the owner's seat preferences are kept. */\n paths: { runs: string; workspaces: string; home?: string };\n /** Seat id to adapter, and the manifests behind them. */\n adapters: ReadonlyMap<string, SeatAdapter>;\n manifests: readonly AdapterManifest[];\n limits: RunLimits;\n /** Injected in tests so nothing needs a CLI installed. */\n execute?: (\n binary: string,\n args: readonly string[],\n ) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n /** The clock elapsed and quiet times are measured against; injected so tests are not timing-dependent. */\n now?: () => Date;\n}\n\nconst MissionLimits = { maxParallel: z.int().min(1).max(16).default(3) };\n\n/**\n * Asks the daemon to run a mission. Returns null when it took it, or the reason it would not.\n *\n * A refusal is passed back rather than swallowed and retried locally: the daemon is the one that knows why, and\n * silently doing it here would turn \"your repository is not where I thought\" into a mission nobody can explain.\n */\nasync function handTo(\n daemon: DaemonLink,\n order: { missionId: string; goal: string; repoRoot: string; plan: unknown; maxParallel: number },\n): Promise<string | null> {\n try {\n const response = await fetch(`${daemon.url}/launch`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${daemon.token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(order),\n signal: AbortSignal.timeout(15_000),\n });\n if (response.ok) return null;\n const said = (await response.json().catch(() => ({}))) as { error?: string };\n return said.error ?? `it answered ${String(response.status)}`;\n } catch (cause) {\n return cause instanceof Error ? cause.message : String(cause);\n }\n}\n\n/** Asks the daemon to stop a mission: true if it did, false if it is not running it, null if it could not be asked. */\nasync function askDaemonToStop(\n daemon: DaemonLink,\n missionId: string,\n reason: string,\n): Promise<boolean | null> {\n try {\n const response = await fetch(`${daemon.url}/cancel`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${daemon.token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ missionId, reason }),\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) return null;\n return ((await response.json()) as { stopped?: boolean }).stopped === true;\n } catch {\n return null;\n }\n}\n\nexport function createFanoutServer(options: FanoutMcpOptions): McpServer {\n const server = new McpServer(\n { name: \"fanout\", version: versionOf(import.meta.url) },\n {\n instructions:\n \"Fanout runs the other coding-agent CLIs on this machine as a crew. Plan with `plan_check`, start with \" +\n \"`launch`, watch with `mission_status`, and read a run's work with `run_diff`. Nothing merges here: review \" +\n \"the diff yourself and apply it, or wait for the merge gate.\",\n },\n );\n\n /*\n * Before anything reads the ledger for an answer: end the runs whose supervisor is gone.\n *\n * The supervisor lives in this process, so every session that closes leaves its in-flight runs recorded as\n * running with nothing watching them. Written down at startup rather than guessed at on read \u2014 a projection\n * that invented a status would be treating the ledger as a suggestion.\n */\n reconcile(options.ledger);\n\n const workspaces = createWorkspaceManager({\n repoRoot: options.repoRoot,\n workspaceRoot: options.paths.workspaces,\n });\n /*\n * Detection spawns processes, so a line uses the crew last reported at startup or by the seats tool rather\n * than waiting on four CLIs before it can begin. Headroom still comes from the ledger every time: a seat\n * running out is exactly the thing that changes between one line and the next.\n */\n let crew: readonly SeatInfo[] = [];\n void detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n }).then((seats) => {\n crew = seats;\n });\n\n const runner = createMissionRunner({\n ledger: options.ledger,\n workspaces,\n adapters: options.adapters,\n runsRoot: options.paths.runs,\n limits: options.limits,\n route: (line) => {\n const home = options.paths.home;\n // Without a home there are no seat preferences to honour, and routing without them could spend a seat the\n // owner switched off. The plan's own seat is the choice that can only fail loudly.\n if (home === undefined) return { kind: \"keep\", seat: line.seat.id };\n return chooseSeat(line.seat.id, {\n home,\n crew,\n headroom: project(options.ledger.read()).headroom,\n now: new Date(),\n });\n },\n });\n const missions = new Map<string, MissionHandle>();\n\n server.registerTool(\n \"seats\",\n {\n title: \"The crew on this machine\",\n description:\n \"Which agent CLIs are installed, which version, and whether each is signed in. A seat whose CLI cannot \" +\n \"tell us is reported as unknown, never as ready.\",\n inputSchema: {},\n },\n async () => {\n const seats = await detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n crew = seats;\n const ready = seats.filter((seat) => seat.supported && seat.signedIn === \"yes\");\n return text(\n `${ready.length} of ${seats.length} seats are ready.\\n` +\n seats\n .map(\n (seat) =>\n `- ${seat.id}: ${seat.version ?? \"not installed\"}, ` +\n (seat.supported ? seat.signedIn : \"unsupported version\"),\n )\n .join(\"\\n\"),\n { seats },\n );\n },\n );\n\n server.registerTool(\n \"repo_overview\",\n {\n title: \"A map of this repository\",\n description:\n \"What is here and where, so a plan can be written without reading every file: the commit the mission \" +\n \"would start from, whether the tree is clean, the top-level areas by size, and the checks the project runs.\",\n inputSchema: {},\n },\n async () => {\n const overview = await repoOverview(options.repoRoot);\n return text(\n `On ${overview.head.slice(0, 7)}${overview.dirty.length > 0 ? ` with ${overview.dirty.length} uncommitted file(s)` : \", clean\"}.\\n` +\n `Areas: ${overview.areas.map((area) => `${area.path} (${area.files})`).join(\", \")}\\n` +\n `Checks: ${overview.checks.length > 0 ? overview.checks.join(\", \") : \"none found\"}`,\n overview,\n );\n },\n );\n\n server.registerTool(\n \"plan_check\",\n {\n title: \"Check a plan before anything runs\",\n description:\n \"Validates a plan and returns the safety report: overlapping write scopes, anything deny-listed in the \" +\n \"repository, seats that are missing or signed out, the concurrency limits, and the exact commands that \" +\n \"would run. Records nothing, so iterate freely.\",\n inputSchema: { lines: z.array(PlanLine), ...MissionLimits },\n },\n async ({ lines, maxParallel }) => {\n const plan = PlanGraph.parse({ lines });\n const report = await gate(options, plan, maxParallel);\n const blocking = report.checks.filter((check) => !check.ok && check.severity === \"block\");\n return text(\n blocking.length === 0\n ? `The plan is ready to launch. ${report.checks.filter((check) => !check.ok).length} warning(s).`\n : `This plan cannot launch yet:\\n${blocking.map((check) => `- ${check.message}`).join(\"\\n\")}`,\n report,\n );\n },\n );\n\n server.registerTool(\n \"launch\",\n {\n title: \"Start a mission\",\n description:\n \"Runs a plan: each line in its own git worktree, in dependency order, never more at once than allowed. \" +\n \"Refuses a plan whose safety report has a blocking failure unless `override` explains why, which is \" +\n \"recorded. Returns as soon as the runs are under way; watch with mission_status.\",\n inputSchema: {\n goal: z.string().min(1).max(4000),\n lines: z.array(PlanLine),\n ...MissionLimits,\n override: z.string().min(10).max(500).optional(),\n },\n },\n async ({ goal, lines, maxParallel, override }) => {\n const plan = PlanGraph.parse({ lines });\n const issues = validatePlan(plan);\n if (issues.length > 0) {\n return text(`This plan cannot run:\\n${issues.map((issue) => `- ${issue.message}`).join(\"\\n\")}`, {\n issues,\n });\n }\n\n const report = await gate(options, plan, maxParallel);\n const blocking = report.checks.filter((check) => !check.ok && check.severity === \"block\");\n if (blocking.length > 0 && override === undefined) {\n return text(\n `Not launching. The safety report has ${blocking.length} blocking failure(s):\\n` +\n `${blocking.map((check) => `- ${check.message}`).join(\"\\n\")}\\n` +\n \"Fix the plan, or pass `override` with the reason if the user has decided to go ahead anyway.\",\n report,\n );\n }\n\n const missionId = missionIdFor(goal);\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: options.repoRoot })).trim();\n options.ledger.appendAll([\n {\n type: \"mission.created\",\n missionId,\n goal,\n repo: { root: options.repoRoot, baseCommit: head },\n limits: { maxParallel, timeoutMinutes: Math.ceil(options.limits.timeoutMs / 60_000) },\n },\n { type: \"plan.proposed\", missionId, plan, by: \"lead\" },\n { type: \"safety.report\", missionId, planRevision: 1, ok: report.ok, checks: report.checks },\n ]);\n\n /*\n * Hand the mission to the daemon when one is running, and only run it here when none is.\n *\n * A runner inside this process dies with the session that owns it, which is what left a run recorded as\n * `running` for a quarter of an hour after the agent had gone (ADR 0024). A daemon outlives a terminal, so\n * a mission it owns survives the lead closing the window and is waiting when they come back.\n *\n * The fallback is not a nicety: a session with no daemon still has to work, and it is better for a mission\n * to be tied to this terminal than for `/fanout` to refuse until somebody runs another command.\n */\n const home = options.paths.home;\n const away = home === undefined ? null : findDaemon(home);\n if (away !== null && (await daemonAnswers(away))) {\n const handed = await handTo(away, { missionId, goal, repoRoot: options.repoRoot, plan, maxParallel });\n if (handed === null) {\n return text(\n `Mission ${missionId} is running ${plan.lines.length} line(s) from ${head.slice(0, 7)}, on the ` +\n `daemon \u2014 so it will keep going if this session ends` +\n `${override === undefined ? \"\" : `, with the safety report overridden: ${override}`}.`,\n { missionId, baseCommit: head, lines: plan.lines.map((line) => line.id), owner: \"daemon\" },\n );\n }\n // It answered and refused, which is a real answer: say what it said rather than quietly doing it here.\n return text(`The daemon would not start this mission: ${handed}`, { missionId });\n }\n\n const handle = runner.launch({ missionId, plan, baseCommit: head, maxParallel });\n missions.set(missionId, handle);\n void handle.finished.then((outcome) => {\n options.ledger.append({\n type: \"mission.finished\",\n missionId,\n outcome: outcome.failed === 0 && outcome.dropped === 0 ? \"completed\" : \"aborted\",\n summary: `${outcome.done} done, ${outcome.failed} failed, ${outcome.dropped} dropped`,\n });\n });\n\n return text(\n `Mission ${missionId} is running ${plan.lines.length} line(s) from ${head.slice(0, 7)}` +\n (override === undefined ? \"\" : `, with the safety report overridden: ${override}`) +\n `. It is running in this session, so it stops if the session does \u2014 start \\`fanout daemon\\` to ` +\n `have missions outlive it.`,\n { missionId, baseCommit: head, lines: plan.lines.map((line) => line.id), owner: \"session\" },\n );\n },\n );\n\n server.registerTool(\n \"mission_status\",\n {\n title: \"How a mission is going\",\n description:\n \"Every run of a mission: how long it has been going, which phase it reported, what it touched and how \" +\n \"it ended. A run still working that has said nothing for a while is marked quiet, which is the \" +\n \"difference between an agent thinking and an agent that has stopped.\",\n inputSchema: { missionId: z.string().min(1) },\n },\n ({ missionId }) => {\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n if (mission === undefined) return text(`No mission called ${missionId}.`, { missionId });\n\n return text(missionReport(mission, (options.now ?? (() => new Date()))()), { mission });\n },\n );\n\n server.registerTool(\n \"run_diff\",\n {\n title: \"What a run actually changed\",\n description:\n \"The diff read from the run's own workspace, not the agent's account of it, plus anything it wrote \" +\n \"outside its declared scope and the report it left.\",\n inputSchema: {\n missionId: z.string().min(1),\n runId: z.string().min(1),\n patch: z.boolean().default(false),\n },\n },\n async ({ missionId, runId, patch }) => {\n /*\n * Through `locate`, like every other tool here. This used to derive the path from the run id, which is the\n * one thing that is wrong for a reworked run: it continues in the worktree of the attempt before it. So the\n * diff was unreadable for exactly the runs a lead most needs to read \u2014 found by running a real mission and\n * being unable to see what came back. `locate` had already been fixed; this was a second copy of the rule.\n */\n const found = locate(missionId, runId);\n if (found === null) return text(`No run called ${runId} in ${missionId}.`, { missionId, runId });\n if (!found.exists) {\n return text(`The workspace for ${runId} is gone, so there is nothing left to read.`, { runId });\n }\n const { line, workspace } = found;\n\n const diff = await workspaces.collect(workspace, line);\n const reportPath = join(options.paths.runs, missionId, runId, \"report.md\");\n const report = existsSync(reportPath) ? readFileSync(reportPath, \"utf8\").slice(0, 20_000) : null;\n\n return text(\n `${runId}: ${diff.stat.files} file(s), +${diff.stat.insertions} \u2212${diff.stat.deletions}.` +\n (diff.outsideScope.length > 0 ? `\\nOutside its scope: ${diff.outsideScope.join(\", \")}` : \"\") +\n (report === null ? \"\" : `\\n\\nIts report:\\n${report}`),\n {\n stat: diff.stat,\n newFiles: diff.newFiles,\n outsideScope: diff.outsideScope,\n report,\n ...(patch ? { patch: diff.patch.slice(0, 200_000) } : {}),\n },\n );\n },\n );\n\n server.registerTool(\n \"cancel_mission\",\n {\n title: \"Stop a mission\",\n description: \"Stops every run still going and drops the lines that had not started, with the reason.\",\n inputSchema: { missionId: z.string().min(1), reason: z.string().min(1).max(500) },\n },\n async ({ missionId, reason }) => {\n const handle = missions.get(missionId);\n if (handle !== undefined) {\n await handle.cancel(reason);\n return text(`Stopped ${missionId}: ${reason}`, { missionId });\n }\n\n /*\n * Ask the daemon, because it may be the one running this.\n *\n * Missions can now live in a process that outlives this session, and a cancel that only looked in this\n * one answered \"not running here\" while the agents carried on spending. Cancel is how somebody stops\n * paying; it is the last control that may quietly do nothing.\n */\n const home = options.paths.home;\n const away = home === undefined ? null : findDaemon(home);\n if (away !== null && (await daemonAnswers(away))) {\n const stopped = await askDaemonToStop(away, missionId, reason);\n if (stopped === true) return text(`Stopped ${missionId}: ${reason}`, { missionId });\n if (stopped === null) {\n return text(`Could not reach the daemon to stop ${missionId}. It may still be running.`, {\n missionId,\n });\n }\n }\n\n /*\n * Nobody is running it, so the only thing left to record is the decision. A mission abandoned in planning\n * otherwise sits in every future listing as though it were about to start.\n */\n const state = project(options.ledger.read({ missionId })).missions[missionId];\n if (state !== undefined && (state.status === \"planning\" || state.status === \"running\")) {\n options.ledger.append({\n type: \"mission.finished\",\n missionId,\n outcome: \"aborted\",\n summary: `cancelled before anything was running: ${reason}`,\n });\n return text(`Nothing was running. Recorded ${missionId} as cancelled: ${reason}`, { missionId });\n }\n\n return text(`Mission ${missionId} is not running here.`, { missionId });\n },\n );\n\n /*\n * The tool this whole product exists for.\n *\n * Most of the code in a Claude Code session is written by the lead and reviewed by the lead, and the lead's own\n * context \u2014 the plan, the reasoning, the justification \u2014 is exactly what hides its mistakes from it. A reader\n * holding only the diff is not smarter, it is differently placed. This is here rather than only in the terminal\n * because a check the lead has to remember to leave the session for is a check the lead will not run.\n */\n server.registerTool(\n \"check_claims\",\n {\n title: \"Have a second vendor try to disprove what you believe\",\n description:\n \"State what you believe about your own uncommitted changes; another vendor's CLI reads them cold, with \" +\n \"no knowledge of why you wrote them, and tries to falsify each claim. Run this before telling anyone \" +\n 'work is done. Write claims that could be proven false \u2014 \"it works\" cannot be checked, \"no caller of ' +\n 'total() passes fewer than two arguments\" can. A claim is only ever reported confirmed when the reader ' +\n \"said so explicitly: anything it skipped or garbled comes back unclear, never as a pass.\",\n inputSchema: {\n claims: z.array(z.string().trim().min(1).max(500)).min(1).max(10),\n },\n },\n async ({ claims }) => {\n const manifest = options.manifests.find((seat) => seat.capabilities.review !== null);\n if (manifest === undefined) {\n return text(\"No seat on this machine can read code it did not write.\", { ran: false });\n }\n\n const { event, refuted } = await checkClaims({\n repoRoot: options.repoRoot,\n claims,\n manifest,\n ...(options.execute === undefined ? {} : { execute: seatExecute(options.execute) }),\n });\n options.ledger.appendAll([event]);\n\n if (!event.ran) {\n // \"We could not ask\" must never read as \"nothing was refuted\".\n return text(\n `${manifest.displayName} did not check these claims: ${event.claims[0]?.evidence ?? \"unknown\"}`,\n { ran: false, claims: event.claims },\n );\n }\n\n const lines = event.claims.map(\n (claim) =>\n `${{ confirmed: \"\u2713\", refuted: \"\u2717\", unclear: \"?\" }[claim.verdict]} ${claim.claim}\\n ${claim.evidence}`,\n );\n const verdict =\n refuted.length > 0\n ? `\\n${String(refuted.length)} refuted. Fix these before saying the work is done.`\n : event.claims.some((claim) => claim.verdict === \"unclear\")\n ? \"\\nNothing refuted, but some claims could not be checked \u2014 that is not the same as fine.\"\n : \"\\nAll confirmed.\";\n\n return text(`${manifest.displayName} read your changes cold:\\n\\n${lines.join(\"\\n\")}\\n${verdict}`, {\n ran: true,\n refuted: refuted.length,\n claims: event.claims,\n });\n },\n );\n\n /*\n * The merge gate, as four tools the lead drives in order.\n *\n * They are deliberately separate. Each records the revision it judged, and `merge_run` refuses unless review,\n * checks, proof and approval all named the same one \u2014 so a single tool that \"reviewed and merged\" would be a\n * tool that could skip its own gate. Splitting them is what makes the refusal possible.\n */\n\n /** Finds a run and its worktree, or explains which part is missing. */\n const locate = (missionId: string, runId: string) => {\n const state = project(options.ledger.read({ missionId }));\n const mission = state.missions[missionId];\n const run = mission?.runs[runId];\n const line = mission?.plan?.lines.find((entry) => entry.id === run?.lineId);\n /*\n * Where the run said it worked, falling back to the convention only for a run that never started. A reworked\n * run continues in the worktree of the attempt before it, so deriving the path from the run id finds nothing\n * for exactly the runs that most need finding.\n */\n if (mission === undefined || run === undefined || line === undefined) return null;\n const path = run.workdir ?? join(options.paths.workspaces, missionId, runId);\n return {\n run,\n line,\n workspace: {\n missionId,\n runId,\n kind: \"worktree\" as const,\n path,\n branch: `fanout/${missionId}/${runId}`,\n baseCommit: mission.repo.baseCommit,\n },\n exists: existsSync(path),\n };\n };\n\n const RUN = { missionId: z.string().min(1), runId: z.string().min(1) };\n\n server.registerTool(\n \"review_run\",\n {\n title: \"Record your verdict on a run's diff\",\n description:\n \"Records what you decided after reading the diff yourself with `run_diff`. Say what you actually \" +\n \"checked, not that it looks fine. `rework` sends it back; `reject` ends it. The verdict is tied to the \" +\n \"diff as it is right now, so if the work changes afterwards this review no longer counts for it.\",\n inputSchema: {\n ...RUN,\n verdict: z.enum([\"accept\", \"rework\", \"reject\"]),\n notes: z.string().trim().min(1).max(20_000),\n },\n },\n async ({ missionId, runId, verdict, notes }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to review.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n options.ledger.appendAll([\n { type: \"review.done\", missionId, runId, revision, verdict, notes, by: { id: \"claude\" } },\n ]);\n return text(\n `Recorded: ${verdict} for ${runId} (${String(diff.stat.files)} file(s) changed).` +\n (verdict === \"accept\" ? \" Next: run_checks.\" : \"\"),\n { revision, verdict },\n );\n },\n );\n\n server.registerTool(\n \"run_checks\",\n {\n title: \"Run the project's own checks against a run's work\",\n description:\n \"Runs the commands the plan declared for this line, in the run's worktree, and believes the exit codes. \" +\n \"The agent's own claim that its tests pass is not evidence: it was made by the only party with an \" +\n \"interest in the answer, inside a sandbox that could not run them properly. A line that declared no \" +\n \"checks is reported as unverified, never as passing.\",\n inputSchema: RUN,\n },\n async ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to check.`, { runId });\n\n // A worktree holds tracked files and nothing else, so the repository lends it node_modules for the length\n // of the check and takes them back afterwards.\n const result = await runChecks({\n cwd: found.workspace.path,\n repoRoot: options.repoRoot,\n commands: found.line.checks,\n });\n options.ledger.appendAll([\n {\n type: \"checks.done\",\n missionId,\n runId,\n revision: result.revision,\n ok: result.ok,\n summary: result.summary,\n commands: result.commands,\n },\n ]);\n const failing = result.outcomes.find((outcome) => outcome.exitCode !== 0);\n return text(\n `${result.ok ? \"\u2713\" : \"\u2717\"} ${result.summary}` +\n (failing === undefined ? \"\" : `\\n\\n${failing.command}:\\n${failing.tail}`),\n { ok: result.ok, revision: result.revision, outcomes: result.outcomes },\n );\n },\n );\n\n server.registerTool(\n \"prove_fix\",\n {\n title: \"Prove a bug fix by failing its test on the old code\",\n description:\n \"For a line the plan marked as a bug fix. Checks out the code as it was, copies only this run's tests \" +\n \"on top of it, and runs them: they must fail. A test that passes on the old code would have passed \" +\n \"before the fix, so it does not test what was broken. Required before such a line can merge.\",\n inputSchema: RUN,\n },\n async ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to prove.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n const result = await proveFix({\n repoRoot: options.repoRoot,\n workspacePath: found.workspace.path,\n baseCommit: found.workspace.baseCommit,\n touched: [...diff.newFiles, ...filesInPatch(diff.patch)],\n commands: found.line.checks,\n });\n\n options.ledger.appendAll([\n { type: \"proof.done\", missionId, runId, revision, ok: result.ok, failedOnOld: result.failedOnOld },\n ]);\n return text(`${result.ok ? \"\u2713 proven\" : \"\u2717 not proven\"}: ${result.why}`, {\n ok: result.ok,\n revision,\n tests: result.tests,\n });\n },\n );\n\n server.registerTool(\n \"rework_run\",\n {\n title: \"Send a diff back to the agent that wrote it\",\n description:\n \"Continues the conversation that produced this diff, with your review notes as the instruction, in the \" +\n \"same worktree. Use it after `review_run` with a `rework` verdict. This is worth far more than running \" +\n \"the line again: the agent still holds its own reasoning about the code, so a note about the header row \" +\n \"lands on someone who knows which header row. Two rounds, then decide instead of asking a third time.\",\n inputSchema: RUN,\n },\n ({ missionId, runId }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to rework.`, { runId });\n\n const adapter = options.adapters.get(found.run.seat.id);\n if (adapter === undefined) {\n return text(`No adapter for ${found.run.seat.id} on this machine.`, { runId });\n }\n\n const outcome = reworkRun({\n ledger: options.ledger,\n adapter,\n missionId,\n line: found.line,\n run: found.run,\n workspacePath: found.workspace.path,\n runsRoot: options.paths.runs,\n limits: options.limits,\n });\n if (outcome.kind === \"refused\") return text(`Not reworked: ${outcome.why}`, { started: false });\n\n // Returns as soon as it is under way, like `launch`: watch it with mission_status.\n return text(\n `${outcome.runId} is picking the work back up where it left off. Watch it with mission_status.`,\n { started: true, runId: outcome.runId },\n );\n },\n );\n\n server.registerTool(\n \"merge_run\",\n {\n title: \"Merge a run's work into the repository\",\n description:\n \"The only tool that changes the user's repository, and it refuses unless review, checks, proof and the \" +\n \"user's approval all judged this exact diff. **Ask the user first, in the chat, and quote their answer \" +\n \"in `approvedBy`.** Applies with a three-way merge; a conflict is reported and rolled back, never \" +\n \"forced. Nothing is merged into a tree with uncommitted changes it would touch.\",\n inputSchema: {\n ...RUN,\n approvedBy: z\n .string()\n .trim()\n .min(1)\n .max(2000)\n .describe(\"What the user actually said when they approved this merge, in their own words.\"),\n allowOutsideScope: z\n .array(z.string().trim().min(1).max(400))\n .max(50)\n .optional()\n .describe(\n \"Paths this run wrote that its plan did not grant, which you have read and want anyway. The merge \" +\n \"refuses otherwise, and names them. Copy them from `run_diff`'s 'Outside its scope' line only \" +\n \"after looking at each one \u2014 they are recorded in the commit as Outside-scope.\",\n ),\n message: z\n .string()\n .trim()\n .min(1)\n .max(4000)\n .optional()\n .describe(\n \"The commit subject and body, in this repository's own convention \u2014 read docs/COMMITS.md or the \" +\n \"recent log before writing it. A project that enforces a format with a hook will refuse anything \" +\n \"else, and the gate will not bypass that hook. Trailers naming the seat and the approver are \" +\n \"added by the gate and are not yours to write.\",\n ),\n },\n },\n async ({ missionId, runId, approvedBy, message, allowOutsideScope }) => {\n const found = locate(missionId, runId);\n if (found?.exists !== true) return text(`No workspace for ${runId} to merge.`, { runId });\n\n const diff = await workspaces.collect(found.workspace, found.line);\n const revision = (await workSnapshot({ cwd: found.workspace.path })).revision;\n\n /*\n * The approval is recorded before the attempt, so a replay shows the authority even when the merge then\n * hits a conflict. It is recorded as the user's because the user is who this tool asks the lead to ask.\n */\n options.ledger.appendAll([\n {\n type: \"merge.approved\",\n missionId,\n runId,\n revision,\n // Relayed, not direct: this is the lead's account of what the user said, and the ledger should say so.\n by: { kind: \"user\", via: \"relayed\" },\n note: approvedBy,\n },\n ]);\n\n const fresh = project(options.ledger.read({ missionId })).missions[missionId]?.runs[runId];\n if (fresh === undefined) return text(`${runId} vanished between reading and merging.`, { runId });\n\n const outcome = await mergeRun({\n repoRoot: options.repoRoot,\n workspacePath: found.workspace.path,\n run: fresh,\n line: found.line,\n revision,\n patch: diff.patch,\n newFiles: diff.newFiles,\n ...(allowOutsideScope === undefined ? {} : { allowOutsideScope }),\n ...(message === undefined ? {} : { message }),\n });\n\n if (outcome.kind === \"refused\") {\n return text(`Not merged:\\n${outcome.why.map((why) => `- ${why}`).join(\"\\n\")}`, { merged: false });\n }\n if (outcome.kind === \"conflict\") {\n options.ledger.appendAll([\n { type: \"merge.conflict\", missionId, runId, revision, files: outcome.files },\n ]);\n return text(\n `Conflict in ${outcome.files.join(\", \")}: ${outcome.why}. Your repository is untouched.`,\n { merged: false, files: outcome.files },\n );\n }\n\n options.ledger.appendAll([\n { type: \"merge.applied\", missionId, runId, revision, files: outcome.files, commit: outcome.commit },\n ]);\n return text(`Merged ${runId} as ${outcome.commit.slice(0, 7)}: ${outcome.files.join(\", \")}`, {\n merged: true,\n commit: outcome.commit,\n files: outcome.files,\n });\n },\n );\n\n return server;\n}\n\n/** The daemon's seat runner takes a working directory and a deadline; the injected test executor takes neither. */\nfunction seatExecute(execute: NonNullable<FanoutMcpOptions[\"execute\"]>) {\n return (binary: string, args: readonly string[]) => execute(binary, args);\n}\n\n/** Every tool answers twice: words for whoever is reading, and data for whatever is next. */\nfunction text(message: string, data: unknown) {\n return {\n content: [{ type: \"text\" as const, text: message }],\n structuredContent: data as Record<string, unknown>,\n };\n}\n\nasync function gate(options: FanoutMcpOptions, plan: PlanGraph, maxParallel: number) {\n const seats = await detectSeats({\n manifests: options.manifests,\n ...(options.execute === undefined ? {} : { execute: options.execute }),\n });\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: options.repoRoot })).trim();\n const commands = Object.fromEntries(\n plan.lines.flatMap((line) => {\n const adapter = options.adapters.get(line.seat.id);\n if (adapter === undefined) return [];\n return [\n [\n line.id,\n adapter.command({\n missionId: \"preview\",\n runId: `${line.id}-1`,\n line,\n workdir: join(options.paths.workspaces, \"preview\", line.id),\n reportPath: join(options.paths.runs, \"preview\", line.id, \"report.md\"),\n baseEnv: {},\n }),\n ],\n ];\n }),\n );\n\n return safetyReport(\n {\n plan,\n planRevision: 1,\n repo: { root: options.repoRoot, baseCommit: head },\n seats: Object.fromEntries(seats.map((seat) => [seat.id, seat])),\n commands,\n denyList: [],\n limits: { maxParallel, perSeat: {} },\n },\n createSafetyDependencies({ repoRoot: options.repoRoot }),\n );\n}\n\nasync function repoOverview(repoRoot: string) {\n const head = (await git([\"rev-parse\", \"HEAD\"], { cwd: repoRoot })).trim();\n const dirty = splitLines(await git([\"status\", \"--porcelain\"], { cwd: repoRoot })).map((entry) =>\n entry.slice(3),\n );\n const files = zeroSeparated(await git([\"ls-files\", \"-z\"], { cwd: repoRoot }));\n\n const counts = new Map<string, number>();\n for (const file of files) {\n const area = file.includes(\"/\") ? `${file.slice(0, file.indexOf(\"/\"))}/` : \"(root)\";\n counts.set(area, (counts.get(area) ?? 0) + 1);\n }\n const areas = [...counts.entries()]\n .map(([path, count]) => ({ path, files: count }))\n .sort((a, b) => b.files - a.files)\n .slice(0, 12);\n\n return { head, dirty, files: files.length, areas, checks: projectChecks(repoRoot) };\n}\n\n/** The commands this project runs to know it is well, read from where they are declared. */\nfunction projectChecks(repoRoot: string): string[] {\n const manifest = join(repoRoot, \"package.json\");\n if (!existsSync(manifest)) return [];\n try {\n const parsed = JSON.parse(readFileSync(manifest, \"utf8\")) as { scripts?: Record<string, string> };\n return Object.keys(parsed.scripts ?? {})\n .filter((name) => [\"check\", \"test\", \"lint\", \"typecheck\", \"build\"].includes(name))\n .map((name) => `npm run ${name}`);\n } catch {\n return [];\n }\n}\n\nfunction missionIdFor(goal: string): string {\n const slug = goal\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 40);\n return `${slug === \"\" ? \"mission\" : slug}-${randomBytes(2).toString(\"hex\")}`;\n}\n", "import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { AdapterContext, ParseResult, SeatAdapter } from \"fanout-core\";\nimport { OutputLine } from \"./protocol.ts\";\nimport { Scenario, type ScenarioInput } from \"./scenario.ts\";\n\n/*\n * The fake seat: a deterministic simulated agent for the offline demo and for every test that needs an agent without\n * an account. It is a seat like any other: `command()` starts its CLI, `parse()` reads its stream.\n */\n\n/**\n * The simulated agent's own executable, wherever this module happens to be running from.\n *\n * Three places, and each one is a lesson rather than a configuration:\n *\n * 1. `fake-agent.js` beside us means we are inside the published bundle, where every workspace package has been\n * compiled into one file. `./cli.js` there is the *lead's* CLI \u2014 spawning it would make the demo run itself.\n * 2. `./cli.ts` is a checkout, where Node runs our TypeScript directly.\n * 3. `./cli.js` is the unbundled compiled layout.\n *\n * A path built as a string is the one import a compiler cannot rewrite, which is why this is worked out at\n * runtime: an earlier version wrote `./cli.ts` into `dist`, and all three demo agents died on the first spawn.\n */\nexport const FAKE_CLI_PATH = resolveFakeCli();\n\nfunction resolveFakeCli(): string {\n const bundled = fileURLToPath(new URL(\"./fake-agent.js\", import.meta.url));\n if (existsSync(bundled)) return bundled;\n return fileURLToPath(new URL(import.meta.url.endsWith(\".ts\") ? \"./cli.ts\" : \"./cli.js\", import.meta.url));\n}\n\nexport interface FakeAdapterOptions {\n /** The scenario a plan line plays. */\n scenarioFor: (line: AdapterContext[\"line\"]) => ScenarioInput;\n}\n\nexport function createFakeAdapter(options: FakeAdapterOptions): SeatAdapter {\n return {\n id: \"fake\",\n command: (context) => ({\n argv: [\n process.execPath,\n FAKE_CLI_PATH,\n \"--scenario-json\",\n JSON.stringify(Scenario.parse(options.scenarioFor(context.line))),\n \"--report\",\n context.reportPath,\n \"--\",\n context.line.prompt,\n ],\n cwd: context.workdir,\n env: { ...context.baseEnv },\n }),\n parse: parseLine,\n };\n}\n\n/** Maps one line of the fake agent's stdout. Never throws: anything unexpected is an `unparsed` signal. */\nexport function parseLine(text: string, context: AdapterContext): ParseResult {\n const unparsed: ParseResult = { events: [], signals: [{ kind: \"unparsed\", line: text }] };\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return unparsed;\n }\n const parsed = OutputLine.safeParse(json);\n if (!parsed.success) return unparsed;\n\n const line = parsed.data;\n const run = { missionId: context.missionId, runId: context.runId };\n switch (line.kind) {\n case \"phase\":\n return {\n events: [\n {\n type: \"run.progress\",\n ...run,\n phase: line.phase,\n ...(line.detail === undefined ? {} : { detail: line.detail }),\n },\n ],\n signals: [],\n };\n case \"tool\":\n return {\n events: [\n {\n type: \"run.tool\",\n ...run,\n tool: line.tool,\n ...(line.summary === undefined ? {} : { summary: line.summary }),\n files: line.files,\n },\n ],\n signals: [],\n };\n case \"usage\":\n return {\n events: [\n {\n type: \"run.usage\",\n ...run,\n seat: context.line.seat.id,\n amount: line.amount,\n unit: line.unit,\n estimated: false,\n },\n ],\n signals: [],\n };\n case \"limit\":\n return { events: [], signals: [{ kind: \"limit\", message: line.message }] };\n case \"sleep\":\n return { events: [], signals: [] };\n case \"report\":\n return { events: [], signals: [{ kind: \"report\", text: line.text }] };\n }\n}\n\nexport { EXIT, OutputLine } from \"./protocol.ts\";\nexport { Scenario, ScenarioStep, type ScenarioInput } from \"./scenario.ts\";\n", "import { RunProgress } from \"fanout-core\";\nimport { z } from \"zod\";\n\n/*\n * The fake agent's stdout: one JSON object per line. It stands in for a vendor CLI's stream, so the adapter parses it\n * the same way a real adapter parses Codex's or Kimi's output. The CLI writes it and the adapter reads it with this\n * one schema.\n */\nexport const OutputLine = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"phase\"),\n phase: RunProgress.shape.phase,\n detail: z.string().max(500).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"tool\"),\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n files: z.array(z.string().min(1).max(1000)).max(200),\n }),\n z.strictObject({ kind: z.literal(\"usage\"), amount: z.int().nonnegative(), unit: z.literal(\"messages\") }),\n z.strictObject({ kind: z.literal(\"limit\"), message: z.string().min(1).max(500) }),\n z.strictObject({ kind: z.literal(\"sleep\"), ms: z.int().nonnegative() }),\n z.strictObject({ kind: z.literal(\"report\"), text: z.string().max(20_000) }),\n]);\nexport type OutputLine = z.infer<typeof OutputLine>;\n\n/** Exit codes besides the scenario's own. */\nexport const EXIT = {\n /** A limit step was played: the simulated seat ran out of usage. */\n limit: 2,\n /** Bad arguments or an invalid scenario (EX_USAGE). */\n usage: 64,\n /** The scenario tried to write outside the working directory (EX_DATAERR). */\n unsafeWrite: 65,\n /** Anything unexpected (EX_SOFTWARE). */\n internal: 70,\n} as const;\n", "import { RunProgress } from \"fanout-core\";\nimport { z } from \"zod\";\n\n/*\n * What the fake agent does, step by step. Deterministic by design: no randomness, no clock in the output.\n * Example:\n * { \"steps\": [ { \"phase\": \"reading\", \"delayMs\": 300 },\n * { \"tool\": \"edit\", \"summary\": \"add csv writer\", \"write\": { \"src/api/csv.ts\": \"export \u2026\" } },\n * { \"usage\": 2 }, { \"limit\": \"usage limit reached\" } ],\n * \"report\": \"Added the endpoint.\", \"exitCode\": 0, \"timeScale\": 0.2 }\n */\n\nconst Delay = z.int().nonnegative().max(60_000).optional();\n\nconst PhaseStep = z.strictObject({\n phase: RunProgress.shape.phase,\n detail: z.string().max(500).optional(),\n delayMs: Delay,\n});\n\nconst ToolStep = z.strictObject({\n tool: z.string().min(1).max(100),\n summary: z.string().max(500).optional(),\n /** Files to really write, relative to the working directory, with their content. */\n write: z.record(z.string().min(1).max(1000), z.string().max(1_000_000)).optional(),\n delayMs: Delay,\n});\n\nconst UsageStep = z.strictObject({ usage: z.int().nonnegative().max(1_000_000), delayMs: Delay });\n\n/** The seat runs out of usage: the agent prints the message, writes its report and exits with code 2. */\nconst LimitStep = z.strictObject({ limit: z.string().min(1).max(500), delayMs: Delay });\n\nconst SleepStep = z.strictObject({ sleep: z.int().nonnegative().max(60_000) });\n\nexport const ScenarioStep = z.union([PhaseStep, ToolStep, UsageStep, LimitStep, SleepStep]);\nexport type ScenarioStep = z.infer<typeof ScenarioStep>;\n\nexport const Scenario = z.strictObject({\n steps: z.array(ScenarioStep).max(1000),\n report: z.string().max(20_000),\n exitCode: z.int().min(0).max(255).default(0),\n /** Keep running after the last step, until killed (to exercise timeouts). */\n hang: z.boolean().default(false),\n /** Multiplies every delay: 0.2 plays five times faster (the demo), 0 plays instantly (tests). */\n timeScale: z.number().nonnegative().max(100).default(1),\n});\nexport type Scenario = z.infer<typeof Scenario>;\nexport type ScenarioInput = z.input<typeof Scenario>;\n", "import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/*\n * Everything Fanout keeps lives in one directory, and only there: the ledger, the token, run logs and workspaces.\n * `FANOUT_HOME` moves the lot, which is how tests get their own and how someone can keep it off a synced folder.\n */\n\nexport interface FanoutHome {\n root: string;\n ledger: string;\n token: string;\n workspaces: string;\n runs: string;\n}\n\nexport function fanoutHome(env: Readonly<Record<string, string | undefined>> = process.env): FanoutHome {\n const root = env[\"FANOUT_HOME\"] ?? join(env[\"HOME\"] ?? homedir(), \".fanout\");\n return {\n root,\n ledger: join(root, \"ledger.db\"),\n token: join(root, \"token\"),\n workspaces: join(root, \"workspaces\"),\n runs: join(root, \"runs\"),\n };\n}\n", "/*\n * A terminal that keeps up with the crew.\n *\n * `fanout demo` used to print a header, go silent for half a minute while three agents worked, and then drop a\n * table of run ids on the floor. Everything interesting happened somewhere the viewer could not see, and the\n * first impression of the product was a frozen screen.\n *\n * Two rules shape this file.\n *\n * **The agent is the subject.** A row says who is working and what they are doing right now, in the words the\n * agent used \u2014 `reading src/api/orders.ts`, not `api-1 \u00B7 fake \u00B7 \u25AA\u25AA\u25AB\u25AB`. Ids and phase glyphs are a debugging view\n * of a mission; they are not what a person wants to know while it runs.\n *\n * **A pipe is not a terminal.** Redrawing in place needs a TTY and a person watching. Piped into a file, a CI log\n * or `verify:pack`, the same render appends one line per real change instead \u2014 no escape codes, no rewritten\n * history, and every state a reader might grep for still shown exactly once.\n */\n\n/** One agent, as a person watching would describe it. */\nexport interface LiveRow {\n /** Who is working. The demo's simulated crew are Agent 1, 2, 3; a real mission names the seat. */\n who: string;\n /** What they were asked for, in the plan's own words. */\n task: string;\n /** What they are doing at this moment, from their own output. Empty while queued. */\n doing: string;\n /** Finished rows keep their result here instead of a live action. */\n result?: string;\n state: \"waiting\" | \"working\" | \"done\" | \"failed\";\n /** Milliseconds since the agent started, or null before it did. */\n elapsedMs: number | null;\n}\n\nconst FRAMES = [\"\u280B\", \"\u2819\", \"\u2839\", \"\u2838\", \"\u283C\", \"\u2834\", \"\u2826\", \"\u2827\", \"\u2807\", \"\u280F\"];\nconst MARK = { waiting: \"\u00B7\", working: \"\", done: \"\u2713\", failed: \"\u2717\" } as const;\n\n/* Dim and green only. A demo that reaches for six colours looks like a toy; restraint reads as confidence. */\nconst DIM = \"\u001B[2m\";\nconst GREEN = \"\u001B[32m\";\nconst RED = \"\u001B[31m\";\nconst RESET = \"\u001B[0m\";\nconst HIDE_CURSOR = \"\u001B[?25l\";\nconst SHOW_CURSOR = \"\u001B[?25h\";\n\nexport interface LiveOptions {\n write: (text: string) => void;\n /** False for a pipe or a CI log, where cursor movement is noise rather than motion. */\n tty: boolean;\n /** How wide the terminal is. Defaults to the real one, or 80 where nothing says. */\n columns?: number;\n}\n\n/**\n * Draws the crew, over and over, without the screen ever flickering or scrolling away.\n *\n * It redraws only the rows it printed last time, so anything already above \u2014 the goal, the header \u2014 stays put and\n * the block never scrolls. A row is written once and then rewritten in place, which is what makes a terminal feel\n * alive rather than chatty.\n */\nexport function createLive(options: LiveOptions) {\n const write = options.write;\n let printed = 0;\n let frame = 0;\n /** What each row last said, so a pipe can print a line only when something actually changed. */\n const said = new Map<string, string>();\n /** The widest each column has ever been, so it never narrows again mid-mission. */\n const widest = new Map<string, number>();\n let cursorHidden = false;\n\n const render = (rows: readonly LiveRow[]): void => {\n if (!options.tty) {\n for (const row of rows) {\n /*\n * The clock is deliberately not part of what counts as a change. Including it printed a line per agent\n * per second \u2014 a log where the interesting moments are buried under a stopwatch. What changed is the\n * state and the action; the time is just stamped on whichever line reports it.\n */\n const key = `${row.state}|${row.result ?? row.doing}`;\n if (said.get(row.who) === key) continue;\n said.set(row.who, key);\n write(`${plainLine(row)}\\n`);\n }\n return;\n }\n\n if (!cursorHidden) {\n write(HIDE_CURSOR);\n cursorHidden = true;\n }\n // Back to the top of the block we drew last time, so this frame replaces it rather than following it.\n if (printed > 0) write(`\u001B[${String(printed)}A`);\n\n /*\n * Column widths only ever grow.\n *\n * Measuring each frame afresh made the layout twitch: `shell npm run check` is wide, the `+8 \u22122` that\n * replaces it is narrow, and the clock jumped left the moment an agent finished. A table that rearranges\n * itself while you read it is the thing that makes a terminal feel cheap, and it costs a few trailing\n * spaces to hold still.\n */\n const widthOf = (key: string, pick: (row: LiveRow) => string): number => {\n const wanted = rows.reduce((wide, row) => Math.max(wide, pick(row).length), 0);\n const held = Math.max(widest.get(key) ?? 0, wanted);\n widest.set(key, held);\n return held;\n };\n const whoWidth = widthOf(\"who\", (row) => row.who);\n const taskWidth = widthOf(\"task\", (row) => row.task);\n /*\n * The action is the column that gives way when the terminal is narrow. A wrapped row breaks the redraw\n * outright \u2014 the cursor moves back by lines, not by rows, so one wrap leaves the block drawing over itself.\n * Truncating is the difference between a tight layout and a corrupted screen.\n */\n /*\n * `process.stdout.columns` is declared as a number and is genuinely `undefined` when stdout is not a\n * terminal \u2014 which is precisely when this code runs in CI. Read it as it really is; taking the declaration\n * at its word makes the budget `NaN` and every row collapses to the minimum.\n */\n const real = process.stdout.columns as number | undefined;\n const budget = (options.columns ?? real ?? 80) - (whoWidth + taskWidth + 16);\n const saidWidth = Math.max(\n 8,\n Math.min(\n widthOf(\"said\", (row) => row.result ?? row.doing),\n budget,\n ),\n );\n\n frame = (frame + 1) % FRAMES.length;\n for (const row of rows) {\n const spinner = row.state === \"working\" ? FRAMES[frame] : MARK[row.state];\n const colour = row.state === \"done\" ? GREEN : row.state === \"failed\" ? RED : \"\";\n const said = fit(row.result ?? row.doing, saidWidth);\n const time = row.elapsedMs === null ? \"\" : clock(row.elapsedMs);\n\n // `\u001B[K` clears to the end of the line: a shorter action must not leave the tail of a longer one.\n write(\n ` ${colour}${spinner}${RESET} ` +\n `${row.who.padEnd(whoWidth)} ` +\n `${row.task.padEnd(taskWidth)} ` +\n `${DIM}${said.padEnd(saidWidth)}${RESET}` +\n (time === \"\" ? \"\" : ` ${DIM}${time}${RESET}`) +\n `\u001B[K\\n`,\n );\n }\n printed = rows.length;\n };\n\n /** Gives the terminal back. A demo that leaves the cursor hidden has broken the shell it was showing off in. */\n const stop = (): void => {\n if (cursorHidden) {\n write(SHOW_CURSOR);\n cursorHidden = false;\n }\n };\n\n return { render, stop };\n}\n\n/** Shortened to fit, with an ellipsis so a reader knows something was cut rather than missing. */\nfunction fit(text: string, width: number): string {\n return text.length <= width ? text : `${text.slice(0, Math.max(1, width - 1))}\u2026`;\n}\n\n/** `0:04`, `1:12`, `11:30` \u2014 a clock, because that is how people read a stopwatch. */\nfunction clock(ms: number): string {\n const total = Math.max(0, Math.floor(ms / 1000));\n return `${String(Math.floor(total / 60))}:${String(total % 60).padStart(2, \"0\")}`;\n}\n\n/** One line for a log: no colour, no spinner, and only when something changed. */\nfunction plainLine(row: LiveRow): string {\n const said = row.result ?? row.doing;\n const time = row.elapsedMs === null ? \"\" : ` (${clock(row.elapsedMs)})`;\n return ` ${row.who} \u00B7 ${row.task} \u00B7 ${row.state}${said === \"\" ? \"\" : ` \u2014 ${said}`}${time}`;\n}\n", "import { execFileSync } from \"node:child_process\";\nimport { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { PlanLine } from \"fanout-core\";\nimport type { ScenarioInput } from \"fanout-adapter-fake\";\n\n/*\n * A whole mission, on a machine with no accounts on it.\n *\n * Everything here is the real thing except the thinking. Real git worktrees, the real safety gate, the real\n * append-only ledger, real diffs collected from real files \u2014 driven by the `fake` seat, which is a genuine CLI\n * speaking the genuine protocol and taking a script instead of a model. Nothing is stubbed out inside the daemon,\n * because a demo that exercised a special path would be a demo of something nobody ships.\n *\n * It is honest about the one thing it cannot do. A cold reader's verdicts need a real second vendor; the demo's\n * are written here, and every surface that shows them says `simulated` out loud. Faking the one claim the product\n * makes would be the single most dishonest thing this repository could contain.\n */\n\n/** A small repository worth changing: three areas, one seeded bug, one commit. */\nexport function buildDemoRepo(root: string): string {\n rmSync(root, { recursive: true, force: true });\n mkdirSync(join(root, \"src\", \"api\"), { recursive: true });\n mkdirSync(join(root, \"src\", \"ui\"), { recursive: true });\n mkdirSync(join(root, \"docs\"), { recursive: true });\n\n writeFileSync(\n join(root, \"src\", \"api\", \"orders.ts\"),\n \"export interface Order {\\n id: string;\\n total: number;\\n}\\n\\n\" +\n \"export function ordersFor(customer: string): Order[] {\\n return [];\\n}\\n\",\n );\n writeFileSync(\n join(root, \"src\", \"api\", \"dates.ts\"),\n \"/** Formats a day. Off by one in December: the bug this demo fixes. */\\n\" +\n \"export function monthOf(date: Date): number {\\n return date.getMonth();\\n}\\n\",\n );\n writeFileSync(join(root, \"src\", \"ui\", \"table.ts\"), \"export const columns = ['id', 'total'];\\n\");\n writeFileSync(join(root, \"docs\", \"orders.md\"), \"# Orders\\n\\nThe orders API.\\n\");\n writeFileSync(\n join(root, \"package.json\"),\n `${JSON.stringify({ name: \"demo-shop\", private: true, scripts: { check: \"echo ok\" } }, null, 2)}\\n`,\n );\n\n const git = (args: string[]): void => {\n execFileSync(\"git\", args, {\n cwd: root,\n stdio: \"ignore\",\n env: { PATH: process.env[\"PATH\"] ?? \"\", HOME: process.env[\"HOME\"] ?? \"\", GIT_CONFIG_NOSYSTEM: \"1\" },\n });\n };\n git([\"init\", \"--quiet\", \"-b\", \"main\"]);\n git([\"config\", \"user.email\", \"demo@example.invalid\"]);\n git([\"config\", \"user.name\", \"Fanout demo\"]);\n git([\"add\", \"-A\"]);\n git([\"commit\", \"--quiet\", \"-m\", \"the shop, before the crew arrives\"]);\n return root;\n}\n\nexport const DEMO_GOAL = \"Add CSV export and fix the December date bug\";\n\n/**\n * Three lines that touch three different areas.\n *\n * One of them is marked `fixesBug`, which is the flag the merge gate holds to the fourth non-negotiable: that\n * line cannot merge without a test proven to fail on the old code. The demo exists partly to show that refusal.\n */\nexport function demoLines(): PlanLine[] {\n return [\n {\n id: \"api\",\n title: \"CSV export endpoint\",\n role: \"builder\",\n prompt: \"Add GET /orders.csv, streaming rows and escaping quotes.\",\n seat: { id: \"fake\", model: \"demo\" },\n // Narrowed to the file it writes. `src/api/**` swallowed the dates line's scope, and the safety gate\n // refused the plan \u2014 on the product's own demo, which is the best argument for the check there is.\n scope: { write: [\"src/api/csv.ts\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: false,\n },\n {\n id: \"dates\",\n title: \"Fix the December month bug\",\n role: \"builder\",\n prompt: \"monthOf() is off by one in December. Fix it and prove it with a test.\",\n seat: { id: \"fake\", model: \"demo\" },\n scope: { write: [\"src/api/dates.ts\", \"src/api/dates.test.ts\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: true,\n },\n {\n id: \"ui\",\n title: \"Export button\",\n role: \"builder\",\n /*\n * The one line that asks for a seat this machine does not have. Nothing here fakes the consequence: the\n * demo's crew really is the simulated seat alone, so the router really does move this line and really does\n * say why \u2014 which is the behaviour worth showing, and the only honest way to show it offline.\n */\n prompt: \"Add the export column and a button that hits the new endpoint.\",\n seat: { id: \"codex\", model: \"gpt-5-codex\" },\n scope: { write: [\"src/ui/**\"] },\n dependsOn: [],\n checks: [\"npm run check\"],\n fixesBug: false,\n },\n ];\n}\n\n/**\n * What each simulated agent does, second by second.\n *\n * `timeScale` is the only dishonesty about time and it is the useful kind: a real run takes minutes and nobody\n * watches a demo for minutes. The phases, the tool calls and the files are what a real run of this shape does.\n */\nexport function demoScenario(line: PlanLine): ScenarioInput {\n const scenarios: Record<string, ScenarioInput> = {\n api: {\n steps: [\n { phase: \"reading\", delayMs: 900 },\n { tool: \"read\", summary: \"src/api/orders.ts\", delayMs: 700 },\n { phase: \"coding\", delayMs: 600 },\n {\n tool: \"edit\",\n summary: \"add the csv writer\",\n delayMs: 1400,\n write: {\n \"src/api/csv.ts\":\n \"import type { Order } from './orders.ts';\\n\\n\" +\n \"/** One row per order. A quote inside a field is doubled, per RFC 4180. */\\n\" +\n \"export function toCsv(orders: Order[]): string {\\n\" +\n \" const rows = orders.map((order) => `${quote(order.id)},${order.total}`);\\n\" +\n \" return ['id,total', ...rows].join('\\\\n');\\n}\\n\\n\" +\n \"function quote(value: string): string {\\n\" +\n \" return value.includes(',') || value.includes('\\\"')\\n\" +\n ' ? `\"${value.split(\\'\"\\').join(\\'\"\"\\')}\"`\\n : value;\\n}\\n',\n },\n },\n { phase: \"testing\", delayMs: 900 },\n { tool: \"shell\", summary: \"npm run check\", delayMs: 1100 },\n { usage: 3 },\n { phase: \"reporting\", delayMs: 400 },\n ],\n report: \"Added toCsv() with RFC 4180 quoting. Streaming is left for a follow-up.\",\n timeScale: 1,\n },\n dates: {\n steps: [\n { phase: \"reading\", delayMs: 800 },\n { phase: \"coding\", delayMs: 900 },\n {\n tool: \"edit\",\n summary: \"months are zero-based\",\n delayMs: 1200,\n write: {\n \"src/api/dates.ts\":\n \"/** Formats a day. getMonth() is zero-based, which is where December went wrong. */\\n\" +\n \"export function monthOf(date: Date): number {\\n return date.getMonth() + 1;\\n}\\n\",\n \"src/api/dates.test.ts\":\n \"import { monthOf } from './dates.ts';\\n\\n\" +\n \"// Fails on the old code: it returned 11 for December.\\n\" +\n \"test('December is the twelfth month', () => {\\n\" +\n \" expect(monthOf(new Date('2026-12-01'))).toBe(12);\\n});\\n\",\n },\n },\n { phase: \"testing\", delayMs: 1000 },\n { tool: \"shell\", summary: \"npm run check\", delayMs: 900 },\n { usage: 2 },\n { phase: \"reporting\", delayMs: 400 },\n ],\n report: \"monthOf() was zero-based. Fixed, with a test that fails on the old code.\",\n timeScale: 1,\n },\n ui: {\n steps: [\n { phase: \"reading\", delayMs: 1000 },\n { phase: \"coding\", delayMs: 1500 },\n {\n tool: \"edit\",\n summary: \"export column and button\",\n delayMs: 1600,\n write: {\n \"src/ui/table.ts\": \"export const columns = ['id', 'total', 'export'];\\n\",\n \"src/ui/export-button.ts\":\n \"export function exportButton(): string {\\n\" +\n \" return '<button data-href=\\\"/orders.csv\\\">Export CSV</button>';\\n}\\n\",\n },\n },\n { usage: 4 },\n { phase: \"reporting\", delayMs: 600 },\n ],\n report: \"Added the column and the button.\",\n timeScale: 1,\n },\n };\n\n const scenario = scenarios[line.id];\n if (scenario === undefined) throw new Error(`the demo has no script for line \"${line.id}\"`);\n return scenario;\n}\n\n/**\n * The claim check the demo shows, written here rather than asked of anyone.\n *\n * Marked `simulated` all the way through to the screen. A real check needs a real second vendor and a\n * subscription; inventing one and presenting it as read would be faking the single thing this product claims to\n * do, which is worse than having no demo at all.\n */\nexport function demoClaims(): {\n claim: string;\n verdict: \"confirmed\" | \"refuted\" | \"unclear\";\n evidence: string;\n}[] {\n return [\n {\n claim: \"The December fix comes with a test that fails on the old code\",\n verdict: \"confirmed\",\n evidence: \"dates.test.ts expects 12; the old monthOf returned 11 \u00B7 src/api/dates.ts:3\",\n },\n {\n claim: \"Nothing outside the three declared scopes was touched\",\n verdict: \"confirmed\",\n evidence: \"every changed path falls inside a declared write scope\",\n },\n {\n claim: \"toCsv escapes every field that needs it\",\n verdict: \"refuted\",\n evidence: \"a field containing a newline is not quoted \u00B7 src/api/csv.ts:10\",\n },\n ];\n}\n", "import {\n elapsedMs,\n EMPTY_POLICY,\n formatDuration,\n silentMs,\n stanceFor,\n type ProjectionState,\n type SeatInfo,\n type SeatPolicy,\n} from \"fanout-core\";\n\n/*\n * How the crew reads in a terminal. The rule everywhere: say what is known, say plainly what is not, and never let\n * an unknown look like a yes.\n */\n\nconst SIGN_IN: Record<SeatInfo[\"signedIn\"], string> = {\n yes: \"signed in\",\n no: \"not signed in\",\n unknown: \"unknown\",\n};\n\nexport function crewTable(seats: readonly SeatInfo[], policy: SeatPolicy = EMPTY_POLICY): string {\n if (seats.length === 0) return \"No agent CLIs found on this machine.\\n\";\n\n const rows = seats.map((seat) => ({\n name: seat.displayName,\n version: seat.version ?? \"not installed\",\n state: seat.supported ? SIGN_IN[seat.signedIn] : seat.version === null ? \"\u2014\" : \"unsupported version\",\n ready: stanceFor(seat, policy).usable,\n // \"normal\" is what a seat is when nobody has said anything, and printing it down every row would bury the\n // one or two the owner actually decided about.\n posture: stanceFor(seat, policy).posture === \"normal\" ? \"\" : stanceFor(seat, policy).posture,\n // Most CLIs do not report a tier. An empty column says that better than a word like \"unknown\" repeated\n // down the table, and the source travels with the value so nobody has to wonder who said it.\n plan: seat.plan === null ? \"\" : `${seat.plan.name} (${seat.plan.source})`,\n }));\n const width = {\n name: Math.max(...rows.map((row) => row.name.length)),\n version: Math.max(...rows.map((row) => row.version.length)),\n state: Math.max(...rows.map((row) => row.state.length)),\n plan: Math.max(...rows.map((row) => row.plan.length)),\n };\n\n const lines = rows.map((row) =>\n (\n ` ${row.ready ? \"\u2022\" : \" \"} ${row.name.padEnd(width.name)} ${row.version.padEnd(width.version)} ` +\n `${row.state.padEnd(width.state)} ${row.plan.padEnd(width.plan)} ${row.posture}`\n ).trimEnd(),\n );\n const ready = rows.filter((row) => row.ready).length;\n\n return `Crew on this machine (${ready} ready)\\n${lines.join(\"\\n\")}\\n`;\n}\n\nexport function missionLines(state: ProjectionState, now: Date = new Date(), repoRoot?: string): string {\n const all = Object.values(state.missions);\n if (all.length === 0) return \"No missions yet.\\n\";\n\n /*\n * Only this repository's missions, when we know which repository we are standing in.\n *\n * The ledger is one file for the whole machine, so without this a developer in their own project was shown\n * missions from two unrelated ones \u2014 found by running `fanout status` in a scratch repo and being told about\n * work on a website and on Fanout itself. The count of what is elsewhere is still worth a line, because\n * silently hiding a running mission is its own kind of lie.\n */\n const missions = repoRoot === undefined ? all : all.filter((m) => m.repo.root === repoRoot);\n const elsewhere = all.length - missions.length;\n const footnote =\n elsewhere === 0\n ? \"\"\n : `\\n ${String(elsewhere)} mission${elsewhere === 1 ? \"\" : \"s\"} in other repositories, not shown.\\n`;\n\n if (missions.length === 0) return `No missions in this repository.${footnote}`;\n\n const lines = missions.map((mission) => {\n const runs = Object.values(mission.runs);\n const running = runs.filter((run) => run.status === \"running\" || run.status === \"queued\").length;\n const merged = runs.filter((run) => run.status === \"merged\").length;\n const waiting = runs.filter((run) => run.status === \"done\" && run.review === null).length;\n // A mission where every working run has gone silent is the one worth walking back to the terminal for.\n const quiet = runs.filter((run) => (silentMs(run, now) ?? 0) >= 60_000).length;\n const longest = runs.reduce((most, run) => Math.max(most, elapsedMs(run, now) ?? 0), 0);\n const parts = [\n `${runs.length} run${runs.length === 1 ? \"\" : \"s\"}`,\n running > 0 ? `${running} running` : \"\",\n waiting > 0 ? `${waiting} waiting for review` : \"\",\n merged > 0 ? `${merged} merged` : \"\",\n longest > 0 ? formatDuration(longest) : \"\",\n quiet > 0 ? `${quiet} quiet` : \"\",\n ].filter((part) => part !== \"\");\n return ` ${mission.missionId.padEnd(16)} ${mission.status.padEnd(9)} ${parts.join(\" \u00B7 \")}`;\n });\n\n const anomalies =\n state.anomalies.length === 0\n ? \"\"\n : `\\n ${state.anomalies.length} event(s) did not fit the story and were kept as anomalies.\\n`;\n\n return `Missions\\n${lines.join(\"\\n\")}\\n${footnote}${anomalies}`;\n}\n", "import { mergeReadiness, type ClaimCheck, type MissionView, type PlanLine, type RunView } from \"fanout-core\";\n\n/*\n * What is still owed, for the Stop hook.\n *\n * Everything else in Fanout is a tool the lead chooses to call, and that is the weakness: the failure mode is not\n * \"the gate said no\", it is \"nobody asked the gate\", or a lead that believes its own work is finished. A hook runs\n * whether or not anyone remembered it, which makes \"done\" a claim the session can check rather than one it asserts.\n *\n * It reports; it does not block. A hook that refused to let a session end would be a hostage-taker the first time\n * someone legitimately wanted to stop \u2014 and a person who wants to walk away from unfinished work is allowed to.\n * The point is that they do it knowingly.\n */\n\n/** What the lead's own uncommitted work still owes, if anything. */\nexport interface OwnWork {\n /** The revision the working tree is at now. */\n revision: string;\n files: number;\n /** The most recent claim check, if any, whatever revision it was about. */\n checked: ClaimCheck | undefined;\n}\n\n/**\n * What to say about the lead's own changes.\n *\n * The runs a crew produced are the obvious thing to guard, and they are not where most of a session's code comes\n * from: the lead writes it, and the lead is its only reader. A check nobody is reminded of is a check nobody runs,\n * which is why this asks about the working tree and not only about the mission.\n */\nexport function ownWorkOwed(work: OwnWork): string {\n if (work.files === 0) return \"\";\n\n const changed = `${String(work.files)} changed file${work.files === 1 ? \"\" : \"s\"}`;\n if (work.checked === undefined) {\n return ` ${changed}, and nobody but you has read them. Try: fanout check \"<something you believe>\"`;\n }\n if (work.checked.revision !== work.revision) {\n // A check of older bytes is not a check of these ones, and saying \"checked\" here would be the lie.\n return ` ${changed}, and they have moved since the last check. Run it again.`;\n }\n if (!work.checked.ran) {\n return ` ${changed}, and the last check could not run at all.`;\n }\n\n const refuted = work.checked.claims.filter((claim) => claim.verdict === \"refuted\");\n if (refuted.length > 0) {\n return [\n ` ${String(refuted.length)} of your own claims was refuted and is not fixed:`,\n ...refuted.map((claim) => ` \u2717 ${claim.claim}\\n ${claim.evidence}`),\n ].join(\"\\n\");\n }\n return \"\";\n}\n\nexport interface Owed {\n missionId: string;\n runId: string;\n /** One line, written for someone about to close their laptop. */\n what: string;\n}\n\n/**\n * Every run that is waiting on the lead: finished agents nobody has reviewed, checks nobody has run, fixes with\n * no proof, work reviewed at a revision that has since moved.\n *\n * Runs still working are deliberately not here. They are not owed by anyone; they are simply not done, and the\n * mission view says so already.\n */\nexport function whatIsOwed(missions: readonly MissionView[]): Owed[] {\n const owed: Owed[] = [];\n\n for (const mission of missions) {\n const lines = new Map<string, PlanLine>((mission.plan?.lines ?? []).map((line) => [line.id, line]));\n\n for (const runId of mission.runOrder) {\n const run = mission.runs[runId];\n if (run === undefined || !waitingOnTheLead(run)) continue;\n\n const line = lines.get(run.lineId);\n if (line === undefined) {\n owed.push({ missionId: mission.missionId, runId, what: \"finished, but its plan line is missing\" });\n continue;\n }\n\n /*\n * The run's own recorded revision is the best we can do from the ledger alone: a hook must not go and read\n * the worktree, because it runs on every turn and must stay fast. Asking readiness about the revision the\n * review saw answers \"is anything missing\", which is the hook's question \u2014 \"has the work moved since\" is\n * the merge tool's, and it recollects the diff to find out.\n */\n const judged = run.review?.revision ?? run.checks?.revision ?? run.approval?.revision ?? \"\";\n const { blockers } = mergeReadiness(run, line, judged);\n const first = blockers[0];\n if (first !== undefined) owed.push({ missionId: mission.missionId, runId, what: first.message });\n }\n }\n\n return owed;\n}\n\n/** A run the agent has finished with, that has not yet been merged, dropped or run into a conflict. */\nfunction waitingOnTheLead(run: RunView): boolean {\n return run.status === \"done\";\n}\n\n/** The hook's whole output. Empty string when nothing is owed, so a quiet session stays quiet. */\nexport function unfinishedReport(owed: readonly Owed[], own = \"\"): string {\n const parts: string[] = [];\n\n if (owed.length > 0) {\n const lines = owed.map((item) => ` ${item.missionId} \u00B7 ${item.runId}: ${item.what}`);\n const count = `${String(owed.length)} run${owed.length === 1 ? \"\" : \"s\"}`;\n parts.push(\n `${count} still waiting on you before anything can merge.\\n${lines.join(\"\\n\")}\\n` +\n `Nothing has been merged. Review them, or drop them on purpose.`,\n );\n }\n if (own !== \"\") parts.push(`Your own changes:\\n${own}`);\n\n return parts.length === 0 ? \"\" : `Fanout: ${parts.join(\"\\n\\n\")}\\n`;\n}\n", "#!/usr/bin/env node\n// First, and it has to stay first: it silences a warning that fires while the imports below are evaluating.\nimport \"./quiet.ts\";\nimport { main } from \"./main.ts\";\n\n/* The thin edge of the CLI: everything testable lives in main.ts, which takes its output as an argument. */\n\nconst code = await main(process.argv.slice(2), {\n out: (text) => process.stdout.write(text),\n err: (text) => process.stderr.write(text),\n});\nprocess.exitCode = code;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AA+BnB,SAAS,SAAiC;AAC/C,QAAM,OAAO,QAAQ,IAAI,MAAM;AAC/B,QAAM,OAAO,QAAQ,IAAI,MAAM;AAC/B,SAAO;AAAA,IACL,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,MAAM,KAAK;AAAA,IAC3C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M,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,SAAO,GAAG,SAAS,YAAY;AAE/B,QAAM,OAAO,MAAM;AACnB,QAAM,IAAI,MAAM;AAChB,SAAO,MAAM;AACb,SAAO;AACT;AAEA,SAAS,cAA6B;AACpC,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,UAAM,OAAO,MAAY;AACvB,cAAQ;AAAA,IACV;AACA,YAAQ,KAAK,UAAU,IAAI;AAC3B,YAAQ,KAAK,WAAW,IAAI;AAAA,EAC9B,CAAC;AACH;;;A0D36BA,IAAM,OAAO,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EAC7C,KAAK,CAACY,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAAA,EACxC,KAAK,CAACA,UAAS,QAAQ,OAAO,MAAMA,KAAI;AAC1C,CAAC;AACD,QAAQ,WAAW;",
6
+ "names": ["run", "existsSync", "realpathSync", "rmSync", "writeFileSync", "join", "z", "text", "z", "z", "lines", "z", "z", "check", "z", "z", "z", "z", "seat", "z", "z", "run", "mission", "message", "run", "mission", "count", "run", "code", "message", "seat", "text", "z", "text", "run", "command", "isAbsolute", "relative", "manifest_default", "z", "manifest", "manifest_default", "TEST_COMMAND", "text", "run", "repoRelative", "isAbsolute", "relative", "isAbsolute", "relative", "manifest_default", "z", "manifest", "manifest_default", "TEST_COMMAND", "WRITING", "text", "run", "command", "repoRelative", "isAbsolute", "relative", "closeSync", "openSync", "status", "text", "handle", "code", "mkdirSync", "dirname", "mkdirSync", "dirname", "handle", "execFile", "readFileSync", "promisify", "promisify", "execFile", "added", "readFileSync", "check", "message", "seat", "count", "status", "execFile", "promisify", "text", "run", "promisify", "execFile", "manifest", "text", "mkdirSync", "join", "run", "adapters", "status", "join", "mkdirSync", "readFileSync", "join", "chmodSync", "existsSync", "mkdirSync", "readFileSync", "dirname", "port", "mission", "run", "lines", "status", "text", "mission", "run", "status", "mkdirSync", "readFileSync", "writeFileSync", "dirname", "join", "join", "text", "readFileSync", "mkdirSync", "dirname", "writeFileSync", "wanted", "run", "mkdirSync", "writeFileSync", "dirname", "isAbsolute", "join", "relative", "join", "relative", "isAbsolute", "run", "applyPatch", "writeFileSync", "mkdirSync", "dirname", "manifest", "text", "item", "count", "execFile", "code", "seat", "manifest", "fill", "firstLines", "describe", "item", "text", "count", "text", "readFileSync", "spawn", "existsSync", "mkdirSync", "readdirSync", "renameSync", "rmSync", "dirname", "join", "relative", "readdirSync", "join", "run", "command", "relative", "existsSync", "rmSync", "renameSync", "mkdirSync", "dirname", "spawn", "code", "count", "copyFileSync", "mkdirSync", "mkdtempSync", "rmSync", "tmpdir", "dirname", "join", "mkdtempSync", "join", "tmpdir", "mkdirSync", "dirname", "copyFileSync", "run", "rmSync", "copyFileSync", "existsSync", "mkdirSync", "dirname", "join", "join", "existsSync", "mkdirSync", "dirname", "copyFileSync", "describe", "run", "execFile", "gitEnv", "join", "run", "attempt", "join", "randomBytes", "existsSync", "readFileSync", "join", "z", "MissionLimits", "daemon", "ready", "seat", "lines", "check", "handle", "mission", "join", "existsSync", "readFileSync", "manifest", "run", "message", "count", "randomBytes", "existsSync", "z", "z", "existsSync", "text", "run", "join", "wanted", "said", "text", "mkdirSync", "rmSync", "writeFileSync", "join", "git", "seat", "lines", "ready", "mission", "run", "owed", "mission", "lines", "run", "item", "count", "manifest", "command", "check", "run", "join", "rmSync", "handle", "mission", "existsSync", "ready", "count", "unclear", "seat", "ledger", "wanted", "writeFileSync", "realpathSync", "text"]
7
7
  }