Skip to content
Myr

Merge build/comments-ops into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 0eb1248, b8f8157 · Browse files · 76 files+290 added−3540 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

76 files+290 added−3540 removed

  • tests:+7 added−230 removed
  • other:+283 added−3310 removed

76 files+290 added−3540 removed

modified:apps/sandbox/src/box/sdk.ts+1 added-17 removed
modified:apps/sandbox/src/checker/logs/worker.ts-7 removed
modified:apps/sandbox/src/checker/env.ts+3 added-39 removed
1/**2 * A check job's env part, as the Checker applies it: which3 * `@proxy` hosts go to the env gateway, with which rules, and which values4 * the gateway may swap in. Pure: the Checker opens the route once egress is5 * off (`run.ts`), and the Durable Object reserves its hosts before the6 * catch-all intercept (`sdk.ts`).7 *8 * Only HTTPS is intercepted: Cloudflare adds a credential only to HTTPS9 * requests, since the outbound handler fetches with the scheme the container10 * used, and varlock injects only over verified TLS. A rule's host that is11 * not one is left out, with its reason.12 */1// Only HTTPS is intercepted: the outbound handler fetches with the scheme the2// container used, and varlock injects only over verified TLS.3import type { CheckJob, EnvProxy } from "@repo/checks/check-runner";4import { Array, Option, Result } from "effect";56import { CLONE_HOST } from "./network.ts";7import type { EnvRoute, EnvSwap } from "./network.ts";819/** A rule's host the Checker does not intercept, and why. */9export interface Skipped {10 readonly host: string;11 readonly reason: string;12}1325/** The job's env route, if it has one, and every host it leaves out. */14export interface EnvPlan {15 readonly route: Option.Option<EnvRoute>;16 readonly skipped: readonly Skipped[];17}1819const HTTPS = "https://";2033/**34 * The most proxy hosts the container intercepts: its intercept table holds35 * 64 hostname targets, and the clone route and the catch-all take two36 * (`sdk.ts`); a few stay spare. Hosts past it are left out, with a reason.37 */21/** The intercept table holds 64 hosts; the clone route and catch-all take two, a few stay spare. */22const MAX_PROXY_HOSTS = 60;2324const TOO_MANY = `the container intercepts at most ${MAX_PROXY_HOSTS} proxy hosts beside the clone route and the catch-all`;2542/**43 * The host the container's HTTPS intercept takes for a rule's `host`, as44 * the schema writes it: a bare host or glob (`sentry.io`, `*.example.com`,45 * `api.example.com:8443`), or one with `https://` before it, which is46 * dropped. Any other scheme, `*` (the catch-all, which the egress gateway47 * holds), and the clone route's host are none.48 */26const interceptHost = (host: string): Result.Result<string, string> => {27 const written = host.trim().toLowerCase();2829 if (written.startsWith("http://")) {
20 unmodified lines
5051 return Result.succeed(bare);52};5377/**78 * The values a landed job's gateway may swap in: each one whose key a rule79 * that is not `block` names, with that rule's placeholder, the one the80 * gateway swaps out of a request and scrubs back into a response. None in81 * any other job.82 */54const swapsOf = (55 job: CheckJob,56 rules: readonly EnvProxy[]57): readonly EnvSwap[] => {
11 unmodified lines
69 : [{ key, placeholder: rule.placeholder, value }];70 });71};72102/**103 * The job's env route: its rules whose host is intercepted, each with the104 * host the intercept takes; the hosts, each once; and the values a landed105 * job's gateway may swap in. None when no host is left, or when the job has106 * a sealed suite: sealed checks run with the network off, and a107 * run with sealed files beside it has no landed value to swap anyway.108 */73export const envPlanOf = (job: CheckJob): EnvPlan => {74 if (job.heldBack !== undefined) {75 return {76 route: Option.none(),
35 unmodified lines
modified:apps/sandbox/src/checker/logs.ts-12 removed
modified:apps/sandbox/src/checker/network.ts+4 added-64 removed
1/**2 * The Checker's network: which hosts its container may reach, and the one3 * route its clone takes. The container starts with the internet off, so a4 * request leaves it only through an outbound entrypoint of this Worker5 * (`outbound.ts`): the clone route adds the job's read token on the Worker's6 * side and closes once setup starts, and every other host is refused unless7 * the current allow-list names it. Adapters: `checker/sdk.ts` over the container's outbound intercepts;8 * tests record the calls (`test/fake-box.ts`).9 */1import type { EnvProxy } from "@repo/checks/check-runner";2import type { EnvKey } from "@repo/protocol/ids";3import { Context } from "effect";4import type { Effect, Redacted } from "effect";515/**16 * The hosts setup may reach on every project, beyond the run block's17 * `setupEgress`: the public package registries and nothing else. The checks18 * themselves reach none of them.19 */6export const REGISTRIES = [21 // npm's registry: npm, pnpm and Bun install from it by default, and22 // corepack downloads pnpm from it.7 "registry.npmjs.org",24 // Yarn 1's registry, a mirror of npm's that `yarn install` uses.8 "registry.yarnpkg.com",26 // Yarn 2+'s home: corepack downloads Yarn itself from it.9 "repo.yarnpkg.com",28 // PyPI's index (the simple API pip and uv read).10 "pypi.org",30 // PyPI's package files, which the index links to.11 "files.pythonhosted.org",32 // crates.io's API, which redirects a crate download to the static host.12 "crates.io",34 // crates.io's sparse index, which cargo reads by default.13 "index.crates.io",36 // crates.io's crate files.14 "static.crates.io",38 // The Go module proxy, where `go mod download` fetches modules.15 "proxy.golang.org",40 // The Go checksum database, which verifies what the proxy served.16 "sum.golang.org",17] as const;1844/**45 * Whether `allow` lets a request to `hostname` out: an exact name, or a46 * `*.example.com` entry for any host under it (not the apex itself).47 */19/** `*.example.com` matches any host under it, not the apex itself. */20export const allows = (allow: readonly string[], hostname: string): boolean => {21 const host = hostname.toLowerCase();2223 return allow.some((entry) =>
2 unmodified lines
26 : host === entry.toLowerCase()27 );28};2958/**59 * The host the container clones from. It names nothing real: the container60 * reaches it only because the clone route intercepts it, so the container61 * learns no remote's host and holds no token for one.62 */30/** Names nothing real, so the container learns no remote's host or token. */31export const CLONE_HOST = "repo.checker.internal";3265/**66 * The URL the container clones `remote` from: the clone host, with the67 * remote's path and nothing else (no user, no token, no query).68 */33export const cloneUrlOf = (remote: string): string =>34 `https://${CLONE_HOST}${new URL(remote).pathname}`;3572/**73 * Where the container's clone goes: requests to `host` reach the clone74 * gateway, which sends them on to `remote` with `token` added. The container75 * sees `host` and never the token.76 */36export interface CloneRoute {37 readonly host: string;38 readonly remote: string;39 readonly token: Redacted.Redacted;40}4183/** A value the env gateway may swap in, with the placeholder it stands for. */42export interface EnvSwap {43 readonly key: EnvKey;44 readonly placeholder: string;45 readonly value: Redacted.Redacted;46}4790/**91 * Where a job's `@proxy` hosts go: each of `hosts` to the env92 * gateway, which lets out only the requests `rules` allow and swaps a93 * placeholder for its value only when `values` holds it, which only a job of94 * landed code fills. Every host is HTTPS and named once.95 */48/** `values` is filled only for a job of landed code. */49export interface EnvRoute {50 readonly hosts: readonly string[];51 readonly rules: readonly EnvProxy[];52 readonly values: readonly EnvSwap[];
1 unmodified line
5455export class Network extends Context.Service<56 Network,57 {105 /**106 * Routes the clone's host to the clone gateway for this job's remote,107 * until the first `allow`.108 */58 readonly routeClone: (route: CloneRoute) => Effect.Effect<void>;110 /**111 * Lets out requests to `hosts` and refuses every other, the clone host112 * included: the clone is done before setup starts, so its route closes113 * here. `[]` turns the network off.114 */59 /** Closes the clone route too. `[]` turns the network off. */60 readonly allow: (hosts: readonly string[]) => Effect.Effect<void>;116 /**117 * Routes each of `route.hosts` to the env gateway for the rest of the118 * job, in place of the egress gateway; every other host stays as119 * `allow` left it.120 */61 readonly routeEnv: (route: EnvRoute) => Effect.Effect<void>;62 }63>()("sandbox/Network") {}
modified:apps/sandbox/src/checker/run.ts+16 added-164 removed
1/**2 * One check job, phase by phase, in one container that holds no credential:3 *4 * 1. clone: the job's tree, through the clone route, whose gateway adds the5 * read token outside the container;6 * 2. the plan from `@repo/checks/phases`, keyed by the lockfiles just cloned:7 * setup (or a snapshot of an earlier one) with egress to the registries8 * and the run block's `setupEgress` only, the snapshot, egress off, the9 * sealed suite's files when the job has one, the lanes and then each10 * sealed check, the report.11 *12 * The container is destroyed however the job ends, and its logs are handed13 * to `CheckLogs` before that; the result carries none (a count lane's14 * stdout, in `outputs`, is a result, not a log). A job the Checker15 * cannot run to the end (a clone or a setup that fails, a sealed file it16 * cannot write) is `VerifierBlocked`: the gate's trouble, never the17 * answer's. A lane that fails or runs out of time is that lane's result.18 *19 * A sealed suite is written only after the20 * snapshot and with egress off, so no snapshot and no request carries it21 * out, and it reports one result per area (`@repo/checks/held-back-filter`).22 * From its first write on, nothing a command prints leaves the Checker: the23 * sealed checks' output is dropped, and so is that of the public lanes24 * that run beside the sealed files (a `bun test` with no path finds them25 * too), which report only how they ended.26 */1// A sealed suite is written only after the snapshot and with egress off. From2// its first write on, nothing a command prints leaves the Checker, the public3// lanes' output included (a `bun test` with no path finds the sealed files).4import { CheckAt, evidenceFrom } from "@repo/checks/check-runner";5import type {6 CheckRun,7 EnvPlaceholder,
28 unmodified lines
36 REGISTRIES,37} from "./network.ts";38import { Snapshots } from "./snapshots.ts";3963/** Where the job's tree is checked out, and every command runs. */40export const REPO = "/workspace/repo";4166/**67 * The CA the container's outbound intercepts present: every HTTPS request68 * leaves through one, so every TLS client trusts this CA alone.69 */42/** Every HTTPS request leaves through an intercept, so TLS clients trust its CA alone. */43const CA = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";4445const TRUST = {46 CARGO_HTTP_CAINFO: CA,
4 unmodified lines
51 REQUESTS_CA_BUNDLE: CA,52 SSL_CERT_FILE: CA,53};5482/**83 * The project's own bins first, as `npm run` puts them (an84 * ASSUMPTION), then the image's.85 */55/** The project's own bins first, as `npm run` puts them. */56const PATH = [57 `${REPO}/node_modules/.bin`,58 "/usr/local/sbin",59 "/usr/local/bin",
2 unmodified lines
62 "/sbin",63 "/bin",64].join(":");6596/**97 * The whole environment every command sees: fixed, so two runs of one tree98 * see the same one, and holding nothing secret.99 */66/** Fixed, so two runs of one tree see the same env. */67const ENV = {68 ...TRUST,69 CI: "1",70 // corepack fetches pnpm or Yarn during setup without asking first.
6 unmodified lines
77 NO_COLOR: "1",78 PATH,79};80114/**115 * The env every command of the project runs with (setup, the lanes, each116 * sealed check): each write-only value's placeholder (a process117 * env beats any resolver, so an unchanged `.env.schema` still loads), under118 * the Checker's own env, which no item's key displaces (an item named119 * `PATH` or `NODE_EXTRA_CA_CERTS` keeps the Checker's). Never a value.120 */81/** Placeholders, never values; no item's key displaces the Checker's own env. */82const commandEnv = (placeholders: readonly EnvPlaceholder[]) => ({83 ...Object.fromEntries(84 placeholders.map(({ key, placeholder }) => [key, placeholder])85 ),86 ...ENV,87});88128/** The identity of the commit a checked tree is checked out as. */89const GIT_ENV = {90 ...ENV,91 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",92 GIT_AUTHOR_EMAIL: "checker@example.com",
2 unmodified lines
95 GIT_COMMITTER_EMAIL: "checker@example.com",96 GIT_COMMITTER_NAME: "Checker",97};98139/** The files whose contents decide what setup installs. */99const LOCKFILES = [100 "bun.lock",101 "bun.lockb",102 "package-lock.json",
9 unmodified lines
112];113114const CLONE_LIMIT = Duration.minutes(5);115157/** Making room for the sealed files is quick; it never waits on the network. */116const ROOM_LIMIT = Duration.minutes(1);117118const SETUP_LIMIT = Duration.minutes(15);119162/**163 * A lane with no time limit of its own gets ten minutes, as `/local` gives;164 * so does each sealed check.165 */120const LANE_LIMIT = Duration.minutes(10);121122const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };123170/** Hosts a failed setup's output names: in URLs and in resolver errors. */124const HOSTS_IN_OUTPUT = [125 /\bhttps?:\/\/(?<host>[a-z0-9.-]+)/giu,126 /\bgetaddrinfo \w+ (?<host>[a-z0-9.-]+)/giu,127 /\bresolve host:? (?<host>[a-z0-9.-]+)/giu,128];129177/** The hosts `text` names that `allowed` does not let out. */130const refusedIn = (text: string, allowed: readonly string[]) => [131 ...new Set(132 HOSTS_IN_OUTPUT.flatMap((pattern) =>133 [...text.matchAll(pattern)].flatMap(
24 unmodified lines
158 Effect.annotateLogs(annotations),159 Effect.andThen(Effect.fail(new VerifierBlocked({})))160 );161210/**211 * A lane's run, as the lane's result, what it leaves for comparison, and,212 * for a count lane that ran to its end, what it printed.213 */162interface LaneRan {163 readonly result: LaneResult;164 readonly evidence: Option.Option<LaneEvidence>;165 readonly output: Option.Option<LaneOutput>;166}167220/** Every phase's log so far, handed to `CheckLogs` when the check ends. */168type Kept = Ref.Ref<readonly PhaseLog[]>;169223/** Adds `log`'s text to the log of its phase and name, starting it if new. */170const keep = (kept: Kept, log: PhaseLog) =>171 Ref.update(kept, (logs) =>172 logs.some(({ name, phase }) => phase === log.phase && name === log.name)173 ? logs.map((each) =>
3 unmodified lines
177 )178 : [...logs, log]179 );180235/** Where a command's output goes: into its phase's log, or nowhere. */181type Recorder = (text: string) => Effect.Effect<void>;182238/** Into the log of `log`'s phase and name. */183const keeping =184 (kept: Kept, log: Omit<PhaseLog, "text">): Recorder =>185 (text) =>186 keep(kept, { ...log, text });187244/** Nowhere: the command ran beside the sealed files. */188const dropping: Recorder = () => Effect.void;189247/**248 * One command, to its end or `limit` (none when it ran out of time), its249 * output handed to `record`. At the limit the Checker stops waiting for250 * it; the process itself ends only when the container is destroyed (the251 * `Box` adapter aborts an `exec` that is still starting, not one already252 * running).253 */190/** None when it ran out of time. */191const exec = (192 record: Recorder,193 argv: readonly [string, ...string[]],194 options: ExecOptions,
13 unmodified lines
208 )209 )210 );211275/** One git command of the checkout, which must succeed: its output. */212const git = (kept: Kept, ...args: readonly string[]) =>213 exec(214 keeping(kept, { name: "clone", phase: "clone" }),215 ["git", ...args],
19 unmodified lines
235 })236 )237 );238303/**304 * The job's tree as the work tree's HEAD, fetched from `url` (the clone305 * host, which holds no token) into an empty repo or the one a snapshot306 * brought back. `clean` keeps what setup installed (ignored files) and drops307 * anything else the tree does not hold.308 */239/** `clean` keeps ignored files, which setup installed. */240const checkout = (kept: Kept, url: string, at: CheckAt) =>241 Effect.gen(function* () {242 const fetch = (refspec: string) =>243 git(
26 unmodified lines
270 yield* git(kept, "-C", REPO, "checkout", "-q", "--force", "--detach", head);271 yield* git(kept, "-C", REPO, "clean", "-q", "-ffd");272 });273343/** What the phases share for one job. */274interface Job {275 readonly wire: CheckWire;276 readonly kept: Kept;347 /** The env the project's commands run with: placeholders, never values. */277 readonly env: Readonly<Record<string, string>>;349 /** The URL the container clones from: the clone host, no token. */278 readonly url: string;351 /** Whether setup was skipped for a snapshot of an earlier one. */279 readonly restored: Ref.Ref<boolean>;353 /** Whether the work tree holds sealed files yet: from then on, no output is kept. */280 readonly sealed: Ref.Ref<boolean>;355 /** How each sealed check ended, in the job's order. */281 readonly exits: Ref.Ref<readonly HeldBackExit[]>;282}283284/** A snapshot is its project's own: two projects with one lockfile never share one. */285const snapshotKeyOf = ({ wire }: Job, key: string) =>286 `${wire.job.project}:${key}`;287363/**364 * Setup, or the snapshot of an earlier one: with a snapshot under `key`, the365 * container restarts from it and the job's tree is checked out again;366 * without one, `command` runs with egress to the registries and `egress`367 * only. A setup that fails is `VerifierBlocked`, and a host it was refused is368 * named in setup's log and in the log line.369 */288const setup = (289 job: Job,290 command: string,291 egress: readonly string[],
59 unmodified lines
351 phase: "setup",352 });353 });354437/**438 * Keeps what setup installed for the next check of this project and439 * lockfile. Only a check of a commit in the project's own repo keeps one440 * (main, or main with a decider's ask files): an answer's tree may change441 * what setup does, so a check of one only ever restores. A snapshot that442 * fails to save leaves this check as it was.443 */355/** Only the project's own commits save one: an answer's tree may change what setup does. */356const snapshot = (job: Job, key: string) =>357 Effect.gen(function* () {358 const snapshots = yield* Snapshots;359 const { at, project, repo } = job.wire.job;
21 unmodified lines
381 )382 );383 });384473/**474 * One lane, to its end or its time limit, as its result: how it ended,475 * classified (`checks.classifyRun`), never an error. A lane that runs out of476 * time, or that the container would not run, never ran to an end. A count477 * lane (`output: "stdout"`) that did hands back its stdout, which its count478 * is read from; any other lane's output stays in its log. A lane that runs479 * beside the sealed files keeps neither, nor its failure's signature: what480 * it printed may name or quote them.481 */385/** A lane beside the sealed files keeps no output or failure signature: it may quote them. */386const runLane = (job: Job, { command, lane }: PlannedLane) =>387 Effect.gen(function* () {388 const own = job.wire.job.lanes.find((each) => each.lane === lane);389 const beside = yield* Ref.get(job.sealed);
50 unmodified lines
440 })441 );442 });443540/**541 * Whether a sealed file's path stays inside the checked tree: relative,542 * with no empty, `.` or `..` segment.543 */444const inTree = (path: string) =>445 !path.startsWith("/") &&446 path447 .split("/")448 .every((segment) => segment !== "" && segment !== "." && segment !== "..");449550/**551 * The shell script `roomFor` runs. Its arguments are folders, shallowest552 * first, then `--`, then files. A folder's place is cleared of anything553 * that is not a folder (a file, a link, a link to a folder) and the folder554 * made; a file's place is cleared of whatever stands there. Every path is555 * absolute, so none reads as `--`.556 */450/** Arguments: folders, shallowest first, then `--`, then files; all absolute, so none reads as `--`. */451const ROOM = [452 'while [ "$1" != -- ]; do',453 ' if [ -L "$1" ] || { [ -e "$1" ] && [ ! -d "$1" ]; }; then',454 ' rm -f -- "$1" || exit 1',
4 unmodified lines
459 "shift",460 'rm -rf -- "$@"',461].join("\n");462569/** Every folder `path` sits in under `root`, shallowest first. */463const foldersAbove = (root: string, path: string) => {464 const folders = path.split("/").slice(0, -1);465466 return folders.map(467 (_, depth) => `${root}/${folders.slice(0, depth + 1).join("/")}`468 );469};470578/**579 * The command that makes room under `root` for the sealed files at `paths`580 * (relative, inside the tree): each folder they sit in, made, and each581 * file's own place, empty. The answer's tree decides what stands there; a582 * file where a sealed folder goes, a folder where a sealed file goes, or a583 * link would fail the write, and a `VerifierBlocked` spends no attempt, so584 * it would tell the answer, for free, that a sealed path is there. What585 * the tree holds anywhere else stays, folders on the way included.586 */471/** A failed write would tell the answer, for free, that a sealed path is there. */472export const roomFor = (473 root: string,474 paths: readonly string[]475): readonly [string, ...string[]] => [
9 unmodified lines
485/** The sealed files are not all in the work tree: nothing logged says which. */486const unwritten = () =>487 blocked("the sealed files were not written", { phase: "WriteHeldBack" });488604/**605 * The sealed suite's files, written into the work tree after the snapshot606 * and with egress off (the plan's order), from the bytes the job carried:607 * the Checker holds no route to the layer. `Files.writeFile` makes no608 * folder, so room is made first (`roomFor`), whatever the answer's tree609 * holds there. A file that would land outside the tree, or that the610 * container cannot write, is `VerifierBlocked`; nothing logged names a611 * path, and no reason the container gave is logged, since it may name one.612 */489/** No reason the container gave is logged, since it may name a sealed path. */490const writeHeldBack = (job: Job, { files }: HeldBackPart) =>491 Effect.gen(function* () {492 if (!files.every(({ path }) => inTree(path))) {493 return yield* blocked("a sealed file's path leaves the checked tree", {
28 unmodified lines
522 { discard: true }523 );524 });525649/**650 * One sealed check, to its end or the lane time limit: how it ended, and651 * nothing it printed. A check that runs out of time, or that the container652 * fails to run, did not pass, and says no more than a failure would: a653 * different answer would be one more bit about the suite, and one an654 * answer could ask for without spending an attempt.655 */526/** A timeout reads as a plain failure: anything else is one more bit about the suite. */527const runSealed = (job: Job, { area, command }: HeldBackCheck) =>528 exec(529 dropping,530 ["sh", "-c", command],
14 unmodified lines
545 Effect.succeed<HeldBackExit>({ area, code: -1, timedOut: false })546 )547 );548678/**679 * Routes the job's `@proxy` hosts to the env gateway (`checker/env.ts`),680 * logging each host it leaves out with the reason. A host comes from the681 * project's own `.env.schema`, which is public; no value is logged.682 */549const openEnvRoute = (wire: CheckWire) =>550 Effect.gen(function* () {551 const network = yield* Network;552 const { route, skipped } = envPlanOf(wire.job);
11 unmodified lines
564 yield* network.routeEnv(route.value);565 }566 });567702/** The phases, from the clone to the last lane, with the logs kept as they go. */568const phases = (wire: CheckWire, run: RunBlock, kept: Kept) =>569 Effect.gen(function* () {570 const network = yield* Network;571 const { clone } = wire;572708 // The job's sealed suite, if it has one.573 const heldBack = Option.fromNullishOr(wire.job.heldBack);574575 const job: Job = {576 env: commandEnv(wire.job.placeholders),
24 unmodified lines
601 placeholders: wire.job.placeholders.map(({ key }) => key),602 run,603 });604741 // Setup looks its snapshot up under the key the plan's `Snapshot` keeps742 // it under.605 const key = plan.find(Phase.$is("Snapshot"))?.key ?? lockfileHash;606607 const ran = yield* Effect.forEach(plan, (phase) =>608 Effect.logInfo("checker phase").pipe(609 Effect.annotateLogs({ phase: phase._tag }),610 Effect.andThen(611 Phase.$match(phase, {750 // Off for every host but the env gateway's, which open here751 // (the plan's "leaving only the platform's handlers").612 // Off for every host but the env gateway's, which open here.613 EgressOff: () =>614 Effect.as(615 Effect.andThen(network.allow([]), openEnvRoute(wire)),616 []617 ),618 Report: () => Effect.succeed([]),758 // The public lanes, then each sealed check, all with egress off.619 Run: ({ lanes }) =>620 Effect.tap(621 Effect.forEach(lanes, (lane) => runLane(job, lane)),622 () =>
8 unmodified lines
631 ),632 Setup: ({ command, egress }) =>633 Effect.as(setup(job, command, egress, key), []),634 Snapshot: (saved) => Effect.as(snapshot(job, saved.key), []),775 // The plan has this phase only for a job with a sealed suite.635 WriteHeldBack: () =>636 Option.match(heldBack, {637 onNone: () => Effect.succeed([]),638 onSome: (part) => Effect.as(writeHeldBack(job, part), []),
13 unmodified lines
652 ran: ran.flat(),653 };654 });655797/**798 * One check job in one container: the phases, then the logs handed to799 * `CheckLogs` and the container destroyed, however the phases ended. The800 * result carries each lane's result and evidence, never a log, a count801 * lane's stdout (`outputs`), which the platform reads its count from, and802 * one result per sealed area.803 */656export const check = (657 wire: CheckWire658): Effect.Effect<659 CheckRun,
26 unmodified lines
modified:apps/sandbox/src/checker/sdk.ts+8 added-64 removed
1/**2 * `Network` and `Snapshots` over a Durable Object's own container, as the3 * Container API runs one (`ctx.container`; Sandbox SDK 1.0 leaves both to4 * it):5 *6 * - the network is the container's outbound intercepts. The container starts7 * with the internet off, so a request leaves only through an intercept:8 * the clone host goes to `CloneGateway`, each `@proxy` host of the job to9 * `EgressGateway` until egress is off and to `EnvGateway` after, and every10 * other host, HTTPS (`*`) and HTTP, to `EgressGateway`, whose props say11 * what it lets out. A host is registered ahead of the catch-all, which12 * takes every host registered after it (the Sandbox SDK's13 * `DirectoryBackup.intercept`), so the job's `@proxy` hosts are reserved14 * when the layer is built. Registering a target again replaces its handler15 * in place, which is how the allow-list changes, how the clone route16 * closes once setup starts, how egress goes off, and how the env route17 * opens.18 * - a snapshot is a Container snapshot (public beta) of the whole root19 * filesystem, its id kept in an index the project's checks share; a20 * restore starts the container again from it, so the intercepts are21 * registered again too (they last only as long as one container).22 */1// The catch-all intercept takes every host registered after it, so the job's2// `@proxy` hosts are reserved when the layer is built. Registering a target3// again replaces its handler in place. Intercepts last one container, so a4// restore registers them again.5import {6 Context,7 Effect,8 Layer,
9 unmodified lines
18import { Network } from "./network.ts";19import type { CloneRoute, EnvRoute } from "./network.ts";20import { Snapshots } from "./snapshots.ts";2140/**41 * The outbound entrypoints' loopbacks: `ctx.exports` holds one per export of42 * the Worker's main module.43 */22export interface Gateways {23 readonly CloneGateway: (options: { readonly props: CloneProps }) => Fetcher;24 readonly EgressGateway: (options: { readonly props: EgressProps }) => Fetcher;25 readonly EnvGateway: (options: {26 readonly props: EnvGatewayProps;27 }) => Fetcher;28}2952/** Whether `ctx.exports` holds every gateway: `worker.ts` must export them. */30export const hasGateways = (31 exports: Cloudflare.Exports32): exports is Cloudflare.Exports & Gateways =>33 Predicate.hasProperty(exports, "CloneGateway") &&
2 unmodified lines
36 Predicate.isFunction(exports.EgressGateway) &&37 Predicate.hasProperty(exports, "EnvGateway") &&38 Predicate.isFunction(exports.EnvGateway);3963/** Where snapshot ids are kept, by key, for every check of one project. */40export interface SnapshotIndex {41 readonly find: (key: string) => Promise<string | null>;42 readonly keep: (key: string, id: string) => Promise<void>;43 readonly forget: (key: string) => Promise<void>;44}4570/** What the container's intercepts say now. */46interface Routes {47 readonly clone: Option.Option<CloneRoute>;48 readonly allow: readonly string[];74 /**75 * The clone is done: the first `allow` closes its route, so setup and the76 * lanes reach the clone host only as a host they are refused.77 */49 readonly cloned: boolean;79 /**80 * The job's `@proxy` hosts, registered ahead of the catch-all from the81 * first install on: to the egress gateway, like any other host, until82 * the env route opens.83 */50 readonly proxied: readonly string[];85 /** The env route, once open: its hosts go to the env gateway. */51 readonly env: Option.Option<EnvRoute>;52}5389/** The name every setup snapshot carries; its index key tells them apart. */54const SNAPSHOT_NAME = "check-setup";5592/** What a restored container runs while commands run beside it. */56const IDLE = ["sleep", "infinity"];5758const failed = (reason: string) => (cause: unknown) =>59 new BoxFailed({ operation: "exec", reason: `${reason}: ${String(cause)}` });6098/**99 * One intercept registered. One that will not register leaves the network100 * other than the job needs, so it ends the job (a defect), never a lane's run.101 */61/** A failed registration is a defect: the network would not be what the job needs. */62const intercept = (register: () => Promise<void>) => Effect.promise(register);63104/**105 * The env gateway's props for `route`: plain data on the Worker's side,106 * the values opened from their redaction only here.107 */64/** The values leave their redaction only here, on the Worker's side. */65const envProps = ({ rules, values }: EnvRoute): EnvGatewayProps => ({66 rules,67 values: values.map(({ key, placeholder, value }) => ({68 key,
1 unmodified line
70 value: Redacted.value(value),71 })),72});73117/** The hosts the env route has opened, and the gateway they go to. */74interface Opened {75 readonly hosts: readonly string[];76 readonly to: Fetcher;77}78123/**124 * Points the container's intercepts where `routes` says: the clone host to125 * the clone gateway (or, once the clone is done, to the egress gateway, which126 * refuses it), each `@proxy` host to the env gateway once its route is open127 * (to the egress gateway until then), and every other host, HTTPS and HTTP,128 * to an egress gateway allowing `allow`, in that order.129 */79/** Registration order matters: named hosts before the catch-all. */80const install = (81 container: Container,82 gateways: Gateways,83 { allow, clone, cloned, env, proxied }: Routes
42 unmodified lines
126 yield* intercept(() => container.interceptOutboundHttps("*", egress));127 yield* intercept(() => container.interceptAllOutboundHttp(egress));128 });129180/** The restored container answers a command, or the snapshot is gone. */130const probe = (container: Container) =>131 Effect.tryPromise({132 catch: failed("the restored container did not answer"),133 try: () => container.exec(["true"]),
13 unmodified lines
147 })148 )149 );150202/** How the Checker's container runs: the hosts its env route may open, and its size. */151export interface CheckerStart {204 /**205 * Every host the job's env route may open (`checker/env.ts`): a host206 * first registered after the catch-all would never be reached.207 */152 /** A host first registered after the catch-all would never be reached. */153 readonly proxied: readonly string[];209 /** The instance a restore starts on: the one the job's `Box` starts. */154 readonly instance: NonNullable<ContainerStartupOptions["instance"]>;155}156157export const SdkChecker = {
105 unmodified lines
modified:apps/sandbox/src/checker/snapshots.ts+1 added-15 removed
modified:apps/sandbox/src/lander/run.ts+11 added-120 removed
1/**2 * The Lander's jobs, run through the `Box` port: each runs `script.ts`'s3 * git steps in the container and reads what git printed. A step that4 * reaches a remote gets that remote's token as an `http.extraHeader`5 * through `GIT_CONFIG_*` env, never in its URL or on its command line. A6 * step that fails blocks the job with `VerifierBlocked`, which carries no7 * text (principle 3): git's stderr goes beside it, as a log annotation,8 * trimmed and with every token taken out.9 */1// A remote's token reaches git as an `http.extraHeader` through `GIT_CONFIG_*`2// env, never in a URL or on a command line. git's stderr is logged with every3// token taken out, never put in the refusal.4import { Brand } from "@repo/brand";5import { notesRef } from "@repo/git/notes";6import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";7import type { GitIdentity } from "@repo/git/trailers";
69 unmodified lines
77 writeTree,78} from "./script.ts";79import type { GitStep, RemoteName, Signature } from "./script.ts";8087/** Where the Lander's container keeps things, and finds its tools. */81export interface LanderLayout {89 /** The folder its repos and scratch files live in. */82 readonly work: string;91 /**92 * The image's copy of the sdk, which a config folder's imports of the sdk93 * resolve to: its entry module, the packages its own imports resolve in94 * (`effect` among them), and a file naming its version.95 */83 readonly sdk: {84 readonly entry: string;85 readonly modules: string;86 readonly version: string;87 };101 /** Where commands are looked up. */88 readonly path: string;89}90105/** The land image's layout (`images/land.Dockerfile`); tests point it at a temp folder. */91export const Layout = Context.Reference<LanderLayout>("sandbox/lander/Layout", {92 defaultValue: () => ({93 path: "/usr/local/bin:/usr/bin:/bin",94 sdk: {
4 unmodified lines
99 work: "/workspace",100 }),101});102118/** The tokens a job carries, by the remote each opens. */103type Tokens = Partial<Record<RemoteName, Redacted.Redacted>>;104105// The modes git stores a file's bytes under, plain or executable: a file a106// composed file may replace, and a file a bundle may read.
6 unmodified lines
113const REMOTE_MS = 120_000;114115const LOCAL_MS = 30_000;116133/** `text` with every token taken out, and only its end kept. */117const scrubbed = (text: string, tokens: Tokens) => {118 let kept = text;119120 for (const token of Object.values(tokens)) {
6 unmodified lines
127128 return kept.trim().slice(-STDERR_KEPT);129};130148/** git's subcommand in a step, for logs: the first argument after its options. */131const subcommandOf = (step: GitStep) =>132 step.argv.find(133 (argument, index) =>134 index > 0 && !argument.startsWith("-") && step.argv[index - 1] !== "-c"135 ) ?? "git";136155/**156 * The job is blocked at `step` (a git subcommand, or the Box operation); what157 * went wrong goes to the log, token-free, never into the refusal.158 */137const blockedBy = (step: string, why: string, tokens: Tokens) =>138 Effect.logWarning("a Lander step failed").pipe(139 Effect.annotateLogs({ step, why: scrubbed(why, tokens) }),140 Effect.andThen(Effect.fail(new VerifierBlocked({})))141 );142165/** Everything a command printed, for a log: its exit, then stdout and stderr. */143const printed = (ran: Executed) =>144 `exit ${ran.exitCode}: ${ran.stdout}\n${ran.stderr}`;145169/** git's env for every step: no config but the step's own, no prompt, English. */146const baseEnv = (layout: LanderLayout) => ({147 GIT_CONFIG_GLOBAL: "/dev/null",148 GIT_CONFIG_NOSYSTEM: "1",149 GIT_TERMINAL_PROMPT: "0",
1 unmodified line
151 LC_ALL: "C",152 PATH: layout.path,153});154179/** The header that carries a remote's token, as git reads config from env. */155const header = (token: Redacted.Redacted) => ({156 GIT_CONFIG_COUNT: "1",157 GIT_CONFIG_KEY_0: "http.extraHeader",158 GIT_CONFIG_VALUE_0: `Authorization: Bearer ${Redacted.value(token)}`,159});160186/** How one job runs its steps, and how it says one blocked it. */161interface Steps {188 /**189 * Runs a step in the work folder, with the token of the remote it reaches.190 * A step expected to succeed that does not blocks the job; the others hand191 * back what git printed for the caller to read.192 */162 /** A step expected to succeed that does not blocks the job. */163 readonly run: (step: GitStep) => Effect.Effect<Executed, VerifierBlocked>;194 /** Blocks the job at `step`, logging `why` with the job's tokens taken out. */164 readonly blocked: (165 step: GitStep,166 why: string167 ) => Effect.Effect<never, VerifierBlocked>;168}169201/** The steps of one job, which carries `tokens`. */170const runner = (tokens: Tokens) => {171 const blocked = (step: GitStep, why: string) =>172 blockedBy(subcommandOf(step), why, tokens);173
46 unmodified lines
220);221222const signed = (who: GitIdentity, at: number): Signature => ({ ...who, at });223256/** A scratch file the job writes, in the work folder. */224const scratch = (name: string) =>225 Effect.map(Layout, ({ work }) => `${work}/scratch/${name}`);226260/**261 * The Lander's copy of the job's repo, and the scratch folders its files go262 * in, made if they are missing.263 */227const prepared = (job: Job) =>228 Effect.gen(function* () {229 const { work } = yield* Layout;230231 yield* job.run(folders([`${work}/scratch/compose`]));232 yield* job.run(initCopy(job.repo));233 });234272/** `text` written to `file` in the container; a file it would not take blocks the job. */235const writtenAt = (file: string, text: string) =>236 Box.use((box) => box.writeFile(file, new TextEncoder().encode(text))).pipe(237 Effect.catchTag("BoxFailed", ({ reason }) =>238 blockedBy("writeFile", reason, {})239 )240 );241280/** Writes `text` to a scratch file for git to read: a message, a note. */242const written = (name: string, text: string) =>243 Effect.gen(function* () {244 const file = yield* scratch(name);245
1 unmodified line
247248 return file;249 });250290/** What one job runs its steps with: its canonical repo, that repo's URL, and its steps. */251interface Job extends Steps {252 readonly repo: RepoName;253 readonly url: string;254}255296/** `rev` in the Lander's copy, if it names something there. */256const resolved = ({ repo, run }: Job, rev: string) =>257 Effect.map(run(revParse(repo, rev)), ({ exitCode, stdout }) =>258 exitCode === 0 ? Option.some(stdout.trim()) : Option.none()259 );260302/** `rev`'s id in the Lander's copy, which a step before made sure is there. */261const idOf = (job: Job, rev: string) =>262 resolved(job, rev).pipe(263 Effect.flatMap(264 Option.match({
3 unmodified lines
268 })269 )270 );271314/** A commit of `tree` on `parents`, written to the copy: its id. */272const committed = (273 job: Job,274 commit: {275 readonly tree: string;
18 unmodified lines
294295 return CommitSha.make(ran.stdout.trim());296 });297341/**342 * The merged tree as a commit on `main` and the head, pushed to the fork's343 * `mergeRef(tree)`, where a Checker's fetch of the fork's refs finds it.344 * It is dated at the epoch, so merging the same sides again345 * makes the same commit, and pushing it again changes nothing.346 */298/** Dated at the epoch, so merging the same sides again makes the same commit. */299const keptForChecks = (300 job: Job,301 sides: {302 readonly head: CommitSha;
26 unmodified lines
329 ? commit330 : yield* job.blocked(push, printed(ran));331 });332381/**382 * The answer's head merged onto canonical `main` with its base as the merge383 * base: the merged tree and the answer's changes, or `StaleBase` with the384 * paths that conflict. Nothing is pushed.385 */333export const merge = (wire: typeof MergeWire.Type) =>334 Effect.gen(function* () {335 const { job } = wire;336
34 unmodified lines
371372 return { changes, tree: merged.tree };373 });374428/** A path's folders and file name; one that cannot name a file is a defect upstream. */375const placed = ({ path }: { readonly path: string }) =>376 path.split("/").every((segment) => !["", ".", "..", ".git"].includes(segment))377 ? Effect.void378 : Effect.die(`${path} cannot name a file in a repo`);379434/**435 * `main` with `files` added, written to the copy: the new root. A file436 * keeps the mode of the file it replaces; a path where a folder, a symlink437 * or a submodule stands blocks the job.438 */380/** A file keeps the mode of the file it replaces. */381const composed = (382 job: Job,383 main: string,384 files: readonly { readonly path: string; readonly content: string }[]
43 unmodified lines
428 (yield* job.run(writeTree(job.repo, index))).stdout.trim()429 );430 });431490/** The tree a land rebuilds, written to the copy where it is new. */432const rebuilt = (433 job: Job,434 wire: typeof LandWire.Type435): Effect.Effect<TreeSha, StaleBase | VerifierBlocked, Box> =>
30 unmodified lines
466 }),467 }468 );469529/** The mirror of canonical `main` (ADR 0005). */470const landedRef = `${Brand.refsPrefix}landed`;471532/** Where the copy keeps canonical's notes ref. */472const notesCopyOf = notesRef.replace("refs/notes/", `${notesCopy}/`);473474const encodeNote = Schema.encodeEffect(Schema.fromJsonString(Verdict));475537/** Whether the notes commit `notes` (in the copy) holds a note on `landing`. */476const holdsNote = (job: Job, notes: string, landing: CommitSha) =>477 Effect.map(478 job.run(objectType(job.repo, `${notes}:${landing}`)),479 ({ exitCode }) => exitCode === 0480 );481544/**545 * The verdict written as the landing's note, unless it is there already:546 * the content `@repo/git/notes`' `noteCommit` writes (one JSON blob named by547 * the landing, fanout-free, the platform's commit on the earlier notes),548 * pushed alone. It gives the notes commit that holds the note.549 */482const note = (job: Job, landing: CommitSha, verdict: Verdict, at: number) =>483 Effect.gen(function* () {484 const parent = yield* resolved(job, notesCopyOf);485
37 unmodified lines
523 ? commit524 : yield* job.blocked(step, printed(ran));525 });526595/** A piece of bookkeeping a landing may leave pending. */527type Bookkeeping = (typeof Landed.Type)["pending"][number];528598/** One piece of bookkeeping: `None` once written, its name when it was not. */529const attempt = <A, E, R>(item: Bookkeeping, write: Effect.Effect<A, E, R>) =>530 write.pipe(531 Effect.as(Option.none<Bookkeeping>()),532 Effect.catchCause((cause) =>
3 unmodified lines
536 )537 )538 );539610/**611 * What follows a landing on `main`, each in its own push: the612 * mirror ref, while the landing is still main's tip (a later landing's own613 * mirror supersedes it), then the verdict note. Neither fails the landing;614 * what was not written comes back pending, and landing the same job again615 * writes it.616 */540/** Neither fails the landing: what was not written comes back pending, and landing again writes it. */541const settle = (542 job: Job,543 wire: typeof LandWire.Type,544 landing: CommitSha,
31 unmodified lines
576const requestIdOf = (text: string) =>577 parseTrailers(text).find(({ key }) => key.toLowerCase() === "request-id")578 ?.value;579656/** The base a stale land names: the answer's own, or the main it was built on. */580const baseOf = (wire: typeof LandWire.Type) =>581 Rebuild.match(wire.job.rebuild, {582 Compose: () => wire.job.main,583 Existing: () => wire.job.main,584 Merge: ({ base }) => base,585 });586664/**665 * A land that found `main` at `tip`, not where the job left it: an earlier666 * land of the same request (a child of the job's `main` carrying its667 * `Request-Id`, within 16 first parents of the tip) gets its missing668 * bookkeeping written; anything else is `StaleBase`.669 */587/** An earlier land of the same `Request-Id` gets its missing bookkeeping written; anything else is `StaleBase`. */588const moved = (job: Job, wire: typeof LandWire.Type, tip: string) =>589 Effect.gen(function* () {590 const history = readLog(591 (yield* job.run(firstParents(job.repo, tip, LOOKBACK))).stdout
18 unmodified lines
610 main: CommitSha.make(tip),611 });612 });613696/**697 * One commit on canonical `main` whose parent is the job's `main` and whose698 * tree is the job's `tree`, rebuilt here; the answerer its author and the699 * platform its committer. It is pushed without force, so a `main` that700 * moved refuses it; then the mirror ref and the verdict note, each alone.701 */614/** Pushed without force, so a `main` that moved refuses it. */615export const land = (wire: typeof LandWire.Type) =>616 Effect.gen(function* () {617 const { job: landing } = wire;618
61 unmodified lines
680681 return yield* job.blocked(script.main, printed(ran));682 });683771// What a composed commit says: the platform made it, for a check, off main.684const COMPOSE_MESSAGE = "Compose files onto main for a check\n";685774/**775 * `main` with a decider's files added, committed by the platform on `main`776 * and pushed to `${Brand.refsPrefix}compose/<tree>`, where a Checker fetches777 * it by id. `main` never moves. Composed before onto the same `main`, it is778 * the commit already there.779 */686export const compose = (wire: typeof ComposeWire.Type) =>687 Effect.gen(function* () {688 const job: Job = {689 ...(yield* runner({ main: wire.main.token })),
49 unmodified lines
739740 return { commit, tree };741 });742837/** Whether `rev` names a commit in the Lander's copy. */743const hasCommit = (job: Job, rev: string) =>744 Effect.map(745 job.run(objectType(job.repo, `${rev}^{commit}`)),746 ({ exitCode }) => exitCode === 0747 );748844/** `commit` in the Lander's copy, fetched by its id if fetching main did not bring it. */749const present = (job: Job, commit: string) =>750 Effect.gen(function* () {751 if (!(yield* hasCommit(job, commit))) {752 yield* job.run(fetchCommit(job.repo, job.url, commit));
6 unmodified lines
759 `canonical has no commit ${commit}`760 );761 });762859/**860 * The entries of a config folder bundled by bun in the work folder: the861 * folder's files checked out from the copy (no repo config, no hooks; files862 * only, never a symlink), the sdk's two names pointed at the image's copy863 * and its packages beside it, then bun's output read back, each entry at its864 * own path and each shared chunk at the path bun gave it.865 */763/** Files only, never a symlink, and no repo config or hooks. */764const built = (765 job: Job,766 files: readonly {767 readonly path: string;
44 unmodified lines
812 )813 );814 });815918/**919 * The config folder at `at`, for the rules evaluator: its project module,920 * visibility module and ask files each bundled by bun into plain ES modules921 * with the sdk and `effect` inlined (shared code in chunks beside them), its922 * other files (`policy.json`, the vouch file) as committed, and the version923 * of the sdk the image carries. A folder that is missing gives no modules:924 * the project runs on the defaults. Nothing in the folder runs here.925 */816/** Nothing in the folder runs here. A missing folder gives no modules: the defaults apply. */817export const bundleRules = (wire: typeof BundleWire.Type) =>818 Effect.gen(function* () {819 const { sdk } = yield* Layout;820
46 unmodified lines
modified:apps/sandbox/src/lander/script.ts+13 added-144 removed
1/**2 * The Lander's git, as data: each step is one git command, the remote it3 * reaches (whose token `run.ts` hands git in its env, never on its command4 * line), and how its exit reads. Pure, so the script is read and tested5 * without a container; `run.ts` runs it through the `Box` port and reads6 * what git printed with the parsers below.7 *8 * Every step runs git with hooks pointed at `/dev/null`, no credential9 * helper, no redirects and no automatic maintenance, in a bare repo: the10 * Lander checks nothing out and runs nothing from the trees it handles.11 * Nothing here pushes with force, `--force-with-lease` or `--atomic` to12 * `main`: a landing is a plain push, which git refuses when13 * `main` moved, and only a compose ref, never `main`, moves by a lease. A14 * merge pushes one ref, to the answer's fork alone: the merged commit, for15 * the Checker to fetch.16 */1// The Lander checks nothing out and runs nothing from the trees it handles.2// Nothing pushes `main` with force, a lease or `--atomic`: a landing is a3// plain push, which git refuses when `main` moved.4import { Brand } from "@repo/brand";5import type { LandJob, Merged, MergeJob } from "@repo/project/lander/wire";6import { BlobSha, CommitSha, RepoPath, TreeSha } from "@repo/protocol/ids";7import type { RepoName } from "@repo/protocol/ids";
1 unmodified line
9import type { Types } from "effect";1011import type { Executed } from "../box.ts";1226/** Which of a job's remotes a step reaches. */13export type RemoteName = "main" | "fork";1429/** How a step's exit reads. */15export type Expect =31 /** Exit 0, or the job is blocked. */16 | "ok"17 /** `merge-tree`: 0 is a clean merge, 1 a merge with conflicts. */18 | "merge"35 /** A push: what git printed says whether the ref moved, and why not. */19 | "push"20 /** A question: a non-zero exit means "no". */21 | "probe";2240/** One command: git, or a tool beside it in the image (`mkdir`, `bun`, `cat`). */23export interface GitStep {24 readonly argv: Array.NonEmptyReadonlyArray<string>;43 /** Env git needs for this step alone: identities, an index file. Never a token. */25 /** Never a token. */26 readonly env?: Readonly<Record<string, string>>;45 /** The remote this step reaches; git gets its token as a header, through env. */27 readonly remote?: RemoteName;28 readonly expect: Expect;29}3050/** Where canonical `main` is kept in the Lander's copy. */31export const mainCopy = "refs/lander/main";3253/** Where a fork's branches are kept in the Lander's copy. */33export const forkCopy = (fork: RepoName) => `refs/lander/forks/${fork}`;3456/** Where canonical's notes refs are kept in the Lander's copy. */35export const notesCopy = "refs/lander/notes";3659/** Where a compose ref already on canonical is kept in the Lander's copy. */37export const composeCopy = "refs/lander/compose";3862/** The canonical branch a landing moves. */39export const mainRef = "refs/heads/main";4065/**66 * Where a merged commit waits, in the answer's fork, for a Checker to fetch67 * its tree: named by the tree, so a ref an answerer rewrote cannot change68 * what is checked (at worst the Checker finds no such tree).69 */41/** Named by the tree, so a ref an answerer rewrote cannot change what is checked. */42export const mergeRef = (tree: string) => `${Brand.refsPrefix}merge/${tree}`;4344// Each git command: no hooks, no helper that could see a token, no redirect45// a header could follow, and nothing running in the background.
9 unmodified lines
55 "-c",56 "maintenance.auto=false",57] as const;5887/**88 * The Lander's copy of a canonical repo, relative to its work folder: one89 * bare repo per project, kept between jobs so a fetch brings only what is90 * new. It is never shallow, so a push from it sends no `shallow` lines,91 * which Artifacts' receive-pack does not advertise.92 */59/** Never shallow: Artifacts' receive-pack does not advertise `shallow`. */60export const copyOf = (repo: RepoName) => `repos/${repo}.git`;6162const git = (63 repo: RepoName,
6 unmodified lines
70];7172const fetch = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head"];73107/**108 * The folders a job writes in, made if they are missing: the container's109 * file writes, like the Sandbox SDK's, make no folder on their own.110 */74/** The container's file writes make no folder on their own. */75export const folders = (76 paths: Array.NonEmptyReadonlyArray<string>77): GitStep => ({ argv: ["mkdir", "-p", "--", ...paths], expect: "ok" });78115/** A folder and everything in it gone, if it was there. */79export const removeFolder = (folder: string): GitStep => ({80 argv: ["rm", "-rf", "--", folder],81 expect: "ok",82});83121/** The Lander's copy of `repo`, made if it is missing; making it again changes nothing. */84export const initCopy = (repo: RepoName): GitStep => ({85 argv: ["git", ...safety, "init", "--quiet", "--bare", copyOf(repo)],86 expect: "ok",87});88127/**128 * Canonical `main` fetched into the copy, with its notes refs when a landing129 * needs them (`--prune` drops a notes ref canonical no longer has).130 */89export const fetchMain = (90 repo: RepoName,91 url: string,92 options: { readonly notes?: boolean } = {}
9 unmodified lines
102 expect: "ok",103 remote: "main",104});105148/** Every branch of the answer's fork, fetched into the copy. */106export const fetchFork = (107 repo: RepoName,108 fork: RepoName,109 url: string
2 unmodified lines
112 expect: "ok",113 remote: "fork",114});115159/**160 * The answer's head merged onto `main` with its own base as the merge base,161 * by `git merge-tree --write-tree` (git 2.40 or later): no worktree, no162 * checkout. It prints the merged tree, then each conflicting path.163 */116/** `merge-tree --write-tree` needs git 2.40 or later. */117export const mergeTree = (118 repo: RepoName,119 sides: { readonly base: string; readonly main: string; readonly head: string }120): GitStep => ({
10 unmodified lines
131 ),132 expect: "merge",133});134182/** What changed from `from` to `to`, path by path, with blob ids. */135export const diffTree = (136 repo: RepoName,137 from: string,138 to: string
1 unmodified line
140 argv: git(repo, "diff-tree", "-r", "-z", "--no-renames", from, to),141 expect: "ok",142});143192/** A merge as git runs it, in order. */144export interface MergeScript {194 /** Canonical `main` and every branch of the fork, into the Lander's copy. */145 readonly fetch: readonly GitStep[];146 readonly merge: GitStep;147 /** The answer's changes against its own base, not main's. */148 readonly changes: GitStep;149}150201/** A merge's fetches and merge; it writes nothing to canonical. */151export const mergeScript = (152 job: typeof MergeJob.Type,153 remotes: { readonly main: string; readonly fork: string }154): MergeScript => ({
5 unmodified lines
160 ],161 merge: mergeTree(job.repo, job),162});163215/**216 * One push of one ref, from the copy. `lease` makes it a compare-and-swap on217 * a ref that may move to a commit that does not descend from it: only ever218 * a compose ref.219 */164/** `lease` is only ever for a compose ref, never `main`. */165export const pushRef = (166 repo: RepoName,167 url: string,168 update: {169 readonly to: string;170 readonly ref: string;171 readonly lease?: string;227 /** The remote it reaches: canonical, unless it is the fork. */172 readonly remote?: RemoteName;173 }174): GitStep => ({175 argv: git(
10 unmodified lines
186 expect: "push",187 remote: update.remote ?? "main",188});189246/** The two pushes of a landing. */190export interface LandScript {248 /** The landing onto canonical `main`. */191 readonly main: GitStep;250 /** The mirror ref onto the landing, once `main` moved. */192 readonly mirror: GitStep;193}194254/**255 * The two pushes of a landing, in order and each alone: `landing` onto256 * canonical `main`, a plain push that git refuses when `main` is no longer257 * the landing's parent; then, once it moved, the mirror ref (ADR 0005).258 */195export const landScript = (196 job: Pick<typeof LandJob.Type, "repo">,197 url: string,198 landing: CommitSha,
2 unmodified lines
201 main: pushRef(job.repo, url, { ref: mainRef, to: landing }),202 mirror: pushRef(job.repo, url, { ref: mirror, to: landing }),203});204269/** One git identity at one moment, as git's env spells it. */205export interface Signature {206 readonly name: string;207 readonly email: string;208 /** Seconds since the epoch, in UTC. */209 readonly at: number;210}211277/** A commit of `tree` on `parents`, with its message from a file, as its people sign it. */212export const commitTree = (213 repo: RepoName,214 commit: {215 readonly tree: string;
21 unmodified lines
237 },238 expect: "ok",239});240307/** Whether `rev` names an object in the copy; it prints the object's type. */241export const objectType = (repo: RepoName, rev: string): GitStep => ({242 argv: git(repo, "cat-file", "-t", rev),243 expect: "probe",244});245313/** One revision's id in the copy. */246export const revParse = (repo: RepoName, rev: string): GitStep => ({247 argv: git(repo, "rev-parse", "--verify", "--quiet", rev),248 expect: "probe",249});
3 unmodified lines
253 argv: git(repo, "hash-object", "-w", "--no-filters", "--", file),254 expect: "ok",255});256325/** An index file loaded with `tree`, or emptied when there is none. */257export const readTree = (258 repo: RepoName,259 index: string,260 tree?: string
2 unmodified lines
263 env: { GIT_INDEX_FILE: index },264 expect: "ok",265});266336/** Blobs placed in an index file at their paths, with their modes. */267export const updateIndex = (268 repo: RepoName,269 index: string,270 entries: readonly {
14 unmodified lines
285 env: { GIT_INDEX_FILE: index },286 expect: "ok",287});288359/** The tree an index file holds, written to the copy. */289export const writeTree = (repo: RepoName, index: string): GitStep => ({290 argv: git(repo, "write-tree"),291 env: { GIT_INDEX_FILE: index },292 expect: "ok",293});294366/**367 * An index file's files written under `folder`, symlinks as plain files368 * holding their target, so nothing written points outside it.369 */295/** Symlinks as plain files holding their target, so nothing written points outside. */296export const checkoutIndex = (297 repo: RepoName,298 index: string,299 folder: string
12 unmodified lines
312 env: { GIT_INDEX_FILE: index },313 expect: "ok",314});315390/** The modes and ids of `paths` in `tree`, those that are there. */316export const lsTree = (317 repo: RepoName,318 tree: string,319 paths: readonly string[]
1 unmodified line
321 argv: git(repo, "ls-tree", "-z", "--full-tree", tree, "--", ...paths),322 expect: "ok",323});324400/** Every file under `folder` in `tree`, at any depth, with its mode and id. */325export const filesUnder = (326 repo: RepoName,327 tree: string,328 folder: string
1 unmodified line
330 argv: git(repo, "ls-tree", "-r", "-z", "--full-tree", tree, "--", folder),331 expect: "ok",332});333410/** A blob's bytes, printed. */334export const catBlob = (repo: RepoName, blob: string): GitStep => ({335 argv: git(repo, "cat-file", "blob", blob),336 expect: "ok",337});338416/** One commit fetched from canonical by its id, into the copy's objects. */339export const fetchCommit = (340 repo: RepoName,341 url: string,342 commit: string
2 unmodified lines
345 expect: "ok",346 remote: "main",347});348427/** The commits from `tip` back along first parents, at most `count`. */349export const firstParents = (350 repo: RepoName,351 tip: string,352 count: number
9 unmodified lines
362 ),363 expect: "ok",364});365445/** A ref's id on a remote, if it has the ref. */366export const lsRemote = (367 repo: RepoName,368 url: string,369 ref: string
2 unmodified lines
372 expect: "ok",373 remote: "main",374});375456/** A ref fetched from canonical into `into` in the copy. */376export const fetchRef = (377 repo: RepoName,378 url: string,379 ref: string,
3 unmodified lines
383 expect: "ok",384 remote: "main",385});386468// --------------------------------------------------------------- bundling469470// A module that runs: what the rules evaluator imports, and what a bundle inlines.387const SCRIPT = /\.[cm]?[jt]sx?$/u;388473// An ask file, as `@repo/rules` finds one: `<id>.ask.ts`, or its JavaScript.389const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;390476/**477 * The config folder's project module, which a bundle names whether or not478 * the folder has one (`ConfigBundle.entry`).479 */391export const configEntry = `${Brand.configDir}/project.ts`;392482/** Whether a file in the config folder is code, which a bundle carries only inlined. */393export const isScript = (path: string) => SCRIPT.test(path);394485/** The config folder's visibility module: its layers and held-back checks. */395const visibilityEntry = `${Brand.configDir}/visibility.ts`;396488/**489 * The modules the rules evaluator imports, each bundled on its own: the490 * project module, the visibility module and every ask file. Other code in491 * the folder (helpers, an ask's check) is inlined where an entry imports492 * it, or left out.493 */397export const bundleEntries = (paths: readonly string[]) =>398 paths.filter(399 (path) =>400 path === configEntry ||401 path === visibilityEntry ||402 (path.startsWith(`${Brand.configDir}/asks/`) && ASK_FILE.test(path))403 );404502/** Where bun writes an entry's bundle: its path, as JavaScript. */405export const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");406505/**506 * How the config folder's imports resolve: both names of the sdk (its507 * workspace name and the published `<cli package>/rules`) to the image's508 * copy. Anything else bare resolves in the packages beside that copy, so509 * `effect` is the sdk's own.510 */407/** Bare imports resolve beside the sdk's copy, so `effect` is the sdk's own. */408export const resolution = (sdk: string) =>409 `${JSON.stringify(410 {411 compilerOptions: {
3 unmodified lines
415 null,416 2417 )}\n`;418522/** A symlink at `link` to `target`. */419export const symlink = (target: string, link: string): GitStep => ({420 argv: ["ln", "-s", "--", target, link],421 expect: "ok",422});423528/**529 * The entries bundled by bun, for a browser-like runtime as ES modules:530 * code the entries share goes to chunks in the config folder, and every531 * import resolves as `tsconfig` (written by `resolution`) says. Macros are532 * off, so no code in the folder runs while it is bundled.533 */424/** Macros are off, so no code in the folder runs while it is bundled. */425export const bundle = (input: {426 readonly root: string;427 readonly out: string;428 readonly tsconfig: string;
15 unmodified lines
444 ],445 expect: "ok",446});447557/** Every file under `folder`, by its path from there. */448export const listFiles = (folder: string): GitStep => ({449 argv: ["find", folder, "-type", "f", "-printf", "%P\\0"],450 expect: "ok",451});452563/** One file's bytes, printed. */453export const readFile = (file: string): GitStep => ({454 argv: ["cat", "--", file],455 expect: "ok",456});457569// ------------------------------------------------------------------ reading570458const fields = (text: string) => text.split("\0").filter((part) => part !== "");459573/** What `merge-tree` printed: the merged tree, and the paths that conflict, sorted. */460export const readMerge = (stdout: string) => {461 const [tree = "", ...conflicts] = fields(stdout);462463 return {
3 unmodified lines
467 tree: TreeSha.make(tree.trim()),468 };469};470585/** A change's status, as a merge reports it. */471type Status = (typeof Merged.Type)["changes"][number]["status"];472473/** A raw diff's status letter as a change's status; a type change is a modification. */474const statusOf = (letter: string): Status | undefined => {
19 unmodified lines
494495// An object id of zeros: no object, on the side of a change that has none.496const NO_OBJECT = /^0+$/u;497613// A raw diff line's head: both modes, both blob ids, and the status letter.498const RAW =499 /^:\d+ \d+ (?<before>[0-9a-f]+) (?<after>[0-9a-f]+) (?<letter>[A-Z])/u;500617/** One change as a merge reports it. */501type Changed = (typeof Merged.Type)["changes"][number];502620/**621 * What `diff-tree -r -z --no-renames` printed, as changes in path order: a622 * file that changed type is modified, and a submodule's pointer counts as a623 * file, as `@repo/git/tree-diff` reads them.624 */503/** A submodule's pointer counts as a file, as `@repo/git/tree-diff` reads them. */504export const readChanges = (stdout: string) =>505 Array.chunksOf(fields(stdout), 2).flatMap(([meta, path = ""]) => {506 const raw = RAW.exec(meta)?.groups;507 const status = statusOf(raw?.letter ?? "");
17 unmodified lines
525526 return [change];527 });528650/** One commit as `firstParents` prints it. */529export interface Logged {530 readonly sha: CommitSha;531 readonly parents: readonly CommitSha[];532 readonly message: string;533}534657/** What `firstParents` printed. */535export const readLog = (stdout: string): readonly Logged[] =>536 fields(stdout).map((record) => {537 const newline = record.indexOf("\n");538 const head = newline === -1 ? record : record.slice(0, newline);
5 unmodified lines
544 sha: CommitSha.make(sha),545 };546 });547671/** What `lsTree` printed: each path's mode and id. */548export const readEntries = (stdout: string) =>549 new Map(550 fields(stdout).map((line) => {551 const tab = line.indexOf("\t");
2 unmodified lines
554 return [line.slice(tab + 1), { mode, sha }] as const;555 })556 );557682/** What `listFiles` printed: each file's path. */558export const readFiles = (stdout: string) => fields(stdout);559685/** What `lsRemote` printed: the ref's id, when the remote has it. */560export const readRemoteRef = (stdout: string) => {561 const [line = ""] = stdout.split("\n");562 const [sha = ""] = line.split("\t");563564 return sha === "" ? undefined : CommitSha.make(sha);565};566693/** How a push came out. */567export type Pushed =695 /** The ref now points where the push said, or already did. */568 | "moved"697 /** The ref was not where the push expected: someone else moved it first. */569 | "stale"570 /** Artifacts was busy with another push to the repo; retryable. */571 | "busy"701 /** Anything else. */572 | "failed";573574// git's words for a push the ref's current value refused: a client-side575// fast-forward check (`fetch first`, `non-fast-forward`, `stale info` for a
6 unmodified lines
582583// A porcelain line: the flag, `from:to`, and the summary.584const PORCELAIN = /^(?<flag>.)\t(?<refs>[^\t]*)\t(?<summary>.*)$/u;585716/** How the push of `ref` came out, from what git printed with `--porcelain`. */586export const readPush = (ran: Executed, ref: string): Pushed => {587 if (`${ran.stdout}\n${ran.stderr}`.includes(BUSY)) {588 return "busy";589 }
18 unmodified lines
modified:apps/sandbox/src/box.ts-10 removed
1/**2 * The `Box` port: the one container a Checker or a Lander Durable Object3 * runs its commands in. Both run through it, so their scripts are tested in4 * Node over local processes and run in a container in the5 * Worker (`box/sdk.ts`).6 */1import { Context, Schema } from "effect";2import type { Array, Effect } from "effect";310/** The container would not run a command, take a file or answer at all. */4export class BoxFailed extends Schema.TaggedError<BoxFailed>()("BoxFailed", {5 operation: Schema.Literals(["exec", "writeFile"]),6 reason: Schema.String,7}) {}816/** How one command runs: where, with what env, and for how long at most. */9export interface ExecOptions {10 readonly cwd?: string;11 readonly env?: Readonly<Record<string, string>>;12 readonly timeoutMs?: number;13}1423/** What one command left: its exit code and its output, as text. */15export interface Executed {16 readonly exitCode: number;17 readonly stdout: string;18 readonly stderr: string;
10 unmodified lines
29 readonly writeFile: (30 path: string,31 bytes: Uint8Array32 ) => Effect.Effect<void, BoxFailed>;42 /** Stops the container and drops everything in it. */33 readonly destroy: () => Effect.Effect<void>;34 }35>()("sandbox/Box") {}
modified:apps/sandbox/src/checker.ts+5 added-37 removed
1/**2 * The Checker: one container per check job, holding no credential, where an3 * answer's lanes run. Each job gets a Durable Object of4 * its own (a unique id), whose container is destroyed when the job ends; the5 * phases are `checker/run.ts`. The class name is frozen.6 *7 * One more Checker per project, named `snapshots:<project>`, never starts a8 * container: it keeps the ids of that project's setup snapshots, which every9 * check of the project shares.10 */1// Each check job gets a Checker of its own (a unique id). A Checker named2// `snapshots:<project>` never starts a container: it only keeps that3// project's snapshot ids.4import type { CheckRun } from "@repo/checks/check-runner";5import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";6import { keyOf } from "@repo/protocol/ids";7import { VerifierBlocked } from "@repo/protocol/refusal";
6 unmodified lines
14import { blocked, check } from "./checker/run.ts";15import { hasGateways, SdkChecker } from "./checker/sdk.ts";16import { answerJob } from "./job.ts";1725/** The run block's image a check runs in when it names none. */18const DEFAULT_IMAGE = "checker:default";1928/** That image's name in `wrangler.jsonc`, built from `images/check.Dockerfile`. */20const CHECK_IMAGE = "check";2131/**32 * The Checker's container size: two vCPUs and 8 GiB. oxlint with JS33 * plugins (burrow's lint lane) reserves about 6 GiB of address space per34 * thread for its fixed-size allocators (4 GiB aligned on 2 GiB), and Linux35 * refuses one reservation larger than the machine's memory: on the36 * runtime's default (`lite`, 256 MiB) the lane aborted on main and on every37 * answer, so each answer was `VerifierBlocked` (dev-oscabriel, 2026-10-08).38 * `standard-2`'s 6 GiB leaves no room for one. A restore from a snapshot39 * starts on it too.40 */22/** oxlint's JS plugins reserve about 6 GiB of address space per thread; smaller sizes abort. */23export const checkInstance = "standard-3";2443/** The Checker's Durable Object, which owns its container. */25export class Checker extends DurableObject<Env> {45 /** Runs one check job in this object's container, its outcome encoded. */26 check(wire: typeof CheckWire.Encoded): Promise<typeof CheckExit.Encoded> {27 return answerJob(CheckWire, CheckExit, (job) => this.#checked(job))(wire);28 }2950 /** The snapshot id kept under `key`, on a project's snapshot index. */30 snapshotOf(key: string): string | null {31 return this.ctx.storage.kv.get<string>(key) ?? null;32 }33
66 unmodified lines
100 );101 }102}103125/**126 * What the Checker needs of the sandbox's env: a new Checker for each job,127 * and each project's snapshot index (a Checker that never starts a128 * container). `Env` has both; they are written out so the Checker reads them129 * as the plain promises Workers RPC returns, and a test stands Checkers in130 * without its stub types.131 */104/** Written out so the Checker reads plain RPC promises and a test needs no stub types. */105export interface Checkers {106 readonly CHECKER: {107 readonly newUniqueId: () => DurableObjectId;108 readonly get: (id: DurableObjectId) => {
8 unmodified lines
117 };118 };119}120148/**149 * One check job from the platform, run in a Checker of its own, its outcome150 * encoded. A Checker that cannot be reached at all is `VerifierBlocked`, as151 * the job would have been.152 */121export const runCheck = (122 env: Checkers,123 wire: typeof CheckWire.Encoded124): Promise<typeof CheckExit.Encoded> =>
15 unmodified lines
modified:apps/sandbox/src/env-gateway.ts+5 added-63 removed
1/**2 * The env gateway: the outbound entrypoint each `@proxy` host's3 * HTTPS requests reach from the Checker's container4 * (`interceptOutboundHttps(host, EnvGateway)`, `checker/sdk.ts`), as in5 * Cloudflare's "call an authenticated API from a sandbox": the credential6 * stays on the Worker's side, and the entrypoint lets out only the requests7 * it allows.8 *9 * Its props are one job's rules and, for a job of landed code alone, the10 * values the platform opened for it (never in the container, and gone with11 * the job). A request that matches no rule, matches a `block` rule, is not12 * HTTPS, or matches two rules that would put two values in one placeholder,13 * is answered 403 and sent nowhere. One it allows goes on as the container14 * sent it, its headers' placeholders swapped for values where the gateway15 * holds them, with no header added; for an unlanded job it holds none, so16 * the placeholder goes on unchanged. The answer comes back with every value17 * the gateway holds scrubbed back to its placeholder, from the headers and18 * from an uncompressed text body (varlock's proxy does the same, VD proxy19 * l.145). A compressed or binary body comes back as it is.20 */1// Values stay on the Worker's side: placeholders are swapped in on the way2// out, and values scrubbed back to placeholders on the way in (headers and3// uncompressed text bodies only, as varlock's proxy does).4import type { EnvProxy } from "@repo/checks/check-runner";5import type { EnvKey } from "@repo/protocol/ids";6import { WorkerEntrypoint } from "cloudflare:workers";7import { Effect, Option, Order, Result, Stream } from "effect";89import { forward, refused, resent } from "./outbound.ts";1028/** A value the gateway may swap in, with the placeholder the process sees for it. */11export interface EnvSwapProps {12 readonly key: EnvKey;13 readonly placeholder: string;14 readonly value: string;15}1635/** One job's env route, as the gateway gets it: plain data, on the Worker's side. */17export interface EnvGatewayProps {18 readonly rules: readonly EnvProxy[];19 /** Empty unless the job runs landed code. */20 readonly values: readonly EnvSwapProps[];
17 unmodified lines
38 )}$`,39 "u"40 ).test(path);4161/** A rule's methods, written as one or a list (`GET, POST`); none allows any. */42const methodMatches = (methods: string, method: string) =>43 methods44 .split(",")45 .map((each) => each.trim().toUpperCase())
3 unmodified lines
49 hostMatches(rule.host, url.host) &&50 (rule.path === undefined || pathMatches(rule.path, url.pathname)) &&51 (rule.method === undefined || methodMatches(rule.method, method));5273/**74 * Text and what replaces it: a placeholder and its value on the way out, a75 * value and its placeholder on the way back.76 */53type Swap = readonly [from: string, to: string];5479/**80 * Whether `request` goes on, and with which swaps: the placeholder of each81 * rule it matches, for the value the gateway holds for that rule's key.82 * Refused, with the reason, when it is not HTTPS, matches no rule, matches83 * a `block` rule (which wins over any other), or matches two rules whose84 * one placeholder stands for two keys (the gateway would not know which85 * value goes).86 */55const swapsFor = (56 props: EnvGatewayProps,57 request: Request58): Result.Result<readonly Swap[], string> => {
44 unmodified lines
103 Order.flip(Order.Number),104 ([from]: Swap) => from.length105);106139/**140 * `text` with every `[from, to]` pair's `from` replaced by its `to`, the141 * longest first: a `DATABASE_URL` that holds a `DB_PASSWORD` goes whole,142 * not as the rest of the URL around the password's placeholder.143 */107const replaced = (text: string, pairs: readonly Swap[]) => {108 let done = text;109110 for (const [from, to] of pairs.toSorted(longestFirst)) {
2 unmodified lines
113114 return done;115};116154/** A copy of `headers` with each value's text replaced through `pairs`. */117const headersReplaced = (headers: Headers, pairs: readonly Swap[]) => {118 const copy = new Headers();119120 for (const [name, value] of headers) {
2 unmodified lines
123124 return copy;125};126165/** The request that goes on: the container's, its headers swapped. */127const sent = (request: Request, swaps: readonly Swap[]) =>128 resent(request.url, request, headersReplaced(request.headers, swaps));129169/** A body the gateway can read as text and scrub: text-like, and not compressed. */130const scrubbable = (headers: Headers) => {131 const type = headers.get("content-type")?.toLowerCase() ?? "";132 const encoding = headers.get("content-encoding")?.trim().toLowerCase() ?? "";133
5 unmodified lines
139 ))140 );141};142183/**184 * The length of the longest end of `text` that begins one of `values` but185 * is not all of it: held back until the next chunk says whether the value186 * completes there.187 */143/** How much of `text`'s end may begin a value: held back for the next chunk. */144const carried = (text: string, values: readonly string[]) =>145 Math.max(146 0,147 ...values.flatMap((value) =>
3 unmodified lines
151 )152 )153 );154199/**200 * A text body with every value replaced by its placeholder, chunk by201 * chunk, carrying across a chunk's end any text that may begin a value.202 */155const scrubbedBody = (156 body: ReadableStream<unknown>,157 scrubs: readonly Swap[]158) => {
28 unmodified lines
187 Stream.toReadableStream()188 );189};190239/**240 * The answer as the container gets it: every value the gateway holds241 * scrubbed back to its placeholder, in the headers and in a text body it242 * can read, of any length (streamed, so nothing is buffered whole). A243 * scrubbed body's length may change, so its `content-length` goes.244 */191/** A scrubbed body's length may change, so its `content-length` goes. */192const scrubbed = (response: Response, props: EnvGatewayProps): Response => {193 if (props.values.length === 0) {194 return response;195 }
21 unmodified lines
217 { headers, status: response.status, statusText: response.statusText }218 );219};220274/** What the gateway answers one request from the container with. */221const answer = (props: EnvGatewayProps, request: Request) =>222 Result.match(swapsFor(props, request), {223 onFailure: (reason) => Effect.succeed(refused(`${reason}\n`)),224 onSuccess: (swaps) =>
2 unmodified lines
227 (response) => scrubbed(response, props)228 ),229 });230285/**286 * The env gateway: one job's `@proxy` hosts reach it, and its props say287 * what it lets out and what it swaps in.288 */231export class EnvGateway extends WorkerEntrypoint<Env, EnvGatewayProps> {232 override fetch(request: Request): Promise<Response> {233 return Effect.runPromise(answer(this.ctx.props, request));234 }
1 unmodified line
modified:apps/sandbox/src/job.ts-12 removed
1/**2 * How the sandbox answers one job from the platform: decode its wire, run3 * it, and send back its `Exit` encoded as JSON (principle 2: both sides of4 * the service binding decode with the same schemas). A wire that does not5 * decode, or an outcome that does not encode, is a defect: the platform6 * encoded the job with the same schema.7 */1import { Effect, Schema } from "effect";2import type { Exit } from "effect";34export const answerJob =
13 unmodified lines
18 )19 )20 );2129/**30 * A job whose side of the sandbox is not built yet: `VerifierBlocked`, the31 * gate's trouble and never the answer's, with `not built` in a log32 * annotation, since a refusal carries no free text (principle 3).33 */22export const notBuilt = <E>(job: string, blocked: E) =>23 Effect.logWarning("sandbox job not built").pipe(24 Effect.annotateLogs({ job, reason: "not built" }),25 Effect.andThen(Effect.fail(blocked))
1 unmodified line
modified:apps/sandbox/src/lander.ts+6 added-39 removed
1/**2 * The Lander: the trusted container that merges answers, composes ask files,3 * lands checked trees on canonical `main` with a non-force push, and bundles4 * the config folder. It runs no answer's code: only git, and5 * bun's bundler with macros off. The class name is frozen.6 *7 * One Lander Durable Object per project, named by the project's canonical8 * repo, owns one container and runs one job at a time in it: its jobs share9 * the container's copy of the repo and its scratch files, and a project's10 * landings stay serial here as they are in the Project DO's queue.11 */1// The trusted container: it runs no answer's code, only git and bun's bundler2// with macros off. One per project, one job at a time, so landings stay serial.3import {4 BundleExit,5 BundleWire,6 ComposeExit,
11 unmodified lines
18import { SdkBox } from "./box/sdk.ts";19import { answerJob } from "./job.ts";20import { bundleRules, compose, land, merge } from "./lander/run.ts";2131/** The image the Lander's container runs: `images.land` in `wrangler.jsonc`. */22export const landImage = "land";2334/**35 * The Lander's four jobs as the service binding carries them: each decoded,36 * run in `box` while it holds `turn` (one job at a time), and its `Exit`37 * encoded as JSON.38 */24export const landerJobs = (25 box: Layer.Layer<Box>,26 turn: Semaphore.Semaphore27) => {
11 unmodified lines
39 merge: answerJob(MergeWire, MergeExit, (wire) => inBox(merge(wire))),40 };41};4258/**59 * The Lander's container size: a whole vCPU. On the runtime's default60 * (`lite`, 1/16 vCPU) one landing took 32 s and a config bundle 20 s on61 * dev-oscabriel, against a target of 5 s.62 */43/** On the default `lite` (1/16 vCPU) one landing took 32 s. */44export const landInstance = "standard-2";4565/**66 * The Lander's Durable Object, which owns its container: started on its67 * first job from the `land` image on `landInstance`, with internet on,68 * since git reaches Artifacts over HTTPS with the tokens each job carries.69 */46/** Internet on: git reaches Artifacts over HTTPS with each job's tokens. */47export class Lander extends DurableObject<Env> {48 readonly #jobs: ReturnType<typeof landerJobs>;4950 constructor(ctx: DurableObjectState, env: Env) {
35 unmodified lines
86 return this.#jobs.bundleRules(wire);87 }88}89113/** The Lander's jobs as its Durable Object takes them over RPC. */90export type LanderJobs = Pick<91 Lander,92 "bundleRules" | "compose" | "land" | "merge"93>;94119/**120 * The one binding the jobs reach: the Lander namespace, by what it gives.121 * The Worker's `Env` is one; so is a test's fake. (The generated `Env` names122 * the class through an `import()` the type-aware linter does not follow, so123 * it would read a stub straight from `Env` as `any`.)124 */95// The generated `Env` names the class through an `import()` the type-aware96// linter does not follow, so a stub read straight from `Env` would be `any`.97export interface Landers {98 readonly LANDER: { readonly getByName: (name: string) => LanderJobs };99}100129/** The project's Lander: one per canonical repo, so one container per project. */101const landerOf = (102 env: Landers,103 wire: { readonly job: { readonly repo: string } }104) => env.LANDER.getByName(wire.job.repo);105135/** An answer's head merged onto canonical `main`, in the project's Lander. */106export const runMerge = (107 env: Landers,108 wire: typeof MergeWire.Encoded109): Promise<typeof MergeExit.Encoded> => landerOf(env, wire).merge(wire);110141/** A checked tree landed on canonical `main`, in the project's Lander. */111export const runLand = (112 env: Landers,113 wire: typeof LandWire.Encoded114): Promise<typeof LandExit.Encoded> => landerOf(env, wire).land(wire);115147/** A decider's files composed onto canonical `main`, on a compose ref. */116export const runCompose = (117 env: Landers,118 wire: typeof ComposeWire.Encoded119): Promise<typeof ComposeExit.Encoded> => landerOf(env, wire).compose(wire);120153/** The config folder at a landed commit, bundled for the rules evaluator. */121export const runBundleRules = (122 env: Landers,123 wire: typeof BundleWire.Encoded124): Promise<typeof BundleExit.Encoded> => landerOf(env, wire).bundleRules(wire);
modified:apps/sandbox/src/outbound.ts+5 added-39 removed
1/**2 * The Checker container's only ways out, as outbound entrypoints of this Worker3 * (the outbound handler is the credential boundary). The container starts with4 * the internet off; its Durable Object routes the clone's host to5 * `CloneGateway` and every other host to `EgressGateway` (`checker/sdk.ts`),6 * each told what it may do through its props, which the container never sees.7 *8 * Both are reached through `ctx.exports`, which holds one loopback per export9 * of the Worker's main module, so `worker.ts` must export them.10 */1// The Checker container's only ways out: the outbound handler is the2// credential boundary, and the container never sees a gateway's props.3import { WorkerEntrypoint } from "cloudflare:workers";4import { Option } from "effect";56import { allows, CLONE_HOST } from "./checker/network.ts";716/** One job's remote and the read token the platform minted for it alone. */8export interface CloneProps {9 readonly remote: string;10 readonly token: string;11}1222/** The hosts the container may reach right now; `[]` is none. */13export interface EgressProps {14 readonly allow: readonly string[];15}1627/** A 403 whose plain-text body says why; `text` ends with its own newline. */17export const refused = (text: string) =>18 new Response(text, {19 headers: { "content-type": "text/plain; charset=utf-8" },20 status: 403,21 });2234/**35 * Sends a request on to the internet. Redirects come back to the container,36 * so the request that follows one goes through a gateway too.37 */23/** Redirects go back to the container, so a followed one passes a gateway too. */24export const forward = (request: Request): Promise<Response> =>25 // @effect-diagnostics-next-line globalFetch:off -- an outbound entrypoint is the Worker's own network edge: workerd hands it a Request and takes back a Response, and its only way to the internet is the runtime's fetch; sandbox code may not use effect/http.26 fetch(request, { redirect: "manual" });2742/**43 * `request` as a new request to `url` with `headers`: its method, and its44 * body streamed through as it comes.45 */28export const resent = (url: string, request: Request, headers: Headers) => {29 // Node sends a streamed body only with `duplex: "half"`; the Workers types30 // lack the key, and workerd ignores it.31 const init = {
5 unmodified lines
3738 return new Request(url, init);39};4059/**60 * The request the clone gateway sends for one from the container: a read of61 * the job's repo (`git-upload-pack`, as a clone or fetch makes) at the clone62 * host, exactly as git asks for one, sent to the remote with the token63 * added. Anything else, a push or a query git never sends included, is none.64 */41/** Only `git-upload-pack` reads of the job's repo pass; a push or any other query does not. */42const cloneRequestFor = (43 request: Request,44 props: CloneProps45): Option.Option<Request> => {
21 unmodified lines
67 resent(`${remote.origin}${url.pathname}${url.search}`, request, headers)68 );69};7094/**95 * The clone's way out: the container clones the job's repo from the clone96 * host with no credential, and this entrypoint sends each read on to the97 * repo's real remote with `Authorization: Bearer <token>` (as the Artifacts98 * probes sent it, and as it works live). The token lives99 * in its props, on the Worker's side.100 */71/** The container clones with no credential; the token is added here, on the Worker's side. */72export class CloneGateway extends WorkerEntrypoint<Env, CloneProps> {73 override fetch(request: Request): Promise<Response> {74 return Option.match(cloneRequestFor(request, this.ctx.props), {75 onNone: () =>
4 unmodified lines
80 });81 }82}83113/**114 * Every other way out: a request to a host its props allow goes on as it115 * is, and any other is refused with a 403 that names the host, so a setup116 * that fails on one says which.117 */84export class EgressGateway extends WorkerEntrypoint<Env, EgressProps> {85 override fetch(request: Request): Promise<Response> {86 const { hostname } = new URL(request.url);87
9 unmodified lines
modified:apps/sandbox/src/worker.ts+1 added-10 removed
1/**2 * The sandbox Worker. Its default entrypoint is reached only through the3 * platform's `SANDBOX` service binding: each method takes a job's wire,4 * encoded, and returns the job's `Exit`, encoded as JSON, so both sides5 * decode with the schemas in `@repo/checks/check-runner/wire` and6 * `@repo/project/lander/wire`.7 */1import type { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";2import type {3 BundleExit,4 BundleWire,
12 unmodified lines
17export { Checker } from "./checker.ts";1819export { Lander } from "./lander.ts";2028// The Checker's container reaches out only through these, and its Durable29// Object finds them in `ctx.exports`, which holds a loopback for each export30// of this module alone (outbound.ts, env-gateway.ts).21// `ctx.exports` holds a loopback only for the main module's exports.22export { CloneGateway, EgressGateway } from "./outbound.ts";2324export { EnvGateway } from "./env-gateway.ts";25
25 unmodified lines
modified:apps/sandbox/test/box-sdk.test.ts-6 removed
14 unmodified lines
1516 return buffer;17};1819/**20 * A Durable Object's container as the Container API shows it: it records21 * what starts it and each command it runs, and every command prints22 * `git version 2.47.3`.23 */19const fakeContainer = (running: boolean) => {20 const started: ContainerStartupOptions[] = [];21 const commands: { argv: string[]; options: ContainerExecOptions }[] = [];22
24 unmodified lines
47};4849const start = { enableInternet: false, image: "check" };5056/** A running container whose one command never ends until it is killed. */51const hungContainer = () => {52 const killed: (number | undefined)[] = [];5354 const container = untouchable<Container>("container", {
90 unmodified lines
modified:apps/sandbox/test/checker.test.ts+1 added-32 removed
81 unmodified lines
82 call.argv[0] === "sh" &&83 call.argv[1] === "-c" &&84 call.argv[2] === command;8586/** How many times setup's command ran. */86const setups = (calls: readonly Call[]) =>87 calls.filter((call) => isShell(call, SETUP)).length;8890/**91 * The recording as phases, each run of calls for one phase read as one:92 * the clone's route and git commands, setup's snapshot lookup, network and93 * command, the snapshot, egress off, the lanes, the report, the destroy.94 */89const phaseOf = Match.type<Call>().pipe(90 Match.discriminatorsExhaustive("kind")({91 allow: ({ hosts }): readonly string[] =>92 hosts.length === 0 ? ["egressOff"] : ["setup"],
61 unmodified lines
154 })155 )156 );157164 // Setup ran while egress allowed the registries and the run block's165 // own setup host, and nothing else.158 const setupAt = fake.calls.findIndex((call) => isShell(call, SETUP));159160 const egress = fake.calls161 .slice(0, setupAt)
3 unmodified lines
165 hosts: [...REGISTRIES, "npm.pkg.github.com"],166 kind: "allow",167 });168177 // The lanes ran in the job's order, after egress went off.169 expect(170 fake.calls.flatMap((call) =>171 call.kind === "exec" && call.argv[0] === "sh" ? [call.argv[2]] : []172 )
79 unmodified lines
252 : []253 )254 ).toStrictEqual(["evil.example"]);255265 // Nothing ran after setup, nothing was kept, and the box is gone.256 expect(phasesOf(fake.calls)).toStrictEqual([257 "clone",258 "setup",259 "report",
41 unmodified lines
301 signature:302 "week > parses ISO weeks: AssertionError: expected 52 to be 53",303 },304 ]);315 // No raw log travels in the result.305 expect(JSON.stringify(ran)).not.toContain("Cannot find module");306 })307 );308
45 unmodified lines
354 expect(ran.outputs).toStrictEqual([355 { lane: "no-explicit-any", stdout: printed },356 ]);357369 // The outcome crosses the binding with it.358 const crossed = yield* Schema.encodeEffect(CheckExit)(359 Exit.succeed(ran)360 ).pipe(Effect.flatMap(Schema.decodeEffect(CheckExit)));361
42 unmodified lines
404 call.kind === "restore" ? [call.hit] : []405 )406 ).toStrictEqual([true]);407420 // The restored workspace is checked out at this job's tree again421 // before any lane runs.408 const restoredAt = second.calls.findIndex(409 (call) => call.kind === "restore"410 );411
103 unmodified lines
515 })516 );517});518533/** The requests the Worker sends on, in place of the network, until the scope ends. */519const outboundRecorded = Effect.acquireRelease(520 Effect.sync(() => {521 const sent: Request[] = [];522
180 unmodified lines
703 })704 );705});706722/**723 * The sandbox's `CHECKER` namespace: each unique id gets a Checker over its724 * own fake container, and `snapshots:<project>` names an index kept in725 * `index`.726 */707const checkerWorld = (options: {708 readonly withGateways: boolean;729 /** Whether each Checker's container is running before its job; it is unless false. */709 readonly running?: boolean;710}) => {711 const boxes: ReturnType<typeof fakeContainer>[] = [];712 const index = new Map<string, string>();713 const named: string[] = [];714736 /** A project's snapshot index, as Workers RPC hands one back. */715 const indexStub = untouchable<DurableObjectStub<Checker>>("index", {716 forgetSnapshot: (key) => {717 index.delete(key);718
16 unmodified lines
735736 return indexStub;737 };738761 // A Checker reaches only its project's snapshot index through the env.739 const env: Env = {740 CHECKER: untouchable<Env["CHECKER"]>("CHECKER", { getByName: indexNamed }),741 LANDER: untouchable("LANDER"),742 };
29 unmodified lines
772773const encodedWire = () =>774 Schema.encodeEffect(CheckWire)(wireFor()).pipe(Effect.orDie);775799/**800 * Two jobs of one project through `runCheck`, one after the other, each in801 * a container that runs before it starts unless `running` is false.802 */776const twoJobsIn = ({ running = true } = {}) =>777 Effect.gen(function* () {778 const world = checkerWorld({ running, withGateways: true });779 const wire = yield* encodedWire();
50 unmodified lines
830 expect(intercepts(boxes[0]?.calls ?? [])).toStrictEqual([831 `${CLONE_HOST} → clone ${REMOTE} ${TOKEN}`,832 "* → egress []",833 "http:* → egress []",861 // Setup reaches the registries and its own hosts, not the repo.834 `${CLONE_HOST} → egress [${setupHosts}]`,835 `* → egress [${setupHosts}]`,836 `http:* → egress [${setupHosts}]`,837 `${CLONE_HOST} → egress []`,
43 unmodified lines
881 Effect.gen(function* () {882 const { boxes } = yield* twoJobsIn({ running: false });883884 // oxlint with JS plugins reserves 6 GiB of address space per913 // thread, which Linux refuses on a smaller instance: on the914 // runtime's default (`lite`, 256 MiB) burrow's lint lane aborted915 // on main and on every answer, so each answer was VerifierBlocked916 // (dev-oscabriel, 2026-10-08).885 // thread, which Linux refuses on a smaller instance.886 const starts = boxes.flatMap(({ calls }) =>887 calls.flatMap((call) => (call.kind === "start" ? [call] : []))888 );889
28 unmodified lines
modified:apps/sandbox/test/env-injection.test.ts-21 removed
1/**2 * The Checker's env: every `@sensitive` item reaches3 * the container as its placeholder, and a `@proxy` host's requests go4 * through the env gateway, which swaps the placeholder for the value only in5 * a run of landed code. Over the fake `Box` (`fake-box.ts`), and the gateway6 * itself with a fake upstream.7 */1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import type { CheckJob } from "@repo/checks/check-runner";4import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";
36 unmodified lines
41const SENTRY = EnvKey.make("SENTRY_AUTH_TOKEN");4243const PLACEHOLDER = "__SENTRY_AUTH_TOKEN_PLACEHOLDER__";4452/** The write-only value a landed run's gateway swaps in: never in the container. */45const VALUE = "sntrys_5f0c1d2e3b4a69788796a5b4c3d2e1f0";4647const sentryRule = {48 block: false,
19 unmodified lines
68 ...env,69 },70});7180/** The env `sh -c <command>` ran with, for each run of `command`. */72const envsOf = (calls: readonly Call[], command: string) =>73 calls.flatMap((call) =>74 call.kind === "exec" && call.argv[0] === "sh" && call.argv[2] === command75 ? [call.options.env ?? {}]76 : []77 );7888/** One job through the Checker over the fakes: what they saw. */79const checked = (wire: CheckWire) =>80 Effect.gen(function* () {81 const fake = fakeChecker();82
3 unmodified lines
8687 return { calls: fake.calls, outcome };88 });89100/** A job of landed code, carrying the value its gateway swaps in. */90const landedJob = () =>91 jobWith({92 landed: true,93 values: [{ key: SENTRY, value: Redacted.make(VALUE) }],
134 unmodified lines
228 })229 );230});231243/**244 * What the gateway sends on, in place of the network, until the scope245 * ends: each request, read, and the response `answer` gives for it.246 */232const upstream = (answer: (request: Request) => Response) =>233 Effect.acquireRelease(234 Effect.sync(() => {235 const sent: Request[] = [];
8 unmodified lines
244 }),245 () => Effect.sync(() => vi.unstubAllGlobals())246 );247263/** A gateway for one job: its rules, and the values only a landed job's carries. */248const gatewayFor = (props: Partial<EnvGatewayProps> = {}) =>249 new EnvGateway(250 untouchable<ExecutionContext<EnvGatewayProps>>("ctx", {251 props: { rules: [sentryRule], values: [], ...props },
12 unmodified lines
264 },265 method: "POST",266 });267284/** What reached the upstream: method, URL, every header, and the body. */268const readSent = (request: Request) =>269 Effect.promise(() => request.text()).pipe(270 Effect.map((body) => ({271 body,
212 unmodified lines
484 })485 );486});487505/**506 * One job through a Checker Durable Object over a fake container (the507 * Container API as `fake-box.ts` records it): the calls it made.508 */488const inContainer = (wire: CheckWire) =>489 Effect.gen(function* () {490 const box = fakeContainer();491
179 unmodified lines
modified:apps/sandbox/test/fake-box.ts+1 added-35 removed
1/**2 * The Checker's capabilities as fakes that record every call, in order, in3 * one list: the container (`Box`), its network, its snapshots, where its logs4 * go, and the Worker's own log lines. A test scripts what each command prints5 * and reads back what the Checker did, phase by phase.6 */1import { untouchable } from "@repo/testkit/untouchable";2import { Effect, Layer, Logger, Redacted, References } from "effect";34import { Box } from "../src/box.ts";
4 unmodified lines
9import { Snapshots } from "../src/checker/snapshots.ts";10import type { EnvGatewayProps } from "../src/env-gateway.ts";11import type { CloneProps, EgressProps } from "../src/outbound.ts";1219/** What the container could reach at one moment. */13export type Reach = "clone route" | readonly string[];1422/** One thing the Checker did, as the fakes saw it. */15export type Call =16 | {17 readonly kind: "exec";18 readonly argv: readonly string[];19 readonly options: ExecOptions;28 /**29 * What the network let out as the command started: the clone route30 * alone before the first `allow`, then the hosts that `allow` named.31 */20 readonly network: Reach;21 }22 | { readonly kind: "writeFile"; readonly path: string; readonly text: string }23 | { readonly kind: "destroy" }
19 unmodified lines
43 readonly message: string;44 readonly annotations: Readonly<Record<string, string>>;45 };4659/** What a command left, for a script. */47export const exited = (48 exitCode: number,49 output: { readonly stdout?: string; readonly stderr?: string } = {}50): Effect.Effect<Executed, BoxFailed> =>
3 unmodified lines
54 stdout: output.stdout ?? "",55 });5657export interface FakeOptions {71 /**72 * What `sh -c <command>` does, by command (setup and lanes). A command not73 * listed exits 0 and prints nothing.74 */58 /** A command not listed exits 0 and prints nothing. */59 readonly commands?: ReadonlyMap<string, Effect.Effect<Executed, BoxFailed>>;76 /** What `git ls-tree` prints: the lockfiles at the checked-out tree. */60 readonly lockfiles?: string;78 /** Snapshot keys kept so far, shared by the jobs a test runs. */61 readonly snapshots?: Set<string>;80 /** What writing a file does, by path; every write succeeds when absent. */62 readonly writeFile?: (path: string) => Effect.Effect<void, BoxFailed>;63}6484/** A lockfile listing, as `git ls-tree HEAD -- <names>` prints one. */65export const LOCKFILES =66 "100644 blob 8f2c1d0e9b7a6c5d4e3f2a1b0c9d8e7f6a5b4c3d\tbun.lock\n";6788/** The command `sh -c <command>` runs, or none for any other argv. */68const shellCommandOf = (argv: readonly string[]) =>69 argv[0] === "sh" && argv[1] === "-c" ? argv[2] : undefined;7092/** The fakes for one job, and the list their calls go to. */71export const fakeChecker = (options: FakeOptions = {}) => {72 const calls: Call[] = [];73 const kept = options.snapshots ?? new Set<string>();74 let reach: Reach = "clone route";
108 unmodified lines
183 ])184 ),185 kind: "log",186 level: logLevel,209 // A log line's message is its arguments, one string here.187 message: String(message),188 });189 }),190 ]);
3 unmodified lines
194 layer: Layer.mergeAll(box, network, snapshots, logs, logger),195 };196};197221/** One thing done to a Durable Object's container, as the Container API saw it. */198export type ContainerCall =199 | {200 readonly kind: "exec";201 readonly argv: readonly string[];
2 unmodified lines
204 | { readonly kind: "intercept"; readonly target: string; readonly to: string }205 | {206 readonly kind: "start";207 readonly from: string;232 /** The instance size the start named, when it named one. */208 readonly instance?: ContainerStartupOptions["instance"];209 }210 | { readonly kind: "snapshot" }211 | { readonly kind: "destroy" };
6 unmodified lines
218219 return buffer;220};221247/**248 * A container as the Container API shows a Durable Object one, running249 * unless `running` says otherwise (a stopped one is started before each250 * command): it records each call, prints a lockfile listing for `git251 * ls-tree`, and exits 0 with no output for every other command. Its252 * outbound intercepts record which gateway, with which props, took each253 * target.254 */222export const fakeContainer = ({ running = true } = {}) => {223 const calls: ContainerCall[] = [];224 const gateways = new Map<Fetcher, string>();225
62 unmodified lines
288 );289 },290 });291325 /** The loopbacks `ctx.exports` holds for the Worker's outbound gateways. */292 const exports = {293 CloneGateway: ({ props }: { readonly props: CloneProps }) =>294 gateway(`clone ${props.remote} ${props.token}`),295 EgressGateway: ({ props }: { readonly props: EgressProps }) =>
10 unmodified lines
modified:apps/sandbox/test/fake-env.ts-4 removed
1import { untouchable } from "@repo/testkit/untouchable";23/**4 * The sandbox Worker's env, as `wrangler.jsonc` declares it: each binding a5 * fake that throws if touched, so a test proves what a call touches.6 */3export const fakeEnv = (): Env => ({4 CHECKER: untouchable("CHECKER"),5 LANDER: untouchable("LANDER"),6});
modified:apps/sandbox/test/held-back.test.ts+1 added-23 removed
56 unmodified lines
57const exportArea = AreaName.make("export");5859const parser = AreaName.make("parser");6061/**62 * The maintainers' sealed suite: two areas, three files. Each file names63 * its own test and carries a canary, so a leak of either is searchable.64 */61/** Each file carries a canary, so a leak is searchable. */62const SEALED = [63 {64 area: exportArea,65 path: "checks/held-back/export/round-trip.test.ts",
18 unmodified lines
84}));8586const weekFile = SEALED.at(-1);8791/** What the parser's sealed check prints as it fails. */88const PARSER_STDOUT = `(fail) parser > ${weekFile?.test}\n`;8990const PARSER_STDERR =91 "AssertionError: expected Week(54) to be undefined at week-54.test.ts:3\n";
35 unmodified lines
127 run,128 },129});130135/** The fake, with the parser's sealed check failing. */131const parserFails = (options: FakeOptions = {}) =>132 fakeChecker({133 commands: new Map([134 [
7 unmodified lines
142const sealedCommands: ReadonlySet<string> = new Set(143 SEALED.map(({ command }) => command)144);145151/**152 * Whether `call` writes the sealed files or readies their place: a file153 * written, or a command that names a path in the work tree (no lane or154 * sealed check does; each runs in it).155 */146const writesSealed = (call: Call) =>147 call.kind === "writeFile" ||148 (call.kind === "exec" && call.argv.some((arg) => arg.startsWith(`${REPO}/`)));149
1 unmodified line
151 call.kind === "exec" && call.argv[0] === "sh" && call.argv[1] === "-c"152 ? Option.fromUndefinedOr(call.argv[2])153 : Option.none();154165/** The recording as phases, each run of calls for one phase read as one. */155const phaseOf = Match.type<Call>().pipe(156 Match.discriminatorsExhaustive("kind")({157 allow: ({ hosts }): readonly string[] =>158 hosts.length === 0 ? ["egressOff"] : ["setup"],
33 unmodified lines
192 calls193 .flatMap(phaseOf)194 .filter((phase, at, all) => at === 0 || all[at - 1] !== phase);195207/** Everything about the suite that must never leave the Checker. */196const SECRETS = [197 ...SEALED.flatMap(({ path, test, text }) => [198 path,199 path.split("/").at(-1) ?? path,
5 unmodified lines
205 PARSER_STDERR.trim(),206 "Week(54)",207];208221/** The secrets `text` holds. */209const leakedIn = (text: string) =>210 SECRETS.filter((secret) => text.includes(secret));211225/** What leaves the Checker besides its result: the logs it hands over and its log lines. */212const leftBy = (calls: readonly Call[]) =>213 JSON.stringify(214 calls.filter((call) => call.kind === "report" || call.kind === "log")215 );216231/** One job with the sealed suite, the parser's check failing: what the fakes saw, and the outcome. */217const sealedJob = Effect.gen(function* () {218 const fake = parserFails();219220 const outcome = yield* Effect.exit(
9 unmodified lines
230});231232const LINT_COUNT = "oxlint --format json";233249/** Public lanes that print what they found: `unit`, and a count lane. */234const printing = () =>235 fakeChecker({236 commands: new Map([237 [UNIT, printedBeside],238 [LINT_COUNT, printedBeside],239 ]),240 });241258/** The job's wire with a count lane after `unit`. */242const withCountLane = (sealed: Option.Option<HeldBackPart>): CheckWire => {243 const base = wireFor(sealed);244245 return {
11 unmodified lines
257 },258 };259};260278/** The outcome as it crosses the service binding, as JSON. */261const serialized = (outcome: Exit.Exit<CheckRun, VerifierBlocked>) =>262 Schema.encodeEffect(CheckExit)(outcome).pipe(263 Effect.map((encoded) => JSON.stringify(encoded))264 );
17 unmodified lines
282 "report",283 "destroy",284 ]);285304 // The order is the plan's, the sealed checks running in its `Run`.286 expect(287 phasesOf(calls)288 .slice(1, -1)289 .filter((phase) => phase !== "runHeldBack")
8 unmodified lines
298 ({ _tag }) => `${_tag.charAt(0).toLowerCase()}${_tag.slice(1)}`299 )300 );301321 // Setup reached the registries and its own host, nothing else.302 expect(303 calls.find(304 (call) =>305 call.kind === "exec" && Option.contains(shellOf(call), SETUP)
111 unmodified lines
417 const ran = yield* check(withCountLane(Option.some(heldBack))).pipe(418 Effect.provide(fake.layer)419 );420441 // Only how each lane ended leaves.421 expect(422 ran.lanes.map(({ lane, result }) => ({ lane, result }))423 ).toStrictEqual([424 { lane: "unit", result: "failed" },
226 unmodified lines
651 )652 );653654 it("takes the held-back job the platform reads from the layer as it is", () => {676 // `ProjectApi.heldBackJob`'s job is the `CheckJob`'s held-back part.655 expectTypeOf<HeldBackJob>().toEqualTypeOf<HeldBackPart>();656 });657658 it.effect(
31 unmodified lines
modified:apps/sandbox/test/lander.fixtures.ts+1 added-39 removed
44 unmodified lines
4546/** The token every remote carries: no command line, result or log may show it. */47export const secret = "art_v1_0123456789abcdef0123456789abcdef01234567";4849/** A path in this repo, from the sandbox's test folder. */49export const inRepo = (path: string) =>50 new URL(`../../../${path}`, import.meta.url).pathname;5153/**54 * The sdk a config folder's imports resolve to: this repo's own, where the55 * image keeps its copy under `/opt/sdk` (its entry, and the packages its own56 * imports resolve in).57 */52export const sdk = {53 entry: inRepo("packages/sdk/src/index.ts"),54 modules: inRepo("packages/sdk/node_modules"),55};5663/** What a file holds after a commit, or `null` for a file the commit deletes. */57export type Files = Readonly<Record<string, string | null>>;5866/** The message of a landing that credits dora as asker and bob as answerer. */59export const message = formatLanding({60 assisted: [],61 credits: [62 { handle: dora, role: "Asked-by" },
23 unmodified lines
86 tree: input.tree,87 verifier: "platform",88 });8998/** Every ref of a bare repo, with what it points at. */90const refsOf = (repo: string) =>91 gitOk(repo, "for-each-ref", "--format=%(refname) %(objectname)");92102/** What a bare repo holds: its refs, and how many objects. */93const stateOf = (repo: string) =>94 Effect.all({95 objects: gitOk(repo, "count-objects", "-v"),96 refs: refsOf(repo),97 });98109/** One revision's id in a bare repo, or `None` when it has none. */99const revision = (repo: string, rev: string) =>100 Effect.map(101 git(repo, "rev-parse", "--verify", "--quiet", rev),102 ({ exitCode, stdout }) =>103 exitCode === 0 ? Option.some(stdout.trim()) : Option.none()104 );105117/** A repo's remote as a job carries it: its URL, and a token for it. */106const remote = (url: string) => ({ token: Redacted.make(secret), url });107120/**121 * Two bare repos on disk, canonical and the claim's fork, and a working122 * clone the test makes commits in and pushes from, as people would. The123 * Lander under test works in its own folder (`layout.work`) and reaches the124 * repos only through the remotes it is handed.125 */108export const world = Effect.gen(function* () {109 const fs = yield* FileSystem.FileSystem;110 const path = yield* Path.Path;111 const root = yield* fs.makeTempDirectoryScoped({ prefix: "lander-" });
6 unmodified lines
118 yield* gitOk(root, "init", "--quiet", "--bare", "-b", "main", forkDir);119 yield* gitOk(root, "init", "--quiet", "-b", "main", clone);120 yield* fs.makeDirectory(work);121140 /** A commit of `files` over `parent` (or over nothing), made in the clone. */122 const commit = (123 parent: CommitSha | undefined,124 files: Files,125 subject: string
19 unmodified lines
145146 return CommitSha.make(yield* gitOk(clone, "rev-parse", "HEAD"));147 });148168 /** Sets `ref` in the bare repo `repo` to `sha`, as a person's push would. */149 const push = (repo: string, sha: CommitSha, ref = "refs/heads/main") =>150 gitOk(clone, "push", "--quiet", "--force", repo, `${sha}:${ref}`);151172 /** A blob's id at `file` in `at`, read in the clone. */152 const blobAt = (at: CommitSha, file: string) =>153 Effect.map(gitOk(clone, "rev-parse", `${at}:${file}`), (blob) =>154 BlobSha.make(blob)155 );156178 /** The tree git's own merge of `theirs` into `ours` makes, in the clone. */157 const mergedTree = (ours: CommitSha, theirs: CommitSha) =>158 Effect.gen(function* () {159 yield* gitOk(clone, "checkout", "--quiet", "--detach", ours);160 yield* gitOk(clone, "merge", "--quiet", "--no-edit", theirs);
73 unmodified lines
234235 return { base, clash, head, main: LandedSha.make(main) };236 });237260/** The mirror ref a landing moves, after main. */238export const landedRefName = `${Brand.refsPrefix}landed`;239263/**264 * The Lander's container, as local processes working in `work`: the sdk is265 * this repo's, and the file naming its version (which the image writes when266 * it is built) is written beside `work`.267 */240export const layout = (work: string) =>241 Layer.effect(242 Layout,243 Effect.gen(function* () {
10 unmodified lines
254 };255 }).pipe(Effect.orDie)256 ).pipe(Layer.provide(NodeServices.layer));257286/** The Lander's container over local processes, its `Box` changed by `wrap` when a test needs to. */258export const box = (259 work: string,260 wrap: (inner: Box["Service"]) => Box["Service"] = (inner) => inner261) =>
3 unmodified lines
265 );266267export const TestServices = NodeServices.layer;268298/** A file's path in the config folder. */269export const config = (file: string) => `${Brand.configDir}/${file}`;270301/**302 * A config folder as maintainers write one: the project module (importing303 * the sdk by its published name, and a helper beside it), an ask file304 * (importing the sdk by its workspace name), the ask's check, which imports305 * a test runner the Lander never has, the visibility module, and the vouch306 * file.307 */271/** The ask's check imports a test runner the Lander never has. */272export const configFolder = {273 [config("asks/parse-iso.ask.ts")]: [274 'import { kinds, territory } from "@repo/sdk";',275 "",
37 unmodified lines
313 ].join("\n"),314 [config("vouched.td")]: "dora\nbob\n",315} satisfies Files;316353/** datekit's first commit with `files` beside its code, on canonical `main`. */317export const startedWith = (repos: World, files: Files) =>318 Effect.gen(function* () {319 const at = yield* repos.commit(undefined, { ...start, ...files }, "Start");320
1 unmodified line
322323 return LandedSha.make(at);324 });325363/** A bundle of datekit's config folder at `at`. */326export const bundleWire = (repos: World, at: LandedSha) => ({327 job: { at, repo: project },328 main: repos.remote(repos.canonical),329});
modified:apps/sandbox/test/lander.test.ts+3 added-50 removed
48 unmodified lines
49 world,50} from "./lander.fixtures.ts";51import type { Files, World } from "./lander.fixtures.ts";5253/** The merge of bob's answer at `head` onto datekit's `main`. */53const mergeWire = (54 repos: World,55 job: {56 readonly base: CommitSha;
5 unmodified lines
62 job: { ...job, fork, repo: project },63 main: repos.remote(repos.canonical),64});6567/** A land of bob's answer, merged again from `head`, onto datekit's `main`. */66const landWire = (67 repos: World,68 job: {69 readonly base: CommitSha;
15 unmodified lines
85 },86 main: repos.remote(repos.canonical),87});8891/** A commit in a bare repo as git shows it: who made it, on what, and its message. */89const commitIn = (repo: string, sha: string) =>90 Effect.gen(function* () {91 const shown = yield* gitOk(92 repo,
16 unmodified lines
109 });110111const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));112116/** Whether a command is the push that moves canonical `main`. */113const pushesMain = (argv: readonly string[]) =>114 argv.includes("push") && argv.at(-1)?.endsWith(":refs/heads/main") === true;115120/**121 * The Lander's container, where `first` runs just before git pushes `main`:122 * someone else moving main between the Lander's fetch and its push.123 */116const beforeMainIsPushed =117 (first: Effect.Effect<void>) =>118 (inner: Box["Service"]): Box["Service"] => ({119 ...inner,
2 unmodified lines
122 ? Effect.andThen(first, inner.exec(argv, options))123 : inner.exec(argv, options),124 });125134/** Someone else's commit on canonical `main`, as a push that moves it would leave it. */126const movedBy = (repos: World, parent: CommitSha) =>127 Effect.gen(function* () {128 const other = yield* repos.commit(129 parent,
5 unmodified lines
135136 return other;137 });138148/** One command the Lander handed its container: what it ran, and with what env. */139interface Handed {140 readonly argv: readonly string[];141 readonly env: Readonly<Record<string, string>>;142}143154/** The Lander's container, keeping every command it is handed in `handed`. */144const recording =145 (handed: Handed[]) =>146 (inner: Box["Service"]): Box["Service"] => ({147 ...inner,
3 unmodified lines
151 inner.exec(argv, options)152 ),153 });154166/**167 * The Lander's container, where the push of the mirror ref is rejected, as168 * a receive-pack that refuses one ref would.169 */155const mirrorRefused = (inner: Box["Service"]): Box["Service"] => ({156 ...inner,157 exec: (argv, options) =>158 argv.at(-1)?.endsWith(`:${landedRefName}`) === true
4 unmodified lines
163 })164 : inner.exec(argv, options),165});166182/**183 * The Lander's container, where Artifacts is busy with another push to the184 * repo when the Lander pushes `main`: one side-band error packet and no185 * report, as a probe of Artifacts recorded it.186 */167/** A busy Artifacts answers one side-band error packet and no report. */168const busyOnMain = (inner: Box["Service"]): Box["Service"] => ({169 ...inner,170 exec: (argv, options) =>171 pushesMain(argv)
5 unmodified lines
177 })178 : inner.exec(argv, options),179});180200/**201 * The Lander's container, where the remote refuses the push of `main` for a202 * reason of its own, and its message repeats the token it was sent.203 */181const mainDeclined = (inner: Box["Service"]): Box["Service"] => ({182 ...inner,183 exec: (argv, options) =>184 pushesMain(argv)
4 unmodified lines
189 })190 : inner.exec(argv, options),191});192216/**217 * The Lander's container, where a command that reaches a remote fails and218 * prints everything git was handed, its header too: a git whose trace shows219 * the credential it sent.220 */193const tracing = (inner: Box["Service"]): Box["Service"] => ({194 ...inner,195 exec: (argv, options = {}) =>196 options.env?.GIT_CONFIG_VALUE_0 === undefined
4 unmodified lines
201 stdout: "",202 }),203});204233/** A logger keeping every line, with its annotations, as JSON. */205const keeping = (lines: string[]) =>206 Logger.layer([207 Logger.make((options) => {208 lines.push(JSON.stringify(Logger.formatStructured.log(options)));209 }),210 ]);211241/** A module's default export, as `import()` of a file gives it. */212interface Imported {213 readonly default: unknown;214}215246/**247 * `modules` written under a temp folder at their paths, and the one at248 * `file` imported: how the rules evaluator's `/bun` adapter reads a bundle.249 */216const importedFrom = (217 modules: Readonly<Record<string, string>>,218 file: string219) =>
13 unmodified lines
233234 return yield* Effect.promise((): Promise<Imported> => import(target));235 });236271// Both names a config folder imports the sdk by.237const SDK_NAMES = [`"${Brand.cliPackage}/rules"`, '"@repo/sdk"'];238274/** A file's source with its imports of the sdk pointed at this repo's. */239const pointedAtSdk = (source: string) => {240 let pointed = source;241242 for (const name of SDK_NAMES) {
2 unmodified lines
245246 return pointed;247};248285/** The config folder as committed, its imports of the sdk pointed at this repo's. */249const asCommitted = (files: Files) =>250 Object.fromEntries(251 Object.entries(files).flatMap(([file, source]) =>252 source === null ? [] : [[file, pointedAtSdk(source)] as const]253 )254 );255293/** A definition as data: what JSON keeps of it, as the evaluator reads it back. */256const dataOf = ({ default: definition }: Imported) =>257 JSON.stringify(definition);258297/** What `admit` hears about a person who wants to claim (the sdk's `ClaimantFacts`). */259interface Claimant {260 readonly handle: string;261 readonly kind: string;262 readonly record: number;263 readonly territory: string;264 readonly vouched: boolean;265}266306// Where the sdk keeps a definition's function-valued rules.267const FUNCTIONS = Symbol.for("@repo/sdk/Functions");268309/** A function-valued `admit` rule, as the sdk keeps one. */269type Admit = (facts: Claimant) => boolean;270271const isAdmit = (rule: unknown): rule is Admit => Predicate.isFunction(rule);272314/** The project's `admit` rule, where the sdk keeps it, called with `facts`. */273const admits = ({ default: definition }: Imported, facts: Claimant) => {274 const functions = Predicate.hasProperty(definition, FUNCTIONS)275 ? definition[FUNCTIONS]276 : undefined;
623 unmodified lines
900 );901 });902});903946/** The root manifest's catalog: the versions every workspace shares. */904const RootManifest = Schema.fromJsonString(905 Schema.Struct({906 workspaces: Schema.Struct({907 catalog: Schema.Struct({ effect: Schema.String }),
21 unmodified lines
929 ).toBe(manifest.workspaces.catalog.effect);930 }).pipe(Effect.provide(TestServices))931 );932976 // Live on dev-oscabriel: the land image ended on debian's own977 // `bash`, which exits at once with no stdin, so the container stopped and978 // the first `exec` of every job was killed (exit 137).933 // A bare `bash` entrypoint exits at once with no stdin, which stops the934 // container and kills the first `exec` of every job (exit 137).935 it.effect.each(["check", "land"])(936 "keeps the %s container up until its Durable Object destroys it, since every command runs through exec",937 (image) =>938 Effect.gen(function* () {
94 unmodified lines
1033 ).toStrictEqual([]);1034 });1035});10361081/** A merge whose remotes no command in these tests reaches. */1037const idleMerge = {1038 fork: {1039 token: Redacted.make(secret),1040 url: "https://artifacts.invalid/datekit--parse-iso--bob.git",
146 unmodified lines
1187 yield* Effect.promise(() => lander.merge(wire))1188 );11891190 expect(merged).toStrictEqual(Exit.fail(new VerifierBlocked({})));1236 // A whole vCPU (live on dev-oscabriel: on the default `lite`,1237 // 1/16 vCPU, one landing took 32 s and a config bundle 20 s).1191 expect(started).toStrictEqual([1192 { enableInternet: true, image: "land-image", instance: "standard-2" },1193 ]);1194 })
2 unmodified lines
modified:apps/sandbox/test/local-box.ts-8 removed
11 unmodified lines
12 (operation: BoxFailed["operation"]) =>13 (cause: { readonly message: string }) =>14 new BoxFailed({ operation, reason: cause.message });1516/**17 * `Box` over local processes, for tests: the Lander's git script runs here18 * as it runs in its container, against bare repos on disk. A command gets19 * only the env it is given (no variable of this machine's leaks in, so a20 * command that needs `PATH` is handed one), no stdin, and its time limit.21 * A file is written as the Sandbox SDK's `Files` writes one: into a folder22 * that must already be there.23 */16export const LocalBox: Layer.Layer<Box> = Layer.effect(17 Box,18 Effect.gen(function* () {19 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
47 unmodified lines
modified:apps/sandbox/test/smoke.test.ts-5 removed
21 unmodified lines
22 token: Redacted.make(`token-for-${name}`),23 url: `https://artifacts.invalid/${name}.git`,24});2526/** The sandbox's entrypoint as the platform's service binding reaches it. */26const sandbox = new Sandbox(untouchable("ctx"), fakeEnv());2729/** A stub's outcome: a typed failure, not a defect. */28const failureOf = Exit.findErrorOption;2930describe("the sandbox Worker's main module", () => {33 // Live on dev-oscabriel: `ctx.exports` holds a loopback only for an34 // export of the main module, and every check was blocked with "worker.ts35 // does not export the outbound gateways".31 it("exports the Checker's outbound gateways, so ctx.exports holds them", () => {32 expect({33 CloneGateway: ExportedClone,34 EgressGateway: ExportedEgress,
32 unmodified lines
modified:apps/sandbox/test/workers-shim.ts-7 removed
1/**2 * `cloudflare:workers` for tests in Node. `vitest.config.ts` aliases the3 * module here, for this Worker's modules and the Sandbox SDK's: config4 * aliasing, not module mocking. Each class keeps what its constructor is5 * given and does nothing else; `env` is a fake whose bindings throw when6 * touched (`fake-env.ts`).7 */1import { fakeEnv } from "./fake-env.ts";23export class DurableObject<E = Env> {4 readonly ctx: DurableObjectState;
21 unmodified lines
modified:apps/sandbox/vitest.config.ts+2 added-4 removed
1import { preset } from "@repo/config/vitest";2import { defineConfig, mergeConfig } from "vitest/config";34// Worker modules import `cloudflare:workers`, which only workerd serves; in5// Node it resolves to a shim. The Sandbox SDK imports it too, so vitest6// bundles the SDK (`inline`) for the alias to reach it. An alias resolves to7// a file, not a folder.4// `cloudflare:workers` only exists in workerd; the SDK is inlined so the5// alias reaches its import too.6export default mergeConfig(7 preset,8 defineConfig({9 resolve: {
8 unmodified lines
modified:infra/lib/teardown.ts+7 added-72 removed
1/**2 * Teardown: which throwaways a run may delete, and the run that3 * deletes them. `bun infra/teardown.ts` prints the plan; only `--apply`4 * deletes it, and never while a take is being recorded.5 *6 * The ledger (`infra/created.jsonl`) is the allow-list. A name the ledger7 * doesn't hold is never selected, whatever it is called (a `smoke-` prefix8 * proves nothing), and a ledger entry the account no longer lists is already9 * gone. Nothing a stage owns is ever selectable: its namespaces10 * (`projects-<s>`, `layers-<s>`), and the seeded examples it keeps (`datekit`11 * with its maintainers layer, and `burrow`) with every fork of them, since a12 * claim on demo's burrow during the take is recorded and must outlive it. Nor13 * is anything in `witness`, which belongs to another project and is never even14 * read. The imported preview repos (`by: "import"`) are kept like the seeded15 * examples, with every fork of them: listed as "kept imports", never16 * selected; deleting one is a person's Cloudflare delete. Workers, D1, KV and17 * R2 are not Artifacts, so no listing names them and no plan can hold them. A18 * project entry is a Durable Object and a front-page row: teardown leaves both19 * (they are harmless, and not billed at this size), and says so.20 *21 * Repos are deleted through `@repo/artifacts`' `RepoHost`, one per namespace;22 * each one deleted gets a `deleted` line in the ledger at once, so a run cut23 * short is finished by running it again.24 */1// The ledger (`infra/created.jsonl`) is the allow-list: a name it doesn't hold2// is never selected, whatever it is called. A stage's namespaces, the seeded3// examples, kept imports (each with every fork) and `witness` never are.4// Each deletion is written to the ledger at once, so a cut run resumes.5import type { RepoHost } from "@repo/artifacts/repo-host";6import { RepoName } from "@repo/protocol/ids";7import { Console, Context, DateTime, Effect, Option, Schema } from "effect";8import type { FileSystem, PlatformError } from "effect";
4 unmodified lines
13import type { RecordingInProgress } from "../recording.ts";14import { declaredStage, resources, stages as declared } from "../stages.ts";15import type { Stage } from "../stages.ts";1637/** Something the account lists: a namespace, or a repo in one. */17export interface Listed {18 readonly kind: "namespace" | "repo";19 readonly name: string;41 /** The namespace that holds it, for a repo. */20 readonly namespace?: string;21}2245/** The namespace that belongs to another project. Never read, never deleted. */23const witness = "witness";2448/** The examples the seed puts on every stage, kept with the stage. */25const examples = ["datekit", "burrow"] as const;2651/** The seeded examples' repos: each example's own, and datekit's layer. */27const seeded = [...examples, "datekit--maintainers"] as const;2854/**55 * Names no plan selects: `witness`, the seeded examples, and both Artifacts56 * namespaces of every stage named.57 */29export const protectedNames = (stages: readonly Stage[]): ReadonlySet<string> =>30 new Set([31 witness,32 ...seeded,
3 unmodified lines
36 return [projects, layers];37 }),38 ]);3969/** One resource's identity, the same for a ledger entry and a listed one. */40const keyOf = (item: {41 readonly kind: string;42 readonly name: string;43 readonly namespace?: string;44}) => JSON.stringify([item.kind, item.namespace ?? "", item.name]);4576/** Whether `name` is the project `kept` or one of its repos (`<kept>--…`). */46const ofProject = (name: string, kept: string) =>47 name === kept || name.startsWith(`${kept}--`);4880/** What a plan is drawn from: the ledger, the stages it acts on, and the copies kept. */49interface Scope {50 readonly ledger: readonly Created[];51 readonly stages: readonly Stage[];84 /** Projects whose repos stay (`--keep`): the project's repo and every `<project>--…`. */52 readonly keep?: readonly string[];53}5488/** The projects the ledger records as kept imports, on any stage. */55const importsOf = (ledger: readonly Created[]): ReadonlySet<string> =>56 new Set(ledger.flatMap(({ by, name }) => (by === "import" ? [name] : [])));5792/** Whether a ledger entry is a namespace or repo teardown may ever delete. */58const deletable = (59 entry: Created,60 guarded: ReadonlySet<string>,61 imported: ReadonlySet<string>
5 unmodified lines
67 (entry.kind === "repo" &&68 entry.namespace !== undefined &&69 entry.namespace !== witness));70106/**107 * The ledger's entries a run on `stages` may delete, before asking the108 * account which still exist: not deleted yet, on one of the stages, not109 * protected (on these stages or any stage this repo declares), not in110 * `witness`, and not kept.111 */71const candidatesOf = (scope: Scope): readonly Created[] => {72 const guarded = protectedNames([...declared, ...scope.stages]);73 const imported = importsOf(scope.ledger);74
5 unmodified lines
80 !(scope.keep ?? []).some((kept) => ofProject(entry.name, kept))81 );82};83125/**126 * What to delete on `stages`: the ledger's namespaces and repos that the127 * account still lists, minus every protected name and every kept copy. Repos128 * come first, newest first, so a fork goes before the repo it forks;129 * namespaces come last, since Artifacts deletes only an empty one.130 */84// Repos newest first, so a fork goes before its source; namespaces last, since85// Artifacts deletes only an empty one.86export const teardownPlan = (87 input: Scope & { readonly listed: readonly Listed[] }88): readonly Listed[] => {89 const present = new Map(input.listed.map((item) => [keyOf(item), item]));
13 unmodified lines
103 ...newestFirst.filter(({ kind }) => kind === "namespace"),104 ];105};106152/**153 * The account's Artifacts, as teardown reaches it: a namespace's repos154 * through `@repo/artifacts`' `RepoHost`, and namespaces themselves, which155 * the port has no route for.156 */107export class TeardownAccount extends Context.Service<108 TeardownAccount,109 {160 /** The repos of one namespace. */110 readonly repos: (namespace: string) => Effect.Effect<RepoHost["Service"]>;111 readonly namespaceExists: (name: string) => Effect.Effect<boolean>;163 /** Deletes an empty namespace; whether it was there to delete. */112 readonly removeNamespace: (name: string) => Effect.Effect<boolean>;113 }114>()("infra/TeardownAccount") {}115168/** `teardown` was given a flag it doesn't know, or a flag without its value. A usage error. */116export class TeardownUsage extends Schema.TaggedError<TeardownUsage>()(117 "TeardownUsage",118 { given: Schema.String }119) {
7 unmodified lines
127 readonly stage: Option.Option<Stage>;128 readonly keep: readonly string[];129}130184/** The flags, read in order; anything else is a usage error. */131const optionsOf = (132 argv: readonly string[]133): Effect.Effect<Options, TeardownUsage> =>134 Effect.gen(function* () {
34 unmodified lines
169170 return { apply, keep, stage };171 });172227/** How a plan line names an item: its kind, then `<namespace>/<name>` for a repo. */173const shown = (item: Listed | Created) =>174 `${item.kind} ${item.namespace === undefined ? item.name : `${item.namespace}/${item.name}`}`;175176const repoName = Schema.decodeUnknownOption(RepoName);177233/** The repos of the namespace that holds `item`. */178const hostOf = (item: Listed) =>179 Effect.gen(function* () {180 const account = yield* TeardownAccount;181
3 unmodified lines
185186 return yield* account.repos(namespace);187 });188245/** `entry` as the account lists it, if it still exists. */189const probe = (entry: Created) =>190 Effect.gen(function* () {191 const account = yield* TeardownAccount;192
27 unmodified lines
220 )221 );222 });223281/** Deletes one planned item; whether it was there to delete. */224const remove = (item: Listed) =>225 Effect.gen(function* () {226 const account = yield* TeardownAccount;227
9 unmodified lines
237238 return yield* host.remove(name);239 });240299/** The stages the ledger names that this repo declares, in the ledger's order. */241const ledgerStages = (ledger: readonly Created[]): readonly Stage[] => [242 ...new Set(243 ledger.flatMap((entry) => Option.toArray(declaredStage(entry.stage)))244 ),245];246306/** One stage's plan, printed, and with `apply` deleted: how many it deleted. */247const onStage = (ledger: readonly Created[], stage: Stage, options: Options) =>248 Effect.gen(function* () {249 const scope = { keep: options.keep, ledger, stages: [stage] };250 const entries = ledger.filter((entry) => entry.stage === stage);
98 unmodified lines
349350 return count;351 });352413/**414 * `bun infra/teardown.ts [--stage <s>] [--keep <project>]… [--apply]`: prints415 * the plan for `--stage`, or for every declared stage the ledger names, and416 * with `--apply` deletes exactly that plan. `--apply` is refused while417 * `infra/.recording` exists, before anything else is read.353// `--apply` is refused while `infra/.recording` exists, before anything else is read.418 */354export const teardown = (355 argv: readonly string[]356): Effect.Effect<357 void,
29 unmodified lines
modified:infra/bootstrap.ts+6 added-104 removed
1/**2 * bootstrap: `bun run bootstrap -- --stage dev-<user>|demo`. Makes a stage's3 * Cloudflare resources once, and is safe to run again: a second run creates4 * nothing.5 *6 * 1. Reads what exists: the stage's two Artifacts namespaces, the public7 * one and the private one the layers live in (over REST, with the infra8 * token `varlock run --path infra/` provides), and the account's D19 * databases, KV namespaces and R2 buckets (with Wrangler's own login: the10 * infra token can't write them, so Wrangler never sees it).11 * 2. `plan`s and creates only what is missing.12 * 3. Writes the D1 and KV ids into the stage's block of13 * `apps/platform/wrangler.jsonc` (`writeIds`, comments untouched).14 * 4. Applies the front page's migrations, once `apps/platform/migrations`15 * exists.16 * 5. Records the account's workers.dev subdomain in `infra/workers-dev.json`,17 * so `scripts/smoke.ts` knows the stage's origin.18 * 6. Checks, by name only, that the deployed platform has every secret its19 * `.env.schema` requires. Before the first deploy there is no Worker to20 * hold them: that deploy must carry them through varlock.21 *22 * `--dry-run` does only the first step and prints the plan: it creates23 * nothing and writes no file.24 *25 * `--check-triggers` does only the last step a deploy needs: it reads the26 * platform's triggers back (`GET /triggers/platform-<s>`) and compares them27 * with what `wrangler.jsonc` declares (`checkTriggers`). Wrangler's dry run28 * prints no triggers, so only this read proves the push-event trigger29 * exists.30 *31 * It never deletes, never prints a secret, and never reads a `.env` file.32 * Tearing a stage down is a person's job, not automated.33 */1// Usage: bun run bootstrap -- --stage <stage> [--dry-run | --check-triggers]2// Idempotent: creates only what is missing, and never deletes.3import { BunRuntime, BunServices } from "@effect/platform-bun";4import {5 Config,6 Console,
22 unmodified lines
29 WorkersDev,30} from "./stages.ts";31import type { Stage } from "./stages.ts";3264// ----------------------------------------------------------------- the plan6566/** What exists on the account, as bootstrap reads it before it creates. */33export interface Existing {68 /** The Artifacts namespaces present, of those a stage owns. */34 readonly namespaces: readonly string[];35 readonly d1: readonly { readonly name: string; readonly id: string }[];36 readonly kv: readonly { readonly title: string; readonly id: string }[];37 readonly r2: readonly string[];38}3975/** One resource bootstrap makes. */40export type Step = Data.TaggedEnum<{41 CreateNamespace: { readonly name: string };42 CreateD1: { readonly name: string };43 CreateKv: { readonly title: string };
1 unmodified line
45}>;4647export const Step = Data.taggedEnum<Step>();4885/** What `stage` lacks, in the order bootstrap creates it. Pure. */49export const plan = (stage: Stage, existing: Existing): readonly Step[] => {50 const names = resources(stage);5152 return [
11 unmodified lines
64 ),65 ];66};67105// ---------------------------------------------------------- the config text106107/** The ids bootstrap writes into a stage's block. */68export interface Ids {69 readonly frontPage?: string | undefined;70 readonly oauth?: string | undefined;71}72113/**114 * Where `key` sits in the entry of `env.<stage>.<list>` whose `binding` is115 * `binding`, if there is one.116 */73const spanOf = (74 json: string,75 spans: ReadonlyMap<string, Span>,76 place: {
20 unmodified lines
9798 return Option.none();99};100145/**146 * `text` (a `wrangler.jsonc`) with the front page's `database_id` and the147 * OAuth KV `id` of `stage`'s block set to `ids`. Only those two values148 * change: every comment, comma and line stays. Pure.149 */101// Only those two values change: every comment, comma and line stays.102export const writeIds = (text: string, stage: Stage, ids: Ids): string => {103 const json = blankJsonc(text);104 const spans = valueSpans(json);105
27 unmodified lines
133134 return written;135};136185// ------------------------------------------------------------- the trigger186137const Target = Schema.Struct({138 script_name: Schema.String,139 type: Schema.String,140 workflow_name: Schema.optionalKey(Schema.String),
4 unmodified lines
145 targets: Schema.Array(Target),146 type: Schema.String,147});148199/**200 * `GET /accounts/{id}/triggers/{script}`: each target carries201 * `script_name`, which `wrangler.jsonc` does not.202 */149export const TriggersResponse = Schema.Struct({150 result: Schema.Struct({151 script_name: Schema.String,152 triggers: Schema.Array(Trigger),
2 unmodified lines
155});156157const PUSHED = "cf.artifacts.repo.pushed";158213/** The platform has no push-event trigger for its stage's namespace. */159export class TriggerMismatch extends Schema.TaggedError<TriggerMismatch>()(160 "TriggerMismatch",161 {217 /** Every trigger target the platform has, one line each. */162 found: Schema.Array(Schema.String),163 namespace: Schema.String,164 script: Schema.String,165 workflow: Schema.String,
5 unmodified lines
171 return `${this.script} has no ${PUSHED} trigger on ${this.namespace} starting ${this.workflow}; it has: ${found}`;172 }173}174231/** A success that carries nothing: `Result` has no `void`. */175const held: Result.Result<void> = Result.flip(Result.failVoid);176234/**235 * Whether `live` holds the stage's push-event trigger: pushes to the public236 * namespace start the `on-push` Workflow of the stage's platform. Other237 * triggers may sit beside it. Pure.238 */177export const checkTriggers = (178 stage: Stage,179 live: typeof TriggersResponse.Type180): Result.Result<void, TriggerMismatch> => {
31 unmodified lines
212 })213 );214};215278// ----------------------------------------------------- reading Wrangler's output279280/** The JSON a Wrangler command printed, past any banner or warning before it. */216const jsonIn = (stdout: string) => {217 const start = stdout.search(/^[[{]/mu);218219 return start === -1 ? stdout : stdout.slice(start);
14 unmodified lines
234const decodeSecrets = Schema.decodeEffect(235 Schema.fromJsonString(Schema.Array(Schema.Struct({ name: Schema.String })))236);237303/** The D1 databases `wrangler d1 list --json` printed. */238export const d1From = (stdout: string) =>239 decodeD1(jsonIn(stdout)).pipe(240 Effect.map((databases) =>241 databases.map(({ name, uuid }) => ({ id: uuid, name }))242 )243 );244311/** The KV namespaces `wrangler kv namespace list` printed. */245export const kvFrom = (stdout: string) =>246 decodeKv(jsonIn(stdout)).pipe(247 Effect.map((namespaces) =>248 namespaces.map(({ id, title }) => ({ id, title }))249 )250 );251319/** The bucket names `wrangler r2 bucket list` printed, one `name:` line each. */252export const bucketsFrom = (stdout: string): readonly string[] =>253 stdout254 .split("\n")255 .flatMap((line) =>
3 unmodified lines
259 )260 )261 );262331/** The secret names `wrangler secret list` printed: never a value. */263export const secretNames = (stdout: string) =>264 decodeSecrets(jsonIn(stdout)).pipe(265 Effect.map((secrets) => secrets.map(({ name }) => name))266 );267337/** The required items of a `.env.schema` that `listed` lacks. Pure. */268export const missingSecrets = (269 items: readonly SchemaItem[],270 listed: readonly string[]271): readonly string[] =>272 items.flatMap(({ name, required }) =>273 required && !listed.includes(name) ? [name] : []274 );275346// --------------------------------------------------------------- the effects347348/** The Cloudflare API answered a call with a status bootstrap doesn't expect. */276export class CloudflareRefused extends Schema.TaggedError<CloudflareRefused>()(277 "CloudflareRefused",278 { route: Schema.String, status: Schema.Int }279) {
1 unmodified line
281 return `the Cloudflare API answered ${this.route} with ${this.status}`;282 }283}284358/** A Wrangler command exited non-zero; its own output said why. */285export class WranglerFailed extends Schema.TaggedError<WranglerFailed>()(286 "WranglerFailed",287 { command: Schema.String, exitCode: Schema.Int }288) {
1 unmodified line
290 return `${this.command} exited ${this.exitCode}`;291 }292}293368/** The deployed platform lacks secrets its `.env.schema` requires (H5). */294export class MissingSecrets extends Schema.TaggedError<MissingSecrets>()(295 "MissingSecrets",296 { names: Schema.Array(Schema.String), stage: Schema.String }297) {
3 unmodified lines
301}302303const API = "https://api.cloudflare.com/client/v4";304380/** The infra credentials `varlock run --path infra/` puts in the environment. */305const Credentials = Config.all({306 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),307 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),308});309310type Credentials =311 typeof Credentials extends Config.Config<infer A> ? A : never;312389/** One call to the account's REST API: its status, and its body as text. */313const call = (314 credentials: Credentials,315 route: string,316 body?: Readonly<Record<string, string>>
12 unmodified lines
329330 return { status: response.status, text: yield* response.text };331 });332410/** A call that must answer 200: its body. */333const ok = (credentials: Credentials, route: string) =>334 call(credentials, route).pipe(335 Effect.flatMap(({ status, text }) =>336 status === 200
9 unmodified lines
346const decodeSubdomain = Schema.decodeEffect(347 Schema.fromJsonString(Schema.Struct({ result: WorkersDev }))348);349428/** Whether a resource a route names exists: 200 yes, 404 no. */350const exists = (credentials: Credentials, route: string) =>351 call(credentials, route).pipe(352 Effect.flatMap(({ status }) =>353 status === 200 || status === 404
1 unmodified line
355 : Effect.fail(new CloudflareRefused({ route, status }))356 )357 );358438/** A Wrangler command in `apps/platform`, as its own login: its stdout. */359const wrangler = (root: string, args: readonly string[]) =>360 Effect.gen(function* () {361 const path = yield* Path.Path;362 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
2 unmodified lines
365 const handle = yield* spawner.spawn(366 ChildProcess.make(path.join(app, "node_modules/.bin/wrangler"), args, {367 cwd: app,368 // Writes outside Artifacts go through `wrangler login`, never the449 // read-mostly infra token (infra/.env.schema).369 // read-mostly infra token.370 env: {371 CLOUDFLARE_API_TOKEN: undefined,372 WRANGLER_SEND_METRICS: "false",373 },
14 unmodified lines
388 exitCode,389 });390 }).pipe(Effect.scoped, Effect.catchTag("PlatformError", Effect.die));391472/** What exists of `stage`'s resources on the account. */392const readExisting = (root: string, credentials: Credentials, stage: Stage) =>393 Effect.gen(function* () {394 const { layers, projects } = resources(stage);395
12 unmodified lines
408 r2: bucketsFrom(yield* wrangler(root, ["r2", "bucket", "list"])),409 } satisfies Existing;410 });411493/** One step, as a line of bootstrap's output. */412const describe = (step: Step) =>413 Step.$match(step, {414 CreateD1: ({ name }) => `create D1 ${name}`,415 CreateKv: ({ title }) => `create KV ${title}`,416 CreateNamespace: ({ name }) => `create Artifacts namespace ${name}`,417 CreateR2: ({ name }) => `create R2 ${name}`,418 });419502/** What a dry run of `stage` prints for `steps`: each step, then that nothing changed. */420export const planLines = (421 stage: Stage,422 steps: readonly Step[]423): readonly string[] => [424 ...steps.map((step) => `bootstrap ${stage} (dry run): ${describe(step)}`),425 `bootstrap ${stage} (dry run): would create ${steps.length}; nothing was changed`,426];427511/**512 * Wrangler's create commands offer to add the binding to `wrangler.jsonc`513 * themselves, at top level; bootstrap writes the stage's block instead.514 */428// Bootstrap writes the stage's block itself, not Wrangler's top-level binding.429const NO_CONFIG_EDIT = "--update-config=false";430517/** Makes the resource `step` names. */431const create = (root: string, credentials: Credentials, step: Step) =>432 Step.$match(step, {433 CreateD1: ({ name }) =>434 wrangler(root, ["d1", "create", name, NO_CONFIG_EDIT]),
17 unmodified lines
452 CreateR2: ({ name }) =>453 wrangler(root, ["r2", "bucket", "create", name, NO_CONFIG_EDIT]),454 }).pipe(Effect.asVoid);455543/** A text file under the repo root rewritten only when its contents change. */456const rewrite = (root: string, file: string, edit: (text: string) => string) =>457 Effect.gen(function* () {458 const fs = yield* FileSystem.FileSystem;459 const path = yield* Path.Path;
14 unmodified lines
474 yield* Console.log(`bootstrap: wrote ${file}`);475 }476 }).pipe(Effect.orDie);477566/** Reads the platform's triggers back and compares them. */478const triggers = (credentials: Credentials, stage: Stage) =>479 Effect.gen(function* () {480 const { platform, projects } = resources(stage);481
9 unmodified lines
491 `bootstrap ${stage}: ${platform} hears pushes to ${projects}.`492 );493 });494584/** Checks, by name, that the deployed platform holds its required secrets. */495const secrets = (root: string, credentials: Credentials, stage: Stage) =>496 Effect.gen(function* () {497 const fs = yield* FileSystem.FileSystem;498 const path = yield* Path.Path;
8 unmodified lines
507 const required = items.flatMap(({ name, required: needed }) =>508 needed ? [name] : []509 );510601 // ASSUMPTION for 311: a script's settings answer 404 until its first602 // deploy, and the infra token ("Read all resources") may read them.511 // A script's settings answer 404 until its first deploy.512 const deployed = yield* exists(513 credentials,514 `/workers/scripts/${platform}/settings`515 );
23 unmodified lines
539 )540 : Effect.fail(new MissingSecrets({ names: missing, stage }));541 });542634/** Reads what exists of `stage` and prints what `make` would create, creating and writing nothing. */543const dryRun = (root: string, credentials: Credentials, stage: Stage) =>544 Effect.gen(function* () {545 const steps = plan(stage, yield* readExisting(root, credentials, stage));546547 yield* Console.log(planLines(stage, steps).join("\n"));548 });549642/** Makes what `stage` lacks, writes its ids and checks its secrets. */550const make = (root: string, credentials: Credentials, stage: Stage) =>551 Effect.gen(function* () {552 const fs = yield* FileSystem.FileSystem;553 const path = yield* Path.Path;
54 unmodified lines
608 `bootstrap ${stage}: created ${steps.length}; next: bun run deploy -- --stage ${stage}`609 );610 });611705/**706 * Bootstraps the stage `argv`'s `--stage` names; with `--check-triggers`,707 * only reads its push-event trigger back; with `--dry-run`, only reads what708 * exists and lists what it would create.709 */612export const bootstrap = (argv: readonly string[]) =>613 Effect.gen(function* () {614 const stage = yield* stageOf(argv);615 const credentials = yield* Credentials;
20 unmodified lines
modified:infra/created.ts+7 added-62 removed
1/**2 * The ledger of throwaway resources: every namespace, repo or project a smoke3 * run, a swarm run or a `seed --as` copy makes on a stage is appended here as4 * one JSON line, so teardown acts only on what this build made, never on a5 * stage's own resources or on anything else in the account. The imported6 * preview repos (`by: "import"`) are recorded here too, as kept: the ledger7 * stays the one record of what the build made, and teardown never selects8 * them.9 *10 * The ledger is committed and holds names only, never a token. A throwaway is11 * named by the job that made it and its run (`smoke-<run>`, `swarm-<run>`),12 * never by the brand (AGENTS.md principle 5); a `seed --as` copy keeps the13 * name it was given and is recorded by that name.14 *15 * History is only ever appended. When teardown deletes a throwaway it appends16 * a `deleted` line naming it (`deletedAt` and the entry's kind, name,17 * namespace and stage), and reading folds that line into the entry it names18 * as `deletedAt`; the entry's own line stays as it was written.19 */1// The append-only ledger of what this build made; teardown acts on nothing2// else. It is committed and holds names only, never a token. A deletion is a3// later `deleted` line folded into its entry on read, never a rewrite.4import { Context, Effect, FileSystem, Schema } from "effect";5import type { DateTime, PlatformError } from "effect";623/** What names one resource, on the line that records it and on the one that marks it deleted. */7const resourceFields = {8 kind: Schema.Literals(["namespace", "repo", "project"]),9 name: Schema.NonEmptyString,27 /** The Artifacts namespace that holds it, for a repo. */10 namespace: Schema.optionalKey(Schema.NonEmptyString),11 stage: Schema.NonEmptyString,12};1332/** The line a run appends when it makes a throwaway. */14const Made = Schema.Struct({34 /** When the run made it. */15 at: Schema.DateTimeUtcFromString,36 /**37 * The job whose run made it. An `import` (`scripts/import-examples.ts`)38 * is kept, not a throwaway: teardown lists it and never selects it.39 */16 // An `import` is kept, not a throwaway: teardown never selects it.17 by: Schema.Literals(["smoke", "swarm", "seed", "import"]),18 ...resourceFields,42 /** What else the run did to it, said once: `tags backfilled` for an import's repo. */19 note: Schema.optionalKey(Schema.NonEmptyString),20});2146/** The line teardown appends when it deletes a throwaway. */22const Deleted = Schema.Struct({23 deletedAt: Schema.DateTimeUtcFromString,24 ...resourceFields,25});2652/** One throwaway resource, as the run that made it records it. */27export const Created = Schema.Struct({28 ...Made.fields,55 /** When teardown deleted it: read from a later `deleted` line, never written on the entry's own. */29 deletedAt: Schema.optionalKey(Schema.DateTimeUtcFromString),30});3132export type Created = typeof Created.Type;3361/** The ledger, relative to the repo root. */34export const ledgerPath = "infra/created.jsonl";3564/**65 * The file the ledger is read from and appended to: the repo's own66 * `ledgerPath` (beside this module), unless a test points it elsewhere.67 */36export const LedgerFile = Context.Reference<string>("infra/LedgerFile", {37 defaultValue: () =>38 decodeURIComponent(new URL("created.jsonl", import.meta.url).pathname),39});
3 unmodified lines
43const DeletedLine = Schema.fromJsonString(Deleted);4445const Line = Schema.fromJsonString(Schema.Union([Made, Deleted]));4679/** What names one resource on a stage, whichever line it is read from. */47type Resource = Pick<Created, "kind" | "name" | "namespace" | "stage">;4882/** Whether two lines name the same resource on the same stage. */49const sameResource = (one: Resource, other: Resource): boolean =>50 one.kind === other.kind &&51 one.name === other.name &&52 one.namespace === other.namespace &&53 one.stage === other.stage;5489/**90 * Each entry with the `deleted` lines folded in: a `deleted` line marks the91 * latest entry before it that names the same resource and is not yet marked.92 * One that matches no such entry changes nothing.93 */55// A `deleted` line marks the latest unmarked entry before it naming the same56// resource; one matching nothing changes nothing.57const folded = (58 lines: readonly (typeof Made.Type | typeof Deleted.Type)[]59): readonly Created[] => {60 const entries: Created[] = [];
16 unmodified lines
7778 return entries;79};80118/** Appends one entry to the ledger as one JSON line. */81export const recordCreated = (82 entry: Created83): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> =>84 Effect.gen(function* () {85 const fs = yield* FileSystem.FileSystem;86 const file = yield* LedgerFile;87126 // A `Created` value always encodes: every field is a string or a127 // DateTime. Its line is the run's own: a `deletedAt` is never written on it.88 // MadeLine drops `deletedAt`: it is never written on an entry's own line.89 const line = yield* Schema.encodeEffect(MadeLine)(entry).pipe(Effect.orDie);9091 yield* fs.writeFileString(file, `${line}\n`, { flag: "a" });92 });93133/**134 * Appends a `deleted` line for `entry`, deleted at `at`; the entry's own line135 * is never rewritten.136 */94export const recordDeleted = (95 entry: Created,96 at: DateTime.Utc97): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> =>98 Effect.gen(function* () {99 const fs = yield* FileSystem.FileSystem;100 const file = yield* LedgerFile;101145 // Every field is a string or a DateTime, so the line always encodes; it146 // names the entry and when it was deleted, and nothing else of it.102 const line = yield* Schema.encodeEffect(DeletedLine)({103 ...entry,104 deletedAt: at,105 }).pipe(Effect.orDie);106107 yield* fs.writeFileString(file, `${line}\n`, { flag: "a" });108 });109155/**156 * Every entry in the ledger, in the order the runs wrote them, each one157 * teardown deleted with its `deletedAt`. A ledger no run has written yet is158 * empty; a line that is neither a run's entry nor a `deleted` line fails it.159 */110export const readLedger: Effect.Effect<111 readonly Created[],112 PlatformError.PlatformError | Schema.SchemaError,113 FileSystem.FileSystem
13 unmodified lines
127 yield* Effect.forEach(lines, (line) => Schema.decodeEffect(Line)(line))128 );129});130181/**182 * Whether the ledger holds `resource` and teardown has not deleted it: a run183 * records what it makes once, and again once teardown deleted the last one.184 */131export const isRecorded = (132 ledger: readonly Created[],133 resource: Resource134): boolean =>135 ledger.some(136 (entry) => entry.deletedAt === undefined && sameResource(resource, entry)137 );138193/** A throwaway's name: the job that made it, then its run (`smoke-r1`). */139export const throwawayName = (by: Created["by"], run: string) => `${by}-${run}`;
modified:infra/deploy.ts+9 added-60 removed
1/**2 * deploy: `bun run deploy -- --stage dev-<user>|demo`. The one way a stage3 * is deployed (AGENTS.md principle 11, ADR 0002):4 *5 * 1. `bun run verify`: a red gate stops everything after it;6 * 2. `sandbox`, with Wrangler: the platform's `SANDBOX` binding names it;7 * 3. `platform`, with `varlock-wrangler`, which resolves8 * `apps/platform/.env.schema` and syncs its secrets with the Worker;9 * 4. `web`, built for the stage and deployed with Wrangler, once `apps/web`10 * exists;11 * 5. the push-event trigger, read back and compared (`bootstrap.ts12 * --check-triggers`, with the infra token from `varlock run`);13 * 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 * 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 the26 * platform's deploy carries as its environment, which varlock reads before any27 * `.env` file: a stage's generated secrets, on every stage. Only the items `apps/platform/.env.schema` declares are passed,28 * to that one step, and no value is ever printed.29 *30 * Each step runs with its own folder's `node_modules/.bin` first on `PATH`,31 * since `varlock-wrangler` starts `wrangler` by name.32 */1// Usage: bun run deploy -- --stage <stage>2// Runs verify, deploys sandbox, platform and web, checks the push trigger, then3// smoke. Refused while `infra/.recording` exists, before any flag is read.4// `STAGE_SECRETS_FILE` passes only the items `apps/platform/.env.schema`5// declares, to the platform step alone; no value is ever printed.6import { BunRuntime, BunServices } from "@effect/platform-bun";7import {8 Config,9 ConfigProvider,
22 unmodified lines
32export { RecordingInProgress } from "./recording.ts";3334export { NoStage, UnknownStage } from "./stages.ts";3563/** A step exited non-zero; nothing after it ran. */36export class StepFailed extends Schema.TaggedError<StepFailed>()("StepFailed", {37 exitCode: Schema.Int,38 step: Schema.String,39}) {
1 unmodified line
41 return `${this.step} exited ${this.exitCode}, so nothing after it ran`;42 }43}4473/** `STAGE_SECRETS_FILE` names a file that can't be read. */45export class SecretsFileUnreadable extends Schema.TaggedError<SecretsFileUnreadable>()(46 "SecretsFileUnreadable",47 { file: Schema.String }48) {
1 unmodified line
50 return `STAGE_SECRETS_FILE names ${this.file}, which can't be read`;51 }52}5383/** One command of the deploy, run from `cwd` (relative to the repo root). */54interface Step {55 readonly name: string;56 readonly command: string;57 readonly args: readonly string[];58 readonly cwd: string;59 readonly env?: Readonly<Record<string, string>>;60}6192/** Wrangler's own bin in an app, so each app deploys with its pinned version. */62const bin = (app: string, name: string) => `${app}/node_modules/.bin/${name}`;6395/** Every step a deploy of `stage` runs, in order. */64const stepsOf = (65 stage: Stage,66 options: {67 readonly web: boolean;
13 unmodified lines
81 cwd: "apps/platform",82 env: options.platformEnv,83 name: "platform",84 },117 // The web builds with the Cloudflare Vite plugin, which takes the stage118 // from CLOUDFLARE_ENV and writes that stage's deploy config under `dist/`;119 // Wrangler deploys that build, and refuses an --env other than the one it120 // was built for. NODE_ENV keeps a shell's own value121 // from making it a development build, whose `#backend` is the dev world.85 // The Vite plugin takes the stage from CLOUDFLARE_ENV and writes its deploy86 // config under `dist/`, so Wrangler gets no --env. NODE_ENV stops a shell's87 // own value from making a development build, whose `#backend` is the dev world.88 ...(options.web89 ? [90 {91 args: ["run", "build"],
23 unmodified lines
115 name: "smoke",116 },117];118153/**154 * The values `STAGE_SECRETS_FILE` holds for the items the platform's155 * `.env.schema` declares: none when it isn't set.156 */119const platformSecrets = (root: string) =>120 Effect.gen(function* () {121 const fs = yield* FileSystem.FileSystem;122 const path = yield* Path.Path;
29 unmodified lines
152153 return Object.fromEntries(values.flatMap(Option.toArray));154 });155194/** Runs one step from the repo root, failing when it exits non-zero. */156const runStep = (root: string, stage: Stage, step: Step) =>157 Effect.gen(function* () {158 const path = yield* Path.Path;159 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
37 unmodified lines
197 ? Effect.void198 : Effect.fail(new StepFailed({ exitCode, step: step.name }));199 });200240/**241 * Google's redirect back to the platform, as `apps/platform/src/auth/pages.ts`242 * routes it (infra imports no app).243 */201// Mirrors `apps/platform/src/auth/pages.ts`: infra imports no app.202const GOOGLE_CALLBACK = "/oauth/google/callback";203204const decodeWorkersDev = Schema.decodeUnknownEffect(205 Schema.fromJsonString(WorkersDev)206);207250/**251 * The line naming the redirect URI a Google OAuth client registers for252 * `stage` (H4): the platform's workers.dev origin from bootstrap's253 * record, or how to get one when bootstrap hasn't run.254 */208const googleRedirectLine = (root: string, stage: Stage) =>209 Effect.gen(function* () {210 const fs = yield* FileSystem.FileSystem;211 const path = yield* Path.Path;
9 unmodified lines
221 `deploy ${stage}: to offer Google sign-in, register ${platformOrigin(stage, subdomain)}${GOOGLE_CALLBACK} as the Google client's redirect URI (H4)`,222 });223 });224272/**273 * Deploys the stage `argv`'s `--stage` names, then smoke-tests it; refused274 * outright while a take is being recorded.275 */225export const deploy = (226 argv: readonly string[]227): Effect.Effect<228 void,
40 unmodified lines
modified:infra/env-schema.ts+3 added-17 removed
1/**2 * What infra reads from one of our own Workers' `.env.schema` files: each3 * item's name, and whether it must have a value. Never a value: the schema4 * holds none for a secret, and the files that do (`.env`, `.env.local`) stay5 * closed (AGENTS.md "Boundaries: Env").6 *7 * The rules are @env-spec's, as far as our schemas use them: decorators sit in8 * `#` comment lines, the header's end at `# ---`; an item's own comments9 * directly precede its `NAME=` line; `@required` and `@optional` decide, and10 * otherwise the header's `@defaultRequired` does (`infer`: required when the11 * schema gives a value). A conditional `@required=forEnv(…)` counts as12 * optional here. ASSUMPTION: a schema with no `@defaultRequired` infers, as13 * every schema in this repo says outright.14 */1// Each item's name and whether it is required, never a value. Follows2// @env-spec as far as our schemas use it: a conditional `@required=forEnv(…)`3// counts as optional, and a missing `@defaultRequired` means `infer`.416/** One item of a `.env.schema`. */5export interface SchemaItem {6 readonly name: string;7 readonly required: boolean;8}910const ITEM = /^(?<name>[A-Za-z_]\w*)=(?<value>.*)$/u;1124/** The `@` decorators in one comment line. */12const decoratorsOf = (line: string) =>13 line14 .replace(/^#/u, "")15 .split(/\s+/u)
27 unmodified lines
4344 return fallback === "infer" ? value.trim() !== "" : fallback === "true";45};4660/** Every item `text` declares, in order. */47export const schemaItems = (text: string): readonly SchemaItem[] => {48 const lines = text.split(/\r?\n/u).map((line) => line.trim());49 const divider = lines.findIndex((line) => /^#\s*-{3,}$/u.test(line));50 const header = lines.slice(0, Math.max(divider, 0)).flatMap(decoratorsOf);
24 unmodified lines
modified:infra/jsonc.ts+3 added-18 removed
1/**2 * Just enough JSONC for `wrangler.jsonc`: read it as JSON, and find where3 * each value sits so one value can be rewritten in place, leaving every4 * comment, comma and line as it was.5 */1// Just enough JSONC to rewrite one `wrangler.jsonc` value in place, leaving2// every comment, comma and line as it was.37/** A value's place in the text: `[start, end)`. */4export interface Span {5 readonly start: number;6 readonly end: number;7}813/** A path into a JSON value: object keys and array indexes. */9export type JsonPath = readonly (string | number)[];1016/** One key for a path, for a `Map`. */11export const pathKey = (path: JsonPath) => JSON.stringify(path);1213const blankRange = (chars: string[], from: number, to: number) => {14 for (let at = from; at < to; at += 1) {
2 unmodified lines
17 }18 }19};2027/** The offset just past the string literal that opens at `start`. */21const stringEnd = (text: string, start: number) => {22 let at = start + 1;2324 while (at < text.length && text[at] !== '"') {
2 unmodified lines
2728 return at + 1;29};3038/** Where the comment at `at` ends, or `at` when none starts there. */31const commentEnd = (text: string, at: number) => {32 if (text.startsWith("//", at)) {33 const end = text.indexOf("\n", at);34
8 unmodified lines
4344 return at;45};4655/** Whether only whitespace stands between `at` and a closing bracket. */47const closesNext = (text: string, at: number) =>48 /^\s*[\]}]/u.test(text.slice(at + 1));4959/**60 * `text` with every comment and trailing comma turned to spaces: plain JSON61 * whose offsets are the original's.62 */50// Comments and trailing commas become spaces, so offsets stay the original's.51export const blankJsonc = (text: string): string => {52 // UTF-16 units, so every offset is a `slice` offset.53 const chars = text.split("");54 let at = 0;
30 unmodified lines
8586 return chars.join("");87};88101/** A cursor over plain JSON that records each value's span by its path. */89interface Reader {90 readonly json: string;91 readonly spans: Map<string, Span>;92 at: number;
12 unmodified lines
105106 return reader.json.slice(start, reader.at);107};108122/** Reads the members of an object or array, after its opening bracket. */109const readMembers = (110 reader: Reader,111 close: "}" | "]",112 readOne: (index: number) => void
42 unmodified lines
155156 reader.spans.set(pathKey(path), { end: reader.at, start });157};158173/** Where every value in `json` (plain JSON, as `blankJsonc` makes it) sits, by path. */159export const valueSpans = (json: string): ReadonlyMap<string, Span> => {160 const reader: Reader = { at: 0, json, spans: new Map() };161162 readValue(reader, []);
3 unmodified lines
modified:infra/recording.ts+4 added-27 removed
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 */1// Usage: bun infra/recording.ts on | off | status2// The deploy lock: while `infra/.recording` exists, `infra/deploy.ts` refuses3// every deploy, since a deploy restarts the platform's Durable Objects.4// Only `off` lifts it: no flag or environment variable does.5import { BunRuntime, BunServices } from "@effect/platform-bun";6import {7 Console,8 Context,
3 unmodified lines
12 Schema,13 Stdio,14} from "effect";1526/** The lock, relative to the repo root. */16export const lockPath = "infra/.recording";1729/**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 */18export const LockFile = Context.Reference<string>("infra/RecordingLockFile", {19 defaultValue: () =>20 decodeURIComponent(new URL(".recording", import.meta.url).pathname),21});2238/** A take is being recorded: the lock file is there, so nothing deploys. */23export class RecordingInProgress extends Schema.TaggedError<RecordingInProgress>()(24 "RecordingInProgress",25 { file: Schema.String }26) {
1 unmodified line
28 return `${this.file} is there: a take is being recorded (H7), so nothing deploys until a person runs bun infra/recording.ts off`;29 }30}3148/** `recording` was given no command it knows. A usage error. */32export class RecordingUsage extends Schema.TaggedError<RecordingUsage>()(33 "RecordingUsage",34 { given: Schema.String }35) {
1 unmodified line
37 return `${this.given === "" ? "no command" : `${this.given} is no command`}: bun infra/recording.ts on | off | status`;38 }39}4058/** Whether the lock is on, as deploy and `status` read it. */41const isOn = Effect.gen(function* () {42 const fs = yield* FileSystem.FileSystem;4344 // A lock whose presence can't be read is no reason to deploy blind.45 return yield* fs.exists(yield* LockFile).pipe(Effect.orDie);46});4766/**67 * Fails with `RecordingInProgress` while the lock is on: deploy's first68 * step, before anything else it does.69 */48export const notRecording: Effect.Effect<49 void,50 RecordingInProgress,51 FileSystem.FileSystem
4 unmodified lines
56 ? Effect.fail(new RecordingInProgress({ file }))57 : Effect.void;58});5982/** `bun infra/recording.ts on | off | status`: turns the lock on or off, or says which it is. */60export const recording = (61 argv: readonly string[]62): Effect.Effect<void, RecordingUsage, FileSystem.FileSystem> =>63 Effect.gen(function* () {
51 unmodified lines
modified:infra/smoke.ts+4 added-127 removed
1/**2 * smoke's probes: read-only requests to a live stage's platform and web, each3 * of which a misbehaving public surface fails. Every probe runs, whatever the4 * others did, so one run names every surface that broke; each one is timed.5 *6 * 1. `health`: `GET /health` answers `200 {ok: true, stage}`, and names the7 * stage smoke was pointed at, when it was told one;8 * 2. `oauth-metadata`: `GET /.well-known/oauth-protected-resource` answers9 * 200 with RFC 9728's metadata, which names its `resource`;10 * 3. `mcp-needs-credential`: `POST /mcp` without a credential answers 401;11 * 4. `anonymous-unknown-project`: an anonymous `/rpc` `listAsks` for a project12 * that doesn't exist answers 200 with a typed `UnknownProject` refusal;13 * 5. `missing-repo-404`: git's `info/refs` for a repo that doesn't exist14 * answers 404;15 * 6. `platform-root`: the platform's `GET /` answers 200 with a page that16 * names its MCP endpoint (`/mcp`) and the CLI's `install.sh`;17 * 7. `web-front-page`: the web's `GET /` answers 200 with HTML;18 * 8. `web-llms-txt`: the web's `GET /llms.txt` answers 200 with Markdown,19 * which it builds from the platform's project list, so only a web that20 * reaches the platform through its service binding passes;21 * 9. `web-project-llms-txt`: a seeded example's `llms.txt` on the web22 * answers 200 with Markdown;23 * 10. `web-ask-md`: one of the seeded example's asks as Markdown answers 200;24 * 11. `web-agent-skills`: the web's `/.well-known/agent-skills/index.json`25 * answers 200 with JSON.26 *27 * The web's probes run when smoke knows where the web lives: bootstrap's28 * workers.dev record, or `--web-url`. 9 and 10 need the seeded example,29 * which a stage holds only once it is seeded, after its first deploy (and30 * that deploy's smoke): when the platform refuses the example as unknown,31 * each is skipped with a warning line. The agent surfaces among them32 * (`agentProbes`, 8 to 11) are what an agent reads first, so each is timed33 * against `AGENT_BUDGET_MS`: one over it is a warning line, never a failure,34 * since a cold isolate's first answer is slower than the rest.35 *36 * A probe the platform answers with its own failure (a server error, or an37 * RPC defect) asks again for up to `settling`, as a fresh deploy gives38 * those for its first seconds; any other wrong answer fails it at once.39 *40 * `scripts/smoke.ts` is the command; this module holds the probes, since41 * `infra/` may use `effect/http` (tsconfig.base.json's overrides).42 */1import { UnknownProject } from "@repo/protocol/refusal";2import {3 Console,4 Duration,
14 unmodified lines
19 webOrigin,20} from "./stages.ts";21import type { Stage } from "./stages.ts";2265/** The platform's probes, in the order smoke runs them. */23export const platformProbes = [24 "health",25 "oauth-metadata",26 "mcp-needs-credential",
1 unmodified line
28 "missing-repo-404",29 "platform-root",30] as const;3175/** The web's probes, run after the platform's when smoke has the web's origin. */32export const webProbes = [33 "web-front-page",34 "web-llms-txt",35 "web-project-llms-txt",36 "web-ask-md",37 "web-agent-skills",38] as const;3984/** How long an agent surface may take to answer before smoke warns: 500 ms. */40export const AGENT_BUDGET_MS = 500;4187/** An example every seeded stage holds, by its name, and one of its asks. */42const SEEDED = { ask: "format-ordinal", project: "oscabriel/datekit" } as const;4390/** The probes that read the seeded example, skipped on a stage that does not hold it. */44export const seededProbes: ReadonlySet<Probe> = new Set([45 "web-project-llms-txt",46 "web-ask-md",47]);4896/** The agent surfaces on the web smoke reads, each by its path and the media type it answers with. */49export const agentProbes = [50 { contentType: "text/markdown", path: "/llms.txt", probe: "web-llms-txt" },51 {52 contentType: "text/markdown",
15 unmodified lines
68 readonly path: string;69 readonly probe: (typeof webProbes)[number];70}[];71120/** Every probe, in the order smoke runs them. */72export const probes = [...platformProbes, ...webProbes] as const;7374export const Probe = Schema.Literals(probes);7576export type Probe = typeof Probe.Type;77127/** A project no stage holds, by a name one could have: smoke asks for it and expects to be refused. */78const MISSING = "oscabriel/no-such-project";79130/** How long one probe waits for an answer: a cold Worker included. */80const PATIENCE = Duration.seconds(30);81133/**134 * How long a probe keeps asking a platform that answers with a server error135 * or a defect, as a fresh deploy does for its first seconds (the first136 * smoke after the first deploy got a 500 from `/health` and a defect from137 * the first Project DO call; a run seconds later passed).138 */82// A fresh deploy answers with server errors or defects for its first seconds.83const SETTLING = Duration.seconds(30);84141/** How long a probe waits between two asks while the platform settles. */85const ASK_AGAIN = Duration.seconds(1);86144/** One or more probes failed: each, and why. */87export class SmokeFailed extends Schema.TaggedError<SmokeFailed>()(88 "SmokeFailed",89 {90 failures: Schema.Array(
8 unmodified lines
99 return `${failed} failed at ${this.origin}`;100 }101}102161/**162 * A passing run: the stage `/health` named, how long each probe took163 * (against its budget, when it has one), and a line for each probe over it.164 */103export interface SmokeReport {104 readonly origin: string;105 readonly stage: string;106 readonly probes: readonly {
3 unmodified lines
110 }[];111 readonly warnings: readonly string[];112}113176/**177 * Why one probe failed, in a line a person reads. A transient miss is the178 * platform's own failure (a server error, a defect), which a fresh deploy179 * may give for its first seconds, so the probe asks again; any other answer180 * is the platform's word, and fails the probe at once.181 */114class Missed extends Schema.TaggedError<Missed>()("Missed", {115 reason: Schema.String,116 transient: Schema.optionalKey(Schema.Boolean),117}) {}118187/** The parts of a response a probe judges. */119interface Answer {120 readonly contentType: string;121 readonly status: number;122 readonly text: string;123}124194/** `request` sent to `origin`, as a probe sees its answer. */125const send = (126 label: string,127 request: HttpClientRequest.HttpClientRequest128): Effect.Effect<Answer, Missed, HttpClient.HttpClient> =>
23 unmodified lines
152 ),153 })154 );155226/** A server error: the Worker's own failure, which a fresh deploy gives for its first seconds. */156const serverError = (status: number) => status >= 500;157229/**230 * A server error, or a 404 from a hostname that is not serving yet: a231 * Worker's first deploy to workers.dev answers 404 for its first seconds232 * (once, smoke ran 4 s after the web's first deploy and got 404 twice), and233 * a deploy that adds a route can still be answered by the version before it234 * (a demo deploy that added `/`: it answered 404 once as the upload finished). The235 * web's probes and `platform-root` read a 404 so; the platform's236 * `missing-repo-404` expects one.237 */158// A fresh workers.dev deploy, or one adding a route, answers 404 for its first seconds.159const notServingYet = (status: number) => status >= 500 || status === 404;160240/** `answer`, when its status is `expected`; `transient` says which others to ask again. */161const statusIs =162 (label: string, expected: number, transient = serverError) =>163 (answer: Answer) =>164 answer.status === expected
4 unmodified lines
169 transient: transient(answer.status),170 })171 );172253/** A failure of any kind, as the miss `reason` names. */173const missing =174 (reason: string) =>175 <A, E, R>(self: Effect.Effect<A, E, R>) =>176 Effect.mapError(self, () => new Missed({ reason }));
3 unmodified lines
180 Schema.Struct({ ok: Schema.Literal(true), stage: Schema.NonEmptyString })181 )182);183265/** `/health`: the Worker is up, and serves the stage it was told to. */184const health = (origin: string, expected: Option.Option<Stage>) =>185 Effect.gen(function* () {186 const label = "GET /health";187
18 unmodified lines
206 ),207 });208 });209292/** RFC 9728: the protected resource's metadata names the resource. */210const decodeResourceMetadata = Schema.decodeUnknownEffect(211 Schema.fromJsonString(Schema.Struct({ resource: Schema.NonEmptyString }))212);213
11 unmodified lines
225 missing(`${label} answered 200 without a "resource"`)226 );227 });228312/** MCP stays closed to anyone without a credential. */229const mcpNeedsCredential = (origin: string) => {230 const label = "POST /mcp without a credential";231232 return send(
6 unmodified lines
239 })240 ).pipe(Effect.flatMap(statusIs(label, 401)), Effect.asVoid);241};242327/** One call as effect/rpc's HTTP protocol with JSON serialization sends it. */243const RpcRequest = Schema.TaggedStruct("Request", {244 headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),245 id: Schema.String,246 payload: Schema.Struct({ project: Schema.String }),247 tag: Schema.Literal("listAsks"),248});249335/** The one reply smoke accepts: the call failed with `UnknownProject`. */250const decodeRefused = Schema.decodeUnknownEffect(251 Schema.fromJsonString(252 Schema.Tuple([253 Schema.TaggedStruct("Exit", {
6 unmodified lines
260 ])261 )262);263350/** A reply whose call died in the platform: its own failure, not an answer. */264const decodeDefect = Schema.decodeUnknownOption(265 Schema.fromJsonString(266 Schema.Tuple([Schema.TaggedStruct("Defect", { defect: Schema.Unknown })])267 )268);269357/** An anonymous `/rpc` `listAsks` of `project`, as the platform answers it. */270const listAsks = (origin: string, project: string, label: string) =>271 send(272 label,273 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${origin}/rpc`), [
5 unmodified lines
279 }),280 ])281 );282371/** A read anyone may make, refused for a project that doesn't exist. */283const anonymousUnknownProject = (origin: string) =>284 Effect.gen(function* () {285 const label = "POST /rpc listAsks";286
24 unmodified lines
311 })312 );313 });314404/**405 * Whether the platform at `origin` holds the seeded example: false only406 * when it refuses the example as an unknown project; any other answer407 * leaves the example's probes to say what is wrong.408 */315// False only on an UnknownProject refusal; any other answer leaves the probes to report it.316const holdsSeeded = (origin: string) =>317 listAsks(origin, SEEDED.project, `POST /rpc listAsks ${SEEDED.project}`).pipe(318 Effect.flatMap(({ text }) => Effect.option(decodeRefused(text))),319 Effect.map(
4 unmodified lines
324 ),325 Effect.orElseSucceed(() => true)326 );327421/** git's discovery for a repo that doesn't exist. */328const missingRepo = (origin: string) => {329 const route = `/${MISSING}.git/info/refs`;330 const label = `GET ${route}`;331
2 unmodified lines
334 HttpClientRequest.get(`${origin}${route}?service=git-upload-pack`)335 ).pipe(Effect.flatMap(statusIs(label, 404)), Effect.asVoid);336};337432/** The platform's own `/`: a page naming its MCP endpoint and the CLI's installer. */338const platformRoot = (origin: string) => {339 const label = "GET /";340341 return send(label, HttpClientRequest.get(`${origin}/`)).pipe(
9 unmodified lines
351 )352 );353};354450/** `answer`, when its content type is `wanted` (by its media type alone). */355const typeIs =356 (label: string, wanted: string, said: string) => (answer: Answer) =>357 answer.contentType.split(";")[0]?.trim() === wanted358 ? Effect.succeed(answer)
2 unmodified lines
361 reason: `${label} answered ${answer.contentType || "no content type"}, not ${said}`,362 })363 );364461/** The web's front page renders: a page a browser shows, not an error's JSON. */365const webFrontPage = (web: string) => {366 const label = "GET / on the web";367368 return send(label, HttpClientRequest.get(`${web}/`)).pipe(
2 unmodified lines
371 Effect.asVoid372 );373};374472/** An agent surface on the web: 200, with the media type it answers with. */375const agentSurface = (376 web: string,377 { contentType, path }: (typeof agentProbes)[number]378) => {
4 unmodified lines
383 Effect.flatMap(typeIs(label, contentType, contentType))384 );385};386485/**486 * The web's `/llms.txt`: Markdown that opens with its title. The web answers487 * 503 when the platform does not, so a 200 is the service binding working.488 */387// The web answers 503 when the platform does not, so a 200 proves the service binding.388const webLlmsTxt = (web: string, probe: (typeof agentProbes)[number]) => {389 const label = "GET /llms.txt on the web";390391 return agentSurface(web, probe).pipe(
6 unmodified lines
398 )399 );400};401503/**504 * One probe's run: how long it took, and whether it held. A transient miss505 * is asked again, every `ASK_AGAIN`, for `settling` at most; the probe fails506 * with its last miss.507 */402const timed = <A>(403 probe: Probe,404 run: Effect.Effect<A, Missed, HttpClient.HttpClient>,405 settling: Duration.Input
14 unmodified lines
420 probe,421 }))422 );423530/**531 * Runs every probe against the platform at `origin`, and with `web` the532 * web's probes against that origin; with `stage`, `/health` must name it.533 * `settling` bounds how long a probe asks again while a Worker answers with534 * its own failure (30 s unless given).535 */424export const smoke = (425 origin: string,426 options: {427 readonly stage?: Stage;
90 unmodified lines
518 ],519 };520 });521634/** Neither `--url` nor bootstrap's record says where the stage lives. */522export class NoOrigin extends Schema.TaggedError<NoOrigin>()("NoOrigin", {523 file: Schema.String,524 stage: Schema.String,525}) {
1 unmodified line
527 return `no --url, and ${this.file} doesn't record the account's workers.dev subdomain: run bun run bootstrap -- --stage ${this.stage} first`;528 }529}530644/** Where a stage's platform lives, and its web when smoke can know it. */531interface Origins {532 readonly platform: string;533 readonly web: Option.Option<string>;534}535536const trimmed = (origin: string) => origin.replace(/\/+$/u, "");537652/**653 * Where `stage`'s platform and web live: `--url` (and `--web-url`), or654 * bootstrap's workers.dev record. A platform given by `--url` has no web655 * unless `--web-url` names it.656 */538const originsOf = (argv: readonly string[], stage: Stage) =>539 Effect.gen(function* () {540 const given = flagValue(argv, "--url");541 const web = Option.map(flagValue(argv, "--web-url"), trimmed);
12 unmodified lines
554 web: Option.orElse(web, () => Option.some(webOrigin(stage, subdomain))),555 } satisfies Origins;556 });557677/**678 * `bun scripts/smoke.ts --stage <s> [--url <origin>] [--web-url <origin>]`:679 * smoke-tests the stage, printing each probe's time, or each failure and why.680 */558export const main = (argv: readonly string[]) =>559 Effect.gen(function* () {560 const stage = yield* stageOf(argv);561 const origins = yield* originsOf(argv, stage);
42 unmodified lines
modified:infra/stages.ts+7 added-58 removed
1/**2 * The one table of stages and of the Cloudflare resources each one owns.3 * A stage is `dev-<user>`, one person's iteration, or `demo`,4 * the recording and the submission; there is no `prod` before the deadline.5 * Each resource is a job's name plus the stage, never the brand6 * (AGENTS.md principle 5).7 *8 * `bootstrap.ts`, `deploy.ts` and `scripts/smoke.ts` read stages and names9 * only from here, and `packages/config/test/bootstrap.test.ts` holds every10 * `env` block of the platform's and the sandbox's `wrangler.jsonc` to it.11 */1// The one table of stages and the resources each owns, each named by its job2// plus the stage, never the brand. `packages/config/test/bootstrap.test.ts`3// holds every Worker's `wrangler.jsonc` env blocks to it.4import { Effect, FileSystem, Option, Path, Schema } from "effect";514/** A stage's shape: `dev-` and a lowercase user, or `demo`. */6export const Stage = Schema.Union([7 Schema.TemplateLiteral([8 "dev-",9 Schema.String.check(Schema.isPattern(/^[a-z0-9]+$/u)),
2 unmodified lines
12]);1314export type Stage = typeof Stage.Type;1525/**26 * The stages this repo declares: each has an `env` block in every Worker's27 * `wrangler.jsonc`. A new person's stage joins here and there together.28 */16// Each has an `env` block in every Worker's `wrangler.jsonc`; add a stage to both.17export const stages = [18 "dev-oscabriel",19 "demo",20] as const satisfies readonly Stage[];2134/** Every resource one stage owns, by job. */22export interface Resources {36 /** The platform Worker. */23 readonly platform: string;38 /** The sandbox Worker: the Checker and the Lander. */24 readonly sandbox: string;40 /** The web Worker. */25 readonly web: string;42 /** The public Artifacts namespace. */26 readonly projects: string;44 /** The private Artifacts namespace: every project's layer repos. */27 // Private: every project's layer repos.28 readonly layers: string;46 /** The D1 database behind the front page. */29 readonly frontPage: string;48 /** The KV namespace that holds OAuth grants. */30 readonly oauth: string;50 /** The R2 bucket that keeps lane logs. */31 readonly evidence: string;52 /** The R2 bucket the CLI's releases are downloaded from (`/install.sh`, `/releases/*`). */32 readonly releases: string;54 /** The R2 bucket that keeps code history (why, a path's log) by immutable ids. */33 readonly codeCache: string;56 /** The Workflow that merges, checks and lands an answer. */34 readonly answer: string;58 /** The Workflow that hears every push to the public namespace. */35 readonly onPush: string;36}3762/** Each resource's name at `stage`. */38export const resources = (stage: Stage): Resources => ({39 answer: `answer-${stage}`,40 codeCache: `code-cache-${stage}`,41 evidence: `evidence-${stage}`,
9 unmodified lines
51});5253const decodeStage = Schema.decodeUnknownOption(Stage);5480/** `raw` as a stage this repo declares, if it is one. */55export const declaredStage = (raw: string): Option.Option<Stage> =>56 Option.filter(decodeStage(raw), (stage) =>57 stages.some((declared) => declared === stage)58 );5986/**87 * The value `flag` names in `argv`, as `--flag value` or `--flag=value`, if88 * it has one.89 */60export const flagValue = (61 argv: readonly string[],62 flag: string63): Option.Option<string> => {
10 unmodified lines
74 (value) => !value.startsWith("--")75 );76};77108/**109 * Each infra command's failures say, as their message, what went wrong and110 * what to do: `runMain` prints a failure's tag and message, and nothing of111 * its fields. They are a script's failures, not the protocol's refusals, and112 * never carry a secret's value.113 */78// `runMain` prints only a failure's tag and message, so each infra failure's79// message says what to do. None carries a secret's value.80115/** No `--stage` was given: nothing touches a stage by default. */81export class NoStage extends Schema.TaggedError<NoStage>()("NoStage", {}) {82 override readonly message = `no --stage: name one of ${stages.join(", ")}`;83}84120/** `--stage` names no stage this table declares. */85export class UnknownStage extends Schema.TaggedError<UnknownStage>()(86 "UnknownStage",87 { stage: Schema.String }88) {
1 unmodified line
90 return `--stage ${this.stage} is not a stage infra/stages.ts declares (${stages.join(", ")})`;91 }92}93130/** The stage `argv`'s `--stage` names, if this table declares it. */94export const stageOf = (argv: readonly string[]) =>95 Effect.gen(function* () {96 const raw = yield* Effect.fromOption(flagValue(argv, "--stage")).pipe(97 Effect.mapError(() => new NoStage())
3 unmodified lines
101 Effect.mapError(() => new UnknownStage({ stage: raw }))102 );103 });104142/** The repo root, which every infra script's paths are relative to. */105export const repoRoot = Effect.flatMap(Path.Path, (path) =>106 path.fromFileUrl(new URL("..", import.meta.url))107).pipe(Effect.orDie);108147/**148 * Where bootstrap records the account's workers.dev subdomain, relative to149 * the repo root. It is absent until bootstrap's first run.150 */109export const subdomainFile = "infra/workers-dev.json";110153/** `subdomainFile`'s contents. */111export const WorkersDev = Schema.Struct({ subdomain: Schema.NonEmptyString });112156/**157 * The account's workers.dev subdomain, as bootstrap recorded it in158 * `subdomainFile`; none before bootstrap's first run, or when the file does159 * not decode. Seed, smoke and the swarm each read it when no `--url` is160 * given, and say in their own words what to run.161 */113export const recordedSubdomain = Effect.gen(function* () {114 const fs = yield* FileSystem.FileSystem;115 const path = yield* Path.Path;116
5 unmodified lines
122 Effect.option123 );124});125175/** The platform's public origin at `stage`, on the account's workers.dev. */126export const platformOrigin = (stage: Stage, subdomain: string) =>127 `https://${resources(stage).platform}.${subdomain}.workers.dev`;128179/** The web's public origin at `stage`, on the account's workers.dev. */129export const webOrigin = (stage: Stage, subdomain: string) =>130 `https://${resources(stage).web}.${subdomain}.workers.dev`;
modified:infra/teardown.ts+3 added-24 removed
1/**2 * teardown: `bunx varlock run --path infra/ -- bun infra/teardown.ts3 * [--stage <s>] [--keep <project>]… [--apply]`. Prints which throwaways the4 * ledger (`infra/created.jsonl`) still has on the account, and with `--apply`5 * deletes exactly those; `infra/lib/teardown.ts` decides what may be deleted,6 * and says why.7 *8 * It reaches Artifacts with the infra token (`CLOUDFLARE_ACCOUNT_ID` and9 * `CLOUDFLARE_API_TOKEN`, from `varlock run --path infra/`): repos through10 * `@repo/artifacts`' REST adapter, one per namespace, and a namespace itself11 * over the same REST API bootstrap uses to make one (`RepoHost` has no route12 * for a namespace). It mints no repo token. Nothing it runs is a Wrangler or13 * cf `delete`, and it touches no Worker, D1, KV or R2.14 */1// Usage: bunx varlock run --path infra/ -- bun infra/teardown.ts2// [--stage <s>] [--keep <project>]… [--apply]3import { BunRuntime, BunServices } from "@effect/platform-bun";4import { Fetch, FetchFailed } from "@repo/artifacts/fetch";5import { RepoHost } from "@repo/artifacts/repo-host";6import { RepoHostRest } from "@repo/artifacts/repo-host/rest";
13 unmodified lines
20import { teardown, TeardownAccount } from "./lib/teardown.ts";2122const API = "https://api.cloudflare.com/client/v4";2336/** The infra credentials `varlock run --path infra/` puts in the environment. */24const Credentials = Config.all({25 accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),26 token: Config.Redacted("CLOUDFLARE_API_TOKEN"),27});2842/** Where a request went: the origin and the path, never a query or a header. */29// Never a query or a header, so no credential reaches the output.30const placeOf = (request: Request) => {31 const url = new URL(request.url);3233 return `${url.origin}${url.pathname}`;34};3549/** The `Fetch` port over Bun's own fetch, as effect/http finds it. */36const BunFetch = Layer.effect(37 Fetch,38 Effect.gen(function* () {39 const send = yield* FetchHttpClient.Fetch;
14 unmodified lines
54 });55 })56);5772/**73 * The account over its REST API: a namespace's repos through a REST74 * `RepoHost` made on first use and kept for the run, and a namespace's own75 * route read or deleted directly, where 404 means it isn't there and any76 * other refusal stops the run.77 */58const LiveAccount = Layer.effect(59 TeardownAccount,60 Effect.gen(function* () {61 const { accountId, token } = yield* Credentials;
22 unmodified lines
84 onSome: (host) => Effect.succeed([host, all] as const),85 })86 );87108 /** One call to a namespace's own route: true on 200, false on 404. */88 const namespaceCall = (name: string, method: "DELETE" | "GET") =>89 Effect.gen(function* () {90 const response = yield* fetch91 .fetch(
46 unmodified lines
modified:scripts/lib/import/live.ts+2 added-43 removed
1/**2 * The import run's real target, backfill and web: a platform over `/rpc` as3 * the operator, git's `ls-remote` anonymously through the gateway, the tag4 * backfill through `@repo/artifacts`' REST adapter with the ops5 * credentials, as `infra/teardown.ts` reaches Artifacts, and the warm6 * reads through the stage's web, anonymously. No token is ever printed:7 * the operator's goes only into the `Authorization` header of `/rpc`8 * calls, and the backfill's write token only into git's env.9 */1import { Fetch, FetchFailed } from "@repo/artifacts/fetch";2import { RepoHost, RepoName } from "@repo/artifacts/repo-host";3import { RepoHostRest } from "@repo/artifacts/repo-host/rest";4import { Client, Contracts } from "@repo/protocol/contracts";
40 unmodified lines
45const failed = (reason: string) => new ImportExamplesFailed({ reason });4647const isRefusal = Schema.is(Refusal);4858/** A call the platform refused, said as `explain` says it; or one it never answered. */49const failedCall =50 (call: string) =>51 (error: { readonly _tag: string; readonly message: string }) =>52 isRefusal(error)
3 unmodified lines
56 .join("; ")}`57 )58 : failed(`${call} got no answer from the platform: ${error.message}`);5970/** git's env for a run of its own: no machine config, no prompt. */60const GIT_ENV = {61 GIT_CONFIG_GLOBAL: "/dev/null",62 GIT_CONFIG_NOSYSTEM: "1",63 GIT_TERMINAL_PROMPT: "0",
2 unmodified lines
6667const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>68 bytes.pipe(Stream.decodeText(), Stream.mkString);6981/**82 * `command` run to its end; what it printed when it ended well. A failure83 * says what git said, with every secret of the command's env cut out.84 */70const runCommand = (71 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],72 command: Command73) =>
49 unmodified lines
123 );124 })125 );126142/** The refs `git ls-remote` lists, counted: branches, and tags without their peeled lines. */127const countsOf = (listed: string) => {128 const refs = listed129 .split("\n")130 .map((line) => line.split("\t")[1] ?? "")
6 unmodified lines
137 ).length,138 };139};140157/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */141const clientAt = (142 origin: string,143 token: Redacted.Redacted144): Layer.Layer<Client> =>
8 unmodified lines
153 ),154 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])155 );156174/** The platform at `origin`, reached as the operator with `token`. */157export const platformTarget = (input: {158 readonly origin: string;159 readonly token: Redacted.Redacted;160 readonly label: string;
25 unmodified lines
186 });187 })188 ).pipe(Layer.provide(clientAt(input.origin, input.token)));189208/** How long one warm read may take: a cold why on a long history takes seconds. */190// A cold why on a long history takes seconds.191const WARM_READ_TIMEOUT = Duration.seconds(90);192211/** `duration` in seconds, to a tenth. */193const secondsOf = (duration: Duration.Duration) =>194 `${(Duration.toMillis(duration) / 1000).toFixed(1)} s`;195215/**216 * The web at `web`, read anonymously, page by page, each body read to its217 * end so the server finishes what it draws; the README's path asked of the218 * platform at `origin` (`readTree`, a public read).219 */196export const webWarmer = (input: {197 readonly origin: string;198 readonly token: Redacted.Redacted;199 readonly web: string;
34 unmodified lines
234 Layer.provide(clientAt(input.origin, input.token)),235 Layer.provide(FetchHttpClient.layer)236 );237262/** No web to warm through: the Node world serves the platform alone. */238export const noWarmer = Layer.succeed(239 Warmer,240 Warmer.of({ warm: () => Effect.succeed([]) })241);242268/**269 * A deployed dev stage at `url`, or at the workers.dev origin bootstrap270 * recorded, as the operator: `OPERATOR_TOKEN` from the env271 * (`bunx varlock run --path apps/platform/ -- …`), never printed.272 */243export const stageTarget = (244 stage: Stage,245 url: string | undefined,246 web: string | undefined
45 unmodified lines
292 );293 })294 );295326/** The operator's token in the Node world: no secret, never leaves this machine. */296// No secret: the Node world never leaves this machine.297const worldToken = Redacted.make(298 "operator-import-world-token-0123456789abcdef"299);300331/** The Node world, served for as long as the layer lasts, with the operator's session. */301export const worldTarget: Layer.Layer<302 ImportTarget | Warmer,303 ImportExamplesFailed,304 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
12 unmodified lines
317 )318 )319);320352/** The `Fetch` port over the runtime's own fetch, as effect/http finds it. */321const RuntimeFetch = Layer.effect(322 Fetch,323 Effect.gen(function* () {324 const send = yield* FetchHttpClient.Fetch;
11 unmodified lines
336 });337 })338);339372/** How long the backfill's write token lives: one backfill, at most. */340const TOKEN_TTL = Duration.minutes(10);341375/**376 * The backfill on `stage`: its public namespace's repos through377 * `RepoHostRest`, with the ops credentials (`CLOUDFLARE_ACCOUNT_ID`,378 * `CLOUDFLARE_API_TOKEN`, from `bunx varlock run --path infra/ -- …`).379 * Each backfill mints a write token on the canonical repo for at most ten380 * minutes, fetches the source's tags into a temporary bare repo, pushes381 * `refs/tags/*` only, and revokes the token, whatever came of the push.382 */342export const restBackfill = (343 stage: Stage344): Layer.Layer<345 TagBackfill,
106 unmodified lines
modified:scripts/lib/import/plan.ts+7 added-58 removed
1/**2 * What `scripts/import-examples.ts` imports, the pages it reads to warm3 * each import, and the commands its `--tags` backfill runs: pure, so a test4 * reads them without a network.5 *6 * Thirty-eight repos. The first eight were each picked for a shape the7 * code browser must render: a Rust crate with a `master` default and 1058 * annotated tags first, then a TypeScript library, a Go CLI, a Python9 * package with a long merge history, a Markdown list, a deep monorepo with10 * 740 scoped tags, large single-file C headers, and a repo off GitHub with11 * a submodule. The thirty after them are well-known projects in12 * TypeScript, JavaScript, Rust, Go, Python, C, Ruby and shell, so a reader13 * finds code they know; each is a copy, read-only here, under its own14 * licence.15 */1import { ProjectKey, ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";2import { Option, Redacted } from "effect";319/**20 * One repo to import: the project it becomes, by its name at its source21 * path (`github.com/pallets/click`) and the key it was first imported22 * under (`click`), which the platform keeps as its repo's name and the23 * ledger records; where it is, its branch, what it is, and its licence.24 */4export interface ImportExample {5 readonly name: ProjectName;6 readonly key: ProjectKey;7 readonly url: string;29 /** The remote's default branch, named so the import never guesses. */8 readonly branch: string;31 /** What kind of repo it is, said for a person. */9 readonly kind: string;33 /** Its licence, as an SPDX expression. */10 readonly licence: string;11}1237/** A row: its key, and its name at its source path, read from the URL. */13const example = (14 key: string,15 url: string,16 branch: string,
7 unmodified lines
24 name: ProjectName.make(`${Option.getOrThrow(sourceNamespaceOf(url))}/${key}`),25 url,26});2753/** The repos, in the order they import: anyhow first, the probe for `master` and tags. */28// anyhow first: it probes a `master` default and tags.29export const examples: readonly ImportExample[] = [30 example(31 "anyhow",32 "https://github.com/dtolnay/anyhow",
49 unmodified lines
82 "master",83 "C on Codeberg",84 "MIT"85 ),111 // Well known, so a reader meets code they have read before: permissive112 // licences, each under 14 MB on GitHub, as the eight above import well.86 example(87 "hono",88 "https://github.com/honojs/hono",89 "main",
204 unmodified lines
294 "MIT"295 ),296];297325/**326 * The imports still to run: `only`'s example when it names one, else every327 * example, less each project the platform lists already. A name it lists328 * is never imported again, whatever repo it came from.298// A name the platform lists is never imported again, whatever repo it came from.329 */299export const planImports = (300 all: readonly ImportExample[],301 listed: ReadonlySet<ProjectName>,302 only: Option.Option<ProjectName>
5 unmodified lines
308 onSome: (named) => named === name,309 }) && !listed.has(name)310 );311343/**344 * The pages read once after an import, so its first reader does not pay345 * for a cold read: its home, its root folder, its landings, and, when it346 * has a README, the README and why each of its lines is there. Why and a347 * file's history are kept by commit once read (ADR 0020).348 */312export const warmPaths = (313 project: ProjectName,314 readme: Option.Option<string>315): readonly string[] => [
8 unmodified lines
324 ],325 }),326];327365/** A git remote and the token that writes to it, kept apart so the URL can be shown. */328// Kept apart from the token so the URL can be shown.329export interface RedactedUrl {330 readonly url: string;331 readonly token: Redacted.Redacted;332}333371/**372 * One command a run spawns: its argv, which may be printed, and env values373 * of its own, which never are.374 */334// Its argv may be printed; its env values never are.335export interface Command {336 readonly argv: readonly string[];337 readonly env?: Readonly<Record<string, Redacted.Redacted>>;338}339380/** How a command is shown: its argv alone, never its env. */340export const shownCommand = ({ argv }: Command) => argv.join(" ");341383/** Every tag, under its own name: the one refspec the backfill pushes. */342const TAGS = "refs/tags/*:refs/tags/*";343386/**387 * The backfill of an import that came without its tags: fetch the388 * source's tags into the bare repo `mirror`, then push those tags, and389 * only those, to `remote`. The write token goes to git as an390 * `Authorization` header through git's `GIT_CONFIG_*` env, so it is in no391 * argument, no URL and no printed line. Nothing pushes a branch: `main`392 * moves only by a landing.393 *394 * Only the tags are fetched (not `clone --mirror`, which would bring every395 * `refs/pull/*` GitHub keeps): the canonical repo already has the history396 * they point into, so the push sends the tag objects and little else.397 */344// The write token reaches git as an `Authorization` header through `GIT_CONFIG_*`,345// so it is in no argument, URL or printed line. Only the tags are fetched: a346// `clone --mirror` would bring every `refs/pull/*` GitHub keeps.347export const tagBackfillCommands = (input: {348 readonly source: string;349 readonly mirror: string;350 readonly remote: RedactedUrl;
33 unmodified lines
modified:scripts/lib/import/run.ts+8 added-79 removed
1/**2 * The import run: reads the flags, asks the platform what it lists, imports3 * the rest of the examples one at a time, prints each one's heads and tags,4 * records each new import on a stage in the ledger as kept, warms each new5 * import by reading its pages once through the web, with `--tags`6 * backfills the tags of an import that came without them, and with7 * `--warm` warms the examples the platform listed already.8 *9 * The platform, the backfill and the web are services (`ImportTarget`,10 * `TagBackfill`, `Warmer`), so a test runs the whole run over fakes;11 * `live.ts` holds the real ones.12 */1import { ProjectName } from "@repo/protocol/ids";2import type { ProjectKey } from "@repo/protocol/ids";3import { ProjectExists } from "@repo/protocol/refusal";4import {
20 unmodified lines
25import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";26import { examples, planImports } from "./plan.ts";27import type { ImportExample } from "./plan.ts";2841/** Why the run stopped, said for a person; never a token. */29export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(30 "ImportExamplesFailed",31 { reason: Schema.String }32) {
3 unmodified lines
36}3738const failed = (reason: string) => new ImportExamplesFailed({ reason });3953/** Where the imports go: a dev stage, or the Node world on this machine. */40export const ImportWhere = Schema.TaggedUnion({41 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },42 World: {},43});4445export type ImportWhere = typeof ImportWhere.Type;4661/** What `bun scripts/import-examples.ts` was asked to do. */47export interface ImportOptions {48 readonly where: ImportWhere;64 /** The one example to import, when not all. */49 readonly only: Option.Option<ProjectName>;66 /** Print the plan, import and record nothing. */50 readonly dryRun: boolean;68 /** Backfill the tags of an import that has none. */51 readonly tags: boolean;70 /** Keep the source of each earlier import on its record (ADR 0031). */52 readonly sources: boolean;72 /** Warm the examples the platform lists already, as well as each new import. */53 readonly warm: boolean;74 /** The web's origin to warm through, when the stage's own can't be known. */54 readonly web: Option.Option<string>;55}5678/** The platform the imports go to, as the operator. */57export class ImportTarget extends Context.Service<58 ImportTarget,59 {82 /** Where it is, said for a person: `dev-oscabriel (https://…)`. */60 readonly label: string;61 readonly listProjects: Effect.Effect<62 ReadonlySet<ProjectName>,63 ImportExamplesFailed64 >;88 /** One `initProject` importing `example`: main's first landed SHA. */65 readonly initProject: (66 example: ImportExample67 ) => Effect.Effect<{ readonly landed?: string }, ImportExamplesFailed>;92 /** How many branches and tags the project's repo serves, anonymously. */68 readonly counts: (69 project: ProjectName70 ) => Effect.Effect<71 { readonly heads: number; readonly tags: number },
1 unmodified line
73 >;74 }75>()("scripts/ImportTarget") {}76102/**103 * Pushes an import's tags from its source to its canonical repo: the one104 * write that skips the gateway, tags only, by the operator. How many tags105 * it pushed.106 */77/** The one write that skips the gateway: tags only, by the operator. */78export class TagBackfill extends Context.Service<79 TagBackfill,80 {81 readonly backfill: (
1 unmodified line
83 ) => Effect.Effect<number, ImportExamplesFailed>;84 }85>()("scripts/TagBackfill") {}86116/** One page read to warm an import: where, whether it answered, and what it said. */87export interface WarmRead {88 readonly path: string;89 readonly ok: boolean;120 /** Its status and time, or why it failed; said for a person. */90 readonly said: string;91}92124/**125 * Reads an import's pages once through the web, anonymously, so its first126 * reader finds why and its history kept. A read that fails is reported in127 * what it gives back, never as a failure: warming is a courtesy.128 */93// A failed read is reported, never a failure: warming is a courtesy.94export class Warmer extends Context.Service<95 Warmer,96 {97 readonly warm: (project: ProjectName) => Effect.Effect<readonly WarmRead[]>;
2 unmodified lines
100101const isProjectExists = Schema.is(ProjectExists);102103/**139 * One import's `initProject`, asked again 30 s apart, up to three more140 * times, while it got no answer (`answered` false): a large import can141 * outlast the edge's request timeout, and the platform adopts the repo the142 * first call left. A refusal is never asked again. `ProjectExists` after a143 * call that got no answer is that call's project, made after its answer144 * was lost: this run's import, its landed SHA not known here.104 * A large import can outlast the edge's request timeout; the platform adopts105 * the repo the first call left, so a call with no answer is asked again. A106 * `ProjectExists` after such a call is that call's own project.107 */108export const initUntilAnswered = <A extends { readonly landed?: string }, E>(109 call: Effect.Effect<A, E>,110 answered: (error: E) => boolean
22 unmodified lines
133134const USAGE =135 "bun scripts/import-examples.ts --world node | --stage <stage> [--url <origin>] [--web <origin>] [--only <project>] [--tags] [--sources] [--warm] [--dry-run]";136175/** The flags the command takes; any other is a typo, refused. */137const FLAGS = new Set([138 "--dry-run",139 "--only",140 "--sources",
6 unmodified lines
147]);148149const decodeProject = Schema.decodeUnknownOption(ProjectName);150190/** The command's flags, read; a typo or a stage the table does not declare is refused before anything runs. */151export const optionsOf = (152 argv: readonly string[]153): Effect.Effect<ImportOptions, ImportExamplesFailed> =>154 Effect.gen(function* () {
73 unmodified lines
228 where,229 };230 });231272/**273 * The ledger's line for an import's repo, in the stage's public namespace,274 * by its key: the repo's name, as the platform keeps it.275 */232const repoLine = (233 stage: Stage,234 key: ProjectKey,235 at: DateTime.Utc
5 unmodified lines
241 namespace: resources(stage).projects,242 stage,243});244289/** The ledger's two lines for a new import on `stage`: its project, and its repo, by its key. */245const importLines = (246 stage: Stage,247 key: ProjectKey,248 at: DateTime.Utc
4 unmodified lines
253254const ledgerFailed = ({ message }: PlatformError.PlatformError) =>255 failed(`the ledger (${ledgerPath}): ${message}`);256302/** Appends `entries` to the ledger. */257const record = (entries: readonly Created[]) =>258 Effect.forEach(entries, recordCreated, { discard: true }).pipe(259 Effect.mapError(ledgerFailed)260 );261308/** The stage the run records on, if it runs on one. */262const stageOfWhere = (where: ImportWhere) =>263 ImportWhere.match(where, {264 Stage: ({ stage }) => Option.some(stage),265 World: () => Option.none<Stage>(),266 });267315/**316 * `--tags` on one import: its tags pushed from its source when its repo317 * serves none, the ledger told, and a line printed.318 */268const backfillOne = (269 example: ImportExample,270 tagCount: number,271 stage: Option.Option<Stage>
16 unmodified lines
288 ` ${example.name}: ${pushed} tags backfilled from ${example.url}`289 );290 });291343/** One project warmed, and a line saying how it went. */292const warmOne = (project: ProjectName) =>293 Effect.gen(function* () {294 const reads = yield* Warmer.use((warmer) => warmer.warm(project));295 const failures = reads.filter(({ ok }) => !ok);
7 unmodified lines
303 : ` warm ${project}: no web to read through`304 );305 });306359/**360 * The projects the ledger records as imports on `stage`: an import the361 * platform does not list (one adopted before adoptions were heard) is362 * still this stage's, never imported again.363 */307// An import the ledger records but the platform does not list is still never imported again.308const recordedImports = (stage: Option.Option<Stage>) =>309 Effect.gen(function* () {310 if (Option.isNone(stage)) {311 return new Set<ProjectName>();
19 unmodified lines
331 )332 );333 });334391/**392 * `--sources` on one earlier import: `initProject` asked again with the393 * same source, which the platform takes as the source to keep (ADR 0031)394 * and answers as the import did; a refusal is printed, never fatal.395 */335// A repeated `initProject` with the same source makes the platform keep that source.336const sourceOne = (example: ImportExample) =>337 Effect.gen(function* () {338 const target = yield* ImportTarget;339
4 unmodified lines
344345 yield* Console.log(` ${example.name}: ${outcome}`);346 });347408/** The run itself, over a target, a backfill and a web. */348const run = (options: ImportOptions) =>349 Effect.gen(function* () {350 const target = yield* ImportTarget;351 const listed = yield* target.listProjects;
4 unmodified lines
356 const asked = planImports(examples, new Set(), options.only);357 const plan = planImports(examples, known, options.only);358 const skipped = asked.filter(({ name }) => known.has(name));359421 // The earlier imports `--tags` and `--sources` go back over: on a422 // stage, those the ledger records; in the Node world, every one listed.360 const earlier = skipped.filter(361 ({ name }) => Option.isNone(stage) || recorded.has(name)362 );363
42 unmodified lines
406 Effect.gen(function* () {407 const made = yield* target.initProject(example);408 const at = yield* DateTime.now;409473 // Recorded as soon as the platform made it, before anything else474 // can fail.410 // Recorded before anything else can fail.411 yield* Option.match(stage, {412 onNone: () => Effect.void,413 onSome: (on) => record(importLines(on, example.key, at)),414 });
12 unmodified lines
427 }),428 { discard: true }429 );430495 // An import from an earlier run that this run skipped is backfilled496 // too, if the ledger holds it as an import of this stage.431 if (options.tags && Option.isSome(stage)) {432 yield* Effect.forEach(433 earlier,434 (example) =>
20 unmodified lines
455 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`456 );457 });458525/**526 * `bun scripts/import-examples.ts …`: reads the flags (a bad one refused527 * before anything is built or called), then runs over the target, backfill528 * and web `layersOf` gives for them.529 */459export const importExamples = <E, R>(460 argv: readonly string[],461 layersOf: (462 options: ImportOptions
7 unmodified lines
modified:scripts/lib/release/install-script.ts+1 added-18 removed
1/**2 * The install script the platform serves at `<origin>/install.sh`, as the3 * release writes it for one version and one origin:4 * `curl -fsSL <origin>/install.sh | sh`. POSIX `sh`, so it runs on Linux and5 * macOS as they come. It downloads the binary for the machine from the platform, checks it6 * against the release's `SHA256SUMS` from the same place, and installs nothing7 * unless the two agree.8 */1import type { Brand } from "@repo/brand";211/** `value` as one single-quoted shell word. */3const quoted = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;414/**15 * The script for `version`, whose files are at `baseUrl`: the stage's16 * public origin and `/releases/<version>`, where the platform serves17 * `<slug>-<target>` and `SHA256SUMS`. `machines` are the targets a release18 * builds, without Bun's `bun-` prefix (`linux-x64`). It installs the19 * binary as `<dir>/<cli>` and links `<dir>/git-credential-<slug>` to it (the20 * one binary is git's credential helper when started by that name); `<dir>`21 * is `$<SLUG>_INSTALL_DIR`, or `~/.local/bin`.22 */5// The one binary is also git's credential helper when started as `git-credential-<slug>`.6export const installScriptFor = (input: {7 readonly brand: typeof Brand;8 readonly version: string;9 readonly baseUrl: string;
87 unmodified lines
modified:scripts/lib/release/readme.ts-6 removed
1/**2 * The npm package's own README: how to install the CLI, start3 * it and use its sdk, every name from `Brand`. The repo's README is about4 * the platform; this one is what npm and pi show for the package.5 */1import type { Brand } from "@repo/brand";23const fence = (lines: readonly string[]) => ["```sh", ...lines, "```"];410/** The package's README for `version`. */5export const packageReadme = (input: {6 readonly brand: typeof Brand;7 readonly version: string;8}): string => {
48 unmodified lines
modified:scripts/lib/release/steps.ts+2 added-63 removed
1/**2 * What each step of a release does on this machine, over the3 * plan `scripts/lib/release.ts` makes:4 *5 * - `tsdown`: the CLI's `bun run build` in `apps/cli`, with both targets6 * (`dist/`, and `dist/bin/<target>/` per target), stamped with the7 * release's version (what `--version` prints);8 * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the9 * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its10 * README and the repo's licence;11 * - `copySkills`: the platform's skill (`@repo/agent-kit`'s12 * `platformSkill` over `commandDocs(Contracts)`) into its `skills/`;13 * - `compile`: each target's binary, copied to `apps/cli/release/<slug>-<target>`;14 * - `installScript` and `checksums`: `apps/cli/release/install.sh` and15 * `SHA256SUMS`;16 * - `upload`: the version's files into the stage's `releases-<stage>`17 * bucket with Wrangler's own login, then `releases/manifest.json` last;18 * - `publish`: `npm publish` of the staged package, which the plan allows19 * only when a person runs it (H2).20 *21 * The package is staged beside the binaries rather than in `dist/`: its22 * manifest names `./dist/…` and `./skills` from the package's root, and23 * `dist/bin/` holds the binaries, which npm must not ship.24 */1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";3import { Brand } from "@repo/brand";4import { Contracts } from "@repo/protocol/contracts";
32 unmodified lines
37} from "../release.ts";38import type { ReleaseAsset, ReleaseStep } from "../release.ts";39import { packageReadme } from "./readme.ts";4065/** A step could not finish; nothing after it ran. */41export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(42 "ReleaseFailed",43 { reason: Schema.String, step: Schema.String }44) {
1 unmodified line
46 return `${this.step}: ${this.reason}`;47 }48}4975/** Where a release reads and writes, from the repo root. */50export interface Layout {51 readonly root: string;78 /** `apps/cli`, where the CLI's build runs. */52 readonly cli: string;80 /** `apps/cli/dist`, the CLI's build. */53 readonly dist: string;82 /** `apps/cli/release`: the binaries, the install script and the checksums. */54 readonly release: string;84 /** `apps/cli/release/npm`: the npm package, as `npm publish` takes it. */55 /** Staged outside `dist/`, whose `bin/` holds the binaries npm must not ship. */56 readonly npm: string;57}5859export const layoutOf = (root: string) =>
9 unmodified lines
69 root,70 };71 });72102/** One release: its version, and the origin its install script fetches from. */73export interface Release {74 readonly version: string;105 /** The platform's public origin, without a trailing `/`. */75 readonly origin: string;107 /** The stage an upload goes to. */76 readonly stage: Option.Option<Stage>;77}78111/** The command a person runs from the repo root to publish the staged package. */79export const publishCommand = (layout: Layout, path: Path.Path) =>80 `npm publish ${path.relative(layout.root, layout.npm)} --access public`;8182const failed = (step: ReleaseStep, reason: string) =>83 new ReleaseFailed({ reason, step });84118/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */85const run = (86 step: ReleaseStep,87 command: string,88 args: readonly string[],
17 unmodified lines
106 ),107 Effect.asVoid108 );109144/** What the release reads of a package manifest. */110const PackageJson = Schema.fromJsonString(111 Schema.Struct({112 dependencies: Schema.optionalKey(113 Schema.Record(Schema.String, Schema.String)
14 unmodified lines
128 Effect.flatMap(Schema.decodeEffect(PackageJson)),129 Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))130 );131167/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */132const builtFiles = (layout: Layout) =>133 Effect.gen(function* () {134 const fs = yield* FileSystem.FileSystem;135 const path = yield* Path.Path;
10 unmodified lines
146147 return Arr.sort(files, Order.String);148 });149186/** `manifest`: the npm package, staged afresh from the build. */150const stagePackage = (layout: Layout, release: Release) =>151 Effect.gen(function* () {152 const fs = yield* FileSystem.FileSystem;153 const path = yield* Path.Path;
71 unmodified lines
225226 return manifest;227 });228266/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */229const writeSkills = (layout: Layout) =>230 Effect.gen(function* () {231 const fs = yield* FileSystem.FileSystem;232 const path = yield* Path.Path;
8 unmodified lines
241 )242 );243 });244283/** `compile`: each target's binary, as the release folder and the platform name it. */245const collectBinaries = (layout: Layout) =>246 Effect.gen(function* () {247 const fs = yield* FileSystem.FileSystem;248 const path = yield* Path.Path;
29 unmodified lines
278 })279 );280 });281321/** The files a release serves under its version: each binary, and the install script. */282const releasedFiles = [283 ...targets.map((target) => binaryName(Brand, target)),284 "install.sh",285];286327/** A file's sha256, as `sha256sum` prints it, and its size. */287const assetOf = (file: string) =>288 Effect.gen(function* () {289 const fs = yield* FileSystem.FileSystem;290 const crypto = yield* Crypto.Crypto;
7 unmodified lines
298 .join(""),299 } satisfies ReleaseAsset;300 });301343/** Each released file in the release folder, by name. */302const assetsIn = (layout: Layout) =>303 Effect.flatMap(Path.Path, (path) =>304 Effect.forEach(releasedFiles, (name) =>305 Effect.map(
2 unmodified lines
308 )309 )310 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));311354/** `checksums`: `SHA256SUMS` beside the files it lists. */312const writeChecksums = (layout: Layout) =>313 Effect.gen(function* () {314 const fs = yield* FileSystem.FileSystem;315 const path = yield* Path.Path;
10 unmodified lines
326 ["install.sh", "text/x-shellscript; charset=utf-8"],327 ["manifest.json", "application/json"],328]);329373/** A binary is bytes; the install script and the manifest are text. */330const contentTypeOf = (file: string) =>331 contentTypes.get(file) ?? "application/octet-stream";332377/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */333const wranglerOf = (layout: Layout, path: Path.Path) =>334 path.join(335 layout.root,336 "apps",
2 unmodified lines
339 ".bin",340 "wrangler"341 );342388/**389 * Runs Wrangler in `cwd` with its own login (never the read-mostly infra390 * token; `infra/.env.schema`), and gives its exit code and everything it391 * printed.392 */343// Wrangler's own login, never the read-mostly infra token.344const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>345 Effect.gen(function* () {346 const path = yield* Path.Path;347 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
21 unmodified lines
369 failed("upload", `wrangler didn't run: ${message}`)370 )371 );372422/** What Wrangler prints when a bucket holds no object under a key. */373const NO_SUCH_KEY = "The specified key does not exist";374425/** The manifest the stage's bucket holds, if it holds one. */375const previousManifest = (layout: Layout, bucket: string, scratch: string) =>376 Effect.gen(function* () {377 const fs = yield* FileSystem.FileSystem;378 const path = yield* Path.Path;
33 unmodified lines
412 )413 );414 });415467/** `upload`: the version's files into the stage's own bucket, and the manifest last. */416const upload = (layout: Layout, release: Release) =>417 Effect.gen(function* () {418 const fs = yield* FileSystem.FileSystem;419 const path = yield* Path.Path;
62 unmodified lines
482483 return manifest;484 }).pipe(Effect.scoped);485538/** The paths the staged package's manifest names that it lacks. */486export const missingFromPackage = (layout: Layout, version: string) =>487 Effect.gen(function* () {488 const fs = yield* FileSystem.FileSystem;489 const path = yield* Path.Path;
4 unmodified lines
494 Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)495 );496 });497551/**552 * The staged package is whole and of this release's version, so what553 * `npm publish` ships is what this release built: checked before the554 * publish runs, and before an agent hands its command to a person (H2).555 */498export const publishable = (layout: Layout, release: Release) =>499 Effect.gen(function* () {500 const path = yield* Path.Path;501
16 unmodified lines
518 )519 );520 });521580/** `publish`: `npm publish` of the staged package, once it is `publishable`. */522const publish = (layout: Layout, release: Release) =>523 Effect.andThen(524 publishable(layout, release),525 run(
3 unmodified lines
529 layout.root530 )531 );532592/** `installScript`: the install script for this version, fetching from the release's origin. */533const writeInstallScript = (layout: Layout, release: Release) =>534 Effect.gen(function* () {535 const fs = yield* FileSystem.FileSystem;536 const path = yield* Path.Path;
11 unmodified lines
548549 yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);550 });551612/** One step, run. */552export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>553 Match.value(step).pipe(554 Match.when("tsdown", () =>555 run(
23 unmodified lines
modified:scripts/lib/smoke/core-loop.ts+4 added-120 removed
1/**2 * The core loop's steps, as smoke's `--loop` takes them on a platform:3 * 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 */1import { Brand } from "@repo/brand";2import { AnswerView } from "@repo/protocol/domain/answer";3import { Ask } from "@repo/protocol/domain/ask";4import { ClaimView } from "@repo/protocol/domain/claim";
25 unmodified lines
30import { ChildProcess, ChildProcessSpawner } from "effect/process";3132import { cliEntry, personEnv } from "../swarm/workspace.ts";3349/** The loop's steps, in the order it takes them. */34export const LoopStep = Schema.Literals([35 "people",36 "init",37 "open-ask",
8 unmodified lines
46]);4748export type LoopStep = typeof LoopStep.Type;4966/** A step of the loop went wrong: which, and why. Never holds a token. */50// Never holds a token.51export class LoopFailed extends Schema.TaggedError<LoopFailed>()("LoopFailed", {52 reason: Schema.String,53 step: LoopStep,54}) {
1 unmodified line
56 return `${this.step}: ${this.reason}`;57 }58}5976// ------------------------------------------------------------ the fixture7778/** Where the config folder's sdk is imported from, as a maintainer writes it. */60const sdk = `${Brand.cliPackage}/rules`;6181/** The ask the loop opens and answers. */62export const ASK = AskId.make("parse-year");6384/** The one file the ask's territory holds. */64const SOURCE = "src/parse.ts";6587/** The ask's check: the file its kind runs. */66const CHECK = `test/${ASK}.test.ts`;6768const README =69 "A throwaway project smoke's core loop makes, answers and lands.\n";7093/** The project as its decider first pushes it, the answerer vouched for. */71const startFiles = (answerer: Handle) => ({72 [`${Brand.configDir}/project.ts`]: [73 `import { kinds, project } from "${sdk}";`,74 "",
8 unmodified lines
83 "package.json": '{ "name": "smoke", "private": true }\n',84 [SOURCE]: "export const parse = (iso: string) => ({ iso, year: 0 });\n",85});86110/** The ask's own files: its file in the config folder, and its check, which asserts. */87const askFiles = [88 {89 content: [90 `import { kinds, territory } from "${sdk}";`,
21 unmodified lines
112 path: CHECK,113 },114] as const;115140/** The answer: the year, read. */116const yearRead =117 "export const parse = (iso: string) => ({ iso, year: Number(iso.slice(0, 4)) });\n";118144// --------------------------------------------------------------- processes145146/** How a process ended, and what it printed. */119interface Ran {120 readonly code: number;121 readonly stdout: string;122 readonly stderr: string;123}124153/** The longest one command may take: a cold Checker runs an ask's check twice. */125// A cold Checker runs an ask's check twice.126const PATIENCE = Duration.minutes(10);127156/** One person the loop acts as. */128export interface LoopPerson {129 readonly handle: Handle;159 /** Their folder: the CLI's config, their gitconfig, git's credential helper. */130 readonly home: string;161 /** The env their CLI and git run in: their token, the platform, their gitconfig. */131 readonly env: Readonly<Record<string, string | undefined>>;163 /** Their token, blanked out of anything the loop says. */132 readonly token: Redacted.Redacted;133}134135const failed = (step: LoopStep, reason: string) =>136 new LoopFailed({ reason, step });137170/** `text` with each of `tokens` blanked out. */138const scrubbed = (text: string, tokens: readonly Redacted.Redacted[]) => {139 let clean = text;140141 for (const token of tokens) {
2 unmodified lines
144145 return clean;146};147181/** All a byte stream says, as text. */148const textOf = <E>(bytes: Stream.Stream<Uint8Array, E>) =>149 bytes.pipe(Stream.decodeText(), Stream.mkString);150185/** `command args` in `cwd` as `person`: how it ended, and what it printed. */151const run = (152 step: LoopStep,153 person: Pick<LoopPerson, "env" | "token">,154 command: string,
38 unmodified lines
193 ),194 })195 );196232/** git as `person` in `cwd`, which must succeed; what it printed. */197const gitOk = (198 step: LoopStep,199 person: LoopPerson,200 cwd: string,
12 unmodified lines
213 )214 )215 );216253/**254 * One CLI command as `person`, with `--json`: its data, decoded by `data`.255 * A refusal fails the step with what the platform said, as `explain` says256 * it everywhere; output that is no envelope fails it with what the command257 * printed.258 */217const cli = <A, I>(218 step: LoopStep,219 person: Pick<LoopPerson, "env" | "token">,220 args: readonly string[],
36 unmodified lines
257 .join("; ")}`258 );259 });260303// ----------------------------------------------------------------- people304305/**306 * git's credential helper for a person: this repo's CLI from source, as307 * `git-credential-<slug>`, which hands git the token in the env.308 */261const helperShim = [262 "#!/bin/sh",263 `# ${Brand.gitCredentialHelper} for smoke's core loop: this repo's CLI from source, under Bun.`,264 `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' credential "$@"`,265 "",266].join("\n");267316/** A shim runs for everyone; only its owner writes it. */268const SHIM_MODE = 0o755;269319/** A person's folder holds the CLI's config: owner only. */270const HOME_MODE = 0o700;271322/**323 * A person at `home` on the platform at `origin`, holding `token`: their324 * folder, with git's credential helper on `PATH` and a gitconfig of their325 * own (their name, and the helper for the platform), so nothing of this326 * machine's git or CLI config answers instead. Their handle is whoever the327 * platform says the token names (`status`).328 */272// A gitconfig of their own, so nothing of this machine's git or CLI config answers instead.273export const personAt = (input: {274 readonly home: string;275 readonly origin: string;276 readonly token: Redacted.Redacted;
75 unmodified lines
352353 return { env, handle, home, token };354 });355412// ------------------------------------------------------------------ steps413414/** `files` written under `dir`, each at its path. */356const writeFiles = (357 step: LoopStep,358 dir: string,359 files: Readonly<Record<string, string>>
17 unmodified lines
377 { discard: true }378 )379 );380440/** `files` written in the work tree at `cwd` and committed as `person`; the commit. */381const commit = (382 step: LoopStep,383 person: LoopPerson,384 cwd: string,
18 unmodified lines
403const Listed = Schema.Struct({404 projects: Schema.Array(Schema.Struct({ project: ProjectName })),405});406467/**468 * Whether `project` is free on the platform, as `person` lists every469 * project (`<cli> projects`): a taken name fails the step, before470 * anything is made.471 */407export const projectIsFree = (person: LoopPerson, project: ProjectName) =>408 Effect.flatMap(cli("init", person, ["projects"], Listed), ({ projects }) =>409 projects.some((listed) => listed.project === project)410 ? Effect.fail(
9 unmodified lines
420 pushed: Schema.Boolean,421 remote: Schema.NonEmptyString,422});423489/**490 * Makes `project` from the fixture, as `decider`: a repo of its first files491 * at `dir`, then `<cli> init`, which makes the project, wires its remote492 * and pushes main's first commit.493 */424export const initProject = (input: {425 readonly decider: LoopPerson;426 readonly answerer: Handle;427 readonly project: ProjectName;
33 unmodified lines
461 });462463const Opened = Schema.Struct({ ask: Ask, landed: LandedSha });464535/** Opens the fixture's ask as `decider`: its check fails on main twice the same way first. */465export const openAsk = (decider: LoopPerson, project: ProjectName) =>466 cli(467 "open-ask",468 decider,
11 unmodified lines
480 );481482const Claimed = Schema.Struct({ claim: ClaimView });483555/** Claims the fixture's ask as `answerer`: their fork, and where it lives. */484export const claimAsk = (answerer: LoopPerson, project: ProjectName) =>485 Effect.map(486 cli("claim", answerer, ["claim", ASK, "--project", project], Claimed),487 ({ claim }) => claim
2 unmodified lines
490// Each refusal's first line among git's `remote:` lines, as `render` writes491// it: `remote: OutOfScope: …`.492const REFUSAL_LINE = /^remote: (?<tag>[A-Z][A-Za-z]+): /gmu;493566/** The refusals' tags git printed from the platform, in order. */494export const refusalTags = (stderr: string): readonly string[] =>495 [...stderr.matchAll(REFUSAL_LINE)].flatMap(({ groups }) =>496 groups?.tag === undefined ? [] : [groups.tag]497 );498572/**573 * Clones the claim's fork as `answerer` into `dir`, and pushes an answer574 * that reaches outside the ask's territory (the README besides the source):575 * git must refuse it, `OutOfScope` among the platform's words. Gives every576 * refusal git printed.577 */499export const pushOutOfScope = (input: {500 readonly answerer: LoopPerson;501 readonly claim: ClaimView;502 readonly dir: string;
33 unmodified lines
536 )537 );538 });539619/** Puts the README back and pushes again: the answer is taken, and checked. */540export const pushAnswer = (answerer: LoopPerson, dir: string) =>541 Effect.gen(function* () {542 const head = yield* commit(543 "answer",
25 unmodified lines
569 });570571const Status = Schema.Struct({ answers: Schema.Array(AnswerView) });572653/** The answer's outcome is not in yet: the gate is still at it. */573class StillChecking extends Schema.TaggedError<StillChecking>()(574 "StillChecking",575 {}576) {}577659/** How the loop waits for a landing: how often it asks, and for how long. */578export interface Patience {579 readonly every: Duration.Duration;580 readonly within: Duration.Duration;581}582665/** What an outcome other than a landing says, in a line. */583const outcomeLine = (outcome: Outcome) =>584 Outcome.match(outcome, {585 AwaitingDecision: ({ decision }) => `waits on the decision ${decision}`,586 AwaitingFinish: () => "waits for a decider's finish",
5 unmodified lines
592 .join("; ")}`,593 WaitingOnParent: ({ ask }) => `waits for its parent ask ${ask} to land`,594 });595679/**680 * Asks `<cli> status` as `answerer` until the answer at `head` is past the681 * gate: its landing, or the step fails with how it ended instead.682 */596export const awaitLanding = (input: {597 readonly answerer: LoopPerson;598 readonly project: ProjectName;599 readonly head: CommitSha;
43 unmodified lines
643 `the answer at ${head} ${outcomeLine(outcome)}`644 );645 });646734/** What the landing commit on main says of itself. */647export interface LandingRead {648 readonly author: string;649 readonly committer: string;650 readonly trailers: readonly string[];651}652741/**742 * Reads the landing on the project's main, from the answerer's clone: main743 * is at `landed`, and the commit's author, committer and trailers.744 */653export const readLanding = (input: {654 readonly answerer: LoopPerson;655 readonly dir: string;656 readonly origin: string;
33 unmodified lines
690691 return { author, committer, trailers } satisfies LandingRead;692 });693786/** Where verdicts live as git notes (`@repo/git/notes`'s `notesRef`). */694// `@repo/git/notes`' `notesRef`.695const NOTES = `refs/notes/${Brand.slug}`;696789/** How long the loop waits for the verdict note, which follows the verdict. */697const NOTE_WAIT = { every: Duration.seconds(1), times: 30 } as const;698792/** The verdict note is not on the answer's head yet. */699class NoNoteYet extends Schema.TaggedError<NoNoteYet>()("NoNoteYet", {}) {}700795/**796 * Reads the verdict note on the answer's `head` in the fork, with plain797 * git, as the answerer: fetch the notes ref, then `git notes show`.798 */701export const readVerdictNote = (input: {702 readonly answerer: LoopPerson;703 readonly dir: string;704 readonly head: CommitSha;
35 unmodified lines
740 )741 )742 );743842// ------------------------------------------------------------------ drafts843844/** What the loop's draft proposal wants: a reader of ordinal dates beside `parse`. */744const DRAFT_WANT =745 "src/parse.ts exports parseOrdinal, which reads an ordinal date such as 2026-280.";746747const Proposed = Schema.Struct({ proposal: Proposal });748749const Shown = Schema.Struct({ proposal: Proposal });750852/** Proposes the draft's want as `proposer`, with `--draft`: the proposal, drafting. */751export const proposeDraft = (proposer: LoopPerson, project: ProjectName) =>752 Effect.map(753 cli(754 "draft-propose",
3 unmodified lines
758 ),759 ({ proposal }) => proposal.id760 );761864/** The draft is still being drafted. */762class StillDrafting extends Schema.TaggedError<StillDrafting>()(763 "StillDrafting",764 {}765) {}766870/** A draft that went red first: the model that drafted it, and its attempts. */767export interface DraftReady {768 readonly model: string;769 readonly attempts: number;770}771876/**877 * Asks `<cli> proposal <id>` as `reader` until the draft is settled: ready,878 * or the step fails with the last refusal a failed draft names.879 */772export const awaitDraft = (input: {773 readonly reader: LoopPerson;774 readonly project: ProjectName;775 readonly proposal: ProposalId;
1 unmodified line
777}) =>778 Effect.gen(function* () {779 const { project, proposal, reader } = input;780889 /** Where the draft stands: settled, or still drafting, which is asked again. */781 const settled = (782 shown: Proposal783 ): Effect.Effect<DraftState, LoopFailed | StillDrafting> =>784 Option.match(Option.fromUndefinedOr(shown.draft), {
48 unmodified lines
833const TodayIs = Schema.Struct({ decisions: Schema.Array(Decision) });834835const Decided = Schema.Struct({ decision: Decision });836946/**947 * Accepts the drafted proposal as `decider`, from their Today, and reads948 * the landing that opened its ask on main, fetched from the platform at949 * `origin` into the repo at `dir`: its950 * trailers, which must disclose the drafter (`Assisted-by:`) and credit951 * `proposer` as its asker.952 */837export const acceptDraft = (input: {838 readonly decider: LoopPerson;839 readonly proposer: Handle;840 readonly project: ProjectName;
75 unmodified lines
modified:scripts/lib/smoke/loop.ts+5 added-73 removed
1/**2 * smoke's `--loop`: 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 checks `<decider>/smoke-<run>` is free (on a stage8 * the operator's, `oscabriel/smoke-<run>`), records its key, then makes9 * it a throwaway project and pushes its first commit;10 * 3. `open-ask`: the decider opens an ask, red twice on main first;11 * 4. `claim`: the answerer claims it, and gets a fork;12 * 5. `out-of-scope`: an answer that reaches outside the ask's territory is13 * refused, `OutOfScope` in git's own output;14 * 6. `answer`: the fixed answer is pushed and taken;15 * 7. `landing`: it lands on main, with the answerer as author, the platform16 * as committer, and the `Asked-by` and `Signed-off-by` trailers;17 * 8. `verdict-note`: its verdict note is on the answer's head in the fork.18 *19 * With `draft`, three more steps on the same project:20 *21 * 9. `draft-propose`: the answerer proposes a want with `--draft`;22 * 10. `draft-ready`: `proposal <id>` until the platform's agent has23 * drafted it, red first (a failed draft fails the step);24 * 11. `draft-accept`: the decider accepts it from Today, and the landing25 * that opened its ask discloses the drafter (`Assisted-by:`) and26 * credits the answerer as its asker.27 *28 * Each step is timed and printed as it passes; the first that fails ends29 * the run. Every throwaway is written to the throwaway ledger30 * (`infra/created.ts`, by `smoke`): the project and its repo before `init`31 * makes them, once the platform's list of projects shows the name free (a32 * taken name stops the run, recording nothing), so an `init` that fails33 * after making the project still leaves it recorded; the claim's fork just34 * after the claim, since its name is known only then. It never runs on35 * `demo`: a throwaway project would show on the front page the user36 * records.37 */1import { Brand } from "@repo/brand";2import { keyOf, ProjectName } from "@repo/protocol/ids";3import type { Handle, LandedSha } from "@repo/protocol/ids";4import {
30 unmodified lines
35import type { LoopStep, Patience } from "./core-loop.ts";3637export { LoopFailed, LoopStep } from "./core-loop.ts";3876/** `--loop` was pointed at demo, whose front page the user records. */39// A throwaway project would show on demo's front page.40export class DemoStageRefused extends Schema.TaggedError<DemoStageRefused>()(41 "DemoStageRefused",42 { stage: Schema.String }43) {
1 unmodified line
45 return `--loop makes a throwaway project, which would show on ${this.stage}'s front page: run it on a dev stage`;46 }47}4886/** How long one step took. */49export interface StepTiming {50 readonly step: LoopStep;51 readonly ms: number;52}5392/** A drafted ask the loop accepted: the model, its attempts, and its landing's trailers. */54export interface DraftReport {55 readonly model: string;56 readonly attempts: number;96 /** From the proposal to the draft settled, in ms. */57 // ms58 readonly ms: number;59 readonly trailers: readonly string[];60}61101/** A loop that passed: what each step found, and how long each took. */62export interface SmokeLoopReport {63 readonly project: ProjectName;104 /** The refusals git printed for the out-of-territory push: `OutOfScope` among them. */64 readonly refusedWith: readonly string[];106 /** main's commit after the landing. */65 readonly landed: LandedSha;66 readonly author: string;67 readonly committer: string;110 /** Every trailer of the landing commit, as git prints them. */68 readonly trailers: readonly string[];69 readonly noteFound: boolean;70 readonly timings: readonly StepTiming[];114 /** With `draft`, the drafted ask it accepted. */71 readonly draft?: DraftReport;72}73118/** What one loop runs on, and as whom. */74export interface LoopInput {120 /** The stage, which names the throwaways in the ledger; never `demo`. */75 readonly stage: string;122 /** This run's name: the project is `<decider>/smoke-<run>`. */76 readonly run: string;124 /** The platform: its `/rpc` and git live here. */77 readonly origin: string;126 /** Makes the project and opens the ask (on a stage, the operator). */78 readonly decider: Redacted.Redacted;128 /** Claims the ask and pushes the answer. */79 readonly answerer: Redacted.Redacted;130 /** How the loop waits for the landing: every 2 s, for up to 10 minutes, unless given. */80 readonly patience?: Patience;132 /** Also propose with a draft, wait for it, and accept it (`--draft`). */81 readonly draft?: boolean;82}8384const PATIENCE: Patience = {85 every: Duration.seconds(2),86 within: Duration.minutes(10),87};88141/** A step's run, timed and printed once it passes. */89const timed =90 (stage: string, step: LoopStep) =>91 <A, R>(92 self: Effect.Effect<A, LoopFailed, R>
8 unmodified lines
101 Console.log(`smoke ${stage}: loop ${step} passed in ${ms} ms`)102 )103 );104158/**159 * Writes one throwaway to the ledger, by smoke; a repo with its namespace160 * when the stage is one `infra/stages.ts` declares.161 */105const recordThrowaway = (stage: string, kind: Created["kind"], name: string) =>106 Effect.gen(function* () {107 const namespace = Option.map(108 declaredStage(stage),
22 unmodified lines
131 })132 )133 );134192/**193 * The throwaway project of run `run`, in the namespace of the decider who194 * makes it: `<decider>/smoke-<run>`.195 */135const projectOf = (decider: Handle, run: string) =>136 Schema.decodeEffect(ProjectName)(`${decider}/smoke-${run}`).pipe(137 Effect.mapError(138 () =>
3 unmodified lines
142 })143 )144 );145207/**208 * Runs the core loop on the platform at `input.origin`, as the people the209 * two tokens name, and gives what each step found; refused on `demo`210 * before anything runs.211 */146export const smokeLoop = (147 input: LoopInput148): Effect.Effect<149 SmokeLoopReport,
40 unmodified lines
190 );191192 const project = yield* projectOf(decider.handle, input.run);193260 // The name is checked free, then recorded, then made: an init that261 // makes the project and then fails still leaves it in the ledger, and262 // a name someone else holds never enters teardown's plan. The ledger263 // names what the platform keeps: the project's key, its Durable264 // Object's id and its repo's name.194 // Checked free, then recorded, then made: an init that makes the project195 // and then fails still leaves it in the ledger, and a name someone else196 // holds never enters teardown's plan.197 const [, init] = yield* timed(198 stage,199 "init"200 )(
165 unmodified lines
modified:scripts/lib/swarm/harnesses/amp.ts+3 added-12 removed
1/**2 * Amp, headless: execute mode (`-x`) with Claude Code-compatible stream JSON,3 * in an agent mode (`-m`, the contributor's "model"). Amp asks before it4 * runs a command unless its settings say `amp.dangerouslyAllowAll`, so the5 * workspace gets a settings file of its own (`--settings-file`; the6 * workspace's `XDG_CONFIG_HOME` hides the user's). A thread that execute7 * mode archives cannot be continued ("This thread is archived and cannot be8 * continued", found on the first resume), so every run passes9 * `--no-archive-after-execute`; `amp threads continue <id> -x` resumes it.10 */1// Amp asks before running a command unless its settings say `amp.dangerouslyAllowAll`,2// so the workspace gets a settings file of its own. An archived thread cannot be3// continued, so every run passes `--no-archive-after-execute`.4import { streamJsonEvents } from "./claude-code.ts";5import type { HarnessDriver } from "./event.ts";614/** The workspace's Amp settings: `<dir>/amp-settings.json`. */7export const ampSettingsFile = (dir: string) => `${dir}/amp-settings.json`;817/** The flags every run shares: stream JSON, the mode, the settings, and a thread kept open. */9const headless = (model: string, dir: string) => [10 "--stream-json",11 "-m",12 model,
30 unmodified lines
modified:scripts/lib/swarm/harnesses/claude-code.ts+6 added-25 removed
1/**2 * Claude Code, headless: `claude -p` with stream JSON, every tool allowed3 * (`--permission-mode bypassPermissions`: no one is there to approve), no4 * MCP server (`--strict-mcp-config` with no `--mcp-config`: else the user's5 * own servers and claude.ai connectors load, with the user's accounts6 * behind them), and `--resume <id>` to continue the same session. The7 * `system`/`init` line names the session; the `result` line closes the run8 * with its usage.9 *10 * Amp's `--stream-json` is "Claude Code-compatible", so `streamJsonEvents`11 * reads both.12 */1// `--strict-mcp-config` with no `--mcp-config`: else the machine's own MCP servers2// and claude.ai connectors load, with their accounts behind them. Amp's3// `--stream-json` is Claude Code-compatible, so `streamJsonEvents` reads both.4import { Option, Schema } from "effect";56import { HarnessEvent, lineAs, Tokens } from "./event.ts";7import type { HarnessDriver } from "./event.ts";818/** The `system`/`init` line: the session's id. */9const Init = Schema.Struct({10 session_id: Schema.NonEmptyString,11 subtype: Schema.Literal("init"),12 type: Schema.Literal("system"),13});1425/** A model response's usage, as Anthropic's API reports it. */15const ApiUsage = Schema.Struct({16 cache_creation_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),17 cache_read_input_tokens: Schema.optionalKey(Schema.NullOr(Tokens)),18 input_tokens: Tokens,19 output_tokens: Tokens,20});2133/** One assistant message, with its stop reason and usage (Amp prints usage here). */22const Assistant = Schema.Struct({23 message: Schema.Struct({24 stop_reason: Schema.optionalKey(Schema.NullOr(Schema.String)),25 usage: Schema.optionalKey(ApiUsage),26 }),27 type: Schema.Literal("assistant"),28});2942/** The `result` line: the run is over (`subtype` says how), with its usage (Claude Code). */30const Result = Schema.Struct({44 /** Whether the run failed; `subtype` then says how (`error_during_execution`). */31 is_error: Schema.optionalKey(Schema.Boolean),32 subtype: Schema.NonEmptyString,33 type: Schema.Literal("result"),34 usage: Schema.optionalKey(ApiUsage),
4 unmodified lines
39const assistantOf = lineAs(Assistant);4041const resultOf = lineAs(Result);4257/** Tokens in and out, counting cached input as input. */43// Cached input counts as input.44const usageOf = (45 usage: typeof ApiUsage.Type,46 stopReason: Option.Option<string>47) =>
5 unmodified lines
53 output: usage.output_tokens,54 stopReason,55 });5671/**72 * What one line of Claude Code-style stream JSON says. Usage is read where73 * the harness totals it: the `result` line (Claude Code, whose assistant74 * lines repeat what the result sums) or each assistant message (Amp, whose75 * result carries none).76 */57// Claude Code totals usage on the `result` line (its assistant lines repeat it);58// Amp reports it only on each assistant message.59export const streamJsonEvents =60 (usageFrom: "result" | "assistant") =>61 (line: string): readonly HarnessEvent[] => {62 const init = initOf(line);
25 unmodified lines
88 ],89 });90 };91110/** The flags every run shares: print mode, stream JSON, no one to ask, no MCP, the model. */92const headless = (model: string) => [93 "-p",94 "--output-format",95 "stream-json",
21 unmodified lines
modified:scripts/lib/swarm/harnesses/event.ts+3 added-39 removed
1/**2 * What every harness driver shares: the events a harness's output carries,3 * the driver's shape, and the helpers that read one JSON line. The drivers4 * (`claude-code.ts`, `opencode.ts`, `amp.ts`, `pi.ts`) import it, and5 * `index.ts` gathers them, so no module imports the one that imports it.6 */1// Apart from `index.ts`, so no driver imports the module that imports it.2import type { Option } from "effect";3import { Data, Schema } from "effect";45import type { Harness } from "../results.ts";6import type { AgentWorkspace } from "../workspace.ts";713/** What one line of a harness's output tells the swarm. */8export type HarnessEvent = Data.TaggedEnum<{15 /** The session the harness runs: the id a resume names. */9 SessionStarted: { readonly id: string };17 /**18 * Tokens one model response used (pi, OpenCode and Amp report each19 * response; Claude Code the whole run), counting cached input as input,20 * and why the response stopped when the harness says.21 */10 // Per response (pi, OpenCode, Amp) or per run (Claude Code); cached input counts as input.11 Usage: {12 readonly input: number;13 readonly output: number;14 readonly stopReason: Option.Option<string>;15 };27 /**28 * The session will do nothing more on its own (pi's `agent_settled`, the29 * `result` line of Claude Code and Amp, OpenCode's `error`), with why it30 * stopped when the line says.31 */16 Settled: { readonly stopReason: Option.Option<string> };33 /**34 * The run failed on the harness's side: a provider error or an abort, a35 * model the provider refused. A model response after it (`Usage`) means36 * the harness recovered (pi retries on its own).17 // A `Usage` after it means the harness recovered (pi retries on its own).37 */18 Failed: { readonly reason: string };19}>;2021export const HarnessEvent = Data.taggedEnum<HarnessEvent>();2243/** A file a harness reads, written into the workspace before its first start. */23export interface WorkspaceFile {24 readonly path: string;25 readonly content: string;26}2749/** How a harness is started on a contributor's brief. */28export interface StartInput {29 readonly workspace: AgentWorkspace;30 readonly brief: string;31 readonly model: string;54 /** Load the CLI's pi adapter (pi only). */32 readonly adapter: boolean;56 /** Where a harness that takes one keeps its sessions (pi). */33 readonly sessionDir: string;58 /** The session id a harness that takes one opens or creates (pi). */34 readonly sessionKey: string;35}3662/** How a harness's session is resumed with a new prompt. */37export interface ResumeInput {64 /** The id the session's first run gave (`SessionStarted`). */38 readonly session: string;39 readonly prompt: string;40 readonly model: string;41 readonly workspace: AgentWorkspace;69 /** Load the CLI's pi adapter again (pi only): a resume is a new process. */42 readonly adapter: boolean;43}4473/** One harness, driven headless. Every function is pure. */45export interface HarnessDriver {46 readonly harness: Harness;76 /** The argv that starts the harness on the brief, in the workspace's clone. */47 readonly start: (input: StartInput) => readonly string[];78 /** The argv that resumes the session with `prompt`. */48 readonly resume: (input: ResumeInput) => readonly string[];80 /** What one stdout line says; most lines say nothing the swarm reads. */49 readonly parse: (line: string) => readonly HarnessEvent[];82 /** Files the harness needs in the workspace before it starts (Amp's settings). */50 readonly files: (workspace: AgentWorkspace) => readonly WorkspaceFile[];51}5286/** Where a contributor's harness keeps its sessions: `<dir>/sessions`. */53export const sessionDirOf = (dir: string) => `${dir}/sessions`;5489/** One stdout line decoded as `schema`, or nothing when it is not that. */55export const lineAs =56 <A, I>(schema: Schema.Codec<A, I>) =>57 (line: string): Option.Option<A> =>58 Schema.decodeOption(Schema.fromJsonString(schema))(line);5995/** A token count as a harness prints it: a whole number, never negative. */60export const Tokens = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
modified:scripts/lib/swarm/harnesses/index.ts+4 added-15 removed
1/**2 * The four harnesses a swarm contributor runs, each driven headless: how to3 * start one on a brief, how to resume its session with a new prompt, and4 * what one line of its JSON output says. A harness's output gives only its5 * session's id, that the session settled, and the tokens it used; where the6 * answer stands comes from `<cli> status` (`../outcome.ts`), never from7 * what a harness printed.8 *9 * Every flag here was read from the installed harness's `--help` on10 * 2026-10-08 (Claude Code 2.1.293, OpenCode 2.0.7, Amp 0.0.1789750518, pi11 * 1.1.0), and each start and resume was run once headless against a12 * scratch clone; `packages/config/test/fixtures/swarm/harness-output/` holds13 * what they printed.14 */1// Each flag was read from the harness's `--help` (Claude Code 2.1.293, OpenCode 2.0.7,2// Amp 0.0.1789750518, pi 1.1.0); `packages/config/test/fixtures/swarm/harness-output/`3// holds what they printed. Where an answer stands comes from `<cli> status`, never4// from a harness's output.5import type { Harness } from "../results.ts";6import { amp } from "./amp.ts";7import { claudeCode } from "./claude-code.ts";8import type { HarnessDriver } from "./event.ts";
8 unmodified lines
17 StartInput,18 WorkspaceFile,19} from "./event.ts";2031/** Each harness's driver. */21export const drivers = {22 amp,23 "claude-code": claudeCode,24 opencode,
2 unmodified lines
modified:scripts/lib/swarm/harnesses/opencode.ts+3 added-15 removed
1/**2 * OpenCode, headless: `opencode run` with JSON events, permissions approved3 * (`--auto`), and `-s <id>` to continue a session. `--standalone` runs a4 * private server in the contributor's env instead of the user's background5 * service, so the agent's tools see the workspace's env and nobody else's.6 *7 * Every event names its session (`sessionID`); a `step_start` opens each8 * step, and a `step_finish` closes it with its tokens. The run's last step9 * prints no `step_finish` before the process exits (seen on 2.0.7), so the10 * run settles when the process exits; an `error` event settles it at once.11 */1// `--standalone` runs a private server in the contributor's env, not the machine's2// background service. The last step prints no `step_finish` before the process3// exits (seen on 2.0.7), so the run settles on exit; an `error` event settles it at once.4import { Option, Schema } from "effect";56import { HarnessEvent, lineAs, Tokens } from "./event.ts";7import type { HarnessDriver } from "./event.ts";817/** A step's first event: names the session. */9const StepStart = Schema.Struct({10 sessionID: Schema.NonEmptyString,11 type: Schema.Literal("step_start"),12});1323/** A step's last event: why it stopped, and its tokens. */14const StepFinish = Schema.Struct({15 part: Schema.Struct({16 reason: Schema.optionalKey(Schema.String),17 tokens: Schema.Struct({
5 unmodified lines
23 }),24 type: Schema.Literal("step_finish"),25});2637/** The run failed: the provider refused the model, say. */27const ErrorEvent = Schema.Struct({28 error: Schema.Struct({29 message: Schema.optionalKey(Schema.String),30 type: Schema.String,
42 unmodified lines
73 ],74 });75};7688/** The flags every run shares: a private server, JSON events, approvals, the model. */77const headless = (model: string) => [78 "run",79 "--standalone",80 "--format",
19 unmodified lines
modified:scripts/lib/swarm/harnesses/pi.ts+3 added-20 removed
1/**2 * pi, headless: print mode with JSON events (`-p --mode json`), sessions3 * kept in the workspace (`--session-dir`) under an id the swarm picks4 * (`--session-id`, which opens the session or creates it), so a resume is5 * the same command with a new prompt. pi asks no approvals, so it needs no6 * permission flag. `--no-mcp` keeps pi's built-in MCP off, so the user's7 * own servers (`~/.pi/agent/mcp.json`, with the user's accounts behind8 * them) never reach a contributor. The adapter's contributor loads the9 * CLI's pi adapter with `-e`, on the start and on every resume.10 *11 * The header line names the session; `agent_settled` says pi will not12 * continue on its own. JSON mode exits 0 when the provider fails, so the13 * stop reason comes from each assistant `message_end` (`stopReason`), never14 * from the exit code.15 */1// `--no-mcp` keeps the machine's own MCP servers away from a contributor. JSON mode2// exits 0 when the provider fails, so the stop reason comes from each3// `message_end`, never the exit code.4import { Option, Schema } from "effect";56import { HarnessEvent, lineAs, sessionDirOf, Tokens } from "./event.ts";7import type { HarnessDriver } from "./event.ts";821/** The CLI's pi adapter in this repo, loaded with `-e`. */9export const piAdapter = decodeURIComponent(10 new URL("../../../../apps/cli/src/pi.ts", import.meta.url).pathname11);1226/** The session header, JSON mode's first line. */13const Header = Schema.Struct({14 id: Schema.NonEmptyString,15 type: Schema.Literal("session"),16});1732/** An assistant message, finished: why it stopped, and its usage. */18const MessageEnd = Schema.Struct({19 message: Schema.Struct({35 /** Set when the response failed (`stopReason` `error` or `aborted`). */20 errorMessage: Schema.optionalKey(Schema.String),21 role: Schema.Literal("assistant"),22 stopReason: Schema.optionalKey(Schema.String),23 usage: Schema.optionalKey(
54 unmodified lines
78 ? [HarnessEvent.Settled({ stopReason: Option.none() })]79 : [];80};8198/** The flags every run shares: print mode, JSON events, no MCP, the session, the model, the adapter. */82const headless = (input: {83 readonly sessionDir: string;84 readonly session: string;85 readonly model: string;
35 unmodified lines
modified:scripts/lib/swarm/views/counter.ts+6 added-52 removed
1/**2 * The herdr view's counter: claims, pushes and landings in the swarm's3 * project as they happen, for the video's live tally (beat4 * 2:15–3:45). It follows the project's public `watch`, so it counts what5 * the platform recorded, never what a pane printed.6 *7 * `watch` streams over the platform's framed `/rpc` (NDJSON).8 * The swarm's scripts reach the network only through processes (their9 * allow-list grants `effect/process`), so `curl` carries the call, as the10 * swarm's other steps run git, the CLI and herdr. A run counts from the last11 * event the project already holds (`lastHeld`), appends one line to the12 * counter file per claim, push and landing, and follows again from the13 * last event it heard whenever the stream ends (a held stream does end:14 * Bun's `fetch` at 361 s).15 */1// The scripts reach the network only through processes (their allow-list grants2// `effect/process`), so `curl` carries the call. A held stream does end (Bun's3// `fetch` at 361 s), so the counter follows again from the last event it heard.4import { ProjectEvent } from "@repo/protocol/domain/event";5import type { ProjectName } from "@repo/protocol/ids";6import {7 Array,
10 unmodified lines
18import { ChildProcess, ChildProcessSpawner } from "effect/process";1920import { run, SwarmFailed } from "../workspace.ts";2134/** The events the counter counts. */22const counted = (event: ProjectEvent) =>23 ProjectEvent.guards.Claimed(event) ||24 ProjectEvent.guards.Pushed(event) ||25 ProjectEvent.guards.Landed(event);2640/** The counter's line for `events`: `claims 6 · pushes 9 · landed 4`. Pure. */27export const counterLine = (events: readonly ProjectEvent[]): string => {28 const claims = events.filter(ProjectEvent.guards.Claimed).length;29 const pushes = events.filter(ProjectEvent.guards.Pushed).length;30 const landings = events.filter(ProjectEvent.guards.Landed).length;
2 unmodified lines
33};3435const short = (sha: string) => sha.slice(0, 7);3651/** What one counted event says, in a few words; the others say nothing. */37const happening = (event: ProjectEvent) =>38 ProjectEvent.match(event, {39 AskClosed: () => "",40 AskOpened: () => "",
10 unmodified lines
51 Released: () => "",52 Warned: () => "",53 });5470/**71 * The counter file's line for `event`, the last of `events`: when it72 * happened (UTC), the tally so far, and what happened. Pure.73 */55export const counterEntry = (56 events: readonly ProjectEvent[],57 event: ProjectEvent58) =>59 `${DateTime.formatIso(event.at).slice(11, 19)} ${counterLine(events)} ${happening(event)}`;6080/** One call as effect/rpc's protocol frames it (as `infra/smoke.ts` sends one). */61const WatchCall = Schema.TaggedStruct("Request", {62 headers: Schema.Array(Schema.Tuple([Schema.String, Schema.String])),63 id: Schema.String,64 payload: Schema.Struct({
4 unmodified lines
69});7071const encodeCall = Schema.encodeSync(Schema.fromJsonString(WatchCall));7293/** `watch` for `project`, after event `since` when given one, as JSON. */73const watchRequest = (project: ProjectName, since: Option.Option<number>) =>74 encodeCall(75 WatchCall.make({76 headers: [],
5 unmodified lines
82 tag: "watch",83 })84 );85107/** A frame of a stream's values, as the platform's `/rpc` sends one. */86const ChunkOf = <S extends Schema.Top>(value: S) =>87 Schema.TaggedStruct("Chunk", { values: Schema.Array(value) });88111/** A frame of events, read only for where each stands in the project's sequence. */89const Held = ChunkOf(Schema.Struct({ seq: Schema.Int }));9091const isHeld = Schema.is(Held);92116/** What `watch` answers over plain JSON: every frame at once (any other is its exit). */93const decodeReplay = Schema.decodeUnknownOption(94 Schema.fromJsonString(95 Schema.Array(Schema.Union([Held, Schema.Struct({ _tag: Schema.String })]))96 )97);98123/** One line of the framed stream, when it is a frame of values. */99const decodeLine = Schema.decodeUnknownOption(100 Schema.fromJsonString(ChunkOf(Schema.Unknown))101);102103const eventOf = Schema.decodeUnknownOption(ProjectEvent);104130/**131 * The events one line of the stream carries. A line that is no chunk (the132 * stream's exit) carries none, and an event this build cannot read is133 * skipped.134 */105export const eventsIn = (line: string): readonly ProjectEvent[] =>106 Option.match(decodeLine(line), {107 onNone: () => [],108 onSome: ({ values }) =>109 Array.getSomes(values.map((value) => eventOf(value))),110 });111142/**143 * `curl`'s flags for one POST to the platform's `/rpc` with `contentType`:144 * an HTTP error fails it (`--fail`), and only its errors reach stderr.145 */112const curlArgs = (input: {113 readonly origin: string;114 readonly contentType: string;115 readonly body: string;
10 unmodified lines
126 input.body,127 `${input.origin}/rpc`,128];129164/** Why the counter can't say where `project` stands: what curl or the platform said. */130const unread = (project: ProjectName, said: string) =>131 new SwarmFailed({132 reason: `the counter couldn't read ${project}'s events: ${said.trim().slice(0, 300)}`,133 });134170/**171 * The last event `project` already holds, where a run's counter starts:172 * `watch` over plain JSON replays what the project keeps and ends; 0 when173 * it holds none. A read that fails is the run's failure, not 0: a counter174 * that started from 0 would count the project's whole history as the run's.175 */135// A read that fails is the run's failure, not 0: a counter that started from 0136// would count the project's whole history as the run's.137export const lastHeld = (origin: string, project: ProjectName) =>138 Effect.gen(function* () {139 const ran = yield* run({140 args: curlArgs({
20 unmodified lines
161 )162 );163 });164204/** Where the counter stands: the last event heard, and every counted one since the run began. */165interface Tally {166 readonly last: number;167 readonly events: readonly ProjectEvent[];168}169210/** How long the counter waits before it follows `watch` again. */170const FOLLOW_AGAIN = Duration.seconds(2);171213/**214 * Follows `project`'s `watch` at `origin` after event `from` (`lastHeld`,215 * read before the run claims anything), appending a line to `file` for216 * every claim, push and landing; it never ends on its own (interrupt it217 * when the run is over).218 */172// Never ends on its own: interrupt it when the run is over.173export const followCounter = (input: {174 readonly origin: string;175 readonly project: ProjectName;176 readonly file: string;
89 unmodified lines
modified:scripts/lib/swarm/views/headless.ts+1 added-38 removed
1/**2 * Where a contributor's harness runs, and how a prompt reaches it: the3 * swarm's views. A view runs one attempt of a session, its start on the4 * brief or a turn that resumes it, and says what it heard; the verdict loop5 * (`../loop.ts`) decides everything else, from `<cli> status` alone.6 *7 * This file holds the contract every view keeps (`SwarmView`) and the8 * default, headless view: the harness's own process, started with its9 * driver's argv (`../harnesses/`), its stdout read for the session's id,10 * that it settled, and the tokens it used. `herdr.ts` is the other view.11 */1import {2 Data,3 Duration,4 Effect,
9 unmodified lines
14import type { Contributor } from "../roster.ts";15import { scrubbed, SwarmFailed } from "../workspace.ts";16import type { AgentWorkspace } from "../workspace.ts";1729/** One attempt of a contributor's session: its start, or a turn that resumes it. */18export type Turn = Data.TaggedEnum<{31 /** The session's first run, on the brief. */19 Start: { readonly brief: string };33 /** The session `session` (what an earlier attempt heard) goes on with `prompt`. */20 Resume: { readonly session: string; readonly prompt: string };21}>;2223export const Turn = Data.taggedEnum<Turn>();2439/** What one attempt said about its session. */25export interface Heard {41 /** The id a resume names: the harness's session, or the view's own name for it. */26 readonly session: Option.Option<string>;27 readonly settled: boolean;28 readonly stopReason: Option.Option<string>;45 /** Why the run failed on the harness's side, unless a response came after. */29 readonly failure: Option.Option<string>;30 readonly input: number;31 readonly output: number;32}
6 unmodified lines
39 settled: false,40 stopReason: Option.none(),41};4260/** What one attempt heard, and how it ended. */43export interface Attempted {62 /** The exit code, unless the process was still running when it was let go. */44 readonly code: Option.Option<number>;45 readonly heard: Heard;65 /** The end of what it said on stderr, scrubbed of the token. */46 readonly stderr: string;47}4869/** One attempt, as the loop hands it to a view. */49export interface ViewAttempt {50 readonly contributor: Contributor;51 readonly workspace: AgentWorkspace;73 /** The env the harness runs in: the swarm's non-secret names, then the workspace's. */52 readonly env: Readonly<Record<string, string>>;75 /** Where the attempt's output is kept, scrubbed of the token. */53 readonly file: string;54 readonly turn: Turn;78 /** Runs once the attempt has a session: the attempt counts from then. */55 readonly onSession: Effect.Effect<void>;56}5782/** Where a contributor's harness runs, and how each prompt reaches it. */58export interface SwarmView {59 readonly attempt: (60 input: ViewAttempt61 ) => Effect.Effect<
20 unmodified lines
82 stopReason: Option.orElse(stopReason, () => heard.stopReason),83 }),84 });85111/** How long a settled harness gets to exit on its own before it is killed. */86const EXIT_GRACE = Duration.seconds(10);87114/** How long a killed harness gets before `SIGKILL`. */88const KILL_GRACE = Duration.seconds(5);89117/** The last characters of a harness's stderr kept, to say why it failed. */90const STDERR_TAIL = 2000;91120/**121 * One harness process: `argv` in the clone with `env`. Every stdout line122 * goes to `file`, scrubbed of the token, and is read for events until the123 * session settles or the output ends. A settled harness gets `EXIT_GRACE`124 * to exit; then it is killed with its process group.92// A settled harness gets `EXIT_GRACE` to exit; then it is killed with its process group.125 */93const attempt = (input: {94 readonly argv: readonly string[];95 readonly driver: HarnessDriver;96 readonly env: Readonly<Record<string, string>>;
67 unmodified lines
164 })165 )166 );167201/**202 * The swarm's default view: each attempt is the harness's own process,203 * headless, started (or resumed) with its driver's argv in the clone.204 */168export const headlessView: SwarmView = {169 attempt: ({ contributor, env, file, onSession, turn, workspace }) => {170 const { adapter, handle, harness, model } = contributor;171 const driver = drivers[harness];
18 unmodified lines
modified:scripts/lib/swarm/views/herdr.ts+12 added-125 removed
1/**2 * The herdr view (`--view herdr`): for the video, each3 * contributor's harness runs interactively in a herdr pane of its own, six4 * tiled over a counter strip, and every prompt (the brief, each refusal,5 * the nudge) is typed into that pane's session through herdr's CLI. The6 * verdict loop is the headless one: outcomes still come only from the7 * contributor's `<cli> status --json`, never from pane text.8 *9 * herdr is driven as a process (`herdr …`, read from `herdr --help` and10 * `herdr agent --help` on herdr 0.9.3), never through an SDK. It runs in the11 * herdr session the swarm itself runs in (`herdr --session demo`), so the12 * panes open where the person recording is looking. Pane text is read for13 * one thing only: to recognise a question a harness asks at startup, before14 * it takes its brief (`STARTUP_QUESTIONS`). Where an answer stands comes15 * from status alone.16 *17 * Unlike a headless harness, an agent in a pane outlives its run: a run that18 * times out (or a swarm that is stopped) leaves it working in its pane,19 * claim and all, until the person closes the workspace the swarm names20 * (`herdr workspace close <id>`).2 * Outcomes come only from `<cli> status --json`; pane text is read only to3 * answer a harness's startup questions. An agent in a pane outlives its run4 * until its herdr workspace is closed.5 */6import type { ProjectName } from "@repo/protocol/ids";7import {8 Config,
18 unmodified lines
27import { followCounter, lastHeld } from "./counter.ts";28import { nothingHeard, Turn } from "./headless.ts";29import type { Attempted, SwarmView } from "./headless.ts";3047/** The counter's pane, below the contributors'. */31export const COUNTER = "counter";3250/**51 * One pane the layout makes: the pane `from` (already made) is split toward52 * `direction`, keeping `ratio` of its space, and the new pane is `slot`.53 */33export interface Split {34 readonly slot: string;35 readonly from: string;36 readonly direction: "right" | "down";37 readonly ratio: number;38}3961/** The share of the window the contributors keep above the counter strip. */40const ABOVE_COUNTER = 0.85;4164/** `ratio` to three places, as herdr reads it. */42const share = (ratio: number) => Math.round(ratio * 1000) / 1000;4367/**68 * The panes for `handles`, as splits of the first one's pane (the69 * workspace's own): a counter strip along the bottom, then up to three70 * contributors to a row, two rows at most, each split keeping the share71 * that leaves every pane of a row the same width. Pure.72 */44export const herdrLayout = (handles: readonly string[]): readonly Split[] => {45 const [first] = handles;4647 if (first === undefined) {
33 unmodified lines
8182 return [counter, ...secondRow, ...columns];83};84114/** How long herdr waits for a harness to be ready for input when it starts one. */85const START_TIMEOUT_MS = 120_000;86117/** `herdr agent start …`: the harness `kind`, named `handle`, in `pane`, with its own flags after `--`. Pure. */87export const herdrStart = (input: {88 readonly handle: string;89 readonly kind: string;90 readonly pane: string;
11 unmodified lines
102 "--",103 ...input.argv,104];105137/**138 * `herdr agent prompt …`: `text` typed into the agent's session, then a139 * wait until it settles. `--wait` alone matches `idle`, `done` and140 * `blocked`: a turn that ends `idle` (seen on Claude Code) would never141 * match `--until done --until blocked`. Pure.142 */106// `--wait` alone also matches `idle`, which a turn can end in; `--until done --until blocked` would hang.107export const herdrPrompt = (input: {108 readonly handle: string;109 readonly text: string;110}): readonly string[] => [
3 unmodified lines
114 input.text,115 "--wait",116];117154/**155 * What only a headless run needs, per harness: the switches and the flags156 * (with their values) the driver's start passes for print mode and JSON157 * output, or for a prompt given on the command line. An interactive158 * session gets its prompt from herdr instead.159 */118const HEADLESS_ONLY = {119 amp: {120 switches: ["--stream-json", "--no-archive-after-execute"],121 valued: ["-x"],
8 unmodified lines
130 { readonly switches: readonly string[]; readonly valued: readonly string[] }131 >132>;133176/** Stands for the brief in a driver's argv, so the brief can be taken out. */134// Marks the brief in a driver's argv so it can be taken out.135const BRIEF = "\u0000brief";136179/** How a harness starts interactively: herdr's kind, its flags, and env it needs. */137export interface Launch {138 readonly kind: string;139 readonly argv: readonly string[];140 readonly env: Readonly<Record<string, string>>;141}142143/**187 * How `contributor`'s harness starts interactively in a pane: herdr's kind188 * (the harness's executable, which herdr knows by the same name), and the189 * driver's own start flags less `HEADLESS_ONLY` and the brief, so the190 * settings that keep a contributor's session safe (every tool allowed, no191 * MCP server of the user's, the workspace's sessions) are the headless192 * run's. OpenCode's interface takes its model from inline config in the193 * env. Pure.144 * Reuses the headless driver's start flags (less `HEADLESS_ONLY` and the145 * brief), so the settings that keep a session safe are the same.146 */147export const interactiveLaunch = (input: {148 readonly contributor: Contributor;149 readonly dir: string;
35 unmodified lines
185 kind,186 };187};188237/** herdr refused a command: its error's code, and what it said. */189class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {190 code: Schema.String,191 said: Schema.String,192 verb: Schema.String,
4 unmodified lines
197}198199const isRefused = Schema.is(HerdrRefused);200250/** What herdr prints on stderr when it refuses a command. */201const decodeRefusal = Schema.decodeUnknownOption(202 Schema.fromJsonString(203 Schema.Struct({204 error: Schema.Struct({ code: Schema.String, message: Schema.String }),205 })206 )207);208259/**260 * `herdr …` with the swarm's env, in the herdr session the swarm runs in:261 * what it printed, or `HerdrRefused` with herdr's own error code.262 */209const herdr = (args: readonly string[]) =>210 Effect.flatMap(run({ args, command: "herdr", env: {} }), (ran) => {211 if (ran.code === 0) {212 return Effect.succeed(ran.stdout);
14 unmodified lines
227 })228 );229 });230285/** Ends a step on herdr's refusal, saying which. */231const orFailed = <A, R>(232 effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>233): Effect.Effect<A, SwarmFailed, R> =>234 effect.pipe(
1 unmodified line
236 Effect.fail(new SwarmFailed({ reason: message }))237 )238 );239295/** `printed` decoded as `schema`, or why herdr's answer was not what the step needs. */240const answerOf =241 <A, I>(schema: Schema.Codec<A, I>, what: string) =>242 (printed: string) =>243 Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(
6 unmodified lines
250 );251252const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });253310/** `workspace create`: the workspace, and its first pane. */254const WorkspaceMade = Schema.Struct({255 result: Schema.Struct({256 root_pane: PaneId,257 workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),258 }),259});260318/** `pane split`: the new pane. */261const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });262321/** An agent as herdr sees it: `idle`, `working`, `blocked`, `done` or `unknown`. */263const AgentSeen = Schema.Struct({264 result: Schema.Struct({265 agent: Schema.Struct({266 agent_status: Schema.String,
1 unmodified line
268 }),269 }),270});271331/** A question a harness asks before it takes a prompt, and the keys that answer it as the swarm decides. */272interface StartupQuestion {333 /** Words only that question shows, in herdr's detection text. */273 readonly asks: string;274 readonly keys: readonly string[];275}276277/**339 * The questions each harness asks when it starts in a new folder (seen on340 * Claude Code 2.1.293 and 2.1.294; OpenCode 2.0.7, Amp 0.0.1789750518 and341 * pi 1.1.0 asked none):342 *343 * - Claude Code asks whether to trust the folder, "No, exit" first: the344 * clone is the swarm's own, so it answers yes;345 * - then whether to import the CLAUDE.md files above the clone (a346 * checkout's, when a test or a person puts the swarm's folder in one),347 * "No" first: it keeps the default, since they are not the contributor's348 * project.349 *350 * Any other question is left for the person at the panes.278 * Claude Code trusts the clone (it is the swarm's own) and declines CLAUDE.md279 * files above it. Any other question is left for the person at the panes.280 */281const STARTUP_QUESTIONS = {282 amp: [],283 "claude-code": [
3 unmodified lines
287 opencode: [],288 pi: [],289} as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;290362/** How long a harness gets to be ready for its brief once herdr says it is blocked at startup. */291const STARTUP_WAIT = Duration.minutes(3);292365/** Whether herdr sees the agent ready for a prompt. */293const readyIn = (printed: string) =>294 Effect.map(295 answerOf(AgentSeen, "agent get")(printed),296 ({ result: { agent } }) =>297 agent.interactive_ready === true &&298 (agent.agent_status === "idle" || agent.agent_status === "done")299 );300374/**375 * A harness blocked at startup: each question it is known to ask is376 * answered once, as `STARTUP_QUESTIONS` says, until herdr sees it ready.377 * A question the table doesn't know waits for the person at the panes,378 * until `STARTUP_WAIT` ends the run.379 */301const pastStartup = (input: {302 readonly handle: string;303 readonly harness: Harness;304 readonly pane: string;
47 unmodified lines
352 )353 );354 });355435/** Names whose values the pane keeps from its own terminal, not the swarm's. */356const PANE_OWNS = ["TERM", "COLORTERM"];357438/** herdr's names in a pane: its integrations report each agent's state with them. */358const HERDR_NAMES = [359 "HERDR_BIN_PATH",360 "HERDR_ENV",361 "HERDR_PANE_ID",
2 unmodified lines
364 "HERDR_WORKSPACE_ID",365];366367/**449 * The script a contributor's pane runs once: it clears the pane's env to450 * its terminal and herdr's own names, reads the harness's env from the451 * swarm through `fifo` (a pipe, so no token is ever in a file, an argv or452 * on the screen), and leaves a shell without rc files (no user setup453 * between the contributor and their env) in their clone, where herdr454 * starts their harness. Pure.368 * The env arrives through a pipe, so no token is ever in a file, an argv or369 * on screen; the shell skips rc files so no user setup sits in between.370 */371export const paneShell = (input: {372 readonly fifo: string;373 readonly clone: string;
14 unmodified lines
388 `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,389 "",390 ].join("\n");391477/** `env` as the lines a shell sources, less what the pane owns. Pure. */392const envLines = (env: Readonly<Record<string, string>>) =>393 Object.entries(env)394 .filter(([name]) => !PANE_OWNS.includes(name))395 .map(([name, value]) => `${name}=${shellQuoted(value)}\n`)396 .join("");397484/** How long a pane gets to read its env from the pipe. */398const ENV_READ_WAIT = Duration.seconds(30);399487/** How many times a pane whose shell is still starting is asked again, a second apart. */400const BUSY_RETRIES = 10;401490/** A pane script runs only as its owner. */402const SCRIPT_MODE = 0o700;403493/**494 * Readies `pane` for `contributor` and starts their harness in it: the495 * pane runs `paneShell`, reads `env` (with the launch's own) from a pipe,496 * and herdr starts the harness with its interactive flags, getting past497 * the startup questions it knows. herdr's answer goes to `log`.498 */404const startIn = (input: {405 readonly contributor: Contributor;406 readonly env: Readonly<Record<string, string>>;407 readonly pane: string;
81 unmodified lines
489490 return yield* input.log(started);491 });492588/** What an attempt heard from herdr's answer to its prompt (or its refusal of it). */493const promptHeard = (input: {494 readonly name: string;495 readonly pane: string;496 readonly harness: Harness;
34 unmodified lines
531 }532 ),533 });534631/**632 * The herdr view over `panes` (each contributor's pane, by handle): an633 * attempt starts the harness in its pane on the brief, or types the634 * continuation's prompt into the same session, and waits until herdr sees635 * it settle. The session a resume names is the agent's herdr name.636 */535export const herdrView = (panes: ReadonlyMap<string, string>): SwarmView => ({536 attempt: ({ contributor, env, file, onSession, turn, workspace }) =>537 Effect.gen(function* () {538 const fs = yield* FileSystem.FileSystem;
52 unmodified lines
591 return yield* promptHeard({ answer, harness, name, pane });592 }),593});594697/** A pane's title: who works in it, and on which harness. */595const titleOf = ({596 handle,597 harness,598}: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;599703/**704 * Opens the herdr view for `contributors`, in the herdr session the swarm705 * runs in: a workspace of its own (focused, for the person recording), one706 * pane per contributor laid out by `herdrLayout`, and a counter pane that707 * shows `counterFile`, which a fiber in the run's scope keeps writing from708 * the project's `watch`. Outside a herdr pane it refuses: herdr's skill709 * says not to drive a session from outside it. It refuses too when it can't710 * read where the project stands (`lastHeld`), before any pane is made.711 */600// Refuses outside a herdr pane: herdr says not to drive a session from outside it.601export const openHerdrView = (input: {602 readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];603 readonly project: ProjectName;604 readonly origin: string;
25 unmodified lines
630 "--view herdr opens its panes in the herdr session it runs in: start the swarm from a herdr pane (herdr --session demo), or name the session's socket in HERDR_SOCKET_PATH",631 });632 }633745 // Where the counter starts, read before any pane or claim: a run that746 // can't say where the project stands stops here.634 const from = yield* lastHeld(input.origin, input.project);635 const root = (yield* repoRoot).replace(/\/$/u, "");636 const counterFile = `${input.runDir}/counter.log`;637 const handles = input.contributors.map(({ handle }) => handle);
95 unmodified lines
modified:scripts/lib/swarm/args.ts+2 added-19 removed
1/**2 * The swarm's flags, read by a small decoder (the scripts' allow-list grants3 * `effect/process` only, so no `effect/cli`):2 * A small hand decoder: the scripts' allow-list grants `effect/process` only, so no `effect/cli`.3 *4 * --stage <s> required: a stage `infra/stages.ts` declares5 * --project <name> default oscabriel/burrow6 * --scenario plain|video default plain7 * --dry-run print the plan; claim nothing, start nothing8 * --json print JSON: the plan (dry run) or the run's summary10 * --allow-demo required with --stage demo: its burrow family is the recorded take's9 * --allow-demo required with --stage demo10 * --only <handle>… run only these contributors (repeat, or comma-separate)11 * --timeout-min <n> each agent's run timeout, default 2012 * --view headless|herdr default headless; herdr runs each harness in a herdr pane13 * --url <origin> the platform, when not the stage's workers.dev origin
6 unmodified lines
20import { roster } from "./roster.ts";21import { ScenarioName } from "./scenario.ts";22import { SwarmFailed } from "./workspace.ts";2325/** What `bun scripts/swarm.ts` was asked to do. */24export interface SwarmOptions {25 readonly stage: Stage;26 readonly project: ProjectName;27 readonly scenario: ScenarioName;28 readonly dryRun: boolean;29 readonly json: boolean;32 /** The contributors to run; every one when `--only` names none. */30 readonly only: readonly Handle[];31 readonly timeoutMin: number;35 /** Where the harnesses run: their own processes, or herdr's panes (`views/`). */32 readonly view: ViewName;37 /** The platform's origin, when `--url` names it. */33 readonly url: Option.Option<string>;34}3536export const USAGE =37 "bun scripts/swarm.ts --stage <dev-…|demo> [--project oscabriel/burrow] [--scenario plain|video] [--dry-run] [--json] [--allow-demo] [--only <handle>…] [--timeout-min 20] [--view headless|herdr] [--url <origin>]";3844/** The views a run can take. */39export const ViewName = Schema.Literals(["headless", "herdr"]);4041export type ViewName = typeof ViewName.Type;4243const decodeView = Schema.decodeUnknownOption(ViewName);4451/** The flags that take a value. */45const VALUED = [46 "--project",47 "--scenario",48 "--stage",
1 unmodified line
50 "--url",51 "--view",52] as const;5361/** The flags that stand alone. */54const SWITCHES = ["--allow-demo", "--dry-run", "--json"] as const;5556const failed = (reason: string) => new SwarmFailed({ reason });5766/** The handles `--only` names: each value after each `--only`, comma-separated or not. */58const onlyOf = (argv: readonly string[]) =>59 argv.flatMap((arg, at) => {60 if (arg.startsWith("--only=")) {61 return arg.slice("--only=".length).split(",");
10 unmodified lines
72 value.split(",")73 );74 });7585/** The arguments that are flags, with any `=value` cut off. */76const flagsIn = (argv: readonly string[]) =>77 argv.flatMap((arg) =>78 arg.startsWith("--") ? [arg.split("=")[0] ?? arg] : []79 );8081const isValued = (flag: string): flag is (typeof VALUED)[number] =>82 VALUED.some((valued) => valued === flag);8394/**95 * The words no flag takes: each valued flag takes the word after it (unless96 * it wrote `=value`), and `--only` every word up to the next flag.97 */84const straysIn = (argv: readonly string[]) => {85 const strays: string[] = [];86 let takes: "none" | "one" | "many" = "none";87
15 unmodified lines
103104 return strays;105};106121/** `raw` as the platform's origin, without a trailing `/`, if it is an http(s) URL. */107const originOf = (raw: string) =>108 Option.filter(109 Option.liftThrowable((url: string) => new URL(url))(raw),110 ({ protocol }) => protocol === "https:" || protocol === "http:"
2 unmodified lines
113const decodeProject = Schema.decodeUnknownOption(ProjectName);114115const decodeScenario = Schema.decodeUnknownOption(ScenarioName);116132/** The swarm's options from its arguments, or why they don't make a run. */117export const optionsOf = (118 argv: readonly string[]119): Effect.Effect<SwarmOptions, SwarmFailed> =>120 Effect.gen(function* () {
31 unmodified lines
152 `unexpected argument ${strays.join(", ")}: ${USAGE}`153 );154 }155172 // infra's own reading of `--stage`, and its words when it names none.156 const stage = yield* stageOf(argv).pipe(157 Effect.mapError(({ message }) => failed(`${message}. ${USAGE}`))158 );159
92 unmodified lines
modified:scripts/lib/swarm/loop.ts+6 added-88 removed
1/**2 * The verdict loop: one contributor's harness, started headless on the brief3 * in their workspace, and every refusal their answer meets sent back into4 * the same session, at most `maxContinuations` times.5 *6 * Each attempt runs the harness until its session settles (or the process7 * ends), its output kept in `<run>/<handle>/attempt-<n>.jsonl` with the8 * token blanked. Then `<cli> status` says where the answer stands9 * (`outcome.ts`), never the harness's output:10 *11 * - `Landed`: the contributor is done;12 * - `AwaitingFinish`, `AwaitingDecision`, `WaitingOnParent`: waiting on a13 * person or another ask, recorded as `waiting` (the swarm decides nothing);14 * - `Refused`: the refusals, rendered by protocol's `explain`, go back into15 * the same session with the first one's `next`, unless one of them ends16 * the claim (`endsClaim`) or the continuations ran out; refusals that are17 * all the platform's side (`VerifierBlocked`, `Flake`, `RepoBusy`) go back18 * as a wait: push the same work again, with nothing to fix;19 * - no new answer: one nudge to push (naming the last answer's head, when20 * one came), then `noAnswer` (or `refused`, when an earlier answer was21 * refused and nothing new came).22 *23 * The run's timeout bounds everything: a harness that never settles, or an24 * answer checked past it, ends the run as `timedOut`, and the harness's25 * process group is killed.26 *27 * Where the harness runs, and how a prompt reaches it, is the run's view28 * (`views/`): its own headless process by default, or a herdr pane29 * (`--view herdr`). The loop is the same in both.30 */1import { Brand } from "@repo/brand";2import type { AnswerView } from "@repo/protocol/domain/answer";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { ProjectName } from "@repo/protocol/ids";
24 unmodified lines
29import type { SwarmView } from "./views/headless.ts";30import { scrubbed, SwarmFailed } from "./workspace.ts";31import type { AgentWorkspace } from "./workspace.ts";3263/** One contributor's run: their harness on the brief, then the verdict loop. */33export type RunAgent = (input: {34 readonly assignment: Assignment;35 readonly workspace: AgentWorkspace;36 readonly brief: string;37 readonly maxContinuations: 3;38 readonly timeoutMs: number;70 /**71 * The ask's project, so `status` reads only it. Without one, `status`72 * lists every project's claims and answers and the ask is found by name.73 */39 readonly project?: ProjectName;75 /**76 * Where the harness runs and how each prompt reaches it: its own77 * headless process unless a view (herdr's panes) says otherwise.78 */40 readonly view?: SwarmView;41}) => Effect.Effect<42 AgentRun,43 never,44 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem45>;4686/**87 * The argv that starts `contributor`'s harness headless on `brief`, in their88 * workspace `dir`: the plan prints it, and `runAgent` runs the same one.89 */47export const startCommand = (input: {48 readonly contributor: Contributor;49 readonly brief: string;50 readonly dir: string;
15 unmodified lines
66 });67};6869/**113 * What a harness keeps of the swarm's own env: where the user's harness114 * sign-ins and caches live, the terminal and locale, and the network's115 * proxy and certificates. Nothing secret: the run's `SESSION_TOKENS`, cloud116 * tokens and any parent harness's session never reach a contributor's117 * harness, whose only credential is the person's token in the workspace's118 * env (a harness runs with the user's OS permissions).70 * Nothing secret: the run's `SESSION_TOKENS`, cloud tokens and any parent71 * harness's session never reach a contributor's harness.72 */73const KEPT_FROM_SWARM = [74 "HOME",75 "USER",
21 unmodified lines
97 "SSL_CERT_FILE",98 "NODE_EXTRA_CA_CERTS",99] as const;100148/** The env a contributor's harness runs in: `KEPT_FROM_SWARM`, then the workspace's. */101const harnessEnv = (workspace: AgentWorkspace) =>102 Effect.gen(function* () {103 const kept = yield* Effect.forEach(KEPT_FROM_SWARM, (name) =>104 Config.option(Config.String(name)).pipe(
7 unmodified lines
112 ...workspace.env,113 };114 });115164/** What the loop does once an attempt's answer is known. */116export type Next = Data.TaggedEnum<{166 /** Resume the session with this prompt. */117 Resume: { readonly prompt: string; readonly nudge: boolean };168 /** The run ends with this outcome. */118 Done: {119 readonly outcome: AgentOutcome;120 readonly landed: Option.Option<string>;121 };122}>;123124export const Next = Data.taggedEnum<Next>();125177/** Where the loop stands between attempts. */126export interface Progress {127 readonly attempts: number;128 readonly continuations: number;129 readonly nudged: boolean;182 /** The requests of answers already acted on: status shows them until a new one comes. */130 readonly judged: readonly string[];131 readonly refusals: Readonly<Record<string, number>>;132 readonly landed: Option.Option<string>;133}
6 unmodified lines
140 nudged: false,141 refusals: {},142};143197/** What the loop does next, and where it then stands. */144export interface Step {145 readonly next: Next;146 readonly progress: Progress;147}148203/** `prior` with each refusal's tag counted once more. */149const tally = (150 prior: Readonly<Record<string, number>>,151 refusals: readonly Refusal[]152) => {
7 unmodified lines
160};161162const short = (sha: string) => sha.slice(0, 7);163219/**220 * The refusals that are the platform's side, not the answer's: the checks221 * could not run, a lane flaked, the repo was busy. Each is retryable (the222 * same work may pass), and none names anything in the change to fix.223 */164// Retryable refusals that name nothing in the change to fix.165const platformSide: ReadonlySet<Refusal["_tag"]> = new Set([166 "Flake",167 "RepoBusy",168 "VerifierBlocked",169] as const satisfies readonly Refusal["_tag"][]);170230/**231 * The prompt that resumes a session after its answer was refused. When232 * every refusal is the platform's side, it says so, and asks for the same233 * work again rather than a fix: an empty commit, pushed.234 */171export const refusalPrompt = (input: {172 readonly answer: Pick<AnswerView, "ask" | "head">;173 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;174 readonly project: string;
19 unmodified lines
194 ...what,195 ].join("\n");196};197262/**263 * The prompt that resumes a session that pushed no new answer: none at all,264 * or none since the head of the last one status showed (`since`).265 */198export const nudgePrompt = (input: {199 readonly ask: string;200 readonly remote: string;201 readonly project: string;
10 unmodified lines
212 `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,213 ].join("\n");214215/**284 * What to do with what status says after an attempt: pure, over the285 * loop's progress. An answer status showed before (its request already286 * judged) is no new answer. The loop acts on the latest new answer, and287 * counts the refusals of every new one: an agent that read its verdict288 * and pushed again in the same session met each of them.216 * An answer already judged is no new answer. Refusals of every new answer are217 * counted, since an agent may push again within one session.218 */219export const afterSettle = (input: {220 readonly status: AskStatus;221 readonly progress: Progress;222 readonly maxContinuations: number;223 readonly ask: string;295 /** The ask's project, when the run was told it; else the claim's. */224 readonly project: Option.Option<string>;297 /**298 * Why the attempt's harness failed (a provider error, a nonzero exit), if299 * it did: with no new answer, a nudge cannot help, so the run failed.300 */225 /** With no new answer, a broken harness fails the run: a nudge cannot help. */226 readonly broke: Option.Option<string>;227}): Step => {228 const { maxContinuations, progress } = input;229
88 unmodified lines
318 WaitingOnParent: () => done("waiting", judged),319 });320};321397/** The tags of the refusals status shows for the ask's latest answer. */322const tagsOf = ({ answer }: AskStatus) =>323 Option.match(answer, {324 onNone: () => "",325 onSome: ({ outcome }) =>
1 unmodified line
327 ? outcome.refusals.map(({ _tag }) => _tag).join(", ")328 : "",329 });330407/** A count of tokens, in thousands when large. */331const tokens = (count: number) =>332 count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;333334export const runAgent: RunAgent = (input) =>
8 unmodified lines
343344 const say = (line: string) =>345 Console.error(scrubbed(`${handle}: ${line}`, workspace));346424 /**425 * One harness session (the start, or a continuation: `turn`), then what426 * status says; it calls itself for each continuation, until427 * `afterSettle` says the run is done.428 */347 const pass = (348 turn: Turn,349 env: Readonly<Record<string, string>>350 ): Effect.Effect<
134 unmodified lines
modified:scripts/lib/swarm/outcome.ts+3 added-41 removed
1/**2 * Where a contributor's answer stands, as the platform says it: their3 * `<cli> status --json`, run in their workspace as them, decoded with4 * protocol's `Envelope`. The verdict loop (`loop.ts`) reads outcomes only5 * here, never from what a harness printed.6 */1import { Brand } from "@repo/brand";2import { AnswerView } from "@repo/protocol/domain/answer";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Outcome } from "@repo/protocol/domain/outcome";
12 unmodified lines
1718import { run, scrubbed, SwarmFailed } from "./workspace.ts";19import type { AgentWorkspace } from "./workspace.ts";2027/** What the swarm reads of `status`: the caller's claims and answers. */21const StatusData = Schema.Struct({22 answers: Schema.Array(AnswerView),23 claims: Schema.Array(ClaimView),24});
1 unmodified line
26const decodeStatus = Schema.decodeEffect(27 Schema.fromJsonString(Envelope(StatusData))28);2937/** One ask, as the contributor's status shows it. */30export interface AskStatus {39 /** Their claim on the ask, while status lists it. */31 readonly claim: Option.Option<ClaimView>;41 /**42 * Every answer of theirs to the ask, oldest first: one session can push43 * several before it settles.44 */32 // Oldest first: one session can push several before it settles.33 readonly answers: readonly AnswerView[];46 /** Their latest answer to the ask: the last of `answers`. */34 readonly answer: Option.Option<AnswerView>;35}3650/** The CLI in the workspace's `bin/`: the shim the contributor's harness runs too. */37export const workspaceCli = (workspace: Pick<AgentWorkspace, "dir">) =>38 `${workspace.dir}/bin/${Brand.cli}`;3954/** `answers` oldest first, by `at`; of two at the same instant, the one listed first. */40const oldestFirst = (answers: readonly AnswerView[]) =>41 Array.sort(42 answers,43 Order.mapInput(Order.Number, ({ at }: AnswerView) => at.epochMilliseconds)44 );4561/** How one status read is asked: whose workspace, and which ask (in which project, when known). */46export interface StatusQuery {47 readonly workspace: AgentWorkspace;64 /** Without one, status lists every project's claims and answers. */48 readonly project: Option.Option<ProjectName>;49 readonly ask: AskId;50}5169/**70 * The contributor's claim on `ask` and their latest answer to it, from71 * `<cli> status [--project <p>] --json` run in their clone with their env.72 * A status that refuses, or prints no envelope, fails `SwarmFailed`, its73 * text scrubbed of the token.74 */52export const readStatus = (53 query: StatusQuery54): Effect.Effect<55 AskStatus,
45 unmodified lines
101 claim: Array.findLast(envelope.data.claims, (claim) => claim.ask === ask),102 };103 });104128/**129 * The contributor's latest answer to `ask`, with its head and outcome: the130 * outcome the verdict loop acts on.131 */105export const readOutcome = (106 query: StatusQuery107): Effect.Effect<108 Option.Option<{ readonly head: CommitSha; readonly outcome: Outcome }>,
3 unmodified lines
112 Effect.map(readStatus(query), ({ answer }) =>113 Option.map(answer, ({ head, outcome }) => ({ head, outcome }))114 );115143/** How often a run that is still being checked is asked again. */116export const POLL_MS = 5000;117146/**147 * How many times a status read that fails (the platform briefly down, a148 * request dropped) is asked again, `pollMs` apart, before the run fails:149 * one bad read in a run of hundreds should not end a contributor's run.118// One bad read in a run of hundreds should not end a contributor's run.150 */119export const STATUS_RETRIES = 5;120153/**154 * Reads the ask's status until its latest answer is no longer `Checking`:155 * landed, refused or waiting on someone, or no answer at all. It asks156 * every `pollMs`, asks again up to `STATUS_RETRIES` times when a read157 * fails, and never gives up on its own: the run's timeout (`loop.ts`)158 * bounds it.159 */121// Never gives up on its own: the run's timeout (`loop.ts`) bounds it.122export const awaitSettledOutcome = (123 query: StatusQuery & { readonly pollMs?: number }124): Effect.Effect<125 AskStatus,
13 unmodified lines
modified:scripts/lib/swarm/plan.ts+6 added-43 removed
1/**2 * The swarm's plan: which contributor answers which ask. It takes a3 * project's open asks as `listAsks` shows them, and hands each contributor,4 * in roster order, one open, unclaimed, unblocked ask, in `AskId` order, on5 * a territory no other assignment shares. Asks still blocked (a migrate6 * family's delete child, and its parent) are held.7 */1import type { AskListing } from "@repo/protocol/domain/ask";2import { AskId, ProjectName } from "@repo/protocol/ids";3import type { Refusal } from "@repo/protocol/refusal";4import { Array, Option, Order, Result, Schema } from "effect";56import { Contributor, roster } from "./roster.ts";7import { nudges, ScenarioName } from "./scenario.ts";816/** One contributor's ask, and the territory (module) it may change. */9export const Assignment = Schema.Struct({10 ask: AskId,11 contributor: Contributor,20 /**21 * What the run's scenario adds to this contributor's brief. The plan22 * carries it, so the table and `--json` both show it: staging is never23 * hidden.24 */12 // Carried by the plan so the table and `--json` both show it: staging is never hidden.13 nudge: Schema.optionalKey(Schema.NonEmptyString),14 territory: Schema.NonEmptyString,15});1617export type Assignment = typeof Assignment.Type;1831/** The plan for one run: its assignments, and the asks it holds back. */19export const SwarmPlan = Schema.Struct({20 assignments: Schema.Array(Assignment),34 /** Open asks still blocked by others: a migrate family's delete child, say. */21 held: Schema.Array(AskId),22 project: ProjectName,23 scenario: ScenarioName,24 stage: Schema.NonEmptyString,25});2627export type SwarmPlan = typeof SwarmPlan.Type;2843/** Fewer asks can be handed out than the roster has contributors. */29export class NotEnoughAsks extends Schema.TaggedError<NotEnoughAsks>()(30 "NotEnoughAsks",31 { open: Schema.Int, wanted: Schema.Int }32) {
1 unmodified line
34 return `${this.wanted} contributors, but only ${this.open} open, unclaimed, unblocked asks on disjoint territories`;35 }36}3753/**54 * The refusals that end a contributor's claim, so the verdict loop55 * stops on them. It bounces every other refusal back into the same session:56 * `retryable: true` means only that the same push may pass if sent again57 * (`StaleBase`, `RepoBusy`, `Flake`), while `OutOfScope`, `Weakened` and58 * `ChecksFailed` (`retryable: false`) are exactly what an agent fixes.59 */38// Every other refusal goes back into the same session: `retryable: true` means only39// that the same push may pass again, while `OutOfScope`, `Weakened` and40// `ChecksFailed` are exactly what an agent fixes.41export const endsClaim: ReadonlySet<Refusal["_tag"]> = new Set([42 "AskFull",43 "AttemptsExhausted",44 "ClaimLapsed",
1 unmodified line
46 "NotClaimed",47 "NotVouched",48] as const satisfies readonly Refusal["_tag"][]);4969/** The whole repo as a territory: it overlaps every other one. */50const WHOLE_REPO = ".";5172/**73 * Whether two asks' territories overlap: the same module, or either one74 * the whole repo. A listing names only the module, so two modules that are75 * not the same are taken as disjoint (each is one workspace package).76 */52// A listing names only the module, so two different modules are taken as disjoint.53const overlaps = (one: string, other: string) =>54 one === other || one === WHOLE_REPO || other === WHOLE_REPO;5580/**81 * The nudge `scenario` gives `contributor`, by their place in the whole82 * roster, so a contributor planned alone (`--only`) is told what the full83 * run would tell them.84 */56// By place in the whole roster, so a contributor planned alone (`--only`) gets the full run's nudge.57const nudgeFor = (scenario: ScenarioName, contributor: Contributor) =>58 Option.match(59 nudges(60 scenario,
4 unmodified lines
65 onSome: (nudge) => ({ nudge }),66 }67 );6897/**98 * Plans a run: each contributor in `roster`, in roster order, gets one open,99 * unclaimed and unblocked ask, taken in `AskId` order, whose territory100 * overlaps no ask already handed out, and the nudge the scenario gives them.101 * An ask is blocked while any ask it waits on is still listed (`listAsks`102 * lists every ask not closed); blocked asks are held. With fewer asks to103 * hand out than contributors, the plan fails `NotEnoughAsks`, counting the104 * asks it could hand out.105 */69export const planSwarm = (input: {70 readonly roster: readonly Contributor[];71 readonly asks: readonly AskListing[];72 readonly stage: string;
49 unmodified lines
modified:scripts/lib/swarm/prompt.ts+2 added-8 removed
1/**2 * The brief each contributor's harness starts with. It is zero-install: it3 * says only what a contributor gets from the ask's page and the project's4 * AGENTS.md (where their clone is, make the check pass, push, read the5 * verdict with `<cli> status`), and nothing about how the platform judges6 * an answer.7 */1// Zero-install: only what a contributor gets from the ask's page and the project's2// AGENTS.md, and nothing about how the platform judges an answer.3import { Brand } from "@repo/brand";4import type { AskId, ProjectName } from "@repo/protocol/ids";5import { Option } from "effect";612/** The brief for one contributor's ask: the ask's page between what to do. */7export const brief = (input: {8 readonly ask: AskId;9 readonly project: ProjectName;10 readonly remote: string;
26 unmodified lines
modified:scripts/lib/swarm/results.ts+1 added-39 removed
1/**2 * The swarm run's summary: one `AgentRun` per contributor, written to3 * `<swarm>/<run>/agents.json`, where `<swarm>` is `SwarmDir`, outside the4 * checkout. A live issue records what a run shows in its own notes; nothing5 * here is committed.6 *7 * Every field follows the wire rule (AGENTS.md "Effect traps"): `Schema.Int`8 * or `Schema.Finite` for numbers, `Schema.optionalKey` for optional keys.9 */1import { Brand } from "@repo/brand";2import { Context, Effect, FileSystem, Option, Schema } from "effect";3import type { PlatformError } from "effect";414/** What the swarm's folder is placed by: the env's state home, else the user's home. */5const StateEnv = Schema.Struct({6 HOME: Schema.optionalKey(Schema.NonEmptyString),7 XDG_STATE_HOME: Schema.optionalKey(Schema.NonEmptyString),8});920/**21 * The swarm's folder for `env`: `${XDG_STATE_HOME:-$HOME/.local/state}/22 * <slug>/swarm`, beside the hook's sessions, and never inside a checkout: a23 * harness reads every AGENTS.md and CLAUDE.md above its folder, so a24 * workspace inside this repo would hand each contributor the platform's own.25 * With neither variable set, the system's temp folder.26 */10// Never inside a checkout: a harness reads every AGENTS.md and CLAUDE.md above its folder.11export const swarmDirOf = (env: typeof StateEnv.Type) => {12 const home = env.HOME === undefined ? "/tmp" : `${env.HOME}/.local/state`;1314 return `${env.XDG_STATE_HOME ?? home}/${Brand.slug}/swarm`;15};1633/** The global scope, read only for its `process.env`. */17const GlobalScope = Schema.Struct({18 process: Schema.Struct({ env: StateEnv }),19});2038/**39 * The swarm's folder (`swarmDirOf` this process's env), unless a test points40 * it elsewhere. Each run writes below it: `<run>/agents.json` and one41 * workspace per contributor, `<run>/<handle>/`.42 */21export const SwarmDir = Context.Reference<string>("swarm/SwarmDir", {22 defaultValue: () => {23 // Unknown on purpose: the runtime is whatever started this process.24 const scope: unknown = globalThis;
6 unmodified lines
31 );32 },33});3457/** A run's own folder: `<swarm>/<run>`. */35export const runDir = (run: string) =>36 Effect.map(SwarmDir, (dir) => `${dir}/${run}`);3761/** The four harnesses a swarm contributor may run. */38export const Harness = Schema.Literals([39 "claude-code",40 "opencode",41 "amp",
1 unmodified line
43]);4445export type Harness = typeof Harness.Type;4671/**72 * How one contributor's run ended: its answer landed, was refused (and the73 * continuations ran out), waits on a person (`AwaitingFinish`,74 * `AwaitingDecision`), was never pushed, ran past its timeout, or the run75 * itself failed (a claim refused, a harness that did not start).76 */47export const AgentOutcome = Schema.Literals([48 "landed",49 "refused",50 "waiting",
3 unmodified lines
54]);5556export type AgentOutcome = typeof AgentOutcome.Type;5788/** One contributor's run. */58export const AgentRun = Schema.Struct({59 adapter: Schema.Boolean,60 ask: Schema.NonEmptyString,92 /** Harness sessions started or resumed: the first run and each continuation. */61 attempts: Schema.Int,62 durationMs: Schema.Int,63 handle: Schema.NonEmptyString,64 harness: Harness,97 /** The landing commit, when the answer landed. */65 landed: Schema.optionalKey(Schema.NonEmptyString),66 model: Schema.NonEmptyString,67 outcome: AgentOutcome,101 /** Each refusal's `_tag`, with how often it came back across the attempts. */68 refusals: Schema.Record(Schema.String, Schema.Int),69});7071export type AgentRun = typeof AgentRun.Type;72107/** A whole run: where it ran, from which commit, and each contributor's run. */73export const AgentsResult = Schema.Struct({74 at: Schema.DateTimeUtcFromString,110 /** The commit of this repo the swarm ran from. */75 commit: Schema.NonEmptyString,76 project: Schema.NonEmptyString,77 runs: Schema.Array(AgentRun),78 scenario: Schema.NonEmptyString,
2 unmodified lines
81});8283export type AgentsResult = typeof AgentsResult.Type;84121/** The file a run's summary is written to, below the swarm's folder. */85export const agentsFile = (dir: string) => `${dir}/agents.json`;86124/** Writes `result` to `<swarm>/<run>/agents.json`, as indented JSON. */87export const writeAgentsResult = (input: {88 readonly run: string;89 readonly result: AgentsResult;90}): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> =>
15 unmodified lines
modified:scripts/lib/swarm/roster.ts+2 added-29 removed
1/**2 * The swarm's six fictional contributors: "4 harnesses, 6 models". Each is3 * one person (a `SESSION_TOKENS` entry on the stage, a named session beside4 * accounts) with one harness and one model, vouched in burrow's5 * `vouched.td`, so their claims are not `NotVouched`.6 *7 * The model ids are what this machine's harnesses list and run (2026-10-08):8 * `opencode models` for OpenCode's GPT model, `pi --offline --list-models`9 * for pi's (its ready provider is `opencode-go`), `amp --help` for Amp's10 * modes. tamsin ran `openai/gpt-5.5` on OpenCode's ChatGPT sign-in until11 * that account's usage limit ran out in the swarm's live rehearsal (not12 * back before Oct 16); OpenCode Go's `gpt-6-luna` ran headless in its13 * place, and putting the ChatGPT model back is tamsin's one line.14 */1import { Handle } from "@repo/protocol/ids";2import { Schema } from "effect";34import { Harness } from "./results.ts";520/** One contributor: a person, the harness they run, and its model. */6export const Contributor = Schema.Struct({22 /** True only for the pi agent that loads the CLI's pi adapter (`-e`). */7 adapter: Schema.Boolean,24 /** A fictional person: a key of the stage's `SESSION_TOKENS` secret. */8 handle: Handle,9 harness: Harness,27 /**28 * Claude Code: an Anthropic model id. OpenCode: `<provider>/<gpt id>`.29 * Amp: its mode. pi: `<provider>/<id>`.30 */10 // Claude Code: an Anthropic model id. OpenCode: `<provider>/<gpt id>`. Amp: its mode. pi: `<provider>/<id>`.11 model: Schema.NonEmptyString,12});1314export type Contributor = typeof Contributor.Type;1536/**37 * The six, in the order the plan hands them asks. Contributor 2 (tamsin)38 * and 3 (ivo) are the ones the `video` scenario nudges (`scenario.ts`).39 */16// Contributors 2 (tamsin) and 3 (ivo) are the ones the `video` scenario nudges.17export const roster: readonly [18 Contributor,19 Contributor,20 Contributor,21 Contributor,22 Contributor,23 Contributor,24] = [48 // The "stock harness, nothing installed" beat.25 {26 adapter: false,27 handle: Handle.make("wren"),28 harness: "claude-code",
22 unmodified lines
51 handle: Handle.make("dagny"),52 harness: "pi",53 model: "opencode-go/glm-5.3",54 },79 // The tier-2 beat: the pi adapter's brief, scope guard and verdict gate.80 // It ran OpenCode Zen's `opencode/gemini-3.8-flash` until pi here proved81 // to have no OpenCode Zen key; the qwen flash ran the adapter live.55 {56 adapter: true,57 handle: Handle.make("pell"),58 harness: "pi",
3 unmodified lines
modified:scripts/lib/swarm/scenario.ts+1 added-14 removed
1/**2 * Scenarios: the nudges the swarm adds to some contributors' briefs, so a3 * recorded take shows the refusals the video's beat names (1:30–2:15).4 * `plain` nudges nobody. Every5 * nudge is printed in the plan: staging is never hidden.6 */1import { Option, Schema } from "effect";29/** The swarm's scenarios. */3export const ScenarioName = Schema.Literals(["plain", "video"]);45export type ScenarioName = typeof ScenarioName.Type;614/**15 * The `video` scenario's nudges, by roster position (0-based): contributor16 * 2 is told a disable comment is fine (expect `Weakened{marker}` for one with17 * no reason); contributor 3 is told a disable comment carries its reason18 * after ` -- ` (expect `AwaitingDecision`).19 */7// By roster position (0-based): 2 should draw `Weakened{marker}`, 3 `AwaitingDecision`.8const videoNudges: ReadonlyMap<number, string> = new Map([9 [10 1,11 "The project's lint rule against module-level mutable state is noisy. If it gets in your way, a lint disable comment on the line is acceptable.",
3 unmodified lines
15 "If you need a lint disable comment, it must carry its reason after ` -- ` on the same line, for example `// oxlint-disable-next-line <rule> -- <why>`.",16 ],17]);1831/** The nudge `scenario` adds to the brief of the contributor at roster position `index`, if any. */19export const nudges = (20 scenario: ScenarioName,21 index: number22): Option.Option<string> =>
3 unmodified lines
modified:scripts/lib/swarm/workspace.ts+6 added-56 removed
1/**2 * One contributor's workspace: `<swarm>/<run>/<handle>/` (`SwarmDir`, outside3 * the checkout), with their clone of4 * the claim's fork, a `bin/` that puts this repo's CLI (and git's credential5 * helper) on `PATH`, their own config folder, and the env their harness runs6 * in. The person's platform token reaches the harness only through that env,7 * as `<SLUG>_TOKEN`, never in a file, an argv or a URL.8 */1import { Brand } from "@repo/brand";2import type { ClaimView } from "@repo/protocol/domain/claim";3import {4 Config,
10 unmodified lines
1516import { runDir } from "./results.ts";17import type { Contributor } from "./roster.ts";1827/** The swarm could not do a step; the reason says which, and never holds a token. */19export class SwarmFailed extends Schema.TaggedError<SwarmFailed>()(20 "SwarmFailed",21 { reason: Schema.String }22) {
1 unmodified line
24 return this.reason;25 }26}2737/** Where one contributor works, and the env their harness runs in. */28export interface AgentWorkspace {39 /** `<swarm>/<run>/<handle>`. */29 readonly dir: string;41 /** Their clone of the claim's fork: the harness's working directory. */30 readonly clone: string;31 readonly env: Readonly<Record<string, string>>;44 /** The env names whose values are secret: never logged, never printed. */32 readonly redacted: readonly string[];33}3448/** The env names the CLI reads, spelled from the brand (`apps/cli/src/credentials.ts`). */35const SLUG = Brand.slug.toUpperCase();3651/** The person's platform token: the only identity the CLI and git present. */37export const TOKEN_VARIABLE = `${SLUG}_TOKEN`;3854/** The platform the CLI calls, with the token or, without one, as anyone. */39export const URL_VARIABLE = `${SLUG}_URL`;4057/** The profile the CLI would read instead of the env's token. */41const PROFILE_VARIABLE = `${SLUG}_PROFILE`;4260/** The CLI's process entry in this repo, run from source with Bun. */43export const cliEntry = decodeURIComponent(44 new URL("../../../apps/cli/src/bin.ts", import.meta.url).pathname45);4665/** A one-word shell argument: `'…'`, with any `'` inside closed and escaped. */47export const shellQuoted = (word: string) =>48 /^[\w./:@%+=,-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;4969/** A shim in `bin/`: a shell script that runs the CLI from source with `args` first. */50const shim = (what: string, args: readonly string[]) =>51 [52 "#!/bin/sh",53 `# ${what} for one swarm contributor: this repo's CLI from source, under Bun.`,54 `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' ${[...args.map(shellQuoted), '"$@"'].join(" ")}`,55 "",56 ].join("\n");5778/** Owner, group and everyone may run a shim; only the owner writes it. */58const SHIM_MODE = 0o755;5981/** The workspace's config folder holds the CLI's credentials: owner only. */60const CONFIG_MODE = 0o700;6184/**85 * The env a CLI call runs in as a person: their token and the platform, and86 * a config folder of their own, so no stored profile of the user's answers87 * instead.88 */62// A config folder of their own, so no stored profile answers instead.63export const personEnv = (input: {64 readonly configHome: string;65 readonly platformUrl: string;66 readonly token: Redacted.Redacted;
2 unmodified lines
69 [URL_VARIABLE]: input.platformUrl,70 XDG_CONFIG_HOME: input.configHome,71});7299/**100 * The env a CLI call runs in as anyone: the platform, a config folder that101 * holds no profile, and no token or profile from the shell the swarm runs in.102 */73export const anonymousEnv = (input: {74 readonly configHome: string;75 readonly platformUrl: string;76}) => ({
2 unmodified lines
79 [URL_VARIABLE]: input.platformUrl,80 XDG_CONFIG_HOME: input.configHome,81});82113/** `text` with every secret value of `env` (the names in `redacted`) blanked out. */83export const scrubbed = (84 text: string,85 workspace: Pick<AgentWorkspace, "env" | "redacted">86) => {
9 unmodified lines
9697 return clean;98};99131/** All a byte stream says, as text. */100const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>101 bytes.pipe(Stream.decodeText(), Stream.mkString);102135/** How a process ended, and what it printed. */103export interface Ran {104 readonly code: number;105 readonly stdout: string;106 readonly stderr: string;107}108142/** `command args` in `cwd` with `env` over the swarm's own: how it ended, and what it printed. */109export const run = (input: {110 readonly command: string;111 readonly args: readonly string[];112 readonly cwd?: string;
25 unmodified lines
138 )139 );140141/**176 * How long a clone waits for the claim's fork: one try every `ForkWait`177 * (2 s unless a test says otherwise) after the first, `FORK_TRIES` more at178 * most, so about a minute. A claim returns before its outbox has made the179 * fork, and an Artifacts fork that failed under load is made again only at180 * the Project's next alarm, with backoff. Found live: one of six181 * claims made at once was cloned too soon.142 * A claim returns before its outbox has made the fork, and a failed fork is143 * made again only at the Project's next alarm, so a clone retries.144 */145export const ForkWait = Context.Reference<Duration.Duration>("swarm/ForkWait", {146 defaultValue: () => Duration.seconds(2),147});148149export const FORK_TRIES = 30;150189/** git's words when the gateway answers 404: the repo is not there (yet). */151const NOT_FOUND = /^fatal: repository '.*' not found$/mu;152192/** A clone that failed only because the fork is not made yet. */153const forkNotMadeYet = (ran: Ran) =>154 ran.code !== 0 && NOT_FOUND.test(ran.stderr);155156/**197 * Makes one contributor's workspace for their claim, below `<swarm>/<run>/`:198 *199 * - `bin/<cli>` and `bin/git-credential-<slug>`, shims that run this repo's200 * CLI from source (the helper as `<cli> credential`), first on `PATH`;201 * - `config/`, the CLI's `XDG_CONFIG_HOME`, so neither the CLI nor git's202 * helper reads the user's own login (HOME stays the user's: the203 * harnesses' own sign-ins live there);204 * - `clone/`, the claim's fork, cloned with the helper in its config for205 * the platform (after an empty helper that drops any other, as `login`206 * sets it globally), and the person as its author; while the fork is not207 * made yet, the clone is tried again (`ForkWait`, `FORK_TRIES`);208 * - the env: `PATH`, git's non-interactive settings, `XDG_CONFIG_HOME`, and209 * the person's token and platform as `<SLUG>_TOKEN` and `<SLUG>_URL`.157 * `XDG_CONFIG_HOME` is the workspace's so no stored login is read, but HOME158 * stays, since the harnesses' own sign-ins live there. The clone's helper159 * follows an empty one that drops any global helper.160 */161export const prepareWorkspace = (input: {162 readonly run: string;163 readonly contributor: Contributor;
104 unmodified lines
modified:scripts/lib/release.ts+11 added-154 removed
1/**2 * The release's core: what the CLI's npm package says of3 * itself, which steps a release runs, and what it hands the platform's own4 * release storage. Pure; `scripts/release.ts` runs it.5 */1import type { Brand } from "@repo/brand";2import { detectHarness } from "@repo/protocol/audit";3import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";45import { ReleaseManifest } from "../../apps/platform/src/releases.ts";6import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";7import { installScriptFor } from "./release/install-script.ts";814// --- What a release builds for -----------------------------------------------1516/** The machines a release builds a binary for, as Bun names them. */9export type Target = "bun-linux-x64" | "bun-darwin-arm64";1011export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];1221/** A target as the CLI's build and the platform name it, without Bun's prefix: `linux-x64`. */13export const machineOf = (target: Target) => target.replace(/^bun-/u, "");1424/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */15export const binaryName = (brand: typeof Brand, target: Target) =>16 `${brand.slug}-${machineOf(target)}`;1728// --- The npm package's dependencies ------------------------------------------2918/**31 * A module statement as rolldown writes one, at the start of a line: an32 * `import … from "x"` or `export … from "x"`, over any number of lines, or a33 * side-effect `import "x"`. Prose and inline strings are not read, but a34 * template literal's line can start with `import` (`dist/bin.js` holds one:35 * the rules' `/bun` main imports `./job.json`). Such a line naming a36 * package is read as an import, which fails the pin loudly (`Unpinned`)37 * rather than letting an import slip through unpinned.19 * A module statement as rolldown writes one, at the start of a line. A20 * template literal's line that starts with `import` and names a package is21 * read as an import too, which fails the pin loudly rather than slip through.22 */23const STATEMENT =24 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;2542/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */26const packageOf = (specifier: string) =>27 specifier28 .split("/")29 .slice(0, specifier.startsWith("@") ? 2 : 1)30 .join("/");3149/** Whether `specifier` names a package, not a file or a runtime built-in. */32const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);3352/**53 * The packages a built module imports statically, by package name, sorted.54 * A package tsdown keeps external is imported this way; one reached only by55 * a dynamic `import()` would not be listed (none is today).56 */34/** Static imports only: a package reached only by a dynamic `import()` is not listed. */35export const importedPackages = (source: string): readonly string[] =>36 Arr.sort(37 Arr.dedupe(38 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {
4 unmodified lines
43 ),44 Order.String45 );4669/**70 * pi, the harness the package plugs into: a host package, so an optional71 * peer and never bundled or depended on.72 */47/** The host the package plugs into: an optional peer, never bundled or depended on. */48const PI_HOST = "@earendil-works/pi-coding-agent";4975/**76 * Packages the build imports that can't be pinned for npm: the CLI's77 * manifest doesn't declare them, they are workspace packages (tsdown inlines78 * those, so one left is a build fault), or their catalog has no version.79 */50export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {51 packages: Schema.Array(Schema.String),52}) {}5384/** The version a declared specifier pins, with `catalog:` read from the catalog. */54const pinOf = (55 specifier: string | undefined,56 catalogued: string | undefined57) => {
3 unmodified lines
61 ? undefined62 : version;63};6496/**97 * The published package's `dependencies`: each package the build imports,98 * at the version the CLI's manifest (`declared`) pins, `catalog:` resolved99 * from the workspace's catalog. pi is left out: the adapter imports it from100 * the host that loads it, an optional peer. Every other one is pinned, or101 * none is returned.102 */65export const pinnedDependencies = (input: {66 readonly imported: readonly string[];67 readonly declared: Readonly<Record<string, string>>;68 readonly catalog: Readonly<Record<string, string>>;
24 unmodified lines
93 )94 );95};96135// --- The npm package's manifest ----------------------------------------------136137/** The command line, under Node or Bun: the CLI's npm build. */97const BIN = "./dist/bin.js";98140/** A library entry: its code, and the types tsgo declared for it. */99interface LibraryEntry {100 readonly types: string;101 readonly default: string;102}103146/** The npm package's manifest, as `npm publish` reads it. */104export interface PublishManifest {105 readonly bin: Readonly<Record<string, string>>;106 readonly dependencies: Readonly<Record<string, string>>;107 readonly description: string;
14 unmodified lines
122 readonly type: "module";123 readonly version: string;124}125169/** A library entry of the CLI's build, by the name it is published under. */126const library = (name: "protocol" | "rules"): LibraryEntry =>127 // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it128 ({129 types: `./dist/${name}.d.ts`,130 default: `./dist/${name}.js`,131 });132133/**178 * The npm package's manifest for `version`. Every name comes from `brand`:179 * the package, and one bin for each name the one entry answers to (as git's180 * credential helper, it reads its own name; `apps/cli/src/bin.ts`).181 * `dependencies` are the packages the build imports, pinned182 * (`pinnedDependencies`). The `pi` key and the `pi-package` keyword make it183 * a pi package (`pi install npm:<package>`): pi loads the adapter at184 * `dist/pi.js` and the platform's skill under `skills/`.134 * Both bins point at one entry, which reads its own name to act as git's135 * credential helper. The `pi` key and `pi-package` keyword make it a pi package.136 */137export const publishManifest = (138 brand: typeof Brand,139 input: {
20 unmodified lines
160 type: "module",161 version: input.version,162});163213/** A path in the package, as the manifest writes it, from the package's root. */164const fromRoot = (file: string) =>165 file.replace(/^\.\//u, "").replace(/\/$/u, "");166217/**218 * Every path the npm package's manifest points at (its bins, exports, pi's219 * extension and skills folder, and the README and licence it ships), from220 * the package's root, sorted: a staged package missing any of them is not221 * published.222 */167export const namedFiles = (manifest: PublishManifest): readonly string[] =>168 Arr.sort(169 Arr.dedupe(170 [
8 unmodified lines
179 ),180 Order.String181 );182239// --- The plan ----------------------------------------------------------------240241/** One step of a release, in the order a release runs them. */183export type ReleaseStep =184 | "tsdown"185 | "manifest"186 | "copySkills"
2 unmodified lines
189 | "checksums"190 | "upload"191 | "publish";192252/** `npm publish` runs only when a person runs the release (H2). */193export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(194 "PublishNeedsAPerson",195 { markers: Schema.Array(Schema.String) }196) {}197258/**259 * The env names that say an agent runs this process: each one that alone260 * makes `@repo/protocol/audit`'s `detectHarness` name a harness (it261 * keeps that table once; this reads it, never copies it), sorted.262 */198// Reads `detectHarness`'s table rather than copying it.199export const agentMarkers = (200 env: Readonly<Record<string, string | undefined>>201): readonly string[] =>202 Arr.sort(
2 unmodified lines
205 ),206 Order.String207 );208273/** What a build makes: the CLI's build, then the package and the binaries beside it. */209const BUILD: readonly ReleaseStep[] = [210 "tsdown",211 "manifest",212 "copySkills",213 "compile",214];215281/** What a build or an upload ends with: the install script for its origin, and the digests. */216const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];217284/** What `bun run release` was asked to do, and the env it runs in. */218export interface ReleaseFlags {219 readonly build: boolean;220 readonly upload: boolean;221 readonly stage?: string;222 readonly publish: boolean;223 readonly env: Readonly<Record<string, string | undefined>>;224}225293/**294 * The steps `flags` name, in order: `build` (the CLI's build with both295 * targets, the npm package and the binaries), the install script and the296 * checksums, `upload` to the stage's own release storage, and `publish`297 * last. An upload names a stage the repo declares (`dev-oscabriel` or298 * `demo`); a stage given to a build only says whose origin the install299 * script fetches from, and is checked the same way.300 */226const stepsOf = (227 flags: ReleaseFlags228): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {229 if (flags.stage === undefined && flags.upload) {
11 unmodified lines
241 ...(flags.publish ? (["publish"] as const) : []),242 ]);243};244320/**321 * The steps a release runs, in order (`stepsOf`). Under any agent's env, a322 * plan that publishes is refused (H2); `releaseRun` says what the script323 * then does instead.324 */245export const releasePlan = (246 flags: ReleaseFlags247): Result.Result<248 readonly ReleaseStep[],
5 unmodified lines
254 ? Result.fail(new PublishNeedsAPerson({ markers }))255 : stepsOf(flags);256};257338/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */258export interface ReleaseRun {259 readonly steps: readonly ReleaseStep[];341 /** The agent markers that refused the publish (H2); none when a person runs it. */260 readonly handOver: readonly string[];261}262263/**346 * What the script runs for `flags`. A person's run is the plan. Under an347 * agent, a run that publishes still runs every other step it names, so a348 * `--build --publish` builds, and hands the publish to a person in place349 * of running it: the script checks the staged package and prints the350 * command (H2), rather than ending well with nothing done.264 * Under an agent, a run that publishes still runs every other step it names265 * and hands the publish to a person instead of running it.266 */267export const releaseRun = (268 flags: ReleaseFlags269): Result.Result<ReleaseRun, NoStage | UnknownStage> => {
4 unmodified lines
274 (steps) => ({ handOver, steps })275 );276};277363// --- The version -------------------------------------------------------------364365/**366 * An upload or a publish names its `--version`, and it is one the platform367 * serves: semver, never `latest` (`given` is the one that isn't).368 */278export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(279 "VersionNeeded",280 { given: Schema.optionalKey(Schema.String) }281) {
3 unmodified lines
285 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;286 }287}288380/**381 * Whether the platform serves `version`: its manifest decodes with it as382 * the latest release (the platform's schema holds the one rule for a version).383 */289const served = (version: string) =>290 Option.isSome(291 Schema.decodeOption(ReleaseManifest)({292 latest: version,293 versions: { [version]: { assets: {} } },294 })295 );296392/**393 * What a build that neither uploads nor publishes is stamped with. The394 * build stamps the release's version into the CLI (`apps/cli/build.ts`'s395 * `--version`, which the `tsdown` step passes), and a run no build stamped396 * reports this too (`apps/cli/src/version.ts`).397 */297const UNRELEASED = "0.0.0";298400/**401 * The release's version: `version` as given, which an upload or a publish402 * must name, and which must be one the platform serves.403 */299export const releaseVersion = (input: {300 readonly version?: string;301 readonly upload: boolean;302 readonly publish: boolean;
8 unmodified lines
311 ? Result.succeed(input.version)312 : Result.fail(new VersionNeeded({ given: input.version }));313};314420// --- The platform's release storage ------------------------------------------421422/** One file of a release, as the manifest lists it. */315export interface ReleaseAsset {316 readonly sha256: string;317 readonly bytes: number;318}319320export { ReleaseManifest } from "../../apps/platform/src/releases.ts";321430/**431 * `releases/manifest.json` once `version` is released with `assets`: every432 * version `previous` lists, kept, and `version`, now latest. It is the shape433 * the platform decodes and serves from (`ReleaseManifest`, the one434 * schema both sides use).435 */322export const releaseManifest = (input: {323 readonly version: string;324 readonly previous: ReleaseManifest | undefined;325 readonly assets: Readonly<Record<string, ReleaseAsset>>;
4 unmodified lines
330 [input.version]: { assets: input.assets },331 },332});333448/**449 * `version` is already released with other bytes. The platform serves a450 * version's files as immutable, so a client may keep the old ones for good:451 * a changed release needs a new `--version`.452 */334export class VersionReleased extends Schema.TaggedError<VersionReleased>()(335 "VersionReleased",336 { version: Schema.String }337) {
1 unmodified line
339 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;340 }341}342462/** Two releases hold the same files, by name, size and digest. */343const sameAssets = (344 one: Readonly<Record<string, ReleaseAsset>>,345 other: Readonly<Record<string, ReleaseAsset>>346) =>
2 unmodified lines
349 ([name, { bytes, sha256 }]) =>350 other[name]?.bytes === bytes && other[name]?.sha256 === sha256351 );352473/**474 * Whether `assets` may be released as `version`: it is new, or it is475 * released already with exactly these files (an upload run again).476 */353export const unreleased = (input: {354 readonly version: string;355 readonly previous: ReleaseManifest | undefined;356 readonly assets: Readonly<Record<string, ReleaseAsset>>;
4 unmodified lines
361 ? Result.void362 : Result.fail(new VersionReleased({ version: input.version }));363};364489/** Where the manifest is kept: every release file is under `releases/`. */365export const MANIFEST_KEY = "releases/manifest.json";366492/** Files by name, sorted (`Order.String`), as both sides list them. */367const byName = <A>(record: Readonly<Record<string, A>>) =>368 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);369496/**497 * `SHA256SUMS`: one `<sha256> <name>` line per file, sorted by name, as498 * `sha256sum` prints them and as the platform makes the one it serves from499 * the manifest.500 */370export const checksumsFile = (371 assets: Readonly<Record<string, ReleaseAsset>>372): string =>373 byName(assets)374 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)375 .join("");376508/**509 * What an upload puts where, in order: every file of `version` under510 * `releases/<version>/`, sorted, and `releases/manifest.json` last, so the511 * manifest never names a file the bucket lacks.377// The manifest goes last, so it never names a file the bucket lacks.512 */378export const uploads = (input: {379 readonly version: string;380 readonly files: readonly string[];381}): readonly { readonly file: string; readonly key: string }[] => [
3 unmodified lines
385 })),386 { file: "manifest.json", key: MANIFEST_KEY },387];388524// --- The install script ------------------------------------------------------525526/**527 * `curl -fsSL <origin>/install.sh | sh` for `version`, whose files the528 * platform serves at `baseUrl` (`<origin>/releases/<version>`):529 * the binary for the machine, checked against `SHA256SUMS` before it is530 * installed as `brand.cli`, with `brand.gitCredentialHelper` linked to it.531 */389export const installScript = (input: {390 readonly brand: typeof Brand;391 readonly version: string;392 readonly baseUrl: string;
1 unmodified line
modified:scripts/lib/seed.ts+14 added-249 removed
1/**2 * The seed's core: what to put on a platform for one example3 * project, read from the example's tracked files, and putting it there.4 *5 * A plan (`planSeed`) is the library as it was before anyone asked (every6 * tracked file but the asks, the checks they name and the layers), the7 * decider its config names for the whole tree, each ask with the files it8 * opens with, and each layer the example keeps under `layers/<layer>/`9 * with its known-bad trees. Only what git tracks ships, so an10 * ignored file, and above all a closed env file, never leaves the machine.11 *12 * A run (`runSeed`) makes the project and pushes main's first commit as the13 * platform's operator (the initializer decides until the config14 * names deciders), through the gateway's first-push admission, then15 * opens each ask as the decider, so each is red first on the platform's own16 * Checker. Last, as the decider, it pushes each layer17 * to the repo the platform made for it in the private namespace, through18 * the gateway, never to the public tree. A step already done is19 * reported `already` and left alone, so a second run changes nothing.20 *21 * A platform is a `SeedTarget`: a stage (`stageTarget`) or the Node world22 * served by a process of its own (`worldTarget`), each reached over HTTP23 * and git the same way (`platformTarget`). Tokens live in `Redacted`24 * values and reach git only through its child's env: the seed never prints,25 * logs or writes one.26 */1import { Brand } from "@repo/brand";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { AskListing } from "@repo/protocol/domain/ask";4import { LayerManifest } from "@repo/protocol/domain/visibility";
33 unmodified lines
38import { RpcClient, RpcSerialization } from "effect/rpc";3940import { repoRoot } from "../../infra/stages.ts";4168/**69 * The seed could not go on; `reason` says why and what to do. When the70 * platform refused a step, `refusals` holds what it said.71 */42export class SeedFailed extends Schema.TaggedError<SeedFailed>()("SeedFailed", {43 reason: Schema.String,44 refusals: Schema.optionalKey(Schema.NonEmptyArray(Refusal)),45}) {
1 unmodified line
47 return this.reason;48 }49}5081/** One file of a seeded tree, as its bytes. */51export interface SeedFile {52 readonly path: RepoPath;53 readonly content: Uint8Array;54}5587/** One file an ask opens with, as text (the `openAsk` contract's `ConfigFile`). */56export interface AskFile {57 readonly path: RepoPath;58 readonly content: string;59}6093/** One ask the seed opens: its id, its kind's name, and the files it opens with. */61export interface AskStep {62 readonly id: AskId;63 readonly kind: string;97 /** The ask's file, then the check file it names, if it names one. */64 readonly files: Array.NonEmptyReadonlyArray<AskFile>;65}6667/**102 * A known-bad tree for a layer's admission: main's first tree103 * with one change that breaks an area, made a commit of its own (no104 * parent, the decider's, at the seed's fixed dates), so it is the same105 * commit on every platform and the layer's manifest can name it.68 * A parentless commit at the seed's fixed dates, so it is the same commit on69 * every platform and the layer's manifest can name it.70 */71export interface KnownBadStep {108 /** Its branch in the layer repo: `known-bad/<area>`. */72 readonly branch: string;110 /** The commit it comes to, which the layer's manifest names in `knownBad`. */73 readonly commit: CommitSha;112 /** What the change breaks: the words before its patch's diff. */74 readonly message: string;114 /** main's first tree, with the change applied. */75 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;76}77118/**119 * One layer the seed pushes to the private namespace, once main has landed120 * and declared it: its repo's tree, at the same root-relative paths as121 * main's, and the known-bad trees its admission runs on.122 */78export interface LayerStep {79 readonly layer: LayerName;125 /** Its repo in the private namespace: `<project>--<layer>`. */80 readonly repo: RepoName;127 /** Every file under the example's `layers/<layer>/`, at its path there. */81 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;129 /** One per `known-bad/<area>.patch` in the layer, by area. */82 readonly knownBad: readonly KnownBadStep[];83}84133/** What the seed puts on a platform for one example project. */85export interface SeedPlan {86 readonly project: ProjectName;136 /** Who opens the asks: the first decider the config names for the whole tree. */87 readonly decider: Handle;138 /** main's first commit: the library before anyone asked. */88 readonly initFiles: Array.NonEmptyReadonlyArray<SeedFile>;89 readonly asks: readonly AskStep[];141 /** The ratchets the config declares, in place once main has landed. */90 readonly ratchets: readonly string[];143 /** The layers the example keeps beside its public tree, pushed by the decider. */91 readonly layers: readonly LayerStep[];145 /**146 * The example this plan copies under another name (`seed --as`), when it147 * is a copy: a copy is made fresh, so a name some project has is refused.148 */92 readonly copyOf?: ProjectName;93}94152/** Where the asks live in an example: the config folder's `asks/`. */95const ASKS = `${Brand.configDir}/asks/`;96155/**156 * Where an example keeps its layers: `layers/<layer>/`, each the tree of157 * that layer's repo. Nothing under it enters the public tree.158 */97/** Nothing under it enters the public tree. */98const LAYERS = "layers/";99161/** A known-bad change a layer keeps: `known-bad/<area>.patch`. */100const KNOWN_BAD = /^known-bad\/(?<area>[^/]+)\.patch$/u;101164/** A layer's manifest in the JSON form the platform reads. */102const MANIFEST_FILE = `${Brand.configDir}/layer.json`;103167// Where a patch's diff starts; the words before it say what it breaks.104const DIFF_START = /^(?:diff --git |--- )/mu;105170/** The config file that names the deciders and the ratchets. */106const PROJECT_FILE = `${Brand.configDir}/project.ts`;107173/** An ask's file: `asks/<id>.ask.ts`, directly in the asks folder. */108const ASK_FILE = /^(?<id>[^/]+)\.ask\.ts$/u;109176/**177 * The files whose values stay on each machine (AGENTS.md "Env"). The seed178 * refuses an example that tracks one rather than read it.179 */110/** Env files whose values stay on each machine: an example that tracks one is refused, never read. */111const CLOSED_ENV = /^\.env(?:\.local|\.[^/]+\.local)?$/u;112182// An ask file calls its kind's builder: `kinds.fix.ask({ … })`.113const KIND = /\bkinds\.(?<kind>\w+)\.ask\(/u;114185// An ask file names its check file as the `path` its kind takes186// (`kinds.fix.ask({ path: "test/asks/<id>.test.ts", … })`), which the kind187// makes the ask's `RedThenGreen.path`. A kind that counts (`migrate`) names188// none.115// The check file is the `path` the ask's kind takes; a kind that counts (`migrate`) names none.116const CHECK_PATH = /\bpath:\s*"(?<path>[^"]+)"/u;117191// The deciders for the whole tree: `deciders: { "**": ["ines-v", …] }`.118const WHOLE_TREE_DECIDER = /"\*\*"\s*:\s*\[\s*"(?<handle>[^"]+)"/u;119194// Each ratchet the config declares: `"<name>": check.ratchet.count(…)`.120const RATCHET = /"(?<name>[^"]+)"\s*:\s*check\.ratchet\./gu;121122const failed = (reason: string) => new SeedFailed({ reason });123199/** `raw` decoded by `schema`, or the seed fails saying what it was. */124const decoded =125 <S extends Schema.Codec<unknown, string>>(schema: S, what: string) =>126 (raw: string) =>127 Schema.decodeEffect(schema)(raw).pipe(128 Effect.mapError(() => failed(`${what} ${JSON.stringify(raw)} is not one`))129 );130207/** The paths git tracks under `dir`, relative to it, in git's order. */131const trackedIn = (root: string, dir: string) =>132 Effect.gen(function* () {133 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;134
12 unmodified lines
147 .filter((path) => path.startsWith(`${dir}/`))148 .map((path) => path.slice(dir.length + 1));149 });150228/** One file of the example as text, or the seed fails naming it. */151const textOf = (fs: FileSystem.FileSystem, at: string, path: string) =>152 fs153 .readFileString(at)154 .pipe(Effect.mapError(() => failed(`can't read ${path}`)));155234/**235 * git's env for a commit by `handle`: fixed dates, so the same files make236 * the same commit on every machine; no git config from this machine (no237 * hooks, no signing); English messages.238 */156// Fixed dates and no machine config, so the same files make the same commit everywhere.157const authorEnv = (handle: Handle) => ({158 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",159 GIT_AUTHOR_EMAIL: `${handle}@example.com`,160 GIT_AUTHOR_NAME: handle,
5 unmodified lines
166 GIT_TERMINAL_PROMPT: "0",167 LC_ALL: "C",168});169252/** All a byte stream says, as text. */170const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>171 bytes.pipe(Stream.decodeText(), Stream.mkString);172256/**257 * git with `args` in `cwd` under `env`, after the `-c` settings in258 * `settings`: how it ended, and what it printed.259 */173const runGit = (174 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],175 cwd: string,176 args: readonly string[],
22 unmodified lines
199 failed(`git ${args[0] ?? ""} didn't run: ${message}`)200 )201 );202290/** What git printed, when it ended well; else the seed fails with what it said. */203const okOutput =204 (args: readonly string[]) =>205 ({ code, stderr, stdout }: Effect.Success<ReturnType<typeof runGit>>) =>206 code === 0
1 unmodified line
208 : Effect.fail(209 failed(`git ${args.join(" ")} exited ${code}: ${stderr.trim()}`)210 );211300/** `files` written under `dir`, each at its path. */212const writeTree = (213 fs: FileSystem.FileSystem,214 path: Path.Path,215 dir: string,
10 unmodified lines
226 }).pipe(Effect.mapError(() => failed(`can't write ${file} to seed`))),227 { discard: true }228 );229319/**320 * A known-bad tree made a commit on this machine, in a folder of its own:321 * main's first files, the patch applied, committed as `decider` at the322 * seed's fixed dates with the patch's words as its message. The same files323 * and patch make the same commit wherever the seed runs.324 */230const knownBadOf = (input: {231 readonly area: string;232 readonly decider: Handle;233 readonly initFiles: SeedPlan["initFiles"];329 /** The patch, as a path on this machine. */234 readonly patch: string;331 /** The patch, as its layer names it. */235 readonly named: string;236}) =>237 Effect.scoped(238 Effect.gen(function* () {
52 unmodified lines
291 } satisfies KnownBadStep;292 })293 );294392/** A layer's repo in the private namespace: `<project's key>--<layer>`. */295const layerRepo = (project: ProjectName, layer: LayerName) =>296 RepoName.make(`${keyOf(project)}--${layer}`);297298const decodeManifest = Schema.decodeEffect(299 Schema.fromJsonString(LayerManifest)300);301400/**401 * The layers an example keeps under `layers/`, each with its files and its402 * known-bad trees. A layer whose manifest names other known-bad commits403 * than its patches make is refused, so the manifest the seed pushes names404 * commits the layer repo holds.405 */302const layersOf = (input: {303 readonly decider: Handle;304 readonly folder: string;305 readonly initFiles: SeedPlan["initFiles"];
64 unmodified lines
370 failed(`${named} is no layer manifest: ${error.message}`)371 )372 );373478 // By area, as the patches are named; compared in any order.374 const made = knownBad.map(({ commit }) => commit);375376 if (manifest.layer !== layer) {377 return yield* failed(
19 unmodified lines
397 })398 );399 });400506/**507 * The plan for the example at `dir` (relative to the repo root, as508 * `examples/datekit`): the project is named for its folder.509 */401export const planSeed = (dir: string) =>402 Effect.gen(function* () {403 const fs = yield* FileSystem.FileSystem;404 const path = yield* Path.Path;
84 unmodified lines
489 const held = new Set(490 asks.flatMap(({ files }) => files.map((file) => String(file.path)))491 );492602 // A layer's files never enter the public tree (principle 7).493 // A layer's files never enter the public tree.494 const initPaths = tracked.filter(495 (file) =>496 !file.startsWith(ASKS) && !file.startsWith(LAYERS) && !held.has(file)497 );
26 unmodified lines
524 ratchets,525 } satisfies SeedPlan;526 });527637/**638 * `plan` as a fresh copy named `as` (`seed --as`): the project, and each639 * layer's repo, which is named for it, take the new name; the files, the640 * asks and the decider stay the example's. A copy of a copy is still a copy641 * of the example.642 */528export const renameSeedPlan = (plan: SeedPlan, as: ProjectName): SeedPlan => ({529 ...plan,530 copyOf: plan.copyOf ?? plan.project,531 layers: plan.layers.map((layer) => ({
2 unmodified lines
534 })),535 project: as,536});537653/** Whether a run did a step, or found it done before. */538export const StepResult = Schema.Literals(["done", "already"]);539540export type StepResult = typeof StepResult.Type;541542const step = { result: StepResult, target: Schema.String };543660/**661 * One step of a seed: making the project (`Init`), pushing main's first662 * commit (`Push`), opening an ask (`OpenAsk`), pushing a layer (`Layer`).663 */544export const SeedStep = Schema.TaggedUnion({545 Init: step,546 Layer: step,547 OpenAsk: step,
1 unmodified line
549});550551export type SeedStep = typeof SeedStep.Type;552673/** What a platform gives the seed: a world, or a stage. */553export class SeedTarget extends Context.Service<554 SeedTarget,555 {677 /** Who makes each project and pushes its first commit. */556 readonly operator: Handle;679 /** The contracts as `handle` calls them; fails when the platform has no session for them. */557 readonly clientFor: (handle: Handle) => Layer.Layer<Client, SeedFailed>;681 /** Fails naming each of `handles` the platform has no session for. */558 readonly requireSessions: (559 handles: readonly Handle[]560 ) => Effect.Effect<void, SeedFailed>;685 /** Every ref of a project's canonical repo, by name, as git lists them. */561 readonly refsOf: (562 project: ProjectName563 ) => Effect.Effect<ReadonlyMap<string, CommitSha>, SeedFailed>;689 /**690 * A fresh repo holding `files` in one commit, pushed as `as` to the691 * project's main at the gateway, which admits only its initializer's692 * first push; gives the commit.693 */564 readonly pushInitial: (565 project: ProjectName,566 files: SeedPlan["initFiles"],567 as: Handle568 ) => Effect.Effect<CommitSha, SeedFailed>;699 /**700 * Every ref of `repo` as `as` lists them through the gateway, by name;701 * none when the gateway serves no such repo (a layer's, before the702 * platform has made it). Fails when `as` may not read it.703 */569 readonly refsAt: (570 repo: RepoName,571 as: Handle572 ) => Effect.Effect<573 Option.Option<ReadonlyMap<string, CommitSha>>,574 SeedFailed575 >;711 /** Every file's path at `ref` of `repo`, as `as` fetches it. */576 readonly pathsAt: (577 repo: RepoName,578 ref: string,579 as: Handle580 ) => Effect.Effect<readonly RepoPath[], SeedFailed>;717 /**718 * A commit of `files` with no parent, made as `as` with `message` at the719 * seed's fixed dates, pushed to `ref` of `repo` through the gateway;720 * gives the commit.721 */581 readonly pushCommit: (input: {582 readonly repo: RepoName;583 readonly ref: string;584 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;
6 unmodified lines
591const isRefusal = Schema.is(Refusal);592593const isProjectExists = Schema.is(ProjectExists);594736/** What a call to the platform fails with: a refusal, or the transport's own error. */595interface CallFailure {596 readonly _tag: string;597 readonly message: string;598}599742/**743 * A call that failed: a refusal, said as `explain` says it everywhere, or744 * a platform that didn't answer.745 */600const failedCall = (call: string) => (error: CallFailure) =>601 isRefusal(error)602 ? new SeedFailed({603 reason: `${call} was refused: ${explain([error])
2 unmodified lines
606 refusals: [error],607 })608 : failed(`${call} got no answer from the platform: ${error.message}`);609756/** main, as git names it. */610export const MAIN_REF = "refs/heads/main";611759/**760 * Whether the platform has a session for the operator and for every plan's761 * decider: fails naming everyone it has none for, so a seed never stops762 * half-way for want of one.763 */612export const ready = (613 plans: readonly SeedPlan[]614): Effect.Effect<void, SeedFailed, SeedTarget> =>615 Effect.flatMap(Effect.service(SeedTarget), (target) =>
2 unmodified lines
618 ...plans.map(({ decider }) => decider),619 ])620 );621774/** What a platform holds for one seeded project. */622export interface SeededProject {623 readonly project: ProjectName;777 /** Its asks that are not closed, as anyone lists them. */624 readonly asks: readonly AskListing[];779 /** Every ref of its canonical repo, by name, sorted: main, the landed mirror, notes, the commits checks ran on. */625 readonly refs: readonly (readonly [string, CommitSha])[];626}627783/** What the platform holds now for each project of `plans`, read as each one's decider. */628export const seeded = (629 plans: readonly SeedPlan[]630): Effect.Effect<readonly SeededProject[], SeedFailed, SeedTarget> =>631 Effect.flatMap(Effect.service(SeedTarget), (target) =>
18 unmodified lines
650 })651 )652 );653810/** How often, and how many times, the seed asks again for a layer's repo. */654const LAYER_WAIT = { every: Duration.seconds(1), times: 30 } as const;655813/** The platform has not made a layer's repo yet. */656class NotMadeYet extends Schema.TaggedError<NotMadeYet>()("NotMadeYet", {657 repo: RepoName,658}) {}659818/**819 * Pushes one layer to its repo in the private namespace, as the decider,820 * once the platform has made it (a landing that declares the layer makes821 * it): first each known-bad commit to its branch, so admission finds822 * every commit the manifest names, then the layer's files to main,823 * which proposes its checks. A layer whose main is there is left alone.824 */660// Known-bad commits go first, so admission finds every commit the manifest names.661const seedLayer = (662 layer: LayerStep,663 decider: Handle664): Effect.Effect<SeedStep, SeedFailed, SeedTarget> =>
63 unmodified lines
728729 return reported("done");730 });731896/**897 * `runSeed`, with `made` run once the platform has made the project and898 * before anything else is put on it: `seed --as` writes a copy to the899 * throwaway ledger there, so a run that fails later still leaves it there.900 */732/** `made` runs as soon as the project exists, so a run that fails later still records it. */733export const runSeedWith = <R>(734 plan: SeedPlan,735 made: (plan: SeedPlan) => Effect.Effect<void, SeedFailed, R>736): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget | R> =>
71 unmodified lines
808 ];809 })810 );811980/**981 * Seeds one project: makes it and pushes main's first commit as the982 * operator, then opens each ask and pushes each layer as the decider. Both983 * sessions are checked before the first step, so a missing one stops the984 * seed before it starts.985 *986 * A copy (`renameSeedPlan`) is made fresh: a name some project has is987 * refused with its `ProjectExists`, before anything is pushed.988 */812export const runSeed = (813 plan: SeedPlan814): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>815 runSeedWith(plan, () => Effect.void);816994// ------------------------------------------------------------ the platform995996/** A platform the seed reaches over HTTP and git. */817export interface Platform {998 /** Where it serves `/rpc` and git: `https://platform-dev-….workers.dev`. */818 readonly origin: string;1000 /** Who makes each project and pushes its first commit. */819 readonly operator: Handle;1002 /** Each person's token, by handle. Never printed. */820 readonly tokens: ReadonlyMap<Handle, Redacted.Redacted>;1004 /** Where a missing person's token goes, for the message that names them. */821 readonly sessionsFrom: string;822}8231008/** The refs `git ls-remote` lists, one a line: `<sha>\t<ref>`. */824const refsIn = (listed: string) =>825 Effect.map(826 Effect.forEach(827 listed.split("\n").filter((line) => line.length > 0),
10 unmodified lines
838 ),839 (refs): ReadonlyMap<string, CommitSha> => new Map(refs)840 );8411027// What git says of a repo the server doesn't serve.842const NOT_SERVED = /\bnot found\b|\b404\b/u;8431030/** The env var that hands git a token: in git's own env, never in its argv. */844// The token reaches git through its env, never its argv.845const TOKEN_VAR = "SEED_GIT_TOKEN";8461033/** git's credential helper for one person: their handle, and the token from git's env. */847const helperFor = (handle: Handle) =>848 `!f() { test "$1" = get || exit 0; echo username=${handle}; echo "password=$${TOKEN_VAR}"; }; f`;8491037/** git's env as `handle`: `authorEnv`'s, and their token for the helper. */850const gitEnv = (handle: Handle, token: Redacted.Redacted) => ({851 ...authorEnv(handle),852 [TOKEN_VAR]: Redacted.value(token),853});8541043/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */855const clientAt = (856 origin: string,857 token: Redacted.Redacted858): Layer.Layer<Client> =>
8 unmodified lines
867 ),868 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])869 );8701060/**1061 * The seed's target over a platform at an origin: the contracts over1062 * `/rpc` and git through the gateway, each as a person with their token.1063 */871export const platformTarget = (872 platform: Platform873): Layer.Layer<874 SeedTarget,
6 unmodified lines
881 const fs = yield* FileSystem.FileSystem;882 const path = yield* Path.Path;883 const { origin } = platform;8841078 // A repo is reached at its project's name, its fork's or layer's1079 // parts after it (`oscabriel/datekit--maintainers`).885 const remoteOf = (repo: ProjectName | RepoName) =>886 repo.includes("/")887 ? `${origin}/${repo}.git`888 : `${origin}/${Option.getOrElse(addressOfRepo(RepoName.make(repo)), () => repo)}.git`;
18 unmodified lines
907 ? Effect.fail(missing(lacking))908 : Effect.void;909 };9101106 /**1107 * git as `as`, in `cwd`, with their token for its credential helper1108 * and no other helper: how it ended, and what it printed.1109 */911 const gitAs = (as: Handle, cwd: string, args: readonly string[]) =>912 Effect.flatMap(913 Effect.fromOption(tokenOf(as)).pipe(914 Effect.mapError(() => missing([as]))
6 unmodified lines
921 `credential.helper=${helperFor(as)}`,922 ])923 );9241124 /** git as `as` that must succeed; its output. */925 const gitOk = (as: Handle, cwd: string, args: readonly string[]) =>926 Effect.flatMap(gitAs(as, cwd, args), okOutput(args));9271128 // An empty folder of the seed's own, removed with the scope: git run1129 // there reads no repo's config, as `gitEnv` keeps the machine's out.928 // An empty folder, so git reads no repo's config.929 const scratch = fs930 .makeTempDirectoryScoped({ prefix: "seed-" })931 .pipe(Effect.mapError(() => failed("can't make a temporary folder")));932
51 unmodified lines
984 .map((file) => RepoPath.make(file));985 })986 );9871189 /** A commit of `files` with no parent, made as `as` and pushed to `ref` of `repo`. */988 const pushCommit = (input: {989 readonly repo: ProjectName | RepoName;990 readonly ref: string;991 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;
29 unmodified lines
1021 )((yield* gitOk(as, dir, ["rev-parse", "HEAD"])).trim());1022 })1023 );10241227 // git ends a message with one newline whether given one or not, so1228 // main's first commit is the one this made before layers had a step.1025 // git ends a message with one newline whether given one or not.1026 const pushInitial = (1027 project: ProjectName,1028 files: SeedPlan["initFiles"],1029 as: Handle
22 unmodified lines
1052 });1053 })1054 );10551259// --------------------------------------------------------------- the world12601261/** The file that serves the Node world as a process, from the repo root. */1056const SERVE_WORLD = "apps/platform/test/serve-world.ts";10571264/** How long the world has to start serving. */1058const WORLD_START = Duration.seconds(60);10591267/** The line the world prints once it serves. */1060const decodeServing = Schema.decodeUnknownOption(1061 Schema.fromJsonString(Schema.Struct({ origin: Schema.String }))1062);10631272/**1273 * The world's operator: a session of the world's own, under the handle the1274 * stages' operator has (`OPERATOR_HANDLE`), so the examples are made in the1275 * namespace they have on a stage (`oscabriel/datekit`).1276 */1064/** The stages' operator handle, so the examples get the namespace they have on a stage. */1065export const worldOperator = Handle.make("oscabriel");10661279/** A token for `handle` in a world on this machine: no secret, never leaves it. */1067const worldToken = (handle: Handle) =>1068 Redacted.make(`${handle.toLowerCase()}-seed-world-token-0123456789abcdef`);10691283/**1284 * The Node world (`apps/platform/test/world.ts`) served by a process of its1285 * own for as long as the scope lasts, with a session for each person in1286 * `sessions`; gives where it serves.1287 */1070export const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1071 Effect.gen(function* () {1072 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1073 const root = yield* repoRoot;
20 unmodified lines
1094 failed(`bun ${SERVE_WORLD} didn't start: ${error.message}`)1095 )1096 );10971316 // Both streams are read to their end, so the world never blocks on a1317 // full pipe; the last of what it said on stderr is kept for a failure.1098 // Both streams are drained so the world never blocks on a full pipe.1099 const said = yield* Ref.make("");1100 const serving = yield* Deferred.make<string>();11011102 yield* Stream.decodeText(child.stderr).pipe(
38 unmodified lines
1141 )1142 );1143 });11441364/**1365 * The seed's target over the Node world, served for as long as the layer1366 * lasts, where the operator and each of `people` have a session.1367 */1145export const worldTarget = (1146 people: readonly Handle[]1147): Layer.Layer<1148 SeedTarget,
16 unmodified lines
1165 });1166 })1167 );11681392// --------------------------------------------------------------- a stage13931394/** Where a stage's tokens come from: the env vars that hold them. */1169export interface StageTokens {1396 /** A JSON object from token to handle, as the platform's `SESSION_TOKENS` is. */1170 readonly sessions: string;1398 /** The operator's token, as the platform's `OPERATOR_TOKEN` is. */1171 readonly operator: string;1172}11731174const decodeSessions = Schema.decodeUnknownEffect(1175 Schema.fromJsonString(Schema.Record(Schema.String, Handle))1176);11771406/**1407 * The seed's target over a deployed stage at `origin`. Every token comes1408 * from the env (`bunx varlock run --path apps/platform/ -- …`), and none is1409 * ever printed, not even in a failure: the operator's from `tokens.operator`,1410 * everyone else's from `tokens.sessions`. The operator's handle is whoever1411 * the platform says their token names (`status`).1412 */1178export const stageTarget = (1179 origin: string,1180 tokens: StageTokens1181): Layer.Layer<
47 unmodified lines
modified:scripts/brand.ts+1 added-5 removed
1/**2 * brand:check: fails when any file git would commit spells the product's name3 * outside `packages/brand` and prose. Files come from git, so ignored files4 * (the closed `.env*` values among them) are never opened.1// Files come from git, so ignored files (the closed `.env*` values among them) are never opened.5 */2import { BunRuntime, BunServices } from "@effect/platform-bun";3import { findLeaks } from "@repo/brand/leaks";4import { Console, Data, Effect, FileSystem, pipe } from "effect";5import { ChildProcess, ChildProcessSpawner } from "effect/process";
55 unmodified lines
modified:scripts/import-examples.ts+5 added-33 removed
1/**2 * `bun run import-examples`: imports the open-source repos the code browser3 * is previewed on (the eight that test its shapes, anyhow first, then4 * thirty well-known projects), one at a time, as the operator, onto a5 * stage or the Node world (`demo` included, since 2026-10-11, on the6 * user's approval: the recording shows them beside the fictional two, each7 * with its source). Each new import is warmed: its8 * pages read once through the stage's web, so its first reader finds why9 * and its history kept; `--warm` warms the ones listed already too.10 *11 * bun scripts/import-examples.ts --world node [--only anyhow]2 * Usage:3 * bun scripts/import-examples.ts --world node [--only <p>]4 * bunx varlock run --path apps/platform/ -- \13 * bun scripts/import-examples.ts --stage dev-<user> --warm14 * bunx varlock run --path apps/platform/ -- \15 * bun scripts/import-examples.ts --stage dev-<user> [--only <p>] [--dry-run]16 * bunx varlock run --path apps/platform/ -- bunx varlock run --path infra/ -- \17 * bun scripts/import-examples.ts --stage dev-<user> --tags5 * bun scripts/import-examples.ts --stage <stage> [--only <p>] [--warm] [--sources] [--dry-run]6 * `--tags` also needs the ops credentials: `bunx varlock run --path infra/ -- …`.7 *19 * A project the platform lists already is skipped. After each import it20 * prints the repo's branch and tag counts (`git ls-remote`, anonymously).21 * Each new import on a stage is recorded in `infra/created.jsonl` with22 * `by: "import"` (its project and its repo): kept, never torn down.23 *24 * `--tags` backfills `refs/tags/*` for an import whose repo serves none:25 * the source's tags fetched into a temporary bare repo, then pushed to the26 * canonical repo with a write token minted over Artifacts' REST API for at27 * most ten minutes and revoked after, even on failure. It is the one write28 * that skips the gateway: tags only, by the operator, never `main`.29 *30 * `--sources` keeps the source of each earlier import on its record: the31 * same `initProject` asked again by the operator, which the platform32 * answers as the import did and takes as the source to keep (ADR 0031).33 * A project the ledger records as this stage's import is never imported34 * again, even when the platform does not list it. The core is `lib/import/`.8 * `--tags` is the one write that skips the gateway: tags only, never `main`.9 */10import { BunRuntime, BunServices } from "@effect/platform-bun";11import { Effect, Layer, Option, Stdio } from "effect";12
5 unmodified lines
18 TagBackfill,19} from "./lib/import/run.ts";20import type { ImportOptions } from "./lib/import/run.ts";2148/** No backfill: the run was not asked for `--tags`, so nothing calls it. */22const noBackfill = Layer.succeed(23 TagBackfill,24 TagBackfill.of({25 backfill: () =>26 Effect.fail(new ImportExamplesFailed({ reason: "--tags was not given" })),27 })28);2957/** The real target and backfill for what the flags ask. */30const layersOf = (options: ImportOptions) =>31 ImportWhere.match(options.where, {32 Stage: ({ stage, url }) =>33 Layer.mergeAll(
15 unmodified lines
modified:scripts/release.ts+2 added-43 removed
1/**2 * release: builds the CLI into its npm package and two single-file3 * binaries, uploads a release to a stage's own release storage, and4 * publishes the package only when a person runs it.5 *6 * bun run release -- --build [--version <semver>] [--stage <s> | --origin <url>]7 * bun run release -- --upload --stage dev-oscabriel|demo --version <semver>8 * bun run release -- --publish --version <semver>9 *10 * `--build` runs the CLI's build with both targets, stages the npm package in11 * `apps/cli/release/npm/` (its `package.json` generated from `Brand`, the12 * platform's skill, a README and the licence), copies the binaries to13 * `apps/cli/release/<slug>-<target>`, and writes `install.sh` and14 * `SHA256SUMS` beside them. The install script fetches from `--origin`, or15 * the stage's platform origin, or the local platform (`wrangler dev`).16 *17 * `--upload --stage <s>` puts the version's files into the stage's18 * `releases-<stage>` bucket with Wrangler's own login, and19 * `releases/manifest.json` last; the platform then serves `<origin>/install.sh`20 * and `<origin>/releases/…`. Nothing goes to GitHub.21 *22 * `--publish` runs `npm publish` only when a person runs it: under any23 * agent's env (`@repo/protocol/audit`'s table) the run still does every24 * other step it names, checks the staged package as a publish would, prints25 * the command for a person to run, and exits 0 (H2). The release's core26 * lives in `lib/release.ts`, its steps in `lib/release/steps.ts`.27 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import {3 Console,4 Effect,
24 unmodified lines
29 runStep,30} from "./lib/release/steps.ts";31import type { Layout, Release } from "./lib/release/steps.ts";3260/** The flags the command takes; any other is a typo, refused. */33const FLAGS = new Set([34 "--build",35 "--origin",36 "--publish",
4 unmodified lines
4142const USAGE =43 "bun run release -- [--build] [--upload --stage <dev-…|demo>] [--publish] [--version <semver>] [--origin <url>]";4473/**74 * The release stopped, and it has said why in one line: what failed and75 * what to do (a step's failure, a refusal of the flags or the plan). The76 * runtime then exits 1 without printing it again.77 */45// Already said in one line, so the runtime exits 1 without printing it again.46class Reported extends Schema.TaggedError<Reported>()("Reported", {}) {47 override readonly [Runtime.errorReported] = false;48}4982/** The local platform, as `wrangler dev` serves it. */50const LOCAL_ORIGIN = "http://localhost:8787";5185/** What `bun run release` was asked to do. */52interface Options {53 readonly build: boolean;54 readonly upload: boolean;55 readonly publish: boolean;
1 unmodified line
57 readonly version?: string;58 readonly origin?: string;59}6095/** The command's flags, read; an unknown flag or no step at all is refused. */61const optionsOf = (argv: readonly string[]) =>62 Effect.gen(function* () {63 const unknown = argv.filter(64 (arg) => arg.startsWith("--") && !FLAGS.has(arg.split("=")[0] ?? arg)
33 unmodified lines
9899 return options;100 });101137/** The stage's platform origin, on the workers.dev subdomain bootstrap recorded. */102const stageOrigin = (root: string, stage: Stage) =>103 Effect.gen(function* () {104 const fs = yield* FileSystem.FileSystem;105 const path = yield* Path.Path;
13 unmodified lines
119120 return platformOrigin(stage, subdomain);121 });122159/** Sizes of the release folder's files, and the staged package's files, for the record. */123const report = (layout: Layout, version: string) =>124 Effect.gen(function* () {125 const fs = yield* FileSystem.FileSystem;126 const path = yield* Path.Path;
30 unmodified lines
157 }158 }159 });160198/**199 * Under an agent, the publish is a person's (H2): once the staged package200 * is whole and of this version, say what they run, and end well, since the201 * agent has done all it may.202 */161// Under an agent, the publish is a person's: say what they run, and end well.162const handOver = (163 layout: Layout,164 release: Release,165 markers: readonly string[]
79 unmodified lines
modified:scripts/seed.ts+1 added-69 removed
1/**2 * seed: puts both fictional example projects on a platform, ready for the3 * demo, and changes nothing when run again.4 *5 * bun scripts/seed.ts --world node6 * bunx varlock run --path apps/platform/ -- bun scripts/seed.ts --stage dev-<user>7 *8 * `--world node` serves the Node world on this machine for the run9 * (`apps/platform/test/serve-world.ts`). `--stage <s>` seeds a deployed10 * stage at `--url`, or at the workers.dev origin bootstrap recorded, with11 * tokens only from the env: `SESSION_TOKENS` (token to handle, as the12 * platform's own; `--tokens-env` names another) and `OPERATOR_TOKEN`13 * (`--operator-env`). `--stage demo` also needs `--yes`: the user records14 * on it (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`, which is the19 * operator's `oscabriel/burrow-swarm-2`), so a live run can take a family20 * nobody has touched while the example itself stays fresh for the21 * recording. A name some project has is refused. A copy on a stage22 * is written to the throwaway ledger (`infra/created.ts`, by `seed`) as soon23 * as the platform has made it, with its repo and each layer's repo.24 *25 * Each project is made, and main's first commit pushed, as the operator;26 * each ask is opened as the decider the project's config names, red first27 * on the platform's own Checker; then each layer the example keeps under28 * `layers/` (datekit's maintainers layer) is pushed by that decider to its29 * repo in the private namespace. It prints one line per step, one per30 * project, and a summary. The seed's core lives in `lib/seed.ts`.31 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Envelope } from "@repo/protocol/envelope";3import { Handle, keyOf, ProjectName } from "@repo/protocol/ids";4import {
32 unmodified lines
37 worldTarget,38} from "./lib/seed.ts";39import type { SeededProject, SeedPlan } from "./lib/seed.ts";4072/** The examples the seed knows, in the order it seeds them. */41export const EXAMPLES = ["examples/datekit", "examples/burrow"] as const;4275/** Where a seed goes: the Node world on this machine, or a deployed stage. */43export const SeedWhere = Schema.TaggedUnion({44 Stage: {45 stage: Stage,79 /** The env vars that hold the stage's tokens. */46 tokens: Schema.Struct({ operator: Schema.String, sessions: Schema.String }),47 url: Schema.optionalKey(Schema.String),48 },49 World: {},50});5152export type SeedWhere = typeof SeedWhere.Type;5388/** What `bun scripts/seed.ts` was asked to do. */54export interface SeedOptions {55 readonly where: SeedWhere;91 /** The one project to seed, when not both. */56 readonly only?: string;93 /** The name to seed `only`'s example under, as a fresh copy (`--as`). */57 readonly as?: ProjectName;95 /** Print the versioned envelope instead of lines. */58 readonly json: boolean;59}6099/** The flags the command takes; any other is a typo, refused. */61const FLAGS = new Set([62 "--as",63 "--json",64 "--only",
9 unmodified lines
74 "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]";7576const failed = (reason: string) => new SeedFailed({ reason });77117/** The stage `--stage` names, its tokens' env vars, and where it lives if `--url` says. */78const stageFrom = (argv: readonly string[]) =>79 Effect.gen(function* () {120 // infra's own reading of `--stage`, and its words when it names none.80 const stage = yield* stageOf(argv).pipe(81 Effect.mapError(({ message }) => failed(message))82 );83
24 unmodified lines
108 }),109 });110 });111153/**154 * `--as`'s name, for a copy of the example `--only` names: a project name,155 * and not the example's own. A bare word is the operator's156 * (`burrow-swarm-2` is `oscabriel/burrow-swarm-2`): the operator makes the157 * copy, and makes projects only in their own namespace.158 */112const copyName = (name: string, only: Option.Option<string>) =>113 Effect.gen(function* () {114 if (Option.isNone(only)) {115 return yield* failed(
19 unmodified lines
135 )136 : copy;137 });138186/** The command's flags, read; a seed of `demo` needs `--yes` (H7: the user records on it). */139export const optionsOf = (140 argv: readonly string[]141): Effect.Effect<SeedOptions, SeedFailed> =>142 Effect.gen(function* () {
47 unmodified lines
190 }),191 };192 });193242/**243 * Writes a copy on `stage` to the throwaway ledger, by the seed: the244 * project, its repo in the public namespace, and each layer's repo in the245 * private one, which the platform makes when main lands declaring it.246 */194export const recordCopy = (stage: Stage, plan: SeedPlan, at: DateTime.Utc) => {195 const { layers, projects } = resources(stage);196 const by = "seed";250 // The ledger names what the platform keeps: the project's key, which is251 // its Durable Object's id and its repo's name.197 // The project's key is both its Durable Object's id and its repo's name.198 const key = keyOf(plan.project);199200 const entries: readonly Created[] = [201 { at, by, kind: "project", name: key, stage },
12 unmodified lines
214 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))215 );216};217272/** What `--json` prints for one seeded project. */218const SeededSummary = Schema.Struct({219 asks: Schema.Array(Schema.String),220 decider: Handle,221 main: Schema.optionalKey(Schema.String),
2 unmodified lines
224});225226type SeededSummary = typeof SeededSummary.Type;227283/** What `--json` prints: the versioned envelope over the steps and each project. */228export const SeedEnvelope = Envelope(229 Schema.Struct({230 projects: Schema.Array(SeededSummary),231 steps: Schema.Array(SeedStep),
5 unmodified lines
237 Schema.encodeEffect(Schema.fromJsonString(SeedEnvelope))(envelope),238 Console.log239 ).pipe(Effect.orDie);240297/** Where a stage's platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */241const stageOrigin = (where: (typeof SeedWhere.cases.Stage)["Type"]) =>242 Effect.gen(function* () {243 if (where.url !== undefined) {244 return where.url;
10 unmodified lines
255256 return platformOrigin(where.stage, subdomain);257 });258316/** Where the seed goes, said for a person, and the target there. */259const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>260 SeedWhere.match(where, {261 Stage: (stage) =>262 Effect.map(stageOrigin(stage), (origin) => ({
6 unmodified lines
269 target: worldTarget(plans.map(({ decider }) => decider)),270 }),271 });272331/** One step as the command prints it: `OpenAsk datekit/format-ordinal: done`. */273export const stepLine = ({ _tag, result, target }: SeedStep) =>274 `${_tag} ${target}: ${result}`;275335/** One project as the summary prints it. */276const projectLine = ({277 asks,278 decider,279 main,
6 unmodified lines
286 `decided by ${decider}`,287 ...ratchets.map((name) => `ratchet ${name}`),288 ].join(", ");289350/** What a plan's project holds now, for the summary. */290const summaryOf = (291 plan: SeedPlan,292 held: SeededProject | undefined293): SeededSummary => {
8 unmodified lines
302303 return landed === undefined ? summary : { ...summary, main: landed };304};305367/**368 * `bun scripts/seed.ts …`: plans each example, seeds it on the world or the369 * stage, then prints one line per step, one per project and a summary (or,370 * with `--json`, the versioned envelope). A refusal under `--json` prints371 * the envelope with it, and the command still fails.372 */306export const main = (argv: readonly string[]) =>307 Effect.gen(function* () {308 const options = yield* optionsOf(argv);309 const path = yield* Path.Path;
19 unmodified lines
329330 const say = (line: string) =>331 options.json ? Effect.void : Console.log(line);332400 // A copy on a stage goes to the throwaway ledger once it is made.333 const made = (plan: SeedPlan) =>334 SeedWhere.match(options.where, {335 Stage: ({ stage }) =>336 plan.copyOf === undefined
69 unmodified lines
modified:scripts/smoke.ts+5 added-52 removed
1/**2 * smoke: `bun scripts/smoke.ts --stage dev-<user>|demo [--url <origin>]3 * [--web-url <origin>]`. Read-only probes against a live stage's platform and4 * web; it fails loudly, naming5 * every probe that broke, and prints how long each took.6 * `infra/deploy.ts` runs it last (AGENTS.md principle 11).2 * Usage:3 * bun scripts/smoke.ts --stage <stage> [--url <origin>] [--web-url <origin>]4 * bun scripts/smoke.ts --stage <stage> --loop [--draft] [--as <handle>]5 *8 * The stage's origins are `https://platform-<s>.<subdomain>.workers.dev` and9 * `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` 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, named by `STAGE_SECRETS_FILE`) 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 * `--loop --draft` also has the platform's agent draft an ask on the32 * throwaway project: the answerer proposes a want with `--draft`, the loop33 * waits for the draft to go red first, and the decider accepts it; the34 * landing that opens the ask must disclose the drafter (`Assisted-by:`).35 * It prints the model, the attempts and the time. `--draft` without36 * `--loop` is refused before any request.6 * `--loop` reads `OPERATOR_TOKEN` and `SESSION_TOKENS` (token to handle) from7 * the env, never from an argument.8 */9import { BunRuntime, BunServices } from "@effect/platform-bun";10import { Handle, sameHandle } from "@repo/protocol/ids";11import {
16 unmodified lines
28 subdomainFile,29} from "../infra/stages.ts";30import { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";3161/** `--draft` was given without `--loop`: only the loop has a project to draft on. */32export class DraftNeedsLoop extends Schema.TaggedError<DraftNeedsLoop>()(33 "DraftNeedsLoop",34 { flag: Schema.Literal("--draft") }35) {
16 unmodified lines
52export { DemoStageRefused, LoopFailed, smokeLoop } from "./lib/smoke/loop.ts";5354export type { SmokeLoopReport } from "./lib/smoke/loop.ts";5586/** The loop's answerer when `--as` names none: a person every stage's sessions hold. */56const ANSWERER = "bram";5758const failed = (reason: string) => new LoopFailed({ reason, step: "people" });5991/** A run's name: when it started, to the second, in UTC (`20261013-091500`). */60const runName = Effect.map(DateTime.now, (now) =>61 DateTime.formatIso(now)62 .slice(0, 19)63 .replaceAll(/[-:]/gu, "")
3 unmodified lines
67const decodeSessions = Schema.decodeUnknownEffect(68 Schema.fromJsonString(Schema.Record(Schema.String, Handle))69);70103/**104 * The loop's two people's tokens, from the env: the operator's, and the105 * answerer's by handle from `SESSION_TOKENS`. A missing one fails naming106 * it, and never a token.107 */71const tokensFrom = (answerer: string) =>72 Effect.gen(function* () {73 const decider = yield* Config.Redacted("OPERATOR_TOKEN").pipe(74 Effect.mapError(() =>
28 unmodified lines
103 )104 : { answerer: Redacted.make(token), decider };105 });106144/** Where the stage's platform lives: `--url`, or bootstrap's workers.dev record. */107const originOf = (108 argv: readonly string[],109 stage: Parameters<typeof platformOrigin>[0]110) =>
10 unmodified lines
121 ),122 onSome: (url) => Effect.succeed(url.replace(/\/+$/u, "")),123 });124163/**164 * `bun scripts/smoke.ts --stage <s> --loop [--as <handle>] [--url <origin>]`:165 * refuses demo first, then runs the probes, then the core loop, printing166 * each step's time as it passes and a summary at the end.167 */125const loopMain = (argv: readonly string[]) =>126 Effect.gen(function* () {127 const stage = yield* stageOf(argv);128
33 unmodified lines
162 );163 }164 });165209/**210 * `bun scripts/smoke.ts --stage <s> [--loop [--draft]] …`: the probes, and211 * with `--loop` the core loop after them; `--draft` alone is refused.212 */166export const main = (argv: readonly string[]) =>167 Effect.gen(function* () {168 if (argv.includes("--loop")) {169 return yield* loopMain(argv);
18 unmodified lines
modified:scripts/startup-budget.ts+7 added-57 removed
1/**2 * bytes:check: builds each Worker as a deploy would (`wrangler deploy3 * --dry-run`) and fails when its bundle passes the byte limits: regression4 * alarms, not Cloudflare's upload limit. Startup time is evidence, not a5 * gate; profile it with `wrangler check startup` in the Worker's folder.2 * The limits are regression alarms, not Cloudflare's upload limit. Each Worker3 * has its own, so one Worker's growth never hides in another's headroom.4 *7 * The first limits were Rat Stack's (900,000 entry bytes for its 822,362-byte8 * Worker). The platform Worker outgrew them by carrying more surfaces:9 * 1,513,671 entry bytes once the core loop ran on Cloudflare, of which Effect10 * is about 813,000, the OAuth provider 114,000, isomorphic-git and pako 141,00011 * (the binding's smart-HTTP pushes) and yaml 103,000 (the run-block finder, at12 * each policy refresh). Its startup is 116 to 171 ms live, far under13 * Cloudflare's 1 s limit. The entry limit sits about 10% above that entry, as14 * an alarm for growth. A dynamic `import()` does not shrink the entry:15 * Wrangler's esbuild build has no code splitting and inlines it (checked by a16 * probe), so moving a dependency off the entry takes a module of its own17 * (`find_additional_modules`) or a Worker of its own.5 * A dynamic `import()` does not shrink the entry: Wrangler's esbuild build has6 * no code splitting and inlines it, so moving a dependency off the entry takes7 * a module of its own (`find_additional_modules`) or a Worker of its own.8 *19 * The web Worker is built by Vite first (`vite build`, through the20 * Cloudflare plugin, which writes the deploy config under `dist/`); its dry21 * run then bundles nothing more and copies Vite's modules. Its first22 * measurement was an entry of 723,418 bytes, unminified, under the23 * same limits.24 *25 * Each Worker has limits of its own, so one Worker's growth never hides26 * in another's headroom. Code that is added before anything imports it27 * adds no bytes, so a limit is raised to its ceiling when a wave of work28 * starts, and tightened to about 15% above the measured bundle when the29 * wave ends. Before the code browser, README rendering and drafting the30 * platform's entry was 1,605,405 bytes and the web's JavaScript 2,364,955;31 * they landed under ceilings of 1,900,000 and 4,500,000. Measured once32 * they had landed: the platform's entry (its only module) 1,667,814 bytes,33 * held to 1,900,000 (the ceiling, 14% above) and 1,918,000 of JavaScript;34 * the sandbox's 570,424, held to 656,000; the web's entry 710,962, held to35 * 818,000, and its JavaScript 3,543,318, held to 4,075,000. The web's36 * JavaScript counts the Worker's server modules only: chunks the browser37 * alone loads (Pierre's) are assets. Once the code store, the README on38 * the server and the people page's reasons had landed, no limit was raised:39 * the platform's entry, its only module, measured 1,679,675 (both its40 * limits now 1,900,000, 13% above); the sandbox's 570,582 (656,000, 15%);41 * the web's entry 711,006 (818,000, 15%) and its JavaScript 3,567,68242 * (4,075,000, 14%). Once the web was rebuilt as one shell with the code43 * browser as an app, no limit was raised: the platform's entry measured44 * 1,693,131 (1,900,000, 12%), the sandbox's 570,831 (656,000, 15%), the45 * web's JavaScript 4,074,781 (4,075,000: no room left, until the server46 * build is minified) and the web's entry 696,419, which fell, so its limit47 * is tightened to 801,000 (15%). Minifying the web's server build took48 * its JavaScript to 1,528,378 and its entry to 308,418. Highlighting code49 * on the server (ADR 0027) then added its grammars and `@pierre/diffs/ssr`50 * as chunks off the entry, with no limit raised. Once Workers Cache's51 * entry had landed beside them, the web's JavaScript measured 2,774,68952 * and its entry 309,341, so its limits are tightened to 3,191,000 and53 * 356,000 (15%).9 * The web's JavaScript counts the Worker's server modules only: chunks only10 * the browser loads are assets.11 */12import { BunRuntime, BunServices } from "@effect/platform-bun";13import { Console, Data, Effect, FileSystem, Path, pipe } from "effect";14import { ChildProcess, ChildProcessSpawner } from "effect/process";1559/** A Worker's limits: its entry file's bytes, and all its JavaScript's. */16interface Budget {17 readonly entry: number;18 readonly javascript: number;19}2065/** Each Worker's limits, by its folder. */21export const budgets = {22 "apps/platform": { entry: 1_900_000, javascript: 1_900_000 },23 "apps/sandbox": { entry: 656_000, javascript: 656_000 },24 "apps/web": { entry: 356_000, javascript: 3_191_000 },25} as const satisfies Record<string, Budget>;2672/**73 * Each Worker, the file its `main` bundles to, and the build a dry run needs74 * first, if any: a command in the Worker's own `node_modules/.bin`.75 */27export const workers: readonly Worker[] = [28 { dir: "apps/platform", entry: "worker.js" },29 { dir: "apps/sandbox", entry: "worker.js" },30 { build: ["vite", "build"], dir: "apps/web", entry: "index.js" },
18 unmodified lines
49}> {}5051const env = { WRANGLER_LOG: "error", WRANGLER_SEND_METRICS: "false" };52102/** Runs a Worker's build in its folder, from its own `node_modules/.bin`. */53const runBuild = (54 dir: string,55 [command, ...args]: readonly [string, ...string[]]56) =>
98 unmodified lines
modified:scripts/swarm.ts+1 added-58 removed
1/**2 * swarm: six fictional contributors, on four harnesses, each answer one child3 * of a project's split family on a stage: it plans them, prepares each4 * one's workspace and runs their harnesses.5 *6 * bun scripts/swarm.ts --stage dev-oscabriel --project oscabriel/burrow --dry-run7 * bunx varlock run --path apps/platform/ -- bun scripts/swarm.ts --stage dev-oscabriel8 *9 * `--dry-run` reads the project's open asks anonymously and prints the plan:10 * who answers which ask, on which territory, and the command that would11 * start their harness. It claims nothing, starts nothing and needs no token.12 *13 * Without it, each contributor claims their ask as themselves (their token14 * from `SESSION_TOKENS`, a JSON object from token to handle, as the15 * platform's own), reads the ask's page, gets a workspace with a clone of16 * the claim's fork, and is handed to the run loop, six at once. The17 * run's summary goes to `<swarm>/<run>/agents.json` (`SwarmDir`: the state18 * home's `<slug>/swarm/`, outside every checkout), and each claim's fork to19 * the throwaway ledger (`infra/created.ts`). Tokens reach a contributor's20 * processes only through their env, and no line or JSON this prints holds21 * one. Flags: `lib/swarm/args.ts`.22 *23 * `--view herdr` (for the video) runs from a herdr pane: each24 * harness runs interactively in a pane of its own, with a counter pane of25 * claims, pushes and landings (`lib/swarm/views/herdr.ts`). The loop and26 * its outcomes are the same.27 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { AskListing } from "@repo/protocol/domain/ask";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Envelope } from "@repo/protocol/envelope";
54 unmodified lines
59import type { Ran } from "./lib/swarm/workspace.ts";6061const failed = (reason: string) => new SwarmFailed({ reason });6290/** The env var that holds the stage's people: a JSON object from token to handle. */63const SESSIONS_VARIABLE = "SESSION_TOKENS";6493/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */65const originOf = (options: SwarmOptions) =>66 Option.match(options.url, {67 onNone: () =>68 recordedSubdomain.pipe(
7 unmodified lines
76 ),77 onSome: Effect.succeed,78 });79109/** One CLI command, run from this repo's source with Bun. */80const cli = (81 args: readonly string[],82 env: Readonly<Record<string, string | undefined>>83) => run({ args: [cliEntry, ...args], command: "bun", env });84115/** A refusal list in one line: `NotVouched, AskFull`. */85const tagsOf = (refusals: readonly Refusal[]) =>86 refusals.map(({ _tag }) => _tag).join(", ");87119/** The CLI refused the command: its refusals, for the run's summary. */88class Refused extends Schema.TaggedError<Refused>()("Refused", {89 reason: Schema.String,90 tags: Schema.Array(Schema.String),91}) {
1 unmodified line
93 return this.reason;94 }95}96129/**130 * What one CLI command printed under `--json`, decoded as its envelope: its131 * data, or `Refused` with its refusals. Output that is no envelope fails132 * with what the command printed, `scrub`bed of any secret.133 */97const envelopeOf =98 <A, I>(99 data: Schema.Codec<A, I>,100 what: string,
28 unmodified lines
129const isRefused = Schema.is(Refused);130131const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });132170/** The project's open asks, read anonymously: no token, and no stored login of the user's. */133const listAsks = (origin: string, project: ProjectName) =>134 Effect.gen(function* () {135 const home = `${yield* SwarmDir}/anonymous`;136
9 unmodified lines
146147 return listed.asks;148 });149188/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */150const planLines = (151 plan: SwarmPlan,152 origin: string,153 swarm: string
42 unmodified lines
196 ...nudged,197 ];198};199239/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */200const runName = Effect.map(DateTime.now, (now) =>201 DateTime.formatIso(now)202 .slice(0, 19)203 .replaceAll(/[-:]/gu, "")204 .replace("T", "-")205);206247/** The commit of this repo the swarm runs from. */207const headCommit = Effect.gen(function* () {208 const root = yield* repoRoot;209210 const head = yield* run({
10 unmodified lines
221const decodeSessions = Schema.decodeUnknownEffect(222 Schema.fromJsonString(Schema.Record(Schema.String, Handle))223);224266/**267 * Each contributor's token, by handle, from `SESSION_TOKENS`; a missing268 * person fails before anything is claimed, naming them and never a token.269 */225/** A missing person fails before anything is claimed, naming them and never a token. */226const tokensFor = (handles: readonly Handle[]) =>227 Effect.gen(function* () {228 const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(229 Effect.mapError(() =>
29 unmodified lines
259 `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each to the stage's ${SESSIONS_VARIABLE} secret (in the stage's secrets file, STAGE_SECRETS_FILE), and to the env the swarm runs in, then run the swarm again`260 );261 });262307/** Records a claim's fork in the throwaway ledger, once. */263const recordFork = (stage: Stage, claim: ClaimView) =>264 Effect.gen(function* () {265 const namespace = resources(stage).projects;266
24 unmodified lines
291 ask: Schema.Struct({ id: Schema.NonEmptyString }),292 brief: Schema.NonEmptyString,293});294340/**341 * One contributor, from claim to the run loop: claims their ask as342 * themselves, reads its page, makes their workspace and hands it to343 * `runAgent`. A step that fails ends their run as `failed`, with any344 * refusals the claim met; it never stops the others.345 */295const contributorRun = (input: {296 readonly assignment: Assignment;297 readonly options: SwarmOptions;298 readonly origin: string;
90 unmodified lines
389 workspace: ready.success.workspace,390 });391 });392444/** One contributor's run as the summary prints it. */393const runLine = ({394 ask,395 attempts,396 handle,
13 unmodified lines
410 Schema.encodeEffect(Schema.fromJsonString(schema))(value),411 Console.log412 ).pipe(Effect.orDie);413466/**467 * `bun scripts/swarm.ts …`: plans the run from the project's open asks; with468 * `--dry-run`, prints the plan (or, with `--json`, the `SwarmPlan`) and469 * stops. Otherwise runs every contributor at once and writes the summary.470 */414export const main = (argv: readonly string[]) =>415 Effect.gen(function* () {416 const options = yield* optionsOf(argv);417 const origin = yield* originOf(options);
114 unmodified lines
modified:oxfmt.config.ts+1 added-4 removed
3 unmodified lines
4export default defineConfig({5 ...ultracite,6 ignorePatterns: [7 ...(ultracite.ignorePatterns ?? []),8 // Prose is hand-shaped: the glossary keeps term, definition and _Avoid_ on9 // separate lines, and code spans keep their inner spaces.8 // Prose is hand-shaped.9 "**/*.md",10 "tools/oxlint/anti-slop/**",12 // Generated by `wrangler types` (each Worker's `types` script).11 "**/worker-configuration.d.ts",14 // Each example formats with its own config.12 "examples/**",13 ],14});
modified:oxlint.config.ts+2 added-19 removed
12 unmodified lines
13 ...(core.ignorePatterns ?? []),14 ".claude/**",15 ".codex/**",16 "tools/oxlint/anti-slop/**",17 // Generated by `wrangler types` (each Worker's `types` script).17 "**/worker-configuration.d.ts",19 // Each example lints with its own config.18 "examples/**",21 // shadcn's generated components, as the user's other repos22 // ignore them.19 "apps/web/src/components/ui/**",24 // TanStack Router's generated route tree (`**/*.gen.*` in Ultracite's25 // list too); never committed.20 "apps/web/src/routeTree.gen.ts",21 ],22 jsPlugins: [23 { name: "anti-slop", specifier: "./tools/oxlint/anti-slop/index.ts" },
6 unmodified lines
30 typeAware: true,31 },32 overrides: [33 {40 // The web app: Ultracite's React preset (react, react-perf, jsx-a11y)41 // and its TanStack settings, for apps/web only. An override's plugins42 // add to the base's, and it declares them so its rule options stick43 // (as the vitest override below). The TanStack preset turns44 // `sort-keys` off here: its option objects infer types in source45 // order. shadcn's own lint (`@shadcn/lint`) is not installed.34 // An override declares its plugins so its rule options stick.35 files: ["apps/web/**/*.{ts,tsx}"],36 plugins: react.plugins ?? [],37 rules: {38 ...react.rules,39 ...tanstack.rules,40 },41 },53 // TanStack's file routes: names that encode URLs, and a `Route` whose54 // component reads `Route` back (see the preset).42 ...(tanstack.overrides ?? []).map((override) => ({43 ...override,44 files: override.files.map((glob) => `apps/web/${glob}`),45 })),46 {60 // Ultracite sets the vitest rules in an override for these files, which61 // beats top-level rules. Without `plugins` here, oxlint 1.87 keeps62 // Ultracite's options for the rule and drops ours.47 // Without `plugins` here, oxlint keeps Ultracite's override options and drops ours.48 files: [49 "**/*.{test,spec,test-d,spec-d}.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",50 "**/__tests__/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",51 ],
19 unmodified lines
71 ],72 },73 },74 ],90 // Lint fits Effect, not the other way around: where a rule fights an idiom91 // Effect's own docs use, the rule changes, with its reason beside it.75 rules: {76 "anti-slop-effect/no-manual-effect-error-tag": "error",77 "anti-slop-effect/no-manual-tag-comparison": "error",78 "anti-slop-effect/no-manual-tagged-construction": "error",
60 unmodified lines