@zabaca/zbc 0.20.0 → 0.21.1

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 (55) hide show
  1. package/package.json +1 -1
  2. package/templates/apps/walgit/CONTEXT.md +37 -0
  3. package/templates/apps/walgit/README.md +193 -4
  4. package/templates/apps/walgit/e2e/harness.ts +2 -2
  5. package/templates/apps/walgit/e2e/scenarios.ts +302 -2
  6. package/templates/apps/walgit/package.json +5 -1
  7. package/templates/apps/walgit/registry.json +1 -1
  8. package/templates/apps/walgit/shared/browse.ts +733 -0
  9. package/templates/apps/walgit/shared/capabilities.ts +17 -0
  10. package/templates/apps/walgit/shared/container-env.ts +9 -0
  11. package/templates/apps/walgit/shared/landing.ts +8 -27
  12. package/templates/apps/walgit/shared/llms.ts +41 -0
  13. package/templates/apps/walgit/shared/mcp.ts +286 -0
  14. package/templates/apps/walgit/shared/policy.ts +21 -0
  15. package/templates/apps/walgit/shared/pooled.ts +31 -0
  16. package/templates/apps/walgit/shared/protocol.ts +140 -0
  17. package/templates/apps/walgit/shared/repo-list.ts +478 -0
  18. package/templates/apps/walgit/shared/store.ts +307 -0
  19. package/templates/apps/walgit/shared/telemetry.ts +79 -6
  20. package/templates/apps/walgit/shared/wal-index.ts +249 -0
  21. package/templates/apps/walgit/shared/web.ts +46 -0
  22. package/templates/apps/walgit/src/announce-main.ts +1 -1
  23. package/templates/apps/walgit/src/announce.ts +1 -1
  24. package/templates/apps/walgit/src/append-only.ts +5 -8
  25. package/templates/apps/walgit/src/browse.ts +230 -0
  26. package/templates/apps/walgit/src/cache.ts +4 -4
  27. package/templates/apps/walgit/src/compact.ts +6 -12
  28. package/templates/apps/walgit/src/delete-repo.ts +4 -3
  29. package/templates/apps/walgit/src/expire.ts +3 -3
  30. package/templates/apps/walgit/src/gc.ts +4 -3
  31. package/templates/apps/walgit/src/git.ts +127 -10
  32. package/templates/apps/walgit/src/hook-main.ts +1 -1
  33. package/templates/apps/walgit/src/http.ts +386 -3
  34. package/templates/apps/walgit/src/limits.ts +1 -1
  35. package/templates/apps/walgit/src/materialize.bench.ts +4 -10
  36. package/templates/apps/walgit/src/materialize.ts +11 -4
  37. package/templates/apps/walgit/src/orphans.ts +3 -3
  38. package/templates/apps/walgit/src/pending.ts +1 -1
  39. package/templates/apps/walgit/src/private.ts +1 -1
  40. package/templates/apps/walgit/src/proposals.ts +3 -3
  41. package/templates/apps/walgit/src/push-cert.ts +10 -1
  42. package/templates/apps/walgit/src/push.ts +11 -9
  43. package/templates/apps/walgit/src/reconcile.ts +4 -3
  44. package/templates/apps/walgit/src/server.ts +29 -2
  45. package/templates/apps/walgit/src/signers.ts +9 -3
  46. package/templates/apps/walgit/src/store-env.ts +8 -21
  47. package/templates/apps/walgit/src/store.ts +12 -241
  48. package/templates/apps/walgit/src/sync.ts +2 -2
  49. package/templates/apps/walgit/src/usage.ts +4 -18
  50. package/templates/apps/walgit/src/verify.ts +2 -2
  51. package/templates/apps/walgit/src/wal-index.ts +20 -239
  52. package/templates/apps/walgit/worker/index.ts +278 -1
  53. package/templates/apps/walgit/worker/mcp.ts +281 -0
  54. /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
  55. /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
@@ -146,6 +146,26 @@ export const READ_CHALLENGE_SCHEME = 'walgit-ssh'
146
146
  /** Where a subscriber connects. A WebSocket upgrade, and nothing else. */
147
147
  export const EVENTS_PATH = '/_walgit/events'
148
148
 
