@zabaca/zbc 0.24.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -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
  *
@@ -60,11 +60,15 @@ type CapabilityVar = Extract<
60
60
  | 'WALGIT_MAX_REPO_BYTES'
61
61
  | 'WALGIT_EVENTS_URL'
62
62
  | 'WALGIT_EVENTS_TOKEN'
63
+ | 'WALGIT_WEBHOOK_URL'
64
+ | 'WALGIT_WEBHOOK_SECRET'
63
65
  | 'WALGIT_PUSH_CERT_SEED'
64
66
  | 'WALGIT_SIGNER_LISTS'
65
67
  | 'WALGIT_PRIVATE_REPOS'
66
68
  | 'WALGIT_PROPOSALS'
69
+ | 'WALGIT_MERGE'
67
70
  | 'WALGIT_WEB'
71
+ | 'WALGIT_TOKEN_PUBLIC_KEYS'
68
72
  | 'WALGIT_RATE_WINDOW_SECONDS'
69
73
  | 'WALGIT_MAX_NEW_REPOS_PER_SOURCE'
70
74
  | 'WALGIT_MAX_PUSHES_PER_SOURCE'
@@ -108,6 +112,12 @@ export type Capabilities = {
108
112
  * since an agent writes the client before finding out.
109
113
  */
110
114
  events: boolean
115
+ /**
116
+ * Every moved ref is also POSTed, signed, to the operator's webhook
117
+ * (shared/webhook.ts). Both halves, read as `webhookConfigFromEnv` reads
118
+ * them. Says only THAT it is on: the URL is the operator's, never published.
119
+ */
120
+ webhook: boolean
111
121
  /**
112
122
  * A signed push is accepted, and who made it is recorded.
113
123
  *
@@ -197,6 +207,19 @@ export type Capabilities = {
197
207
  * operator opts into rather than acquires on upgrade.
198
208
  */
199
209
  web: boolean
210
+ /**
211
+ * Scoped tokens are accepted (`shared/scoped-token.ts`, docs/adr/0021): an
212
+ * issuer holding the private key mints a short-lived credential for one
213
+ * repository, read or write. Off unless `WALGIT_TOKEN_PUBLIC_KEYS` is set.
214
+ */
215
+ scopedTokens: boolean
216
+ /**
217
+ * The host merges on request (`src/merge.ts`, docs/adr/0022): `POST
218
+ * /_walgit/merge` moves a branch by fast-forward or squash, as a
219
+ * compare-and-swap, through the same push path a client's push takes. Off
220
+ * unless `WALGIT_MERGE` is set, and then the route does not exist.
221
+ */
222
+ merge: boolean
200
223
  /** A repository is collected this many hours after its last push. */
201
224
  retentionHours: number | null
202
225
  /**
@@ -300,6 +323,7 @@ export function capabilitiesFrom(
300
323
  // (`src/announce.ts`) makes of the same two variables — the config the push
301
324
  // path announces with and this advertisement cannot be allowed to disagree.
302
325
  events: nonBlank(env.WALGIT_EVENTS_URL) && nonBlank(env.WALGIT_EVENTS_TOKEN),
326
+ webhook: nonBlank(env.WALGIT_WEBHOOK_URL) && nonBlank(env.WALGIT_WEBHOOK_SECRET),
303
327
  signedPushes,
304
328
  namesCanRefuse,
305
329
  namesCanBeClaimed,
@@ -310,6 +334,8 @@ export function capabilitiesFrom(
310
334
  seedValue(env.WALGIT_PRIVATE_REPOS) !== null,
311
335
  proposals: namesCanRefuse && signedPushes && flagEnabled(env.WALGIT_PROPOSALS),
312
336
  web: flagEnabled(env.WALGIT_WEB),
337
+ scopedTokens: seedValue(env.WALGIT_TOKEN_PUBLIC_KEYS) !== null,
338
+ merge: flagEnabled(env.WALGIT_MERGE),
313
339
  retentionHours,
314
340
  claimedRetentionHours:
315
341
  namesCanBeClaimed &&
@@ -71,6 +71,11 @@ export const CONTAINER_ENV = [
71
71
  // stranger fabricating events (shared/events.ts).
72
72
  'WALGIT_EVENTS_URL',
73
73
  'WALGIT_EVENTS_TOKEN',
74
+ // The push webhook's two halves (shared/webhook.ts). Delivered from the same
75
+ // detached announcer as the stream, inside the container, so the container
76
+ // is the side that needs the URL and the signing secret.
77
+ 'WALGIT_WEBHOOK_URL',
78
+ 'WALGIT_WEBHOOK_SECRET',
74
79
  // Signed pushes. The seed is what `git-receive-pack` derives its nonce from,
75
80
  // and receive-pack runs inside the container — so this is the variable that
76
81
  // decides whether the capability is advertised at all (src/push-cert.ts).
@@ -91,6 +96,9 @@ export const CONTAINER_ENV = [
91
96
  // nonce and mints nothing — it only widens what `pre-receive` accepts on a
92
97
  // claimed name, and the hook that widens runs in the container.
93
98
  'WALGIT_PROPOSALS',
99
+ // Host merges (docs/adr/0022). A plain flag: the merge route and the push it
100
+ // makes are both the container's, so it is the container that must know.
101
+ 'WALGIT_MERGE',
94
102
  // The web view (`shared/repo-list.ts`). The only variable on this list that
95
103
  // nothing inside the container reads: the list is answered at the edge, off
96
104
  // the log, precisely so a browse does not wake the container. It is here
@@ -100,6 +108,10 @@ export const CONTAINER_ENV = [
100
108
  // list buys everywhere else: the deploy that first sets it changes the
101
109
  // fingerprint and replaces the running container once.
102
110
  'WALGIT_WEB',
111
+ // Scoped tokens (docs/adr/0021). The edge verifies before it wakes the
112
+ // container, and the container verifies again on what reaches it, so both
113
+ // halves need the public keys — never a private one; walgit holds none.
114
+ 'WALGIT_TOKEN_PUBLIC_KEYS',
103
115
  // Per-source rate limits (src/rate-limit.ts). The verdict is reached in the
104
116
  // container's own HTTP handler — the only place that sees both the source the
105
117
  // edge attributed the request to and the repository it names — so the numbers
@@ -130,7 +130,7 @@ export function inactivityTimeoutMs(sleepAfterMs: number): number {
130
130
  * drops a response without reading or cancelling its body leaves a stream that
131
131
  * may never finish, and one such request would keep the container up forever:
132
132
  * the alarm sees it in flight and re-arms, every time. An hour is far past any
133
- * clone or push this host takes (the push cap is 99 MiB), so a request still
133
+ * clone or push this host takes (the public push cap is 90 MiB), so a request still
134
134
  * counted after it is let go of, and the idle clock starts.
135
135
  */
136
136
  export const INFLIGHT_MAX_MS = 60 * 60 * 1000
@@ -23,6 +23,10 @@
23
23
  * per-user model needs the repo namespace milestone 3 introduces. git sends the
24
24
  * credential this way, so accepting it is what makes `git clone https://…`
25
25
  * work with a bare token at all.
26
+ *
27
+ * A scoped token (docs/adr/0021) is read here too, and nowhere else: what this
28
+ * returns is what `shared/scoped-token.ts` judges, so the admin token and a
29
+ * scoped one cannot arrive by two parsers that disagree about the header.
26
30
  */
27
31
  export function presentedCredential(header: string): string | null {
28
32
  const bearer = /^Bearer (.+)$/i.exec(header)