Close W7: cross-compile the release again, guard pi's edits, and keep the swarm out of this checkout
Before adoption: this commit came in with the history the project adopted, so no landing records it.
W7's merges came in four groups (5060ac3, 2b7b80c, ce68196, 368c432); this folds each issue's open requests that the merges or the demo force. No stretch issue was cut: 708, 709 and 710 all started and merged; 708 (cut line 2) and 709 (cut line 3) land as tested modules nothing calls yet, and README's "Keep or cut" now says so. - The release build failed on main since 710's wiring: `bun build --compile --target=bun-darwin-arm64` could not resolve `@opentui/core-darwin-arm64`, which `bun install` skips on Linux. `build.ts` now fetches each cross target's OpenTUI native packages into a temp folder with `bun install --os --cpu` and compiles with `NODE_PATH` on it (`build-targets.ts`'s `npmMachineOf`; `apps/cli/test/build-targets.test.ts`, red on a stub first). `bun run release -- --build` passes; `node apps/cli/dist/bin.js --help` prints the banner. Binaries grow with the TUI's native library: linux-x64 100.7 MB (was 82.8), darwin-arm64 69.0 MB (was 63.8). - pi's edits are judged (706 #3): `hook/decide.ts` exports `toolRefusals`, Claude Code's pre-tool-use and pi's `edit`/`write` both ask it, from the kept facts only. Test: `pi.test.ts` "judge an edit as the hook's pre-tool-use does" (TouchedJudge, OutOfScope, none inside the territory, none without a claim), red by assertion first. - The local check starts at the claim's base (706 #5b): `HookClaim.base`, `PushCheck.run(root, base)` passes `--base`, so work committed on the fork's main is seen by the Stop hook and pi's preflight and settle. Tests: `hook.test.ts` (the argv carries `--base <sha>`; the stop hook asks from the claim's base), red first. - The swarm's folder moved out of the checkout (717 #1): `SwarmDir` defaults to `${XDG_STATE_HOME:-$HOME/.local/state}/<slug>/swarm`, so no contributor's harness reads this repo's own AGENTS.md or CLAUDE.md. Tests: `swarm.test.ts` "the swarm's folder", red on a stub first. - The verdict loop (717 #2): refusals that are all the platform's side (`VerifierBlocked`, `Flake`, `RepoBusy`) go back as a wait ("not a fault in your change", push the same work again with an empty commit), and a nudge after a refused answer names the head it last saw instead of saying none arrived. Tests in `swarm-loop.test.ts`, red first. - tamsin runs `openai/gpt-5.5` (711 #2): OpenCode on a ChatGPT account refuses `gpt-6.1-sol`. Golden argv rows updated first (red), then the roster. - `docs/demo/swarm-scenario.md` quotes the roster's model ids and both video nudges word for word (713 #1); `demo-docs.test.ts` holds both against `roster` and `nudges("video", i)`, red first. - `LayerName` takes an ask's words (707): a layer `a--b` would make a repo that reads as a claim fork. `domain.test.ts`, red first; ADR 0008 updated. - One home each: `recordedSubdomain` in `infra/stages.ts` for seed, smoke and the swarm (702); `committable` and `textOf` in `packages/config/test/root.ts` for the README and cartridge tests (704); `@repo/agent-kit` is a root devDependency, so the release imports it by package (715 #5). - Docs: AGENTS.md's `swarm` line says what the swarm does now (711 and 717 merged); README links ADR 0014 and 0015; the platform's `.env.schema` and `tsdown.config.ts` no longer cite the private build plan. - Not applied, each answered in its issue: the version stamp (715 #4), the npm build's config runtime (715 #7), wiring 708 and 709, one `sessionFacts` (706 #4), gitignored and `.git/` edits (415 #20), refusal wording (707), and the sweep of plan citations left in code comments (313 lines in 196 files, before H3). - verify green: cli 318, config 231, protocol 385, checks 334, project 474, platform 417; brand:check 1065 files; platform entry 1,605,405 of 1,665,000.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
39 files+733 added−288 removed
- tests:+286 added−106 removed
- other:+447 added−182 removed
Provenance
- Commit
842f042- Tree
6259609- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
368c432
39 files changed+733 added−288 removed
modified:apps/cli/src/hook/decide.ts+26 added-8 removed
1 /**2 * The one hook policy: what `<cli> hook <event>` answers a harness, from3 * facts gathered elsewhere. Pure, so every harness adapter (Claude Code's4- * hook format here; pi's events in W7) asks the same function.4+ * hook format here; pi's events in `../pi.ts`) asks the same function.5 *6 * It writes no second policy: a path's refusal is the gate's own reading of7 * the territory and the judge closure (`@repo/gate/glob`, over the closure8 * `@repo/checks` computes), and its text is `@repo/protocol/render`'s5 unmodified lines14 import { Brand } from "@repo/brand";15 import { matchAny } from "@repo/gate/glob";16 import type { Policy } from "@repo/protocol/domain/policy";17 import { Territory } from "@repo/protocol/domain/territory";18-import { AskId, ProjectName, RepoPath } from "@repo/protocol/ids";18+import { AskId, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";19 import { OutOfScope, TouchedJudge } from "@repo/protocol/refusal";20 import type { Refusal } from "@repo/protocol/refusal";21 import { explain } from "@repo/protocol/render";22 import { Array, Option, Predicate, Schema } from "effect";2 unmodified lines25 26 /** The claim this session works on, as the hook needs it. */27 export const HookClaim = Schema.Struct({28 ask: AskId,29+ /** Main when the claim was made: where the gateway's diff of an answer starts. */30+ base: CommitSha,31 /** What `<cli> check` runs locally for the ask: the claim's own. */32 checkCommand: Schema.NonEmptyString,33 project: ProjectName,34 territory: Territory,133 unmodified lines168 ? []169 : [new OutOfScope({ paths: [path] })];170 };171 170-const preToolUse = (input: HookInput, facts: HookFacts): HookDecision =>172+/**173+ * What the gate's shape stage would refuse of the file a writing tool is174+ * about to change: none without a claim, for a tool that writes no file, or175+ * for a file outside the repo. Every harness's edit guard asks this (Claude176+ * Code's pre-tool-use below; pi's `edit` and `write` in `../pi.ts`).177+ */178+export const toolRefusals = (179+ input: HookInput,180+ facts: Pick<HookFacts, "claim" | "judge" | "root">181+): readonly Refusal[] =>182 Option.match(facts.claim, {172- onNone: () => allow(facts.holds, NO_CLAIM),173- onSome: (claim) => {174- const refusals = Option.match(183+ onNone: () => [],184+ onSome: (claim) =>185+ Option.match(186 Option.flatMap(fileOf(input), (file) =>187 repoPathOf(facts.root, input.cwd, file)188 ),189 {179- onNone: (): readonly Refusal[] => [],190+ onNone: () => [],191 onSome: (path) => pathRefusals(claim, facts.judge, path),192 }182- );193+ ),194+ });195 196+const preToolUse = (input: HookInput, facts: HookFacts): HookDecision =>197+ Option.match(facts.claim, {198+ onNone: () => allow(facts.holds, NO_CLAIM),199+ onSome: () => {200+ const refusals = toolRefusals(input, facts);201+202 return Array.isReadonlyArrayNonEmpty(refusals)203 ? {204 holds: facts.holds,205 note: Option.none(),118 unmodified linesmodified:apps/cli/src/hook/facts.ts+1 added
147 unmodified linesExpand all14814915015115215315415515611 unmodified lines147 unmodified linesExpand all );
const claim: HookClaim = { ask: live.ask, base: live.base, checkCommand: live.checkCommand, project: live.project, territory: shown.ask.territory, want: shown.ask.brief.want,11 unmodified linesmodified:apps/cli/src/hook/push-check.ts+21 added-10 removed
1 /**2 * The Stop hook's question: does `<cli> check` refuse the work as it stands?3 * Asked through a port, so the hook never imports the check command's4 * modules: the default adapter runs this same CLI as a child process,5- * `check --shape-only --offline --json`, and decodes its envelope.5+ * `check --shape-only --offline --json --base <claim's base>`, and decodes6+ * its envelope. Offline, the check cannot read the claim's base itself, and7+ * main would be the wrong start for work committed on main.8 */9 import { Envelope } from "@repo/protocol/envelope";10 import type { Refusal } from "@repo/protocol/refusal";11 import {19 unmodified lines31 32 export class PushCheck extends Context.Service<33 PushCheck,34 {33- /** The refusals `<cli> check --shape-only` gives for the repo at `root`; none when it passes. */35+ /**36+ * The refusals `<cli> check --shape-only` gives for the repo at `root`,37+ * diffed from the claim's `base` as the gateway diffs; none when it passes.38+ */39 readonly run: (35- root: string40+ root: string,41+ base: string42 ) => Effect.Effect<readonly Refusal[], PushCheckFailed>;43 }44 >()("cli/PushCheck") {}45 11 unmodified lines57 bytes.pipe(Stream.decodeText(), Stream.mkString);58 59 /**60 * `PushCheck` over a child process: `command` (the CLI, as this process was55- * started) with `check --shape-only --offline --json`, in `root`. It exits 161+ * started) with `check --shape-only --offline --json --base <base>`, in62+ * `root`. It exits 163 * when it refuses, so the exit code says nothing; the envelope says all.64 */65 export const pushCheckWith = (66 command: readonly [string, ...string[]]3 unmodified lines70 Effect.gen(function* () {71 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;72 const [executable, ...leading] = command;73 67- const run = (root: string) =>74+ const run = (root: string, base: string) =>75 Effect.scoped(76 Effect.gen(function* () {77 const child = yield* spawner.spawn(78+ ChildProcess.make(79+ executable,80+ [...leading, ...CHECK, "--base", base],71- ChildProcess.make(executable, [...leading, ...CHECK], {72- cwd: root,73- stderr: "ignore",74- stdin: "ignore",75- })81+ {82+ cwd: root,83+ stderr: "ignore",84+ stdin: "ignore",85+ }86+ )87 );88 89 const [stdout] = yield* Effect.all(90 [text(child.stdout), child.exitCode],92 unmodified linesmodified:apps/cli/src/hook.ts+7 added-4 removed
97 unmodified lines98 99 return gathered;100 });101 102-/** Stop asks the local check; nothing else does, and only with a claim. */103-const refusalsFor = (event: HookEvent, state: SessionState) =>104- event === "stop" && state.claim !== undefined105- ? Effect.flatMap(pushCheck, (check) => check.run(state.root))102+/** Stop asks the local check, from the claim's base; nothing else does, and only with a claim. */103+const refusalsFor = (event: HookEvent, state: SessionState) => {104+ const { claim } = state;105+106+ return event === "stop" && claim !== undefined107+ ? Effect.flatMap(pushCheck, (check) => check.run(state.root, claim.base))108 : Effect.succeed([]);109+};110 111 /** Answers one event: the decision's JSON, with its note on stderr. */112 const answer = (event: HookEvent, input: HookInput) =>113 Effect.gen(function* () {109 unmodified linesmodified:apps/cli/src/pi.ts+26 added-10 removed
40 unmodified lines41 import type { FileSystem, Path } from "effect";42 import type { ChildProcessSpawner } from "effect/process";43 44 import { CredentialsFile } from "./credentials.ts";45-import { decideHook, MAX_HOLDS } from "./hook/decide.ts";45+import { decideHook, MAX_HOLDS, toolRefusals } from "./hook/decide.ts";46 import type { HookFacts } from "./hook/decide.ts";47 import { gatherFacts } from "./hook/facts.ts";48 import type { HookInput } from "./hook/input.ts";49 import { PushCheck, pushCheckWith } from "./hook/push-check.ts";365 unmodified lines415 session_id: session.id,416 });417 418 /**419- * What `<cli> check --shape-only` refuses of the work as it stands, by the420- * policy's own `PushCheck`; nothing is asked without a claim.419+ * What `<cli> check --shape-only` refuses of the work as it stands, from the420+ * claim's base, by the policy's own `PushCheck`; nothing is asked without a421+ * claim.422 */422-const localCheck = (state: SessionState) =>423- state.claim === undefined423+const localCheck = ({ claim, root }: SessionState) =>424+ claim === undefined425 ? Effect.succeed<readonly Refusal[]>([])426 : Effect.flatMap(Effect.service(PushCheck), (check) =>426- check.run(state.root)427+ check.run(root, claim.base)428 );429 430 /** What the hook policy runs on. */431 export type PolicyServices =35 unmodified lines467 (failed) => new HookFailed({ reason: failed.message })468 ),469 Effect.provide(services)470 ),470- // The policy decides an edit (`decideHook`'s pre-tool-use) but hands471- // back only its text, not the refusals; until it hands them back, a472- // pi edit is left to the gateway.473- Write: () => Effect.succeedNone,471+ // An edit is judged as the hook's pre-tool-use judges one, from the472+ // kept facts alone: no check runs and the platform is never asked.473+ Write: ({ file }) =>474+ Effect.map(factsOf(session, false), (state) =>475+ Array.match(476+ toolRefusals(477+ {478+ ...hookInput("pre-tool-use", session),479+ tool_input: { file_path: file },480+ tool_name: "Write",481+ },482+ hookFacts(state, [])483+ ),484+ {485+ onEmpty: () => Option.none(),486+ onNonEmpty: (refusals) => Option.some(refusals),487+ }488+ )489+ ).pipe(Effect.provide(services)),490 }),491 492 settle: (session) =>493 Effect.gen(function* () {43 unmodified linesadded:apps/cli/test/build-targets.test.ts+34 added
12345678910111213141516171819202122232425262728293031323334/** * A cross-compiled binary needs another machine's native packages, which * `bun install` leaves out on this one: the build fetches them for npm's * `os` and `cpu`, read here from Bun's target names. */import { describe, expect, it } from "@effect/vitest";import { Option } from "effect";
import { npmMachineOf } from "../build-targets.ts";
describe("a compile target's machine, as npm names it", () => { it("reads the release's two targets, with or without Bun's prefix", () => { expect(npmMachineOf("bun-darwin-arm64")).toStrictEqual( Option.some({ cpu: "arm64", os: "darwin" }) ); expect(npmMachineOf("linux-x64")).toStrictEqual( Option.some({ cpu: "x64", os: "linux" }) ); });
it("calls Windows win32, and drops Bun's modifiers", () => { expect(npmMachineOf("bun-windows-x64-baseline")).toStrictEqual( Option.some({ cpu: "x64", os: "win32" }) ); expect(npmMachineOf("linux-arm64-musl")).toStrictEqual( Option.some({ cpu: "arm64", os: "linux" }) ); });
it("knows no machine for a target Bun does not name", () => { expect(npmMachineOf("bun-plan9-x64")).toStrictEqual(Option.none()); expect(npmMachineOf("darwin")).toStrictEqual(Option.none()); });});modified:apps/cli/test/hook.test.ts+49 added-2 removed
97 unmodified lines98 99 /** Alice's claim on `fix-week`, as the hook keeps it. */100 const claim: HookClaim = {101 ask: ask.id,102+ base: CommitSha.make("1".repeat(40)),103 checkCommand: `bun test ${checkPath}`,104 project: ask.project,105 territory: ask.territory,106 want: ask.brief.want,634 unmodified lines741 Effect.gen(function* () {742 const { base, dir } = yield* aClone(fork);743 const state = yield* tempDir;744 const { platform } = yield* platformFor(base);745+ const asked: string[] = [];746 747 const refusing = Layer.mergeAll(748 platform,749 Layer.succeed(PushCheck)({748- run: () => Effect.succeed([weakened]),750+ run: (_root, from) =>751+ Effect.as(752+ Effect.sync(() => asked.push(from)),753+ [weakened]754+ ),755 })756 );757 758 const stopRun = runHook(19 unmodified lines778 expect(fourth.out).toStrictEqual(["{}"]);779 expect(fourth.code).toBe(0);780 expect(fourth.err.join("\n")).toContain("Weakened");781 expect((yield* stopRun).out).toStrictEqual([held]);782+ // Each check starts from the claim's base, not from main.783+ expect(new Set(asked)).toStrictEqual(new Set([base]));784 }).pipe(Effect.provide(NodeServices.layer))785 );786 787 it.live(323 unmodified lines1111 Effect.service(PushCheck),1112 pushCheckWith(["sh", "-c", `cat '${printed}'; exit ${code}`])1113 );1114 1107- return yield* Effect.result(check.run(dir));1115+ return yield* Effect.result(check.run(dir, "main"));1116 }).pipe(Effect.provide(NodeServices.layer));1117 1118 describe("the default push check: this CLI, run again", () => {1119 it.live("reads the refusals from a refused envelope, though it exits 1", () =>17 unmodified lines1137 expect(result).toStrictEqual(Result.succeed([]));1138 })1139 );1140 1141+ it.live(1142+ "asks the check from the claim's base, as the gateway diffs, so work committed on main is seen",1143+ () =>1144+ Effect.gen(function* () {1145+ const fs = yield* FileSystem.FileSystem;1146+ const path = yield* Path.Path;1147+ const dir = yield* tempDir;1148+ const args = path.join(dir, "args");1149+ const printed = path.join(dir, "envelope.json");1150+1151+ yield* fs.writeFileString(1152+ printed,1153+ encodeEnvelope({ command: "check", data: {}, ok: true, v: 1 })1154+ );1155+1156+ const check = yield* Effect.provide(1157+ Effect.service(PushCheck),1158+ pushCheckWith([1159+ "sh",1160+ "-c",1161+ `printf '%s\\n' "$@" > '${args}'; cat '${printed}'`,1162+ "check",1163+ ])1164+ );1165+1166+ yield* check.run(dir, sha("1"));1167+1168+ expect((yield* fs.readFileString(args)).split("\n")).toStrictEqual([1169+ "check",1170+ "--shape-only",1171+ "--offline",1172+ "--json",1173+ "--base",1174+ sha("1"),1175+ "",1176+ ]);1177+ }).pipe(Effect.provide(NodeServices.layer))1178+ );1179+1180 it.live("fails, for the hook to allow, when no envelope comes back", () =>1181 Effect.gen(function* () {1182 const result = yield* checkPrinting("error: not built", 1);1183 26 unmodified linesmodified:apps/cli/test/pi.test.ts+37 added-1 removed
14 unmodified lines15 import { describe, expect, it } from "@effect/vitest";16 import { Brand } from "@repo/brand";17 import { Client } from "@repo/protocol/contracts";18 import { Glob } from "@repo/protocol/domain/common";19-import { AskId, ProjectName, RepoPath } from "@repo/protocol/ids";19+import { AskId, CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";20 import {21 ChecksFailed,22 OutOfScope,23 RepoBusy,744 unmodified lines768 /** Kept facts for a session on `fix-week` in a clone at `root`. */769 const claimedIn = (root: string): SessionState => ({770 claim: {771 ask: AskId.make("fix-week"),772+ base: CommitSha.make("1".repeat(40)),773 checkCommand: "bun test packages/a",774 project: ProjectName.make("datekit"),775 territory: { module: "a", paths: [Glob.make("packages/a/**")] },776 want,141 unmodified lines918 }919 })920 );921 922+ it.live(923+ "judge an edit as the hook's pre-tool-use does, from the kept facts and without the check",924+ () =>925+ Effect.gen(function* () {926+ const { deps, folder, keep, roots } = yield* policyWith(927+ refusing(outside)928+ );929+930+ yield* keep("s6", claimedIn(folder));931+932+ // pi names a file absolutely, or from the agent's folder.933+ const session = { cwd: `${folder}/packages/a`, id: "s6" };934+935+ const judged = yield* Effect.forEach(936+ [`${folder}/${projectFile}`, "../../README.md", "src/week.ts"],937+ (file) => deps.guardTool(session, GuardedCall.Write({ file }))938+ );939+940+ const unclaimed = yield* deps.guardTool(941+ { cwd: folder, id: "s7" },942+ GuardedCall.Write({ file: projectFile })943+ );944+945+ expect({ judged, roots, unclaimed }).toStrictEqual({946+ judged: [947+ Option.some([new TouchedJudge({ paths: [projectFile] })]),948+ Option.some([outside]),949+ Option.none(),950+ ],951+ roots: [],952+ unclaimed: Option.none(),953+ });954+ })955+ );956+957 it.live("fail as HookFailed when the local check gives no answer", () =>958 Effect.gen(function* () {959 const { deps, folder, keep } = yield* policyWith(960 Effect.fail(new PushCheckFailed({ reason: "it ran past 1m" }))10 unmodified linesadded:apps/cli/build-targets.ts+44 added
1+/**2+ * What `bun build --compile --target=<target>` needs from npm for another3+ * machine. `bun install` installs only this machine's optional native4+ * packages, so a binary for another one (darwin-arm64 from Linux) cannot5+ * embed OpenTUI's native library until the build fetches it (`build.ts`).6+ */7+import { Option } from "effect";8+9+/** A machine as npm's `os` and `cpu` fields name it. */10+export interface NpmMachine {11+ readonly cpu: string;12+ readonly os: string;13+}14+15+/** Bun's operating systems, by npm's name for each. */16+const OS = new Map([17+ ["darwin", "darwin"],18+ ["linux", "linux"],19+ ["windows", "win32"],20+]);21+22+const CPU = new Set(["arm64", "x64"]);23+24+/**25+ * npm's machine for a Bun compile target (`bun-darwin-arm64`, `linux-x64`,26+ * `bun-linux-x64-musl`, `bun-windows-x64-baseline`): its OS and CPU, with27+ * Bun's prefix and modifiers dropped. None for a target Bun does not name.28+ */29+export const npmMachineOf = (target: string): Option.Option<NpmMachine> => {30+ const [os, cpu] = target.replace(/^bun-/u, "").split("-");31+32+ return Option.flatMap(Option.fromUndefinedOr(OS.get(os ?? "")), (npmOs) =>33+ cpu !== undefined && CPU.has(cpu)34+ ? Option.some({ cpu, os: npmOs })35+ : Option.none()36+ );37+};38+39+/**40+ * The packages whose optional dependencies hold the native code the CLI's41+ * binary embeds: OpenTUI's core (`today --tui`) loads its library from42+ * `@opentui/core-<os>-<cpu>`.43+ */44+export const NATIVE = ["@opentui/core"] as const;modified:apps/cli/build.ts+107 added-15 removed
7 unmodified lines8 * 3. `bun build --compile` makes the standalone binary `bin/<cli>` for this9 * machine, or `bin/<target>/<cli>` for each of `--targets`. It embeds the10 * sdk and the rules' entry, each bundled whole, and hands their embedded11 * paths to `src/local/config-runtime.ts` before the CLI starts, so the12- * binary alone can bundle and evaluate a TypeScript config folder.12+ * binary alone can bundle and evaluate a TypeScript config folder. For13+ * each of `--targets`, the target's native packages (`build-targets.ts`)14+ * are fetched from npm into a temp folder the compile resolves through15+ * `NODE_PATH`: `bun install` left out every other machine's.16 * 4. Beside each binary, `git-credential-<slug>` links to it: the binary17 * sees the name it was started by (`src/bin.ts`), so the link is git's18 * credential helper.19 *13 unmodified lines33 import { Command, Flag } from "effect/cli";34 import { ChildProcess, ChildProcessSpawner } from "effect/process";35 import { build } from "tsdown";36 37+import { NATIVE, npmMachineOf } from "./build-targets.ts";38 import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";39 import { declarations, library } from "./tsdown.config.ts";40 41 class BuildFailed extends Data.TaggedError("BuildFailed")<{17 unmodified lines59 readonly files: readonly string[];60 readonly include?: readonly string[];61 }62 63+/** What the build reads of a native package's manifest: its machines' packages. */64+const NativeManifest = Schema.fromJsonString(65+ Schema.Struct({66+ optionalDependencies: Schema.Record(Schema.String, Schema.String),67+ })68+);69+70 /** What the build reads of a workspace package's manifest. */71 const Manifest = Schema.fromJsonString(72 Schema.Struct({73 exports: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),74 name: Schema.String,75 })76 );77 67-/** Runs `command` with this terminal's output; any exit but 0 fails `step`. */68-const run = (step: string, command: string, args: readonly string[]) =>78+/**79+ * Runs `command` with this terminal's output, in `cwd` and with `env` over80+ * this process's own when given; any exit but 0 fails `step`.81+ */82+const run = (83+ step: string,84+ command: string,85+ args: readonly string[],86+ options: {87+ readonly cwd?: string;88+ readonly env?: Readonly<Record<string, string>>;89+ } = {}90+) =>91 Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>92 spawner.exitCode(93 ChildProcess.make(command, args, {94+ cwd: options.cwd,95+ env: { ...options.env },96+ extendEnv: true,97 stderr: "inherit",98 stdin: "ignore",99 stdout: "inherit",100 })169 unmodified lines270 "",271 ].join("\n")272 );273 274+ /**275+ * `node_modules` in a temp folder holding the native packages of276+ * `target`'s machine, as each of `NATIVE` pins them: `bun install`277+ * filtered them to this machine's. The versions are the installed278+ * manifests' own exact pins.279+ */280+ const nativeFor = (target: string) =>281+ Effect.gen(function* () {282+ const machine = yield* Effect.fromOption(npmMachineOf(target)).pipe(283+ Effect.mapError(284+ () =>285+ new BuildFailed({286+ detail: `Bun names no machine ${target}`,287+ step: "native packages",288+ })289+ )290+ );291+292+ const dependencies: Record<string, string> = {};293+294+ for (const name of NATIVE) {295+ const manifest = yield* path.fromFileUrl(296+ new URL(import.meta.resolve(`${name}/package.json`))297+ );298+299+ const { optionalDependencies } = yield* fs300+ .readFileString(manifest)301+ .pipe(Effect.flatMap(Schema.decodeEffect(NativeManifest)));302+303+ Object.assign(dependencies, optionalDependencies);304+ }305+306+ const folder = yield* fs.makeTempDirectoryScoped({307+ prefix: `${Brand.slug}-native-`,308+ });309+310+ yield* fs.writeFileString(311+ path.join(folder, "package.json"),312+ JSON.stringify({ dependencies, name: "native", private: true })313+ );314+315+ yield* run(316+ `native packages for ${target}`,317+ "bun",318+ [319+ "install",320+ "--no-save",321+ `--os=${machine.os}`,322+ `--cpu=${machine.cpu}`,323+ ],324+ { cwd: folder }325+ );326+327+ return path.join(folder, "node_modules");328+ });329+330 // 4. The binaries, each with its credential helper link.331 const outputs =332 targets.length === 0333 ? [{ dir: path.join(dist, "bin"), target: Option.none<string>() }]2 unmodified lines336 target: Option.some(target),337 }));338 339 for (const { dir, target } of outputs) {259- yield* run("bun build --compile", "bun", [260- "build",261- "--compile",262- "--minify",263- ...Option.match(target, {264- onNone: () => [],265- onSome: (name) => [`--target=bun-${name}`],266- }),267- path.join(compile, "main.ts"),268- "--outfile",269- path.join(dir, Brand.cli),270- ]);340+ const env = yield* Option.match(target, {341+ onNone: () => Effect.succeed({}),342+ onSome: (name) =>343+ Effect.map(nativeFor(name), (modules) => ({ NODE_PATH: modules })),344+ });345 346+ yield* run(347+ "bun build --compile",348+ "bun",349+ [350+ "build",351+ "--compile",352+ "--minify",353+ ...Option.match(target, {354+ onNone: () => [],355+ onSome: (name) => [`--target=bun-${name}`],356+ }),357+ path.join(compile, "main.ts"),358+ "--outfile",359+ path.join(dir, Brand.cli),360+ ],361+ { env }362+ );363+364 yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));365 }366 }).pipe(Effect.scoped);367 29 unmodified linesmodified:apps/cli/tsconfig.json+7 added-1 removed
1 unmodified line2 "extends": "../../tsconfig.base.json",3 "compilerOptions": {4 "allowImportingTsExtensions": true5 },6- "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts", "build.ts"]6+ "include": [7+ "src/**/*.ts",8+ "test/**/*.ts",9+ "*.config.ts",10+ "build.ts",11+ "build-targets.ts"12+ ]13 }modified:apps/cli/tsdown.config.ts+2 added-2 removed
16 unmodified lines17 18 const shared = {19 deps: {20 alwaysBundle: [/^@repo\//u],21- // pi's adapter takes it as an optional peer (W7 706): never inlined.21+ // pi's adapter takes it as an optional peer: never inlined.22 neverBundle: [/^@earendil-works\/pi-coding-agent(?:\/|$)/u],23 },24 // `.js` and `.d.ts`: the package is ESM by its `type`.25 fixedExtension: false,24 unmodified lines50 51 export default defineConfig([52 { ...shared, dts: false, entry: { bin: "src/bin.ts" } },53 { ...shared, dts: false, entry: library },54- // The pi extension (W7 706), which the publish manifest's `"pi"` key names.54+ // The pi extension, which the publish manifest's `"pi"` key names.55 { ...shared, dts: false, entry: { pi: "src/pi.ts" } },56 ]);modified:apps/platform/.env.schema+6 added-6 removed
10 unmodified lines11 # contracts as `OPERATOR_HANDLE` (wrangler.jsonc).12 # @required @sensitive @type=string(minLength=32)13 OPERATOR_TOKEN=14 15-# Named sessions beside accounts (spec §8 D9): a JSON object from token to15+# Named sessions beside accounts: a JSON object from token to16 # handle, `{"<token>":"alice"}`, for the demo's fictional people. Each token17 # is at least 32 characters. The operator's token wins if both name one.18 # @optional @sensitive19 SESSION_TOKENS=20 21-# Sign-in (W3 316): the key a sign-in in progress is sealed into its form21+# Sign-in: the key a sign-in in progress is sealed into its form22 # with (HMAC-SHA-256), at least 32 characters. Accounts are the platform's23 # own, so every stage signs people in and needs no third party.24 # @required @sensitive @type=string(minLength=32)25 COOKIE_KEY=26 27-# Sign-in (W3 316): the pepper every password is HMAC'd with before PBKDF2,27+# Sign-in: the pepper every password is HMAC'd with before PBKDF2,28 # at least 32 characters. Without it a copy of the accounts table is29 # useless; changing it makes every stored password fail to verify.30 # @required @sensitive @type=string(minLength=32)31 PASSWORD_PEPPER=32 33-# Google sign-in (W4 419), optional: the id of the platform's Google OAuth33+# Google sign-in, optional: the id of the platform's Google OAuth34 # client, a "Web application" client whose authorised redirect URI is35-# `<platform origin>/oauth/google/callback` (spec §1.5 H4). Set it with35+# `<platform origin>/oauth/google/callback`. Set it with36 # GOOGLE_CLIENT_SECRET or not at all; with neither, sign-in offers only a37 # password. Not secret: Google shows it to everyone who signs in.38 # @optional39 GOOGLE_CLIENT_ID=40 41-# Google sign-in (W4 419), optional: that client's secret, set with its id.41+# Google sign-in, optional: that client's secret, set with its id.42 # @optional @sensitive43 GOOGLE_CLIENT_SECRET=44 45 # Write-only env values (W6): the 256-bit key, as 64 hex characters, that6 unmodified linesmodified:docs/adr/0008-claims-are-exclusive-by-default.md+1 added-1 removed
14 unmodified lines15 The front page shows an ask as either claimed or open.16 17 ## Amended (2026-10-08)18 19-- **Fork names carry their parts.** A claim's fork is `<project>--<ask>--<handle>` and a person's working fork `<project>--me--<handle>`, the handle in lowercase; a layer's repo is `<project>--<layer>`. A project name or an ask id is lowercase words joined by single hyphens, so neither can hold `--`, and a claim fork's or a working fork's name splits back into its parts. A layer's name follows the config folder's looser grammar, which does not refuse `--`. `me` and `layer` are reserved ask ids, as are `open` and `flag`, which the CLI's `ask` subcommands take.19+- **Fork names carry their parts.** A claim's fork is `<project>--<ask>--<handle>` and a person's working fork `<project>--me--<handle>`, the handle in lowercase; a layer's repo is `<project>--<layer>`. A project name, an ask id and a layer's name are each lowercase words joined by single hyphens, so none can hold `--`, and a claim fork's, a working fork's or a layer repo's name splits back into its parts. `me` and `layer` are reserved ask ids, as are `open` and `flag`, which the CLI's `ask` subcommands take.20 - **Making a claim's fork is safe to retry, and converges on one repo.** Ten claims at once against live Artifacts (Oct 7) were all ready within 9.9 s, so no pool of pre-made forks is needed. Under that load 4 of 10 fork calls first answered HTTP 500, then 409 "repo already exists" when retried under the same name, and each still ended as exactly one repo. So a 500 is read as "maybe made" and tried once more, and an already-exists on the claim's own name counts as made once that repo holds `main`. The name comes from the claim, so claiming again finds the same fork.modified:docs/demo/shot-list.md+1 added-1 removed
20 unmodified lines21 | S08 | One weed becomes a rule | terminal | `cd ~/demo`, `git clone https://platform-demo.oscargabriel.workers.dev/burrow.git`, `cd burrow`, `git show HEAD:.myr/project.ts` | The ratchet block on screen: `no-module-level-mutable-state`, counted by `bun run lint --format json`. | `examples/burrow/.myr/project.ts` in the editor, the same file. |22 | S09 | One weed becomes a rule | terminal | From the repo root: `bun run swarm -- --stage demo --project burrow --scenario video --dry-run --allow-demo` | The swarm is built. The plan prints six rows on four harnesses, the held delete child, and both nudges in full. It makes no claim and needs no token. | The same plan from the dev stage (`--stage dev-oscabriel` on a fresh copy of burrow), captioned with its stage. |23 | S10 | One weed becomes a rule | split | Cut from S12, in the pane of the contributor nudged that a disable comment is acceptable: its `git push myr HEAD:main`, refused in git's remote lines | S12 running. The `remote:` lines carry `Weakened` with the marker and its line. Staged by the nudge S09 printed. | That pane's re-prompt, where the run hands the rendered refusal back to the session. If the agent never adds the comment, cut S10 and its line in the narration. |24 | S11 | One weed becomes a rule | web | `https://web-demo.oscargabriel.workers.dev/burrow/answers/<child>`, the child being the ask S09's plan gives the contributor told to give a reason | S12 running; that answer's checks passed. The page reads "Waiting on decision dec-…". Staged by the nudge. | The same outcome in that contributor's pane, from `myr status`. If the agent adds no comment, cut S11 and the line. |25-| S12 | Six harnesses at once | terminal | From the repo root: `bunx varlock run --path apps/platform/ -- bun run swarm -- --stage demo --project burrow --scenario video --view herdr --allow-demo` | Pre-flight done: herdr session `demo` open, six harnesses logged in, the six people's tokens in the stage's `SESSION_TOKENS`, burrow's family untouched. The recording lock on. | Six tiled terminals, each running the same command with `--view headless --only <handle>`. Last resort: the recorded dev-stage take, with its `.swarm/<run>/agents.json` summary as a caption. |25+| S12 | Six harnesses at once | terminal | From the repo root: `bunx varlock run --path apps/platform/ -- bun run swarm -- --stage demo --project burrow --scenario video --view herdr --allow-demo` | Pre-flight done: herdr session `demo` open, six harnesses logged in, the six people's tokens in the stage's `SESSION_TOKENS`, burrow's family untouched. The recording lock on. | Six tiled terminals, each running the same command with `--view headless --only <handle>`. Last resort: the recorded dev-stage take, with its run's `agents.json` summary as a caption. |26 | S13 | Six harnesses at once | web | `https://web-demo.oscargabriel.workers.dev/burrow` | Open during S12; the asks update live as children are claimed and land. | Reload between cuts. |27 | S14 | Six harnesses at once | web | `https://web-demo.oscargabriel.workers.dev/burrow/asks/drop-legacy-fetch-delete` | The sixth child landed: the delete child is open. | `myr asks --project burrow` lists it open. If a child timed out, say "five of six" and keep the delete child waiting on screen. |28 | S15 | The top half is open | split | Left: `export MYR_PROFILE=bram`, `git clone --branch main https://platform-demo.oscargabriel.workers.dev/datekit--maintainers.git`. Right: `export MYR_PROFILE=ines-v`, the same clone, then `git -C datekit--maintainers ls-files` | Left and right in separate empty folders. bram's clone fails with `remote: bram may not read datekit--maintainers` and HTTP 403; ines-v's holds `checks/held-back/export/` (7 files) and `parser/` (4). `--branch main` because the layer's HEAD follows the first branch the seed pushed. | The dev stage's recorded clones, captioned with their stage. |29 | S16 | The top half is open | terminal | `cd ~/demo`, `git clone https://platform-demo.oscargabriel.workers.dev/datekit.git datekit-read`, `cd datekit-read`, `git show HEAD:.myr/visibility.ts` | Anonymous: no profile needed. S20 reuses this clone. | `examples/datekit/.myr/visibility.ts` in the editor. |22 unmodified linesmodified:docs/demo/swarm-scenario.md+20 added-12 removed
8 unmodified lines9 Six of the people burrow's `.myr/vouched.td` vouches for, each with one harness and one model: "4 harnesses, 6 models". Each is a fictional person with a token of their own in the stage's `SESSION_TOKENS`; their agent acts only through it. No agent holds an account or credit: the claim is the person's, and a landing credits the person, with the agent disclosed apart as `Assisted-by`.10 11 | # | Contributor | Harness | Model | Adapter | Child (when all six are open) |12 | --- | --- | --- | --- | --- | --- |13-| 1 | wren | Claude Code, as it ships | an Anthropic model | none | `drop-legacy-fetch-burrow-auth` |14-| 2 | tamsin | OpenCode | a GPT model (`openai/…`) | none | `drop-legacy-fetch-burrow-billing` |15-| 3 | ivo | Amp | one of its modes | none | `drop-legacy-fetch-burrow-catalog` |16-| 4 | marisol | pi | `kimi-k3` | none | `drop-legacy-fetch-burrow-kit` |17-| 5 | dagny | pi | `glm-5.3` | none | `drop-legacy-fetch-burrow-notify` |18-| 6 | pell | pi | a Gemini flash model | the pi adapter (`-e`): the brief, the scope guard and a verdict gate | `drop-legacy-fetch-burrow-search` |13+| 1 | wren | Claude Code, as it ships | `claude-opus-5-5` | none | `drop-legacy-fetch-burrow-auth` |14+| 2 | tamsin | OpenCode | `openai/gpt-5.5` | none | `drop-legacy-fetch-burrow-billing` |15+| 3 | ivo | Amp | `medium` (one of its modes) | none | `drop-legacy-fetch-burrow-catalog` |16+| 4 | marisol | pi | `opencode-go/kimi-k3` | none | `drop-legacy-fetch-burrow-kit` |17+| 5 | dagny | pi | `opencode-go/glm-5.3` | none | `drop-legacy-fetch-burrow-notify` |18+| 6 | pell | pi | `opencode/gemini-3.8-flash` | the pi adapter (`-e`): the brief, the scope guard and a verdict gate | `drop-legacy-fetch-burrow-search` |19 20-The exact handle on each row, and each model's exact id, are the ones `scripts/lib/swarm/roster.ts` holds; the plan prints them (S09), and that printout is what the video shows. The table above is the intended shape.20+Each handle and model id is the one `scripts/lib/swarm/roster.ts` holds, word for word; the plan prints them (S09), and that printout is what the video shows. pell's Gemini flash is OpenCode Zen's, which pi reaches only once the OpenCode Zen key is in pi on the machine that runs the take; without it, pell's run is recorded as failed with that reason, and `opencode-go/qwen3.8-flash` (which runs headless with the adapter) is the one-line swap in the roster.21 22 Every agent gets the same zero-install brief: the ask as its page says it, the fork's remote, and the loop the project's AGENTS.md gives (claim, work inside the territory, `myr check`, push, read the verdict). Nothing about the gate's internals.23 24 ## The plan for the burrow family2 unmodified lines27 28 - six children, `drop-legacy-fetch-burrow-{auth,billing,catalog,kit,notify,search}`, each with the territory of one package (`packages/<name>/**`), so their territories are disjoint;29 - `drop-legacy-fetch-delete`, blocked by all six: it opens when the last caller is gone.30 31-The plan takes the open, unclaimed, unblocked children in ask order and gives them to the roster in its order, one each; the delete child is held, not assigned. Each contributor claims their child as themselves, gets a fork, and their harness starts headless in a workspace of its own (`.swarm/<run>/<handle>/`), with git's editor and prompts turned off.31+The plan takes the open, unclaimed, unblocked children in ask order and gives them to the roster in its order, one each; the delete child is held, not assigned. Each contributor claims their child as themselves, gets a fork, and their harness starts headless in a workspace of its own (`<run>/<handle>/` in the swarm's folder, `$XDG_STATE_HOME/<slug>/swarm/` or `~/.local/state/<slug>/swarm/`, outside every checkout, so no agent reads this repo's own AGENTS.md), with git's editor and prompts turned off.32 33 Beside the migrate, burrow's own lint rule, `no-module-level-mutable-state`, is a ratchet: six module-level bindings, one in each package's `src/`, a count that may only fall. Each child's package holds one of them, which is why the nudges below are about this rule.34 35 ## The video scenario's nudges (staged)36 37-`--scenario video` adds a nudge to two briefs; `--scenario plain` adds none. They live in `scripts/lib/swarm/scenario.ts` (`nudges("video", …)`), and the plan prints each one in full beside its contributor. In substance:37+`--scenario video` adds a nudge to two briefs; `--scenario plain` adds none. They live in `scripts/lib/swarm/scenario.ts` (`nudges("video", …)`), and the plan prints each one in full beside its contributor. Word for word:38 39-- **Staged, the second contributor:** the lint rule is noisy, and a disable comment is acceptable. The likely result: the agent adds `oxlint-disable` with no reason after ` -- `, and its push is refused as `Weakened{marker}`, at the line.40-- **Staged, the third contributor:** a disable comment must carry its reason after ` -- `. The likely result: the agent adds one with a reason, which the gate does not refuse but counts against the package's escapes. With burrow's escapes at zero, the answer waits for a decider as `AwaitingDecision` (a waiver), which shows on okafor's Today in beat 6.39+- **Staged, the second contributor (tamsin):**40 41+ > The project's lint rule against module-level mutable state is noisy. If it gets in your way, a lint disable comment on the line is acceptable.42+43+ The likely result: the agent adds `oxlint-disable` with no reason after ` -- `, and its push is refused as `Weakened{marker}`, at the line.44+- **Staged, the third contributor (ivo):**45+46+ > If you need a lint disable comment, it must carry its reason after ` -- ` on the same line, for example `// oxlint-disable-next-line <rule> -- <why>`.47+48+ The likely result: the agent adds one with a reason, which the gate does not refuse but counts against the package's escapes. With burrow's escapes at zero, the answer waits for a decider as `AwaitingDecision` (a waiver), which shows on okafor's Today in beat 6.49+50 Neither result is guaranteed: an agent may fix the module's state properly and add no comment at all. Then that moment is cut, and so is its line in the narration.51 52 ## Refusals expected, and why53 28 unmodified lines82 ```sh83 bunx varlock run --path apps/platform/ -- bun run swarm -- --stage dev-oscabriel --project burrow-swarm-2 --scenario video --view herdr84 ```85 78-The run writes its summary to `.swarm/<run>/agents.json`: per contributor, the attempts, the refusals by tag, the outcome and the time taken.86+The run writes its summary to `<run>/agents.json` in the swarm's folder (the run prints its path last): per contributor, the attempts, the refusals by tag, the outcome and the time taken.87 88 ## When an agent stalls89 90 - **The per-run timeout ends it.** Each run has a timeout (`--timeout-min`, 20 minutes unless set); a run past it is recorded as `timedOut` and the other five carry on.3 unmodified linesmodified:infra/smoke.ts+5 added-18 removed
31 unmodified lines32 import {33 Console,34 Duration,35 Effect,36- FileSystem,36 Option,38- Path,37 Result,38 Schedule,39 Schema,40 } from "effect";1 unmodified line42 43 import {44 flagValue,45 platformOrigin,48- repoRoot,46+ recordedSubdomain,47 stageOf,48 subdomainFile,49 webOrigin,52- WorkersDev,50 } from "./stages.ts";51 import type { Stage } from "./stages.ts";52 53 /** The platform's probes, in the order smoke runs them. */424 unmodified lines478 stage: first.outcome.success,479 };480 });481 485-const decodeWorkersDev = Schema.decodeUnknownEffect(486- Schema.fromJsonString(WorkersDev)487-);488-482 /** Neither `--url` nor bootstrap's record says where the stage lives. */483 export class NoOrigin extends Schema.TaggedError<NoOrigin>()("NoOrigin", {484 file: Schema.String,485 stage: Schema.String,24 unmodified lines510 if (Option.isSome(given)) {511 return { platform: trimmed(given.value), web } satisfies Origins;512 }513 521- const fs = yield* FileSystem.FileSystem;522- const path = yield* Path.Path;523- const unknown = new NoOrigin({ file: subdomainFile, stage });514+ const subdomain = yield* recordedSubdomain.pipe(515+ Effect.flatMap(Effect.fromOption),516+ Effect.mapError(() => new NoOrigin({ file: subdomainFile, stage }))517+ );518 525- const { subdomain } = yield* fs526- .readFileString(path.join(yield* repoRoot, subdomainFile))527- .pipe(528- Effect.flatMap(decodeWorkersDev),529- Effect.mapError(() => unknown)530- );531-519 return {520 platform: platformOrigin(stage, subdomain),521 web: Option.orElse(web, () => Option.some(webOrigin(stage, subdomain))),522 } satisfies Origins;42 unmodified linesmodified:infra/stages.ts+20 added-1 removed
7 unmodified lines8 * `bootstrap.ts`, `deploy.ts` and `scripts/smoke.ts` read stages and names9 * only from here, and `packages/config/test/bootstrap.test.ts` holds every10 * `env` block of the platform's and the sandbox's `wrangler.jsonc` to it.11 */12-import { Effect, Option, Path, Schema } from "effect";12+import { Effect, FileSystem, Option, Path, Schema } from "effect";13 14 /** A stage's shape: `dev-` and a lowercase user, or `demo`. */15 export const Stage = Schema.Union([16 Schema.TemplateLiteral([132 unmodified lines149 150 /** `subdomainFile`'s contents. */151 export const WorkersDev = Schema.Struct({ subdomain: Schema.NonEmptyString });152 153+/**154+ * The account's workers.dev subdomain, as bootstrap recorded it in155+ * `subdomainFile`; none before bootstrap's first run, or when the file does156+ * not decode. Seed, smoke and the swarm each read it when no `--url` is157+ * given, and say in their own words what to run.158+ */159+export const recordedSubdomain = Effect.gen(function* () {160+ const fs = yield* FileSystem.FileSystem;161+ const path = yield* Path.Path;162+163+ return yield* fs164+ .readFileString(path.join(yield* repoRoot, subdomainFile))165+ .pipe(166+ Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(WorkersDev))),167+ Effect.map(({ subdomain }) => subdomain),168+ Effect.option169+ );170+});171+172 /** The platform's public origin at `stage`, on the account's workers.dev. */173 export const platformOrigin = (stage: Stage, subdomain: string) =>174 `https://${resources(stage).platform}.${subdomain}.workers.dev`;175 3 unmodified linesmodified:packages/config/test/cartridge.test.ts+3 added-48 removed
14 unmodified lines15 * re-exports and `import()`.16 */17 import { NodeServices } from "@effect/platform-node";18 import { describe, expect, it } from "@effect/vitest";19-import {20- Array,21- Effect,22- FileSystem,23- Option,24- Path,25- Schema,26- Stream,27-} from "effect";28-import { ChildProcess, ChildProcessSpawner } from "effect/process";19+import { Array, Effect, FileSystem, Option, Path, Schema } from "effect";20+import type { ChildProcessSpawner } from "effect/process";21 30-import { repoRoot } from "./root.ts";22+import { committable, repoRoot, textOf } from "./root.ts";23 24 /** The cartridge's folders, from the repo root; each ends with `/`, and each exists. */25 const MANIFEST = [26 "packages/visibility/",97 unmodified lines124 const isSource = (file: string) => /\.tsx?$/u.test(file);125 126 // ------------------------------------------------------------ the repo127 136-/** Every file git tracks or would track (ignored files left out), from the repo root. */137-const committable = Effect.gen(function* () {138- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;139- const cwd = yield* repoRoot;140-141- const handle = yield* spawner.spawn(142- ChildProcess.make(143- "git",144- ["ls-files", "--cached", "--others", "--exclude-standard"],145- { cwd }146- )147- );148-149- const [listed, code] = yield* Effect.all(150- [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],151- { concurrency: "unbounded" }152- );153-154- if (code !== 0) {155- return yield* Effect.die(`git ls-files exited with ${code}`);156- }157-158- return listed.split("\n").filter((line) => line.length > 0);159-}).pipe(Effect.scoped);160-161-/** A file under the repo root, as text; one deleted but not yet staged reads as none. */162-const textOf = (file: string) =>163- Effect.gen(function* () {164- const fs = yield* FileSystem.FileSystem;165- const path = yield* Path.Path;166- const at = path.join(yield* repoRoot, file);167-168- return (yield* fs.exists(at))169- ? Option.some(yield* fs.readFileString(at))170- : Option.none<string>();171- });172-128 /** Every committable file with its text, `filter` deciding which. */129 const filesWhere = (filter: (file: string) => boolean) =>130 Effect.flatMap(committable, (files) =>131 Effect.forEach(files.filter(filter), (file) =>615 unmodified linesmodified:packages/config/test/demo-docs.test.ts+34 added-1 removed
15 unmodified lines16 * failed assertion, not a load error.17 */18 import { NodeServices } from "@effect/platform-node";19 import { describe, expect, it } from "@effect/vitest";20-import { Effect, FileSystem, Path, Schema } from "effect";20+import { Effect, FileSystem, Option, Path, Schema } from "effect";21 22 import { blankJsonc } from "../../../infra/jsonc.ts";23 import {24 platformOrigin,25 subdomainFile,26 webOrigin,27 WorkersDev,28 } from "../../../infra/stages.ts";29+import { roster } from "../../../scripts/lib/swarm/roster.ts";30+import { nudges } from "../../../scripts/lib/swarm/scenario.ts";31 import { commandDocs } from "../../agent-kit/src/command-doc.ts";32 import type { CommandDoc } from "../../agent-kit/src/command-doc.ts";33 import { Brand } from "../../brand/src/index.ts";34 import { Contracts } from "../../protocol/src/contracts.ts";558 unmodified lines593 })594 )595 );596 597+ it.live(598+ "names each contributor's exact model, and quotes the video's nudges word for word",599+ () =>600+ live(601+ Effect.gen(function* () {602+ const scenario = yield* presentText(`${DEMO}/swarm-scenario.md`);603+604+ const rows = scenario605+ .split("\n")606+ .filter((line) => /^\| \d \|/u.test(line))607+ .map((line) => line.split("|").map((cell) => cell.trim()));608+609+ expect(610+ rows.map((cells) => [611+ cells[2],612+ /`(?<id>[^`]+)`/u.exec(cells[4] ?? "")?.groups?.id,613+ ])614+ ).toStrictEqual(roster.map(({ handle, model }) => [handle, model]));615+616+ const told = roster.flatMap((_, index) =>617+ Option.toArray(nudges("video", index))618+ );619+620+ expect(told, "the video scenario nudges two").toHaveLength(2);621+ expect(622+ told.filter((nudge) => !scenario.includes(`> ${nudge}`))623+ ).toStrictEqual([]);624+ })625+ )626+ );627+628 it.live("rehearses every shot once, by its id", () =>629 live(630 Effect.gen(function* () {631 const shots = shotsOf(yield* presentText(`${DEMO}/shot-list.md`))11 unmodified linesmodified:packages/config/test/readme.test.ts+7 added-47 removed
15 unmodified lines16 * a path may name.17 */18 import { NodeServices } from "@effect/platform-node";19 import { describe, expect, it } from "@effect/vitest";20-import {21- Array,22- Effect,23- FileSystem,24- Option,25- Path,26- Schema,27- Stream,28-} from "effect";29-import { ChildProcess, ChildProcessSpawner } from "effect/process";20+import { Array, Effect, FileSystem, Option, Path, Schema } from "effect";21 31-import { repoRoot } from "./root.ts";22+import { committable, repoRoot, textOf } from "./root.ts";23 24 /** The H2 sections after the pitch, in order; the pitch's title is free. */25 const SECTIONS = [26 "Run it",69 unmodified lines96 const FILE_PATH = /^\.?[\w-][\w.-]*(?:\/[\w.[\]$<>{},*-]+)+\.\w+$/u;97 98 // ------------------------------------------------------------ the repo99 109-/** A file under the repo root, as text, if it exists. */110-const textOf = (file: string) =>111- Effect.gen(function* () {112- const fs = yield* FileSystem.FileSystem;113- const path = yield* Path.Path;114- const at = path.join(yield* repoRoot, file);115-116- return (yield* fs.exists(at))117- ? Option.some(yield* fs.readFileString(at))118- : Option.none<string>();119- });120-100 /** The README, or nothing yet: a missing README fails by assertion, not by a read error. */101 const readme = Effect.map(102 textOf("README.md"),103 Option.getOrElse(() => "")14 unmodified lines118 : (yield* Schema.decodeEffect(Manifest)(text.value)).scripts;119 });120 121 /** Every file git tracks or would track and that is on disk, from the repo root. */143-const committable = Effect.gen(function* () {144- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;122+const onDisk = Effect.gen(function* () {123 const fs = yield* FileSystem.FileSystem;124 const path = yield* Path.Path;125 const cwd = yield* repoRoot;126 149- const handle = yield* spawner.spawn(150- ChildProcess.make(151- "git",152- ["ls-files", "--cached", "--others", "--exclude-standard"],153- { cwd }154- )127+ return yield* Effect.filter(yield* committable, (file) =>128+ fs.exists(path.join(cwd, file))129 );130+});131 157- const [listed, code] = yield* Effect.all(158- [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],159- { concurrency: "unbounded" }160- );161-162- if (code !== 0) {163- return yield* Effect.die(`git ls-files exited with ${code}`);164- }165-166- return yield* Effect.filter(167- listed.split("\n").filter((line) => line.length > 0),168- (file) => fs.exists(path.join(cwd, file))169- );170-}).pipe(Effect.scoped);171-132 /** The upstream repositories every committable file's header names, sorted. */133 const portedUpstreams = (files: readonly string[]) =>134 Effect.gen(function* () {135 const fs = yield* FileSystem.FileSystem;195 unmodified lines331 // ------------------------------------------------------------ the tests332 333 /** The README with what it is read against: the files a path may name and their top-level entries. */334 const world = Effect.gen(function* () {375- const files = yield* committable;335+ const files = yield* onDisk;336 337 return {338 files,339 roots: new Set(files.map((file) => file.split("/")[0] ?? "")),149 unmodified linesmodified:packages/config/test/root.ts+43 added-1 removed
1-import { Effect, Path } from "effect";1+import { Effect, FileSystem, Option, Path, Stream } from "effect";2+import { ChildProcess, ChildProcessSpawner } from "effect/process";3 4 /** The repo root. Vitest runs in the package's folder, two below it. */5 export const repoRoot = Effect.map(Path.Path, (path) =>6 path.resolve("..", "..")7 );8+9+/**10+ * Every file git tracks or would track (ignored files left out), from the11+ * repo root. A tracked file deleted but not yet staged is still listed:12+ * `textOf` reads it as none.13+ */14+export const committable = Effect.gen(function* () {15+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;16+ const cwd = yield* repoRoot;17+18+ const handle = yield* spawner.spawn(19+ ChildProcess.make(20+ "git",21+ ["ls-files", "--cached", "--others", "--exclude-standard"],22+ { cwd }23+ )24+ );25+26+ const [listed, code] = yield* Effect.all(27+ [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],28+ { concurrency: "unbounded" }29+ );30+31+ if (code !== 0) {32+ return yield* Effect.die(`git ls-files exited with ${code}`);33+ }34+35+ return listed.split("\n").filter((line) => line.length > 0);36+}).pipe(Effect.scoped);37+38+/** A file under the repo root, as text, if it is on disk. */39+export const textOf = (file: string) =>40+ Effect.gen(function* () {41+ const fs = yield* FileSystem.FileSystem;42+ const path = yield* Path.Path;43+ const at = path.join(yield* repoRoot, file);44+45+ return (yield* fs.exists(at))46+ ? Option.some(yield* fs.readFileString(at))47+ : Option.none<string>();48+ });modified:packages/config/test/swarm-herdr.test.ts+1 added-1 removed
177 unmodified lines178 },179 {180 argv: ["--standalone", "--auto"],181 // OpenCode's interface takes no model flag: its inline config does.182- env: { OPENCODE_CONFIG_CONTENT: '{"model":"openai/gpt-6.1-sol"}' },182+ env: { OPENCODE_CONFIG_CONTENT: '{"model":"openai/gpt-5.5"}' },183 kind: "opencode",184 },185 {186 argv: [1102 unmodified linesmodified:packages/config/test/swarm-loop.test.ts+39 added-4 removed
28 unmodified lines29 ChecksFailed,30 ClaimLapsed,31 OutOfScope,32 StaleBase,33+ VerifierBlocked,34 } from "@repo/protocol/refusal";35 import type { Refusal } from "@repo/protocol/refusal";36 import { explain } from "@repo/protocol/render";37 import {560 unmodified lines598 })599 );600 601 it.effect(601- "takes an old answer status still shows after a continuation as no new answer",602+ "takes an old answer status still shows after a continuation as no new answer, and nudges with the head it last saw",603 () =>604 Effect.gen(function* () {605 const start = yield* recorded("claude-code", "start");606 const resume = yield* recorded("claude-code", "resume");607 const first = answer(1, refused(checksFailed));608 608- const { result } = yield* agentRun({609+ const { harnessRuns, result } = yield* agentRun({610 harness: [{ lines: start }, { lines: resume }, { lines: resume }],611 statuses: [status(first)],612 });613 1 unmodified line615 result.outcome,616 result.attempts,617 result.refusals,618 ]).toStrictEqual(["refused", 3, { ChecksFailed: 1 }]);619+620+ // An answer did arrive: the nudge must not say none ever did.621+ const nudge = promptOf(harnessRuns[2]);622+623+ expect(nudge).toContain(`since ${first.head.slice(0, 7)}`);624+ expect(nudge).not.toContain("yet");625 })626 );627 628 it.effect(629+ "sends a refusal on the platform's side back as a wait, not as something to fix",630+ () =>631+ Effect.gen(function* () {632+ const start = yield* recorded("claude-code", "start");633+ const resume = yield* recorded("claude-code", "resume");634+ const blocked = answer(1, refused(new VerifierBlocked({})));635+ const landed = answer(2, Outcome.cases.Landed.make({ sha: landing }));636+637+ const { harnessRuns, result } = yield* agentRun({638+ harness: [{ lines: start }, { lines: resume }],639+ statuses: [status(blocked), status(blocked, landed)],640+ });641+642+ expect([643+ result.outcome,644+ result.attempts,645+ result.refusals,646+ ]).toStrictEqual(["landed", 2, { VerifierBlocked: 1 }]);647+648+ const prompt = promptOf(harnessRuns[1]);649+650+ expect(prompt).toContain("not a fault in your change");651+ expect(prompt).toContain("git commit --allow-empty");652+ expect(prompt).not.toContain("Fix what the refusal names");653+ })654+ );655+656+ it.effect(657 "counts the refusals of every answer one session pushed, not only its last",658 () =>659 Effect.gen(function* () {660 const start = yield* recorded("claude-code", "start");256 unmodified lines917 "--format",918 "json",919 "--auto",920 "-m",886- "openai/gpt-6.1-sol",921+ "openai/gpt-5.5",922 "-s",923 "S-1",924 "Fix it.",925 ],4 unmodified lines930 "--format",931 "json",932 "--auto",933 "-m",899- "openai/gpt-6.1-sol",934+ "openai/gpt-5.5",935 "Answer it.",936 ],937 },938 {192 unmodified linesmodified:packages/config/test/swarm.test.ts+24 added-1 removed
38 unmodified lines39 import { brief } from "../../../scripts/lib/swarm/prompt.ts";40 import {41 AgentsResult,42 SwarmDir,43+ swarmDirOf,44 writeAgentsResult,45 } from "../../../scripts/lib/swarm/results.ts";46 import { roster } from "../../../scripts/lib/swarm/roster.ts";47 import type { Contributor } from "../../../scripts/lib/swarm/roster.ts";691 unmodified lines739 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))740 );741 });742 743+describe("the swarm's folder", () => {744+ it("lives in the state home, as the hook's sessions do", () => {745+ expect(746+ swarmDirOf({ HOME: "/home/ada", XDG_STATE_HOME: "/var/state/ada" })747+ ).toBe(`/var/state/ada/${Brand.slug}/swarm`);748+ expect(swarmDirOf({ HOME: "/home/ada" })).toBe(749+ `/home/ada/.local/state/${Brand.slug}/swarm`750+ );751+ });752+753+ // A harness reads every AGENTS.md and CLAUDE.md above its folder: inside754+ // this checkout, each contributor would read the platform's own.755+ it.effect("is never inside this checkout", () =>756+ Effect.gen(function* () {757+ const root = yield* repoRoot;758+ const dir = yield* SwarmDir;759+760+ expect(dir.startsWith(`${root}/`)).toBeFalsy();761+ }).pipe(Effect.provide(NodeServices.layer))762+ );763+});764+765 /** Why the flags `argv` make no run, or `accepted` when they make one. */766 const reasonOf = (argv: readonly string[]) =>767 optionsOf(argv).pipe(768 Effect.match({201 unmodified lines970 ],971 [972 "tamsin",973 "opencode",951- "openai/gpt-6.1-sol",974+ "openai/gpt-5.5",975 children[1],976 "@burrow/billing",977 ],978 ["ivo", "amp", "medium", children[2], "@burrow/catalog"],407 unmodified linesmodified:packages/protocol/src/ids.ts+6 added-2 removed
144 unmodified lines145 );146 147 export type KindName = typeof KindName.Type;148 149-/** A layer's name, as the config folder declares it: `maintainers`. */149+/**150+ * A layer's name, as the config folder declares it: `maintainers`. In an151+ * ask's words (lowercase, single hyphens): its repo is `<project>--<layer>`,152+ * and a `--` in the name would read as a claim fork's.153+ */154 export const LayerName = Schema.String.pipe(151- Schema.check(Schema.isPattern(ConfigName)),155+ Schema.check(Schema.isPattern(Words)),156 Schema.brand("LayerName")157 );158 159 export type LayerName = typeof LayerName.Type;132 unmodified linesmodified:packages/protocol/test/domain.test.ts+15 added
318 unmodified lines319 ] as const)("%s takes %j and refuses %j", (_name, good, bad, schema) => {320 expect(refuses(schema, good)).toBeFalsy();321 expect(refuses(schema, bad)).toBeTruthy();322 });323+324+ // A layer's repo is `<project>--<layer>`; a layer named `a--b` would make325+ // `<project>--a--b`, which reads as a claim fork (`<project>--<ask>--<handle>`).326+ it("names a layer in an ask's words, so its repo never reads as a claim fork", () => {327+ expect(328+ ["security-review", "maintainers2"].map((name) =>329+ refuses(LayerName, name)330+ )331+ ).toStrictEqual([false, false]);332+ expect(333+ ["a--b", "triageTeam", "fix-", "x".repeat(0)].map((name) =>334+ refuses(LayerName, name)335+ )336+ ).toStrictEqual([true, true, true, true]);337+ });338 });339 340 describe("the caller", () => {341 it("is a person named by their handle, or anyone at all", () => {10 unmodified linesmodified:scripts/lib/release/steps.ts+2 added-2 removed
19 unmodified lines20 * The package is staged beside the binaries rather than in `dist/`: its21 * manifest names `./dist/…` and `./skills` from the package's root, and22 * `dist/bin/` holds the binaries, which npm must not ship.23 */24+import { commandDocs } from "@repo/agent-kit/command-doc";25+import { platformSkill } from "@repo/agent-kit/platform";26 import { Brand } from "@repo/brand";27 import { Contracts } from "@repo/protocol/contracts";28 import {29 Array as Arr,11 unmodified lines41 import { ChildProcess, ChildProcessSpawner } from "effect/process";42 43 import { resources } from "../../../infra/stages.ts";44 import type { Stage } from "../../../infra/stages.ts";43-import { commandDocs } from "../../../packages/agent-kit/src/command-doc.ts";44-import { platformSkill } from "../../../packages/agent-kit/src/platform.ts";45 import {46 binaryName,47 checksumsFile,48 importedPackages,582 unmodified linesmodified:scripts/lib/swarm/views/herdr.ts+4 added-3 removed
340 unmodified lines341 * pi 1.1.0 asked none):342 *343 * - Claude Code asks whether to trust the folder, "No, exit" first: the344 * clone is the swarm's own, so it answers yes;345- * - then whether to import the CLAUDE.md files above the clone (this346- * repo's own, when `.swarm/` sits in the checkout), "No" first: it keeps347- * the default, since they are not the contributor's project.345+ * - then whether to import the CLAUDE.md files above the clone (a346+ * checkout's, when a test or a person puts the swarm's folder in one),347+ * "No" first: it keeps the default, since they are not the contributor's348+ * project.349 *350 * Any other question is left for the person at the panes.351 */352 const STARTUP_QUESTIONS = {493 unmodified linesmodified:scripts/lib/swarm/loop.ts+52 added-11 removed
11 unmodified lines12 * - `AwaitingFinish`, `AwaitingDecision`, `WaitingOnParent`: waiting on a13 * person or another ask, recorded as `waiting` (the swarm decides nothing);14 * - `Refused`: the refusals, rendered by protocol's `explain`, go back into15 * the same session with the first one's `next`, unless one of them ends16- * the claim (`endsClaim`) or the continuations ran out;17- * - no new answer: one nudge to push, then `noAnswer` (or `refused`, when an18- * earlier answer was refused and nothing new came).16+ * the claim (`endsClaim`) or the continuations ran out; refusals that are17+ * all the platform's side (`VerifierBlocked`, `Flake`, `RepoBusy`) go back18+ * as a wait: push the same work again, with nothing to fix;19+ * - no new answer: one nudge to push (naming the last answer's head, when20+ * one came), then `noAnswer` (or `refused`, when an earlier answer was21+ * refused and nothing new came).22 *23 * The run's timeout bounds everything: a harness that never settles, or an24 * answer checked past it, ends the run as `timedOut`, and the harness's25 * process group is killed.189 unmodified lines215 };216 217 const short = (sha: string) => sha.slice(0, 7);218 216-/** The prompt that resumes a session after its answer was refused. */219+/**220+ * The refusals that are the platform's side, not the answer's: the checks221+ * could not run, a lane flaked, the repo was busy. Each is retryable (the222+ * same work may pass), and none names anything in the change to fix.223+ */224+const platformSide: ReadonlySet<Refusal["_tag"]> = new Set([225+ "Flake",226+ "RepoBusy",227+ "VerifierBlocked",228+] as const satisfies readonly Refusal["_tag"][]);229+230+/**231+ * The prompt that resumes a session after its answer was refused. When232+ * every refusal is the platform's side, it says so, and asks for the same233+ * work again rather than a fix: an empty commit, pushed.234+ */235 export const refusalPrompt = (input: {236 readonly answer: Pick<AnswerView, "ask" | "head">;237 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;238 readonly project: string;221-}) =>222- [239+}) => {240+ const status = `\`${Brand.cli} status --project ${input.project}\``;241+242+ const what = input.refusals.every(({ _tag }) => platformSide.has(_tag))243+ ? [244+ 'This is not a fault in your change: the platform could not finish checking it. Change nothing; push the same work again with an empty commit (`git commit --allow-empty -m "Check again"`, then `git push`).',245+ `Then run ${status} for the new verdict.`,246+ ]247+ : [248+ `Next: ${Array.headNonEmpty(input.refusals).next}`,249+ "",250+ `Fix what the refusal names, commit, and push again; then run ${status} for the new verdict.`,251+ ];252+253+ return [254 `Your answer to ${input.answer.ask} at ${short(input.answer.head)} was refused:`,255 "",256 ...explain(input.refusals),257 "",227- `Next: ${Array.headNonEmpty(input.refusals).next}`,228- "",229- `Fix what the refusal names, commit, and push again; then run \`${Brand.cli} status --project ${input.project}\` for the new verdict.`,258+ ...what,259 ].join("\n");260+};261 232-/** The prompt that resumes a session that pushed no answer. */262+/**263+ * The prompt that resumes a session that pushed no new answer: none at all,264+ * or none since the head of the last one status showed (`since`).265+ */266 export const nudgePrompt = (input: {267 readonly ask: string;268 readonly remote: string;269 readonly project: string;270+ readonly since: Option.Option<string>;271 }) =>272 [273+ Option.match(input.since, {274+ onNone: () =>239- `No answer of yours to ${input.ask} has reached the platform yet.`,275+ `No answer of yours to ${input.ask} has reached the platform yet.`,276+ onSome: (head) =>277+ `No new answer of yours to ${input.ask} has reached the platform since ${short(head)}.`,278+ }),279 `Commit your change and push it to ${input.remote} with \`git push\`. If git printed refusals in its \`remote:\` lines, fix what they name first, then push again.`,280 `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,281 ].join("\n");282 53 unmodified lines336 remote: Option.match(input.status.claim, {337 onNone: () => "origin",338 onSome: ({ remote }) => remote,339 }),340+ // Status's latest answer here is one already judged, if any.341+ since: Option.map(input.status.answer, ({ head }) => head),342 }),343 }),344 progress: {345 ...progress,221 unmodified linesmodified:scripts/lib/swarm/results.ts+45 added-10 removed
1 /**2 * The swarm run's summary: one `AgentRun` per contributor, written to3- * `.swarm/<run>/agents.json` (gitignored). A live issue records what a run4- * shows in its own notes; nothing here is committed.3+ * `<swarm>/<run>/agents.json`, where `<swarm>` is `SwarmDir`, outside the4+ * checkout. A live issue records what a run shows in its own notes; nothing5+ * here is committed.6 *7 * Every field follows the wire rule (AGENTS.md "Effect traps"): `Schema.Int`8 * or `Schema.Finite` for numbers, `Schema.optionalKey` for optional keys.9 */10+import { Brand } from "@repo/brand";9-import { Context, Effect, FileSystem, Schema } from "effect";11+import { Context, Effect, FileSystem, Option, Schema } from "effect";12 import type { PlatformError } from "effect";13 14+/** What the swarm's folder is placed by: the env's state home, else the user's home. */15+const StateEnv = Schema.Struct({16+ HOME: Schema.optionalKey(Schema.NonEmptyString),17+ XDG_STATE_HOME: Schema.optionalKey(Schema.NonEmptyString),18+});19+20 /**13- * The swarm's folder, `.swarm/` at the repo root (beside `scripts/`), unless14- * a test points it elsewhere. Each run writes below it: `<run>/agents.json`15- * and one workspace per contributor, `<run>/<handle>/`.21+ * The swarm's folder for `env`: `${XDG_STATE_HOME:-$HOME/.local/state}/22+ * <slug>/swarm`, beside the hook's sessions, and never inside a checkout: a23+ * harness reads every AGENTS.md and CLAUDE.md above its folder, so a24+ * workspace inside this repo would hand each contributor the platform's own.25+ * With neither variable set, the system's temp folder.26 */27+export const swarmDirOf = (env: typeof StateEnv.Type) => {28+ const home = env.HOME === undefined ? "/tmp" : `${env.HOME}/.local/state`;29+30+ return `${env.XDG_STATE_HOME ?? home}/${Brand.slug}/swarm`;31+};32+33+/** The global scope, read only for its `process.env`. */34+const GlobalScope = Schema.Struct({35+ process: Schema.Struct({ env: StateEnv }),36+});37+38+/**39+ * The swarm's folder (`swarmDirOf` this process's env), unless a test points40+ * it elsewhere. Each run writes below it: `<run>/agents.json` and one41+ * workspace per contributor, `<run>/<handle>/`.42+ */43 export const SwarmDir = Context.Reference<string>("swarm/SwarmDir", {18- defaultValue: () =>19- decodeURIComponent(new URL("../../../.swarm", import.meta.url).pathname),44+ defaultValue: () => {45+ // Unknown on purpose: the runtime is whatever started this process.46+ const scope: unknown = globalThis;47+48+ return swarmDirOf(49+ Option.match(Schema.decodeUnknownOption(GlobalScope)(scope), {50+ onNone: () => ({}),51+ onSome: ({ process }) => process.env,52+ })53+ );54+ },55 });56 22-/** A run's own folder: `.swarm/<run>`. */57+/** A run's own folder: `<swarm>/<run>`. */58 export const runDir = (run: string) =>59 Effect.map(SwarmDir, (dir) => `${dir}/${run}`);60 61 /** The four harnesses a swarm contributor may run. */58 unmodified lines120 121 /** The file a run's summary is written to, below the swarm's folder. */122 export const agentsFile = (dir: string) => `${dir}/agents.json`;123 89-/** Writes `result` to `.swarm/<run>/agents.json`, as indented JSON. */124+/** Writes `result` to `<swarm>/<run>/agents.json`, as indented JSON. */125 export const writeAgentsResult = (input: {126 readonly run: string;127 readonly result: AgentsResult;128 }): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> =>15 unmodified linesmodified:scripts/lib/swarm/roster.ts+9 added-7 removed
1 /**2- * The swarm's six fictional contributors: "4 harnesses, 6 models" (SYN Q28).3- * Each is one person (a `SESSION_TOKENS` entry on the stage, spec D9) with4- * one harness and one model, vouched in burrow's `vouched.td`, so their5- * claims are not `NotVouched`.2+ * The swarm's six fictional contributors: "4 harnesses, 6 models". Each is3+ * one person (a `SESSION_TOKENS` entry on the stage, a named session beside4+ * accounts) with one harness and one model, vouched in burrow's5+ * `vouched.td`, so their claims are not `NotVouched`.6 *7- * The model ids are what this machine's harnesses list (2026-10-08):7+ * The model ids are what this machine's harnesses list and run (2026-10-08):8 * `opencode models` for OpenCode's GPT model and OpenCode Zen's Gemini flash,9 * `pi --offline --list-models` for pi's (its ready provider is `opencode-go`),10- * `amp --help` for Amp's modes.10+ * `amp --help` for Amp's modes. OpenCode signed in with a ChatGPT account11+ * refuses `openai/gpt-6.1-sol` ("not supported when using Codex with a12+ * ChatGPT account"), so tamsin runs `openai/gpt-5.5`, which ran headless.13 */14 import { Handle } from "@repo/protocol/ids";15 import { Schema } from "effect";16 37 unmodified lines54 {55 adapter: false,56 handle: Handle.make("tamsin"),57 harness: "opencode",56- model: "openai/gpt-6.1-sol",58+ model: "openai/gpt-5.5",59 },60 {61 adapter: false,62 handle: Handle.make("ivo"),25 unmodified linesmodified:scripts/lib/swarm/workspace.ts+4 added-3 removed
1 /**2- * One contributor's workspace: `.swarm/<run>/<handle>/`, with their clone of2+ * One contributor's workspace: `<swarm>/<run>/<handle>/` (`SwarmDir`, outside3+ * the checkout), with their clone of4 * the claim's fork, a `bin/` that puts this repo's CLI (and git's credential5 * helper) on `PATH`, their own config folder, and the env their harness runs6 * in. The person's platform token reaches the harness only through that env,7 * as `<SLUG>_TOKEN`, never in a file, an argv or a URL.17 unmodified lines25 }26 27 /** Where one contributor works, and the env their harness runs in. */28 export interface AgentWorkspace {28- /** `.swarm/<run>/<handle>`. */29+ /** `<swarm>/<run>/<handle>`. */30 readonly dir: string;31 /** Their clone of the claim's fork: the harness's working directory. */32 readonly clone: string;33 readonly env: Readonly<Record<string, string>>;128 unmodified lines162 )163 );164 165 /**165- * Makes one contributor's workspace for their claim, below `.swarm/<run>/`:166+ * Makes one contributor's workspace for their claim, below `<swarm>/<run>/`:167 *168 * - `bin/<cli>` and `bin/git-credential-<slug>`, shims that run this repo's169 * CLI from source (the helper as `<cli> credential`), first on `PATH`;170 * - `config/`, the CLI's `XDG_CONFIG_HOME`, so neither the CLI nor git's108 unmodified linesmodified:scripts/seed.ts+10 added-26 removed
22 unmodified lines23 */24 import { BunRuntime, BunServices } from "@effect/platform-bun";25 import { Envelope } from "@repo/protocol/envelope";26 import { Handle, ProjectName } from "@repo/protocol/ids";27-import {28- Array,29- Console,30- Effect,31- FileSystem,32- Option,33- Path,34- Schema,35- Stdio,36-} from "effect";27+import { Array, Console, Effect, Option, Path, Schema, Stdio } from "effect";28 29 import {30 flagValue,31 platformOrigin,41- repoRoot,32+ recordedSubdomain,33 Stage,34 stageOf,35 subdomainFile,45- WorkersDev,36 } from "../infra/stages.ts";37 import {38 MAIN_REF,39 planSeed,158 unmodified lines198 if (where.url !== undefined) {199 return where.url;200 }201 212- const fs = yield* FileSystem.FileSystem;213- const path = yield* Path.Path;214- const root = yield* repoRoot;215-216- const recorded = yield* fs217- .readFileString(path.join(root, subdomainFile))218- .pipe(219- Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(WorkersDev))),220- Effect.mapError(() =>221- failed(222- `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${where.stage} first`202+ const subdomain = yield* recordedSubdomain.pipe(203+ Effect.flatMap(Effect.fromOption),204+ Effect.mapError(() =>205+ failed(206+ `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${where.stage} first`223- )207 )225- );208+ )209+ );210 227- return platformOrigin(where.stage, recorded.subdomain);211+ return platformOrigin(where.stage, subdomain);212 });213 214 /** Where the seed goes, said for a person, and the target there. */215 const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>137 unmodified linesmodified:scripts/swarm.ts+12 added-24 removed
12 unmodified lines13 * Without it, each contributor claims their ask as themselves (their token14 * from `SESSION_TOKENS`, a JSON object from token to handle, as the15 * platform's own), reads the ask's page, gets a workspace with a clone of16 * the claim's fork, and is handed to the run loop (711), six at once. The17- * run's summary goes to `.swarm/<run>/agents.json`, and each claim's fork to17+ * run's summary goes to `<swarm>/<run>/agents.json` (`SwarmDir`: the state18+ * home's `<slug>/swarm/`, outside every checkout), and each claim's fork to19 * the throwaway ledger (`infra/created.ts`). Tokens reach a contributor's20 * processes only through their env, and no line or JSON this prints holds21 * one. Flags: `lib/swarm/args.ts`.22 *14 unmodified lines37 Config,38 Console,39 DateTime,40 Effect,40- FileSystem,41 Option,42- Path,42 Redacted,43 Result,44 Schema,45 Stdio,1 unmodified line47 48 import { readLedger, recordCreated } from "../infra/created.ts";49 import {50 platformOrigin,51+ recordedSubdomain,52 repoRoot,53 resources,54 subdomainFile,55- WorkersDev,55 } from "../infra/stages.ts";56 import type { Stage } from "../infra/stages.ts";57 import { optionsOf } from "./lib/swarm/args.ts";58 import type { SwarmOptions } from "./lib/swarm/args.ts";34 unmodified lines93 /** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */94 const originOf = (options: SwarmOptions) =>95 Option.match(options.url, {96 onNone: () =>98- Effect.gen(function* () {99- const fs = yield* FileSystem.FileSystem;100- const path = yield* Path.Path;101- const root = yield* repoRoot;102-103- const recorded = yield* fs104- .readFileString(path.join(root, subdomainFile))105- .pipe(106- Effect.flatMap(107- Schema.decodeEffect(Schema.fromJsonString(WorkersDev))108- ),109- Effect.mapError(() =>110- failed(111- `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`112- )113- )114- );115-97+ recordedSubdomain.pipe(98+ Effect.flatMap(Effect.fromOption),99+ Effect.mapError(() =>100+ failed(101+ `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${options.stage} first`102+ )103+ ),104+ Effect.map((subdomain) => platformOrigin(options.stage, subdomain))105+ ),116- return platformOrigin(options.stage, recorded.subdomain);117- }),106 onSome: Effect.succeed,107 });108 109 /** One CLI command, run from this repo's source with Bun. */480 unmodified linesmodified:AGENTS.md+1 added-1 removed
64 unmodified lines65 - `bootstrap -- --stage <stage>`: makes a stage's Cloudflare resources; a second run creates nothing, and `--dry-run` only prints the plan.66 - `deploy -- --stage <stage>`: the one way to deploy. It runs `verify`, deploys the three Workers with Wrangler, reads the push trigger back, then runs `smoke`.67 - `smoke -- --stage <stage>`: read-only probes against a live stage.68 - `seed`: puts the two example projects on a platform (`--world node` on this machine, or `--stage <stage>`); a second run changes nothing.69-- `swarm -- --stage <stage> --project <name>`: plans six fictional contributors, on four harnesses, against one split family on a stage, claims each one's ask and prepares a workspace with a clone of its fork; `--dry-run` only prints the plan. Starting the harnesses is not built yet: each run is recorded as failed.69+- `swarm -- --stage <stage> --project <name>`: plans six fictional contributors, on four harnesses, against one split family on a stage, claims each one's ask, prepares a workspace with a clone of its fork outside the checkout, starts each harness headless on the brief and sends every refusal back into the same session, at most three times, then writes the run's summary; `--view herdr` runs them in herdr panes beside a counter, and `--dry-run` only prints the plan.70 - `release -- --build | --upload --stage <stage> | --publish`: builds the CLI's npm package and two binaries, uploads a release to the stage's own bucket, which the platform serves, and leaves `npm publish` to a person: under an agent it prints the command instead.71 72 ## Nouns73 72 unmodified linesmodified:bun.lock+3 added-2 removed
6 unmodified lines7 "devDependencies": {8 "@effect/platform-bun": "catalog:",9 "@effect/tsgo": "0.48.1",10 "@oxlint/plugins": "1.87.0",11+ "@repo/agent-kit": "workspace:*",12 "@repo/brand": "workspace:*",13 "@repo/protocol": "workspace:*",14 "cf": "1.0.0-beta.12",15 "effect": "catalog:",1882 unmodified lines1898 "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],1899 1900 "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],1901 1901- "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],1902+ "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],1903 1904 "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],1905 1906 "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],359 unmodified lines2266 "proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],2267 2268 "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="],2269 2269- "react-reconciler/scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],2270+ "react-dom/scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],2271 2272 "restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],2273 2274 "rolldown-plugin-dts/obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="],146 unmodified linesmodified:package.json+1 added
37 unmodified lines38 "devDependencies": {39 "@effect/platform-bun": "catalog:",40 "@effect/tsgo": "0.48.1",41 "@oxlint/plugins": "1.87.0",42+ "@repo/agent-kit": "workspace:*",43 "@repo/brand": "workspace:*",44 "@repo/protocol": "workspace:*",45 "cf": "1.0.0-beta.12",46 "effect": "catalog:",10 unmodified linesmodified:README.md+4 added-2 removed
182 unmodified lines183 184 What it does not promise:185 186 - **Held-back checks are hidden from people and agents, not from the code under test.** They run in the check job's own container with the network off, nothing they or the lanes beside them print comes back, and a claim, or a person in one area, may fail an area only a few times each week. That raises the cost of reading them; it cannot stop a determined reader whose code runs beside them. The `Held-back:` trailer names each area, how many of its sealed checks passed and the suite's commitment, nothing more.187-- **Verdicts after the push are asynchronous.** Custody and shape refusals arrive in `git push`; the merged-tree checks report through `myr status`, `myr verdict`, MCP, the web, and a git note on the answer's head.187+- **Verdicts after the push are asynchronous.** Custody and shape refusals arrive in `git push`; the merged-tree checks report through `myr status`, `myr verdict`, MCP, the web, and a git note on the answer's head ([ADR 0015](docs/adr/0015-submitting-an-answer-is-asynchronous.md)).188 - **No numbers but the table's.** The Numbers section holds only what a live run measured, each with its stage and date.189 190 ## Keep or cut191 6 unmodified lines198 | 1 | Today full-screen at a terminal, `myr today --tui` (`myr today` goes back to the contract's projected command, which prints the same) | `apps/cli/src/tui/`, `apps/cli/test/tui/`, the `@opentui/*` lines in `apps/cli/package.json`; `today` in `wrapped`, `entries` and `Every` in `apps/cli/src/surfaces.ts`, its row in `packages/agent-kit/src/command-doc.ts` and its word in `packages/agent-kit/test/command-doc.test.ts` |199 | 1 | Agent extras: the Markdown ask page, per-project well-known skills, and `myr schema` | `apps/web/src/features/ask/markdown.ts`, `apps/web/test/ask-markdown.test.ts`; `packages/agent-kit/src/well-known.ts`, `apps/platform/src/well-known.ts`, `apps/platform/test/well-known.test.ts`, `apps/web/src/routes/[.]well-known/agent-skills/$.ts`; `apps/cli/test/schema.test.ts` and the `schema` command in `apps/cli/src/surfaces.ts` |200 | 1 | The pi adapter | `apps/cli/src/pi.ts`, `apps/cli/test/pi.test.ts`, its entry and its `neverBundle` line in `apps/cli/tsdown.config.ts`, the pi dev dependency in `apps/cli/package.json`, and the adapter's line in the package manifest's `pi` key in `scripts/lib/release.ts` |201 | 2 | `myr why`, verdicts as git notes, and the `ReachedInternals` stage | `apps/cli/src/local/why.ts`, `apps/cli/test/local/why.test.ts`; `packages/git/src/notes.ts`, `apps/platform/src/workflows/notes.ts`, `packages/git/test/notes.test.ts`, `apps/platform/test/notes.test.ts` (verdicts still reach `status`, `verdict` and MCP); `packages/gate/src/imports.ts`, `packages/gate/test/imports.test.ts` and its branch in `packages/gate/src/stages/shape.ts` |202+| 2 | The null-answer codemod: a check that passes against an answer whose exports do nothing is `WeakCheck` (built and tested; no ask runs it yet, since it needs a third check run and a step in the Checker's image) | `packages/checks/src/null-answer.ts`, `packages/checks/test/null-answer.test.ts`, `packages/checks/test/fixtures/null-answer/`, and its `./null-answer` export and `ts-morph` line in `packages/checks/package.json` |203+| 3 | Garden's Promote: a finish repeated across answers becomes a proposed `lintToZero` ask behind one decision (built and tested; no landing calls it yet, since no finish carries the rule it names) | `packages/project/src/attention/promote.ts`, `packages/project/test/attention/promote.test.ts` |204 | 3 | Admission runs and env injection | `packages/project/src/visibility/admission.ts`, `apps/platform/src/workflows/admission-steps.ts`, `packages/project/test/visibility/admission.test.ts`, `apps/platform/test/visibility/admission.test.ts`; `apps/sandbox/src/env-gateway.ts`, `apps/sandbox/src/checker/env.ts`, `apps/sandbox/test/env-injection.test.ts` |205 | 4 | Live streaming views (the pages poll every 5 s instead, as they already do when the stream fails) | `apps/platform/src/watch.ts`, `apps/platform/test/watch.test.ts`, the `ProjectSockets` entry in `apps/platform/src/ports.ts`, the `Watch` contract in `packages/protocol/src/contracts.ts` with its callers, and the stream half of `apps/web/src/client/watch.ts` and `apps/web/test/watch.test.ts`, keeping the polling |206 | 4 | The D1 projection (the platform falls back to an empty memory front page) | `packages/project/src/projection-d1/`, `packages/project/test/projection-d1.test.ts`, `packages/project/test/projection-d1-credits.test.ts`, `packages/project/test/projection-d1.fixtures.ts`, `apps/platform/migrations/0001_front_page.sql`, `apps/platform/migrations/0004_projects_credits.sql`, and its entry in `apps/platform/src/ports.ts` |207 | 5 | Visibility, the cartridge: layers, held-back checks, posture, the ledger, the env shape and write-only values | `packages/visibility/`, `packages/project/src/visibility/`, `packages/project/test/visibility/`, `apps/platform/src/visibility/`, `apps/platform/test/visibility/`, `apps/cli/test/local/env-set-live.test.ts`, `packages/config/test/seed-layer.test.ts`, `examples/datekit/layers/`, `packages/config/test/cartridge.test.ts`; the marked line in `apps/platform/src/cartridges.ts`; the `@repo/visibility` lines in `apps/platform/package.json` and `packages/project/package.json`; `ARTIFACTS_PRIVATE` and `MASTER_KEY` wherever they are named outside it (`apps/platform/wrangler.jsonc`, `apps/platform/.env.schema`, the env decode in `apps/platform/src/platform.ts`, the platform's test env in `apps/platform/test/fake-env.ts` and `apps/platform/test/serve-world.ts`, and their type and binding tests), with the layer rows in `packages/config/test/bootstrap.test.ts` and `packages/config/test/seed.test.ts`; then `bun run --cwd apps/platform types` |56 unmodified lines264 Read it back with `myr status`, `myr verdict`, `myr why <path>:<line>`, the verdict note, MCP or the web.265 266 ### What the design rests on267 266-Artifacts, the git storage under every repo, has no atomic multi-ref push, so `main` lands by itself, with a non-force push that fails if `main` moved (a compare-and-swap), and the bookkeeping refs (the landed mirror and the notes) follow in pushes of their own. The Project Durable Object's landed SHA is the truth. Any write token can force-push `main`, so a canonical repo's write tokens never leave the platform's own jobs: answers go to forks through the gateway, and only the trusted Lander, which runs no answer code, gets a write token on a canonical repo, for five minutes, inside a landing. Events fire once per pushed ref, the platform's own bookkeeping pushes included, so `OnPush` recognizes those and ignores them. The binding resolves only short branch names and commit SHAs, so the Durable Object keeps the SHAs of custom refs itself.268+Artifacts, the git storage under every repo, has no atomic multi-ref push, so `main` lands by itself, with a non-force push that fails if `main` moved (a compare-and-swap), and the bookkeeping refs (the landed mirror and the notes) follow in pushes of their own. The Project Durable Object's landed SHA is the truth. Any write token can force-push `main`, so a canonical repo's write tokens never leave the platform's own jobs: answers go to forks through the gateway, and only the trusted Lander, which runs no answer code, gets a write token on a canonical repo, for five minutes, inside a landing. Events fire once per pushed ref, the platform's own bookkeeping pushes included, so `OnPush` recognizes those and ignores them. The binding resolves only short branch names and commit SHAs, so the Durable Object keeps the SHAs of custom refs itself ([ADR 0014](docs/adr/0014-landing-is-a-cas-push-of-main-then-bookkeeping-refs.md)).269 270 ### Plain git, so you can leave271 272 Export is `git clone`. Code, asks (files in the config folder), the rules (TypeScript on `main`) and credit trailers, `Decided-by` included, leave with a clone. Verdict notes need one more fetch of `refs/notes/*`, because `git clone` copies no notes:39 unmodified lines