Add bun infra/teardown.ts: it prints which of the ledger's throwaways still exist, and deletes exactly those only with --apply
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- infra/lib/teardown.ts: `teardownPlan` and `protectedNames` are pure. The plan is the ledger's live repos and namespaces on the stages named that the account still lists. Repos come first, newest first, so a fork goes before what it forks; namespaces come last, since Artifacts deletes only an empty one. A name absent from the ledger is never selected, whatever its prefix. A ledger entry the account no longer lists is gone already. - Never selectable: both Artifacts namespaces of every declared stage (not only the stages named), anything in `witness` (never even probed), and the seeded examples `datekit`, `datekit--maintainers` and `burrow`. Beyond the issue, every fork of datekit or burrow is also never selectable. Reason: the take's swarm records its claim forks of demo's burrow in the ledger, and a later --apply must not delete them from the demo stage. So dev's `burrow--drop-legacy-fetch-burrow-auth--wren` (ledger, a released claim) is listed as never selectable. - --apply checks `infra/.recording` first (806's `notRecording`, `RecordingInProgress`), before flags, the ledger or the account are read. The plan alone may print during a take: it only reads. - `TeardownAccount` is the seam: a namespace's repos come through `@repo/artifacts`' `RepoHost`. The live adapter in infra/teardown.ts makes one REST `RepoHost` per namespace, under the infra token from `varlock run --path infra/`, with `Fetch` over effect/http's fetch. Existence is `remote` (404 means gone), and the delete is `remove`. No repo token is minted. A namespace's own route (GET or DELETE) is called directly, as bootstrap does, since the port has no route for it. The ledger holds no namespace entry today. - Flags: --stage <declared stage> (the default is every declared stage the ledger names), --apply, and --keep <project>, which goes beyond the issue's interface. --keep leaves a copy's repo and its `<project>--…` forks out of the plan, so the user can keep an --as copy. Anything else is a `TeardownUsage`. - infra/created.ts: the ledger only grows. A `deleted` line (`deletedAt`, kind, name, namespace, stage) is appended for each repo removed, at once, so a run that stops partway is finished by running it again. `readLedger` folds each deleted line into the latest unmarked entry it names, as `deletedAt`. A run's own line never carries `deletedAt`. The same name made again after its delete is a new live entry. `isRecorded` is the one "already recorded" check, and scripts/swarm.ts now uses it. Without it, a fork teardown deleted and the swarm made again would go unrecorded. - Project entries are a Durable Object and a front-page row. Teardown leaves both, and the plan says so. - No agent ran --apply. This build's standing rule is that agents delete no Cloudflare resource, so the user runs the plan from a script they read first. It also deletes the pre-ledger leftovers that a read-only check found still there (19 W3/W4 repos, wren's stale fork of dev's burrow only while dev's web shows its ask unclaimed, `S8B_PROBE`, two test accounts and their three OAuth grants). `infra/stages.md` §3-§5 record the plan, what is kept and why, and the user's step. README and AGENTS.md now say how throwaways leave. - Found while checking: dev's `datekit--add-months-clamp--bram`, which W5 called a released claim's fork, belongs to a claim that is open again (dev's datekit llms.txt says Claimed), so it is kept. - Tests: packages/config/test/teardown.test.ts (18), each red by an assertion first. The plan over a fixture ledger and a fake listing: what is selected, never selected and gone already, stage scoping, namespace order, deleted entries. The ledger's deleted line and its fold, and `isRecorded`. The apply path over memory RepoHosts and a temp ledger: dry run, --apply then a converging second run, RecordingInProgress with nothing read, --keep, and usage errors. - ASSUMPTION: Artifacts deletes a repo that has forks without deleting the forks. The plan deletes forks first anyway. The plan, as `bunx varlock run --path infra/ -- bun infra/teardown.ts` printed it on 2026-10-08 at 18:00 UTC (nothing deleted): teardown on dev-oscabriel: 69 ledger entries, 52 to delete delete repo projects-dev-oscabriel/burrow-805--drop-legacy-fetch-burrow-kit--dagny delete repo projects-dev-oscabriel/burrow-805--drop-legacy-fetch-burrow-catalog--marisol delete repo projects-dev-oscabriel/datekit-805--add-months-clamp--bram delete repo projects-dev-oscabriel/datekit-805--parse-iso-week--bram delete repo projects-dev-oscabriel/datekit-805--format-ordinal--bram delete repo projects-dev-oscabriel/burrow-805--drop-legacy-fetch-burrow-auth--tamsin delete repo projects-dev-oscabriel/burrow-805--drop-legacy-fetch-burrow-billing--ivo delete repo projects-dev-oscabriel/burrow-805 delete repo layers-dev-oscabriel/datekit-805--maintainers delete repo projects-dev-oscabriel/datekit-805 delete repo projects-dev-oscabriel/smoke-20261008-165645--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-165645 delete repo projects-dev-oscabriel/smoke-20261008-165400--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-165400 delete repo projects-dev-oscabriel/smoke-20261008-165218--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-165218 delete repo projects-dev-oscabriel/smoke-20261008-165040--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-165040 delete repo projects-dev-oscabriel/smoke-20261008-164858--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-164858 delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-notify--dagny delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-billing--tamsin delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-auth--wren delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-catalog--ivo delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-kit--marisol delete repo projects-dev-oscabriel/burrow-swarm-2--drop-legacy-fetch-burrow-search--pell delete repo projects-dev-oscabriel/burrow-swarm-2 delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-billing--tamsin delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-search--pell delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-auth--wren delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-catalog--ivo delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-notify--dagny delete repo projects-dev-oscabriel/burrow-swarm-1 delete repo projects-dev-oscabriel/datekit-803--add-months-clamp--bram delete repo projects-dev-oscabriel/burrow-803--drop-legacy-fetch-burrow-auth--tamsin delete repo projects-dev-oscabriel/burrow-803--drop-legacy-fetch-burrow-billing--ivo delete repo projects-dev-oscabriel/datekit-803--format-ordinal--bram delete repo projects-dev-oscabriel/datekit-803--parse-iso-week--bram delete repo projects-dev-oscabriel/burrow-803 delete repo layers-dev-oscabriel/datekit-803--maintainers delete repo projects-dev-oscabriel/datekit-803 delete repo projects-dev-oscabriel/smoke-20261008-145715--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-145715 delete repo projects-dev-oscabriel/smoke-20261008-145551--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-145551 delete repo projects-dev-oscabriel/burrow-lint-807--drop-legacy-fetch-burrow-auth--wren delete repo projects-dev-oscabriel/burrow-lint-807 delete repo projects-dev-oscabriel/smoke-20261008-144139--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-144139 delete repo projects-dev-oscabriel/smoke-20261008-143944--parse-year--bram delete repo projects-dev-oscabriel/smoke-20261008-143944 never selectable: repo projects-dev-oscabriel/burrow--drop-legacy-fetch-burrow-auth--wren kept: 16 projects (smoke-20261008-143944, smoke-20261008-144139, burrow-lint-807, smoke-20261008-145551, smoke-20261008-145715, datekit-803, burrow-803, burrow-swarm-1, burrow-swarm-2, smoke-20261008-164858, smoke-20261008-165040, smoke-20261008-165218, smoke-20261008-165400, smoke-20261008-165645, datekit-805, burrow-805): each one's Durable Object and front-page row stay dry run: nothing deleted; --apply deletes exactly this plan
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+1414 added−36 removed
- tests:+656 added−0 removed
- other:+758 added−36 removed
Provenance
- Commit
f2215bd- Tree
d428793- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
0190ff0
8 files changed+1414 added−36 removed
added:infra/lib/teardown.ts+427 added
1+/**2+ * Teardown (issue 808): which throwaways a run may delete, and the run that3+ * deletes them. `bun infra/teardown.ts` prints the plan; only `--apply`4+ * deletes it, and never while a take is being recorded.5+ *6+ * The ledger (`infra/created.jsonl`) is the allow-list. A name the ledger7+ * doesn't hold is never selected, whatever it is called (a `smoke-` prefix8+ * proves nothing), and a ledger entry the account no longer lists is already9+ * gone. Nothing a stage owns is ever selectable: its namespaces10+ * (`projects-<s>`, `layers-<s>`), and the seeded examples it keeps (`datekit`11+ * with its maintainers layer, and `burrow`) with every fork of them, since a12+ * claim on demo's burrow during the take is recorded and must outlive it. Nor13+ * is anything in `witness`, which belongs to another project and is never even14+ * read. Workers, D1, KV and15+ * R2 are not Artifacts, so no listing names them and no plan can hold them. A16+ * project entry is a Durable Object and a front-page row: teardown leaves both17+ * (they are harmless, and not billed at this size), and says so.18+ *19+ * Repos are deleted through `@repo/artifacts`' `RepoHost`, one per namespace;20+ * each one deleted gets a `deleted` line in the ledger at once, so a run cut21+ * short is finished by running it again.22+ */23+import type { RepoHost } from "@repo/artifacts/repo-host";24+import { RepoName } from "@repo/protocol/ids";25+import { Console, Context, DateTime, Effect, Option, Schema } from "effect";26+import type { FileSystem, PlatformError } from "effect";27+28+import { readLedger, recordDeleted } from "../created.ts";29+import type { Created } from "../created.ts";30+import { notRecording } from "../recording.ts";31+import type { RecordingInProgress } from "../recording.ts";32+import { declaredStage, resources, stages as declared } from "../stages.ts";33+import type { Stage } from "../stages.ts";34+35+/** Something the account lists: a namespace, or a repo in one. */36+export interface Listed {37+ readonly kind: "namespace" | "repo";38+ readonly name: string;39+ /** The namespace that holds it, for a repo. */40+ readonly namespace?: string;41+}42+43+/** The namespace that belongs to another project. Never read, never deleted. */44+const witness = "witness";45+46+/** The examples the seed puts on every stage, kept with the stage. */47+const examples = ["datekit", "burrow"] as const;48+49+/** The seeded examples' repos: each example's own, and datekit's layer. */50+const seeded = [...examples, "datekit--maintainers"] as const;51+52+/**53+ * Names no plan selects: `witness`, the seeded examples, and both Artifacts54+ * namespaces of every stage named.55+ */56+export const protectedNames = (stages: readonly Stage[]): ReadonlySet<string> =>57+ new Set([58+ witness,59+ ...seeded,60+ ...stages.flatMap((stage) => {61+ const { layers, projects } = resources(stage);62+63+ return [projects, layers];64+ }),65+ ]);66+67+/** One resource's identity, the same for a ledger entry and a listed one. */68+const keyOf = (item: {69+ readonly kind: string;70+ readonly name: string;71+ readonly namespace?: string;72+}) => JSON.stringify([item.kind, item.namespace ?? "", item.name]);73+74+/** Whether `name` is the project `kept` or one of its repos (`<kept>--…`). */75+const ofProject = (name: string, kept: string) =>76+ name === kept || name.startsWith(`${kept}--`);77+78+/** What a plan is drawn from: the ledger, the stages it acts on, and the copies kept. */79+interface Scope {80+ readonly ledger: readonly Created[];81+ readonly stages: readonly Stage[];82+ /** Projects whose repos stay (`--keep`): the project's repo and every `<project>--…`. */83+ readonly keep?: readonly string[];84+}85+86+/** Whether a ledger entry is a namespace or repo teardown may ever delete. */87+const deletable = (entry: Created, guarded: ReadonlySet<string>) =>88+ !guarded.has(entry.name) &&89+ !examples.some((example) => ofProject(entry.name, example)) &&90+ (entry.kind === "namespace" ||91+ (entry.kind === "repo" &&92+ entry.namespace !== undefined &&93+ entry.namespace !== witness));94+95+/**96+ * The ledger's entries a run on `stages` may delete, before asking the97+ * account which still exist: not deleted yet, on one of the stages, not98+ * protected (on these stages or any stage this repo declares), not in99+ * `witness`, and not kept.100+ */101+const candidatesOf = (scope: Scope): readonly Created[] => {102+ const guarded = protectedNames([...declared, ...scope.stages]);103+104+ return scope.ledger.filter(105+ (entry) =>106+ entry.deletedAt === undefined &&107+ scope.stages.some((stage) => stage === entry.stage) &&108+ deletable(entry, guarded) &&109+ !(scope.keep ?? []).some((kept) => ofProject(entry.name, kept))110+ );111+};112+113+/**114+ * What to delete on `stages`: the ledger's namespaces and repos that the115+ * account still lists, minus every protected name and every kept copy. Repos116+ * come first, newest first, so a fork goes before the repo it forks;117+ * namespaces come last, since Artifacts deletes only an empty one.118+ */119+export const teardownPlan = (120+ input: Scope & { readonly listed: readonly Listed[] }121+): readonly Listed[] => {122+ const present = new Map(input.listed.map((item) => [keyOf(item), item]));123+124+ const chosen = new Map(125+ candidatesOf(input).flatMap((entry) => {126+ const item = present.get(keyOf(entry));127+128+ return item === undefined ? [] : [[keyOf(item), item] as const];129+ })130+ );131+132+ const newestFirst = [...chosen.values()].toReversed();133+134+ return [135+ ...newestFirst.filter(({ kind }) => kind === "repo"),136+ ...newestFirst.filter(({ kind }) => kind === "namespace"),137+ ];138+};139+140+/**141+ * The account's Artifacts, as teardown reaches it: a namespace's repos142+ * through `@repo/artifacts`' `RepoHost`, and namespaces themselves, which143+ * the port has no route for.144+ */145+export class TeardownAccount extends Context.Service<146+ TeardownAccount,147+ {148+ /** The repos of one namespace. */149+ readonly repos: (namespace: string) => Effect.Effect<RepoHost["Service"]>;150+ readonly namespaceExists: (name: string) => Effect.Effect<boolean>;151+ /** Deletes an empty namespace; whether it was there to delete. */152+ readonly removeNamespace: (name: string) => Effect.Effect<boolean>;153+ }154+>()("infra/TeardownAccount") {}155+156+/** `teardown` was given a flag it doesn't know, or a flag without its value. A usage error. */157+export class TeardownUsage extends Schema.TaggedError<TeardownUsage>()(158+ "TeardownUsage",159+ { given: Schema.String }160+) {161+ override get message() {162+ return `${this.given} is not understood: bun infra/teardown.ts [--stage <declared stage>] [--keep <project>]… [--apply]`;163+ }164+}165+166+interface Options {167+ readonly apply: boolean;168+ readonly stage: Option.Option<Stage>;169+ readonly keep: readonly string[];170+}171+172+/** The flags, read in order; anything else is a usage error. */173+const optionsOf = (174+ argv: readonly string[]175+): Effect.Effect<Options, TeardownUsage> =>176+ Effect.gen(function* () {177+ const keep: string[] = [];178+ let apply = false;179+ let stage = Option.none<Stage>();180+181+ for (let at = 0; at < argv.length; at += 1) {182+ const flag = argv[at] ?? "";183+184+ const value = Option.filter(185+ Option.fromNullishOr(argv[at + 1]),186+ (given) => given.length > 0 && !given.startsWith("--")187+ );188+189+ if (flag === "--apply") {190+ apply = true;191+ } else if (flag === "--stage" || flag === "--keep") {192+ if (Option.isNone(value)) {193+ return yield* new TeardownUsage({ given: flag });194+ }195+196+ if (flag === "--keep") {197+ keep.push(value.value);198+ } else {199+ stage = declaredStage(value.value);200+201+ if (Option.isNone(stage)) {202+ return yield* new TeardownUsage({ given: value.value });203+ }204+ }205+206+ at += 1;207+ } else {208+ return yield* new TeardownUsage({ given: flag });209+ }210+ }211+212+ return { apply, keep, stage };213+ });214+215+/** How a plan line names an item: its kind, then `<namespace>/<name>` for a repo. */216+const shown = (item: Listed | Created) =>217+ `${item.kind} ${item.namespace === undefined ? item.name : `${item.namespace}/${item.name}`}`;218+219+const repoName = Schema.decodeUnknownOption(RepoName);220+221+/** The repos of the namespace that holds `item`. */222+const hostOf = (item: Listed) =>223+ Effect.gen(function* () {224+ const account = yield* TeardownAccount;225+226+ const namespace = yield* Effect.fromNullishOr(item.namespace).pipe(227+ Effect.catch(() => Effect.die(`${item.name} names no namespace`))228+ );229+230+ return yield* account.repos(namespace);231+ });232+233+/** `entry` as the account lists it, if it still exists. */234+const probe = (entry: Created) =>235+ Effect.gen(function* () {236+ const account = yield* TeardownAccount;237+238+ const item: Listed =239+ entry.namespace === undefined240+ ? {241+ kind: entry.kind === "namespace" ? "namespace" : "repo",242+ name: entry.name,243+ }244+ : { kind: "repo", name: entry.name, namespace: entry.namespace };245+246+ if (item.kind === "namespace") {247+ return (yield* account.namespaceExists(item.name))248+ ? Option.some(item)249+ : Option.none<Listed>();250+ }251+252+ // A name no repo can have is no repo there.253+ const name = repoName(item.name);254+255+ if (Option.isNone(name)) {256+ return Option.none<Listed>();257+ }258+259+ const host = yield* hostOf(item);260+261+ return yield* host.remote(name.value).pipe(262+ Effect.as(Option.some(item)),263+ Effect.catchTag("RepoNotFound", () =>264+ Effect.succeed(Option.none<Listed>())265+ )266+ );267+ });268+269+/** Deletes one planned item; whether it was there to delete. */270+const remove = (item: Listed) =>271+ Effect.gen(function* () {272+ const account = yield* TeardownAccount;273+274+ if (item.kind === "namespace") {275+ return yield* account.removeNamespace(item.name);276+ }277+278+ const host = yield* hostOf(item);279+280+ const name = yield* Effect.fromOption(repoName(item.name)).pipe(281+ Effect.catch(() => Effect.die(`${item.name} is no repo name`))282+ );283+284+ return yield* host.remove(name);285+ });286+287+/** The stages the ledger names that this repo declares, in the ledger's order. */288+const ledgerStages = (ledger: readonly Created[]): readonly Stage[] => [289+ ...new Set(290+ ledger.flatMap((entry) => Option.toArray(declaredStage(entry.stage)))291+ ),292+];293+294+/** One stage's plan, printed, and with `apply` deleted: how many it deleted. */295+const onStage = (ledger: readonly Created[], stage: Stage, options: Options) =>296+ Effect.gen(function* () {297+ const scope = { keep: options.keep, ledger, stages: [stage] };298+ const entries = ledger.filter((entry) => entry.stage === stage);299+ const candidates = candidatesOf(scope);300+301+ const unique = [302+ ...new Map(candidates.map((entry) => [keyOf(entry), entry])).values(),303+ ];304+305+ const listed = (yield* Effect.forEach(unique, probe, {306+ concurrency: 8,307+ })).flatMap(Option.toArray);308+309+ const plan = teardownPlan({ ...scope, listed });310+ const there = new Set(listed.map(keyOf));311+ const live = entries.filter(({ deletedAt }) => deletedAt === undefined);312+ const chosen = new Set(candidates.map(keyOf));313+ const guarded = protectedNames([...declared, stage]);314+315+ const kept = live.filter(316+ (entry) =>317+ deletable(entry, guarded) &&318+ options.keep.some((name) => ofProject(entry.name, name))319+ );320+321+ const never = live.filter(322+ (entry) =>323+ entry.kind !== "project" &&324+ !chosen.has(keyOf(entry)) &&325+ !kept.includes(entry)326+ );327+328+ const projects = live.flatMap(({ kind, name }) =>329+ kind === "project" ? [name] : []330+ );331+332+ yield* Console.log(333+ `teardown on ${stage}: ${entries.length} ledger entries, ${plan.length} to delete`334+ );335+336+ yield* Effect.forEach(337+ [338+ ...plan.map((item) => ` delete ${shown(item)}`),339+ ...unique.flatMap((entry) =>340+ there.has(keyOf(entry)) ? [] : [` gone already: ${shown(entry)}`]341+ ),342+ ...kept.map((entry) => ` kept by --keep: ${shown(entry)}`),343+ ...never.map((entry) => ` never selectable: ${shown(entry)}`),344+ ...(projects.length === 0345+ ? []346+ : [347+ ` kept: ${projects.length} project${projects.length === 1 ? "" : "s"} (${projects.join(", ")}): each one's Durable Object and front-page row stay`,348+ ]),349+ ],350+ (line) => Console.log(line),351+ { discard: true }352+ );353+354+ if (!options.apply) {355+ return 0;356+ }357+358+ const deleted = yield* Effect.forEach(plan, (item) =>359+ Effect.gen(function* () {360+ if (!(yield* remove(item))) {361+ yield* Console.log(`gone already: ${shown(item)}`);362+363+ return false;364+ }365+366+ const at = yield* DateTime.now;367+368+ yield* Effect.forEach(369+ live.filter((entry) => keyOf(entry) === keyOf(item)),370+ (entry) => recordDeleted(entry, at),371+ { discard: true }372+ );373+374+ yield* Console.log(`deleted ${shown(item)}`);375+376+ return true;377+ })378+ );379+380+ const count = deleted.filter(Boolean).length;381+382+ yield* Console.log(383+ `deleted ${count} of ${plan.length}, each marked deleted in the ledger`384+ );385+386+ return count;387+ });388+389+/**390+ * `bun infra/teardown.ts [--stage <s>] [--keep <project>]… [--apply]`: prints391+ * the plan for `--stage`, or for every declared stage the ledger names, and392+ * with `--apply` deletes exactly that plan. `--apply` is refused while393+ * `infra/.recording` exists, before anything else is read.394+ */395+export const teardown = (396+ argv: readonly string[]397+): Effect.Effect<398+ void,399+ | TeardownUsage400+ | RecordingInProgress401+ | PlatformError.PlatformError402+ | Schema.SchemaError,403+ TeardownAccount | FileSystem.FileSystem404+> =>405+ Effect.gen(function* () {406+ if (argv.includes("--apply")) {407+ yield* notRecording;408+ }409+410+ const options = yield* optionsOf(argv);411+ const ledger = yield* readLedger;412+413+ const stages = Option.match(options.stage, {414+ onNone: () => ledgerStages(ledger),415+ onSome: (stage) => [stage],416+ });417+418+ yield* Effect.forEach(stages, (stage) => onStage(ledger, stage, options), {419+ discard: true,420+ });421+422+ if (!options.apply) {423+ yield* Console.log(424+ "dry run: nothing deleted; --apply deletes exactly this plan"425+ );426+ }427+ });modified:infra/created.ts+116 added-16 removed
6 unmodified lines789101112131415161713181915161718192020212223242526272829303132333435363738394041424344454647484950515253546 unmodified lines616263644265666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161175253545511811912012112212312412561621261271281291301311321331341351361371381391401411421431441451461471481491501511521531541558 unmodified lines16416516616780811681691701711721731741751761771781791801811821831841851866 unmodified lines * The ledger is committed and holds names only, never a token. A throwaway is * named by the job that made it and its run (`smoke-<run>`, `swarm-<run>`), * never by the brand (AGENTS.md principle 5); a `seed --as` copy keeps the * name it was given and is recorded by that name. * * History is only ever appended. When teardown deletes a throwaway it appends * a `deleted` line naming it (`deletedAt` and the entry's kind, name, * namespace and stage), and reading folds that line into the entry it names * as `deletedAt`; the entry's own line stays as it was written. */import { Context, Effect, FileSystem, Schema } from "effect";import type { PlatformError } from "effect";import type { DateTime, PlatformError } from "effect";
/** One throwaway resource, as the run that made it records it. */export const Created = Schema.Struct({ /** When the run made it. */ at: Schema.DateTimeUtcFromString, /** The job whose run made it. */ by: Schema.Literals(["smoke", "swarm", "seed"]),/** What names one resource, on the line that records it and on the one that marks it deleted. */const resourceFields = { kind: Schema.Literals(["namespace", "repo", "project"]), name: Schema.NonEmptyString, /** The Artifacts namespace that holds it, for a repo. */ namespace: Schema.optionalKey(Schema.NonEmptyString), stage: Schema.NonEmptyString,};
/** The line a run appends when it makes a throwaway. */const Made = Schema.Struct({ /** When the run made it. */ at: Schema.DateTimeUtcFromString, /** The job whose run made it. */ by: Schema.Literals(["smoke", "swarm", "seed"]), ...resourceFields,});
/** The line teardown appends when it deletes a throwaway. */const Deleted = Schema.Struct({ deletedAt: Schema.DateTimeUtcFromString, ...resourceFields,});
/** One throwaway resource, as the run that made it records it. */export const Created = Schema.Struct({ ...Made.fields, /** When teardown deleted it: read from a later `deleted` line, never written on the entry's own. */ deletedAt: Schema.optionalKey(Schema.DateTimeUtcFromString),});
export type Created = typeof Created.Type;
/** The ledger, relative to the repo root. */export const ledgerPath = "infra/created.jsonl";6 unmodified lines defaultValue: () => decodeURIComponent(new URL("created.jsonl", import.meta.url).pathname),});
const CreatedLine = Schema.fromJsonString(Created);const MadeLine = Schema.fromJsonString(Made);
const DeletedLine = Schema.fromJsonString(Deleted);
const Line = Schema.fromJsonString(Schema.Union([Made, Deleted]));
/** What names one resource on a stage, whichever line it is read from. */type Resource = Pick<Created, "kind" | "name" | "namespace" | "stage">;
/** Whether two lines name the same resource on the same stage. */const sameResource = (one: Resource, other: Resource): boolean => one.kind === other.kind && one.name === other.name && one.namespace === other.namespace && one.stage === other.stage;
/** * Each entry with the `deleted` lines folded in: a `deleted` line marks the * latest entry before it that names the same resource and is not yet marked. * One that matches no such entry changes nothing. */const folded = ( lines: readonly (typeof Made.Type | typeof Deleted.Type)[]): readonly Created[] => { const entries: Created[] = [];
for (const line of lines) { if ("deletedAt" in line) { const index = entries.findLastIndex( (entry) => entry.deletedAt === undefined && sameResource(line, entry) );
const marked = entries[index];
if (marked !== undefined) { entries[index] = { ...marked, deletedAt: line.deletedAt }; } } else { entries.push(line); } }
return entries;};
/** Appends one entry to the ledger as one JSON line. */export const recordCreated = ( entry: Created): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const file = yield* LedgerFile;
// A `Created` value always encodes: every field is a string or a DateTime. const line = yield* Schema.encodeEffect(CreatedLine)(entry).pipe( Effect.orDie ); // A `Created` value always encodes: every field is a string or a // DateTime. Its line is the run's own: a `deletedAt` is never written on it. const line = yield* Schema.encodeEffect(MadeLine)(entry).pipe(Effect.orDie);
yield* fs.writeFileString(file, `${line}\n`, { flag: "a" }); });
/** * Every entry in the ledger, in the order the runs wrote them. A ledger no run * has written yet is empty; a line that is not a `Created` entry fails it. * Appends a `deleted` line for `entry`, deleted at `at`; the entry's own line * is never rewritten. */export const recordDeleted = ( entry: Created, at: DateTime.Utc): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const file = yield* LedgerFile;
// Every field is a string or a DateTime, so the line always encodes; it // names the entry and when it was deleted, and nothing else of it. const line = yield* Schema.encodeEffect(DeletedLine)({ ...entry, deletedAt: at, }).pipe(Effect.orDie);
yield* fs.writeFileString(file, `${line}\n`, { flag: "a" }); });
/** * Every entry in the ledger, in the order the runs wrote them, each one * teardown deleted with its `deletedAt`. A ledger no run has written yet is * empty; a line that is neither a run's entry nor a `deleted` line fails it. */export const readLedger: Effect.Effect< readonly Created[], PlatformError.PlatformError | Schema.SchemaError, FileSystem.FileSystem8 unmodified lines const lines = (yield* fs.readFileString(file)) .split("\n") .filter((line) => line.length > 0);
return yield* Effect.forEach(lines, (line) => Schema.decodeEffect(CreatedLine)(line) return folded( yield* Effect.forEach(lines, (line) => Schema.decodeEffect(Line)(line)) );});
/** * Whether the ledger holds `resource` and teardown has not deleted it: a run * records what it makes once, and again once teardown deleted the last one. */export const isRecorded = ( ledger: readonly Created[], resource: Resource): boolean => ledger.some( (entry) => entry.deletedAt === undefined && sameResource(resource, entry) );
/** A throwaway's name: the job that made it, then its run (`smoke-r1`). */export const throwawayName = (by: Created["by"], run: string) => `${by}-${run}`;modified:infra/stages.md+46 added-9 removed
9 unmodified lines10 4. [Teardown policy](#4-teardown-policy)11 5. [Human steps status](#5-human-steps-status)12 6. [URLs](#6-urls)13 14-Sections 1 to 6 hold the state as of 2026-10-08, 16:00 UTC, read from the account with read-only calls.14+Sections 1 to 6 hold the state as of 2026-10-08, 18:00 UTC, read from the account with read-only calls.15 16 ## 1. Stages17 18 | Stage | What it is for | State on 2026-10-08 |62 unmodified lines81 | Seeded projects | `datekit` (with its `datekit--maintainers` layer repo in `layers-demo`) and `burrow` in `projects-demo` | seed | 2026-10-08 15:40 to 15:44 | keep: the recording takes them. Don't reseed over them; a fresh copy is `seed --as`. |82 83 ## 3. Throwaway ledger summary84 85-A throwaway is something a smoke run, a swarm run or a `seed --as` copy makes on a stage, beside the stage's own resources. Each run appends one JSON line for each throwaway to `infra/created.jsonl` (`infra/created.ts`), and teardown acts only on those lines.85+A throwaway is something a smoke run, a swarm run or a `seed --as` copy makes on a stage, beside the stage's own resources. Each run appends one JSON line for each throwaway to `infra/created.jsonl` (`infra/created.ts`), and teardown acts only on those lines. When teardown deletes one, it appends a `deleted` line naming it (`deletedAt`, then its kind, name, namespace and stage). No line is ever rewritten or removed.86 87-On 2026-10-08 at 17:00 UTC the ledger holds 57 entries, all on `dev-oscabriel`, and each still exists:87+On 2026-10-08 at 18:00 UTC the ledger holds 69 entries, all on `dev-oscabriel`: 16 projects and 53 repos. None is marked deleted yet. A read-only listing found every one of the 53 repos still there:88 89 | When (UTC) | By | Kind | Name | Where |90 | --- | --- | --- | --- | --- |91-| 2026-10-08 12:37 | swarm | repo | `burrow--drop-legacy-fetch-burrow-auth--wren` (a released claim's fork) | `projects-dev-oscabriel` |91+| 2026-10-08 12:37 | swarm | repo | `burrow--drop-legacy-fetch-burrow-auth--wren` (a released claim's fork of the stage's `burrow`) | `projects-dev-oscabriel` |92 | 2026-10-08 14:40 to 14:58 | smoke | project, repo, repo | four core-loop runs, `smoke-20261008-143944`, `smoke-20261008-144139`, `smoke-20261008-145551` and `smoke-20261008-145715`: each one's project, its repo, and its claim's fork `<project>--parse-year--bram` | `projects-dev-oscabriel` |93 | 2026-10-08 14:52 to 14:54 | seed | project, repo, repo | `burrow-lint-807`, a `seed --as` copy of burrow that proved the Checker runs burrow's lint lane, with its repo and wren's claim fork `burrow-lint-807--drop-legacy-fetch-burrow-auth--wren` | `projects-dev-oscabriel` |94 | 2026-10-08 16:07 to 16:21 | seed, swarm | 2 projects, 8 repos | the harness checks' copies: `datekit-803` (its repo, its layer repo `datekit-803--maintainers`, and bram's claim forks `--parse-iso-week--bram`, `--format-ordinal--bram` and `--add-months-clamp--bram`) and `burrow-803` (its repo, and tamsin's and ivo's claim forks) | `projects-dev-oscabriel`, the layer in `layers-dev-oscabriel` |95 | 2026-10-08 16:29 to 16:41 | seed, swarm | 2 projects, 14 repos | the swarm's two live runs: `burrow-swarm-1` and `burrow-swarm-2`, each a `seed --as` copy of burrow with its repo and the six contributors' claim forks `<project>--drop-legacy-fetch-burrow-<package>--<handle>` | `projects-dev-oscabriel` |96 | 2026-10-08 16:49 to 16:57 | smoke | 5 projects, 10 repos | five core-loop runs, `smoke-20261008-164858`, `smoke-20261008-165040`, `smoke-20261008-165218`, `smoke-20261008-165400` and `smoke-20261008-165645`, each with its repo and its claim's fork `<project>--parse-year--bram` | `projects-dev-oscabriel` |97+| 2026-10-08 17:12 to 17:39 | seed, swarm | 2 projects, 10 repos | the rehearsal's copies: `datekit-805` (its repo, its layer repo `datekit-805--maintainers`, and bram's three claim forks) and `burrow-805` (its repo, and the claim forks of tamsin, ivo, marisol and dagny) | `projects-dev-oscabriel`, the layer in `layers-dev-oscabriel` |98 98-The live runs before the ledger existed left throwaways that it doesn't hold, all on `dev-oscabriel`. Teardown lists them separately and checks each one still exists before it deletes anything:99+The live runs before the ledger existed left throwaways that it doesn't hold, all on `dev-oscabriel`. A read-only listing on 2026-10-08 at 18:00 UTC found each one still there:100 100-- In `projects-dev-oscabriel`, 25 repos on 2026-10-08. Two of them, `datekit` and `burrow`, are the stage's seeded examples, and their working and claim forks (`datekit--me--ines-v`, `datekit--format-ordinal--bram`, `datekit--add-months-clamp--bram`) belong to them. The rest are test projects and their forks: `w3live-muyjz31t`, `w3live-muyk0528`, `w3live-muyk72qm`, `w3live-muykamf1`, `w3live-muyklikt` (with `--parse-iso--alice`), `w3live-muyl0wps` (with `--parse-iso--alice`), `w3live-muyl2z12` (with `--parse-iso--alice`), `scratch-onpush-muykseuk`, `w4-rehearsal` (with `--first-day--alice`, `--canada-sunday--alice`, `--brazil-sunday--alice` and `--mexico-sunday--alice`), and `w4-ratchet` (with `--no-any-in-parser--alice` and `--pad-day--bob`).101+- In `projects-dev-oscabriel`, 75 repos. Of these, 53 are the ledger's. `datekit` and `burrow` are the stage's seeded examples, and their forks `datekit--me--ines-v`, `datekit--format-ordinal--bram` and `datekit--add-months-clamp--bram` belong to them. The other 19 are test projects and their forks: `w3live-muyjz31t`, `w3live-muyk0528`, `w3live-muyk72qm`, `w3live-muykamf1`, `w3live-muyklikt` (with `--parse-iso--alice`), `w3live-muyl0wps` (with `--parse-iso--alice`), `w3live-muyl2z12` (with `--parse-iso--alice`), `scratch-onpush-muykseuk`, `w4-rehearsal` (with `--first-day--alice`, `--canada-sunday--alice`, `--brazil-sunday--alice` and `--mexico-sunday--alice`), and `w4-ratchet` (with `--no-any-in-parser--alice` and `--pad-day--bob`).102+- In `layers-dev-oscabriel`, 3 repos: datekit's `datekit--maintainers` and the ledger's two copies' layers.103 - The secret `S8B_PROBE` on `platform-dev-oscabriel`.102-- The test accounts `w3tester-muyk9zdx` and `w5web-muz3airr` in `front-page-dev-oscabriel`, and the latter's OAuth grant in `oauth-dev-oscabriel`.104+- The test accounts `w3tester-muyk9zdx` and `w5web-muz3airr` in `front-page-dev-oscabriel` (no identity or credit rows), and their OAuth grants in `oauth-dev-oscabriel`: one for `w5web-muz3airr` and two for `w3tester-muyk9zdx`.105 - The Project Durable Objects and front-page rows of those test projects. They are harmless and are not deleted.106 105-`demo` has no throwaways, and nothing that makes them is meant to run there: the core-loop smoke and the swarm's rehearsals run on the dev stage, the swarm on a `seed --as` copy.107+`demo` has no throwaways: `projects-demo` holds `datekit` and `burrow`, and `layers-demo` holds `datekit--maintainers`. Nothing that makes throwaways is meant to run there before the take: the core-loop smoke and the swarm's rehearsals run on the dev stage, the swarm on a `seed --as` copy. The take's swarm on demo's `burrow` will record its claim forks in the ledger; teardown never selects them (section 4).108 109 ## 4. Teardown policy110 111 - This build deletes only throwaway resources recorded in `infra/created.jsonl` that it no longer needs.1 unmodified line113 - It never touches `witness`.114 115 No agent deletes a Cloudflare resource itself. Teardown first prints its plan: the ledger's entries that still exist, minus every stage's own names and `witness`. The deletes in that plan, together with the pre-ledger leftovers in section 3 that still exist, are written into one script that the user reads and then runs in their own terminal. A stage itself is torn down only by hand, by the user, as [Tear down a stage](#tear-down-a-stage) says.116 117+### The teardown tool118+119+```sh120+bunx varlock run --path infra/ -- bun infra/teardown.ts # print the plan121+bunx varlock run --path infra/ -- bun infra/teardown.ts --apply # delete exactly that plan122+bunx varlock run --path infra/ -- bun infra/teardown.ts --keep burrow-805 --stage dev-oscabriel123+```124+125+It reads the ledger, asks the account which of its repos and namespaces still exist (with the infra token, one name at a time), and prints the plan: what it would delete, what is already gone, and what the ledger holds but no plan may select. Without `--stage` it covers every declared stage the ledger names. `--keep <project>` leaves a `seed --as` copy's repo and every `<project>--…` fork out of the plan. Only `--apply` deletes, repos first and newest first, so a fork goes before what it forks, and a namespace last, since Artifacts deletes only an empty one. Repos go through `@repo/artifacts`' REST adapter. Each one deleted gets its `deleted` line at once, so a run that stops partway is finished by running it again. While `infra/.recording` exists, `--apply` is refused with `RecordingInProgress` before anything is read.126+127+No plan ever holds:128+129+- a name the ledger doesn't hold, whatever it is called;130+- either Artifacts namespace of any declared stage (`projects-<s>`, `layers-<s>`), or anything in `witness`, which is never even read;131+- the seeded examples `datekit`, `datekit--maintainers` and `burrow`, or any fork of `datekit` or `burrow`. A claim made on demo's `burrow` during the take is recorded in the ledger and has to outlive teardown;132+- a Worker, a D1 database, a KV namespace or an R2 bucket. Those are not Artifacts, so no listing names them;133+- a project's Durable Object or front-page row. A project entry stays, and the plan says so.134+135+### The teardown record136+137+| When (UTC) | What |138+| --- | --- |139+| 2026-10-08 18:00 | `bun infra/teardown.ts` printed the plan for `dev-oscabriel`: **52 repos to delete**. These are all of the ledger's repos except `burrow--drop-legacy-fetch-burrow-auth--wren`, a fork of the stage's `burrow` that is never selectable. 50 are in `projects-dev-oscabriel`: nine smoke runs' repos and forks, `burrow-lint-807`, `burrow-803`, `datekit-803`, `burrow-swarm-1`, `burrow-swarm-2`, `burrow-805` and `datekit-805`, each with its claim forks. 2 are in `layers-dev-oscabriel`: `datekit-803--maintainers` and `datekit-805--maintainers`. The 16 projects' Durable Objects and front-page rows stay. Nothing was deleted. |140+| 2026-10-08 18:00 | The build's agent wrote the user's teardown script. It runs the plan with `--apply`. It also deletes the 19 pre-ledger test repos in section 3, wren's fork of `burrow` (only while dev's web still shows that ask open and unclaimed), `S8B_PROBE`, the two test accounts and their three OAuth grants. Each one is checked again just before its delete. The script refuses to run while `infra/.recording` exists. |141+| when the user runs it | The ledger's `deleted` lines record each repo the tool deleted, and when. Commit `infra/created.jsonl` afterwards. |142+143+Kept, and why:144+145+- **The demo stage, whole.** It holds the recording and the submission.146+- **The dev stage's own resources** (section 2) and its seeded `datekit` (with `datekit--maintainers`) and `burrow`. The user decides whether to tear the stage down after submission.147+- **Dev's forks of datekit.** `datekit--me--ines-v` is ines-v's working fork. `datekit--format-ordinal--bram` holds bram's landed answer and its verdict notes. `datekit--add-months-clamp--bram` belongs to a claim that is open again.148+- **Every project's Durable Object and front-page row.** They are harmless, and not billed at this size. A test project's row stays on dev's front page after its repo is gone.149+- **Finished `Answer` Workflow instances** on `platform-dev-oscabriel`. They are records, not resources.150+- **Any `--as` copy the user still wants.** Add `--keep <project>` to the script's two teardown lines.151+152 ## 5. Human steps status153 154 As of 2026-10-08, after the demo's bootstrap. "Agent" is the build's agent.155 9 unmodified lines165 | H8: submitting | Open, due Oct 14 by noon PDT. | The demo URL is `https://web-demo.oscargabriel.workers.dev` (section 6). | Submit the repo URL, the video and the demo URL. |166 | H9: `docker login` | Not needed so far. No image pull has been rate-limited. | Nothing. | Only if a deploy's image pull is rate-limited: run `docker login` in your own terminal. |167 | ChatGPT usage for the swarm's tamsin | Not blocking: the fallback was taken on 2026-10-08. | OpenCode's ChatGPT sign-in hit its usage limit during the swarm's live rehearsal, and Codex says it is back on Oct 16, after the deadline. The roster now runs tamsin on `opencode-go/gpt-6-luna` (OpenCode Go, signed in). | Nothing. To show `openai/gpt-5.5` in the take instead, raise the ChatGPT plan's limit (a purchase, yours to make) and swap the roster's one line back. |168 | OpenCode Zen key for the swarm's pell | Not blocking: the fallback was taken on 2026-10-08. | pi here still has no OpenCode Zen key, so the roster now runs pell on `opencode-go/qwen3.8-flash`, as it ran in the swarm's live rehearsal on `dev-oscabriel`. | Nothing. To show Gemini flash in the take instead, add OpenCode Zen's key to pi and swap the roster's one line back. |132-| Deleting the throwaways | Open, after the rehearsal. | The teardown plan (section 4). | Read the teardown script and run it in your own terminal. |169+| Deleting the throwaways | Open: the script is ready, and nothing is deleted yet (section 4, [The teardown record](#the-teardown-record)). | `bun infra/teardown.ts` printed the plan (52 repos on `dev-oscabriel`), and the user's script runs it with `--apply`. The script also removes the pre-ledger leftovers that still exist and skips any that are already gone. | After the last take and before Oct 14, read the teardown script and run it in your own terminal. Then commit `infra/created.jsonl`, which now carries a `deleted` line for each repo removed. |170 171 ## 6. URLs172 173 The account's workers.dev subdomain is in `infra/workers-dev.json`. The demo's rows are filled in when it is deployed.121 unmodified linesadded:infra/teardown.ts+158 added
1+/**2+ * teardown: `bunx varlock run --path infra/ -- bun infra/teardown.ts3+ * [--stage <s>] [--keep <project>]… [--apply]`. Prints which throwaways the4+ * ledger (`infra/created.jsonl`) still has on the account, and with `--apply`5+ * deletes exactly those; `infra/lib/teardown.ts` decides what may be deleted,6+ * and `infra/stages.md` §4 says why.7+ *8+ * It reaches Artifacts with the infra token (`CLOUDFLARE_ACCOUNT_ID` and9+ * `CLOUDFLARE_API_TOKEN`, from `varlock run --path infra/`): repos through10+ * `@repo/artifacts`' REST adapter, one per namespace, and a namespace itself11+ * over the same REST API bootstrap uses to make one (`RepoHost` has no route12+ * for a namespace). It mints no repo token. Nothing it runs is a Wrangler or13+ * cf `delete`, and it touches no Worker, D1, KV or R2.14+ */15+import { BunRuntime, BunServices } from "@effect/platform-bun";16+import { Fetch, FetchFailed } from "@repo/artifacts/fetch";17+import { RepoHost } from "@repo/artifacts/repo-host";18+import { RepoHostRest } from "@repo/artifacts/repo-host/rest";19+import {20+ Config,21+ Context,22+ Effect,23+ Layer,24+ Option,25+ Redacted,26+ Scope,27+ Stdio,28+ SynchronizedRef,29+} from "effect";30+import { FetchHttpClient } from "effect/http";31+32+import { teardown, TeardownAccount } from "./lib/teardown.ts";33+34+const API = "https://api.cloudflare.com/client/v4";35+36+/** The infra credentials `varlock run --path infra/` puts in the environment. */37+const Credentials = Config.all({38+ accountId: Config.String("CLOUDFLARE_ACCOUNT_ID"),39+ token: Config.Redacted("CLOUDFLARE_API_TOKEN"),40+});41+42+/** Where a request went: the origin and the path, never a query or a header. */43+const placeOf = (request: Request) => {44+ const url = new URL(request.url);45+46+ return `${url.origin}${url.pathname}`;47+};48+49+/** The `Fetch` port over Bun's own fetch, as effect/http finds it. */50+const BunFetch = Layer.effect(51+ Fetch,52+ Effect.gen(function* () {53+ const send = yield* FetchHttpClient.Fetch;54+55+ return Fetch.of({56+ fetch: (request) =>57+ Effect.tryPromise({58+ catch: (cause) =>59+ new FetchFailed({60+ reason:61+ cause instanceof Error62+ ? `the request got no response: ${cause.name}`63+ : "the request got no response",64+ url: placeOf(request),65+ }),66+ try: () => send(request),67+ }),68+ });69+ })70+);71+72+/**73+ * The account over its REST API: a namespace's repos through a REST74+ * `RepoHost` made on first use and kept for the run, and a namespace's own75+ * route read or deleted directly, where 404 means it isn't there and any76+ * other refusal stops the run.77+ */78+const LiveAccount = Layer.effect(79+ TeardownAccount,80+ Effect.gen(function* () {81+ const { accountId, token } = yield* Credentials;82+ const fetch = yield* Fetch;83+ const scope = yield* Scope.Scope;84+85+ const hosts = yield* SynchronizedRef.make<86+ ReadonlyMap<string, RepoHost["Service"]>87+ >(new Map());88+89+ const repos = (namespace: string) =>90+ SynchronizedRef.modifyEffect(hosts, (all) =>91+ Option.match(Option.fromNullishOr(all.get(namespace)), {92+ onNone: () =>93+ Layer.buildWithScope(94+ RepoHostRest.layer({ accountId, namespace, token }),95+ scope96+ ).pipe(97+ Effect.provideService(Fetch, fetch),98+ Effect.map((context) => {99+ const host = Context.get(context, RepoHost);100+101+ return [host, new Map(all).set(namespace, host)] as const;102+ })103+ ),104+ onSome: (host) => Effect.succeed([host, all] as const),105+ })106+ );107+108+ /** One call to a namespace's own route: true on 200, false on 404. */109+ const namespaceCall = (name: string, method: "DELETE" | "GET") =>110+ Effect.gen(function* () {111+ const response = yield* fetch112+ .fetch(113+ new Request(114+ `${API}/accounts/${encodeURIComponent(accountId)}/artifacts/namespaces/${encodeURIComponent(name)}`,115+ {116+ headers: {117+ accept: "application/json",118+ authorization: `Bearer ${Redacted.value(token)}`,119+ },120+ method,121+ }122+ )123+ )124+ .pipe(Effect.orDie);125+126+ if (response.status === 200 || response.status === 404) {127+ return response.status === 200;128+ }129+130+ return yield* Effect.die(131+ `${method} namespace ${name} answered ${response.status}`132+ );133+ });134+135+ return TeardownAccount.of({136+ namespaceExists: (name) => namespaceCall(name, "GET"),137+ removeNamespace: (name) => namespaceCall(name, "DELETE"),138+ repos,139+ });140+ })141+);142+143+if (import.meta.main) {144+ BunRuntime.runMain(145+ Effect.gen(function* () {146+ const args = yield* (yield* Stdio.Stdio).args;147+148+ return yield* teardown(args);149+ }).pipe(150+ Effect.provide(151+ Layer.mergeAll(152+ LiveAccount.pipe(Layer.provide(BunFetch)),153+ BunServices.layer154+ )155+ )156+ )157+ );158+}added:packages/config/test/teardown.test.ts+656 added
1+/**2+ * Teardown (issue 808): `bun infra/teardown.ts` prints a plan, and only3+ * `--apply` deletes it. The plan is the ledger's throwaways that the account4+ * still lists, never a stage's own namespaces, never `witness`, never the5+ * seeded examples, and never a name the ledger doesn't hold, whatever it is6+ * called.7+ */8+import { NodeServices } from "@effect/platform-node";9+import { describe, expect, it } from "@effect/vitest";10+import {11+ Console,12+ Context,13+ DateTime,14+ Effect,15+ FileSystem,16+ Layer,17+ Path,18+ Ref,19+ Result,20+} from "effect";21+22+import {23+ isRecorded,24+ LedgerFile,25+ readLedger,26+ recordCreated,27+ recordDeleted,28+} from "../../../infra/created.ts";29+import type { Created } from "../../../infra/created.ts";30+import {31+ protectedNames,32+ teardown,33+ TeardownAccount,34+ teardownPlan,35+ TeardownUsage,36+} from "../../../infra/lib/teardown.ts";37+import type { Listed } from "../../../infra/lib/teardown.ts";38+import { LockFile, RecordingInProgress } from "../../../infra/recording.ts";39+import { RepoHost } from "../../artifacts/src/repo-host.ts";40+import { RepoHostMemory } from "../../artifacts/src/repo-host/memory.ts";41+import { RepoName } from "../../protocol/src/ids.ts";42+43+const dev = "dev-oscabriel";44+45+const projects = "projects-dev-oscabriel";46+47+const layers = "layers-dev-oscabriel";48+49+/** One ledger line, made by `by` on the dev stage; a repo's names its namespace. */50+const made = (51+ by: Created["by"],52+ kind: Created["kind"],53+ name: string,54+ namespace?: string55+): Created => {56+ const entry: Created = {57+ at: DateTime.makeUnsafe("2026-10-08T16:00:00Z"),58+ by,59+ kind,60+ name,61+ stage: dev,62+ };63+64+ return namespace === undefined ? entry : { ...entry, namespace };65+};66+67+const repo = (name: string, namespace = projects): Listed => ({68+ kind: "repo",69+ name,70+ namespace,71+});72+73+const namespace = (name: string): Listed => ({ kind: "namespace", name });74+75+/** A smoke run's project and repos, and a `seed --as` swarm copy's. */76+const ledger: readonly Created[] = [77+ made("smoke", "project", "smoke-r1"),78+ made("smoke", "repo", "smoke-r1", projects),79+ made("smoke", "repo", "smoke-r1--parse-year--bram", projects),80+ made("seed", "project", "burrow-swarm-1"),81+ made("seed", "repo", "burrow-swarm-1", projects),82+ made(83+ "swarm",84+ "repo",85+ "burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol",86+ projects87+ ),88+ made("seed", "repo", "datekit-805--maintainers", layers),89+];90+91+/** What the account lists: every ledger repo, and much that isn't the ledger's. */92+const listed: readonly Listed[] = [93+ repo("datekit"),94+ repo("burrow"),95+ repo("smoke-r1"),96+ repo("smoke-r1--parse-year--bram"),97+ repo("smoke-unrecorded"),98+ repo("burrow-swarm-1"),99+ repo("burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol"),100+ repo("w3live-muyjz31t"),101+ repo("datekit--maintainers", layers),102+ repo("datekit-805--maintainers", layers),103+ namespace(projects),104+ namespace(layers),105+ namespace("projects-demo"),106+ namespace("layers-demo"),107+ namespace("witness"),108+];109+110+describe("the teardown plan", () => {111+ it("selects a smoke run's repos and a swarm copy's repos that are in both the ledger and the listing, forks before what they fork", () => {112+ expect(teardownPlan({ ledger, listed, stages: [dev] })).toStrictEqual([113+ repo("datekit-805--maintainers", layers),114+ repo("burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol"),115+ repo("burrow-swarm-1"),116+ repo("smoke-r1--parse-year--bram"),117+ repo("smoke-r1"),118+ ]);119+ });120+121+ it("never selects witness, a stage's namespaces, the seeded examples or their forks, or a name absent from the ledger, even one that starts with smoke-", () => {122+ const stageNames: readonly Created[] = [123+ made("smoke", "namespace", "witness"),124+ made("smoke", "repo", "smoke-r9", "witness"),125+ made("smoke", "namespace", "projects-demo"),126+ made("smoke", "namespace", "layers-demo"),127+ made("smoke", "namespace", projects),128+ made("smoke", "namespace", layers),129+ made("seed", "repo", "datekit", projects),130+ made("seed", "repo", "burrow", projects),131+ made("seed", "repo", "datekit--maintainers", layers),132+ made(133+ "swarm",134+ "repo",135+ "burrow--drop-legacy-fetch-burrow-auth--wren",136+ projects137+ ),138+ {139+ ...made(140+ "swarm",141+ "repo",142+ "burrow--drop-legacy-fetch-burrow-kit--marisol",143+ "projects-demo"144+ ),145+ stage: "demo",146+ },147+ made("seed", "repo", "datekit--add-months-clamp--bram", projects),148+ ];149+150+ expect({151+ everyStage: teardownPlan({152+ ledger: stageNames,153+ listed: [154+ ...listed,155+ repo("smoke-r9", "witness"),156+ repo("burrow--drop-legacy-fetch-burrow-auth--wren"),157+ repo(158+ "burrow--drop-legacy-fetch-burrow-kit--marisol",159+ "projects-demo"160+ ),161+ repo("datekit--add-months-clamp--bram"),162+ ],163+ stages: [dev, "demo"],164+ }),165+ unrecorded: teardownPlan({166+ ledger: [],167+ listed,168+ stages: [dev, "demo"],169+ }),170+ }).toStrictEqual({ everyStage: [], unrecorded: [] });171+ });172+173+ it("treats a ledger entry the account no longer lists as already gone", () => {174+ expect(175+ teardownPlan({176+ ledger,177+ listed: listed.filter(({ name }) => !name.startsWith("smoke-")),178+ stages: [dev],179+ })180+ ).toStrictEqual([181+ repo("datekit-805--maintainers", layers),182+ repo("burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol"),183+ repo("burrow-swarm-1"),184+ ]);185+ });186+187+ it("acts only on the stages named, and still guards every declared stage's namespaces", () => {188+ const onDemo: Created = {189+ ...made("smoke", "repo", "smoke-d1", "projects-demo"),190+ stage: "demo",191+ };192+193+ const demoNamespace: Created = {194+ ...made("smoke", "namespace", "projects-demo"),195+ stage: dev,196+ };197+198+ expect({199+ demo: teardownPlan({200+ ledger: [onDemo],201+ listed: [repo("smoke-d1", "projects-demo")],202+ stages: ["demo"],203+ }),204+ dev: teardownPlan({205+ ledger: [onDemo, demoNamespace],206+ listed: [repo("smoke-d1", "projects-demo"), namespace("projects-demo")],207+ stages: [dev],208+ }),209+ }).toStrictEqual({ demo: [repo("smoke-d1", "projects-demo")], dev: [] });210+ });211+212+ it("deletes a ledger namespace only after the repos in it", () => {213+ expect(214+ teardownPlan({215+ ledger: [216+ made("smoke", "namespace", "smoke-r2"),217+ made("smoke", "repo", "smoke-r2", "smoke-r2"),218+ made("smoke", "repo", "smoke-r2--parse-year--bram", "smoke-r2"),219+ ],220+ listed: [221+ namespace("smoke-r2"),222+ repo("smoke-r2", "smoke-r2"),223+ repo("smoke-r2--parse-year--bram", "smoke-r2"),224+ ],225+ stages: [dev],226+ })227+ ).toStrictEqual([228+ repo("smoke-r2--parse-year--bram", "smoke-r2"),229+ repo("smoke-r2", "smoke-r2"),230+ namespace("smoke-r2"),231+ ]);232+ });233+234+ it("selects a repo the ledger holds only under the namespace it was made in", () => {235+ expect(236+ teardownPlan({237+ ledger: [made("smoke", "repo", "smoke-r3", projects)],238+ listed: [repo("smoke-r3", "projects-demo"), repo("smoke-r3", layers)],239+ stages: [dev],240+ })241+ ).toStrictEqual([]);242+ });243+});244+245+/** A fresh ledger file in a temp dir, for the scope of one test. */246+const tempLedger = Effect.gen(function* () {247+ const fs = yield* FileSystem.FileSystem;248+ const path = yield* Path.Path;249+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "teardown-808-" });250+251+ return path.join(dir, "created.jsonl");252+});253+254+describe("a deleted ledger entry", () => {255+ it.live(256+ "gains deletedAt from a deleted line appended after it, and its own line is never rewritten",257+ () =>258+ Effect.gen(function* () {259+ const fs = yield* FileSystem.FileSystem;260+ const file = yield* tempLedger;261+ const smokeRepo = made("smoke", "repo", "smoke-r1", projects);262+ const deletedAt = DateTime.makeUnsafe("2026-10-13T20:00:00Z");263+264+ const read = yield* Effect.gen(function* () {265+ yield* recordCreated(smokeRepo);266+ yield* recordDeleted(smokeRepo, deletedAt);267+268+ return yield* readLedger;269+ }).pipe(Effect.provideService(LedgerFile, file));270+271+ expect({272+ lines: (yield* fs.readFileString(file)).split("\n"),273+ read,274+ }).toStrictEqual({275+ lines: [276+ '{"at":"2026-10-08T16:00:00.000Z","by":"smoke","kind":"repo","name":"smoke-r1","namespace":"projects-dev-oscabriel","stage":"dev-oscabriel"}',277+ '{"deletedAt":"2026-10-13T20:00:00.000Z","kind":"repo","name":"smoke-r1","namespace":"projects-dev-oscabriel","stage":"dev-oscabriel"}',278+ "",279+ ],280+ read: [{ ...smokeRepo, deletedAt }],281+ });282+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))283+ );284+285+ it.live(286+ "is never planned again, while the same name made again after it is a new entry",287+ () =>288+ Effect.gen(function* () {289+ const file = yield* tempLedger;290+ const first = made("smoke", "repo", "smoke-r1", projects);291+292+ const fork = made(293+ "smoke",294+ "repo",295+ "smoke-r1--parse-year--bram",296+ projects297+ );298+299+ const again = {300+ ...first,301+ at: DateTime.makeUnsafe("2026-10-14T09:00:00Z"),302+ };303+304+ const read = yield* Effect.gen(function* () {305+ yield* recordCreated(first);306+ yield* recordCreated(fork);307+ yield* recordDeleted(308+ first,309+ DateTime.makeUnsafe("2026-10-13T20:00:00Z")310+ );311+ yield* recordDeleted(312+ fork,313+ DateTime.makeUnsafe("2026-10-13T20:00:01Z")314+ );315+ yield* recordCreated(again);316+317+ return yield* readLedger;318+ }).pipe(Effect.provideService(LedgerFile, file));319+320+ expect({321+ live: read.filter(({ deletedAt }) => deletedAt === undefined),322+ plan: teardownPlan({323+ ledger: read,324+ listed: [repo("smoke-r1"), repo("smoke-r1--parse-year--bram")],325+ stages: [dev],326+ }),327+ }).toStrictEqual({ live: [again], plan: [repo("smoke-r1")] });328+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))329+ );330+331+ it("is no longer recorded, so a run that makes the same name again records it again", () => {332+ const fork = made(333+ "swarm",334+ "repo",335+ "burrow--drop-legacy-fetch-burrow-auth--wren",336+ projects337+ );338+339+ const deletedAt = DateTime.makeUnsafe("2026-10-13T20:00:00Z");340+341+ expect({342+ deleted: isRecorded([{ ...fork, deletedAt }], fork),343+ live: isRecorded([fork], fork),344+ otherStage: isRecorded([fork], { ...fork, stage: "demo" }),345+ }).toStrictEqual({ deleted: false, live: true, otherStage: false });346+ });347+});348+349+describe("the protected names", () => {350+ it("are witness and both namespaces of every stage named", () => {351+ expect([...protectedNames([dev, "demo"])].toSorted()).toStrictEqual([352+ "burrow",353+ "datekit",354+ "datekit--maintainers",355+ "layers-demo",356+ "layers-dev-oscabriel",357+ "projects-demo",358+ "projects-dev-oscabriel",359+ "witness",360+ ]);361+ });362+});363+364+/**365+ * The account in memory: each namespace a memory `RepoHost` holding `repos`.366+ * A namespace it doesn't hold, `witness` among them, dies when read.367+ */368+const memoryAccount = (repos: Readonly<Record<string, readonly string[]>>) =>369+ Effect.gen(function* () {370+ const read = yield* Ref.make<readonly string[]>([]);371+372+ const hosts = new Map(373+ yield* Effect.forEach(Object.entries(repos), ([space, names]) =>374+ Effect.gen(function* () {375+ const host = Context.get(376+ yield* Layer.build(Layer.fresh(RepoHostMemory)),377+ RepoHost378+ );379+380+ yield* Effect.forEach(names, (name) =>381+ host.create(RepoName.make(name)).pipe(Effect.orDie)382+ );383+384+ return [space, host] as const;385+ })386+ )387+ );388+389+ const hostOf = (space: string) =>390+ Ref.update(read, (all) => [...all, space]).pipe(391+ Effect.andThen(392+ Effect.fromNullishOr(hosts.get(space)).pipe(393+ Effect.catch(() => Effect.die(`${space} was read`))394+ )395+ )396+ );397+398+ /** Of `names`, those the namespace still holds. */399+ const standing = (space: string, names: readonly string[]) =>400+ Effect.gen(function* () {401+ const host = yield* Effect.fromNullishOr(hosts.get(space)).pipe(402+ Effect.orDie403+ );404+405+ return yield* Effect.filter(names, (name) =>406+ host.remote(RepoName.make(name)).pipe(407+ Effect.as(true),408+ Effect.catchTag("RepoNotFound", () => Effect.succeed(false))409+ )410+ );411+ });412+413+ return {414+ account: TeardownAccount.of({415+ namespaceExists: (name) => Effect.succeed(hosts.has(name)),416+ removeNamespace: (name) => Effect.die(`${name} was deleted`),417+ repos: hostOf,418+ }),419+ read: Ref.get(read),420+ standing,421+ };422+ });423+424+/** A temp root with a ledger written from `entries` and no recording lock. */425+const tempRoot = (entries: readonly Created[]) =>426+ Effect.gen(function* () {427+ const fs = yield* FileSystem.FileSystem;428+ const path = yield* Path.Path;429+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "teardown-808-" });430+ const ledgerFile = path.join(dir, "created.jsonl");431+432+ yield* Effect.forEach(entries, recordCreated).pipe(433+ Effect.provideService(LedgerFile, ledgerFile)434+ );435+436+ return { ledgerFile, lock: path.join(dir, ".recording") };437+ });438+439+/** `teardown(argv)` over `account`: how it ended, and what it printed. */440+const tornDown = (441+ argv: readonly string[],442+ account: TeardownAccount["Service"],443+ files: { readonly ledgerFile: string; readonly lock: string }444+) =>445+ Effect.gen(function* () {446+ const printed: string[] = [];447+448+ const captured: Console.Console = {449+ ...console,450+ log: (...args: readonly unknown[]) => {451+ printed.push(args.map(String).join(" "));452+ },453+ };454+455+ const result = yield* teardown(argv).pipe(456+ Effect.provideService(TeardownAccount, account),457+ Effect.provideService(LedgerFile, files.ledgerFile),458+ Effect.provideService(LockFile, files.lock),459+ Effect.provideService(Console.Console, captured),460+ Effect.result461+ );462+463+ return { printed, result };464+ });465+466+/** The dev stage's two namespaces as a smoke run, a swarm copy and the seed left them. */467+const devRepos = {468+ [layers]: ["datekit--maintainers", "datekit-805--maintainers"],469+ [projects]: [470+ "datekit",471+ "burrow",472+ "smoke-r1",473+ "smoke-r1--parse-year--bram",474+ "smoke-unrecorded",475+ "burrow-swarm-1",476+ "burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol",477+ "w3live-muyjz31t",478+ ],479+};480+481+/** The ledger: `ledger` above, one repo already gone, and one in `witness`. */482+const devLedger: readonly Created[] = [483+ ...ledger,484+ made("smoke", "repo", "smoke-r0", projects),485+ made("smoke", "repo", "smoke-r9", "witness"),486+];487+488+const thePlan = [489+ "teardown on dev-oscabriel: 9 ledger entries, 5 to delete",490+ " delete repo layers-dev-oscabriel/datekit-805--maintainers",491+ " delete repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol",492+ " delete repo projects-dev-oscabriel/burrow-swarm-1",493+ " delete repo projects-dev-oscabriel/smoke-r1--parse-year--bram",494+ " delete repo projects-dev-oscabriel/smoke-r1",495+ " gone already: repo projects-dev-oscabriel/smoke-r0",496+ " never selectable: repo witness/smoke-r9",497+ " kept: 2 projects (smoke-r1, burrow-swarm-1): each one's Durable Object and front-page row stay",498+];499+500+describe("bun infra/teardown.ts", () => {501+ it.live("prints the plan and deletes nothing without --apply", () =>502+ Effect.gen(function* () {503+ const files = yield* tempRoot(devLedger);504+ const fake = yield* memoryAccount(devRepos);505+ const { printed, result } = yield* tornDown([], fake.account, files);506+507+ expect({508+ layers: yield* fake.standing(layers, devRepos[layers]),509+ ledger: (yield* readLedger.pipe(510+ Effect.provideService(LedgerFile, files.ledgerFile)511+ )).filter(({ deletedAt }) => deletedAt !== undefined),512+ printed,513+ projects: yield* fake.standing(projects, devRepos[projects]),514+ result: Result.isSuccess(result),515+ witnessRead: (yield* fake.read).includes("witness"),516+ }).toStrictEqual({517+ layers: devRepos[layers],518+ ledger: [],519+ printed: [520+ ...thePlan,521+ "dry run: nothing deleted; --apply deletes exactly this plan",522+ ],523+ projects: devRepos[projects],524+ result: true,525+ witnessRead: false,526+ });527+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))528+ );529+530+ it.live(531+ "--apply deletes exactly the plan through RepoHost's remove, marks each one deleted in the ledger, and a second run finds nothing left",532+ () =>533+ Effect.gen(function* () {534+ const files = yield* tempRoot(devLedger);535+ const fake = yield* memoryAccount(devRepos);536+ const first = yield* tornDown(["--apply"], fake.account, files);537+ const second = yield* tornDown(["--apply"], fake.account, files);538+539+ const read = yield* readLedger.pipe(540+ Effect.provideService(LedgerFile, files.ledgerFile)541+ );542+543+ expect({544+ deleted: read545+ .filter(({ deletedAt }) => deletedAt !== undefined)546+ .map(({ name }) => name),547+ first: first.printed,548+ layers: yield* fake.standing(layers, devRepos[layers]),549+ projects: yield* fake.standing(projects, devRepos[projects]),550+ second: second.printed,551+ witnessRead: (yield* fake.read).includes("witness"),552+ }).toStrictEqual({553+ deleted: [554+ "smoke-r1",555+ "smoke-r1--parse-year--bram",556+ "burrow-swarm-1",557+ "burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol",558+ "datekit-805--maintainers",559+ ],560+ first: [561+ ...thePlan,562+ "deleted repo layers-dev-oscabriel/datekit-805--maintainers",563+ "deleted repo projects-dev-oscabriel/burrow-swarm-1--drop-legacy-fetch-burrow-kit--marisol",564+ "deleted repo projects-dev-oscabriel/burrow-swarm-1",565+ "deleted repo projects-dev-oscabriel/smoke-r1--parse-year--bram",566+ "deleted repo projects-dev-oscabriel/smoke-r1",567+ "deleted 5 of 5, each marked deleted in the ledger",568+ ],569+ layers: ["datekit--maintainers"],570+ projects: [571+ "datekit",572+ "burrow",573+ "smoke-unrecorded",574+ "w3live-muyjz31t",575+ ],576+ second: [577+ "teardown on dev-oscabriel: 9 ledger entries, 0 to delete",578+ " gone already: repo projects-dev-oscabriel/smoke-r0",579+ " never selectable: repo witness/smoke-r9",580+ " kept: 2 projects (smoke-r1, burrow-swarm-1): each one's Durable Object and front-page row stay",581+ "deleted 0 of 0, each marked deleted in the ledger",582+ ],583+ witnessRead: false,584+ });585+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))586+ );587+588+ it.live(589+ "--apply is refused with RecordingInProgress while infra/.recording exists, before it reads the ledger or the account",590+ () =>591+ Effect.gen(function* () {592+ const fs = yield* FileSystem.FileSystem;593+ const files = yield* tempRoot(devLedger);594+ const fake = yield* memoryAccount(devRepos);595+596+ yield* fs.writeFileString(files.lock, "recording since a moment ago\n");597+598+ const { printed, result } = yield* tornDown(599+ ["--apply", "--stage", dev],600+ fake.account,601+ files602+ );603+604+ expect({605+ printed,606+ projects: yield* fake.standing(projects, devRepos[projects]),607+ read: yield* fake.read,608+ result,609+ }).toStrictEqual({610+ printed: [],611+ projects: devRepos[projects],612+ read: [],613+ result: Result.fail(new RecordingInProgress({ file: files.lock })),614+ });615+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))616+ );617+618+ it.live("--keep leaves a copy's repos and forks out of the plan", () =>619+ Effect.gen(function* () {620+ const files = yield* tempRoot(devLedger);621+ const fake = yield* memoryAccount(devRepos);622+623+ const { printed } = yield* tornDown(624+ ["--keep", "burrow-swarm-1", "--keep", "datekit-805"],625+ fake.account,626+ files627+ );628+629+ expect(printed.slice(0, 3)).toStrictEqual([630+ "teardown on dev-oscabriel: 9 ledger entries, 2 to delete",631+ " delete repo projects-dev-oscabriel/smoke-r1--parse-year--bram",632+ " delete repo projects-dev-oscabriel/smoke-r1",633+ ]);634+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))635+ );636+637+ it.live.each([638+ [["--stage", "prod"], "prod"],639+ [["--stage"], "--stage"],640+ [["--force"], "--force"],641+ [["--keep"], "--keep"],642+ ] as const)(643+ "refuses %j with TeardownUsage before it reads anything",644+ ([argv, given]) =>645+ Effect.gen(function* () {646+ const files = yield* tempRoot(devLedger);647+ const fake = yield* memoryAccount(devRepos);648+ const { result } = yield* tornDown(argv, fake.account, files);649+650+ expect({ read: yield* fake.read, result }).toStrictEqual({651+ read: [],652+ result: Result.fail(new TeardownUsage({ given })),653+ });654+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))655+ );656+});modified:scripts/swarm.ts+7 added-8 removed
43 unmodified lines44 Schema,45 Stdio,46 } from "effect";47 48-import { readLedger, recordCreated } from "../infra/created.ts";48+import { isRecorded, readLedger, recordCreated } from "../infra/created.ts";49 import {50 platformOrigin,51 recordedSubdomain,52 repoRoot,255 unmodified lines308 const recordFork = (stage: Stage, claim: ClaimView) =>309 Effect.gen(function* () {310 const namespace = resources(stage).projects;311 312- const known = (yield* readLedger).some(313- (entry) =>314- entry.kind === "repo" &&315- entry.name === claim.fork &&316- entry.namespace === namespace &&317- entry.stage === stage318- );312+ const known = isRecorded(yield* readLedger, {313+ kind: "repo",314+ name: claim.fork,315+ namespace,316+ stage,317+ });318 319 if (!known) {320 yield* recordCreated({321 at: yield* DateTime.now,267 unmodified linesmodified:AGENTS.md+1 added-1 removed
86 unmodified lines87 88 - **Competition rules apply to repo text.** Describe rival projects by mechanism, neutrally. All of this repo's code is public; no part of the submission lives in a private layer.89 - **Git.** Commit on branches and merge locally. Pushing and adding a remote are the user's to do.90 - **Env.** To see the env, run `bun run env:check` (`varlock load --agent`, values redacted). That is the only way to read it: `.env`, `.env.local` and `.env.*.local` stay closed. To add a variable, edit the `.env.schema` that owns it (`infra/` for tool credentials, an app's for its Worker) and ask the user to set the value. Product code reads a project's `.env.schema` only through `@repo/visibility`'s parser, and never resolves it.91-- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs: `bun infra/recording.ts on` makes every deploy refuse until a person runs `off`. `wrangler delete` auto-confirms in a non-interactive shell, so never run it without the user's OK; cf deletes need `--force` when non-interactive.91+- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs: `bun infra/recording.ts on` makes every deploy refuse until a person runs `off`. `wrangler delete` auto-confirms in a non-interactive shell, so never run it without the user's OK; cf deletes need `--force` when non-interactive. Throwaways leave through `bun infra/teardown.ts`, which prints its plan from the ledger (`infra/created.jsonl`); its `--apply` deletes, so it is the user's to run, as a cf `delete` is.92 - **Ported code is ours.** A ported file carries its upstream licence notice in its header; a vendored folder or a font keeps its licence file beside it. Change ported files freely; upstream `main` is never synced in. Borrowed code stays under 15% of the codebase (aim for about 5%).93 94 ## Effect traps95 50 unmodified linesmodified:README.md+3 added-2 removed
129 unmodified lines130 ```sh131 ./node_modules/.bin/varlock run --path apps/platform/ -- bun scripts/smoke.ts --stage dev-<you> --loop132 ```133 134-`infra/stages.md` lists every resource a stage owns, the secrets, and how a person tears a stage down by hand; no script deletes anything.134+`infra/stages.md` lists every resource a stage owns, the secrets, and how a person tears a stage down by hand; no script deletes a stage's own resources. Every throwaway a smoke loop, a swarm run or a `seed --as` copy makes is recorded in `infra/created.jsonl`. `bunx varlock run --path infra/ -- bun infra/teardown.ts` prints which of them still exist, and adding `--apply` deletes exactly those.135 136 ### Install the CLI137 138 The platform serves the CLI itself: the install script and the linux-x64 and darwin-arm64 binaries come from the stage's own `releases-<stage>` bucket:83 unmodified lines222 | The web's production build carries none of the dev world. | `apps/web/test/production-bundle.test.ts` |223 | Visibility plugs in by one marked line, and nothing else reaches into it. | `packages/config/test/cartridge.test.ts` |224 | Each Worker's bundle stays under its byte budget. | `bun run bytes:check` |225 | A deploy names its stage, runs `verify` first and smoke after, and none runs while a take is recorded (`bun infra/recording.ts on`). | `packages/config/test/deploy.test.ts`, `packages/config/test/recording.test.ts` |226+| Teardown deletes only the throwaways the ledger records, never a stage's namespaces, the seeded examples or their forks, or anything in `witness`, and never while a take is recorded. | `packages/config/test/teardown.test.ts` |227 | Every path and command in this README exists. | `packages/config/test/readme.test.ts` |228 229 What it does not promise:230 44 unmodified lines275 agent-kit/ generated agent files: the project skill, the AGENTS.md block, hooks, the command list276 testkit/ scenario builders, golden git transcripts, process fakes277 brand/ the name, and every identifier made from it278 config/ the vitest preset and the repo's own tests278-infra/ bootstrap, deploy, the recording lock, the stage table, smoke's probes279+infra/ bootstrap, deploy, the recording lock, the stage table, smoke's probes, teardown280 scripts/ brand and byte checks, seed, smoke, swarm, release281 examples/ datekit and burrow, fictional projects for the demo282 tools/oxlint/ the vendored anti-slop lint plugins283 docs/ decisions (adr/), agent conventions (agents/), the demo (demo/)73 unmodified lines