@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
@@ -0,0 +1,356 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import * as path from 'node:path'
3
+ import { copyTemplateFile } from './copy-template'
4
+ import {
5
+ ensureCleanGitTree,
6
+ git,
7
+ isVendorMode,
8
+ subtreeAdd,
9
+ subtreePull,
10
+ subtreeSplitCommit,
11
+ VENDOR_PREFIX,
12
+ } from './subtree'
13
+ import { assertStampReadable, readAppStamps, writeAppStamp } from './vendor-stamp'
14
+
15
+ /**
16
+ * A vendored app: a whole application a project pulls as a git subtree of the
17
+ * app's own public copy, at a prefix of its own, and keeps as files it may
18
+ * change. It is the engine's distribution (ADR-0005) applied to an app that is
19
+ * too large, and changes too often, to be a template copied once: `zbc add
20
+ * <app>` runs the squashed `subtree add`, `zbc update <app>` the squashed pull,
21
+ * and the project's own edits ride through a pull as any merge carries them.
22
+ *
23
+ * The app is NOT in the npm package. The CLI knows only its name, where its
24
+ * public copy is and where it lands; everything else about it (its workspace
25
+ * folders, the modules its deploy needs, the files a new install starts from)
26
+ * is the app's own manifest, read from the pulled copy, so the app can change
27
+ * those without a CLI release.
28
+ */
29
+ export interface VendoredApp {
30
+ name: string
31
+ /** The app's public copy: a repository CI splits from this one, never edited directly. */
32
+ url: string
33
+ /** Where it lands in a project, relative to the project root. */
34
+ prefix: string
35
+ }
36
+
37
+ export const VENDORED_APPS: Record<string, VendoredApp> = {
38
+ space: {
39
+ name: 'space',
40
+ url: 'https://github.com/Zabaca/zbc-space.git',
41
+ prefix: 'vendor/space',
42
+ },
43
+ }
44
+
45
+ /** The app's manifest, at the root of its folder. */
46
+ export const APP_MANIFEST = 'zbc-app.json'
47
+
48
+ export interface AppManifest {
49
+ name: string
50
+ /** Workspace patterns, relative to the app's folder (`packages/*`). */
51
+ workspaces?: string[]
52
+ /** The zbc modules the app's deploy builds its instances from. */
53
+ modules?: string[]
54
+ /**
55
+ * Files a new install starts from: `from` is relative to the app's folder,
56
+ * `to` to the project root. Both may hold `{{ENV}}`; what a file's body may
57
+ * hold is `layStarter`'s to say. Written only when absent: they are the
58
+ * project's own from then on.
59
+ */
60
+ starter?: { from: string; to: string }[]
61
+ }
62
+
63
+ export async function readAppManifest(projectRoot: string, app: VendoredApp): Promise<AppManifest> {
64
+ const file = Bun.file(path.join(projectRoot, app.prefix, APP_MANIFEST))
65
+ if (!(await file.exists())) return { name: app.name }
66
+ return (await file.json()) as AppManifest
67
+ }
68
+
69
+ /** `v1.4.0` as its three numbers. */
70
+ const numbers = (tag: string) => tag.slice(1).split('.').map(Number)
71
+
72
+ /**
73
+ * The newest version tag of a repository (`v1.4.0`, read as numbers), asked of
74
+ * the remote without fetching it. An app's tags are its own versions, not the
75
+ * CLI's, so there is no version to compute a ref from as the engine does.
76
+ */
77
+ export function newestTag(url: string, cwd: string = process.cwd()): string {
78
+ const listing = git(cwd, ['ls-remote', '--tags', '--refs', url])
79
+ const tags = listing
80
+ .split('\n')
81
+ .map((line) => /refs\/tags\/(v\d+\.\d+\.\d+)$/.exec(line)?.[1])
82
+ .filter((tag): tag is string => tag !== undefined)
83
+ if (tags.length === 0) {
84
+ throw new Error(
85
+ `${url} has no version tag (vX.Y.Z). Name a ref instead: --ref main pulls the newest commit.`,
86
+ )
87
+ }
88
+ return tags.toSorted((a, b) => {
89
+ const [x, y] = [numbers(a), numbers(b)]
90
+ return x[0]! - y[0]! || x[1]! - y[1]! || x[2]! - y[2]!
91
+ })[tags.length - 1]!
92
+ }
93
+
94
+ /**
95
+ * Add the app's workspace folders to the project's root manifest. Returns the
96
+ * patterns it added; one already listed is left alone, so a second run adds
97
+ * nothing.
98
+ */
99
+ export async function addWorkspaces(
100
+ projectRoot: string,
101
+ app: VendoredApp,
102
+ patterns: string[],
103
+ ): Promise<string[]> {
104
+ const file = path.join(projectRoot, 'package.json')
105
+ const pkg = JSON.parse(await fs.readFile(file, 'utf8')) as {
106
+ workspaces?: string[] | { packages?: string[] }
107
+ }
108
+ // Both spellings a root manifest may use: a list, or `{ packages: [...] }`.
109
+ const listed = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? [])
110
+ const wanted = patterns.map((pattern) => path.posix.join(app.prefix, pattern))
111
+ const added = wanted.filter((pattern) => !listed.includes(pattern))
112
+ if (added.length === 0) return []
113
+ const next = [...listed, ...added]
114
+ if (Array.isArray(pkg.workspaces) || pkg.workspaces === undefined) pkg.workspaces = next
115
+ else pkg.workspaces.packages = next
116
+ await fs.writeFile(file, `${JSON.stringify(pkg, null, 2)}\n`)
117
+ return added
118
+ }
119
+
120
+ /**
121
+ * Where the things a starter file imports are, from the project root. The app's
122
+ * glue imports the project's own zbc modules, and where those are depends on
123
+ * how the project took the engine: a subtree project has them under
124
+ * `vendor/zbc`, a copy-mode one under `packages/infra`.
125
+ */
126
+ export async function starterRoots(
127
+ projectRoot: string,
128
+ app: VendoredApp,
129
+ ): Promise<{ APP: string; MODULES: string; ENGINE: string }> {
130
+ const vendored = await isVendorMode(projectRoot)
131
+ return {
132
+ APP: app.prefix,
133
+ MODULES: vendored ? `${VENDOR_PREFIX}/modules` : 'packages/infra/modules',
134
+ ENGINE: vendored ? `${VENDOR_PREFIX}/src` : 'packages/infra/src',
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Write the files a new install starts from, each only when absent. Returns the
140
+ * project-relative paths written and the ones left as they were.
141
+ *
142
+ * A file's body may hold `{{ENV}}`, and `{{APP}}`, `{{MODULES}}` and
143
+ * `{{ENGINE}}`, which become the path from THAT file's folder to the app's
144
+ * folder, the project's zbc modules and its engine, so a starter's imports are
145
+ * right wherever the manifest puts it.
146
+ */
147
+ export async function layStarter(
148
+ projectRoot: string,
149
+ app: VendoredApp,
150
+ manifest: AppManifest,
151
+ env: string,
152
+ ): Promise<{ written: string[]; kept: string[] }> {
153
+ const roots = await starterRoots(projectRoot, app)
154
+ const inPath = (text: string) => text.replaceAll('{{ENV}}', env)
155
+ const written: string[] = []
156
+ const kept: string[] = []
157
+ for (const entry of manifest.starter ?? []) {
158
+ const appRoot = path.join(projectRoot, app.prefix)
159
+ const from = path.resolve(appRoot, inPath(entry.from))
160
+ // And it is copied from the app's own folder, never from somewhere else in the project.
161
+ if (path.relative(appRoot, from).startsWith('..')) {
162
+ throw new Error(
163
+ `${app.name}'s manifest names a starter file outside its own folder: ${entry.from}`,
164
+ )
165
+ }
166
+ const to = inPath(entry.to)
167
+ // A starter path is the app's to name, and it names a place in the project:
168
+ // one that climbs out of the project root is refused before anything is written.
169
+ const dest = path.resolve(projectRoot, to)
170
+ if (path.isAbsolute(to) || path.relative(projectRoot, dest).startsWith('..')) {
171
+ throw new Error(`${app.name}'s manifest names a starter file outside the project: ${to}`)
172
+ }
173
+ const fromHere = (target: string) => {
174
+ const relative = path.posix.relative(path.posix.dirname(to), target)
175
+ return relative.startsWith('.') ? relative : `./${relative}`
176
+ }
177
+ const vars = {
178
+ ENV: env,
179
+ APP: fromHere(roots.APP),
180
+ MODULES: fromHere(roots.MODULES),
181
+ ENGINE: fromHere(roots.ENGINE),
182
+ }
183
+ const wrote = await copyTemplateFile(from, dest, { vars, skipIfExists: true })
184
+ ;(wrote ? written : kept).push(to)
185
+ }
186
+ return { written, kept }
187
+ }
188
+
189
+ export interface AppAudit {
190
+ /** Files the project tracks under the prefix that the pulled commit does not ship. */
191
+ own: string[]
192
+ /** Files that differ from the pulled commit: the project's edits. */
193
+ edited: string[]
194
+ /** Files the pulled commit ships that the project no longer has. */
195
+ removed: string[]
196
+ }
197
+
198
+ /**
199
+ * Compare what the project tracks under the app's prefix with the commit it
200
+ * pulled, blob for blob. Offline and exact: a pull has just fetched that commit,
201
+ * so git holds its tree. Null when git does not hold it (a fresh clone of the
202
+ * project, where the squashed history keeps only the commit's id).
203
+ */
204
+ export function auditVendoredApp(
205
+ projectRoot: string,
206
+ app: VendoredApp,
207
+ commit: string,
208
+ ): AppAudit | null {
209
+ let upstreamListing: string
210
+ try {
211
+ upstreamListing = git(projectRoot, ['ls-tree', '-r', '-z', commit])
212
+ } catch {
213
+ return null
214
+ }
215
+ const blobs = (listing: string, strip: string) => {
216
+ const map = new Map<string, string>()
217
+ for (const entry of listing.split('\0')) {
218
+ // `<mode> blob <sha>\t<path>` from ls-tree, `<mode> <sha> <stage>\t<path>` from ls-files.
219
+ const match = /^\d+ (?:blob )?([0-9a-f]+)(?: \d)?\t(.+)$/.exec(entry)
220
+ if (!match) continue
221
+ map.set(path.posix.relative(strip, match[2]!), match[1]!)
222
+ }
223
+ return map
224
+ }
225
+ const upstream = blobs(upstreamListing, '')
226
+ // Asked from the project root, where git takes and prints paths relative to
227
+ // that folder: `vendor/space` holds whether the project is the repository or
228
+ // a subfolder of one.
229
+ const local = blobs(git(projectRoot, ['ls-files', '-s', '-z', '--', app.prefix]), app.prefix)
230
+ const own = [...local.keys()].filter((file) => !upstream.has(file)).toSorted()
231
+ const edited = [...local.keys()]
232
+ .filter((file) => upstream.has(file) && upstream.get(file) !== local.get(file))
233
+ .toSorted()
234
+ const removed = [...upstream.keys()].filter((file) => !local.has(file)).toSorted()
235
+ return { own, edited, removed }
236
+ }
237
+
238
+ /** The audit as lines to print: information for whoever pulled, never a failure. */
239
+ export function describeAppAudit(app: VendoredApp, audit: AppAudit | null): string[] {
240
+ if (audit === null) {
241
+ return [
242
+ ` (the pulled commit is not in this clone, so ${app.prefix}/ was not compared with it)`,
243
+ ]
244
+ }
245
+ const lines: string[] = []
246
+ const list = (title: string, files: string[]) => {
247
+ if (files.length === 0) return
248
+ lines.push(` ${files.length} ${title}`)
249
+ for (const file of files.slice(0, 40)) lines.push(` ${app.prefix}/${file}`)
250
+ if (files.length > 40) lines.push(` ... and ${files.length - 40} more`)
251
+ }
252
+ list(
253
+ `file(s) under ${app.prefix}/ are this project's own (the copy does not ship them):`,
254
+ audit.own,
255
+ )
256
+ list("file(s) differ from the pulled copy (this project's edits, kept):", audit.edited)
257
+ list('file(s) the copy ships are not in this project:', audit.removed)
258
+ if (lines.length === 0) lines.push(` ${app.prefix}/ is the pulled copy, file for file.`)
259
+ return lines
260
+ }
261
+
262
+ export interface VendorResult {
263
+ ref: string
264
+ commit: string
265
+ workspacesAdded: string[]
266
+ starter: { written: string[]; kept: string[] }
267
+ manifest: AppManifest
268
+ }
269
+
270
+ /**
271
+ * `zbc add <app>`: the squashed subtree add at the newest tag (or the ref
272
+ * named), then what makes the folder usable: its workspace folders in the root
273
+ * manifest, the starting files of one environment, and the stamp. The subtree
274
+ * add is a commit; everything after it is left in the working tree for the
275
+ * operator to read and commit.
276
+ */
277
+ export async function addVendoredApp(
278
+ projectRoot: string,
279
+ app: VendoredApp,
280
+ opts: { ref?: string; url?: string; env: string },
281
+ ): Promise<VendorResult> {
282
+ if (await exists(path.join(projectRoot, app.prefix))) {
283
+ throw new Error(
284
+ `${app.prefix}/ is already there. \`zbc update ${app.name}\` pulls a newer copy over it.`,
285
+ )
286
+ }
287
+ ensureCleanGitTree(projectRoot)
288
+ await assertStampReadable(projectRoot)
289
+ const url = opts.url ?? app.url
290
+ const ref = opts.ref ?? newestTag(url, projectRoot)
291
+ subtreeAdd(projectRoot, { url, ref, prefix: app.prefix })
292
+ // The pull is a commit by now. What follows only writes files, so a failure in it leaves the app in place and
293
+ // says so: a second `add` would refuse the folder, and an `update` never writes the starting files.
294
+ try {
295
+ return await finishPull(projectRoot, app, { url, ref, env: opts.env })
296
+ } catch (err) {
297
+ throw new Error(
298
+ `${app.prefix}/ was pulled and committed (${ref}), but what follows the pull failed: ${(err as Error).message}\n` +
299
+ ` To start over: git reset --hard HEAD~1 (the pull is the last commit), delete what git status then lists as new, and run \`zbc add ${app.name}\` again.`,
300
+ { cause: err },
301
+ )
302
+ }
303
+ }
304
+
305
+ /**
306
+ * `zbc update <app>`: the squashed pull of the newest tag, or of the ref named
307
+ * (a branch for the newest commit). A conflict with the project's own edits is
308
+ * git's, left for the operator: it is the same merge any pull is.
309
+ */
310
+ export async function updateVendoredApp(
311
+ projectRoot: string,
312
+ app: VendoredApp,
313
+ opts: { ref?: string; url?: string },
314
+ ): Promise<VendorResult & { audit: AppAudit | null }> {
315
+ if (!(await exists(path.join(projectRoot, app.prefix)))) {
316
+ throw new Error(`${app.prefix}/ is not there. \`zbc add ${app.name}\` pulls it first.`)
317
+ }
318
+ ensureCleanGitTree(projectRoot)
319
+ await assertStampReadable(projectRoot)
320
+ // A fork pulls from where it was added from, unless told otherwise.
321
+ const stamped = (await readAppStamps(projectRoot))[app.name]
322
+ const url = opts.url ?? (stamped?.url || app.url)
323
+ const ref = opts.ref ?? newestTag(url, projectRoot)
324
+ subtreePull(projectRoot, { url, ref, prefix: app.prefix })
325
+ const result = await finishPull(projectRoot, app, { url, ref })
326
+ return { ...result, audit: auditVendoredApp(projectRoot, app, result.commit) }
327
+ }
328
+
329
+ async function finishPull(
330
+ projectRoot: string,
331
+ app: VendoredApp,
332
+ opts: { url: string; ref: string; env?: string },
333
+ ): Promise<VendorResult> {
334
+ const commit = subtreeSplitCommit(projectRoot, app.prefix)
335
+ if (commit === null) {
336
+ throw new Error(`git recorded no pulled commit for ${app.prefix}/: the subtree did not land.`)
337
+ }
338
+ const manifest = await readAppManifest(projectRoot, app)
339
+ const workspacesAdded = await addWorkspaces(projectRoot, app, manifest.workspaces ?? [])
340
+ // Starting files are an `add`'s: an update never writes into an environment.
341
+ const starter =
342
+ opts.env === undefined
343
+ ? { written: [], kept: [] }
344
+ : await layStarter(projectRoot, app, manifest, opts.env)
345
+ await writeAppStamp(projectRoot, app.name, { url: opts.url, ref: opts.ref, commit })
346
+ return { ref: opts.ref, commit, workspacesAdded, starter, manifest }
347
+ }
348
+
349
+ async function exists(target: string): Promise<boolean> {
350
+ try {
351
+ await fs.stat(target)
352
+ return true
353
+ } catch {
354
+ return false
355
+ }
356
+ }
@@ -20,7 +20,7 @@ writing a module. `.claude/settings.json` enables it. To install it by hand, run
20
20
  ## Common commands
21
21
 
22
22
  - `bun install` — install dependencies
23
- - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; `secret-relay` — the browser-based secret request relay; `warehouse` — a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies)
23
+ - `bunx @zabaca/zbc add <module>`, vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`secret-relay`: the browser-based secret request relay; `warehouse`: a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies), or pull the vendored app `space` (a company's mail, chat and calls, calendar, forms and signed documents, clients and knowledge in one Worker) into `vendor/space/` as a git subtree, which `bunx @zabaca/zbc update space` later updates
24
24
  - `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
25
25
  - `bunx @zabaca/zbc apply <env> --json <path>` — the same, plus the result (`{ env, instances: [{ name, module, outputs }] }`) written to a file. Treat that file as secret: outputs carry credentials
26
26
  - `bunx @zabaca/zbc list <env>` — what the environment declares, in dependency order (add `--json` for a machine-readable listing)
@@ -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**: