@zabaca/zbc 0.12.0 → 0.13.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 (73) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/package.json +2 -1
  3. package/templates/apps/inbox/package.json +1 -1
  4. package/templates/apps/walgit/CONTEXT.md +135 -0
  5. package/templates/apps/walgit/Dockerfile +40 -18
  6. package/templates/apps/walgit/README.md +518 -55
  7. package/templates/apps/walgit/e2e/README.md +100 -6
  8. package/templates/apps/walgit/e2e/harness.ts +262 -1
  9. package/templates/apps/walgit/e2e/live.ts +588 -0
  10. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  11. package/templates/apps/walgit/e2e/suite.ts +5 -5
  12. package/templates/apps/walgit/examples/watch.ts +209 -0
  13. package/templates/apps/walgit/package.json +12 -3
  14. package/templates/apps/walgit/registry.json +6 -11
  15. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  16. package/templates/apps/walgit/shared/container-env.ts +114 -0
  17. package/templates/apps/walgit/shared/credentials.ts +81 -0
  18. package/templates/apps/walgit/shared/events.ts +277 -0
  19. package/templates/apps/walgit/shared/landing.ts +1241 -0
  20. package/templates/apps/walgit/shared/llms.ts +463 -0
  21. package/templates/apps/walgit/shared/outbox.ts +266 -0
  22. package/templates/apps/walgit/shared/policy.ts +59 -0
  23. package/templates/apps/walgit/shared/protocol.ts +197 -0
  24. package/templates/apps/walgit/shared/provenance.ts +154 -0
  25. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  26. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  27. package/templates/apps/walgit/src/announce-main.ts +37 -0
  28. package/templates/apps/walgit/src/announce.ts +98 -0
  29. package/templates/apps/walgit/src/append-only.ts +112 -0
  30. package/templates/apps/walgit/src/cache.ts +172 -0
  31. package/templates/apps/walgit/src/cli.ts +493 -0
  32. package/templates/apps/walgit/src/compact.ts +25 -23
  33. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  34. package/templates/apps/walgit/src/expire.ts +248 -0
  35. package/templates/apps/walgit/src/gc.ts +8 -16
  36. package/templates/apps/walgit/src/git-backend.ts +29 -0
  37. package/templates/apps/walgit/src/git.ts +78 -0
  38. package/templates/apps/walgit/src/hook-main.ts +259 -17
  39. package/templates/apps/walgit/src/hooks.ts +4 -3
  40. package/templates/apps/walgit/src/http.ts +237 -45
  41. package/templates/apps/walgit/src/instructions.ts +240 -0
  42. package/templates/apps/walgit/src/keys.ts +126 -0
  43. package/templates/apps/walgit/src/limits.ts +158 -0
  44. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  45. package/templates/apps/walgit/src/materialize.ts +48 -40
  46. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  47. package/templates/apps/walgit/src/orphans.ts +2 -5
  48. package/templates/apps/walgit/src/pending.ts +201 -0
  49. package/templates/apps/walgit/src/push-cert.ts +254 -0
  50. package/templates/apps/walgit/src/push.ts +233 -46
  51. package/templates/apps/walgit/src/reconcile.ts +5 -8
  52. package/templates/apps/walgit/src/repo.ts +22 -77
  53. package/templates/apps/walgit/src/server.ts +148 -26
  54. package/templates/apps/walgit/src/signers.ts +577 -0
  55. package/templates/apps/walgit/src/store-env.ts +5 -4
  56. package/templates/apps/walgit/src/store.ts +47 -24
  57. package/templates/apps/walgit/src/usage.ts +404 -0
  58. package/templates/apps/walgit/src/verify.ts +171 -0
  59. package/templates/apps/walgit/src/wal-index.ts +189 -11
  60. package/templates/apps/walgit/tsconfig.json +8 -2
  61. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  62. package/templates/apps/walgit/worker/events-do.ts +259 -0
  63. package/templates/apps/walgit/worker/index.ts +572 -0
  64. package/templates/apps/walgit/wrangler.jsonc +95 -0
  65. package/templates/apps/warehouse/package.json +1 -1
  66. package/templates/infra/modules/cloudflare/index.ts +77 -6
  67. package/templates/infra/modules/fly/index.ts +150 -10
  68. package/templates/infra/modules/turso/index.ts +43 -3
  69. package/templates/infra/package.json +1 -1
  70. package/templates/apps/walgit/entrypoint.sh +0 -59
  71. package/templates/apps/walgit/fly.toml +0 -52
  72. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  73. package/templates/apps/walgit/sshd_config +0 -38
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The disk cache: bringing a bare repo into existence on this machine.
3
+ *
4
+ * ADR-0007's sentence is that object storage holds the write-ahead log and is
5
+ * the source of truth, and the bare repo on local disk is a disposable cache.
6
+ * This is the file that provisions that cache — `git init --bare`, the three
7
+ * config keys walgit cannot run without, the hooks that ARE the push path, and
8
+ * a sweep of hand-off records left by a `git-receive-pack` that died.
9
+ *
10
+ * It is separate from `repo.ts` because that file answers a different question.
11
+ * `repo.ts` turns an attacker-controlled name into a path and does nothing
12
+ * else; it has no imports and touches no disk. Everything that writes to the
13
+ * disk is here. Keeping them together meant `http.ts`, which wants only
14
+ * `resolveRepo`, transitively depended on the hooks, the object store and the
15
+ * write-ahead log.
16
+ */
17
+
18
+ import * as fs from 'node:fs'
19
+ import * as path from 'node:path'
20
+
21
+ import { capabilitiesFrom } from '../shared/capabilities'
22
+ import { appendOnlyEnabled } from './append-only'
23
+ import { git, gitOrThrow } from './git'
24
+ import { installHooks } from './hooks'
25
+ import { PUSH_CERT_NONCE_SLOP_SECONDS, pushCertSeed } from './push-cert'
26
+ import { sweepPending } from './pending'
27
+ import type { ResolvedRepo } from './repo'
28
+
29
+ /**
30
+ * Set one git config key, but only when it does not already hold that value.
31
+ *
32
+ * The read is not an optimisation. `git config <key> <value>` takes an
33
+ * exclusive `config.lock`, and git does NOT retry when it cannot: it prints
34
+ * `could not lock config file …: File exists` and exits non-zero. Two
35
+ * processes calling `ensureBareRepo` at the same moment is not exotic here —
36
+ * it is the normal case, because compaction materializes (materialize.ts calls
37
+ * ensureBareRepo) in a detached process while the front door is still serving
38
+ * pushes into the same repository. The loser's throw reaches
39
+ * `createHttpHandler`, which cannot tell a repo that failed to open from one
40
+ * that does not exist and answers `404 not found`, so a healthy push dies with
41
+ * `fatal: repository '…' not found`.
42
+ *
43
+ * Reading first makes the steady state lock-free: after the first call these
44
+ * three keys already hold their values and nothing is written at all. When a
45
+ * write is genuinely needed and loses the race, the value the winner wrote is
46
+ * the value this call wanted — identical arguments from identical code — so a
47
+ * re-read that finds it is success, not a papered-over error. Anything else
48
+ * still throws.
49
+ */
50
+ function ensureConfig(gitDir: string, key: string, value: string): void {
51
+ if (readConfig(gitDir, key) === value) return
52
+ const res = git(['--git-dir', gitDir, 'config', key, value])
53
+ if (res.status === 0) return
54
+ if (readConfig(gitDir, key) === value) return
55
+ throw new Error(`git config ${key} ${value} failed: ${res.stderr.trim()}`)
56
+ }
57
+
58
+ /** Remove a config key, if it is set. Losing the lock race is not fatal here. */
59
+ function clearConfig(gitDir: string, key: string): void {
60
+ if (readConfig(gitDir, key) === undefined) return
61
+ git(['--git-dir', gitDir, 'config', '--unset', key])
62
+ }
63
+
64
+ /** The configured value, or undefined when the key is unset. */
65
+ function readConfig(gitDir: string, key: string): string | undefined {
66
+ const res = git(['--git-dir', gitDir, 'config', '--get', key])
67
+ return res.status === 0 ? res.stdout.trim() : undefined
68
+ }
69
+
70
+ /**
71
+ * Create the bare repo if it is missing, and return it either way.
72
+ *
73
+ * Auto-creation on first contact is deliberate: a walgit repository has no
74
+ * lifecycle of its own on this machine — the disk is a cache, and a push to a
75
+ * name nobody has used yet is how a repo comes into existence.
76
+ *
77
+ * "Empty" is the right starting point even for a repo the log already knows
78
+ * about: `syncRepo` runs on every access, and an empty repo is one whose refs
79
+ * are all missing, which is precisely the signal that materializes it. Creating
80
+ * and restoring are therefore the same code path with different amounts of log.
81
+ */
82
+ export function ensureBareRepo(repo: ResolvedRepo): ResolvedRepo {
83
+ if (!fs.existsSync(path.join(repo.dir, 'HEAD'))) {
84
+ fs.mkdirSync(repo.dir, { recursive: true })
85
+ // `main` as the default HEAD, because HEAD on a bare repo is what a clone
86
+ // checks out: created as `master` and pushed to as `main`, a clone succeeds
87
+ // and leaves an empty working tree, which reads as data loss.
88
+ gitOrThrow(['init', '--bare', '--quiet', '--initial-branch=main', repo.dir])
89
+ }
90
+ // Re-applied on every call, not just at creation: `receive.unpackLimit=0`
91
+ // is what makes a small push arrive as a packfile rather than exploding into
92
+ // loose objects, and there is no packfile to upload if it does.
93
+ ensureConfig(repo.dir, 'receive.unpackLimit', '0')
94
+ // git's own housekeeping is turned OFF, and that is not a performance
95
+ // choice. `receive.autogc` runs `git gc --auto` after a push, which on a repo
96
+ // holding one pack per WAL entry fires almost immediately (gc.autoPackLimit
97
+ // is 50) and does two things walgit cannot allow:
98
+ //
99
+ // - It repacks concurrently with `compact`, whose `git repack -adf` expects
100
+ // to be the only writer. gc leaves a main pack AND a cruft pack for the
101
+ // unreachable objects, so compaction finds two and refuses to publish
102
+ // rather than risk a partial one.
103
+ // - It renames what it repacks. `materialize` decides "do I already have
104
+ // this entry?" from the pack's filename, derived from the WAL key, so a
105
+ // repo gc has touched re-downloads the entire log on next access.
106
+ //
107
+ // Packing on this disk belongs to compaction, which publishes the result to
108
+ // the log. A cache that repacks itself behind the log's back is a cache that
109
+ // disagrees with it.
110
+ ensureConfig(repo.dir, 'receive.autogc', 'false')
111
+ ensureConfig(repo.dir, 'gc.auto', '0')
112
+ // The backstop under `pre-receive`'s append-only check. git enforces these
113
+ // AFTER the hook, so they never produce the message a client reads in
114
+ // practice — they are here so a bug in the hook cannot cost anyone history.
115
+ // Written on every access rather than at creation, because the instance can
116
+ // turn the flag on over repositories that already exist.
117
+ if (appendOnlyEnabled()) {
118
+ ensureConfig(repo.dir, 'receive.denyNonFastForwards', 'true')
119
+ ensureConfig(repo.dir, 'receive.denyDeletes', 'true')
120
+ }
121
+ // The backstop under `pre-receive`'s size check — but deliberately NOT set to
122
+ // the cap itself. git hands `receive.maxInputSize` to `index-pack`, which
123
+ // fails while the pack is still being read, i.e. BEFORE `pre-receive` runs:
124
+ // set to the cap, it would win every race and every client would read
125
+ // `fatal: pack exceeds maximum allowed size` instead of the message
126
+ // src/limits.ts exists to write. So it is set with headroom: the hook owns
127
+ // every refusal a real client can provoke, and this only bounds a pack so far
128
+ // past the cap that a bug in the hook is the likelier explanation.
129
+ // Cleared when the cap is, because a stale limit on a repository whose
130
+ // instance no longer sets one would refuse pushes nothing documents.
131
+ const { maxPushBytes } = capabilitiesFrom(process.env)
132
+ if (maxPushBytes === null) {
133
+ clearConfig(repo.dir, 'receive.maxInputSize')
134
+ } else {
135
+ ensureConfig(repo.dir, 'receive.maxInputSize', String(Math.floor(maxPushBytes) * 2))
136
+ }
137
+ // Signed pushes exist on this repository exactly when a nonce seed does.
138
+ // `receive.certNonceSeed` is what makes `git-receive-pack` advertise the
139
+ // `push-cert` capability at all, so this one key is the whole of "the host
140
+ // accepts a signed push" (src/push-cert.ts, docs/adr/0011).
141
+ //
142
+ // Written here rather than at creation for the reason the whole file works
143
+ // this way: the disk is a cache, and a repository materialized from the log
144
+ // after a restart is a repository this line has to reach. Cleared when the
145
+ // variable is, so turning the capability off stops the advertisement on the
146
+ // next access instead of leaving repositories that predate the change
147
+ // certifying pushes nothing else knows about.
148
+ //
149
+ // `receive.certNonceSlop` travels with the seed and is not optional beside
150
+ // it: git's nonce carries the second it was minted in, a push is two requests
151
+ // that mint one each, and with the default slop of 0 only a round trip that
152
+ // stayed inside a single second reports `OK`. Every other one reports `SLOP`,
153
+ // establishes no Signer, and — on a name held by a Signer List — refuses the
154
+ // owner's own push (src/push-cert.ts, docs/adr/0012).
155
+ const seed = pushCertSeed()
156
+ if (seed === null) {
157
+ clearConfig(repo.dir, 'receive.certNonceSeed')
158
+ clearConfig(repo.dir, 'receive.certNonceSlop')
159
+ } else {
160
+ ensureConfig(repo.dir, 'receive.certNonceSeed', seed)
161
+ ensureConfig(repo.dir, 'receive.certNonceSlop', String(PUSH_CERT_NONCE_SLOP_SECONDS))
162
+ }
163
+ // The hooks ARE the push path. Re-installed on every access for the same
164
+ // reason as the config above: a repo that arrived here by any other route
165
+ // would otherwise accept pushes that never reach the write-ahead log.
166
+ installHooks(repo.dir, repo.repoId)
167
+ // A `git-receive-pack` killed between its hooks leaves a hand-off record
168
+ // behind. Keyed by pid, it is unreadable by any other push — but it should
169
+ // not accumulate either, and a recycled pid must never resurrect it.
170
+ sweepPending(repo.dir)
171
+ return repo
172
+ }
@@ -0,0 +1,493 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `walgit` — the operator front door.
4
+ *
5
+ * Everything here is a THIN front over the functions the server already calls:
6
+ * `materialize`, `reconcile`, `findOrphans`, `verifyRepo`. That is not tidiness,
7
+ * it is the only way `verify` can be trusted — a command-line reimplementation
8
+ * of "is this disk current?" would answer for itself rather than for the server,
9
+ * and would drift silently the first time the real path changed.
10
+ *
11
+ * Credentials come from `store-env.ts`, the same reader the smart-HTTP server
12
+ * and both hook processes use. There is deliberately no `~/.walgit/config`: a
13
+ * second configuration path is a second thing to be wrong about, and the
14
+ * environment is what a shell inside the container already has.
15
+ *
16
+ * Run it inside the container, where that environment exists — or anywhere the
17
+ * same WALGIT_* variables are set:
18
+ *
19
+ * bun src/cli.ts verify myrepo
20
+ *
21
+ * Exit codes are meant to be branched on: 0 success, 1 a divergence or failure
22
+ * the command was asked to detect, 2 misuse (unknown command, bad arguments,
23
+ * missing configuration).
24
+ */
25
+
26
+ import * as path from 'node:path'
27
+
28
+ import { compact, configuredGraceMs, type CompactResult } from './compact'
29
+ import { configuredDeleteGraceMs, deleteRepo } from './delete-repo'
30
+ import { configuredExpiryMs, expireRepos } from './expire'
31
+ import { collectGarbage } from './gc'
32
+ import { materialize, round } from './materialize'
33
+ import { normalizeRepoId, resolveRepo } from './repo'
34
+ import { requireStore } from './store-env'
35
+ import { collectUsage, formatUsage, parseDuration } from './usage'
36
+ import { formatVerify, verifyRepo } from './verify'
37
+
38
+ const OK = 0
39
+ const DIVERGED = 1
40
+ const MISUSE = 2
41
+
42
+ export interface ParsedArgs {
43
+ command: string
44
+ positional: string[]
45
+ flags: Record<string, string | true>
46
+ }
47
+
48
+ /**
49
+ * `--flag`, `--flag=value`, `--flag value`, and everything else positional.
50
+ *
51
+ * `KNOWN_VALUE_FLAGS` is what makes `--min-age 30` work without making
52
+ * `gc myrepo --yes myotherrepo` swallow a repo id: a flag takes the next token
53
+ * only when it is declared to want one.
54
+ */
55
+ const KNOWN_VALUE_FLAGS = new Set(['min-age', 'repos-dir', 'grace', 'after', 'since', 'top'])
56
+
57
+ export function parseArgs(argv: readonly string[]): ParsedArgs {
58
+ const positional: string[] = []
59
+ const flags: Record<string, string | true> = {}
60
+ for (let i = 0; i < argv.length; i += 1) {
61
+ const arg = argv[i]!
62
+ if (!arg.startsWith('--')) {
63
+ positional.push(arg)
64
+ continue
65
+ }
66
+ const body = arg.slice(2)
67
+ const eq = body.indexOf('=')
68
+ if (eq >= 0) {
69
+ flags[body.slice(0, eq)] = body.slice(eq + 1)
70
+ } else if (KNOWN_VALUE_FLAGS.has(body) && i + 1 < argv.length) {
71
+ i += 1
72
+ flags[body] = argv[i]!
73
+ } else {
74
+ flags[body] = true
75
+ }
76
+ }
77
+ return { command: positional.shift() ?? '', positional, flags }
78
+ }
79
+
80
+ const USAGE = `walgit — operator CLI for a WAL-backed git host
81
+
82
+ walgit serve run the git front end (smart-HTTP)
83
+ walgit materialize <repo_id> [path] rebuild a repo from the write-ahead log
84
+ walgit verify <repo_id> [path] check local state against index.json
85
+ walgit gc <repo_id...> reclaim orphaned WAL objects (dry run)
86
+ walgit compact <repo_id> [path] repack the log into one entry, now
87
+ walgit delete <repo_id...> remove repositories entirely (dry run)
88
+ walgit usage what the log says this service holds
89
+ walgit expire [repo_id...] collect repos idle past the window (dry run)
90
+
91
+ Options
92
+ --repos-dir <dir> where bare repos live (default: $WALGIT_REPOS_DIR)
93
+ --json machine-readable output
94
+ --yes gc/delete/expire: actually delete (else they only report)
95
+ --force=false compact: respect the entry-count threshold instead of forcing
96
+ --min-age <minutes> gc: never collect an object younger than this (default 60)
97
+ --grace <minutes> delete/expire: how long a repo is tombstoned first (default 60)
98
+ --after <hours> expire: idle window (default $WALGIT_RETENTION_HOURS; unset = off)
99
+ --since <duration> usage: push window, e.g. 24h, 7d, 30m (default 24h)
100
+ --top <n> usage: how many repositories to name (0 = all, default 10)
101
+
102
+ The object store is read from the environment the app itself uses:
103
+ WALGIT_S3_ENDPOINT / _BUCKET / _ACCESS_KEY_ID / _SECRET_ACCESS_KEY, or
104
+ WALGIT_STORE_DIR for local use. Exit codes: 0 ok, 1 divergence, 2 misuse.`
105
+
106
+ function reposDirOf(args: ParsedArgs, env: NodeJS.ProcessEnv): string {
107
+ const flag = args.flags['repos-dir']
108
+ if (typeof flag === 'string') return flag
109
+ return env.WALGIT_REPOS_DIR ?? '/srv/walgit/repos'
110
+ }
111
+
112
+ /** The repo the operator named, at the path they named, or at the default one. */
113
+ function repoAt(args: ParsedArgs, env: NodeJS.ProcessEnv, requested: string, dir?: string) {
114
+ if (dir) return { repoId: normalizeRepoId(requested), dir: path.resolve(dir) }
115
+ return resolveRepo(reposDirOf(args, env), requested)
116
+ }
117
+
118
+ function emit(args: ParsedArgs, payload: unknown, text: string): void {
119
+ if (args.flags.json) console.log(JSON.stringify(payload, null, 2))
120
+ else console.log(text)
121
+ }
122
+
123
+ // ── Commands ────────────────────────────────────────────────────────────────
124
+
125
+ /**
126
+ * `serve` delegates to `src/server.ts` by importing it — that module starts the
127
+ * server as a side effect of loading. The container entrypoint still calls that
128
+ * file directly, so there is exactly one server with one startup sequence, and
129
+ * this is a convenience over it rather than a second way to boot.
130
+ */
131
+ async function serve(): Promise<number> {
132
+ await import('./server')
133
+ // The server holds the process open; returning is unreachable in practice.
134
+ return OK
135
+ }
136
+
137
+ async function materializeCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
138
+ const [requested, target] = args.positional
139
+ if (!requested) {
140
+ console.error('walgit materialize: usage: walgit materialize <repo_id> [path]')
141
+ return MISUSE
142
+ }
143
+ const store = requireStore(env)
144
+ const repo = repoAt(args, env, requested, target)
145
+
146
+ const result = await materialize(store, repo)
147
+ emit(
148
+ args,
149
+ { ...round(result.stats), dir: repo.dir, refs: Object.keys(result.index.refs).length },
150
+ `materialized ${repo.repoId} into ${repo.dir}\n` +
151
+ ` ${result.stats.fetched} entries fetched, ${result.stats.skipped} already present, ` +
152
+ `${result.stats.superseded} superseded\n` +
153
+ ` ${Object.keys(result.index.refs).length} refs, ${Math.round(result.stats.totalMs)} ms`,
154
+ )
155
+
156
+ // A ref the log names but no downloaded object satisfies means the log itself
157
+ // is incomplete — reporting success here would hand back a repo that clones
158
+ // short, which is the one outcome this whole design exists to prevent.
159
+ if (result.reconciled.missing.length > 0) {
160
+ console.error(
161
+ `walgit: ${result.reconciled.missing.length} refs could not be restored: ` +
162
+ result.reconciled.missing.join(', '),
163
+ )
164
+ return DIVERGED
165
+ }
166
+ return OK
167
+ }
168
+
169
+ async function verifyCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
170
+ const [requested, target] = args.positional
171
+ if (!requested) {
172
+ console.error('walgit verify: usage: walgit verify <repo_id> [path]')
173
+ return MISUSE
174
+ }
175
+ const store = requireStore(env)
176
+ const repo = repoAt(args, env, requested, target)
177
+
178
+ const report = await verifyRepo(store, repo)
179
+ emit(args, report, formatVerify(report))
180
+ return report.ok ? OK : DIVERGED
181
+ }
182
+
183
+ async function gcCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
184
+ if (args.positional.length === 0) {
185
+ // No "collect everything" mode on purpose: a `LIST` of the whole bucket
186
+ // would name repos this node has never served, and the blast radius of a
187
+ // wrong guess is objects deleted from the source of truth.
188
+ console.error('walgit gc: usage: walgit gc <repo_id...> [--yes] [--min-age <minutes>]')
189
+ return MISUSE
190
+ }
191
+ const store = requireStore(env)
192
+ const minAgeFlag = args.flags['min-age']
193
+ const graceMs =
194
+ typeof minAgeFlag === 'string' ? Number(minAgeFlag) * 60_000 : configuredGraceMs(env)
195
+ if (!Number.isFinite(graceMs) || graceMs < 0) {
196
+ console.error(`walgit gc: --min-age must be a number of minutes, got ${String(minAgeFlag)}`)
197
+ return MISUSE
198
+ }
199
+
200
+ // Dry run is the default. An operator reaching for `gc` on a bad day should
201
+ // be able to look before anything is gone, so deleting takes an extra word.
202
+ const dryRun = args.flags.yes !== true
203
+ const results = []
204
+ for (const requested of args.positional) {
205
+ const repoId = normalizeRepoId(requested)
206
+ results.push({ repoId, ...(await collectGarbage(store, repoId, { graceMs, dryRun })) })
207
+ }
208
+
209
+ const lines: string[] = []
210
+ let total = 0
211
+ for (const result of results) {
212
+ const reclaimable = [...result.collected, ...result.orphansCollected]
213
+ total += reclaimable.length
214
+ const verb = dryRun ? 'would collect' : 'collected'
215
+ lines.push(`${result.repoId}: ${verb} ${reclaimable.length} objects`)
216
+ for (const key of result.collected)
217
+ lines.push(` ${dryRun ? '-' : 'deleted'} ${key} (superseded)`)
218
+ for (const key of result.orphansCollected)
219
+ lines.push(` ${dryRun ? '-' : 'deleted'} ${key} (orphan)`)
220
+ // Held objects are named rather than counted: "why is this still here" is
221
+ // the question an operator actually arrives with.
222
+ for (const key of result.retained) lines.push(` kept (in grace) ${key}`)
223
+ for (const key of result.orphansHeld) lines.push(` kept (too young or undatable) ${key}`)
224
+ }
225
+ if (
226
+ results.every(
227
+ (r) =>
228
+ r.collected.length +
229
+ r.orphansCollected.length +
230
+ r.retained.length +
231
+ r.orphansHeld.length ===
232
+ 0,
233
+ )
234
+ ) {
235
+ lines.push('nothing to collect')
236
+ }
237
+ if (dryRun && total > 0) lines.push('nothing was deleted — re-run with --yes')
238
+ emit(args, results, lines.join('\n'))
239
+ return OK
240
+ }
241
+
242
+ /**
243
+ * Remove repositories entirely — index, WAL objects, and the cached bare repo.
244
+ *
245
+ * Deferred in two steps by design: the first `--yes` run tombstones, and a
246
+ * later one collects once the grace period has elapsed. See `delete-repo.ts`
247
+ * for why the wait is not optional and why the index goes first.
248
+ */
249
+ async function deleteCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
250
+ if (args.positional.length === 0) {
251
+ console.error('walgit delete: usage: walgit delete <repo_id...> [--yes] [--grace <minutes>]')
252
+ return MISUSE
253
+ }
254
+ const store = requireStore(env)
255
+ const graceFlag = args.flags.grace
256
+ const graceMs =
257
+ typeof graceFlag === 'string' ? Number(graceFlag) * 60_000 : configuredDeleteGraceMs(env)
258
+ if (!Number.isFinite(graceMs) || graceMs < 0) {
259
+ console.error(`walgit delete: --grace must be a number of minutes, got ${String(graceFlag)}`)
260
+ return MISUSE
261
+ }
262
+
263
+ // Dry run is the default, as it is for `gc`, and more emphatically: this
264
+ // command deletes objects the index still names.
265
+ const dryRun = args.flags.yes !== true
266
+ const results = []
267
+ for (const requested of args.positional) {
268
+ const repo = repoAt(args, env, requested)
269
+ results.push(await deleteRepo(store, repo.repoId, { graceMs, dryRun, dir: repo.dir }))
270
+ }
271
+
272
+ const lines: string[] = []
273
+ for (const result of results) {
274
+ if (result.status === 'absent') {
275
+ lines.push(`${result.repoId}: nothing to delete`)
276
+ } else if (result.status === 'tombstoned') {
277
+ lines.push(
278
+ `${result.repoId}: ${dryRun ? 'would be scheduled' : 'scheduled'} for deletion, ` +
279
+ `collectable after ${result.collectAfter}`,
280
+ )
281
+ } else if (result.status === 'retained') {
282
+ lines.push(
283
+ `${result.repoId}: already scheduled — nothing may be deleted before ` +
284
+ `${result.collectAfter}`,
285
+ )
286
+ } else {
287
+ const verb = dryRun ? 'would delete' : 'deleted'
288
+ lines.push(`${result.repoId}: ${verb} ${result.deleted.length} objects`)
289
+ }
290
+ for (const key of result.deleted) lines.push(` ${dryRun ? '-' : 'deleted'} ${key}`)
291
+ for (const kept of result.retained) lines.push(` kept ${kept.key} (${kept.reason})`)
292
+ if (result.cacheRemoved) lines.push(` removed cache ${result.cacheRemoved}`)
293
+ }
294
+ if (dryRun && results.some((r) => r.status !== 'absent')) {
295
+ lines.push('nothing was changed — re-run with --yes')
296
+ }
297
+ emit(args, results, lines.join('\n'))
298
+ return OK
299
+ }
300
+
301
+ /**
302
+ * Collect repositories nobody has pushed to for longer than the window.
303
+ *
304
+ * Named repositories may be given, but the point of the command is the bare
305
+ * form: it enumerates every repository in the store, which is exactly what `gc`
306
+ * refuses to do. The difference is what a wrong answer costs. `gc` deletes
307
+ * objects `index.json` does not name, so guessing the repo set there risks
308
+ * deleting a live repository's packs; expiry deletes only what the log itself
309
+ * dates as idle, and every case it cannot date resolves toward keeping.
310
+ *
311
+ * Off unless `WALGIT_RETENTION_HOURS` (or `--after`) says otherwise, because an
312
+ * instance that has not been told to expire anything must not.
313
+ */
314
+ async function expireCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
315
+ const afterFlag = args.flags.after
316
+ const windowMs =
317
+ typeof afterFlag === 'string' ? Number(afterFlag) * 3_600_000 : configuredExpiryMs(env)
318
+ if (windowMs !== null && (!Number.isFinite(windowMs) || windowMs <= 0)) {
319
+ console.error(
320
+ `walgit expire: --after must be a positive number of hours, got ${String(afterFlag)}`,
321
+ )
322
+ return MISUSE
323
+ }
324
+ const graceFlag = args.flags.grace
325
+ const graceMs =
326
+ typeof graceFlag === 'string' ? Number(graceFlag) * 60_000 : configuredDeleteGraceMs(env)
327
+ if (!Number.isFinite(graceMs) || graceMs < 0) {
328
+ console.error(`walgit expire: --grace must be a number of minutes, got ${String(graceFlag)}`)
329
+ return MISUSE
330
+ }
331
+
332
+ if (windowMs === null) {
333
+ // Not an error: an instance with no retention window is a valid instance,
334
+ // and the timer calling this should not start failing because of it.
335
+ emit(
336
+ args,
337
+ { collected: [], retained: [], windowMs: null, dryRun: true },
338
+ 'expiry is not configured — set WALGIT_RETENTION_HOURS or pass --after <hours>',
339
+ )
340
+ return OK
341
+ }
342
+
343
+ const store = requireStore(env)
344
+ const dryRun = args.flags.yes !== true
345
+ const result = await expireRepos(store, {
346
+ windowMs,
347
+ graceMs,
348
+ dryRun,
349
+ reposDir: reposDirOf(args, env),
350
+ repoIds:
351
+ args.positional.length > 0 ? args.positional.map((r) => normalizeRepoId(r)) : undefined,
352
+ })
353
+
354
+ const lines: string[] = [
355
+ `window ${windowMs / 3_600_000}h — ${result.collected.length} collected, ` +
356
+ `${result.retained.length} retained`,
357
+ ]
358
+ for (const outcome of result.collected) {
359
+ const status = outcome.deletion?.status ?? 'collected'
360
+ lines.push(
361
+ ` ${dryRun ? 'would collect' : status} ${outcome.repoId} (${outcome.decision.reason})`,
362
+ )
363
+ }
364
+ // Retentions are named with their reason rather than counted: a repository
365
+ // that should have gone and did not is only debuggable if the run says why.
366
+ for (const outcome of result.retained) {
367
+ lines.push(` kept ${outcome.repoId} (${outcome.decision.reason})`)
368
+ }
369
+ if (dryRun && result.collected.length > 0) lines.push('nothing was changed — re-run with --yes')
370
+ emit(args, result, lines.join('\n'))
371
+ return OK
372
+ }
373
+
374
+ /**
375
+ * Force a compaction, bypassing the entry-count threshold.
376
+ *
377
+ * The threshold exists so compaction happens on its own after enough pushes;
378
+ * this command is for the case that has already gone wrong — a repo whose
379
+ * restore is slow because its log is long, and an operator who wants it short
380
+ * now rather than after the next N pushes.
381
+ */
382
+ async function compactCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
383
+ const [requested] = args.positional
384
+ if (!requested) {
385
+ console.error('walgit compact: usage: walgit compact <repo_id> [path] [--force]')
386
+ return MISUSE
387
+ }
388
+ const store = requireStore(env)
389
+ const repo = repoAt(args, env, requested)
390
+ // Forcing is the default here and nowhere else: someone typing `compact` has
391
+ // already decided, whereas the automatic path must respect the threshold.
392
+ // `--force=false` opts back into it, which is how an operator asks "would
393
+ // this compact on its own yet?" without making it happen.
394
+ const result = await compact(store, repo, { force: args.flags.force !== 'false' })
395
+
396
+ const lines: Record<CompactResult['status'], () => string> = {
397
+ compacted: () => {
398
+ const r = result as Extract<CompactResult, { status: 'compacted' }>
399
+ return (
400
+ `${repo.repoId}: compacted into seq ${r.seq}, superseding through ` +
401
+ `${r.supersedes_through} (${r.tombstoned.length} objects tombstoned, ` +
402
+ `${(r.bytes / 1024).toFixed(0)} KiB, ${r.ms.toFixed(0)}ms)\n` +
403
+ 'Tombstoned objects are deleted by `walgit gc` once their grace period elapses.'
404
+ )
405
+ },
406
+ 'not-due': () =>
407
+ `${repo.repoId}: not due — ${(result as { pending: number }).pending} entries pending`,
408
+ held: () =>
409
+ `${repo.repoId}: another node holds the compaction lease (${(result as { holder: string }).holder})`,
410
+ empty: () => `${repo.repoId}: nothing to compact`,
411
+ }
412
+ emit(args, result, lines[result.status]())
413
+ // `held` is not a failure: the work is being done, just not by this process.
414
+ return OK
415
+ }
416
+
417
+ /**
418
+ * `usage` reads and only reads. It needs no repos directory, no local cache and
419
+ * no running server — bucket credentials are the whole requirement, so it can
420
+ * be run from a laptop while the service is on fire.
421
+ */
422
+ async function usageCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<number> {
423
+ if (args.positional.length > 0) {
424
+ console.error('walgit usage: usage: walgit usage [--since 24h] [--top 10] [--json]')
425
+ return MISUSE
426
+ }
427
+ const since = args.flags.since
428
+ const top = args.flags.top
429
+ const topN = typeof top === 'string' ? Number(top) : 10
430
+ if (!Number.isInteger(topN) || topN < 0) {
431
+ console.error(`walgit usage: --top expects a non-negative integer, got ${String(top)}`)
432
+ return MISUSE
433
+ }
434
+ const store = requireStore(env)
435
+
436
+ const report = await collectUsage(store, {
437
+ // A window is the default because "what is happening now" is the question
438
+ // that brings someone here; `--since 0` asks for lifetime totals only.
439
+ sinceMs: parseDuration(typeof since === 'string' ? since : '24h') || undefined,
440
+ top: topN,
441
+ })
442
+ emit(args, report, formatUsage(report))
443
+ return OK
444
+ }
445
+
446
+ // ── Entry point ─────────────────────────────────────────────────────────────
447
+
448
+ export async function main(
449
+ argv: readonly string[],
450
+ env: NodeJS.ProcessEnv = process.env,
451
+ ): Promise<number> {
452
+ const args = parseArgs(argv)
453
+ if (args.command === '' || args.flags.help || args.command === 'help') {
454
+ console.log(USAGE)
455
+ return args.command === '' && !args.flags.help ? MISUSE : OK
456
+ }
457
+
458
+ try {
459
+ switch (args.command) {
460
+ case 'serve':
461
+ return await serve()
462
+ case 'materialize':
463
+ return await materializeCommand(args, env)
464
+ case 'verify':
465
+ return await verifyCommand(args, env)
466
+ case 'gc':
467
+ return await gcCommand(args, env)
468
+ case 'compact':
469
+ return await compactCommand(args, env)
470
+ case 'delete':
471
+ return await deleteCommand(args, env)
472
+ case 'usage':
473
+ return await usageCommand(args, env)
474
+ case 'expire':
475
+ return await expireCommand(args, env)
476
+ default:
477
+ console.error(`walgit: unknown command "${args.command}"\n\n${USAGE}`)
478
+ return MISUSE
479
+ }
480
+ } catch (error) {
481
+ // One message, no stack: the failures an operator hits here are a missing
482
+ // credential, a bad repo name, or an unreachable bucket, and a stack trace
483
+ // buries all three.
484
+ console.error(`walgit: ${error instanceof Error ? error.message : String(error)}`)
485
+ return MISUSE
486
+ }
487
+ }
488
+
489
+ // `import.meta.main` is false when the test suite imports this file, so the
490
+ // exported `main` stays callable without the process exiting under it.
491
+ if (import.meta.main) {
492
+ process.exitCode = await main(process.argv.slice(2))
493
+ }