Add the live-run tooling: smoke --loop, seed --as, a recording lock for deploys, and a Playwright check of the deployed web
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- `bun scripts/smoke.ts --stage <s> --loop` runs the probes, then the whole core loop through the CLI and git (`scripts/lib/smoke/loop.ts`, steps in `core-loop.ts`): a throwaway project `smoke-<run>` made with `<cli> init`, an ask opened red twice on main, a claim, an out-of-territory push whose stderr must carry `OutOfScope`, the fixed push, the landing (answerer as author, the platform as committer, `Asked-by` and `Signed-off-by`), and the verdict note on the head in the fork. Each step is timed and printed as it passes. Tokens come only from the env: the operator's (`OPERATOR_TOKEN`) makes the project and opens the ask, the answerer's comes from `SESSION_TOKENS` by `--as` (bram unless given); git's credential helper is the CLI itself, with a gitconfig of the run's own. `--loop --stage demo` is refused with `DemoStageRefused` before any request or process. - The project, its repo and the claim's fork are written to the throwaway ledger by `smoke` as each exists. - The loop fails with `LoopFailed {step, reason}`, not the interface's `SmokeFailed`: infra/smoke.ts's `SmokeFailed` names a closed list of probes, and 308's checks stay as they are. - `apps/platform/test/serve-world.ts` now carries queued answer runs every 250 ms, as the Answer Workflow does on a stage; before, nothing in the served world called `settle`, so no answer pushed over git could land there. - `bun run seed -- --only <example> --as <name>` seeds a fresh copy: `renameSeedPlan` (pure) renames the project and each layer's repo, and marks the plan `copyOf` its example. A copy is never "already": a taken name is refused, `SeedFailed` with its `ProjectExists`, before anything is pushed. `runSeedWith(plan, made)` sits beside `runSeed(plan)` (signature kept) and writes a copy on a stage to the ledger by `seed` right after Init: the project, its repo, and each layer's repo. `--as` needs `--only` and a name other than the example's. - `bun infra/recording.ts on|off|status` writes or removes `infra/.recording` (gitignored). `infra/deploy.ts` checks it first, before it reads a flag, and refuses with `RecordingInProgress` naming the file. Nothing but `off` lifts it. `LockFile` is a Context.Reference (as `LedgerFile` is) for tests. deploy.test.ts points it at an absent path, so a real take's lock never decides those tests. - `apps/web/e2e/deployed.e2e.ts` and `playwright.config.ts`: the front page, a project page, an ask page, its `.md` and `/llms.txt` on `WEB_URL`, each asserted on its key text, one screenshot each in `e2e/out/` (gitignored). The suite is skipped without `WEB_URL`. Run it with `bun run --cwd apps/web e2e`: `bunx playwright` at the root finds no local bin and would fetch npm's latest. The file is named `*.e2e.ts` because the repo's lint gives every `*.spec.ts` vitest's rules. Checked against the web's local dev server: 5 passed. Chromium 1243 was installed. - The root gets the workspace devDependency `@repo/artifacts` for 808's teardown. - Docs: the rehearsal's pre-flight runs `bun infra/recording.ts on` and `status`, a new "After the last take" section runs `off`, and the "until that lock exists" prose is gone (799's comment). AGENTS.md principle 11 names recording.test.ts. AGENTS.md's commands, the README's stage steps and its promises table, and stages.md's H7 row now cover the loop, the copy and the lock. - Tests, each red by assertion first: packages/config/test/smoke-loop.test.ts (the loop on the Node world, and both demo refusals), seed-as.test.ts (renaming, the taken name, a copy on the world, the flags, the ledger rows), recording.test.ts (refused for every argv while locked, the same seven steps without the lock, on/status/off). - ASSUMPTION: the stage's Checker runs `bun test {path}` for the fixture, as it does for datekit. 807 runs the loop live.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+2672 added−41 removed
- tests:+794 added−2 removed
- other:+1878 added−39 removed
Provenance
- Commit
030c4d6- Tree
be57fab- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
d5649f9
23 files changed+2672 added−41 removed
modified:apps/platform/test/serve-world.ts+28 added-1 removed
11 unmodified lines12 * commit or tree it is given (`CheckRunnerLocal`), so an ask's check is13 * red first, or not, by what it really does.14 * - Beside dora, alice and bob, the people in `WORLD_SESSIONS` (a JSON15 * object from token to handle, as `SESSION_TOKENS` is) may call.16+ * - Every answer run a push queues is carried a moment later, for as long17+ * as the world serves, as the `Answer` Workflow carries it on a stage:18+ * an answer pushed over git lands with nobody calling `settle` (W8 806's19+ * `smoke --loop` runs against this world).20 * - Every cartridge the platform plugs in (`cartridges.ts`) is plugged in21 * here too, as `ports.ts` plugs them into the Worker, for a stage whose22 * private namespace is the world's second store of bare repos: so a23 * project that declares a layer gets its repo there, and its maintainers15 unmodified lines39 import { Projects } from "@repo/project/projects";40 import { VerifierBlocked } from "@repo/protocol/refusal";41 import { git } from "@repo/testkit/git";42 import { untouchable } from "@repo/testkit/untouchable";39-import { Console, Effect, FileSystem, Layer, Stdio, Stream } from "effect";43+import {44+ Console,45+ Duration,46+ Effect,47+ FileSystem,48+ Layer,49+ Stdio,50+ Stream,51+} from "effect";52 53 import type * as Cartridges from "../src/cartridges.ts";54 import type { Cartridge } from "../src/cartridges.ts";55 import type { decodeEnv, PlatformConfig } from "../src/platform.ts";112 unmodified lines168 worker: all,169 };170 };171 172+/** How long after the last round the world carries queued answer runs again. */173+const CARRY_EVERY = Duration.millis(250);174+175 const serve = Effect.gen(function* () {176 yield* shimWorkers;177 178 const sessions = yield* worldSessions;13 unmodified lines192 plugIn: cartridgesOver(cartridges, decodeEnv),193 sessions,194 });195 196+ // The Answer Workflow's stand-in: the queued runs, carried every197+ // `CARRY_EVERY` while the world serves. A run that dies is logged, and198+ // the next round carries on.199+ yield* world.settle().pipe(200+ Effect.catchCause((cause) =>201+ Effect.logWarning("the world's answer runs failed", cause)202+ ),203+ Effect.andThen(Effect.sleep(CARRY_EVERY)),204+ Effect.forever,205+ Effect.forkScoped206+ );207+208 yield* Console.log(JSON.stringify({ origin: world.origin }));209 210 const stdio = yield* Stdio.Stdio;211 6 unmodified linesadded:apps/web/e2e/deployed.e2e.ts+149 added
1+/**2+ * The deployed web, as a browser shows it (issue 806): the front page, a3+ * project's page, an ask's page and the same ask as Markdown, and4+ * `/llms.txt`, each asserted on its key text, each saved as one screenshot5+ * in `e2e/out/` for the shot list.6+ *7+ * It runs only against `WEB_URL` (a stage's web origin) and is skipped8+ * without it. `WEB_PROJECT` and `WEB_ASK` pick the project and the ask9+ * (datekit's format-ordinal, which the seed opens on every stage, unless10+ * given). It only reads.11+ */12+import { expect, test } from "@playwright/test";13+import type { Page } from "@playwright/test";14+import { Config, Effect, Option } from "effect";15+16+/** What the check reads of its env: where the web lives, and which ask to look at. */17+const settings = Effect.runSync(18+ Effect.gen(function* () {19+ return {20+ ask: yield* Config.NonEmptyString("WEB_ASK").pipe(21+ Config.withDefault("format-ordinal")22+ ),23+ project: yield* Config.NonEmptyString("WEB_PROJECT").pipe(24+ Config.withDefault("datekit")25+ ),26+ web: Option.map(27+ yield* Config.option(Config.NonEmptyString("WEB_URL")),28+ (url) => url.replace(/\/+$/u, "")29+ ),30+ };31+ })32+);33+34+const { ask, project } = settings;35+36+/** Where each page's screenshot goes: `e2e/out/<shot>.png`. */37+const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);38+39+/** What every page that could not reach the platform says instead of its content. */40+const UNREACHABLE = "The platform did not answer";41+42+/** `url` on the web. */43+const at = (path: string) =>44+ `${Option.getOrElse(settings.web, () => "")}${path}`;45+46+/**47+ * Opens `path` as a page, waits for each of `texts`, checks the platform48+ * answered it, and saves the screenshot `shot`.49+ */50+const page = (51+ browser: Page,52+ path: string,53+ shot: string,54+ texts: readonly string[]55+) =>56+ Effect.gen(function* () {57+ const response = yield* Effect.promise(() => browser.goto(at(path)));58+59+ expect(response?.status()).toBe(200);60+61+ yield* Effect.forEach(62+ texts,63+ (text) =>64+ Effect.promise(() =>65+ expect(browser.getByText(text).first()).toBeVisible()66+ ),67+ { discard: true }68+ );69+70+ yield* Effect.promise(() =>71+ expect(browser.getByText(UNREACHABLE)).toHaveCount(0)72+ );73+74+ yield* Effect.promise(() =>75+ browser.screenshot({ fullPage: true, path: `${out}${shot}.png` })76+ );77+ });78+79+/**80+ * Fetches `path` as Markdown, checks it opens with a title and holds each81+ * of `texts`, and saves a screenshot of it, shown as plain text.82+ */83+const markdown = (84+ browser: Page,85+ path: string,86+ shot: string,87+ texts: readonly string[]88+) =>89+ Effect.gen(function* () {90+ const response = yield* Effect.promise(() => browser.request.get(at(path)));91+92+ const body = yield* Effect.promise(() => response.text());93+94+ expect({95+ status: response.status(),96+ title: body.startsWith("# "),97+ type: response.headers()["content-type"]?.split(";")[0],98+ }).toStrictEqual({ status: 200, title: true, type: "text/markdown" });99+100+ for (const text of texts) {101+ expect(body).toContain(text);102+ }103+104+ yield* Effect.promise(() =>105+ browser.setContent(106+ `<pre style="white-space: pre-wrap; font: 14px/1.5 monospace; margin: 24px"></pre>`107+ )108+ );109+110+ yield* Effect.promise(() =>111+ browser.locator("pre").evaluate((pre, text) => {112+ pre.textContent = text;113+ }, body)114+ );115+116+ yield* Effect.promise(() =>117+ browser.screenshot({ fullPage: true, path: `${out}${shot}.png` })118+ );119+ });120+121+test.describe("the deployed web", () => {122+ test.skip(123+ Option.isNone(settings.web),124+ "WEB_URL is not set: point it at a deployed web's origin to run this check"125+ );126+127+ test("the front page lists the open asks", ({ page: browser }) =>128+ Effect.runPromise(page(browser, "/", "front-page", ["Open asks"])));129+130+ test(`${project}'s page shows the project`, ({ page: browser }) =>131+ Effect.runPromise(page(browser, `/${project}`, "project-page", [project])));132+133+ test(`${project}/${ask}'s page shows the ask`, ({ page: browser }) =>134+ Effect.runPromise(135+ page(browser, `/${project}/asks/${ask}`, "ask-page", [ask])136+ ));137+138+ test(`${project}/${ask}.md is the ask's brief in Markdown`, ({139+ page: browser,140+ }) =>141+ Effect.runPromise(142+ markdown(browser, `/${project}/asks/${ask}.md`, "ask-markdown", [143+ `Ask \`${ask}\` in ${project}`,144+ ])145+ ));146+147+ test("/llms.txt is the web's Markdown for agents", ({ page: browser }) =>148+ Effect.runPromise(markdown(browser, "/llms.txt", "llms-txt", [project])));149+});modified:apps/web/package.json+2 added-1 removed
12 unmodified lines131415161717181920212239 unmodified lines12 unmodified lines "build": "vite build", "routes": "bun scripts/route-tree.ts", "types": "wrangler types --include-runtime=false --strict-vars=false", "typecheck": "bun run routes && tsc --noEmit -p tsconfig.json", "test": "vitest run" "test": "vitest run", "e2e": "playwright test -c playwright.config.ts" }, "dependencies": { "@base-ui/react": "1.8.0", "@effect/atom-react": "4.0.1",39 unmodified linesadded:apps/web/playwright.config.ts+33 added
123456789101112131415161718192021222324252627282930313233import { defineConfig, devices } from "@playwright/test";
/** * The Playwright check of a deployed web (issue 806), never part of verify: * vitest runs only `test/`, and this runs only `e2e/*.e2e.ts`, against the stage * `WEB_URL` names (the spec skips itself without one). From `apps/web`: * * bunx playwright install chromium * WEB_URL=https://web-dev-oscabriel.oscargabriel.workers.dev bun run e2e * * Each page's screenshot lands in `e2e/out/` (gitignored), for the shot * list; Playwright's own traces and failures go to `e2e/out/results/`. */export default defineConfig({ forbidOnly: true, outputDir: "e2e/out/results", projects: [ { name: "chromium", use: { ...devices["Desktop Chrome"], viewport: { height: 800, width: 1280 }, }, }, ], reporter: "list", retries: 0, testDir: "e2e", // `*.e2e.ts`, not `*.spec.ts`: the repo's lint gives every `*.spec.ts` // vitest's rules, and these are Playwright's tests. testMatch: "*.e2e.ts", timeout: 60_000,});modified:apps/web/tsconfig.json+1 added
16 unmodified lines1718192021222324252616 unmodified lines "src/**/*.ts", "src/**/*.tsx", "test/**/*.ts", "test/**/*.tsx", "e2e/**/*.ts", "scripts/**/*.ts", "*.config.ts", "worker-configuration.d.ts" ]}modified:docs/demo/rehearsal.md+16 added-2 removed
1 # Rehearsal2 3-**No deploys during takes.** Nothing deploys between the first take and the last: a deploy restarts the platform's Durable Objects mid-take. Turn on the deploy recording lock before the first take and off after the last; while it is on, `infra/deploy.ts` refuses every deploy. Until that lock exists in `infra/`, hold the rule by hand: nobody runs `bun run deploy` while anyone records.3+**No deploys during takes.** Nothing deploys between the first take and the last: a deploy restarts the platform's Durable Objects mid-take. Turn on the deploy recording lock before the first take and off after the last; while it is on, `infra/deploy.ts` refuses every deploy with `RecordingInProgress`. No flag or environment variable lifts it: only `bun infra/recording.ts off`, run by a person once the last take is done.4 5 This checklist is walked once on the live stages before the recording: the read-only shots on `demo`, the shots that consume asks on `dev-oscabriel` (on a fresh copy of each example, so demo's asks stay open for the take), with the same commands [`shot-list.md`](shot-list.md) gives. Mark each line as it is walked:6 7 - a pass: `- [x] S07 … PASS 2026-10-13 demo, 0:41`;33 unmodified lines41 ## Pre-flight42 43 On the morning of the take, in this order.44 45-- [ ] The recording lock is on (until it exists, everyone who can deploy knows a take is running), and nobody plans a deploy until the last take is done.45+- [ ] The recording lock is on, and nobody plans a deploy until the last take is done:46+47+ ```sh48+ bun infra/recording.ts on49+ bun infra/recording.ts status50+ ```51+52 - [ ] Smoke passes on demo:53 54 ```sh55 bun scripts/smoke.ts --stage demo49 unmodified lines105 - [ ] Panes laid out: one terminal (or herdr's six plus the counter for S12) beside one browser window at 1280 px; one colour scheme for every take; terminal font large enough to read at 1080p.106 - [ ] Notifications off: system do-not-disturb, chat apps closed, the browser's notifications blocked.107 - [ ] The recording order in `shot-list.md` is printed beside the screen.108 109+## After the last take110+111+- [ ] The recording lock is off, so deploys run again:112+113+ ```sh114+ bun infra/recording.ts off115+ ```116+117 ## Beat timings118 119 Filled in by the walk: how long each beat ran, against its range in [`script.md`](script.md). If the total runs over 10:00, cut the env paragraph and S20 first.120 9 unmodified linesmodified:infra/deploy.ts+20 added-4 removed
12 unmodified lines13 * 6. `scripts/smoke.ts` against the live stage;14 * 7. the redirect URI a Google OAuth client registers for the stage (H4),15 * printed for a person to copy; Google sign-in stays off without one.16 *17- * Without `--stage`, or with a stage `stages.ts` doesn't declare, it refuses18- * before it spawns anything. It takes no other flag: verify always runs.17+ * While a take is being recorded (`infra/.recording`, which18+ * `bun infra/recording.ts on` writes), it refuses every deploy with19+ * `RecordingInProgress` before it reads a flag or spawns anything; only20+ * `bun infra/recording.ts off` lifts that. Without `--stage`, or with a stage21+ * `stages.ts` doesn't declare, it refuses before it spawns anything. It takes no other flag: verify always runs.22 * Every command runs with `WRANGLER_SEND_METRICS=false`; Wrangler deploys23 * with its own login, never the read-mostly infra token.24 *25 * `STAGE_SECRETS_FILE` names a dotenv file outside the repo whose values the19 unmodified lines45 } from "effect";46 import { ChildProcess, ChildProcessSpawner } from "effect/process";47 48 import { schemaItems } from "./env-schema.ts";49+import { notRecording } from "./recording.ts";50+import type { RecordingInProgress } from "./recording.ts";51 import {52 platformOrigin,53 repoRoot,54 stageOf,1 unmodified line56 WorkersDev,57 } from "./stages.ts";58 import type { NoStage, Stage, UnknownStage } from "./stages.ts";59 60+export { RecordingInProgress } from "./recording.ts";61+62 export { NoStage, UnknownStage } from "./stages.ts";63 64 /** A step exited non-zero; nothing after it ran. */65 export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", {203 unmodified lines269 `deploy ${stage}: to offer Google sign-in, register ${platformOrigin(stage, subdomain)}${GOOGLE_CALLBACK} as the Google client's redirect URI (H4)`,270 });271 });272 266-/** Deploys the stage `argv`'s `--stage` names, then smoke-tests it. */273+/**274+ * Deploys the stage `argv`'s `--stage` names, then smoke-tests it; refused275+ * outright while a take is being recorded.276+ */277 export const deploy = (278 argv: readonly string[]279 ): Effect.Effect<280 void,271- NoStage | UnknownStage | StepFailed | SecretsFileUnreadable,281+ | RecordingInProgress282+ | NoStage283+ | UnknownStage284+ | StepFailed285+ | SecretsFileUnreadable,286 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path287 > =>288 Effect.gen(function* () {289+ yield* notRecording;290+291 const stage = yield* stageOf(argv);292 const fs = yield* FileSystem.FileSystem;293 const path = yield* Path.Path;294 const root = yield* repoRoot;26 unmodified linesadded:infra/recording.ts+137 added
1+/**2+ * recording: `bun infra/recording.ts on | off | status`. The deploy lock for3+ * recording days (H7; AGENTS.md: never deploy during a recording): a deploy4+ * restarts the platform's Durable Objects, so one mid-take breaks the take.5+ *6+ * - `on` writes `infra/.recording` (gitignored), saying since when;7+ * - `off` removes it;8+ * - `status` says whether it is there.9+ *10+ * While the file is there, `infra/deploy.ts` refuses every deploy before it11+ * reads its flags or spawns anything, with `RecordingInProgress` naming the12+ * file. Nothing else lifts it: no flag, no environment variable. `off` is the13+ * only way out, and during a take only a person runs it.14+ */15+import { BunRuntime, BunServices } from "@effect/platform-bun";16+import {17+ Console,18+ Context,19+ DateTime,20+ Effect,21+ FileSystem,22+ Schema,23+ Stdio,24+} from "effect";25+26+/** The lock, relative to the repo root. */27+export const lockPath = "infra/.recording";28+29+/**30+ * The lock file deploy looks for and this command writes: the repo's own31+ * `lockPath` (beside this module), unless a test points it elsewhere.32+ */33+export const LockFile = Context.Reference<string>("infra/RecordingLockFile", {34+ defaultValue: () =>35+ decodeURIComponent(new URL(".recording", import.meta.url).pathname),36+});37+38+/** A take is being recorded: the lock file is there, so nothing deploys. */39+export class RecordingInProgress extends Schema.TaggedError<RecordingInProgress>()(40+ "RecordingInProgress",41+ { file: Schema.String }42+) {43+ override get message() {44+ return `${this.file} is there: a take is being recorded (H7), so nothing deploys until a person runs bun infra/recording.ts off`;45+ }46+}47+48+/** `recording` was given no command it knows. A usage error. */49+export class RecordingUsage extends Schema.TaggedError<RecordingUsage>()(50+ "RecordingUsage",51+ { given: Schema.String }52+) {53+ override get message() {54+ return `${this.given === "" ? "no command" : `${this.given} is no command`}: bun infra/recording.ts on | off | status`;55+ }56+}57+58+/** Whether the lock is on, as deploy and `status` read it. */59+const isOn = Effect.gen(function* () {60+ const fs = yield* FileSystem.FileSystem;61+62+ // A lock whose presence can't be read is no reason to deploy blind.63+ return yield* fs.exists(yield* LockFile).pipe(Effect.orDie);64+});65+66+/**67+ * Fails with `RecordingInProgress` while the lock is on: deploy's first68+ * step, before anything else it does.69+ */70+export const notRecording: Effect.Effect<71+ void,72+ RecordingInProgress,73+ FileSystem.FileSystem74+> = Effect.gen(function* () {75+ const file = yield* LockFile;76+77+ return yield* (yield* isOn)78+ ? Effect.fail(new RecordingInProgress({ file }))79+ : Effect.void;80+});81+82+/** `bun infra/recording.ts on | off | status`: turns the lock on or off, or says which it is. */83+export const recording = (84+ argv: readonly string[]85+): Effect.Effect<void, RecordingUsage, FileSystem.FileSystem> =>86+ Effect.gen(function* () {87+ const fs = yield* FileSystem.FileSystem;88+ const file = yield* LockFile;89+ const [command = ""] = argv;90+91+ if (command === "on") {92+ const since = DateTime.formatIso(yield* DateTime.now);93+94+ yield* fs95+ .writeFileString(96+ file,97+ `recording since ${since}; bun infra/recording.ts off lifts it\n`98+ )99+ .pipe(Effect.orDie);100+101+ return yield* Console.log(102+ `recording: on since ${since}; every deploy is refused until bun infra/recording.ts off`103+ );104+ }105+106+ if (command === "off") {107+ const was = yield* isOn;108+109+ yield* fs.remove(file, { force: true }).pipe(Effect.orDie);110+111+ return yield* Console.log(112+ was113+ ? "recording: off; deploys run again"114+ : "recording: off already; deploys run"115+ );116+ }117+118+ if (command === "status") {119+ return yield* Console.log(120+ (yield* isOn)121+ ? `recording: on (${(yield* fs.readFileString(file).pipe(Effect.orDie)).trim()})`122+ : "recording: off; deploys run"123+ );124+ }125+126+ return yield* new RecordingUsage({ given: command });127+ });128+129+if (import.meta.main) {130+ BunRuntime.runMain(131+ Effect.gen(function* () {132+ const args = yield* (yield* Stdio.Stdio).args;133+134+ return yield* recording(args);135+ }).pipe(Effect.provide(BunServices.layer))136+ );137+}modified:infra/stages.md+1 added-1 removed
112 unmodified lines113 | H3: the GitHub org and the public repo | Open, due before submission (Oct 14). | Every commit is on local `main`. No remote exists and nothing has been pushed. | Create the org and an empty public repo, then `git remote add origin …` and push. Before that, rotate the generated secrets (the H5 row). |114 | H4: a Google OAuth client | Not done, and optional. Sign-in works with platform accounts (a handle and a password). | The redirect URIs are in [section 6](#6-urls). Migrations `0003_identities.sql` and later are applied on both stages. | Only if Google sign-in is wanted: create a Web client with the stage's redirect URI, set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` together, then redeploy. |115 | H5: secret values | Done by the agent on both stages, under a recorded decision that extends generated secrets to `demo` (see [Secrets](#secrets)). Not blocking. | Five values per stage, generated and kept only in that stage's secrets file outside the repo (mode 600), never printed or committed. `SESSION_TOKENS` on `demo` holds bram, ines-v, okafor, okonkwo, lin-h and the swarm's six (wren, tamsin, ivo, marisol, dagny, pell). | **Rotate both stages' generated secrets before the repo goes public**, and keep a copy of each stage's `MASTER_KEY` somewhere other than this machine. Rotating `PASSWORD_PEPPER` breaks every stored password, rotating `MASTER_KEY` loses every stored env value unless they are re-wrapped first, and rotating `SESSION_TOKENS` means each CLI profile logs in again. |116 | H6: Workers Paid | Confirmed. | The account's subscriptions, read again on 2026-10-08, list `workers_paid` as Paid. The sandbox (containers) and both Workflows have run on `dev-oscabriel` since 2026-10-07. | Nothing. |117-| H7: the recording | Open (Oct 13). | `docs/demo/` holds the script, the shot list and the rehearsal checklist. The demo stage is bootstrapped. Its deploy, seed, rehearsal and a recording lock for deploys come next. | Record with no deploys during takes. |117+| H7: the recording | Open (Oct 13). | `docs/demo/` holds the script, the shot list and the rehearsal checklist. The demo stage is bootstrapped; its deploy, seed and rehearsal come next. The recording lock exists: while `infra/.recording` is there, `infra/deploy.ts` refuses every deploy. | Run `bun infra/recording.ts on` before the first take and `bun infra/recording.ts off` after the last (the rehearsal checklist says when). |118 | H8: submitting | Open, due Oct 14 by noon PDT. | Nothing yet. The demo URL comes after the demo's deploy (section 6). | Submit the repo URL, the video and the demo URL. |119 | H9: `docker login` | Not needed so far. No image pull has been rate-limited. | Nothing. | Only if a deploy's image pull is rate-limited: run `docker login` in your own terminal. |120 | OpenCode Zen key for the swarm's pell | Open. | pell is planned on `opencode/gemini-3.8-flash`. The fallback, a one-line swap to `opencode-go/qwen3.8-flash`, is recorded. | Add OpenCode Zen's key to pi, or accept the fallback. |121 | Deleting the throwaways | Open, after the rehearsal. | The teardown plan (section 4). | Read the teardown script and run it in your own terminal. |115 unmodified linesmodified:packages/config/test/deploy.test.ts+13 added-1 removed
18 unmodified lines19 NoStage,20 StepFailed,21 UnknownStage,22 } from "../../../infra/deploy.ts";23+import { LockFile } from "../../../infra/recording.ts";24 import { repoRoot } from "./root.ts";25 26 /** One command the deploy spawned, with its folder relative to the repo root. */27 interface Spawned {58 unmodified lines86 readonly env?: Readonly<Record<string, string>>;87 } = {}88 ) =>89 Effect.gen(function* () {90+ const fs = yield* FileSystem.FileSystem;91+ const path = yield* Path.Path;92 const fake = yield* recording(options.exitOf ?? (() => 0));93 94+ // A lock nobody wrote, so a take being recorded on this machine95+ // (`infra/.recording`) never decides these tests; recording.test.ts96+ // holds the lock itself.97+ const unlocked = path.join(98+ yield* fs.makeTempDirectoryScoped({ prefix: "deploy-unlocked-" }),99+ ".recording"100+ );101+102 const result = yield* deploy(argv).pipe(103 Effect.provide(fake.layer),104+ Effect.provideService(LockFile, unlocked),105 // Only what the test sets, whatever the shell running the tests has.106 Effect.provideService(107 ConfigProvider.ConfigProvider,108 ConfigProvider.fromEnv({ env: { ...options.env } })1 unmodified line110 Effect.result111 );112 113 return { result, spawned: yield* fake.spawned };102- }).pipe(Effect.provide(NodeServices.layer));114+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));115 116 /** A spawned command as one line: `apps/sandbox$ wrangler deploy --env x`. */117 const line = ({ args, command, cwd }: Spawned) =>118 `${cwd === "" ? "." : cwd}$ ${[command, ...args].join(" ")}`;347 unmodified linesadded:packages/config/test/recording.test.ts+235 added
1+/**2+ * The deploy lock for recording days (issue 806): `bun infra/recording.ts3+ * on` writes `infra/.recording`, and while it is there `infra/deploy.ts`4+ * refuses every deploy with `RecordingInProgress` before it spawns anything.5+ * `off` is the only way out.6+ */7+import { NodeServices } from "@effect/platform-node";8+import { describe, expect, it } from "@effect/vitest";9+import {10+ ConfigProvider,11+ Console,12+ Effect,13+ FileSystem,14+ Layer,15+ Path,16+ Ref,17+ Result,18+ Sink,19+ Stream,20+} from "effect";21+import { ChildProcess, ChildProcessSpawner } from "effect/process";22+23+import { deploy } from "../../../infra/deploy.ts";24+import {25+ LockFile,26+ lockPath,27+ recording,28+ RecordingInProgress,29+ RecordingUsage,30+} from "../../../infra/recording.ts";31+import { repoRoot } from "./root.ts";32+33+/**34+ * A spawner that runs nothing and exits 0: each command it was asked for,35+ * as `<folder>$ <command> <args>`, its folder relative to the repo root.36+ */37+const spawning = Effect.gen(function* () {38+ const path = yield* Path.Path;39+ const root = yield* repoRoot;40+ const lines = yield* Ref.make<readonly string[]>([]);41+42+ const spawner = ChildProcessSpawner.make((command) =>43+ Effect.gen(function* () {44+ if (!ChildProcess.isStandardCommand(command)) {45+ return yield* Effect.die("the deploy pipes no commands");46+ }47+48+ const cwd = path.relative(root, command.options.cwd ?? root);49+50+ yield* Ref.update(lines, (all) => [51+ ...all,52+ `${cwd === "" ? "." : cwd}$ ${[path.basename(command.command), ...command.args].join(" ")}`,53+ ]);54+55+ return ChildProcessSpawner.makeHandle({56+ all: Stream.empty,57+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),58+ getInputFd: () => Sink.drain,59+ getOutputFd: () => Stream.empty,60+ isRunning: Effect.succeed(false),61+ kill: () => Effect.void,62+ pid: ChildProcessSpawner.ProcessId(1),63+ stderr: Stream.empty,64+ stdin: Sink.drain,65+ stdout: Stream.empty,66+ unref: Effect.succeed(Effect.void),67+ });68+ })69+ );70+71+ return {72+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),73+ spawned: Ref.get(lines),74+ };75+});76+77+/** A temp root's lock file, `infra/.recording` under it, for one test's scope. */78+const tempLock = Effect.gen(function* () {79+ const fs = yield* FileSystem.FileSystem;80+ const path = yield* Path.Path;81+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "recording-806-" });82+83+ yield* fs.makeDirectory(path.join(root, "infra"));84+85+ return path.join(root, lockPath);86+});87+88+/** `deploy(argv)` with the lock at `lock`: how it ended, and what it spawned. */89+const deployed = (argv: readonly string[], lock: string) =>90+ Effect.gen(function* () {91+ const fake = yield* spawning;92+93+ const result = yield* deploy(argv).pipe(94+ Effect.provide(fake.layer),95+ Effect.provideService(LockFile, lock),96+ // No STAGE_SECRETS_FILE or PATH from the shell running the tests.97+ Effect.provideService(98+ ConfigProvider.ConfigProvider,99+ ConfigProvider.fromEnv({ env: {} })100+ ),101+ Effect.result102+ );103+104+ return { result, spawned: yield* fake.spawned };105+ });106+107+/** What `recording(argv)` prints, with the lock at `lock`. */108+const printedBy = (argv: readonly string[], lock: string) =>109+ Effect.gen(function* () {110+ const printed: string[] = [];111+112+ const captured: Console.Console = {113+ ...console,114+ log: (...args: readonly unknown[]) => {115+ printed.push(args.map(String).join(" "));116+ },117+ };118+119+ yield* recording(argv).pipe(120+ Effect.provideService(Console.Console, captured),121+ Effect.provideService(LockFile, lock)122+ );123+124+ return printed;125+ });126+127+describe("a deploy while a take is being recorded", () => {128+ it.live.each([129+ [["--stage", "dev-oscabriel"]],130+ [["--stage", "demo"]],131+ [[]],132+ ] as const)(133+ "is refused with RecordingInProgress for %j, naming the lock, before any step runs",134+ ([argv]) =>135+ Effect.gen(function* () {136+ const fs = yield* FileSystem.FileSystem;137+ const lock = yield* tempLock;138+139+ yield* fs.writeFileString(lock, "recording since a moment ago\n");140+141+ const { result, spawned } = yield* deployed(argv, lock);142+143+ expect(result).toStrictEqual(144+ Result.fail(new RecordingInProgress({ file: lock }))145+ );146+ expect(spawned).toStrictEqual([]);147+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))148+ );149+150+ it.effect("says what to run to lift it", () =>151+ Effect.sync(() => {152+ expect(new RecordingInProgress({ file: lockPath }).message).toBe(153+ "infra/.recording is there: a take is being recorded (H7), so nothing deploys until a person runs bun infra/recording.ts off"154+ );155+ })156+ );157+});158+159+describe("a deploy with no take being recorded", () => {160+ it.live("runs the same steps as ever when the lock is absent", () =>161+ Effect.gen(function* () {162+ const { result, spawned } = yield* deployed(163+ ["--stage", "dev-oscabriel"],164+ yield* tempLock165+ );166+167+ expect(Result.isSuccess(result)).toBeTruthy();168+ expect(spawned).toStrictEqual([169+ ".$ bun run verify",170+ "apps/sandbox$ wrangler deploy --env dev-oscabriel",171+ "apps/platform$ varlock-wrangler deploy --env dev-oscabriel",172+ "apps/web$ bun run build",173+ "apps/web$ wrangler deploy --env dev-oscabriel",174+ ".$ bun run bootstrap --stage dev-oscabriel --check-triggers",175+ ".$ bun scripts/smoke.ts --stage dev-oscabriel",176+ ]);177+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))178+ );179+});180+181+describe("bun infra/recording.ts", () => {182+ it.live(183+ "on writes the lock and refuses deploys; status says so; off removes it, and deploys run again",184+ () =>185+ Effect.gen(function* () {186+ const fs = yield* FileSystem.FileSystem;187+ const lock = yield* tempLock;188+ const before = yield* printedBy(["status"], lock);189+ const on = yield* printedBy(["on"], lock);190+ const held = yield* printedBy(["status"], lock);191+ const refused = yield* deployed(["--stage", "dev-oscabriel"], lock);192+ const off = yield* printedBy(["off"], lock);193+ const again = yield* printedBy(["off"], lock);194+ const after = yield* deployed(["--stage", "dev-oscabriel"], lock);195+196+ expect({197+ after: after.spawned.length,198+ again,199+ before,200+ held: held.map((line) => line.replace(/since \S+;/u, "since <t>;")),201+ lockGone: !(yield* fs.exists(lock)),202+ off,203+ on: on.map((line) => line.replace(/since \S+;/u, "since <t>;")),204+ refused: refused.result,205+ }).toStrictEqual({206+ after: 7,207+ again: ["recording: off already; deploys run"],208+ before: ["recording: off; deploys run"],209+ held: [210+ "recording: on (recording since <t>; bun infra/recording.ts off lifts it)",211+ ],212+ lockGone: true,213+ off: ["recording: off; deploys run again"],214+ on: [215+ "recording: on since <t>; every deploy is refused until bun infra/recording.ts off",216+ ],217+ refused: Result.fail(new RecordingInProgress({ file: lock })),218+ });219+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))220+ );221+222+ it.live("refuses a command it doesn't know, and changes nothing", () =>223+ Effect.gen(function* () {224+ const fs = yield* FileSystem.FileSystem;225+ const lock = yield* tempLock;226+227+ const failure = yield* Effect.flip(printedBy(["pause"], lock));228+229+ expect({ exists: yield* fs.exists(lock), failure }).toStrictEqual({230+ exists: false,231+ failure: new RecordingUsage({ given: "pause" }),232+ });233+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))234+ );235+});added:packages/config/test/seed-as.test.ts+254 added
1+/**2+ * `seed --as` (issue 806): a fresh copy of an example under another project3+ * name, so a live run (the swarm's rehearsal) can take a family nobody has4+ * touched while the original stays fresh for the recording. A name some5+ * project already has is refused, and a copy on a stage is written to the6+ * throwaway ledger for teardown.7+ */8+import { NodeServices } from "@effect/platform-node";9+import { describe, expect, it } from "@effect/vitest";10+import { Console, DateTime, Effect, FileSystem, Layer, Path } from "effect";11+12+import { LedgerFile, readLedger } from "../../../infra/created.ts";13+import {14+ planSeed,15+ renameSeedPlan,16+ runSeed,17+ SeedTarget,18+ worldTarget,19+} from "../../../scripts/lib/seed.ts";20+import { main, optionsOf, recordCopy } from "../../../scripts/seed.ts";21+import { Client } from "../../protocol/src/contracts.ts";22+import { ProjectName } from "../../protocol/src/ids.ts";23+import { ProjectExists } from "../../protocol/src/refusal.ts";24+25+const swarmCopy = ProjectName.make("burrow-swarm-2");26+27+describe(renameSeedPlan, () => {28+ it.effect(29+ "renames burrow's project and keeps everything else: its decider, main's first files, its ratchet and every ask",30+ () =>31+ Effect.gen(function* () {32+ const plan = yield* planSeed("examples/burrow");33+ const copy = renameSeedPlan(plan, swarmCopy);34+35+ expect({36+ asks: copy.asks,37+ copyOf: copy.copyOf,38+ decider: copy.decider,39+ initFiles: copy.initFiles,40+ layers: copy.layers,41+ project: copy.project,42+ ratchets: copy.ratchets,43+ }).toStrictEqual({44+ asks: plan.asks,45+ copyOf: "burrow",46+ decider: "okafor",47+ initFiles: plan.initFiles,48+ layers: [],49+ project: "burrow-swarm-2",50+ ratchets: ["no-module-level-mutable-state"],51+ });52+ }).pipe(Effect.provide(NodeServices.layer))53+ );54+55+ it.effect(56+ "names each layer's repo for the copy, keeping the layer's files and known-bad commits",57+ () =>58+ Effect.gen(function* () {59+ const plan = yield* planSeed("examples/datekit");60+61+ const copy = renameSeedPlan(62+ renameSeedPlan(plan, ProjectName.make("datekit-copy")),63+ ProjectName.make("datekit-copy-2")64+ );65+66+ expect(67+ copy.layers.map(({ files, knownBad, layer, repo }) => ({68+ files: files.length,69+ knownBad: knownBad.map(({ commit }) => commit),70+ layer,71+ repo,72+ }))73+ ).toStrictEqual(74+ plan.layers.map(({ files, knownBad, layer }) => ({75+ files: files.length,76+ knownBad: knownBad.map(({ commit }) => commit),77+ layer,78+ repo: `datekit-copy-2--${layer}`,79+ }))80+ );81+82+ // A copy of a copy is still a copy of the example.83+ expect(copy.copyOf).toBe("datekit");84+ }).pipe(Effect.provide(NodeServices.layer))85+ );86+});87+88+describe("runSeed, for a copy", () => {89+ it.live(90+ "refuses a name some project already has, with ProjectExists, and pushes nothing to it",91+ () =>92+ Effect.gen(function* () {93+ const plan = yield* planSeed("examples/burrow");94+ const taken = ProjectName.make("burrow-taken");95+96+ const { failure, refs } = yield* Effect.gen(function* () {97+ const target = yield* SeedTarget;98+99+ yield* Client.use((client) =>100+ client.initProject({ project: taken })101+ ).pipe(Effect.provide(target.clientFor(target.operator)));102+103+ const stopped = yield* Effect.flip(104+ runSeed(renameSeedPlan(plan, taken))105+ );106+107+ return { failure: stopped, refs: yield* target.refsOf(taken) };108+ }).pipe(109+ Effect.provide(110+ worldTarget([plan.decider]).pipe(Layer.provide(NodeServices.layer))111+ )112+ );113+114+ expect({115+ reason: failure.reason,116+ refs: refs.size,117+ refusals: failure.refusals,118+ }).toStrictEqual({119+ reason:120+ "burrow-taken is taken: --as makes a fresh copy of burrow, so name a project nobody has",121+ refs: 0,122+ refusals: [new ProjectExists({ project: taken })],123+ });124+ }).pipe(Effect.provide(NodeServices.layer)),125+ 60_000126+ );127+});128+129+/** What `main` prints, line by line. */130+const printedBy = (argv: readonly string[]) =>131+ Effect.gen(function* () {132+ const printed: string[] = [];133+134+ const captured: Console.Console = {135+ ...console,136+ log: (...args: readonly unknown[]) => {137+ printed.push(args.map(String).join(" "));138+ },139+ };140+141+ yield* main(argv).pipe(Effect.provideService(Console.Console, captured));142+143+ return printed;144+ }).pipe(Effect.provide(NodeServices.layer));145+146+describe("bun scripts/seed.ts --as", () => {147+ it.live(148+ "seeds datekit as datekit-copy on the Node world, its asks red first and its layer in the copy's own repo",149+ () =>150+ Effect.gen(function* () {151+ const printed = yield* printedBy([152+ "--world",153+ "node",154+ "--only",155+ "datekit",156+ "--as",157+ "datekit-copy",158+ ]);159+160+ expect(printed.slice(0, 7)).toStrictEqual([161+ "seed: datekit-copy (a copy of datekit) on the Node world",162+ "Init datekit-copy: done",163+ "Push datekit-copy: done",164+ "OpenAsk datekit-copy/add-months-clamp: done",165+ "OpenAsk datekit-copy/format-ordinal: done",166+ "OpenAsk datekit-copy/parse-iso-week: done",167+ "Layer datekit-copy--maintainers: done",168+ ]);169+ }),170+ 120_000171+ );172+});173+174+describe("optionsOf, with --as", () => {175+ it.effect("reads the copy's name beside the one example it copies", () =>176+ Effect.map(177+ optionsOf([178+ "--world",179+ "node",180+ "--only",181+ "burrow",182+ "--as",183+ "burrow-swarm-2",184+ ]),185+ (options) => {186+ expect({ as: options.as, only: options.only }).toStrictEqual({187+ as: "burrow-swarm-2",188+ only: "burrow",189+ });190+ }191+ )192+ );193+194+ it.effect.each([195+ [["--world", "node", "--as", "burrow-swarm-2"], "--only"],196+ [["--world", "node", "--only", "burrow", "--as", "Burrow 2"], "Burrow 2"],197+ [["--world", "node", "--only", "burrow", "--as", "burrow"], "burrow"],198+ ] as const)("refuses %j, saying %s", ([argv, said]) =>199+ Effect.map(Effect.flip(optionsOf(argv)), (failure) => {200+ expect(failure.reason).toContain(said);201+ })202+ );203+});204+205+describe(recordCopy, () => {206+ it.live(207+ "writes the copy's project, its repo and each layer's repo to the ledger, by the seed",208+ () =>209+ Effect.gen(function* () {210+ const fs = yield* FileSystem.FileSystem;211+ const path = yield* Path.Path;212+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "seed-as-" });213+ const ledger = path.join(dir, "created.jsonl");214+ const plan = yield* planSeed("examples/datekit");215+ const at = DateTime.makeUnsafe("2026-10-13T09:00:00Z");216+217+ const written = yield* Effect.gen(function* () {218+ yield* recordCopy(219+ "dev-oscabriel",220+ renameSeedPlan(plan, ProjectName.make("datekit-copy")),221+ at222+ );223+224+ return yield* readLedger;225+ }).pipe(Effect.provideService(LedgerFile, ledger));226+227+ expect(written).toStrictEqual([228+ {229+ at,230+ by: "seed",231+ kind: "project",232+ name: "datekit-copy",233+ stage: "dev-oscabriel",234+ },235+ {236+ at,237+ by: "seed",238+ kind: "repo",239+ name: "datekit-copy",240+ namespace: "projects-dev-oscabriel",241+ stage: "dev-oscabriel",242+ },243+ {244+ at,245+ by: "seed",246+ kind: "repo",247+ name: "datekit-copy--maintainers",248+ namespace: "layers-dev-oscabriel",249+ stage: "dev-oscabriel",250+ },251+ ]);252+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))253+ );254+});added:packages/config/test/smoke-loop.test.ts+264 added
1+/**2+ * smoke's core loop (issue 806): `bun scripts/smoke.ts --stage <s> --loop`3+ * makes a throwaway project, opens an ask red first, claims it, pushes an4+ * answer that reaches outside the ask's territory and hears `OutOfScope`5+ * in git's own output, pushes the fix, and reads back its landing and its6+ * verdict note, all through the CLI and git as a person would. Here it runs7+ * against the Node world (`apps/platform/test/serve-world.ts`), reached8+ * over HTTP and git as a stage is.9+ */10+import { NodeServices } from "@effect/platform-node";11+import { describe, expect, it } from "@effect/vitest";12+import {13+ Effect,14+ FileSystem,15+ Layer,16+ Path,17+ Redacted,18+ Ref,19+ Result,20+ Sink,21+ Stream,22+} from "effect";23+import { FetchHttpClient } from "effect/http";24+import { ChildProcess, ChildProcessSpawner } from "effect/process";25+26+import { LedgerFile, readLedger } from "../../../infra/created.ts";27+import { servedWorld } from "../../../scripts/lib/seed.ts";28+import {29+ DemoStageRefused,30+ smokeLoop,31+} from "../../../scripts/lib/smoke/loop.ts";32+import { main } from "../../../scripts/smoke.ts";33+import { Brand } from "../../brand/src/index.ts";34+import { Handle } from "../../protocol/src/ids.ts";35+36+const decider = Handle.make("ines-v");37+38+const answerer = Handle.make("bram");39+40+/** Each person's token in the world: no secret, it never leaves this machine. */41+const tokens = {42+ answerer: Redacted.make("bram-smoke-loop-world-token-0123456789abcdef"),43+ decider: Redacted.make("ines-v-smoke-loop-world-token-0123456789abcd"),44+};45+46+/** A person in a trailer: their handle and the address the platform gives them. */47+const credited = (handle: string) =>48+ `${handle} <${handle}@users.${Brand.domain}>`;49+50+/** All a byte stream says, as text. */51+const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>52+ bytes.pipe(Stream.decodeText(), Stream.mkString);53+54+/** `git ls-remote <remote> <ref>` as anyone, with no credential at all. */55+const anonymousTip = (remote: string, ref: string) =>56+ Effect.scoped(57+ Effect.gen(function* () {58+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;59+60+ const child = yield* spawner.spawn(61+ ChildProcess.make("git", ["ls-remote", remote, ref], {62+ env: {63+ GIT_CONFIG_GLOBAL: "/dev/null",64+ GIT_CONFIG_NOSYSTEM: "1",65+ GIT_TERMINAL_PROMPT: "0",66+ },67+ extendEnv: true,68+ })69+ );70+71+ const [listed] = yield* Effect.all(72+ [textOf(child.stdout), child.exitCode],73+ { concurrency: "unbounded" }74+ );75+76+ return listed.split("\t")[0] ?? "";77+ })78+ );79+80+describe("smokeLoop, against the Node world", () => {81+ it.live(82+ "opens an ask red first, hears OutOfScope from git, lands the fix with its author, committer and trailers, finds the verdict note, and writes its throwaways to the ledger",83+ () =>84+ Effect.gen(function* () {85+ const fs = yield* FileSystem.FileSystem;86+ const path = yield* Path.Path;87+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "smoke-806-" });88+ const ledger = path.join(dir, "created.jsonl");89+90+ const { main: tip, report } = yield* Effect.scoped(91+ Effect.gen(function* () {92+ const origin = yield* servedWorld(93+ new Map([94+ [decider, tokens.decider],95+ [answerer, tokens.answerer],96+ ])97+ );98+99+ const ran = yield* smokeLoop({100+ answerer: tokens.answerer,101+ decider: tokens.decider,102+ origin,103+ run: "r1",104+ stage: "node",105+ });106+107+ return {108+ main: yield* anonymousTip(109+ `${origin}/${ran.project}.git`,110+ "refs/heads/main"111+ ),112+ report: ran,113+ };114+ })115+ ).pipe(Effect.provideService(LedgerFile, ledger));116+117+ expect({118+ author: report.author,119+ committer: report.committer,120+ landed: report.landed,121+ noteFound: report.noteFound,122+ project: report.project,123+ refusedWith: report.refusedWith,124+ steps: report.timings.map(({ step }) => step),125+ timed: report.timings.every(({ ms }) => ms >= 0),126+ trailers: report.trailers.filter((trailer) =>127+ /^(?:Asked-by|Signed-off-by):/u.test(trailer)128+ ),129+ }).toStrictEqual({130+ author: "bram",131+ committer: Brand.name,132+ landed: tip,133+ noteFound: true,134+ project: "smoke-r1",135+ refusedWith: ["OutOfScope"],136+ steps: [137+ "people",138+ "init",139+ "open-ask",140+ "claim",141+ "out-of-scope",142+ "answer",143+ "landing",144+ "verdict-note",145+ ],146+ timed: true,147+ trailers: [148+ `Asked-by: ${credited("ines-v")}`,149+ `Signed-off-by: ${credited("bram")}`,150+ ],151+ });152+153+ expect(154+ (yield* readLedger.pipe(155+ Effect.provideService(LedgerFile, ledger)156+ )).map(({ by, kind, name, stage }) => ({ by, kind, name, stage }))157+ ).toStrictEqual([158+ { by: "smoke", kind: "project", name: "smoke-r1", stage: "node" },159+ { by: "smoke", kind: "repo", name: "smoke-r1", stage: "node" },160+ {161+ by: "smoke",162+ kind: "repo",163+ name: "smoke-r1--parse-year--bram",164+ stage: "node",165+ },166+ ]);167+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),168+ 240_000169+ );170+});171+172+/**173+ * A spawner that runs nothing: each command it was asked for, by name. Any174+ * command fails, so a run that reached one could not pass by accident.175+ */176+const refusing = Effect.gen(function* () {177+ const asked = yield* Ref.make<readonly string[]>([]);178+179+ const spawner = ChildProcessSpawner.make((command) =>180+ Effect.gen(function* () {181+ yield* Ref.update(asked, (all) => [182+ ...all,183+ ChildProcess.isStandardCommand(command) ? command.command : "a pipe",184+ ]);185+186+ return ChildProcessSpawner.makeHandle({187+ all: Stream.empty,188+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),189+ getInputFd: () => Sink.drain,190+ getOutputFd: () => Stream.empty,191+ isRunning: Effect.succeed(false),192+ kill: () => Effect.void,193+ pid: ChildProcessSpawner.ProcessId(1),194+ stderr: Stream.empty,195+ stdin: Sink.drain,196+ stdout: Stream.empty,197+ unref: Effect.succeed(Effect.void),198+ });199+ })200+ );201+202+ return {203+ asked: Ref.get(asked),204+ layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),205+ };206+});207+208+describe("smoke --loop on demo", () => {209+ it.live(210+ "is refused with DemoStageRefused before any request or process: a throwaway project would show on demo's front page",211+ () =>212+ Effect.gen(function* () {213+ const fetched: string[] = [];214+ const spawner = yield* refusing;215+216+ const result = yield* main(["--stage", "demo", "--loop"]).pipe(217+ Effect.provide(spawner.layer),218+ Effect.provideService(FetchHttpClient.Fetch, (input) => {219+ fetched.push(new Request(input).url);220+221+ return Promise.reject(new Error("smoke --loop on demo fetched"));222+ }),223+ Effect.result224+ );225+226+ expect({227+ fetched,228+ result,229+ spawned: yield* spawner.asked,230+ }).toStrictEqual({231+ fetched: [],232+ result: Result.fail(new DemoStageRefused({ stage: "demo" })),233+ spawned: [],234+ });235+ }).pipe(Effect.provide(NodeServices.layer))236+ );237+238+ it.live("is refused by smokeLoop itself, whoever calls it", () =>239+ Effect.gen(function* () {240+ const spawner = yield* refusing;241+242+ const failure = yield* Effect.flip(243+ smokeLoop({244+ answerer: tokens.answerer,245+ decider: tokens.decider,246+ origin: "https://platform-demo.example.workers.dev",247+ run: "r1",248+ stage: "demo",249+ })250+ ).pipe(Effect.provide(spawner.layer));251+252+ expect({253+ failure,254+ message: failure.message,255+ spawned: yield* spawner.asked,256+ }).toStrictEqual({257+ failure: new DemoStageRefused({ stage: "demo" }),258+ message:259+ "--loop makes a throwaway project, which would show on demo's front page: run it on a dev stage",260+ spawned: [],261+ });262+ }).pipe(Effect.provide(NodeServices.layer))263+ );264+});added:scripts/lib/smoke/core-loop.ts+808 added
1+/**2+ * The core loop's steps, as smoke's `--loop` takes them on a platform (spec3+ * §5 steps 1, 3, 4, 6–8 and 10): each one through the CLI (this repo's, run4+ * from source with Bun) or git, as a person would, with the person's5+ * platform token only in their processes' env, and git's credential helper6+ * the CLI itself.7+ *8+ * The project is a fixture made here: one source file, a config folder that9+ * runs `bun test {path}` and vouches for the answerer, and one ask whose10+ * check fails on main by an assertion. The answer reaches outside the ask's11+ * territory first (the README), then puts the README back.12+ *13+ * Every step fails with `LoopFailed`, naming the step and what went wrong in14+ * words a person reads, never a token.15+ */16+import { Brand } from "@repo/brand";17+import { AnswerView } from "@repo/protocol/domain/answer";18+import { Ask } from "@repo/protocol/domain/ask";19+import { ClaimView } from "@repo/protocol/domain/claim";20+import { Outcome } from "@repo/protocol/domain/outcome";21+import { Envelope } from "@repo/protocol/envelope";22+import { AskId, CommitSha, Handle, LandedSha } from "@repo/protocol/ids";23+import type { ProjectName } from "@repo/protocol/ids";24+import { explain } from "@repo/protocol/render";25+import {26+ Array,27+ Config,28+ Duration,29+ Effect,30+ FileSystem,31+ Option,32+ Redacted,33+ Schedule,34+ Schema,35+ Stream,36+} from "effect";37+import { ChildProcess, ChildProcessSpawner } from "effect/process";38+39+import { cliEntry, personEnv } from "../swarm/workspace.ts";40+41+/** The loop's steps, in the order it takes them. */42+export const LoopStep = Schema.Literals([43+ "people",44+ "init",45+ "open-ask",46+ "claim",47+ "out-of-scope",48+ "answer",49+ "landing",50+ "verdict-note",51+]);52+53+export type LoopStep = typeof LoopStep.Type;54+55+/** A step of the loop went wrong: which, and why. Never holds a token. */56+export class LoopFailed extends Schema.TaggedError<LoopFailed>()("LoopFailed", {57+ reason: Schema.String,58+ step: LoopStep,59+}) {60+ override get message() {61+ return `${this.step}: ${this.reason}`;62+ }63+}64+65+// ------------------------------------------------------------ the fixture66+67+/** Where the config folder's sdk is imported from, as a maintainer writes it. */68+const sdk = `${Brand.cliPackage}/rules`;69+70+/** The ask the loop opens and answers. */71+export const ASK = AskId.make("parse-year");72+73+/** The one file the ask's territory holds. */74+const SOURCE = "src/parse.ts";75+76+/** The ask's check: the file its kind runs. */77+const CHECK = `test/${ASK}.test.ts`;78+79+const README =80+ "A throwaway project smoke's core loop makes, answers and lands.\n";81+82+/** The project as its decider first pushes it, the answerer vouched for. */83+const startFiles = (answerer: Handle) => ({84+ [`${Brand.configDir}/project.ts`]: [85+ `import { kinds, project } from "${sdk}";`,86+ "",87+ "export default project({",88+ " kinds: [kinds.fix],",89+ ' run: { checks: {}, test: "bun test {path}" },',90+ "});",91+ "",92+ ].join("\n"),93+ [`${Brand.configDir}/vouched.td`]: `${answerer}\n`,94+ "README.md": README,95+ "package.json": '{ "name": "smoke", "private": true }\n',96+ [SOURCE]: "export const parse = (iso: string) => ({ iso, year: 0 });\n",97+});98+99+/** The ask's own files: its file in the config folder, and its check, which asserts. */100+const askFiles = [101+ {102+ content: [103+ `import { kinds, territory } from "${sdk}";`,104+ "",105+ "export default kinds.fix.ask({",106+ ` path: "${CHECK}",`,107+ ` territory: territory.paths("${SOURCE}"),`,108+ ' want: "parse reads the year of an ISO date",',109+ "});",110+ "",111+ ].join("\n"),112+ path: `${Brand.configDir}/asks/${ASK}.ask.ts`,113+ },114+ {115+ content: [116+ 'import { expect, it } from "bun:test";',117+ "",118+ `import { parse } from "../${SOURCE}";`,119+ "",120+ 'it("parse reads the year of an ISO date", () => {',121+ ' expect(parse("2026-10-13").year).toBe(2026);',122+ "});",123+ "",124+ ].join("\n"),125+ path: CHECK,126+ },127+] as const;128+129+/** The answer: the year, read. */130+const yearRead =131+ "export const parse = (iso: string) => ({ iso, year: Number(iso.slice(0, 4)) });\n";132+133+// --------------------------------------------------------------- processes134+135+/** How a process ended, and what it printed. */136+interface Ran {137+ readonly code: number;138+ readonly stdout: string;139+ readonly stderr: string;140+}141+142+/** The longest one command may take: a cold Checker runs an ask's check twice. */143+const PATIENCE = Duration.minutes(10);144+145+/** One person the loop acts as. */146+export interface LoopPerson {147+ readonly handle: Handle;148+ /** Their folder: the CLI's config, their gitconfig, git's credential helper. */149+ readonly home: string;150+ /** The env their CLI and git run in: their token, the platform, their gitconfig. */151+ readonly env: Readonly<Record<string, string | undefined>>;152+ /** Their token, blanked out of anything the loop says. */153+ readonly token: Redacted.Redacted;154+}155+156+const failed = (step: LoopStep, reason: string) =>157+ new LoopFailed({ reason, step });158+159+/** `text` with each of `tokens` blanked out. */160+const scrubbed = (text: string, tokens: readonly Redacted.Redacted[]) => {161+ let clean = text;162+163+ for (const token of tokens) {164+ clean = clean.replaceAll(Redacted.value(token), "<redacted>");165+ }166+167+ return clean;168+};169+170+/** All a byte stream says, as text. */171+const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>172+ bytes.pipe(Stream.decodeText(), Stream.mkString);173+174+/** `command args` in `cwd` as `person`: how it ended, and what it printed. */175+const run = (176+ step: LoopStep,177+ person: Pick<LoopPerson, "env" | "token">,178+ command: string,179+ args: readonly string[],180+ cwd?: string181+): Effect.Effect<Ran, LoopFailed, ChildProcessSpawner.ChildProcessSpawner> =>182+ Effect.scoped(183+ Effect.gen(function* () {184+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;185+186+ const child = yield* spawner.spawn(187+ ChildProcess.make(command, args, {188+ cwd,189+ env: { ...person.env },190+ extendEnv: true,191+ stdin: "ignore",192+ })193+ );194+195+ const [stdout, stderr, code] = yield* Effect.all(196+ [textOf(child.stdout), textOf(child.stderr), child.exitCode],197+ { concurrency: "unbounded" }198+ );199+200+ return { code: Number(code), stderr, stdout };201+ })202+ ).pipe(203+ Effect.mapError(({ message }) =>204+ failed(205+ step,206+ `${command} didn't run: ${scrubbed(message, [person.token])}`207+ )208+ ),209+ Effect.timeoutOrElse({210+ duration: PATIENCE,211+ orElse: () =>212+ Effect.fail(213+ failed(214+ step,215+ `${command} ${args[0] ?? ""} took longer than ${Duration.format(PATIENCE)}`216+ )217+ ),218+ })219+ );220+221+/** git as `person` in `cwd`, which must succeed; what it printed. */222+const gitOk = (223+ step: LoopStep,224+ person: LoopPerson,225+ cwd: string,226+ args: readonly string[]227+) =>228+ Effect.flatMap(run(step, person, "git", args, cwd), (ran) =>229+ ran.code === 0230+ ? Effect.succeed(ran.stdout.trim())231+ : Effect.fail(232+ failed(233+ step,234+ scrubbed(235+ `git ${args.join(" ")} exited ${ran.code}: ${ran.stderr.trim()}`,236+ [person.token]237+ )238+ )239+ )240+ );241+242+/**243+ * One CLI command as `person`, with `--json`: its data, decoded by `data`.244+ * A refusal fails the step with what the platform said, as `explain` says245+ * it everywhere; output that is no envelope fails it with what the command246+ * printed.247+ */248+const cli = <A, I>(249+ step: LoopStep,250+ person: Pick<LoopPerson, "env" | "token">,251+ args: readonly string[],252+ data: Schema.Codec<A, I>,253+ cwd?: string254+) =>255+ Effect.gen(function* () {256+ const ran = yield* run(257+ step,258+ person,259+ "bun",260+ [cliEntry, ...args, "--json"],261+ cwd262+ );263+264+ const said = scrubbed(265+ (ran.stderr.trim() === "" ? ran.stdout : ran.stderr).trim().slice(0, 800),266+ [person.token]267+ );268+269+ const envelope = yield* Schema.decodeEffect(270+ Schema.fromJsonString(Envelope(data))271+ )(ran.stdout.trim()).pipe(272+ Effect.mapError(() =>273+ failed(274+ step,275+ `${Brand.cli} ${args.join(" ")} exited ${ran.code} without its JSON: ${said}`276+ )277+ )278+ );279+280+ return envelope.ok281+ ? envelope.data282+ : yield* failed(283+ step,284+ `${Brand.cli} ${args[0] ?? ""} was refused: ${explain(285+ envelope.refusals286+ )287+ .map((line) => line.trim())288+ .join("; ")}`289+ );290+ });291+292+// ----------------------------------------------------------------- people293+294+/**295+ * git's credential helper for a person: this repo's CLI from source, as296+ * `git-credential-<slug>`, which hands git the token in the env.297+ */298+const helperShim = [299+ "#!/bin/sh",300+ `# ${Brand.gitCredentialHelper} for smoke's core loop: this repo's CLI from source, under Bun.`,301+ `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' credential "$@"`,302+ "",303+].join("\n");304+305+/** A shim runs for everyone; only its owner writes it. */306+const SHIM_MODE = 0o755;307+308+/** A person's folder holds the CLI's config: owner only. */309+const HOME_MODE = 0o700;310+311+/**312+ * A person at `home` on the platform at `origin`, holding `token`: their313+ * folder, with git's credential helper on `PATH` and a gitconfig of their314+ * own (their name, and the helper for the platform), so nothing of this315+ * machine's git or CLI config answers instead. Their handle is whoever the316+ * platform says the token names (`status`).317+ */318+export const personAt = (input: {319+ readonly home: string;320+ readonly origin: string;321+ readonly token: Redacted.Redacted;322+}): Effect.Effect<323+ LoopPerson,324+ LoopFailed,325+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem326+> =>327+ Effect.gen(function* () {328+ const fs = yield* FileSystem.FileSystem;329+ const { home, origin, token } = input;330+ const bin = `${home}/bin`;331+ const gitconfig = `${home}/gitconfig`;332+333+ yield* Effect.gen(function* () {334+ yield* fs.makeDirectory(`${home}/config`, {335+ mode: HOME_MODE,336+ recursive: true,337+ });338+ yield* fs.makeDirectory(bin, { recursive: true });339+340+ const helper = `${bin}/${Brand.gitCredentialHelper}`;341+342+ yield* fs.writeFileString(helper, helperShim, { mode: SHIM_MODE });343+ yield* fs.chmod(helper, SHIM_MODE);344+ }).pipe(345+ Effect.mapError(({ message }) =>346+ failed("people", `a person's folder: ${message}`)347+ )348+ );349+350+ const path = yield* Config.String("PATH").pipe(351+ Config.withDefault(""),352+ Effect.orElseSucceed(() => "")353+ );354+355+ const env = {356+ ...personEnv({357+ configHome: `${home}/config`,358+ platformUrl: origin,359+ token,360+ }),361+ [`${Brand.slug.toUpperCase()}_PROFILE`]: undefined,362+ GIT_CONFIG_GLOBAL: gitconfig,363+ GIT_CONFIG_NOSYSTEM: "1",364+ GIT_EDITOR: ":",365+ GIT_TERMINAL_PROMPT: "0",366+ PATH: path === "" ? bin : `${bin}:${path}`,367+ };368+369+ const { handle } = yield* cli(370+ "people",371+ { env, token },372+ ["status"],373+ Schema.Struct({ handle: Handle })374+ );375+376+ yield* fs377+ .writeFileString(378+ gitconfig,379+ [380+ "[user]",381+ `\tname = ${handle}`,382+ `\temail = ${handle}@example.com`,383+ "[commit]",384+ "\tgpgsign = false",385+ `[credential "${origin}"]`,386+ "\thelper =",387+ `\thelper = ${Brand.slug}`,388+ "\tuseHttpPath = true",389+ "",390+ ].join("\n")391+ )392+ .pipe(393+ Effect.mapError(({ message }) =>394+ failed("people", `${handle}'s gitconfig: ${message}`)395+ )396+ );397+398+ return { env, handle, home, token };399+ });400+401+// ------------------------------------------------------------------ steps402+403+/** `files` written under `dir`, each at its path. */404+const writeFiles = (405+ step: LoopStep,406+ dir: string,407+ files: Readonly<Record<string, string>>408+) =>409+ Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>410+ Effect.forEach(411+ Object.entries(files),412+ ([path, content]) =>413+ Effect.gen(function* () {414+ const at = `${dir}/${path}`;415+416+ yield* fs.makeDirectory(at.slice(0, at.lastIndexOf("/")), {417+ recursive: true,418+ });419+ yield* fs.writeFileString(at, content);420+ }).pipe(421+ Effect.mapError(({ message }) =>422+ failed(step, `writing ${path}: ${message}`)423+ )424+ ),425+ { discard: true }426+ )427+ );428+429+/** `files` written in the work tree at `cwd` and committed as `person`; the commit. */430+const commit = (431+ step: LoopStep,432+ person: LoopPerson,433+ cwd: string,434+ message: string,435+ files: Readonly<Record<string, string>>436+) =>437+ Effect.gen(function* () {438+ yield* writeFiles(step, cwd, files);439+ yield* gitOk(step, person, cwd, ["add", "--all"]);440+ yield* gitOk(step, person, cwd, [441+ "commit",442+ "--quiet",443+ "--message",444+ message,445+ ]);446+447+ return CommitSha.make(448+ yield* gitOk(step, person, cwd, ["rev-parse", "HEAD"])449+ );450+ });451+452+const Inited = Schema.Struct({453+ pushed: Schema.Boolean,454+ remote: Schema.NonEmptyString,455+});456+457+/**458+ * Makes `project` from the fixture, as `decider`: a repo of its first files459+ * at `dir`, then `<cli> init`, which makes the project, wires its remote460+ * and pushes main's first commit.461+ */462+export const initProject = (input: {463+ readonly decider: LoopPerson;464+ readonly answerer: Handle;465+ readonly project: ProjectName;466+ readonly dir: string;467+}) =>468+ Effect.gen(function* () {469+ const { decider, dir, project } = input;470+471+ yield* writeFiles("init", dir, startFiles(input.answerer));472+ yield* gitOk("init", decider, dir, [473+ "init",474+ "--quiet",475+ "--initial-branch=main",476+ ]);477+ yield* gitOk("init", decider, dir, ["add", "--all"]);478+ yield* gitOk("init", decider, dir, [479+ "commit",480+ "--quiet",481+ "--message",482+ `Start ${project}`,483+ ]);484+485+ const made = yield* cli(486+ "init",487+ decider,488+ ["init", "--project", project, "--yes"],489+ Inited,490+ dir491+ );492+493+ return made.pushed494+ ? made495+ : yield* failed(496+ "init",497+ `${Brand.cli} init made ${project} but pushed nothing`498+ );499+ });500+501+const Opened = Schema.Struct({ ask: Ask, landed: LandedSha });502+503+/** Opens the fixture's ask as `decider`: its check fails on main twice the same way first. */504+export const openAsk = (decider: LoopPerson, project: ProjectName) =>505+ cli(506+ "open-ask",507+ decider,508+ [509+ "ask",510+ "open",511+ ASK,512+ "--project",513+ project,514+ "--files",515+ JSON.stringify(askFiles),516+ "--yes",517+ ],518+ Opened519+ );520+521+const Claimed = Schema.Struct({ claim: ClaimView });522+523+/** Claims the fixture's ask as `answerer`: their fork, and where it lives. */524+export const claimAsk = (answerer: LoopPerson, project: ProjectName) =>525+ Effect.map(526+ cli("claim", answerer, ["claim", ASK, "--project", project], Claimed),527+ ({ claim }) => claim528+ );529+530+// Each refusal's first line among git's `remote:` lines, as `render` writes531+// it: `remote: OutOfScope: …`.532+const REFUSAL_LINE = /^remote: (?<tag>[A-Z][A-Za-z]+): /gmu;533+534+/** The refusals' tags git printed from the platform, in order. */535+export const refusalTags = (stderr: string): readonly string[] =>536+ [...stderr.matchAll(REFUSAL_LINE)].flatMap(({ groups }) =>537+ groups?.tag === undefined ? [] : [groups.tag]538+ );539+540+/**541+ * Clones the claim's fork as `answerer` into `dir`, and pushes an answer542+ * that reaches outside the ask's territory (the README besides the source):543+ * git must refuse it, `OutOfScope` among the platform's words. Gives every544+ * refusal git printed.545+ */546+export const pushOutOfScope = (input: {547+ readonly answerer: LoopPerson;548+ readonly claim: ClaimView;549+ readonly dir: string;550+}) =>551+ Effect.gen(function* () {552+ const { answerer, claim, dir } = input;553+554+ yield* gitOk("out-of-scope", answerer, answerer.home, [555+ "clone",556+ "--quiet",557+ claim.remote,558+ dir,559+ ]);560+561+ yield* commit("out-of-scope", answerer, dir, "Read the year, and say so", {562+ "README.md": `${README}It reads years now.\n`,563+ [SOURCE]: yearRead,564+ });565+566+ const pushed = yield* run(567+ "out-of-scope",568+ answerer,569+ "git",570+ ["push", "origin", "HEAD:main"],571+ dir572+ );573+574+ const tags = refusalTags(pushed.stderr);575+576+ return pushed.code !== 0 && tags.includes("OutOfScope")577+ ? tags578+ : yield* failed(579+ "out-of-scope",580+ scrubbed(581+ `a push outside ${ASK}'s territory exited ${pushed.code}${tags.length === 0 ? " with no refusal" : `, refused ${tags.join(", ")}`}, not OutOfScope: ${pushed.stderr.trim()}`,582+ [answerer.token]583+ )584+ );585+ });586+587+/** Puts the README back and pushes again: the answer is taken, and checked. */588+export const pushAnswer = (answerer: LoopPerson, dir: string) =>589+ Effect.gen(function* () {590+ const head = yield* commit(591+ "answer",592+ answerer,593+ dir,594+ "Leave the readme alone",595+ {596+ "README.md": README,597+ }598+ );599+600+ const pushed = yield* run(601+ "answer",602+ answerer,603+ "git",604+ ["push", "origin", "HEAD:main"],605+ dir606+ );607+608+ return pushed.code === 0609+ ? head610+ : yield* failed(611+ "answer",612+ scrubbed(613+ `the fixed answer's push exited ${pushed.code}: ${pushed.stderr.trim()}`,614+ [answerer.token]615+ )616+ );617+ });618+619+const Status = Schema.Struct({ answers: Schema.Array(AnswerView) });620+621+/** The answer's outcome is not in yet: the gate is still at it. */622+class StillChecking extends Schema.TaggedError<StillChecking>()(623+ "StillChecking",624+ {}625+) {}626+627+/** How the loop waits for a landing: how often it asks, and for how long. */628+export interface Patience {629+ readonly every: Duration.Duration;630+ readonly within: Duration.Duration;631+}632+633+/** What an outcome other than a landing says, in a line. */634+const outcomeLine = (outcome: Outcome) =>635+ Outcome.match(outcome, {636+ AwaitingDecision: ({ decision }) => `waits on the decision ${decision}`,637+ AwaitingFinish: () => "waits for a decider's finish",638+ Checking: ({ stage }) => `is still being checked at ${stage}`,639+ Landed: ({ sha }) => `landed as ${sha}`,640+ Refused: ({ refusals }) =>641+ `was refused: ${explain(refusals)642+ .map((line) => line.trim())643+ .join("; ")}`,644+ WaitingOnParent: ({ ask }) => `waits for its parent ask ${ask} to land`,645+ });646+647+/**648+ * Asks `<cli> status` as `answerer` until the answer at `head` is past the649+ * gate: its landing, or the step fails with how it ended instead.650+ */651+export const awaitLanding = (input: {652+ readonly answerer: LoopPerson;653+ readonly project: ProjectName;654+ readonly head: CommitSha;655+ readonly patience: Patience;656+}) =>657+ Effect.gen(function* () {658+ const { answerer, head, project } = input;659+660+ const outcome = yield* cli(661+ "landing",662+ answerer,663+ ["status", "--project", project],664+ Status665+ ).pipe(666+ Effect.flatMap(({ answers }) =>667+ Option.match(668+ Array.findLast(answers, (answer) => answer.head === head),669+ {670+ onNone: () => Effect.fail(new StillChecking()),671+ onSome: ({ outcome: now }) =>672+ Outcome.guards.Checking(now)673+ ? Effect.fail(new StillChecking())674+ : Effect.succeed(now),675+ }676+ )677+ ),678+ Effect.retry({679+ schedule: Schedule.spaced(input.patience.every).pipe(680+ Schedule.upTo({ duration: input.patience.within })681+ ),682+ while: Schema.is(StillChecking),683+ }),684+ Effect.catchTag("StillChecking", () =>685+ Effect.fail(686+ failed(687+ "landing",688+ `the answer at ${head} was still being checked after ${Duration.format(input.patience.within)}`689+ )690+ )691+ )692+ );693+694+ return Outcome.guards.Landed(outcome)695+ ? outcome.sha696+ : yield* failed(697+ "landing",698+ `the answer at ${head} ${outcomeLine(outcome)}`699+ );700+ });701+702+/** What the landing commit on main says of itself. */703+export interface LandingRead {704+ readonly author: string;705+ readonly committer: string;706+ readonly trailers: readonly string[];707+}708+709+/**710+ * Reads the landing on the project's main, from the answerer's clone: main711+ * is at `landed`, and the commit's author, committer and trailers.712+ */713+export const readLanding = (input: {714+ readonly answerer: LoopPerson;715+ readonly dir: string;716+ readonly origin: string;717+ readonly project: ProjectName;718+ readonly landed: LandedSha;719+}) =>720+ Effect.gen(function* () {721+ const { answerer, dir, landed } = input;722+723+ yield* gitOk("landing", answerer, dir, [724+ "fetch",725+ "--quiet",726+ `${input.origin}/${input.project}.git`,727+ "refs/heads/main",728+ ]);729+730+ const main = yield* gitOk("landing", answerer, dir, [731+ "rev-parse",732+ "FETCH_HEAD",733+ ]);734+735+ if (main !== landed) {736+ return yield* failed(737+ "landing",738+ `${input.project}'s main is at ${main}, not the landing ${landed}`739+ );740+ }741+742+ const [author = "", committer = "", ...trailers] = (yield* gitOk(743+ "landing",744+ answerer,745+ dir,746+ ["log", "-1", "--format=%an%n%cn%n%(trailers:only,unfold)", landed]747+ ))748+ .split("\n")749+ .filter((line) => line.length > 0);750+751+ return { author, committer, trailers } satisfies LandingRead;752+ });753+754+/** Where verdicts live as git notes (`@repo/git/notes`'s `notesRef`). */755+const NOTES = `refs/notes/${Brand.slug}`;756+757+/** How long the loop waits for the verdict note, which follows the verdict. */758+const NOTE_WAIT = { every: Duration.seconds(1), times: 30 } as const;759+760+/** The verdict note is not on the answer's head yet. */761+class NoNoteYet extends Schema.TaggedError<NoNoteYet>()("NoNoteYet", {}) {}762+763+/**764+ * Reads the verdict note on the answer's `head` in the fork, with plain765+ * git, as the answerer: fetch the notes ref, then `git notes show`.766+ */767+export const readVerdictNote = (input: {768+ readonly answerer: LoopPerson;769+ readonly dir: string;770+ readonly head: CommitSha;771+}) =>772+ Effect.gen(function* () {773+ const { answerer, dir, head } = input;774+775+ const fetched = yield* run(776+ "verdict-note",777+ answerer,778+ "git",779+ ["fetch", "--quiet", "origin", `+${NOTES}:${NOTES}`],780+ dir781+ );782+783+ const shown = yield* run(784+ "verdict-note",785+ answerer,786+ "git",787+ ["notes", `--ref=${NOTES}`, "show", head],788+ dir789+ );790+791+ return fetched.code === 0 && shown.code === 0 && shown.stdout.trim() !== ""792+ ? shown.stdout.trim()793+ : yield* new NoNoteYet();794+ }).pipe(795+ Effect.retry({796+ schedule: Schedule.spaced(NOTE_WAIT.every),797+ times: NOTE_WAIT.times,798+ while: Schema.is(NoNoteYet),799+ }),800+ Effect.catchTag("NoNoteYet", () =>801+ Effect.fail(802+ failed(803+ "verdict-note",804+ `no verdict note on ${input.head} in the fork after ${NOTE_WAIT.times} s`805+ )806+ )807+ )808+ );added:scripts/lib/smoke/loop.ts+347 added
1+/**2+ * smoke's `--loop` (issue 806): the whole core loop on a platform, through3+ * the CLI and git, as its people would take it (`core-loop.ts` holds the4+ * steps):5+ *6+ * 1. `people`: who the decider's and the answerer's tokens name;7+ * 2. `init`: the decider makes a throwaway project, `smoke-<run>`, and8+ * pushes its first commit;9+ * 3. `open-ask`: the decider opens an ask, red twice on main first;10+ * 4. `claim`: the answerer claims it, and gets a fork;11+ * 5. `out-of-scope`: an answer that reaches outside the ask's territory is12+ * refused, `OutOfScope` in git's own output;13+ * 6. `answer`: the fixed answer is pushed and taken;14+ * 7. `landing`: it lands on main, with the answerer as author, the platform15+ * as committer, and the `Asked-by` and `Signed-off-by` trailers;16+ * 8. `verdict-note`: its verdict note is on the answer's head in the fork.17+ *18+ * Each step is timed and printed as it passes; the first that fails ends19+ * the run. The throwaway project, its repo and the claim's fork are written20+ * to the throwaway ledger (`infra/created.ts`, by `smoke`) as soon as each21+ * exists. It never runs on `demo`: a throwaway project would show on the22+ * front page the user records.23+ */24+import { Brand } from "@repo/brand";25+import { ProjectName } from "@repo/protocol/ids";26+import type { LandedSha } from "@repo/protocol/ids";27+import {28+ Console,29+ DateTime,30+ Duration,31+ Effect,32+ FileSystem,33+ Option,34+ Schema,35+} from "effect";36+import type { Redacted } from "effect";37+import type { ChildProcessSpawner } from "effect/process";38+39+import { recordCreated } from "../../../infra/created.ts";40+import type { Created } from "../../../infra/created.ts";41+import { declaredStage, resources } from "../../../infra/stages.ts";42+import {43+ awaitLanding,44+ claimAsk,45+ initProject,46+ LoopFailed,47+ openAsk,48+ personAt,49+ pushAnswer,50+ pushOutOfScope,51+ readLanding,52+ readVerdictNote,53+} from "./core-loop.ts";54+import type { LoopStep, Patience } from "./core-loop.ts";55+56+export { LoopFailed, LoopStep } from "./core-loop.ts";57+58+/** `--loop` was pointed at demo, whose front page the user records. */59+export class DemoStageRefused extends Schema.TaggedError<DemoStageRefused>()(60+ "DemoStageRefused",61+ { stage: Schema.String }62+) {63+ override get message() {64+ return `--loop makes a throwaway project, which would show on ${this.stage}'s front page: run it on a dev stage`;65+ }66+}67+68+/** How long one step took. */69+export interface StepTiming {70+ readonly step: LoopStep;71+ readonly ms: number;72+}73+74+/** A loop that passed: what each step found, and how long each took. */75+export interface SmokeLoopReport {76+ readonly project: ProjectName;77+ /** The refusals git printed for the out-of-territory push: `OutOfScope` among them. */78+ readonly refusedWith: readonly string[];79+ /** main's commit after the landing. */80+ readonly landed: LandedSha;81+ readonly author: string;82+ readonly committer: string;83+ /** Every trailer of the landing commit, as git prints them. */84+ readonly trailers: readonly string[];85+ readonly noteFound: boolean;86+ readonly timings: readonly StepTiming[];87+}88+89+/** What one loop runs on, and as whom. */90+export interface LoopInput {91+ /** The stage, which names the throwaways in the ledger; never `demo`. */92+ readonly stage: string;93+ /** This run's name: the project is `smoke-<run>`. */94+ readonly run: string;95+ /** The platform: its `/rpc` and git live here. */96+ readonly origin: string;97+ /** Makes the project and opens the ask (on a stage, the operator). */98+ readonly decider: Redacted.Redacted;99+ /** Claims the ask and pushes the answer. */100+ readonly answerer: Redacted.Redacted;101+ /** How the loop waits for the landing: every 2 s, for up to 10 minutes, unless given. */102+ readonly patience?: Patience;103+}104+105+const PATIENCE: Patience = {106+ every: Duration.seconds(2),107+ within: Duration.minutes(10),108+};109+110+/** A step's run, timed and printed once it passes. */111+const timed =112+ (stage: string, step: LoopStep) =>113+ <A, R>(114+ self: Effect.Effect<A, LoopFailed, R>115+ ): Effect.Effect<readonly [A, StepTiming], LoopFailed, R> =>116+ Effect.timed(self).pipe(117+ Effect.map(([elapsed, value]) => {118+ const ms = Math.round(Duration.toMillis(elapsed));119+120+ return [value, { ms, step }] as const;121+ }),122+ Effect.tap(([, { ms }]) =>123+ Console.log(`smoke ${stage}: loop ${step} passed in ${ms} ms`)124+ )125+ );126+127+/**128+ * Writes one throwaway to the ledger, by smoke; a repo with its namespace129+ * when the stage is one `infra/stages.ts` declares.130+ */131+const recordThrowaway = (stage: string, kind: Created["kind"], name: string) =>132+ Effect.gen(function* () {133+ const namespace = Option.map(134+ declaredStage(stage),135+ (declared) => resources(declared).projects136+ );137+138+ const entry: Created = {139+ at: yield* DateTime.now,140+ by: "smoke",141+ kind,142+ name,143+ stage,144+ };145+146+ yield* recordCreated(147+ kind === "repo" && Option.isSome(namespace)148+ ? { ...entry, namespace: namespace.value }149+ : entry150+ );151+ }).pipe(152+ Effect.mapError(153+ ({ message }) =>154+ new LoopFailed({155+ reason: `the throwaway ledger: ${message}`,156+ step: kind === "project" ? "init" : "claim",157+ })158+ )159+ );160+161+/** The throwaway project of run `run`: `smoke-<run>`. */162+const projectOf = (run: string) =>163+ Schema.decodeEffect(ProjectName)(`smoke-${run}`).pipe(164+ Effect.mapError(165+ () =>166+ new LoopFailed({167+ reason: `smoke-${run} is no project name: a run is lowercase words joined by dashes`,168+ step: "init",169+ })170+ )171+ );172+173+/**174+ * Runs the core loop on the platform at `input.origin`, as the people the175+ * two tokens name, and gives what each step found; refused on `demo`176+ * before anything runs.177+ */178+export const smokeLoop = (179+ input: LoopInput180+): Effect.Effect<181+ SmokeLoopReport,182+ LoopFailed | DemoStageRefused,183+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem184+> =>185+ Effect.gen(function* () {186+ const { origin, stage } = input;187+188+ if (stage === "demo") {189+ return yield* new DemoStageRefused({ stage });190+ }191+192+ const project = yield* projectOf(input.run);193+ const fs = yield* FileSystem.FileSystem;194+195+ const dir = yield* fs196+ .makeTempDirectoryScoped({ prefix: `smoke-${input.run}-` })197+ .pipe(198+ Effect.mapError(199+ ({ message }) =>200+ new LoopFailed({201+ reason: `a folder for the run: ${message}`,202+ step: "people",203+ })204+ )205+ );206+207+ const [{ answerer, decider }, people] = yield* timed(208+ stage,209+ "people"210+ )(211+ Effect.all({212+ answerer: personAt({213+ home: `${dir}/answerer`,214+ origin,215+ token: input.answerer,216+ }),217+ decider: personAt({218+ home: `${dir}/decider`,219+ origin,220+ token: input.decider,221+ }),222+ })223+ );224+225+ const [, init] = yield* timed(226+ stage,227+ "init"228+ )(229+ initProject({230+ answerer: answerer.handle,231+ decider,232+ dir: `${dir}/start`,233+ project,234+ }).pipe(235+ Effect.tap(() =>236+ Effect.andThen(237+ recordThrowaway(stage, "project", project),238+ recordThrowaway(stage, "repo", project)239+ )240+ )241+ )242+ );243+244+ const [, opened] = yield* timed(245+ stage,246+ "open-ask"247+ )(openAsk(decider, project));248+249+ const [claim, claimed] = yield* timed(250+ stage,251+ "claim"252+ )(253+ claimAsk(answerer, project).pipe(254+ Effect.tap(({ fork }) => recordThrowaway(stage, "repo", fork))255+ )256+ );257+258+ const work = `${answerer.home}/answer`;259+260+ const [refusedWith, refused] = yield* timed(261+ stage,262+ "out-of-scope"263+ )(pushOutOfScope({ answerer, claim, dir: work }));264+265+ const [head, answered] = yield* timed(266+ stage,267+ "answer"268+ )(pushAnswer(answerer, work));269+270+ const [{ landed, read }, landing] = yield* timed(271+ stage,272+ "landing"273+ )(274+ Effect.gen(function* () {275+ const sha = yield* awaitLanding({276+ answerer,277+ head,278+ patience: input.patience ?? PATIENCE,279+ project,280+ });281+282+ const found = yield* readLanding({283+ answerer,284+ dir: work,285+ landed: sha,286+ origin,287+ project,288+ });289+290+ const wanted = [291+ ["author", found.author, answerer.handle],292+ // The platform commits every landing under its own name.293+ ["committer", found.committer, Brand.name],294+ ] as const;295+296+ for (const [what, got, expected] of wanted) {297+ if (got !== expected) {298+ return yield* new LoopFailed({299+ reason: `the landing ${sha}'s ${what} is ${got}, not ${expected}`,300+ step: "landing",301+ });302+ }303+ }304+305+ const missing = [306+ `Asked-by: ${decider.handle} `,307+ `Signed-off-by: ${answerer.handle} `,308+ ].filter(309+ (prefix) => !found.trailers.some((line) => line.startsWith(prefix))310+ );311+312+ if (missing.length > 0) {313+ return yield* new LoopFailed({314+ reason: `the landing ${sha} lacks ${missing.map((prefix) => prefix.trim()).join(" and ")}: its trailers are ${found.trailers.join("; ") || "none"}`,315+ step: "landing",316+ });317+ }318+319+ return { landed: sha, read: found };320+ })321+ );322+323+ const [, noted] = yield* timed(324+ stage,325+ "verdict-note"326+ )(readVerdictNote({ answerer, dir: work, head }));327+328+ return {329+ author: read.author,330+ committer: read.committer,331+ landed,332+ noteFound: true,333+ project,334+ refusedWith,335+ timings: [336+ people,337+ init,338+ opened,339+ claimed,340+ refused,341+ answered,342+ landing,343+ noted,344+ ],345+ trailers: read.trailers,346+ };347+ }).pipe(Effect.scoped);modified:scripts/lib/seed.ts+67 added-13 removed
36 unmodified lines37 RepoName,38 RepoPath,39 sameHandle,40 } from "@repo/protocol/ids";41-import { Refusal } from "@repo/protocol/refusal";41+import { ProjectExists, Refusal } from "@repo/protocol/refusal";42 import { explain } from "@repo/protocol/render";43 import {44 Array,45 Config,93 unmodified lines139 /** The ratchets the config declares, in place once main has landed. */140 readonly ratchets: readonly string[];141 /** The layers the example keeps beside its public tree, pushed by the decider. */142 readonly layers: readonly LayerStep[];143+ /**144+ * The example this plan copies under another name (`seed --as`), when it145+ * is a copy: a copy is made fresh, so a name some project has is refused.146+ */147+ readonly copyOf?: ProjectName;148 }149 150 /** Where the asks live in an example: the config folder's `asks/`. */151 const ASKS = `${Brand.configDir}/asks/`;234 unmodified lines386 } satisfies KnownBadStep;387 })388 );389 390+/** A layer's repo in the private namespace: `<project>--<layer>` (spec §4.5). */391+const layerRepo = (project: ProjectName, layer: LayerName) =>392+ RepoName.make(`${project}--${layer}`);393+394 const decodeManifest = Schema.decodeEffect(395 Schema.fromJsonString(LayerManifest)396 );397 96 unmodified lines494 return {495 files,496 knownBad,497 layer,489- repo: RepoName.make(`${input.project}--${layer}`),498+ repo: layerRepo(input.project, layer),499 } satisfies LayerStep;500 })501 );502 });128 unmodified lines631 ratchets,632 } satisfies SeedPlan;633 });634 635+/**636+ * `plan` as a fresh copy named `as` (`seed --as`): the project, and each637+ * layer's repo, which is named for it, take the new name; the files, the638+ * asks and the decider stay the example's. A copy of a copy is still a copy639+ * of the example.640+ */641+export const renameSeedPlan = (plan: SeedPlan, as: ProjectName): SeedPlan => ({642+ ...plan,643+ copyOf: plan.copyOf ?? plan.project,644+ layers: plan.layers.map((layer) => ({645+ ...layer,646+ repo: layerRepo(as, layer.layer),647+ })),648+ project: as,649+});650+651 /** Whether a run did a step, or found it done before. */652 export const StepResult = Schema.Literals(["done", "already"]);653 654 export type StepResult = typeof StepResult.Type;73 unmodified lines728 >()("seed/SeedTarget") {}729 730 const isRefusal = Schema.is(Refusal);731 732+const isProjectExists = Schema.is(ProjectExists);733+734 /** What a call to the platform fails with: a refusal, or the transport's own error. */735 interface CallFailure {736 readonly _tag: string;737 readonly message: string;153 unmodified lines891 return reported("done");892 });893 894 /**868- * Seeds one project: makes it and pushes main's first commit as the869- * operator, then opens each ask and pushes each layer as the decider. Both870- * sessions are checked before the first step, so a missing one stops the871- * seed before it starts.895+ * `runSeed`, with `made` run once the platform has made the project and896+ * before anything else is put on it: `seed --as` writes a copy to the897+ * throwaway ledger there, so a run that fails later still leaves it there.898 */873-export const runSeed = (874- plan: SeedPlan875-): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>899+export const runSeedWith = <R>(900+ plan: SeedPlan,901+ made: (plan: SeedPlan) => Effect.Effect<void, SeedFailed, R>902+): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget | R> =>903 Effect.scoped(904 Effect.gen(function* () {905 const target = yield* SeedTarget;906 const { decider, project } = plan;11 unmodified lines918 );919 920 const init = yield* operator.initProject({ project }).pipe(921 Effect.as<StepResult>("done"),895- Effect.catchTag("ProjectExists", () =>896- Effect.succeed<StepResult>("already")922+ Effect.catchTag("ProjectExists", (exists) =>923+ plan.copyOf === undefined924+ ? Effect.succeed<StepResult>("already")925+ : Effect.fail(exists)926 ),898- Effect.mapError(failedCall(`initProject ${project}`))927+ Effect.mapError((error) =>928+ isProjectExists(error) && plan.copyOf !== undefined929+ ? new SeedFailed({930+ reason: `${project} is taken: --as makes a fresh copy of ${plan.copyOf}, so name a project nobody has`,931+ refusals: [error],932+ })933+ : failedCall(`initProject ${project}`)(error)934+ )935 );936 937+ if (init === "done") {938+ yield* made(plan);939+ }940+941 const landed = (yield* target.refsOf(project)).has(MAIN_REF);942 943 const push = landed944 ? "already"29 unmodified lines974 ];975 })976 );977 978+/**979+ * Seeds one project: makes it and pushes main's first commit as the980+ * operator, then opens each ask and pushes each layer as the decider. Both981+ * sessions are checked before the first step, so a missing one stops the982+ * seed before it starts.983+ *984+ * A copy (`renameSeedPlan`) is made fresh: a name some project has is985+ * refused with its `ProjectExists`, before anything is pushed.986+ */987+export const runSeed = (988+ plan: SeedPlan989+): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>990+ runSeedWith(plan, () => Effect.void);991+992 // ------------------------------------------------------------ the platform993 994 /** A platform the seed reaches over HTTP and git. */995 export interface Platform {278 unmodified lines1274 * The Node world (`apps/platform/test/world.ts`) served by a process of its1275 * own for as long as the scope lasts, with a session for each person in1276 * `sessions`; gives where it serves.1277 */1224-const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1278+export const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1279 Effect.gen(function* () {1280 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1281 const root = yield* repoRoot;1282 171 unmodified linesmodified:scripts/seed.ts+119 added-9 removed
12 unmodified lines13 * (`--operator-env`). `--stage demo` also needs `--yes`: the user records14 * on it (spec §1.5 H7). `--only <project>` seeds one example; `--json`15 * prints the versioned envelope.16 *17+ * `--only <example> --as <name>` seeds a fresh copy of that example under18+ * another project name (`--only burrow --as burrow-swarm-2`), so a live run19+ * can take a family nobody has touched while the example itself stays fresh20+ * for the recording. A name some project has is refused. A copy on a stage21+ * is written to the throwaway ledger (`infra/created.ts`, by `seed`) as soon22+ * as the platform has made it, with its repo and each layer's repo.23+ *24 * Each project is made, and main's first commit pushed, as the operator;25 * each ask is opened as the decider the project's config names, red first26 * on the platform's own Checker; then each layer the example keeps under27 * `layers/` (datekit's maintainers layer) is pushed by that decider to its2 unmodified lines30 */31 import { BunRuntime, BunServices } from "@effect/platform-bun";32 import { Envelope } from "@repo/protocol/envelope";33 import { Handle, ProjectName } from "@repo/protocol/ids";27-import { Array, Console, Effect, Option, Path, Schema, Stdio } from "effect";34+import {35+ Array,36+ Console,37+ DateTime,38+ Effect,39+ Option,40+ Path,41+ Schema,42+ Stdio,43+} from "effect";44 45+import { recordCreated } from "../infra/created.ts";46+import type { Created } from "../infra/created.ts";47 import {48 flagValue,49 platformOrigin,50 recordedSubdomain,51+ resources,52 Stage,53 stageOf,54 subdomainFile,55 } from "../infra/stages.ts";56 import {57 MAIN_REF,58 planSeed,59 ready,60+ renameSeedPlan,41- runSeed,61+ runSeedWith,62 SeedFailed,63 seeded,64 SeedStep,65 stageTarget,21 unmodified lines87 export interface SeedOptions {88 readonly where: SeedWhere;89 /** The one project to seed, when not both. */90 readonly only?: string;91+ /** The name to seed `only`'s example under, as a fresh copy (`--as`). */92+ readonly as?: ProjectName;93 /** Print the versioned envelope instead of lines. */94 readonly json: boolean;95 }96 97 /** The flags the command takes; any other is a typo, refused. */98 const FLAGS = new Set([99+ "--as",100 "--json",101 "--only",102 "--operator-env",103 "--stage",3 unmodified lines107 "--yes",108 ]);109 110 const USAGE =88- "bun scripts/seed.ts --world node | --stage <dev-…|demo> [--url <origin>] [--tokens-env SESSION_TOKENS] [--operator-env OPERATOR_TOKEN] [--only <project>] [--json] [--yes]";111+ "bun scripts/seed.ts --world node | --stage <dev-…|demo> [--url <origin>] [--tokens-env SESSION_TOKENS] [--operator-env OPERATOR_TOKEN] [--only <project> [--as <copy>]] [--json] [--yes]";112 113 const failed = (reason: string) => new SeedFailed({ reason });114 115 /** The stage `--stage` names, its tokens' env vars, and where it lives if `--url` says. */31 unmodified lines147 }),148 });149 });150 151+/**152+ * `--as`'s name, for a copy of the example `--only` names: a project name,153+ * and not the example's own.154+ */155+const copyName = (name: string, only: Option.Option<string>) =>156+ Effect.gen(function* () {157+ if (Option.isNone(only)) {158+ return yield* failed(159+ `--as ${name} names one copy: add --only <example> to say which example it copies`160+ );161+ }162+163+ const copy = yield* Schema.decodeEffect(ProjectName)(name).pipe(164+ Effect.mapError(() =>165+ failed(166+ `--as ${name} is no project name: use lowercase words joined by dashes`167+ )168+ )169+ );170+171+ return copy === only.value172+ ? yield* failed(173+ `--as ${name} is the example's own name: a copy needs a name of its own`174+ )175+ : copy;176+ });177+178 /** The command's flags, read; a seed of `demo` needs `--yes` (H7: the user records on it). */179 export const optionsOf = (180 argv: readonly string[]181 ): Effect.Effect<SeedOptions, SeedFailed> =>27 unmodified lines209 onSome: () => stageFrom(argv),210 });211 212 const json = argv.includes("--json");213+ const only = flagValue(argv, "--only");214 164- return Option.match(flagValue(argv, "--only"), {165- onNone: () => ({ json, where }),166- onSome: (only) => ({ json, only, where }),215+ const as = yield* Option.match(flagValue(argv, "--as"), {216+ onNone: () => Effect.succeedNone,217+ onSome: (name) => Effect.asSome(copyName(name, only)),218 });219+220+ return {221+ json,222+ where,223+ ...Option.match(only, {224+ onNone: () => ({}),225+ onSome: (one) => ({ only: one }),226+ }),227+ ...Option.match(as, {228+ onNone: () => ({}),229+ onSome: (copy) => ({ as: copy }),230+ }),231+ };232 });233 234+/**235+ * Writes a copy on `stage` to the throwaway ledger, by the seed: the236+ * project, its repo in the public namespace, and each layer's repo in the237+ * private one, which the platform makes when main lands declaring it.238+ */239+export const recordCopy = (stage: Stage, plan: SeedPlan, at: DateTime.Utc) => {240+ const { layers, projects } = resources(stage);241+ const by = "seed";242+243+ const entries: readonly Created[] = [244+ { at, by, kind: "project", name: plan.project, stage },245+ { at, by, kind: "repo", name: plan.project, namespace: projects, stage },246+ ...plan.layers.map(({ repo }): Created => ({247+ at,248+ by,249+ kind: "repo",250+ name: repo,251+ namespace: layers,252+ stage,253+ })),254+ ];255+256+ return Effect.forEach(entries, recordCreated, { discard: true }).pipe(257+ Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))258+ );259+};260+261 /** What `--json` prints for one seeded project. */262 const SeededSummary = Schema.Struct({263 asks: Schema.Array(Schema.String),264 decider: Handle,109 unmodified lines374 `--only ${options.only ?? ""} names no example: ${EXAMPLES.map((folder) => path.basename(folder)).join(", ")}`375 );376 }377 287- const plans = yield* Effect.forEach(folders, planSeed);378+ const plans = yield* Effect.forEach(folders, (folder) =>379+ Effect.map(planSeed(folder), (plan): SeedPlan =>380+ options.as === undefined ? plan : renameSeedPlan(plan, options.as)381+ )382+ );383+384 const { label, target } = yield* targetFor(options.where, plans);385 386 const say = (line: string) =>387 options.json ? Effect.void : Console.log(line);388 389+ // A copy on a stage goes to the throwaway ledger once it is made.390+ const made = (plan: SeedPlan) =>391+ SeedWhere.match(options.where, {392+ Stage: ({ stage }) =>393+ plan.copyOf === undefined394+ ? Effect.void395+ : Effect.flatMap(DateTime.now, (at) => recordCopy(stage, plan, at)),396+ World: () => Effect.void,397+ });398+399 yield* say(294- `seed: ${plans.map(({ project }) => project).join(", ")} on ${label}`400+ `seed: ${plans401+ .map(({ copyOf, project }) =>402+ copyOf === undefined ? project : `${project} (a copy of ${copyOf})`403+ )404+ .join(", ")} on ${label}`405 );406 407 const run = Effect.gen(function* () {408 yield* ready(plans);409 410 const steps = yield* Effect.forEach(plans, (plan) =>301- Effect.tap(runSeed(plan), (done) =>411+ Effect.tap(runSeedWith(plan, made), (done) =>412 Effect.forEach(done, (each) => say(stepLine(each)), {413 discard: true,414 })415 )47 unmodified linesmodified:scripts/smoke.ts+156 added-3 removed
8 unmodified lines9 * `https://web-<s>.<subdomain>.workers.dev`, with the subdomain `bun run10 * bootstrap` records in `infra/workers-dev.json`; `--url` points it at another11 * platform (the web's probes then run only with `--web-url`). The probes live12 * in `infra/smoke.ts`.13+ *14+ * `--loop` (issue 806) runs the whole core loop after the probes, through the15+ * CLI and git (`lib/smoke/loop.ts`): a throwaway project `smoke-<run>`, an16+ * ask opened red first, a claim, an out-of-territory push git refuses with17+ * `OutOfScope`, the fixed answer landed with its credit, and its verdict18+ * note. It needs two people's tokens in the env, never in an argument: the19+ * operator's (`OPERATOR_TOKEN`), who makes the project and opens the ask,20+ * and the answerer's, from `SESSION_TOKENS` (a JSON object from token to21+ * handle, as the platform's own) by the handle `--as` names (`bram` unless22+ * given). For example, with the stage's generated secrets file (outside the23+ * repo, `infra/stages.md` says where) loaded into the env:24+ *25+ * set -a; . <the stage's secrets file>; set +a26+ * bun scripts/smoke.ts --stage dev-oscabriel --loop27+ *28+ * `--loop` refuses `--stage demo` before anything else: the throwaway would29+ * show on the front page the user records.30 */31 import { BunRuntime, BunServices } from "@effect/platform-bun";15-import { Effect, Stdio } from "effect";32+import { Handle, sameHandle } from "@repo/protocol/ids";33+import {34+ Config,35+ Console,36+ DateTime,37+ Effect,38+ Option,39+ Redacted,40+ Schema,41+ Stdio,42+} from "effect";43 17-import { main } from "../infra/smoke.ts";44+import { main as probeMain } from "../infra/smoke.ts";45+import {46+ flagValue,47+ platformOrigin,48+ recordedSubdomain,49+ stageOf,50+ subdomainFile,51+} from "../infra/stages.ts";52+import { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";53 54 export {20- main,55 NoOrigin,56 platformProbes,57 probes,58 smoke,2 unmodified lines61 } from "../infra/smoke.ts";62 63 export type { SmokeReport } from "../infra/smoke.ts";64 65+export { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";66+67+export type { SmokeLoopReport } from "./lib/smoke/loop.ts";68+69+/** The loop's answerer when `--as` names none: a person every stage's sessions hold. */70+const ANSWERER = "bram";71+72+const failed = (reason: string) => new LoopFailed({ reason, step: "people" });73+74+/** A run's name: when it started, to the second, in UTC (`20261013-091500`). */75+const runName = Effect.map(DateTime.now, (now) =>76+ DateTime.formatIso(now)77+ .slice(0, 19)78+ .replaceAll(/[-:]/gu, "")79+ .replace("T", "-")80+);81+82+const decodeSessions = Schema.decodeUnknownEffect(83+ Schema.fromJsonString(Schema.Record(Schema.String, Handle))84+);85+86+/**87+ * The loop's two people's tokens, from the env: the operator's, and the88+ * answerer's by handle from `SESSION_TOKENS`. A missing one fails naming89+ * it, and never a token.90+ */91+const tokensFrom = (answerer: string) =>92+ Effect.gen(function* () {93+ const decider = yield* Config.Redacted("OPERATOR_TOKEN").pipe(94+ Effect.mapError(() =>95+ failed(96+ "no OPERATOR_TOKEN in the environment: run with the stage's secrets in the env"97+ )98+ )99+ );100+101+ const sessions = yield* Config.String("SESSION_TOKENS").pipe(102+ Effect.mapError(() =>103+ failed(104+ "no SESSION_TOKENS in the environment: run with the stage's secrets in the env"105+ )106+ ),107+ Effect.flatMap((raw) =>108+ decodeSessions(raw).pipe(109+ Effect.mapError(() =>110+ failed("SESSION_TOKENS is not a JSON object from token to handle")111+ )112+ )113+ )114+ );115+116+ const token = Object.entries(sessions).find(([, handle]) =>117+ sameHandle(handle, Handle.make(answerer))118+ )?.[0];119+120+ return token === undefined121+ ? yield* failed(122+ `SESSION_TOKENS has no session for ${answerer}: name another with --as`123+ )124+ : { answerer: Redacted.make(token), decider };125+ });126+127+/** Where the stage's platform lives: `--url`, or bootstrap's workers.dev record. */128+const originOf = (129+ argv: readonly string[],130+ stage: Parameters<typeof platformOrigin>[0]131+) =>132+ Option.match(flagValue(argv, "--url"), {133+ onNone: () =>134+ recordedSubdomain.pipe(135+ Effect.flatMap(Effect.fromOption),136+ Effect.mapError(() =>137+ failed(138+ `no --url, and ${subdomainFile} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${stage} first`139+ )140+ ),141+ Effect.map((subdomain) => platformOrigin(stage, subdomain))142+ ),143+ onSome: (url) => Effect.succeed(url.replace(/\/+$/u, "")),144+ });145+146+/**147+ * `bun scripts/smoke.ts --stage <s> --loop [--as <handle>] [--url <origin>]`:148+ * refuses demo first, then runs the probes, then the core loop, printing149+ * each step's time as it passes and a summary at the end.150+ */151+const loopMain = (argv: readonly string[]) =>152+ Effect.gen(function* () {153+ const stage = yield* stageOf(argv);154+155+ yield* stage === "demo"156+ ? Effect.fail(new DemoStageRefused({ stage }))157+ : Effect.void;158+159+ const answerer = Option.getOrElse(flagValue(argv, "--as"), () => ANSWERER);160+ const tokens = yield* tokensFrom(answerer);161+ const origin = yield* originOf(argv, stage);162+163+ yield* probeMain(argv.filter((arg) => arg !== "--loop"));164+165+ const run = yield* runName;166+167+ yield* Console.log(`smoke ${stage}: loop smoke-${run} at ${origin}`);168+169+ const report = yield* smokeLoop({ ...tokens, origin, run, stage });170+ const total = report.timings.reduce((sum, { ms }) => sum + ms, 0);171+172+ yield* Console.log(173+ `smoke ${stage}: loop passed in ${total} ms: ${report.project} landed ${report.landed.slice(0, 12)} by ${report.author}, refused first with ${report.refusedWith.join(", ")}; trailers ${report.trailers.join("; ")}`174+ );175+ });176+177+/**178+ * `bun scripts/smoke.ts --stage <s> [--loop] …`: the probes, and with179+ * `--loop` the core loop after them.180+ */181+export const main = (argv: readonly string[]) =>182+ argv.includes("--loop") ? loopMain(argv) : probeMain(argv);183+184 if (import.meta.main) {185 BunRuntime.runMain(186 Effect.gen(function* () {187 const args = yield* (yield* Stdio.Stdio).args;5 unmodified linesmodified:.gitignore+8 added
31 unmodified lines32 33 # The CLI's release: the two single-file binaries and `install.sh`, uploaded34 # to a stage's releases bucket, never committed.35 apps/cli/release/36+37+# The deploy lock for recording days (`bun infra/recording.ts on`): a38+# machine's own state while a take runs, never committed.39+infra/.recording40+41+# The Playwright check of a deployed web: one screenshot per page, for the42+# shot list.43+apps/web/e2e/out/modified:AGENTS.md+4 added-4 removed
20 unmodified lines21 | 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace or Artifacts binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both) |22 | 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`. No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23 | 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `no-restricted-imports` |24 | 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |25-| 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`) |25+| 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |26 | 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts` (model tests over effect/Arbitrary histories, each seen catching its planted bug); `apps/platform/test/project-do.test.ts`. No fence: `Effect.sleep` and `Effect.delay` in `packages/project/src` |27 28 ## Verify29 33 unmodified lines63 - `env:check`: shows the env with its values redacted.64 - `ops -- <command>`: runs cf with the ops credentials (see Boundaries).65 - `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.67+- `smoke -- --stage <stage>`: read-only probes against a live stage. `--loop` then runs the whole core loop on a throwaway project, `smoke-<run>`, through the CLI and git, and refuses `demo`.68+- `seed`: puts the two example projects on a platform (`--world node` on this machine, or `--stage <stage>`); a second run changes nothing. `--only <example> --as <name>` seeds a fresh copy under another name, and refuses a taken one.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 ## Nouns14 unmodified lines87 88 - **Competition rules apply to repo text.** Describe rival projects by mechanism, neutrally. All of this repo's code is public; no part of the submission lives in a private layer.89 - **Git.** Commit on branches and merge locally. Pushing and adding a remote are the user's to do.90 - **Env.** To see the env, run `bun run env:check` (`varlock load --agent`, values redacted). That is the only way to read it: `.env`, `.env.local` and `.env.*.local` stay closed. To add a variable, edit the `.env.schema` that owns it (`infra/` for tool credentials, an app's for its Worker) and ask the user to set the value. Product code reads a project's `.env.schema` only through `@repo/visibility`'s parser, and never resolves it.91-- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs. `wrangler delete` auto-confirms in a non-interactive shell, so never run it without the user's OK; cf deletes need `--force` when non-interactive.91+- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs: `bun infra/recording.ts on` makes every deploy refuse until a person runs `off`. `wrangler delete` auto-confirms in a non-interactive shell, so never run it without the user's OK; cf deletes need `--force` when non-interactive.92 - **Ported code is ours.** A ported file carries its upstream licence notice in its header; a vendored folder or a font keeps its licence file beside it. Change ported files freely; upstream `main` is never synced in. Borrowed code stays under 15% of the codebase (aim for about 5%).93 94 ## Effect traps95 50 unmodified linesmodified:bun.lock+1 added
7 unmodified lines8 "@effect/platform-bun": "catalog:",9 "@effect/tsgo": "0.48.1",10 "@oxlint/plugins": "1.87.0",11 "@repo/agent-kit": "workspace:*",12+ "@repo/artifacts": "workspace:*",13 "@repo/brand": "workspace:*",14 "@repo/protocol": "workspace:*",15 "cf": "1.0.0-beta.12",16 "effect": "catalog:",2405 unmodified linesmodified:package.json+1 added
38 unmodified lines39 "@effect/platform-bun": "catalog:",40 "@effect/tsgo": "0.48.1",41 "@oxlint/plugins": "1.87.0",42 "@repo/agent-kit": "workspace:*",43+ "@repo/artifacts": "workspace:*",44 "@repo/brand": "workspace:*",45 "@repo/protocol": "workspace:*",46 "cf": "1.0.0-beta.12",47 "effect": "catalog:",10 unmodified linesmodified:README.md+8 added-2 removed
123 unmodified lines124 ```sh125 bun scripts/smoke.ts --stage dev-<you>126 ```127 128+8. Run the whole core loop on a dev stage, through the CLI and git: a throwaway project `smoke-<run>`, an ask opened red first, an answer refused `OutOfScope`, then the fix landed with its trailers and its verdict note. It makes the project as the operator and answers as `bram` (`--as` names another), so it needs both tokens; it refuses `demo`, whose front page the video shows:129+130+ ```sh131+ ./node_modules/.bin/varlock run --path apps/platform/ -- bun scripts/smoke.ts --stage dev-<you> --loop132+ ```133+134 `infra/stages.md` lists every resource a stage owns, the secrets, and how a person tears a stage down by hand; no script deletes anything.135 136 ### Install the CLI137 45 unmodified lines183 | Lifecycles are pure transitions, and model tests over generated histories hold every invariant after every step. | `packages/project/test/claim.model.test.ts`, `packages/project/test/landing.model.test.ts` |184 | The web's production build carries none of the dev world. | `apps/web/test/production-bundle.test.ts` |185 | Visibility plugs in by one marked line, and nothing else reaches into it. | `packages/config/test/cartridge.test.ts` |186 | Each Worker's bundle stays under its byte budget. | `bun run bytes:check` |181-| A deploy names its stage, runs `verify` first and smoke after. | `packages/config/test/deploy.test.ts` |187+| A deploy names its stage, runs `verify` first and smoke after, and none runs while a take is recorded (`bun infra/recording.ts on`). | `packages/config/test/deploy.test.ts`, `packages/config/test/recording.test.ts` |188 | Every path and command in this README exists. | `packages/config/test/readme.test.ts` |189 190 What it does not promise:191 44 unmodified lines236 agent-kit/ generated agent files: the project skill, the AGENTS.md block, hooks, the command list237 testkit/ scenario builders, golden git transcripts, process fakes238 brand/ the name, and every identifier made from it239 config/ the vitest preset and the repo's own tests234-infra/ bootstrap, deploy, the stage table, smoke's probes240+infra/ bootstrap, deploy, the recording lock, the stage table, smoke's probes241 scripts/ brand and byte checks, seed, smoke, swarm, release242 examples/ datekit and burrow, fictional projects for the demo243 tools/oxlint/ the vendored anti-slop lint plugins244 docs/ decisions (adr/), agent conventions (agents/), the demo (demo/)73 unmodified lines