@zabaca/zbc 0.12.0 → 0.14.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 (111) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/package.json +6 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/init.ts +1 -0
  5. package/src/engine/apply.ts +60 -21
  6. package/src/engine/destroy.ts +183 -14
  7. package/src/engine/discover.ts +1 -1
  8. package/src/engine/resolve.ts +56 -11
  9. package/src/utils/copy-template.ts +10 -0
  10. package/templates/apps/inbox/package.json +4 -2
  11. package/templates/apps/inbox/tsconfig.json +3 -1
  12. package/templates/apps/inbox/worker/api.ts +197 -0
  13. package/templates/apps/inbox/worker/commands.ts +299 -0
  14. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  15. package/templates/apps/inbox/worker/index.ts +15 -202
  16. package/templates/apps/inbox/worker/mcp.ts +49 -100
  17. package/templates/apps/walgit/CONTEXT.md +135 -0
  18. package/templates/apps/walgit/Dockerfile +40 -18
  19. package/templates/apps/walgit/README.md +518 -55
  20. package/templates/apps/walgit/e2e/README.md +100 -6
  21. package/templates/apps/walgit/e2e/harness.ts +262 -1
  22. package/templates/apps/walgit/e2e/live.ts +588 -0
  23. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  24. package/templates/apps/walgit/e2e/suite.ts +5 -5
  25. package/templates/apps/walgit/examples/watch.ts +209 -0
  26. package/templates/apps/walgit/package.json +12 -3
  27. package/templates/apps/walgit/registry.json +6 -11
  28. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  29. package/templates/apps/walgit/shared/container-env.ts +114 -0
  30. package/templates/apps/walgit/shared/credentials.ts +81 -0
  31. package/templates/apps/walgit/shared/events.ts +277 -0
  32. package/templates/apps/walgit/shared/landing.ts +1241 -0
  33. package/templates/apps/walgit/shared/llms.ts +463 -0
  34. package/templates/apps/walgit/shared/outbox.ts +266 -0
  35. package/templates/apps/walgit/shared/policy.ts +59 -0
  36. package/templates/apps/walgit/shared/protocol.ts +197 -0
  37. package/templates/apps/walgit/shared/provenance.ts +154 -0
  38. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  39. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  40. package/templates/apps/walgit/src/announce-main.ts +37 -0
  41. package/templates/apps/walgit/src/announce.ts +98 -0
  42. package/templates/apps/walgit/src/append-only.ts +112 -0
  43. package/templates/apps/walgit/src/cache.ts +172 -0
  44. package/templates/apps/walgit/src/cli.ts +493 -0
  45. package/templates/apps/walgit/src/compact.ts +25 -23
  46. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  47. package/templates/apps/walgit/src/expire.ts +248 -0
  48. package/templates/apps/walgit/src/gc.ts +8 -16
  49. package/templates/apps/walgit/src/git-backend.ts +29 -0
  50. package/templates/apps/walgit/src/git.ts +78 -0
  51. package/templates/apps/walgit/src/hook-main.ts +259 -17
  52. package/templates/apps/walgit/src/hooks.ts +4 -3
  53. package/templates/apps/walgit/src/http.ts +237 -45
  54. package/templates/apps/walgit/src/instructions.ts +240 -0
  55. package/templates/apps/walgit/src/keys.ts +126 -0
  56. package/templates/apps/walgit/src/limits.ts +158 -0
  57. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  58. package/templates/apps/walgit/src/materialize.ts +48 -40
  59. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  60. package/templates/apps/walgit/src/orphans.ts +2 -5
  61. package/templates/apps/walgit/src/pending.ts +201 -0
  62. package/templates/apps/walgit/src/push-cert.ts +254 -0
  63. package/templates/apps/walgit/src/push.ts +233 -46
  64. package/templates/apps/walgit/src/reconcile.ts +5 -8
  65. package/templates/apps/walgit/src/repo.ts +22 -77
  66. package/templates/apps/walgit/src/server.ts +148 -26
  67. package/templates/apps/walgit/src/signers.ts +577 -0
  68. package/templates/apps/walgit/src/store-env.ts +5 -4
  69. package/templates/apps/walgit/src/store.ts +47 -24
  70. package/templates/apps/walgit/src/usage.ts +404 -0
  71. package/templates/apps/walgit/src/verify.ts +171 -0
  72. package/templates/apps/walgit/src/wal-index.ts +189 -11
  73. package/templates/apps/walgit/tsconfig.json +8 -2
  74. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  75. package/templates/apps/walgit/worker/events-do.ts +259 -0
  76. package/templates/apps/walgit/worker/index.ts +572 -0
  77. package/templates/apps/walgit/wrangler.jsonc +95 -0
  78. package/templates/apps/warehouse/package.json +1 -1
  79. package/templates/infra/modules/cloudflare/index.ts +93 -67
  80. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  81. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  82. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  83. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  84. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  85. package/templates/infra/modules/cloudflare-token/index.ts +10 -30
  86. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  87. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  88. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  89. package/templates/infra/modules/fly/index.ts +158 -35
  90. package/templates/infra/modules/host-file/index.ts +6 -7
  91. package/templates/infra/modules/provision-core/index.ts +21 -15
  92. package/templates/infra/modules/r2/index.ts +38 -55
  93. package/templates/infra/modules/r2/registry.json +1 -1
  94. package/templates/infra/modules/remote-provision/index.ts +1 -3
  95. package/templates/infra/modules/turso/index.ts +45 -7
  96. package/templates/infra/modules/vm-provision/index.ts +10 -3
  97. package/templates/infra/package.json +1 -1
  98. package/templates/infra/src/context.ts +115 -0
  99. package/templates/infra/src/define-module.ts +8 -2
  100. package/templates/infra/src/index.ts +11 -1
  101. package/templates/infra/src/types.ts +72 -3
  102. package/src/commands/add-registry.test.ts +0 -92
  103. package/src/commands/secret.test.ts +0 -717
  104. package/src/commands/vendor-mode.test.ts +0 -183
  105. package/src/infra-types.ts +0 -38
  106. package/src/utils/subtree.test.ts +0 -127
  107. package/templates/apps/inbox/worker/send-op.ts +0 -174
  108. package/templates/apps/walgit/entrypoint.sh +0 -59
  109. package/templates/apps/walgit/fly.toml +0 -52
  110. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  111. package/templates/apps/walgit/sshd_config +0 -38
