Skip to content
Myr

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

9 files+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 */1import { ProjectName } from "@repo/protocol/ids";2import type { ProjectKey } from "@repo/protocol/ids";3import { ProjectExists } from "@repo/protocol/refusal";4import {
20 unmodified lines
25import { flagValue, resources, Stage, stageOf } from "../../../infra/stages.ts";26import { examples, planImports } from "./plan.ts";27import type { ImportExample } from "./plan.ts";2841/** Why the run stopped, said for a person; never a token. */29export class ImportExamplesFailed extends Schema.TaggedError<ImportExamplesFailed>()(30 "ImportExamplesFailed",31 { reason: Schema.String }32) {
3 unmodified lines
36}3738const failed = (reason: string) => new ImportExamplesFailed({ reason });3953/** Where the imports go: a dev stage, or the Node world on this machine. */40export const ImportWhere = Schema.TaggedUnion({41 Stage: { stage: Stage, url: Schema.optionalKey(Schema.String) },42 World: {},43});4445export type ImportWhere = typeof ImportWhere.Type;4661/** What `bun scripts/import-examples.ts` was asked to do. */47export interface ImportOptions {48 readonly where: ImportWhere;64 /** The one example to import, when not all. */49 readonly only: Option.Option<ProjectName>;66 /** Print the plan, import and record nothing. */50 readonly dryRun: boolean;68 /** Backfill the tags of an import that has none. */51 readonly tags: boolean;70 /** Keep the source of each earlier import on its record (ADR 0031). */52 readonly sources: boolean;72 /** Warm the examples the platform lists already, as well as each new import. */53 readonly warm: boolean;74 /** The web's origin to warm through, when the stage's own can't be known. */54 readonly web: Option.Option<string>;55}5678/** The platform the imports go to, as the operator. */57export class ImportTarget extends Context.Service<58 ImportTarget,59 {82 /** Where it is, said for a person: `dev-oscabriel (https://…)`. */60 readonly label: string;61 readonly listProjects: Effect.Effect<62 ReadonlySet<ProjectName>,63 ImportExamplesFailed64 >;88 /** One `initProject` importing `example`: main's first landed SHA. */65 readonly initProject: (66 example: ImportExample67 ) => Effect.Effect<{ readonly landed?: string }, ImportExamplesFailed>;92 /** How many branches and tags the project's repo serves, anonymously. */68 readonly counts: (69 project: ProjectName70 ) => Effect.Effect<71 { readonly heads: number; readonly tags: number },
1 unmodified line
73 >;74 }75>()("scripts/ImportTarget") {}76102/**103 * Pushes an import's tags from its source to its canonical repo: the one104 * write that skips the gateway, tags only, by the operator. How many tags105 * it pushed.106 */77/** The one write that skips the gateway: tags only, by the operator. */78export class TagBackfill extends Context.Service<79 TagBackfill,80 {81 readonly backfill: (
1 unmodified line
83 ) => Effect.Effect<number, ImportExamplesFailed>;84 }85>()("scripts/TagBackfill") {}86116/** One page read to warm an import: where, whether it answered, and what it said. */87export interface WarmRead {88 readonly path: string;89 readonly ok: boolean;120 /** Its status and time, or why it failed; said for a person. */90 readonly said: string;91}92124/**125 * Reads an import's pages once through the web, anonymously, so its first126 * reader finds why and its history kept. A read that fails is reported in127 * what it gives back, never as a failure: warming is a courtesy.128 */93// A failed read is reported, never a failure: warming is a courtesy.94export class Warmer extends Context.Service<95 Warmer,96 {97 readonly warm: (project: ProjectName) => Effect.Effect<readonly WarmRead[]>;
2 unmodified lines
100101const isProjectExists = Schema.is(ProjectExists);102103/**139 * One import's `initProject`, asked again 30 s apart, up to three more140 * times, while it got no answer (`answered` false): a large import can141 * outlast the edge's request timeout, and the platform adopts the repo the142 * first call left. A refusal is never asked again. `ProjectExists` after a143 * call that got no answer is that call's project, made after its answer144 * was lost: this run's import, its landed SHA not known here.104 * A large import can outlast the edge's request timeout; the platform adopts105 * the repo the first call left, so a call with no answer is asked again. A106 * `ProjectExists` after such a call is that call's own project.107 */108export const initUntilAnswered = <A extends { readonly landed?: string }, E>(109 call: Effect.Effect<A, E>,110 answered: (error: E) => boolean
22 unmodified lines
133134const USAGE =135 "bun scripts/import-examples.ts --world node | --stage <stage> [--url <origin>] [--web <origin>] [--only <project>] [--tags] [--sources] [--warm] [--dry-run]";136175/** The flags the command takes; any other is a typo, refused. */137const FLAGS = new Set([138 "--dry-run",139 "--only",140 "--sources",
6 unmodified lines
147]);148149const decodeProject = Schema.decodeUnknownOption(ProjectName);150190/** The command's flags, read; a typo or a stage the table does not declare is refused before anything runs. */151export const optionsOf = (152 argv: readonly string[]153): Effect.Effect<ImportOptions, ImportExamplesFailed> =>154 Effect.gen(function* () {
73 unmodified lines
228 where,229 };230 });231272/**273 * The ledger's line for an import's repo, in the stage's public namespace,274 * by its key: the repo's name, as the platform keeps it.275 */232const repoLine = (233 stage: Stage,234 key: ProjectKey,235 at: DateTime.Utc
5 unmodified lines
241 namespace: resources(stage).projects,242 stage,243});244289/** The ledger's two lines for a new import on `stage`: its project, and its repo, by its key. */245const importLines = (246 stage: Stage,247 key: ProjectKey,248 at: DateTime.Utc
4 unmodified lines
253254const ledgerFailed = ({ message }: PlatformError.PlatformError) =>255 failed(`the ledger (${ledgerPath}): ${message}`);256302/** Appends `entries` to the ledger. */257const record = (entries: readonly Created[]) =>258 Effect.forEach(entries, recordCreated, { discard: true }).pipe(259 Effect.mapError(ledgerFailed)260 );261308/** The stage the run records on, if it runs on one. */262const stageOfWhere = (where: ImportWhere) =>263 ImportWhere.match(where, {264 Stage: ({ stage }) => Option.some(stage),265 World: () => Option.none<Stage>(),266 });267315/**316 * `--tags` on one import: its tags pushed from its source when its repo317 * serves none, the ledger told, and a line printed.318 */268const backfillOne = (269 example: ImportExample,270 tagCount: number,271 stage: Option.Option<Stage>
16 unmodified lines
288 ` ${example.name}: ${pushed} tags backfilled from ${example.url}`289 );290 });291343/** One project warmed, and a line saying how it went. */292const warmOne = (project: ProjectName) =>293 Effect.gen(function* () {294 const reads = yield* Warmer.use((warmer) => warmer.warm(project));295 const failures = reads.filter(({ ok }) => !ok);
7 unmodified lines
303 : ` warm ${project}: no web to read through`304 );305 });306359/**360 * The projects the ledger records as imports on `stage`: an import the361 * platform does not list (one adopted before adoptions were heard) is362 * still this stage's, never imported again.363 */307// An import the ledger records but the platform does not list is still never imported again.308const recordedImports = (stage: Option.Option<Stage>) =>309 Effect.gen(function* () {310 if (Option.isNone(stage)) {311 return new Set<ProjectName>();
19 unmodified lines
331 )332 );333 });334391/**392 * `--sources` on one earlier import: `initProject` asked again with the393 * same source, which the platform takes as the source to keep (ADR 0031)394 * and answers as the import did; a refusal is printed, never fatal.395 */335// A repeated `initProject` with the same source makes the platform keep that source.336const sourceOne = (example: ImportExample) =>337 Effect.gen(function* () {338 const target = yield* ImportTarget;339
4 unmodified lines
344345 yield* Console.log(` ${example.name}: ${outcome}`);346 });347408/** The run itself, over a target, a backfill and a web. */348const run = (options: ImportOptions) =>349 Effect.gen(function* () {350 const target = yield* ImportTarget;351 const listed = yield* target.listProjects;
4 unmodified lines
356 const asked = planImports(examples, new Set(), options.only);357 const plan = planImports(examples, known, options.only);358 const skipped = asked.filter(({ name }) => known.has(name));359421 // The earlier imports `--tags` and `--sources` go back over: on a422 // stage, those the ledger records; in the Node world, every one listed.360 const earlier = skipped.filter(361 ({ name }) => Option.isNone(stage) || recorded.has(name)362 );363
42 unmodified lines
406 Effect.gen(function* () {407 const made = yield* target.initProject(example);408 const at = yield* DateTime.now;409473 // Recorded as soon as the platform made it, before anything else474 // can fail.410 // Recorded before anything else can fail.411 yield* Option.match(stage, {412 onNone: () => Effect.void,413 onSome: (on) => record(importLines(on, example.key, at)),414 });
12 unmodified lines
427 }),428 { discard: true }429 );430495 // An import from an earlier run that this run skipped is backfilled496 // too, if the ledger holds it as an import of this stage.431 if (options.tags && Option.isSome(stage)) {432 yield* Effect.forEach(433 earlier,434 (example) =>
20 unmodified lines
455 : `imported ${plan.length} of ${plan.length} into the Node world (not recorded: the ledger is for stages)`456 );457 });458525/**526 * `bun scripts/import-examples.ts …`: reads the flags (a bad one refused527 * before anything is built or called), then runs over the target, backfill528 * and web `layersOf` gives for them.529 */459export const importExamples = <E, R>(460 argv: readonly string[],461 layersOf: (462 options: ImportOptions
7 unmodified lines
modified:scripts/lib/release/steps.ts+2 added-63 removed
1/**2 * What each step of a release does on this machine, over the3 * plan `scripts/lib/release.ts` makes:4 *5 * - `tsdown`: the CLI's `bun run build` in `apps/cli`, with both targets6 * (`dist/`, and `dist/bin/<target>/` per target), stamped with the7 * release's version (what `--version` prints);8 * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the9 * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its10 * README and the repo's licence;11 * - `copySkills`: the platform's skill (`@repo/agent-kit`'s12 * `platformSkill` over `commandDocs(Contracts)`) into its `skills/`;13 * - `compile`: each target's binary, copied to `apps/cli/release/<slug>-<target>`;14 * - `installScript` and `checksums`: `apps/cli/release/install.sh` and15 * `SHA256SUMS`;16 * - `upload`: the version's files into the stage's `releases-<stage>`17 * bucket with Wrangler's own login, then `releases/manifest.json` last;18 * - `publish`: `npm publish` of the staged package, which the plan allows19 * only when a person runs it (H2).20 *21 * The package is staged beside the binaries rather than in `dist/`: its22 * manifest names `./dist/…` and `./skills` from the package's root, and23 * `dist/bin/` holds the binaries, which npm must not ship.24 */1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";3import { Brand } from "@repo/brand";4import { Contracts } from "@repo/protocol/contracts";
32 unmodified lines
37} from "../release.ts";38import type { ReleaseAsset, ReleaseStep } from "../release.ts";39import { packageReadme } from "./readme.ts";4065/** A step could not finish; nothing after it ran. */41export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(42 "ReleaseFailed",43 { reason: Schema.String, step: Schema.String }44) {
1 unmodified line
46 return `${this.step}: ${this.reason}`;47 }48}4975/** Where a release reads and writes, from the repo root. */50export interface Layout {51 readonly root: string;78 /** `apps/cli`, where the CLI's build runs. */52 readonly cli: string;80 /** `apps/cli/dist`, the CLI's build. */53 readonly dist: string;82 /** `apps/cli/release`: the binaries, the install script and the checksums. */54 readonly release: string;84 /** `apps/cli/release/npm`: the npm package, as `npm publish` takes it. */55 /** Staged outside `dist/`, whose `bin/` holds the binaries npm must not ship. */56 readonly npm: string;57}5859export const layoutOf = (root: string) =>
9 unmodified lines
69 root,70 };71 });72102/** One release: its version, and the origin its install script fetches from. */73export interface Release {74 readonly version: string;105 /** The platform's public origin, without a trailing `/`. */75 readonly origin: string;107 /** The stage an upload goes to. */76 readonly stage: Option.Option<Stage>;77}78111/** The command a person runs from the repo root to publish the staged package. */79export const publishCommand = (layout: Layout, path: Path.Path) =>80 `npm publish ${path.relative(layout.root, layout.npm)} --access public`;8182const failed = (step: ReleaseStep, reason: string) =>83 new ReleaseFailed({ reason, step });84118/** Runs `command` in `cwd` with this terminal's output; any exit but 0 fails `step`. */85const run = (86 step: ReleaseStep,87 command: string,88 args: readonly string[],
17 unmodified lines
106 ),107 Effect.asVoid108 );109144/** What the release reads of a package manifest. */110const PackageJson = Schema.fromJsonString(111 Schema.Struct({112 dependencies: Schema.optionalKey(113 Schema.Record(Schema.String, Schema.String)
14 unmodified lines
128 Effect.flatMap(Schema.decodeEffect(PackageJson)),129 Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))130 );131167/** The files of the build the npm package ships: `dist/*.js` and `dist/*.d.ts`. */132const builtFiles = (layout: Layout) =>133 Effect.gen(function* () {134 const fs = yield* FileSystem.FileSystem;135 const path = yield* Path.Path;
10 unmodified lines
146147 return Arr.sort(files, Order.String);148 });149186/** `manifest`: the npm package, staged afresh from the build. */150const stagePackage = (layout: Layout, release: Release) =>151 Effect.gen(function* () {152 const fs = yield* FileSystem.FileSystem;153 const path = yield* Path.Path;
71 unmodified lines
225226 return manifest;227 });228266/** `copySkills`: the platform's skill, as the platform and the CLI's MCP prompt serve it. */229const writeSkills = (layout: Layout) =>230 Effect.gen(function* () {231 const fs = yield* FileSystem.FileSystem;232 const path = yield* Path.Path;
8 unmodified lines
241 )242 );243 });244283/** `compile`: each target's binary, as the release folder and the platform name it. */245const collectBinaries = (layout: Layout) =>246 Effect.gen(function* () {247 const fs = yield* FileSystem.FileSystem;248 const path = yield* Path.Path;
29 unmodified lines
278 })279 );280 });281321/** The files a release serves under its version: each binary, and the install script. */282const releasedFiles = [283 ...targets.map((target) => binaryName(Brand, target)),284 "install.sh",285];286327/** A file's sha256, as `sha256sum` prints it, and its size. */287const assetOf = (file: string) =>288 Effect.gen(function* () {289 const fs = yield* FileSystem.FileSystem;290 const crypto = yield* Crypto.Crypto;
7 unmodified lines
298 .join(""),299 } satisfies ReleaseAsset;300 });301343/** Each released file in the release folder, by name. */302const assetsIn = (layout: Layout) =>303 Effect.flatMap(Path.Path, (path) =>304 Effect.forEach(releasedFiles, (name) =>305 Effect.map(
2 unmodified lines
308 )309 )310 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));311354/** `checksums`: `SHA256SUMS` beside the files it lists. */312const writeChecksums = (layout: Layout) =>313 Effect.gen(function* () {314 const fs = yield* FileSystem.FileSystem;315 const path = yield* Path.Path;
10 unmodified lines
326 ["install.sh", "text/x-shellscript; charset=utf-8"],327 ["manifest.json", "application/json"],328]);329373/** A binary is bytes; the install script and the manifest are text. */330const contentTypeOf = (file: string) =>331 contentTypes.get(file) ?? "application/octet-stream";332377/** Wrangler's own bin, pinned in `apps/platform`, as bootstrap runs it. */333const wranglerOf = (layout: Layout, path: Path.Path) =>334 path.join(335 layout.root,336 "apps",
2 unmodified lines
339 ".bin",340 "wrangler"341 );342388/**389 * Runs Wrangler in `cwd` with its own login (never the read-mostly infra390 * token; `infra/.env.schema`), and gives its exit code and everything it391 * printed.392 */343// Wrangler's own login, never the read-mostly infra token.344const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>345 Effect.gen(function* () {346 const path = yield* Path.Path;347 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
21 unmodified lines
369 failed("upload", `wrangler didn't run: ${message}`)370 )371 );372422/** What Wrangler prints when a bucket holds no object under a key. */373const NO_SUCH_KEY = "The specified key does not exist";374425/** The manifest the stage's bucket holds, if it holds one. */375const previousManifest = (layout: Layout, bucket: string, scratch: string) =>376 Effect.gen(function* () {377 const fs = yield* FileSystem.FileSystem;378 const path = yield* Path.Path;
33 unmodified lines
412 )413 );414 });415467/** `upload`: the version's files into the stage's own bucket, and the manifest last. */416const upload = (layout: Layout, release: Release) =>417 Effect.gen(function* () {418 const fs = yield* FileSystem.FileSystem;419 const path = yield* Path.Path;
62 unmodified lines
482483 return manifest;484 }).pipe(Effect.scoped);485538/** The paths the staged package's manifest names that it lacks. */486export const missingFromPackage = (layout: Layout, version: string) =>487 Effect.gen(function* () {488 const fs = yield* FileSystem.FileSystem;489 const path = yield* Path.Path;
4 unmodified lines
494 Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)495 );496 });497551/**552 * The staged package is whole and of this release's version, so what553 * `npm publish` ships is what this release built: checked before the554 * publish runs, and before an agent hands its command to a person (H2).555 */498export const publishable = (layout: Layout, release: Release) =>499 Effect.gen(function* () {500 const path = yield* Path.Path;501
16 unmodified lines
518 )519 );520 });521580/** `publish`: `npm publish` of the staged package, once it is `publishable`. */522const publish = (layout: Layout, release: Release) =>523 Effect.andThen(524 publishable(layout, release),525 run(
3 unmodified lines
529 layout.root530 )531 );532592/** `installScript`: the install script for this version, fetching from the release's origin. */533const writeInstallScript = (layout: Layout, release: Release) =>534 Effect.gen(function* () {535 const fs = yield* FileSystem.FileSystem;536 const path = yield* Path.Path;
11 unmodified lines
548549 yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);550 });551612/** One step, run. */552export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>553 Match.value(step).pipe(554 Match.when("tsdown", () =>555 run(
23 unmodified lines
modified:scripts/lib/swarm/views/herdr.ts+12 added-125 removed
1/**2 * The herdr view (`--view herdr`): for the video, each3 * contributor's harness runs interactively in a herdr pane of its own, six4 * tiled over a counter strip, and every prompt (the brief, each refusal,5 * the nudge) is typed into that pane's session through herdr's CLI. The6 * verdict loop is the headless one: outcomes still come only from the7 * contributor's `<cli> status --json`, never from pane text.8 *9 * herdr is driven as a process (`herdr …`, read from `herdr --help` and10 * `herdr agent --help` on herdr 0.9.3), never through an SDK. It runs in the11 * herdr session the swarm itself runs in (`herdr --session demo`), so the12 * panes open where the person recording is looking. Pane text is read for13 * one thing only: to recognise a question a harness asks at startup, before14 * it takes its brief (`STARTUP_QUESTIONS`). Where an answer stands comes15 * from status alone.16 *17 * Unlike a headless harness, an agent in a pane outlives its run: a run that18 * times out (or a swarm that is stopped) leaves it working in its pane,19 * claim and all, until the person closes the workspace the swarm names20 * (`herdr workspace close <id>`).2 * Outcomes come only from `<cli> status --json`; pane text is read only to3 * answer a harness's startup questions. An agent in a pane outlives its run4 * until its herdr workspace is closed.5 */6import type { ProjectName } from "@repo/protocol/ids";7import {8 Config,
18 unmodified lines
27import { followCounter, lastHeld } from "./counter.ts";28import { nothingHeard, Turn } from "./headless.ts";29import type { Attempted, SwarmView } from "./headless.ts";3047/** The counter's pane, below the contributors'. */31export const COUNTER = "counter";3250/**51 * One pane the layout makes: the pane `from` (already made) is split toward52 * `direction`, keeping `ratio` of its space, and the new pane is `slot`.53 */33export interface Split {34 readonly slot: string;35 readonly from: string;36 readonly direction: "right" | "down";37 readonly ratio: number;38}3961/** The share of the window the contributors keep above the counter strip. */40const ABOVE_COUNTER = 0.85;4164/** `ratio` to three places, as herdr reads it. */42const share = (ratio: number) => Math.round(ratio * 1000) / 1000;4367/**68 * The panes for `handles`, as splits of the first one's pane (the69 * workspace's own): a counter strip along the bottom, then up to three70 * contributors to a row, two rows at most, each split keeping the share71 * that leaves every pane of a row the same width. Pure.72 */44export const herdrLayout = (handles: readonly string[]): readonly Split[] => {45 const [first] = handles;4647 if (first === undefined) {
33 unmodified lines
8182 return [counter, ...secondRow, ...columns];83};84114/** How long herdr waits for a harness to be ready for input when it starts one. */85const START_TIMEOUT_MS = 120_000;86117/** `herdr agent start …`: the harness `kind`, named `handle`, in `pane`, with its own flags after `--`. Pure. */87export const herdrStart = (input: {88 readonly handle: string;89 readonly kind: string;90 readonly pane: string;
11 unmodified lines
102 "--",103 ...input.argv,104];105137/**138 * `herdr agent prompt …`: `text` typed into the agent's session, then a139 * wait until it settles. `--wait` alone matches `idle`, `done` and140 * `blocked`: a turn that ends `idle` (seen on Claude Code) would never141 * match `--until done --until blocked`. Pure.142 */106// `--wait` alone also matches `idle`, which a turn can end in; `--until done --until blocked` would hang.107export const herdrPrompt = (input: {108 readonly handle: string;109 readonly text: string;110}): readonly string[] => [
3 unmodified lines
114 input.text,115 "--wait",116];117154/**155 * What only a headless run needs, per harness: the switches and the flags156 * (with their values) the driver's start passes for print mode and JSON157 * output, or for a prompt given on the command line. An interactive158 * session gets its prompt from herdr instead.159 */118const HEADLESS_ONLY = {119 amp: {120 switches: ["--stream-json", "--no-archive-after-execute"],121 valued: ["-x"],
8 unmodified lines
130 { readonly switches: readonly string[]; readonly valued: readonly string[] }131 >132>;133176/** Stands for the brief in a driver's argv, so the brief can be taken out. */134// Marks the brief in a driver's argv so it can be taken out.135const BRIEF = "\u0000brief";136179/** How a harness starts interactively: herdr's kind, its flags, and env it needs. */137export interface Launch {138 readonly kind: string;139 readonly argv: readonly string[];140 readonly env: Readonly<Record<string, string>>;141}142143/**187 * How `contributor`'s harness starts interactively in a pane: herdr's kind188 * (the harness's executable, which herdr knows by the same name), and the189 * driver's own start flags less `HEADLESS_ONLY` and the brief, so the190 * settings that keep a contributor's session safe (every tool allowed, no191 * MCP server of the user's, the workspace's sessions) are the headless192 * run's. OpenCode's interface takes its model from inline config in the193 * env. Pure.144 * Reuses the headless driver's start flags (less `HEADLESS_ONLY` and the145 * brief), so the settings that keep a session safe are the same.146 */147export const interactiveLaunch = (input: {148 readonly contributor: Contributor;149 readonly dir: string;
35 unmodified lines
185 kind,186 };187};188237/** herdr refused a command: its error's code, and what it said. */189class HerdrRefused extends Schema.TaggedError<HerdrRefused>()("HerdrRefused", {190 code: Schema.String,191 said: Schema.String,192 verb: Schema.String,
4 unmodified lines
197}198199const isRefused = Schema.is(HerdrRefused);200250/** What herdr prints on stderr when it refuses a command. */201const decodeRefusal = Schema.decodeUnknownOption(202 Schema.fromJsonString(203 Schema.Struct({204 error: Schema.Struct({ code: Schema.String, message: Schema.String }),205 })206 )207);208259/**260 * `herdr …` with the swarm's env, in the herdr session the swarm runs in:261 * what it printed, or `HerdrRefused` with herdr's own error code.262 */209const herdr = (args: readonly string[]) =>210 Effect.flatMap(run({ args, command: "herdr", env: {} }), (ran) => {211 if (ran.code === 0) {212 return Effect.succeed(ran.stdout);
14 unmodified lines
227 })228 );229 });230285/** Ends a step on herdr's refusal, saying which. */231const orFailed = <A, R>(232 effect: Effect.Effect<A, HerdrRefused | SwarmFailed, R>233): Effect.Effect<A, SwarmFailed, R> =>234 effect.pipe(
1 unmodified line
236 Effect.fail(new SwarmFailed({ reason: message }))237 )238 );239295/** `printed` decoded as `schema`, or why herdr's answer was not what the step needs. */240const answerOf =241 <A, I>(schema: Schema.Codec<A, I>, what: string) =>242 (printed: string) =>243 Schema.decodeEffect(Schema.fromJsonString(schema))(printed).pipe(
6 unmodified lines
250 );251252const PaneId = Schema.Struct({ pane_id: Schema.NonEmptyString });253310/** `workspace create`: the workspace, and its first pane. */254const WorkspaceMade = Schema.Struct({255 result: Schema.Struct({256 root_pane: PaneId,257 workspace: Schema.Struct({ workspace_id: Schema.NonEmptyString }),258 }),259});260318/** `pane split`: the new pane. */261const PaneMade = Schema.Struct({ result: Schema.Struct({ pane: PaneId }) });262321/** An agent as herdr sees it: `idle`, `working`, `blocked`, `done` or `unknown`. */263const AgentSeen = Schema.Struct({264 result: Schema.Struct({265 agent: Schema.Struct({266 agent_status: Schema.String,
1 unmodified line
268 }),269 }),270});271331/** A question a harness asks before it takes a prompt, and the keys that answer it as the swarm decides. */272interface StartupQuestion {333 /** Words only that question shows, in herdr's detection text. */273 readonly asks: string;274 readonly keys: readonly string[];275}276277/**339 * The questions each harness asks when it starts in a new folder (seen on340 * Claude Code 2.1.293 and 2.1.294; OpenCode 2.0.7, Amp 0.0.1789750518 and341 * pi 1.1.0 asked none):342 *343 * - Claude Code asks whether to trust the folder, "No, exit" first: the344 * clone is the swarm's own, so it answers yes;345 * - then whether to import the CLAUDE.md files above the clone (a346 * checkout's, when a test or a person puts the swarm's folder in one),347 * "No" first: it keeps the default, since they are not the contributor's348 * project.349 *350 * Any other question is left for the person at the panes.278 * Claude Code trusts the clone (it is the swarm's own) and declines CLAUDE.md279 * files above it. Any other question is left for the person at the panes.280 */281const STARTUP_QUESTIONS = {282 amp: [],283 "claude-code": [
3 unmodified lines
287 opencode: [],288 pi: [],289} as const satisfies Readonly<Record<Harness, readonly StartupQuestion[]>>;290362/** How long a harness gets to be ready for its brief once herdr says it is blocked at startup. */291const STARTUP_WAIT = Duration.minutes(3);292365/** Whether herdr sees the agent ready for a prompt. */293const readyIn = (printed: string) =>294 Effect.map(295 answerOf(AgentSeen, "agent get")(printed),296 ({ result: { agent } }) =>297 agent.interactive_ready === true &&298 (agent.agent_status === "idle" || agent.agent_status === "done")299 );300374/**375 * A harness blocked at startup: each question it is known to ask is376 * answered once, as `STARTUP_QUESTIONS` says, until herdr sees it ready.377 * A question the table doesn't know waits for the person at the panes,378 * until `STARTUP_WAIT` ends the run.379 */301const pastStartup = (input: {302 readonly handle: string;303 readonly harness: Harness;304 readonly pane: string;
47 unmodified lines
352 )353 );354 });355435/** Names whose values the pane keeps from its own terminal, not the swarm's. */356const PANE_OWNS = ["TERM", "COLORTERM"];357438/** herdr's names in a pane: its integrations report each agent's state with them. */358const HERDR_NAMES = [359 "HERDR_BIN_PATH",360 "HERDR_ENV",361 "HERDR_PANE_ID",
2 unmodified lines
364 "HERDR_WORKSPACE_ID",365];366367/**449 * The script a contributor's pane runs once: it clears the pane's env to450 * its terminal and herdr's own names, reads the harness's env from the451 * swarm through `fifo` (a pipe, so no token is ever in a file, an argv or452 * on the screen), and leaves a shell without rc files (no user setup453 * between the contributor and their env) in their clone, where herdr454 * starts their harness. Pure.368 * The env arrives through a pipe, so no token is ever in a file, an argv or369 * on screen; the shell skips rc files so no user setup sits in between.370 */371export const paneShell = (input: {372 readonly fifo: string;373 readonly clone: string;
14 unmodified lines
388 `esac' pane-shell ${shellQuoted(input.fifo)} ${shellQuoted(input.clone)}`,389 "",390 ].join("\n");391477/** `env` as the lines a shell sources, less what the pane owns. Pure. */392const envLines = (env: Readonly<Record<string, string>>) =>393 Object.entries(env)394 .filter(([name]) => !PANE_OWNS.includes(name))395 .map(([name, value]) => `${name}=${shellQuoted(value)}\n`)396 .join("");397484/** How long a pane gets to read its env from the pipe. */398const ENV_READ_WAIT = Duration.seconds(30);399487/** How many times a pane whose shell is still starting is asked again, a second apart. */400const BUSY_RETRIES = 10;401490/** A pane script runs only as its owner. */402const SCRIPT_MODE = 0o700;403493/**494 * Readies `pane` for `contributor` and starts their harness in it: the495 * pane runs `paneShell`, reads `env` (with the launch's own) from a pipe,496 * and herdr starts the harness with its interactive flags, getting past497 * the startup questions it knows. herdr's answer goes to `log`.498 */404const startIn = (input: {405 readonly contributor: Contributor;406 readonly env: Readonly<Record<string, string>>;407 readonly pane: string;
81 unmodified lines
489490 return yield* input.log(started);491 });492588/** What an attempt heard from herdr's answer to its prompt (or its refusal of it). */493const promptHeard = (input: {494 readonly name: string;495 readonly pane: string;496 readonly harness: Harness;
34 unmodified lines
531 }532 ),533 });534631/**632 * The herdr view over `panes` (each contributor's pane, by handle): an633 * attempt starts the harness in its pane on the brief, or types the634 * continuation's prompt into the same session, and waits until herdr sees635 * it settle. The session a resume names is the agent's herdr name.636 */535export const herdrView = (panes: ReadonlyMap<string, string>): SwarmView => ({536 attempt: ({ contributor, env, file, onSession, turn, workspace }) =>537 Effect.gen(function* () {538 const fs = yield* FileSystem.FileSystem;
52 unmodified lines
591 return yield* promptHeard({ answer, harness, name, pane });592 }),593});594697/** A pane's title: who works in it, and on which harness. */595const titleOf = ({596 handle,597 harness,598}: Pick<Contributor, "handle" | "harness">) => `${handle} · ${harness}`;599703/**704 * Opens the herdr view for `contributors`, in the herdr session the swarm705 * runs in: a workspace of its own (focused, for the person recording), one706 * pane per contributor laid out by `herdrLayout`, and a counter pane that707 * shows `counterFile`, which a fiber in the run's scope keeps writing from708 * the project's `watch`. Outside a herdr pane it refuses: herdr's skill709 * says not to drive a session from outside it. It refuses too when it can't710 * read where the project stands (`lastHeld`), before any pane is made.711 */600// Refuses outside a herdr pane: herdr says not to drive a session from outside it.601export const openHerdrView = (input: {602 readonly contributors: readonly Pick<Contributor, "handle" | "harness">[];603 readonly project: ProjectName;604 readonly origin: string;
25 unmodified lines
630 "--view herdr opens its panes in the herdr session it runs in: start the swarm from a herdr pane (herdr --session demo), or name the session's socket in HERDR_SOCKET_PATH",631 });632 }633745 // Where the counter starts, read before any pane or claim: a run that746 // can't say where the project stands stops here.634 const from = yield* lastHeld(input.origin, input.project);635 const root = (yield* repoRoot).replace(/\/$/u, "");636 const counterFile = `${input.runDir}/counter.log`;637 const handles = input.contributors.map(({ handle }) => handle);
95 unmodified lines
modified:scripts/lib/swarm/loop.ts+6 added-88 removed
1/**2 * The verdict loop: one contributor's harness, started headless on the brief3 * in their workspace, and every refusal their answer meets sent back into4 * the same session, at most `maxContinuations` times.5 *6 * Each attempt runs the harness until its session settles (or the process7 * ends), its output kept in `<run>/<handle>/attempt-<n>.jsonl` with the8 * token blanked. Then `<cli> status` says where the answer stands9 * (`outcome.ts`), never the harness's output:10 *11 * - `Landed`: the contributor is done;12 * - `AwaitingFinish`, `AwaitingDecision`, `WaitingOnParent`: waiting on a13 * person or another ask, recorded as `waiting` (the swarm decides nothing);14 * - `Refused`: the refusals, rendered by protocol's `explain`, go back into15 * the same session with the first one's `next`, unless one of them ends16 * the claim (`endsClaim`) or the continuations ran out; refusals that are17 * all the platform's side (`VerifierBlocked`, `Flake`, `RepoBusy`) go back18 * as a wait: push the same work again, with nothing to fix;19 * - no new answer: one nudge to push (naming the last answer's head, when20 * one came), then `noAnswer` (or `refused`, when an earlier answer was21 * refused and nothing new came).22 *23 * The run's timeout bounds everything: a harness that never settles, or an24 * answer checked past it, ends the run as `timedOut`, and the harness's25 * process group is killed.26 *27 * Where the harness runs, and how a prompt reaches it, is the run's view28 * (`views/`): its own headless process by default, or a herdr pane29 * (`--view herdr`). The loop is the same in both.30 */1import { Brand } from "@repo/brand";2import type { AnswerView } from "@repo/protocol/domain/answer";3import { Outcome } from "@repo/protocol/domain/outcome";4import type { ProjectName } from "@repo/protocol/ids";
24 unmodified lines
29import type { SwarmView } from "./views/headless.ts";30import { scrubbed, SwarmFailed } from "./workspace.ts";31import type { AgentWorkspace } from "./workspace.ts";3263/** One contributor's run: their harness on the brief, then the verdict loop. */33export type RunAgent = (input: {34 readonly assignment: Assignment;35 readonly workspace: AgentWorkspace;36 readonly brief: string;37 readonly maxContinuations: 3;38 readonly timeoutMs: number;70 /**71 * The ask's project, so `status` reads only it. Without one, `status`72 * lists every project's claims and answers and the ask is found by name.73 */39 readonly project?: ProjectName;75 /**76 * Where the harness runs and how each prompt reaches it: its own77 * headless process unless a view (herdr's panes) says otherwise.78 */40 readonly view?: SwarmView;41}) => Effect.Effect<42 AgentRun,43 never,44 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem45>;4686/**87 * The argv that starts `contributor`'s harness headless on `brief`, in their88 * workspace `dir`: the plan prints it, and `runAgent` runs the same one.89 */47export const startCommand = (input: {48 readonly contributor: Contributor;49 readonly brief: string;50 readonly dir: string;
15 unmodified lines
66 });67};6869/**113 * What a harness keeps of the swarm's own env: where the user's harness114 * sign-ins and caches live, the terminal and locale, and the network's115 * proxy and certificates. Nothing secret: the run's `SESSION_TOKENS`, cloud116 * tokens and any parent harness's session never reach a contributor's117 * harness, whose only credential is the person's token in the workspace's118 * env (a harness runs with the user's OS permissions).70 * Nothing secret: the run's `SESSION_TOKENS`, cloud tokens and any parent71 * harness's session never reach a contributor's harness.72 */73const KEPT_FROM_SWARM = [74 "HOME",75 "USER",
21 unmodified lines
97 "SSL_CERT_FILE",98 "NODE_EXTRA_CA_CERTS",99] as const;100148/** The env a contributor's harness runs in: `KEPT_FROM_SWARM`, then the workspace's. */101const harnessEnv = (workspace: AgentWorkspace) =>102 Effect.gen(function* () {103 const kept = yield* Effect.forEach(KEPT_FROM_SWARM, (name) =>104 Config.option(Config.String(name)).pipe(
7 unmodified lines
112 ...workspace.env,113 };114 });115164/** What the loop does once an attempt's answer is known. */116export type Next = Data.TaggedEnum<{166 /** Resume the session with this prompt. */117 Resume: { readonly prompt: string; readonly nudge: boolean };168 /** The run ends with this outcome. */118 Done: {119 readonly outcome: AgentOutcome;120 readonly landed: Option.Option<string>;121 };122}>;123124export const Next = Data.taggedEnum<Next>();125177/** Where the loop stands between attempts. */126export interface Progress {127 readonly attempts: number;128 readonly continuations: number;129 readonly nudged: boolean;182 /** The requests of answers already acted on: status shows them until a new one comes. */130 readonly judged: readonly string[];131 readonly refusals: Readonly<Record<string, number>>;132 readonly landed: Option.Option<string>;133}
6 unmodified lines
140 nudged: false,141 refusals: {},142};143197/** What the loop does next, and where it then stands. */144export interface Step {145 readonly next: Next;146 readonly progress: Progress;147}148203/** `prior` with each refusal's tag counted once more. */149const tally = (150 prior: Readonly<Record<string, number>>,151 refusals: readonly Refusal[]152) => {
7 unmodified lines
160};161162const short = (sha: string) => sha.slice(0, 7);163219/**220 * The refusals that are the platform's side, not the answer's: the checks221 * could not run, a lane flaked, the repo was busy. Each is retryable (the222 * same work may pass), and none names anything in the change to fix.223 */164// Retryable refusals that name nothing in the change to fix.165const platformSide: ReadonlySet<Refusal["_tag"]> = new Set([166 "Flake",167 "RepoBusy",168 "VerifierBlocked",169] as const satisfies readonly Refusal["_tag"][]);170230/**231 * The prompt that resumes a session after its answer was refused. When232 * every refusal is the platform's side, it says so, and asks for the same233 * work again rather than a fix: an empty commit, pushed.234 */171export const refusalPrompt = (input: {172 readonly answer: Pick<AnswerView, "ask" | "head">;173 readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;174 readonly project: string;
19 unmodified lines
194 ...what,195 ].join("\n");196};197262/**263 * The prompt that resumes a session that pushed no new answer: none at all,264 * or none since the head of the last one status showed (`since`).265 */198export const nudgePrompt = (input: {199 readonly ask: string;200 readonly remote: string;201 readonly project: string;
10 unmodified lines
212 `Then run \`${Brand.cli} status --project ${input.project}\` for the verdict.`,213 ].join("\n");214215/**284 * What to do with what status says after an attempt: pure, over the285 * loop's progress. An answer status showed before (its request already286 * judged) is no new answer. The loop acts on the latest new answer, and287 * counts the refusals of every new one: an agent that read its verdict288 * and pushed again in the same session met each of them.216 * An answer already judged is no new answer. Refusals of every new answer are217 * counted, since an agent may push again within one session.218 */219export const afterSettle = (input: {220 readonly status: AskStatus;221 readonly progress: Progress;222 readonly maxContinuations: number;223 readonly ask: string;295 /** The ask's project, when the run was told it; else the claim's. */224 readonly project: Option.Option<string>;297 /**298 * Why the attempt's harness failed (a provider error, a nonzero exit), if299 * it did: with no new answer, a nudge cannot help, so the run failed.300 */225 /** With no new answer, a broken harness fails the run: a nudge cannot help. */226 readonly broke: Option.Option<string>;227}): Step => {228 const { maxContinuations, progress } = input;229
88 unmodified lines
318 WaitingOnParent: () => done("waiting", judged),319 });320};321397/** The tags of the refusals status shows for the ask's latest answer. */322const tagsOf = ({ answer }: AskStatus) =>323 Option.match(answer, {324 onNone: () => "",325 onSome: ({ outcome }) =>
1 unmodified line
327 ? outcome.refusals.map(({ _tag }) => _tag).join(", ")328 : "",329 });330407/** A count of tokens, in thousands when large. */331const tokens = (count: number) =>332 count >= 10_000 ? `${Math.round(count / 1000)}k` : `${count}`;333334export const runAgent: RunAgent = (input) =>
8 unmodified lines
343344 const say = (line: string) =>345 Console.error(scrubbed(`${handle}: ${line}`, workspace));346424 /**425 * One harness session (the start, or a continuation: `turn`), then what426 * status says; it calls itself for each continuation, until427 * `afterSettle` says the run is done.428 */347 const pass = (348 turn: Turn,349 env: Readonly<Record<string, string>>350 ): Effect.Effect<
134 unmodified lines
modified:scripts/lib/swarm/workspace.ts+6 added-56 removed
1/**2 * One contributor's workspace: `<swarm>/<run>/<handle>/` (`SwarmDir`, outside3 * the checkout), with their clone of4 * the claim's fork, a `bin/` that puts this repo's CLI (and git's credential5 * helper) on `PATH`, their own config folder, and the env their harness runs6 * in. The person's platform token reaches the harness only through that env,7 * as `<SLUG>_TOKEN`, never in a file, an argv or a URL.8 */1import { Brand } from "@repo/brand";2import type { ClaimView } from "@repo/protocol/domain/claim";3import {4 Config,
10 unmodified lines
1516import { runDir } from "./results.ts";17import type { Contributor } from "./roster.ts";1827/** The swarm could not do a step; the reason says which, and never holds a token. */19export class SwarmFailed extends Schema.TaggedError<SwarmFailed>()(20 "SwarmFailed",21 { reason: Schema.String }22) {
1 unmodified line
24 return this.reason;25 }26}2737/** Where one contributor works, and the env their harness runs in. */28export interface AgentWorkspace {39 /** `<swarm>/<run>/<handle>`. */29 readonly dir: string;41 /** Their clone of the claim's fork: the harness's working directory. */30 readonly clone: string;31 readonly env: Readonly<Record<string, string>>;44 /** The env names whose values are secret: never logged, never printed. */32 readonly redacted: readonly string[];33}3448/** The env names the CLI reads, spelled from the brand (`apps/cli/src/credentials.ts`). */35const SLUG = Brand.slug.toUpperCase();3651/** The person's platform token: the only identity the CLI and git present. */37export const TOKEN_VARIABLE = `${SLUG}_TOKEN`;3854/** The platform the CLI calls, with the token or, without one, as anyone. */39export const URL_VARIABLE = `${SLUG}_URL`;4057/** The profile the CLI would read instead of the env's token. */41const PROFILE_VARIABLE = `${SLUG}_PROFILE`;4260/** The CLI's process entry in this repo, run from source with Bun. */43export const cliEntry = decodeURIComponent(44 new URL("../../../apps/cli/src/bin.ts", import.meta.url).pathname45);4665/** A one-word shell argument: `'…'`, with any `'` inside closed and escaped. */47export const shellQuoted = (word: string) =>48 /^[\w./:@%+=,-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;4969/** A shim in `bin/`: a shell script that runs the CLI from source with `args` first. */50const shim = (what: string, args: readonly string[]) =>51 [52 "#!/bin/sh",53 `# ${what} for one swarm contributor: this repo's CLI from source, under Bun.`,54 `exec bun '${cliEntry.replaceAll("'", `'\\''`)}' ${[...args.map(shellQuoted), '"$@"'].join(" ")}`,55 "",56 ].join("\n");5778/** Owner, group and everyone may run a shim; only the owner writes it. */58const SHIM_MODE = 0o755;5981/** The workspace's config folder holds the CLI's credentials: owner only. */60const CONFIG_MODE = 0o700;6184/**85 * The env a CLI call runs in as a person: their token and the platform, and86 * a config folder of their own, so no stored profile of the user's answers87 * instead.88 */62// A config folder of their own, so no stored profile answers instead.63export const personEnv = (input: {64 readonly configHome: string;65 readonly platformUrl: string;66 readonly token: Redacted.Redacted;
2 unmodified lines
69 [URL_VARIABLE]: input.platformUrl,70 XDG_CONFIG_HOME: input.configHome,71});7299/**100 * The env a CLI call runs in as anyone: the platform, a config folder that101 * holds no profile, and no token or profile from the shell the swarm runs in.102 */73export const anonymousEnv = (input: {74 readonly configHome: string;75 readonly platformUrl: string;76}) => ({
2 unmodified lines
79 [URL_VARIABLE]: input.platformUrl,80 XDG_CONFIG_HOME: input.configHome,81});82113/** `text` with every secret value of `env` (the names in `redacted`) blanked out. */83export const scrubbed = (84 text: string,85 workspace: Pick<AgentWorkspace, "env" | "redacted">86) => {
9 unmodified lines
9697 return clean;98};99131/** All a byte stream says, as text. */100const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>101 bytes.pipe(Stream.decodeText(), Stream.mkString);102135/** How a process ended, and what it printed. */103export interface Ran {104 readonly code: number;105 readonly stdout: string;106 readonly stderr: string;107}108142/** `command args` in `cwd` with `env` over the swarm's own: how it ended, and what it printed. */109export const run = (input: {110 readonly command: string;111 readonly args: readonly string[];112 readonly cwd?: string;
25 unmodified lines
138 )139 );140141/**176 * How long a clone waits for the claim's fork: one try every `ForkWait`177 * (2 s unless a test says otherwise) after the first, `FORK_TRIES` more at178 * most, so about a minute. A claim returns before its outbox has made the179 * fork, and an Artifacts fork that failed under load is made again only at180 * the Project's next alarm, with backoff. Found live: one of six181 * claims made at once was cloned too soon.142 * A claim returns before its outbox has made the fork, and a failed fork is143 * made again only at the Project's next alarm, so a clone retries.144 */145export const ForkWait = Context.Reference<Duration.Duration>("swarm/ForkWait", {146 defaultValue: () => Duration.seconds(2),147});148149export const FORK_TRIES = 30;150189/** git's words when the gateway answers 404: the repo is not there (yet). */151const NOT_FOUND = /^fatal: repository '.*' not found$/mu;152192/** A clone that failed only because the fork is not made yet. */153const forkNotMadeYet = (ran: Ran) =>154 ran.code !== 0 && NOT_FOUND.test(ran.stderr);155156/**197 * Makes one contributor's workspace for their claim, below `<swarm>/<run>/`:198 *199 * - `bin/<cli>` and `bin/git-credential-<slug>`, shims that run this repo's200 * CLI from source (the helper as `<cli> credential`), first on `PATH`;201 * - `config/`, the CLI's `XDG_CONFIG_HOME`, so neither the CLI nor git's202 * helper reads the user's own login (HOME stays the user's: the203 * harnesses' own sign-ins live there);204 * - `clone/`, the claim's fork, cloned with the helper in its config for205 * the platform (after an empty helper that drops any other, as `login`206 * sets it globally), and the person as its author; while the fork is not207 * made yet, the clone is tried again (`ForkWait`, `FORK_TRIES`);208 * - the env: `PATH`, git's non-interactive settings, `XDG_CONFIG_HOME`, and209 * the person's token and platform as `<SLUG>_TOKEN` and `<SLUG>_URL`.157 * `XDG_CONFIG_HOME` is the workspace's so no stored login is read, but HOME158 * stays, since the harnesses' own sign-ins live there. The clone's helper159 * follows an empty one that drops any global helper.160 */161export const prepareWorkspace = (input: {162 readonly run: string;163 readonly contributor: Contributor;
104 unmodified lines
modified:scripts/lib/release.ts+11 added-154 removed
1/**2 * The release's core: what the CLI's npm package says of3 * itself, which steps a release runs, and what it hands the platform's own4 * release storage. Pure; `scripts/release.ts` runs it.5 */1import type { Brand } from "@repo/brand";2import { detectHarness } from "@repo/protocol/audit";3import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";45import { ReleaseManifest } from "../../apps/platform/src/releases.ts";6import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";7import { installScriptFor } from "./release/install-script.ts";814// --- What a release builds for -----------------------------------------------1516/** The machines a release builds a binary for, as Bun names them. */9export type Target = "bun-linux-x64" | "bun-darwin-arm64";1011export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];1221/** A target as the CLI's build and the platform name it, without Bun's prefix: `linux-x64`. */13export const machineOf = (target: Target) => target.replace(/^bun-/u, "");1424/** A target's binary, as the release folder and the platform name it: `<slug>-linux-x64`. */15export const binaryName = (brand: typeof Brand, target: Target) =>16 `${brand.slug}-${machineOf(target)}`;1728// --- The npm package's dependencies ------------------------------------------2918/**31 * A module statement as rolldown writes one, at the start of a line: an32 * `import … from "x"` or `export … from "x"`, over any number of lines, or a33 * side-effect `import "x"`. Prose and inline strings are not read, but a34 * template literal's line can start with `import` (`dist/bin.js` holds one:35 * the rules' `/bun` main imports `./job.json`). Such a line naming a36 * package is read as an import, which fails the pin loudly (`Unpinned`)37 * rather than letting an import slip through unpinned.19 * A module statement as rolldown writes one, at the start of a line. A20 * template literal's line that starts with `import` and names a package is21 * read as an import too, which fails the pin loudly rather than slip through.22 */23const STATEMENT =24 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;2542/** The package a bare specifier names: `@scope/name` or `name`, without a subpath. */26const packageOf = (specifier: string) =>27 specifier28 .split("/")29 .slice(0, specifier.startsWith("@") ? 2 : 1)30 .join("/");3149/** Whether `specifier` names a package, not a file or a runtime built-in. */32const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);3352/**53 * The packages a built module imports statically, by package name, sorted.54 * A package tsdown keeps external is imported this way; one reached only by55 * a dynamic `import()` would not be listed (none is today).56 */34/** Static imports only: a package reached only by a dynamic `import()` is not listed. */35export const importedPackages = (source: string): readonly string[] =>36 Arr.sort(37 Arr.dedupe(38 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {
4 unmodified lines
43 ),44 Order.String45 );4669/**70 * pi, the harness the package plugs into: a host package, so an optional71 * peer and never bundled or depended on.72 */47/** The host the package plugs into: an optional peer, never bundled or depended on. */48const PI_HOST = "@earendil-works/pi-coding-agent";4975/**76 * Packages the build imports that can't be pinned for npm: the CLI's77 * manifest doesn't declare them, they are workspace packages (tsdown inlines78 * those, so one left is a build fault), or their catalog has no version.79 */50export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {51 packages: Schema.Array(Schema.String),52}) {}5384/** The version a declared specifier pins, with `catalog:` read from the catalog. */54const pinOf = (55 specifier: string | undefined,56 catalogued: string | undefined57) => {
3 unmodified lines
61 ? undefined62 : version;63};6496/**97 * The published package's `dependencies`: each package the build imports,98 * at the version the CLI's manifest (`declared`) pins, `catalog:` resolved99 * from the workspace's catalog. pi is left out: the adapter imports it from100 * the host that loads it, an optional peer. Every other one is pinned, or101 * none is returned.102 */65export const pinnedDependencies = (input: {66 readonly imported: readonly string[];67 readonly declared: Readonly<Record<string, string>>;68 readonly catalog: Readonly<Record<string, string>>;
24 unmodified lines
93 )94 );95};96135// --- The npm package's manifest ----------------------------------------------136137/** The command line, under Node or Bun: the CLI's npm build. */97const BIN = "./dist/bin.js";98140/** A library entry: its code, and the types tsgo declared for it. */99interface LibraryEntry {100 readonly types: string;101 readonly default: string;102}103146/** The npm package's manifest, as `npm publish` reads it. */104export interface PublishManifest {105 readonly bin: Readonly<Record<string, string>>;106 readonly dependencies: Readonly<Record<string, string>>;107 readonly description: string;
14 unmodified lines
122 readonly type: "module";123 readonly version: string;124}125169/** A library entry of the CLI's build, by the name it is published under. */126const library = (name: "protocol" | "rules"): LibraryEntry =>127 // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it128 ({129 types: `./dist/${name}.d.ts`,130 default: `./dist/${name}.js`,131 });132133/**178 * The npm package's manifest for `version`. Every name comes from `brand`:179 * the package, and one bin for each name the one entry answers to (as git's180 * credential helper, it reads its own name; `apps/cli/src/bin.ts`).181 * `dependencies` are the packages the build imports, pinned182 * (`pinnedDependencies`). The `pi` key and the `pi-package` keyword make it183 * a pi package (`pi install npm:<package>`): pi loads the adapter at184 * `dist/pi.js` and the platform's skill under `skills/`.134 * Both bins point at one entry, which reads its own name to act as git's135 * credential helper. The `pi` key and `pi-package` keyword make it a pi package.136 */137export const publishManifest = (138 brand: typeof Brand,139 input: {
20 unmodified lines
160 type: "module",161 version: input.version,162});163213/** A path in the package, as the manifest writes it, from the package's root. */164const fromRoot = (file: string) =>165 file.replace(/^\.\//u, "").replace(/\/$/u, "");166217/**218 * Every path the npm package's manifest points at (its bins, exports, pi's219 * extension and skills folder, and the README and licence it ships), from220 * the package's root, sorted: a staged package missing any of them is not221 * published.222 */167export const namedFiles = (manifest: PublishManifest): readonly string[] =>168 Arr.sort(169 Arr.dedupe(170 [
8 unmodified lines
179 ),180 Order.String181 );182239// --- The plan ----------------------------------------------------------------240241/** One step of a release, in the order a release runs them. */183export type ReleaseStep =184 | "tsdown"185 | "manifest"186 | "copySkills"
2 unmodified lines
189 | "checksums"190 | "upload"191 | "publish";192252/** `npm publish` runs only when a person runs the release (H2). */193export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(194 "PublishNeedsAPerson",195 { markers: Schema.Array(Schema.String) }196) {}197258/**259 * The env names that say an agent runs this process: each one that alone260 * makes `@repo/protocol/audit`'s `detectHarness` name a harness (it261 * keeps that table once; this reads it, never copies it), sorted.262 */198// Reads `detectHarness`'s table rather than copying it.199export const agentMarkers = (200 env: Readonly<Record<string, string | undefined>>201): readonly string[] =>202 Arr.sort(
2 unmodified lines
205 ),206 Order.String207 );208273/** What a build makes: the CLI's build, then the package and the binaries beside it. */209const BUILD: readonly ReleaseStep[] = [210 "tsdown",211 "manifest",212 "copySkills",213 "compile",214];215281/** What a build or an upload ends with: the install script for its origin, and the digests. */216const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];217284/** What `bun run release` was asked to do, and the env it runs in. */218export interface ReleaseFlags {219 readonly build: boolean;220 readonly upload: boolean;221 readonly stage?: string;222 readonly publish: boolean;223 readonly env: Readonly<Record<string, string | undefined>>;224}225293/**294 * The steps `flags` name, in order: `build` (the CLI's build with both295 * targets, the npm package and the binaries), the install script and the296 * checksums, `upload` to the stage's own release storage, and `publish`297 * last. An upload names a stage the repo declares (`dev-oscabriel` or298 * `demo`); a stage given to a build only says whose origin the install299 * script fetches from, and is checked the same way.300 */226const stepsOf = (227 flags: ReleaseFlags228): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {229 if (flags.stage === undefined && flags.upload) {
11 unmodified lines
241 ...(flags.publish ? (["publish"] as const) : []),242 ]);243};244320/**321 * The steps a release runs, in order (`stepsOf`). Under any agent's env, a322 * plan that publishes is refused (H2); `releaseRun` says what the script323 * then does instead.324 */245export const releasePlan = (246 flags: ReleaseFlags247): Result.Result<248 readonly ReleaseStep[],
5 unmodified lines
254 ? Result.fail(new PublishNeedsAPerson({ markers }))255 : stepsOf(flags);256};257338/** One run of `bun run release`: the steps it runs, and who it hands the publish to. */258export interface ReleaseRun {259 readonly steps: readonly ReleaseStep[];341 /** The agent markers that refused the publish (H2); none when a person runs it. */260 readonly handOver: readonly string[];261}262263/**346 * What the script runs for `flags`. A person's run is the plan. Under an347 * agent, a run that publishes still runs every other step it names, so a348 * `--build --publish` builds, and hands the publish to a person in place349 * of running it: the script checks the staged package and prints the350 * command (H2), rather than ending well with nothing done.264 * Under an agent, a run that publishes still runs every other step it names265 * and hands the publish to a person instead of running it.266 */267export const releaseRun = (268 flags: ReleaseFlags269): Result.Result<ReleaseRun, NoStage | UnknownStage> => {
4 unmodified lines
274 (steps) => ({ handOver, steps })275 );276};277363// --- The version -------------------------------------------------------------364365/**366 * An upload or a publish names its `--version`, and it is one the platform367 * serves: semver, never `latest` (`given` is the one that isn't).368 */278export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(279 "VersionNeeded",280 { given: Schema.optionalKey(Schema.String) }281) {
3 unmodified lines
285 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;286 }287}288380/**381 * Whether the platform serves `version`: its manifest decodes with it as382 * the latest release (the platform's schema holds the one rule for a version).383 */289const served = (version: string) =>290 Option.isSome(291 Schema.decodeOption(ReleaseManifest)({292 latest: version,293 versions: { [version]: { assets: {} } },294 })295 );296392/**393 * What a build that neither uploads nor publishes is stamped with. The394 * build stamps the release's version into the CLI (`apps/cli/build.ts`'s395 * `--version`, which the `tsdown` step passes), and a run no build stamped396 * reports this too (`apps/cli/src/version.ts`).397 */297const UNRELEASED = "0.0.0";298400/**401 * The release's version: `version` as given, which an upload or a publish402 * must name, and which must be one the platform serves.403 */299export const releaseVersion = (input: {300 readonly version?: string;301 readonly upload: boolean;302 readonly publish: boolean;
8 unmodified lines
311 ? Result.succeed(input.version)312 : Result.fail(new VersionNeeded({ given: input.version }));313};314420// --- The platform's release storage ------------------------------------------421422/** One file of a release, as the manifest lists it. */315export interface ReleaseAsset {316 readonly sha256: string;317 readonly bytes: number;318}319320export { ReleaseManifest } from "../../apps/platform/src/releases.ts";321430/**431 * `releases/manifest.json` once `version` is released with `assets`: every432 * version `previous` lists, kept, and `version`, now latest. It is the shape433 * the platform decodes and serves from (`ReleaseManifest`, the one434 * schema both sides use).435 */322export const releaseManifest = (input: {323 readonly version: string;324 readonly previous: ReleaseManifest | undefined;325 readonly assets: Readonly<Record<string, ReleaseAsset>>;
4 unmodified lines
330 [input.version]: { assets: input.assets },331 },332});333448/**449 * `version` is already released with other bytes. The platform serves a450 * version's files as immutable, so a client may keep the old ones for good:451 * a changed release needs a new `--version`.452 */334export class VersionReleased extends Schema.TaggedError<VersionReleased>()(335 "VersionReleased",336 { version: Schema.String }337) {
1 unmodified line
339 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;340 }341}342462/** Two releases hold the same files, by name, size and digest. */343const sameAssets = (344 one: Readonly<Record<string, ReleaseAsset>>,345 other: Readonly<Record<string, ReleaseAsset>>346) =>
2 unmodified lines
349 ([name, { bytes, sha256 }]) =>350 other[name]?.bytes === bytes && other[name]?.sha256 === sha256351 );352473/**474 * Whether `assets` may be released as `version`: it is new, or it is475 * released already with exactly these files (an upload run again).476 */353export const unreleased = (input: {354 readonly version: string;355 readonly previous: ReleaseManifest | undefined;356 readonly assets: Readonly<Record<string, ReleaseAsset>>;
4 unmodified lines
361 ? Result.void362 : Result.fail(new VersionReleased({ version: input.version }));363};364489/** Where the manifest is kept: every release file is under `releases/`. */365export const MANIFEST_KEY = "releases/manifest.json";366492/** Files by name, sorted (`Order.String`), as both sides list them. */367const byName = <A>(record: Readonly<Record<string, A>>) =>368 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);369496/**497 * `SHA256SUMS`: one `<sha256> <name>` line per file, sorted by name, as498 * `sha256sum` prints them and as the platform makes the one it serves from499 * the manifest.500 */370export const checksumsFile = (371 assets: Readonly<Record<string, ReleaseAsset>>372): string =>373 byName(assets)374 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)375 .join("");376508/**509 * What an upload puts where, in order: every file of `version` under510 * `releases/<version>/`, sorted, and `releases/manifest.json` last, so the511 * manifest never names a file the bucket lacks.377// The manifest goes last, so it never names a file the bucket lacks.512 */378export const uploads = (input: {379 readonly version: string;380 readonly files: readonly string[];381}): readonly { readonly file: string; readonly key: string }[] => [
3 unmodified lines
385 })),386 { file: "manifest.json", key: MANIFEST_KEY },387];388524// --- The install script ------------------------------------------------------525526/**527 * `curl -fsSL <origin>/install.sh | sh` for `version`, whose files the528 * platform serves at `baseUrl` (`<origin>/releases/<version>`):529 * the binary for the machine, checked against `SHA256SUMS` before it is530 * installed as `brand.cli`, with `brand.gitCredentialHelper` linked to it.531 */389export const installScript = (input: {390 readonly brand: typeof Brand;391 readonly version: string;392 readonly baseUrl: string;
1 unmodified line
modified:scripts/lib/seed.ts+14 added-249 removed
1/**2 * The seed's core: what to put on a platform for one example3 * project, read from the example's tracked files, and putting it there.4 *5 * A plan (`planSeed`) is the library as it was before anyone asked (every6 * tracked file but the asks, the checks they name and the layers), the7 * decider its config names for the whole tree, each ask with the files it8 * opens with, and each layer the example keeps under `layers/<layer>/`9 * with its known-bad trees. Only what git tracks ships, so an10 * ignored file, and above all a closed env file, never leaves the machine.11 *12 * A run (`runSeed`) makes the project and pushes main's first commit as the13 * platform's operator (the initializer decides until the config14 * names deciders), through the gateway's first-push admission, then15 * opens each ask as the decider, so each is red first on the platform's own16 * Checker. Last, as the decider, it pushes each layer17 * to the repo the platform made for it in the private namespace, through18 * the gateway, never to the public tree. A step already done is19 * reported `already` and left alone, so a second run changes nothing.20 *21 * A platform is a `SeedTarget`: a stage (`stageTarget`) or the Node world22 * served by a process of its own (`worldTarget`), each reached over HTTP23 * and git the same way (`platformTarget`). Tokens live in `Redacted`24 * values and reach git only through its child's env: the seed never prints,25 * logs or writes one.26 */1import { Brand } from "@repo/brand";2import { Client, Contracts } from "@repo/protocol/contracts";3import type { AskListing } from "@repo/protocol/domain/ask";4import { LayerManifest } from "@repo/protocol/domain/visibility";
33 unmodified lines
38import { RpcClient, RpcSerialization } from "effect/rpc";3940import { repoRoot } from "../../infra/stages.ts";4168/**69 * The seed could not go on; `reason` says why and what to do. When the70 * platform refused a step, `refusals` holds what it said.71 */42export class SeedFailed extends Schema.TaggedError<SeedFailed>()("SeedFailed", {43 reason: Schema.String,44 refusals: Schema.optionalKey(Schema.NonEmptyArray(Refusal)),45}) {
1 unmodified line
47 return this.reason;48 }49}5081/** One file of a seeded tree, as its bytes. */51export interface SeedFile {52 readonly path: RepoPath;53 readonly content: Uint8Array;54}5587/** One file an ask opens with, as text (the `openAsk` contract's `ConfigFile`). */56export interface AskFile {57 readonly path: RepoPath;58 readonly content: string;59}6093/** One ask the seed opens: its id, its kind's name, and the files it opens with. */61export interface AskStep {62 readonly id: AskId;63 readonly kind: string;97 /** The ask's file, then the check file it names, if it names one. */64 readonly files: Array.NonEmptyReadonlyArray<AskFile>;65}6667/**102 * A known-bad tree for a layer's admission: main's first tree103 * with one change that breaks an area, made a commit of its own (no104 * parent, the decider's, at the seed's fixed dates), so it is the same105 * commit on every platform and the layer's manifest can name it.68 * A parentless commit at the seed's fixed dates, so it is the same commit on69 * every platform and the layer's manifest can name it.70 */71export interface KnownBadStep {108 /** Its branch in the layer repo: `known-bad/<area>`. */72 readonly branch: string;110 /** The commit it comes to, which the layer's manifest names in `knownBad`. */73 readonly commit: CommitSha;112 /** What the change breaks: the words before its patch's diff. */74 readonly message: string;114 /** main's first tree, with the change applied. */75 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;76}77118/**119 * One layer the seed pushes to the private namespace, once main has landed120 * and declared it: its repo's tree, at the same root-relative paths as121 * main's, and the known-bad trees its admission runs on.122 */78export interface LayerStep {79 readonly layer: LayerName;125 /** Its repo in the private namespace: `<project>--<layer>`. */80 readonly repo: RepoName;127 /** Every file under the example's `layers/<layer>/`, at its path there. */81 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;129 /** One per `known-bad/<area>.patch` in the layer, by area. */82 readonly knownBad: readonly KnownBadStep[];83}84133/** What the seed puts on a platform for one example project. */85export interface SeedPlan {86 readonly project: ProjectName;136 /** Who opens the asks: the first decider the config names for the whole tree. */87 readonly decider: Handle;138 /** main's first commit: the library before anyone asked. */88 readonly initFiles: Array.NonEmptyReadonlyArray<SeedFile>;89 readonly asks: readonly AskStep[];141 /** The ratchets the config declares, in place once main has landed. */90 readonly ratchets: readonly string[];143 /** The layers the example keeps beside its public tree, pushed by the decider. */91 readonly layers: readonly LayerStep[];145 /**146 * The example this plan copies under another name (`seed --as`), when it147 * is a copy: a copy is made fresh, so a name some project has is refused.148 */92 readonly copyOf?: ProjectName;93}94152/** Where the asks live in an example: the config folder's `asks/`. */95const ASKS = `${Brand.configDir}/asks/`;96155/**156 * Where an example keeps its layers: `layers/<layer>/`, each the tree of157 * that layer's repo. Nothing under it enters the public tree.158 */97/** Nothing under it enters the public tree. */98const LAYERS = "layers/";99161/** A known-bad change a layer keeps: `known-bad/<area>.patch`. */100const KNOWN_BAD = /^known-bad\/(?<area>[^/]+)\.patch$/u;101164/** A layer's manifest in the JSON form the platform reads. */102const MANIFEST_FILE = `${Brand.configDir}/layer.json`;103167// Where a patch's diff starts; the words before it say what it breaks.104const DIFF_START = /^(?:diff --git |--- )/mu;105170/** The config file that names the deciders and the ratchets. */106const PROJECT_FILE = `${Brand.configDir}/project.ts`;107173/** An ask's file: `asks/<id>.ask.ts`, directly in the asks folder. */108const ASK_FILE = /^(?<id>[^/]+)\.ask\.ts$/u;109176/**177 * The files whose values stay on each machine (AGENTS.md "Env"). The seed178 * refuses an example that tracks one rather than read it.179 */110/** Env files whose values stay on each machine: an example that tracks one is refused, never read. */111const CLOSED_ENV = /^\.env(?:\.local|\.[^/]+\.local)?$/u;112182// An ask file calls its kind's builder: `kinds.fix.ask({ … })`.113const KIND = /\bkinds\.(?<kind>\w+)\.ask\(/u;114185// An ask file names its check file as the `path` its kind takes186// (`kinds.fix.ask({ path: "test/asks/<id>.test.ts", … })`), which the kind187// makes the ask's `RedThenGreen.path`. A kind that counts (`migrate`) names188// none.115// The check file is the `path` the ask's kind takes; a kind that counts (`migrate`) names none.116const CHECK_PATH = /\bpath:\s*"(?<path>[^"]+)"/u;117191// The deciders for the whole tree: `deciders: { "**": ["ines-v", …] }`.118const WHOLE_TREE_DECIDER = /"\*\*"\s*:\s*\[\s*"(?<handle>[^"]+)"/u;119194// Each ratchet the config declares: `"<name>": check.ratchet.count(…)`.120const RATCHET = /"(?<name>[^"]+)"\s*:\s*check\.ratchet\./gu;121122const failed = (reason: string) => new SeedFailed({ reason });123199/** `raw` decoded by `schema`, or the seed fails saying what it was. */124const decoded =125 <S extends Schema.Codec<unknown, string>>(schema: S, what: string) =>126 (raw: string) =>127 Schema.decodeEffect(schema)(raw).pipe(128 Effect.mapError(() => failed(`${what} ${JSON.stringify(raw)} is not one`))129 );130207/** The paths git tracks under `dir`, relative to it, in git's order. */131const trackedIn = (root: string, dir: string) =>132 Effect.gen(function* () {133 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;134
12 unmodified lines
147 .filter((path) => path.startsWith(`${dir}/`))148 .map((path) => path.slice(dir.length + 1));149 });150228/** One file of the example as text, or the seed fails naming it. */151const textOf = (fs: FileSystem.FileSystem, at: string, path: string) =>152 fs153 .readFileString(at)154 .pipe(Effect.mapError(() => failed(`can't read ${path}`)));155234/**235 * git's env for a commit by `handle`: fixed dates, so the same files make236 * the same commit on every machine; no git config from this machine (no237 * hooks, no signing); English messages.238 */156// Fixed dates and no machine config, so the same files make the same commit everywhere.157const authorEnv = (handle: Handle) => ({158 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",159 GIT_AUTHOR_EMAIL: `${handle}@example.com`,160 GIT_AUTHOR_NAME: handle,
5 unmodified lines
166 GIT_TERMINAL_PROMPT: "0",167 LC_ALL: "C",168});169252/** All a byte stream says, as text. */170const streamText = <E>(bytes: Stream.Stream<Uint8Array, E>) =>171 bytes.pipe(Stream.decodeText(), Stream.mkString);172256/**257 * git with `args` in `cwd` under `env`, after the `-c` settings in258 * `settings`: how it ended, and what it printed.259 */173const runGit = (174 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],175 cwd: string,176 args: readonly string[],
22 unmodified lines
199 failed(`git ${args[0] ?? ""} didn't run: ${message}`)200 )201 );202290/** What git printed, when it ended well; else the seed fails with what it said. */203const okOutput =204 (args: readonly string[]) =>205 ({ code, stderr, stdout }: Effect.Success<ReturnType<typeof runGit>>) =>206 code === 0
1 unmodified line
208 : Effect.fail(209 failed(`git ${args.join(" ")} exited ${code}: ${stderr.trim()}`)210 );211300/** `files` written under `dir`, each at its path. */212const writeTree = (213 fs: FileSystem.FileSystem,214 path: Path.Path,215 dir: string,
10 unmodified lines
226 }).pipe(Effect.mapError(() => failed(`can't write ${file} to seed`))),227 { discard: true }228 );229319/**320 * A known-bad tree made a commit on this machine, in a folder of its own:321 * main's first files, the patch applied, committed as `decider` at the322 * seed's fixed dates with the patch's words as its message. The same files323 * and patch make the same commit wherever the seed runs.324 */230const knownBadOf = (input: {231 readonly area: string;232 readonly decider: Handle;233 readonly initFiles: SeedPlan["initFiles"];329 /** The patch, as a path on this machine. */234 readonly patch: string;331 /** The patch, as its layer names it. */235 readonly named: string;236}) =>237 Effect.scoped(238 Effect.gen(function* () {
52 unmodified lines
291 } satisfies KnownBadStep;292 })293 );294392/** A layer's repo in the private namespace: `<project's key>--<layer>`. */295const layerRepo = (project: ProjectName, layer: LayerName) =>296 RepoName.make(`${keyOf(project)}--${layer}`);297298const decodeManifest = Schema.decodeEffect(299 Schema.fromJsonString(LayerManifest)300);301400/**401 * The layers an example keeps under `layers/`, each with its files and its402 * known-bad trees. A layer whose manifest names other known-bad commits403 * than its patches make is refused, so the manifest the seed pushes names404 * commits the layer repo holds.405 */302const layersOf = (input: {303 readonly decider: Handle;304 readonly folder: string;305 readonly initFiles: SeedPlan["initFiles"];
64 unmodified lines
370 failed(`${named} is no layer manifest: ${error.message}`)371 )372 );373478 // By area, as the patches are named; compared in any order.374 const made = knownBad.map(({ commit }) => commit);375376 if (manifest.layer !== layer) {377 return yield* failed(
19 unmodified lines
397 })398 );399 });400506/**507 * The plan for the example at `dir` (relative to the repo root, as508 * `examples/datekit`): the project is named for its folder.509 */401export const planSeed = (dir: string) =>402 Effect.gen(function* () {403 const fs = yield* FileSystem.FileSystem;404 const path = yield* Path.Path;
84 unmodified lines
489 const held = new Set(490 asks.flatMap(({ files }) => files.map((file) => String(file.path)))491 );492602 // A layer's files never enter the public tree (principle 7).493 // A layer's files never enter the public tree.494 const initPaths = tracked.filter(495 (file) =>496 !file.startsWith(ASKS) && !file.startsWith(LAYERS) && !held.has(file)497 );
26 unmodified lines
524 ratchets,525 } satisfies SeedPlan;526 });527637/**638 * `plan` as a fresh copy named `as` (`seed --as`): the project, and each639 * layer's repo, which is named for it, take the new name; the files, the640 * asks and the decider stay the example's. A copy of a copy is still a copy641 * of the example.642 */528export const renameSeedPlan = (plan: SeedPlan, as: ProjectName): SeedPlan => ({529 ...plan,530 copyOf: plan.copyOf ?? plan.project,531 layers: plan.layers.map((layer) => ({
2 unmodified lines
534 })),535 project: as,536});537653/** Whether a run did a step, or found it done before. */538export const StepResult = Schema.Literals(["done", "already"]);539540export type StepResult = typeof StepResult.Type;541542const step = { result: StepResult, target: Schema.String };543660/**661 * One step of a seed: making the project (`Init`), pushing main's first662 * commit (`Push`), opening an ask (`OpenAsk`), pushing a layer (`Layer`).663 */544export const SeedStep = Schema.TaggedUnion({545 Init: step,546 Layer: step,547 OpenAsk: step,
1 unmodified line
549});550551export type SeedStep = typeof SeedStep.Type;552673/** What a platform gives the seed: a world, or a stage. */553export class SeedTarget extends Context.Service<554 SeedTarget,555 {677 /** Who makes each project and pushes its first commit. */556 readonly operator: Handle;679 /** The contracts as `handle` calls them; fails when the platform has no session for them. */557 readonly clientFor: (handle: Handle) => Layer.Layer<Client, SeedFailed>;681 /** Fails naming each of `handles` the platform has no session for. */558 readonly requireSessions: (559 handles: readonly Handle[]560 ) => Effect.Effect<void, SeedFailed>;685 /** Every ref of a project's canonical repo, by name, as git lists them. */561 readonly refsOf: (562 project: ProjectName563 ) => Effect.Effect<ReadonlyMap<string, CommitSha>, SeedFailed>;689 /**690 * A fresh repo holding `files` in one commit, pushed as `as` to the691 * project's main at the gateway, which admits only its initializer's692 * first push; gives the commit.693 */564 readonly pushInitial: (565 project: ProjectName,566 files: SeedPlan["initFiles"],567 as: Handle568 ) => Effect.Effect<CommitSha, SeedFailed>;699 /**700 * Every ref of `repo` as `as` lists them through the gateway, by name;701 * none when the gateway serves no such repo (a layer's, before the702 * platform has made it). Fails when `as` may not read it.703 */569 readonly refsAt: (570 repo: RepoName,571 as: Handle572 ) => Effect.Effect<573 Option.Option<ReadonlyMap<string, CommitSha>>,574 SeedFailed575 >;711 /** Every file's path at `ref` of `repo`, as `as` fetches it. */576 readonly pathsAt: (577 repo: RepoName,578 ref: string,579 as: Handle580 ) => Effect.Effect<readonly RepoPath[], SeedFailed>;717 /**718 * A commit of `files` with no parent, made as `as` with `message` at the719 * seed's fixed dates, pushed to `ref` of `repo` through the gateway;720 * gives the commit.721 */581 readonly pushCommit: (input: {582 readonly repo: RepoName;583 readonly ref: string;584 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;
6 unmodified lines
591const isRefusal = Schema.is(Refusal);592593const isProjectExists = Schema.is(ProjectExists);594736/** What a call to the platform fails with: a refusal, or the transport's own error. */595interface CallFailure {596 readonly _tag: string;597 readonly message: string;598}599742/**743 * A call that failed: a refusal, said as `explain` says it everywhere, or744 * a platform that didn't answer.745 */600const failedCall = (call: string) => (error: CallFailure) =>601 isRefusal(error)602 ? new SeedFailed({603 reason: `${call} was refused: ${explain([error])
2 unmodified lines
606 refusals: [error],607 })608 : failed(`${call} got no answer from the platform: ${error.message}`);609756/** main, as git names it. */610export const MAIN_REF = "refs/heads/main";611759/**760 * Whether the platform has a session for the operator and for every plan's761 * decider: fails naming everyone it has none for, so a seed never stops762 * half-way for want of one.763 */612export const ready = (613 plans: readonly SeedPlan[]614): Effect.Effect<void, SeedFailed, SeedTarget> =>615 Effect.flatMap(Effect.service(SeedTarget), (target) =>
2 unmodified lines
618 ...plans.map(({ decider }) => decider),619 ])620 );621774/** What a platform holds for one seeded project. */622export interface SeededProject {623 readonly project: ProjectName;777 /** Its asks that are not closed, as anyone lists them. */624 readonly asks: readonly AskListing[];779 /** Every ref of its canonical repo, by name, sorted: main, the landed mirror, notes, the commits checks ran on. */625 readonly refs: readonly (readonly [string, CommitSha])[];626}627783/** What the platform holds now for each project of `plans`, read as each one's decider. */628export const seeded = (629 plans: readonly SeedPlan[]630): Effect.Effect<readonly SeededProject[], SeedFailed, SeedTarget> =>631 Effect.flatMap(Effect.service(SeedTarget), (target) =>
18 unmodified lines
650 })651 )652 );653810/** How often, and how many times, the seed asks again for a layer's repo. */654const LAYER_WAIT = { every: Duration.seconds(1), times: 30 } as const;655813/** The platform has not made a layer's repo yet. */656class NotMadeYet extends Schema.TaggedError<NotMadeYet>()("NotMadeYet", {657 repo: RepoName,658}) {}659818/**819 * Pushes one layer to its repo in the private namespace, as the decider,820 * once the platform has made it (a landing that declares the layer makes821 * it): first each known-bad commit to its branch, so admission finds822 * every commit the manifest names, then the layer's files to main,823 * which proposes its checks. A layer whose main is there is left alone.824 */660// Known-bad commits go first, so admission finds every commit the manifest names.661const seedLayer = (662 layer: LayerStep,663 decider: Handle664): Effect.Effect<SeedStep, SeedFailed, SeedTarget> =>
63 unmodified lines
728729 return reported("done");730 });731896/**897 * `runSeed`, with `made` run once the platform has made the project and898 * before anything else is put on it: `seed --as` writes a copy to the899 * throwaway ledger there, so a run that fails later still leaves it there.900 */732/** `made` runs as soon as the project exists, so a run that fails later still records it. */733export const runSeedWith = <R>(734 plan: SeedPlan,735 made: (plan: SeedPlan) => Effect.Effect<void, SeedFailed, R>736): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget | R> =>
71 unmodified lines
808 ];809 })810 );811980/**981 * Seeds one project: makes it and pushes main's first commit as the982 * operator, then opens each ask and pushes each layer as the decider. Both983 * sessions are checked before the first step, so a missing one stops the984 * seed before it starts.985 *986 * A copy (`renameSeedPlan`) is made fresh: a name some project has is987 * refused with its `ProjectExists`, before anything is pushed.988 */812export const runSeed = (813 plan: SeedPlan814): Effect.Effect<readonly SeedStep[], SeedFailed, SeedTarget> =>815 runSeedWith(plan, () => Effect.void);816994// ------------------------------------------------------------ the platform995996/** A platform the seed reaches over HTTP and git. */817export interface Platform {998 /** Where it serves `/rpc` and git: `https://platform-dev-….workers.dev`. */818 readonly origin: string;1000 /** Who makes each project and pushes its first commit. */819 readonly operator: Handle;1002 /** Each person's token, by handle. Never printed. */820 readonly tokens: ReadonlyMap<Handle, Redacted.Redacted>;1004 /** Where a missing person's token goes, for the message that names them. */821 readonly sessionsFrom: string;822}8231008/** The refs `git ls-remote` lists, one a line: `<sha>\t<ref>`. */824const refsIn = (listed: string) =>825 Effect.map(826 Effect.forEach(827 listed.split("\n").filter((line) => line.length > 0),
10 unmodified lines
838 ),839 (refs): ReadonlyMap<string, CommitSha> => new Map(refs)840 );8411027// What git says of a repo the server doesn't serve.842const NOT_SERVED = /\bnot found\b|\b404\b/u;8431030/** The env var that hands git a token: in git's own env, never in its argv. */844// The token reaches git through its env, never its argv.845const TOKEN_VAR = "SEED_GIT_TOKEN";8461033/** git's credential helper for one person: their handle, and the token from git's env. */847const helperFor = (handle: Handle) =>848 `!f() { test "$1" = get || exit 0; echo username=${handle}; echo "password=$${TOKEN_VAR}"; }; f`;8491037/** git's env as `handle`: `authorEnv`'s, and their token for the helper. */850const gitEnv = (handle: Handle, token: Redacted.Redacted) => ({851 ...authorEnv(handle),852 [TOKEN_VAR]: Redacted.value(token),853});8541043/** The contracts over HTTP at `origin`'s `/rpc`, with `token` as the bearer. */855const clientAt = (856 origin: string,857 token: Redacted.Redacted858): Layer.Layer<Client> =>
8 unmodified lines
867 ),868 Layer.provide([FetchHttpClient.layer, RpcSerialization.layerJson])869 );8701060/**1061 * The seed's target over a platform at an origin: the contracts over1062 * `/rpc` and git through the gateway, each as a person with their token.1063 */871export const platformTarget = (872 platform: Platform873): Layer.Layer<874 SeedTarget,
6 unmodified lines
881 const fs = yield* FileSystem.FileSystem;882 const path = yield* Path.Path;883 const { origin } = platform;8841078 // A repo is reached at its project's name, its fork's or layer's1079 // parts after it (`oscabriel/datekit--maintainers`).885 const remoteOf = (repo: ProjectName | RepoName) =>886 repo.includes("/")887 ? `${origin}/${repo}.git`888 : `${origin}/${Option.getOrElse(addressOfRepo(RepoName.make(repo)), () => repo)}.git`;
18 unmodified lines
907 ? Effect.fail(missing(lacking))908 : Effect.void;909 };9101106 /**1107 * git as `as`, in `cwd`, with their token for its credential helper1108 * and no other helper: how it ended, and what it printed.1109 */911 const gitAs = (as: Handle, cwd: string, args: readonly string[]) =>912 Effect.flatMap(913 Effect.fromOption(tokenOf(as)).pipe(914 Effect.mapError(() => missing([as]))
6 unmodified lines
921 `credential.helper=${helperFor(as)}`,922 ])923 );9241124 /** git as `as` that must succeed; its output. */925 const gitOk = (as: Handle, cwd: string, args: readonly string[]) =>926 Effect.flatMap(gitAs(as, cwd, args), okOutput(args));9271128 // An empty folder of the seed's own, removed with the scope: git run1129 // there reads no repo's config, as `gitEnv` keeps the machine's out.928 // An empty folder, so git reads no repo's config.929 const scratch = fs930 .makeTempDirectoryScoped({ prefix: "seed-" })931 .pipe(Effect.mapError(() => failed("can't make a temporary folder")));932
51 unmodified lines
984 .map((file) => RepoPath.make(file));985 })986 );9871189 /** A commit of `files` with no parent, made as `as` and pushed to `ref` of `repo`. */988 const pushCommit = (input: {989 readonly repo: ProjectName | RepoName;990 readonly ref: string;991 readonly files: Array.NonEmptyReadonlyArray<SeedFile>;
29 unmodified lines
1021 )((yield* gitOk(as, dir, ["rev-parse", "HEAD"])).trim());1022 })1023 );10241227 // git ends a message with one newline whether given one or not, so1228 // main's first commit is the one this made before layers had a step.1025 // git ends a message with one newline whether given one or not.1026 const pushInitial = (1027 project: ProjectName,1028 files: SeedPlan["initFiles"],1029 as: Handle
22 unmodified lines
1052 });1053 })1054 );10551259// --------------------------------------------------------------- the world12601261/** The file that serves the Node world as a process, from the repo root. */1056const SERVE_WORLD = "apps/platform/test/serve-world.ts";10571264/** How long the world has to start serving. */1058const WORLD_START = Duration.seconds(60);10591267/** The line the world prints once it serves. */1060const decodeServing = Schema.decodeUnknownOption(1061 Schema.fromJsonString(Schema.Struct({ origin: Schema.String }))1062);10631272/**1273 * The world's operator: a session of the world's own, under the handle the1274 * stages' operator has (`OPERATOR_HANDLE`), so the examples are made in the1275 * namespace they have on a stage (`oscabriel/datekit`).1276 */1064/** The stages' operator handle, so the examples get the namespace they have on a stage. */1065export const worldOperator = Handle.make("oscabriel");10661279/** A token for `handle` in a world on this machine: no secret, never leaves it. */1067const worldToken = (handle: Handle) =>1068 Redacted.make(`${handle.toLowerCase()}-seed-world-token-0123456789abcdef`);10691283/**1284 * The Node world (`apps/platform/test/world.ts`) served by a process of its1285 * own for as long as the scope lasts, with a session for each person in1286 * `sessions`; gives where it serves.1287 */1070export const servedWorld = (sessions: ReadonlyMap<Handle, Redacted.Redacted>) =>1071 Effect.gen(function* () {1072 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1073 const root = yield* repoRoot;
20 unmodified lines
1094 failed(`bun ${SERVE_WORLD} didn't start: ${error.message}`)1095 )1096 );10971316 // Both streams are read to their end, so the world never blocks on a1317 // full pipe; the last of what it said on stderr is kept for a failure.1098 // Both streams are drained so the world never blocks on a full pipe.1099 const said = yield* Ref.make("");1100 const serving = yield* Deferred.make<string>();11011102 yield* Stream.decodeText(child.stderr).pipe(
38 unmodified lines
1141 )1142 );1143 });11441364/**1365 * The seed's target over the Node world, served for as long as the layer1366 * lasts, where the operator and each of `people` have a session.1367 */1145export const worldTarget = (1146 people: readonly Handle[]1147): Layer.Layer<1148 SeedTarget,
16 unmodified lines
1165 });1166 })1167 );11681392// --------------------------------------------------------------- a stage13931394/** Where a stage's tokens come from: the env vars that hold them. */1169export interface StageTokens {1396 /** A JSON object from token to handle, as the platform's `SESSION_TOKENS` is. */1170 readonly sessions: string;1398 /** The operator's token, as the platform's `OPERATOR_TOKEN` is. */1171 readonly operator: string;1172}11731174const decodeSessions = Schema.decodeUnknownEffect(1175 Schema.fromJsonString(Schema.Record(Schema.String, Handle))1176);11771406/**1407 * The seed's target over a deployed stage at `origin`. Every token comes1408 * from the env (`bunx varlock run --path apps/platform/ -- …`), and none is1409 * ever printed, not even in a failure: the operator's from `tokens.operator`,1410 * everyone else's from `tokens.sessions`. The operator's handle is whoever1411 * the platform says their token names (`status`).1412 */1178export const stageTarget = (1179 origin: string,1180 tokens: StageTokens1181): Layer.Layer<
47 unmodified lines
modified:scripts/seed.ts+1 added-69 removed
1/**2 * seed: puts both fictional example projects on a platform, ready for the3 * demo, and changes nothing when run again.4 *5 * bun scripts/seed.ts --world node6 * bunx varlock run --path apps/platform/ -- bun scripts/seed.ts --stage dev-<user>7 *8 * `--world node` serves the Node world on this machine for the run9 * (`apps/platform/test/serve-world.ts`). `--stage <s>` seeds a deployed10 * stage at `--url`, or at the workers.dev origin bootstrap recorded, with11 * tokens only from the env: `SESSION_TOKENS` (token to handle, as the12 * platform's own; `--tokens-env` names another) and `OPERATOR_TOKEN`13 * (`--operator-env`). `--stage demo` also needs `--yes`: the user records14 * on it (H7). `--only <project>` seeds one example; `--json`15 * prints the versioned envelope.16 *17 * `--only <example> --as <name>` seeds a fresh copy of that example under18 * another project name (`--only burrow --as burrow-swarm-2`, which is the19 * operator's `oscabriel/burrow-swarm-2`), so a live run can take a family20 * nobody has touched while the example itself stays fresh for the21 * recording. A name some project has is refused. A copy on a stage22 * is written to the throwaway ledger (`infra/created.ts`, by `seed`) as soon23 * as the platform has made it, with its repo and each layer's repo.24 *25 * Each project is made, and main's first commit pushed, as the operator;26 * each ask is opened as the decider the project's config names, red first27 * on the platform's own Checker; then each layer the example keeps under28 * `layers/` (datekit's maintainers layer) is pushed by that decider to its29 * repo in the private namespace. It prints one line per step, one per30 * project, and a summary. The seed's core lives in `lib/seed.ts`.31 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Envelope } from "@repo/protocol/envelope";3import { Handle, keyOf, ProjectName } from "@repo/protocol/ids";4import {
32 unmodified lines
37 worldTarget,38} from "./lib/seed.ts";39import type { SeededProject, SeedPlan } from "./lib/seed.ts";4072/** The examples the seed knows, in the order it seeds them. */41export const EXAMPLES = ["examples/datekit", "examples/burrow"] as const;4275/** Where a seed goes: the Node world on this machine, or a deployed stage. */43export const SeedWhere = Schema.TaggedUnion({44 Stage: {45 stage: Stage,79 /** The env vars that hold the stage's tokens. */46 tokens: Schema.Struct({ operator: Schema.String, sessions: Schema.String }),47 url: Schema.optionalKey(Schema.String),48 },49 World: {},50});5152export type SeedWhere = typeof SeedWhere.Type;5388/** What `bun scripts/seed.ts` was asked to do. */54export interface SeedOptions {55 readonly where: SeedWhere;91 /** The one project to seed, when not both. */56 readonly only?: string;93 /** The name to seed `only`'s example under, as a fresh copy (`--as`). */57 readonly as?: ProjectName;95 /** Print the versioned envelope instead of lines. */58 readonly json: boolean;59}6099/** The flags the command takes; any other is a typo, refused. */61const FLAGS = new Set([62 "--as",63 "--json",64 "--only",
9 unmodified lines
74 "bun scripts/seed.ts --world node | --stage <dev-…|demo> [--url <origin>] [--tokens-env SESSION_TOKENS] [--operator-env OPERATOR_TOKEN] [--only <project> [--as <copy>]] [--json] [--yes]";7576const failed = (reason: string) => new SeedFailed({ reason });77117/** The stage `--stage` names, its tokens' env vars, and where it lives if `--url` says. */78const stageFrom = (argv: readonly string[]) =>79 Effect.gen(function* () {120 // infra's own reading of `--stage`, and its words when it names none.80 const stage = yield* stageOf(argv).pipe(81 Effect.mapError(({ message }) => failed(message))82 );83
24 unmodified lines
108 }),109 });110 });111153/**154 * `--as`'s name, for a copy of the example `--only` names: a project name,155 * and not the example's own. A bare word is the operator's156 * (`burrow-swarm-2` is `oscabriel/burrow-swarm-2`): the operator makes the157 * copy, and makes projects only in their own namespace.158 */112const copyName = (name: string, only: Option.Option<string>) =>113 Effect.gen(function* () {114 if (Option.isNone(only)) {115 return yield* failed(
19 unmodified lines
135 )136 : copy;137 });138186/** The command's flags, read; a seed of `demo` needs `--yes` (H7: the user records on it). */139export const optionsOf = (140 argv: readonly string[]141): Effect.Effect<SeedOptions, SeedFailed> =>142 Effect.gen(function* () {
47 unmodified lines
190 }),191 };192 });193242/**243 * Writes a copy on `stage` to the throwaway ledger, by the seed: the244 * project, its repo in the public namespace, and each layer's repo in the245 * private one, which the platform makes when main lands declaring it.246 */194export const recordCopy = (stage: Stage, plan: SeedPlan, at: DateTime.Utc) => {195 const { layers, projects } = resources(stage);196 const by = "seed";250 // The ledger names what the platform keeps: the project's key, which is251 // its Durable Object's id and its repo's name.197 // The project's key is both its Durable Object's id and its repo's name.198 const key = keyOf(plan.project);199200 const entries: readonly Created[] = [201 { at, by, kind: "project", name: key, stage },
12 unmodified lines
214 Effect.mapError(({ message }) => failed(`the throwaway ledger: ${message}`))215 );216};217272/** What `--json` prints for one seeded project. */218const SeededSummary = Schema.Struct({219 asks: Schema.Array(Schema.String),220 decider: Handle,221 main: Schema.optionalKey(Schema.String),
2 unmodified lines
224});225226type SeededSummary = typeof SeededSummary.Type;227283/** What `--json` prints: the versioned envelope over the steps and each project. */228export const SeedEnvelope = Envelope(229 Schema.Struct({230 projects: Schema.Array(SeededSummary),231 steps: Schema.Array(SeedStep),
5 unmodified lines
237 Schema.encodeEffect(Schema.fromJsonString(SeedEnvelope))(envelope),238 Console.log239 ).pipe(Effect.orDie);240297/** Where a stage's platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */241const stageOrigin = (where: (typeof SeedWhere.cases.Stage)["Type"]) =>242 Effect.gen(function* () {243 if (where.url !== undefined) {244 return where.url;
10 unmodified lines
255256 return platformOrigin(where.stage, subdomain);257 });258316/** Where the seed goes, said for a person, and the target there. */259const targetFor = (where: SeedWhere, plans: readonly SeedPlan[]) =>260 SeedWhere.match(where, {261 Stage: (stage) =>262 Effect.map(stageOrigin(stage), (origin) => ({
6 unmodified lines
269 target: worldTarget(plans.map(({ decider }) => decider)),270 }),271 });272331/** One step as the command prints it: `OpenAsk datekit/format-ordinal: done`. */273export const stepLine = ({ _tag, result, target }: SeedStep) =>274 `${_tag} ${target}: ${result}`;275335/** One project as the summary prints it. */276const projectLine = ({277 asks,278 decider,279 main,
6 unmodified lines
286 `decided by ${decider}`,287 ...ratchets.map((name) => `ratchet ${name}`),288 ].join(", ");289350/** What a plan's project holds now, for the summary. */290const summaryOf = (291 plan: SeedPlan,292 held: SeededProject | undefined293): SeededSummary => {
8 unmodified lines
302303 return landed === undefined ? summary : { ...summary, main: landed };304};305367/**368 * `bun scripts/seed.ts …`: plans each example, seeds it on the world or the369 * stage, then prints one line per step, one per project and a summary (or,370 * with `--json`, the versioned envelope). A refusal under `--json` prints371 * the envelope with it, and the command still fails.372 */306export const main = (argv: readonly string[]) =>307 Effect.gen(function* () {308 const options = yield* optionsOf(argv);309 const path = yield* Path.Path;
19 unmodified lines
329330 const say = (line: string) =>331 options.json ? Effect.void : Console.log(line);332400 // A copy on a stage goes to the throwaway ledger once it is made.333 const made = (plan: SeedPlan) =>334 SeedWhere.match(options.where, {335 Stage: ({ stage }) =>336 plan.copyOf === undefined
69 unmodified lines
modified:scripts/swarm.ts+1 added-58 removed
1/**2 * swarm: six fictional contributors, on four harnesses, each answer one child3 * of a project's split family on a stage: it plans them, prepares each4 * one's workspace and runs their harnesses.5 *6 * bun scripts/swarm.ts --stage dev-oscabriel --project oscabriel/burrow --dry-run7 * bunx varlock run --path apps/platform/ -- bun scripts/swarm.ts --stage dev-oscabriel8 *9 * `--dry-run` reads the project's open asks anonymously and prints the plan:10 * who answers which ask, on which territory, and the command that would11 * start their harness. It claims nothing, starts nothing and needs no token.12 *13 * Without it, each contributor claims their ask as themselves (their token14 * from `SESSION_TOKENS`, a JSON object from token to handle, as the15 * platform's own), reads the ask's page, gets a workspace with a clone of16 * the claim's fork, and is handed to the run loop, six at once. The17 * run's summary goes to `<swarm>/<run>/agents.json` (`SwarmDir`: the state18 * home's `<slug>/swarm/`, outside every checkout), and each claim's fork to19 * the throwaway ledger (`infra/created.ts`). Tokens reach a contributor's20 * processes only through their env, and no line or JSON this prints holds21 * one. Flags: `lib/swarm/args.ts`.22 *23 * `--view herdr` (for the video) runs from a herdr pane: each24 * harness runs interactively in a pane of its own, with a counter pane of25 * claims, pushes and landings (`lib/swarm/views/herdr.ts`). The loop and26 * its outcomes are the same.27 */1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { AskListing } from "@repo/protocol/domain/ask";3import { ClaimView } from "@repo/protocol/domain/claim";4import { Envelope } from "@repo/protocol/envelope";
54 unmodified lines
59import type { Ran } from "./lib/swarm/workspace.ts";6061const failed = (reason: string) => new SwarmFailed({ reason });6290/** The env var that holds the stage's people: a JSON object from token to handle. */63const SESSIONS_VARIABLE = "SESSION_TOKENS";6493/** Where the platform lives: `--url`, or the workers.dev subdomain bootstrap recorded. */65const originOf = (options: SwarmOptions) =>66 Option.match(options.url, {67 onNone: () =>68 recordedSubdomain.pipe(
7 unmodified lines
76 ),77 onSome: Effect.succeed,78 });79109/** One CLI command, run from this repo's source with Bun. */80const cli = (81 args: readonly string[],82 env: Readonly<Record<string, string | undefined>>83) => run({ args: [cliEntry, ...args], command: "bun", env });84115/** A refusal list in one line: `NotVouched, AskFull`. */85const tagsOf = (refusals: readonly Refusal[]) =>86 refusals.map(({ _tag }) => _tag).join(", ");87119/** The CLI refused the command: its refusals, for the run's summary. */88class Refused extends Schema.TaggedError<Refused>()("Refused", {89 reason: Schema.String,90 tags: Schema.Array(Schema.String),91}) {
1 unmodified line
93 return this.reason;94 }95}96129/**130 * What one CLI command printed under `--json`, decoded as its envelope: its131 * data, or `Refused` with its refusals. Output that is no envelope fails132 * with what the command printed, `scrub`bed of any secret.133 */97const envelopeOf =98 <A, I>(99 data: Schema.Codec<A, I>,100 what: string,
28 unmodified lines
129const isRefused = Schema.is(Refused);130131const Listed = Schema.Struct({ asks: Schema.Array(AskListing) });132170/** The project's open asks, read anonymously: no token, and no stored login of the user's. */133const listAsks = (origin: string, project: ProjectName) =>134 Effect.gen(function* () {135 const home = `${yield* SwarmDir}/anonymous`;136
9 unmodified lines
146147 return listed.asks;148 });149188/** The plan as the terminal shows it: one row per contributor, ending in the command that starts them. */150const planLines = (151 plan: SwarmPlan,152 origin: string,153 swarm: string
42 unmodified lines
196 ...nudged,197 ];198};199239/** A run's name: when it started, to the second, in UTC (`20261008-154500`). */200const runName = Effect.map(DateTime.now, (now) =>201 DateTime.formatIso(now)202 .slice(0, 19)203 .replaceAll(/[-:]/gu, "")204 .replace("T", "-")205);206247/** The commit of this repo the swarm runs from. */207const headCommit = Effect.gen(function* () {208 const root = yield* repoRoot;209210 const head = yield* run({
10 unmodified lines
221const decodeSessions = Schema.decodeUnknownEffect(222 Schema.fromJsonString(Schema.Record(Schema.String, Handle))223);224266/**267 * Each contributor's token, by handle, from `SESSION_TOKENS`; a missing268 * person fails before anything is claimed, naming them and never a token.269 */225/** A missing person fails before anything is claimed, naming them and never a token. */226const tokensFor = (handles: readonly Handle[]) =>227 Effect.gen(function* () {228 const raw = yield* Config.String(SESSIONS_VARIABLE).pipe(229 Effect.mapError(() =>
29 unmodified lines
259 `${SESSIONS_VARIABLE} has no session for ${missing.join(", ")}: add each to the stage's ${SESSIONS_VARIABLE} secret (in the stage's secrets file, STAGE_SECRETS_FILE), and to the env the swarm runs in, then run the swarm again`260 );261 });262307/** Records a claim's fork in the throwaway ledger, once. */263const recordFork = (stage: Stage, claim: ClaimView) =>264 Effect.gen(function* () {265 const namespace = resources(stage).projects;266
24 unmodified lines
291 ask: Schema.Struct({ id: Schema.NonEmptyString }),292 brief: Schema.NonEmptyString,293});294340/**341 * One contributor, from claim to the run loop: claims their ask as342 * themselves, reads its page, makes their workspace and hands it to343 * `runAgent`. A step that fails ends their run as `failed`, with any344 * refusals the claim met; it never stops the others.345 */295const contributorRun = (input: {296 readonly assignment: Assignment;297 readonly options: SwarmOptions;298 readonly origin: string;
90 unmodified lines
389 workspace: ready.success.workspace,390 });391 });392444/** One contributor's run as the summary prints it. */393const runLine = ({394 ask,395 attempts,396 handle,
13 unmodified lines
410 Schema.encodeEffect(Schema.fromJsonString(schema))(value),411 Console.log412 ).pipe(Effect.orDie);413466/**467 * `bun scripts/swarm.ts …`: plans the run from the project's open asks; with468 * `--dry-run`, prints the plan (or, with `--json`, the `SwarmPlan`) and469 * stops. Otherwise runs every contributor at once and writes the summary.470 */414export const main = (argv: readonly string[]) =>415 Effect.gen(function* () {416 const options = yield* optionsOf(argv);417 const origin = yield* originOf(options);
114 unmodified lines