Skip to content
Myr

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.

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

  • tests:+1061 added−0 removed
  • other:+1108 added−0 removed

10 files+2169 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+364 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 Person {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): Person => ({28 email: `${handle}@users.${Brand.domain}`,29 name: handle,30});3132/** The platform, which commits every landing. */33export const committerLine: Person = {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/** One line, so no value or subject can open a paragraph or a trailer of its own. */58const oneLine = (text: string) => text.replaceAll(/\s+/gu, " ").trim();5960const personOf = (handle: Handle) => {61 const { email, name } = authorLine(handle);6263 return `${name} <${email}>`;64};6566// The kernel's `AGENT:MODEL` shape, then whether the platform confirmed it:67// `claude-code:opus-4 (verified)`. A harness name holds no colon.68const agentOf = ({ harness, model, verified }: AgentTrailer) =>69 `${oneLine(harness)}${model === undefined ? "" : `:${oneLine(model)}`} (${verified ? "verified" : "claimed"})`;7071const roleOrder = (role: CreditRole) => CreditRole.literals.indexOf(role);7273/**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 */77const 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 );8384/**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 */89export 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 ];117118 const body = input.body?.trim() ?? "";119120 const paragraphs = [121 oneLine(input.subject),122 ...(body === "" ? [] : [body]),123 ...(trailers.length === 0124 ? []125 : [trailers.map(({ key, value }) => `${key}: ${value}`).join("\n")]),126 ];127128 return `${paragraphs.join("\n\n")}\n`;129};130131// C's `isspace`, which git's trailer code tests with.132const SPACE = /^[ \t\n\v\f\r]/u;133134const isSpace = (text: string) => SPACE.test(text);135136const isBlank = (line: string) => /^[ \t\n\v\f\r]*$/u.test(line);137138const isComment = (line: string) => line.startsWith("#");139140// Lines git counts as trailers whatever the rest of the paragraph holds.141const GIT_GENERATED = ["Signed-off-by: ", "(cherry picked from commit "];142143/**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 */147const separatorOf = (line: string) => {148 let blank = false;149150 for (let at = 0; at < line.length; at += 1) {151 const char = line.charAt(at);152153 if (char === ":") {154 return at;155 }156157 if (!blank && /^[A-Za-z0-9-]$/u.test(char)) {158 continue;159 }160161 if (at > 0 && (char === " " || char === "\t")) {162 blank = true;163 continue;164 }165166 break;167 }168169 return -1;170};171172/** The message's lines up to a `---` divider, less trailing comments and empty lines. */173const logLines = (message: string) => {174 const lines = message.split("\n");175 const ended = message.endsWith("\n");176177 if (ended) {178 lines.pop();179 }180181 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 );188189 const kept = divider === -1 ? lines : lines.slice(0, divider);190 let end = kept.length;191192 while (end > 0 && (kept[end - 1] === "" || isComment(kept[end - 1] ?? ""))) {193 end -= 1;194 }195196 return kept.slice(0, end);197};198199/**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 */204const blockStart = (lines: readonly string[]): Option.Option<number> => {205 const titleEnd = lines.findIndex((line) => !isComment(line) && isBlank(line));206207 if (titleEnd === -1) {208 return Option.none();209 }210211 let onlySpaces = true;212 let recognized = false;213 let trailerLines = 0;214 let otherLines = 0;215 let continuations = 0;216217 for (let at = lines.length - 1; at >= titleEnd; at -= 1) {218 const line = lines[at] ?? "";219220 if (isComment(line)) {221 otherLines += continuations;222 continuations = 0;223 } else if (isBlank(line)) {224 if (!onlySpaces) {225 otherLines += continuations;226227 return (recognized && trailerLines * 3 >= otherLines) ||228 (trailerLines > 0 && otherLines === 0)229 ? Option.some(at + 1)230 : Option.none();231 }232 } else {233 onlySpaces = false;234235 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 }250251 return Option.none();252};253254/** A value with its continuation lines folded to single spaces. */255const 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, "");260261/**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 */266export const parseTrailers = (message: string): readonly Trailer[] => {267 const lines = logLines(message);268269 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;275276 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 }284285 return items.flatMap((item) => {286 const cut = separatorOf(item);287288 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};300301const escaped = (text: string) =>302 text.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`);303304// Exactly what `personOf` writes: a handle at the platform's users domain.305const PERSON = new RegExp(306 `^(?<handle>[A-Za-z0-9][A-Za-z0-9-]*) <\\k<handle>@users\\.${escaped(Brand.domain)}>$`,307 "u"308);309310const AGENT =311 /^(?<harness>[^:]+?)(?::(?<model>.+))? \((?<mark>claimed|verified)\)$/u;312313const decodeRole = Schema.decodeUnknownOption(CreditRole);314315const decodeHandle = Schema.decodeUnknownOption(Handle);316317const 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 );324325 const handle = yield* decodeHandle(PERSON.exec(value)?.groups?.handle);326327 return { handle, role };328 });329330const agentFrom = ({ key, value }: Trailer): Option.Option<AgentTrailer> => {331 const groups = AGENT.exec(value)?.groups;332333 if (key.toLowerCase() !== ASSISTED.toLowerCase() || groups === undefined) {334 return Option.none();335 }336337 const harness = groups.harness ?? "";338 const { model } = groups;339 const verified = groups.mark === "verified";340341 return Option.some(342 model === undefined ? { harness, verified } : { harness, model, verified }343 );344};345346/** The people a landing credits, and the agents it discloses. */347export interface LandingCredits {348 readonly credits: readonly Credit[];349 readonly assisted: readonly AgentTrailer[];350}351352/**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 */357export const creditsOf = (message: string): LandingCredits => {358 const trailers = parseTrailers(message);359360 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
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 } 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// Subtrees read at once: each read is a call to the store.25const READS = { concurrency: 8 } as const;2627const 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 });4041const treeIdOf = (entry: TreeEntry | undefined) =>42 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();4344// A submodule's pointer counts as a file at its path, so a change to it is seen.45const fileIdOf = (entry: TreeEntry | undefined) =>46 entry === undefined || entry.type === "tree"47 ? undefined48 : BlobSha.make(entry.sha);4950const fileChange = (51 path: string,52 before: BlobSha | undefined,53 after: BlobSha | undefined54): readonly Change[] => {55 const at = RepoPath.make(path);5657 if (before !== undefined && after !== undefined) {58 return [{ after, before, path: at, status: "modified" }];59 }6061 if (before !== undefined) {62 return [{ before, path: at, status: "deleted" }];63 }6465 return after === undefined ? [] : [{ after, path: at, status: "added" }];66};6768const 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 );7980 const beforeByName = new Map(before.map((entry) => [entry.name, entry]));81 const afterByName = new Map(after.map((entry) => [entry.name, entry]));8283 const names = Array.sort(84 new Set([...beforeByName.keys(), ...afterByName.keys()]),85 Order.String86 );8788 const changed = yield* Effect.forEach(89 names,90 (name) => {91 const old = beforeByName.get(name);92 const next = afterByName.get(name);9394 // 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 }9899 const path = `${prefix}${name}`;100 const files = fileChange(path, fileIdOf(old), fileIdOf(next));101 const inside = [treeIdOf(old), treeIdOf(next)] as const;102103 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 );111112 return changed.flat();113 });114115/**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 */120export 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));126127// git's own test: a NUL among the first bytes means the blob is not text.128const SNIFF = 8192;129130const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);131132const linesOf = (bytes: Uint8Array) => {133 const text = new TextDecoder().decode(bytes);134 const lines = text.split("\n");135136 if (text.endsWith("\n")) {137 lines.pop();138 }139140 return lines;141};142143// Past this many edits the diff stops looking for the shortest script.144const MAX_EDITS = 1024;145146const at = (values: Int32Array, index: number) => values[index] ?? 0;147148/**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 */152const 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;159160 for (let edits = trace.length - 1; edits > 0; edits -= 1) {161 const previous = trace[edits - 1] ?? new Int32Array();162 const diagonal = x - y;163164 const reached = (k: number) => at(previous, k + edits - 1);165166 const down =167 diagonal === -edits ||168 (diagonal !== edits && reached(diagonal - 1) < reached(diagonal + 1));169170 const from = down ? diagonal + 1 : diagonal - 1;171172 x = reached(from);173 y = x - from;174175 if (down) {176 inserts.push(y);177 }178 }179180 return inserts.toReversed();181};182183/**184 * Lines of `next` with no partner in `previous`, matched by count: the185 * fallback for a rewrite too large for the shortest script.186 */187const unmatched = (previous: readonly string[], next: readonly string[]) => {188 const left = new Map<string, number>();189190 for (const line of previous) {191 left.set(line, (left.get(line) ?? 0) + 1);192 }193194 return next.flatMap((line, index) => {195 const count = left.get(line) ?? 0;196197 left.set(line, count - 1);198199 return count > 0 ? [] : [index];200 });201};202203/**204 * Indexes of the lines of `next` a shortest edit script from `previous`205 * inserts (Myers' O(ND) diff).206 */207const 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[] = [];214215 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;223224 let y = x - diagonal;225226 while (x < n && y < m && previous[x] === next[y]) {227 x += 1;228 y += 1;229 }230231 reach[offset + diagonal] = x;232233 if (x >= n && y >= m) {234 trace.push(reach.slice(offset - edits, offset + edits + 1));235236 return insertsFrom(trace, { m, n });237 }238 }239240 trace.push(reach.slice(offset - edits, offset + edits + 1));241 }242243 return unmatched(previous, next);244};245246/** The lines of `next` that are not in `previous`, numbered from 1. */247const added = (248 previous: readonly string[],249 next: readonly string[]250): readonly AddedLine[] => {251 let start = 0;252253 while (254 start < previous.length &&255 start < next.length &&256 previous[start] === next[start]257 ) {258 start += 1;259 }260261 let end = 0;262263 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 }270271 const middle = myers(272 previous.slice(start, previous.length - end),273 next.slice(start, next.length - end)274 );275276 return middle.map((index) => ({277 line: start + index + 1,278 text: next[start + index] ?? "",279 }));280};281282const 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 );291292const 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 );300301/**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 */305export 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 );321322 const lines = Option.match(next, {323 onNone: () => [],324 onSome: (text) =>325 added(326 Option.getOrElse(previous, () => []),327 text328 ),329 });330331 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
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+168 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 return parsed === ""60 ? []61 : parsed.split("\n").map((line) => {62 const cut = line.indexOf(": ");6364 return { key: line.slice(0, cut), value: line.slice(cut + 2) };65 });66 }).pipe(Effect.scoped);6768// 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.71const 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];7980describe("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 ];9293 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 );101102 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 );112113 expect(114 edges.map((message) => ({115 message,116 trailers: parseTrailers(message),117 }))118 ).toStrictEqual(read);119 }).pipe(Effect.provide(NodeServices.layer)),120 20_000121 );122123 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 });133134 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 });157158 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
1import { describe, expect, it } from "@effect/vitest";2import {3 ObjectId,4 RefName,5 RepoHost,6 RepoName,7} from "@repo/artifacts/repo-host";8import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";9import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10import { BlobSha, RepoPath, TreeSha } from "@repo/protocol/ids";11import type { CommitSha } from "@repo/protocol/ids";12import { gitClient } from "@repo/testkit/git-client";13import type { Files } from "@repo/testkit/git-client";14import { Effect, Layer, Option, Ref } from "effect";1516import { addedLines, treeDiff } from "../src/tree-diff.ts";1718const repo = RepoName.make("demo");1920const main = RefName.make("refs/heads/main");2122const 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];2829const 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];3637/** The memory store, with each tree id `readTree` is asked for written to `reads`. */38const countedBy = (reads: Ref.Ref<readonly string[]>) =>39 Layer.effect(40 RepoHost,41 Effect.gen(function* () {42 const host = yield* RepoHost;4344 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));5354/** Two commits in `demo`, and the ids of their trees and blobs as git wrote them. */55const 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]);6061 yield* repos.create(repo);62 yield* repos.push(repo, client.source, [63 { from: Option.none(), ref: main, to: second },64 ]);6566 const treeOf = (sha: CommitSha) =>67 repos.readCommit(repo, sha).pipe(68 Effect.map(Option.getOrThrow),69 Effect.map(({ tree }) => TreeSha.make(tree))70 );7172 /** 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("/");7677 const entries = yield* repos78 .readTree(repo, ObjectId.make(root))79 .pipe(Effect.orDie, Effect.map(Option.getOrThrow));8081 const entry = entries.find(({ name }) => name === head);8283 if (entry === undefined) {84 return yield* Effect.die(`no ${path}`);85 }8687 return rest.length === 088 ? entry.sha89 : yield* idAt(entry.sha, rest.join("/"));90 });9192 const base = yield* treeOf(first);93 const head = yield* treeOf(second);9495 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});103104/** Lines from a three-word alphabet, from a fixed seed (Park and Miller's generator). */105const randomFiles = (cases: number) => {106 let state = 20_261_007;107108 const next = (below: number) => {109 state = (state * 16_807) % 2_147_483_647;110111 return state % below;112 };113114 const file = () =>115 Array.from({ length: next(9) }, () => ["a", "b", "c"][next(3)] ?? "a");116117 return Array.from({ length: cases }, () => [file(), file()] as const);118};119120/** The length of a longest common subsequence, by the textbook table. */121const 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 );125126 for (let i = 1; i <= one.length; i += 1) {127 for (let j = 1; j <= other.length; j += 1) {128 const row = table[i] ?? [];129130 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 }136137 return table[one.length]?.[other.length] ?? 0;138};139140const text = (lines: readonly string[]) =>141 lines.map((line) => `${line}\n`).join("");142143const isSubsequence = (part: readonly string[], whole: readonly string[]) => {144 let found = 0;145146 for (const line of whole) {147 if (line === part[found]) {148 found += 1;149 }150 }151152 return found === part.length;153};154155describe("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);160161 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 );188189 it.effect("never reads a subtree whose id did not change", () =>190 Effect.gen(function* () {191 const reads = yield* Ref.make<readonly string[]>([]);192193 yield* Effect.gen(function* () {194 const { base, head, tree } = yield* twoCommits;195 const kept = yield* tree(head, "lib");196197 expect(yield* tree(base, "lib")).toBe(kept);198199 yield* Ref.set(reads, []);200 yield* treeDiff(repo, base, head);201202 const read = yield* Ref.get(reads);203204 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 );210211 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));215216 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 );228229 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());235236 const cases = yield* Effect.forEach(237 randomFiles(60),238 ([previous, next], index) =>239 Effect.gen(function* () {240 const name = RepoName.make(`case-${index}`);241242 const first = yield* client.commit("before", [243 ["f.txt", text(previous)],244 ]);245246 const second = yield* client.commit(247 "after",248 [["f.txt", text(next)]],249 [first]250 );251252 yield* repos.create(name);253 yield* repos.push(name, client.source, [254 { from: Option.none(), ref: main, to: second },255 ]);256257 const treeOf = (sha: CommitSha) =>258 repos259 .readCommit(name, sha)260 .pipe(261 Effect.map((commit) =>262 TreeSha.make(Option.getOrThrow(commit).tree)263 )264 );265266 const changes = yield* treeDiff(267 name,268 yield* treeOf(first),269 yield* treeOf(second)270 );271272 const lines = yield* addedLines(name, changes);273274 const fresh = new Set(275 (lines.get(RepoPath.make("f.txt")) ?? []).map(276 ({ line }) => line277 )278 );279280 const kept = next.filter((_, at) => !fresh.has(at + 1));281282 return {283 kept: kept.length,284 longest: lcs(previous, next),285 pair: `${previous.join("")} -> ${next.join("")}`,286 subsequence: isSubsequence(kept, previous),287 };288 })289 );290291 // 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
1import { describe, expect, it } from "@effect/vitest";2import { Fetch } 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 } 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("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");239240 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});