@zabaca/zbc 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/update.ts +33 -6
  5. package/src/utils/detect-mode.ts +1 -1
  6. package/src/utils/host-workspaces.ts +57 -0
  7. package/src/utils/subtree.ts +54 -15
  8. package/src/utils/vendor-audit.ts +12 -8
  9. package/src/utils/vendor-stamp.ts +10 -0
  10. package/src/utils/vendored-app.ts +3 -0
  11. package/templates/apps/walgit/CONTEXT.md +45 -4
  12. package/templates/apps/walgit/README.md +394 -11
  13. package/templates/apps/walgit/shared/browse.ts +61 -0
  14. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  15. package/templates/apps/walgit/shared/container-env.ts +12 -0
  16. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  17. package/templates/apps/walgit/shared/credentials.ts +4 -0
  18. package/templates/apps/walgit/shared/events.ts +35 -1
  19. package/templates/apps/walgit/shared/instructions.ts +4 -1
  20. package/templates/apps/walgit/shared/landing.ts +2 -1
  21. package/templates/apps/walgit/shared/llms.ts +73 -5
  22. package/templates/apps/walgit/shared/mcp.ts +19 -3
  23. package/templates/apps/walgit/shared/protocol.ts +40 -3
  24. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  25. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  26. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  27. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  28. package/templates/apps/walgit/shared/webhook.ts +281 -0
  29. package/templates/apps/walgit/src/admin.ts +510 -0
  30. package/templates/apps/walgit/src/announce-main.ts +17 -9
  31. package/templates/apps/walgit/src/announce.ts +86 -0
  32. package/templates/apps/walgit/src/browse.ts +255 -2
  33. package/templates/apps/walgit/src/cli.ts +140 -0
  34. package/templates/apps/walgit/src/expire.ts +5 -0
  35. package/templates/apps/walgit/src/git.ts +103 -0
  36. package/templates/apps/walgit/src/hook-main.ts +6 -3
  37. package/templates/apps/walgit/src/http.ts +563 -3
  38. package/templates/apps/walgit/src/limits.ts +3 -0
  39. package/templates/apps/walgit/src/merge.ts +525 -0
  40. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  41. package/templates/apps/walgit/src/server.ts +65 -1
  42. package/templates/apps/walgit/worker/events-do.ts +218 -3
  43. package/templates/apps/walgit/worker/index.ts +134 -9
  44. package/templates/apps/walgit/worker/mcp.ts +17 -2
@@ -74,6 +74,10 @@ first push to a name printed `fatal:` before succeeding — which an agent reads
74
74
  Reading a repository in a browser: the list at `/repos`, and under it `/<name>` and `/<name>/tree/<ref>/<path>` (a directory), `/<name>/blob/<ref>/<path>` (a file), `/<name>/raw/<ref>/<path>` (its bytes) and `/<name>/commits/<ref>` (the history). One Advertised capability (`WALGIT_WEB`, `caps.web`), default off like every other. The list is a fold over Indexes and is answered at the **edge**, off the log, so it never wakes the container; a repository page needs git objects, which only the **Cache** holds, so it is answered by the container at `/_walgit/browse` and rendered at the edge. A Browse is a **read**: it never creates a name, and it is behind exactly the gate a clone is behind — the deployment credential, then the **Read Challenge** on a **Private** name.
75
75
  _Avoid_: the UI, the website, the dashboard (it shows what the log holds; it operates nothing)
76
76
 
77
+ **Compare**:
78
+ One more **Browse** read: `op=compare&base=<ref>&head=<ref>` on `/_walgit/browse`, answering the head against its merge base with the base (three-dot) — the merge base, a per-file summary (added/modified/deleted/renamed, line counts, binary), totals and the unified diff, or the diff alone as text. Both sides are **Browse Refs**. Bounded at 300 files and 1 MiB of diff (`COMPARE_MAX_FILES`, `COMPARE_MAX_DIFF_BYTES`, `shared/browse.ts`), marked `truncated` past either while the totals still count every file. Gated as every Browse is, Scoped Tokens included.
79
+ _Disambiguate_: not a **Proposal**'s `merged`, which is ancestry and reads no diff; and not a **Host Merge**: a Compare reads and moves nothing.
80
+
77
81
  **Browse Ref**:
78
82
  What a browse URL is allowed to name: an entry in `index.refs` — with `refs/heads/` or `refs/tags/` allowed to be left off — or a full forty-character oid. Never a `HEAD`, an abbreviation or a rev-parse expression: whatever is accepted reaches `git ls-tree`, `cat-file` or `git log` as an operand, and the **Index** rather than the **Cache** is what decides, because the disk is a cache. A branch name may contain slashes, so the URL remainder after the page kind is split by **longest ref prefix** — `feature/x/src` is the branch `feature/x` and the directory `src`. The same split serves all four kinds.
79
83
 
@@ -97,7 +101,7 @@ The first of `README`, `README.md`, `README.txt` at a tree ROOT, case-insensitiv
97
101
 
98
102
  **Ref Event**:
99
103
  A message telling a subscriber that a watched ref is now at a given sha. Latest-state, never a replayed history: there is no cursor, no `since`, and no sequence number on the wire. A deletion is the same message with a null sha. When the ref is a branch and the move landed Proposals, it also carries `merged` — their ids — so a Watcher on `main` learns a Proposal landed without a second call; the field is absent, never empty, when it landed none, and a Handshake never carries it, because nothing moved. That is not a second kind of state: it is a property of the move, computed in `post-receive` by the same ancestry walk the Proposal read surface uses, and a subscriber that was disconnected reads what is open from `GET /<name>.git/proposals` instead.
100
- _Avoid_: notification (implies delivery to an endpoint, which is exactly what this is not), webhook
104
+ _Avoid_: notification (implies delivery to an endpoint, which is exactly what this is not), webhook (that is the **Push Webhook**, below)
101
105
 
102
106
  **Watch**:
103
107
  A subscriber's declared interest — a repository, optionally narrowed to named refs. Omitting the refs means every ref in that repository. Capped per connection at 64 repositories and 256 refs each, with no wildcard across repositories.
@@ -112,6 +116,10 @@ _Avoid_: the hub, the broker
112
116
  **Announce**:
113
117
  The container telling the Fan-out that refs moved, over `/_walgit/announce`, from `post-receive` — after the compare-and-swap has won and the push is durable, never from `reference-transaction`, which would announce a push that then loses. Authenticated, off the push's latency path, and never able to fail a push.
114
118
 
