Add packages/git: the git gateway, with custody and typed refusals in git's output
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- gateway(request) speaks git's smart HTTP: info/refs, git-upload-pack (protocol v2 passes straight through) and git-receive-pack. Packs stream through and are never held whole; the client's credentials never reach the upstream (accept, content-encoding, content-type and git-protocol only). - Upstream port: the git server behind the gateway, holding the platform's credentials. Custody port: admit before forwarding (a refusal forwards nothing) and review after the upstream took the push. A push lands whole or not at all at the gateway: every ref gets `ng <ref> <headline>`, and every refusal is explained on `remote:` lines, both from protocol/render. - Upstream rejections in the closed union: `stale ref` (Artifacts) and `incorrect old value provided` (git 2.56) become StaleBase, with main read from a fresh advertisement; Artifacts' busy reply (one side-band 3 packet, no report) becomes RepoBusy. - git's `0000` probe before a large push is forwarded untouched. - Tests drive real git through the gateway to `git http-backend`: clone and fetch, an admitted push, a chunked push past the post buffer, refusals before and after forwarding, a two-ref push, a ref moved under a push, and Artifacts' recorded busy reply. - tsconfig: packages/git/test may use effect/http and effect/process (user sign-off), to serve the gateway and run git. - S2 against live Artifacts (wanted-explainer S2-RESULTS.md): pass, +4.6% push latency, refusals shown in Claude Code.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+1584 added−1 removed
- tests:+681 added−0 removed
- other:+903 added−1 removed
Provenance
- Commit
d2fdbdc- Tree
f222362- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
ee6ebff
14 files changed+1584 added−1 removed
added:packages/git/src/custody.ts+36 added
123456789101112131415161718192021222324252627282930313233343536import type { RefName, RepoName } from "@repo/artifacts/repo-host";import type { CommitSha } from "@repo/protocol/ids";import type { Refusal } from "@repo/protocol/refusal";import { Context } from "effect";import type { Array, Effect, Option } from "effect";
/** One ref in a push: `None` for `from` creates it, for `to` deletes it. */export interface Command { readonly ref: RefName; readonly from: Option.Option<CommitSha>; readonly to: Option.Option<CommitSha>;}
/** * Who may push what. A push lands whole or not at all at the gateway: any * refusal turns every ref in it away, and each refusal reaches the pusher in * git's own output. */export class Custody extends Context.Service< Custody, { /** Before anything reaches the upstream; a refusal forwards nothing. */ readonly admit: ( repo: RepoName, commands: Array.NonEmptyReadonlyArray<Command> ) => Effect.Effect<readonly Refusal[]>; /** * After the upstream took the push, such as stage 0–1 over the * answerer's fork; a refusal reaches the pusher though the fork keeps it. */ readonly review: ( repo: RepoName, commands: Array.NonEmptyReadonlyArray<Command> ) => Effect.Effect<readonly Refusal[]>; }>()("git/Custody") {}added:packages/git/src/gateway.ts+361 added
1+import { RepoName } from "@repo/artifacts/repo-host";2+import type { CommitSha } from "@repo/protocol/ids";3+import { RepoBusy, StaleBase } from "@repo/protocol/refusal";4+import { headline } from "@repo/protocol/render";5+import { Array, Effect, Equal, Match, Option } from "effect";6+7+import { Custody } from "./custody.ts";8+import type { Command } from "./custody.ts";9+import {10+ drain,11+ readAdvertisement,12+ readOpening,13+ readReport,14+ refuseAll,15+ resume,16+ writeReport,17+} from "./receive-pack.ts";18+import type { Opening, RefStatus } from "./receive-pack.ts";19+import { Exchange, Upstream, UpstreamFailure } from "./upstream.ts";20+import type { Service } from "./upstream.ts";21+22+const ROUTE =23+ /^\/(?<name>[A-Za-z0-9._-]+?)(?:\.git)?\/(?<endpoint>info\/refs|git-upload-pack|git-receive-pack)$/u;24+25+const isService = (service: string | null): service is Service =>26+ service === "git-upload-pack" || service === "git-receive-pack";27+28+// What the upstream needs of the client's headers. Credentials are never on29+// the list: the upstream sees only the platform's.30+const FORWARDED = [31+ "accept",32+ "content-encoding",33+ "content-type",34+ "git-protocol",35+];36+37+const forwarded = (headers: Headers) => {38+ const picked = new Headers();39+40+ for (const name of FORWARDED) {41+ const value = headers.get(name);42+43+ if (value !== null) {44+ picked.set(name, value);45+ }46+ }47+48+ return picked;49+};50+51+/**52+ * Passes bytes and fails the stream on anything else: the Workers types leave53+ * a request body's chunk type open.54+ */55+const bytes = () =>56+ new TransformStream<unknown, Uint8Array>({57+ transform: (chunk, controller) => {58+ if (chunk instanceof Uint8Array) {59+ controller.enqueue(chunk);60+ } else {61+ controller.error(62+ new TypeError("a request body held something other than bytes")63+ );64+ }65+ },66+ });67+68+/** A POST's body, the only kind of request with one here. */69+const bodyOf = (request: Request) =>70+ request.method === "POST" && request.body !== null71+ ? Option.some(request.body.pipeThrough(bytes()))72+ : Option.none();73+74+const plain = (status: number, text: string) =>75+ new Response(`${text}\n`, {76+ headers: { "content-type": "text/plain; charset=utf-8" },77+ status,78+ });79+80+/** The upstream's reply as the client gets it: status, type and body, uncached. */81+const relay = (response: Response) =>82+ new Response(response.body, {83+ headers: {84+ "cache-control": "no-cache",85+ "content-type":86+ response.headers.get("content-type") ?? "application/octet-stream",87+ },88+ status: response.status,89+ });90+91+const result = (report: Uint8Array) =>92+ new Response(report, {93+ headers: {94+ "cache-control": "no-cache",95+ "content-type": "application/x-git-receive-pack-result",96+ },97+ });98+99+// What an upstream says when a ref moved under a push: Artifacts (S1), then100+// git's own receive-pack (2.56).101+const MOVED = new Set(["stale ref", "incorrect old value provided"]);102+103+// Artifacts' whole reply to a push it is too busy for: one fatal side-band104+// message and no report (S1, S2).105+const BUSY = "artifacts_git_receive_pack_busy";106+107+const busy = (messages: readonly Uint8Array[]) =>108+ messages.some((message) => new TextDecoder().decode(message).includes(BUSY));109+110+/** Where each ref in the upstream points now. */111+const tipsOf = (repo: RepoName) =>112+ Effect.gen(function* () {113+ const response = yield* (yield* Upstream).exchange(114+ repo,115+ Exchange.Advertise({116+ headers: new Headers(),117+ service: "git-receive-pack",118+ })119+ );120+121+ const advertisement = yield* Effect.tryPromise(() =>122+ response.arrayBuffer()123+ );124+125+ return yield* Effect.try(() =>126+ readAdvertisement(new Uint8Array(advertisement))127+ );128+ }).pipe(Effect.orElseSucceed(() => new Map<string, CommitSha>()));129+130+/**131+ * The upstream's refusals in the closed union: a ref that moved under the132+ * push is `StaleBase`, from the base the pusher named to where the ref is now.133+ */134+const translate = (135+ repo: RepoName,136+ commands: readonly Command[],137+ refs: readonly RefStatus[]138+) =>139+ Effect.gen(function* () {140+ const moved = refs.filter(({ ng }) =>141+ Option.exists(ng, (reason) => MOVED.has(reason))142+ );143+144+ if (moved.length === 0) {145+ return new Map<string, StaleBase>();146+ }147+148+ const tips = yield* tipsOf(repo);149+150+ return new Map(151+ moved.flatMap(({ ref }) => {152+ const base = commands.find((command) => command.ref === ref)?.from;153+ const tip = tips.get(ref);154+155+ return base === undefined || Option.isNone(base) || tip === undefined156+ ? []157+ : [158+ [159+ ref,160+ new StaleBase({ base: base.value, conflicts: [], main: tip }),161+ ] as const,162+ ];163+ })164+ );165+ });166+167+/**168+ * The upstream's reply to a push, as the pusher gets it. When every ref169+ * landed, custody reviews the push and may still turn it away. A reply that170+ * is not a report passes on as it came.171+ */172+const answer = (173+ repo: RepoName,174+ opening: Opening,175+ commands: Array.NonEmptyReadonlyArray<Command>,176+ response: Response177+) =>178+ Effect.gen(function* () {179+ if (response.status !== 200) {180+ return relay(response);181+ }182+183+ const reply = new Uint8Array(184+ yield* Effect.tryPromise({185+ catch: () =>186+ new UpstreamFailure({187+ reason: "the push's report was cut off",188+ repo,189+ }),190+ try: () => response.arrayBuffer(),191+ })192+ );193+194+ const report = Effect.try(() => readReport(opening.capabilities, reply));195+ const read = yield* Effect.option(report);196+197+ if (Option.isNone(read)) {198+ return result(reply);199+ }200+201+ const { messages, refs, unpack } = read.value;202+203+ if (busy(messages)) {204+ const refusals = [new RepoBusy()] as const;205+206+ return result(207+ writeReport(208+ opening.capabilities,209+ [],210+ refusals,211+ refuseAll(commands, refusals)212+ )213+ );214+ }215+216+ const translated = yield* translate(repo, commands, refs);217+218+ if (translated.size > 0) {219+ return result(220+ writeReport(221+ opening.capabilities,222+ messages,223+ [...translated.values()],224+ refs.map((status) => {225+ const refusal = translated.get(status.ref);226+227+ return refusal === undefined228+ ? status229+ : { ng: Option.some(headline([refusal])), ref: status.ref };230+ })231+ )232+ );233+ }234+235+ const landed =236+ Equal.equals(unpack, Option.some("ok")) &&237+ refs.length === commands.length &&238+ refs.every(({ ng }) => Option.isNone(ng));239+240+ if (!landed) {241+ return result(reply);242+ }243+244+ const refused = yield* (yield* Custody).review(repo, commands);245+246+ return Array.isReadonlyArrayNonEmpty(refused)247+ ? result(248+ writeReport(249+ opening.capabilities,250+ messages,251+ refused,252+ refuseAll(commands, refused)253+ )254+ )255+ : result(reply);256+ });257+258+/**259+ * A push: custody admits it or it goes no further. A refused push is read to260+ * its end and answered here; the upstream never sees it.261+ */262+const push = (263+ repo: RepoName,264+ headers: Headers,265+ body: ReadableStream<Uint8Array>266+) =>267+ Effect.gen(function* () {268+ const custody = yield* Custody;269+ const upstream = yield* Upstream;270+ const opening = yield* readOpening(body);271+272+ const forward = upstream.exchange(273+ repo,274+ Exchange.Call({275+ body: resume(opening.read, body),276+ headers,277+ service: "git-receive-pack",278+ })279+ );280+281+ // git's probe before a large push names no refs; nothing to judge.282+ if (!Array.isReadonlyArrayNonEmpty(opening.commands)) {283+ return relay(yield* forward);284+ }285+286+ const { commands } = opening;287+ const refused = yield* custody.admit(repo, commands);288+289+ if (Array.isReadonlyArrayNonEmpty(refused)) {290+ yield* drain(body);291+292+ return result(293+ writeReport(294+ opening.capabilities,295+ [],296+ refused,297+ refuseAll(commands, refused)298+ )299+ );300+ }301+302+ return yield* answer(repo, opening, commands, yield* forward);303+ }).pipe(304+ Effect.catchTag("Malformed", ({ reason }) =>305+ Effect.succeed(plain(400, reason))306+ )307+ );308+309+/**310+ * The platform's git endpoint, speaking git's smart HTTP: `info/refs`,311+ * `git-upload-pack` (protocol v2 passes straight through) and312+ * `git-receive-pack`. Packs stream through and are never held whole.313+ */314+export const gateway = (315+ request: Request316+): Effect.Effect<Response, never, Upstream | Custody> =>317+ Effect.gen(function* () {318+ const url = new URL(request.url);319+ const route = ROUTE.exec(url.pathname)?.groups;320+321+ if (route?.name === undefined) {322+ return plain(404, "not a git endpoint");323+ }324+325+ const upstream = yield* Upstream;326+ const repo = RepoName.make(route.name);327+ const headers = forwarded(request.headers);328+329+ return yield* Match.value(route.endpoint).pipe(330+ Match.when("info/refs", () => {331+ const service = url.searchParams.get("service");332+333+ return request.method === "GET" && isService(service)334+ ? upstream335+ .exchange(repo, Exchange.Advertise({ headers, service }))336+ .pipe(Effect.map(relay))337+ : Effect.succeed(plain(403, "this gateway speaks smart HTTP only"));338+ }),339+ Match.when("git-upload-pack", (service) =>340+ Option.match(bodyOf(request), {341+ onNone: () => Effect.succeed(plain(405, "POST a git request")),342+ onSome: (body) =>343+ upstream344+ .exchange(repo, Exchange.Call({ body, headers, service }))345+ .pipe(Effect.map(relay)),346+ })347+ ),348+ Match.when("git-receive-pack", () =>349+ Option.match(bodyOf(request), {350+ onNone: () => Effect.succeed(plain(405, "POST a git request")),351+ onSome: (body) => push(repo, headers, body),352+ })353+ ),354+ Match.orElse(() => Effect.succeed(plain(404, "not a git endpoint")))355+ );356+ }).pipe(357+ Effect.catchTags({358+ RepoNotFound: ({ name }) => Effect.succeed(plain(404, `no repo ${name}`)),359+ UpstreamFailure: ({ reason }) => Effect.succeed(plain(502, reason)),360+ })361+ );added:packages/git/src/pkt-line.ts+85 added
1+/**2+ * git's pkt-line framing (gitprotocol-common): four hex digits giving the3+ * line's length including themselves, then the payload; `0000` is a flush.4+ */5+import { Option } from "effect";6+7+const encoder = new TextEncoder();8+9+export const FLUSH = encoder.encode("0000");10+11+export const concat = (parts: readonly Uint8Array[]) => {12+ const all = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));13+ let at = 0;14+15+ for (const part of parts) {16+ all.set(part, at);17+ at += part.length;18+ }19+20+ return all;21+};22+23+export const utf8 = (text: string) => encoder.encode(text);24+25+/** One pkt-line around `payload`. */26+export const pkt = (payload: Uint8Array) =>27+ concat([28+ encoder.encode((payload.length + 4).toString(16).padStart(4, "0")),29+ payload,30+ ]);31+32+/** A data line's payload, or `Flush`. */33+export type Packet = Uint8Array | "Flush";34+35+/**36+ * The packet that starts at `at`, with where the next one starts; `None` if37+ * the bytes stop before the packet does.38+ */39+export const packetAt = (40+ bytes: Uint8Array,41+ at: number42+): Option.Option<{ readonly packet: Packet; readonly next: number }> => {43+ if (bytes.length < at + 4) {44+ return Option.none();45+ }46+47+ const length = Number.parseInt(48+ new TextDecoder().decode(bytes.subarray(at, at + 4)),49+ 1650+ );51+52+ if (length === 0) {53+ return Option.some({ next: at + 4, packet: "Flush" });54+ }55+56+ if (Number.isNaN(length) || length < 4) {57+ throw new RangeError(`not a pkt-line length at byte ${at}`);58+ }59+60+ return bytes.length < at + length61+ ? Option.none()62+ : Option.some({63+ next: at + length,64+ packet: bytes.subarray(at + 4, at + length),65+ });66+};67+68+/** Every packet in `bytes`, which must hold whole packets only. */69+export const packets = (bytes: Uint8Array) => {70+ const found: Packet[] = [];71+ let at = 0;72+73+ while (at < bytes.length) {74+ const next = packetAt(bytes, at);75+76+ if (Option.isNone(next)) {77+ throw new RangeError(`a pkt-line runs past the end at byte ${at}`);78+ }79+80+ found.push(next.value.packet);81+ at = next.value.next;82+ }83+84+ return found;85+};added:packages/git/src/receive-pack.ts+296 added
1+/**2+ * The receive-pack side of git's smart HTTP (gitprotocol-pack): the command3+ * list that opens a push, and the report-status that answers it.4+ */5+import { RefName } from "@repo/artifacts/repo-host";6+import { CommitSha } from "@repo/protocol/ids";7+import type { Refusal } from "@repo/protocol/refusal";8+import { explain, headline } from "@repo/protocol/render";9+import { Array, Data, Effect, Option, Schema, Stream } from "effect";10+11+import type { Command } from "./custody.ts";12+import { FLUSH, concat, packetAt, packets, pkt, utf8 } from "./pkt-line.ts";13+14+/** The request is not a receive-pack request git would send. */15+export class Malformed extends Data.TaggedError("Malformed")<{16+ readonly reason: string;17+}> {}18+19+const ZERO = "0".repeat(40);20+21+const COMMAND =22+ /^(?<from>[0-9a-f]{40}) (?<to>[0-9a-f]{40}) (?<ref>[^\0\n ]+)(?:\0(?<capabilities>[^\n]*))?\n?$/u;23+24+const objectId = (hex: string) =>25+ hex === ZERO ? Option.none() : Option.some(CommitSha.make(hex));26+27+const isRefName = Schema.is(RefName);28+29+/** The opening of a push, and every byte read to find it. */30+export interface Opening {31+ readonly commands: readonly Command[];32+ readonly capabilities: ReadonlySet<string>;33+ readonly read: Uint8Array;34+}35+36+const parse = (lines: readonly string[]) =>37+ Effect.gen(function* () {38+ const commands: Command[] = [];39+ let capabilities = new Set<string>();40+41+ // A shallow clone names its shallow commits before its commands.42+ for (const line of lines.filter((text) => !text.startsWith("shallow "))) {43+ const fields = COMMAND.exec(line)?.groups;44+45+ if (fields?.from === undefined || fields.to === undefined) {46+ return yield* new Malformed({ reason: `not a push command: ${line}` });47+ }48+49+ if (fields.ref === undefined || !isRefName(fields.ref)) {50+ return yield* new Malformed({51+ reason: `not a ref this gateway carries: ${fields.ref ?? ""}`,52+ });53+ }54+55+ if (commands.length === 0) {56+ capabilities = new Set(57+ (fields.capabilities ?? "").split(" ").filter((word) => word !== "")58+ );59+ }60+61+ commands.push({62+ from: objectId(fields.from),63+ ref: fields.ref,64+ to: objectId(fields.to),65+ });66+ }67+68+ return { capabilities, commands };69+ });70+71+const packetIn = (bytes: Uint8Array, at: number) =>72+ Effect.try({73+ catch: () => new Malformed({ reason: `bad pkt-line at byte ${at}` }),74+ try: () => packetAt(bytes, at),75+ });76+77+const chunkOf = (reader: ReadableStreamDefaultReader<Uint8Array>) =>78+ Effect.tryPromise({79+ catch: () => new Malformed({ reason: "the push could not be read" }),80+ try: () => reader.read(),81+ });82+83+/**84+ * Reads a push's command list, up to its flush, from the request body, then85+ * lets the body go: the pack that follows stays unread in it. An empty list86+ * is git's probe before a large push.87+ */88+export const readOpening = (body: ReadableStream<Uint8Array>) =>89+ Effect.gen(function* () {90+ const reader = body.getReader();91+ const lines: string[] = [];92+ let read = new Uint8Array(0);93+ let at = 0;94+ let flushed = false;95+96+ while (!flushed) {97+ const next = yield* packetIn(read, at);98+99+ if (Option.isSome(next)) {100+ const { packet } = next.value;101+102+ at = next.value.next;103+ flushed = packet === "Flush";104+105+ if (packet !== "Flush") {106+ lines.push(new TextDecoder().decode(packet));107+ }108+ } else {109+ const chunk = yield* chunkOf(reader);110+111+ if (chunk.done) {112+ return yield* new Malformed({113+ reason: "the push ended inside its command list",114+ });115+ }116+117+ read = concat([read, chunk.value]);118+ }119+ }120+121+ reader.releaseLock();122+123+ const { capabilities, commands } = yield* parse(lines);124+125+ return { capabilities, commands, read } satisfies Opening;126+ });127+128+const rest = (body: ReadableStream<Uint8Array>) =>129+ Stream.fromReadableStream({130+ evaluate: () => body,131+ onError: () => new Malformed({ reason: "the push could not be read" }),132+ });133+134+/** Reads the rest of a body and drops it, so the client finishes sending. */135+export const drain = (body: ReadableStream<Uint8Array>) =>136+ Stream.runDrain(rest(body)).pipe(Effect.ignore);137+138+/** The bytes already read, then the rest of the body, as one stream. */139+export const resume = (read: Uint8Array, body: ReadableStream<Uint8Array>) =>140+ Stream.toReadableStream(Stream.concat(Stream.succeed(read), rest(body)));141+142+// The largest payload a side-band packet carries, by the client's capability.143+const bandLimit = (capabilities: ReadonlySet<string>) => {144+ if (capabilities.has("side-band-64k")) {145+ return Option.some(65_515);146+ }147+148+ return capabilities.has("side-band") ? Option.some(995) : Option.none();149+};150+151+const band = (channel: 1 | 2, payload: Uint8Array) =>152+ pkt(concat([Uint8Array.of(channel), payload]));153+154+const chunks = (bytes: Uint8Array, limit: number) => {155+ const parts: Uint8Array[] = [];156+157+ for (let at = 0; at < bytes.length; at += limit) {158+ parts.push(bytes.subarray(at, at + limit));159+ }160+161+ return parts;162+};163+164+/** One ref's line in a report: `None` if it landed, else git's reason. */165+export interface RefStatus {166+ readonly ref: string;167+ readonly ng: Option.Option<string>;168+}169+170+/** The upstream's answer to a push, out of its side band. */171+export interface UpstreamReport {172+ /** Side-band messages, which git prints as `remote:` lines. */173+ readonly messages: readonly Uint8Array[];174+ /** `ok`, or why the pack did not unpack; `None` if no report came. */175+ readonly unpack: Option.Option<string>;176+ readonly refs: readonly RefStatus[];177+}178+179+const text = (bytes: Uint8Array) =>180+ new TextDecoder().decode(bytes).replace(/\n$/u, "");181+182+const STATUS = /^(?<verdict>ok|ng) (?<ref>\S+)(?: (?<reason>.*))?$/u;183+184+/** Reads the upstream's reply to a push; throws if it is not pkt-lines. */185+export const readReport = (186+ capabilities: ReadonlySet<string>,187+ reply: Uint8Array188+): UpstreamReport => {189+ const messages: Uint8Array[] = [];190+ const status: Uint8Array[] = [];191+192+ if (Option.isSome(bandLimit(capabilities))) {193+ for (const packet of packets(reply)) {194+ if (packet !== "Flush") {195+ // Band 1 carries the report, 2 progress, 3 a fatal error.196+ (packet[0] === 1 ? status : messages).push(packet.subarray(1));197+ }198+ }199+ } else {200+ status.push(reply);201+ }202+203+ const lines = packets(concat(status)).flatMap((packet) =>204+ packet === "Flush" ? [] : [text(packet)]205+ );206+207+ const unpack = Option.fromNullishOr(208+ lines.find((line) => line.startsWith("unpack "))?.slice("unpack ".length)209+ );210+211+ const refs = lines.flatMap((line): RefStatus[] => {212+ const fields = STATUS.exec(line)?.groups;213+214+ return fields?.ref === undefined215+ ? []216+ : [217+ {218+ ng:219+ fields.verdict === "ng"220+ ? Option.some(fields.reason ?? "")221+ : Option.none(),222+ ref: fields.ref,223+ },224+ ];225+ });226+227+ return { messages, refs, unpack };228+};229+230+/**231+ * The reply a pusher gets: side-band messages, then every refusal explained,232+ * as `remote:` lines; then `ok` or `ng <ref> <reason>` for every ref.233+ */234+export const writeReport = (235+ capabilities: ReadonlySet<string>,236+ messages: readonly Uint8Array[],237+ refusals: readonly Refusal[],238+ refs: readonly RefStatus[]239+) => {240+ const reports =241+ capabilities.has("report-status") || capabilities.has("report-status-v2");242+243+ const status = reports244+ ? concat([245+ pkt(utf8("unpack ok\n")),246+ ...refs.map(({ ng, ref }) =>247+ pkt(248+ utf8(249+ Option.match(ng, {250+ onNone: () => `ok ${ref}\n`,251+ onSome: (reason) => `ng ${ref} ${reason}\n`,252+ })253+ )254+ )255+ ),256+ FLUSH,257+ ])258+ : new Uint8Array(0);259+260+ const explained = Array.isReadonlyArrayNonEmpty(refusals)261+ ? explain(refusals)262+ : [];263+264+ return Option.match(bandLimit(capabilities), {265+ onNone: () => status,266+ onSome: (limit) =>267+ concat([268+ ...messages.map((message) => band(2, message)),269+ ...explained.map((line) => band(2, utf8(`${line}\n`))),270+ ...chunks(status, limit).map((part) => band(1, part)),271+ FLUSH,272+ ]),273+ });274+};275+276+const ADVERTISED = /^(?<oid>[0-9a-f]{40}) (?<ref>[^\0\n ]+)/u;277+278+/** The refs in a ref advertisement (`info/refs`) and the commit each names. */279+export const readAdvertisement = (advertisement: Uint8Array) =>280+ new Map(281+ packets(advertisement).flatMap((packet) => {282+ const fields =283+ packet === "Flush" ? undefined : ADVERTISED.exec(text(packet))?.groups;284+285+ return fields?.oid === undefined || fields.ref === undefined286+ ? []287+ : [[fields.ref, CommitSha.make(fields.oid)] as const];288+ })289+ );290+291+/** Every ref turned away for the same refusals. */292+export const refuseAll = (293+ commands: readonly Command[],294+ refusals: Array.NonEmptyReadonlyArray<Refusal>295+): RefStatus[] =>296+ commands.map(({ ref }) => ({ ng: Option.some(headline(refusals)), ref }));added:packages/git/src/upstream.ts+44 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344import { RepoName } from "@repo/artifacts/repo-host";import type { RepoNotFound } from "@repo/artifacts/repo-host";import { Context, Data, Schema } from "effect";import type { Effect } from "effect";
/** The two git services the gateway carries. */export type Service = "git-upload-pack" | "git-receive-pack";
/** * One smart-HTTP exchange with the git server behind the gateway: a ref * advertisement (`GET info/refs?service=…`) or a service call (`POST * <service>`). The headers are the gateway's own pick of the client's; the * client's credentials are never among them. */export type Exchange = Data.TaggedEnum<{ Advertise: { readonly service: Service; readonly headers: Headers }; Call: { readonly service: Service; readonly headers: Headers; readonly body: ReadableStream<Uint8Array>; };}>;
export const Exchange = Data.taggedEnum<Exchange>();
/** The git server behind the gateway did not answer. */export class UpstreamFailure extends Schema.TaggedError<UpstreamFailure>()( "UpstreamFailure", { reason: Schema.String, repo: RepoName }) {}
/** * The git server the gateway forwards to, holding the platform's credentials: * Artifacts in production, `git http-backend` in tests. */export class Upstream extends Context.Service< Upstream, { readonly exchange: ( repo: RepoName, exchange: Exchange ) => Effect.Effect<Response, RepoNotFound | UpstreamFailure>; }>()("git/Upstream") {}added:packages/git/test/gateway.test.ts+340 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { CommitSha, RepoPath } from "@repo/protocol/ids";4+import { OutOfScope, StaleBase, TouchedJudge } from "@repo/protocol/refusal";5+import type { Refusal } from "@repo/protocol/refusal";6+import { Effect, Option, Ref } from "effect";7+8+import { Custody } from "../src/custody.ts";9+import { git, gitOk } from "./git.ts";10+import { admitAll, commit, world } from "./world.ts";11+12+/** Custody that refuses, before forwarding, any push touching `ref`. */13+const refusing = (ref: string, refusals: readonly Refusal[]) =>14+ Custody.of({15+ admit: (_repo, commands) =>16+ Effect.succeed(17+ commands.some((command) => command.ref === ref) ? refusals : []18+ ),19+ review: () => Effect.succeed([]),20+ });21+22+/**23+ * Artifacts' whole reply to a push it is too busy to take, as S2 recorded it:24+ * one side-band 3 (fatal) packet, then the end of the response.25+ */26+const artifactsBusy = () =>27+ new Response("0024\u0003artifacts_git_receive_pack_busy", {28+ headers: { "content-type": "application/x-git-receive-pack-result" },29+ });30+31+/**32+ * The lines git printed from the server's side band, less the spaces git pads33+ * them with to clear a progress line.34+ */35+const remoteLines = (stderr: string) =>36+ stderr37+ .split("\n")38+ .filter((line) => line.startsWith("remote: "))39+ .map((line) => line.trimEnd());40+41+// A credential the client sends; the gateway must keep it from the upstream.42+const asClient = ["-c", "http.extraHeader=Authorization: Bearer client-secret"];43+44+/** Text that compresses poorly, from a fixed seed (Park and Miller's generator). */45+const noise = (length: number) => {46+ const digits: string[] = [];47+ let state = 20_261_006;48+49+ while (digits.length < length) {50+ state = (state * 16_807) % 2_147_483_647;51+ digits.push((state % 16).toString(16));52+ }53+54+ return digits.join("");55+};56+57+describe("the gateway between git and its upstream", () => {58+ it.live(59+ "clones and fetches, keeping the client's credentials to itself",60+ () =>61+ Effect.gen(function* () {62+ const { root, seed, upstream, url } = yield* world(admitAll);63+ const clone = `${root}/clone`;64+65+ yield* gitOk(root, ...asClient, "clone", "--quiet", url, clone);66+67+ expect(yield* gitOk(clone, "rev-parse", "HEAD")).toBe(68+ yield* gitOk(seed, "rev-parse", "HEAD")69+ );70+71+ const second = yield* commit(seed, "second", { "b.txt": "b\n" });72+73+ yield* gitOk(seed, "push", "--quiet", upstream, "HEAD:refs/heads/main");74+ yield* gitOk(clone, ...asClient, "fetch", "--quiet");75+76+ expect(yield* gitOk(clone, "rev-parse", "origin/main")).toBe(second);77+ }).pipe(Effect.provide(NodeServices.layer)),78+ 20_00079+ );80+81+ it.live(82+ "forwards a push custody admits, and the upstream takes it",83+ () =>84+ Effect.gen(function* () {85+ const { root, upstream, url } = yield* world(admitAll);86+ const clone = `${root}/clone`;87+88+ yield* gitOk(root, "clone", "--quiet", url, clone);89+90+ const answer = yield* commit(clone, "answer", { "b.txt": "b\n" });91+92+ const pushed = yield* git(93+ clone,94+ "push",95+ "origin",96+ "HEAD:refs/heads/answer"97+ );98+99+ expect(pushed.exitCode).toBe(0);100+ expect(yield* gitOk(upstream, "rev-parse", "refs/heads/answer")).toBe(101+ answer102+ );103+ }).pipe(Effect.provide(NodeServices.layer)),104+ 20_000105+ );106+107+ it.live(108+ "forwards a push larger than git's post buffer, sent as a probe and then in chunks",109+ () =>110+ Effect.gen(function* () {111+ const { root, upstream, url } = yield* world(admitAll);112+ const clone = `${root}/clone`;113+114+ yield* gitOk(root, "clone", "--quiet", url, clone);115+116+ const answer = yield* commit(clone, "large", {117+ "large.bin": noise(300_000),118+ });119+120+ const pushed = yield* git(121+ clone,122+ // git's smallest post buffer; a larger request is probed with an123+ // empty one first, then streamed chunked.124+ "-c",125+ "http.postBuffer=65520",126+ "push",127+ "origin",128+ "HEAD:refs/heads/large"129+ );130+131+ expect(pushed.exitCode).toBe(0);132+ expect(yield* gitOk(upstream, "rev-parse", "refs/heads/large")).toBe(133+ answer134+ );135+ }).pipe(Effect.provide(NodeServices.layer)),136+ 20_000137+ );138+139+ it.live(140+ "refuses a push before forwarding it, in git's own output",141+ () =>142+ Effect.gen(function* () {143+ const stale = new StaleBase({144+ base: CommitSha.make("1".repeat(40)),145+ conflicts: [],146+ main: CommitSha.make("2".repeat(40)),147+ });148+149+ const { root, upstream, url } = yield* world(150+ refusing("refs/heads/main", [stale])151+ );152+153+ const clone = `${root}/clone`;154+155+ yield* gitOk(root, "clone", "--quiet", url, clone);156+ yield* commit(clone, "answer", { "b.txt": "b\n" });157+158+ const before = yield* gitOk(upstream, "rev-parse", "main");159+ const pushed = yield* git(clone, "push", "origin", "HEAD:main");160+161+ expect(pushed.exitCode).toBe(1);162+ expect(remoteLines(pushed.stderr)).toStrictEqual([163+ "remote: StaleBase: main moved to 2222222, past your base 1111111",164+ "remote: next: git pull --rebase",165+ "remote: retryable: yes",166+ ]);167+ expect(pushed.stderr).toContain(168+ " ! [remote rejected] HEAD -> main (StaleBase)"169+ );170+ expect(yield* gitOk(upstream, "rev-parse", "main")).toBe(before);171+ }).pipe(Effect.provide(NodeServices.layer)),172+ 20_000173+ );174+175+ it.live(176+ "turns a whole push away when custody refuses one of its refs",177+ () =>178+ Effect.gen(function* () {179+ const path = RepoPath.make("src/a.ts");180+181+ const { root, upstream, url } = yield* world(182+ refusing("refs/heads/main", [183+ new OutOfScope({ paths: [path] }),184+ new TouchedJudge({ paths: [path] }),185+ ])186+ );187+188+ const clone = `${root}/clone`;189+190+ yield* gitOk(root, "clone", "--quiet", url, clone);191+ yield* commit(clone, "answer", { "b.txt": "b\n" });192+193+ const before = yield* gitOk(upstream, "rev-parse", "main");194+195+ const pushed = yield* git(196+ clone,197+ "push",198+ "origin",199+ "HEAD:main",200+ "HEAD:refs/heads/answer"201+ );202+203+ expect(pushed.exitCode).toBe(1);204+ expect(pushed.stderr).toContain(205+ " ! [remote rejected] HEAD -> main (OutOfScope and 1 more)"206+ );207+ expect(pushed.stderr).toContain(208+ " ! [remote rejected] HEAD -> answer (OutOfScope and 1 more)"209+ );210+ expect(yield* gitOk(upstream, "rev-parse", "main")).toBe(before);211+ expect(212+ (yield* git(upstream, "rev-parse", "--verify", "--quiet", "answer"))213+ .exitCode214+ ).toBe(1);215+ }).pipe(Effect.provide(NodeServices.layer)),216+ 20_000217+ );218+219+ it.live(220+ "refuses a push after the upstream took it, when custody's review says so",221+ () =>222+ Effect.gen(function* () {223+ const outOfScope = new OutOfScope({224+ paths: [RepoPath.make("src/a.ts")],225+ });226+227+ const { root, upstream, url } = yield* world(228+ Custody.of({229+ admit: () => Effect.succeed([]),230+ review: () => Effect.succeed([outOfScope]),231+ })232+ );233+234+ const clone = `${root}/clone`;235+236+ yield* gitOk(root, "clone", "--quiet", url, clone);237+238+ const answer = yield* commit(clone, "answer", { "b.txt": "b\n" });239+240+ const pushed = yield* git(241+ clone,242+ "push",243+ "origin",244+ "HEAD:refs/heads/answer"245+ );246+247+ expect(pushed.exitCode).toBe(1);248+ expect(remoteLines(pushed.stderr)).toContain(249+ "remote: OutOfScope: changes paths outside the ask's territory: src/a.ts"250+ );251+ expect(pushed.stderr).toContain(252+ " ! [remote rejected] HEAD -> answer (OutOfScope)"253+ );254+ // The answerer's fork keeps what the upstream took.255+ expect(yield* gitOk(upstream, "rev-parse", "answer")).toBe(answer);256+ }).pipe(Effect.provide(NodeServices.layer)),257+ 20_000258+ );259+260+ it.live(261+ "names a ref the upstream found moved under the push StaleBase",262+ () =>263+ Effect.gen(function* () {264+ const moved = yield* Ref.make(Option.none<string>());265+266+ const { root, upstream, url } = yield* world(admitAll, (repos) =>267+ Effect.gen(function* () {268+ const tip = yield* commit(repos.seed, "moved", { "c.txt": "c\n" });269+270+ yield* gitOk(271+ repos.seed,272+ "push",273+ "--quiet",274+ repos.upstream,275+ "HEAD:refs/heads/main"276+ );277+ yield* Ref.set(moved, Option.some(tip));278+279+ return Option.none();280+ })281+ );282+283+ const clone = `${root}/clone`;284+285+ yield* gitOk(root, "clone", "--quiet", url, clone);286+287+ const base = yield* gitOk(clone, "rev-parse", "HEAD");288+289+ yield* commit(clone, "answer", { "b.txt": "b\n" });290+291+ const pushed = yield* git(clone, "push", "origin", "HEAD:main");292+ const tip = Option.getOrThrow(yield* Ref.get(moved));293+294+ expect(pushed.exitCode).toBe(1);295+ expect(remoteLines(pushed.stderr).slice(-3)).toStrictEqual([296+ `remote: StaleBase: main moved to ${tip.slice(0, 7)}, past your base ${base.slice(0, 7)}`,297+ "remote: next: git pull --rebase",298+ "remote: retryable: yes",299+ ]);300+ expect(pushed.stderr).toContain(301+ " ! [remote rejected] HEAD -> main (StaleBase)"302+ );303+ expect(yield* gitOk(upstream, "rev-parse", "main")).toBe(tip);304+ }).pipe(Effect.provide(NodeServices.layer)),305+ 20_000306+ );307+308+ it.live(309+ "names Artifacts' busy refusal RepoBusy",310+ () =>311+ Effect.gen(function* () {312+ const { root, url } = yield* world(admitAll, () =>313+ Effect.succeedSome(artifactsBusy())314+ );315+316+ const clone = `${root}/clone`;317+318+ yield* gitOk(root, "clone", "--quiet", url, clone);319+ yield* commit(clone, "answer", { "b.txt": "b\n" });320+321+ const pushed = yield* git(322+ clone,323+ "push",324+ "origin",325+ "HEAD:refs/heads/answer"326+ );327+328+ expect(pushed.exitCode).toBe(1);329+ expect(remoteLines(pushed.stderr)).toStrictEqual([330+ "remote: RepoBusy: the repo was busy with another push",331+ "remote: next: git push",332+ "remote: retryable: yes",333+ ]);334+ expect(pushed.stderr).toContain(335+ " ! [remote rejected] HEAD -> answer (RepoBusy)"336+ );337+ }).pipe(Effect.provide(NodeServices.layer)),338+ 20_000339+ );340+});added:packages/git/test/git.ts+71 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import { Effect, Stream } from "effect";import type { Scope } from "effect";import { ChildProcess, ChildProcessSpawner } from "effect/process";
export interface Ran { readonly exitCode: number; readonly stdout: string; readonly stderr: string;}
// Fixed identity and dates, English messages, and no config from this machine.const env = { GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z", GIT_AUTHOR_EMAIL: "answerer@example.com", GIT_AUTHOR_NAME: "Answerer", GIT_COMMITTER_DATE: "2026-10-06T12:00:00Z", GIT_COMMITTER_EMAIL: "answerer@example.com", GIT_COMMITTER_NAME: "Answerer", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C",};
const text = <E>(bytes: Stream.Stream<Uint8Array, E>) => bytes.pipe(Stream.decodeText(), Stream.mkString);
/** Spawns a process and hands back its handle, for callers that feed stdin. */export const spawn = ( command: string, args: readonly string[], options: ChildProcess.CommandOptions): Effect.Effect< ChildProcessSpawner.ChildProcessHandle, never, ChildProcessSpawner.ChildProcessSpawner | Scope.Scope> => Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) => spawner.spawn( ChildProcess.make(command, args, { ...options, env: { ...env, ...options.env }, extendEnv: true, }) ) ).pipe(Effect.orDie);
/** Runs git in `cwd` to the end; a failing git is a result, not an error. */export const git = (cwd: string, ...args: string[]) => Effect.scoped( Effect.gen(function* () { const child = yield* spawn("git", args, { cwd });
const [stdout, stderr, exitCode] = yield* Effect.all( [text(child.stdout), text(child.stderr), child.exitCode], { concurrency: "unbounded" } ).pipe(Effect.orDie);
return { exitCode, stderr, stdout } satisfies Ran; }) );
/** Runs git and returns its trimmed output; a failing git fails the test. */export const gitOk = (cwd: string, ...args: string[]) => Effect.flatMap(git(cwd, ...args), (ran) => ran.exitCode === 0 ? Effect.succeed(ran.stdout.trim()) : Effect.die( `git ${args.join(" ")} exited ${ran.exitCode}: ${ran.stderr}` ) );added:packages/git/test/http-backend.ts+152 added
1+import type { RepoName } from "@repo/artifacts/repo-host";2+import { Effect, Option, Stream } from "effect";3+import type { ChildProcessSpawner } from "effect/process";4+5+import { Exchange, Upstream } from "../src/upstream.ts";6+import { spawn } from "./git.ts";7+8+const concat = (chunks: readonly Uint8Array[]) => {9+ const all = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));10+ let at = 0;11+12+ for (const chunk of chunks) {13+ all.set(chunk, at);14+ at += chunk.length;15+ }16+17+ return all;18+};19+20+const blankLine = (bytes: Uint8Array) => {21+ for (let at = 0; at + 3 < bytes.length; at += 1) {22+ if (23+ bytes[at] === 13 &&24+ bytes[at + 1] === 10 &&25+ bytes[at + 2] === 13 &&26+ bytes[at + 3] === 1027+ ) {28+ return at;29+ }30+ }31+32+ return -1;33+};34+35+/** A CGI reply (`Status:` and headers, a blank line, the body) as a Response. */36+const fromCgi = (output: Uint8Array) => {37+ const cut = blankLine(output);38+ const head = new TextDecoder().decode(output.slice(0, Math.max(cut, 0)));39+ const headers = new Headers();40+ let status = 200;41+42+ for (const line of head.split("\r\n")) {43+ const [name = "", ...rest] = line.split(": ");44+ const value = rest.join(": ");45+46+ if (name.toLowerCase() === "status") {47+ status = Number(value.split(" ")[0]);48+ } else if (name !== "") {49+ headers.append(name, value);50+ }51+ }52+53+ return new Response(output.slice(cut + 4), { headers, status });54+};55+56+const cgi = (root: string, repo: RepoName, exchange: Exchange) => {57+ const header = (name: string) => exchange.headers.get(name) ?? "";58+59+ const request = Exchange.$match(exchange, {60+ Advertise: ({ service }) => ({61+ PATH_INFO: `/${repo}.git/info/refs`,62+ QUERY_STRING: `service=${service}`,63+ REQUEST_METHOD: "GET",64+ }),65+ Call: ({ service }) => ({66+ PATH_INFO: `/${repo}.git/${service}`,67+ QUERY_STRING: "",68+ REQUEST_METHOD: "POST",69+ }),70+ });71+72+ return {73+ ...request,74+ CONTENT_TYPE: header("content-type"),75+ GIT_HTTP_EXPORT_ALL: "1",76+ GIT_PROJECT_ROOT: root,77+ GIT_PROTOCOL: header("git-protocol"),78+ HTTP_CONTENT_ENCODING: header("content-encoding"),79+ REMOTE_ADDR: "127.0.0.1",80+ // http-backend serves receive-pack only to an authenticated user.81+ REMOTE_USER: "gateway",82+ };83+};84+85+/**86+ * `git http-backend` over the bare repos in `root`, as the gateway's87+ * upstream. Like Artifacts, it takes no credentials from the client: an88+ * exchange carrying any is refused. `atPush` runs as each receive-pack call89+ * arrives, so a test can move a ref under a push; a reply it gives stands in90+ * for the upstream's.91+ */92+export const httpBackend = (93+ root: string,94+ atPush: Effect.Effect<95+ Option.Option<Response>,96+ never,97+ ChildProcessSpawner.ChildProcessSpawner98+ > = Effect.succeedNone99+) =>100+ Effect.map(101+ Effect.context<ChildProcessSpawner.ChildProcessSpawner>(),102+ (context) =>103+ Upstream.of({104+ exchange: (repo, exchange) =>105+ Effect.scoped(106+ Effect.gen(function* () {107+ if (exchange.headers.has("authorization")) {108+ return new Response(109+ "the client's credentials reached the upstream",110+ {111+ status: 400,112+ }113+ );114+ }115+116+ const stdin = Exchange.$match(exchange, {117+ Advertise: () => "ignore" as const,118+ Call: ({ body }) =>119+ Stream.fromReadableStream({120+ evaluate: () => body,121+ onError: (cause) => cause,122+ }).pipe(Stream.orDie),123+ });124+125+ const instead =126+ Exchange.$is("Call")(exchange) &&127+ exchange.service === "git-receive-pack"128+ ? yield* atPush129+ : Option.none();130+131+ if (Option.isSome(instead)) {132+ if (stdin !== "ignore") {133+ yield* Stream.runDrain(stdin);134+ }135+136+ return instead.value;137+ }138+139+ const child = yield* spawn("git", ["http-backend"], {140+ env: cgi(root, repo, exchange),141+ stdin,142+ });143+144+ const output = yield* Stream.runCollect(child.stdout).pipe(145+ Effect.orDie146+ );147+148+ return fromCgi(concat(output));149+ })150+ ).pipe(Effect.provide(context)),151+ })152+ );added:packages/git/test/world.ts+118 added
1+import { NodeHttpServer } from "@effect/platform-node";2+import { CommitSha } from "@repo/protocol/ids";3+import { Context, Effect, FileSystem, Layer } from "effect";4+import type { Option } from "effect";5+import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";6+import type { ChildProcessSpawner } from "effect/process";7+8+import { Custody } from "../src/custody.ts";9+import { gateway } from "../src/gateway.ts";10+import { Upstream } from "../src/upstream.ts";11+import { gitOk } from "./git.ts";12+import { httpBackend } from "./http-backend.ts";13+14+/** Custody that lets every push through. */15+export const admitAll = Custody.of({16+ admit: () => Effect.succeed([]),17+ review: () => Effect.succeed([]),18+});19+20+/** Writes the files, commits them all, and returns the commit's id. */21+export const commit = (22+ cwd: string,23+ message: string,24+ files: Readonly<Record<string, string>>25+) =>26+ Effect.gen(function* () {27+ const fs = yield* FileSystem.FileSystem;28+29+ for (const [path, content] of Object.entries(files)) {30+ yield* fs.writeFileString(`${cwd}/${path}`, content).pipe(Effect.orDie);31+ }32+33+ yield* gitOk(cwd, "add", "--all");34+ yield* gitOk(cwd, "commit", "--quiet", "--message", message);35+36+ return CommitSha.make(yield* gitOk(cwd, "rev-parse", "HEAD"));37+ });38+39+const app = Effect.gen(function* () {40+ const request = yield* HttpServerRequest.HttpServerRequest;41+ const response = yield* gateway(yield* HttpServerRequest.toWeb(request));42+43+ return HttpServerResponse.fromWeb(response);44+}).pipe(Effect.orDie);45+46+/** The two repos a test reaches past the gateway. */47+export interface Repos {48+ /** A work tree that pushes to the upstream directly. */49+ readonly seed: string;50+ /** The bare repo behind the gateway. */51+ readonly upstream: string;52+}53+54+/**55+ * A bare upstream repo `demo.git` whose `main` holds one commit, a `seed`56+ * clone that pushes to it directly, and the gateway in front of it on a57+ * local port, judging pushes with `custody`. `atPush` runs as each push58+ * reaches the upstream; a reply it gives stands in for the upstream's.59+ */60+export const world = (61+ custody: Custody["Service"],62+ atPush: (63+ repos: Repos64+ ) => Effect.Effect<65+ Option.Option<Response>,66+ never,67+ ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem68+ > = () => Effect.succeedNone69+) =>70+ Effect.gen(function* () {71+ const fs = yield* FileSystem.FileSystem;72+ const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);73+ const upstream = `${root}/demo.git`;74+ const seed = `${root}/seed`;75+76+ yield* gitOk(77+ root,78+ "init",79+ "--quiet",80+ "--bare",81+ "--initial-branch=main",82+ upstream83+ );84+ yield* gitOk(root, "init", "--quiet", "--initial-branch=main", seed);85+ yield* commit(seed, "first", { "README.md": "demo\n" });86+ yield* gitOk(seed, "push", "--quiet", upstream, "HEAD:refs/heads/main");87+88+ const served = yield* Layer.build(89+ HttpServer.serve(app).pipe(90+ Layer.provideMerge(NodeHttpServer.layerTest),91+ Layer.provide(92+ Layer.effect(93+ Upstream,94+ httpBackend(95+ root,96+ atPush({ seed, upstream }).pipe(97+ Effect.provideService(FileSystem.FileSystem, fs)98+ )99+ )100+ )101+ ),102+ Layer.provide(Layer.succeed(Custody, custody))103+ )104+ ).pipe(Effect.orDie);105+106+ const { address } = Context.get(served, HttpServer.HttpServer);107+108+ if (!("port" in address)) {109+ return yield* Effect.die("the gateway listens on a unix socket");110+ }111+112+ return {113+ root,114+ seed,115+ upstream,116+ url: `http://127.0.0.1:${address.port}/demo.git`,117+ };118+ });added:packages/git/package.json+27 added
123456789101112131415161718192021222324252627{ "name": "@repo/git", "private": true, "type": "module", "exports": { "./custody": "./src/custody.ts", "./gateway": "./src/gateway.ts", "./upstream": "./src/upstream.ts" }, "scripts": { "typecheck": "tsc --noEmit -p tsconfig.json", "test": "vitest run" }, "dependencies": { "@repo/artifacts": "workspace:*", "@repo/protocol": "workspace:*", "effect": "catalog:" }, "devDependencies": { "@cloudflare/workers-types": "5.20261006.1", "@effect/platform-node": "4.0.1", "@effect/vitest": "catalog:", "@repo/config": "workspace:*", "typescript": "catalog:", "vitest": "catalog:" }}added:packages/git/tsconfig.json+8 added
12345678{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true, "types": ["@cloudflare/workers-types"] }, "include": ["src/**/*.ts", "test/**/*.ts", "*.config.ts"]}added:packages/git/vitest.config.ts+1 added
1export { preset as default } from "@repo/config/vitest";modified:bun.lock+39 added-1 removed
51 unmodified lines52 "typescript": "catalog:",53 "vitest": "catalog:",54 },55 },56+ "packages/git": {57+ "name": "@repo/git",58+ "dependencies": {59+ "@repo/artifacts": "workspace:*",60+ "@repo/protocol": "workspace:*",61+ "effect": "catalog:",62+ },63+ "devDependencies": {64+ "@cloudflare/workers-types": "5.20261006.1",65+ "@effect/platform-node": "4.0.1",66+ "@effect/vitest": "catalog:",67+ "@repo/config": "workspace:*",68+ "typescript": "catalog:",69+ "vitest": "catalog:",70+ },71+ },72 "packages/protocol": {73 "name": "@repo/protocol",74 "dependencies": {75 "@repo/brand": "workspace:*",44 unmodified lines120 "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261001.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-oOk3Zj6k/8oP0FJgZBWDn7+BqbsqIMEMaV95pulHPVbwVu4wYoLfQq2hp0vkbCNsCFLqZb7cqixXdrwD54ZIow=="],121 122 "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261001.1", "", { "os": "win32", "cpu": "x64" }, "sha512-uRxm5W4VyBkoSaoP1BfOuH0873tE+vxsknF4sab6/5YIRvIAufChq3QDp+zlAn67PuGPGcn7W8QraA0t4ucmOQ=="],123 124+ "@cloudflare/workers-types": ["@cloudflare/workers-types@5.20261006.1", "", {}, "sha512-5OclwQK1d8f5LCPvOlyldC3ryKLUa4nLXegcgPZeUxAPudczQ9xujJDdpS2Tenp7JqbBLW3OgGciHJmuc7QShg=="],125+126 "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="],127 128 "@effect/platform-bun": ["@effect/platform-bun@4.0.1", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.1" }, "peerDependencies": { "effect": "^4.0.1" } }, "sha512-m+QR4bp39ZWujCuEsUhZADIYIOFZcUHHlmrixENZqZRbEYgaPLMUWiPrRJ69CM4BuuHW8oCOxfMGUU7oSw/o5g=="],129 130+ "@effect/platform-node": ["@effect/platform-node@4.0.1", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.1", "undici": "^8.11.2" }, "peerDependencies": { "effect": "^4.0.1", "redis": ">=5.0.0 <7.0.0" } }, "sha512-FT0Fu5LO0/XP9zBpj0HqrtJNLluK4StNKqf6TSulUsjp8FPBsDVXGJiDuyoN5J2yVMT7tgvhxSwaDcObWVRIaQ=="],131+132 "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.1", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.22.0" }, "peerDependencies": { "effect": "^4.0.1" } }, "sha512-VanaejudEhKJ4mpmqnEzdncVUhN6sGSO9ZDND54mRxAlZxj+4dYAWjDTYAy9o4tJo9aALeP2U8cVcOFzEdSeLg=="],133 134 "@effect/tsgo": ["@effect/tsgo@0.48.1", "", { "optionalDependencies": { "@effect/tsgo-darwin-arm64": "0.48.1", "@effect/tsgo-darwin-x64": "0.48.1", "@effect/tsgo-linux-arm": "0.48.1", "@effect/tsgo-linux-arm64": "0.48.1", "@effect/tsgo-linux-x64": "0.48.1", "@effect/tsgo-win32-arm64": "0.48.1", "@effect/tsgo-win32-x64": "0.48.1" }, "bin": { "effect-tsgo": "dist/effect-tsgo.cjs" } }, "sha512-yLgXNwPaUWfGxcQw7FwLYwOF7me69r+tY4oHYV5hwMFE16qClXbIRnotNPp8pZ5pnbeLgPeRvCE7AWGQyYqQ2A=="],135 178 unmodified lines314 "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],315 316 "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],317 318+ "@redis/bloom": ["@redis/bloom@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-NQ5poYpZr0jv6zazN1cy6JY5kIipKFZ3R9GTL4kOUTX3a9YAfY29U8bsE4lWhVQEM+G4V0BXVC57mubIdDijeA=="],319+320+ "@redis/client": ["@redis/client@6.3.0", "", { "peerDependencies": { "@node-rs/xxhash": "^1.1.0", "@opentelemetry/api": ">=1 <2" }, "optionalPeers": ["@node-rs/xxhash", "@opentelemetry/api"] }, "sha512-fHrjwGCBvAANGi+TuRuwKi83sIOzgHr8eh+Uf48w3fSX7Hhrz174NrWqfJhAC2vnN0d/tfaZpdr6+o6JC3QHwg=="],321+322+ "@redis/json": ["@redis/json@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-yt6vRfPBXtW/3qm53cF81TSQpLMjWdW4/2E9WQ2GgbvsKkuCKCFQIcMiKlil1ZMnezK+IQuS795xKU5psbaegw=="],323+324+ "@redis/search": ["@redis/search@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-RPXAZmKjZZG7Tm7m1w9keFdXzbL91PiSHQBfQRe9xwW40jNsTRbG0FwhIz4QlHPU4gKDAsCy8IQHj4yZl4H9rw=="],325+326+ "@redis/time-series": ["@redis/time-series@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-+fJOB8mN1z5WRakCJNh5lVdz1KqvHGSOistsKeitD24QsCtPwyRQXWC0iq6T/i/ubLE/YcguZqPm8F598MKk4A=="],327+328 "@repo/artifacts": ["@repo/artifacts@workspace:packages/artifacts"],329 330 "@repo/brand": ["@repo/brand@workspace:packages/brand"],331 332 "@repo/config": ["@repo/config@workspace:packages/config"],333 334+ "@repo/git": ["@repo/git@workspace:packages/git"],335+336 "@repo/protocol": ["@repo/protocol@workspace:packages/protocol"],337 338 "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.12", "", { "os": "android", "cpu": "arm" }, "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A=="],339 370 unmodified lines710 "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],711 712 "readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],713 714+ "redis": ["redis@6.3.0", "", { "dependencies": { "@redis/bloom": "6.3.0", "@redis/client": "6.3.0", "@redis/json": "6.3.0", "@redis/search": "6.3.0", "@redis/time-series": "6.3.0" } }, "sha512-XFQbPie1lGpKeUZ8ySYY43yLnQy/iIQtHNvIr/1XdaABpb96rUSdm3Mfl+98FEVbv9ZJIzINMno5s0Nh8E5LEw=="],715+716 "resolve.exports": ["resolve.exports@2.0.3", "", {}, "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A=="],717 718 "restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],719 60 unmodified lines780 "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="],781 782 "ultracite": ["ultracite@7.12.4", "", { "dependencies": { "@clack/prompts": "^1.8.1", "cli-truncate": "^6.1.1", "commander": "^15.0.0", "deepmerge": "^4.3.1", "empathic": "^2.1.0", "execa": "^10.0.1", "fast-glob": "^3.3.3", "find-workspaces": "^0.3.1", "jsonc-parser": "^3.3.1", "log-update": "^8.0.0", "magicast": "^0.5.5", "npm-run-path": "^6.0.0", "nypm": "^0.6.10", "resolve.exports": "^2.0.3", "semver": "^7.8.5", "string-width": "^8.3.0", "which-command": "^0.1.0", "yaml": "^2.9.1", "zod": "^4.6.5" }, "peerDependencies": { "@biomejs/biome": "^2.5.0", "eslint": "^10.9.0", "oxfmt": ">=0.59.0", "oxlint": "^1.86.0", "prettier": "^3.0.0", "stylelint": "^17.0.0" }, "optionalPeers": ["@biomejs/biome", "eslint", "oxfmt", "oxlint", "prettier", "stylelint"], "bin": { "ultracite": "dist/index.js" } }, "sha512-6jVEwaZBaytFm6XRoI3WGS2ZydrkrNvHTD0qTf7983ti2FlEWL1YcxnPaMaYuS6PkXqMhIK2XGr0cbsL4x5pQA=="],783 750- "undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],784+ "undici": ["undici@8.11.2", "", {}, "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ=="],785 786 "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],787 788 "unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],35 unmodified lines824 "@cspotcode/source-map-support/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="],825 826 "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],827 828+ "miniflare/undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],829+830 "miniflare/workerd": ["workerd@1.20260930.2", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260930.2", "@cloudflare/workerd-darwin-arm64": "1.20260930.2", "@cloudflare/workerd-linux-64": "1.20260930.2", "@cloudflare/workerd-linux-arm64": "1.20260930.2", "@cloudflare/workerd-windows-64": "1.20260930.2" }, "bin": { "workerd": "bin/workerd" } }, "sha512-k1lQzEiGyCDqaRsR5+o9PBT5wVU5omtas6hXx3spbEHHMFo8a7tkAixVCMsWFeiT7xhrmg21Hd6a9jLNrkcUMg=="],831 832 "miniflare/ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],833 834+ "@cloudflare/runtime-types/miniflare/undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],835+836 "@cloudflare/runtime-types/miniflare/ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],837 838 "miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260930.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-wxKsfekWeev6xkjHEMx3x7nz6WfWOn1/scQ8geqWQhUm8qRl1ZRZhjnj+rucIMLhLhP9RGSYMZIjEm3AV0zwVQ=="],839 9 unmodified linesmodified:tsconfig.base.json+6 added
69 unmodified lines70717273747576777879808182832 unmodified lines69 unmodified lines "include": ["scripts/**/*.ts"], "options": { "allowedUnstableApis": ["effect/process"] } }, { "include": ["packages/git/test/**/*.ts"], "options": { "allowedUnstableApis": ["effect/http", "effect/process"] } } ] } ]2 unmodified lines