Skip to content
Myr

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).

authored by oscabriel · committed by oscabriel · parent 3d5870c · Browse files · 10 files+2324 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+2324 added−10 removed

  • tests:+1064 added−10 removed
  • other:+1260 added−0 removed

10 files+2324 added−10 removed

added:packages/testkit/src/clock.ts+25 added
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 */22import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";23import {24 Data,25 DateTime,26 Duration,27 Effect,28 Match,29 Option,30 Redacted,31 Schema,32} from "effect";33import { constVoid } from "effect/Function";3435import { defaultNow } from "./clock.ts";3637/** A git object id, branded as `@repo/artifacts`' `ObjectId` is. */38export const ObjectId = Schema.String.pipe(39 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),40 Schema.brand("ObjectId")41);4243export type ObjectId = typeof ObjectId.Type;4445/** A short branch name, branded as `@repo/artifacts`' `BranchName` is. */46export 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);5455export type BranchName = typeof BranchName.Type;5657/** Where a read starts, as `@repo/artifacts`' `Revision` has it. */58export type Revision = Data.TaggedEnum<{59 Branch: { readonly name: BranchName };60 Commit: { readonly sha: CommitSha };61}>;6263export const Revision = Data.taggedEnum<Revision>();6465/** What a host fails with: `RepoHost`'s errors, by shape. */66export 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 };7677interface Person {78 readonly email: string;79 readonly name: string;80}8182interface 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}9091interface HostTreeEntry {92 readonly mode: "100644" | "100755" | "120000" | "040000" | "160000";93 readonly name: string;94 readonly sha: string;95 readonly type: "blob" | "tree" | "commit";96}9798interface HostCreated {99 readonly name: string;100 readonly remote: string;101}102103/**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 */108export 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}160161export 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}169170/** A refusal the binding throws, before it becomes the thrown error. */171class Refused extends Data.TaggedError("Refused")<{172 readonly code: ArtifactsError["code"];173 readonly reason: string;174}> {}175176/**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 */181const numericCodes = {182 ALREADY_EXISTS: 10_201,183 INTERNAL_ERROR: 10_400,184} as const;185186const 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 );192193/** A host's error as the binding words it (S1 #22, S7 #2). */194const 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 });218219/** The repos the fake made, with what `info()` and `list()` report. */220interface 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}232233// Artifacts stamps repos with the time they were made; the fake with the234// scenarios' fixed instant, so two runs give the same values.235const stamped = DateTime.formatIso(defaultNow);236237const isObjectId = Schema.is(ObjectId);238239const decodeName = Schema.decodeUnknownOption(RepoName);240241const decodeBranch = Schema.decodeUnknownOption(BranchName);242243const decodePath = Schema.decodeUnknownOption(RepoPath);244245/**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 */249const 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 }));253254// Artifacts gives canonical modes: a folder is `40000`, not `040000`.255const 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 );263264const entryOf = (entry: HostTreeEntry): ArtifactsTreeEntry => ({265 hash: entry.sha,266 mode: entry.mode.replace(/^0/u, ""),267 name: entry.name,268 type: typeOf(entry),269});270271// `RepoHost`'s commits carry no times, so the fake reports the epoch.272const 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});282283const refuse = (code: ArtifactsError["code"], reason: string) =>284 Effect.fail(new Refused({ code, reason }));285286const named = (name: string, code: ArtifactsError["code"]) =>287 Option.match(decodeName(name), {288 onNone: () => refuse(code, `Invalid repository name: ${name}`),289 onSome: Effect.succeed,290 });291292const objectId = (hash: string): Effect.Effect<ObjectId, Refused> =>293 isObjectId(hash)294 ? Effect.succeed(hash)295 : refuse("INVALID_INPUT", `Invalid object id: ${hash}`);296297const blobOf = (bytes: Uint8Array) =>298 new Blob([bytes], { type: "application/octet-stream" });299300/** An Artifacts binding over `host`, with the real one's surprises (see the module's doc). */301export 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;308309 /** 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 });318319 /** 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 );341342 const remoteOf = (name: RepoName) =>343 options.remoteBase === undefined344 ? host.remote(name)345 : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));346347 const keep = (348 name: RepoName,349 fields: Partial<Pick<Kept, "description" | "defaultBranch" | "source">>350 ) => {351 made += 1;352353 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 };362363 kept.set(name, repo);364365 return repo;366 };367368 /** What `info()` shows for a repo the fake did not make itself. */369 const keptOf = (name: RepoName) => kept.get(name) ?? keep(name, {});370371 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);376377 keptOf(name).tokens.set(token.id, {378 createdAt: stamped,379 expiresAt,380 id: token.id,381 plaintext,382 scope,383 state: "active",384 });385386 return { expiresAt, id: token.id, plaintext, scope: token.scope };387 })388 );389390 /** 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);395396 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 });405406 /** 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 });419420 const info = (repo: Kept) =>421 remoteOf(repo.name).pipe(422 Effect.map((remote): ArtifactsRepoInfo => ({423 ...summaryOf(repo),424 remote,425 }))426 );427428 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");446447 yield* host.fork(name, fork);448449 const repo = keep(fork, {450 description: forkOptions?.description ?? null,451 source: `artifacts:fake/${name}`,452 });453454 if (forkFailures > 0) {455 forkFailures -= 1;456457 return yield* refuse(458 "INTERNAL_ERROR",459 "An internal error occurred."460 );461 }462463 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 );480481 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;491492 const at =493 ref === "HEAD"494 ? Option.some(495 Revision.Branch({496 name: BranchName.make(keptOf(name).defaultBranch),497 })498 )499 : revisionOf(ref);500501 if (Option.isNone(at)) {502 return [];503 }504505 const commits = yield* host.log(name, at.value, offset + limit);506507 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);531532 if (ref === "" || Option.isNone(file)) {533 return yield* refuse(534 "INVALID_INPUT",535 "ref and path must not be empty"536 );537 }538539 if (Option.isNone(at)) {540 return null;541 }542543 const bytes = yield* host.readFile(name, at.value, file.value);544545 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 }566567 const { tokens } = keptOf(name);568569 const token = [...tokens.values()].find(570 ({ id, plaintext }) => id === tokenOrId || plaintext === tokenOrId571 );572573 const revoked = yield* host.revokeToken(name, token?.id ?? tokenOrId);574575 if (token !== undefined && revoked) {576 tokens.set(token.id, { ...token, state: "revoked" });577 }578579 return revoked;580 })581 ),582 [Symbol.dispose]: constVoid,583 });584585 return {586 create: (name, createOptions) =>587 run(588 Effect.gen(function* () {589 const repoName = yield* named(name, "INVALID_REPO_NAME");590591 yield* host.create(repoName);592593 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");605606 kept.delete(repoName);607608 return yield* host.remove(repoName);609 })610 ),611 get: (name) =>612 run(613 Effect.gen(function* () {614 const repoName = yield* named(name, "NOT_FOUND");615616 yield* host.remote(repoName);617618 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");625626 const branch = Option.fromNullishOr(source.branch).pipe(627 Option.flatMap(decodeBranch)628 );629630 yield* host.importFrom(631 repoName,632 Option.match(branch, {633 onNone: () => ({ url: source.url }),634 onSome: (name) => ({ branch: name, url: source.url }),635 })636 );637638 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()];652653 const repos = all.slice(from, from + limit).map(summaryOf);654 const next = from + limit;655656 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 */8import { Brand } from "@repo/brand";9import { Config, Context, Effect, FileSystem } from "effect";1011/**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 */16export const GoldenDir = Context.Reference<string>("testkit/GoldenDir", {17 defaultValue: () => "test/golden",18});1920// 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`.23const TEMP_PATH =24 /(?<![\w.-])(?:\/private)?(?:\/var\/folders\/[^\s/'"]+\/[^\s/'"]+\/T|\/var\/tmp|\/tmp)\/[^\s/'"]+/gu;2526// A full SHA-1 object id, and nothing longer: a SHA-256 stays as it is.27const OBJECT_ID = /(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])/gu;2829// A server a test started on this machine, whose port changes every run.30const LOCAL_SERVER = /\b(?:127\.0\.0\.1|localhost):\d+/gu;3132/**33 * What a terminal shows of one line git rewrote with carriage returns (a34 * progress meter): the last version of it.35 */36const lastRewrite = (line: string) => line.split("\r").at(-1) ?? line;3738/**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 */45export 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");5657// Letters on either side make it another word, not the product's name:58// the rule `brand:check` applies.59const NAME = new RegExp(`(?<![a-z])${Brand.slug}(?![a-z])`, "giu");6061/**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 */67const unbranded = (text: string) =>68 text.replaceAll(Brand.configDir, "<configDir>").replaceAll(NAME, "<brand>");6970/** The lines that differ, as `- golden` and `+ actual`, in order. */71const difference = (golden: string, actual: string) => {72 const was = golden.split("\n");73 const now = actual.split("\n");7475 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};8687/**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 */92export 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);101102 const update = yield* Config.Boolean("UPDATE_GOLDEN").pipe(103 Config.withDefault(false)104 );105106 if (update) {107 yield* fs.makeDirectory(file.slice(0, file.lastIndexOf("/")), {108 recursive: true,109 });110111 return yield* fs.writeFileString(file, actual);112 }113114 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 }121122 const golden = yield* fs.readFileString(file);123124 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 */15import { Brand } from "@repo/brand";16import { Ask } from "@repo/protocol/domain/ask";17import { CheckSpec } from "@repo/protocol/domain/check";18import { Command, SymbolName } from "@repo/protocol/domain/common";19import { AskKind } from "@repo/protocol/domain/kind";20import { Policy } from "@repo/protocol/domain/policy";21import { Territory } from "@repo/protocol/domain/territory";22import {23 CommitSha,24 DecisionId,25 Handle,26 LandedSha,27 ProjectName,28 ProposalId,29 RepoPath,30 RequestId,31} from "@repo/protocol/ids";32import { Array as Arr, DateTime, Pipeable, Schema } from "effect";33import type { Types } from "effect";3435import { defaultNow } from "./clock.ts";3637/** An ask kind as a test writes it, before decoding. */38export type AskKindEncoded = typeof AskKind.Encoded;3940/** A project at one landed commit, with the people a test acts as. */41export 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}5253type ScenarioFields = Omit<Scenario, "pipe">;5455// A class only for `pipe`: its fields are its own, so `Equal.equals` compares56// two scenarios by what they hold.57class 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;6465 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}7576const withPolicy = (scenario: Scenario, policy: Policy): Scenario =>77 new Built({ ...scenario, policy });7879const WORD = 2 ** 32;8081/**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 */85const xorLowByte = (word: number, byte: number) => {86 const low = word % 256;87 let mixed = 0;8889 for (let place = 1; place < 256; place *= 2) {90 const ours = Math.floor(low / place) % 2;91 const theirs = Math.floor(byte / place) % 2;9293 mixed += ours === theirs ? 0 : place;94 }9596 return word - low + mixed;97};9899/** FNV-1a (32-bit) over the UTF-8 bytes of `text`, as eight hex digits. */100const fnv1a = (text: string) => {101 let hash = 0x81_1c_9d_c5;102103 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 }107108 return hash.toString(16).padStart(8, "0");109};110111/**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 */115export const sha = (seed: string): CommitSha =>116 CommitSha.make(117 [0, 1, 2, 3, 4].map((round) => fnv1a(`${round}:${seed}`)).join("")118 );119120/** `prefix-000001`, `prefix-000002`, …: one counter per call of `ids()`. */121const counter = (prefix: string) => {122 let next = 0;123124 return () => {125 next += 1;126127 return `${prefix}-${String(next).padStart(6, "0")}`;128 };129};130131/**132 * Fresh counters for the ids a project mints: `req-000001`, `prop-000001`,133 * `dec-000001`. Each call starts again at 1.134 */135export const ids = () => {136 const request = counter("req");137 const proposal = counter("prop");138 const decision = counter("dec");139140 return {141 decision: () => DecisionId.make(decision()),142 proposal: () => ProposalId.make(proposal()),143 request: () => RequestId.make(request()),144 };145};146147const 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};157158const 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};168169const decodePolicy = Schema.decodeSync(Policy);170171const decodeAsk = Schema.decodeSync(Ask);172173const decodeKind = Schema.decodeSync(AskKind);174175const decodeTerritory = Schema.decodeSync(Territory);176177const encodeTerritory = Schema.encodeSync(Territory);178179const encodeCheck = Schema.encodeSync(CheckSpec);180181/**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 */186export 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`));198199 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 });225226 const names = [...deciders, ...(options.people ?? [])];227228 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};237238/** `packages/parser` → its module `parser` and its paths `packages/parser/**`; `.` → the whole repo. */239const territoryOf = (folder: string) =>240 decodeTerritory(241 folder === "."242 ? { module: ".", paths: ["**"] }243 : {244 module: folder.split("/").at(-1) ?? folder,245 paths: [`${folder}/**`],246 }247 );248249/** An ask as `withAsk` takes it. */250interface 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}262263/**264 * Opens `ask` over `territory` in the scenario, and records the territory as265 * a module when `module` says it is one.266 */267const openAsk = (268 scenario: Scenario,269 ask: AskOptions,270 territory: Territory,271 module: boolean272): Scenario => {273 const tests = ask.territory === "." ? "test" : `${ask.territory}/test`;274275 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 };296297 if (ask.parent !== undefined) {298 encoded.parent = ask.parent;299 }300301 if (ask.reserve !== undefined) {302 encoded.reserve = ask.reserve;303 }304305 const { modules } = scenario.policy;306 const known = modules.some((each) => each.module === territory.module);307308 return withPolicy(scenario, {309 ...scenario.policy,310 asks: [...scenario.policy.asks, decodeAsk(encoded)],311 modules: module && !known ? [...modules, territory] : modules,312 });313};314315/**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 */321export const withAsk =322 (ask: AskOptions) =>323 (scenario: Scenario): Scenario =>324 openAsk(scenario, ask, territoryOf(ask.territory), true);325326/** Adds an ask kind, in place of one with the same name. */327export const withKind =328 (kind: AskKindEncoded) =>329 (scenario: Scenario): Scenario => {330 const added = decodeKind(kind);331 const { kinds } = scenario.policy;332333 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 };340341/** Adds the vouch file's lines: `handles` vouched for, then `denounced`. */342export 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 });359360/** `legacyFetch` → `legacy-fetch`, `http.get` → `http-get`: a name an ask id can carry. */361const 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, "");367368const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);369370/** The six packages together: where a family's parent and delete child reach. */371const allSix = decodeTerritory({372 module: ".",373 paths: Arr.map(packages, (folder) => `${folder}/**`),374});375376/**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 */383export 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`;390391 const check = CheckSpec.cases.Migrate.make({392 count: Command.make(count),393 from: SymbolName.make(symbol),394 to: SymbolName.make(to),395 });396397 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 }));405406 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 );418419 let split = opened;420421 for (const child of children) {422 split = withAsk(child)(split);423 }424425 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
1remote: received <sha> for refs/heads/main2To <tmp>/remote.git3 * [new branch] HEAD -> main
added:packages/testkit/test/clock.test.ts+46 added
added:packages/testkit/test/fake-artifacts-binding.test.ts+432 added
1import { describe, expect, it } from "@effect/vitest";2import type { RepoName } from "@repo/protocol/ids";3import { CommitSha } from "@repo/protocol/ids";4import { Data, DateTime, Effect, Match, Option, Redacted } from "effect";56import {7 fakeArtifactsBinding,8 ObjectId,9} from "../src/fake-artifacts-binding.ts";10import type { HostLike } from "../src/fake-artifacts-binding.ts";1112class RepoNotFound extends Data.TaggedError("RepoNotFound")<{13 readonly name: RepoName;14}> {}1516class RepoExists extends Data.TaggedError("RepoExists")<{17 readonly name: RepoName;18}> {}1920class ImportRefused extends Data.TaggedError("ImportRefused")<{21 readonly name: RepoName;22 readonly reason: string;23}> {}2425/** What a promise of the binding threw. */26class Thrown extends Data.TaggedError("Thrown")<{ readonly error: Error }> {}2728const commit = CommitSha.make("c".repeat(40));2930const tree = ObjectId.make("d".repeat(40));3132const subtree = ObjectId.make("e".repeat(40));3334const blob = ObjectId.make("f".repeat(40));3536const hello = new TextEncoder().encode("hello\n");3738const answerer = { email: "answerer@example.com", name: "Answerer" };3940/**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 */44const tinyHost = (): HostLike => {45 const repos = new Set<RepoName>();46 let minted = 0;4748 const known = (name: RepoName): Effect.Effect<void, RepoNotFound> =>49 repos.has(name) ? Effect.void : Effect.fail(new RepoNotFound({ name }));5051 const make = (name: RepoName) =>52 repos.has(name)53 ? Effect.fail(new RepoExists({ name }))54 : Effect.sync(() => {55 repos.add(name);5657 return { name, remote: `memory://${name}.git` };58 });5960 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;9192 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};159160/** Awaits one of the binding's promises. */161const 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 });169170/** What one of the binding's promises threw, or an error saying it resolved. */171const 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 );178179const text = (bytes: Blob | null) =>180 bytes === null ? Effect.succeed(null) : call(() => bytes.text());181182/** An error as a plain record: its name and message, and its code and number if it has them. */183const 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});190191/** A binding over a fresh tiny host, with `datekit` made, and the repo `get` hands back. */192const 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"));199200 return { binding, created, repo };201 });202203describe("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();207208 expect(created).toMatchObject({209 defaultBranch: "main",210 description: null,211 name: "datekit",212 remote: "memory://datekit.git",213 token: "secret-1",214 });215 })216 );217218 it.effect("hands back a repo whose reads by object id go to the host", () =>219 Effect.gen(function* () {220 const { repo } = yield* withDatekit();221222 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 );241242 it.effect("reads null for an object the host doesn't have", () =>243 Effect.gen(function* () {244 const { repo } = yield* withDatekit();245246 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 );251252 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 );259260 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 );269270 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"));277278 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 );291292 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"));301302 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 );323324 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();329330 const read = (ref: string) =>331 call(() => repo.readFile({ path: "a.txt", ref })).pipe(332 Effect.flatMap(text)333 );334335 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 );349350 it.effect("refuses a malformed object id, an empty path or a bad name", () =>351 Effect.gen(function* () {352 const { binding, repo } = yield* withDatekit();353354 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);360361 expect(codes).toStrictEqual([362 "INVALID_INPUT",363 "INVALID_INPUT",364 "INVALID_REPO_NAME",365 "INVALID_TTL",366 ]);367 })368 );369370 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 });377378 const info = yield* call(() => repo.info());379380 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 );390391 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());397398 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 );411412 it.effect("lists and deletes what it made", () =>413 Effect.gen(function* () {414 const { binding } = yield* withDatekit();415416 yield* call(() => binding.create("burrow"));417418 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"));422423 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
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Cause, ConfigProvider, Effect, Exit, FileSystem } from "effect";56import { git, gitOk } from "../src/git.ts";7import { expectGolden, GoldenDir, normaliseGitOutput } from "../src/golden.ts";89const id = "0123456789abcdef0123456789abcdef01234567";1011/**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 */15const 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`;2122 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");4142 return yield* git(work, "push", remote, "HEAD:refs/heads/main");43}).pipe(Effect.scoped);4445/** What a failed expectation says, or nothing when it passed. */46const complaint = (exit: Exit.Exit<void>) =>47 Exit.isFailure(exit) ? String(Cause.squash(exit.cause)) : "";4849/** Runs with golden files in a fresh folder, and `UPDATE_GOLDEN` as given. */50const 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);5758 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);6768describe("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 });7879 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 });9899 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 });108109 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 });116117 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 });124125 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;131132 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 );138139 yield* expectGolden(140 "push-new-branch",141 normaliseGitOutput(first.stderr)142 );143 }).pipe(Effect.provide(NodeServices.layer)),144 20_000145 );146});147148describe("golden files", () => {149 it.effect("pass when the text matches the file", () =>150 Effect.gen(function* () {151 const fs = yield* FileSystem.FileSystem;152153 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);159160 const exit = yield* Effect.exit(161 expectGolden("same", "To <tmp>/remote.git\n")162 );163164 expect(complaint(exit)).toBe("");165 })166 );167 }).pipe(Effect.provide(NodeServices.layer))168 );169170 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;175176 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);184185 const exit = yield* Effect.exit(186 expectGolden("changed", "line one\nline 2\n")187 );188189 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 );197198 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"));202203 expect(complaint(exit)).toContain("absent.txt");204 expect(complaint(exit)).toContain("UPDATE_GOLDEN=1");205 })206 ).pipe(Effect.provide(NodeServices.layer))207 );208209 it.effect("are written, folder and all, under UPDATE_GOLDEN=1", () =>210 Effect.gen(function* () {211 const fs = yield* FileSystem.FileSystem;212213 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);219220 yield* expectGolden("rewritten", "new\n");221 yield* expectGolden("nested/fresh", "fresh\n");222223 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 );236237 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;242243 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 );249250 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
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec } from "@repo/protocol/domain/check";5import { Command, SymbolName } from "@repo/protocol/domain/common";6import { Policy } from "@repo/protocol/domain/policy";7import {8 CommitSha,9 DecisionId,10 ProposalId,11 RepoPath,12 RequestId,13} from "@repo/protocol/ids";14import { DateTime, Equal, Schema } from "effect";15import { vi } from "vitest";1617import {18 aProject,19 ids,20 sha,21 sixChildren,22 withAsk,23 withKind,24 withVouches,25} from "../src/scenarios.ts";2627const six = [1, 2, 3, 4, 5, 6];2829const children = six.map((n) => `drop-legacy-fetch-p${n}`);3031const isPolicy = Schema.is(Policy);3233const isAsk = Schema.is(Ask);3435const lintToZero = CheckSpec.cases.LintToZero.make({36 command: Command.make("bun run lint --format json"),37 rule: "no-floating-effect",38});3940const 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;5051const parserFix = () =>52 aProject().pipe(53 withAsk({ id: "fix-parser", territory: "packages/parser" }),54 withVouches(["bob"])55 );5657describe("a project scenario", () => {58 it("holds a policy that decodes as a Policy, at its landed commit", () => {59 const { landed, policy } = aProject();6061 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 });7273 it("is decided, by default, by its initializer alice, for every path", () => {74 const { initializer, policy, project } = aProject();7576 expect({ initializer, project }).toStrictEqual({77 initializer: "alice",78 project: "datekit",79 });80 expect(policy.deciders).toStrictEqual([81 { handles: ["alice"], paths: "**" },82 ]);83 });8485 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 });9192 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 });104105 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");107108 const scenario = aProject({ now }).pipe(109 withAsk({ id: "fix-parser", territory: "packages/parser" })110 );111112 const [ask] = scenario.policy.asks;113114 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 });136137 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 );149150 const [, ask] = scenario.policy.asks;151152 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 });161162 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 });167168 it("adds a kind, replacing one of the same name", () => {169 const scenario = aProject().pipe(170 withKind(lintKind),171 withKind({ ...lintKind, race: 2 })172 );173174 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 });181182 it("records vouches and denouncements as the vouch file's lines", () => {183 const scenario = aProject().pipe(184 withVouches(["bob", "carol"], ["mallory"])185 );186187 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 });194195 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});201202describe("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();205206 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 });214215 it("has a parent migrating the symbol across the six packages", () => {216 const [parent] = sixChildren().policy.asks;217218 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 });231232 it("splits into six children on disjoint packages, the project's modules", () => {233 const { policy } = sixChildren();234 const steps = policy.asks.slice(1, 7);235236 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 });258259 it("ends with a delete child blocked by all six", () => {260 const last = sixChildren().policy.asks.at(-1);261262 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 });273274 it("names the family after the symbol it moves", () => {275 const { policy } = sixChildren({ symbol: "oldClock", to: "clock.now" });276277 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});288289describe("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 });297298 it("mints request, proposal and decision ids from counters", () => {299 const next = ids();300301 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 });311312 it("mints ids the domain accepts, without reading randomness", () => {313 const random = vi.spyOn(crypto, "randomUUID");314 const next = ids();315316 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();320321 random.mockRestore();322 });323});
deleted:packages/testkit/test/smoke.test.ts-10 removed