Keep the fake Artifacts binding from listing repos it never had, and keep progress lines that end in a carriage return
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Review of 211 against its issue (Spec) and AGENTS.md (Standards), fixed point main. - fake-artifacts-binding: keptOf now asks the host before it records a repo. Before, info(), log() and revokeToken() on a stale handle to a deleted repo re-created its record, and list() showed a repo the host no longer had. - fake-artifacts-binding: readOnly from create, fork and import reaches info() and list(); it always read false. - fake-artifacts-binding: one Effect.mapError maps failures to the thrown error in place of matchEffect/die/succeed, and refusalOf takes Refused too, so the five-arm Match that sent four tags to refusalOf is gone. log resolves HEAD through revisionOf like every other ref. - scenarios: withAsk over "." no longer makes the whole repo a module (modules are workspaces; sixChildren already kept "." out). - golden: normaliseGitOutput keeps the last non-empty version of a line rewritten with carriage returns. A line ending in a bare "\r" (a progress meter cut off) came out empty. - Tests added: the fake lists nothing it deleted after a stale handle's reads, and reports read-only repos; withAsk over "." adds no module; a progress line ending in "\r" survives normalising. Each was red by assertion first. - Test tightened: the determinism test spies on crypto.randomUUID, crypto.getRandomValues, Math.random and Date.now across every builder and restores its spies when it finishes, even when it fails. A planted Math.random() read in aProject turned it red. The tiny host's commit is one constant. - Checked, not committed: a throwaway probe in packages/artifacts/test showed a RepoHost value is assignable to HostLike (tsc rejects a mismatched one), and the fake behaves as tested over RepoHostMemory.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+164 added−85 removed
- tests:+108 added−27 removed
- other:+56 added−58 removed
Provenance
- Commit
eb8fd27- Tree
047df8c- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
d6d17af
6 files changed+164 added−85 removed
modified:packages/testkit/src/fake-artifacts-binding.ts+47 added-52 removed
188 unmodified lines189 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) =>193+/** A host's error as the binding words it (S1 #22, S7 #2); a refusal stays as it is. */194+const refusalOf = (error: HostError | Refused) =>195 Match.valueTags(error, {196 ForkInProgress: ({ name }) =>197 new Refused({198 code: "FORK_IN_PROGRESS",4 unmodified lines203 code: "INTERNAL_ERROR",204 reason: "An internal error occurred.",205 }),206 ImportRefused: ({ reason }) => new Refused({ code: "INVALID_URL", reason }),207+ Refused: (refused) => refused,208 RepoExists: ({ name }) =>209 new Refused({210 code: "ALREADY_EXISTS",211 reason: `repo already exists: ${name}`,107 unmodified lines319 320 /** Runs one call as the binding answers: a promise, rejected with its error. */321 const run = <A>(effect: Effect.Effect<A, Refused | HostError>) =>322 Effect.runPromise(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- )323+ Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))324 );325 326 const remoteOf = (name: RepoName) =>327 options.remoteBase === undefined1 unmodified line329 : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));330 331 const keep = (332 name: RepoName,349- fields: Partial<Pick<Kept, "description" | "defaultBranch" | "source">>333+ fields: Partial<334+ Pick<Kept, "description" | "defaultBranch" | "readOnly" | "source">335+ >336 ) => {337 made += 1;338 339 const repo: Kept = {340 defaultBranch: fields.defaultBranch ?? "main",341 description: fields.description ?? null,342 id: `repo-${String(made).padStart(6, "0")}`,343 name,358- readOnly: false,344+ readOnly: fields.readOnly ?? false,345 source: fields.source ?? null,346 tokens: new Map(),347 };348 1 unmodified line350 351 return repo;352 };353 368- /** What `info()` shows for a repo the fake did not make itself. */369- const keptOf = (name: RepoName) => kept.get(name) ?? keep(name, {});354+ /**355+ * The fake's record of a repo the host has: the one it made, or a fresh one356+ * for a repo made on the host directly. A repo the host lacks fails with357+ * `RepoNotFound` and leaves no record, so `list()` never shows it.358+ */359+ const keptOf = (name: RepoName) =>360+ host.remote(name).pipe(Effect.map(() => kept.get(name) ?? keep(name, {})));361 362 const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>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);363+ Effect.gen(function* () {364+ const token = yield* host.mintToken(365+ name,366+ scope,367+ Duration.seconds(seconds)368+ );369 377- keptOf(name).tokens.set(token.id, {378- createdAt: stamped,379- expiresAt,380- id: token.id,381- plaintext,382- scope,383- state: "active",384- });370+ const { tokens } = yield* keptOf(name);371+ const plaintext = Redacted.value(token.secret);372+ const expiresAt = DateTime.formatIso(token.expiresAt);373 386- return { expiresAt, id: token.id, plaintext, scope: token.scope };387- })388- );374+ tokens.set(token.id, {375+ createdAt: stamped,376+ expiresAt,377+ id: token.id,378+ plaintext,379+ scope,380+ state: "active",381+ });382 383+ return { expiresAt, id: token.id, plaintext, scope: token.scope };384+ });385+386 /** A new repo's result: its metadata, its remote and a day-long write token (S1 #2). */387 const createdOf = (repo: Kept) =>388 Effect.gen(function* () {389 const remote = yield* remoteOf(repo.name);53 unmodified lines443 yield* host.fork(name, fork);444 445 const repo = keep(fork, {446 description: forkOptions?.description ?? null,447+ readOnly: forkOptions?.readOnly ?? false,448 source: `artifacts:fake/${name}`,449 });450 451 if (forkFailures > 0) {7 unmodified lines459 460 return yield* createdOf(repo);461 })462 ),466- info: () => run(info(keptOf(name))),463+ info: () => run(keptOf(name).pipe(Effect.flatMap(info))),464 listTokens: () =>465 run(469- host.remote(name).pipe(470- Effect.map(() => {471- const tokens = [...keptOf(name).tokens.values()].map(466+ keptOf(name).pipe(467+ Effect.map((repo) => {468+ const tokens = [...repo.tokens.values()].map(469 ({ createdAt, expiresAt, id, scope, state }) => ({470 createdAt,471 expiresAt,472 id,12 unmodified lines485 const ref = logOptions?.ref ?? "HEAD";486 const limit = Math.min(logOptions?.limit ?? 50, 1000);487 const offset = logOptions?.offset ?? 0;488 492- const at =493- ref === "HEAD"494- ? Option.some(495- Revision.Branch({496- name: BranchName.make(keptOf(name).defaultBranch),497- })498- )499- : revisionOf(ref);489+ // `HEAD` is the repo's default branch.490+ const at = revisionOf(491+ ref === "HEAD" ? (yield* keptOf(name)).defaultBranch : ref492+ );493 494 if (Option.isNone(at)) {495 return [];496 }59 unmodified lines556 "tokenOrId must not be empty"557 );558 }559 567- const { tokens } = keptOf(name);560+ const { tokens } = yield* keptOf(name);561 562 const token = [...tokens.values()].find(563 ({ id, plaintext }) => id === tokenOrId || plaintext === tokenOrId564 );21 unmodified lines586 return yield* createdOf(587 keep(repoName, {588 defaultBranch: createOptions?.setDefaultBranch ?? "main",589 description: createOptions?.description ?? null,590+ readOnly: createOptions?.readOnly ?? false,591 })592 );593 })594 ),36 unmodified lines631 632 return yield* createdOf(633 keep(repoName, {634 description: target.opts?.description ?? null,635+ readOnly: target.opts?.readOnly ?? false,636 source: source.url,637 })638 );639 })18 unmodified linesmodified:packages/testkit/src/golden.ts+4 added-2 removed
29 unmodified lines30313233343435363637383940414291 unmodified lines29 unmodified linesconst LOCAL_SERVER = /\b(?:127\.0\.0\.1|localhost):\d+/gu;
/** * What a terminal shows of one line git rewrote with carriage returns (a * progress meter): the last version of it. * progress meter): the last version of it. A carriage return with nothing * after it only moves the cursor, so the version before it still shows. */const lastRewrite = (line: string) => line.split("\r").at(-1) ?? line;const lastRewrite = (line: string) => line.split("\r").findLast((version) => version !== "") ?? "";
/** * Git's output, the same on every run of the same push: without the eight * spaces git pads side-band lines with when stderr is not a terminal (and any91 unmodified linesmodified:packages/testkit/src/scenarios.ts+5 added-4 removed
312 unmodified lines313 };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.317+ * territory's module. The territory is a folder (`packages/parser`) or `.`318+ * (the whole repo, which is no module: modules are workspaces); the kind319+ * defaults to `fix`, the check to a `RedThenGreen` file in the territory, the320+ * want to a sentence naming both.321 */322 export const withAsk =323 (ask: AskOptions) =>324 (scenario: Scenario): Scenario =>324- openAsk(scenario, ask, territoryOf(ask.territory), true);325+ openAsk(scenario, ask, territoryOf(ask.territory), ask.territory !== ".");326 327 /** Adds an ask kind, in place of one with the same name. */328 export const withKind =329 (kind: AskKindEncoded) =>114 unmodified linesmodified:packages/testkit/test/fake-artifacts-binding.test.ts+59 added-22 removed
35 unmodified lines36 const hello = new TextEncoder().encode("hello\n");37 38 const answerer = { email: "answerer@example.com", name: "Answerer" };39 40+/** The one commit every repo holds on `main`. */41+const firstCommit = {42+ author: answerer,43+ committer: answerer,44+ message: "first",45+ parents: [],46+ sha: commit,47+ tree,48+};49+50 /**51 * A repo host as small as the fake needs: every repo holds one commit on52 * `main`, whose tree has `a.txt` ("hello") and a folder `src`.53 */26 unmodified lines80 Match.valueTags(at, {81 Branch: ({ name: branch }) => branch === "main",82 Commit: ({ sha }) => sha === commit,83 })74- ? [75- {76- author: answerer,77- committer: answerer,78- message: "first",79- parents: [],80- sha: commit,81- tree,82- },83- ]84+ ? [firstCommit]85 : []86 )87 ),88 mintToken: (name, scope, ttl) =>17 unmodified lines106 Effect.as(sha === blob ? Option.some(hello) : Option.none())107 ),108 readCommit: (name, sha) =>109 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- )110+ Effect.as(sha === commit ? Option.some(firstCommit) : Option.none())111 ),112 readFile: (name, at, path) =>113 known(name).pipe(114 Effect.as(303 unmodified lines418 expect([deleted, again]).toStrictEqual([true, false]);419 expect(described(gone).code).toBe("NOT_FOUND");420 })421 );422+423+ it.effect("reports a repo made read-only as read-only", () =>424+ Effect.gen(function* () {425+ const { binding, repo } = yield* withDatekit();426+427+ yield* call(() => binding.create("archive", { readOnly: true }));428+ yield* call(() => repo.fork("datekit--mirror", { readOnly: true }));429+430+ const { repos } = yield* call(() => binding.list());431+432+ expect(repos.map(({ name, readOnly }) => [name, readOnly])).toStrictEqual(433+ [434+ ["datekit", false],435+ ["archive", true],436+ ["datekit--mirror", true],437+ ]438+ );439+ })440+ );441+442+ it.effect(443+ "lists nothing it deleted, even after a stale handle reads the repo",444+ () =>445+ Effect.gen(function* () {446+ const { binding, repo } = yield* withDatekit();447+448+ yield* call(() => binding.delete("datekit"));449+450+ const codes = [451+ yield* thrown(() => repo.info()),452+ yield* thrown(() => repo.log()),453+ yield* thrown(() => repo.revokeToken("secret-1")),454+ yield* thrown(() => repo.listTokens()),455+ ].map((error) => described(error).code);456+457+ expect(codes).toStrictEqual([458+ "NOT_FOUND",459+ "NOT_FOUND",460+ "NOT_FOUND",461+ "NOT_FOUND",462+ ]);463+ expect(yield* call(() => binding.list())).toStrictEqual({464+ repos: [],465+ total: 0,466+ });467+ })468+ );469 });modified:packages/testkit/test/golden.test.ts+8 added
120 unmodified lines121 )122 ).toBe("Writing objects: 100% (2/2), done.\nTo x\n");123 });124 125+ it("keeps a progress line that ends in a carriage return, as a terminal still shows it", () => {126+ expect(127+ normaliseGitOutput(128+ "Counting objects: 1\rCounting objects: 2\r\r\nTo x\nWriting objects: 50% (1/2)\r"129+ )130+ ).toBe("Counting objects: 2\nTo x\nWriting objects: 50% (1/2)");131+ });132+133 it.live(134 "makes two runs of the same push compare equal, and match their golden file",135 () =>136 Effect.gen(function* () {132 unmodified linesmodified:packages/testkit/test/scenarios.test.ts+41 added-5 removed
10 unmodified lines11 RepoPath,12 RequestId,13 } from "@repo/protocol/ids";14 import { DateTime, Equal, Schema } from "effect";15-import { vi } from "vitest";15+import { onTestFinished, vi } from "vitest";16 17 import {18 aProject,19 ids,138 unmodified lines158 });159 expect(scenario.policy.modules).toHaveLength(1);160 });161 162+ it("opens an ask over the whole repo without making the repo a module", () => {163+ const scenario = aProject().pipe(164+ withAsk({ id: "tidy-readme", territory: "." })165+ );166+167+ expect(scenario.policy.asks[0]?.territory).toStrictEqual({168+ module: ".",169+ paths: ["**"],170+ });171+ expect(scenario.policy.modules).toStrictEqual([]);172+ });173+174 it("refuses an ask the domain refuses, such as one named after a reserved word", () => {175 expect(() =>176 aProject().pipe(withAsk({ id: "me", territory: "packages/parser" }))177 ).toThrow("reserved");142 unmodified lines320 ]);321 expect(ids().request()).toBe("req-000001");322 });323 312- it("mints ids the domain accepts, without reading randomness", () => {313- const random = vi.spyOn(crypto, "randomUUID");324+ it("mints ids the domain accepts", () => {325 const next = ids();326 327 expect(Schema.is(RequestId)(next.request())).toBeTruthy();328 expect(Schema.is(ProposalId)(next.proposal())).toBeTruthy();329 expect(Schema.is(DecisionId)(next.decision())).toBeTruthy();319- expect(random).not.toHaveBeenCalled();330+ });331 332+ it("builds every value without reading the clock or randomness", () => {333+ const reads = {334+ getRandomValues: vi.spyOn(crypto, "getRandomValues"),335+ now: vi.spyOn(Date, "now"),336+ random: vi.spyOn(Math, "random"),337+ randomUUID: vi.spyOn(crypto, "randomUUID"),338+ };339+340+ onTestFinished(() => {341+ for (const read of Object.values(reads)) {321- random.mockRestore();342+ read.mockRestore();343+ }344+ });345+346+ const next = ids();347+348+ parserFix();349+ sixChildren();350+ sha("main");351+ next.request();352+ next.proposal();353+ next.decision();354+355+ expect(356+ Object.values(reads).map((read) => read.mock.calls.length)357+ ).toStrictEqual([0, 0, 0, 0]);358 });359 });