Credit landings in trailers, diff two trees through RepoHost, give change sets a PatchId, write verdicts as git notes, and forward the gateway to the store with cached tokens
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- trailers: formatLanding writes subject, body, then one trailer block: credits ordered by CreditRole and deduped (the same rows always make the same message), `Assisted-by: <harness>[:<model>] (verified|claimed)` (the kernel's AGENT:MODEL shape), `Ask: <project>/<ask>`, `Verdict: <patchId> <checkVersion>`, `Held-back: <value>` and `Request-id:`. Subject and values are folded to one line so none can open a trailer of its own. parseTrailers follows git's documented rules (title never trailers; last paragraph all trailers, or a sign-off and 25%; continuation lines; `---` divider; trailing comments). creditsOf counts only credits in the platform's exact `handle <handle@users.<domain>>` form, so an imported sign-off is not credit. - tree-diff: walks readTree from both roots, skipping any entry whose id and mode match, so an unchanged subtree is never read; subtree reads run 8 at a time. Change is an interface structurally equal to gate's. A submodule pointer counts as a change at its path; a mode-only change is `modified` with equal blobs. addedLines: Myers' O(ND) diff after trimming the common prefix and suffix; past 1024 edits it falls back to matching lines by count; a NUL in the first 8 KiB means binary (no lines). - patchId (D7): SHA-256 via WebCrypto over the sorted `path\0before\0after\n` lines, absent blob as "". - notes (D22): notesRef is `refs/notes/${Brand.slug}`. noteCommit writes the blob, the fanout-free tree and the platform's commit as loose zlib objects (CompressionStream + SHA-1) in a memoryFs scratch dir, plus the ref. Departure from the Interface: it takes `repo` and needs RepoHost, since it reads the parent notes tree through the port (as the issue's own note says); it returns a ScratchSource, a PushSource whose fs is typed memoryFs. Objects are written by hand because packages/git has no isomorphic-git (isolated linker; package.json is not this issue's). - UpstreamRepoHost: Basic auth `x:<secret less ?expires=>` (what Artifacts takes over git HTTPS), read token for upload-pack and write for receive-pack; remote and token cached per (repo, scope) in an effect Cache made when the layer is built, until a minute before expiry; failed mints aren't kept. Call bodies stream (`duplex: "half"` for Node; workerd ignores it). Fetch failures become UpstreamFailure. - Tests: trailers (real git interpret-trailers on the landing message and six edge messages), tree-diff (blob ids, readTree count through a wrapping layer, added lines and a binary file, a seeded property test against a textbook LCS), patch-id (a literal from sha256sum, order, sensitivity), notes (push into RepoHostMemory, which re-serializes every object through isomorphic-git and checks its id; read back through the port; real `git notes show` and `git notes list` on a disk copy of the scratch dir, in place of isomorphic-git's readNote, which git's tests cannot import), upstream (Fetch fake, TestClock expiry, RepoNotFound). Each failed by assertion against stubs first. - ASSUMPTION: the binding adapter (217) can push a source that holds only the new note objects and references earlier notes by id; the memory adapter can, since it skips objects the repo already has.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+2169 added−0 removed
- tests:+1061 added−0 removed
- other:+1108 added−0 removed
Provenance
- Commit
992c278- Tree
c0b6350- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3d5870c
10 files changed+2169 added−0 removed
added:packages/git/src/upstream/repo-host.ts+126 added
1+import { Fetch } from "@repo/artifacts/fetch";2+import { RepoHost } from "@repo/artifacts/repo-host";3+import type { RepoName, TokenScope } from "@repo/artifacts/repo-host";4+import {5+ Cache,6+ Data,7+ DateTime,8+ Duration,9+ Effect,10+ Exit,11+ Layer,12+ Redacted,13+} from "effect";14+15+import { Exchange, Upstream, UpstreamFailure } from "../upstream.ts";16+import type { Service } from "../upstream.ts";17+18+/** How long a token the upstream mints is asked to last. */19+const TOKEN_TTL = Duration.hours(1);20+21+/** A token is dropped this long before it expires, so none expires mid-exchange. */22+const MARGIN = Duration.minutes(1);23+24+/** Tokens kept at once, one per (repo, scope). */25+const CAPACITY = 1024;26+27+class TokenKey extends Data.Class<{28+ readonly repo: RepoName;29+ readonly scope: TokenScope;30+}> {}31+32+/** A clone or fetch reads; only a push writes. */33+const scopeOf = (service: Service): TokenScope =>34+ service === "git-receive-pack" ? "write" : "read";35+36+/**37+ * Basic auth as Artifacts takes it: any user name, and the token's secret38+ * without its `?expires=` suffix as the password.39+ */40+const basic = (secret: Redacted.Redacted) => {41+ const [password = ""] = Redacted.value(secret).split("?expires=");42+43+ return `Basic ${btoa(`x:${password}`)}`;44+};45+46+const requestOf = (47+ remote: string,48+ exchange: Exchange,49+ authorization: string50+) => {51+ const headers = new Headers(exchange.headers);52+53+ headers.set("authorization", authorization);54+55+ return Exchange.$match(exchange, {56+ Advertise: ({ service }) =>57+ new Request(`${remote}/info/refs?service=${service}`, { headers }),58+ Call: ({ body, service }) => {59+ // Node sends a streamed body only with `duplex: "half"`; the Workers60+ // types lack the key, and workerd ignores it.61+ const init = { body, duplex: "half", headers, method: "POST" };62+63+ return new Request(`${remote}/${service}`, init);64+ },65+ });66+};67+68+/**69+ * The production `Upstream`: each exchange goes to the repo's own remote in70+ * the store, with a token the store minted for the exchange's scope. Tokens71+ * are cached per (repo, scope) until a minute before they expire, in a cache72+ * made when the layer is built: one per isolate in a Worker (S7 #2).73+ */74+export const UpstreamRepoHost: Layer.Layer<Upstream, never, RepoHost | Fetch> =75+ Layer.effect(76+ Upstream,77+ Effect.gen(function* () {78+ const host = yield* RepoHost;79+ const client = yield* Fetch;80+81+ const credentials = yield* Cache.makeWith(82+ ({ repo, scope }: TokenKey) =>83+ Effect.gen(function* () {84+ const remote = yield* host.remote(repo);85+ const token = yield* host.mintToken(repo, scope, TOKEN_TTL);86+ const now = yield* DateTime.now;87+88+ return {89+ authorization: basic(token.secret),90+ lasts: Duration.subtract(91+ DateTime.distance(now, token.expiresAt),92+ MARGIN93+ ),94+ remote,95+ };96+ }),97+ {98+ capacity: CAPACITY,99+ // A failed mint is not kept, nor a token too short-lived to use.100+ timeToLive: (exit) =>101+ Exit.isSuccess(exit) &&102+ Duration.isGreaterThan(exit.value.lasts, Duration.zero)103+ ? exit.value.lasts104+ : Duration.zero,105+ }106+ );107+108+ return Upstream.of({109+ exchange: (repo, exchange) =>110+ Effect.gen(function* () {111+ const { authorization, remote } = yield* Cache.get(112+ credentials,113+ new TokenKey({ repo, scope: scopeOf(exchange.service) })114+ );115+116+ return yield* client117+ .fetch(requestOf(remote, exchange, authorization))118+ .pipe(119+ Effect.mapError(120+ ({ reason }) => new UpstreamFailure({ reason, repo })121+ )122+ );123+ }),124+ });125+ })126+ );added:packages/git/src/notes.ts+255 added
1+import { ObjectId, RefName, RepoHost } from "@repo/artifacts/repo-host";2+import type {3+ PushSource,4+ RepoNotFound,5+ TreeEntry,6+} from "@repo/artifacts/repo-host";7+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";8+import { Brand } from "@repo/brand";9+import { Verdict } from "@repo/protocol/domain/answer";10+import { CommitSha } from "@repo/protocol/ids";11+import type { RepoName } from "@repo/protocol/ids";12+import { DateTime, Effect, Option, Schema } from "effect";13+14+import { committerLine } from "./trailers.ts";15+16+/**17+ * Where verdicts live as git notes (spec D22): one JSON note per commit, read18+ * with `git notes --ref=<slug> show <commit>`.19+ */20+export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);21+22+/** A verdict to write as the note on `target`, on top of the notes at `notesParent` in `repo`. */23+export interface NoteInput {24+ readonly repo: RepoName;25+ readonly notesParent: Option.Option<CommitSha>;26+ readonly target: CommitSha;27+ readonly verdict: Verdict;28+ readonly now: DateTime.Utc;29+}30+31+/**32+ * A git directory in memory that a push takes objects from: a `PushSource`33+ * whose file system is `memoryFs`, so a reader gets its typed API.34+ */35+export interface ScratchSource extends PushSource {36+ readonly fs: MemoryFs;37+}38+39+type MemoryFs = ReturnType<typeof memoryFs>;40+41+const encoder = new TextEncoder();42+43+const concat = (parts: readonly Uint8Array[]) => {44+ const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));45+ let at = 0;46+47+ for (const part of parts) {48+ all.set(part, at);49+ at += part.byteLength;50+ }51+52+ return all;53+};54+55+const hex = (bytes: ArrayBuffer) =>56+ [...new Uint8Array(bytes)]57+ .map((byte) => byte.toString(16).padStart(2, "0"))58+ .join("");59+60+const bytesOfHex = (id: string) =>61+ Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));62+63+/** git's zlib stream, as a loose object holds it. */64+const deflate = (bytes: Uint8Array) =>65+ Effect.promise(() =>66+ new Response(67+ new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))68+ ).arrayBuffer()69+ ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));70+71+const sortKey = (entry: TreeEntry) =>72+ encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);73+74+// git sorts a tree's entries by name, a subtree's name as if it ended in "/".75+const treeOrder = (one: TreeEntry, other: TreeEntry) => {76+ const left = sortKey(one);77+ const right = sortKey(other);78+79+ for (let at = 0; at < Math.min(left.length, right.length); at += 1) {80+ const diff = (left[at] ?? 0) - (right[at] ?? 0);81+82+ if (diff !== 0) {83+ return diff;84+ }85+ }86+87+ return left.length - right.length;88+};89+90+// A tree object spells a subtree's mode without its leading zero.91+const modeOf = (entry: TreeEntry) => entry.mode.replace(/^0/u, "");92+93+const treeBytes = (entries: readonly TreeEntry[]) =>94+ concat(95+ entries96+ .toSorted(treeOrder)97+ .flatMap((entry) => [98+ encoder.encode(`${modeOf(entry)} ${entry.name}\0`),99+ bytesOfHex(entry.sha),100+ ])101+ );102+103+const signature = (now: DateTime.Utc) =>104+ `${committerLine.name} <${committerLine.email}> ${Math.floor(DateTime.toEpochMillis(now) / 1000)} +0000`;105+106+const commitBytes = (input: {107+ readonly tree: string;108+ readonly parents: readonly CommitSha[];109+ readonly now: DateTime.Utc;110+ readonly message: string;111+}) =>112+ encoder.encode(113+ [114+ `tree ${input.tree}`,115+ ...input.parents.map((parent) => `parent ${parent}`),116+ `author ${signature(input.now)}`,117+ `committer ${signature(input.now)}`,118+ "",119+ input.message,120+ ].join("\n")121+ );122+123+/**124+ * A bare git directory in memory that a push takes objects from: loose,125+ * zlib-deflated objects named by the SHA-1 of their header and content.126+ */127+const scratch = () =>128+ Effect.gen(function* () {129+ const fs = memoryFs();130+ const gitdir = "/notes.git";131+ const made = new Set<string>();132+133+ const mkdir = (path: string) =>134+ made.has(path)135+ ? Effect.void136+ : Effect.promise(() => fs.promises.mkdir(path)).pipe(137+ Effect.tap(() => Effect.sync(() => made.add(path)))138+ );139+140+ const write = (path: string, data: string | Uint8Array) =>141+ Effect.promise(() => fs.promises.writeFile(path, data));142+143+ yield* Effect.forEach(144+ ["", "/objects", "/refs", "/refs/heads", "/refs/notes", "/refs/tags"],145+ (dir) => mkdir(`${gitdir}${dir}`)146+ );147+ yield* write(`${gitdir}/HEAD`, "ref: refs/heads/main\n");148+ yield* write(149+ `${gitdir}/config`,150+ "[core]\n\trepositoryformatversion = 0\n\tbare = true\n"151+ );152+153+ const object = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>154+ Effect.gen(function* () {155+ const raw = concat([156+ encoder.encode(`${kind} ${content.byteLength}\0`),157+ content,158+ ]);159+160+ const id = hex(161+ yield* Effect.promise(() => crypto.subtle.digest("SHA-1", raw))162+ );163+164+ const dir = `${gitdir}/objects/${id.slice(0, 2)}`;165+166+ yield* mkdir(dir);167+ yield* write(`${dir}/${id.slice(2)}`, yield* deflate(raw));168+169+ return id;170+ });171+172+ return {173+ object,174+ ref: (ref: RefName, sha: CommitSha) =>175+ write(`${gitdir}/${ref}`, `${sha}\n`),176+ source: { fs, gitdir } satisfies ScratchSource,177+ };178+ });179+180+/** The notes tree's entries at `parent`, read through the port; none for the first note. */181+const notesAt = (repo: RepoName, parent: Option.Option<CommitSha>) =>182+ Option.match(parent, {183+ onNone: () => Effect.succeed<readonly TreeEntry[]>([]),184+ onSome: (sha) =>185+ Effect.gen(function* () {186+ const host = yield* RepoHost;187+ const commit = yield* host.readCommit(repo, sha);188+189+ if (Option.isNone(commit)) {190+ return yield* Effect.die(`${repo} has no notes commit ${sha}`);191+ }192+193+ const tree = yield* host.readTree(repo, commit.value.tree);194+195+ if (Option.isNone(tree)) {196+ return yield* Effect.die(`${repo} has no tree ${commit.value.tree}`);197+ }198+199+ return tree.value;200+ }),201+ });202+203+const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));204+205+/**206+ * The notes commit that puts `verdict` on `target`, in git's own notes207+ * layout: a fanout-free tree with one blob per annotated commit, named by its208+ * SHA, holding the verdict as JSON. The tree keeps every note under209+ * `notesParent` (read through the port), and the platform commits it at210+ * `now`. The new blob, tree and commit sit in a scratch git directory in211+ * memory, which `RepoHost.push` takes them from; the earlier notes' objects212+ * are referenced by id and are already in `repo`.213+ */214+export const noteCommit = (215+ input: NoteInput216+): Effect.Effect<217+ { readonly source: ScratchSource; readonly commit: CommitSha },218+ RepoNotFound,219+ RepoHost220+> =>221+ Effect.gen(function* () {222+ const earlier = yield* notesAt(input.repo, input.notesParent);223+ const json = yield* encodeVerdict(input.verdict).pipe(Effect.orDie);224+ const repo = yield* scratch();225+ const blob = yield* repo.object("blob", encoder.encode(`${json}\n`));226+227+ const tree = yield* repo.object(228+ "tree",229+ treeBytes([230+ ...earlier.filter(({ name }) => name !== input.target),231+ {232+ mode: "100644",233+ name: input.target,234+ sha: ObjectId.make(blob),235+ type: "blob",236+ },237+ ])238+ );239+240+ const commit = CommitSha.make(241+ yield* repo.object(242+ "commit",243+ commitBytes({244+ message: `Verdict on ${input.target}\n`,245+ now: input.now,246+ parents: Option.toArray(input.notesParent),247+ tree,248+ })249+ )250+ );251+252+ yield* repo.ref(notesRef, commit);253+254+ return { commit, source: repo.source };255+ });added:packages/git/src/patch-id.ts+29 added
1234567891011121314151617181920212223242526272829import { PatchId } from "@repo/protocol/ids";import { Array, Effect, Order } from "effect";
import type { Change } from "./tree-diff.ts";
const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)] .map((byte) => byte.toString(16).padStart(2, "0")) .join("");
/** * An answer's patch id (spec D7): SHA-256 over its change set as sorted * `path\0before\0after\n` lines, an absent blob as the empty string. It * ignores order and moves exactly when a blob the answer touches moves. It * is the platform's own id, not `git patch-id`, so a Worker computes it with * WebCrypto and no diff. */export const patchId = (changes: readonly Change[]): Effect.Effect<PatchId> => { const lines = Array.sort( changes.map( ({ after, before, path }) => `${path}\0${before ?? ""}\0${after ?? ""}\n` ), Order.String );
return Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(lines.join(""))) ).pipe(Effect.map((digest) => PatchId.make(hex(digest))));};added:packages/git/src/trailers.ts+364 added
1+import { Brand } from "@repo/brand";2+import { CreditRole } from "@repo/protocol/domain/credit";3+import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";4+import { Handle } from "@repo/protocol/ids";5+import type {6+ AskId,7+ CheckVersion,8+ PatchId,9+ ProjectName,10+ RequestId,11+} from "@repo/protocol/ids";12+import { Array, Option, Order, Schema } from "effect";13+14+/** One `Key: value` line of a commit message's trailer block. */15+export interface Trailer {16+ readonly key: string;17+ readonly value: string;18+}19+20+/** A git identity: the name and email of an author or committer line. */21+export interface Person {22+ readonly name: string;23+ readonly email: string;24+}25+26+/** The accountable person, as a landing's author: their handle at the platform's users domain. */27+export const authorLine = (handle: Handle): Person => ({28+ email: `${handle}@users.${Brand.domain}`,29+ name: handle,30+});31+32+/** The platform, which commits every landing. */33+export const committerLine: Person = {34+ email: `platform@${Brand.domain}`,35+ name: Brand.name,36+};37+38+/** What a landing commit's message is made of; every trailer comes from the platform's own rows. */39+export interface LandingMessage {40+ readonly subject: string;41+ readonly body?: string;42+ readonly credits: readonly Credit[];43+ /** The agents people worked through: a disclosure, never credit. */44+ readonly assisted: readonly AgentTrailer[];45+ readonly ask?: { readonly project: ProjectName; readonly ask: AskId };46+ readonly verdict?: {47+ readonly patchId: PatchId;48+ readonly checkVersion: CheckVersion;49+ };50+ /** The `Held-back:` value, such as `export 7/7 @ sha256:…`, without its key. */51+ readonly heldBack?: string;52+ readonly requestId?: RequestId;53+}54+55+const ASSISTED = "Assisted-by";56+57+/** One line, so no value or subject can open a paragraph or a trailer of its own. */58+const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();59+60+const personOf = (handle: Handle) => {61+ const { email, name } = authorLine(handle);62+63+ return `${name} <${email}>`;64+};65+66+// The kernel's `AGENT:MODEL` shape, then whether the platform confirmed it:67+// `claude-code:opus-4 (verified)`. A harness name holds no colon.68+const agentOf = ({ harness, model, verified }: AgentTrailer) =>69+ `${oneLine(harness)}${model === undefined ? "" : `:${oneLine(model)}`} (${verified ? "verified" : "claimed"})`;70+71+const roleOrder = (role: CreditRole) => CreditRole.literals.indexOf(role);72+73+/**74+ * Credits in the order of `CreditRole`, people within a role in the order75+ * given, each (role, person) once: the same rows always make the same message.76+ */77+const ordered = (credits: readonly Credit[]) =>78+ Array.dedupeWith(79+ Array.sortWith(credits, ({ role }) => roleOrder(role), Order.Number),80+ (one: Credit, other: Credit) =>81+ one.role === other.role && one.handle === other.handle82+ );83+84+/**85+ * A landing commit's message: the subject, the body, then one trailer block86+ * that credits each person by role, discloses each agent as `Assisted-by`,87+ * and cites the ask, the verdict, the held-back result and the request.88+ */89+export const formatLanding = (input: LandingMessage): string => {90+ const trailers: readonly Trailer[] = [91+ ...ordered(input.credits).map(({ handle, role }) => ({92+ key: role,93+ value: personOf(handle),94+ })),95+ ...input.assisted.map((agent) => ({96+ key: ASSISTED,97+ value: agentOf(agent),98+ })),99+ ...(input.ask === undefined100+ ? []101+ : [{ key: "Ask", value: `${input.ask.project}/${input.ask.ask}` }]),102+ ...(input.verdict === undefined103+ ? []104+ : [105+ {106+ key: "Verdict",107+ value: `${input.verdict.patchId} ${oneLine(input.verdict.checkVersion)}`,108+ },109+ ]),110+ ...(input.heldBack === undefined111+ ? []112+ : [{ key: "Held-back", value: oneLine(input.heldBack) }]),113+ ...(input.requestId === undefined114+ ? []115+ : [{ key: "Request-id", value: input.requestId }]),116+ ];117+118+ const body = input.body?.trim() ?? "";119+120+ const paragraphs = [121+ oneLine(input.subject),122+ ...(body === "" ? [] : [body]),123+ ...(trailers.length === 0124+ ? []125+ : [trailers.map(({ key, value }) => `${key}: ${value}`).join("\n")]),126+ ];127+128+ return `${paragraphs.join("\n\n")}\n`;129+};130+131+// C's `isspace`, which git's trailer code tests with.132+const SPACE = /^[ \t\n\v\f\r]/u;133+134+const isSpace = (text: string) => SPACE.test(text);135+136+const isBlank = (line: string) => /^[ \t\n\v\f\r]*$/u.test(line);137+138+const isComment = (line: string) => line.startsWith("#");139+140+// Lines git counts as trailers whatever the rest of the paragraph holds.141+const GIT_GENERATED = ["Signed-off-by: ", "(cherry picked from commit "];142+143+/**144+ * Where a trailer's key ends: letters, digits and dashes, then optional145+ * blanks, then `:`. `-1` when the line has no key (git's `find_separator`).146+ */147+const separatorOf = (line: string) => {148+ let blank = false;149+150+ for (let at = 0; at < line.length; at += 1) {151+ const char = line.charAt(at);152+153+ if (char === ":") {154+ return at;155+ }156+157+ if (!blank && /^[A-Za-z0-9-]$/u.test(char)) {158+ continue;159+ }160+161+ if (at > 0 && (char === " " || char === "\t")) {162+ blank = true;163+ continue;164+ }165+166+ break;167+ }168+169+ return -1;170+};171+172+/** The message's lines up to a `---` divider, less trailing comments and empty lines. */173+const logLines = (message: string) => {174+ const lines = message.split("\n");175+ const ended = message.endsWith("\n");176+177+ if (ended) {178+ lines.pop();179+ }180+181+ const divider = lines.findIndex(182+ (line, at) =>183+ line.startsWith("---") &&184+ (line.length > 3185+ ? isSpace(line.slice(3))186+ : at < lines.length - 1 || ended)187+ );188+189+ const kept = divider === -1 ? lines : lines.slice(0, divider);190+ let end = kept.length;191+192+ while (end > 0 && (kept[end - 1] === "" || isComment(kept[end - 1] ?? ""))) {193+ end -= 1;194+ }195+196+ return kept.slice(0, end);197+};198+199+/**200+ * Where the trailer block starts, by git's rule: the last paragraph after201+ * the title, if all its lines are trailers, or if one is a sign-off and at202+ * least a quarter are trailers.203+ */204+const blockStart = (lines: readonly string[]): Option.Option<number> => {205+ const titleEnd = lines.findIndex((line) => !isComment(line) && isBlank(line));206+207+ if (titleEnd === -1) {208+ return Option.none();209+ }210+211+ let onlySpaces = true;212+ let recognized = false;213+ let trailerLines = 0;214+ let otherLines = 0;215+ let continuations = 0;216+217+ for (let at = lines.length - 1; at >= titleEnd; at -= 1) {218+ const line = lines[at] ?? "";219+220+ if (isComment(line)) {221+ otherLines += continuations;222+ continuations = 0;223+ } else if (isBlank(line)) {224+ if (!onlySpaces) {225+ otherLines += continuations;226+227+ return (recognized && trailerLines * 3 >= otherLines) ||228+ (trailerLines > 0 && otherLines === 0)229+ ? Option.some(at + 1)230+ : Option.none();231+ }232+ } else {233+ onlySpaces = false;234+235+ if (GIT_GENERATED.some((prefix) => line.startsWith(prefix))) {236+ trailerLines += 1;237+ continuations = 0;238+ recognized = true;239+ } else if (separatorOf(line) >= 1 && !isSpace(line)) {240+ trailerLines += 1;241+ continuations = 0;242+ } else if (isSpace(line)) {243+ continuations += 1;244+ } else {245+ otherLines += 1 + continuations;246+ continuations = 0;247+ }248+ }249+ }250+251+ return Option.none();252+};253+254+/** A value with its continuation lines folded to single spaces. */255+const unfold = (value: string) =>256+ value257+ .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "")258+ .replaceAll(/\n[ \t\n\v\f\r]*/gu, " ")259+ .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "");260+261+/**262+ * A message's trailers in order, as `git interpret-trailers --parse` reads263+ * them: keys and values trimmed, continuation lines unfolded, lines that are264+ * not trailers left out.265+ */266+export const parseTrailers = (message: string): readonly Trailer[] => {267+ const lines = logLines(message);268+269+ return Option.match(blockStart(lines), {270+ onNone: () => [],271+ onSome: (start) => {272+ // Each item is one trailer with its continuation lines, or another line.273+ const items: string[] = [];274+ let open = false;275+276+ for (const line of lines.slice(start)) {277+ if (open && isSpace(line)) {278+ items.push(`${items.pop() ?? ""}\n${line}`);279+ } else {280+ items.push(line);281+ open = separatorOf(line) >= 1;282+ }283+ }284+285+ return items.flatMap((item) => {286+ const cut = separatorOf(item);287+288+ return isComment(item) || cut < 1289+ ? []290+ : [291+ {292+ key: item.slice(0, cut).trim(),293+ value: unfold(item.slice(cut + 1)),294+ },295+ ];296+ });297+ },298+ });299+};300+301+const escaped = (text: string) =>302+ text.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`);303+304+// Exactly what `personOf` writes: a handle at the platform's users domain.305+const PERSON = new RegExp(306+ `^(?<handle>[A-Za-z0-9][A-Za-z0-9-]*) <\\k<handle>@users\\.${escaped(Brand.domain)}>$`,307+ "u"308+);309+310+const AGENT =311+ /^(?<harness>[^:]+?)(?::(?<model>.+))? \((?<mark>claimed|verified)\)$/u;312+313+const decodeRole = Schema.decodeUnknownOption(CreditRole);314+315+const decodeHandle = Schema.decodeUnknownOption(Handle);316+317+const creditOf = ({ key, value }: Trailer): Option.Option<Credit> =>318+ Option.gen(function* () {319+ const role = yield* decodeRole(320+ CreditRole.literals.find(321+ (literal) => literal.toLowerCase() === key.toLowerCase()322+ )323+ );324+325+ const handle = yield* decodeHandle(PERSON.exec(value)?.groups?.handle);326+327+ return { handle, role };328+ });329+330+const agentFrom = ({ key, value }: Trailer): Option.Option<AgentTrailer> => {331+ const groups = AGENT.exec(value)?.groups;332+333+ if (key.toLowerCase() !== ASSISTED.toLowerCase() || groups === undefined) {334+ return Option.none();335+ }336+337+ const harness = groups.harness ?? "";338+ const { model } = groups;339+ const verified = groups.mark === "verified";340+341+ return Option.some(342+ model === undefined ? { harness, verified } : { harness, model, verified }343+ );344+};345+346+/** The people a landing credits, and the agents it discloses. */347+export interface LandingCredits {348+ readonly credits: readonly Credit[];349+ readonly assisted: readonly AgentTrailer[];350+}351+352+/**353+ * Who a landing credits, and which agents it discloses. Only trailers the354+ * platform writes count: a credit names a platform handle by `authorLine`,355+ * and `Assisted-by` is never credit.356+ */357+export const creditsOf = (message: string): LandingCredits => {358+ const trailers = parseTrailers(message);359+360+ return {361+ assisted: Array.getSomes(trailers.map(agentFrom)),362+ credits: Array.getSomes(trailers.map(creditOf)),363+ };364+};added:packages/git/src/tree-diff.ts+334 added
1+import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2+import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3+import { BlobSha, RepoPath } from "@repo/protocol/ids";4+import type { RepoName, TreeSha } from "@repo/protocol/ids";5+import { Array, Effect, Option, Order } from "effect";6+7+/**8+ * One file an answer changed, with its blob ids before and after. The same9+ * shape as the gate's `Change` (`@repo/gate/facts`), which git cannot import.10+ */11+export interface Change {12+ readonly path: RepoPath;13+ readonly status: "added" | "modified" | "deleted";14+ readonly before?: BlobSha;15+ readonly after?: BlobSha;16+}17+18+/** A line a change added, numbered from 1 in the new file. */19+export interface AddedLine {20+ readonly line: number;21+ readonly text: string;22+}23+24+// Subtrees read at once: each read is a call to the store.25+const READS = { concurrency: 8 } as const;26+27+const entriesOf = (repo: RepoName, tree: Option.Option<string>) =>28+ Option.match(tree, {29+ onNone: () => Effect.succeed<readonly TreeEntry[]>([]),30+ onSome: (id) =>31+ RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(32+ Effect.flatMap(33+ Option.match({34+ onNone: () => Effect.die(`${repo} has no tree ${id}`),35+ onSome: Effect.succeed,36+ })37+ )38+ ),39+ });40+41+const treeIdOf = (entry: TreeEntry | undefined) =>42+ entry?.type === "tree" ? Option.some(entry.sha) : Option.none();43+44+// A submodule's pointer counts as a file at its path, so a change to it is seen.45+const fileIdOf = (entry: TreeEntry | undefined) =>46+ entry === undefined || entry.type === "tree"47+ ? undefined48+ : BlobSha.make(entry.sha);49+50+const fileChange = (51+ path: string,52+ before: BlobSha | undefined,53+ after: BlobSha | undefined54+): readonly Change[] => {55+ const at = RepoPath.make(path);56+57+ if (before !== undefined && after !== undefined) {58+ return [{ after, before, path: at, status: "modified" }];59+ }60+61+ if (before !== undefined) {62+ return [{ before, path: at, status: "deleted" }];63+ }64+65+ return after === undefined ? [] : [{ after, path: at, status: "added" }];66+};67+68+const walk = (69+ repo: RepoName,70+ prefix: string,71+ base: Option.Option<string>,72+ head: Option.Option<string>73+): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>74+ Effect.gen(function* () {75+ const [before, after] = yield* Effect.all(76+ [entriesOf(repo, base), entriesOf(repo, head)],77+ READS78+ );79+80+ const beforeByName = new Map(before.map((entry) => [entry.name, entry]));81+ const afterByName = new Map(after.map((entry) => [entry.name, entry]));82+83+ const names = Array.sort(84+ new Set([...beforeByName.keys(), ...afterByName.keys()]),85+ Order.String86+ );87+88+ const changed = yield* Effect.forEach(89+ names,90+ (name) => {91+ const old = beforeByName.get(name);92+ const next = afterByName.get(name);93+94+ // The same id and mode: nothing under it changed, so it is never read.95+ if (old?.sha === next?.sha && old?.mode === next?.mode) {96+ return Effect.succeed<readonly Change[]>([]);97+ }98+99+ const path = `${prefix}${name}`;100+ const files = fileChange(path, fileIdOf(old), fileIdOf(next));101+ const inside = [treeIdOf(old), treeIdOf(next)] as const;102+103+ return Option.isNone(inside[0]) && Option.isNone(inside[1])104+ ? Effect.succeed(files)105+ : walk(repo, `${path}/`, inside[0], inside[1]).pipe(106+ Effect.map((nested) => [...files, ...nested])107+ );108+ },109+ READS110+ );111+112+ return changed.flat();113+ });114+115+/**116+ * The files that differ between two trees of `repo`, read through the117+ * `RepoHost` port alone: it walks both roots and descends only into subtrees118+ * whose ids differ, since the store has no diff of its own.119+ */120+export const treeDiff = (121+ repo: RepoName,122+ base: TreeSha,123+ head: TreeSha124+): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>125+ walk(repo, "", Option.some(base), Option.some(head));126+127+// git's own test: a NUL among the first bytes means the blob is not text.128+const SNIFF = 8192;129+130+const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);131+132+const linesOf = (bytes: Uint8Array) => {133+ const text = new TextDecoder().decode(bytes);134+ const lines = text.split("\n");135+136+ if (text.endsWith("\n")) {137+ lines.pop();138+ }139+140+ return lines;141+};142+143+// Past this many edits the diff stops looking for the shortest script.144+const MAX_EDITS = 1024;145+146+const at = (values: Int32Array, index: number) => values[index] ?? 0;147+148+/**149+ * Indexes in `next` that the edit script ending at `(n, m)` inserts, read150+ * back from `trace`, where `trace[d]` holds diagonals `-d..d` after `d` edits.151+ */152+const insertsFrom = (153+ trace: readonly Int32Array[],154+ ends: { readonly n: number; readonly m: number }155+) => {156+ const inserts: number[] = [];157+ let x = ends.n;158+ let y = ends.m;159+160+ for (let edits = trace.length - 1; edits > 0; edits -= 1) {161+ const previous = trace[edits - 1] ?? new Int32Array();162+ const diagonal = x - y;163+164+ const reached = (k: number) => at(previous, k + edits - 1);165+166+ const down =167+ diagonal === -edits ||168+ (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));169+170+ const from = down ? diagonal + 1 : diagonal - 1;171+172+ x = reached(from);173+ y = x - from;174+175+ if (down) {176+ inserts.push(y);177+ }178+ }179+180+ return inserts.toReversed();181+};182+183+/**184+ * Lines of `next` with no partner in `previous`, matched by count: the185+ * fallback for a rewrite too large for the shortest script.186+ */187+const unmatched = (previous: readonly string[], next: readonly string[]) => {188+ const left = new Map<string, number>();189+190+ for (const line of previous) {191+ left.set(line, (left.get(line) ?? 0) + 1);192+ }193+194+ return next.flatMap((line, index) => {195+ const count = left.get(line) ?? 0;196+197+ left.set(line, count - 1);198+199+ return count > 0 ? [] : [index];200+ });201+};202+203+/**204+ * Indexes of the lines of `next` a shortest edit script from `previous`205+ * inserts (Myers' O(ND) diff).206+ */207+const myers = (previous: readonly string[], next: readonly string[]) => {208+ const n = previous.length;209+ const m = next.length;210+ const limit = Math.min(n + m, MAX_EDITS);211+ const offset = limit + 1;212+ const reach = new Int32Array(2 * limit + 3);213+ const trace: Int32Array[] = [];214+215+ for (let edits = 0; edits <= limit; edits += 1) {216+ for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {217+ let x =218+ diagonal === -edits ||219+ (diagonal !== edits &&220+ at(reach, offset + diagonal - 1) < at(reach, offset + diagonal + 1))221+ ? at(reach, offset + diagonal + 1)222+ : at(reach, offset + diagonal - 1) + 1;223+224+ let y = x - diagonal;225+226+ while (x < n && y < m && previous[x] === next[y]) {227+ x += 1;228+ y += 1;229+ }230+231+ reach[offset + diagonal] = x;232+233+ if (x >= n && y >= m) {234+ trace.push(reach.slice(offset - edits, offset + edits + 1));235+236+ return insertsFrom(trace, { m, n });237+ }238+ }239+240+ trace.push(reach.slice(offset - edits, offset + edits + 1));241+ }242+243+ return unmatched(previous, next);244+};245+246+/** The lines of `next` that are not in `previous`, numbered from 1. */247+const added = (248+ previous: readonly string[],249+ next: readonly string[]250+): readonly AddedLine[] => {251+ let start = 0;252+253+ while (254+ start < previous.length &&255+ start < next.length &&256+ previous[start] === next[start]257+ ) {258+ start += 1;259+ }260+261+ let end = 0;262+263+ while (264+ end < previous.length - start &&265+ end < next.length - start &&266+ previous[previous.length - 1 - end] === next[next.length - 1 - end]267+ ) {268+ end += 1;269+ }270+271+ const middle = myers(272+ previous.slice(start, previous.length - end),273+ next.slice(start, next.length - end)274+ );275+276+ return middle.map((index) => ({277+ line: start + index + 1,278+ text: next[start + index] ?? "",279+ }));280+};281+282+const blobOf = (repo: RepoName, blob: BlobSha) =>283+ RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(284+ Effect.flatMap(285+ Option.match({286+ onNone: () => Effect.die(`${repo} has no blob ${blob}`),287+ onSome: Effect.succeed,288+ })289+ )290+ );291+292+const textOf = (repo: RepoName, blob: BlobSha | undefined) =>293+ blob === undefined294+ ? Effect.succeedSome<readonly string[]>([])295+ : blobOf(repo, blob).pipe(296+ Effect.map((bytes) =>297+ isBinary(bytes) ? Option.none() : Option.some(linesOf(bytes))298+ )299+ );300+301+/**302+ * The lines each added or modified file gained, by a line diff of its blobs.303+ * A binary blob (a NUL in its first 8 KiB) reports no lines.304+ */305+export const addedLines = (306+ repo: RepoName,307+ changes: readonly Change[]308+): Effect.Effect<309+ ReadonlyMap<RepoPath, readonly AddedLine[]>,310+ RepoNotFound,311+ RepoHost312+> =>313+ Effect.forEach(314+ changes.filter((change) => change.after !== undefined),315+ (change) =>316+ Effect.gen(function* () {317+ const [previous, next] = yield* Effect.all(318+ [textOf(repo, change.before), textOf(repo, change.after)],319+ READS320+ );321+322+ const lines = Option.match(next, {323+ onNone: () => [],324+ onSome: (text) =>325+ added(326+ Option.getOrElse(previous, () => []),327+ text328+ ),329+ });330+331+ return [change.path, lines] as const;332+ }),333+ READS334+ ).pipe(Effect.map((entries) => new Map(entries)));added:packages/git/test/notes.test.ts+285 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import {4+ ObjectId,5+ RefName,6+ RefOutcome,7+ RepoHost,8+ RepoName,9+} from "@repo/artifacts/repo-host";10+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";11+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";12+import { Brand } from "@repo/brand";13+import { Verdict } from "@repo/protocol/domain/answer";14+import { Outcome } from "@repo/protocol/domain/outcome";15+import {16+ AskId,17+ CheckVersion,18+ CommitSha,19+ LaneName,20+ PatchId,21+ ProjectName,22+ TreeSha,23+} from "@repo/protocol/ids";24+import { gitOk } from "@repo/testkit/git";25+import { gitClient } from "@repo/testkit/git-client";26+import { DateTime, Effect, FileSystem, Layer, Option, Schema } from "effect";27+28+import { noteCommit, notesRef } from "../src/notes.ts";29+import type { ScratchSource } from "../src/notes.ts";30+import { committerLine } from "../src/trailers.ts";31+32+const repo = RepoName.make("demo");33+34+const main = RefName.make("refs/heads/main");35+36+/** A verdict on the answer whose head is `head`. */37+const verdictOn = (head: CommitSha) =>38+ Verdict.make({39+ ask: AskId.make("week-at-year-end"),40+ at: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),41+ base: CommitSha.make("1".repeat(40)),42+ checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),43+ head,44+ heldBack: [],45+ lanes: [46+ {47+ command: "bun test",48+ durationMs: 1200,49+ lane: LaneName.make("unit"),50+ result: "passed",51+ },52+ ],53+ outcome: Outcome.cases.Checking.make({ stage: "checks" }),54+ patchId: PatchId.make("2".repeat(64)),55+ project: ProjectName.make("datekit"),56+ stage: "checks",57+ tree: TreeSha.make("3".repeat(40)),58+ verifier: "platform",59+ });60+61+const encodeVerdict = Schema.encodeEffect(Verdict);62+63+/** The note's text as a verdict, encoded again: compared with what was written. */64+const reencoded = (note: Option.Option<string>) =>65+ Schema.decodeEffect(Schema.fromJsonString(Verdict))(66+ Option.getOrElse(note, () => "")67+ ).pipe(Effect.flatMap(encodeVerdict));68+69+const now = DateTime.makeUnsafe("2026-10-07T12:30:00Z");70+71+/** Two commits on `demo`'s main, the targets the notes are written on. */72+const targets = Effect.gen(function* () {73+ const repos = yield* RepoHost;74+ const client = yield* gitClient(memoryFs());75+ const first = yield* client.commit("first", [["a.ts", "1\n"]]);76+ const second = yield* client.commit("second", [["a.ts", "2\n"]], [first]);77+78+ yield* repos.create(repo);79+ yield* repos.push(repo, client.source, [80+ { from: Option.none(), ref: main, to: second },81+ ]);82+83+ return { first, second };84+});85+86+/**87+ * The notes commit at `notesRef`, the names in its tree, and the note on88+ * `target`: read through the port as plain git would find them.89+ */90+const notesThroughPort = (target: CommitSha) =>91+ Effect.gen(function* () {92+ const repos = yield* RepoHost;93+ const tip = (yield* repos.refs(repo)).get(notesRef);94+95+ if (tip === undefined) {96+ return yield* Effect.die(`${notesRef} is not on ${repo}`);97+ }98+99+ const commit = Option.getOrThrow(yield* repos.readCommit(repo, tip));100+101+ const entries = Option.getOrThrow(yield* repos.readTree(repo, commit.tree));102+103+ const entry = entries.find(({ name }) => name === target);104+105+ const blob =106+ entry === undefined107+ ? Option.none()108+ : yield* repos.readBlob(repo, ObjectId.make(entry.sha));109+110+ return {111+ commit,112+ names: entries.map(({ name }) => name),113+ note: Option.map(blob, (bytes) => new TextDecoder().decode(bytes)),114+ };115+ });116+117+/** Copies a scratch git directory onto disk, so git itself can read it. */118+const onDisk = (source: ScratchSource) =>119+ Effect.gen(function* () {120+ const fs = yield* FileSystem.FileSystem;121+ const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);122+ const { promises } = source.fs;123+124+ const copy = (path: string): Effect.Effect<void> =>125+ Effect.gen(function* () {126+ const stat = yield* Effect.promise(() => promises.stat(path));127+128+ if (stat.isDirectory()) {129+ const names = yield* Effect.promise(() => promises.readdir(path));130+131+ yield* fs132+ .makeDirectory(`${root}${path}`, { recursive: true })133+ .pipe(Effect.orDie);134+ yield* Effect.forEach(names, (name) => copy(`${path}/${name}`));135+136+ return;137+ }138+139+ const bytes = yield* Effect.promise(() => promises.readFile(path));140+141+ yield* fs142+ .writeFile(143+ `${root}${path}`,144+ bytes instanceof Uint8Array145+ ? bytes146+ : new TextEncoder().encode(bytes)147+ )148+ .pipe(Effect.orDie);149+ });150+151+ yield* copy(source.gitdir);152+153+ return `${root}${source.gitdir}`;154+ });155+156+describe("verdicts as git notes", () => {157+ it.live(158+ "writes a verdict as a JSON note that the port and git both read",159+ () =>160+ Effect.gen(function* () {161+ const repos = yield* RepoHost;162+ const { first } = yield* targets;163+ const verdict = verdictOn(first);164+165+ const { commit, source } = yield* noteCommit({166+ notesParent: Option.none(),167+ now,168+ repo,169+ target: first,170+ verdict,171+ });172+173+ expect(notesRef).toBe(`refs/notes/${Brand.slug}`);174+ expect(175+ yield* repos.push(repo, source, [176+ { from: Option.none(), ref: notesRef, to: commit },177+ ])178+ ).toStrictEqual([RefOutcome.Updated({ ref: notesRef })]);179+180+ const read = yield* notesThroughPort(first);181+182+ expect({183+ author: read.commit.author,184+ committer: read.commit.committer,185+ names: read.names,186+ parents: read.commit.parents,187+ sha: read.commit.sha,188+ }).toStrictEqual({189+ author: committerLine,190+ committer: committerLine,191+ names: [first],192+ parents: [],193+ sha: commit,194+ });195+ expect(yield* reencoded(read.note)).toStrictEqual(196+ yield* encodeVerdict(verdict)197+ );198+199+ // git's own notes layout: `git notes show` finds the same note.200+ const gitdir = yield* onDisk(source);201+202+ expect(203+ yield* gitOk(204+ gitdir,205+ `--git-dir=${gitdir}`,206+ "notes",207+ `--ref=${Brand.slug}`,208+ "show",209+ first210+ )211+ ).toBe(Option.getOrElse(read.note, () => "").trim());212+ }).pipe(213+ Effect.scoped,214+ Effect.provide(Layer.mergeAll(RepoHostMemory, NodeServices.layer))215+ ),216+ 20_000217+ );218+219+ it.live(220+ "keeps every earlier note when it writes the next",221+ () =>222+ Effect.gen(function* () {223+ const repos = yield* RepoHost;224+ const { first, second } = yield* targets;225+226+ const one = yield* noteCommit({227+ notesParent: Option.none(),228+ now,229+ repo,230+ target: first,231+ verdict: verdictOn(first),232+ });233+234+ yield* repos.push(repo, one.source, [235+ { from: Option.none(), ref: notesRef, to: one.commit },236+ ]);237+238+ const two = yield* noteCommit({239+ notesParent: Option.some(one.commit),240+ now,241+ repo,242+ target: second,243+ verdict: verdictOn(second),244+ });245+246+ expect(247+ yield* repos.push(repo, two.source, [248+ { from: Option.some(one.commit), ref: notesRef, to: two.commit },249+ ])250+ ).toStrictEqual([RefOutcome.Updated({ ref: notesRef })]);251+252+ const read = yield* notesThroughPort(first);253+254+ expect({255+ names: new Set(read.names),256+ parents: read.commit.parents,257+ }).toStrictEqual({258+ names: new Set([first, second]),259+ parents: [one.commit],260+ });261+ expect(yield* reencoded(read.note)).toStrictEqual(262+ yield* encodeVerdict(verdictOn(first))263+ );264+265+ // git lists both notes from the second notes commit's tree.266+ const gitdir = yield* onDisk(two.source);267+268+ const listed = yield* gitOk(269+ gitdir,270+ `--git-dir=${gitdir}`,271+ "notes",272+ `--ref=${Brand.slug}`,273+ "list"274+ );275+276+ expect(277+ new Set(listed.split("\n").map((line) => line.split(" ")[1]))278+ ).toStrictEqual(new Set([first, second]));279+ }).pipe(280+ Effect.scoped,281+ Effect.provide(Layer.mergeAll(RepoHostMemory, NodeServices.layer))282+ ),283+ 20_000284+ );285+});added:packages/git/test/patch-id.test.ts+58 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { describe, expect, it } from "@effect/vitest";import { BlobSha, RepoPath } from "@repo/protocol/ids";import { Effect } from "effect";
import { patchId } from "../src/patch-id.ts";import type { Change } from "../src/tree-diff.ts";
const blob = (digit: string) => BlobSha.make(digit.repeat(40));
const modified: Change = { after: blob("2"), before: blob("1"), path: RepoPath.make("src/a.ts"), status: "modified",};
const added: Change = { after: blob("3"), path: RepoPath.make("src/b.ts"), status: "added",};
const deleted: Change = { before: blob("4"), path: RepoPath.make("docs/x.md"), status: "deleted",};
describe("an answer's patch id", () => { it.effect("is SHA-256 over the sorted (path, before, after) lines", () => Effect.gen(function* () { // `printf 'src/a.ts\0<1×40>\0<2×40>\nsrc/b.ts\0\0<3×40>\n' | sha256sum` expect(yield* patchId([added, modified])).toBe( "41cf8262f0d7d26011b85d7576fb81865b70e05c5f5d0668b6420045d3b1091d" ); }) );
it.effect("is the same for the same change set in any order", () => Effect.gen(function* () { const one = yield* patchId([modified, added, deleted]);
expect(yield* patchId([deleted, modified, added])).toBe(one); expect(yield* patchId([added, deleted, modified])).toBe(one); expect(one).toMatch(/^[0-9a-f]{64}$/u); }) );
it.effect("moves when one file's new blob moves", () => Effect.gen(function* () { const one = yield* patchId([modified, added]);
expect( yield* patchId([{ ...modified, after: blob("5") }, added]) ).not.toBe(one); }) );});added:packages/git/test/trailers.test.ts+168 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Brand } from "@repo/brand";4+import {5+ AskId,6+ CheckVersion,7+ Handle,8+ PatchId,9+ ProjectName,10+ RequestId,11+} from "@repo/protocol/ids";12+import { gitOk } from "@repo/testkit/git";13+import { Effect, FileSystem } from "effect";14+15+import {16+ authorLine,17+ committerLine,18+ creditsOf,19+ formatLanding,20+ parseTrailers,21+} from "../src/trailers.ts";22+23+const alice = Handle.make("alice");24+25+const bob = Handle.make("bob");26+27+const carol = Handle.make("carol");28+29+const landing = formatLanding({30+ ask: {31+ ask: AskId.make("week-at-year-end"),32+ project: ProjectName.make("datekit"),33+ },34+ assisted: [{ harness: "claude-code", model: "opus-4", verified: true }],35+ body: "The ISO week of December 31 was one too high.\nNow it rolls over.",36+ credits: [37+ { handle: alice, role: "Asked-by" },38+ { handle: bob, role: "Signed-off-by" },39+ { handle: carol, role: "Decided-by" },40+ ],41+ subject: "Give December 31 the week it belongs to",42+});43+44+/** What git itself reads as `message`'s trailers, one `key: value` per line. */45+const gitTrailers = (message: string) =>46+ Effect.gen(function* () {47+ const fs = yield* FileSystem.FileSystem;48+ const dir = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);49+50+ yield* fs.writeFileString(`${dir}/message`, message).pipe(Effect.orDie);51+52+ const parsed = yield* gitOk(53+ dir,54+ "interpret-trailers",55+ "--parse",56+ "message"57+ );58+59+ return parsed === ""60+ ? []61+ : parsed.split("\n").map((line) => {62+ const cut = line.indexOf(": ");63+64+ return { key: line.slice(0, cut), value: line.slice(cut + 2) };65+ });66+ }).pipe(Effect.scoped);67+68+// Messages whose last paragraph tests git's rules: a title is never trailers,69+// a mixed paragraph counts only with a sign-off and 25% trailers, an indented70+// line continues the trailer above it, and `---` ends the message.71+const edges = [72+ "Only a title: Not-a-trailer\n",73+ "Title\n\nProse that ends.\nAcked-by: someone\n",74+ "Title\n\nProse that ends.\nSigned-off-by: bob\nAcked-by: someone\n",75+ "Title\n\nFixes: the parser\n and the printer\nReviewed-by : carol\n",76+ "Title\n\nBody\n\nReported-by: dee\n---\nNot-read: after the divider\n",77+ "Title\n\nBody\n\nSee-also: one\n\n \n",78+];79+80+describe("landing trailers", () => {81+ it.live(82+ "git reads a landing's trailers as the platform wrote them, in order",83+ () =>84+ Effect.gen(function* () {85+ const expected = [86+ { key: "Asked-by", value: `alice <alice@users.${Brand.domain}>` },87+ { key: "Signed-off-by", value: `bob <bob@users.${Brand.domain}>` },88+ { key: "Decided-by", value: `carol <carol@users.${Brand.domain}>` },89+ { key: "Assisted-by", value: "claude-code:opus-4 (verified)" },90+ { key: "Ask", value: "datekit/week-at-year-end" },91+ ];92+93+ expect(yield* gitTrailers(landing)).toStrictEqual(expected);94+ expect(parseTrailers(landing)).toStrictEqual(expected);95+ expect(landing.split("\n\n")[0]).toBe(96+ "Give December 31 the week it belongs to"97+ );98+ }).pipe(Effect.provide(NodeServices.layer)),99+ 20_000100+ );101+102+ it.live(103+ "parses any message's trailers the way git does",104+ () =>105+ Effect.gen(function* () {106+ const read = yield* Effect.forEach(edges, (message) =>107+ Effect.map(gitTrailers(message), (trailers) => ({108+ message,109+ trailers,110+ }))111+ );112+113+ expect(114+ edges.map((message) => ({115+ message,116+ trailers: parseTrailers(message),117+ }))118+ ).toStrictEqual(read);119+ }).pipe(Effect.provide(NodeServices.layer)),120+ 20_000121+ );122+123+ it("credits people and only people; Assisted-by is never credit", () => {124+ expect(creditsOf(landing)).toStrictEqual({125+ assisted: [{ harness: "claude-code", model: "opus-4", verified: true }],126+ credits: [127+ { handle: alice, role: "Asked-by" },128+ { handle: bob, role: "Signed-off-by" },129+ { handle: carol, role: "Decided-by" },130+ ],131+ });132+ });133+134+ it("cites the verdict, the held-back result and the request", () => {135+ expect(136+ parseTrailers(137+ formatLanding({138+ assisted: [{ harness: "pi", verified: false }],139+ credits: [{ handle: bob, role: "Signed-off-by" }],140+ heldBack: `export 7/7 @ sha256:${"a".repeat(64)}`,141+ requestId: RequestId.make("push-0123456789"),142+ subject: "Land it",143+ verdict: {144+ checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),145+ patchId: PatchId.make("b".repeat(64)),146+ },147+ })148+ )149+ ).toStrictEqual([150+ { key: "Signed-off-by", value: `bob <bob@users.${Brand.domain}>` },151+ { key: "Assisted-by", value: "pi (claimed)" },152+ { key: "Verdict", value: `${"b".repeat(64)} redThenGreen@0.0.0+abc` },153+ { key: "Held-back", value: `export 7/7 @ sha256:${"a".repeat(64)}` },154+ { key: "Request-id", value: "push-0123456789" },155+ ]);156+ });157+158+ it("names the answerer by handle and the platform as committer", () => {159+ expect(authorLine(alice)).toStrictEqual({160+ email: `alice@users.${Brand.domain}`,161+ name: "alice",162+ });163+ expect(committerLine).toStrictEqual({164+ email: `platform@${Brand.domain}`,165+ name: Brand.name,166+ });167+ });168+});added:packages/git/test/tree-diff.test.ts+299 added
1+import { describe, expect, it } from "@effect/vitest";2+import {3+ ObjectId,4+ RefName,5+ RepoHost,6+ RepoName,7+} from "@repo/artifacts/repo-host";8+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";9+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10+import { BlobSha, RepoPath, TreeSha } from "@repo/protocol/ids";11+import type { CommitSha } from "@repo/protocol/ids";12+import { gitClient } from "@repo/testkit/git-client";13+import type { Files } from "@repo/testkit/git-client";14+import { Effect, Layer, Option, Ref } from "effect";15+16+import { addedLines, treeDiff } from "../src/tree-diff.ts";17+18+const repo = RepoName.make("demo");19+20+const main = RefName.make("refs/heads/main");21+22+const before: Files = [23+ ["README.md", "demo\n"],24+ ["docs/x.md", "gone soon\n"],25+ ["lib/kept.ts", "export const kept = 1;\n"],26+ ["src/a.ts", "one\ntwo\nthree\nfour\n"],27+];28+29+const after: Files = [30+ ["README.md", "demo\n"],31+ ["assets/logo.bin", "\u0000PNG\nline\n"],32+ ["lib/kept.ts", "export const kept = 1;\n"],33+ ["src/a.ts", "one\nbetween\ntwo\nthree\nFOUR\nfive\n"],34+ ["src/b/c.ts", "export const c = 3;\n"],35+];36+37+/** The memory store, with each tree id `readTree` is asked for written to `reads`. */38+const countedBy = (reads: Ref.Ref<readonly string[]>) =>39+ Layer.effect(40+ RepoHost,41+ Effect.gen(function* () {42+ const host = yield* RepoHost;43+44+ return RepoHost.of({45+ ...host,46+ readTree: (name, tree) =>47+ Ref.update(reads, (all) => [...all, tree]).pipe(48+ Effect.andThen(host.readTree(name, tree))49+ ),50+ });51+ })52+ ).pipe(Layer.provide(RepoHostMemory));53+54+/** Two commits in `demo`, and the ids of their trees and blobs as git wrote them. */55+const twoCommits = Effect.gen(function* () {56+ const repos = yield* RepoHost;57+ const client = yield* gitClient(memoryFs());58+ const first = yield* client.commit("before", before);59+ const second = yield* client.commit("after", after, [first]);60+61+ yield* repos.create(repo);62+ yield* repos.push(repo, client.source, [63+ { from: Option.none(), ref: main, to: second },64+ ]);65+66+ const treeOf = (sha: CommitSha) =>67+ repos.readCommit(repo, sha).pipe(68+ Effect.map(Option.getOrThrow),69+ Effect.map(({ tree }) => TreeSha.make(tree))70+ );71+72+ /** The id of the entry at `path` under `root`. */73+ const idAt = (root: string, path: string): Effect.Effect<string> =>74+ Effect.gen(function* () {75+ const [head = "", ...rest] = path.split("/");76+77+ const entries = yield* repos78+ .readTree(repo, ObjectId.make(root))79+ .pipe(Effect.orDie, Effect.map(Option.getOrThrow));80+81+ const entry = entries.find(({ name }) => name === head);82+83+ if (entry === undefined) {84+ return yield* Effect.die(`no ${path}`);85+ }86+87+ return rest.length === 088+ ? entry.sha89+ : yield* idAt(entry.sha, rest.join("/"));90+ });91+92+ const base = yield* treeOf(first);93+ const head = yield* treeOf(second);94+95+ return {96+ base,97+ blob: (tree: TreeSha, path: string) =>98+ idAt(tree, path).pipe(Effect.map((id) => BlobSha.make(id))),99+ head,100+ tree: (tree: TreeSha, path: string) => idAt(tree, path),101+ };102+});103+104+/** Lines from a three-word alphabet, from a fixed seed (Park and Miller's generator). */105+const randomFiles = (cases: number) => {106+ let state = 20_261_007;107+108+ const next = (below: number) => {109+ state = (state * 16_807) % 2_147_483_647;110+111+ return state % below;112+ };113+114+ const file = () =>115+ Array.from({ length: next(9) }, () => ["a", "b", "c"][next(3)] ?? "a");116+117+ return Array.from({ length: cases }, () => [file(), file()] as const);118+};119+120+/** The length of a longest common subsequence, by the textbook table. */121+const lcs = (one: readonly string[], other: readonly string[]) => {122+ const table = Array.from({ length: one.length + 1 }, () =>123+ Array.from({ length: other.length + 1 }, () => 0)124+ );125+126+ for (let i = 1; i <= one.length; i += 1) {127+ for (let j = 1; j <= other.length; j += 1) {128+ const row = table[i] ?? [];129+130+ row[j] =131+ one[i - 1] === other[j - 1]132+ ? (table[i - 1]?.[j - 1] ?? 0) + 1133+ : Math.max(table[i - 1]?.[j] ?? 0, row[j - 1] ?? 0);134+ }135+ }136+137+ return table[one.length]?.[other.length] ?? 0;138+};139+140+const text = (lines: readonly string[]) =>141+ lines.map((line) => `${line}\n`).join("");142+143+const isSubsequence = (part: readonly string[], whole: readonly string[]) => {144+ let found = 0;145+146+ for (const line of whole) {147+ if (line === part[found]) {148+ found += 1;149+ }150+ }151+152+ return found === part.length;153+};154+155+describe("the changes between two trees", () => {156+ it.effect("finds each added, modified and deleted file with its blobs", () =>157+ Effect.gen(function* () {158+ const { base, blob, head } = yield* twoCommits;159+ const changes = yield* treeDiff(repo, base, head);160+161+ expect(162+ changes.toSorted((one, other) => one.path.localeCompare(other.path))163+ ).toStrictEqual([164+ {165+ after: yield* blob(head, "assets/logo.bin"),166+ path: RepoPath.make("assets/logo.bin"),167+ status: "added",168+ },169+ {170+ before: yield* blob(base, "docs/x.md"),171+ path: RepoPath.make("docs/x.md"),172+ status: "deleted",173+ },174+ {175+ after: yield* blob(head, "src/a.ts"),176+ before: yield* blob(base, "src/a.ts"),177+ path: RepoPath.make("src/a.ts"),178+ status: "modified",179+ },180+ {181+ after: yield* blob(head, "src/b/c.ts"),182+ path: RepoPath.make("src/b/c.ts"),183+ status: "added",184+ },185+ ]);186+ }).pipe(Effect.provide(RepoHostMemory))187+ );188+189+ it.effect("never reads a subtree whose id did not change", () =>190+ Effect.gen(function* () {191+ const reads = yield* Ref.make<readonly string[]>([]);192+193+ yield* Effect.gen(function* () {194+ const { base, head, tree } = yield* twoCommits;195+ const kept = yield* tree(head, "lib");196+197+ expect(yield* tree(base, "lib")).toBe(kept);198+199+ yield* Ref.set(reads, []);200+ yield* treeDiff(repo, base, head);201+202+ const read = yield* Ref.get(reads);203+204+ expect(read).toContain(base);205+ expect(read).toContain(yield* tree(head, "src"));206+ expect(read).not.toContain(kept);207+ }).pipe(Effect.provide(countedBy(reads)));208+ })209+ );210+211+ it.effect("gives a modified file's new lines, numbered in the new file", () =>212+ Effect.gen(function* () {213+ const { base, head } = yield* twoCommits;214+ const lines = yield* addedLines(repo, yield* treeDiff(repo, base, head));215+216+ expect(lines.get(RepoPath.make("src/a.ts"))).toStrictEqual([217+ { line: 2, text: "between" },218+ { line: 5, text: "FOUR" },219+ { line: 6, text: "five" },220+ ]);221+ expect(lines.get(RepoPath.make("src/b/c.ts"))).toStrictEqual([222+ { line: 1, text: "export const c = 3;" },223+ ]);224+ expect(lines.get(RepoPath.make("assets/logo.bin"))).toStrictEqual([]);225+ expect([...lines.keys()]).not.toContain(RepoPath.make("docs/x.md"));226+ }).pipe(Effect.provide(RepoHostMemory))227+ );228+229+ it.effect(230+ "keeps a longest common run of lines and calls only the rest added",231+ () =>232+ Effect.gen(function* () {233+ const repos = yield* RepoHost;234+ const client = yield* gitClient(memoryFs());235+236+ const cases = yield* Effect.forEach(237+ randomFiles(60),238+ ([previous, next], index) =>239+ Effect.gen(function* () {240+ const name = RepoName.make(`case-${index}`);241+242+ const first = yield* client.commit("before", [243+ ["f.txt", text(previous)],244+ ]);245+246+ const second = yield* client.commit(247+ "after",248+ [["f.txt", text(next)]],249+ [first]250+ );251+252+ yield* repos.create(name);253+ yield* repos.push(name, client.source, [254+ { from: Option.none(), ref: main, to: second },255+ ]);256+257+ const treeOf = (sha: CommitSha) =>258+ repos259+ .readCommit(name, sha)260+ .pipe(261+ Effect.map((commit) =>262+ TreeSha.make(Option.getOrThrow(commit).tree)263+ )264+ );265+266+ const changes = yield* treeDiff(267+ name,268+ yield* treeOf(first),269+ yield* treeOf(second)270+ );271+272+ const lines = yield* addedLines(name, changes);273+274+ const fresh = new Set(275+ (lines.get(RepoPath.make("f.txt")) ?? []).map(276+ ({ line }) => line277+ )278+ );279+280+ const kept = next.filter((_, at) => !fresh.has(at + 1));281+282+ return {283+ kept: kept.length,284+ longest: lcs(previous, next),285+ pair: `${previous.join("")} -> ${next.join("")}`,286+ subsequence: isSubsequence(kept, previous),287+ };288+ })289+ );290+291+ // Every case keeps a common subsequence as long as any there is.292+ expect(293+ cases.filter(294+ ({ kept, longest, subsequence }) => !subsequence || kept !== longest295+ )296+ ).toStrictEqual([]);297+ }).pipe(Effect.provide(RepoHostMemory))298+ );299+});added:packages/git/test/upstream.test.ts+251 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Fetch } from "@repo/artifacts/fetch";3+import { RepoHost, RepoName, RepoNotFound } from "@repo/artifacts/repo-host";4+import type { TokenScope } from "@repo/artifacts/repo-host";5+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";6+import {7+ DateTime,8+ Duration,9+ Effect,10+ Layer,11+ Redacted,12+ Ref,13+ Stream,14+} from "effect";15+import { TestClock } from "effect/testing";16+17+import { Exchange, Upstream } from "../src/upstream.ts";18+import { UpstreamRepoHost } from "../src/upstream/repo-host.ts";19+20+const repo = RepoName.make("demo");21+22+/** A token the store minted: its scope, its secret and when it expires. */23+interface Minted {24+ readonly scope: TokenScope;25+ readonly secret: string;26+ readonly expiresAt: DateTime.Utc;27+}28+29+/** What one test sees: every request sent upstream and every token minted. */30+interface Seen {31+ readonly requests: Ref.Ref<readonly Request[]>;32+ readonly minted: Ref.Ref<readonly Minted[]>;33+}34+35+/**36+ * The memory store, minting tokens shaped like Artifacts' (a secret, then37+ * `?expires=`), with each mint written to `minted`.38+ */39+const store = (minted: Seen["minted"]) =>40+ Layer.effect(41+ RepoHost,42+ Effect.gen(function* () {43+ const host = yield* RepoHost;44+45+ return RepoHost.of({46+ ...host,47+ mintToken: (name, scope, ttl) =>48+ Effect.gen(function* () {49+ const token = yield* host.mintToken(name, scope, ttl);50+ const secret = Redacted.value(token.secret);51+52+ yield* Ref.update(minted, (all) => [53+ ...all,54+ { expiresAt: token.expiresAt, scope, secret },55+ ]);56+57+ return {58+ ...token,59+ secret: Redacted.make(60+ `${secret}?expires=${DateTime.toEpochMillis(token.expiresAt) / 1000}`61+ ),62+ };63+ }),64+ });65+ })66+ ).pipe(Layer.provide(RepoHostMemory));67+68+/** A `Fetch` that writes down each request and answers 200. */69+const recording = (requests: Seen["requests"]) =>70+ Layer.succeed(71+ Fetch,72+ Fetch.of({73+ fetch: (request) =>74+ Ref.update(requests, (all) => [...all, request]).pipe(75+ Effect.as(new Response("upstream"))76+ ),77+ })78+ );79+80+const world = (seen: Seen) =>81+ UpstreamRepoHost.pipe(82+ Layer.provideMerge(83+ Layer.mergeAll(store(seen.minted), recording(seen.requests))84+ )85+ );86+87+const advertise = Exchange.Advertise({88+ headers: new Headers({ "git-protocol": "version=2" }),89+ service: "git-upload-pack",90+});91+92+/** Runs `body` against the upstream over the memory store, with `demo` created. */93+const withUpstream = <A, E>(94+ body: (seen: Seen) => Effect.Effect<A, E, Upstream | RepoHost>95+) =>96+ Effect.gen(function* () {97+ const seen: Seen = {98+ minted: yield* Ref.make<readonly Minted[]>([]),99+ requests: yield* Ref.make<readonly Request[]>([]),100+ };101+102+ return yield* Effect.gen(function* () {103+ yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);104+105+ return yield* body(seen);106+ }).pipe(Effect.provide(world(seen)));107+ });108+109+const basic = (secret: string) => `Basic ${btoa(`x:${secret}`)}`;110+111+/** What the upstream sent: the method, the URL and the headers that matter. */112+const sent = (request: Request) => ({113+ authorization: request.headers.get("authorization"),114+ method: request.method,115+ protocol: request.headers.get("git-protocol"),116+ url: request.url,117+});118+119+describe("the upstream over RepoHost", () => {120+ it.effect(121+ "advertises refs at the repo's remote with a minted read token",122+ () =>123+ withUpstream((seen) =>124+ Effect.gen(function* () {125+ const upstream = yield* Upstream;126+ const response = yield* upstream.exchange(repo, advertise);127+ const remote = yield* RepoHost.use((host) => host.remote(repo));128+ const minted = yield* Ref.get(seen.minted);129+130+ expect(yield* Effect.promise(() => response.text())).toBe("upstream");131+ expect({132+ requests: (yield* Ref.get(seen.requests)).map(sent),133+ scopes: minted.map(({ scope }) => scope),134+ }).toStrictEqual({135+ requests: [136+ {137+ authorization: basic(minted[0]?.secret ?? ""),138+ method: "GET",139+ protocol: "version=2",140+ url: `${remote}/info/refs?service=git-upload-pack`,141+ },142+ ],143+ scopes: ["read"],144+ });145+ })146+ )147+ );148+149+ it.effect("posts a receive-pack call with a write token", () =>150+ withUpstream((seen) =>151+ Effect.gen(function* () {152+ const upstream = yield* Upstream;153+ const remote = yield* RepoHost.use((host) => host.remote(repo));154+155+ yield* upstream.exchange(156+ repo,157+ Exchange.Call({158+ body: Stream.toReadableStream(159+ Stream.make(new TextEncoder().encode("0000"))160+ ),161+ headers: new Headers({162+ "content-type": "application/x-git-receive-pack-request",163+ }),164+ service: "git-receive-pack",165+ })166+ );167+168+ const [request] = yield* Ref.get(seen.requests);169+ const minted = yield* Ref.get(seen.minted);170+171+ expect({172+ request: request === undefined ? undefined : sent(request),173+ scopes: minted.map(({ scope }) => scope),174+ }).toStrictEqual({175+ request: {176+ authorization: basic(minted[0]?.secret ?? ""),177+ method: "POST",178+ protocol: null,179+ url: `${remote}/git-receive-pack`,180+ },181+ scopes: ["write"],182+ });183+ expect(184+ yield* Effect.promise(() => request?.text() ?? Promise.resolve(""))185+ ).toBe("0000");186+ })187+ )188+ );189+190+ it.effect(191+ "mints once while the token lasts, and again a minute before it expires",192+ () =>193+ withUpstream((seen) =>194+ Effect.gen(function* () {195+ const upstream = yield* Upstream;196+197+ yield* upstream.exchange(repo, advertise);198+ yield* upstream.exchange(repo, advertise);199+200+ const first = yield* Ref.get(seen.minted);201+202+ expect(first).toHaveLength(1);203+204+ // The token is used until a minute before it expires.205+ const lasts = Duration.subtract(206+ DateTime.distance(207+ yield* DateTime.now,208+ first[0]?.expiresAt ?? DateTime.makeUnsafe(0)209+ ),210+ Duration.seconds(60)211+ );212+213+ yield* TestClock.adjust(214+ Duration.subtract(lasts, Duration.seconds(1))215+ );216+ yield* upstream.exchange(repo, advertise);217+218+ expect(yield* Ref.get(seen.minted)).toHaveLength(1);219+220+ yield* TestClock.adjust(Duration.seconds(1));221+ yield* upstream.exchange(repo, advertise);222+223+ const minted = yield* Ref.get(seen.minted);224+ const requests = yield* Ref.get(seen.requests);225+226+ expect(minted).toHaveLength(2);227+ expect(requests.at(-1)?.headers.get("authorization")).toBe(228+ basic(minted[1]?.secret ?? "")229+ );230+ })231+ )232+ );233+234+ it.effect("passes RepoNotFound through for a repo the store lacks", () =>235+ withUpstream(() =>236+ Effect.gen(function* () {237+ const upstream = yield* Upstream;238+ const missing = RepoName.make("missing");239+240+ expect(241+ yield* upstream.exchange(missing, advertise).pipe(242+ Effect.match({243+ onFailure: (error) => error,244+ onSuccess: () => "forwarded",245+ })246+ )247+ ).toStrictEqual(new RepoNotFound({ name: missing }));248+ })249+ )250+ );251+});