@zabaca/zbc 0.22.0 → 0.23.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 (44) hide show
  1. package/package.json +1 -1
  2. package/templates/CLAUDE.md +5 -0
  3. package/templates/apps/walgit/CONTEXT.md +5 -1
  4. package/templates/apps/walgit/README.md +164 -27
  5. package/templates/apps/walgit/package.json +2 -2
  6. package/templates/apps/walgit/registry.json +1 -1
  7. package/templates/apps/walgit/shared/browse.ts +18 -4
  8. package/templates/apps/walgit/shared/capabilities.ts +28 -3
  9. package/templates/apps/walgit/shared/container-env.ts +41 -2
  10. package/templates/apps/walgit/shared/container-lifecycle.ts +239 -0
  11. package/templates/apps/walgit/shared/container-snapshot.ts +219 -0
  12. package/templates/apps/walgit/shared/edge-refs.ts +612 -0
  13. package/templates/apps/walgit/{src → shared}/instructions.ts +8 -4
  14. package/templates/apps/walgit/shared/keys.ts +17 -0
  15. package/templates/apps/walgit/shared/landing.ts +10 -3
  16. package/templates/apps/walgit/shared/llms.ts +24 -7
  17. package/templates/apps/walgit/shared/policy.ts +1 -1
  18. package/templates/apps/walgit/shared/protocol.ts +35 -0
  19. package/templates/apps/walgit/shared/sleep-after.ts +44 -0
  20. package/templates/apps/walgit/shared/wal-index.ts +22 -1
  21. package/templates/apps/walgit/src/boot-residue.ts +58 -0
  22. package/templates/apps/walgit/src/cache.ts +9 -0
  23. package/templates/apps/walgit/src/cli.ts +39 -4
  24. package/templates/apps/walgit/src/delete-repo.ts +58 -9
  25. package/templates/apps/walgit/src/edge-refs.ts +148 -0
  26. package/templates/apps/walgit/src/expire.ts +75 -7
  27. package/templates/apps/walgit/src/hook-main.ts +2 -0
  28. package/templates/apps/walgit/src/http.ts +17 -4
  29. package/templates/apps/walgit/src/materialize.ts +34 -15
  30. package/templates/apps/walgit/src/private.ts +6 -2
  31. package/templates/apps/walgit/src/push.ts +34 -8
  32. package/templates/apps/walgit/src/reconcile.ts +6 -1
  33. package/templates/apps/walgit/src/server.ts +69 -8
  34. package/templates/apps/walgit/src/sync.ts +10 -2
  35. package/templates/apps/walgit/worker/container-binding.ts +104 -0
  36. package/templates/apps/walgit/worker/durable-container.ts +786 -0
  37. package/templates/apps/walgit/worker/events-do.ts +16 -12
  38. package/templates/apps/walgit/worker/index.ts +235 -17
  39. package/templates/apps/walgit/worker/mcp.ts +9 -4
  40. package/templates/apps/walgit/wrangler.jsonc +44 -33
  41. package/templates/claude/settings.json +8 -0
  42. package/templates/infra/modules/cloudflare/index.ts +9 -0
  43. package/templates/infra/modules/d1/index.ts +30 -4
  44. package/templates/infra/modules/d1/registry.json +1 -1
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The container's half of answering ref checks at the edge: saying, once per
3
+ * boot, what its own git advertises (`shared/edge-refs.ts`).
4
+ *
5
+ * The edge answers a protocol-v2 `info/refs` and an `ls-refs` without waking
6
+ * this process, and both answers carry bytes only git can author — the
7
+ * capability advertisement, and the headers `git http-backend` puts on each.
8
+ * Typing them out at the edge would be a promise about a git binary the edge
9
+ * cannot see: the image's git is Alpine's, it moves when the image is rebuilt,
10
+ * and an advertisement that outlived it would offer a client something the
11
+ * container then refuses. So the container asks its own git, through the same
12
+ * `runGitHttpBackend` every real request goes through, against a probe
13
+ * repository provisioned by the same `ensureBareRepo` every Cache is — and
14
+ * publishes the answers under the fingerprint of the environment it booted
15
+ * with. The edge reads only the fingerprint IT would boot a container with, so
16
+ * it serves this git's words exactly while this is the container behind it.
17
+ */
18
+
19
+ import { spawnSync } from 'node:child_process'
20
+ import * as fs from 'node:fs'
21
+ import * as os from 'node:os'
22
+ import * as path from 'node:path'
23
+
24
+ import {
25
+ REQUEST_TYPE,
26
+ serializeUploadPackRecord,
27
+ uploadPackKeyFor,
28
+ type CapturedResponse,
29
+ type UploadPackRecord,
30
+ } from '../shared/edge-refs'
31
+ import { UPLOAD_PACK_PREFIX } from '../shared/keys'
32
+ import type { ObjectStore } from '../shared/store'
33
+ import { ensureBareRepo } from './cache'
34
+ import { runGitHttpBackend } from './git-backend'
35
+ import type { BackendRequest } from './http'
36
+
37
+ /** The probe's name. Never a repository: it lives in a temporary directory, not under the repos dir. */
38
+ const PROBE = 'walgit-probe'
39
+
40
+ /**
41
+ * Ask this image's git what it advertises, the way a client would.
42
+ *
43
+ * Two requests through `runGitHttpBackend` — the v2 `info/refs`, and an
44
+ * `ls-refs` against the probe, which holds no refs and so answers a bare flush
45
+ * whose status and headers are the ones every `ls-refs` gets. The probe is
46
+ * created in `probeParent` and removed afterwards; it is never a repository
47
+ * anyone can name.
48
+ */
49
+ export async function captureUploadPack(
50
+ probeParent: string = os.tmpdir(),
51
+ runBackend: (req: BackendRequest) => Promise<Response> = runGitHttpBackend,
52
+ ): Promise<UploadPackRecord> {
53
+ const root = fs.mkdtempSync(path.join(probeParent, 'walgit-probe-'))
54
+ try {
55
+ const repo = ensureBareRepo({ repoId: PROBE, dir: path.join(root, `${PROBE}.git`) })
56
+ const origin = 'http://walgit.internal'
57
+ const advertisement = await capture(
58
+ runBackend({
59
+ repo,
60
+ pathInfo: `/${PROBE}.git/info/refs`,
61
+ request: new Request(`${origin}/${PROBE}.git/info/refs?service=git-upload-pack`, {
62
+ headers: { 'git-protocol': 'version=2' },
63
+ }),
64
+ }),
65
+ )
66
+ const lsRefs = await capture(
67
+ runBackend({
68
+ repo,
69
+ pathInfo: `/${PROBE}.git/git-upload-pack`,
70
+ request: new Request(`${origin}/${PROBE}.git/git-upload-pack`, {
71
+ method: 'POST',
72
+ headers: { 'git-protocol': 'version=2', 'content-type': REQUEST_TYPE },
73
+ body: '0014command=ls-refs\n00010000',
74
+ }),
75
+ }),
76
+ )
77
+ const version = spawnSync('git', ['--version'], { encoding: 'utf8' })
78
+ return { version: 1, git: version.stdout.trim(), advertisement, lsRefs }
79
+ } finally {
80
+ fs.rmSync(root, { recursive: true, force: true })
81
+ }
82
+ }
83
+
84
+ async function capture(pending: Promise<Response>): Promise<CapturedResponse> {
85
+ const response = await pending
86
+ return {
87
+ status: response.status,
88
+ headers: [...response.headers],
89
+ body: await response.text(),
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Capture and publish this container's record, and collect the ones earlier
95
+ * environments left behind. Returns the key written, or `null` when this
96
+ * environment gives the edge no way to tell images apart (`uploadPackKeyFor`)
97
+ * and nothing is published.
98
+ *
99
+ * The older records are deleted because nothing will read them again: the
100
+ * Worker computes one fingerprint, and it is this container's. A Worker
101
+ * version still mid-rollout that reads a deleted one falls through, which is
102
+ * what it would do anyway. The collection is best effort for the same reason.
103
+ */
104
+ export async function publishUploadPack(
105
+ store: ObjectStore,
106
+ env: Record<string, string | undefined> = process.env,
107
+ probeParent?: string,
108
+ ): Promise<string | null> {
109
+ const key = uploadPackKeyFor(env)
110
+ if (key === null) return null
111
+ const record = await captureUploadPack(probeParent)
112
+ const written = await store.put(key, serializeUploadPackRecord(record))
113
+ if (!written.ok) throw new Error(`walgit: could not publish ${key}`)
114
+ try {
115
+ for (const old of await store.list(UPLOAD_PACK_PREFIX)) {
116
+ if (old !== key) await store.delete(old)
117
+ }
118
+ } catch {
119
+ // An extra object of a few hundred bytes, read by nobody.
120
+ }
121
+ return key
122
+ }
123
+
124
+ /**
125
+ * `publishUploadPack` at boot, retried, and never fatal.
126
+ *
127
+ * Off the request path: the request that woke this container is already being
128
+ * served the ordinary way, and until the record lands every ref check simply
129
+ * keeps coming here, which is exactly what happened before the edge answered
130
+ * any. Retried because a boot is when the store is likeliest to be slow, and a
131
+ * record that never lands costs a whole container lifetime of wake-ups.
132
+ */
133
+ export async function publishUploadPackAtBoot(store: ObjectStore): Promise<void> {
134
+ for (const delayMs of [0, 2_000, 10_000, 60_000]) {
135
+ if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs))
136
+ try {
137
+ const key = await publishUploadPack(store)
138
+ console.log(
139
+ key === null
140
+ ? 'walgit edge-refs: no WALGIT_BUILD_ID, so the edge answers no ref checks'
141
+ : `walgit edge-refs: published ${key}`,
142
+ )
143
+ return
144
+ } catch (err) {
145
+ console.error(`walgit edge-refs: publish failed: ${(err as Error).message}`)
146
+ }
147
+ }
148
+ }
@@ -26,6 +26,7 @@
26
26
  */
