Let tests build a project scenario, a fake Artifacts binding and normalised git transcripts in one line each
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- scenarios: aProject() is a Scenario value (pipeable, compared by Equal.equals) with a Policy decoded by protocol's own Policy schema at a landed commit made from the project's name; deciders default to alice for every path (D20); people map the names a test gives to Handles. withAsk/withKind/withVouches add decoded asks, kinds and vouch lines, so a scenario the domain would refuse throws while it is built. sixChildren() is burrow's migrate family: drop-legacy-fetch, six children on packages/p1..p6 (the project's modules), and drop-legacy-fetch-delete (SymbolAbsent) blocked by all six, ids shaped as 506's childId/deleteChildId. - Determinism: builders take now (default 2026-10-07T12:00:00Z, clock.defaultNow) and never read the clock; sha(seed) is FNV-1a over 0:seed..4:seed (the xor in arithmetic, since lint bans bitwise operators); ids() mints req-/prop-/dec-000001 from counters. - Decision: withAsk's check takes a CheckSpec built with CheckSpec.cases.<Tag>.make, not the encoded form the issue named: anti-slop refuses every literal _tag object, so no caller could write an encoded check. withAsk also takes parent and want, sixChildren takes to, and Scenario carries now (asks open at it). - golden: normaliseGitOutput drops git's 8-space side-band padding and any trailing space, and writes temp folders as <tmp>, full object ids as <sha>, a local server's host:port as <host> (gateway tests use ephemeral ports), and each carriage-return rewrite as a terminal leaves it. expectGolden compares with <GoldenDir>/<name>.txt (GoldenDir is a Context.Reference, default test/golden), dies with a line diff and the UPDATE_GOLDEN=1 hint, and writes the file under UPDATE_GOLDEN=1, with the config dir as <configDir> and the slug as <brand> so no golden file names the product. - clock: at(iso), advanceTo(iso) over TestClock.setTime, hours(n). - fake-artifacts-binding: an @cloudflare/workers-types Artifacts over a structural HostLike (RepoHost's methods with protocol ids and the same brand keys, so a RepoHost value is one; testkit imports no adapter package). It keeps the spikes' surprises: codeless plain Errors as under wrangler dev (S1 #22, verbatim message), a fork that throws a 500 after making the repo then 409 on the retry (S7), readFile/log resolving only short branch names and commit ids (S1 #20), lastPushAt null (S1 #21). Errors are Object.assign(new Error, {code, name: "ArtifactsError", numericCode}); each call is one Effect.runPromise at the promise boundary. - ASSUMPTION: numericCode is 10201 (ALREADY_EXISTS) and 10400 (INTERNAL_ERROR) as S7 recorded; other codes read 0, never recorded. readCommit's authoredAt/committedAt are 0 (RepoHost commits carry no times). A TMPDIR outside /tmp, /var/tmp, /private/tmp or macOS's /var/folders/.../T is not normalised. - Tests added: scenarios (Policy and Ask decode, defaults, people, kinds, vouches, Equal twice, the family's shape, a pinned FNV value worked out by a separate implementation, counters with no randomUUID), golden (each normalisation rule, two real pushes through a pre-receive hook comparing equal and matching test/golden/push-new-branch.txt, and expectGolden's pass, diff, missing, rewrite and brand cases in a temp GoldenDir), clock (instant, durations, setTime, sleepers waking), and the fake over a tiny in-test host (delegated reads, NOT_FOUND, codeless, 500 then 409, refs, invalid input, remoteBase, tokens, list and delete). Each was red by assertion over empty stubs first. A throwaway probe (not committed) confirmed RepoHost is assignable to HostLike and ran the fake over RepoHostMemory. - test/smoke.test.ts is deleted. UPDATE_GOLDEN does not pass through turbo's strict env mode; run vitest in the package (the issue's Comments ask the integrator about passThroughEnv).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+2324 added−10 removed
- tests:+1064 added−10 removed
- other:+1260 added−0 removed
Provenance
- Commit
d6d17af- Tree
d55e6c0- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3d5870c
10 files changed+2324 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+662 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). */194+const refusalOf = (error: HostError) =>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+ RepoExists: ({ name }) =>208+ new Refused({209+ code: "ALREADY_EXISTS",210+ reason: `repo already exists: ${name}`,211+ }),212+ RepoNotFound: ({ name }) =>213+ new Refused({214+ code: "NOT_FOUND",215+ reason: `Repository not found: ${name}`,216+ }),217+ });218+219+/** The repos the fake made, with what `info()` and `list()` report. */220+interface Kept {221+ readonly id: string;222+ readonly name: RepoName;223+ readonly description: string | null;224+ readonly defaultBranch: string;225+ readonly source: string | null;226+ readonly readOnly: boolean;227+ readonly tokens: Map<228+ string,229+ ArtifactsTokenInfo & { readonly plaintext: string }230+ >;231+}232+233+// Artifacts stamps repos with the time they were made; the fake with the234+// scenarios' fixed instant, so two runs give the same values.235+const stamped = DateTime.formatIso(defaultNow);236+237+const isObjectId = Schema.is(ObjectId);238+239+const decodeName = Schema.decodeUnknownOption(RepoName);240+241+const decodeBranch = Schema.decodeUnknownOption(BranchName);242+243+const decodePath = Schema.decodeUnknownOption(RepoPath);244+245+/**246+ * `main` → that branch; 40 hex digits → that commit; anything else, such as247+ * `refs/heads/main` or a tag, resolves to nothing (S1 #20).248+ */249+const revisionOf = (ref: string): Option.Option<Revision> =>250+ isObjectId(ref)251+ ? Option.some(Revision.Commit({ sha: CommitSha.make(ref) }))252+ : Option.map(decodeBranch(ref), (name) => Revision.Branch({ name }));253+254+// Artifacts gives canonical modes: a folder is `40000`, not `040000`.255+const typeOf = (entry: HostTreeEntry): ArtifactsTreeEntryType =>256+ Match.value(entry.mode).pipe(257+ Match.when("040000", () => "tree" as const),258+ Match.when("100755", () => "exec" as const),259+ Match.when("120000", () => "symlink" as const),260+ Match.when("160000", () => "gitlink" as const),261+ Match.orElse(() => "blob" as const)262+ );263+264+const entryOf = (entry: HostTreeEntry): ArtifactsTreeEntry => ({265+ hash: entry.sha,266+ mode: entry.mode.replace(/^0/u, ""),267+ name: entry.name,268+ type: typeOf(entry),269+});270+271+// `RepoHost`'s commits carry no times, so the fake reports the epoch.272+const metadataOf = (commit: HostCommit): ArtifactsCommitMetadata => ({273+ author: { email: commit.author.email, name: commit.author.name },274+ authoredAt: 0,275+ committedAt: 0,276+ committer: { email: commit.committer.email, name: commit.committer.name },277+ hash: commit.sha,278+ message: commit.message,279+ parents: [...commit.parents],280+ treeHash: commit.tree,281+});282+283+const refuse = (code: ArtifactsError["code"], reason: string) =>284+ Effect.fail(new Refused({ code, reason }));285+286+const named = (name: string, code: ArtifactsError["code"]) =>287+ Option.match(decodeName(name), {288+ onNone: () => refuse(code, `Invalid repository name: ${name}`),289+ onSome: Effect.succeed,290+ });291+292+const objectId = (hash: string): Effect.Effect<ObjectId, Refused> =>293+ isObjectId(hash)294+ ? Effect.succeed(hash)295+ : refuse("INVALID_INPUT", `Invalid object id: ${hash}`);296+297+const blobOf = (bytes: Uint8Array) =>298+ new Blob([bytes], { type: "application/octet-stream" });299+300+/** An Artifacts binding over `host`, with the real one's surprises (see the module's doc). */301+export const fakeArtifactsBinding = (302+ host: HostLike,303+ options: FakeOptions = {}304+): Artifacts => {305+ const kept = new Map<RepoName, Kept>();306+ let forkFailures = options.forkFailures ?? 0;307+ let made = 0;308+309+ /** The thrown error: an `ArtifactsError`, or a plain one when codeless. */310+ const thrown = ({ code, reason }: Refused) =>311+ options.codeless === true312+ ? new Error(`ArtifactsError: ${reason}`)313+ : Object.assign(new Error(reason), {314+ code,315+ name: "ArtifactsError" as const,316+ numericCode: numericOf(code),317+ });318+319+ /** Runs one call as the binding answers: a promise, rejected with its error. */320+ const run = <A>(effect: Effect.Effect<A, Refused | HostError>) =>321+ Effect.runPromise(322+ effect.pipe(323+ Effect.matchEffect({324+ onFailure: (error) =>325+ Effect.die(326+ thrown(327+ Match.valueTags(error, {328+ ForkInProgress: refusalOf,329+ HostBusy: refusalOf,330+ ImportRefused: refusalOf,331+ Refused: (refused) => refused,332+ RepoExists: refusalOf,333+ RepoNotFound: refusalOf,334+ })335+ )336+ ),337+ onSuccess: Effect.succeed,338+ })339+ )340+ );341+342+ const remoteOf = (name: RepoName) =>343+ options.remoteBase === undefined344+ ? host.remote(name)345+ : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));346+347+ const keep = (348+ name: RepoName,349+ fields: Partial<Pick<Kept, "description" | "defaultBranch" | "source">>350+ ) => {351+ made += 1;352+353+ const repo: Kept = {354+ defaultBranch: fields.defaultBranch ?? "main",355+ description: fields.description ?? null,356+ id: `repo-${String(made).padStart(6, "0")}`,357+ name,358+ readOnly: false,359+ source: fields.source ?? null,360+ tokens: new Map(),361+ };362+363+ kept.set(name, repo);364+365+ return repo;366+ };367+368+ /** What `info()` shows for a repo the fake did not make itself. */369+ const keptOf = (name: RepoName) => kept.get(name) ?? keep(name, {});370+371+ const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>372+ host.mintToken(name, scope, Duration.seconds(seconds)).pipe(373+ Effect.map((token) => {374+ const plaintext = Redacted.value(token.secret);375+ const expiresAt = DateTime.formatIso(token.expiresAt);376+377+ keptOf(name).tokens.set(token.id, {378+ createdAt: stamped,379+ expiresAt,380+ id: token.id,381+ plaintext,382+ scope,383+ state: "active",384+ });385+386+ return { expiresAt, id: token.id, plaintext, scope: token.scope };387+ })388+ );389+390+ /** A new repo's result: its metadata, its remote and a day-long write token (S1 #2). */391+ const createdOf = (repo: Kept) =>392+ Effect.gen(function* () {393+ const remote = yield* remoteOf(repo.name);394+ const token = yield* mint(repo.name, "write", 86_400);395+396+ return {397+ defaultBranch: repo.defaultBranch,398+ description: repo.description,399+ id: repo.id,400+ name: repo.name,401+ remote,402+ token: token.plaintext,403+ };404+ });405+406+ /** What `list()` shows of a repo; `info()` adds its remote. */407+ const summaryOf = (repo: Kept): Omit<ArtifactsRepoInfo, "remote"> => ({408+ createdAt: stamped,409+ defaultBranch: repo.defaultBranch,410+ description: repo.description,411+ id: repo.id,412+ // Still null after pushes (S1 #21).413+ lastPushAt: null,414+ name: repo.name,415+ readOnly: repo.readOnly,416+ source: repo.source,417+ updatedAt: stamped,418+ });419+420+ const info = (repo: Kept) =>421+ remoteOf(repo.name).pipe(422+ Effect.map((remote): ArtifactsRepoInfo => ({423+ ...summaryOf(repo),424+ remote,425+ }))426+ );427+428+ const handle = (name: RepoName): ArtifactsRepo => ({429+ createToken: (scope = "write", ttl = 86_400) =>430+ run(431+ ttl < 60 || ttl > 31_536_000432+ ? refuse("INVALID_TTL", `ttl must be between 60 and 31536000: ${ttl}`)433+ : mint(name, scope, ttl).pipe(434+ Effect.map(({ expiresAt, id, plaintext }) => ({435+ expiresAt,436+ id,437+ plaintext,438+ scope,439+ }))440+ )441+ ),442+ fork: (target, forkOptions) =>443+ run(444+ Effect.gen(function* () {445+ const fork = yield* named(target, "INVALID_REPO_NAME");446+447+ yield* host.fork(name, fork);448+449+ const repo = keep(fork, {450+ description: forkOptions?.description ?? null,451+ source: `artifacts:fake/${name}`,452+ });453+454+ if (forkFailures > 0) {455+ forkFailures -= 1;456+457+ return yield* refuse(458+ "INTERNAL_ERROR",459+ "An internal error occurred."460+ );461+ }462+463+ return yield* createdOf(repo);464+ })465+ ),466+ info: () => run(info(keptOf(name))),467+ listTokens: () =>468+ run(469+ host.remote(name).pipe(470+ Effect.map(() => {471+ const tokens = [...keptOf(name).tokens.values()].map(472+ ({ createdAt, expiresAt, id, scope, state }) => ({473+ createdAt,474+ expiresAt,475+ id,476+ scope,477+ state,478+ })479+ );480+481+ return { tokens, total: tokens.length };482+ })483+ )484+ ),485+ log: (logOptions) =>486+ run(487+ Effect.gen(function* () {488+ const ref = logOptions?.ref ?? "HEAD";489+ const limit = Math.min(logOptions?.limit ?? 50, 1000);490+ const offset = logOptions?.offset ?? 0;491+492+ const at =493+ ref === "HEAD"494+ ? Option.some(495+ Revision.Branch({496+ name: BranchName.make(keptOf(name).defaultBranch),497+ })498+ )499+ : revisionOf(ref);500+501+ if (Option.isNone(at)) {502+ return [];503+ }504+505+ const commits = yield* host.log(name, at.value, offset + limit);506+507+ return commits.slice(offset).map(metadataOf);508+ })509+ ),510+ readBlob: (hash) =>511+ run(512+ objectId(hash).pipe(513+ Effect.flatMap((blob) => host.readBlob(name, blob)),514+ Effect.map((bytes) => Option.getOrNull(Option.map(bytes, blobOf)))515+ )516+ ),517+ readCommit: (hash) =>518+ run(519+ objectId(hash).pipe(520+ Effect.flatMap((sha) => host.readCommit(name, CommitSha.make(sha))),521+ Effect.map((commit) =>522+ Option.getOrNull(Option.map(commit, metadataOf))523+ )524+ )525+ ),526+ readFile: ({ path, ref }) =>527+ run(528+ Effect.gen(function* () {529+ const file = decodePath(path);530+ const at = revisionOf(ref);531+532+ if (ref === "" || Option.isNone(file)) {533+ return yield* refuse(534+ "INVALID_INPUT",535+ "ref and path must not be empty"536+ );537+ }538+539+ if (Option.isNone(at)) {540+ return null;541+ }542+543+ const bytes = yield* host.readFile(name, at.value, file.value);544+545+ return Option.getOrNull(Option.map(bytes, blobOf));546+ })547+ ),548+ readTree: (hash) =>549+ run(550+ objectId(hash).pipe(551+ Effect.flatMap((tree) => host.readTree(name, tree)),552+ Effect.map((entries) =>553+ Option.getOrNull(Option.map(entries, (each) => each.map(entryOf)))554+ )555+ )556+ ),557+ revokeToken: (tokenOrId) =>558+ run(559+ Effect.gen(function* () {560+ if (tokenOrId === "") {561+ return yield* refuse(562+ "INVALID_INPUT",563+ "tokenOrId must not be empty"564+ );565+ }566+567+ const { tokens } = keptOf(name);568+569+ const token = [...tokens.values()].find(570+ ({ id, plaintext }) => id === tokenOrId || plaintext === tokenOrId571+ );572+573+ const revoked = yield* host.revokeToken(name, token?.id ?? tokenOrId);574+575+ if (token !== undefined && revoked) {576+ tokens.set(token.id, { ...token, state: "revoked" });577+ }578+579+ return revoked;580+ })581+ ),582+ [Symbol.dispose]: constVoid,583+ });584+585+ return {586+ create: (name, createOptions) =>587+ run(588+ Effect.gen(function* () {589+ const repoName = yield* named(name, "INVALID_REPO_NAME");590+591+ yield* host.create(repoName);592+593+ return yield* createdOf(594+ keep(repoName, {595+ defaultBranch: createOptions?.setDefaultBranch ?? "main",596+ description: createOptions?.description ?? null,597+ })598+ );599+ })600+ ),601+ delete: (name) =>602+ run(603+ Effect.gen(function* () {604+ const repoName = yield* named(name, "INVALID_REPO_NAME");605+606+ kept.delete(repoName);607+608+ return yield* host.remove(repoName);609+ })610+ ),611+ get: (name) =>612+ run(613+ Effect.gen(function* () {614+ const repoName = yield* named(name, "NOT_FOUND");615+616+ yield* host.remote(repoName);617+618+ return handle(repoName);619+ })620+ ),621+ import: ({ source, target }) =>622+ run(623+ Effect.gen(function* () {624+ const repoName = yield* named(target.name, "INVALID_REPO_NAME");625+626+ const branch = Option.fromNullishOr(source.branch).pipe(627+ Option.flatMap(decodeBranch)628+ );629+630+ yield* host.importFrom(631+ repoName,632+ Option.match(branch, {633+ onNone: () => ({ url: source.url }),634+ onSome: (name) => ({ branch: name, url: source.url }),635+ })636+ );637+638+ return yield* createdOf(639+ keep(repoName, {640+ description: target.opts?.description ?? null,641+ source: source.url,642+ })643+ );644+ })645+ ),646+ list: (listOptions) =>647+ run(648+ Effect.sync(() => {649+ const limit = Math.min(Math.max(listOptions?.limit ?? 50, 1), 200);650+ const from = Number(listOptions?.cursor ?? "0");651+ const all = [...kept.values()];652+653+ const repos = all.slice(from, from + limit).map(summaryOf);654+ const next = from + limit;655+656+ return next < all.length657+ ? { cursor: String(next), repos, total: all.length }658+ : { repos, total: all.length };659+ })660+ ),661+ };662+};added:packages/testkit/src/golden.ts+131 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.35+ */36+const lastRewrite = (line: string) => line.split("\r").at(-1) ?? line;37+38+/**39+ * Git's output, the same on every run of the same push: without the eight40+ * spaces git pads side-band lines with when stderr is not a terminal (and any41+ * other trailing space), with temporary folders as `<tmp>`, full object ids as42+ * `<sha>`, a local server's address as `<host>`, and each line rewritten with43+ * carriage returns as a terminal leaves it.44+ */45+export const normaliseGitOutput = (text: string): string =>46+ text47+ .split(/\r?\n/u)48+ .map((line) =>49+ lastRewrite(line)50+ .replaceAll(TEMP_PATH, "<tmp>")51+ .replaceAll(LOCAL_SERVER, "<host>")52+ .replaceAll(OBJECT_ID, "<sha>")53+ .trimEnd()54+ )55+ .join("\n");56+57+// Letters on either side make it another word, not the product's name:58+// the rule `brand:check` applies.59+const NAME = new RegExp(`(?<![a-z])${Brand.slug}(?![a-z])`, "giu");60+61+/**62+ * The text as a golden file holds it: the product's config folder as63+ * `<configDir>` and every other spelling of its name as `<brand>`, so no64+ * golden file names the product (`brand:check`) and a renamed brand still65+ * matches.66+ */67+const unbranded = (text: string) =>68+ text.replaceAll(Brand.configDir, "<configDir>").replaceAll(NAME, "<brand>");69+70+/** The lines that differ, as `- golden` and `+ actual`, in order. */71+const difference = (golden: string, actual: string) => {72+ const was = golden.split("\n");73+ const now = actual.split("\n");74+75+ return Array.from({ length: Math.max(was.length, now.length) }, (_, at) =>76+ was[at] === now[at]77+ ? []78+ : [79+ ...(was[at] === undefined ? [] : [`- ${was[at]}`]),80+ ...(now[at] === undefined ? [] : [`+ ${now[at]}`]),81+ ]82+ )83+ .flat()84+ .join("\n");85+};86+87+/**88+ * Compares `text` with `test/golden/<name>.txt`, and fails the test where89+ * they differ. With `UPDATE_GOLDEN=1` it writes the file instead, folders90+ * and all: run the package's tests that way once, then read the diff.91+ */92+export const expectGolden = (93+ name: string,94+ text: string95+): Effect.Effect<void, never, FileSystem.FileSystem> =>96+ Effect.gen(function* () {97+ const fs = yield* FileSystem.FileSystem;98+ const dir = yield* GoldenDir;99+ const file = `${dir}/${name}.txt`;100+ const actual = unbranded(text);101+102+ const update = yield* Config.Boolean("UPDATE_GOLDEN").pipe(103+ Config.withDefault(false)104+ );105+106+ if (update) {107+ yield* fs.makeDirectory(file.slice(0, file.lastIndexOf("/")), {108+ recursive: true,109+ });110+111+ return yield* fs.writeFileString(file, actual);112+ }113+114+ if (!(yield* fs.exists(file))) {115+ return yield* Effect.die(116+ new Error(117+ `no golden file ${file} yet: run this package's tests with UPDATE_GOLDEN=1 to write it`118+ )119+ );120+ }121+122+ const golden = yield* fs.readFileString(file);123+124+ return yield* golden === actual125+ ? Effect.void126+ : Effect.die(127+ new Error(128+ `${file} differs from the output (rerun with UPDATE_GOLDEN=1 to accept it):\n${difference(golden, actual)}`129+ )130+ );131+ }).pipe(Effect.orDie);added:packages/testkit/src/scenarios.ts+442 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 kind defaults to `fix`, the check to a `RedThenGreen` file in the319+ * territory, the want to a sentence naming both.320+ */321+export const withAsk =322+ (ask: AskOptions) =>323+ (scenario: Scenario): Scenario =>324+ openAsk(scenario, ask, territoryOf(ask.territory), true);325+326+/** Adds an ask kind, in place of one with the same name. */327+export const withKind =328+ (kind: AskKindEncoded) =>329+ (scenario: Scenario): Scenario => {330+ const added = decodeKind(kind);331+ const { kinds } = scenario.policy;332+333+ return withPolicy(scenario, {334+ ...scenario.policy,335+ kinds: kinds.some(({ name }) => name === added.name)336+ ? kinds.map((each) => (each.name === added.name ? added : each))337+ : [...kinds, added],338+ });339+ };340+341+/** Adds the vouch file's lines: `handles` vouched for, then `denounced`. */342+export const withVouches =343+ (handles: readonly string[], denounced: readonly string[] = []) =>344+ (scenario: Scenario): Scenario =>345+ withPolicy(scenario, {346+ ...scenario.policy,347+ vouches: [348+ ...scenario.policy.vouches,349+ ...handles.map((handle) => ({350+ denounced: false,351+ handle: Handle.make(handle),352+ })),353+ ...denounced.map((handle) => ({354+ denounced: true,355+ handle: Handle.make(handle),356+ })),357+ ],358+ });359+360+/** `legacyFetch` → `legacy-fetch`, `http.get` → `http-get`: a name an ask id can carry. */361+const words = (symbol: string) =>362+ symbol363+ .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower>-$<upper>")364+ .toLowerCase()365+ .replaceAll(/[^a-z0-9]+/gu, "-")366+ .replaceAll(/^-|-$/gu, "");367+368+const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);369+370+/** The six packages together: where a family's parent and delete child reach. */371+const allSix = decodeTerritory({372+ module: ".",373+ paths: Arr.map(packages, (folder) => `${folder}/**`),374+});375+376+/**377+ * "Six agents claim six children" (CAA §2.F): the project `burrow` with a378+ * migrate ask `drop-<symbol>` over `packages/p1` … `packages/p6`, a child per379+ * package (`drop-<symbol>-p1` …), each moving the symbol in its own package,380+ * and a delete child (`drop-<symbol>-delete`) blocked by all six. The six381+ * packages are the project's modules.382+ */383+export const sixChildren = (384+ options: { readonly symbol?: string; readonly to?: string } = {}385+): Scenario => {386+ const symbol = options.symbol ?? "legacyFetch";387+ const to = options.to ?? "http.get";388+ const parent = `drop-${words(symbol)}`;389+ const count = `node scripts/count-callers.mjs ${symbol} --json`;390+391+ const check = CheckSpec.cases.Migrate.make({392+ count: Command.make(count),393+ from: SymbolName.make(symbol),394+ to: SymbolName.make(to),395+ });396+397+ const children = packages.map((folder) => ({398+ check,399+ id: `${parent}-${folder.split("/").at(-1) ?? folder}`,400+ kind: "migrate",401+ parent,402+ territory: folder,403+ want: `${folder}: move every use of ${symbol} to ${to}`,404+ }));405+406+ const opened = openAsk(407+ aProject({ name: "burrow" }),408+ {409+ check,410+ id: parent,411+ kind: "migrate",412+ territory: ".",413+ want: `Move every use of ${symbol} to ${to}, then delete ${symbol}`,414+ },415+ allSix,416+ false417+ );418+419+ let split = opened;420+421+ for (const child of children) {422+ split = withAsk(child)(split);423+ }424+425+ return openAsk(426+ split,427+ {428+ blockedBy: children.map(({ id }) => id),429+ check: CheckSpec.cases.SymbolAbsent.make({430+ count: Command.make(count),431+ symbol: SymbolName.make(symbol),432+ }),433+ id: `${parent}-delete`,434+ kind: "migrate",435+ parent,436+ territory: ".",437+ want: `Delete ${symbol}: nothing uses it any more`,438+ },439+ allSix,440+ false441+ );442+};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+432 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+/**41+ * A repo host as small as the fake needs: every repo holds one commit on42+ * `main`, whose tree has `a.txt` ("hello") and a folder `src`.43+ */44+const tinyHost = (): HostLike => {45+ const repos = new Set<RepoName>();46+ let minted = 0;47+48+ const known = (name: RepoName): Effect.Effect<void, RepoNotFound> =>49+ repos.has(name) ? Effect.void : Effect.fail(new RepoNotFound({ name }));50+51+ const make = (name: RepoName) =>52+ repos.has(name)53+ ? Effect.fail(new RepoExists({ name }))54+ : Effect.sync(() => {55+ repos.add(name);56+57+ return { name, remote: `memory://${name}.git` };58+ });59+60+ return {61+ create: make,62+ fork: (base, name) => known(base).pipe(Effect.andThen(make(name))),63+ importFrom: (name, source) =>64+ Effect.fail(65+ new ImportRefused({ name, reason: `no repo at ${source.url}` })66+ ),67+ log: (name, at) =>68+ known(name).pipe(69+ Effect.as(70+ Match.valueTags(at, {71+ Branch: ({ name: branch }) => branch === "main",72+ Commit: ({ sha }) => sha === commit,73+ })74+ ? [75+ {76+ author: answerer,77+ committer: answerer,78+ message: "first",79+ parents: [],80+ sha: commit,81+ tree,82+ },83+ ]84+ : []85+ )86+ ),87+ mintToken: (name, scope, ttl) =>88+ known(name).pipe(89+ Effect.map(() => {90+ minted += 1;91+92+ return {93+ expiresAt: DateTime.addDuration(94+ DateTime.makeUnsafe("2026-10-07T12:00:00Z"),95+ ttl96+ ),97+ id: `token-${minted}`,98+ scope,99+ secret: Redacted.make(`secret-${minted}`),100+ };101+ })102+ ),103+ readBlob: (name, sha) =>104+ known(name).pipe(105+ Effect.as(sha === blob ? Option.some(hello) : Option.none())106+ ),107+ readCommit: (name, sha) =>108+ known(name).pipe(109+ Effect.as(110+ sha === commit111+ ? Option.some({112+ author: answerer,113+ committer: answerer,114+ message: "first",115+ parents: [],116+ sha: commit,117+ tree,118+ })119+ : Option.none()120+ )121+ ),122+ readFile: (name, at, path) =>123+ known(name).pipe(124+ Effect.as(125+ Match.valueTags(at, {126+ Branch: ({ name: branch }) => branch === "main",127+ Commit: ({ sha }) => sha === commit,128+ }) && path === "a.txt"129+ ? Option.some(hello)130+ : Option.none()131+ )132+ ),133+ readTree: (name, sha) =>134+ known(name).pipe(135+ Effect.as(136+ sha === tree137+ ? Option.some([138+ {139+ mode: "100644" as const,140+ name: "a.txt",141+ sha: blob,142+ type: "blob" as const,143+ },144+ {145+ mode: "040000" as const,146+ name: "src",147+ sha: subtree,148+ type: "tree" as const,149+ },150+ ])151+ : Option.none()152+ )153+ ),154+ remote: (name) => known(name).pipe(Effect.as(`memory://${name}.git`)),155+ remove: (name) => Effect.sync(() => repos.delete(name)),156+ revokeToken: (name) => known(name).pipe(Effect.as(true)),157+ };158+};159+160+/** Awaits one of the binding's promises. */161+const call = <A>(run: () => Promise<A>) =>162+ Effect.tryPromise({163+ catch: (error) =>164+ new Thrown({165+ error: error instanceof Error ? error : new Error(String(error)),166+ }),167+ try: run,168+ });169+170+/** What one of the binding's promises threw, or an error saying it resolved. */171+const thrown = <A>(run: () => Promise<A>) =>172+ call(run).pipe(173+ Effect.match({174+ onFailure: ({ error }) => error,175+ onSuccess: (value) => new Error(`resolved with ${String(value)}`),176+ })177+ );178+179+const text = (bytes: Blob | null) =>180+ bytes === null ? Effect.succeed(null) : call(() => bytes.text());181+182+/** An error as a plain record: its name and message, and its code and number if it has them. */183+const described = (error: Error) => ({184+ code: "code" in error ? error.code : undefined,185+ isError: error instanceof Error,186+ message: error.message,187+ name: error.name,188+ numericCode: "numericCode" in error ? error.numericCode : undefined,189+});190+191+/** A binding over a fresh tiny host, with `datekit` made, and the repo `get` hands back. */192+const withDatekit = (193+ options: Parameters<typeof fakeArtifactsBinding>[1] = {}194+) =>195+ Effect.gen(function* () {196+ const binding = fakeArtifactsBinding(tinyHost(), options);197+ const created = yield* call(() => binding.create("datekit"));198+ const repo = yield* call(() => binding.get("datekit"));199+200+ return { binding, created, repo };201+ });202+203+describe("the fake Artifacts binding", () => {204+ it.effect("creates a repo with a remote and a write token", () =>205+ Effect.gen(function* () {206+ const { created } = yield* withDatekit();207+208+ expect(created).toMatchObject({209+ defaultBranch: "main",210+ description: null,211+ name: "datekit",212+ remote: "memory://datekit.git",213+ token: "secret-1",214+ });215+ })216+ );217+218+ it.effect("hands back a repo whose reads by object id go to the host", () =>219+ Effect.gen(function* () {220+ const { repo } = yield* withDatekit();221+222+ expect(yield* call(() => repo.readTree(tree))).toStrictEqual([223+ { hash: blob, mode: "100644", name: "a.txt", type: "blob" },224+ { hash: subtree, mode: "40000", name: "src", type: "tree" },225+ ]);226+ expect(yield* text(yield* call(() => repo.readBlob(blob)))).toBe(227+ "hello\n"228+ );229+ expect(yield* call(() => repo.readCommit(commit))).toStrictEqual({230+ author: answerer,231+ authoredAt: 0,232+ committedAt: 0,233+ committer: answerer,234+ hash: commit,235+ message: "first",236+ parents: [],237+ treeHash: tree,238+ });239+ })240+ );241+242+ it.effect("reads null for an object the host doesn't have", () =>243+ Effect.gen(function* () {244+ const { repo } = yield* withDatekit();245+246+ expect(yield* call(() => repo.readTree(subtree))).toBeNull();247+ expect(yield* call(() => repo.readBlob(tree))).toBeNull();248+ expect(yield* call(() => repo.readCommit(blob))).toBeNull();249+ })250+ );251+252+ it.effect(253+ "throws NOT_FOUND, as an ArtifactsError, for a repo it doesn't have",254+ () =>255+ Effect.gen(function* () {256+ const error = yield* thrown(() =>257+ fakeArtifactsBinding(tinyHost()).get("nobody")258+ );259+260+ expect(described(error)).toStrictEqual({261+ code: "NOT_FOUND",262+ isError: true,263+ message: "Repository not found: nobody",264+ name: "ArtifactsError",265+ numericCode: 0,266+ });267+ })268+ );269+270+ it.effect(271+ "throws plain Errors with no code when codeless, as wrangler dev's remote bindings do (S1 #22)",272+ () =>273+ Effect.gen(function* () {274+ const { binding } = yield* withDatekit({ codeless: true });275+ const missing = yield* thrown(() => binding.get("nobody"));276+ const again = yield* thrown(() => binding.create("datekit"));277+278+ expect(described(missing)).toStrictEqual({279+ code: undefined,280+ isError: true,281+ message: "ArtifactsError: Repository not found: nobody",282+ name: "Error",283+ numericCode: undefined,284+ });285+ expect(described(again)).toMatchObject({286+ code: undefined,287+ message: "ArtifactsError: repo already exists: datekit",288+ });289+ })290+ );291+292+ it.effect(293+ "answers a fork under load with a 500 after making it, then a 409 on the retry (S7)",294+ () =>295+ Effect.gen(function* () {296+ const { binding, repo } = yield* withDatekit({ forkFailures: 1 });297+ const first = yield* thrown(() => repo.fork("datekit--fix--bob"));298+ const made = yield* call(() => binding.get("datekit--fix--bob"));299+ const retry = yield* thrown(() => repo.fork("datekit--fix--bob"));300+ const next = yield* call(() => repo.fork("datekit--fix--carol"));301+302+ expect(described(first)).toStrictEqual({303+ code: "INTERNAL_ERROR",304+ isError: true,305+ message: "An internal error occurred.",306+ name: "ArtifactsError",307+ numericCode: 10_400,308+ });309+ // The fork was made all the same.310+ expect(yield* text(yield* call(() => made.readBlob(blob)))).toBe(311+ "hello\n"312+ );313+ expect(described(retry)).toStrictEqual({314+ code: "ALREADY_EXISTS",315+ isError: true,316+ message: "repo already exists: datekit--fix--bob",317+ name: "ArtifactsError",318+ numericCode: 10_201,319+ });320+ expect(next).toMatchObject({ name: "datekit--fix--carol" });321+ })322+ );323+324+ it.effect(325+ "resolves only short branch names and commit ids in reads by ref (S1 #20)",326+ () =>327+ Effect.gen(function* () {328+ const { repo } = yield* withDatekit();329+330+ const read = (ref: string) =>331+ call(() => repo.readFile({ path: "a.txt", ref })).pipe(332+ Effect.flatMap(text)333+ );334+335+ expect(yield* read("refs/heads/main")).toBeNull();336+ expect(yield* read("asked/landed")).toBeNull();337+ expect([yield* read("main"), yield* read(commit)]).toStrictEqual([338+ "hello\n",339+ "hello\n",340+ ]);341+ expect(342+ yield* call(() => repo.log({ ref: "refs/heads/main" }))343+ ).toStrictEqual([]);344+ expect(345+ (yield* call(() => repo.log())).map(({ hash }) => hash)346+ ).toStrictEqual([commit]);347+ })348+ );349+350+ it.effect("refuses a malformed object id, an empty path or a bad name", () =>351+ Effect.gen(function* () {352+ const { binding, repo } = yield* withDatekit();353+354+ const codes = [355+ yield* thrown(() => repo.readTree("HEAD")),356+ yield* thrown(() => repo.readFile({ path: "", ref: "main" })),357+ yield* thrown(() => binding.create("no spaces")),358+ yield* thrown(() => repo.createToken("read", 59)),359+ ].map((error) => described(error).code);360+361+ expect(codes).toStrictEqual([362+ "INVALID_INPUT",363+ "INVALID_INPUT",364+ "INVALID_REPO_NAME",365+ "INVALID_TTL",366+ ]);367+ })368+ );369+370+ it.effect(371+ "serves remotes under a base URL, for a git server the test runs",372+ () =>373+ Effect.gen(function* () {374+ const { created, repo } = yield* withDatekit({375+ remoteBase: "http://127.0.0.1:9000/git",376+ });377+378+ const info = yield* call(() => repo.info());379+380+ expect(created.remote).toBe("http://127.0.0.1:9000/git/datekit.git");381+ expect(info).toMatchObject({382+ defaultBranch: "main",383+ lastPushAt: null,384+ name: "datekit",385+ remote: "http://127.0.0.1:9000/git/datekit.git",386+ source: null,387+ });388+ })389+ );390+391+ it.effect("mints, lists and revokes tokens through the host", () =>392+ Effect.gen(function* () {393+ const { repo } = yield* withDatekit();394+ const token = yield* call(() => repo.createToken("read", 60));395+ const revoked = yield* call(() => repo.revokeToken("secret-2"));396+ const { tokens } = yield* call(() => repo.listTokens());397+398+ expect(token).toStrictEqual({399+ expiresAt: "2026-10-07T12:01:00.000Z",400+ id: "token-2",401+ plaintext: "secret-2",402+ scope: "read",403+ });404+ expect(revoked).toBeTruthy();405+ expect(tokens.map(({ id, state }) => [id, state])).toStrictEqual([406+ ["token-1", "active"],407+ ["token-2", "revoked"],408+ ]);409+ })410+ );411+412+ it.effect("lists and deletes what it made", () =>413+ Effect.gen(function* () {414+ const { binding } = yield* withDatekit();415+416+ yield* call(() => binding.create("burrow"));417+418+ const listed = yield* call(() => binding.list());419+ const deleted = yield* call(() => binding.delete("datekit"));420+ const again = yield* call(() => binding.delete("datekit"));421+ const gone = yield* thrown(() => binding.get("datekit"));422+423+ expect(listed).toMatchObject({ total: 2 });424+ expect(listed.repos.map(({ name }) => name)).toStrictEqual([425+ "datekit",426+ "burrow",427+ ]);428+ expect([deleted, again]).toStrictEqual([true, false]);429+ expect(described(gone).code).toBe("NOT_FOUND");430+ })431+ );432+});added:packages/testkit/test/golden.test.ts+260 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.live(126+ "makes two runs of the same push compare equal, and match their golden file",127+ () =>128+ Effect.gen(function* () {129+ const first = yield* pushOnce;130+ const second = yield* pushOnce;131+132+ expect([first.exitCode, second.exitCode]).toStrictEqual([0, 0]);133+ expect(first.stderr).toContain(" \n");134+ expect(first.stderr).not.toBe(second.stderr);135+ expect(normaliseGitOutput(first.stderr)).toBe(136+ normaliseGitOutput(second.stderr)137+ );138+139+ yield* expectGolden(140+ "push-new-branch",141+ normaliseGitOutput(first.stderr)142+ );143+ }).pipe(Effect.provide(NodeServices.layer)),144+ 20_000145+ );146+});147+148+describe("golden files", () => {149+ it.effect("pass when the text matches the file", () =>150+ Effect.gen(function* () {151+ const fs = yield* FileSystem.FileSystem;152+153+ yield* inTempGoldens("0", (dir) =>154+ Effect.gen(function* () {155+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie);156+ yield* fs157+ .writeFileString(`${dir}/same.txt`, "To <tmp>/remote.git\n")158+ .pipe(Effect.orDie);159+160+ const exit = yield* Effect.exit(161+ expectGolden("same", "To <tmp>/remote.git\n")162+ );163+164+ expect(complaint(exit)).toBe("");165+ })166+ );167+ }).pipe(Effect.provide(NodeServices.layer))168+ );169+170+ it.effect(171+ "fail, naming the file and how to accept the change, when the text differs",172+ () =>173+ Effect.gen(function* () {174+ const fs = yield* FileSystem.FileSystem;175+176+ yield* inTempGoldens("0", (dir) =>177+ Effect.gen(function* () {178+ yield* fs179+ .makeDirectory(dir, { recursive: true })180+ .pipe(Effect.orDie);181+ yield* fs182+ .writeFileString(`${dir}/changed.txt`, "line one\nline two\n")183+ .pipe(Effect.orDie);184+185+ const exit = yield* Effect.exit(186+ expectGolden("changed", "line one\nline 2\n")187+ );188+189+ expect(complaint(exit)).toContain(`${dir}/changed.txt`);190+ expect(complaint(exit)).toContain("UPDATE_GOLDEN=1");191+ expect(complaint(exit)).toContain("- line two");192+ expect(complaint(exit)).toContain("+ line 2");193+ })194+ );195+ }).pipe(Effect.provide(NodeServices.layer))196+ );197+198+ it.effect("fail when there is no file yet", () =>199+ inTempGoldens("0", () =>200+ Effect.gen(function* () {201+ const exit = yield* Effect.exit(expectGolden("absent", "text\n"));202+203+ expect(complaint(exit)).toContain("absent.txt");204+ expect(complaint(exit)).toContain("UPDATE_GOLDEN=1");205+ })206+ ).pipe(Effect.provide(NodeServices.layer))207+ );208+209+ it.effect("are written, folder and all, under UPDATE_GOLDEN=1", () =>210+ Effect.gen(function* () {211+ const fs = yield* FileSystem.FileSystem;212+213+ yield* inTempGoldens("1", (dir) =>214+ Effect.gen(function* () {215+ yield* fs.makeDirectory(dir, { recursive: true }).pipe(Effect.orDie);216+ yield* fs217+ .writeFileString(`${dir}/rewritten.txt`, "old\n")218+ .pipe(Effect.orDie);219+220+ yield* expectGolden("rewritten", "new\n");221+ yield* expectGolden("nested/fresh", "fresh\n");222+223+ expect(yield* fs.exists(`${dir}/nested/fresh.txt`)).toBeTruthy();224+ expect(225+ yield* fs.readFileString(`${dir}/rewritten.txt`).pipe(Effect.orDie)226+ ).toBe("new\n");227+ expect(228+ yield* fs229+ .readFileString(`${dir}/nested/fresh.txt`)230+ .pipe(Effect.orDie)231+ ).toBe("fresh\n");232+ })233+ );234+ }).pipe(Effect.provide(NodeServices.layer))235+ );236+237+ it.effect(238+ "never spell the product's name: its config folder and name are written as placeholders",239+ () =>240+ Effect.gen(function* () {241+ const fs = yield* FileSystem.FileSystem;242+243+ yield* inTempGoldens("1", (dir) =>244+ Effect.gen(function* () {245+ yield* expectGolden(246+ "brand",247+ `wrote ${Brand.configDir}/project.ts; next: ${Brand.cli} status, then ${Brand.name} lands it\n`248+ );249+250+ expect(yield* fs.exists(`${dir}/brand.txt`)).toBeTruthy();251+ expect(252+ yield* fs.readFileString(`${dir}/brand.txt`).pipe(Effect.orDie)253+ ).toBe(254+ "wrote <configDir>/project.ts; next: <brand> status, then <brand> lands it\n"255+ );256+ })257+ );258+ }).pipe(Effect.provide(NodeServices.layer))259+ );260+});added:packages/testkit/test/scenarios.test.ts+323 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 { 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("refuses an ask the domain refuses, such as one named after a reserved word", () => {163+ expect(() =>164+ aProject().pipe(withAsk({ id: "me", territory: "packages/parser" }))165+ ).toThrow("reserved");166+ });167+168+ it("adds a kind, replacing one of the same name", () => {169+ const scenario = aProject().pipe(170+ withKind(lintKind),171+ withKind({ ...lintKind, race: 2 })172+ );173+174+ expect(scenario.policy.kinds.map(({ name }) => name)).toStrictEqual([175+ "fix",176+ "migrate",177+ "lintToZero",178+ ]);179+ expect(scenario.policy.kinds[2]).toStrictEqual({ ...lintKind, race: 2 });180+ });181+182+ it("records vouches and denouncements as the vouch file's lines", () => {183+ const scenario = aProject().pipe(184+ withVouches(["bob", "carol"], ["mallory"])185+ );186+187+ expect(scenario.policy.vouches).toStrictEqual([188+ { denounced: false, handle: "bob" },189+ { denounced: false, handle: "carol" },190+ { denounced: true, handle: "mallory" },191+ ]);192+ expect(isPolicy(scenario.policy)).toBeTruthy();193+ });194+195+ it("builds the same value every time", () => {196+ expect(Equal.equals(parserFix(), parserFix())).toBeTruthy();197+ expect(Equal.equals(sixChildren(), sixChildren())).toBeTruthy();198+ expect(Equal.equals(parserFix(), aProject({ name: "burrow" }))).toBeFalsy();199+ });200+});201+202+describe("six children of a migrate ask", () => {203+ it("is a parent, six children and a delete child, each a valid ask", () => {204+ const { policy } = sixChildren();205+206+ expect(policy.asks.map(({ id }) => id)).toStrictEqual([207+ "drop-legacy-fetch",208+ ...children,209+ "drop-legacy-fetch-delete",210+ ]);211+ expect(policy.asks.every((ask) => isAsk(ask))).toBeTruthy();212+ expect(isPolicy(policy)).toBeTruthy();213+ });214+215+ it("has a parent migrating the symbol across the six packages", () => {216+ const [parent] = sixChildren().policy.asks;217+218+ expect(parent).toMatchObject({219+ check: CheckSpec.cases.Migrate.make({220+ count: Command.make(221+ "node scripts/count-callers.mjs legacyFetch --json"222+ ),223+ from: SymbolName.make("legacyFetch"),224+ to: SymbolName.make("http.get"),225+ }),226+ kind: "migrate",227+ territory: { paths: six.map((n) => `packages/p${n}/**`) },228+ });229+ expect(parent?.parent).toBeUndefined();230+ });231+232+ it("splits into six children on disjoint packages, the project's modules", () => {233+ const { policy } = sixChildren();234+ const steps = policy.asks.slice(1, 7);235+236+ expect(237+ steps.map(({ blockedBy, id, parent, territory }) => ({238+ blockedBy,239+ id,240+ parent,241+ territory,242+ }))243+ ).toStrictEqual(244+ six.map((n) => ({245+ blockedBy: [],246+ id: `drop-legacy-fetch-p${n}`,247+ parent: "drop-legacy-fetch",248+ territory: { module: `p${n}`, paths: [`packages/p${n}/**`] },249+ }))250+ );251+ expect(252+ steps.every(({ check }) => CheckSpec.guards.Migrate(check))253+ ).toBeTruthy();254+ expect(policy.modules.map(({ module }) => module)).toStrictEqual(255+ six.map((n) => `p${n}`)256+ );257+ });258+259+ it("ends with a delete child blocked by all six", () => {260+ const last = sixChildren().policy.asks.at(-1);261+262+ expect(last).toMatchObject({263+ blockedBy: children,264+ check: CheckSpec.cases.SymbolAbsent.make({265+ count: Command.make(266+ "node scripts/count-callers.mjs legacyFetch --json"267+ ),268+ symbol: SymbolName.make("legacyFetch"),269+ }),270+ parent: "drop-legacy-fetch",271+ });272+ });273+274+ it("names the family after the symbol it moves", () => {275+ const { policy } = sixChildren({ symbol: "oldClock", to: "clock.now" });276+277+ expect(policy.asks.map(({ id }) => id)).toStrictEqual([278+ "drop-old-clock",279+ ...six.map((n) => `drop-old-clock-p${n}`),280+ "drop-old-clock-delete",281+ ]);282+ expect(policy.asks[0]?.check).toMatchObject({283+ from: "oldClock",284+ to: "clock.now",285+ });286+ });287+});288+289+describe("deterministic ids", () => {290+ it("makes a commit id from a seed with FNV-1a, the same every run", () => {291+ // Worked out by a separate FNV-1a implementation over `0:main` … `4:main`.292+ expect(sha("main")).toBe("72245cbe78d5b41b2cadf2502b38c3a5d6578b1a");293+ expect(Schema.is(CommitSha)(sha("main"))).toBeTruthy();294+ expect(sha("main")).not.toBe(sha("answer"));295+ expect(aProject().landed).toBe("6a1d765d8fd2f48cf995fb978771958e356e2bb1");296+ });297+298+ it("mints request, proposal and decision ids from counters", () => {299+ const next = ids();300+301+ expect([next.request(), next.request()]).toStrictEqual([302+ "req-000001",303+ "req-000002",304+ ]);305+ expect([next.proposal(), next.decision()]).toStrictEqual([306+ "prop-000001",307+ "dec-000001",308+ ]);309+ expect(ids().request()).toBe("req-000001");310+ });311+312+ it("mints ids the domain accepts, without reading randomness", () => {313+ const random = vi.spyOn(crypto, "randomUUID");314+ const next = ids();315+316+ expect(Schema.is(RequestId)(next.request())).toBeTruthy();317+ expect(Schema.is(ProposalId)(next.proposal())).toBeTruthy();318+ expect(Schema.is(DecisionId)(next.decision())).toBeTruthy();319+ expect(random).not.toHaveBeenCalled();320+321+ random.mockRestore();322+ });323+});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"); });});