@@ -5,13 +5,28 @@
5
5
  * auth, routing, and delegation to `git http-backend` — is observable without a
6
6
  * socket or a git process. The backend runner is injected for the same reason.
7
7
  *
8
- * Smart-HTTP exists alongside SSH because not every client can hold a key: CI
9
- * jobs, ephemeral agent sandboxes and `git clone` inside a container all have a
10
- * token long before they have an SSH identity.
8
+ * Smart-HTTP is the only transport walgit serves. It is also the one every
9
+ * client already has: CI jobs, ephemeral agent sandboxes and `git clone` inside
10
+ * a container hold a token long before they hold an identity of any other kind.
11
11
  */
12
12
 
13
+ import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
14
+ import { authorizedBy } from '../shared/credentials'
15
+ import {
16
+ EXPIRE_PATH,
17
+ HEALTH_PATH,
18
+ INTERNAL_HEADER,
19
+ PROVENANCE_PATH,
20
+ REFS_PATH,
21
+ REJECT_HEADER,
22
+ SERVED_HEADER,
23
+ SMART_HTTP,
24
+ type ContainerRejectKind,
25
+ } from '../shared/protocol'
26
+ import { renderInstructions } from './instructions'
13
27
  import type { ResolvedRepo } from './repo'
14
28
  import { resolveRepo } from './repo'
29
+ import type { Claim, Provenance } from './wal-index'
15
30
 
