Trim comments in scripts/ (seed, swarm, release, import runners)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parent b52e116 · Browse files · 9 files·+61 added−941 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+61 added−941 removed
- other:+61 added−941 removed
Provenance
- Commit
aba93c8- Tree
a04a609- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
b52e116
9 files changed+61 added−941 removed
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- */1 import { ProjectName } from "@repo/protocol/ids";2 import type { ProjectKey } from "@repo/protocol/ids";3 import { ProjectExists } from "@repo/protocol/refusal";4 import {20 unmodified lines25 import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";26 import { examples, planImports } from "./plan.ts";27 import type { ImportExample } from "./plan.ts";28 41-/** Why the run stopped, said for a person; never a token. */29 export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(30 "ImportExamplesFailed",31 { reason: Schema.String }32 ) {3 unmodified lines36 }37 38 const failed = (reason: string) => new ImportExamplesFailed({ reason });39 53-/** Where the imports go: a dev stage, or the Node world on this machine. */40 export const ImportWhere = Schema.TaggedUnion({41 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },42 World: {},43 });44 45 export type ImportWhere = typeof ImportWhere.Type;46 61-/** What `bun scripts/import-examples.ts` was asked to do. */47 export 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 }56 78-/** The platform the imports go to, as the operator. */57 export 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 line73 >;74 }75 >()("scripts/ImportTarget") {}76 102-/**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. */78 export class TagBackfill extends Context.Service<79 TagBackfill,80 {81 readonly backfill: (1 unmodified line83 ) => Effect.Effect<number, ImportExamplesFailed>;84 }85 >()("scripts/TagBackfill") {}86 116-/** One page read to warm an import: where, whether it answered, and what it said. */87 export 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 }92 124-/**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.94 export class Warmer extends Context.Service<95 Warmer,96 {97 readonly warm: (project: ProjectName) => Effect.Effect<readonly WarmRead[]>;2 unmodified lines100 101 const isProjectExists = Schema.is(ProjectExists);102 103 /**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 */108 export const initUntilAnswered = <A extends { readonly landed?: string }, E>(109 call: Effect.Effect<A, E>,110 answered: (error: E) => boolean22 unmodified lines133 134 const USAGE =135 "bun scripts/import-examples.ts --world node | --stage <stage> [--url <origin>] [--web <origin>] [--only <project>] [--tags] [--sources] [--warm] [--dry-run]";136 175-/** The flags the command takes; any other is a typo, refused. */137 const FLAGS = new Set([138 "--dry-run",139 "--only",140 "--sources",6 unmodified lines147 ]);148 149 const decodeProject = Schema.decodeUnknownOption(ProjectName);150 190-/** The command's flags, read; a typo or a stage the table does not declare is refused before anything runs. */151 export const optionsOf = (152 argv: readonly string[]153 ): Effect.Effect<ImportOptions, ImportExamplesFailed> =>154 Effect.gen(function* () {73 unmodified lines228 where,229 };230 });231 272-/**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- */232 const repoLine = (233 stage: Stage,234 key: ProjectKey,235 at: DateTime.Utc5 unmodified lines241 namespace: resources(stage).projects,242 stage,243 });244 289-/** The ledger's two lines for a new import on `stage`: its project, and its repo, by its key. */245 const importLines = (246 stage: Stage,247 key: ProjectKey,248 at: DateTime.Utc4 unmodified lines253 254 const ledgerFailed = ({ message }: PlatformError.PlatformError) =>255 failed(`the ledger (${ledgerPath}): ${message}`);256 302-/** Appends `entries` to the ledger. */257 const record = (entries: readonly Created[]) =>258 Effect.forEach(entries, recordCreated, { discard: true }).pipe(259 Effect.mapError(ledgerFailed)260 );261 308-/** The stage the run records on, if it runs on one. */262 const stageOfWhere = (where: ImportWhere) =>263 ImportWhere.match(where, {264 Stage: ({ stage }) => Option.some(stage),265 World: () => Option.none<Stage>(),266 });267 315-/**316- * `--tags` on one import: its tags pushed from its source when its repo317- * serves none, the ledger told, and a line printed.318- */268 const backfillOne = (269 example: ImportExample,270 tagCount: number,271 stage: Option.Option<Stage>16 unmodified lines288 ` ${example.name}: ${pushed} tags backfilled from ${example.url}`289 );290 });291 343-/** One project warmed, and a line saying how it went. */292 const 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 lines303 : ` warm ${project}: no web to read through`304 );305 });306 359-/**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.308 const recordedImports = (stage: Option.Option<Stage>) =>309 Effect.gen(function* () {310 if (Option.isNone(stage)) {311 return new Set<ProjectName>();19 unmodified lines331 )332 );333 });334 391-/**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.336 const sourceOne = (example: ImportExample) =>337 Effect.gen(function* () {338 const target = yield* ImportTarget;339 4 unmodified lines344 345 yield* Console.log(` ${example.name}: ${outcome}`);346 });347 408-/** The run itself, over a target, a backfill and a web. */348 const run = (options: ImportOptions) =>349 Effect.gen(function* () {350 const target = yield* ImportTarget;351 const listed = yield* target.listProjects;4 unmodified lines356 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));359 421- // 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 lines406 Effect.gen(function* () {407 const made = yield* target.initProject(example);408 const at = yield* DateTime.now;409 473- // 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 lines427 }),428 { discard: true }429 );430 495- // 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 lines455 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`456 );457 });458 525-/**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- */459 export const importExamples = <E, R>(460 argv: readonly string[],461 layersOf: (462 options: ImportOptions7 unmodified linesmodified: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- */1 import { commandDocs } from "@repo/agent-kit/command-doc";2 import { platformSkill } from "@repo/agent-kit/platform";3 import { Brand } from "@repo/brand";4 import { Contracts } from "@repo/protocol/contracts";32 unmodified lines37 } from "../release.ts";38 import type { ReleaseAsset, ReleaseStep } from "../release.ts";39 import { packageReadme } from "./readme.ts";40 65-/** A step could not finish; nothing after it ran. */41 export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(42 "ReleaseFailed",43 { reason: Schema.String, step: Schema.String }44 ) {1 unmodified line46 return `${this.step}: ${this.reason}`;47 }48 }49 75-/** Where a release reads and writes, from the repo root. */50 export 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 }58 59 export const layoutOf = (root: string) =>9 unmodified lines69 root,70 };71 });72 102-/** One release: its version, and the origin its install script fetches from. */73 export 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 }78 111-/** The command a person runs from the repo root to publish the staged package. */79 export const publishCommand = (layout: Layout, path: Path.Path) =>80 `npm publish ${path.relative(layout.root, layout.npm)} --access public`;81 82 const failed = (step: ReleaseStep, reason: string) =>83 new ReleaseFailed({ reason, step });84 118-/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */85 const run = (86 step: ReleaseStep,87 command: string,88 args: readonly string[],17 unmodified lines106 ),107 Effect.asVoid108 );109 144-/** What the release reads of a package manifest. */110 const PackageJson = Schema.fromJsonString(111 Schema.Struct({112 dependencies: Schema.optionalKey(113 Schema.Record(Schema.String, Schema.String)14 unmodified lines128 Effect.flatMap(Schema.decodeEffect(PackageJson)),129 Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))130 );131 167-/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */132 const builtFiles = (layout: Layout) =>133 Effect.gen(function* () {134 const fs = yield* FileSystem.FileSystem;135 const path = yield* Path.Path;10 unmodified lines146 147 return Arr.sort(files, Order.String);148 });149 186-/** `manifest`: the npm package, staged afresh from the build. */150 const stagePackage = (layout: Layout, release: Release) =>151 Effect.gen(function* () {152 const fs = yield* FileSystem.FileSystem;153 const path = yield* Path.Path;71 unmodified lines225 226 return manifest;227 });228 266-/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */229 const writeSkills = (layout: Layout) =>230 Effect.gen(function* () {231 const fs = yield* FileSystem.FileSystem;232 const path = yield* Path.Path;8 unmodified lines241 )242 );243 });244 283-/** `compile`: each target's binary, as the release folder and the platform name it. */245 const collectBinaries = (layout: Layout) =>246 Effect.gen(function* () {247 const fs = yield* FileSystem.FileSystem;248 const path = yield* Path.Path;29 unmodified lines278 })279 );280 });281 321-/** The files a release serves under its version: each binary, and the install script. */282 const releasedFiles = [283 ...targets.map((target) => binaryName(Brand, target)),284 "install.sh",285 ];286 327-/** A file's sha256, as `sha256sum` prints it, and its size. */287 const assetOf = (file: string) =>288 Effect.gen(function* () {289 const fs = yield* FileSystem.FileSystem;290 const crypto = yield* Crypto.Crypto;7 unmodified lines298 .join(""),299 } satisfies ReleaseAsset;300 });301 343-/** Each released file in the release folder, by name. */302 const assetsIn = (layout: Layout) =>303 Effect.flatMap(Path.Path, (path) =>304 Effect.forEach(releasedFiles, (name) =>305 Effect.map(2 unmodified lines308 )309 )310 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));311 354-/** `checksums`: `SHA256SUMS` beside the files it lists. */312 const writeChecksums = (layout: Layout) =>313 Effect.gen(function* () {314 const fs = yield* FileSystem.FileSystem;315 const path = yield* Path.Path;10 unmodified lines326 ["install.sh", "text/x-shellscript; charset=utf-8"],327 ["manifest.json", "application/json"],328 ]);329 373-/** A binary is bytes; the install script and the manifest are text. */330 const contentTypeOf = (file: string) =>331 contentTypes.get(file) ?? "application/octet-stream";332 377-/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */333 const wranglerOf = (layout: Layout, path: Path.Path) =>334 path.join(335 layout.root,336 "apps",2 unmodified lines339 ".bin",340 "wrangler"341 );342 388-/**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.344 const 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 lines369 failed("upload", `wrangler didn't run: ${message}`)370 )371 );372 422-/** What Wrangler prints when a bucket holds no object under a key. */373 const NO_SUCH_KEY = "The specified key does not exist";374 425-/** The manifest the stage's bucket holds, if it holds one. */375 const 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 lines412 )413 );414 });415 467-/** `upload`: the version's files into the stage's own bucket, and the manifest last. */416 const upload = (layout: Layout, release: Release) =>417 Effect.gen(function* () {418 const fs = yield* FileSystem.FileSystem;419 const path = yield* Path.Path;62 unmodified lines482 483 return manifest;484 }).pipe(Effect.scoped);485 538-/** The paths the staged package's manifest names that it lacks. */486 export const missingFromPackage = (layout: Layout, version: string) =>487 Effect.gen(function* () {488 const fs = yield* FileSystem.FileSystem;489 const path = yield* Path.Path;4 unmodified lines494 Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)495 );496 });497 551-/**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- */498 export const publishable = (layout: Layout, release: Release) =>499 Effect.gen(function* () {500 const path = yield* Path.Path;501 16 unmodified lines518 )519 );520 });521 580-/** `publish`: `npm publish` of the staged package, once it is `publishable`. */522 const publish = (layout: Layout, release: Release) =>523 Effect.andThen(524 publishable(layout, release),525 run(3 unmodified lines529 layout.root530 )531 );532 592-/** `installScript`: the install script for this version, fetching from the release's origin. */533 const writeInstallScript = (layout: Layout, release: Release) =>534 Effect.gen(function* () {535 const fs = yield* FileSystem.FileSystem;536 const path = yield* Path.Path;11 unmodified lines548 549 yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);550 });551 612-/** One step, run. */552 export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>553 Match.value(step).pipe(554 Match.when("tsdown", () =>555 run(23 unmodified linesmodified: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 */6 import type { ProjectName } from "@repo/protocol/ids";7 import {8 Config,18 unmodified lines27 import { followCounter, lastHeld } from "./counter.ts";28 import { nothingHeard, Turn } from "./headless.ts";29 import type { Attempted, SwarmView } from "./headless.ts";30 47-/** The counter's pane, below the contributors'. */31 export const COUNTER = "counter";32 50-/**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- */33 export interface Split {34 readonly slot: string;35 readonly from: string;36 readonly direction: "right" | "down";37 readonly ratio: number;38 }39 61-/** The share of the window the contributors keep above the counter strip. */40 const ABOVE_COUNTER = 0.85;41 64-/** `ratio` to three places, as herdr reads it. */42 const share = (ratio: number) => Math.round(ratio * 1000) / 1000;43 67-/**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- */44 export const herdrLayout = (handles: readonly string[]): readonly Split[] => {45 const [first] = handles;46 47 if (first === undefined) {33 unmodified lines81 82 return [counter, ...secondRow, ...columns];83 };84 114-/** How long herdr waits for a harness to be ready for input when it starts one. */85 const START_TIMEOUT_MS = 120_000;86 117-/** `herdr agent start …`: the harness `kind`, named `handle`, in `pane`, with its own flags after `--`. Pure. */87 export const herdrStart = (input: {88 readonly handle: string;89 readonly kind: string;90 readonly pane: string;11 unmodified lines102 "--",103 ...input.argv,104 ];105 137-/**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.107 export const herdrPrompt = (input: {108 readonly handle: string;109 readonly text: string;110 }): readonly string[] => [3 unmodified lines114 input.text,115 "--wait",116 ];117 154-/**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- */118 const HEADLESS_ONLY = {119 amp: {120 switches: ["--stream-json", "--no-archive-after-execute"],121 valued: ["-x"],8 unmodified lines130 { readonly switches: readonly string[]; readonly valued: readonly string[] }131 >132 >;133 176-/** 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.135 const BRIEF = "\u0000brief";136 179-/** How a harness starts interactively: herdr's kind, its flags, and env it needs. */137 export interface Launch {138 readonly kind: string;139 readonly argv: readonly string[];140 readonly env: Readonly<Record<string, string>>;141 }142 143 /**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 */147 export const interactiveLaunch = (input: {148 readonly contributor: Contributor;149 readonly dir: string;35 unmodified lines185 kind,186 };187 };188 237-/** herdr refused a command: its error's code, and what it said. */189 class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {190 code: Schema.String,191 said: Schema.String,192 verb: Schema.String,4 unmodified lines197 }198 199 const isRefused = Schema.is(HerdrRefused);200 250-/** What herdr prints on stderr when it refuses a command. */201 const decodeRefusal = Schema.decodeUnknownOption(202 Schema.fromJsonString(203 Schema.Struct({204 error: Schema.Struct({ code: Schema.String, message: Schema.String }),205 })206 )207 );208 259-/**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- */209 const 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 lines227 })228 );229 });230 285-/** Ends a step on herdr's refusal, saying which. */231 const orFailed = <A, R>(232 effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>233 ): Effect.Effect<A, SwarmFailed, R> =>234 effect.pipe(1 unmodified line236 Effect.fail(new SwarmFailed({ reason: message }))237 )238 );239 295-/** `printed` decoded as `schema`, or why herdr's answer was not what the step needs. */240 const answerOf =241 <A, I>(schema: Schema.Codec<A, I>, what: string) =>242 (printed: string) =>243 Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(6 unmodified lines250 );251 252 const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });253 310-/** `workspace create`: the workspace, and its first pane. */254 const WorkspaceMade = Schema.Struct({255 result: Schema.Struct({256 root_pane: PaneId,257 workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),258 }),259 });260 318-/** `pane split`: the new pane. */261 const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });262 321-/** An agent as herdr sees it: `idle`, `working`, `blocked`, `done` or `unknown`. */263 const AgentSeen = Schema.Struct({264 result: Schema.Struct({265 agent: Schema.Struct({266 agent_status: Schema.String,1 unmodified line268 }),269 }),270 });271 331-/** A question a harness asks before it takes a prompt, and the keys that answer it as the swarm decides. */272 interface StartupQuestion {333- /** Words only that question shows, in herdr's detection text. */273 readonly asks: string;274 readonly keys: readonly string[];275 }276 277 /**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 */281 const STARTUP_QUESTIONS = {282 amp: [],283 "claude-code": [3 unmodified lines287 opencode: [],288 pi: [],289 } as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;290 362-/** How long a harness gets to be ready for its brief once herdr says it is blocked at startup. */291 const STARTUP_WAIT = Duration.minutes(3);292 365-/** Whether herdr sees the agent ready for a prompt. */293 const 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 );300 374-/**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- */301 const pastStartup = (input: {302 readonly handle: string;303 readonly harness: Harness;304 readonly pane: string;47 unmodified lines352 )353 );354 });355 435-/** Names whose values the pane keeps from its own terminal, not the swarm's. */356 const PANE_OWNS = ["TERM", "COLORTERM"];357 438-/** herdr's names in a pane: its integrations report each agent's state with them. */358 const HERDR_NAMES = [359 "HERDR_BIN_PATH",360 "HERDR_ENV",361 "HERDR_PANE_ID",2 unmodified lines364 "HERDR_WORKSPACE_ID",365 ];366 367 /**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 */371 export const paneShell = (input: {372 readonly fifo: string;373 readonly clone: string;14 unmodified lines388 `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,389 "",390 ].join("\n");391 477-/** `env` as the lines a shell sources, less what the pane owns. Pure. */392 const 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("");397 484-/** How long a pane gets to read its env from the pipe. */398 const ENV_READ_WAIT = Duration.seconds(30);399 487-/** How many times a pane whose shell is still starting is asked again, a second apart. */400 const BUSY_RETRIES = 10;401 490-/** A pane script runs only as its owner. */402 const SCRIPT_MODE = 0o700;403 493-/**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- */404 const startIn = (input: {405 readonly contributor: Contributor;406 readonly env: Readonly<Record<string, string>>;407 readonly pane: string;81 unmodified lines489 490 return yield* input.log(started);491 });492 588-/** What an attempt heard from herdr's answer to its prompt (or its refusal of it). */493 const promptHeard = (input: {494 readonly name: string;495 readonly pane: string;496 readonly harness: Harness;34 unmodified lines531 }532 ),533 });534 631-/**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- */535 export 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 lines591 return yield* promptHeard({ answer, harness, name, pane });592 }),593 });594 697-/** A pane's title: who works in it, and on which harness. */595 const titleOf = ({596 handle,597 harness,598 }: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;599 703-/**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.601 export const openHerdrView = (input: {602 readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];603 readonly project: ProjectName;604 readonly origin: string;25 unmodified lines630 "--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 }633 745- // 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 linesmodified: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- */1 import { Brand } from "@repo/brand";2 import type { AnswerView } from "@repo/protocol/domain/answer";3 import { Outcome } from "@repo/protocol/domain/outcome";4 import type { ProjectName } from "@repo/protocol/ids";24 unmodified lines29 import type { SwarmView } from "./views/headless.ts";30 import { scrubbed, SwarmFailed } from "./workspace.ts";31 import type { AgentWorkspace } from "./workspace.ts";32 63-/** One contributor's run: their harness on the brief, then the verdict loop. */33 export 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 >;46 86-/**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- */47 export const startCommand = (input: {48 readonly contributor: Contributor;49 readonly brief: string;50 readonly dir: string;15 unmodified lines66 });67 };68 69 /**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 */73 const KEPT_FROM_SWARM = [74 "HOME",75 "USER",21 unmodified lines97 "SSL_CERT_FILE",98 "NODE_EXTRA_CA_CERTS",99 ] as const;100 148-/** The env a contributor's harness runs in: `KEPT_FROM_SWARM`, then the workspace's. */101 const 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 lines112 ...workspace.env,113 };114 });115 164-/** What the loop does once an attempt's answer is known. */116 export 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 }>;123 124 export const Next = Data.taggedEnum<Next>();125 177-/** Where the loop stands between attempts. */126 export 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 lines140 nudged: false,141 refusals: {},142 };143 197-/** What the loop does next, and where it then stands. */144 export interface Step {145 readonly next: Next;146 readonly progress: Progress;147 }148 203-/** `prior` with each refusal's tag counted once more. */149 const tally = (150 prior: Readonly<Record<string, number>>,151 refusals: readonly Refusal[]152 ) => {7 unmodified lines160 };161 162 const short = (sha: string) => sha.slice(0, 7);163 219-/**220- * The refusals that are the platform's side, not the answer's: the checks221- * could not run, a lane flaked, the repo was busy. Each is retryable (the222- * same work may pass), and none names anything in the change to fix.223- */164+// Retryable refusals that name nothing in the change to fix.165 const platformSide: ReadonlySet<Refusal["_tag"]> = new Set([166 "Flake",167 "RepoBusy",168 "VerifierBlocked",169 ] as const satisfies readonly Refusal["_tag"][]);170 230-/**231- * The prompt that resumes a session after its answer was refused. When232- * every refusal is the platform's side, it says so, and asks for the same233- * work again rather than a fix: an empty commit, pushed.234- */171 export const refusalPrompt = (input: {172 readonly answer: Pick<AnswerView, "ask" | "head">;173 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;174 readonly project: string;19 unmodified lines194 ...what,195 ].join("\n");196 };197 262-/**263- * The prompt that resumes a session that pushed no new answer: none at all,264- * or none since the head of the last one status showed (`since`).265- */198 export const nudgePrompt = (input: {199 readonly ask: string;200 readonly remote: string;201 readonly project: string;10 unmodified lines212 `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,213 ].join("\n");214 215 /**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 */219 export 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 lines318 WaitingOnParent: () => done("waiting", judged),319 });320 };321 397-/** The tags of the refusals status shows for the ask's latest answer. */322 const tagsOf = ({ answer }: AskStatus) =>323 Option.match(answer, {324 onNone: () => "",325 onSome: ({ outcome }) =>1 unmodified line327 ? outcome.refusals.map(({ _tag }) => _tag).join(", ")328 : "",329 });330 407-/** A count of tokens, in thousands when large. */331 const tokens = (count: number) =>332 count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;333 334 export const runAgent: RunAgent = (input) =>8 unmodified lines343 344 const say = (line: string) =>345 Console.error(scrubbed(`${handle}: ${line}`, workspace));346 424- /**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 linesmodified: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- */1 import { Brand } from "@repo/brand";2 import type { ClaimView } from "@repo/protocol/domain/claim";3 import {4 Config,10 unmodified lines15 16 import { runDir } from "./results.ts";17 import type { Contributor } from "./roster.ts";18 27-/** The swarm could not do a step; the reason says which, and never holds a token. */19 export class SwarmFailed extends Schema.TaggedError<SwarmFailed>()(20 "SwarmFailed",21 { reason: Schema.String }22 ) {1 unmodified line24 return this.reason;25 }26 }27 37-/** Where one contributor works, and the env their harness runs in. */28 export 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 }34 48-/** The env names the CLI reads, spelled from the brand (`apps/cli/src/credentials.ts`). */35 const SLUG = Brand.slug.toUpperCase();36 51-/** The person's platform token: the only identity the CLI and git present. */37 export const TOKEN_VARIABLE = `${SLUG}_TOKEN`;38 54-/** The platform the CLI calls, with the token or, without one, as anyone. */39 export const URL_VARIABLE = `${SLUG}_URL`;40 57-/** The profile the CLI would read instead of the env's token. */41 const PROFILE_VARIABLE = `${SLUG}_PROFILE`;42 60-/** The CLI's process entry in this repo, run from source with Bun. */43 export const cliEntry = decodeURIComponent(44 new URL("../../../apps/cli/src/bin.ts", import.meta.url).pathname45 );46 65-/** A one-word shell argument: `'…'`, with any `'` inside closed and escaped. */47 export const shellQuoted = (word: string) =>48 /^[\w./:@%+=,-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;49 69-/** A shim in `bin/`: a shell script that runs the CLI from source with `args` first. */50 const 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");57 78-/** Owner, group and everyone may run a shim; only the owner writes it. */58 const SHIM_MODE = 0o755;59 81-/** The workspace's config folder holds the CLI's credentials: owner only. */60 const CONFIG_MODE = 0o700;61 84-/**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.63 export const personEnv = (input: {64 readonly configHome: string;65 readonly platformUrl: string;66 readonly token: Redacted.Redacted;2 unmodified lines69 [URL_VARIABLE]: input.platformUrl,70 XDG_CONFIG_HOME: input.configHome,71 });72 99-/**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- */73 export const anonymousEnv = (input: {74 readonly configHome: string;75 readonly platformUrl: string;76 }) => ({2 unmodified lines79 [URL_VARIABLE]: input.platformUrl,80 XDG_CONFIG_HOME: input.configHome,81 });82 113-/** `text` with every secret value of `env` (the names in `redacted`) blanked out. */83 export const scrubbed = (84 text: string,85 workspace: Pick<AgentWorkspace, "env" | "redacted">86 ) => {9 unmodified lines96 97 return clean;98 };99 131-/** All a byte stream says, as text. */100 const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>101 bytes.pipe(Stream.decodeText(), Stream.mkString);102 135-/** How a process ended, and what it printed. */103 export interface Ran {104 readonly code: number;105 readonly stdout: string;106 readonly stderr: string;107 }108 142-/** `command args` in `cwd` with `env` over the swarm's own: how it ended, and what it printed. */109 export const run = (input: {110 readonly command: string;111 readonly args: readonly string[];112 readonly cwd?: string;25 unmodified lines138 )139 );140 141 /**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 */145 export const ForkWait = Context.Reference<Duration.Duration>("swarm/ForkWait", {146 defaultValue: () => Duration.seconds(2),147 });148 149 export const FORK_TRIES = 30;150 189-/** git's words when the gateway answers 404: the repo is not there (yet). */151 const NOT_FOUND = /^fatal: repository '.*' not found$/mu;152 192-/** A clone that failed only because the fork is not made yet. */153 const forkNotMadeYet = (ran: Ran) =>154 ran.code !== 0 && NOT_FOUND.test(ran.stderr);155 156 /**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 */161 export const prepareWorkspace = (input: {162 readonly run: string;163 readonly contributor: Contributor;104 unmodified linesmodified: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- */1 import type { Brand } from "@repo/brand";2 import { detectHarness } from "@repo/protocol/audit";3 import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";4 5 import { ReleaseManifest } from "../../apps/platform/src/releases.ts";6 import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";7 import { installScriptFor } from "./release/install-script.ts";8 14-// --- What a release builds for -----------------------------------------------15-16-/** The machines a release builds a binary for, as Bun names them. */9 export type Target = "bun-linux-x64" | "bun-darwin-arm64";10 11 export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];12 21-/** A target as the CLI's build and the platform name it, without Bun's prefix: `linux-x64`. */13 export const machineOf = (target: Target) => target.replace(/^bun-/u, "");14 24-/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */15 export const binaryName = (brand: typeof Brand, target: Target) =>16 `${brand.slug}-${machineOf(target)}`;17 28-// --- The npm package's dependencies ------------------------------------------29-18 /**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 */23 const STATEMENT =24 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;25 42-/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */26 const packageOf = (specifier: string) =>27 specifier28 .split("/")29 .slice(0, specifier.startsWith("@") ? 2 : 1)30 .join("/");31 49-/** Whether `specifier` names a package, not a file or a runtime built-in. */32 const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);33 52-/**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. */35 export const importedPackages = (source: string): readonly string[] =>36 Arr.sort(37 Arr.dedupe(38 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {4 unmodified lines43 ),44 Order.String45 );46 69-/**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. */48 const PI_HOST = "@earendil-works/pi-coding-agent";49 75-/**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- */50 export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {51 packages: Schema.Array(Schema.String),52 }) {}53 84-/** The version a declared specifier pins, with `catalog:` read from the catalog. */54 const pinOf = (55 specifier: string | undefined,56 catalogued: string | undefined57 ) => {3 unmodified lines61 ? undefined62 : version;63 };64 96-/**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- */65 export const pinnedDependencies = (input: {66 readonly imported: readonly string[];67 readonly declared: Readonly<Record<string, string>>;68 readonly catalog: Readonly<Record<string, string>>;24 unmodified lines93 )94 );95 };96 135-// --- The npm package's manifest ----------------------------------------------136-137-/** The command line, under Node or Bun: the CLI's npm build. */97 const BIN = "./dist/bin.js";98 140-/** A library entry: its code, and the types tsgo declared for it. */99 interface LibraryEntry {100 readonly types: string;101 readonly default: string;102 }103 146-/** The npm package's manifest, as `npm publish` reads it. */104 export interface PublishManifest {105 readonly bin: Readonly<Record<string, string>>;106 readonly dependencies: Readonly<Record<string, string>>;107 readonly description: string;14 unmodified lines122 readonly type: "module";123 readonly version: string;124 }125 169-/** A library entry of the CLI's build, by the name it is published under. */126 const 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 });132 133 /**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 */137 export const publishManifest = (138 brand: typeof Brand,139 input: {20 unmodified lines160 type: "module",161 version: input.version,162 });163 213-/** A path in the package, as the manifest writes it, from the package's root. */164 const fromRoot = (file: string) =>165 file.replace(/^\.\//u, "").replace(/\/$/u, "");166 217-/**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- */167 export const namedFiles = (manifest: PublishManifest): readonly string[] =>168 Arr.sort(169 Arr.dedupe(170 [8 unmodified lines179 ),180 Order.String181 );182 239-// --- The plan ----------------------------------------------------------------240-241-/** One step of a release, in the order a release runs them. */183 export type ReleaseStep =184 | "tsdown"185 | "manifest"186 | "copySkills"2 unmodified lines189 | "checksums"190 | "upload"191 | "publish";192 252-/** `npm publish` runs only when a person runs the release (H2). */193 export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(194 "PublishNeedsAPerson",195 { markers: Schema.Array(Schema.String) }196 ) {}197 258-/**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.199 export const agentMarkers = (200 env: Readonly<Record<string, string | undefined>>201 ): readonly string[] =>202 Arr.sort(2 unmodified lines205 ),206 Order.String207 );208 273-/** What a build makes: the CLI's build, then the package and the binaries beside it. */209 const BUILD: readonly ReleaseStep[] = [210 "tsdown",211 "manifest",212 "copySkills",213 "compile",214 ];215 281-/** What a build or an upload ends with: the install script for its origin, and the digests. */216 const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];217 284-/** What `bun run release` was asked to do, and the env it runs in. */218 export 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 }225 293-/**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- */226 const stepsOf = (227 flags: ReleaseFlags228 ): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {229 if (flags.stage === undefined && flags.upload) {11 unmodified lines241 ...(flags.publish ? (["publish"] as const) : []),242 ]);243 };244 320-/**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- */245 export const releasePlan = (246 flags: ReleaseFlags247 ): Result.Result<248 readonly ReleaseStep[],5 unmodified lines254 ? Result.fail(new PublishNeedsAPerson({ markers }))255 : stepsOf(flags);256 };257 338-/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */258 export 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 }262 263 /**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 */267 export const releaseRun = (268 flags: ReleaseFlags269 ): Result.Result<ReleaseRun, NoStage | UnknownStage> => {4 unmodified lines274 (steps) => ({ handOver, steps })275 );276 };277 363-// --- The version -------------------------------------------------------------364-365-/**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- */278 export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(279 "VersionNeeded",280 { given: Schema.optionalKey(Schema.String) }281 ) {3 unmodified lines285 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;286 }287 }288 380-/**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- */289 const served = (version: string) =>290 Option.isSome(291 Schema.decodeOption(ReleaseManifest)({292 latest: version,293 versions: { [version]: { assets: {} } },294 })295 );296 392-/**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- */297 const UNRELEASED = "0.0.0";298 400-/**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- */299 export const releaseVersion = (input: {300 readonly version?: string;301 readonly upload: boolean;302 readonly publish: boolean;8 unmodified lines311 ? Result.succeed(input.version)312 : Result.fail(new VersionNeeded({ given: input.version }));313 };314 420-// --- The platform's release storage ------------------------------------------421-422-/** One file of a release, as the manifest lists it. */315 export interface ReleaseAsset {316 readonly sha256: string;317 readonly bytes: number;318 }319 320 export { ReleaseManifest } from "../../apps/platform/src/releases.ts";321 430-/**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- */322 export const releaseManifest = (input: {323 readonly version: string;324 readonly previous: ReleaseManifest | undefined;325 readonly assets: Readonly<Record<string, ReleaseAsset>>;4 unmodified lines330 [input.version]: { assets: input.assets },331 },332 });333 448-/**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- */334 export class VersionReleased extends Schema.TaggedError<VersionReleased>()(335 "VersionReleased",336 { version: Schema.String }337 ) {1 unmodified line339 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;340 }341 }342 462-/** Two releases hold the same files, by name, size and digest. */343 const sameAssets = (344 one: Readonly<Record<string, ReleaseAsset>>,345 other: Readonly<Record<string, ReleaseAsset>>346 ) =>2 unmodified lines349 ([name, { bytes, sha256 }]) =>350 other[name]?.bytes === bytes && other[name]?.sha256 === sha256351 );352 473-/**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- */353 export const unreleased = (input: {354 readonly version: string;355 readonly previous: ReleaseManifest | undefined;356 readonly assets: Readonly<Record<string, ReleaseAsset>>;4 unmodified lines361 ? Result.void362 : Result.fail(new VersionReleased({ version: input.version }));363 };364 489-/** Where the manifest is kept: every release file is under `releases/`. */365 export const MANIFEST_KEY = "releases/manifest.json";366 492-/** Files by name, sorted (`Order.String`), as both sides list them. */367 const byName = <A>(record: Readonly<Record<string, A>>) =>368 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);369 496-/**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- */370 export const checksumsFile = (371 assets: Readonly<Record<string, ReleaseAsset>>372 ): string =>373 byName(assets)374 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)375 .join("");376 508-/**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- */378 export const uploads = (input: {379 readonly version: string;380 readonly files: readonly string[];381 }): readonly { readonly file: string; readonly key: string }[] => [3 unmodified lines385 })),386 { file: "manifest.json", key: MANIFEST_KEY },387 ];388 524-// --- The install script ------------------------------------------------------525-526-/**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- */389 export const installScript = (input: {390 readonly brand: typeof Brand;391 readonly version: string;392 readonly baseUrl: string;1 unmodified linemodified: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- */1 import { Brand } from "@repo/brand";2 import { Client, Contracts } from "@repo/protocol/contracts";3 import type { AskListing } from "@repo/protocol/domain/ask";4 import { LayerManifest } from "@repo/protocol/domain/visibility";33 unmodified lines38 import { RpcClient, RpcSerialization } from "effect/rpc";39 40 import { repoRoot } from "../../infra/stages.ts";41 68-/**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- */42 export class SeedFailed extends Schema.TaggedError<SeedFailed>()("SeedFailed", {43 reason: Schema.String,44 refusals: Schema.optionalKey(Schema.NonEmptyArray(Refusal)),45 }) {1 unmodified line47 return this.reason;48 }49 }50 81-/** One file of a seeded tree, as its bytes. */51 export interface SeedFile {52 readonly path: RepoPath;53 readonly content: Uint8Array;54 }55 87-/** One file an ask opens with, as text (the `openAsk` contract's `ConfigFile`). */56 export interface AskFile {57 readonly path: RepoPath;58 readonly content: string;59 }60 93-/** One ask the seed opens: its id, its kind's name, and the files it opens with. */61 export 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 }66 67 /**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 */71 export 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 }77 118-/**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- */78 export 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 }84 133-/** What the seed puts on a platform for one example project. */85 export 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 }94 152-/** Where the asks live in an example: the config folder's `asks/`. */95 const ASKS = `${Brand.configDir}/asks/`;96 155-/**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. */98 const LAYERS = "layers/";99 161-/** A known-bad change a layer keeps: `known-bad/<area>.patch`. */100 const KNOWN_BAD = /^known-bad\/(?<area>[^/]+)\.patch$/u;101 164-/** A layer's manifest in the JSON form the platform reads. */102 const MANIFEST_FILE = `${Brand.configDir}/layer.json`;103 167-// Where a patch's diff starts; the words before it say what it breaks.104 const DIFF_START = /^(?:diff --git |--- )/mu;105 170-/** The config file that names the deciders and the ratchets. */106 const PROJECT_FILE = `${Brand.configDir}/project.ts`;107 173-/** An ask's file: `asks/<id>.ask.ts`, directly in the asks folder. */108 const ASK_FILE = /^(?<id>[^/]+)\.ask\.ts$/u;109 176-/**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. */111 const CLOSED_ENV = /^\.env(?:\.local|\.[^/]+\.local)?$/u;112 182-// An ask file calls its kind's builder: `kinds.fix.ask({ … })`.113 const KIND = /\bkinds\.(?<kind>\w+)\.ask\(/u;114 185-// 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.116 const CHECK_PATH = /\bpath:\s*"(?<path>[^"]+)"/u;117 191-// The deciders for the whole tree: `deciders: { "**": ["ines-v", …] }`.118 const WHOLE_TREE_DECIDER = /"\*\*"\s*:\s*\[\s*"(?<handle>[^"]+)"/u;119 194-// Each ratchet the config declares: `"<name>": check.ratchet.count(…)`.120 const RATCHET = /"(?<name>[^"]+)"\s*:\s*check\.ratchet\./gu;121 122 const failed = (reason: string) => new SeedFailed({ reason });123 199-/** `raw` decoded by `schema`, or the seed fails saying what it was. */124 const 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 );130 207-/** The paths git tracks under `dir`, relative to it, in git's order. */131 const trackedIn = (root: string, dir: string) =>132 Effect.gen(function* () {133 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;134 12 unmodified lines147 .filter((path) => path.startsWith(`${dir}/`))148 .map((path) => path.slice(dir.length + 1));149 });150 228-/** One file of the example as text, or the seed fails naming it. */151 const textOf = (fs: FileSystem.FileSystem, at: string, path: string) =>152 fs153 .readFileString(at)154 .pipe(Effect.mapError(() => failed(`can't read ${path}`)));155 234-/**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.157 const 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 lines166 GIT_TERMINAL_PROMPT: "0",167 LC_ALL: "C",168 });169 252-/** All a byte stream says, as text. */170 const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>171 bytes.pipe(Stream.decodeText(), Stream.mkString);172 256-/**257- * git with `args` in `cwd` under `env`, after the `-c` settings in258- * `settings`: how it ended, and what it printed.259- */173 const runGit = (174 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],175 cwd: string,176 args: readonly string[],22 unmodified lines199 failed(`git ${args[0] ?? ""} didn't run: ${message}`)200 )201 );202 290-/** What git printed, when it ended well; else the seed fails with what it said. */203 const okOutput =204 (args: readonly string[]) =>205 ({ code, stderr, stdout }: Effect.Success<ReturnType<typeof runGit>>) =>206 code === 01 unmodified line208 : Effect.fail(209 failed(`git ${args.join(" ")} exited ${code}: ${stderr.trim()}`)210 );211 300-/** `files` written under `dir`, each at its path. */212 const writeTree = (213 fs: FileSystem.FileSystem,214 path: Path.Path,215 dir: string,10 unmodified lines226 }).pipe(Effect.mapError(() => failed(`can't write ${file} to seed`))),227 { discard: true }228 );229 319-/**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- */230 const 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 lines291 } satisfies KnownBadStep;292 })293 );294 392-/** A layer's repo in the private namespace: `<project's key>--<layer>`. */295 const layerRepo = (project: ProjectName, layer: LayerName) =>296 RepoName.make(`${keyOf(project)}--${layer}`);297 298 const decodeManifest = Schema.decodeEffect(299 Schema.fromJsonString(LayerManifest)300 );301 400-/**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- */302 const layersOf = (input: {303 readonly decider: Handle;304 readonly folder: string;305 readonly initFiles: SeedPlan["initFiles"];64 unmodified lines370 failed(`${named} is no layer manifest: ${error.message}`)371 )372 );373 478- // By area, as the patches are named; compared in any order.374 const made = knownBad.map(({ commit }) => commit);375 376 if (manifest.layer !== layer) {377 return yield* failed(19 unmodified lines397 })398 );399 });400 506-/**507- * The plan for the example at `dir` (relative to the repo root, as508- * `examples/datekit`): the project is named for its folder.509- */401 export const planSeed = (dir: string) =>402 Effect.gen(function* () {403 const fs = yield* FileSystem.FileSystem;404 const path = yield* Path.Path;84 unmodified lines489 const held = new Set(490 asks.flatMap(({ files }) => files.map((file) => String(file.path)))491 );492 602- // 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 lines524 ratchets,525 } satisfies SeedPlan;526 });527 637-/**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- */528 export const renameSeedPlan = (plan: SeedPlan, as: ProjectName): SeedPlan => ({529 ...plan,530 copyOf: plan.copyOf ?? plan.project,531 layers: plan.layers.map((layer) => ({2 unmodified lines534 })),535 project: as,536 });537 653-/** Whether a run did a step, or found it done before. */538 export const StepResult = Schema.Literals(["done", "already"]);539 540 export type StepResult = typeof StepResult.Type;541 542 const step = { result: StepResult, target: Schema.String };543 660-/**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- */544 export const SeedStep = Schema.TaggedUnion({545 Init: step,546 Layer: step,547 OpenAsk: step,1 unmodified line549 });550 551 export type SeedStep = typeof SeedStep.Type;552 673-/** What a platform gives the seed: a world, or a stage. */553 export 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 lines591 const isRefusal = Schema.is(Refusal);592 593 const isProjectExists = Schema.is(ProjectExists);594 736-/** What a call to the platform fails with: a refusal, or the transport's own error. */595 interface CallFailure {596 readonly _tag: string;597 readonly message: string;598 }599 742-/**743- * A call that failed: a refusal, said as `explain` says it everywhere, or744- * a platform that didn't answer.745- */600 const failedCall = (call: string) => (error: CallFailure) =>601 isRefusal(error)602 ? new SeedFailed({603 reason: `${call} was refused: ${explain([error])2 unmodified lines606 refusals: [error],607 })608 : failed(`${call} got no answer from the platform: ${error.message}`);609 756-/** main, as git names it. */610 export const MAIN_REF = "refs/heads/main";611 759-/**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- */612 export const ready = (613 plans: readonly SeedPlan[]614 ): Effect.Effect<void, SeedFailed, SeedTarget> =>615 Effect.flatMap(Effect.service(SeedTarget), (target) =>2 unmodified lines618 ...plans.map(({ decider }) => decider),619 ])620 );621 774-/** What a platform holds for one seeded project. */622 export 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 }627 783-/** What the platform holds now for each project of `plans`, read as each one's decider. */628 export const seeded = (629 plans: readonly SeedPlan[]630 ): Effect.Effect<readonly SeededProject[], SeedFailed, SeedTarget> =>631 Effect.flatMap(Effect.service(SeedTarget), (target) =>18 unmodified lines650 })651 )652 );653 810-/** How often, and how many times, the seed asks again for a layer's repo. */654 const LAYER_WAIT = { every: Duration.seconds(1), times: 30 } as const;655 813-/** The platform has not made a layer's repo yet. */656 class NotMadeYet extends Schema.TaggedError<NotMadeYet>()("NotMadeYet", {657 repo: RepoName,658 }) {}659 818-/**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.661 const seedLayer = (662 layer: LayerStep,663 decider: Handle664 ): Effect.Effect<SeedStep, SeedFailed, SeedTarget> =>63 unmodified lines728 729 return reported("done");730 });731 896-/**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. */733 export 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 lines808 ];809 })810 );811 980-/**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- */812 export const runSeed = (813 plan: SeedPlan814 ): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>815 runSeedWith(plan, () => Effect.void);816 994-// ------------------------------------------------------------ the platform995-996-/** A platform the seed reaches over HTTP and git. */817 export 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 }823 1008-/** The refs `git ls-remote` lists, one a line: `<sha>\t<ref>`. */824 const refsIn = (listed: string) =>825 Effect.map(826 Effect.forEach(827 listed.split("\n").filter((line) => line.length > 0),10 unmodified lines838 ),839 (refs): ReadonlyMap<string, CommitSha> => new Map(refs)840 );841 1027-// What git says of a repo the server doesn't serve.842 const NOT_SERVED = /\bnot found\b|\b404\b/u;843 1030-/** 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.845 const TOKEN_VAR = "SEED_GIT_TOKEN";846 1033-/** git's credential helper for one person: their handle, and the token from git's env. */847 const helperFor = (handle: Handle) =>848 `!f() { test "$1" = get || exit 0; echo username=${handle}; echo "password=$${TOKEN_VAR}"; }; f`;849 1037-/** git's env as `handle`: `authorEnv`'s, and their token for the helper. */850 const gitEnv = (handle: Handle, token: Redacted.Redacted) => ({851 ...authorEnv(handle),852 [TOKEN_VAR]: Redacted.value(token),853 });854 1043-/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */855 const clientAt = (856 origin: string,857 token: Redacted.Redacted858 ): Layer.Layer<Client> =>8 unmodified lines867 ),868 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])869 );870 1060-/**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- */871 export const platformTarget = (872 platform: Platform873 ): Layer.Layer<874 SeedTarget,6 unmodified lines881 const fs = yield* FileSystem.FileSystem;882 const path = yield* Path.Path;883 const { origin } = platform;884 1078- // 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 lines907 ? Effect.fail(missing(lacking))908 : Effect.void;909 };910 1106- /**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 lines921 `credential.helper=${helperFor(as)}`,922 ])923 );924 1124- /** 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));927 1128- // 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 lines984 .map((file) => RepoPath.make(file));985 })986 );987 1189- /** 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 lines1021 )((yield* gitOk(as, dir, ["rev-parse", "HEAD"])).trim());1022 })1023 );1024 1227- // 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: Handle22 unmodified lines1052 });1053 })1054 );1055 1259-// --------------------------------------------------------------- the world1260-1261-/** The file that serves the Node world as a process, from the repo root. */1056 const SERVE_WORLD = "apps/platform/test/serve-world.ts";1057 1264-/** How long the world has to start serving. */1058 const WORLD_START = Duration.seconds(60);1059 1267-/** The line the world prints once it serves. */1060 const decodeServing = Schema.decodeUnknownOption(1061 Schema.fromJsonString(Schema.Struct({ origin: Schema.String }))1062 );1063 1272-/**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. */1065 export const worldOperator = Handle.make("oscabriel");1066 1279-/** A token for `handle` in a world on this machine: no secret, never leaves it. */1067 const worldToken = (handle: Handle) =>1068 Redacted.make(`${handle.toLowerCase()}-seed-world-token-0123456789abcdef`);1069 1283-/**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- */1070 export const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1071 Effect.gen(function* () {1072 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1073 const root = yield* repoRoot;20 unmodified lines1094 failed(`bun ${SERVE_WORLD} didn't start: ${error.message}`)1095 )1096 );1097 1316- // 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>();1101 1102 yield* Stream.decodeText(child.stderr).pipe(38 unmodified lines1141 )1142 );1143 });1144 1364-/**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- */1145 export const worldTarget = (1146 people: readonly Handle[]1147 ): Layer.Layer<1148 SeedTarget,16 unmodified lines1165 });1166 })1167 );1168 1392-// --------------------------------------------------------------- a stage1393-1394-/** Where a stage's tokens come from: the env vars that hold them. */1169 export 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 }1173 1174 const decodeSessions = Schema.decodeUnknownEffect(1175 Schema.fromJsonString(Schema.Record(Schema.String, Handle))1176 );1177 1406-/**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- */1178 export const stageTarget = (1179 origin: string,1180 tokens: StageTokens1181 ): Layer.Layer<47 unmodified linesmodified: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- */1 import { BunRuntime, BunServices } from "@effect/platform-bun";2 import { Envelope } from "@repo/protocol/envelope";3 import { Handle, keyOf, ProjectName } from "@repo/protocol/ids";4 import {32 unmodified lines37 worldTarget,38 } from "./lib/seed.ts";39 import type { SeededProject, SeedPlan } from "./lib/seed.ts";40 72-/** The examples the seed knows, in the order it seeds them. */41 export const EXAMPLES = ["examples/datekit", "examples/burrow"] as const;42 75-/** Where a seed goes: the Node world on this machine, or a deployed stage. */43 export 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 });51 52 export type SeedWhere = typeof SeedWhere.Type;53 88-/** What `bun scripts/seed.ts` was asked to do. */54 export 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 }60 99-/** The flags the command takes; any other is a typo, refused. */61 const FLAGS = new Set([62 "--as",63 "--json",64 "--only",9 unmodified lines74 "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]";75 76 const failed = (reason: string) => new SeedFailed({ reason });77 117-/** The stage `--stage` names, its tokens' env vars, and where it lives if `--url` says. */78 const 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 lines108 }),109 });110 });111 153-/**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- */112 const copyName = (name: string, only: Option.Option<string>) =>113 Effect.gen(function* () {114 if (Option.isNone(only)) {115 return yield* failed(19 unmodified lines135 )136 : copy;137 });138 186-/** The command's flags, read; a seed of `demo` needs `--yes` (H7: the user records on it). */139 export const optionsOf = (140 argv: readonly string[]141 ): Effect.Effect<SeedOptions, SeedFailed> =>142 Effect.gen(function* () {47 unmodified lines190 }),191 };192 });193 242-/**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- */194 export 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);199 200 const entries: readonly Created[] = [201 { at, by, kind: "project", name: key, stage },12 unmodified lines214 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))215 );216 };217 272-/** What `--json` prints for one seeded project. */218 const SeededSummary = Schema.Struct({219 asks: Schema.Array(Schema.String),220 decider: Handle,221 main: Schema.optionalKey(Schema.String),2 unmodified lines224 });225 226 type SeededSummary = typeof SeededSummary.Type;227 283-/** What `--json` prints: the versioned envelope over the steps and each project. */228 export const SeedEnvelope = Envelope(229 Schema.Struct({230 projects: Schema.Array(SeededSummary),231 steps: Schema.Array(SeedStep),5 unmodified lines237 Schema.encodeEffect(Schema.fromJsonString(SeedEnvelope))(envelope),238 Console.log239 ).pipe(Effect.orDie);240 297-/** Where a stage's platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */241 const stageOrigin = (where: (typeof SeedWhere.cases.Stage)["Type"]) =>242 Effect.gen(function* () {243 if (where.url !== undefined) {244 return where.url;10 unmodified lines255 256 return platformOrigin(where.stage, subdomain);257 });258 316-/** Where the seed goes, said for a person, and the target there. */259 const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>260 SeedWhere.match(where, {261 Stage: (stage) =>262 Effect.map(stageOrigin(stage), (origin) => ({6 unmodified lines269 target: worldTarget(plans.map(({ decider }) => decider)),270 }),271 });272 331-/** One step as the command prints it: `OpenAsk datekit/format-ordinal: done`. */273 export const stepLine = ({ _tag, result, target }: SeedStep) =>274 `${_tag} ${target}: ${result}`;275 335-/** One project as the summary prints it. */276 const projectLine = ({277 asks,278 decider,279 main,6 unmodified lines286 `decided by ${decider}`,287 ...ratchets.map((name) => `ratchet ${name}`),288 ].join(", ");289 350-/** What a plan's project holds now, for the summary. */290 const summaryOf = (291 plan: SeedPlan,292 held: SeededProject | undefined293 ): SeededSummary => {8 unmodified lines302 303 return landed === undefined ? summary : { ...summary, main: landed };304 };305 367-/**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- */306 export const main = (argv: readonly string[]) =>307 Effect.gen(function* () {308 const options = yield* optionsOf(argv);309 const path = yield* Path.Path;19 unmodified lines329 330 const say = (line: string) =>331 options.json ? Effect.void : Console.log(line);332 400- // 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 === undefined69 unmodified linesmodified: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- */1 import { BunRuntime, BunServices } from "@effect/platform-bun";2 import { AskListing } from "@repo/protocol/domain/ask";3 import { ClaimView } from "@repo/protocol/domain/claim";4 import { Envelope } from "@repo/protocol/envelope";54 unmodified lines59 import type { Ran } from "./lib/swarm/workspace.ts";60 61 const failed = (reason: string) => new SwarmFailed({ reason });62 90-/** The env var that holds the stage's people: a JSON object from token to handle. */63 const SESSIONS_VARIABLE = "SESSION_TOKENS";64 93-/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */65 const originOf = (options: SwarmOptions) =>66 Option.match(options.url, {67 onNone: () =>68 recordedSubdomain.pipe(7 unmodified lines76 ),77 onSome: Effect.succeed,78 });79 109-/** One CLI command, run from this repo's source with Bun. */80 const cli = (81 args: readonly string[],82 env: Readonly<Record<string, string | undefined>>83 ) => run({ args: [cliEntry, ...args], command: "bun", env });84 115-/** A refusal list in one line: `NotVouched, AskFull`. */85 const tagsOf = (refusals: readonly Refusal[]) =>86 refusals.map(({ _tag }) => _tag).join(", ");87 119-/** The CLI refused the command: its refusals, for the run's summary. */88 class Refused extends Schema.TaggedError<Refused>()("Refused", {89 reason: Schema.String,90 tags: Schema.Array(Schema.String),91 }) {1 unmodified line93 return this.reason;94 }95 }96 129-/**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- */97 const envelopeOf =98 <A, I>(99 data: Schema.Codec<A, I>,100 what: string,28 unmodified lines129 const isRefused = Schema.is(Refused);130 131 const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });132 170-/** The project's open asks, read anonymously: no token, and no stored login of the user's. */133 const listAsks = (origin: string, project: ProjectName) =>134 Effect.gen(function* () {135 const home = `${yield* SwarmDir}/anonymous`;136 9 unmodified lines146 147 return listed.asks;148 });149 188-/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */150 const planLines = (151 plan: SwarmPlan,152 origin: string,153 swarm: string42 unmodified lines196 ...nudged,197 ];198 };199 239-/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */200 const runName = Effect.map(DateTime.now, (now) =>201 DateTime.formatIso(now)202 .slice(0, 19)203 .replaceAll(/[-:]/gu, "")204 .replace("T", "-")205 );206 247-/** The commit of this repo the swarm runs from. */207 const headCommit = Effect.gen(function* () {208 const root = yield* repoRoot;209 210 const head = yield* run({10 unmodified lines221 const decodeSessions = Schema.decodeUnknownEffect(222 Schema.fromJsonString(Schema.Record(Schema.String, Handle))223 );224 266-/**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. */226 const tokensFor = (handles: readonly Handle[]) =>227 Effect.gen(function* () {228 const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(229 Effect.mapError(() =>29 unmodified lines259 `${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 });262 307-/** Records a claim's fork in the throwaway ledger, once. */263 const recordFork = (stage: Stage, claim: ClaimView) =>264 Effect.gen(function* () {265 const namespace = resources(stage).projects;266 24 unmodified lines291 ask: Schema.Struct({ id: Schema.NonEmptyString }),292 brief: Schema.NonEmptyString,293 });294 340-/**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- */295 const contributorRun = (input: {296 readonly assignment: Assignment;297 readonly options: SwarmOptions;298 readonly origin: string;90 unmodified lines389 workspace: ready.success.workspace,390 });391 });392 444-/** One contributor's run as the summary prints it. */393 const runLine = ({394 ask,395 attempts,396 handle,13 unmodified lines410 Schema.encodeEffect(Schema.fromJsonString(schema))(value),411 Console.log412 ).pipe(Effect.orDie);413 466-/**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- */414 export const main = (argv: readonly string[]) =>415 Effect.gen(function* () {416 const options = yield* optionsOf(argv);417 const origin = yield* originOf(options);114 unmodified lines