149
+ /**
150
+ * The Model Context Protocol endpoint (Streamable HTTP), answered at the edge.
151
+ *
152
+ * An MCP client reaches walgit by URL, so there is nothing to install and
153
+ * nothing to spawn — which is the whole reason it is here rather than in a
154
+ * package an agent's harness has to start. It carries only what the host can
155
+ * answer without the agent's disk: a name's state, a ref moving, who pushed it,
156
+ * and the manual. Everything that touches a clone stays a shell command.
157
+ *
158
+ * Under `/_walgit/` like health, events and provenance, and for the same
159
+ * reason: the prefix is reserved, and a repository is reached at
160
+ * `/<name>.git/…`, so this route cannot shadow one — not even a repository
161
+ * actually called `mcp`, which lives at `/mcp.git/…`.
162
+ *
163
+ * Both verbs, on one path: Streamable HTTP puts client messages on POST and the
164
+ * server-to-client stream on GET, and a transport that claimed only one of them
165
+ * is a client that connects and then hears nothing.
166
+ */
167
+ export const MCP_PATH = '/_walgit/mcp'
168
+
149
169
  /**
150
170
  * Where the container publishes a push it has already made durable.
151
171
  *
@@ -155,6 +175,121 @@ export const EVENTS_PATH = '/_walgit/events'
155
175
  */
156
176
  export const ANNOUNCE_PATH = '/_walgit/announce'
157
177
 
178
+ /**
179
+ * The repository list — the web view's one page that is about the deployment
180
+ * rather than about a name (`shared/repo-list.ts`).
181
+ *
182
+ * Not under `/_walgit/`, unlike every path above it: this one is TYPED by a
183
+ * person into a browser, and the reserved prefix exists for endpoints a client
184
+ * speaks rather than for pages someone reads. It lives here rather than in
185
+ * `shared/repo-list.ts` so `classifyRequest` can name the route without
186
+ * importing the renderer.
187
+ *
188
+ * Same collision argument as `/llms.txt` and its neighbours: a repository is
189
+ * reached at `/<name>.git/…`, so a repository actually called `repos` keeps its
190
+ * clone URL and only loses its bare browse URL (README).
191
+ */
192
+ export const REPOS_PATH = '/repos'
193
+
194
+ /**
195
+ * One repository's refs and one level of its tree, read on the Cache.
196
+ *
197
+ * `?repo=&op=refs|tree&ref=&path=`, and under `/_walgit/` for the reason every
198
+ * endpoint above is: the prefix is reserved and a repository is reached at
199
+ * `/<name>.git/…`, so it cannot shadow one.
200
+ *
201
+ * It is for the EDGE rather than for a client — the two browse pages are
202
+ * rendered from its answer (`shared/browse.ts`) — but it is gated as the
203
+ * Provenance Read beside it is, by the deployment credential and then the Read
204
+ * Challenge, rather than by `INTERNAL_HEADER`: it answers a question about one
205
+ * repository, and the credential a clone of that repository needs is exactly
206
+ * the credential a browse of it needs.
207
+ *
208
+ * Unlike every other read here it has to touch the Cache, because the Index
209
+ * holds refs and no objects — which is why it is the container that answers it
210
+ * at all, where the repository list is answered at the edge off the log.
211
+ */
212
+ export const BROWSE_PATH = '/_walgit/browse'
213
+
214
+ /**
215
+ * The browse URLs a person types: `/<name>`, and `/<name>/<kind>/<rest>` for
216
+ * each of the four GitHub-shaped reads.
217
+ *
218
+ * Group 1 is the repository; group 2 is the kind; group 3 is everything after
219
+ * it, which is a ref and a path RUN TOGETHER — a branch name may contain
220
+ * slashes, so where one ends is a question only the Index can answer
221
+ * (`shared/browse.ts` splits it by longest ref prefix). The regex therefore
222
+ * takes the remainder whole rather than pretending the URL says where the
223
+ * boundary is.
224
+ *
225
+ * The kinds are spelled out rather than matched as `[^/]+` so a URL naming one
226
+ * walgit does not serve — `/<name>/blame/…` — is not a page at all rather than
227
+ * a browse that 404s from deeper in; and so a repository page cannot be
228
+ * confused with a directory inside one.
229
+ *
230
+ * Not under `/_walgit/`, like `REPOS_PATH` and for the same reason: these are
231
+ * pages someone reads rather than endpoints a client speaks. Same collision
232
+ * argument too — a repository is cloned at `/<name>.git/…`, so a repository
233
+ * called `repos` keeps its clone URL and only loses its bare browse URL.
234
+ */
235
+ export const BROWSE_HTTP = /^\/([^/]+)(?:\/(tree|blob|raw|commits)\/(.+))?$/
236
+
237
+ /**
238
+ * Which of the four reads a browse URL names.
239
+ *
240
+ * `tree` is a directory (and the bare `/<name>`), `blob` a file's page, `raw`
241
+ * its bytes, `commits` the history. One vocabulary for the URL, the container's
242
+ * `op` and the page renderer, so a route the edge claims and the container does
243
+ * not answer is a type error rather than a 404 someone finds later.
244
+ */
245
+ export type BrowseKind = 'tree' | 'blob' | 'raw' | 'commits'
246
+
247
+ /** A browse URL, as the page routes spell one. */
248
+ export interface BrowseRoute {
249
+ repo: string
250
+ kind: BrowseKind
251
+ /** Everything after the kind: a ref and a path run together, or `''`. */
252
+ rest: string
253
+ }
254
+
255
+ /**
256
+ * Is this one of the two browse pages, and which repository?
257
+ *
258
+ * Only GET and HEAD, and only a name walgit would actually serve — the path is
259
+ * attacker-controlled, and a name this accepted and `resolveRepo` refused would
260
+ * be a page about a repository half the service can see.
261
+ *
262
+ * Here beside the grammar rather than in `shared/browse.ts` for the reason
263
+ * `SMART_HTTP` is here: the edge ROUTES on it and `classifyRequest` COUNTS on
264
+ * it, and two readings of the grammar would be a metric describing traffic
265
+ * that never happened. The classifier makes one deliberate narrowing on top of
266
+ * it — a path whose SHAPE already has a bucket (`/wp-login.php`, `/.env`) keeps
267
+ * that bucket rather than becoming a repository page, so the scanner baseline
268
+ * those buckets exist to measure stays measurable. It is stated there, once.
269
+ */
270
+ export function wantsBrowse(method: string, pathname: string): BrowseRoute | null {
271
+ if (method !== 'GET' && method !== 'HEAD') return null
272
+ const route = BROWSE_HTTP.exec(pathname)
273
+ if (!route) return null
274
+ const repo = route[1]!
275
+ if (!REPO_ID.test(repo)) return null
276
+ // A bare `/<name>` is the tree at the default branch: the kind is absent
277
+ // from the URL because there is nothing yet to disambiguate.
278
+ return { repo, kind: (route[2] as BrowseKind | undefined) ?? 'tree', rest: route[3] ?? '' }
279
+ }
280
+
281
+ /**
282
+ * The challenge every walgit refusal of a read carries.
283
+ *
284
+ * One string, because it is answered by two very different clients and refused
285
+ * in four places: git prompts for a credential only when challenged in this
286
+ * scheme (which is what makes `git clone https://…` work interactively at all),
287
+ * and a browser prompts for the same reason on the web view. The realm is what
288
+ * ties them together — one credential answers both — so it is stated here with
289
+ * the rest of the wire vocabulary rather than typed out at each refusal.
290
+ */
291
+ export const BASIC_CHALLENGE = 'Basic realm="walgit"'
292
+
158
293
  // ── Grammar ─────────────────────────────────────────────────────────────────