16
31
  export type BackendRequest = {
17
32
  repo: ResolvedRepo
@@ -24,6 +39,18 @@ export type HttpHandlerDeps = {
24
39
  reposDir: string
25
40
  /** Accepted credentials. A request must present one of these. */
26
41
  tokens: string[]
42
+ /**
43
+ * Serve every request with no credential at all — the public instance, where
44
+ * writes are open and there is therefore nothing for a credential to prove.
45
+ *
46
+ * Explicit on purpose: an EMPTY `tokens` list does NOT mean public. A
47
+ * deployment that loses its secret would then be indistinguishable from one
48
+ * that chose to be open, and the failure direction is unrecoverable — once
49
+ * strangers have pushed to an accidentally public instance there is no
50
+ * undoing it. So the two must be configured separately, and the combination
51
+ * of neither is refused outright (see below).
52
+ */
53
+ public?: boolean
27
54
  ensureRepo: (repo: ResolvedRepo) => ResolvedRepo
28
55
  /**
29
56
  * Bring the local cache in line with the log before serving. Optional only so
@@ -32,35 +59,203 @@ export type HttpHandlerDeps = {
32
59
  */
33
60
  syncRepo?: (repo: ResolvedRepo) => Promise<unknown>
34
61
  runBackend: (req: BackendRequest) => Promise<Response>
62
+ /**
63
+ * What `GET /` tells an agent about this instance
64
+ * (`shared/capabilities.ts`), so the page can never promise a rule the
65
+ * deployment does not enforce. Optional so the routing can be tested without
66
+ * one; a handler given none advertises nothing at all, which is the safe
67
+ * direction for a document about what is offered.
68
+ */
69
+ capabilities?: Capabilities
70
+ /**
71
+ * Run one expiry sweep. Optional: an instance that is not given one simply
72
+ * does not answer the endpoint, which is what a deployment with no timer in
73
+ * front of it should do.
74
+ *
75
+ * The sweep lives out here rather than on a timer inside the container
76
+ * because the container sleeps when idle — an internal `setInterval` would
77
+ * stop firing at exactly the moment there is nothing keeping it awake, which
78
+ * is exactly when there are idle repositories to collect. The deployment's
79
+ * Cron Trigger wakes it instead (`worker/index.ts`).
80
+ */
81
+ sweep?: () => Promise<unknown>
82
+ /**
83
+ * The Index's ref state for one repository — what a ref-event subscriber's
84
+ * handshake is answered with (`worker/events-do.ts`).
85
+ *
86
+ * Read from `index.json` rather than from the bare repo on disk, because the
87
+ * Index is the source of truth and the disk is a cache: answering from the
88
+ * cache would tell a subscriber where this node happens to stand, which is
89
+ * exactly the stale answer the whole design exists to avoid. Optional, so an
90
+ * instance with no store — or no event stream — simply does not answer.
91
+ */
92
+ readRefs?: (repoId: string) => Promise<Record<string, string>>
93
+ /**
94
+ * What the Index records about who wrote one repository: the push provenance
95
+ * — ref → the Signer that moved it, and when (docs/adr/0011) — and the Signer
96
+ * List that repository holds, when it holds one (docs/adr/0012). Read from
97
+ * the Index for the same reason `readRefs` is: the Index is where a push
98
+ * records both, and the disk holds no copy of either.
99
+ *
100
+ * One reader for both because they are one object read answering one
101
+ * endpoint. Two readers would double an Index fetch to answer a single
102
+ * request, and would let a caller wire one and forget the other.
103
+ *
104
+ * Optional like every other reader here, and absent means the endpoint does
105
+ * not exist rather than answering an empty map — an instance with no store
106
+ * has no authoritative answer, and inventing "nobody signed anything" out of
107
+ * a missing log is the one wrong answer this feature can give.
108
+ */
109
+ readProvenance?: (repoId: string) => Promise<ProvenanceRead>
110
+ }
111
+
112
+ /** What `GET /_walgit/provenance` answers with, before it is serialized. */
113
+ export type ProvenanceRead = {
114
+ provenance: Record<string, Provenance>
115
+ /** Absent for an unclaimed repository, which is most of them. */
116
+ claim?: Claim
117
+ }
118
+
119
+ /**
120
+ * Refuse, and say which kind of refusal it was.
121
+ *
122
+ * The kind is `ContainerRejectKind` rather than a free string because the
123
+ * Worker in front counts refusals by kind and cannot derive one from a status
124
+ * code several refusals share (`shared/telemetry.ts`). A kind this process
125
+ * invented and the Worker did not know would land in its `other` bucket,
126
+ * silently, which is exactly the drift the shared vocabulary exists to stop.
127
+ */
128
+ function reject(
129
+ status: number,
130
+ kind: ContainerRejectKind,
131
+ body: string,
132
+ headers: Record<string, string> = {},
133
+ ): Response {
134
+ return new Response(body, { status, headers: { ...headers, [REJECT_HEADER]: kind } })
35
135
  }
36
136
 
37
137
  const UNAUTHORIZED = () =>
38
- new Response('unauthorized\n', {
39
- status: 401,
40
- // git prompts for a credential only when challenged in this scheme, so the
41
- // header is what makes `git clone https://…` work interactively at all.
42
- headers: { 'www-authenticate': 'Basic realm="walgit"' },
138
+ // git prompts for a credential only when challenged in this scheme, so the
139
+ // header is what makes `git clone https://…` work interactively at all.
140
+ reject(401, 'unauthorized', 'unauthorized\n', {
141
+ 'www-authenticate': 'Basic realm="walgit"',
43
142
  })
44
143
 
144
+ const NOT_FOUND = () => reject(404, 'not-found', 'not found\n')
145
+
45
146
  /**
46
- * The smart-HTTP protocol is three endpoints and no more. Everything else a
47
- * bare repo exposes over HTTP is DUMB http — raw objects, packs, HEAD — which
48
- * would read the on-disk cache directly and bypass the WAL the cache is derived
49
- * from. Not routed, so not served.
147
+ * What a handler wired without capabilities says it offers: nothing.
148
+ *
149
+ * The empty environment read through the one derivation, rather than an object
150
+ * literal — a hand-written "all off" would be a second place a capability has
151
+ * to be remembered, which is the whole defect `shared/capabilities.ts` exists
152
+ * to remove.
50
153
  */
51
- const SMART_HTTP = /^\/([^/]+)\.git\/(?:info\/refs|git-upload-pack|git-receive-pack)$/
154
+ const ADVERTISES_NOTHING = capabilitiesFrom({})
52
155
 
53
- const NOT_FOUND = () => new Response('not found\n', { status: 404 })
156
+ /**
157
+ * Stamp a response as walgit's own. Rebuilt rather than mutated because a
158
+ * Response's headers are immutable once constructed — the body is passed
159
+ * through by reference, so a streamed clone is not buffered to do this.
160
+ */
161
+ export function stamp(response: Response): Response {
162
+ const stamped = new Response(response.body, response)
163
+ stamped.headers.set(SERVED_HEADER, '1')
164
+ return stamped
165
+ }
54
166
 
55
167
  export function createHttpHandler(deps: HttpHandlerDeps): (req: Request) => Promise<Response> {
168
+ if (!deps.public && deps.tokens.length === 0) {
169
+ // Fail closed. With no tokens every comparison fails, so the instance would
170
+ // serve nothing but 401s while looking, from the client side, exactly like
171
+ // a wrong credential — hours of debugging for a config that is simply
172
+ // absent. Refusing here means the misconfiguration is reported once, at
173
+ // boot, in the words of the thing that is missing.
174
+ throw new Error(
175
+ 'walgit: no tokens configured and public mode is off — refusing to serve (set tokens, or opt in to public mode explicitly)',
176
+ )
177
+ }
178
+
179
+ const route = createRouter(deps)
180
+ return async (request) => stamp(await route(request))
181
+ }
182
+
183
+ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response> {
56
184
  return async (request) => {
57
185
  const url = new URL(request.url)
58
186
 
59
- // Unauthenticated on purpose: Fly's health check has no credential, and it
60
- // reveals nothing but that a machine is up.
61
- if (url.pathname === '/_walgit/health') return new Response('ok\n')
187
+ // Unauthenticated on purpose: an external health check carries no
188
+ // credential, and this reveals nothing but that the container is up.
189
+ if (url.pathname === HEALTH_PATH) return new Response('ok\n')
190
+
191
+ // The sweeper's front door. Not part of the git protocol and not reachable
192
+ // from the internet: the Worker deletes INTERNAL_HEADER from everything it
193
+ // forwards, so a request carrying it can only have been originated by the
194
+ // Worker's scheduled handler. A 404 rather than a 403 for the same reason
195
+ // every other unroutable path gets one — an endpoint nobody may call should
196
+ // not advertise that it exists.
197
+ if (url.pathname === EXPIRE_PATH) {
198
+ if (!deps.sweep || request.method !== 'POST') return NOT_FOUND()
199
+ if (request.headers.get(INTERNAL_HEADER) !== '1') return NOT_FOUND()
200
+ const report = await deps.sweep()
201
+ return new Response(`${JSON.stringify(report)}\n`, {
202
+ headers: { 'content-type': 'application/json; charset=utf-8' },
203
+ })
204
+ }
62
205
 
63
- if (!isAuthorized(request, deps.tokens)) return UNAUTHORIZED()
206
+ // Current ref state, for the event stream's handshake. Internal for the
207
+ // same reason expiry is: it is not part of the git protocol, and the Worker
208
+ // strips INTERNAL_HEADER from everything arriving from the internet, so a
209
+ // request carrying it can only have come from the Worker itself.
210
+ if (url.pathname === REFS_PATH) {
211
+ if (!deps.readRefs || request.method !== 'GET') return NOT_FOUND()
212
+ if (request.headers.get(INTERNAL_HEADER) !== '1') return NOT_FOUND()
213
+ const repoId = requestedRepoId(deps.reposDir, url)
214
+ if (repoId === null) return NOT_FOUND()
215
+ const refs = await deps.readRefs(repoId)
216
+ return new Response(`${JSON.stringify({ repo: repoId, refs })}\n`, {
217
+ headers: { 'content-type': 'application/json; charset=utf-8' },
218
+ })
219
+ }
220
+
221
+ // The instructions are the API surface, so they come BEFORE the credential
222
+ // check: an agent that has to authenticate to learn how to authenticate
223
+ // has nowhere to start. text/plain because the reader is a model with a
224
+ // default fetch, not a browser — no markup to parse to find the endpoint.
225
+ if (url.pathname === '/' && (request.method === 'GET' || request.method === 'HEAD')) {
226
+ return new Response(
227
+ renderInstructions(publicOrigin(request, url), deps.capabilities ?? ADVERTISES_NOTHING),
228
+ { headers: { 'content-type': 'text/plain; charset=utf-8' } },
229
+ )
230
+ }
231
+
232
+ if (!deps.public && !authorizedBy(request.headers.get('authorization'), deps.tokens)) {
233
+ return UNAUTHORIZED()
234
+ }
235
+
236
+ // Push provenance, read back (docs/adr/0011). Placed HERE — below the
237
+ // credential gate and above the git endpoints — because that position is
238
+ // the requirement: the read is behind exactly the credential a clone of
239
+ // this repository needs, so a public instance answers anyone and a
240
+ // token-gated one answers nobody else, with no second authorization model
241
+ // to keep in agreement with the first.
242
+ if (url.pathname === PROVENANCE_PATH) {
243
+ if (!deps.readProvenance || request.method !== 'GET') return NOT_FOUND()
244
+ const repoId = requestedRepoId(deps.reposDir, url)
245
+ if (repoId === null) return NOT_FOUND()
246
+ // A repository nobody has signed a push to reads as an empty map, not a
247
+ // 404 and not an error: signing is opt-in, so "no Signer recorded" is the
248
+ // ordinary answer here and has to be a cheap one to consume.
249
+ //
250
+ // `claim` is OMITTED rather than null for an unclaimed one, so that the
251
+ // absence a client tests for is the same absence the Index carries and
252
+ // there is no second spelling of "nobody has claimed this name".
253
+ const { provenance, claim } = await deps.readProvenance(repoId)
254
+ const body = { repo: repoId, provenance, ...(claim ? { claim } : {}) }
255
+ return new Response(`${JSON.stringify(body)}\n`, {
256
+ headers: { 'content-type': 'application/json; charset=utf-8' },
257
+ })
258
+ }
64
259
 
65
260
  const route = SMART_HTTP.exec(url.pathname)
66
261
  if (!route) return NOT_FOUND()
@@ -80,7 +275,7 @@ export function createHttpHandler(deps: HttpHandlerDeps): (req: Request) => Prom
80
275
  // Serving a repo we could not verify against the log would hand out
81
276
  // refs that may already have been superseded, which for a fetch is
82
277
  // indistinguishable from data loss. Refuse instead.
83
- return new Response(`walgit: ${(err as Error).message}\n`, { status: 503 })
278
+ return reject(503, 'unavailable', `walgit: ${(err as Error).message}\n`)
84
279
  }
85
280
  }
86
281
 
@@ -88,33 +283,30 @@ export function createHttpHandler(deps: HttpHandlerDeps): (req: Request) => Prom
88
283
  }
89
284
  }
90
285
 
91
- function isAuthorized(request: Request, tokens: string[]): boolean {
92
- const header = request.headers.get('authorization') ?? ''
93
- const presented = presentedCredential(header)
94
- if (!presented) return false
95
- return tokens.some((token) => constantTimeEquals(token, presented))
96
- }
97
-
98
- function presentedCredential(header: string): string | null {
99
- const bearer = /^Bearer (.+)$/i.exec(header)
100
- if (bearer) return bearer[1]!
101
- const basic = /^Basic (.+)$/i.exec(header)
102
- if (basic) {
103
- // git sends `<user>:<password>`; the user half is ignored — there is one
104
- // trust boundary in v0, and a per-user model needs the repo namespace that
105
- // milestone 3 introduces.
106
- const decoded = Buffer.from(basic[1]!, 'base64').toString('utf8')
107
- const colon = decoded.indexOf(':')
108
- return colon === -1 ? decoded : decoded.slice(colon + 1)
286
+ /**
287
+ * The repository a `?repo=` reader names, or `null` when it names none walgit
288
+ * would serve.
289
+ *
290
+ * Through `resolveRepo`, which is the same gate a path segment goes through —
291
+ * a name accepted here and refused there would be a repository half the service
292
+ * can see, which is exactly what `REPO_ID` exists to stop.
293
+ */
294
+ function requestedRepoId(reposDir: string, url: URL): string | null {
295
+ try {
296
+ return resolveRepo(reposDir, url.searchParams.get('repo') ?? '').repoId
297
+ } catch {
298
+ return null
109
299
  }
110
- return null
111
300
  }
112
301
 
113
- /** Length-independent comparison, so a wrong token leaks nothing by timing. */
114
- function constantTimeEquals(a: string, b: string): boolean {
115
- let diff = a.length ^ b.length
116
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
117
- diff |= (a.charCodeAt(i % a.length || 0) || 0) ^ (b.charCodeAt(i % b.length || 0) || 0)
118
- }
119
- return diff === 0
302
+ /**
303
+ * The host in the example has to be the host the agent typed. Behind a proxy
304
+ * (the deployment is fronted by a Worker) the request URL carries the internal
305
+ * address, so the forwarded headers win when present.
306
+ */
307
+ function publicOrigin(request: Request, url: URL): string {
308
+ const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host')
309
+ if (!host) return url.origin
310
+ const proto = request.headers.get('x-forwarded-proto') ?? url.protocol.replace(':', '')
311
+ return `${proto}://${host}`
120
312
  }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * `GET /` is the whole API surface.
3
+ *
4
+ * There is no create endpoint and no client library — the API is git — so this
5
+ * text is the only thing standing between an agent and a working repository.
6
+ * It is written for a model: plain text, short declarative sentences, one
7
+ * worked example, no markup to parse and no link needed to understand it.
8
+ *
9
+ * The limits are the content, not the fine print. An agent that learns about
10
+ * the retention window after pushing has been misled, so every limit the
11
+ * instance enforces is stated before the example — and a limit the instance
12
+ * does NOT enforce is never claimed, which is why the text is rendered from
13
+ * `Capabilities` (`shared/capabilities.ts`) — the one derivation the push path
14
+ * and the two edge documents also read — rather than written once as a
15
+ * constant.
16
+ */
17
+
18
+ import type { Capabilities } from '../shared/capabilities'
19
+ import { describeBytes } from '../shared/policy'
20
+ import { EVENTS_PATH, PROVENANCE_PATH } from '../shared/protocol'
21
+
22
+ /**
23
+ * Rendered per request rather than baked at boot, because the host an agent
24
+ * must type is the host it reached us on: a deployment behind a proxy, a
25
+ * preview URL and a local test each need the example to work verbatim.
26
+ *
27
+ * A full ORIGIN, scheme included, unlike the two edge documents which take a
28
+ * bare hostname and supply `https://` themselves — a local test reaches this
29
+ * over plain http and the example has to work verbatim there too. That is why
30
+ * neither spelling of the host is a field on `Capabilities`.
31
+ *
32
+ * What this page does with each capability is the shortest reading of it in the
33
+ * package. It has a byte budget, and ADR-0012 put ownership's discovery in
34
+ * `/llms.txt` and in the refusal itself — so `namesCanRefuse` buys two
35
+ * corrections here and nothing else, and `namesCanBeClaimed` is not read at
36
+ * all: this document never teaches anyone to hold a name.
37
+ */
38
+ export function renderInstructions(origin: string, caps: Capabilities): string {
39
+ const lines: string[] = [
40
+ 'walgit — a git host for agents.',
41
+ '',
42
+ ...wrap(
43
+ 'Push to a name and the repository exists. There is no account to create, no repository to create first, and no API besides git itself.',
44
+ ),
45
+ '',
46
+ 'BEFORE YOU PUSH',
47
+ '',
48
+ ]
49
+
50
+ for (const fact of facts(caps)) lines.push(...wrap(`- ${fact}`), '')
51
+
52
+ lines.push(
53
+ 'PUSH A REPOSITORY YOU ALREADY HAVE',
54
+ '',
55
+ ' NAME=my-project-$(openssl rand -hex 4)',
56
+ ` git remote add walgit ${origin}/$NAME.git`,
57
+ ' git push walgit HEAD:refs/heads/main',
58
+ '',
59
+ 'START FROM NOTHING',
60
+ '',
61
+ ' NAME=scratch-$(openssl rand -hex 4)',
62
+ ' git init . && git add -A',
63
+ ' git -c user.email=agent@localhost -c user.name=agent commit -m first',
64
+ ` git push ${origin}/$NAME.git HEAD:refs/heads/main`,
65
+ '',
66
+ "READ SOMEBODY ELSE'S WORK",
67
+ '',
68
+ ` git clone ${origin}/$NAME.git`,
69
+ '',
70
+ ...(caps.signedPushes ? signingSection(origin, caps.namesCanRefuse) : []),
71
+ ...(caps.events ? watchSection(origin) : []),
72
+ ...(caps.events
73
+ ? []
74
+ : [...wrap(`The full manual, with worked examples, is at ${origin}/llms.txt.`), '']),
75
+ 'IF A PUSH IS REFUSED',
76
+ '',
77
+ ...wrap(
78
+ 'Read the message. A refusal names what it refused and what to do instead; it is not a transport failure, and retrying the same push will not change it. The usual cause is that the name is already held by an unrelated history — push to a new name.',
79
+ ),
80
+ '',
81
+ )
82
+
83
+ return `${lines.join('\n')}\n`
84
+ }
85
+
86
+ function facts(caps: Capabilities): string[] {
87
+ const facts: string[] = [
88
+ caps.publicAccess
89
+ ? publicAccessFact(caps.namesCanRefuse)
90
+ : 'This instance requires a credential. Send it as the password of an HTTP basic credential or as a bearer token; the username is ignored.',
91
+ 'A repository is created by the first push to its name. Names are a single segment, claimed first-come, and never reassigned.',
92
+ ]
93
+
94
+ if (caps.appendOnly) {
95
+ /**
96
+ * The last sentence is gated too, and for the same reason the access bullet
97
+ * above it is: *"That holds for everyone, so a stranger can build on your
98
+ * work"* is the same promise of unconditional writability in different
99
+ * words, and a document that corrects one sentence and leaves the next one
100
+ * contradicting it has not been corrected. What append-only guarantees is
101
+ * unchanged — it is who gets to push at all that the gate narrows — so the
102
+ * gated version says *whoever the name takes a push from* and hands the
103
+ * question back to the bullet that answers it.
104
+ */
105
+ facts.push(
106
+ `Refs are append-only. A push that would rewrite history or delete a ref is refused. You can always add a commit or a branch; nothing can ever be removed. ${
107
+ caps.namesCanRefuse
108
+ ? 'Whoever the name takes a push from can build on your work but cannot destroy it.'
109
+ : 'That holds for everyone, so a stranger can build on your work but cannot destroy it.'
110
+ }`,
111
+ )
112
+ }
113
+ if (caps.retentionHours !== null) {
114
+ facts.push(
115
+ `A repository is deleted ${describeHours(caps.retentionHours)} after its LAST PUSH. Cloning does not extend it; pushing does. This is scratch space — copy the work elsewhere if it must outlive that window.`,
116
+ )
117
+ }
118
+ if (caps.maxPushBytes !== null) {
119
+ facts.push(`A single push may not exceed ${describeBytes(caps.maxPushBytes)}.`)
120
+ }
121
+ if (caps.maxRepoBytes !== null) {
122
+ facts.push(`One repository may not exceed ${describeBytes(caps.maxRepoBytes)} in total.`)
123
+ }
124
+
125
+ facts.push(
126
+ 'Put a random suffix on the name. Many agents run near-identical prompts at the same time; a plain name is probably taken already, and a taken name means your push is refused.',
127
+ )
128
+ return facts
129
+ }
130
+
131
+ /**
132
+ * What a push costs, on a host that asks for nothing.
133
+ *
134
+ * The gated sentence is the SHORTER of the two, which is the whole difficulty:
135
+ * this page had three bytes of headroom under the 3,000-byte budget asserted in
136
+ * `instructions.test.ts`, and the correction had to be bought rather than
137
+ * added. What it cost is the opening summary — *"Everything here is public."* —
138
+ * which said in five words what *"world-readable"* says three words later, and
139
+ * the word *"by"* in *"by anyone"*. What it deliberately did NOT cost is *"or
140
+ * anything you would not publish"*: that clause is the one that catches the
141
+ * case an agent has not thought of, and a warning about secrets is not the
142
+ * place to find savings. The page still grows on net — the signing clause is
143
+ * longer with the gate on than without it — and the measured figures live in
144
+ * the budget test rather than here, so there is one place to keep current.
145
+ *
146
+ * It names the Signer List and stops. Not the ref, not `ssh-keygen`, not how to
147
+ * write one — ADR-0012 put that in `/llms.txt` and in the refusal, and this
148
+ * page's job is only to stop claiming the opposite.
149
+ */
150
+ function publicAccessFact(namesCanRefuse: boolean): string {
151
+ return namesCanRefuse
152
+ ? 'Every repository is world-readable. Anyone may push, with no credential, unless a name holds a Signer List. Do not push a secret, a token, or anything you would not publish.'
153
+ : 'Everything here is public. Every repository is world-readable and world-writable, by anyone, with no credential. Do not push a secret, a token, or anything you would not publish.'
154
+ }
155
+
156
+ /**
157
+ * Signing, in the fewest lines that leave an agent able to do it.
158
+ *
159
+ * This document is read mid-task, so the section is the flag, the config it
160
+ * needs and where the answer comes back — the argument for any of it is in
161
+ * `/llms.txt`. `--signed=if-asked` rather than `=yes` deliberately: it signs
162
+ * against a host that takes certificates and pushes normally against one that
163
+ * does not, so an agent can put one form in its habits and never branch on
164
+ * which host it is talking to.
165
+ */
166
+ function signingSection(origin: string, namesCanRefuse: boolean): string[] {
167
+ return [
168
+ 'SIGN A PUSH, AND BE CREDITED FOR IT',
169
+ '',
170
+ ...wrap(
171
+ 'Push with --signed=if-asked and the fingerprint of your key is recorded as who moved each ref. Any SSH key works, including the one you already push to GitHub with. ' +
172
+ (namesCanRefuse
173
+ ? 'Unsigned is fine unless a name holds a Signer List.'
174
+ : 'Nothing is refused for being unsigned.'),
175
+ ),
176
+ '',
177
+ ' git -c gpg.format=ssh -c user.signingkey=~/.ssh/id_ed25519.pub \\',
178
+ ' push --signed=if-asked walgit HEAD:refs/heads/main',
179
+ ` curl ${origin}${PROVENANCE_PATH}?repo=$NAME`,
180
+ '',
181
+ ]
182
+ }
183
+
184
+ /**
185
+ * The stream, described where an agent will actually read about it.
186
+ *
187
+ * Written as the answer to "is my main still current?", because that is the
188
+ * question the polling it replaces was asking. The wire vocabulary is the one
189
+ * `shared/events.ts` implements — a `watch` message, a handshake carrying the
190
+ * current sha of everything watched, then one message per ref that moves — so
191
+ * the text and the protocol cannot describe two different things.
192
+ *
193
+ * No cursor is mentioned anywhere, deliberately: events are latest state, and
194
+ * an agent told to resume from a position would build a client the server has
195
+ * no way to serve.
196
+ */
197
+ function watchSection(origin: string): string[] {
198
+ return [
199
+ 'WATCH FOR PUSHES INSTEAD OF FETCHING ON A TIMER',
200
+ '',
201
+ ' bunx @zabaca/agentgit watch',
202
+ '',
203
+ ...wrap(
204
+ 'Run it inside a clone: it reads the host, repository and ref from the remote, fetches on every push, and says when what arrived collides with your uncommitted work. --once blocks until the next push; npx works too.',
205
+ ),
206
+ '',
207
+ ...wrap(
208
+ `It holds one socket, ${websocket(origin)}${EVENTS_PATH}, opened outbound so a sandbox needs no address. The wire format, the four lines that speak it directly, and the collision check are at ${origin}/llms.txt.`,
209
+ ),
210
+ '',
211
+ ]
212
+ }
213
+
214
+ /** The same origin the example pushes to, as the scheme a socket dials. */
215
+ function websocket(origin: string): string {
216
+ return origin.replace(/^http/, 'ws')
217
+ }
218
+
219
+ function describeHours(hours: number): string {
220
+ if (hours >= 48 && hours % 24 === 0) return `${hours / 24} days`
221
+ return `${hours} hour${hours === 1 ? '' : 's'}`
222
+ }
223
+
224
+ /** Hard-wrapped, so the text reads the same in a terminal as in a context window. */
225
+ function wrap(text: string, width = 78): string[] {
226
+ const indent = text.startsWith('- ') ? ' ' : ''
227
+ const out: string[] = []
228
+ let line = ''
229
+ for (const word of text.split(' ')) {
230
+ const candidate = line ? `${line} ${word}` : word
231
+ if (candidate.length > width && line) {
232
+ out.push(line)
233
+ line = indent + word
234
+ } else {
235
+ line = candidate
236
+ }
237
+ }
238
+ if (line) out.push(line)
239
+ return out
240
+ }