119
+ **Push Webhook**:
120
+ One HMAC-SHA256-signed POST per moved ref to the single URL a deployment's operator configured (`WALGIT_WEBHOOK_URL` + `WALGIT_WEBHOOK_SECRET`), for a receiver that cannot hold a Watch open. It is the Announce's sibling, not a second source of truth: the same `post-receive` announcer produces both from the same ref changes, so it fires only for a durable push and for anything that moves a ref through that path. Unlike a Ref Event it is delivered at least once — bounded retry with backoff, a stable event `id` to de-duplicate on — because a URL has no Handshake to catch up through; it is still not a log, and an event whose attempts all fail, or whose retries a container restart interrupts, is dropped. Its delivery never fails or slows a push.
121
+ _Avoid_: callback, notification (for the stream, which this is not)
122
+
115
123
  **Coalesce Window**:
116
124
  The 250 ms in which one socket gets at most one message for a given repository and ref. A second move inside it REPLACES the queued message rather than joining it, so what a subscriber receives when the window elapses is the newest sha, once. It is a rate bound and not a reaction to a slow reader: the Workers runtime reports no backlog for a socket (no `bufferedAmount`), so there is nothing to react to. Sound only because a Ref Event is latest-state.
117
125
  _Avoid_: backpressure, throttling, debounce (each implies a reader being watched, or a message being dropped rather than superseded)
@@ -139,8 +147,8 @@ _Avoid_: identity, attribution log, audit trail
139
147
  _Avoid_: the provenance API, the audit endpoint
140
148
 
141
149
  **Source** / **Per-source limit**:
142
- The client one push is attributed to — the IP the edge saw (`cf-connecting-ip`, falling back to `x-forwarded-for`), which is all a Worker in front of a container can know — and the counts a deployment bounds it by in a window: new repositories, pushes, and pushed bytes (`src/rate-limit.ts`). Off unless configured, like every capability here. A request walgit cannot attribute to a Source is not limited, because pooling the unattributable into one bucket would let the first such request throttle every other. The verdict is reached at the smart-HTTP handler, the only layer that sees both the Source and the repository; it is **spoken** by `pre-receive`, because a status code on that route reaches git as `RPC failed; HTTP …` — a transport fault, which a client retries — while stderr from the hook reaches it as the same `remote:` reject line a size cap produces. The window is in memory and a container restart forgives it: over-forgiving is the safe direction, and a durable write per push would cost more than the spike it is there to make cheap.
143
- _Avoid_: rate limiting the repository (nothing here is per repository), throttling (nothing is slowed — a push is served or refused), the client's identity (a Source is an address, not a who)
150
+ Who one push is counted against, and the counts a deployment bounds it by in a window: new repositories, pushes, and pushed bytes (`src/rate-limit.ts`). The Source is the tenant when the push carries a verified **Scoped Token** with a `sub` claim — one bucket for that `sub`, across all its repositories and addresses, because hosted agents share cloud addresses — and otherwise (no scoped token, one without `sub`, the admin credential) the IP the edge saw (`cf-connecting-ip`, falling back to `x-forwarded-for`). The two key spaces are separate, so a `sub` never shares a bucket with an address, and an unverified claim is never a key. Off unless configured, like every capability here. A request walgit cannot attribute to a Source is not limited, because pooling the unattributable into one bucket would let the first such request throttle every other. The verdict is reached at the smart-HTTP handler, the only layer that sees both the Source and the repository; it is **spoken** by `pre-receive`, because a status code on that route reaches git as `RPC failed; HTTP …` — a transport fault, which a client retries — while stderr from the hook reaches it as the same `remote:` reject line a size cap produces. The window is in memory and a container restart forgives it: over-forgiving is the safe direction, and a durable write per push would cost more than the spike it is there to make cheap.
151
+ _Avoid_: rate limiting the repository (nothing here is per repository), throttling (nothing is slowed — a push is served or refused), the client's identity (a Source is a verified tenant or an address, never a claimed who)
144
152
 
145
153
  **Advertised capability**:
146
154
  What the three agent-facing documents say a deployment can do, rendered from the thing that enforces it and never written as prose. The derivation has one owner — `shared/capabilities.ts`, whose `capabilitiesFrom(env)` returns the `Capabilities` that the plain-text `GET /`, the landing page and `/llms.txt` all render from, that `pre-receive` takes its size caps from (`limitsOf`), and that the Worker claims the event socket on. A capability with no field there is not advertised; a field added there fails to compile at every construction site until it is answered. Signing joins the size caps, the retention window and the stream under this rule: with no `WALGIT_PUSH_CERT_SEED`, none of the three mentions signing, keys or Provenance at all. Sharper here than for a cap, because a client asking to sign a host that does not advertise `push-cert` is refused by its OWN git — the agent finds out only after it has written the push. The stream is the same rule read across two variables: `events` is true only when `WALGIT_EVENTS_URL` and `WALGIT_EVENTS_TOKEN` are both set, because the token alone claims a socket the container's `post-receive` has nowhere to announce to — an advertised stream that never delivers.
