Skip to content
Myr

Merge build/207-git-trailers-diff-notes: a landing commit carries its credit, a push's changes are known, and verdicts travel as git notes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents c55b5bf, 3d547d8 · Browse files · 10 files+2509 added−0 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+2509 added−0 removed

  • tests:+1362 added−0 removed
  • other:+1147 added−0 removed

10 files+2509 added−0 removed

added:packages/git/src/upstream/repo-host.ts+126 added
1import { Fetch } from "@repo/artifacts/fetch";2import { RepoHost } from "@repo/artifacts/repo-host";3import type { RepoName, TokenScope } from "@repo/artifacts/repo-host";4import {5 Cache,6 Data,7 DateTime,8 Duration,9 Effect,10 Exit,11 Layer,12 Redacted,13} from "effect";1415import { Exchange, Upstream, UpstreamFailure } from "../upstream.ts";16import type { Service } from "../upstream.ts";1718/** How long a token the upstream mints is asked to last. */19const TOKEN_TTL = Duration.hours(1);2021/** A token is dropped this long before it expires, so none expires mid-exchange. */22const MARGIN = Duration.minutes(1);2324/** Tokens kept at once, one per (repo, scope). */25const CAPACITY = 1024;2627class TokenKey extends Data.Class<{28 readonly repo: RepoName;29 readonly scope: TokenScope;30}> {}3132/** A clone or fetch reads; only a push writes. */33const scopeOf = (service: Service): TokenScope =>34 service === "git-receive-pack" ? "write" : "read";3536/**37 * Basic auth as Artifacts takes it: any user name, and the token's secret38 * without its `?expires=` suffix as the password.39 */40const basic = (secret: Redacted.Redacted) => {41 const [password = ""] = Redacted.value(secret).split("?expires=");4243 return `Basic ${btoa(`x:${password}`)}`;44};4546const requestOf = (47 remote: string,48 exchange: Exchange,49 authorization: string50) => {51 const headers = new Headers(exchange.headers);5253 headers.set("authorization", authorization);5455 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" };6263 return new Request(`${remote}/${service}`, init);64 },65 });66};6768/**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 */74export 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;8081 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;8788 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 );107108 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 );115116 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
1import { ObjectId, RefName, RepoHost } from "@repo/artifacts/repo-host";2import type {3 PushSource,4 RepoNotFound,5 TreeEntry,6} from "@repo/artifacts/repo-host";7import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";8import { Brand } from "@repo/brand";9import { Verdict } from "@repo/protocol/domain/answer";10import { CommitSha } from "@repo/protocol/ids";11import type { RepoName } from "@repo/protocol/ids";12import { DateTime, Effect, Option, Schema } from "effect";1314import { committerLine } from "./trailers.ts";1516/**17 * Where verdicts live as git notes (spec D22): one JSON note per commit, read18 * with `git notes --ref=<slug> show <commit>`.19 */20export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);2122/** A verdict to write as the note on `target`, on top of the notes at `notesParent` in `repo`. */23export 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}3031/**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 */35export interface ScratchSource extends PushSource {36 readonly fs: MemoryFs;37}3839type MemoryFs = ReturnType<typeof memoryFs>;4041const encoder = new TextEncoder();4243const concat = (parts: readonly Uint8Array[]) => {44 const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));45 let at = 0;4647 for (const part of parts) {48 all.set(part, at);49 at += part.byteLength;50 }5152 return all;53};5455const hex = (bytes: ArrayBuffer) =>56 [...new Uint8Array(bytes)]57 .map((byte) => byte.toString(16).padStart(2, "0"))58 .join("");5960const bytesOfHex = (id: string) =>61 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));6263/** git's zlib stream, as a loose object holds it. */64const 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)));7071const sortKey = (entry: TreeEntry) =>72 encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);7374// git sorts a tree's entries by name, a subtree's name as if it ended in "/".75const treeOrder = (one: TreeEntry, other: TreeEntry) => {76 const left = sortKey(one);77 const right = sortKey(other);7879 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {80 const diff = (left[at] ?? 0) - (right[at] ?? 0);8182 if (diff !== 0) {83 return diff;84 }85 }8687 return left.length - right.length;88};8990// A tree object spells a subtree's mode without its leading zero.91const modeOf = (entry: TreeEntry) => entry.mode.replace(/^0/u, "");9293const 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 );102103const signature = (now: DateTime.Utc) =>104 `${committerLine.name} <${committerLine.email}> ${Math.floor(DateTime.toEpochMillis(now) / 1000)} +0000`;105106const 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 );122123/**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 */127const scratch = () =>128 Effect.gen(function* () {129 const fs = memoryFs();130 const gitdir = "/notes.git";131 const made = new Set<string>();132133 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 );139140 const write = (path: string, data: string | Uint8Array) =>141 Effect.promise(() => fs.promises.writeFile(path, data));142143 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 );152153 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 ]);159160 const id = hex(161 yield* Effect.promise(() => crypto.subtle.digest("SHA-1", raw))162 );163164 const dir = `${gitdir}/objects/${id.slice(0, 2)}`;165166 yield* mkdir(dir);167 yield* write(`${dir}/${id.slice(2)}`, yield* deflate(raw));168169 return id;170 });171172 return {173 object,174 ref: (ref: RefName, sha: CommitSha) =>175 write(`${gitdir}/${ref}`, `${sha}\n`),176 source: { fs, gitdir } satisfies ScratchSource,177 };178 });179180/** The notes tree's entries at `parent`, read through the port; none for the first note. */181const 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);188189 if (Option.isNone(commit)) {190 return yield* Effect.die(`${repo} has no notes commit ${sha}`);191 }192193 const tree = yield* host.readTree(repo, commit.value.tree);194195 if (Option.isNone(tree)) {196 return yield* Effect.die(`${repo} has no tree ${commit.value.tree}`);197 }198199 return tree.value;200 }),201 });202203const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));204205/**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 */214export 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`));226227 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 );239240 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 );251252 yield* repo.ref(notesRef, commit);253254 return { commit, source: repo.source };255 });
added:packages/git/src/patch-id.ts+29 added
added:packages/git/src/trailers.ts+390 added
1import { Brand } from "@repo/brand";2import { CreditRole } from "@repo/protocol/domain/credit";3import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";4import { Handle } from "@repo/protocol/ids";5import type {6 AskId,7 CheckVersion,8 PatchId,9 ProjectName,10 RequestId,11} from "@repo/protocol/ids";12import { Array, Option, Order, Schema } from "effect";1314/** One `Key: value` line of a commit message's trailer block. */15export interface Trailer {16 readonly key: string;17 readonly value: string;18}1920/** A git identity: the name and email of an author or committer line. */21export interface GitIdentity {22 readonly name: string;23 readonly email: string;24}2526/** The accountable person, as a landing's author: their handle at the platform's users domain. */27export const authorLine = (handle: Handle): GitIdentity => ({28 email: `${handle}@users.${Brand.domain}`,29 name: handle,30});3132/** The platform, which commits every landing. */33export const committerLine: GitIdentity = {34 email: `platform@${Brand.domain}`,35 name: Brand.name,36};3738/** What a landing commit's message is made of; every trailer comes from the platform's own rows. */39export 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}5455const ASSISTED = "Assisted-by";5657// C's `isspace`, which git's trailer code tests with.58const SPACE = /^[ \t\n\v\f\r]/u;5960const isSpace = (text: string) => SPACE.test(text);6162// git's scissors line: it and everything below it are not the message.63const SCISSORS = "# ------------------------ >8 ------------------------";6465/**66 * Whether git reads `line` as the end of a commit message: a `---` divider67 * (then a blank or the line's end) or the scissors line.68 */69const endsMessage = (line: string) =>70 line.startsWith(SCISSORS) ||71 (line.startsWith("---") && (line.length === 3 || isSpace(line.slice(3))));7273/** One line, so no value or subject can open a paragraph or a trailer of its own. */74const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();7576/**77 * A subject or body line as written, indented by a space if git would read78 * it as the end of the message, which would hide the trailers below it and79 * let a paragraph above it pass for them.80 */81const inMessage = (line: string) => (endsMessage(line) ? ` ${line}` : line);8283const personOf = (handle: Handle) => {84 const { email, name } = authorLine(handle);8586 return `${name} <${email}>`;87};8889// The kernel's `AGENT:MODEL` shape, then whether the platform confirmed it:90// `claude-code:opus-4 (verified)`. A harness name holds no colon.91const agentOf = ({ harness, model, verified }: AgentTrailer) =>92 `${oneLine(harness)}${model === undefined ? "" : `:${oneLine(model)}`} (${verified ? "verified" : "claimed"})`;9394const roleOrder = (role: CreditRole) => CreditRole.literals.indexOf(role);9596/**97 * Credits in the order of `CreditRole`, people within a role in the order98 * given, each (role, person) once: the same rows always make the same message.99 */100const ordered = (credits: readonly Credit[]) =>101 Array.dedupeWith(102 Array.sortWith(credits, ({ role }) => roleOrder(role), Order.Number),103 (one: Credit, other: Credit) =>104 one.role === other.role && one.handle === other.handle105 );106107/**108 * A landing commit's message: the subject, the body, then one trailer block109 * that credits each person by role, discloses each agent as `Assisted-by`,110 * and cites the ask, the verdict, the held-back result and the request.111 */112export const formatLanding = (input: LandingMessage): string => {113 const trailers: readonly Trailer[] = [114 ...ordered(input.credits).map(({ handle, role }) => ({115 key: role,116 value: personOf(handle),117 })),118 ...input.assisted.map((agent) => ({119 key: ASSISTED,120 value: agentOf(agent),121 })),122 ...(input.ask === undefined123 ? []124 : [{ key: "Ask", value: `${input.ask.project}/${input.ask.ask}` }]),125 ...(input.verdict === undefined126 ? []127 : [128 {129 key: "Verdict",130 value: `${input.verdict.patchId} ${oneLine(input.verdict.checkVersion)}`,131 },132 ]),133 ...(input.heldBack === undefined134 ? []135 : [{ key: "Held-back", value: oneLine(input.heldBack) }]),136 ...(input.requestId === undefined137 ? []138 : [{ key: "Request-Id", value: input.requestId }]),139 ];140141 const body = input.body?.trim() ?? "";142143 const paragraphs = [144 inMessage(oneLine(input.subject)),145 ...(body === "" ? [] : [body.split("\n").map(inMessage).join("\n")]),146 ...(trailers.length === 0147 ? []148 : [trailers.map(({ key, value }) => `${key}: ${value}`).join("\n")]),149 ];150151 return `${paragraphs.join("\n\n")}\n`;152};153154const isBlank = (line: string) => /^[ \t\n\v\f\r]*$/u.test(line);155156const isComment = (line: string) => line.startsWith("#");157158// Lines git counts as trailers whatever the rest of the paragraph holds.159const GIT_GENERATED = ["Signed-off-by: ", "(cherry picked from commit "];160161/**162 * Where a trailer's key ends: letters, digits and dashes, then optional163 * blanks, then `:`. `-1` when the line has no key (git's `find_separator`).164 */165const separatorOf = (line: string) => {166 let blank = false;167168 for (let at = 0; at < line.length; at += 1) {169 const char = line.charAt(at);170171 if (char === ":") {172 return at;173 }174175 if (!blank && /^[A-Za-z0-9-]$/u.test(char)) {176 continue;177 }178179 if (at > 0 && (char === " " || char === "\t")) {180 blank = true;181 continue;182 }183184 break;185 }186187 return -1;188};189190/**191 * The lines git reads as the log message: up to a `---` divider or the192 * scissors line, less a closing run of comments, empty lines and an old193 * `Conflicts:` block (git's `find_end_of_log_message`). Like git, it reads194 * a last line with no newline as if it had one.195 */196const logLines = (message: string) => {197 const lines = message.split("\n");198199 if (message.endsWith("\n")) {200 lines.pop();201 }202203 const cut = lines.findIndex(endsMessage);204 const kept = cut === -1 ? lines : lines.slice(0, cut);205206 // Where the closing run starts; git keeps a run that starts at the top.207 let run = 0;208 let conflicts = false;209210 for (const [at, line] of kept.entries()) {211 const header = line === "Conflicts:";212213 if (line === "" || isComment(line) || header) {214 conflicts ||= header;215 run = run === 0 ? at : run;216 } else if (!(conflicts && line.startsWith("\t")) && run !== 0) {217 run = 0;218 conflicts = false;219 }220 }221222 return kept.slice(0, run === 0 ? kept.length : run);223};224225/**226 * Where the trailer block starts, by git's rule: the last paragraph after227 * the title, if all its lines are trailers, or if one is a sign-off and at228 * least a quarter are trailers.229 */230const blockStart = (lines: readonly string[]): Option.Option<number> => {231 const titleEnd = lines.findIndex((line) => !isComment(line) && isBlank(line));232233 if (titleEnd === -1) {234 return Option.none();235 }236237 let onlySpaces = true;238 let recognized = false;239 let trailerLines = 0;240 let otherLines = 0;241 let continuations = 0;242243 for (let at = lines.length - 1; at >= titleEnd; at -= 1) {244 const line = lines[at] ?? "";245246 if (isComment(line)) {247 otherLines += continuations;248 continuations = 0;249 } else if (isBlank(line)) {250 if (!onlySpaces) {251 otherLines += continuations;252253 return (recognized && trailerLines * 3 >= otherLines) ||254 (trailerLines > 0 && otherLines === 0)255 ? Option.some(at + 1)256 : Option.none();257 }258 } else {259 onlySpaces = false;260261 if (GIT_GENERATED.some((prefix) => line.startsWith(prefix))) {262 trailerLines += 1;263 continuations = 0;264 recognized = true;265 } else if (separatorOf(line) >= 1 && !isSpace(line)) {266 trailerLines += 1;267 continuations = 0;268 } else if (isSpace(line)) {269 continuations += 1;270 } else {271 otherLines += 1 + continuations;272 continuations = 0;273 }274 }275 }276277 return Option.none();278};279280/** A value with its continuation lines folded to single spaces. */281const unfold = (value: string) =>282 value283 .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "")284 .replaceAll(/\n[ \t\n\v\f\r]*/gu, " ")285 .replaceAll(/^[ \t\n\v\f\r]+|[ \t\n\v\f\r]+$/gu, "");286287/**288 * A message's trailers in order, as `git interpret-trailers --parse` reads289 * them: keys and values trimmed, continuation lines unfolded, lines that are290 * not trailers left out.291 */292export const parseTrailers = (message: string): readonly Trailer[] => {293 const lines = logLines(message);294295 return Option.match(blockStart(lines), {296 onNone: () => [],297 onSome: (start) => {298 // Each item is one trailer with its continuation lines, or another line.299 const items: string[] = [];300 let open = false;301302 for (const line of lines.slice(start)) {303 if (open && isSpace(line)) {304 items.push(`${items.pop() ?? ""}\n${line}`);305 } else {306 items.push(line);307 open = separatorOf(line) >= 1;308 }309 }310311 return items.flatMap((item) => {312 const cut = separatorOf(item);313314 return isComment(item) || cut < 1315 ? []316 : [317 {318 key: item.slice(0, cut).trim(),319 value: unfold(item.slice(cut + 1)),320 },321 ];322 });323 },324 });325};326327const escaped = (text: string) =>328 text.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`);329330// Exactly what `personOf` writes: a handle at the platform's users domain.331const PERSON = new RegExp(332 `^(?<handle>[A-Za-z0-9][A-Za-z0-9-]*) <\\k<handle>@users\\.${escaped(Brand.domain)}>$`,333 "u"334);335336const AGENT =337 /^(?<harness>[^:]+?)(?::(?<model>.+))? \((?<mark>claimed|verified)\)$/u;338339const decodeRole = Schema.decodeUnknownOption(CreditRole);340341const decodeHandle = Schema.decodeUnknownOption(Handle);342343const creditOf = ({ key, value }: Trailer): Option.Option<Credit> =>344 Option.gen(function* () {345 const role = yield* decodeRole(346 CreditRole.literals.find(347 (literal) => literal.toLowerCase() === key.toLowerCase()348 )349 );350351 const handle = yield* decodeHandle(PERSON.exec(value)?.groups?.handle);352353 return { handle, role };354 });355356const agentFrom = ({ key, value }: Trailer): Option.Option<AgentTrailer> => {357 const groups = AGENT.exec(value)?.groups;358359 if (key.toLowerCase() !== ASSISTED.toLowerCase() || groups === undefined) {360 return Option.none();361 }362363 const harness = groups.harness ?? "";364 const { model } = groups;365 const verified = groups.mark === "verified";366367 return Option.some(368 model === undefined ? { harness, verified } : { harness, model, verified }369 );370};371372/** The people a landing credits, and the agents it discloses. */373export interface LandingCredits {374 readonly credits: readonly Credit[];375 readonly assisted: readonly AgentTrailer[];376}377378/**379 * Who a landing credits, and which agents it discloses. Only trailers the380 * platform writes count: a credit names a platform handle by `authorLine`,381 * and `Assisted-by` is never credit.382 */383export const creditsOf = (message: string): LandingCredits => {384 const trailers = parseTrailers(message);385386 return {387 assisted: Array.getSomes(trailers.map(agentFrom)),388 credits: Array.getSomes(trailers.map(creditOf)),389 };390};
added:packages/git/src/tree-diff.ts+347 added
1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";2import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";3import { BlobSha, RepoPath } from "@repo/protocol/ids";4import type { RepoName, TreeSha } from "@repo/protocol/ids";5import { Array, Effect, Option, Order, Semaphore } from "effect";67/**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 */11export interface Change {12 readonly path: RepoPath;13 readonly status: "added" | "modified" | "deleted";14 readonly before?: BlobSha;15 readonly after?: BlobSha;16}1718/** A line a change added, numbered from 1 in the new file. */19export interface AddedLine {20 readonly line: number;21 readonly text: string;22}2324// Store calls under way at once, however deep the walk or long the change set.25const STORE_CALLS = 8;2627// The walk forks freely; the semaphore alone holds the store to its calls.28const ALL = { concurrency: "unbounded" } as const;2930const entriesOf = (31 calls: Semaphore.Semaphore,32 repo: RepoName,33 tree: Option.Option<string>34) =>35 Option.match(tree, {36 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),37 onSome: (id) =>38 RepoHost.use((host) => host.readTree(repo, ObjectId.make(id))).pipe(39 Semaphore.withPermit(calls),40 Effect.flatMap(41 Option.match({42 onNone: () => Effect.die(`${repo} has no tree ${id}`),43 onSome: Effect.succeed,44 })45 )46 ),47 });4849const treeIdOf = (entry: TreeEntry | undefined) =>50 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();5152// A submodule's pointer counts as a file at its path, so a change to it is seen.53const fileIdOf = (entry: TreeEntry | undefined) =>54 entry === undefined || entry.type === "tree"55 ? undefined56 : BlobSha.make(entry.sha);5758const fileChange = (59 path: string,60 before: BlobSha | undefined,61 after: BlobSha | undefined62): readonly Change[] => {63 const at = RepoPath.make(path);6465 if (before !== undefined && after !== undefined) {66 return [{ after, before, path: at, status: "modified" }];67 }6869 if (before !== undefined) {70 return [{ before, path: at, status: "deleted" }];71 }7273 return after === undefined ? [] : [{ after, path: at, status: "added" }];74};7576const walk = (77 calls: Semaphore.Semaphore,78 repo: RepoName,79 prefix: string,80 base: Option.Option<string>,81 head: Option.Option<string>82): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>83 Effect.gen(function* () {84 const [before, after] = yield* Effect.all(85 [entriesOf(calls, repo, base), entriesOf(calls, repo, head)],86 ALL87 );8889 const beforeByName = new Map(before.map((entry) => [entry.name, entry]));90 const afterByName = new Map(after.map((entry) => [entry.name, entry]));9192 // The same id and mode: nothing under it changed, so it is never read.93 const names = Array.sort(94 new Set([...beforeByName.keys(), ...afterByName.keys()]),95 Order.String96 ).filter((name) => {97 const old = beforeByName.get(name);98 const next = afterByName.get(name);99100 return old?.sha !== next?.sha || old?.mode !== next?.mode;101 });102103 const changed = yield* Effect.forEach(104 names,105 (name) => {106 const old = beforeByName.get(name);107 const next = afterByName.get(name);108 const path = `${prefix}${name}`;109 const files = fileChange(path, fileIdOf(old), fileIdOf(next));110 const inside = [treeIdOf(old), treeIdOf(next)] as const;111112 return Option.isNone(inside[0]) && Option.isNone(inside[1])113 ? Effect.succeed(files)114 : walk(calls, repo, `${path}/`, inside[0], inside[1]).pipe(115 Effect.map((nested) => [...files, ...nested])116 );117 },118 ALL119 );120121 return changed.flat();122 });123124/**125 * The files that differ between two trees of `repo`, read through the126 * `RepoHost` port alone: it walks both roots and descends only into subtrees127 * whose ids differ, since the store has no diff of its own. At most eight128 * trees are read at once.129 */130export const treeDiff = (131 repo: RepoName,132 base: TreeSha,133 head: TreeSha134): Effect.Effect<readonly Change[], RepoNotFound, RepoHost> =>135 Effect.flatMap(Semaphore.make(STORE_CALLS), (calls) =>136 walk(calls, repo, "", Option.some(base), Option.some(head))137 );138139// git's own test: a NUL among the first bytes means the blob is not text.140const SNIFF = 8192;141142const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);143144const linesOf = (bytes: Uint8Array) => {145 const text = new TextDecoder().decode(bytes);146 const lines = text.split("\n");147148 if (text.endsWith("\n")) {149 lines.pop();150 }151152 return lines;153};154155// Past this many edits the diff stops looking for the shortest script.156const MAX_EDITS = 1024;157158const at = (values: Int32Array, index: number) => values[index] ?? 0;159160/**161 * Indexes in `next` that the edit script ending at `(n, m)` inserts, read162 * back from `trace`, where `trace[d]` holds diagonals `-d..d` after `d` edits.163 */164const insertsFrom = (165 trace: readonly Int32Array[],166 ends: { readonly n: number; readonly m: number }167) => {168 const inserts: number[] = [];169 let x = ends.n;170 let y = ends.m;171172 for (let edits = trace.length - 1; edits > 0; edits -= 1) {173 const previous = trace[edits - 1] ?? new Int32Array();174 const diagonal = x - y;175176 const reached = (k: number) => at(previous, k + edits - 1);177178 const down =179 diagonal === -edits ||180 (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));181182 const from = down ? diagonal + 1 : diagonal - 1;183184 x = reached(from);185 y = x - from;186187 if (down) {188 inserts.push(y);189 }190 }191192 return inserts.toReversed();193};194195/**196 * Lines of `next` with no partner in `previous`, matched by count: the197 * fallback for a rewrite too large for the shortest script.198 */199const unmatched = (previous: readonly string[], next: readonly string[]) => {200 const left = new Map<string, number>();201202 for (const line of previous) {203 left.set(line, (left.get(line) ?? 0) + 1);204 }205206 return next.flatMap((line, index) => {207 const count = left.get(line) ?? 0;208209 left.set(line, count - 1);210211 return count > 0 ? [] : [index];212 });213};214215/**216 * Indexes of the lines of `next` a shortest edit script from `previous`217 * inserts (Myers' O(ND) diff).218 */219const myers = (previous: readonly string[], next: readonly string[]) => {220 const n = previous.length;221 const m = next.length;222 const limit = Math.min(n + m, MAX_EDITS);223 const offset = limit + 1;224 const reach = new Int32Array(2 * limit + 3);225 const trace: Int32Array[] = [];226227 for (let edits = 0; edits <= limit; edits += 1) {228 for (let diagonal = -edits; diagonal <= edits; diagonal += 2) {229 let x =230 diagonal === -edits ||231 (diagonal !== edits &&232 at(reach, offset + diagonal - 1) < at(reach, offset + diagonal + 1))233 ? at(reach, offset + diagonal + 1)234 : at(reach, offset + diagonal - 1) + 1;235236 let y = x - diagonal;237238 while (x < n && y < m && previous[x] === next[y]) {239 x += 1;240 y += 1;241 }242243 reach[offset + diagonal] = x;244245 if (x >= n && y >= m) {246 trace.push(reach.slice(offset - edits, offset + edits + 1));247248 return insertsFrom(trace, { m, n });249 }250 }251252 trace.push(reach.slice(offset - edits, offset + edits + 1));253 }254255 return unmatched(previous, next);256};257258/** The lines of `next` that are not in `previous`, numbered from 1. */259const added = (260 previous: readonly string[],261 next: readonly string[]262): readonly AddedLine[] => {263 let start = 0;264265 while (266 start < previous.length &&267 start < next.length &&268 previous[start] === next[start]269 ) {270 start += 1;271 }272273 let end = 0;274275 while (276 end < previous.length - start &&277 end < next.length - start &&278 previous[previous.length - 1 - end] === next[next.length - 1 - end]279 ) {280 end += 1;281 }282283 const middle = myers(284 previous.slice(start, previous.length - end),285 next.slice(start, next.length - end)286 );287288 return middle.map((index) => ({289 line: start + index + 1,290 text: next[start + index] ?? "",291 }));292};293294/**295 * A file's lines; none for a binary blob, or for a submodule's pointer, whose296 * id names a commit in another repo, so the store has no blob by it.297 */298const textOf = (repo: RepoName, blob: BlobSha | undefined) =>299 blob === undefined300 ? Effect.succeedSome<readonly string[]>([])301 : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(302 Effect.map(303 Option.flatMap((bytes) =>304 isBinary(bytes) ? Option.none() : Option.some(linesOf(bytes))305 )306 )307 );308309// Changes diffed at once, each reading its two blobs together: eight store310// calls, and no more than four files' text held at a time.311const CHANGES = { concurrency: STORE_CALLS / 2 } as const;312313/**314 * The lines each added or modified file gained, by a line diff of its blobs.315 * A binary blob (a NUL in its first 8 KiB) and a submodule's pointer report316 * no lines. At most eight blobs are read at once.317 */318export const addedLines = (319 repo: RepoName,320 changes: readonly Change[]321): Effect.Effect<322 ReadonlyMap<RepoPath, readonly AddedLine[]>,323 RepoNotFound,324 RepoHost325> =>326 Effect.forEach(327 changes.filter((change) => change.after !== undefined),328 (change) =>329 Effect.gen(function* () {330 const [previous, next] = yield* Effect.all(331 [textOf(repo, change.before), textOf(repo, change.after)],332 ALL333 );334335 const lines = Option.match(next, {336 onNone: () => [],337 onSome: (text) =>338 added(339 Option.getOrElse(previous, () => []),340 text341 ),342 });343344 return [change.path, lines] as const;345 }),346 CHANGES347 ).pipe(Effect.map((entries) => new Map(entries)));
added:packages/git/test/notes.test.ts+285 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import {4 ObjectId,5 RefName,6 RefOutcome,7 RepoHost,8 RepoName,9} from "@repo/artifacts/repo-host";10import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";11import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";12import { Brand } from "@repo/brand";13import { Verdict } from "@repo/protocol/domain/answer";14import { Outcome } from "@repo/protocol/domain/outcome";15import {16 AskId,17 CheckVersion,18 CommitSha,19 LaneName,20 PatchId,21 ProjectName,22 TreeSha,23} from "@repo/protocol/ids";24import { gitOk } from "@repo/testkit/git";25import { gitClient } from "@repo/testkit/git-client";26import { DateTime, Effect, FileSystem, Layer, Option, Schema } from "effect";2728import { noteCommit, notesRef } from "../src/notes.ts";29import type { ScratchSource } from "../src/notes.ts";30import { committerLine } from "../src/trailers.ts";3132const repo = RepoName.make("demo");3334const main = RefName.make("refs/heads/main");3536/** A verdict on the answer whose head is `head`. */37const 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 });6061const encodeVerdict = Schema.encodeEffect(Verdict);6263/** The note's text as a verdict, encoded again: compared with what was written. */64const reencoded = (note: Option.Option<string>) =>65 Schema.decodeEffect(Schema.fromJsonString(Verdict))(66 Option.getOrElse(note, () => "")67 ).pipe(Effect.flatMap(encodeVerdict));6869const now = DateTime.makeUnsafe("2026-10-07T12:30:00Z");7071/** Two commits on `demo`'s main, the targets the notes are written on. */72const 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]);7778 yield* repos.create(repo);79 yield* repos.push(repo, client.source, [80 { from: Option.none(), ref: main, to: second },81 ]);8283 return { first, second };84});8586/**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 */90const notesThroughPort = (target: CommitSha) =>91 Effect.gen(function* () {92 const repos = yield* RepoHost;93 const tip = (yield* repos.refs(repo)).get(notesRef);9495 if (tip === undefined) {96 return yield* Effect.die(`${notesRef} is not on ${repo}`);97 }9899 const commit = Option.getOrThrow(yield* repos.readCommit(repo, tip));100101 const entries = Option.getOrThrow(yield* repos.readTree(repo, commit.tree));102103 const entry = entries.find(({ name }) => name === target);104105 const blob =106 entry === undefined107 ? Option.none()108 : yield* repos.readBlob(repo, ObjectId.make(entry.sha));109110 return {111 commit,112 names: entries.map(({ name }) => name),113 note: Option.map(blob, (bytes) => new TextDecoder().decode(bytes)),114 };115 });116117/** Copies a scratch git directory onto disk, so git itself can read it. */118const 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;123124 const copy = (path: string): Effect.Effect<void> =>125 Effect.gen(function* () {126 const stat = yield* Effect.promise(() => promises.stat(path));127128 if (stat.isDirectory()) {129 const names = yield* Effect.promise(() => promises.readdir(path));130131 yield* fs132 .makeDirectory(`${root}${path}`, { recursive: true })133 .pipe(Effect.orDie);134 yield* Effect.forEach(names, (name) => copy(`${path}/${name}`));135136 return;137 }138139 const bytes = yield* Effect.promise(() => promises.readFile(path));140141 yield* fs142 .writeFile(143 `${root}${path}`,144 bytes instanceof Uint8Array145 ? bytes146 : new TextEncoder().encode(bytes)147 )148 .pipe(Effect.orDie);149 });150151 yield* copy(source.gitdir);152153 return `${root}${source.gitdir}`;154 });155156describe("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);164165 const { commit, source } = yield* noteCommit({166 notesParent: Option.none(),167 now,168 repo,169 target: first,170 verdict,171 });172173 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 })]);179180 const read = yield* notesThroughPort(first);181182 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 );198199 // git's own notes layout: `git notes show` finds the same note.200 const gitdir = yield* onDisk(source);201202 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 );218219 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;225226 const one = yield* noteCommit({227 notesParent: Option.none(),228 now,229 repo,230 target: first,231 verdict: verdictOn(first),232 });233234 yield* repos.push(repo, one.source, [235 { from: Option.none(), ref: notesRef, to: one.commit },236 ]);237238 const two = yield* noteCommit({239 notesParent: Option.some(one.commit),240 now,241 repo,242 target: second,243 verdict: verdictOn(second),244 });245246 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 })]);251252 const read = yield* notesThroughPort(first);253254 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 );264265 // git lists both notes from the second notes commit's tree.266 const gitdir = yield* onDisk(two.source);267268 const listed = yield* gitOk(269 gitdir,270 `--git-dir=${gitdir}`,271 "notes",272 `--ref=${Brand.slug}`,273 "list"274 );275276 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
added:packages/git/test/trailers.test.ts+285 added
1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import {5 AskId,6 CheckVersion,7 Handle,8 PatchId,9 ProjectName,10 RequestId,11} from "@repo/protocol/ids";12import { gitOk } from "@repo/testkit/git";13import { Effect, FileSystem } from "effect";1415import {16 authorLine,17 committerLine,18 creditsOf,19 formatLanding,20 parseTrailers,21} from "../src/trailers.ts";2223const alice = Handle.make("alice");2425const bob = Handle.make("bob");2627const carol = Handle.make("carol");2829const 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});4344/** What git itself reads as `message`'s trailers, one `key: value` per line. */45const gitTrailers = (message: string) =>46 Effect.gen(function* () {47 const fs = yield* FileSystem.FileSystem;48 const dir = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);4950 yield* fs.writeFileString(`${dir}/message`, message).pipe(Effect.orDie);5152 const parsed = yield* gitOk(53 dir,54 "interpret-trailers",55 "--parse",56 "message"57 );5859 // git prints `key: value`; a key holds no colon, and an empty value60 // leaves `key:` once the output is trimmed.61 return parsed === ""62 ? []63 : parsed.split("\n").map((line) => {64 const cut = line.indexOf(":");6566 return {67 key: line.slice(0, cut),68 value: line.slice(cut + 1).replace(/^ /u, ""),69 };70 });71 }).pipe(Effect.scoped);7273// git's scissors line: it and everything below it are not the message.74const scissors = "# ------------------------ >8 ------------------------";7576// Messages whose last paragraph tests git's rules: a title is never trailers,77// a mixed paragraph counts only with a sign-off and 25% trailers, an indented78// line continues the trailer above it, `---` and the scissors line end the79// message, and an old `Conflicts:` block at the end is not part of it.80const edges = [81 "Only a title: Not-a-trailer\n",82 "Title\n\nProse that ends.\nAcked-by: someone\n",83 "Title\n\nProse that ends.\nSigned-off-by: bob\nAcked-by: someone\n",84 "Title\n\nFixes: the parser\n and the printer\nReviewed-by : carol\n",85 "Title\n\nBody\n\nReported-by: dee\n---\nNot-read: after the divider\n",86 "Title\n\nBody\n\nSee-also: one\n\n \n",87 `Title\n\nBody\n\nReported-by: dee\n${scissors}\n\nNot-read: below the scissors\n`,88 "Title\n\nBody\n\nAcked-by: someone\n\nConflicts:\n\tsrc/a.ts\n# a comment\n",89];9091// Lines git's trailer rules turn on, for messages drawn at random.92const pieces = [93 "Title",94 "",95 "",96 "Prose here.",97 "Acked-by: a",98 "Signed-off-by: b",99 "Key : v",100 " continued",101 "\tsrc/a.ts",102 "# a comment",103 "---",104 "--- x",105 "----",106 "Conflicts:",107 scissors,108 "(cherry picked from commit 0123abc)",109 "x:y",110 "-k: v",111 " ",112 "Not a: trailer",113];114115/** Messages of 1 to 14 lines from `pieces`, from a fixed seed (Park and Miller's generator). */116const randomMessages = (count: number) => {117 let state = 20_261_007;118119 const draw = (below: number) => {120 state = (state * 16_807) % 2_147_483_647;121122 return state % below;123 };124125 return Array.from({ length: count }, () => {126 const lines = Array.from(127 { length: 1 + draw(14) },128 () => pieces[draw(pieces.length)] ?? ""129 );130131 // One in four has no newline after its last line.132 return `${lines.join("\n")}${draw(4) === 0 ? "" : "\n"}`;133 });134};135136describe("landing trailers", () => {137 it.live(138 "git reads a landing's trailers as the platform wrote them, in order",139 () =>140 Effect.gen(function* () {141 const expected = [142 { key: "Asked-by", value: `alice <alice@users.${Brand.domain}>` },143 { key: "Signed-off-by", value: `bob <bob@users.${Brand.domain}>` },144 { key: "Decided-by", value: `carol <carol@users.${Brand.domain}>` },145 { key: "Assisted-by", value: "claude-code:opus-4 (verified)" },146 { key: "Ask", value: "datekit/week-at-year-end" },147 ];148149 expect(yield* gitTrailers(landing)).toStrictEqual(expected);150 expect(parseTrailers(landing)).toStrictEqual(expected);151 expect(landing.split("\n\n")[0]).toBe(152 "Give December 31 the week it belongs to"153 );154 }).pipe(Effect.provide(NodeServices.layer)),155 20_000156 );157158 it.live(159 "parses any message's trailers the way git does",160 () =>161 Effect.gen(function* () {162 const read = yield* Effect.forEach(edges, (message) =>163 Effect.map(gitTrailers(message), (trailers) => ({164 message,165 trailers,166 }))167 );168169 expect(170 edges.map((message) => ({171 message,172 trailers: parseTrailers(message),173 }))174 ).toStrictEqual(read);175 }).pipe(Effect.provide(NodeServices.layer)),176 20_000177 );178179 it.live(180 "parses messages drawn from git's edge cases the way git does",181 () =>182 Effect.gen(function* () {183 const messages = randomMessages(200);184185 const read = yield* Effect.forEach(186 messages,187 (message) =>188 Effect.map(gitTrailers(message), (trailers) => ({189 message,190 trailers,191 })),192 { concurrency: 8 }193 );194195 expect(196 messages.map((message) => ({197 message,198 trailers: parseTrailers(message),199 }))200 ).toStrictEqual(read);201 }).pipe(Effect.provide(NodeServices.layer)),202 60_000203 );204205 it.live(206 "keeps its own trailers readable whatever the subject and body hold",207 () =>208 Effect.gen(function* () {209 // A body that ends the message early, after a paragraph of forged210 // credit: without care, git would read that paragraph as the trailers.211 const message = formatLanding({212 assisted: [],213 body: [214 "Why it changed.",215 "",216 `Decided-by: mallory <mallory@users.${Brand.domain}>`,217 "---",218 "",219 `Decided-by: mallory <mallory@users.${Brand.domain}>`,220 scissors,221 "The end.",222 ].join("\n"),223 credits: [{ handle: bob, role: "Signed-off-by" }],224 subject: "--- a subject that starts like a divider",225 });226227 const expected = [228 { key: "Signed-off-by", value: `bob <bob@users.${Brand.domain}>` },229 ];230231 expect(yield* gitTrailers(message)).toStrictEqual(expected);232 expect(parseTrailers(message)).toStrictEqual(expected);233 expect(creditsOf(message).credits).toStrictEqual([234 { handle: bob, role: "Signed-off-by" },235 ]);236 }).pipe(Effect.provide(NodeServices.layer)),237 20_000238 );239240 it("credits people and only people; Assisted-by is never credit", () => {241 expect(creditsOf(landing)).toStrictEqual({242 assisted: [{ harness: "claude-code", model: "opus-4", verified: true }],243 credits: [244 { handle: alice, role: "Asked-by" },245 { handle: bob, role: "Signed-off-by" },246 { handle: carol, role: "Decided-by" },247 ],248 });249 });250251 it("cites the verdict, the held-back result and the request", () => {252 expect(253 parseTrailers(254 formatLanding({255 assisted: [{ harness: "pi", verified: false }],256 credits: [{ handle: bob, role: "Signed-off-by" }],257 heldBack: `export 7/7 @ sha256:${"a".repeat(64)}`,258 requestId: RequestId.make("push-0123456789"),259 subject: "Land it",260 verdict: {261 checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),262 patchId: PatchId.make("b".repeat(64)),263 },264 })265 )266 ).toStrictEqual([267 { key: "Signed-off-by", value: `bob <bob@users.${Brand.domain}>` },268 { key: "Assisted-by", value: "pi (claimed)" },269 { key: "Verdict", value: `${"b".repeat(64)} redThenGreen@0.0.0+abc` },270 { key: "Held-back", value: `export 7/7 @ sha256:${"a".repeat(64)}` },271 { key: "Request-Id", value: "push-0123456789" },272 ]);273 });274275 it("names the answerer by handle and the platform as committer", () => {276 expect(authorLine(alice)).toStrictEqual({277 email: `alice@users.${Brand.domain}`,278 name: "alice",279 });280 expect(committerLine).toStrictEqual({281 email: `platform@${Brand.domain}`,282 name: Brand.name,283 });284 });285});
added:packages/git/test/tree-diff.test.ts+449 added
1import { describe, expect, it } from "@effect/vitest";2import {3 ObjectId,4 RefName,5 RepoHost,6 RepoName,7} from "@repo/artifacts/repo-host";8import type { TreeEntry } from "@repo/artifacts/repo-host";9import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";10import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";11import { BlobSha, RepoPath, TreeSha } from "@repo/protocol/ids";12import type { CommitSha } from "@repo/protocol/ids";13import { gitClient } from "@repo/testkit/git-client";14import type { Files } from "@repo/testkit/git-client";15import { Effect, Layer, Option, Ref } from "effect";1617import { addedLines, treeDiff } from "../src/tree-diff.ts";1819const repo = RepoName.make("demo");2021const main = RefName.make("refs/heads/main");2223const before: Files = [24 ["README.md", "demo\n"],25 ["docs/x.md", "gone soon\n"],26 ["lib/kept.ts", "export const kept = 1;\n"],27 ["src/a.ts", "one\ntwo\nthree\nfour\n"],28];2930const after: Files = [31 ["README.md", "demo\n"],32 ["assets/logo.bin", "\u0000PNG\nline\n"],33 ["lib/kept.ts", "export const kept = 1;\n"],34 ["src/a.ts", "one\nbetween\ntwo\nthree\nFOUR\nfive\n"],35 ["src/b/c.ts", "export const c = 3;\n"],36];3738/** The memory store, with each tree id `readTree` is asked for written to `reads`. */39const countedBy = (reads: Ref.Ref<readonly string[]>) =>40 Layer.effect(41 RepoHost,42 Effect.gen(function* () {43 const host = yield* RepoHost;4445 return RepoHost.of({46 ...host,47 readTree: (name, tree) =>48 Ref.update(reads, (all) => [...all, tree]).pipe(49 Effect.andThen(host.readTree(name, tree))50 ),51 });52 })53 ).pipe(Layer.provide(RepoHostMemory));5455/**56 * The memory store, with a submodule's pointer added to the trees `links`57 * names: git writes one as a `160000` entry naming a commit in another repo.58 */59const withSubmodules = (links: Ref.Ref<ReadonlyMap<string, TreeEntry>>) =>60 Layer.effect(61 RepoHost,62 Effect.gen(function* () {63 const host = yield* RepoHost;6465 return RepoHost.of({66 ...host,67 readTree: (name, tree) =>68 Effect.gen(function* () {69 const entries = yield* host.readTree(name, tree);70 const link = (yield* Ref.get(links)).get(tree);7172 return link === undefined73 ? entries74 : Option.map(entries, (all) => [...all, link]);75 }),76 });77 })78 ).pipe(Layer.provide(RepoHostMemory));7980/** Store reads under way at once: now, and the most at any moment. */81interface InFlight {82 readonly now: number;83 readonly most: number;84}8586/** The memory store, with the `readTree` calls under way at once counted in `reads`. */87const inFlightBy = (reads: Ref.Ref<InFlight>) =>88 Layer.effect(89 RepoHost,90 Effect.gen(function* () {91 const host = yield* RepoHost;9293 return RepoHost.of({94 ...host,95 readTree: (name, tree) =>96 Ref.update(reads, ({ most, now }) => ({97 most: Math.max(most, now + 1),98 now: now + 1,99 })).pipe(100 Effect.andThen(Effect.yieldNow),101 Effect.andThen(host.readTree(name, tree)),102 Effect.ensuring(103 Ref.update(reads, ({ most, now }) => ({ most, now: now - 1 }))104 )105 ),106 });107 })108 ).pipe(Layer.provide(RepoHostMemory));109110/**111 * Nine folders of nine folders, each file holding `content`: when every file112 * changes, a walk that reads eight at a time at each depth has far more than113 * eight reads under way.114 */115const grid = (content: string): Files =>116 Array.from({ length: 81 }, (_, at) => [117 `p${Math.floor(at / 9)}/q${at % 9}/f.txt`,118 content,119 ]);120121/** A submodule's pointer at `vendor`, naming commit `digit` × 40 in another repo. */122const pointer = (digit: string): TreeEntry => ({123 mode: "160000",124 name: "vendor",125 sha: ObjectId.make(digit.repeat(40)),126 type: "commit",127});128129/** Two commits in `demo`, and the ids of their trees and blobs as git wrote them. */130const twoCommits = Effect.gen(function* () {131 const repos = yield* RepoHost;132 const client = yield* gitClient(memoryFs());133 const first = yield* client.commit("before", before);134 const second = yield* client.commit("after", after, [first]);135136 yield* repos.create(repo);137 yield* repos.push(repo, client.source, [138 { from: Option.none(), ref: main, to: second },139 ]);140141 const treeOf = (sha: CommitSha) =>142 repos.readCommit(repo, sha).pipe(143 Effect.map(Option.getOrThrow),144 Effect.map(({ tree }) => TreeSha.make(tree))145 );146147 /** The id of the entry at `path` under `root`. */148 const idAt = (root: string, path: string): Effect.Effect<string> =>149 Effect.gen(function* () {150 const [head = "", ...rest] = path.split("/");151152 const entries = yield* repos153 .readTree(repo, ObjectId.make(root))154 .pipe(Effect.orDie, Effect.map(Option.getOrThrow));155156 const entry = entries.find(({ name }) => name === head);157158 if (entry === undefined) {159 return yield* Effect.die(`no ${path}`);160 }161162 return rest.length === 0163 ? entry.sha164 : yield* idAt(entry.sha, rest.join("/"));165 });166167 const base = yield* treeOf(first);168 const head = yield* treeOf(second);169170 return {171 base,172 blob: (tree: TreeSha, path: string) =>173 idAt(tree, path).pipe(Effect.map((id) => BlobSha.make(id))),174 head,175 tree: (tree: TreeSha, path: string) => idAt(tree, path),176 };177});178179/** Lines from a three-word alphabet, from a fixed seed (Park and Miller's generator). */180const randomFiles = (cases: number) => {181 let state = 20_261_007;182183 const next = (below: number) => {184 state = (state * 16_807) % 2_147_483_647;185186 return state % below;187 };188189 const file = () =>190 Array.from({ length: next(9) }, () => ["a", "b", "c"][next(3)] ?? "a");191192 return Array.from({ length: cases }, () => [file(), file()] as const);193};194195/** The length of a longest common subsequence, by the textbook table. */196const lcs = (one: readonly string[], other: readonly string[]) => {197 const table = Array.from({ length: one.length + 1 }, () =>198 Array.from({ length: other.length + 1 }, () => 0)199 );200201 for (let i = 1; i <= one.length; i += 1) {202 for (let j = 1; j <= other.length; j += 1) {203 const row = table[i] ?? [];204205 row[j] =206 one[i - 1] === other[j - 1]207 ? (table[i - 1]?.[j - 1] ?? 0) + 1208 : Math.max(table[i - 1]?.[j] ?? 0, row[j - 1] ?? 0);209 }210 }211212 return table[one.length]?.[other.length] ?? 0;213};214215const text = (lines: readonly string[]) =>216 lines.map((line) => `${line}\n`).join("");217218const isSubsequence = (part: readonly string[], whole: readonly string[]) => {219 let found = 0;220221 for (const line of whole) {222 if (line === part[found]) {223 found += 1;224 }225 }226227 return found === part.length;228};229230describe("the changes between two trees", () => {231 it.effect("finds each added, modified and deleted file with its blobs", () =>232 Effect.gen(function* () {233 const { base, blob, head } = yield* twoCommits;234 const changes = yield* treeDiff(repo, base, head);235236 expect(237 changes.toSorted((one, other) => one.path.localeCompare(other.path))238 ).toStrictEqual([239 {240 after: yield* blob(head, "assets/logo.bin"),241 path: RepoPath.make("assets/logo.bin"),242 status: "added",243 },244 {245 before: yield* blob(base, "docs/x.md"),246 path: RepoPath.make("docs/x.md"),247 status: "deleted",248 },249 {250 after: yield* blob(head, "src/a.ts"),251 before: yield* blob(base, "src/a.ts"),252 path: RepoPath.make("src/a.ts"),253 status: "modified",254 },255 {256 after: yield* blob(head, "src/b/c.ts"),257 path: RepoPath.make("src/b/c.ts"),258 status: "added",259 },260 ]);261 }).pipe(Effect.provide(RepoHostMemory))262 );263264 it.effect("never reads a subtree whose id did not change", () =>265 Effect.gen(function* () {266 const reads = yield* Ref.make<readonly string[]>([]);267268 yield* Effect.gen(function* () {269 const { base, head, tree } = yield* twoCommits;270 const kept = yield* tree(head, "lib");271272 expect(yield* tree(base, "lib")).toBe(kept);273274 yield* Ref.set(reads, []);275 yield* treeDiff(repo, base, head);276277 const read = yield* Ref.get(reads);278279 expect(read).toContain(base);280 expect(read).toContain(yield* tree(head, "src"));281 expect(read).not.toContain(kept);282 }).pipe(Effect.provide(countedBy(reads)));283 })284 );285286 it.effect("reads at most eight trees from the store at once", () =>287 Effect.gen(function* () {288 const reads = yield* Ref.make<InFlight>({ most: 0, now: 0 });289290 yield* Effect.gen(function* () {291 const repos = yield* RepoHost;292 const client = yield* gitClient(memoryFs());293 const first = yield* client.commit("before", grid("1\n"));294 const second = yield* client.commit("after", grid("2\n"), [first]);295296 yield* repos.create(repo);297 yield* repos.push(repo, client.source, [298 { from: Option.none(), ref: main, to: second },299 ]);300301 const treeOf = (sha: CommitSha) =>302 repos303 .readCommit(repo, sha)304 .pipe(305 Effect.map((commit) =>306 TreeSha.make(Option.getOrThrow(commit).tree)307 )308 );309310 const changes = yield* treeDiff(311 repo,312 yield* treeOf(first),313 yield* treeOf(second)314 );315316 expect(changes).toHaveLength(81);317 }).pipe(Effect.provide(inFlightBy(reads)));318319 expect(yield* Ref.get(reads)).toStrictEqual({ most: 8, now: 0 });320 })321 );322323 it.effect(324 "counts a submodule's moved pointer as a change with no lines",325 () =>326 Effect.gen(function* () {327 const links = yield* Ref.make<ReadonlyMap<string, TreeEntry>>(328 new Map()329 );330331 yield* Effect.gen(function* () {332 const { base, head } = yield* twoCommits;333334 yield* Ref.set(335 links,336 new Map([337 [base, pointer("a")],338 [head, pointer("b")],339 ])340 );341342 const changes = yield* treeDiff(repo, base, head);343 const lines = yield* addedLines(repo, changes);344345 expect(346 changes.filter(({ path }) => path === RepoPath.make("vendor"))347 ).toStrictEqual([348 {349 after: BlobSha.make("b".repeat(40)),350 before: BlobSha.make("a".repeat(40)),351 path: RepoPath.make("vendor"),352 status: "modified",353 },354 ]);355 expect(lines.get(RepoPath.make("vendor"))).toStrictEqual([]);356 expect(lines.get(RepoPath.make("src/a.ts"))).toHaveLength(3);357 }).pipe(Effect.provide(withSubmodules(links)));358 })359 );360361 it.effect("gives a modified file's new lines, numbered in the new file", () =>362 Effect.gen(function* () {363 const { base, head } = yield* twoCommits;364 const lines = yield* addedLines(repo, yield* treeDiff(repo, base, head));365366 expect(lines.get(RepoPath.make("src/a.ts"))).toStrictEqual([367 { line: 2, text: "between" },368 { line: 5, text: "FOUR" },369 { line: 6, text: "five" },370 ]);371 expect(lines.get(RepoPath.make("src/b/c.ts"))).toStrictEqual([372 { line: 1, text: "export const c = 3;" },373 ]);374 expect(lines.get(RepoPath.make("assets/logo.bin"))).toStrictEqual([]);375 expect([...lines.keys()]).not.toContain(RepoPath.make("docs/x.md"));376 }).pipe(Effect.provide(RepoHostMemory))377 );378379 it.effect(380 "keeps a longest common run of lines and calls only the rest added",381 () =>382 Effect.gen(function* () {383 const repos = yield* RepoHost;384 const client = yield* gitClient(memoryFs());385386 const cases = yield* Effect.forEach(387 randomFiles(60),388 ([previous, next], index) =>389 Effect.gen(function* () {390 const name = RepoName.make(`case-${index}`);391392 const first = yield* client.commit("before", [393 ["f.txt", text(previous)],394 ]);395396 const second = yield* client.commit(397 "after",398 [["f.txt", text(next)]],399 [first]400 );401402 yield* repos.create(name);403 yield* repos.push(name, client.source, [404 { from: Option.none(), ref: main, to: second },405 ]);406407 const treeOf = (sha: CommitSha) =>408 repos409 .readCommit(name, sha)410 .pipe(411 Effect.map((commit) =>412 TreeSha.make(Option.getOrThrow(commit).tree)413 )414 );415416 const changes = yield* treeDiff(417 name,418 yield* treeOf(first),419 yield* treeOf(second)420 );421422 const lines = yield* addedLines(name, changes);423424 const fresh = new Set(425 (lines.get(RepoPath.make("f.txt")) ?? []).map(426 ({ line }) => line427 )428 );429430 const kept = next.filter((_, at) => !fresh.has(at + 1));431432 return {433 kept: kept.length,434 longest: lcs(previous, next),435 pair: `${previous.join("")} -> ${next.join("")}`,436 subsequence: isSubsequence(kept, previous),437 };438 })439 );440441 // Every case keeps a common subsequence as long as any there is.442 expect(443 cases.filter(444 ({ kept, longest, subsequence }) => !subsequence || kept !== longest445 )446 ).toStrictEqual([]);447 }).pipe(Effect.provide(RepoHostMemory))448 );449});
added:packages/git/test/upstream.test.ts+285 added
1import { describe, expect, it } from "@effect/vitest";2import { Fetch, FetchFailed } from "@repo/artifacts/fetch";3import { RepoHost, RepoName, RepoNotFound } from "@repo/artifacts/repo-host";4import type { TokenScope } from "@repo/artifacts/repo-host";5import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";6import {7 DateTime,8 Duration,9 Effect,10 Layer,11 Redacted,12 Ref,13 Stream,14} from "effect";15import { TestClock } from "effect/testing";1617import { Exchange, Upstream, UpstreamFailure } from "../src/upstream.ts";18import { UpstreamRepoHost } from "../src/upstream/repo-host.ts";1920const repo = RepoName.make("demo");2122/** A token the store minted: its scope, its secret and when it expires. */23interface Minted {24 readonly scope: TokenScope;25 readonly secret: string;26 readonly expiresAt: DateTime.Utc;27}2829/** What one test sees: every request sent upstream and every token minted. */30interface Seen {31 readonly requests: Ref.Ref<readonly Request[]>;32 readonly minted: Ref.Ref<readonly Minted[]>;33}3435/**36 * The memory store, minting tokens shaped like Artifacts' (a secret, then37 * `?expires=`), with each mint written to `minted`.38 */39const store = (minted: Seen["minted"]) =>40 Layer.effect(41 RepoHost,42 Effect.gen(function* () {43 const host = yield* RepoHost;4445 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);5152 yield* Ref.update(minted, (all) => [53 ...all,54 { expiresAt: token.expiresAt, scope, secret },55 ]);5657 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));6768/** A `Fetch` that writes down each request and answers 200. */69const 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 );7980const world = (seen: Seen) =>81 UpstreamRepoHost.pipe(82 Layer.provideMerge(83 Layer.mergeAll(store(seen.minted), recording(seen.requests))84 )85 );8687const advertise = Exchange.Advertise({88 headers: new Headers({ "git-protocol": "version=2" }),89 service: "git-upload-pack",90});9192/** Runs `body` against the upstream over the memory store, with `demo` created. */93const 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 };101102 return yield* Effect.gen(function* () {103 yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);104105 return yield* body(seen);106 }).pipe(Effect.provide(world(seen)));107 });108109const basic = (secret: string) => `Basic ${btoa(`x:${secret}`)}`;110111/** What the upstream sent: the method, the URL and the headers that matter. */112const 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});118119describe("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);129130 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 );148149 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));154155 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 );167168 const [request] = yield* Ref.get(seen.requests);169 const minted = yield* Ref.get(seen.minted);170171 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 );189190 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;196197 yield* upstream.exchange(repo, advertise);198 yield* upstream.exchange(repo, advertise);199200 const first = yield* Ref.get(seen.minted);201202 expect(first).toHaveLength(1);203204 // 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 );212213 yield* TestClock.adjust(214 Duration.subtract(lasts, Duration.seconds(1))215 );216 yield* upstream.exchange(repo, advertise);217218 expect(yield* Ref.get(seen.minted)).toHaveLength(1);219220 yield* TestClock.adjust(Duration.seconds(1));221 yield* upstream.exchange(repo, advertise);222223 const minted = yield* Ref.get(seen.minted);224 const requests = yield* Ref.get(seen.requests);225226 expect(minted).toHaveLength(2);227 expect(requests.at(-1)?.headers.get("authorization")).toBe(228 basic(minted[1]?.secret ?? "")229 );230 })231 )232 );233234 it.effect("calls a request that got no response an UpstreamFailure", () =>235 Effect.gen(function* () {236 const unreachable = Layer.succeed(237 Fetch,238 Fetch.of({239 fetch: (request) =>240 Effect.fail(241 new FetchFailed({ reason: "connection reset", url: request.url })242 ),243 })244 );245246 const minted = yield* Ref.make<readonly Minted[]>([]);247248 const failure = yield* Effect.gen(function* () {249 yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);250251 return yield* Upstream.use((upstream) =>252 upstream.exchange(repo, advertise)253 ).pipe(Effect.flip);254 }).pipe(255 Effect.provide(256 UpstreamRepoHost.pipe(257 Layer.provideMerge(Layer.mergeAll(store(minted), unreachable))258 )259 )260 );261262 expect(failure).toStrictEqual(263 new UpstreamFailure({ reason: "connection reset", repo })264 );265 })266 );267268 it.effect("passes RepoNotFound through for a repo the store lacks", () =>269 withUpstream(() =>270 Effect.gen(function* () {271 const upstream = yield* Upstream;272 const missing = RepoName.make("missing");273274 expect(275 yield* upstream.exchange(missing, advertise).pipe(276 Effect.match({277 onFailure: (error) => error,278 onSuccess: () => "forwarded",279 })280 )281 ).toStrictEqual(new RepoNotFound({ name: missing }));282 })283 )284 );285});