c8ctl-plugin-nano 1.67.0 → 1.69.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.
@@ -0,0 +1,944 @@
1
+ // WIP checkpoints for ephemeral agent workers (issue #264).
2
+ //
3
+ // A host-provisioned agent job runs in a throwaway clone. If the worker dies
4
+ // mid-run (crash, OOM, preemption, `stop --force`), every UNCOMMITTED change and
5
+ // every unpushed local commit dies with it, and the re-activation (#239) can only
6
+ // replay the transcript. This module lets the worker periodically snapshot the
7
+ // workspace to a deterministic remote ref WITHOUT touching the agent's HEAD,
8
+ // index, or branch, and restore that snapshot on the next activation.
9
+ //
10
+ // - Snapshot: a "shadow commit" built through a TEMPORARY index
11
+ // (`GIT_INDEX_FILE`): `read-tree HEAD` (or the empty tree on an UNBORN HEAD) →
12
+ // `add -A` (honours .gitignore) → drop deny-listed / oversized paths →
13
+ // `write-tree` → `commit-tree -p HEAD` (parentless when unborn).
14
+ // The agent's own index and refs are never written.
15
+ // - Push: `refs/nano/wip/<elementInstanceKey>` with `--force-with-lease` against
16
+ // the last sha WE pushed, so a zombie prior owner can't clobber a newer run.
17
+ // The snapshot's ancestry carries any unpushed local commits too.
18
+ // - Restore: fetch the ref; if the fresh clone's HEAD is an ancestor of the
19
+ // snapshot's parent, move the branch to that parent (recovering local commits)
20
+ // and lay the snapshot tree down as UNCOMMITTED changes. Otherwise apply the
21
+ // prior run's base→snapshot diff onto the new HEAD (`--3way`), else skip.
22
+ // - Delete the ref after a successful finalize.
23
+ //
24
+ // - GC: a throttled background sweep deletes WIP refs past a TTL, or whose
25
+ // element instance the engine reports terminal (orphans from cancelled or
26
+ // never-reactivated jobs).
27
+ //
28
+ // Mode (`NANO_AGENT_CHECKPOINT`): `auto` (default) runs only for provisioned jobs
29
+ // that already push an authenticated working branch; `on` forces it for any
30
+ // provisioned job; `off` disables. Everything is BEST-EFFORT: any failure is
31
+ // logged and degrades to today's behaviour (transcript-only resume). Git runs
32
+ // ASYNC here (not spawnSync) so a slow push never blocks the ACP event loop.
33
+
34
+ import { spawn } from 'node:child_process';
35
+ import { mkdtempSync, rmSync } from 'node:fs';
36
+ import { tmpdir } from 'node:os';
37
+ import { join } from 'node:path';
38
+
39
+ export const CHECKPOINT_REF_PREFIX = 'refs/nano/wip/';
40
+ export const CHECKPOINT_BASE_TRAILER = 'Nano-Checkpoint-Base';
41
+ export const CHECKPOINT_RUN_TRAILER = 'Nano-Checkpoint-Run';
42
+ // The RAW (unsanitized) base ref the run was provisioned against (e.g. `main` or
43
+ // `feature/foo`). The generated per-run fallback branch embeds only the SANITIZED
44
+ // base segment, and distinct real refs can sanitize identically (`feature/foo` and
45
+ // `feature-foo` both become `feature-foo`), so the branch name alone cannot prove
46
+ // two fallbacks share a base. Restore requires this unambiguous raw identity to
47
+ // match before treating a per-run rename as benign; a snapshot that cannot prove
48
+ // it (no trailer) is refused rather than patch-restored onto the wrong branch.
49
+ export const CHECKPOINT_BASEREF_TRAILER = 'Nano-Checkpoint-BaseRef';
50
+ // The symbolic branch HEAD was on when the snapshot was taken. Restore refuses to
51
+ // FAST-restore (reset HEAD + recover commits) a snapshot whose branch differs from
52
+ // the run's expected working branch, so off-branch commits can never be reset onto
53
+ // — and later pushed by finalizeGit to — the wrong branch.
54
+ export const CHECKPOINT_BRANCH_TRAILER = 'Nano-Checkpoint-Branch';
55
+ // Explicit "HEAD was detached" identity, recorded (instead of an OMITTED trailer)
56
+ // when a snapshot is taken off any branch. The `:` makes it an impossible git
57
+ // branch name, so it can never equal a real `expectedBranch` and always trips the
58
+ // branch-identity guard — a detached snapshot's `parent` may still be an ancestor
59
+ // of the run's work-branch tip, so without this it would masquerade as a legacy
60
+ // trailerless snapshot and be fast-restored (resetting the work branch onto the
61
+ // off-branch commit). Legacy snapshots (created before this trailer existed) carry
62
+ // NO trailer at all and keep the prior ancestry-only behaviour.
63
+ export const CHECKPOINT_DETACHED_MARKER = 'HEAD:detached';
64
+
65
+ // Per-run fallback branches provisioning cuts when a job supplies no stable working
66
+ // branch: `nano/agent-work/<base>-<runId>`. The `runId` segment makes the name differ
67
+ // on EVERY activation, so a checkpoint's branch trailer can never equal the next run's
68
+ // expected working branch. That rename is BENIGN — both are ephemeral fallbacks off the
69
+ // same base, not a genuine off-branch/detached move — so the restore path treats it
70
+ // specially: it still refuses the ancestry-RESET fast path but falls through to the
71
+ // non-reset PATCH restore, recovering the fallback job's WIP instead of stranding it.
72
+ const FALLBACK_BRANCH_RE = /^nano\/agent-work\//;
73
+ // The unique run-token provisioning appends to a generated fallback segment:
74
+ // `nano/agent-work/<base>-<runToken>`, where <runToken> is the run's UUID (production)
75
+ // or a `run-<token>` workspace basename (the direct-call test fallback). Anchored at the
76
+ // END so a <base> that itself contains dashes still parses. Used to validate a benign
77
+ // per-run rename on the generated fallback IDENTITY (its <base> AND <runToken>), not
78
+ // merely the `nano/agent-work/` namespace prefix — an unrelated or stable branch that
79
+ // only lives under that namespace must NOT be mistaken for a per-run fallback rename.
80
+ const FALLBACK_UNIQ_RE = /-((?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})|run-[0-9A-Za-z]+)$/;
81
+ // Parse a generated per-run fallback branch into { base, token }, or null when `name`
82
+ // is not a generated fallback (missing namespace prefix, or no trailing run-token).
83
+ function fallbackBranchParts(name) {
84
+ if (typeof name !== 'string' || !FALLBACK_BRANCH_RE.test(name)) return null;
85
+ const m = name.match(FALLBACK_UNIQ_RE);
86
+ if (!m) return null;
87
+ const base = name.slice('nano/agent-work/'.length, name.length - m[0].length);
88
+ if (!base) return null;
89
+ return { base, token: m[1] };
90
+ }
91
+
92
+ // Canonical git branch-segment sanitizer. Provisioning builds a per-run fallback
93
+ // branch `nano/agent-work/${sanitizeBranchSegment(base)}-${sanitizeBranchSegment(runId)}`
94
+ // (c8ctl-plugin.js), and the restore path reconstructs that generated run-token to
95
+ // validate a benign per-run rename — so both MUST share ONE implementation to avoid
96
+ // drift. Exported and consumed by the plugin as the single source of truth.
97
+ export function sanitizeBranchSegment(s) {
98
+ const cleaned = String(s == null ? '' : s)
99
+ .replace(/[^0-9A-Za-z._-]+/g, '-') // collapse anything unusual to a dash
100
+ .replace(/\.{2,}/g, '.') // no doubled dots (git forbids "..")
101
+ .replace(/^[-.]+/, '') // no leading dot or dash
102
+ .slice(0, 60) // bound the segment BEFORE the trailing
103
+ .replace(/[-.]+$/g, '') // checks, so truncating at char 60 can't
104
+ .replace(/\.lock$/i, 'lock'); // re-introduce a trailing dot/dash or ".lock"
105
+ return cleaned || 'base';
106
+ }
107
+
108
+ const DEFAULTS = Object.freeze({
109
+ minIntervalMs: 60_000,
110
+ intervalMs: 300_000,
111
+ maxFileBytes: 5 * 1024 * 1024,
112
+ gitTimeoutMs: 60_000,
113
+ // Grace window after SIGTERM before escalating to SIGKILL when a git child (or a
114
+ // transport/credential helper it spawned) ignores the polite terminate on
115
+ // timeout/abort — bounds how long the runner can stay pending past its deadline.
116
+ gitKillGraceMs: 5_000,
117
+ flushTimeoutMs: 20_000,
118
+ ttlMs: 7 * 24 * 60 * 60 * 1000,
119
+ gcGraceMs: 60 * 60 * 1000,
120
+ gcEveryMs: 60 * 60 * 1000,
121
+ });
122
+ const MIN_INTERVAL_FLOOR_MS = 5_000;
123
+
124
+ // Paths that must never leave the worker even if the agent forgot to gitignore
125
+ // them. Matched against the repo-relative path (any directory depth).
126
+ export const DENY_PATTERNS = Object.freeze([
127
+ // Any basename beginning with `.env` (the documented `.env*` policy): `.env`,
128
+ // `.env.local`, but also `.envrc`, `.envlocal`, … — not just dot-suffixed names.
129
+ /(^|\/)\.env[^/]*$/i,
130
+ /(^|\/)\.npmrc$/i,
131
+ /(^|\/)\.netrc$/i,
132
+ /(^|\/)\.pypirc$/i,
133
+ // The whole `id_` basename family (the documented `id_*` policy): `id_rsa`,
134
+ // `id_ed25519`, but also `id_token`, `id_ed25519_old`, `id_custom`, … so a
135
+ // private key the content scanner does not recognise still never leaves the host.
136
+ /(^|\/)id_[^/]*$/i,
137
+ /\.(pem|key|p12|pfx|jks|keystore)$/i,
138
+ /(^|\/)\.(aws|ssh|gnupg)\//i,
139
+ /(^|\/)credentials(\.json)?$/i,
140
+ /(^|\/)secrets?\.(json|ya?ml|toml)$/i,
141
+ /(^|\/)\.git-credentials$/i,
142
+ ]);
143
+
144
+ export function isDeniedPath(path) {
145
+ const p = String(path ?? '');
146
+ return DENY_PATTERNS.some((re) => re.test(p));
147
+ }
148
+
149
+ // Content patterns for well-known credential formats. A changed file whose text
150
+ // matches any of these (or contains a secret value this job was given) is kept
151
+ // out of the snapshot.
152
+ export const SECRET_CONTENT_PATTERNS = Object.freeze([
153
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
154
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/,
155
+ /\bgithub_pat_[A-Za-z0-9_]{60,}\b/,
156
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/,
157
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/,
158
+ /\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{32,}\b/,
159
+ /\bAIza[0-9A-Za-z_-]{35}\b/,
160
+ /\bnpm_[A-Za-z0-9]{36}\b/,
161
+ ]);
162
+ export function normalizeSecretValues(values) {
163
+ const out = new Set();
164
+ for (const v of values || []) {
165
+ const s = typeof v === 'string' ? v.trim() : '';
166
+ // Honour EVERY non-empty injected secret value regardless of length. The
167
+ // documented guarantee excludes any changed file whose content contains an
168
+ // injected secret from the checkpoint; dropping short values (the old 8-char
169
+ // floor) would silently let a short `setup.secretRefs` value slip into a WIP
170
+ // ref. Over-excluding a file that merely contains a short secret substring is
171
+ // the safe degradation — leaking a secret is not.
172
+ if (s) out.add(s);
173
+ }
174
+ return [...out];
175
+ }
176
+
177
+ export function containsSecret(text, secretValues = []) {
178
+ const t = String(text ?? '');
179
+ if (!t) return false;
180
+ if (secretValues.some((v) => t.includes(v))) return true;
181
+ return SECRET_CONTENT_PATTERNS.some((re) => re.test(t));
182
+ }
183
+
184
+ // Extract any credentials embedded in a remote URL's userinfo (`user:pass@host`).
185
+ // Provisioning deliberately preserves author-supplied userinfo in the origin URL,
186
+ // and for such credential-bearing URLs no separate repo token exists — so the URL
187
+ // password would otherwise never be in the checkpoint secret-scan set and a changed
188
+ // file echoing it could enter the readable WIP ref. Returns the password (and
189
+ // username), in BOTH raw and percent-decoded forms, so a file containing either the
190
+ // encoded or decoded credential is excluded. Non-HTTP(S) / userinfo-less URLs yield [].
191
+ export function credentialsFromUrl(url) {
192
+ const s = typeof url === 'string' ? url.trim() : '';
193
+ if (!s) return [];
194
+ let u;
195
+ try { u = new URL(s); } catch { return []; }
196
+ if (!/^https?:$/i.test(u.protocol)) return [];
197
+ const out = new Set();
198
+ for (const raw of [u.password, u.username]) {
199
+ if (!raw) continue;
200
+ out.add(raw);
201
+ try { const dec = decodeURIComponent(raw); if (dec) out.add(dec); } catch { /* leave raw */ }
202
+ }
203
+ return [...out];
204
+ }
205
+
206
+ const truthy = (v) => /^(1|on|true|yes)$/i.test(String(v ?? '').trim());
207
+ const intOr = (v, dflt) => {
208
+ const n = Number.parseInt(String(v ?? ''), 10);
209
+ return Number.isFinite(n) && n >= 0 ? n : dflt;
210
+ };
211
+
212
+ const MODES = new Set(['auto', 'on', 'off']);
213
+ export function checkpointMode(value) {
214
+ const v = String(value ?? '').trim().toLowerCase();
215
+ if (!v) return 'auto';
216
+ if (MODES.has(v)) return v;
217
+ if (truthy(v)) return 'on';
218
+ if (/^(0|false|no|disabled?)$/.test(v)) return 'off';
219
+ return 'auto';
220
+ }
221
+
222
+ export function checkpointConfig(env = process.env) {
223
+ const mode = checkpointMode(env.NANO_AGENT_CHECKPOINT);
224
+ return {
225
+ mode,
226
+ enabled: mode !== 'off',
227
+ minIntervalMs: Math.max(MIN_INTERVAL_FLOOR_MS, intOr(env.NANO_AGENT_CHECKPOINT_MIN_INTERVAL_MS, DEFAULTS.minIntervalMs)),
228
+ // 0 disables the safety-net timer (event-driven + final flush only).
229
+ intervalMs: intOr(env.NANO_AGENT_CHECKPOINT_INTERVAL_MS, DEFAULTS.intervalMs),
230
+ maxFileBytes: intOr(env.NANO_AGENT_CHECKPOINT_MAX_FILE_BYTES, DEFAULTS.maxFileBytes),
231
+ ttlMs: intOr(env.NANO_AGENT_CHECKPOINT_TTL_MS, DEFAULTS.ttlMs),
232
+ gcGraceMs: DEFAULTS.gcGraceMs,
233
+ gcEveryMs: DEFAULTS.gcEveryMs,
234
+ gitTimeoutMs: DEFAULTS.gitTimeoutMs,
235
+ flushTimeoutMs: DEFAULTS.flushTimeoutMs,
236
+ };
237
+ }
238
+
239
+ // Does this remote URL carry its OWN push authentication, independent of a
240
+ // separately-supplied token? Provisioning preserves author-embedded HTTPS
241
+ // userinfo (`https://user:pass@host/…`, kept by `authUrl`) and an SSH remote
242
+ // (`git@host:path` or `ssh://…`) authenticates through the host SSH agent/config.
243
+ // Either can push with NO `repoToken`, so token presence alone under-detects an
244
+ // authenticated clone and would silently skip default-on checkpointing.
245
+ export function isAuthenticatedRemote(url) {
246
+ const s = String(url ?? '').trim();
247
+ if (!s) return false;
248
+ // scp-like SSH syntax `[user@]host:path` (no URL scheme).
249
+ if (/^[^/@]+@[^/:]+:/.test(s)) return true;
250
+ try {
251
+ const u = new URL(s);
252
+ if (u.protocol === 'ssh:') return true;
253
+ if ((u.protocol === 'https:' || u.protocol === 'http:') && (u.username || u.password)) return true;
254
+ } catch { /* not a parseable URL — no embedded auth we can recognize */ }
255
+ return false;
256
+ }
257
+
258
+ // Should this job checkpoint? `auto` only when the job already publishes its work:
259
+ // a provisioned, authenticated clone on a symbolic working branch that pushes.
260
+ export function checkpointEligibility({ mode, provisioned, envelope, token }) {
261
+ if (mode === 'off') return { enabled: false, reason: 'NANO_AGENT_CHECKPOINT=off' };
262
+ if (!provisioned?.workspaceDir) return { enabled: false, reason: 'no provisioned workspace' };
263
+ if (mode === 'on') return { enabled: true, reason: 'NANO_AGENT_CHECKPOINT=on' };
264
+ const push = envelope?.branch?.push;
265
+ if (push === false || /^(false|0|no|off)$/i.test(String(push ?? ''))) return { enabled: false, reason: 'job does not push (branch.push=false)' };
266
+ // Authentication is NOT synonymous with a token: provisioning also authenticates
267
+ // via author-embedded HTTPS userinfo or an SSH remote. Prefer provisioning's own
268
+ // authentication result when it stamped one; else fall back to token presence or
269
+ // recognizing an authenticated remote URL form.
270
+ const authenticated = provisioned?.authenticated === true
271
+ || !!token
272
+ || isAuthenticatedRemote(envelope?.repository?.url);
273
+ if (!authenticated) return { enabled: false, reason: 'anonymous clone (no push credentials)' };
274
+ if (!provisioned.workingBranch) return { enabled: false, reason: 'detached checkout (no working branch)' };
275
+ return { enabled: true, reason: 'auto: job pushes an authenticated working branch' };
276
+ }
277
+
278
+ export function checkpointRef(elementInstanceKey) {
279
+ const key = String(elementInstanceKey ?? '').trim();
280
+ return /^[0-9A-Za-z_-]{1,128}$/.test(key) ? `${CHECKPOINT_REF_PREFIX}${key}` : null;
281
+ }
282
+
283
+ // Never let git invoke the host's configured credential helper for our remote
284
+ // checkpoint ops. The job token is delivered ONLY via GIT_ASKPASS; a configured
285
+ // helper such as `store` would otherwise reuse or PERSIST that token to disk on a
286
+ // push/fetch/delete. Suppress it on EVERY invocation (mirrors the provisioning
287
+ // path's `credential.helper=` at clone/fetch/push) — it is a no-op for local ops,
288
+ // so baking it into the runner guarantees no remote checkpoint op (main runner,
289
+ // scratch-repo delete, or GC sweep) is ever missed. Preserves askpass-only secrets.
290
+ const CRED_SUPPRESS = ['-c', 'credential.helper='];
291
+
292
+ // Async git runner: `git(args, { env?, input? })` → { status, stdout, stderr }.
293
+ // An optional `signal` (AbortSignal) makes the runner CANCELLABLE: once it aborts,
294
+ // any in-flight child is killed and every subsequent invocation fails fast instead
295
+ // of spawning. This lets a bounded background job (e.g. the GC sweep) be TORN DOWN
296
+ // deterministically rather than abandoned to keep running git against a workspace
297
+ // the caller is about to reap.
298
+ export function createGitRunner({ cwd, env = process.env, timeoutMs = DEFAULTS.gitTimeoutMs, killGraceMs = DEFAULTS.gitKillGraceMs, signal } = {}) {
299
+ return (args, opts = {}) => new Promise((resolve) => {
300
+ if (signal?.aborted) {
301
+ resolve({ status: null, stdout: '', stderr: '[aborted]' });
302
+ return;
303
+ }
304
+ let child;
305
+ try {
306
+ // `detached` makes the child a process-group leader on POSIX, so a timeout or
307
+ // abort can signal the WHOLE group (git plus any transport / credential helper
308
+ // it spawned) via a negative pid — a transport that ignores git's own SIGTERM
309
+ // would otherwise keep the stdio pipes open so `close` never fires, stranding
310
+ // the runner past `gitTimeoutMs`.
311
+ child = spawn('git', [...CRED_SUPPRESS, ...args], {
312
+ cwd,
313
+ env: { ...env, ...(opts.env || {}) },
314
+ stdio: ['pipe', 'pipe', 'pipe'],
315
+ detached: process.platform !== 'win32',
316
+ });
317
+ } catch (err) {
318
+ resolve({ status: null, stdout: '', stderr: String(err?.message || err) });
319
+ return;
320
+ }
321
+ let stdout = '';
322
+ let stderr = '';
323
+ let killTimer = null;
324
+ // Signal the child's whole PROCESS GROUP (negative pid, where `detached` made it
325
+ // the leader); fall back to the single pid on Windows or if the group signal
326
+ // fails (e.g. the child already reaped).
327
+ const killGroup = (sig) => {
328
+ const pid = child.pid;
329
+ if (process.platform !== 'win32' && typeof pid === 'number') {
330
+ try { process.kill(-pid, sig); return; } catch { /* fall through */ }
331
+ }
332
+ try { child.kill(sig); } catch { /* already gone */ }
333
+ };
334
+ // Bounded, ESCALATING termination: SIGTERM, then SIGKILL after a grace window if
335
+ // the group is still alive, so the child is guaranteed to exit and `close` fires
336
+ // — the runner settles only once all child I/O has closed, never hangs.
337
+ const terminate = () => {
338
+ killGroup('SIGTERM');
339
+ if (!killTimer) {
340
+ killTimer = setTimeout(() => killGroup('SIGKILL'), opts.killGraceMs ?? killGraceMs);
341
+ killTimer.unref?.();
342
+ }
343
+ };
344
+ const timer = setTimeout(() => { stderr += '\n[timed out]'; terminate(); }, opts.timeoutMs ?? timeoutMs);
345
+ timer.unref?.();
346
+ const onAbort = () => { stderr += '\n[aborted]'; terminate(); };
347
+ signal?.addEventListener?.('abort', onAbort, { once: true });
348
+ child.stdout.on('data', (d) => { stdout += d; });
349
+ child.stderr.on('data', (d) => { stderr += d; });
350
+ child.on('error', (err) => { stderr += String(err?.message || err); });
351
+ child.on('close', (code) => {
352
+ clearTimeout(timer);
353
+ if (killTimer) clearTimeout(killTimer);
354
+ signal?.removeEventListener?.('abort', onAbort);
355
+ resolve({ status: code, stdout, stderr });
356
+ });
357
+ // An `AbortSignal` does NOT replay an abort that already fired: one that lands in
358
+ // the window between the fast-path guard at entry and `addEventListener` above is
359
+ // never delivered to `onAbort`, so the child would otherwise run to its normal
360
+ // timeout — holding a workspace the caller is reaping open for up to `timeoutMs`.
361
+ // Recheck now, with all handlers wired, so a race-landed abort still tears the
362
+ // child down immediately. (`onAbort` is idempotent with the `once` listener.)
363
+ if (signal?.aborted) onAbort();
364
+ if (opts.input != null) child.stdin.end(opts.input); else child.stdin.end();
365
+ });
366
+ }
367
+
368
+ const ok = (r) => r && r.status === 0;
369
+ const out = (r) => (r?.stdout || '').trim();
370
+ // Redact HTTPS/HTTP URL userinfo (`user:pass@host` → `***@host`) before any git
371
+ // diagnostic reaches a log or result. Git echoes the origin URL in some failure
372
+ // messages, and a provisioned remote can carry the token in its userinfo.
373
+ export const redactUrlUserinfo = (s) => String(s).replace(/(https?:\/\/)[^/@\s]+@/gi, '$1***@');
374
+ const errText = (r) => redactUrlUserinfo((r?.stderr || r?.stdout || '').trim()).split('\n').slice(-3).join(' | ').slice(0, 400);
375
+
376
+ // Build a shadow commit of the working tree. Never writes the real index/refs.
377
+ // Returns { sha, tree, head, excluded } or { skipped: reason }.
378
+ export async function snapshotWorktree({ git, baseSha = '', baseRefName = '', runId = '', lastTree = null, maxFileBytes = DEFAULTS.maxFileBytes, secretValues = [], message = 'nano: WIP checkpoint' }) {
379
+ const head = await git(['rev-parse', '--verify', '-q', 'HEAD']);
380
+ // An UNBORN HEAD (a fresh clone of an empty repo, or before the agent's first
381
+ // commit) has no HEAD commit, yet provisioning treats such a clone as pushable —
382
+ // so pre-first-commit WIP is checkpoint-ELIGIBLE and must not be silently dropped.
383
+ // We snapshot the working tree as a PARENTLESS shadow commit (diffed against the
384
+ // empty tree) that `restoreCheckpoint` lays back onto a fresh unborn clone.
385
+ const unborn = !ok(head);
386
+ const headSha = unborn ? '' : out(head);
387
+ // The symbolic branch HEAD is on right now. When HEAD is DETACHED there is no
388
+ // branch, so we record an explicit detached marker (not an omitted trailer):
389
+ // that distinguishes a genuinely off-branch snapshot from a legacy trailerless
390
+ // one, so a later restore refuses to fast-restore it onto the run's work branch
391
+ // (which would otherwise reset the work branch to the detached/off-branch commit).
392
+ const symbolicBranch = out(await git(['symbolic-ref', '--short', '-q', 'HEAD'])) || CHECKPOINT_DETACHED_MARKER;
393
+ const dir = mkdtempSync(join(tmpdir(), 'nano-ckpt-'));
394
+ const env = { GIT_INDEX_FILE: join(dir, 'index') };
395
+ try {
396
+ // For an unborn HEAD there is no HEAD tree to seed from / diff against, so use
397
+ // git's empty tree (computed for the repo's object format). `git read-tree`,
398
+ // `git diff --cached` and the path-limited `git reset` all accept a tree-ish, so
399
+ // the same code path serves born and unborn snapshots with only `baseRef` swapped.
400
+ const emptyTree = out(await git(['hash-object', '-t', 'tree', '--stdin'], { input: '' })) || '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
401
+ const baseRef = unborn ? emptyTree : 'HEAD';
402
+ let r = await git(['read-tree', baseRef], { env });
403
+ if (!ok(r)) return { skipped: `read-tree failed: ${errText(r)}` };
404
+ r = await git(['add', '-A'], { env });
405
+ if (!ok(r)) return { skipped: `add failed: ${errText(r)}` };
406
+
407
+ // AMT (added/modified/type-changed), NOT D: a type change (e.g. a tracked
408
+ // symlink/submodule replaced by a regular file) is staged by `add -A` and
409
+ // enters the written tree, so it must be scanned against the deny-list, size
410
+ // limit and secret-content check too — excluding T would let it bypass them.
411
+ const changed = await git(['diff', '--cached', '--name-only', '--no-renames', '-z', '--diff-filter=AMT', baseRef], { env });
412
+ if (!ok(changed)) return { skipped: `diff failed: ${errText(changed)}` };
413
+ const excluded = [];
414
+ for (const path of changed.stdout.split('\0').filter(Boolean)) {
415
+ let why = isDeniedPath(path) ? 'denied' : null;
416
+ if (!why) {
417
+ const size = await git(['cat-file', '-s', `:${path}`], { env });
418
+ if (maxFileBytes > 0 && ok(size) && Number(out(size)) > maxFileBytes) why = 'too-large';
419
+ else {
420
+ const blob = await git(['cat-file', 'blob', `:${path}`], { env });
421
+ if (!ok(blob)) why = 'unreadable';
422
+ else if (containsSecret(blob.stdout, secretValues)) why = 'secret-content';
423
+ }
424
+ }
425
+ if (why) excluded.push({ path, why });
426
+ }
427
+ if (excluded.length) {
428
+ // Revert excluded paths to their base state in the temp index (drops new ones).
429
+ r = await git(['reset', '-q', baseRef, '--', ...excluded.map((e) => e.path)], { env });
430
+ if (!ok(r)) return { skipped: `exclude failed: ${errText(r)}` };
431
+ }
432
+
433
+ const tree = await git(['write-tree'], { env });
434
+ if (!ok(tree)) return { skipped: `write-tree failed: ${errText(tree)}` };
435
+ const treeSha = out(tree);
436
+ if (lastTree && treeSha === lastTree.tree && headSha === lastTree.head) return { skipped: 'unchanged' };
437
+ const headTree = unborn ? emptyTree : out(await git(['rev-parse', 'HEAD^{tree}']));
438
+ // "Clean" (nothing worth a WIP ref) means the working tree matches HEAD AND the
439
+ // committed state is already safe on the remote. With a known base that is
440
+ // `headSha === baseSha` (HEAD is the base, no local commits). But an EMPTY-base
441
+ // run (`!baseSha`, a fresh clone of an empty repo) is only clean while HEAD is
442
+ // still UNBORN: once the agent lands its first local commit, `treeSha === headTree`
443
+ // again, yet that commit is unpushed — skipping it would lose it if the worker
444
+ // dies before the branch push, so snapshot it (recoverable via the WIP ref).
445
+ if (treeSha === headTree && (baseSha ? headSha === baseSha : unborn)) return { skipped: 'clean' };
446
+
447
+ const trailers = [
448
+ baseSha ? `${CHECKPOINT_BASE_TRAILER}: ${baseSha}` : '',
449
+ // A ref name never contains whitespace, so a single-token value is the only
450
+ // valid shape — guard against anything else so a malformed value can neither
451
+ // inject an extra trailer line nor be silently truncated on read-back.
452
+ /^\S+$/.test(baseRefName) ? `${CHECKPOINT_BASEREF_TRAILER}: ${baseRefName}` : '',
453
+ runId ? `${CHECKPOINT_RUN_TRAILER}: ${runId}` : '',
454
+ symbolicBranch ? `${CHECKPOINT_BRANCH_TRAILER}: ${symbolicBranch}` : '',
455
+ ].filter(Boolean).join('\n');
456
+ const body = `${message}\n\n${trailers}\n`;
457
+ // A born snapshot descends from HEAD; an unborn one is PARENTLESS (there is no
458
+ // HEAD commit) — `restoreCheckpoint` keys the unborn-restore path off that.
459
+ const commit = await git(unborn ? ['commit-tree', treeSha] : ['commit-tree', treeSha, '-p', headSha], { input: body });
460
+ if (!ok(commit)) return { skipped: `commit-tree failed: ${errText(commit)}` };
461
+ return { sha: out(commit), tree: treeSha, head: headSha, excluded };
462
+ } finally {
463
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
464
+ }
465
+ }
466
+
467
+ // Push `sha` to `ref`. `expectSha` is the last sha we believe the remote holds
468
+ // ('' = must not exist). Returns { ok, rejected?, error? }.
469
+ // Why did a push fail?
470
+ // lease — our --force-with-lease expectation was stale (another writer moved the ref)
471
+ // policy — the remote refused it (repository rules, secret push protection, hooks)
472
+ // auth — no permission / bad credentials
473
+ // transient — anything else (network, timeout); worth retrying later
474
+ export function classifyPushFailure(text) {
475
+ const t = String(text ?? '');
476
+ if (/\(stale info\)/i.test(t)) return 'lease';
477
+ if (/remote rejected|GH0\d\d|push protection|repository rule|pre-receive hook|protected ref|declined/i.test(t)) return 'policy';
478
+ if (/permission (to .* )?denied|403|authentication failed|could not read username|invalid username or password|access denied|not authorized/i.test(t)) return 'auth';
479
+ if (/! \[rejected\]/i.test(t)) return 'lease';
480
+ return 'transient';
481
+ }
482
+
483
+ export async function pushCheckpoint({ git, ref, sha, expectSha = '', remote = 'origin' }) {
484
+ const r = await git(['push', '--quiet', '--no-verify', `--force-with-lease=${ref}:${expectSha}`, remote, `${sha}:${ref}`]);
485
+ if (ok(r)) return { ok: true };
486
+ const kind = classifyPushFailure(`${r.stderr}\n${r.stdout}`);
487
+ return { ok: false, kind, rejected: kind === 'lease', error: errText(r) };
488
+ }
489
+
490
+ // Delete `ref`. When `expectSha` is a non-null string the delete is FENCED with
491
+ // `--force-with-lease=<ref>:<expectSha>` so it only removes the ref while it still
492
+ // holds the SHA this run owns: an older activation that finishes after a newer one
493
+ // took over the same element-instance ref can no longer delete the newer worker's
494
+ // recoverable WIP. A lease mismatch (the ref moved on) returns `{ staleLease:true }`
495
+ // and leaves the ref intact for its new owner. `expectSha = ''` demands the ref not
496
+ // exist. `expectSha = null` (default) is the legacy unconditional delete.
497
+ export async function deleteCheckpointRef({ git, ref, remote = 'origin', expectSha = null }) {
498
+ const args = expectSha != null
499
+ ? ['push', '--quiet', '--no-verify', `--force-with-lease=${ref}:${expectSha}`, remote, `:${ref}`]
500
+ : ['push', '--quiet', '--no-verify', remote, `:${ref}`];
501
+ const r = await git(args);
502
+ if (ok(r)) return { ok: true };
503
+ const text = `${r.stderr}${r.stdout}`;
504
+ if (/remote ref does not exist|unable to delete .*not found/i.test(text)) return { ok: true, absent: true };
505
+ if (expectSha != null && classifyPushFailure(text) === 'lease') return { ok: false, staleLease: true, error: errText(r) };
506
+ return { ok: false, error: errText(r) };
507
+ }
508
+
509
+ // Fetch the checkpoint ref. Returns { sha, parent, base } or null when absent.
510
+ export async function fetchCheckpoint({ git, ref, remote = 'origin' }) {
511
+ const r = await git(['fetch', '--quiet', '--no-tags', remote, `+${ref}:${ref}`]);
512
+ if (!ok(r)) {
513
+ if (/couldn't find remote ref|no such ref|not our ref/i.test(`${r.stderr}${r.stdout}`)) return null;
514
+ throw new Error(`fetch ${ref} failed: ${errText(r)}`);
515
+ }
516
+ const sha = out(await git(['rev-parse', '--verify', '-q', `${ref}^{commit}`]));
517
+ if (!sha) return null;
518
+ const parent = out(await git(['rev-parse', '--verify', '-q', `${sha}^1`]));
519
+ const msg = (await git(['log', '-1', '--format=%B', sha])).stdout || '';
520
+ const trailer = (name) => (msg.match(new RegExp(`^${name}:[ \\t]*(\\S+)[ \\t]*$`, 'mi')) || [])[1] || '';
521
+ const base = trailer(CHECKPOINT_BASE_TRAILER);
522
+ return { sha, parent, base: /^[0-9a-f]{7,64}$/.test(base) ? base : '', baseRef: trailer(CHECKPOINT_BASEREF_TRAILER), runId: trailer(CHECKPOINT_RUN_TRAILER), branch: trailer(CHECKPOINT_BRANCH_TRAILER) };
523
+ }
524
+
525
+ // Lay a fetched checkpoint down onto the fresh clone. HEAD stays on the current
526
+ // branch; the snapshot's changes become UNCOMMITTED working-tree changes.
527
+ // `expectedBranchEphemeral` marks the run's working branch as a per-run fallback
528
+ // branch (`nano/agent-work/…-<runId>`), whose name necessarily differs from the
529
+ // snapshot's every activation — a benign rename that must still recover WIP.
530
+ export async function restoreCheckpoint({ git, checkpoint, expectedBranch = null, expectedBranchEphemeral = false, expectedBaseRef = '' }) {
531
+ const { sha, parent, base, branch, runId: snapshotRunId = '', baseRef: snapshotBaseRef = '' } = checkpoint || {};
532
+ if (!sha) return { restored: false, reason: 'no-sha' };
533
+ const head = out(await git(['rev-parse', '--verify', '-q', 'HEAD']));
534
+ const status = await git(['status', '--porcelain']);
535
+ if (!ok(status) || out(status)) return { restored: false, reason: 'workspace-dirty' };
536
+
537
+ // Branch-identity guard (applies to EVERY restore below — parentless OR parentful,
538
+ // born OR unborn clone): a snapshot records the symbolic branch HEAD was on (or an
539
+ // explicit detached marker). If it was taken on a DIFFERENT branch — or DETACHED —
540
+ // relative to this run's expected working branch, recovering it would lay off-branch
541
+ // work into this run's workspace and let a later `finalizeGit` commit/push it to the
542
+ // wrong branch (bypassing branch-mismatch protection). This is true even for a
543
+ // PARENTLESS (unborn) snapshot: an agent can `git checkout -b other` before its first
544
+ // commit, so the snapshot records `other`; restoring its tree onto this run's expected
545
+ // branch and committing it there publishes off-branch WIP just the same. Refuse
546
+ // cross-identity recovery and retain the checkpoint for explicit recovery. (Legacy
547
+ // snapshots carry no branch trailer — `branch` empty — and keep the prior
548
+ // ancestry-only behaviour; the detached marker never equals a real branch name.)
549
+ const branchMismatch = Boolean(branch) && Boolean(expectedBranch) && branch !== expectedBranch;
550
+ // A per-run fallback branch is re-cut with a fresh runId every activation, so its name
551
+ // never matches the snapshot's trailer even though both are ephemeral fallbacks off the
552
+ // SAME base. Validate that benign rename on the generated fallback IDENTITY — but the
553
+ // shared `<base>` alone is NOT proof: an agent can `git checkout` a DIFFERENT generated
554
+ // branch under the same namespace+base (or a base that sanitizes identically), whose
555
+ // off-branch commits must not be patch-restored onto — and then published on — this
556
+ // run's work branch. Provisioning names the branch `nano/agent-work/<base>-<sanitize(runId)>`,
557
+ // so require the snapshot's branch <runToken> to equal the sanitized run-token of the run
558
+ // that WROTE the snapshot (its own `runId` trailer, returned by `fetchCheckpoint`).
559
+ //
560
+ // The sanitized `<base>` segment is AMBIGUOUS — distinct real refs (`feature/foo` vs
561
+ // `feature-foo`) collapse to the same segment — so matching it cannot prove the two
562
+ // fallbacks share a base and a colliding snapshot could be patch-restored onto the wrong
563
+ // branch. Require the UNAMBIGUOUS raw base identity instead: the snapshot's recorded raw
564
+ // `baseRef` trailer must equal this run's `expectedBaseRef`. A snapshot with no baseRef
565
+ // trailer (identity unprovable) can only satisfy this against an equally-empty base — a
566
+ // real (non-empty) base ref never matches an empty one, so an unprovable snapshot is
567
+ // refused rather than restored across a base boundary.
568
+ const snapParts = fallbackBranchParts(branch);
569
+ const expParts = fallbackBranchParts(expectedBranch);
570
+ const fallbackRename = branchMismatch && expectedBranchEphemeral === true
571
+ && snapParts !== null && expParts !== null
572
+ && snapParts.base === expParts.base
573
+ && snapshotBaseRef === expectedBaseRef
574
+ && snapParts.token === sanitizeBranchSegment(snapshotRunId);
575
+ const branchGuardRefused = branchMismatch && !fallbackRename;
576
+
577
+ // A PARENTLESS snapshot was taken on an UNBORN HEAD (pre-first-commit WIP). It can
578
+ // only be laid back onto a still-unborn clone: read its tree into the working tree,
579
+ // then empty the index so the files return as uncommitted (untracked) changes on the
580
+ // unborn branch. No branch pointer moves during the restore, but a later `finalizeGit`
581
+ // commits+pushes the laid-down tree onto this run's expected branch, so the SAME
582
+ // branch-identity guard applies: refuse an off-branch/detached snapshot (a benign
583
+ // per-run fallback rename still passes) so pre-commit off-branch WIP is not published
584
+ // to the wrong branch.
585
+ if (!parent) {
586
+ if (head) return { restored: false, reason: 'unborn snapshot but clone already has commits' };
587
+ if (branchGuardRefused) {
588
+ const where = branch === CHECKPOINT_DETACHED_MARKER ? 'a detached HEAD' : `'${branch}'`;
589
+ return { restored: false, reason: `branch-mismatch (snapshot on ${where}, expected '${expectedBranch}')`, branchMismatch: true };
590
+ }
591
+ let r = await git(['read-tree', '-u', '--reset', sha]);
592
+ if (!ok(r)) return { restored: false, reason: `read-tree failed: ${errText(r)}` };
593
+ r = await git(['read-tree', '--empty']);
594
+ if (!ok(r)) return { restored: false, reason: `unstage failed: ${errText(r)}` };
595
+ return { restored: true, mode: 'unborn', head: '', priorHead: '', commitsRecovered: false };
596
+ }
597
+
598
+ // PARENTFUL snapshot on an UNBORN clone: the prior run made its first local commit(s)
599
+ // on a fresh clone of an (empty) remote — never pushed to the base — then checkpointed,
600
+ // so the snapshot is parentful (its parent is that first commit) while a re-clone of the
601
+ // still-empty remote is unborn again. The fetched WIP ref carries those commits as
602
+ // `parent`'s ancestry; recover them by pointing the (unborn) branch at `parent`, then
603
+ // lay the snapshot tree down as uncommitted changes — instead of unconditionally
604
+ // discarding the fetch as `no-head` and losing the first local commit. Subject to the
605
+ // same branch-identity guard (a genuine off-branch/detached snapshot is left on the ref).
606
+ if (!head) {
607
+ if (branchGuardRefused) {
608
+ const where = branch === CHECKPOINT_DETACHED_MARKER ? 'a detached HEAD' : `'${branch}'`;
609
+ return { restored: false, reason: `branch-mismatch (snapshot on ${where}, expected '${expectedBranch}')`, branchMismatch: true };
610
+ }
611
+ // The clone is UNBORN, so `reset --hard parent` makes the branch BORN — recovering
612
+ // the prior run's first local commit onto it. A FAILURE in the following tree
613
+ // operations must therefore roll the clone back to its pristine unborn+empty state:
614
+ // otherwise a `restored: false` return leaves those recovered commits sitting on the
615
+ // branch, and the caller (which then degrades to transcript-only) would still publish
616
+ // them via finalizeGit — exactly the data the "not restored, ref retained" path is
617
+ // meant to withhold. Capture the unborn branch ref up front so we can detach it again.
618
+ const unbornRef = out(await git(['symbolic-ref', '-q', 'HEAD']));
619
+ const rollbackUnborn = async (reason) => {
620
+ // Detach the (now-born) branch back to unborn and wipe the partially-restored tree.
621
+ let recovered = true;
622
+ if (unbornRef) recovered = ok(await git(['update-ref', '-d', unbornRef])) && recovered;
623
+ recovered = ok(await git(['read-tree', '--empty'])) && recovered;
624
+ recovered = ok(await git(['clean', '-fdq'])) && recovered;
625
+ return recovered
626
+ ? { restored: false, reason }
627
+ : { restored: false, reason: `${reason}; rollback to the pristine unborn state FAILED`, rollbackFailed: true };
628
+ };
629
+ let r = await git(['reset', '-q', '--hard', parent]);
630
+ if (!ok(r)) return rollbackUnborn(`reset failed: ${errText(r)}`);
631
+ r = await git(['read-tree', '-u', '--reset', sha]);
632
+ if (!ok(r)) return rollbackUnborn(`read-tree failed: ${errText(r)}`);
633
+ r = await git(['reset', '-q', parent]);
634
+ if (!ok(r)) return rollbackUnborn(`unstage failed: ${errText(r)}`);
635
+ return { restored: true, mode: 'unborn-parentful', head: parent, priorHead: '', commitsRecovered: true };
636
+ }
637
+
638
+ const fast = !branchMismatch && ok(await git(['merge-base', '--is-ancestor', head, parent]));
639
+ if (fast) {
640
+ let r = await git(['reset', '-q', '--hard', parent]);
641
+ if (!ok(r)) return { restored: false, reason: `reset failed: ${errText(r)}` };
642
+ r = await git(['read-tree', '-u', '--reset', sha]);
643
+ if (!ok(r)) { await git(['reset', '-q', '--hard', head]); return { restored: false, reason: `read-tree failed: ${errText(r)}` }; }
644
+ r = await git(['reset', '-q', parent]);
645
+ if (!ok(r)) { await git(['reset', '-q', '--hard', head]); return { restored: false, reason: `unstage failed: ${errText(r)}` }; }
646
+ return { restored: true, mode: 'fast-forward', head: parent, priorHead: head, commitsRecovered: head !== parent };
647
+ }
648
+
649
+ // A GENUINELY branch-mismatched snapshot (off-branch/detached) must NOT be
650
+ // commit-recovered onto this branch; its work lives only on the ref and is left
651
+ // there for explicit, human recovery. A benign per-run fallback rename instead
652
+ // falls through to the non-reset patch restore below (it never moves the branch).
653
+ if (branchMismatch && !fallbackRename) {
654
+ const where = branch === CHECKPOINT_DETACHED_MARKER ? 'a detached HEAD' : `'${branch}'`;
655
+ return { restored: false, reason: `branch-mismatch (snapshot on ${where}, expected '${expectedBranch}')`, branchMismatch: true };
656
+ }
657
+
658
+ // The fresh clone moved past the prior run's base (e.g. main advanced and the
659
+ // job cuts a per-run fallback branch): replay base→snapshot as a patch. A snapshot
660
+ // with NO base trailer was taken on a clone of an EMPTY remote (no base sha existed):
661
+ // if that remote has since gained its first commit this clone is now born, so rather
662
+ // than refuse (and lose the checkpointed WIP) diff the snapshot against the empty tree
663
+ // — the full snapshot tree becomes an additive patch laid onto the current HEAD (any
664
+ // path the new base commit already introduced is reconciled by `apply --3way`, which
665
+ // still refuses a genuine conflict). The branch guard above already gated this.
666
+ let patchBase = base;
667
+ if (!base) {
668
+ // Empty tree object id for this repo's hash algo, computed cross-platform via
669
+ // `mktree` reading empty stdin (avoids the non-portable `hash-object /dev/null`).
670
+ const mk = await git(['mktree'], { input: '' });
671
+ if (!ok(mk) || !/^[0-9a-f]{7,64}$/.test(out(mk))) return { restored: false, reason: 'diverged (no base trailer; empty-tree unavailable)' };
672
+ patchBase = out(mk);
673
+ }
674
+ const diff = await git(['diff', '--binary', '--full-index', patchBase, sha]);
675
+ if (!ok(diff)) return { restored: false, reason: `diff failed: ${errText(diff)}` };
676
+ if (!diff.stdout.trim()) return { restored: false, reason: 'empty diff' };
677
+ const apply = await git(['apply', '--3way', '--whitespace=nowarn'], { input: diff.stdout });
678
+ if (!ok(apply) || /conflict/i.test(apply.stderr)) {
679
+ await git(['reset', '-q', '--hard', head]);
680
+ await git(['clean', '-fdq']);
681
+ return { restored: false, reason: `patch did not apply cleanly: ${errText(apply)}` };
682
+ }
683
+ await git(['reset', '-q']);
684
+ return { restored: true, mode: base ? 'patch' : 'patch-empty-base', head, priorHead: head, commitsRecovered: false };
685
+ }
686
+
687
+ // Stateful "take a checkpoint now" function bound to one workspace + ref.
688
+ //
689
+ // Ownership: `expectSha` is the remote sha this run took over (the restored
690
+ // checkpoint) and `priorRunId` the run that wrote it. On a lease rejection we
691
+ // re-read the ref: if it was moved by THIS run itself (a transient push error
692
+ // after the server had already accepted our checkpoint left our `remoteSha`
693
+ // stale) we take over from it and re-push. If it was moved by the SAME
694
+ // superseded run (`priorRunId` — a zombie's late abort-flush racing our startup)
695
+ // we must NOT clobber it: that write is independent, newer WIP our divergent
696
+ // workspace does not hold, so we leave the ref intact and retry rather than
697
+ // overwriting it. If it was moved by any other run, a newer owner exists and we
698
+ // stop writing.
699
+ //
700
+ // `startupFetchFailed` marks a BLIND START: the setup-time `fetchCheckpoint`
701
+ // threw, so we hold no `priorRunId` and could not restore the existing ref. An
702
+ // existing ref then rejects our first `--force-with-lease=ref:''` push, but that
703
+ // rejection is NOT proof a newer run owns it — it may simply be the ref we failed
704
+ // to read. Per the documented retry-on-next-trigger contract, treat that initial
705
+ // conflict as RETRYABLE rather than permanently disabling (and never clobber it:
706
+ // blind-clobbering could overwrite a genuinely newer run's WIP). Once we prove the
707
+ // ref's state (a successful push or a legitimate take-over) the blind window ends
708
+ // and a later lease rejection disables normally.
709
+ export function createWorkspaceCheckpoint({ git, ref, baseSha = '', baseRefName = '', runId = '', expectSha = '', priorRunId = '', startupFetchFailed = false, maxFileBytes, secretValues = [], message, now = () => Date.now() }) {
710
+ let lastTree = null;
711
+ let remoteSha = expectSha;
712
+ let disabled = null;
713
+ let established = !startupFetchFailed;
714
+ return async function checkpoint(reason = 'manual') {
715
+ if (disabled) return { skipped: `disabled: ${disabled}` };
716
+ const snap = await snapshotWorktree({ git, baseSha, baseRefName, runId, lastTree, maxFileBytes, secretValues, message: `${message || 'nano: WIP checkpoint'} (${reason})` });
717
+ if (!snap.sha) return snap;
718
+ let pushed = await pushCheckpoint({ git, ref, sha: snap.sha, expectSha: remoteSha });
719
+ if (!pushed.ok && pushed.kind === 'lease') {
720
+ let current = null;
721
+ try { current = await fetchCheckpoint({ git, ref }); } catch { /* treat as foreign */ }
722
+ // Take over ONLY when the ref moved to a checkpoint THIS run itself wrote: a
723
+ // transient push error after the server had already accepted our push leaves our
724
+ // `remoteSha` stale, so re-pushing our own (identical-lineage) snapshot is safe.
725
+ const selfTakeOver = !!(current && runId && current.runId === runId);
726
+ if (selfTakeOver) {
727
+ remoteSha = current?.sha || '';
728
+ pushed = await pushCheckpoint({ git, ref, sha: snap.sha, expectSha: remoteSha });
729
+ } else if (current && priorRunId && current.runId === priorRunId) {
730
+ // The SUPERSEDED run we took over from wrote a NEWER checkpoint after our startup
731
+ // fetch (a zombie's late abort-flush). That ref holds independent, uncommitted WIP
732
+ // (and possibly local commits) our divergent workspace does not contain — a
733
+ // `--force-with-lease` over it would destroy exactly the work this takeover path
734
+ // exists to preserve. Leave the newer ref INTACT and retry on a future trigger
735
+ // rather than overwriting it; never disable (ownership may still legitimately
736
+ // settle, e.g. the zombie finally exits and a later run reconciles).
737
+ return { skipped: `push failed (lease): superseded run ${priorRunId} wrote a newer checkpoint — left intact`, kind: 'lease', rejected: true, retryable: true, disabled: null };
738
+ }
739
+ }
740
+ if (!pushed.ok) {
741
+ // Retrying would fail the same way for everything but a transient error.
742
+ if (pushed.kind === 'lease') {
743
+ if (!established) {
744
+ // Blind start: a transient setup fetch left us unable to read/own the
745
+ // ref. Don't disable — retry on the next trigger (the fetch may recover
746
+ // and a legitimate owner emerge); clobbering could destroy a newer run's WIP.
747
+ return { skipped: `push failed (lease, blind start): ${pushed.error}`, kind: 'lease', rejected: true, retryable: true, disabled: null };
748
+ }
749
+ disabled = 'lease rejected (ref moved by a newer run)';
750
+ }
751
+ else if (pushed.kind === 'policy') disabled = `remote refused the push (repository rule / push protection): ${pushed.error}`;
752
+ else if (pushed.kind === 'auth') disabled = `no permission to push ${ref}: ${pushed.error}`;
753
+ return { skipped: `push failed (${pushed.kind}): ${pushed.error}`, kind: pushed.kind, rejected: pushed.kind === 'lease', disabled: disabled || null };
754
+ }
755
+ lastTree = { tree: snap.tree, head: snap.head };
756
+ remoteSha = snap.sha;
757
+ established = true;
758
+ return { ref, sha: snap.sha, head: snap.head, at: new Date(now()).toISOString(), reason, excluded: snap.excluded };
759
+ };
760
+ }
761
+
762
+ // Is this ACP `session/update` a good moment to snapshot? A completed tool call
763
+ // (edits/commands just finished) or a plan change (a step boundary).
764
+ export function isCheckpointTrigger(update) {
765
+ if (!update || typeof update !== 'object') return false;
766
+ if (update.sessionUpdate === 'plan') return true;
767
+ return update.sessionUpdate === 'tool_call_update' && (update.status === 'completed' || update.status === 'failed');
768
+ }
769
+
770
+ // Rate-limited, serialized scheduler around a `checkpoint(reason)` function.
771
+ // notify(update) — feed ACP session/updates; triggers are coalesced so at most
772
+ // one checkpoint runs per `minIntervalMs` (trailing edge).
773
+ // flush(reason) — run one now (bounded by timeoutMs), after pending work.
774
+ // stop() — clear timers; later notify/flush calls are no-ops.
775
+ export function createCheckpointer({ checkpoint, minIntervalMs = DEFAULTS.minIntervalMs, intervalMs = DEFAULTS.intervalMs, onCheckpoint = null, logger = null, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout }) {
776
+ let lastRunAt = -Infinity;
777
+ let trailing = null;
778
+ let ticker = null;
779
+ let chain = Promise.resolve();
780
+ let running = false;
781
+ let stopped = false;
782
+ const stats = { taken: 0, skipped: 0, failed: 0 };
783
+
784
+ const run = (reason, { force = false } = {}) => {
785
+ // Reserve the run slot SYNCHRONOUSLY, before the async `chain.then` body runs.
786
+ // If several ACP updates arrive in one tick, the first `request()` that lands
787
+ // here flips `running`/`lastRunAt` immediately, so the rest coalesce onto the
788
+ // trailing timer instead of each enqueueing its own checkpoint.
789
+ running = true;
790
+ lastRunAt = now();
791
+ const p = chain.then(async () => {
792
+ if (stopped && !force) { running = false; return null; }
793
+ try {
794
+ const res = await checkpoint(reason);
795
+ if (res?.sha) {
796
+ stats.taken++;
797
+ if (onCheckpoint) { try { await onCheckpoint(res); } catch (err) { logger?.debug?.(`checkpoint onCheckpoint threw: ${err?.message || err}`); } }
798
+ } else {
799
+ stats.skipped++;
800
+ if (res?.disabled) logger?.warn?.(`WIP checkpoints stopped for this job — ${res.disabled}`);
801
+ else if (res?.skipped && !/^(unchanged|clean|disabled: )/.test(res.skipped)) logger?.warn?.(`WIP checkpoint (${reason}) skipped — ${res.skipped}`);
802
+ }
803
+ return res;
804
+ } catch (err) {
805
+ stats.failed++;
806
+ logger?.warn?.(`WIP checkpoint (${reason}) failed — ${err?.message || err}`);
807
+ return null;
808
+ } finally {
809
+ running = false;
810
+ }
811
+ });
812
+ chain = p.catch(() => null);
813
+ return p;
814
+ };
815
+
816
+ const request = (reason) => {
817
+ if (stopped || trailing) return;
818
+ const wait = lastRunAt + minIntervalMs - now();
819
+ if (wait <= 0 && !running) { run(reason); return; }
820
+ trailing = setTimer(() => { trailing = null; run(reason); }, Math.max(0, wait));
821
+ trailing?.unref?.();
822
+ };
823
+
824
+ const scheduleTick = () => {
825
+ if (!intervalMs || stopped) return;
826
+ ticker = setTimer(() => { ticker = null; request('timer'); scheduleTick(); }, intervalMs);
827
+ ticker?.unref?.();
828
+ };
829
+ scheduleTick();
830
+
831
+ const clearAll = () => {
832
+ if (trailing) { clearTimer(trailing); trailing = null; }
833
+ if (ticker) { clearTimer(ticker); ticker = null; }
834
+ };
835
+
836
+ return {
837
+ stats,
838
+ notify(update) { if (isCheckpointTrigger(update)) request(update.sessionUpdate === 'plan' ? 'plan' : 'tool'); },
839
+ async flush(reason = 'final', { timeoutMs = DEFAULTS.flushTimeoutMs } = {}) {
840
+ clearAll();
841
+ stopped = true;
842
+ // Force the run past the post-stop guard AND preserve the caller's reason so
843
+ // an abort/failure flush records `abort`/`failed` (not `final`) in the commit
844
+ // message, logs and `agentCheckpoint.reason`.
845
+ const p = run(reason, { force: true }).then((r) => r, () => null);
846
+ if (!timeoutMs) return p;
847
+ let t;
848
+ const timeout = new Promise((resolve) => { t = setTimer(() => resolve({ skipped: `flush timed out after ${timeoutMs}ms (${reason})` }), timeoutMs); t?.unref?.(); });
849
+ try { return await Promise.race([p, timeout]); } finally { clearTimer(t); }
850
+ },
851
+ // Clear timers and wait for any in-flight checkpoint to finish.
852
+ stop() { clearAll(); stopped = true; return chain; },
853
+ };
854
+ }
855
+
856
+ // ── Orphan GC ────────────────────────────────────────────────────────────────
857
+ // A WIP ref outlives its job when the job never succeeds again (cancelled
858
+ // instance, exhausted retries, deleted definition). Sweep them from any job's
859
+ // clone: delete refs whose snapshot is older than `ttlMs`, and refs older than
860
+ // `graceMs` whose element instance the engine reports terminal. An unknown /
861
+ // unreachable element (404, another engine sharing the repo) is NOT treated as
862
+ // terminal — only the TTL reclaims those.
863
+ const lastSweepAt = new Map();
864
+
865
+ export function shouldSweep(key, { everyMs = DEFAULTS.gcEveryMs, now = Date.now(), registry = lastSweepAt } = {}) {
866
+ const last = registry.get(key);
867
+ if (last != null && now - last < everyMs) return false;
868
+ registry.set(key, now);
869
+ return true;
870
+ }
871
+
872
+ export async function sweepStaleCheckpoints({ git, ownRef = null, ttlMs = DEFAULTS.ttlMs, graceMs = DEFAULTS.gcGraceMs, isTerminal = null, now = () => Date.now(), maxDeletes = 50, maxLookups = 20, remote = 'origin', signal = null }) {
873
+ const ls = await git(['ls-remote', '--refs', remote, `${CHECKPOINT_REF_PREFIX}*`]);
874
+ if (!ok(ls)) return { error: errText(ls), deleted: [] };
875
+ const entries = out(ls).split('\n').filter(Boolean).map((l) => { const [sha, ref] = l.split(/\s+/); return { sha, ref }; }).filter((e) => e.ref && e.ref !== ownRef);
876
+ if (!entries.length) return { scanned: 0, deleted: [] };
877
+ const refs = entries.map((e) => e.ref);
878
+ const local = (r) => `refs/nano-gc/${r.slice(CHECKPOINT_REF_PREFIX.length)}`;
879
+ const fetch = await git(['fetch', '--quiet', '--no-tags', '--no-write-fetch-head', remote, ...refs.map((r) => `+${r}:${local(r)}`)]);
880
+ if (!ok(fetch)) return { error: errText(fetch), deleted: [] };
881
+ const doomed = [];
882
+ let lookups = 0;
883
+ try {
884
+ for (const { ref, sha } of entries) {
885
+ if (doomed.length >= maxDeletes) break;
886
+ // The overall GC deadline (the caller's abort signal) bounds the WHOLE sweep, not
887
+ // just its git ops: each `isTerminal` engine lookup carries its own per-call
888
+ // deadline, so up to `maxLookups` sequential hung lookups could otherwise outlast
889
+ // the overall timeout and keep the awaited `close()` (and the job workspace) alive
890
+ // far past it. Stop scheduling any further lookups/git ops once it fires; unreached
891
+ // refs are reclaimed on a later sweep.
892
+ if (signal?.aborted) break;
893
+ const at = Number(out(await git(['log', '-1', '--format=%ct', local(ref)]))) * 1000;
894
+ if (!Number.isFinite(at) || at <= 0) continue;
895
+ const age = now() - at;
896
+ if (ttlMs > 0 && age > ttlMs) { doomed.push({ ref, sha, why: 'ttl' }); continue; }
897
+ if (isTerminal && age > graceMs && lookups < maxLookups && !signal?.aborted) {
898
+ lookups++;
899
+ let terminal = false;
900
+ try { terminal = await isTerminal(ref.slice(CHECKPOINT_REF_PREFIX.length)); } catch { terminal = false; }
901
+ if (terminal) doomed.push({ ref, sha, why: 'element-terminal' });
902
+ }
903
+ }
904
+ if (!doomed.length) return { scanned: refs.length, deleted: [] };
905
+ // Lease each delete against the SHA we observed at ls-remote time so a newer
906
+ // checkpoint another activation pushed in the meantime is left intact (a lease
907
+ // mismatch skips that one ref rather than race-deleting a live recovery point).
908
+ const deleted = [];
909
+ let lastError = null;
910
+ for (const d of doomed) {
911
+ const r = await deleteCheckpointRef({ git, ref: d.ref, remote, expectSha: d.sha });
912
+ if (r.ok) deleted.push({ ref: d.ref, why: d.why });
913
+ else if (r.error) lastError = r.error;
914
+ }
915
+ const result = { scanned: refs.length, deleted };
916
+ if (!deleted.length && lastError) result.error = lastError;
917
+ return result;
918
+ } finally {
919
+ for (const ref of refs) await git(['update-ref', '-d', local(ref)]);
920
+ }
921
+ }
922
+
923
+ // Prompt note appended when a checkpoint was restored into the workspace.
924
+ export function checkpointRestoredNote(info) {
925
+ if (!info?.restored) return '';
926
+ const lines = [
927
+ '',
928
+ '---',
929
+ 'WORKSPACE RESTORED FROM A WIP CHECKPOINT: a previous attempt at this task was interrupted.',
930
+ 'Its in-progress working tree has been restored into this workspace as UNCOMMITTED changes',
931
+ info.commitsRecovered ? '(its local commits were recovered too — they are on the current branch).' : '(on top of the current branch).',
932
+ 'Before doing anything else, run `git status` and `git diff` to see what was already done,',
933
+ 'then continue from there rather than redoing it. The restored state may include a',
934
+ 'partially written file if the interruption happened mid-edit — verify before relying on it.',
935
+ 'This supersedes any statement above that uncommitted work from the prior run was lost.',
936
+ ];
937
+ return lines.join('\n');
938
+ }
939
+
940
+ export function withCheckpointNote(envelope, info) {
941
+ const note = checkpointRestoredNote(info);
942
+ if (!note || !envelope || typeof envelope !== 'object' || !envelope.task || typeof envelope.task.prompt !== 'string') return envelope;
943
+ return { ...envelope, task: { ...envelope.task, prompt: `${envelope.task.prompt}\n${note}` } };
944
+ }