@@ -204,7 +212,7 @@ A ref under `refs/walgit/proposals/` that names a commit its pusher wants in a t
204
212
  _Avoid_: pull request (GitHub's, and already means a GitHub PR elsewhere in the repository), merge request, change request (an approval-board ticket), PR
205
213
 
206
214
  **Merged**:
207
- A Proposal whose tip is an ancestor of its target ref's tip. Computed on read, never recorded, so it is only ever true because someone with the right to write the target pushed a fast-forward or a true merge of the Proposal's tip. A squash or a rebase of it does not merge the Proposal, and a Proposal is never Merged by anything but ancestry.
215
+ A Proposal whose tip is an ancestor of its target ref's tip. Computed on read, never recorded, so it is only ever true because someone with the right to write the target pushed a fast-forward or a true merge of the Proposal's tip — or, where a deployment sets `WALGIT_MERGE`, asked the host for a fast-forward **Host Merge**. A squash or a rebase of it does not merge the Proposal, and a Proposal is never Merged by anything but ancestry.
208
216
  _Avoid_: closed, accepted (nothing records an acceptance), landed
209
217
 
210
218
  **Signer List Proposal**:
@@ -227,6 +235,39 @@ deliberately not reported: ADR-0018 admits it only if the same walk yields it
227
235
  free, and it does not.
228
236
  _Avoid_: list endpoint, PR list, the proposals API
229
237
 
238
+ ## Host merges (ADR-0022)
239
+
240
+ **Host Merge**:
241
+ A merge the host performs on request, where the deployment sets `WALGIT_MERGE`: `POST /_walgit/merge?repo=` moves a target branch to a source by **fast-forward**, or to one new **squash** commit whose only parent is the target and whose tree is git's three-way merge. A compare-and-swap: the caller names the commit the target is **expected** at, and a target that moved is a 409 with nothing written. It is a **push the host makes** — built in a scratch repository on the Cache's objects and pushed into the Cache — so the size caps, append-only, the publish's compare-and-swap and the Announce all apply as to any push. A conflict is a 409 naming the paths, never a marker. A name holding a **Signer List** refuses it, because the host holds no key and makes no Push Certificate. A squash-merged Proposal is not **Merged**: Merged is ancestry and stays so.
242
+ _Avoid_: accept (a Signer's push accepts a Proposal), PR merge, auto-merge
243
+ _Disambiguate_: not **Merged**, which is a Proposal's derived state; a Host Merge can produce it only by fast-forward.
244
+
245
+ ## Scoped tokens (ADR-0021)
246
+
247
+ **Scoped Token**:
248
+ A credential for exactly one repository, minted by somebody else: a compact JWT signed with Ed25519 (`alg: EdDSA`) whose claims are `repo` (an exact repository id — never a prefix or a pattern), `mode` (`read` or `write`), `exp` and `iat` (both required) and optionally `sub` (the tenant). The **Issuer** holds the private key; walgit holds only the public keys, in `WALGIT_TOKEN_PUBLIC_KEYS`, so it can verify a token and never make one. Presented where any token is (the Basic-auth password or `Bearer`), verified at the edge before the container wakes and again in the container. Valid only for its repository on every surface — smart HTTP, the web view, the Provenance Read, Proposals, a Watch, every MCP tool call — and the repository list shows it that one name. Anywhere else it is refused with 403, even where an anonymous request is served. A `write` token may create its repository on first push; a `read` token is refused at `git-receive-pack`. Off unless the keys are set.
249
+ _Avoid_: API key, access token (too general), PAT, session
250
+ _Disambiguate_: the **admin token** is `WALGIT_HTTP_TOKENS`, which reads and writes everything and still does; a Scoped Token never reaches past its claim. Neither is a Read Challenge, which proves a key rather than presenting a grant; both use the one `Authorization` header, so a Scoped Token cannot open a Private repository.
251
+
252
+ **Issuer**:
253
+ Whoever holds the private key and mints Scoped Tokens — the first is Fredrin. Outside walgit by construction. `walgit token mint` is an operator's tool for testing and docs, not the issuer.
254
+ _Avoid_: auth server, IdP
255
+
256
+ **Scope**:
257
+ The one repository and mode a Scoped Token's claims grant. "Out of scope" is a 403; a token that does not verify at all (expired, badly signed, wrong key, malformed, the wrong `alg`) is a 401.
258
+
259
+ **Tokens Valid Since**:
260
+ A repository's revocation instant, `tokens_valid_since` in its Index: every Scoped Token for that repository whose `iat` is earlier is refused with 401, on every surface. Set by the Admin Route `…/revoke-tokens` (to now, or to a given instant no later than now) and only ever moved forward. Absent means nothing is revoked. It revokes every token for the name issued so far — there is no per-token denylist. Propagation is the next request: the edge, the container and the event fan-out read the Index on every scoped request (an unreadable one refuses), and an open Watch on a covered token is closed when the revoke is announced. Other repositories and the admin token are untouched.
261
+ _Avoid_: denylist, blocklist, revoked tokens list
262
+
263
+ **Admin Route**:
264
+ `/_walgit/admin/repos/<name>` — create (optionally with a **Seed**), delete, `…/usage`, and `…/revoke-tokens` (moves **Tokens Valid Since** forward) — answered only to the admin token, so a server holding no store credentials can manage repositories. A Scoped Token is refused there with 403 whatever its Scope; a deployment with no admin token has no Admin Routes (404).
265
+ _Avoid_: management API, control plane
266
+
267
+ **Seed**:
268
+ The first commit an Admin Route create may carry: files, a message, an author and a branch. It is built in a scratch repository and **pushed**, so the hooks judge it as they judge any push — never written into the Index directly.
269
+ _Avoid_: template, import
270
+
230
271
  ## The MCP endpoint
231
272
 
232
273
  **MCP Endpoint**:
@@ -28,6 +28,8 @@ by layer:
28
28
  | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
29
29
  | `shared/protocol.ts` | the wire contract: header names, internal paths, the smart-HTTP grammar, the repo-id and ref-name grammars, the zero oid, the refusal vocabulary |
30
30
  | `shared/credentials.ts` | reading a credential off the wire: the two auth forms, the token list, the constant-time compare |
31
+ | `shared/scoped-token.ts` | scoped tokens: the Ed25519 JWT verifier, what a request reaches, the 401/403 verdict (ADR-0021) |
32
+ | `shared/token-revocation.ts` | revocation: a repository's tokens-valid-since, read from the Index on every scoped request (ADR-0021) |
31
33
  | `shared/policy.ts` | reading a limit from the environment, and saying what it is — so the cap stated and the cap enforced are one number |
32
34
  | `shared/events.ts`, `shared/outbox.ts` | the ref-event protocol and the per-ref coalesce window that bounds a subscriber's message rate — every decision, pure |
33
35
  | `shared/telemetry.ts` | classifying a request and a refusal into the datapoint the Worker writes |
@@ -193,6 +195,81 @@ objects survive until `--grace` minutes have passed (default 60,
193
195
  twice inside the window does not restart the clock, and deleting a repository
194
196
  that is not there is a no-op rather than an error.
195
197
 
198
+ ### The same three over HTTP
199
+
200
+ A server that holds the admin credential (`WALGIT_HTTP_TOKENS`) and no bucket
201
+ credentials — a host minting one repository per tenant — creates, deletes and
202
+ measures one repository over HTTP instead:
203
+
204
+ ```bash
205
+ # create an empty repository: 201 { "repo": "my-thing" }
206
+ curl -X POST -H "Authorization: Bearer $ADMIN" https://<host>/_walgit/admin/repos/my-thing
207
+
208
+ # create one holding a first commit: 201 { "repo", "commit", "ref" }
209
+ curl -X POST -H "Authorization: Bearer $ADMIN" -H 'content-type: application/json' \
210
+ https://<host>/_walgit/admin/repos/my-thing --data '{
211
+ "files": { "README.md": "# my-thing\n" },
212
+ "message": "Initial commit",
213
+ "author": { "name": "Ada Example", "email": "ada@example.com" },
214
+ "branch": "main"
215
+ }'
216
+
217
+ # delete it: 200 { "repo", "status", "collectAfter"?, "deleted", "retained" }
218
+ curl -X DELETE -H "Authorization: Bearer $ADMIN" https://<host>/_walgit/admin/repos/my-thing
219
+
220
+ # its storage usage: 200, the `walgit usage` row for this one repository,
221
+ # plus `tokensValidSince` (null until its tokens are revoked)
222
+ curl -H "Authorization: Bearer $ADMIN" https://<host>/_walgit/admin/repos/my-thing/usage
223
+
224
+ # revoke every scoped token for it issued before now: 200 { "repo", "tokensValidSince", "announced" }
225
+ curl -X POST -H "Authorization: Bearer $ADMIN" https://<host>/_walgit/admin/repos/my-thing/revoke-tokens
226
+ # …or before a given instant, no later than now
227
+ curl -X POST -H "Authorization: Bearer $ADMIN" -H 'content-type: application/json' \
228
+ https://<host>/_walgit/admin/repos/my-thing/revoke-tokens --data '{ "since": "2026-11-11T12:00:00Z" }'
229
+ ```
230
+
231
+ - **Create** claims the name by writing an empty `index.json` under an
232
+ if-absent compare-and-swap, so of two creates racing for one name exactly one
233
+ wins. A name that already has an Index — including one tombstoned and not yet
234
+ collected, whose 409 says when the name frees up — is a **409**, never an
235
+ overwrite. The seed is optional; `branch`
236
+ defaults to `main`, every file is mode `100644`, and the author is also the
237
+ committer. The body is at most 1 MiB and 1000 files; a malformed one is a
238
+ **400** and creates nothing.
239
+ - **A seed is a push.** The commit is built in a scratch repository and pushed
240
+ into the new repository over git's local transport, so `pre-receive` and
241
+ `reference-transaction` judge it like any client's push — size caps, the
242
+ Signer List rules, the WAL publish that makes it durable — and a refusal is a
243
+ **422** carrying git's words, with the claimed Index removed so the request
244
+ can be fixed and retried. A path git will not carry in a tree (`.git` in any
245
+ spelling, NTFS's `.git.` and `GIT~1` among them) is refused, never committed
246
+ short. A failure that is walgit's rather than the seed's — the store
247
+ unreachable — is a **503**, and the claimed Index is removed the same way. A brand-new name holds no Signer List, so nothing
248
+ there is bypassed: a seed can only push a branch, never `refs/walgit/signers`.
249
+ - **Delete** is `walgit delete --yes` with the same grace
250
+ (`WALGIT_DELETE_GRACE_MS`): the first call answers `tombstoned` and the
251
+ repository survives until `collectAfter`; a call inside the grace answers
252
+ `retained` and does not restart the clock; a call after it answers
253
+ `collected`. Deleting a repository that is not there answers `absent` with a
254
+ 200 — harmless, and safe to retry. The cron sweep's collect-only run finishes
255
+ a tombstone nobody asks about again.
256
+ - **Usage** answers `404` for a name with no Index.
257
+ - **Revoke tokens** moves the repository's *tokens valid since* forward — see
258
+ [revocation](#revoking-a-repositorys-tokens). It answers `404` for a name with
259
+ no Index and creates none; a `since` more than a minute later than now, or one
260
+ that is not an ISO 8601 instant, is a **400** (one a little ahead is taken as
261
+ now).
262
+
263
+ Only the admin credential may call these, over Bearer or Basic like every other
264
+ credential. No credential (or a wrong one) is a **401**; a [scoped
265
+ token](#scoped-tokens) is a **403** whatever its mode or repository, refused at
266
+ the edge before the container wakes; and a deployment with no
267
+ `WALGIT_HTTP_TOKENS` — a public one — has no admin, so the routes answer
268
+ **404**. They are demanded even on a public deployment that does set an admin
269
+ credential. A create records `created_at` in the Index, and expiry dates a
270
+ repository that has never been pushed to by it — so one created and never used
271
+ is collected like one pushed to once and left.
272
+
196
273
  `compact` forces a compaction rather than waiting for
197
274
  `WALGIT_COMPACTION_THRESHOLD` pushes to trigger one — for the repo whose restore
198
275
  is already slow because its log is already long. It takes the same per-repo
@@ -641,6 +718,117 @@ Both bounds — one tree level, fifty commits — are bounds on work done on the
641
718
  request path in the one container that is also serving pushes. A reader who
642
719
  wants the whole history clones it, which is what walgit is.
643
720
 
721
+ ### Comparing two refs
722
+
723
+ `GET /_walgit/browse?repo=<name>&op=compare&base=<ref>&head=<ref>` is a review of
724
+ a branch without a checkout: the head **against its merge base with the base**
725
+ (three-dot, as code review reads it), so whatever the base gained after the
726
+ branch was cut is not in the answer. Both refs resolve the way every browse ref
727
+ does — an Index key, `refs/heads/` or `refs/tags/` optional, or a full oid. It
728
+ answers JSON:
729
+
730
+ ```json
731
+ {
732
+ "repo": "my-thing",
733
+ "base": { "ref": "refs/heads/main", "oid": "…" },
734
+ "head": { "ref": "refs/heads/feature/x", "oid": "…" },
735
+ "mergeBase": "…",
736
+ "files": [
737
+ { "path": "src/new.ts", "previousPath": "src/old.ts", "status": "renamed", "additions": 2, "deletions": 1, "binary": false }
738
+ ],
739
+ "totals": { "files": 1, "additions": 2, "deletions": 1 },
740
+ "truncated": false,
741
+ "diff": "diff --git a/src/old.ts b/src/new.ts\n…"
742
+ }
743
+ ```
744
+
745
+ alongside the ref list every browse answer carries. `status` is `added`,
746
+ `modified`, `deleted` or `renamed` (`git diff -M`; a type change is
747
+ `modified`), and a binary file has `binary: true` with zero counts.
748
+ `?format=diff`, or an `Accept` preferring `text/x-diff` or `text/plain` to
749
+ `application/json` by q-value, answers the unified diff alone as `text/plain` with
750
+ `X-Walgit-Truncated` and `X-Walgit-Merge-Base` headers.
751
+
752
+ - **Bounded.** At most **300 files** are listed and diffed, and at most
753
+ **1 MiB** of diff is carried, cut on a line boundary — the byte cap is
754
+ enforced on git's output as it is read, so a huge diff is stopped in the
755
+ subprocess rather than buffered. Hitting either sets `truncated: true`;
756
+ `totals` still counts every changed file.
757
+ Every git command of one compare also runs under a shared **10-second**
758
+ budget, because git is synchronous in the process that serves pushes; a
759
+ comparison that needs longer, or whose summary alone runs past 16 MiB, is
760
+ `503` (`unavailable`) rather than a partial answer — compare it in a clone.
761
+ When the file cap is hit, only the listed files' sections are kept in the
762
+ diff.
763
+ - **Refusals.** An unknown ref, or an oid the Cache does not hold, is `404`; a
764
+ request naming no `base` or no `head`, or two refs sharing no history (there
765
+ is no merge base), is `400`. `base.oid` and `head.oid` are the commits
766
+ compared, so an annotated tag reports the commit it names.
767
+ - **Gated as a browse.** It is one more `op` of the browse endpoint, so it
768
+ exists only with `WALGIT_WEB` on, never creates a name, and is read under the
769
+ same deployment credential, Read Challenge and Scoped Token rules: a `read`
770
+ or `write` token for the repository may compare, another repository's token
771
+ is `403`, and a public deployment answers it with no credential at all.
772
+
773
+ ### Merging a branch on the host
774
+
775
+ With **`WALGIT_MERGE=1`** (off by default; [ADR-0022](../../../../../docs/adr/0022-a-host-merge-is-a-push-the-host-makes-where-a-deployment-opts-in.md)),
776
+ a client with no checkout can ship what it just reviewed with a compare:
777
+
778
+ ```sh
779
+ curl -X POST "https://$HOST/_walgit/merge?repo=my-thing" \
780
+ -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
781
+ -d '{"source":"feature/x","target":"main","method":"squash",
782
+ "expected":"<the commit main is at>",
783
+ "message":"Land feature/x","author":{"name":"Ada Example","email":"ada@example.com"}}'
784
+ ```
785
+
786
+ - **`method`** is `fast-forward` (the target moves to the source; refused when
787
+ it is not one) or `squash` (one new commit whose only parent is the target and
788
+ whose tree is git's three-way merge, authored and committed by `author`).
789
+ `message` and `author` are required for a squash and ignored otherwise.
790
+ - **`expected` is required** — the full commit id the target stands at, as the
791
+ review saw it. It is a **compare-and-swap**: if the target has moved, the
792
+ answer is `409` with `"error": "stale"` and the `actual` commit, and nothing
793
+ is written. Of two merges racing for one target exactly one lands; the other
794
+ is `409` (`stale`, or `contended` when it lost to a write still in flight).
795
+ - **A merge is a push.** The host builds the result in a scratch repository
796
+ and pushes it into its own Cache, so every rule a push meets applies — the
797
+ size caps, `WALGIT_APPEND_ONLY`, the Index compare-and-swap that publishes it
798
+ — and the move is announced to Watchers and the push webhook like any push.
799
+ A refusal by one of those rules is `422` (`refused`) in the rule's own words;
800
+ a push that failed for any other reason (a store outage) is `503`
801
+ (`unavailable`) — retry it.
802
+ - **Bounded.** Building the merge (merge base, ancestry, a squash's three-way
803
+ merge) has **20 seconds**; past that it is `503` (`too-large`) — merge it in
804
+ a clone. A merge is **counted as one push** against the per-source window
805
+ (`WALGIT_MAX_PUSHES_PER_SOURCE`, below), `429` (`rate-limited`) once spent.
806
+ - **Answers.** `200` with `{ repo, method, source: { ref, oid }, target: { ref,
807
+ previous, oid }, commit, files, totals, truncated }` — the compare's file
808
+ summary of the target before and after, with no diff text (`files` and
809
+ `totals` are `null`, `truncated` true, when it could not be computed in time;
810
+ the merge still stands). Every refusal is JSON with an `error` naming it. `409`
811
+ `not-fast-forward`, `409` `up-to-date` (the target already holds the source),
812
+ `409` `conflict` with `conflicts: [paths]` — **never conflict markers**;
813
+ resolve those in a clone — `400` for a malformed body or two refs with no
814
+ history in common, `404` for a name or a ref the Index does not hold.
815
+ - **A Signer List refuses it.** On a claimed name a ref moves only by a push a
816
+ listed key signed, and the host has no key: the merge is `403` (`signed`),
817
+ before any work is done. Merge in a clone and push it signed.
818
+ - **Who may merge is who may push**: a `write` scoped token for the repository
819
+ or the deployment credential. A `read` token is `403`, another repository's
820
+ token `403`, none `401` (on a public deployment, anyone — as anyone may push).
821
+ A squash's author is the request's word: nothing records which credential
822
+ asked for the merge.
823
+ - **Squash and Proposals.** A Proposal is Merged when its tip is an ancestor of
824
+ its target (ADR-0018), so a squash-merged Proposal does **not** read as
825
+ Merged. Fast-forward it if it should.
826
+
827
+ With `WALGIT_MERGE` unset, `/_walgit/merge` is a `404` and nothing else changes.
828
+ It is independent of `WALGIT_WEB`: a merge is a write, not a browse. The flag is
829
+ on `CONTAINER_ENV`, so the deploy that first sets it replaces the running
830
+ container once.
831
+
644
832
  `WALGIT_WEB` is on `CONTAINER_ENV`, which is what makes the browse endpoint
645
833
  above possible at all: `caps.web` is read on both sides — at the edge to claim
646
834
  the routes, in the container to decide whether `/_walgit/browse` exists — and a
@@ -776,6 +964,9 @@ cloudflare instance's `workerSecrets`):
776
964
 
777
965
  - `WALGIT_HTTP_TOKENS` — comma-separated bearer tokens (comma-separated so a
778
966
  credential can be rotated without a window where neither works).
967
+ - `WALGIT_TOKEN_PUBLIC_KEYS` — optional: comma-separated Ed25519 public keys
968
+ (base64url, 32 raw bytes) that verify [scoped tokens](#scoped-tokens). Public
969
+ keys, so not strictly a secret; off unless set.
779
970
  - `WALGIT_S3_ENDPOINT`, `WALGIT_S3_BUCKET`, `WALGIT_S3_ACCESS_KEY_ID`,
780
971
  `WALGIT_S3_SECRET_ACCESS_KEY` — the write-ahead log's home (the `r2` module
781
972
  instance and its S3-API credentials). Without them the host serves reads from
@@ -787,10 +978,13 @@ Optional instance configuration (plain env, not secrets): `WALGIT_APPEND_ONLY`,
787
978
  `WALGIT_MAX_NEW_REPOS_PER_SOURCE`, `WALGIT_MAX_PUSHES_PER_SOURCE`,
788
979
  `WALGIT_MAX_PUSH_BYTES_PER_SOURCE`, `WALGIT_RATE_WINDOW_SECONDS`,
789
980
  `WALGIT_RETENTION_HOURS`, `WALGIT_CLAIMED_RETENTION_HOURS`,
790
- `WALGIT_PUBLIC`, `WALGIT_SIGNER_LISTS`, `WALGIT_WEB` (the web view above) —
981
+ `WALGIT_PUBLIC`, `WALGIT_SIGNER_LISTS`, `WALGIT_WEB` (the web view above),
982
+ `WALGIT_MERGE` (host merges, above) —
791
983
  each unset means the behaviour is off
792
984
  and `GET /` does not claim it. `WALGIT_EVENTS_URL` and `WALGIT_EVENTS_TOKEN` (a
793
- secret) turn on the ref-event stream below, `WALGIT_PUSH_CERT_SEED` (a secret)
985
+ secret) turn on the ref-event stream below, `WALGIT_WEBHOOK_URL` and
986
+ `WALGIT_WEBHOOK_SECRET` (a secret) turn on the push webhook below,
987
+ `WALGIT_PUSH_CERT_SEED` (a secret)
794
988
  turns on signed pushes, and `WALGIT_PRIVATE_REPOS` (a secret) turns on read
795
989
  gating.
796
990
 
@@ -940,8 +1134,8 @@ first thing walgit ever says to most of them.
940
1134
  ## Per-source limits
941
1135
 
942
1136
  `WALGIT_MAX_NEW_REPOS_PER_SOURCE`, `WALGIT_MAX_PUSHES_PER_SOURCE` and
943
- `WALGIT_MAX_PUSH_BYTES_PER_SOURCE` bound what **one client** may spend in a
944
- window; `WALGIT_RATE_WINDOW_SECONDS` is the window and defaults to an hour when
1137
+ `WALGIT_MAX_PUSH_BYTES_PER_SOURCE` bound what **one source** — a tenant, or
1138
+ else a client address — may spend in a window; `WALGIT_RATE_WINDOW_SECONDS` is the window and defaults to an hour when
945
1139
  a count is set without one. All three are **unset by default**, and with them
946
1140
  unset nothing about a push changes.
947
1141
 
@@ -967,8 +1161,20 @@ direction. Whether a name is *new* is read from the Index (a repository holding
967
1161
  no ref is one being created); an Index that cannot be read never invents a
968
1162
  creation refusal.
969
1163
 
1164
+ **Per tenant, when a scoped token names one.** A push carrying a verified
1165
+ [scoped token](#scoped-tokens) with a `sub` claim is counted in a bucket for
1166
+ that `sub` — across every repository it holds a token for and every address it
1167
+ pushes from — because hosted agents share cloud addresses, and keying them on
1168
+ the address would put unrelated tenants in one bucket. A token without `sub`,
1169
+ no scoped token, and the admin credential (`WALGIT_HTTP_TOKENS`) are all
1170
+ counted by address, exactly as before. Only a claim the handler has verified is
1171
+ ever a key, and tenants and addresses are kept in separate key spaces, so a
1172
+ `sub` of `203.0.113.7` is not that address. The refusal says which it counted:
1173
+ `one tenant`, counted across its repositories and addresses, or `one client`.
1174
+
970
1175
  `GET /` and `/llms.txt` state each limit that is on, from the same
971
- `Capabilities` the handler enforces.
1176
+ `Capabilities` the handler enforces — and say "per tenant" only on a deployment
1177
+ that verifies scoped tokens.
972
1178
 
973
1179
  ## Size limits
974
1180
 
@@ -987,9 +1193,15 @@ before a proxy can answer: measured against Fly, 99 MiB passes and 100 MiB is
987
1193
  refused only after all 104,879,625 bytes have gone up — 37 s of upload to be
988
1194
  told `RPC failed; HTTP 413` and `unexpected disconnect`, which reads like a
989
1195
  dropped network and gets retried. A documented cap must therefore sit under the
990
- **chunked** cutoff, not the `Content-Length` one (which 413s at 101 MiB after
991
- ~2 MB): ~99 MiB is the safe ceiling for the public instance, with a repository
992
- total of ~250 MB.
1196
+ **chunked** cutoff of whatever is in front, not the `Content-Length` one (which
1197
+ 413s early). Behind Cloudflare that is the plan's request-body limit, 100 MB
1198
+ (100,000,000 bytes, 95.37 MiB) on Free and Pro, so the public instance caps a
1199
+ push at 90 MiB, with ~5.6 MB of room for the ref commands and a push
1200
+ certificate, and a repository total of ~250 MB. (The Fly measurement above
1201
+ allowed 99 MiB, and the public instance kept that number after it moved to
1202
+ Cloudflare, where a 96–99 MiB push passed walgit's cap and was refused by the
1203
+ edge.) `src/large-push.e2e.test.ts` pushes 20 MiB, eight 20 MiB pushes at
1204
+ once, and one either side of the cap against a local node.
993
1205
 
994
1206
  The repository total needs no new state. Every WAL entry carries its `size`, so
995
1207
  the total is a sum over the entries above the compaction frontier — the live
@@ -1109,11 +1321,182 @@ when the window elapses is the one you would have converged to anyway. The cost
1109
1321
  is that a push can reach a subscriber up to half a second late when its ref is
1110
1322
  already moving.
1111
1323
 
1324
+ ## Push webhook
1325
+
1326
+ The stream needs a client that can hold a socket open. A serverless receiver
1327
+ cannot, so a deployment can also POST every ref move to one URL its operator
1328
+ configures. Set both `WALGIT_WEBHOOK_URL` and `WALGIT_WEBHOOK_SECRET` (a shared
1329
+ secret, in `workerSecrets`) to turn it on; with either unset nothing is sent and
1330
+ walgit behaves exactly as without it. The URL is never published — `/llms.txt`
1331
+ says only that the webhook is on.
1332
+
1333
+ Each moved ref is one POST with a JSON body. The names are the stream's, plus
1334
+ `oldSha`, an `id` and a `timestamp`:
1335
+
1336
+ ```json
1337
+ {
1338
+ "id": "01JD3Q8X6M2P4R7T9V0WXYZABC",
1339
+ "repo": "my-thing",
1340
+ "ref": "refs/heads/main",
1341
+ "oldSha": "9f2c…",
1342
+ "sha": "0ab7…",
1343
+ "timestamp": "2026-11-11T12:00:00.000Z"
1344
+ }
1345
+ ```
1346
+
1347
+ `oldSha` is `null` when the push created the ref and `sha` is `null` when it
1348
+ deleted it; `merged` (the Proposals the move landed) appears exactly when it does
1349
+ on the stream. The headers are `X-Walgit-Event` (the `id` again),
1350
+ `X-Walgit-Timestamp` (Unix seconds at the attempt) and `X-Walgit-Signature`:
1351
+ `sha256=` and the hex HMAC-SHA256, keyed by the secret, of
1352
+ `<timestamp>.<raw body>`.
1353
+
1354
+ It fires from the same `post-receive` announcer as the stream
1355
+ (`publish` in `src/announce.ts`), so it fires only once the push is durable,
1356
+ never for a push that lost the compare-and-swap, and for anything that moves a
1357
+ ref through that path. Delivery is **at least once**: a network failure, a 5xx,
1358
+ a 408 or a 429 is retried with backoff (1, 2, 4, 8 seconds — five attempts, five
1359
+ seconds each), every attempt carries the same `id` and body, and the timestamp
1360
+ is re-stamped so a late retry is still fresh. Any other 4xx, and any redirect,
1361
+ is not repeated — a redirect is never followed, so the signed body only ever
1362
+ goes to the configured URL. One push's events go out at most four at a time,
1363
+ with jittered backoff. It all runs in the detached announcer, so a receiver
1364
+ that is down never fails or slows a push. That is also the limit of "at least
1365
+ once": an event whose attempts all fail is dropped, and so is one still being
1366
+ retried when the container restarts — nothing replays it, because the refs are
1367
+ in `index.json` regardless. The secret is used verbatim as the HMAC key
1368
+ (surrounding whitespace included) and is never logged.
1369
+
1370
+ Verify on the receiver against the **raw** body — parse it after:
1371
+
1372
+ ```ts
1373
+ import { createHmac, timingSafeEqual } from 'node:crypto'
1374
+
1375
+ function verify(secret: string, raw: string, headers: Headers): boolean {
1376
+ const timestamp = headers.get('x-walgit-timestamp') ?? ''
1377
+ const signature = Buffer.from(headers.get('x-walgit-signature') ?? '')
1378
+ // Refuse a replay: five minutes covers clock skew, and every retry is re-stamped.
1379
+ if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false
1380
+ const expected = Buffer.from(
1381
+ `sha256=${createHmac('sha256', secret).update(`${timestamp}.${raw}`).digest('hex')}`,
1382
+ )
1383
+ // Lengths compared as bytes, so a forged multibyte header is refused, not thrown on.
1384
+ return signature.length === expected.length && timingSafeEqual(signature, expected)
1385
+ }
1386
+ ```
1387
+
1388
+ Then de-duplicate on `id`. `verifyWebhook` in `shared/webhook.ts` is the same
1389
+ check in WebCrypto, for a receiver on Workers.
1390
+
1112
1391
  ## Authorization, today
1113
1392
 
1114
- One trust boundary: any HTTP token can read and write any repository. Per-repo
1115
- authorization is deferred until the repo namespace exists in the WAL — the
1116
- `tokens` list is the seam it plugs into.
1393
+ The admin token (`WALGIT_HTTP_TOKENS`) is one trust boundary: any holder can
1394
+ read and write any repository. Per-repository credentials are **scoped tokens**,
1395
+ below.
1396
+
1397
+ ### Scoped tokens
1398
+
1399
+ A scoped token ([ADR-0021](../../../../../docs/adr/0021-a-scoped-token-opens-one-repository.md))
1400
+ grants `read` or `write` on **exactly one repository**, for a short time. It is
1401
+ a compact JWT signed with Ed25519 (`alg: EdDSA` — every other `alg`, `none`
1402
+ included, is refused) by an **issuer** that holds the private key. walgit holds
1403
+ only the public keys, so a compromised walgit cannot mint one.
1404
+
1405
+ ```sh
1406
+ # The issuer's keypair. Keep key.pem with the issuer; never put it on walgit.
1407
+ bun src/cli.ts token keygen --out key.pem # prints the public key
1408
+ # …or with openssl, which writes the same PKCS#8 file:
1409
+ openssl genpkey -algorithm ed25519 -out key.pem
1410
+ bun src/cli.ts token public-key --key key.pem # the WALGIT_TOKEN_PUBLIC_KEYS entry
1411
+
1412
+ # Configure walgit with the public half (comma-separate several to rotate):
1413
+ # WALGIT_TOKEN_PUBLIC_KEYS=<base64url of the 32 raw public-key bytes>
1414
+
1415
+ # Mint one for testing (an issuer in production uses its own JWT library):
1416
+ TOKEN=$(bun src/cli.ts token mint --key key.pem --repo my-thing --mode write --ttl 1h --sub tenant-1)
1417
+ git clone "https://walgit:$TOKEN@$HOST/my-thing.git" # or: Authorization: Bearer $TOKEN
1418
+ ```
1419
+
1420
+ Claims: `repo` (required, an **exact** repository id — no prefix, no wildcard),
1421
+ `mode` (required, `read` | `write`), `exp` and `iat` (required, seconds since the
1422
+ epoch; 60 seconds of clock skew is allowed either way, and an `iat` further in
1423
+ the future is refused), `sub` (optional, the tenant — the bucket the [per-source limits](#per-source-limits)
1424
+ count it in). `iat` is required because [revocation](#revoking-a-repositorys-tokens)
1425
+ refuses every token issued before an instant.
1426
+
1427
+ - **Where it works:** on its own repository, on every surface — git smart HTTP
1428
+ (`info/refs`, `git-upload-pack`, `git-receive-pack`), the web view and raw
1429
+ files, the Provenance Read, Proposals, a ref-event `watch`, and every MCP tool
1430
+ call. The repository list (`/repos`) shows it its own repository and nothing
1431
+ else.
1432
+ - **Where it doesn't:** any other repository, and any other route, is **403** —
1433
+ even where an anonymous request would be served. A client that wants the
1434
+ anonymous view sends no credential. A `read` token is 403 at
1435
+ `git-receive-pack`, including the advertisement, so git stops before it sends
1436
+ a pack.
1437
+ - **A token that does not verify** — expired, badly signed, signed by a key not
1438
+ configured, malformed, the wrong `alg` — is **401** with the Basic challenge.
1439
+ - **Create on first push:** a `write` token may create the repository it names,
1440
+ exactly as the admin token can.
1441
+ - **On top, unchanged:** Private repositories, Reader Lists, Signer Lists,
1442
+ signed pushes and per-source rate limits. A scoped token **cannot** open a
1443
+ Private repository: it and a Read Challenge signature both travel in the one
1444
+ `Authorization` header, and a Private repository answers only the signature.
1445
+ - **One keypair per deployment.** There is no `aud` claim; the key is the
1446
+ boundary, so a token for `my-thing` on one walgit does not open `my-thing` on
1447
+ another. `nbf` is honoured when present. walgit sets no maximum lifetime;
1448
+ a leaked one is ended by [revoking](#revoking-a-repositorys-tokens) its
1449
+ repository's tokens, which also ends that repository's other tokens.
1450
+ - **An open `watch`** is closed by the first ref event after its token expires.
1451
+ - **Where it's checked:** at the edge Worker first, so a bad credential never
1452
+ wakes the container, and again in the container with the same function
1453
+ (`shared/scoped-token.ts`).
1454
+
1455
+ #### Revoking a repository's tokens
1456
+
1457
+ A scoped token is stateless, so there is nothing per token to delete. Each
1458
+ repository instead carries one optional instant in its `index.json`,
1459
+ `tokens_valid_since`: every scoped token **for that repository** whose `iat` is
1460
+ earlier is refused with **401**, on every surface above. One admin call sets it
1461
+ (`POST /_walgit/admin/repos/<name>/revoke-tokens`, [above](#the-same-three-over-http)):
1462
+ it revokes every token minted for the name so far, and tokens minted after it
1463
+ work. Other repositories' tokens and the admin credential are unaffected. Absent
1464
+ (the default) means nothing is revoked.
1465
+
1466
+ - **Propagation: the next request.** Nothing caches the verdict. The edge, the
1467
+ container and the event fan-out each read the token's repository's Index on
1468
+ every scoped request — a conditional GET, so an unchanged Index costs a `304` —
1469
+ and a store that cannot be read refuses the token (**503**) rather than
1470
+ letting it through — including an edge with no object store configured,
1471
+ which has no Index to read and so refuses scoped tokens outright. A `watch`
1472
+ already open is closed when the revoke lands: the container announces it to
1473
+ the fan-out, which closes every socket watching on a token it covers, and the
1474
+ response's `announced` says whether that was acknowledged. If it was not, the
1475
+ socket is still re-judged against the Index before the next event it would
1476
+ be sent, so it is never served after the revocation.
1477
+ - **Deleting the repository discards its revocation**, with everything else in
1478
+ `index.json` — an admin delete once collected, and retention expiry alike.
1479
+ The name is then first-come again, and a revoked `write` token that has not
1480
+ reached `exp` could re-create it. To end every token for good, rotate the
1481
+ signing key (`WALGIT_TOKEN_PUBLIC_KEYS`); keep lifetimes short regardless.
1482
+ - **Rolling back** to a walgit older than this field ignores it, which makes
1483
+ every revoked token valid again until `exp`.
1484
+ - **It only moves forward.** An older `since` than the one stored leaves the
1485
+ stored one standing, so a revocation cannot be undone by accident. To restore
1486
+ a revoked token, mint a new one.
1487
+ - **Whole seconds.** `iat` is in seconds and the instant in milliseconds, so a
1488
+ token minted in the same second as the revocation, after it, is refused too —
1489
+ mint again a second later. An issuer whose clock runs ahead can mint an `iat`
1490
+ up to the 60-second skew past a revocation; revoke from the issuer's clock, or
1491
+ wait out the skew, if that matters.
1492
+ - **A name with no repository** has no Index to revoke in, and a `write` token
1493
+ can still create it on first push. To shut such a token out, create the
1494
+ repository first (`POST …/repos/<name>`), then revoke.
1495
+
1496
+ `WALGIT_TOKEN_PUBLIC_KEYS` unset (the default) means every credential is judged
1497
+ exactly as before. A malformed entry is reported at the container's boot and
1498
+ refuses scoped tokens with a 503 naming the entry; the admin token keeps
1499
+ working.
1117
1500
 
1118
1501
  `WALGIT_PUBLIC` removes that boundary entirely: reads, writes and ref-event
1119
1502
  subscriptions all serve anyone, with no credential. It is an **explicit opt-in
@@ -151,6 +151,67 @@ export interface BrowseLogAnswer extends BrowseRefsAnswer {
151
151
  next: string | null
152
152
  }
153
153
 
154
+ /**
155
+ * How many files one compare lists, and diffs: 300.
156
+ *
157
+ * GitHub's own figure for a compare, and a bound on work done on the request
158
+ * path in the one container that is also serving pushes. The totals are still
159
+ * counted over EVERY changed file — the per-file summary is one `git diff
160
+ * --numstat` either way — so a reader is told how much was left out, not merely
161
+ * that something was.
162
+ */
163
+ export const COMPARE_MAX_FILES = 300
164
+
165
+ /**
166
+ * How much unified diff one compare carries: 1 MiB.
167
+ *
168
+ * Enforced on git's OUTPUT as it is read (`gitBounded`, `src/git.ts`), so a
169
+ * diff past it is cut off in the subprocess rather than buffered whole and
170
+ * then trimmed. The cut lands on a line boundary. A reader wanting the rest
171
+ * clones the repository, or compares fewer changes.
172
+ */
173
+ export const COMPARE_MAX_DIFF_BYTES = 1024 * 1024
174
+
175
+ /** What one file did between the merge base and the head. */
176
+ export type CompareStatus = 'added' | 'modified' | 'deleted' | 'renamed'
177
+
178
+ /** One changed file, as `git diff --raw --numstat -M` reports it. */
179
+ export interface CompareFile {
180
+ /** The path at the head; for a deletion, the path that was deleted. */
181
+ path: string
182
+ /** For a rename only: the path at the merge base. */
183
+ previousPath?: string
184
+ status: CompareStatus
185
+ /** Lines added. `0` for a binary file, which has no lines to count. */
186
+ additions: number
187
+ /** Lines deleted. `0` for a binary file. */
188
+ deletions: number
189
+ binary: boolean
190
+ }
191
+
192
+ /** A compare, as the Cache answers it — before the Index facts join it. */
193
+ export interface Comparison {
194
+ /** The commit the head is diffed against: `git merge-base base head`. */
195
+ mergeBase: string
196
+ /** The changed files, in git's path order, capped at `COMPARE_MAX_FILES`. */
197
+ files: CompareFile[]
198
+ /** Counted over every changed file, including any `files` leaves out. */
199
+ totals: { files: number; additions: number; deletions: number }
200
+ /** The unified diff of the listed files, cut at `COMPARE_MAX_DIFF_BYTES`. */
201
+ diff: string
202
+ /** A cap was hit: `files` is not every changed file, or `diff` was cut. */
203
+ truncated: boolean
204
+ }
205
+
206
+ /**
207
+ * What `op=compare` answers: the repository, the two refs as resolved, and the
208
+ * comparison of the head against their merge base (three-dot).
209
+ */
210
+ export interface BrowseCompareAnswer extends BrowseRefsAnswer, Comparison {
211
+ base: { ref: string; oid: string }
212
+ head: { ref: string; oid: string }
213
+ }
214
+
154
215
  /**
155
216
  * The README a directory listing holds, by the fixed preference order.
156
217
  *