27
27
 
28
28
  import { deleteRepo, type DeleteResult } from './delete-repo'
29
+ import { capabilitiesFrom } from '../shared/capabilities'
29
30
  import type { ObjectStore } from '../shared/store'
30
31
  import { listRepoIds } from '../shared/keys'
31
32
  import { loadIndex, type WalIndex } from '../shared/wal-index'
@@ -41,6 +42,19 @@ export function configuredExpiryMs(env = process.env): number | null {
41
42
  return hours * 60 * 60 * 1000
42
43
  }
43
44
 
45
+ /**
46
+ * A claimed repository's window, or `null` when a claim buys no extra time.
47
+ *
48
+ * Read through `capabilitiesFrom` rather than straight off the variable, because
49
+ * the rules for when it applies — names can be claimed, expiry is on, and it is
50
+ * longer than the base window — are the ones `GET /` states it under, and a
51
+ * second reading here is how the page and the sweeper would come to disagree.
52
+ */
53
+ export function configuredClaimedExpiryMs(env = process.env): number | null {
54
+ const hours = capabilitiesFrom(env).claimedRetentionHours
55
+ return hours === null ? null : hours * 60 * 60 * 1000
56
+ }
57
+
44
58
  export type ExpiryVerdict = 'collect' | 'retain'