159
294
 
160
295
  /**
@@ -238,6 +373,9 @@ export const SIGNERS_REF = 'refs/walgit/signers'
238
373
  * a misconfigured client
239
374
  * - `collision` a name already taken — a product signal about naming
240
375
  * - `unauthorized` a bad or missing credential
376
+ * - `invalid` a request walgit could not read at all — a malformed
377
+ * history cursor, say. Not a thing that might have existed,
378
+ * which is what separates it from `not-found`
241
379
  * - `edge` walgit did not refuse; something in front of it did. This
242
380
  * one is a BUG SIGNAL: every refusal walgit means to make it
243
381
  * should make itself, with an explanation. Absorbing it into
@@ -247,6 +385,7 @@ export type RejectKind =
247
385
  | 'size-cap'
248
386
  | 'collision'
249
387
  | 'unauthorized'
388
+ | 'invalid'
250
389
  | 'not-found'
251
390
  | 'unavailable'
252
391
  | 'edge'
@@ -269,6 +408,7 @@ const KINDS = new Set<RejectKind>([
269
408
  'size-cap',
270
409
  'collision',
271
410
  'unauthorized',
411
+ 'invalid',
272
412
  'not-found',
273
413
  'unavailable',
274
414
  'edge',
@@ -0,0 +1,478 @@
1
+ /**
2
+ * `/repos` — what this deployment holds, answered at the edge.
3
+ *
4
+ * The whole point of the placement is the same one the landing page makes: the
5
+ * container serves git, and somebody clicking around a browser should not wake
6
+ * it, queue behind a clone, or count against the one instance serving pushes.
7
+ * Everything this page shows is already in the log — `index.json` carries the
8
+ * full ref state, the entry list and the Claim (`shared/wal-index.ts`) — so the
9
+ * list is a fold over objects the edge can read for itself.
10
+ *
11
+ * ── it is a capability, so it is default off ────────────────────────────────
12
+ *
13
+ * `caps.web` (`shared/capabilities.ts`) is the one switch, read once like every
14
+ * other Advertised capability, and the route does not exist without it. A list
15
+ * of names is the one thing a credentialed deployment has not already been
16
+ * asked to publish: the credential still gates this route, but *enumerating*
17
+ * names is a surface an operator opts into rather than acquires on upgrade.
18
+ *
19
+ * ── a value, not a Response ─────────────────────────────────────────────────
20
+ *
21
+ * Like `shared/robots.ts` and `shared/favicon.ts`: this module states the
22
+ * status, the headers and the body, and the Worker owns the `Response`. That is
23
+ * what keeps `shared/`'s one rule (docs/adr/0010) — no runtime here — and what
24
+ * lets the gate, the negotiation, the cache headers and every row be driven
25
+ * from `src/repo-list.test.ts` with no Workers runtime and no socket.
26
+ *
27
+ * ── the gate is the one that already exists ─────────────────────────────────
28
+ *
29
+ * `authorizedBy` (`shared/credentials.ts`), the same function the event socket
30
+ * is gated on and the same credential a clone presents. A second copy of the
31
+ * check would be a second policy the first time either was edited. It is
32
+ * answered BEFORE the store is touched, so a stranger cannot make a credentialed
33
+ * deployment read its own bucket.
34
+ *
35
+ * ── no name the log holds is ever omitted ───────────────────────────────────
36
+ *
37
+ * An Index that cannot be read renders as the bare name with no facts, never as
38
+ * a skipped row. A missing repository is the one failure a reader cannot detect
39
+ * and the one that would send somebody looking for a name they can see is gone
40
+ * — and the asymmetry `src/usage.ts` already names holds here: naming a
41
+ * repository we know nothing about costs a line, hiding one costs trust.
42
+ */
43
+
44
+ import type { Capabilities } from './capabilities'
45
+ import { authorizedBy } from './credentials'
46
+ import { indexKey, listRepoIds } from './keys'
47
+ import { escapeHtml } from './landing'
48
+ import { pooled } from './pooled'
49
+ import { shortBytes } from './policy'
50
+ import { BASIC_CHALLENGE, REPOS_PATH } from './protocol'
51
+ import type { ObjectStore } from './store'
52
+ import { WEB_STYLE, webCacheControl } from './web'
53
+ import type { WalIndex } from './wal-index'
54
+
55
+ /** Rows on one page. A hundred names is a screenful to scroll, not to load. */
56
+ export const REPO_LIST_PAGE_SIZE = 100
57
+
58
+ /**
59
+ * How many names this view will read Indexes for in order to sort by recency.
60
+ *
61
+ * One delimited LIST names every repository cheaply (`listRepoIds`); reading
62
+ * `index.json` for each of them does not scale the same way, and sorting by
63
+ * last push requires all of them. So past this many names the view stops
64
+ * claiming recency: the order stays the one the store gave (name order), only
65
+ * the requested page's Indexes are read, and the page says so. A thousand is
66
+ * also one R2 listing page, which is what makes the cheap path exactly one
67
+ * round trip.
68
+ */
69
+ export const REPO_LIST_MAX_FACTS = 1000
70
+
71
+ /** Indexes read at once. Enough to hide latency, few enough to not be a burst. */
72
+ export const REPO_LIST_CONCURRENCY = 16
73
+
74
+ /** What the Worker knows about the request, and nothing about its runtime. */
75
+ export interface RepoListRequest {
76
+ method: string
77
+ /** The `Accept` header, verbatim. HTML for a browser, anything else is JSON. */
78
+ accept: string
79
+ /** The `Authorization` header, or `null`. */
80
+ authorization: string | null
81
+ /** The query string, e.g. `?page=2`. Absent reads as the first page. */
82
+ search?: string
83
+ }
84
+
85
+ export interface RepoListDeps {
86
+ store: ObjectStore
87
+ /** What this deployment offers — the gate reads `publicAccess` from it. */
88
+ caps: Capabilities
89
+ /** The configured credentials (`parseTokens`). */
90
+ tokens: readonly string[]
91
+ }
92
+
93
+ /** A response as a value: the Worker turns this into a `Response`. */
94
+ export interface EdgeResponse {
95
+ status: number
96
+ headers: Record<string, string>
97
+ body: string
98
+ }
99
+
100
+ /** One repository, as the list shows it. `null` means the Index did not say. */
101
+ export interface RepoRow {
102
+ name: string
103
+ /** ISO instant of the newest push entry, or `null` when there is none. */
104
+ lastPush: string | null
105
+ refs: number | null
106
+ /** Bytes a restore would download — entries above the compaction frontier. */
107
+ liveBytes: number | null
108
+ /** It holds a Signer List, so a stranger's push is refused (docs/adr/0012). */
109
+ claimed: boolean
110
+ /** It holds a Reader List, so a stranger's read is refused (docs/adr/0013). */
111
+ private: boolean
112
+ /** Scheduled for deletion and inside its grace period. */
113
+ deletionPending: boolean
114
+ /** Present only when the Index could not be read, which is what it means. */
115
+ unreadable?: true
116
+ }
117
+
118
+ /** Only GET or HEAD on the one path. A POST to it is not this document. */
119
+ export function wantsRepoList(method: string, pathname: string): boolean {
120
+ if (method !== 'GET' && method !== 'HEAD') return false
121
+ return pathname === REPOS_PATH
122
+ }
123
+
124
+ /**
125
+ * The list, as a status, headers and a body.
126
+ *
127
+ * `HEAD` is answered with the same headers as the `GET` it precedes — the
128
+ * Worker drops the body, the way it does for every other edge route.
129
+ */
130
+ export async function repoListResponse(
131
+ request: RepoListRequest,
132
+ deps: RepoListDeps,
133
+ ): Promise<EdgeResponse> {
134
+ const { caps, store, tokens } = deps
135
+
136
+ // Before the store is touched. A refusal must not be the reason a bucket is
137
+ // read, and must never be cached: the next request carries a credential.
138
+ if (!caps.publicAccess && !authorizedBy(request.authorization, tokens)) {
139
+ return {
140
+ status: 401,
141
+ headers: {
142
+ 'content-type': 'text/plain; charset=utf-8',
143
+ // The challenge git is refused with, so one credential answers the
144
+ // clone and the browse (`shared/protocol.ts`).
145
+ 'www-authenticate': BASIC_CHALLENGE,
146
+ 'cache-control': 'no-store',
147
+ },
148
+ body: 'unauthorized\n',
149
+ }
150
+ }
151
+
152
+ const page = requestedPage(request.search)
153
+ const listing = await collectRepoList(store, page)
154
+
155
+ // A minute, and only where a read takes no credential — the same reasoning
156
+ // the landing page's header carries, plus the one this page adds: a shared
157
+ // cache must not hold a document that exists because THIS request presented
158
+ // a token. One function for both web-view pages (`shared/web.ts`).
159
+ const cacheControl = webCacheControl(caps)
160
+
161
+ const wantsHtml = request.accept.toLowerCase().includes('text/html')
162
+ if (!wantsHtml) {
163
+ return {
164
+ status: 200,
165
+ headers: {
166
+ 'content-type': 'application/json; charset=utf-8',
167
+ 'cache-control': cacheControl,
168
+ 'x-robots-tag': 'noindex',
169
+ },
170
+ body: `${JSON.stringify(listing, null, 2)}\n`,
171
+ }
172
+ }
173
+
174
+ return {
175
+ status: 200,
176
+ headers: {
177
+ 'content-type': 'text/html; charset=utf-8',
178
+ 'cache-control': cacheControl,
179
+ // A list of names is not a page anyone should reach from a search
180
+ // engine, and on a credentialed deployment it is not one a crawler can
181
+ // read at all. Stated in the header as well as the document, because a
182
+ // crawler that fetched it before reading the markup has already been
183
+ // told.
184
+ 'x-robots-tag': 'noindex',
185
+ // The filter below is the only script and there is no other resource:
186
+ // nothing may load, nothing may connect, nothing may post.
187
+ 'content-security-policy':
188
+ "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; " +
189
+ "img-src data:; base-uri 'none'; form-action 'none'",
190
+ },
191
+ body: renderRepoList(listing),
192
+ }
193
+ }
194
+
195
+ /** What one request asked for, and what the log answered. */
196
+ export interface RepoListing {
197
+ repos: RepoRow[]
198
+ /** 1-based, clamped into range. */
199
+ page: number
200
+ pages: number
201
+ /** Every name the log holds, not just this page. */
202
+ total: number
203
+ /**
204
+ * What the order means. `push` is last push descending; `name` is the store's
205
+ * own order, which is what this view falls back to past
206
+ * `REPO_LIST_MAX_FACTS` names.
207
+ */
208
+ sortedBy: 'push' | 'name'
209
+ }
210
+
211
+ /**
212
+ * Read the log into one page of rows.
213
+ *
214
+ * Two paths, and the fork is the count of names rather than a configuration:
215
+ * up to `REPO_LIST_MAX_FACTS` every Index is read, so the page can be sorted by
216
+ * recency; past it only the page being rendered is read and the order stays the
217
+ * store's.
218
+ *
219
+ * What is NOT bounded is the name listing itself: `listRepoIds` pages through
220
+ * the store until it has every name, which on a bucket holding fifty thousand
221
+ * repositories is fifty delimited LISTs rather than one. That is deliberate,
222
+ * and it is the cheaper half by a wide margin — a listing page names a thousand
223
+ * repositories, where the Index reads it feeds cost one GET each. Capping it
224
+ * would mean either paginating no further than the cap (so a name the log holds
225
+ * would have no page it appears on) or renumbering pages per request; the rule
226
+ * this view is held to is that no name is ever omitted, so the listing runs to
227
+ * the end.
228
+ */
229
+ export async function collectRepoList(store: ObjectStore, page: number): Promise<RepoListing> {
230
+ // One delimited LIST where the store can roll up prefixes, and a derived
231
+ // listing where it cannot (`shared/keys.ts`).
232
+ const names = await listRepoIds(store)
233
+ const pages = Math.max(1, Math.ceil(names.length / REPO_LIST_PAGE_SIZE))
234
+ const current = Math.min(Math.max(page, 1), pages)
235
+
236
+ if (names.length > REPO_LIST_MAX_FACTS) {
237
+ const slice = names.slice((current - 1) * REPO_LIST_PAGE_SIZE, current * REPO_LIST_PAGE_SIZE)
238
+ return {
239
+ repos: await pooled(slice, REPO_LIST_CONCURRENCY, (name) => rowFor(store, name)),
240
+ page: current,
241
+ pages,
242
+ total: names.length,
243
+ sortedBy: 'name',
244
+ }
245
+ }
246
+
247
+ const rows = await pooled(names, REPO_LIST_CONCURRENCY, (name) => rowFor(store, name))
248
+ // Newest push first, and a name with no push entry — a ref-only push appends
249
+ // none — sorts after every name that has one rather than to the top, which is
250
+ // where an empty string would put it.
251
+ rows.sort((a, b) => {
252
+ if (a.lastPush === b.lastPush) return a.name < b.name ? -1 : 1
253
+ if (a.lastPush === null) return 1
254
+ if (b.lastPush === null) return -1
255
+ return a.lastPush < b.lastPush ? 1 : -1
256
+ })
257
+ return {
258
+ repos: rows.slice((current - 1) * REPO_LIST_PAGE_SIZE, current * REPO_LIST_PAGE_SIZE),
259
+ page: current,
260
+ pages,
261
+ total: names.length,
262
+ sortedBy: 'push',
263
+ }
264
+ }
265
+
266
+ /**
267
+ * One row, or the bare name.
268
+ *
269
+ * Every failure is the same row: absent, unparseable, the wrong version, or an
270
+ * index declaring a different `repo_id` (which is a routing fault, and serving
271
+ * its facts under this name would hide one). Nothing here throws — a single
272
+ * unreadable object must not be able to take the page down.
273
+ */
274
+ async function rowFor(store: ObjectStore, name: string): Promise<RepoRow> {
275
+ try {
276
+ const found = await store.get(indexKey(name))
277
+ if (!found) return bare(name)
278
+ const index = JSON.parse(new TextDecoder().decode(found.body)) as WalIndex
279
+ if (index.version !== 1 || index.repo_id !== name) return bare(name)
280
+ return foldIndex(name, index)
281
+ } catch {
282
+ return bare(name)
283
+ }
284
+ }
285
+
286
+ const bare = (name: string): RepoRow => ({
287
+ name,
288
+ lastPush: null,
289
+ refs: null,
290
+ liveBytes: null,
291
+ claimed: false,
292
+ private: false,
293
+ deletionPending: false,
294
+ unreadable: true,
295
+ })
296
+
297
+ /**
298
+ * The three numbers this page shows, folded out of one Index.
299
+ *
300
+ * `src/usage.ts`'s `usageOfIndex` folds the same object into fourteen fields
301
+ * for the operator's report, and is deliberately not reused: it lives on the
302
+ * container side (it is reached through the CLI), and `shared/` may not import
303
+ * `src/`. What is duplicated is the two lines that define live bytes and last
304
+ * push, held to exactly the three fields a row shows.
305
+ */
306
+ function foldIndex(name: string, index: WalIndex): RepoRow {
307
+ let liveBytes = 0
308
+ for (const entry of index.entries) {
309
+ // What a restore actually downloads. Entries at or below the frontier have
310
+ // been superseded by a compaction and are storage waiting on `walgit gc`.
311
+ if (entry.seq > index.compaction_frontier) liveBytes += entry.size
312
+ }
313
+ return {
314
+ name,
315
+ lastPush: lastPushOf(index),
316
+ refs: Object.keys(index.refs ?? {}).length,
317
+ liveBytes,
318
+ // A Claim IS the Signer List, so its presence is what makes the name
319
+ // refuse a stranger's push. A Reader List is a field inside it, and its
320
+ // presence — `[]` included — is what makes the name Private.
321
+ claimed: index.claim !== undefined,
322
+ private: index.claim?.readers !== undefined,
323
+ deletionPending: index.deletion !== undefined,
324
+ }
325
+ }
326
+
327
+ /**
328
+ * When this repository last took a push, or `null` when it has taken none.
329
+ *
330
+ * A COMPACTION entry is not a push: a repack is storage, not traffic, and
331
+ * counting one would make a quiet repository look busy on the day it was
332
+ * compacted — and, where a retention window is set, would silently extend its
333
+ * life on the page that states it (`shared/browse.ts` renders the same fact as
334
+ * "expires in N hours", and the sweeper measures the same one).
335
+ *
336
+ * Exported because the browse reads it too, and two folds of one field are how
337
+ * a page and a sweeper come to disagree about when a repository dies.
338
+ */
339
+ export function lastPushOf(index: WalIndex): string | null {
340
+ let lastPush: string | null = null
341
+ for (const entry of index.entries) {
342
+ if (entry.kind !== 'push') continue
343
+ if (lastPush === null || entry.ts > lastPush) lastPush = entry.ts
344
+ }
345
+ return lastPush
346
+ }
347
+
348
+ /** The page number the query string asked for. Anything else is the first. */
349
+ function requestedPage(search: string | undefined): number {
350
+ const raw = new URLSearchParams(search ?? '').get('page')
351
+ const page = Number(raw)
352
+ return Number.isInteger(page) && page > 0 ? page : 1
353
+ }
354
+
355
+ // ── The page ────────────────────────────────────────────────────────────────
356
+
357
+ /**
358
+ * A name arrives here as bytes from a bucket rather than as a path the
359
+ * smart-HTTP grammar checked, so it is escaped rather than trusted — with the
360
+ * landing page's own escaper (`shared/landing.ts`), because two of those is two
361
+ * chances for one of them to miss a character. The page also carries a CSP that
362
+ * would refuse a script even if this were wrong.
363
+ *
364
+ * Bytes are `shortBytes` (`shared/policy.ts`), derived from the one
365
+ * `describeBytes` a refusal prints: a size in this table and the cap
366
+ * `pre-receive` refuses on must not look like two different numbers.
367
+ */
368
+
369
+ /** An instant, as a date. The page is a directory, not a clock. */
370
+ function shortDate(iso: string): string {
371
+ const at = Date.parse(iso)
372
+ // An unparseable timestamp is shown verbatim rather than as `Invalid Date`:
373
+ // it came out of the log, and inventing a reading of it would be worse than
374
+ // printing what is there.
375
+ return Number.isFinite(at) ? new Date(at).toISOString().slice(0, 10) : iso
376
+ }
377
+
378
+ function row(repo: RepoRow): string {
379
+ const tags = [
380
+ repo.private ? '<span class="tag">Private</span>' : '',
381
+ // Both, where both hold: a Reader List lives INSIDE the Claim
382
+ // (`shared/wal-index.ts`), so a Private name is a claimed name, and a row
383
+ // that showed only the second fact would be dropping the first.
384
+ repo.claimed ? '<span class="tag">claimed</span>' : '',
385
+ repo.deletionPending ? '<span class="tag leaving">being removed</span>' : '',
386
+ ]
387
+ .filter((tag) => tag !== '')
388
+ .join(' ')
389
+ const name = escapeHtml(repo.name)
390
+ return ` <tr${repo.deletionPending ? ' class="leaving"' : ''} data-name="${name}">
391
+ <td class="n"><a href="/${name}">${name}</a> ${tags}</td>
392
+ <td class="f">${repo.lastPush === null ? '—' : shortDate(repo.lastPush)}</td>
393
+ <td class="f">${repo.refs === null ? '—' : repo.refs}</td>
394
+ <td class="f">${repo.liveBytes === null ? '—' : shortBytes(repo.liveBytes)}</td>
395
+ </tr>`
396
+ }
397
+
398
+ function pager(listing: RepoListing): string {
399
+ if (listing.pages < 2) return ''
400
+ const links = [
401
+ listing.page > 1 ? `<a href="${REPOS_PATH}?page=${listing.page - 1}">← newer</a>` : '',
402
+ `<span>page ${listing.page} of ${listing.pages}</span>`,
403
+ listing.page < listing.pages
404
+ ? `<a href="${REPOS_PATH}?page=${listing.page + 1}">older →</a>`
405
+ : '',
406
+ ].filter((link) => link !== '')
407
+ return ` <nav class="pager">${links.join(' ')}</nav>\n`
408
+ }
409
+
410
+ /**
411
+ * The page, as a string.
412
+ *
413
+ * No framework, no build step and no request beyond the document itself: one
414
+ * inline stylesheet, and one inline script whose entire job is to hide rows
415
+ * that do not match what was typed. The table is complete and sorted before
416
+ * any script runs, so a reader with no JavaScript loses the filter and nothing
417
+ * else.
418
+ */
419
+ export function renderRepoList(listing: RepoListing): string {
420
+ const notice =
421
+ listing.sortedBy === 'name'
422
+ ? ` <p class="note">${listing.total} repositories — more than this view reads state for, so they are in name order rather than by last push.</p>\n`
423
+ : ''
424
+
425
+ const table =
426
+ listing.repos.length === 0
427
+ ? ' <p class="note">No repositories yet. The first push creates one.</p>\n'
428
+ : ` <table>
429
+ <thead><tr><th>name</th><th class="f">last push</th><th class="f">refs</th><th class="f">size</th></tr></thead>
430
+ <tbody id="rows">
431
+ ${listing.repos.map(row).join('\n')}
432
+ </tbody>
433
+ </table>
434
+ `
435
+
436
+ return `<!doctype html>
437
+ <html lang="en">
438
+ <head>
439
+ <meta charset="utf-8">
440
+ <meta name="viewport" content="width=device-width, initial-scale=1">
441
+ <meta name="robots" content="noindex">
442
+ <title>repositories</title>
443
+ <style>
444
+ ${WEB_STYLE}
445
+ input { width: 100%; box-sizing: border-box; padding: .5rem .6rem; margin-bottom: 1rem;
446
+ color: inherit; background: transparent; border: 1px solid var(--muted); border-radius: 4px; font: inherit; }
447
+ tr.leaving { opacity: .5; }
448
+ .tag.leaving { color: var(--accent); border-color: var(--accent); }
449
+ .pager { margin-top: 1rem; display: flex; gap: 1rem; color: var(--muted); }
450
+ </style>
451
+ </head>
452
+ <body>
453
+ <main>
454
+ <h1>repositories <span class="note">(${listing.total})</span></h1>
455
+ <input id="filter" type="search" placeholder="filter by name" autocomplete="off" aria-label="filter by name">
456
+ ${notice}${table}${pager(listing)} <p class="note"><a href="/">what this is</a> · <a href="/llms.txt">the manual</a></p>
457
+ </main>
458
+ <script>
459
+ // The filter, and nothing else. The rows are already in the document, so a
460
+ // reader with no JavaScript keeps the whole list — only this convenience is
461
+ // lost. It filters the page it has: paging is a link, not a fetch.
462
+ (function () {
463
+ var input = document.getElementById("filter");
464
+ var rows = document.getElementById("rows");
465
+ if (!input || !rows) return;
466
+ input.addEventListener("input", function () {
467
+ var needle = input.value.trim().toLowerCase();
468
+ Array.prototype.forEach.call(rows.rows, function (tr) {
469
+ var name = (tr.getAttribute("data-name") || "").toLowerCase();
470
+ tr.hidden = needle !== "" && name.indexOf(needle) === -1;
471
+ });
472
+ });
473
+ })();
474
+ </script>
475
+ </body>
476
+ </html>
477
+ `
478
+ }