Merge build/211-testkit: tests build a project scenario, a fake Artifacts binding and git transcripts in one line each
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 625134d, eb8fd27 · Browse files · 10 files·+2403 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+2403 added−10 removed
- tests:+1145 added−10 removed
- other:+1258 added−0 removed
Provenance
- Commit
56730f7- Tree
b8609b0- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
625134d- Parent 2
eb8fd27
10 files changed+2403 added−10 removed
added:packages/testkit/src/clock.ts+25 added
12345678910111213141516171819202122232425/** * Time for tests, on top of the TestClock `@effect/vitest`'s `it.effect` * provides. Like everything in `@repo/testkit`, this module is for `test/` * directories only: no `src/` imports it (`imports:check` refuses one). */import { DateTime, Duration } from "effect";import type { Effect } from "effect";import { TestClock } from "effect/testing";
/** An ISO 8601 instant, such as `2026-10-07T12:00:00Z`, as a UTC date-time. */export const at = (iso: string): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(iso));
/** The instant every scenario starts at unless it is given another. */export const defaultNow: DateTime.Utc = at("2026-10-07T12:00:00Z");
/** * Moves the TestClock to an instant, waking everything that sleeps until then: * `advanceTo("2026-10-07T14:00:00Z")` lets a claim's two-hour alarm fire. */export const advanceTo = (iso: string): Effect.Effect<void> => TestClock.setTime(DateTime.toEpochMillis(at(iso)));
/** `n` hours, the unit claims are warned and lapsed in. */export const hours = (n: number): Duration.Duration => Duration.hours(n);added:packages/testkit/src/fake-artifacts-binding.ts+657 added
1+/**2+ * A fake of the Workers `Artifacts` binding over a repo host, for tests of3+ * code that takes the binding. It keeps the surprises the spikes found in the4+ * real one:5+ *6+ * - under `wrangler dev`, errors arrive as plain `Error`s with no `code`7+ * (S1 #22): pass `{ codeless: true }`;8+ * - under load, a fork answers HTTP 500 after making the repo, and the retry9+ * answers 409 (S7 #2): pass `{ forkFailures: n }`;10+ * - reads by ref resolve short branch names and commit ids only, never11+ * `refs/heads/main` (S1 #20);12+ * - `info().lastPushAt` stays `null` after pushes (S1 #21).13+ *14+ * It takes its host structurally (`HostLike`), so `@repo/testkit` depends on15+ * no adapter package: a `RepoHost` service value satisfies `HostLike`. Each16+ * call runs the host's Effect with `Effect.runPromise`, since the binding is17+ * a promise API; this is a test double, in a package only tests import.18+ *19+ * Like everything in `@repo/testkit`, this module is for `test/` directories20+ * only: no `src/` imports it (`imports:check` refuses one).21+ */22+import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";23+import {24+ Data,25+ DateTime,26+ Duration,27+ Effect,28+ Match,29+ Option,30+ Redacted,31+ Schema,32+} from "effect";33+import { constVoid } from "effect/Function";34+35+import { defaultNow } from "./clock.ts";36+37+/** A git object id, branded as `@repo/artifacts`' `ObjectId` is. */38+export const ObjectId = Schema.String.pipe(39+ Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),40+ Schema.brand("ObjectId")41+);42+43+export type ObjectId = typeof ObjectId.Type;44+45+/** A short branch name, branded as `@repo/artifacts`' `BranchName` is. */46+export const BranchName = Schema.String.pipe(47+ Schema.check(48+ Schema.isPattern(49+ /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u50+ )51+ ),52+ Schema.brand("BranchName")53+);54+55+export type BranchName = typeof BranchName.Type;56+57+/** Where a read starts, as `@repo/artifacts`' `Revision` has it. */58+export type Revision = Data.TaggedEnum<{59+ Branch: { readonly name: BranchName };60+ Commit: { readonly sha: CommitSha };61+}>;62+63+export const Revision = Data.taggedEnum<Revision>();64+65+/** What a host fails with: `RepoHost`'s errors, by shape. */66+export type HostError =67+ | { readonly _tag: "RepoNotFound"; readonly name: RepoName }68+ | { readonly _tag: "RepoExists"; readonly name: RepoName }69+ | { readonly _tag: "ForkInProgress"; readonly name: RepoName }70+ | {71+ readonly _tag: "ImportRefused";72+ readonly name: RepoName;73+ readonly reason: string;74+ }75+ | { readonly _tag: "HostBusy"; readonly name: RepoName };76+77+interface Person {78+ readonly email: string;79+ readonly name: string;80+}81+82+interface HostCommit {83+ readonly author: Person;84+ readonly committer: Person;85+ readonly message: string;86+ readonly parents: readonly string[];87+ readonly sha: string;88+ readonly tree: string;89+}90+91+interface HostTreeEntry {92+ readonly mode: "100644" | "100755" | "120000" | "040000" | "160000";93+ readonly name: string;94+ readonly sha: string;95+ readonly type: "blob" | "tree" | "commit";96+}97+98+interface HostCreated {99+ readonly name: string;100+ readonly remote: string;101+}102+103+/**104+ * The `RepoHost` methods the fake calls, by shape: the same parameters, with105+ * the domain's ids, and results at least as wide. A `RepoHost` service value106+ * is one.107+ */108+export interface HostLike {109+ readonly create: (name: RepoName) => Effect.Effect<HostCreated, HostError>;110+ readonly importFrom: (111+ name: RepoName,112+ source: { readonly url: string; readonly branch?: BranchName }113+ ) => Effect.Effect<HostCreated, HostError>;114+ readonly fork: (115+ base: RepoName,116+ name: RepoName117+ ) => Effect.Effect<HostCreated, HostError>;118+ readonly remove: (name: RepoName) => Effect.Effect<boolean>;119+ readonly mintToken: (120+ name: RepoName,121+ scope: "read" | "write",122+ ttl: Duration.Duration123+ ) => Effect.Effect<124+ {125+ readonly id: string;126+ readonly secret: Redacted.Redacted;127+ readonly scope: "read" | "write";128+ readonly expiresAt: DateTime.Utc;129+ },130+ HostError131+ >;132+ readonly revokeToken: (133+ name: RepoName,134+ id: string135+ ) => Effect.Effect<boolean, HostError>;136+ readonly remote: (name: RepoName) => Effect.Effect<string, HostError>;137+ readonly readFile: (138+ name: RepoName,139+ at: Revision,140+ path: RepoPath141+ ) => Effect.Effect<Option.Option<Uint8Array>, HostError>;142+ readonly readCommit: (143+ name: RepoName,144+ sha: CommitSha145+ ) => Effect.Effect<Option.Option<HostCommit>, HostError>;146+ readonly readTree: (147+ name: RepoName,148+ tree: ObjectId149+ ) => Effect.Effect<Option.Option<readonly HostTreeEntry[]>, HostError>;150+ readonly readBlob: (151+ name: RepoName,152+ blob: ObjectId153+ ) => Effect.Effect<Option.Option<Uint8Array>, HostError>;154+ readonly log: (155+ name: RepoName,156+ at: Revision,157+ limit: number158+ ) => Effect.Effect<readonly HostCommit[], HostError>;159+}160+161+export interface FakeOptions {162+ /** Throw plain `Error`s with no `code`, as remote bindings under `wrangler dev` do. */163+ readonly codeless?: boolean;164+ /** How many forks fail with a 500 after making the repo, as under load. */165+ readonly forkFailures?: number;166+ /** Remotes are `<remoteBase>/<name>.git`, for a git server the test runs; else the host's. */167+ readonly remoteBase?: string;168+}169+170+/** A refusal the binding throws, before it becomes the thrown error. */171+class Refused extends Data.TaggedError("Refused")<{172+ readonly code: ArtifactsError["code"];173+ readonly reason: string;174+}> {}175+176+/**177+ * The REST API's numeric code for each binding code. The spikes recorded two178+ * (S7: 10201 and 10400); the rest are unknown and read 0, so tests match on179+ * `code`.180+ */181+const numericCodes = {182+ ALREADY_EXISTS: 10_201,183+ INTERNAL_ERROR: 10_400,184+} as const;185+186+const numericOf = (code: ArtifactsError["code"]) =>187+ Match.value(code).pipe(188+ Match.when("ALREADY_EXISTS", () => numericCodes.ALREADY_EXISTS),189+ Match.when("INTERNAL_ERROR", () => numericCodes.INTERNAL_ERROR),190+ Match.orElse(() => 0)191+ );192+193+/** A host's error as the binding words it (S1 #22, S7 #2); a refusal stays as it is. */194+const refusalOf = (error: HostError | Refused) =>195+ Match.valueTags(error, {196+ ForkInProgress: ({ name }) =>197+ new Refused({198+ code: "FORK_IN_PROGRESS",199+ reason: `Fork in progress: ${name}`,200+ }),201+ HostBusy: () =>202+ new Refused({203+ code: "INTERNAL_ERROR",204+ reason: "An internal error occurred.",205+ }),206+ ImportRefused: ({ reason }) => new Refused({ code: "INVALID_URL", reason }),207+ Refused: (refused) => refused,208+ RepoExists: ({ name }) =>209+ new Refused({210+ code: "ALREADY_EXISTS",211+ reason: `repo already exists: ${name}`,212+ }),213+ RepoNotFound: ({ name }) =>214+ new Refused({215+ code: "NOT_FOUND",216+ reason: `Repository not found: ${name}`,217+ }),218+ });219+220+/** The repos the fake made, with what `info()` and `list()` report. */221+interface Kept {222+ readonly id: string;223+ readonly name: RepoName;224+ readonly description: string | null;225+ readonly defaultBranch: string;226+ readonly source: string | null;227+ readonly readOnly: boolean;228+ readonly tokens: Map<229+ string,230+ ArtifactsTokenInfo & { readonly plaintext: string }231+ >;232+}233+234+// Artifacts stamps repos with the time they were made; the fake with the235+// scenarios' fixed instant, so two runs give the same values.236+const stamped = DateTime.formatIso(defaultNow);237+238+const isObjectId = Schema.is(ObjectId);239+240+const decodeName = Schema.decodeUnknownOption(RepoName);241+242+const decodeBranch = Schema.decodeUnknownOption(BranchName);243+244+const decodePath = Schema.decodeUnknownOption(RepoPath);245+246+/**247+ * `main` → that branch; 40 hex digits → that commit; anything else, such as248+ * `refs/heads/main` or a tag, resolves to nothing (S1 #20).249+ */250+const revisionOf = (ref: string): Option.Option<Revision> =>251+ isObjectId(ref)252+ ? Option.some(Revision.Commit({ sha: CommitSha.make(ref) }))253+ : Option.map(decodeBranch(ref), (name) => Revision.Branch({ name }));254+255+// Artifacts gives canonical modes: a folder is `40000`, not `040000`.256+const typeOf = (entry: HostTreeEntry): ArtifactsTreeEntryType =>257+ Match.value(entry.mode).pipe(258+ Match.when("040000", () => "tree" as const),259+ Match.when("100755", () => "exec" as const),260+ Match.when("120000", () => "symlink" as const),261+ Match.when("160000", () => "gitlink" as const),262+ Match.orElse(() => "blob" as const)263+ );264+265+const entryOf = (entry: HostTreeEntry): ArtifactsTreeEntry => ({266+ hash: entry.sha,267+ mode: entry.mode.replace(/^0/u, ""),268+ name: entry.name,269+ type: typeOf(entry),270+});271+272+// `RepoHost`'s commits carry no times, so the fake reports the epoch.273+const metadataOf = (commit: HostCommit): ArtifactsCommitMetadata => ({274+ author: { email: commit.author.email, name: commit.author.name },275+ authoredAt: 0,276+ committedAt: 0,277+ committer: { email: commit.committer.email, name: commit.committer.name },278+ hash: commit.sha,279+ message: commit.message,280+ parents: [...commit.parents],281+ treeHash: commit.tree,282+});283+284+const refuse = (code: ArtifactsError["code"], reason: string) =>285+ Effect.fail(new Refused({ code, reason }));286+287+const named = (name: string, code: ArtifactsError["code"]) =>288+ Option.match(decodeName(name), {289+ onNone: () => refuse(code, `Invalid repository name: ${name}`),290+ onSome: Effect.succeed,291+ });292+293+const objectId = (hash: string): Effect.Effect<ObjectId, Refused> =>294+ isObjectId(hash)295+ ? Effect.succeed(hash)296+ : refuse("INVALID_INPUT", `Invalid object id: ${hash}`);297+298+const blobOf = (bytes: Uint8Array) =>299+ new Blob([bytes], { type: "application/octet-stream" });300+301+/** An Artifacts binding over `host`, with the real one's surprises (see the module's doc). */302+export const fakeArtifactsBinding = (303+ host: HostLike,304+ options: FakeOptions = {}305+): Artifacts => {306+ const kept = new Map<RepoName, Kept>();307+ let forkFailures = options.forkFailures ?? 0;308+ let made = 0;309+310+ /** The thrown error: an `ArtifactsError`, or a plain one when codeless. */311+ const thrown = ({ code, reason }: Refused) =>312+ options.codeless === true313+ ? new Error(`ArtifactsError: ${reason}`)314+ : Object.assign(new Error(reason), {315+ code,316+ name: "ArtifactsError" as const,317+ numericCode: numericOf(code),318+ });319+320+ /** Runs one call as the binding answers: a promise, rejected with its error. */321+ const run = <A>(effect: Effect.Effect<A, Refused | HostError>) =>322+ Effect.runPromise(323+ Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))324+ );325+326+ const remoteOf = (name: RepoName) =>327+ options.remoteBase === undefined328+ ? host.remote(name)329+ : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));330+331+ const keep = (332+ name: RepoName,333+ fields: Partial<334+ Pick<Kept, "description" | "defaultBranch" | "readOnly" | "source">335+ >336+ ) => {337+ made += 1;338+339+ const repo: Kept = {340+ defaultBranch: fields.defaultBranch ?? "main",341+ description: fields.description ?? null,342+ id: `repo-${String(made).padStart(6, "0")}`,343+ name,344+ readOnly: fields.readOnly ?? false,345+ source: fields.source ?? null,346+ tokens: new Map(),347+ };348+349+ kept.set(name, repo);350+351+ return repo;352+ };353+354+ /**355+ * The fake's record of a repo the host has: the one it made, or a fresh one356+ * for a repo made on the host directly. A repo the host lacks fails with357+ * `RepoNotFound` and leaves no record, so `list()` never shows it.358+ */359+ const keptOf = (name: RepoName) =>360+ host.remote(name).pipe(Effect.map(() => kept.get(name) ?? keep(name, {})));361+362+ const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>363+ Effect.gen(function* () {364+ const token = yield* host.mintToken(365+ name,366+ scope,367+ Duration.seconds(seconds)368+ );369+370+ const { tokens } = yield* keptOf(name);371+ const plaintext = Redacted.value(token.secret);372+ const expiresAt = DateTime.formatIso(token.expiresAt);373+374+ tokens.set(token.id, {375+ createdAt: stamped,376+ expiresAt,377+ id: token.id,378+ plaintext,379+ scope,380+ state: "active",381+ });382+383+ return { expiresAt, id: token.id, plaintext, scope: token.scope };384+ });385+386+ /** A new repo's result: its metadata, its remote and a day-long write token (S1 #2). */387+ const createdOf = (repo: Kept) =>388+ Effect.gen(function* () {389+ const remote = yield* remoteOf(repo.name);390+ const token = yield* mint(repo.name, "write", 86_400);391+392+ return {393+ defaultBranch: repo.defaultBranch,394+ description: repo.description,395+ id: repo.id,396+ name: repo.name,397+ remote,398+ token: token.plaintext,399+ };400+ });401+402+ /** What `list()` shows of a repo; `info()` adds its remote. */403+ const summaryOf = (repo: Kept): Omit<ArtifactsRepoInfo, "remote"> => ({404+ createdAt: stamped,405+ defaultBranch: repo.defaultBranch,406+ description: repo.description,407+ id: repo.id,408+ // Still null after pushes (S1 #21).409+ lastPushAt: null,410+ name: repo.name,411+ readOnly: repo.readOnly,412+ source: repo.source,413+ updatedAt: stamped,414+ });415+416+ const info = (repo: Kept) =>417+ remoteOf(repo.name).pipe(418+ Effect.map((remote): ArtifactsRepoInfo => ({419+ ...summaryOf(repo),420+ remote,421+ }))422+ );423+424+ const handle = (name: RepoName): ArtifactsRepo => ({425+ createToken: (scope = "write", ttl = 86_400) =>426+ run(427+ ttl < 60 || ttl > 31_536_000428+ ? refuse("INVALID_TTL", `ttl must be between 60 and 31536000: ${ttl}`)429+ : mint(name, scope, ttl).pipe(430+ Effect.map(({ expiresAt, id, plaintext }) => ({431+ expiresAt,432+ id,433+ plaintext,434+ scope,435+ }))436+ )437+ ),438+ fork: (target, forkOptions) =>439+ run(440+ Effect.gen(function* () {441+ const fork = yield* named(target, "INVALID_REPO_NAME");442+443+ yield* host.fork(name, fork);444+445+ const repo = keep(fork, {446+ description: forkOptions?.description ?? null,447+ readOnly: forkOptions?.readOnly ?? false,448+ source: `artifacts:fake/${name}`,449+ });450+451+ if (forkFailures > 0) {452+ forkFailures -= 1;453+454+ return yield* refuse(455+ "INTERNAL_ERROR",456+ "An internal error occurred."457+ );458+ }459+460+ return yield* createdOf(repo);461+ })462+ ),463+ info: () => run(keptOf(name).pipe(Effect.flatMap(info))),464+ listTokens: () =>465+ run(466+ keptOf(name).pipe(467+ Effect.map((repo) => {468+ const tokens = [...repo.tokens.values()].map(469+ ({ createdAt, expiresAt, id, scope, state }) => ({470+ createdAt,471+ expiresAt,472+ id,473+ scope,474+ state,475+ })476+ );477+478+ return { tokens, total: tokens.length };479+ })480+ )481+ ),482+ log: (logOptions) =>483+ run(484+ Effect.gen(function* () {485+ const ref = logOptions?.ref ?? "HEAD";486+ const limit = Math.min(logOptions?.limit ?? 50, 1000);487+ const offset = logOptions?.offset ?? 0;488+489+ // `HEAD` is the repo's default branch.490+ const at = revisionOf(491+ ref === "HEAD" ? (yield* keptOf(name)).defaultBranch : ref492+ );493+494+ if (Option.isNone(at)) {495+ return [];496+ }497+498+ const commits = yield* host.log(name, at.value, offset + limit);499+500+ return commits.slice(offset).map(metadataOf);501+ })502+ ),503+ readBlob: (hash) =>504+ run(505+ objectId(hash).pipe(506+ Effect.flatMap((blob) => host.readBlob(name, blob)),507+ Effect.map((bytes) => Option.getOrNull(Option.map(bytes, blobOf)))508+ )509+ ),510+ readCommit: (hash) =>511+ run(512+ objectId(hash).pipe(513+ Effect.flatMap((sha) => host.readCommit(name, CommitSha.make(sha))),514+ Effect.map((commit) =>515+ Option.getOrNull(Option.map(commit, metadataOf))516+ )517+ )518+ ),519+ readFile: ({ path, ref }) =>520+ run(521+ Effect.gen(function* () {522+ const file = decodePath(path);523+ const at = revisionOf(ref);524+525+ if (ref === "" || Option.isNone(file)) {526+ return yield* refuse(527+ "INVALID_INPUT",528+ "ref and path must not be empty"529+ );530+ }531+532+ if (Option.isNone(at)) {533+ return null;534+ }535+536+ const bytes = yield* host.readFile(name, at.value, file.value);537+538+ return Option.getOrNull(Option.map(bytes, blobOf));539+ })540+ ),541+ readTree: (hash) =>542+ run(543+ objectId(hash).pipe(544+ Effect.flatMap((tree) => host.readTree(name, tree)),545+ Effect.map((entries) =>546+ Option.getOrNull(Option.map(entries, (each) => each.map(entryOf)))547+ )548+ )549+ ),550+ revokeToken: (tokenOrId) =>551+ run(552+ Effect.gen(function* () {553+ if (tokenOrId === "") {554+ return yield* refuse(555+ "INVALID_INPUT",556+ "tokenOrId must not be empty"557+ );558+ }559+560+ const { tokens } = yield* keptOf(name);561+562+ const token = [...tokens.values()].find(563+ ({ id, plaintext }) => id === tokenOrId || plaintext === tokenOrId564+ );565+566+ const revoked = yield* host.revokeToken(name, token?.id ?? tokenOrId);567+568+ if (token !== undefined && revoked) {569+ tokens.set(token.id, { ...token, state: "revoked" });570+ }571+572+ return revoked;573+ })574+ ),575+ [Symbol.dispose]: constVoid,576+ });577+578+ return {579+ create: (name, createOptions) =>580+ run(581+ Effect.gen(function* () {582+ const repoName = yield* named(name, "INVALID_REPO_NAME");583+584+ yield* host.create(repoName);585+586+ return yield* createdOf(587+ keep(repoName, {588+ defaultBranch: createOptions?.setDefaultBranch ?? "main",589+ description: createOptions?.description ?? null,590+ readOnly: createOptions?.readOnly ?? false,591+ })592+ );593+ })594+ ),595+ delete: (name) =>596+ run(597+ Effect.gen(function* () {598+ const repoName = yield* named(name, "INVALID_REPO_NAME");599+600+ kept.delete(repoName);601+602+ return yield* host.remove(repoName);603+ })604+ ),605+ get: (name) =>606+ run(607+ Effect.gen(function* () {608+ const repoName = yield* named(name, "NOT_FOUND");609+610+ yield* host.remote(repoName);611+612+ return handle(repoName);613+ })614+ ),615+ import: ({ source, target }) =>616+ run(617+ Effect.gen(function* () {618+ const repoName = yield* named(target.name, "INVALID_REPO_NAME");619+620+ const branch = Option.fromNullishOr(source.branch).pipe(621+ Option.flatMap(decodeBranch)622+ );623+624+ yield* host.importFrom(625+ repoName,626+ Option.match(branch, {627+ onNone: () => ({ url: source.url }),628+ onSome: (name) => ({ branch: name, url: source.url }),629+ })630+ );631+632+ return yield* createdOf(633+ keep(repoName, {634+ description: target.opts?.description ?? null,635+ readOnly: target.opts?.readOnly ?? false,636+ source: source.url,637+ })638+ );639+ })640+ ),641+ list: (listOptions) =>642+ run(643+ Effect.sync(() => {644+ const limit = Math.min(Math.max(listOptions?.limit ?? 50, 1), 200);645+ const from = Number(listOptions?.cursor ?? "0");646+ const all = [...kept.values()];647+648+ const repos = all.slice(from, from + limit).map(summaryOf);649+ const next = from + limit;650+651+ return next < all.length652+ ? { cursor: String(next), repos, total: all.length }653+ : { repos, total: all.length };654+ })655+ ),656+ };657+};added:packages/testkit/src/golden.ts+133 added
1+/**2+ * Golden git transcripts: git's output made the same on every run and every3+ * machine, compared with a file under `test/golden/`.4+ *5+ * Like everything in `@repo/testkit`, this module is for `test/` directories6+ * only: no `src/` imports it (`imports:check` refuses one).7+ */8+import { Brand } from "@repo/brand";9+import { Config, Context, Effect, FileSystem } from "effect";10+11+/**12+ * Where golden files live: `test/golden`, from the package whose tests run13+ * (vitest runs in the package's folder). A test about golden files14+ * themselves points it at a temporary folder.15+ */16+export const GoldenDir = Context.Reference<string>("testkit/GoldenDir", {17+ defaultValue: () => "test/golden",18+});19+20+// A directory made under the system's temporary folder, up to and including21+// the random name it was made with: Linux's `/tmp/x1y2z3`, macOS's22+// `/var/folders/ab/cd/T/x1y2z3`, as given or as resolved through `/private`.23+const TEMP_PATH =24+ /(?<![\w.-])(?:\/private)?(?:\/var\/folders\/[^\s/'"]+\/[^\s/'"]+\/T|\/var\/tmp|\/tmp)\/[^\s/'"]+/gu;25+26+// A full SHA-1 object id, and nothing longer: a SHA-256 stays as it is.27+const OBJECT_ID = /(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])/gu;28+29+// A server a test started on this machine, whose port changes every run.30+const LOCAL_SERVER = /\b(?:127\.0\.0\.1|localhost):\d+/gu;31+32+/**33+ * What a terminal shows of one line git rewrote with carriage returns (a34+ * progress meter): the last version of it. A carriage return with nothing35+ * after it only moves the cursor, so the version before it still shows.36+ */37+const lastRewrite = (line: string) =>38+ line.split("\r").findLast((version) => version !== "") ?? "";39+40+/**41+ * Git's output, the same on every run of the same push: without the eight42+ * spaces git pads side-band lines with when stderr is not a terminal (and any43+ * other trailing space), with temporary folders as `<tmp>`, full object ids as44+ * `<sha>`, a local server's address as `<host>`, and each line rewritten with45+ * carriage returns as a terminal leaves it.46+ */47+export const normaliseGitOutput = (text: string): string =>48+ text49+ .split(/\r?\n/u)50+ .map((line) =>51+ lastRewrite(line)52+ .replaceAll(TEMP_PATH, "<tmp>")53+ .replaceAll(LOCAL_SERVER, "<host>")54+ .replaceAll(OBJECT_ID, "<sha>")55+ .trimEnd()56+ )57+ .join("\n");58+59+// Letters on either side make it another word, not the product's name:60+// the rule `brand:check` applies.61+const NAME = new RegExp(`(?<![a-z])${Brand.slug}(?![a-z])`, "giu");62+63+/**64+ * The text as a golden file holds it: the product's config folder as65+ * `<configDir>` and every other spelling of its name as `<brand>`, so no66+ * golden file names the product (`brand:check`) and a renamed brand still67+ * matches.68+ */69+const unbranded = (text: string) =>70+ text.replaceAll(Brand.configDir, "<configDir>").replaceAll(NAME, "<brand>");71+72+/** The lines that differ, as `- golden` and `+ actual`, in order. */73+const difference = (golden: string, actual: string) => {74+ const was = golden.split("\n");75+ const now = actual.split("\n");76+77+ return Array.from({ length: Math.max(was.length, now.length) }, (_, at) =>78+ was[at] === now[at]79+ ? []80+ : [81+ ...(was[at] === undefined ? [] : [`- ${was[at]}`]),82+ ...(now[at] === undefined ? [] : [`+ ${now[at]}`]),83+ ]84+ )85+ .flat()86+ .join("\n");87+};88+89+/**90+ * Compares `text` with `test/golden/<name>.txt`, and fails the test where91+ * they differ. With `UPDATE_GOLDEN=1` it writes the file instead, folders92+ * and all: run the package's tests that way once, then read the diff.93+ */94+export const expectGolden = (95+ name: string,96+ text: string97+): Effect.Effect<void, never, FileSystem.FileSystem> =>98+ Effect.gen(function* () {99+ const fs = yield* FileSystem.FileSystem;100+ const dir = yield* GoldenDir;101+ const file = `${dir}/${name}.txt`;102+ const actual = unbranded(text);103+104+ const update = yield* Config.Boolean("UPDATE_GOLDEN").pipe(105+ Config.withDefault(false)106+ );107+108+ if (update) {109+ yield* fs.makeDirectory(file.slice(0, file.lastIndexOf("/")), {110+ recursive: true,111+ });112+113+ return yield* fs.writeFileString(file, actual);114+ }115+116+ if (!(yield* fs.exists(file))) {117+ return yield* Effect.die(118+ new Error(119+ `no golden file ${file} yet: run this package's tests with UPDATE_GOLDEN=1 to write it`120+ )121+ );122+ }123+124+ const golden = yield* fs.readFileString(file);125+126+ return yield* golden === actual127+ ? Effect.void128+ : Effect.die(129+ new Error(130+ `${file} differs from the output (rerun with UPDATE_GOLDEN=1 to accept it):\n${difference(golden, actual)}`131+ )132+ );133+ }).pipe(Effect.orDie);added:packages/testkit/src/scenarios.ts+443 added
1+/**2+ * Scenario builders: a project, its people and its policy as plain values,3+ * built the same way every run. `aProject()` starts one; `withAsk`, `withKind`4+ * and `withVouches` add to it in a pipe; `sixChildren()` is the migrate family5+ * six agents claim at once (CAA §2.F).6+ *7+ * Values, not services: every builder is a pure function. None reads the8+ * clock or randomness; time comes from `now` (default `2026-10-07T12:00:00Z`)9+ * and ids from counters. Each value is decoded with the domain's own schema10+ * as it is built, so a scenario the domain would refuse throws here.11+ *12+ * Like everything in `@repo/testkit`, this module is for `test/` directories13+ * only: no `src/` imports it (`imports:check` refuses one).14+ */15+import { Brand } from "@repo/brand";16+import { Ask } from "@repo/protocol/domain/ask";17+import { CheckSpec } from "@repo/protocol/domain/check";18+import { Command, SymbolName } from "@repo/protocol/domain/common";19+import { AskKind } from "@repo/protocol/domain/kind";20+import { Policy } from "@repo/protocol/domain/policy";21+import { Territory } from "@repo/protocol/domain/territory";22+import {23+ CommitSha,24+ DecisionId,25+ Handle,26+ LandedSha,27+ ProjectName,28+ ProposalId,29+ RepoPath,30+ RequestId,31+} from "@repo/protocol/ids";32+import { Array as Arr, DateTime, Pipeable, Schema } from "effect";33+import type { Types } from "effect";34+35+import { defaultNow } from "./clock.ts";36+37+/** An ask kind as a test writes it, before decoding. */38+export type AskKindEncoded = typeof AskKind.Encoded;39+40+/** A project at one landed commit, with the people a test acts as. */41+export interface Scenario extends Pipeable.Pipeable {42+ readonly project: ProjectName;43+ /** The person who made the project; the first decider. */44+ readonly initializer: Handle;45+ readonly policy: Policy;46+ readonly landed: LandedSha;47+ /** Everyone in the scenario by the name the test gave them, deciders first. */48+ readonly people: ReadonlyMap<string, Handle>;49+ /** When the scenario's asks opened. */50+ readonly now: DateTime.Utc;51+}52+53+type ScenarioFields = Omit<Scenario, "pipe">;54+55+// A class only for `pipe`: its fields are its own, so `Equal.equals` compares56+// two scenarios by what they hold.57+class Built extends Pipeable.Class implements Scenario {58+ readonly project: ProjectName;59+ readonly initializer: Handle;60+ readonly policy: Policy;61+ readonly landed: LandedSha;62+ readonly people: ReadonlyMap<string, Handle>;63+ readonly now: DateTime.Utc;64+65+ constructor(fields: ScenarioFields) {66+ super();67+ this.project = fields.project;68+ this.initializer = fields.initializer;69+ this.policy = fields.policy;70+ this.landed = fields.landed;71+ this.people = fields.people;72+ this.now = fields.now;73+ }74+}75+76+const withPolicy = (scenario: Scenario, policy: Policy): Scenario =>77+ new Built({ ...scenario, policy });78+79+const WORD = 2 ** 32;80+81+/**82+ * `word` with its low byte exclusive-ored with `byte`, in arithmetic: lint83+ * keeps bitwise operators out of the codebase, and FNV needs only this one.84+ */85+const xorLowByte = (word: number, byte: number) => {86+ const low = word % 256;87+ let mixed = 0;88+89+ for (let place = 1; place < 256; place *= 2) {90+ const ours = Math.floor(low / place) % 2;91+ const theirs = Math.floor(byte / place) % 2;92+93+ mixed += ours === theirs ? 0 : place;94+ }95+96+ return word - low + mixed;97+};98+99+/** FNV-1a (32-bit) over the UTF-8 bytes of `text`, as eight hex digits. */100+const fnv1a = (text: string) => {101+ let hash = 0x81_1c_9d_c5;102+103+ for (const byte of new TextEncoder().encode(text)) {104+ // `Math.imul` multiplies modulo 2^32, signed; the remainder makes it unsigned.105+ hash = (Math.imul(xorLowByte(hash, byte), 0x01_00_01_93) + WORD) % WORD;106+ }107+108+ return hash.toString(16).padStart(8, "0");109+};110+111+/**112+ * A commit id made from a seed: FNV-1a over `0:<seed>` … `4:<seed>`, so the113+ * same seed always gives the same 40 hex digits (FNV, not crypto).114+ */115+export const sha = (seed: string): CommitSha =>116+ CommitSha.make(117+ [0, 1, 2, 3, 4].map((round) => fnv1a(`${round}:${seed}`)).join("")118+ );119+120+/** `prefix-000001`, `prefix-000002`, …: one counter per call of `ids()`. */121+const counter = (prefix: string) => {122+ let next = 0;123+124+ return () => {125+ next += 1;126+127+ return `${prefix}-${String(next).padStart(6, "0")}`;128+ };129+};130+131+/**132+ * Fresh counters for the ids a project mints: `req-000001`, `prop-000001`,133+ * `dec-000001`. Each call starts again at 1.134+ */135+export const ids = () => {136+ const request = counter("req");137+ const proposal = counter("prop");138+ const decision = counter("dec");139+140+ return {141+ decision: () => DecisionId.make(decision()),142+ proposal: () => ProposalId.make(proposal()),143+ request: () => RequestId.make(request()),144+ };145+};146+147+const fix: AskKindEncoded = {148+ checkKind: "redThenGreen",149+ claimers: "vouched",150+ finish: "optional",151+ name: "fix",152+ oneWay: false,153+ race: 1,154+ requires: ["want", "check", "territory"],155+ strength: "assertion",156+};157+158+const migrate: AskKindEncoded = {159+ checkKind: "migrate",160+ claimers: "vouched",161+ finish: "never",162+ name: "migrate",163+ oneWay: false,164+ race: 1,165+ requires: ["want", "check", "territory"],166+ strength: "assertion",167+};168+169+const decodePolicy = Schema.decodeSync(Policy);170+171+const decodeAsk = Schema.decodeSync(Ask);172+173+const decodeKind = Schema.decodeSync(AskKind);174+175+const decodeTerritory = Schema.decodeSync(Territory);176+177+const encodeTerritory = Schema.encodeSync(Territory);178+179+const encodeCheck = Schema.encodeSync(CheckSpec);180+181+/**182+ * A project at its first landed commit: the defaults the config folder183+ * leaves out (spec §2.5), the kinds `fix` and `migrate`, and its deciders184+ * (default `alice`) deciding everything (D20). `people` are everyone else.185+ */186+export const aProject = (187+ options: {188+ readonly name?: string;189+ readonly now?: DateTime.Utc;190+ readonly deciders?: readonly string[];191+ readonly people?: readonly string[];192+ } = {}193+): Scenario => {194+ const name = options.name ?? "datekit";195+ const [first = "alice", ...more] = options.deciders ?? [];196+ const deciders = [first, ...more] as const;197+ const landed = LandedSha.make(sha(`${name}:landed`));198+199+ const policy = decodePolicy({200+ agents: "trailer",201+ asks: [],202+ at: landed,203+ budget: { decisionsPerDay: 5, expireDays: 14 },204+ caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },205+ claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },206+ deciders: [{ handles: deciders, paths: "**" }],207+ functions: { admit: false, opensAlone: false },208+ judge: {209+ paths: [`${Brand.configDir}/**`],210+ pointers: ["package.json#/scripts"],211+ },212+ kinds: [fix, migrate],213+ modules: [],214+ ratchets: [],215+ record: { countsAfterDays: 30, windowDays: 365 },216+ run: {217+ checks: { lint: "bun run lint", types: "bun run typecheck" },218+ test: "bun test {path}",219+ },220+ source: "config",221+ vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },222+ vouches: [],223+ weakening: { markers: [".skip(", ".only(", ".todo("] },224+ });225+226+ const names = [...deciders, ...(options.people ?? [])];227+228+ return new Built({229+ initializer: Handle.make(first),230+ landed,231+ now: options.now ?? defaultNow,232+ people: new Map(names.map((person) => [person, Handle.make(person)])),233+ policy,234+ project: ProjectName.make(name),235+ });236+};237+238+/** `packages/parser` → its module `parser` and its paths `packages/parser/**`; `.` → the whole repo. */239+const territoryOf = (folder: string) =>240+ decodeTerritory(241+ folder === "."242+ ? { module: ".", paths: ["**"] }243+ : {244+ module: folder.split("/").at(-1) ?? folder,245+ paths: [`${folder}/**`],246+ }247+ );248+249+/** An ask as `withAsk` takes it. */250+interface AskOptions {251+ readonly id: string;252+ readonly territory: string;253+ readonly kind?: string;254+ /** Built with the domain's constructors: `CheckSpec.cases.LintToZero.make(…)`. */255+ readonly check?: CheckSpec;256+ readonly blockedBy?: readonly string[];257+ readonly reserve?: "newcomers" | "people";258+ /** The migrate ask this one is a step of. */259+ readonly parent?: string;260+ readonly want?: string;261+}262+263+/**264+ * Opens `ask` over `territory` in the scenario, and records the territory as265+ * a module when `module` says it is one.266+ */267+const openAsk = (268+ scenario: Scenario,269+ ask: AskOptions,270+ territory: Territory,271+ module: boolean272+): Scenario => {273+ const tests = ask.territory === "." ? "test" : `${ask.territory}/test`;274+275+ const encoded: Types.Mutable<typeof Ask.Encoded> = {276+ askedBy: scenario.initializer,277+ blockedBy: ask.blockedBy ?? [],278+ brief: {279+ want: ask.want ?? `${ask.id}: its check passes in ${ask.territory}`,280+ },281+ check: encodeCheck(282+ ask.check ??283+ CheckSpec.cases.RedThenGreen.make({284+ path: RepoPath.make(`${tests}/${ask.id}.test.ts`),285+ })286+ ),287+ file: `${Brand.configDir}/asks/${ask.id}.ask.ts`,288+ id: ask.id,289+ kind: ask.kind ?? "fix",290+ openedAt: DateTime.formatIso(scenario.now),291+ openedIn: scenario.landed,292+ project: scenario.project,293+ state: "open",294+ territory: encodeTerritory(territory),295+ };296+297+ if (ask.parent !== undefined) {298+ encoded.parent = ask.parent;299+ }300+301+ if (ask.reserve !== undefined) {302+ encoded.reserve = ask.reserve;303+ }304+305+ const { modules } = scenario.policy;306+ const known = modules.some((each) => each.module === territory.module);307+308+ return withPolicy(scenario, {309+ ...scenario.policy,310+ asks: [...scenario.policy.asks, decodeAsk(encoded)],311+ modules: module && !known ? [...modules, territory] : modules,312+ });313+};314+315+/**316+ * Adds an open ask, asked by the initializer in the landed commit, and its317+ * territory's module. The territory is a folder (`packages/parser`) or `.`318+ * (the whole repo, which is no module: modules are workspaces); the kind319+ * defaults to `fix`, the check to a `RedThenGreen` file in the territory, the320+ * want to a sentence naming both.321+ */322+export const withAsk =323+ (ask: AskOptions) =>324+ (scenario: Scenario): Scenario =>325+ openAsk(scenario, ask, territoryOf(ask.territory), ask.territory !== ".");326+327+/** Adds an ask kind, in place of one with the same name. */328+export const withKind =329+ (kind: AskKindEncoded) =>330+ (scenario: Scenario): Scenario => {331+ const added = decodeKind(kind);332+ const { kinds } = scenario.policy;333+334+ return withPolicy(scenario, {335+ ...scenario.policy,336+ kinds: kinds.some(({ name }) => name === added.name)337+ ? kinds.map((each) => (each.name === added.name ? added : each))338+ : [...kinds, added],339+ });340+ };341+342+/** Adds the vouch file's lines: `handles` vouched for, then `denounced`. */343+export const withVouches =344+ (handles: readonly string[], denounced: readonly string[] = []) =>345+ (scenario: Scenario): Scenario =>346+ withPolicy(scenario, {347+ ...scenario.policy,348+ vouches: [349+ ...scenario.policy.vouches,350+ ...handles.map((handle) => ({351+ denounced: false,352+ handle: Handle.make(handle),353+ })),354+ ...denounced.map((handle) => ({355+ denounced: true,356+ handle: Handle.make(handle),357+ })),358+ ],359+ });360+361+/** `legacyFetch` → `legacy-fetch`, `http.get` → `http-get`: a name an ask id can carry. */362+const words = (symbol: string) =>363+ symbol364+ .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower>-$<upper>")365+ .toLowerCase()366+ .replaceAll(/[^a-z0-9]+/gu, "-")367+ .replaceAll(/^-|-$/gu, "");368+369+const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);370+371+/** The six packages together: where a family's parent and delete child reach. */372+const allSix = decodeTerritory({373+ module: ".",374+ paths: Arr.map(packages, (folder) => `${folder}/**`),375+});376+377+/**378+ * "Six agents claim six children" (CAA §2.F): the project `burrow` with a379+ * migrate ask `drop-<symbol>` over `packages/p1` … `packages/p6`, a child per380+ * package (`drop-<symbol>-p1` …), each moving the symbol in its own package,381+ * and a delete child (`drop-<symbol>-delete`) blocked by all six. The six382+ * packages are the project's modules.383+ */384+export const sixChildren = (385+ options: { readonly symbol?: string; readonly to?: string } = {}386+): Scenario => {387+ const symbol = options.symbol ?? "legacyFetch";388+ const to = options.to ?? "http.get";389+ const parent = `drop-${words(symbol)}`;390+ const count = `node scripts/count-callers.mjs ${symbol} --json`;391+392+ const check = CheckSpec.cases.Migrate.make({393+ count: Command.make(count),394+ from: SymbolName.make(symbol),395+ to: SymbolName.make(to),396+ });397+398+ const children = packages.map((folder) => ({399+ check,400+ id: `${parent}-${folder.split("/").at(-1) ?? folder}`,401+ kind: "migrate",402+ parent,403+ territory: folder,404+ want: `${folder}: move every use of ${symbol} to ${to}`,405+ }));406+407+ const opened = openAsk(408+ aProject({ name: "burrow" }),409+ {410+ check,411+ id: parent,412+ kind: "migrate",413+ territory: ".",414+ want: `Move every use of ${symbol} to ${to}, then delete ${symbol}`,415+ },416+ allSix,417+ false418+ );419+420+ let split = opened;421+422+ for (const child of children) {423+ split = withAsk(child)(split);424+ }425+426+ return openAsk(427+ split,428+ {429+ blockedBy: children.map(({ id }) => id),430+ check: CheckSpec.cases.SymbolAbsent.make({431+ count: Command.make(count),432+ symbol: SymbolName.make(symbol),433+ }),434+ id: `${parent}-delete`,435+ kind: "migrate",436+ parent,437+ territory: ".",438+ want: `Delete ${symbol}: nothing uses it any more`,439+ },440+ allSix,441+ false442+ );443+};added:packages/testkit/test/golden/push-new-branch.txt+3 added
1+remote: received <sha> for refs/heads/main2+To <tmp>/remote.git3+ * [new branch] HEAD -> mainadded:packages/testkit/test/clock.test.ts+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import { describe, expect, it } from "@effect/vitest";import { Clock, DateTime, Duration, Effect, Fiber } from "effect";
import { advanceTo, at, defaultNow, hours } from "../src/clock.ts";
describe("the test clock helpers", () => { it("reads an ISO instant as a UTC date-time", () => { expect(DateTime.toEpochMillis(at("2026-10-07T12:00:00Z"))).toBe( 1_791_374_400_000 ); expect(DateTime.isUtc(at("2026-10-07T12:00:00Z"))).toBeTruthy(); expect(defaultNow).toStrictEqual(at("2026-10-07T12:00:00Z")); });
it("counts hours as durations", () => { expect(Duration.toMillis(hours(2))).toBe(7_200_000); expect(Duration.toMillis(hours(24))).toBe(86_400_000); });
it.effect("moves the test clock to an instant", () => Effect.gen(function* () { yield* advanceTo("2026-10-07T12:00:00Z");
expect(yield* Clock.currentTimeMillis).toBe(1_791_374_400_000); expect(yield* DateTime.now).toStrictEqual(at("2026-10-07T12:00:00Z")); }) );
it.effect( "wakes what sleeps until the instant it moves to, and nothing later", () => Effect.gen(function* () { yield* advanceTo("2026-10-07T12:00:00Z");
const warn = yield* Effect.forkChild(Effect.sleep(hours(2))); const lapse = yield* Effect.forkChild(Effect.sleep(hours(24)));
yield* advanceTo("2026-10-07T14:00:00Z");
expect(warn.pollUnsafe()).toBeDefined(); expect(lapse.pollUnsafe()).toBeUndefined();
yield* Fiber.interrupt(lapse); }) );});added:packages/testkit/test/fake-artifacts-binding.test.ts+469 added
1+import { describe, expect, it } from "@effect/vitest";2+import type { RepoName } from "@repo/protocol/ids";3+import { CommitSha } from "@repo/protocol/ids";4+import { Data, DateTime, Effect, Match, Option, Redacted } from "effect";5+6+import {7+ fakeArtifactsBinding,8+ ObjectId,9+} from "../src/fake-artifacts-binding.ts";10+import type { HostLike } from "../src/fake-artifacts-binding.ts";11+12+class RepoNotFound extends Data.TaggedError("RepoNotFound")<{13+ readonly name: RepoName;14+}> {}15+16+class RepoExists extends Data.TaggedError("RepoExists")<{17+ readonly name: RepoName;18+}> {}19+20+class ImportRefused extends Data.TaggedError("ImportRefused")<{21+ readonly name: RepoName;22+ readonly reason: string;23+}> {}24+25+/** What a promise of the binding threw. */26+class Thrown extends Data.TaggedError("Thrown")<{ readonly error: Error }> {}27+28+const commit = CommitSha.make("c".repeat(40));29+30+const tree = ObjectId.make("d".repeat(40));31+32+const subtree = ObjectId.make("e".repeat(40));33+34+const blob = ObjectId.make("f".repeat(40));35+36+const hello = new TextEncoder().encode("hello\n");37+38+const answerer = { email: "answerer@example.com", name: "Answerer" };39+40+/** The one commit every repo holds on `main`. */41+const firstCommit = {42+ author: answerer,43+ committer: answerer,44+ message: "first",45+ parents: [],46+ sha: commit,47+ tree,48+};49+50+/**51+ * A repo host as small as the fake needs: every repo holds one commit on52+ * `main`, whose tree has `a.txt` ("hello") and a folder `src`.53+ */54+const tinyHost = (): HostLike => {55+ const repos = new Set<RepoName>();56+ let minted = 0;57+58+ const known = (name: RepoName): Effect.Effect<void, RepoNotFound> =>59+ repos.has(name) ? Effect.void : Effect.fail(new RepoNotFound({ name }));60+61+ const make = (name: RepoName) =>62+ repos.has(name)63+ ? Effect.fail(new RepoExists({ name }))64+ : Effect.sync(() => {65+ repos.add(name);66+67+ return { name, remote: `memory://${name}.git` };68+ });69+70+ return {71+ create: make,72+ fork: (base, name) => known(base).pipe(Effect.andThen(make(name))),73+ importFrom: (name, source) =>74+ Effect.fail(75+ new ImportRefused({ name, reason: `no repo at ${source.url}` })76+ ),77+ log: (name, at) =>78+ known(name).pipe(79+ Effect.as(80+ Match.valueTags(at, {81+ Branch: ({ name: branch }) => branch === "main",82+ Commit: ({ sha }) => sha === commit,83+ })84+ ? [firstCommit]85+ : []86+ )87+ ),88+ mintToken: (name, scope, ttl) =>89+ known(name).pipe(90+ Effect.map(() => {91+ minted += 1;92+93+ return {94+ expiresAt: DateTime.addDuration(95+ DateTime.makeUnsafe("2026-10-07T12:00:00Z"),96+ ttl97+ ),98+ id: `token-${minted}`,99+ scope,100+ secret: Redacted.make(`secret-${minted}`),101+ };102+ })103+ ),104+ readBlob: (name, sha) =>105+ known(name).pipe(106+ Effect.as(sha === blob ? Option.some(hello) : Option.none())107+ ),108+ readCommit: (name, sha) =>109+ known(name).pipe(110+ Effect.as(sha === commit ? Option.some(firstCommit) : Option.none())111+ ),112+ readFile: (name, at, path) =>113+ known(name).pipe(114+ Effect.as(115+ Match.valueTags(at, {116+ Branch: ({ name: branch }) => branch === "main",117+ Commit: ({ sha }) => sha === commit,118+ }) && path === "a.txt"119+ ? Option.some(hello)120+ : Option.none()121+ )122+ ),123+ readTree: (name, sha) =>124+ known(name).pipe(125+ Effect.as(126+ sha === tree127+ ? Option.some([128+ {129+ mode: "100644" as const,130+ name: "a.txt",131+ sha: blob,132+ type: "blob" as const,133+ },134+ {135+ mode: "040000" as const,136+ name: "src",137+ sha: subtree,138+ type: "tree" as const,139+ },140+ ])141+ : Option.none()142+ )143+ ),144+ remote: (name) => known(name).pipe(Effect.as(`memory://${name}.git`)),145+ remove: (name) => Effect.sync(() => repos.delete(name)),146+ revokeToken: (name) => known(name).pipe(Effect.as(true)),147+ };148+};149+150+/** Awaits one of the binding's promises. */151+const call = <A>(run: () => Promise<A>) =>152+ Effect.tryPromise({153+ catch: (error) =>154+ new Thrown({155+ error: error instanceof Error ? error : new Error(String(error)),156+ }),157+ try: run,158+ });159+160+/** What one of the binding's promises threw, or an error saying it resolved. */161+const thrown = <A>(run: () => Promise<A>) =>162+ call(run).pipe(163+ Effect.match({164+ onFailure: ({ error }) => error,165+ onSuccess: (value) => new Error(`resolved with ${String(value)}`),166+ })167+ );168+169+const text = (bytes: Blob | null) =>170+ bytes === null ? Effect.succeed(null) : call(() => bytes.text());171+172+/** An error as a plain record: its name and message, and its code and number if it has them. */173+const described = (error: Error) => ({174+ code: "code" in error ? error.code : undefined,175+ isError: error instanceof Error,176+ message: error.message,177+ name: error.name,178+ numericCode: "numericCode" in error ? error.numericCode : undefined,179+});180+181+/** A binding over a fresh tiny host, with `datekit` made, and the repo `get` hands back. */182+const withDatekit = (183+ options: Parameters<typeof fakeArtifactsBinding>[1] = {}184+) =>185+ Effect.gen(function* () {186+ const binding = fakeArtifactsBinding(tinyHost(), options);187+ const created = yield* call(() => binding.create("datekit"));188+ const repo = yield* call(() => binding.get("datekit"));189+190+ return { binding, created, repo };191+ });192+193+describe("the fake Artifacts binding", () => {194+ it.effect("creates a repo with a remote and a write token", () =>195+ Effect.gen(function* () {196+ const { created } = yield* withDatekit();197+198+ expect(created).toMatchObject({199+ defaultBranch: "main",200+ description: null,201+ name: "datekit",202+ remote: "memory://datekit.git",203+ token: "secret-1",204+ });205+ })206+ );207+208+ it.effect("hands back a repo whose reads by object id go to the host", () =>209+ Effect.gen(function* () {210+ const { repo } = yield* withDatekit();211+212+ expect(yield* call(() => repo.readTree(tree))).toStrictEqual([213+ { hash: blob, mode: "100644", name: "a.txt", type: "blob" },214+ { hash: subtree, mode: "40000", name: "src", type: "tree" },215+ ]);216+ expect(yield* text(yield* call(() => repo.readBlob(blob)))).toBe(217+ "hello\n"218+ );219+ expect(yield* call(() => repo.readCommit(commit))).toStrictEqual({220+ author: answerer,221+ authoredAt: 0,222+ committedAt: 0,223+ committer: answerer,224+ hash: commit,225+ message: "first",226+ parents: [],227+ treeHash: tree,228+ });229+ })230+ );231+232+ it.effect("reads null for an object the host doesn't have", () =>233+ Effect.gen(function* () {234+ const { repo } = yield* withDatekit();235+236+ expect(yield* call(() => repo.readTree(subtree))).toBeNull();237+ expect(yield* call(() => repo.readBlob(tree))).toBeNull();238+ expect(yield* call(() => repo.readCommit(blob))).toBeNull();239+ })240+ );241+242+ it.effect(243+ "throws NOT_FOUND, as an ArtifactsError, for a repo it doesn't have",244+ () =>245+ Effect.gen(function* () {246+ const error = yield* thrown(() =>247+ fakeArtifactsBinding(tinyHost()).get("nobody")248+ );249+250+ expect(described(error)).toStrictEqual({251+ code: "NOT_FOUND",252+ isError: true,253+ message: "Repository not found: nobody",254+ name: "ArtifactsError",255+ numericCode: 0,256+ });257+ })258+ );259+260+ it.effect(261+ "throws plain Errors with no code when codeless, as wrangler dev's remote bindings do (S1 #22)",262+ () =>263+ Effect.gen(function* () {264+ const { binding } = yield* withDatekit({ codeless: true });265+ const missing = yield* thrown(() => binding.get("nobody"));266+ const again = yield* thrown(() => binding.create("datekit"));267+268+ expect(described(missing)).toStrictEqual({269+ code: undefined,270+ isError: true,271+ message: "ArtifactsError: Repository not found: nobody",272+ name: "Error",273+ numericCode: undefined,274+ });275+ expect(described(again)).toMatchObject({276+ code: undefined,277+ message: "ArtifactsError: repo already exists: datekit",278+ });279+ })280+ );281+282+ it.effect(283+ "answers a fork under load with a 500 after making it, then a 409 on the retry (S7)",284+ () =>285+ Effect.gen(function* () {286+ const { binding, repo } = yield* withDatekit({ forkFailures: 1 });287+ const first = yield* thrown(() => repo.fork("datekit--fix--bob"));288+ const made = yield* call(() => binding.get("datekit--fix--bob"));289+ const retry = yield* thrown(() => repo.fork("datekit--fix--bob"));290+ const next = yield* call(() => repo.fork("datekit--fix--carol"));291+292+ expect(described(first)).toStrictEqual({293+ code: "INTERNAL_ERROR",294+ isError: true,295+ message: "An internal error occurred.",296+ name: "ArtifactsError",297+ numericCode: 10_400,298+ });299+ // The fork was made all the same.300+ expect(yield* text(yield* call(() => made.readBlob(blob)))).toBe(301+ "hello\n"302+ );303+ expect(described(retry)).toStrictEqual({304+ code: "ALREADY_EXISTS",305+ isError: true,306+ message: "repo already exists: datekit--fix--bob",307+ name: "ArtifactsError",308+ numericCode: 10_201,309+ });310+ expect(next).toMatchObject({ name: "datekit--fix--carol" });311+ })312+ );313+314+ it.effect(315+ "resolves only short branch names and commit ids in reads by ref (S1 #20)",316+ () =>317+ Effect.gen(function* () {318+ const { repo } = yield* withDatekit();319+320+ const read = (ref: string) =>321+ call(() => repo.readFile({ path: "a.txt", ref })).pipe(322+ Effect.flatMap(text)323+ );324+325+ expect(yield* read("refs/heads/main")).toBeNull();326+ expect(yield* read("asked/landed")).toBeNull();327+ expect([yield* read("main"), yield* read(commit)]).toStrictEqual([328+ "hello\n",329+ "hello\n",330+ ]);331+ expect(332+ yield* call(() => repo.log({ ref: "refs/heads/main" }))333+ ).toStrictEqual([]);334+ expect(335+ (yield* call(() => repo.log())).map(({ hash }) => hash)336+ ).toStrictEqual([commit]);337+ })338+ );339+340+ it.effect("refuses a malformed object id, an empty path or a bad name", () =>341+ Effect.gen(function* () {342+ const { binding, repo } = yield* withDatekit();343+344+ const codes = [345+ yield* thrown(() => repo.readTree("HEAD")),346+ yield* thrown(() => repo.readFile({ path: "", ref: "main" })),347+ yield* thrown(() => binding.create("no spaces")),348+ yield* thrown(() => repo.createToken("read", 59)),349+ ].map((error) => described(error).code);350+351+ expect(codes).toStrictEqual([352+ "INVALID_INPUT",353+ "INVALID_INPUT",354+ "INVALID_REPO_NAME",355+ "INVALID_TTL",356+ ]);357+ })358+ );359+360+ it.effect(361+ "serves remotes under a base URL, for a git server the test runs",362+ () =>363+ Effect.gen(function* () {364+ const { created, repo } = yield* withDatekit({365+ remoteBase: "http://127.0.0.1:9000/git",366+ });367+368+ const info = yield* call(() => repo.info());369+370+ expect(created.remote).toBe("http://127.0.0.1:9000/git/datekit.git");371+ expect(info).toMatchObject({372+ defaultBranch: "main",373+ lastPushAt: null,374+ name: "datekit",375+ remote: "http://127.0.0.1:9000/git/datekit.git",376+ source: null,377+ });378+ })379+ );380+381+ it.effect("mints, lists and revokes tokens through the host", () =>382+ Effect.gen(function* () {383+ const { repo } = yield* withDatekit();384+ const token = yield* call(() => repo.createToken("read", 60));385+ const revoked = yield* call(() => repo.revokeToken("secret-2"));386+ const { tokens } = yield* call(() => repo.listTokens());387+388+ expect(token).toStrictEqual({389+ expiresAt: "2026-10-07T12:01:00.000Z",390+ id: "token-2",391+ plaintext: "secret-2",392+ scope: "read",393+ });394+ expect(revoked).toBeTruthy();395+ expect(tokens.map(({ id, state }) => [id, state])).toStrictEqual([396+ ["token-1", "active"],397+ ["token-2", "revoked"],398+ ]);399+ })400+ );401+402+ it.effect("lists and deletes what it made", () =>403+ Effect.gen(function* () {404+ const { binding } = yield* withDatekit();405+406+ yield* call(() => binding.create("burrow"));407+408+ const listed = yield* call(() => binding.list());409+ const deleted = yield* call(() => binding.delete("datekit"));410+ const again = yield* call(() => binding.delete("datekit"));411+ const gone = yield* thrown(() => binding.get("datekit"));412+413+ expect(listed).toMatchObject({ total: 2 });414+ expect(listed.repos.map(({ name }) => name)).toStrictEqual([415+ "datekit",416+ "burrow",417+ ]);418+ expect([deleted, again]).toStrictEqual([true, false]);419+ expect(described(gone).code).toBe("NOT_FOUND");420+ })421+ );422+423+ it.effect("reports a repo made read-only as read-only", () =>424+ Effect.gen(function* () {425+ const { binding, repo } = yield* withDatekit();426+427+ yield* call(() => binding.create("archive", { readOnly: true }));428+ yield* call(() => repo.fork("datekit--mirror", { readOnly: true }));429+430+ const { repos } = yield* call(() => binding.list());431+432+ expect(repos.map(({ name, readOnly }) => [name, readOnly])).toStrictEqual(433+ [434+ ["datekit", false],435+ ["archive", true],436+ ["datekit--mirror", true],437+ ]438+ );439+ })440+ );441+442+ it.effect(443+ "lists nothing it deleted, even after a stale handle reads the repo",444+ () =>445+ Effect.gen(function* () {446+ const { binding, repo } = yield* withDatekit();447+448+ yield* call(() => binding.delete("datekit"));449+450+ const codes = [451+ yield* thrown(() => repo.info()),452+ yield* thrown(() => repo.log()),453+ yield* thrown(() => repo.revokeToken("secret-1")),454+ yield* thrown(() => repo.listTokens()),455+ ].map((error) => described(error).code);456+457+ expect(codes).toStrictEqual([458+ "NOT_FOUND",459+ "NOT_FOUND",460+ "NOT_FOUND",461+ "NOT_FOUND",462+ ]);463+ expect(yield* call(() => binding.list())).toStrictEqual({464+ repos: [],465+ total: 0,466+ });467+ })468+ );469+});added:packages/testkit/test/golden.test.ts+268 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import { Cause, ConfigProvider, Effect, Exit, FileSystem } from "effect";5+6+import { git, gitOk } from "../src/git.ts";7+import { expectGolden, GoldenDir, normaliseGitOutput } from "../src/golden.ts";8+9+const id = "0123456789abcdef0123456789abcdef01234567";10+11+/**12+ * One push of one fixed commit to a new bare repo, through a pre-receive hook13+ * that prints what it received: git's whole stderr, as it printed it.14+ */15+const pushOnce = Effect.gen(function* () {16+ const fs = yield* FileSystem.FileSystem;17+ const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);18+ const remote = `${root}/remote.git`;19+ const work = `${root}/work`;20+ const hook = `${remote}/hooks/pre-receive`;21+22+ yield* gitOk(23+ root,24+ "init",25+ "--quiet",26+ "--bare",27+ "--initial-branch=main",28+ remote29+ );30+ yield* fs31+ .writeFileString(32+ hook,33+ '#!/bin/sh\nwhile read old new ref; do echo "received $new for $ref"; done\n'34+ )35+ .pipe(Effect.orDie);36+ yield* fs.chmod(hook, 0o755).pipe(Effect.orDie);37+ yield* gitOk(root, "init", "--quiet", "--initial-branch=main", work);38+ yield* fs.writeFileString(`${work}/a.txt`, "a\n").pipe(Effect.orDie);39+ yield* gitOk(work, "add", "--all");40+ yield* gitOk(work, "commit", "--quiet", "--message", "first");41+42+ return yield* git(work, "push", remote, "HEAD:refs/heads/main");43+}).pipe(Effect.scoped);44+45+/** What a failed expectation says, or nothing when it passed. */46+const complaint = (exit: Exit.Exit<void>) =>47+ Exit.isFailure(exit) ? String(Cause.squash(exit.cause)) : "";48+49+/** Runs with golden files in a fresh folder, and `UPDATE_GOLDEN` as given. */50+const inTempGoldens = <A, E, R>(51+ update: string,52+ run: (dir: string) => Effect.Effect<A, E, R>53+) =>54+ Effect.gen(function* () {55+ const fs = yield* FileSystem.FileSystem;56+ const dir = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);57+58+ return yield* run(`${dir}/golden`).pipe(59+ Effect.provideService(GoldenDir, `${dir}/golden`),60+ Effect.provide(61+ ConfigProvider.layer(62+ ConfigProvider.fromEnv({ env: { UPDATE_GOLDEN: update } })63+ )64+ )65+ );66+ }).pipe(Effect.scoped);67+68+describe("git output, normalised", () => {69+ it("drops the eight spaces git pads side-band lines with, and any other trailing space", () => {70+ expect(71+ normaliseGitOutput(72+ "remote: StaleBase: main moved \nremote: next: git pull --rebase \nTo here \t\n"73+ )74+ ).toBe(75+ "remote: StaleBase: main moved\nremote: next: git pull --rebase\nTo here\n"76+ );77+ });78+79+ it("names temporary folders <tmp>, on Linux and on macOS", () => {80+ expect(81+ normaliseGitOutput(82+ [83+ "To /tmp/Ab3dE9/remote.git",84+ "To /var/folders/x1/y2z3w4/T/Qq81Zk/remote.git",85+ "To /private/var/folders/x1/y2z3w4/T/Qq81Zk/remote.git",86+ "fatal: '/private/tmp/kk2/work' is not a git repository",87+ ].join("\n")88+ )89+ ).toBe(90+ [91+ "To <tmp>/remote.git",92+ "To <tmp>/remote.git",93+ "To <tmp>/remote.git",94+ "fatal: '<tmp>/work' is not a git repository",95+ ].join("\n")96+ );97+ });98+99+ it("names full object ids <sha>, and leaves short ids and longer hex alone", () => {100+ expect(101+ normaliseGitOutput(102+ `remote: received ${id} for refs/heads/main\n 0123456..89abcde main -> main\nsha256 ${id}0123`103+ )104+ ).toBe(105+ `remote: received <sha> for refs/heads/main\n 0123456..89abcde main -> main\nsha256 ${id}0123`106+ );107+ });108+109+ it("names a local server's address <host>, since its port changes every run", () => {110+ expect(111+ normaliseGitOutput(112+ "To http://127.0.0.1:43567/datekit--fix--bob.git\nTo http://localhost:8787/x.git"113+ )114+ ).toBe("To http://<host>/datekit--fix--bob.git\nTo http://<host>/x.git");115+ });116+117+ it("keeps what a terminal would show of a line rewritten with carriage returns", () => {118+ expect(119+ normaliseGitOutput(120+ "Writing objects: 50% (1/2)\rWriting objects: 100% (2/2), done.\r\nTo x\r\n"121+ )122+ ).toBe("Writing objects: 100% (2/2), done.\nTo x\n");123+ });124+125+ it("keeps a progress line that ends in a carriage return, as a terminal still shows it", () => {126+ expect(127+ normaliseGitOutput(128+ "Counting objects: 1\rCounting objects: 2\r\r\nTo x\nWriting objects: 50% (1/2)\r"129+ )130+ ).toBe("Counting objects: 2\nTo x\nWriting objects: 50% (1/2)");131+ });132+133+ it.live(134+ "makes two runs of the same push compare equal, and match their golden file",135+ () =>136+ Effect.gen(function* () {137+ const first = yield* pushOnce;138+ const second = yield* pushOnce;139+140+ expect([first.exitCode, second.exitCode]).toStrictEqual([0, 0]);141+ expect(first.stderr).toContain(" \n");142+ expect(first.stderr).not.toBe(second.stderr);143+ expect(normaliseGitOutput(first.stderr)).toBe(144+ normaliseGitOutput(second.stderr)145+ );146+147+ yield* expectGolden(148+ "push-new-branch",149+ normaliseGitOutput(first.stderr)150+ );151+ }).pipe(Effect.provide(NodeServices.layer)),152+ 20_000153+ );154+});155+156+describe("golden files", () => {157+ it.effect("pass when the text matches the file", () =>158+ Effect.gen(function* () {159+ const fs = yield* FileSystem.FileSystem;160+161+ yield* inTempGoldens("0", (dir) =>162+ Effect.gen(function* () {163+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie);164+ yield* fs165+ .writeFileString(`${dir}/same.txt`, "To <tmp>/remote.git\n")166+ .pipe(Effect.orDie);167+168+ const exit = yield* Effect.exit(169+ expectGolden("same", "To <tmp>/remote.git\n")170+ );171+172+ expect(complaint(exit)).toBe("");173+ })174+ );175+ }).pipe(Effect.provide(NodeServices.layer))176+ );177+178+ it.effect(179+ "fail, naming the file and how to accept the change, when the text differs",180+ () =>181+ Effect.gen(function* () {182+ const fs = yield* FileSystem.FileSystem;183+184+ yield* inTempGoldens("0", (dir) =>185+ Effect.gen(function* () {186+ yield* fs187+ .makeDirectory(dir, { recursive: true })188+ .pipe(Effect.orDie);189+ yield* fs190+ .writeFileString(`${dir}/changed.txt`, "line one\nline two\n")191+ .pipe(Effect.orDie);192+193+ const exit = yield* Effect.exit(194+ expectGolden("changed", "line one\nline 2\n")195+ );196+197+ expect(complaint(exit)).toContain(`${dir}/changed.txt`);198+ expect(complaint(exit)).toContain("UPDATE_GOLDEN=1");199+ expect(complaint(exit)).toContain("- line two");200+ expect(complaint(exit)).toContain("+ line 2");201+ })202+ );203+ }).pipe(Effect.provide(NodeServices.layer))204+ );205+206+ it.effect("fail when there is no file yet", () =>207+ inTempGoldens("0", () =>208+ Effect.gen(function* () {209+ const exit = yield* Effect.exit(expectGolden("absent", "text\n"));210+211+ expect(complaint(exit)).toContain("absent.txt");212+ expect(complaint(exit)).toContain("UPDATE_GOLDEN=1");213+ })214+ ).pipe(Effect.provide(NodeServices.layer))215+ );216+217+ it.effect("are written, folder and all, under UPDATE_GOLDEN=1", () =>218+ Effect.gen(function* () {219+ const fs = yield* FileSystem.FileSystem;220+221+ yield* inTempGoldens("1", (dir) =>222+ Effect.gen(function* () {223+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie);224+ yield* fs225+ .writeFileString(`${dir}/rewritten.txt`, "old\n")226+ .pipe(Effect.orDie);227+228+ yield* expectGolden("rewritten", "new\n");229+ yield* expectGolden("nested/fresh", "fresh\n");230+231+ expect(yield* fs.exists(`${dir}/nested/fresh.txt`)).toBeTruthy();232+ expect(233+ yield* fs.readFileString(`${dir}/rewritten.txt`).pipe(Effect.orDie)234+ ).toBe("new\n");235+ expect(236+ yield* fs237+ .readFileString(`${dir}/nested/fresh.txt`)238+ .pipe(Effect.orDie)239+ ).toBe("fresh\n");240+ })241+ );242+ }).pipe(Effect.provide(NodeServices.layer))243+ );244+245+ it.effect(246+ "never spell the product's name: its config folder and name are written as placeholders",247+ () =>248+ Effect.gen(function* () {249+ const fs = yield* FileSystem.FileSystem;250+251+ yield* inTempGoldens("1", (dir) =>252+ Effect.gen(function* () {253+ yield* expectGolden(254+ "brand",255+ `wrote ${Brand.configDir}/project.ts; next: ${Brand.cli} status, then ${Brand.name} lands it\n`256+ );257+258+ expect(yield* fs.exists(`${dir}/brand.txt`)).toBeTruthy();259+ expect(260+ yield* fs.readFileString(`${dir}/brand.txt`).pipe(Effect.orDie)261+ ).toBe(262+ "wrote <configDir>/project.ts; next: <brand> status, then <brand> lands it\n"263+ );264+ })265+ );266+ }).pipe(Effect.provide(NodeServices.layer))267+ );268+});added:packages/testkit/test/scenarios.test.ts+359 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import { Ask } from "@repo/protocol/domain/ask";4+import { CheckSpec } from "@repo/protocol/domain/check";5+import { Command, SymbolName } from "@repo/protocol/domain/common";6+import { Policy } from "@repo/protocol/domain/policy";7+import {8+ CommitSha,9+ DecisionId,10+ ProposalId,11+ RepoPath,12+ RequestId,13+} from "@repo/protocol/ids";14+import { DateTime, Equal, Schema } from "effect";15+import { onTestFinished, vi } from "vitest";16+17+import {18+ aProject,19+ ids,20+ sha,21+ sixChildren,22+ withAsk,23+ withKind,24+ withVouches,25+} from "../src/scenarios.ts";26+27+const six = [1, 2, 3, 4, 5, 6];28+29+const children = six.map((n) => `drop-legacy-fetch-p${n}`);30+31+const isPolicy = Schema.is(Policy);32+33+const isAsk = Schema.is(Ask);34+35+const lintToZero = CheckSpec.cases.LintToZero.make({36+ command: Command.make("bun run lint --format json"),37+ rule: "no-floating-effect",38+});39+40+const lintKind = {41+ checkKind: "lintToZero",42+ claimers: "anyone",43+ finish: "never",44+ name: "lintToZero",45+ oneWay: false,46+ race: 1,47+ requires: ["want"],48+ strength: "assertion",49+} as const;50+51+const parserFix = () =>52+ aProject().pipe(53+ withAsk({ id: "fix-parser", territory: "packages/parser" }),54+ withVouches(["bob"])55+ );56+57+describe("a project scenario", () => {58+ it("holds a policy that decodes as a Policy, at its landed commit", () => {59+ const { landed, policy } = aProject();60+61+ expect(isPolicy(policy)).toBeTruthy();62+ expect(63+ Schema.decodeSync(Policy)(Schema.encodeSync(Policy)(policy))64+ ).toStrictEqual(policy);65+ expect(policy.at).toBe(landed);66+ expect(policy.vouch.file).toBe(`${Brand.configDir}/vouched.td`);67+ expect(policy.kinds.map(({ name }) => name)).toStrictEqual([68+ "fix",69+ "migrate",70+ ]);71+ });72+73+ it("is decided, by default, by its initializer alice, for every path", () => {74+ const { initializer, policy, project } = aProject();75+76+ expect({ initializer, project }).toStrictEqual({77+ initializer: "alice",78+ project: "datekit",79+ });80+ expect(policy.deciders).toStrictEqual([81+ { handles: ["alice"], paths: "**" },82+ ]);83+ });84+85+ it("names its people by the names it was given, deciders first", () => {86+ const scenario = aProject({87+ deciders: ["dana", "eve"],88+ name: "burrow",89+ people: ["bob", "carol"],90+ });91+92+ expect(scenario.project).toBe("burrow");93+ expect(scenario.initializer).toBe("dana");94+ expect([...scenario.people]).toStrictEqual([95+ ["dana", "dana"],96+ ["eve", "eve"],97+ ["bob", "bob"],98+ ["carol", "carol"],99+ ]);100+ expect(scenario.policy.deciders).toStrictEqual([101+ { handles: ["dana", "eve"], paths: "**" },102+ ]);103+ });104+105+ it("opens an ask in its territory, asked by the initializer in the landed commit", () => {106+ const now = DateTime.makeUnsafe("2026-10-09T08:30:00Z");107+108+ const scenario = aProject({ now }).pipe(109+ withAsk({ id: "fix-parser", territory: "packages/parser" })110+ );111+112+ const [ask] = scenario.policy.asks;113+114+ expect(isAsk(ask)).toBeTruthy();115+ expect(ask).toStrictEqual({116+ askedBy: "alice",117+ blockedBy: [],118+ brief: { want: "fix-parser: its check passes in packages/parser" },119+ check: CheckSpec.cases.RedThenGreen.make({120+ path: RepoPath.make("packages/parser/test/fix-parser.test.ts"),121+ }),122+ file: `${Brand.configDir}/asks/fix-parser.ask.ts`,123+ id: "fix-parser",124+ kind: "fix",125+ openedAt: now,126+ openedIn: scenario.landed,127+ project: "datekit",128+ state: "open",129+ territory: { module: "parser", paths: ["packages/parser/**"] },130+ });131+ expect(scenario.policy.modules).toStrictEqual([132+ { module: "parser", paths: ["packages/parser/**"] },133+ ]);134+ expect(isPolicy(scenario.policy)).toBeTruthy();135+ });136+137+ it("takes an ask's kind, check, blockers and reserve, and keeps one module per territory", () => {138+ const scenario = aProject().pipe(139+ withAsk({ id: "fix-parser", territory: "packages/parser" }),140+ withAsk({141+ blockedBy: ["fix-parser"],142+ check: lintToZero,143+ id: "lint-parser",144+ kind: "lintToZero",145+ reserve: "newcomers",146+ territory: "packages/parser",147+ })148+ );149+150+ const [, ask] = scenario.policy.asks;151+152+ expect(isAsk(ask)).toBeTruthy();153+ expect(ask).toMatchObject({154+ blockedBy: ["fix-parser"],155+ check: lintToZero,156+ kind: "lintToZero",157+ reserve: "newcomers",158+ });159+ expect(scenario.policy.modules).toHaveLength(1);160+ });161+162+ it("opens an ask over the whole repo without making the repo a module", () => {163+ const scenario = aProject().pipe(164+ withAsk({ id: "tidy-readme", territory: "." })165+ );166+167+ expect(scenario.policy.asks[0]?.territory).toStrictEqual({168+ module: ".",169+ paths: ["**"],170+ });171+ expect(scenario.policy.modules).toStrictEqual([]);172+ });173+174+ it("refuses an ask the domain refuses, such as one named after a reserved word", () => {175+ expect(() =>176+ aProject().pipe(withAsk({ id: "me", territory: "packages/parser" }))177+ ).toThrow("reserved");178+ });179+180+ it("adds a kind, replacing one of the same name", () => {181+ const scenario = aProject().pipe(182+ withKind(lintKind),183+ withKind({ ...lintKind, race: 2 })184+ );185+186+ expect(scenario.policy.kinds.map(({ name }) => name)).toStrictEqual([187+ "fix",188+ "migrate",189+ "lintToZero",190+ ]);191+ expect(scenario.policy.kinds[2]).toStrictEqual({ ...lintKind, race: 2 });192+ });193+194+ it("records vouches and denouncements as the vouch file's lines", () => {195+ const scenario = aProject().pipe(196+ withVouches(["bob", "carol"], ["mallory"])197+ );198+199+ expect(scenario.policy.vouches).toStrictEqual([200+ { denounced: false, handle: "bob" },201+ { denounced: false, handle: "carol" },202+ { denounced: true, handle: "mallory" },203+ ]);204+ expect(isPolicy(scenario.policy)).toBeTruthy();205+ });206+207+ it("builds the same value every time", () => {208+ expect(Equal.equals(parserFix(), parserFix())).toBeTruthy();209+ expect(Equal.equals(sixChildren(), sixChildren())).toBeTruthy();210+ expect(Equal.equals(parserFix(), aProject({ name: "burrow" }))).toBeFalsy();211+ });212+});213+214+describe("six children of a migrate ask", () => {215+ it("is a parent, six children and a delete child, each a valid ask", () => {216+ const { policy } = sixChildren();217+218+ expect(policy.asks.map(({ id }) => id)).toStrictEqual([219+ "drop-legacy-fetch",220+ ...children,221+ "drop-legacy-fetch-delete",222+ ]);223+ expect(policy.asks.every((ask) => isAsk(ask))).toBeTruthy();224+ expect(isPolicy(policy)).toBeTruthy();225+ });226+227+ it("has a parent migrating the symbol across the six packages", () => {228+ const [parent] = sixChildren().policy.asks;229+230+ expect(parent).toMatchObject({231+ check: CheckSpec.cases.Migrate.make({232+ count: Command.make(233+ "node scripts/count-callers.mjs legacyFetch --json"234+ ),235+ from: SymbolName.make("legacyFetch"),236+ to: SymbolName.make("http.get"),237+ }),238+ kind: "migrate",239+ territory: { paths: six.map((n) => `packages/p${n}/**`) },240+ });241+ expect(parent?.parent).toBeUndefined();242+ });243+244+ it("splits into six children on disjoint packages, the project's modules", () => {245+ const { policy } = sixChildren();246+ const steps = policy.asks.slice(1, 7);247+248+ expect(249+ steps.map(({ blockedBy, id, parent, territory }) => ({250+ blockedBy,251+ id,252+ parent,253+ territory,254+ }))255+ ).toStrictEqual(256+ six.map((n) => ({257+ blockedBy: [],258+ id: `drop-legacy-fetch-p${n}`,259+ parent: "drop-legacy-fetch",260+ territory: { module: `p${n}`, paths: [`packages/p${n}/**`] },261+ }))262+ );263+ expect(264+ steps.every(({ check }) => CheckSpec.guards.Migrate(check))265+ ).toBeTruthy();266+ expect(policy.modules.map(({ module }) => module)).toStrictEqual(267+ six.map((n) => `p${n}`)268+ );269+ });270+271+ it("ends with a delete child blocked by all six", () => {272+ const last = sixChildren().policy.asks.at(-1);273+274+ expect(last).toMatchObject({275+ blockedBy: children,276+ check: CheckSpec.cases.SymbolAbsent.make({277+ count: Command.make(278+ "node scripts/count-callers.mjs legacyFetch --json"279+ ),280+ symbol: SymbolName.make("legacyFetch"),281+ }),282+ parent: "drop-legacy-fetch",283+ });284+ });285+286+ it("names the family after the symbol it moves", () => {287+ const { policy } = sixChildren({ symbol: "oldClock", to: "clock.now" });288+289+ expect(policy.asks.map(({ id }) => id)).toStrictEqual([290+ "drop-old-clock",291+ ...six.map((n) => `drop-old-clock-p${n}`),292+ "drop-old-clock-delete",293+ ]);294+ expect(policy.asks[0]?.check).toMatchObject({295+ from: "oldClock",296+ to: "clock.now",297+ });298+ });299+});300+301+describe("deterministic ids", () => {302+ it("makes a commit id from a seed with FNV-1a, the same every run", () => {303+ // Worked out by a separate FNV-1a implementation over `0:main` … `4:main`.304+ expect(sha("main")).toBe("72245cbe78d5b41b2cadf2502b38c3a5d6578b1a");305+ expect(Schema.is(CommitSha)(sha("main"))).toBeTruthy();306+ expect(sha("main")).not.toBe(sha("answer"));307+ expect(aProject().landed).toBe("6a1d765d8fd2f48cf995fb978771958e356e2bb1");308+ });309+310+ it("mints request, proposal and decision ids from counters", () => {311+ const next = ids();312+313+ expect([next.request(), next.request()]).toStrictEqual([314+ "req-000001",315+ "req-000002",316+ ]);317+ expect([next.proposal(), next.decision()]).toStrictEqual([318+ "prop-000001",319+ "dec-000001",320+ ]);321+ expect(ids().request()).toBe("req-000001");322+ });323+324+ it("mints ids the domain accepts", () => {325+ const next = ids();326+327+ expect(Schema.is(RequestId)(next.request())).toBeTruthy();328+ expect(Schema.is(ProposalId)(next.proposal())).toBeTruthy();329+ expect(Schema.is(DecisionId)(next.decision())).toBeTruthy();330+ });331+332+ it("builds every value without reading the clock or randomness", () => {333+ const reads = {334+ getRandomValues: vi.spyOn(crypto, "getRandomValues"),335+ now: vi.spyOn(Date, "now"),336+ random: vi.spyOn(Math, "random"),337+ randomUUID: vi.spyOn(crypto, "randomUUID"),338+ };339+340+ onTestFinished(() => {341+ for (const read of Object.values(reads)) {342+ read.mockRestore();343+ }344+ });345+346+ const next = ids();347+348+ parserFix();349+ sixChildren();350+ sha("main");351+ next.request();352+ next.proposal();353+ next.decision();354+355+ expect(356+ Object.values(reads).map((read) => read.mock.calls.length)357+ ).toStrictEqual([0, 0, 0, 0]);358+ });359+});deleted:packages/testkit/test/smoke.test.ts-10 removed
12345678910import { describe, expect, it } from "@effect/vitest";
import manifest from "../package.json" with { type: "json" };
// A skeleton's one test, so vitest finds a file; real tests replace it.describe("the package", () => { it("is @repo/testkit", () => { expect(manifest.name).toBe("@repo/testkit"); });});