45
59
 
46
60
  export interface ExpiryDecision {
@@ -80,6 +94,19 @@ export interface DecideOptions {
80
94
  now: Date
81
95
  /** Null means expiry is not configured, so nothing is ever collected. */
82
96
  windowMs: number | null
97
+ /**
98
+ * The window for a repository with a Signer List (`index.claim`), when a claim
99
+ * earns a longer one. Null or absent: every repository gets `windowMs`.
100
+ */
101
+ claimedWindowMs?: number | null
102
+ /**
103
+ * Finish deletions only: collect what is already tombstoned and past its
104
+ * grace, and tombstone nothing new. The second of the deployment's two daily
105
+ * sweeps runs this way (`wrangler.jsonc`), so that a repository tombstoned by
106
+ * the first is collected a grace period later rather than a day later — and
107
+ * so that nothing it tombstones itself sits waiting a day for the next one.
108
+ */
109
+ collectOnly?: boolean
83
110
  }
84
111
 
85
112
  /**
@@ -88,9 +115,14 @@ export interface DecideOptions {
88
115
  * sweep that would hide them.
89
116
  */
90
117
  export function decideExpiry(index: WalIndex | null, opts: DecideOptions): ExpiryDecision {
91
- const { now, windowMs } = opts
118
+ const { now, collectOnly = false } = opts
119
+ // Which window this repository is judged by. Decided before anything else so
120
+ // that every reason below names the window that was actually applied.
121
+ const claimed = opts.claimedWindowMs != null && index?.claim !== undefined
122
+ const windowMs = claimed ? (opts.claimedWindowMs ?? null) : opts.windowMs
123
+ const which = claimed ? 'claimed ' : ''
92
124
 
93
- if (windowMs === null) {
125
+ if (opts.windowMs === null || windowMs === null) {
94
126
  return { verdict: 'retain', reason: 'expiry is not configured (WALGIT_RETENTION_HOURS unset)' }
95
127
  }
96
128
 
@@ -148,7 +180,16 @@ export function decideExpiry(index: WalIndex | null, opts: DecideOptions): Expir
148
180
  if (idleMs < windowMs) {
149
181
  return {
150
182
  verdict: 'retain',
151
- reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, inside the ${describe(windowMs)} window`,
183
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, inside the ${which}${describe(windowMs)} window`,
184
+ lastPushAt,
185
+ idleMs,
186
+ }
187
+ }
188
+
189
+ if (collectOnly) {
190
+ return {
191
+ verdict: 'retain',
192
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${which}${describe(windowMs)} window — left for the next full sweep to tombstone`,
152
193
  lastPushAt,
153
194
  idleMs,
154
195
  }
@@ -156,7 +197,7 @@ export function decideExpiry(index: WalIndex | null, opts: DecideOptions): Expir
156
197
 
157
198
  return {
158
199
  verdict: 'collect',
159
- reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${describe(windowMs)} window`,
200
+ reason: `last push ${lastPushAt} is ${describe(idleMs)} ago, past the ${which}${describe(windowMs)} window`,
160
201
  lastPushAt,
161
202
  idleMs,
162
203
  }
@@ -172,7 +213,7 @@ function describe(ms: number): string {
172
213
  export interface ExpiryOutcome {
173
214
  repoId: string
174
215
  decision: ExpiryDecision
175
- /** Present only for a collected repository: what `deleteRepo` did. */
216
+ /** What `deleteRepo` did — present when it was asked, so also on a superseded one. */
176
217
  deletion?: DeleteResult
177
218
  }
178
219
 
@@ -182,6 +223,8 @@ export interface ExpireResult {
182
223
  /** Repositories deliberately kept, each carrying the reason it was kept. */
183
224
  retained: ExpiryOutcome[]
184
225
  windowMs: number | null
226
+ claimedWindowMs: number | null
227
+ collectOnly: boolean
185
228
  dryRun: boolean
186
229
  }
187
230
 
@@ -189,6 +232,10 @@ export interface ExpireOptions {
189
232
  now?: () => Date
190
233
  /** Null (the default when unconfigured) sweeps nothing. */
191
234
  windowMs?: number | null
235
+ /** A claimed repository's window — see `DecideOptions.claimedWindowMs`. */
236
+ claimedWindowMs?: number | null
237
+ /** Collect tombstoned repositories only — see `DecideOptions.collectOnly`. */
238
+ collectOnly?: boolean
192
239
  dryRun?: boolean
193
240
  /** Only consider these repositories, instead of every one in the store. */
194
241
  repoIds?: readonly string[]
@@ -213,9 +260,18 @@ export async function expireRepos(
213
260
  ): Promise<ExpireResult> {
214
261
  const now = opts.now ?? (() => new Date())
215
262
  const windowMs = opts.windowMs ?? null
263
+ const claimedWindowMs = opts.claimedWindowMs ?? null
264
+ const collectOnly = opts.collectOnly ?? false
216
265
  const dryRun = opts.dryRun !== false
217
266
 
218
- const result: ExpireResult = { collected: [], retained: [], windowMs, dryRun }
267
+ const result: ExpireResult = {
268
+ collected: [],
269
+ retained: [],
270
+ windowMs,
271
+ claimedWindowMs,
272
+ collectOnly,
273
+ dryRun,
274
+ }
219
275
 
220
276
  // Unconfigured stops before the LIST, not after it: an instance that does not
221
277
  // expire should not be walking its bucket on a timer either.
@@ -228,7 +284,7 @@ export async function expireRepos(
228
284
  for (const repoId of repoIds) {
229
285
  const loaded = await loadIndex(store, repoId)
230
286
  const index = loaded.etag === null ? null : loaded.index
231
- const decision = decideExpiry(index, { now: now(), windowMs })
287
+ const decision = decideExpiry(index, { now: now(), windowMs, claimedWindowMs, collectOnly })
232
288
 
233
289
  if (decision.verdict === 'retain') {
234
290
  result.retained.push({ repoId, decision })
@@ -238,9 +294,21 @@ export async function expireRepos(
238
294
  const deletion = await deleteRepo(store, repoId, {
239
295
  now,
240
296
  dryRun,
297
+ by: 'expiry',
298
+ // Re-judged on the Index the mark would land on, so a push between this
299
+ // read and that write keeps the repository rather than marking it.
300
+ stillDue: (current) =>
301
+ decideExpiry(current, { now: now(), windowMs, claimedWindowMs, collectOnly }).verdict ===
302
+ 'collect',
241
303
  graceMs: opts.graceMs,
242
304
  dir: opts.reposDir ? `${opts.reposDir}/${repoId}.git` : undefined,
243
305
  })
306
+ // A push between the decision and the write: kept, and reported as kept.
307
+ if (deletion.status === 'superseded') {
308
+ const reason = deletion.retained[0]?.reason ?? 'the repository moved under the sweep'
309
+ result.retained.push({ repoId, decision: { verdict: 'retain', reason }, deletion })
310
+ continue
311
+ }
244
312
  result.collected.push({ repoId, decision, deletion })
245
313
  }
246
314
 
@@ -418,6 +418,8 @@ function publishRefusal(result: Extract<PublishResult, { ok: false }>): string {
418
418
  return result.message
419
419
  case 'contended':
420
420
  return 'walgit: the write-ahead log stayed contended — retry the push'
421
+ case 'deleting':
422
+ return 'walgit: this repository is being deleted — push to a new name'
421
423
  }
422
424
  }
423
425
 
@@ -42,7 +42,7 @@ import {
42
42
  type ContainerRejectKind,
43
43
  } from '../shared/protocol'
44
44
  import { emptyReadResponse } from './empty-read'
45
- import { renderInstructions } from './instructions'
45
+ import { renderInstructions } from '../shared/instructions'
46
46
  import { acceptedNonces, readAllowed, readChallengeNonce, renderReadChallenge } from './private'
47
47
  import type { ProposalListing } from './proposals'
48
48
  import { countsNewRepos, createSourceLimiter, rateLimitsEnforced, rateLimitsOf } from './rate-limit'
@@ -67,6 +67,9 @@ export type BackendRequest = {
67
67
  env?: Record<string, string>
68
68
  }
69
69
 
70
+ /** How one expiry sweep runs — see `decideExpiry`'s `collectOnly`. */
71
+ export type SweepOptions = { collectOnly: boolean }
72
+
70
73
  export type HttpHandlerDeps = {
71
74
  reposDir: string
72
75
  /** Accepted credentials. A request must present one of these. */
@@ -110,7 +113,7 @@ export type HttpHandlerDeps = {
110
113
  * is exactly when there are idle repositories to collect. The deployment's
111
114
  * Cron Trigger wakes it instead (`worker/index.ts`).
112
115
  */
113
- sweep?: () => Promise<unknown>
116
+ sweep?: (opts: SweepOptions) => Promise<unknown>
114
117
  /**
115
118
  * The Index's ref state for one repository — what a ref-event subscriber's
116
119
  * handshake is answered with (`worker/events-do.ts`).
@@ -287,6 +290,8 @@ export type BrowseReads = {
287
290
  export type BrowseIndex = {
288
291
  refs: Record<string, string>
289
292
  lastPush: string | null
293
+ /** The repository has a Signer List, so a claimed window may apply. */
294
+ claimed?: boolean
290
295
  }
291
296
 
292
297
  /** Verify a `walgit-read` signature over a message; name the key, or `null`. */
@@ -577,7 +582,13 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
577
582
  .toSorted()
578
583
  .map((name) => ({ name, oid: index.refs[name]! }))
579
584
  const head = defaultBranch(index.refs)
580
- const common = { repo: resolved.repoId, defaultBranch: head, refs, lastPush: index.lastPush }
585
+ const common = {
586
+ repo: resolved.repoId,
587
+ defaultBranch: head,
588
+ refs,
589
+ lastPush: index.lastPush,
590
+ claimed: index.claimed === true,
591
+ }
581
592
 
582
593
  const op = url.searchParams.get('op')
583
594
  if (op === 'refs') return json(common)
@@ -739,7 +750,9 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
739
750
  if (url.pathname === EXPIRE_PATH) {
740
751
  if (!deps.sweep || request.method !== 'POST') return NOT_FOUND()
741
752
  if (request.headers.get(INTERNAL_HEADER) !== '1') return NOT_FOUND()
742
- const report = await deps.sweep()
753
+ // `?collect=only` is the second daily sweep (`worker/index.ts`): finish
754
+ // the deletions the first one started, tombstone nothing new.
755
+ const report = await deps.sweep({ collectOnly: url.searchParams.get('collect') === 'only' })
743
756
  return new Response(`${JSON.stringify(report)}\n`, {
744
757
  headers: { 'content-type': 'application/json; charset=utf-8' },
745
758
  })
@@ -36,6 +36,7 @@
36
36
  import * as fs from 'node:fs'
37
37
  import * as path from 'node:path'
38
38
 
39
+ import { defaultBranch } from '../shared/browse'
39
40
  import { ensureBareRepo } from './cache'
40
41
  import { git } from './git'
41
42
  import { siblingIdx } from '../shared/keys'
@@ -176,7 +177,7 @@ export async function materialize(
176
177
 
177
178
  const refsStart = performance.now()
178
179
  const reconciled = reconcile(repo.dir, index)
179
- ensureHead(repo.dir, index)
180
+ ensureHead(repo.dir, index.refs)
180
181
  const refsMs = performance.now() - refsStart
181
182
 
182
183
  fs.rmSync(markerPath(repo.dir), { force: true })
@@ -255,26 +256,36 @@ function writeAtomic(target: string, body: Uint8Array): void {
255
256
  }
256
257
 
257
258
  /**
258
- * Point HEAD at a branch that exists.
259
+ * Point HEAD at the Index's Default Branch (`defaultBranch`, `shared/browse.ts`).
259
260
  *
260
261
  * A bare repo is initialised with HEAD on `main`; a repo whose log only carries
261
262
  * `master` would then clone successfully into an empty working tree, which
262
263
  * reads as data loss. The log's ref state is the only thing that knows.
264
+ *
265
+ * A function of the Index and nothing else, which is a property and not a
266
+ * simplification. It used to keep whatever HEAD already named while that branch
267
+ * existed, so the answer depended on the disk's history: a name first pushed as
268
+ * `feature` and later given `main` reported `feature` on a container that had
269
+ * watched it happen and `main` on one that had just Materialized it. Now every
270
+ * Cache says what the Index says — and so does the edge, which answers
271
+ * `ls-refs` off the Index without a Cache at all (`shared/edge-refs.ts`) and
272
+ * calls the same function for the same answer. Exported so `sync.ts` can
273
+ * assert it on every access, which is what makes a first push of a branch
274
+ * other than `main` visible as HEAD without waiting for a restart.
275
+ *
276
+ * A repository with no branch is left alone: HEAD is unborn there either way.
263
277
  */
264
- function ensureHead(gitDir: string, index: WalIndex): void {
265
- const branches = Object.keys(index.refs).filter((ref) => ref.startsWith('refs/heads/'))
266
- if (branches.length === 0) return
278
+ export function ensureHead(gitDir: string, refs: Record<string, string>): void {
279
+ const head = defaultBranch(refs)
280
+ if (head === null) return
267
281
 
268
282
  const headFile = path.join(gitDir, 'HEAD')
269
- const current = fs.existsSync(headFile) ? fs.readFileSync(headFile, 'utf8').trim() : ''
270
- const target = /^ref: (.+)$/.exec(current)?.[1]
271
- if (target && branches.includes(target)) return
272
-
273
- const preferred =
274
- branches.find((ref) => ref === 'refs/heads/main') ??
275
- branches.find((ref) => ref === 'refs/heads/master') ??
276
- branches.sort()[0]!
277
- fs.writeFileSync(headFile, `ref: ${preferred}\n`)
283
+ const wanted = `ref: ${head}\n`
284
+ const current = fs.existsSync(headFile) ? fs.readFileSync(headFile, 'utf8') : ''
285
+ if (current === wanted) return
286
+ // Renamed into place, because a `git upload-pack` reading HEAD while it is
287
+ // being written would otherwise see an empty file and report no HEAD at all.
288
+ writeAtomic(headFile, new TextEncoder().encode(wanted))
278
289
  }
279
290
 
280
291
  /**
@@ -293,7 +304,15 @@ function ensureHead(gitDir: string, index: WalIndex): void {
293
304
  * is genuinely absent.
294
305
  */
295
306
  function acquire(gitDir: string): Promise<LockRelease> {
296
- return acquireLock(path.join(gitDir, LOCK), { breakAfter: 1200 })
307
+ return acquireLock(lockPath(gitDir), { breakAfter: 1200 })
308
+ }
309
+
310
+ /**
311
+ * Where that lock lives. Exported for the one other reader: the boot-time
312
+ * sweep (src/boot-residue.ts), which removes a lock no process can hold yet.
313
+ */
314
+ export function lockPath(gitDir: string): string {
315
+ return path.join(gitDir, LOCK)
297
316
  }
298
317
 
299
318
  /**
@@ -169,7 +169,7 @@ export function readAllowed({ enabled, claim, presented }: ReadRequest): boolean
169
169
  * Rendered rather than written as prose in `src/http.ts` for the reason every
170
170
  * other agent-facing document in this package is: the 401 is where discovery
171
171
  * actually lands — the moment it is relevant, on our server — so it names the
172
- * helper, the one config line, and the by-hand exchange for a reader who would
172
+ * helper, the two config lines, and the by-hand exchange for a reader who would
173
173
  * rather see the mechanism than install anything.
174
174
  *
175
175
  * `origin` is the host the agent TYPED (behind the Worker the request URL
@@ -185,7 +185,11 @@ export function renderReadChallenge(origin: string): string {
185
185
  '',
186
186
  'Once per machine, and then git needs nothing typed:',
187
187
  '',
188
- ` git config --global credential.${origin}.helper '!agentgit credential'`,
188
+ ` git config --global --replace-all credential.${origin}.helper ''`,
189
+ ` git config --global --add credential.${origin}.helper '!agentgit credential'`,
190
+ '',
191
+ 'Both lines: the empty helper clears any inherited from the system config',
192
+ '(osxkeychain), which would save the signature and replay it once expired.',
189
193
  '',
190
194
  'By hand, if you would rather see the exchange:',
191
195
  '',
@@ -254,6 +254,8 @@ export type PublishResult =
254
254
  * has to read like one.
255
255
  */
256
256
  | { ok: false; reason: 'not-allowed'; kind: GateRefusal; message: string }
257
+ /** The repository is being deleted right now (`RepoDeletion.collecting_at`). */
258
+ | { ok: false; reason: 'deleting' }
257
259
 
258
260
  export interface PublishOptions {
259
261
  /** How many compare-and-swap attempts before giving up. */
@@ -318,6 +320,23 @@ function claimIsThisPush(index: WalIndex, pending: PendingPush): boolean {
318
320
  )
319
321
  }
320
322
 
323
+ /**
324
+ * A push lifts an expiry mark: expiry marked the repository because nobody had
325
+ * pushed to it, and somebody just did. Left in place, the mark's grace would run
326
+ * out and the collection would delete the push this compare-and-swap is about to
327
+ * acknowledge. An operator's mark (no `by`) stays — that was a decision about
328
+ * the repository, not a reading of its idleness.
329
+ *
330
+ * A ref-only push lifts it too, though it appends no WAL entry and so does not
331
+ * move the date expiry reads: the next full sweep marks the repository again.
332
+ * That is a day's notice rather than a silent loss.
333
+ */
334
+ export function liftExpiry(next: WalIndex): WalIndex {
335
+ if (next.deletion?.by !== 'expiry') return next
336
+ const { deletion: _lifted, ...rest } = next
337
+ return rest
338
+ }
339
+
321
340
  /**
322
341
  * Publish the pending entry with the push's ref changes, under CAS.
323
342
  *
@@ -345,6 +364,11 @@ export async function publishPush(
345
364
  for (let i = 0; i < attempts; i += 1) {
346
365
  const { index, etag } = await loadIndex(store, repoId)
347
366
 
367
+ // Refused, not published: past this field the collection is removing the
368
+ // repository and will not look at the Index again, so anything published
369
+ // now would be acknowledged and then deleted.
370
+ if (index.deletion?.collecting_at) return { ok: false, reason: 'deleting' }
371
+
348
372
  for (const change of changes) {
349
373
  const actual = index.refs[change.ref] ?? ZERO_OID
350
374
  if (actual !== change.oldOid) {
@@ -417,14 +441,16 @@ export async function publishPush(
417
441
  provenance: pending.provenance ?? null,
418
442
  claim: pending.claim ?? null,
419
443
  }
420
- const next = pending.entry
421
- ? nextIndex(index, pending.entry, changes, record)
422
- : {
423
- ...index,
424
- refs: applyRefChanges(index.refs, changes),
425
- provenance: applyProvenance(index.provenance, changes, record.provenance),
426
- claim: applyClaim(index.claim, changes, record.claim),
427
- }
444
+ const next = liftExpiry(
445
+ pending.entry
446
+ ? nextIndex(index, pending.entry, changes, record)
447
+ : {
448
+ ...index,
449
+ refs: applyRefChanges(index.refs, changes),
450
+ provenance: applyProvenance(index.provenance, changes, record.provenance),
451
+ claim: applyClaim(index.claim, changes, record.claim),
452
+ },
453
+ )
428
454
 
429
455
  const result = await commitIndex(store, next, etag)
430
456
  if (result.ok) return { ok: true, index: next }
@@ -98,7 +98,12 @@ export function reconcile(gitDir: string, index: WalIndex): ReconcileResult {
98
98
  * for exactly the refs that were wrong.
99
99
  */
100
100
  function writePackedRefs(gitDir: string, refs: Record<string, string>): void {
101
- const lines = ['# pack-refs with: peeled fully-peeled sorted ']
101
+ // `sorted` and nothing else. `peeled`/`fully-peeled` promise that every
102
+ // annotated tag carries its `^<oid>` line, and these lines come from the
103
+ // Index, which holds no object types — so git trusted the promise and
104
+ // advertised annotated tags with no peeled value. Without the traits git
105
+ // peels them itself from the objects.
106
+ const lines = ['# pack-refs with: sorted ']
102
107
  for (const ref of Object.keys(refs).sort()) lines.push(`${refs[ref]} ${ref}`)
103
108
 
104
109
  const target = path.join(gitDir, 'packed-refs')