opencode-model-router 1.13.0 → 1.15.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,2117 @@
1
+ // src/verify/reference.ts
2
+ //
3
+ // ============================================================================
4
+ // DISPATCH REFERENCE AND EPHEMERAL REFERENCE WORKTREE (S2 infrastructure)
5
+ // Design note: task 1.5.1 of docs/plans/verification-resource-budget-plan.md.
6
+ // Implementation: task 1.5.2 (the bodies below are contract stubs until then).
7
+ // Evidence: docs/qa/verification-resource-budget/phase-1.5.md (Spikes D, E,
8
+ // gather) and the 1.5.1 measurements quoted inline ("measured in 1.5.1":
9
+ // git 2.51.0.windows.1, win32, Node v24.21.0).
10
+ // ============================================================================
11
+ //
12
+ // PURPOSE
13
+ // At dispatch, record a cheap, git-only description of the tree the producer
14
+ // started from. No tests run at this point. Later, and only when scoped tests
15
+ // fail, materialize that tree in a throw-away worktree under os.tmpdir() so
16
+ // that the failing test files can be re-run there (S2).
17
+ // The overriding property: nothing here may delete, overwrite or change real
18
+ // data. That covers the user's working tree, the index content, the stash
19
+ // list, refs, other worktrees, and the real node_modules directories we link
20
+ // to.
21
+ // This module never imports node:child_process. Every git run goes through
22
+ // the injected ArgvSeam (task 1.2.2 contract), which provides the timeout,
23
+ // the abort signal and the process-tree kill. Until runArgv (1.2) is merged,
24
+ // the 1.5.3 tests inject a local spawn-based helper defined inside the test
25
+ // file only (env merged over process.env, tree kill on abort or timeout,
26
+ // resolved after the process closed). Contract relied on by cleanup: a
27
+ // seam call resolves only after the process tree has exited.
28
+ //
29
+ // ----------------------------------------------------------------------------
30
+ // 1. WHAT THE REFERENCE CONTAINS (DispatchReference)
31
+ // ----------------------------------------------------------------------------
32
+ // root path.resolve(`git rev-parse --show-toplevel`) run from the
33
+ // dispatch cwd.
34
+ // head `git rev-parse --verify HEAD^{commit}` at capture.
35
+ // commit Output of `git stash create` when it is non-empty. That is a
36
+ // commit whose tree holds the working-tree state of every TRACKED
37
+ // file, staged and unstaged; untracked files are excluded
38
+ // (Spike E). When the output is empty (tracked tree clean, per
39
+ // Spike E), commit = head.
40
+ // untracked Map<relPath, sha256 hex> over every untracked, NOT ignored file,
41
+ // from `git ls-files --others --exclude-standard --full-name -z`
42
+ // run at root. relPath uses git's form: forward slashes,
43
+ // root-relative. The value is the sha256 of the file bytes. An
44
+ // untracked symbolic link gets the value UNTRACKED_SYMLINK and is
45
+ // never reproduced. This module computes the per-file hashes
46
+ // itself: snapshotTree (tree.ts) keeps only one aggregate hash
47
+ // over all untracked files (spike gather notes).
48
+ // tracked Map<relPath, sha256 hex> of the LIVE bytes of every tracked
49
+ // path that differs between head and commit and is a regular
50
+ // file at capture (section 2e). Empty when commit = head.
51
+ // captureReasons InexactReasons found at capture (section 2f).
52
+ // capturedAt now() when the capture resolved.
53
+ // Ignored content (node_modules, dist, .env, ...) is NOT part of the
54
+ // reference. At materialize, node_modules directories are linked from the
55
+ // live tree (section 5). Any other ignored entry is simply absent from the
56
+ // reference worktree and is listed in `unreproduced`.
57
+ //
58
+ // ----------------------------------------------------------------------------
59
+ // 2. EXACT VS APPROXIMATE (§1.5-7, extended by D3)
60
+ // ----------------------------------------------------------------------------
61
+ // A materialized reference is EXACT only when all of the following hold:
62
+ // (a) Every dispatch-time untracked file still exists in the live tree as a
63
+ // regular file with the recorded sha256, and was written into the
64
+ // worktree. A modified, deleted or unreadable file makes the reference
65
+ // approximate (§1.5-7).
66
+ // (b) No untracked symbolic link was recorded (links are never reproduced).
67
+ // (c) No dependency drift: no DEPENDENCY_FILES entry, in any directory,
68
+ // differs between `commit` and the live tree. node_modules is linked
69
+ // from the LIVE tree, so it matches the reference only if the manifests
70
+ // and lockfiles do.
71
+ // (d) No workspace-link drift. A linked node_modules may hold a package link
72
+ // that resolves into the live repository outside any node_modules
73
+ // segment (npm/pnpm/yarn workspaces, e.g. node_modules/@s/a ->
74
+ // packages/a). If that target directory contains a path that differs
75
+ // between `commit` and the live tree, an import through the link would
76
+ // load CURRENT code at the reference, so exact is false. Detection: for
77
+ // each linked node_modules, readdir its top level plus one level under
78
+ // each `@scope` directory, lstat each entry, and realpath every link.
79
+ // (e) The checkout reproduces the live bytes (QA-1.5-6a). The stash commit
80
+ // stores normalized blobs, and checkout converts them again, so the
81
+ // reference can differ from the live tree byte for byte: with
82
+ // core.autocrlf=true live "x\n" became "x\r\n"; with input, a dirty
83
+ // CRLF file became LF; `text`/`eol`/`filter` attributes do the same.
84
+ // Three checks: core.autocrlf set to anything but false (true, input,
85
+ // yes, on, 1) at materialize adds "checkout-conversion" with path ""
86
+ // (it also affects files git reports as clean); every entry of
87
+ // `tracked` must hash equal to the checked-out file, otherwise
88
+ // "checkout-conversion" with that path; and, for files git reports as
89
+ // CLEAN (QA-1.5-13), the working-tree eol class (`w/` column of
90
+ // `git ls-files --eol -z`: lf, crlf, mixed, none, -text) must be the
91
+ // same in root and dir for every tracked path that is neither in
92
+ // `tracked` nor changed since the commit (section 4 step 7b; the full
93
+ // listing, QA-1.5-18: a clean file's live bytes come from its LAST
94
+ // checkout, e.g. under an older core.autocrlf, a legacy `crlf`
95
+ // attribute or a working-tree-encoding added later, so no attribute
96
+ // pathspec can limit it). A path changed since the commit but not in
97
+ // `tracked` (edited after capture, QA-1.5-16) is flagged when the
98
+ // reference's own `w/` class differs from its `i/` class. QA's
99
+ // repro: `* text=auto`, core.autocrlf=false, core.eol unset (native
100
+ // CRLF on win32), live "a0\n" and `git status` clean; the reference got
101
+ // "a0\r\n" while exact stayed true. LF files under text=auto are common
102
+ // on win32 (e.g. Prettier's default endOfLine: lf). Each differing path
103
+ // adds "checkout-conversion" for it, up to MAX_CONVERSION_REASONS, then
104
+ // one "" reason.
105
+ // (f) No index entry is assume-unchanged or skip-worktree at capture
106
+ // (QA-1.5-6b). Git skips such entries, so neither stash create nor the
107
+ // drift diff sees a local edit to them (live "v2-local" became "v1" at
108
+ // the reference, exact: true). `git ls-files -v` tags them with a
109
+ // lowercase letter or `S`; the first such path (sorted) adds one
110
+ // "index-flags" reason, recorded in captureReasons.
111
+ // Each violation adds one InexactReason; exact === (inexactReasons.length ===
112
+ // 0). An approximate reference never excuses a failure: the recheck (2.x)
113
+ // turns a reference-side failure of an approximate reference into
114
+ // `unverifiable` (§1.5-7).
115
+ // "Differs between commit and the live tree" means the union of:
116
+ // - `git diff --name-only -z --no-renames --no-ext-diff <commit> --`
117
+ // (tracked paths; --no-renames lists both sides of a rename);
118
+ // - untracked paths now present (`git ls-files --others --exclude-standard
119
+ // -z`) that are missing from `untracked` or whose hash differs.
120
+ // Exactness makes no claim about ignored content. `unreproduced` lists the
121
+ // ignored entries that exist in the live tree but are absent from the
122
+ // worktree (e.g. `.env`, `dist/`), so that the recheck can classify setup
123
+ // failures (§1.5-8). An untracked file created after dispatch is not part of
124
+ // the reference: it is never copied and does not affect exactness.
125
+ //
126
+ // ----------------------------------------------------------------------------
127
+ // 3. CAPTURE captureReference(cwd, signal, deps) -> DispatchReference | undefined
128
+ // ----------------------------------------------------------------------------
129
+ // Budget: deps.timeoutMs (default DEFAULT_CAPTURE_TIMEOUT_MS, which equals the
130
+ // baselineTimeoutMs default of 15000). Each git call gets
131
+ // timeoutMs = min(remaining budget) and the caller's signal, except
132
+ // `stash create` (step 4), which gets the timeout only. File reads use
133
+ // AbortSignal.any([signal, AbortSignal.timeout(remaining)]).
134
+ // Every git call in this module runs as `git --no-optional-locks ...`
135
+ // (QA-1.5-2), so a read-only call never refreshes, and so never rewrites,
136
+ // the user's index.
137
+ // 1. `git rev-parse --show-toplevel` (cwd: the dispatch cwd) -> root. A
138
+ // non-zero exit (outside a repository, or a bare repository) returns
139
+ // undefined.
140
+ // 2. `git ls-files --stage` (cwd: root). Any line starting "160000 " (a
141
+ // gitlink, i.e. a submodule) returns undefined. This is the same refusal
142
+ // snapshotTree makes (tree.ts). Then `git ls-files -v -z`: the first
143
+ // assume-unchanged or skip-worktree path adds "index-flags" to
144
+ // captureReasons (section 2f).
145
+ // Scale limit (QA-1.5-24): a listing cut at the seam's output cap is a
146
+ // failed call (QA-1.5-21), so capture returns undefined. `ls-files
147
+ // --stage` costs 51 + path chars per entry (75 under SHA-256), more than
148
+ // `--eol`, so at the default 10 M-char cap it fails first: a repository
149
+ // with more than ~95-150k tracked paths gets NO reference (fail closed:
150
+ // the recheck is unverifiable), not the "" fallback of step 7b.
151
+ // 3. `git rev-parse --verify HEAD^{commit}` -> head. Failure (e.g. an unborn
152
+ // branch) returns undefined.
153
+ // 4. `git stash create` on a PRIVATE INDEX (QA-1.5-1/2) -> trimmed stdout.
154
+ // Empty means commit = head. A 40- or 64-character hex SHA becomes
155
+ // commit. Anything else, or a non-zero exit (e.g. an unmerged index),
156
+ // returns undefined.
157
+ // - `git rev-parse --git-path index` names the index file (the
158
+ // per-worktree one in a linked worktree). Its bytes are read with
159
+ // fs.readFile and written (mode 0o600, flag "wx") to <scratch>/index,
160
+ // and the copy gets the original's mtime (floored to ms). Git's
161
+ // racy-git check compares entry mtimes with the index FILE's mtime; a
162
+ // fresh copy's later mtime made git trust stale stat data and miss a
163
+ // same-size edit made in the index's second (found while fixing
164
+ // QA-1.5-1: the stash commit and the drift diff lost such edits).
165
+ // scratch is a fresh omr-ref-<pid>-<16 hex> dir, made with
166
+ // mkdir(0o700) directly under realpath(deps.tmpdir ?? os.tmpdir())
167
+ // after assertSafeRefDir (R3), and kept in the in-use set meanwhile.
168
+ // - `git -c core.splitIndex=false stash create` then runs with env
169
+ // GIT_INDEX_FILE=<scratch>/index. Git takes its mandatory index lock,
170
+ // and writes its temporary `<index>.stash.<pid>`, next to the COPY.
171
+ // core.splitIndex=false makes git write the copy as one file, never a
172
+ // new sharedindex.* inside .git.
173
+ // - This one call gets the remaining budget as its timeout but NOT the
174
+ // caller's signal: an abort must not kill git while it holds a lock.
175
+ // If the caller aborted meanwhile, the result is discarded. A timeout
176
+ // kill can still strand a lock, but only on the copy.
177
+ // - The scratch dir is removed in a finally block by the section 6
178
+ // pipeline without its git steps. If that fails, the dir is left for
179
+ // GC, which treats it as an orphan without a .git file (section 11).
180
+ // Measured by QA on this host: the same tree as a plain `stash create`,
181
+ // and 0/120 producer `git add` failures against a capture loop, versus
182
+ // 27/120 when stash create shared the user's index.
183
+ // Then, when commit != head: `git diff-tree -r -z --name-only
184
+ // --no-renames <head> <commit>` lists the dirty tracked paths. Each is
185
+ // checked against the RELPATH rules (a violation returns undefined),
186
+ // lstat'ed, and, if it is a regular file, read and hashed into
187
+ // `tracked` (section 2e). A deleted path or a non-file is skipped. The
188
+ // MAX_UNTRACKED_FILES / MAX_UNTRACKED_BYTES caps apply to this set on
189
+ // its own, as to the untracked set; exceeding them returns undefined.
190
+ // 5. `git ls-files --others --exclude-standard --full-name -z` (cwd: root).
191
+ // For each path, in sorted order: apply the RELPATH rules (section 10),
192
+ // then lstat. A regular file is read (with the signal) and hashed with
193
+ // sha256; a symlink gets UNTRACKED_SYMLINK; anything else returns
194
+ // undefined (as snapshotTree does). Exceeding MAX_UNTRACKED_FILES files or
195
+ // MAX_UNTRACKED_BYTES bytes returns undefined. This guards against temp-
196
+ // dir exhaustion; the usual cause is a missing node_modules ignore rule.
197
+ // 6. If the signal is aborted or the budget is spent at any point, return
198
+ // undefined. Every error returns undefined. The function never throws.
199
+ // Effects on the repository. Acceptance requires working tree, index,
200
+ // stash list and refs to be unchanged; tests assert this with git status,
201
+ // git stash list and git for-each-ref before and after:
202
+ // - No ref is created (no pinning; see section 8 and D1).
203
+ // - `git stash create` writes unreferenced loose objects: the stash commit,
204
+ // its index commit, trees and blobs. `git gc` may later prune them.
205
+ // - The user's index file is never written and its lock is never taken.
206
+ // `git stash create` refreshes the stat cache of the index it works on
207
+ // (measured in 1.5.1 on the shared index: "index bytes changed=True"),
208
+ // and that refresh needs the MANDATORY index lock. On the shared index, a
209
+ // tree kill during that window left .git/index.lock behind in 9 of 10 QA
210
+ // runs, and every later git write in the user's repository failed until
211
+ // the lock was removed by hand (QA-1.5-1). With the private copy, the
212
+ // refresh, the lock and the temporary stash index all live in scratch.
213
+ // - An abort or timeout mid-capture leaves nothing in the repository but
214
+ // such unreferenced objects (at most, a git object write interrupted by a
215
+ // timeout kill leaves a tmp_obj_* file, which git gc removes).
216
+ // Consistency: the capture is not atomic. Tracked state is taken at step 4
217
+ // and untracked state at step 5. Under §1.5-14 the caller (2.x) discards a
218
+ // capture that resolves after an edit was observed in an overlapping
219
+ // directory.
220
+ //
221
+ // ----------------------------------------------------------------------------
222
+ // 4. MATERIALIZE materialize(ref, currentTree, signal, deps) -> MaterializeResult
223
+ // ----------------------------------------------------------------------------
224
+ // Never throws. If anything fails after step 3 creates the worktree, the
225
+ // dispose pipeline (section 6) runs before { ok: false } is returned, so an
226
+ // abort leaves no partial state. Budget: deps.timeoutMs (default
227
+ // DEFAULT_MATERIALIZE_TIMEOUT_MS) and the caller's signal.
228
+ // 0. currentTree is optional. If given, currentTree.cwd must lie inside
229
+ // ref.root; otherwise return ok:false "error" (wrong repository). It is
230
+ // never used to decide exactness, because TreeSnapshot has no per-file
231
+ // hashes (gather notes). Every file is re-read instead.
232
+ // 1. `git cat-file -e <commit>^{commit}` (cwd: root). If the commit is
233
+ // missing, return ok:false "commit-missing": the unreferenced stash commit
234
+ // was pruned (section 8).
235
+ // 2. tmp = realpath(deps.tmpdir ?? os.tmpdir()), long form. Measured in
236
+ // 1.5.1: git stores and lists worktree paths in long form with forward
237
+ // slashes ("C:/Users/Marquinho/AppData/..."), even when TEMP is an 8.3
238
+ // short path. dir = tmp/<refDirName(pid, 16 random hex)>. Call
239
+ // assertSafeRefDir(dir) before anything is created. Add dir to the
240
+ // process-wide ACTIVE set, which gcStaleReferences skips (section 11),
241
+ // and start the heartbeat once the dir exists. Then
242
+ // mkdir(dir, { mode: 0o700 }), non-recursive (QA-1.5-10): EEXIST returns
243
+ // ok:false "unsafe-path" and nothing is cleaned up. On POSIX,
244
+ // chmod(dir, 0o700) follows, so the mode is exact whatever the umask.
245
+ // The dir is private BEFORE git writes the first tracked byte into it.
246
+ // 3. `git -c core.hooksPath=<tmp>/omr-nohooks-<16 random hex>
247
+ // -c advice.detachedHead=false worktree add --detach --lock --reason
248
+ // <referenceLockReason(pid)> <dir> <commit>` (cwd: root, env LC_ALL=C so
249
+ // git's own messages and the fallback's "initializing" lock reason stay
250
+ // untranslated). The lock lasts the reference's whole life (QA-1.5-12,
251
+ // D10): its junctions lead into the LIVE node_modules, and a user's or an
252
+ // IDE's `git worktree remove [--force]` on an unlocked entry would empty
253
+ // them (Spike D method 5). git refuses a locked entry unless given
254
+ // `-f -f`, and prints our reason. Per git's add_worktree, the `locked`
255
+ // file holds our reason from the start ("initializing" is written only
256
+ // without --lock), is kept after a successful checkout, and is removed if
257
+ // the add fails. `add --reason` needs git >= 2.33 (release notes: "git
258
+ // worktree add --lock learned to record why the worktree is locked").
259
+ // Older git fails in its option parser ("unknown option `reason'")
260
+ // before writing anything: the dir is checked to be still empty, a
261
+ // warning is logged, and the add is repeated without --lock (the pre-fix
262
+ // behaviour: an unlocked entry). Git accepts the existing empty dir. The hooks path is
263
+ // checked to be absent and is never created, and it lies OUTSIDE the
264
+ // worktree, so post-checkout hooks (repository code) never run
265
+ // (QA-1.5-8: the former `<dir>/.omr-no-hooks` was inside the worktree,
266
+ // and a committed `.omr-no-hooks/post-checkout` ran during
267
+ // materialize). Clean/smudge filters such as LFS still run, within the
268
+ // budget. Failure returns ok:false "worktree-add-failed". Once the
269
+ // worktree exists, its HEAD pins the commit against gc (Spike E).
270
+ // 3b. Byte-exactness (section 2e/2f): start from ref.captureReasons; run
271
+ // `git config --get core.autocrlf` (cwd: root); then, for each
272
+ // [rel, hash] of ref.tracked in sorted order, lstat and hash dir/rel.
273
+ // A missing file, a non-file, a hash mismatch or an unsafe rel adds
274
+ // "checkout-conversion" for rel.
275
+ // 4. Copy untracked files, for each [rel, hash] in ref.untracked, in sorted
276
+ // order:
277
+ // - rel fails the RELPATH rules -> inexact "untracked-unsafe-path".
278
+ // hash === UNTRACKED_SYMLINK -> inexact "untracked-symlink".
279
+ // - lstat(root/rel): ENOENT -> "untracked-deleted"; not a regular file ->
280
+ // "untracked-not-file"; read error -> "untracked-unreadable".
281
+ // - bytes = readFile(root/rel). sha256(bytes) !== hash ->
282
+ // "untracked-modified".
283
+ // - dest = dir/rel. mkdir -p the parent, then check that realpath(parent)
284
+ // is strictly inside dir (isStrictlyInside). Write with
285
+ // writeFile(dest, bytes, { mode: stat.mode & 0o777, flag: "wx" }).
286
+ // The same buffer that was hashed is the one written, so the check and
287
+ // the copy cannot disagree. "wx" never overwrites and never writes
288
+ // through an existing link.
289
+ // 5. Discovery: `git ls-files --others --ignored --exclude-standard
290
+ // --directory -z` (cwd: root). Measured in 1.5.1 with node_modules/,
291
+ // .env and legacy/ ignored, the output was [.env] [legacy/]
292
+ // [node_modules/] [packages/a/node_modules/]. The ignored parent legacy/
293
+ // is collapsed, so its nested node_modules is not listed, and that parent
294
+ // is absent from the worktree anyway. Entries whose last segment is
295
+ // `node_modules` are link candidates (section 5). All other entries go to
296
+ // `unreproduced`. Nothing ignored is ever copied.
297
+ // 6. Link each candidate (section 5), parents before children. Git's sorted
298
+ // output already puts them in that order.
299
+ // 7. Drift checks (c) and (d) of section 2 (two git calls, cwd: root). The
300
+ // drift `git diff` runs on a private index copy, exactly like stash
301
+ // create (section 3 step 4, with the caller's signal here). Porcelain
302
+ // `git diff <commit>` rewrote .git/index after a stat-only change
303
+ // (QA-1.5-2), and re-measured while fixing it, it STILL did so under
304
+ // --no-optional-locks: its closing refresh_index_quietly() takes the
305
+ // index lock whenever it is free, whatever GIT_OPTIONAL_LOCKS says.
306
+ // 7b. Clean-file conversion (section 2e, QA-1.5-13), skipped when a ""
307
+ // "checkout-conversion" reason (core.autocrlf) is already recorded:
308
+ // `git ls-files --eol -z` at root and at dir, run concurrently
309
+ // (the cost of QA-1.5-17; QA-1.5-18: no pathspec limit is sound).
310
+ // A path in both lists, not in ref.tracked and
311
+ // not in the drift set of step 7, whose `w/` class differs adds
312
+ // "checkout-conversion" for it. A path in the drift set but not in
313
+ // ref.tracked (edited after capture, QA-1.5-16) has unknown dispatch
314
+ // bytes, so it adds "checkout-conversion" when the reference's own `w/`
315
+ // class differs from its `i/` class (the checkout converted it). This is
316
+ // the last step, so these calls get the
317
+ // remaining budget with the caller's signal only: a budget that runs out
318
+ // here, or a failing call, adds "" instead of failing materialize; a
319
+ // caller abort returns ok:false "aborted".
320
+ // 8. Return { ok: true, reference: { dir, exact, inexactReasons,
321
+ // unreproduced, links, toRefPath, dispose } }. toRefPath(p) maps an
322
+ // absolute live path under root, or under realpath(root), to the same
323
+ // relative path under dir, or returns undefined when p is outside both.
324
+ // The recheck uses it for the runner cwd and the failing test files, which
325
+ // the planner canonicalises with the native realpath (E2E-2: a root
326
+ // reached through an 8.3 name, a junction or a subst drive is spelled
327
+ // differently by git and by realpath).
328
+ // Repository effects of materialize, dispose and GC: they write only the
329
+ // admin entry .git/worktrees/<name> and the dir itself. The main index
330
+ // content, the refs and the stash list are never touched.
331
+ //
332
+ // ----------------------------------------------------------------------------
333
+ // 5. LINK STRATEGY (every ignored node_modules: the root and each workspace package)
334
+ // ----------------------------------------------------------------------------
335
+ // For each candidate relPath R from discovery (step 5):
336
+ // - src = root/R. lstat(src) must be a directory or a link. target =
337
+ // realpath(src), and lstat(target) must be a real directory. Otherwise
338
+ // skip R.
339
+ // - linkPath = dir/R. Its parent must already exist in the worktree as a real
340
+ // directory (lstat, not a link). Links never get a mkdir: a package that
341
+ // does not exist at the reference gets no node_modules. linkPath itself
342
+ // must not exist (lstat returns ENOENT), so a tracked node_modules is left
343
+ // alone.
344
+ // - Push linkPath onto `links` BEFORE creating the link. dispose lstat-checks
345
+ // every entry, so a recorded link that was never created is harmless.
346
+ // - win32: fs.symlink(target, linkPath, "junction"). Junctions need an
347
+ // absolute target and no privilege, and can cross local volumes (e.g. a
348
+ // D:\ repo and a C:\ temp dir). POSIX: fs.symlink(target, linkPath,
349
+ // "dir"). Spike D: lstat().isSymbolicLink() is true for junctions made
350
+ // either way, which is the basis of every removal check.
351
+ // - Links point at LIVE, shared state. Tests at the reference that write into
352
+ // node_modules (vite/jest caches, .cache) write into the real directory.
353
+ // That is cache data, not source; the runner adapter may redirect caches.
354
+ // Only node_modules is linked. Python virtualenvs are NOT linked: an editable
355
+ // install points at the live tree's sources and would make the reference
356
+ // silently run current code (see OPEN RISKS).
357
+ //
358
+ // ----------------------------------------------------------------------------
359
+ // 6. DISPOSE handle.dispose() -> Promise<void>
360
+ // ----------------------------------------------------------------------------
361
+ // Idempotent: the promise is memoised, so every call returns the first
362
+ // call's promise. It never rejects: every failure goes to logger.warn and
363
+ // the leftover is left for GC. Contract: call it only after the recheck's
364
+ // process tree has exited. It does not use the caller's signal, because
365
+ // cleanup must still run after an abort.
366
+ // Order: unlink-first as in Spike D method 8, plus a sweep (D6), but git
367
+ // never deletes a tree (QA-1.5-3):
368
+ // 1. Recorded links, in reverse order. Check isStrictlyInside(link, dir),
369
+ // then lstat. ENOENT: skip. isSymbolicLink(): fs.unlink, retrying
370
+ // transient errors. A real file or directory at that path is worktree
371
+ // content: leave it for the later steps.
372
+ // 2. Link sweep. Walk dir with lstat, never descending into a link (the
373
+ // worktree's `.git` is a file), and fs.unlink every link found. Before
374
+ // each readdir, realpath(current) must be dir's realpath or inside it,
375
+ // so a real directory swapped for a junction after its lstat is not
376
+ // walked into (the race window shrinks to realpath..readdir). Tests can
377
+ // create links, and `git worktree remove --force` follows junctions and
378
+ // DELETES TARGET CONTENTS (Spike D, BANNED list). If a link survives step
379
+ // 1 or 2, or the walk exceeds MAX_SWEEP_ENTRIES, STOP: nothing more is
380
+ // removed. Warn "reference worktree left in place: <reason>"; GC retries
381
+ // later.
382
+ // 3. Run assertSafeRefDir(dir) and confirm lstat(dir) is a real directory.
383
+ // Then fs.rm(dir, { recursive: true, force: true, maxRetries: 0 }) inside
384
+ // the module's flat retry loop (see below): Spike D SAFE #5, the only
385
+ // recursive deleter. fs.rm removes a link without following it,
386
+ // so a junction created after the sweep costs nothing (QA-1.5-3 repro:
387
+ // `git worktree remove` in this slot deleted the late junction's target
388
+ // contents; fs.rm left them intact). The sweep stays, because fs.rm's
389
+ // non-following is proven only on Node v24.21.0 and engines is >=20. If
390
+ // dir still exists afterwards (EBUSY from a process whose cwd is inside),
391
+ // warn and leave it for GC; git is not run.
392
+ // 4. Only once dir is gone, and while the admin entry is still registered:
393
+ // assertSafeRefDir(dir), lstat(dir) must be ENOENT, then
394
+ // `git worktree remove --force <dir>` (cwd: root, timeout
395
+ // CLEANUP_GIT_TIMEOUT_MS). Measured in 1.5.1: on an already-deleted dir
396
+ // it exited 0 and removed only that entry, with no recursion;
397
+ // `git worktree prune -v` afterwards found nothing. `git worktree prune`
398
+ // is never run (D5). Residual race: a dir recreated between that lstat
399
+ // and git's own check would be deleted by git; only this module creates
400
+ // omr-ref names, under an in-use entry.
401
+ // A locked entry makes `remove --force` fail. Our entry is locked with
402
+ // referenceLockReason(<pid of its name>) for its whole life (step 3,
403
+ // QA-1.5-12). The git < 2.33 fallback adds without --lock, and git then
404
+ // locks the entry with "initializing" until its checkout ends, so a tree
405
+ // kill mid-checkout leaves that lock forever (QA-1.5-5). If the entry's
406
+ // lock reason is exactly one of those two, and the caller allows it
407
+ // (materialize's own handle and cleanup; GC per section 11 step 2),
408
+ // `git worktree unlock <dir>` runs first: here, only after the dir is
409
+ // gone and R3 passed, so the junctions are unprotected by the lock only
410
+ // once they no longer exist. Any other lock reason (including an omr
411
+ // reason naming another pid) is someone else's: warn, keep the entry.
412
+ // Our own `worktree add` runs with LC_ALL=C, so "initializing" is never
413
+ // translated.
414
+ // 0. (Before step 1) stop the heartbeat (section 11).
415
+ // 5. Remove dir from ACTIVE. If any step failed, add it to RELEASED, so
416
+ // that this process's next GC collects it without waiting for the age
417
+ // rule (section 11).
418
+ // Transient errors (TRANSIENT_FS_CODES: EBUSY, EPERM, EACCES, ENOTEMPTY,
419
+ // caused by Windows AV scans or open handles) are retried up to
420
+ // CLEANUP_RETRIES times with CLEANUP_RETRY_BASE_MS * 2^n backoff, then
421
+ // logged, and the leftover is left for GC. They are never treated as
422
+ // success. If dir was deleted externally, every step tolerates ENOENT.
423
+ // There is ONE flat retry loop (withRetry); fs.rm itself runs with
424
+ // maxRetries: 0 (QA-1.5-11). Node's JS fs.promises.rm retries inside every
425
+ // recursive child call, so its own retries nest once per directory level
426
+ // above a held dir: T(d) ~ 6*T(d-1) + 1.5 s, measured by QA as 11 s at one
427
+ // level and 66 s at two (about 6.5 min at three, extrapolated). The flat
428
+ // loop costs about 3.1 s of backoff at any depth. GC passes its deadline:
429
+ // no retry starts after GC's budget is spent, and step 4 is then skipped
430
+ // (the dir is gone and the entry is collected by the next GC).
431
+ //
432
+ // ----------------------------------------------------------------------------
433
+ // 7. REMOVAL RULES (normative; QA checks every destructive call against them)
434
+ // ----------------------------------------------------------------------------
435
+ // R1 Every removal is preceded by an lstat check. A link is only ever removed
436
+ // with fs.unlink, which is single-entry and never recursive.
437
+ // R2 A recursive removal (fs.rm with recursive; nothing else) is allowed
438
+ // only on a path that (i) passed assertSafeRefDir immediately before,
439
+ // (ii) lstat shows is a real directory, not a link, and (iii) the sweep
440
+ // proved link-free. `git worktree remove --force` is only ever run on a
441
+ // dir that passed assertSafeRefDir and that lstat shows is gone, so it
442
+ // only drops the admin entry (QA-1.5-3).
443
+ // R3 assertSafeRefDir(dir, tmpRoots) accepts dir only if it is absolute,
444
+ // has no "." or ".." segment, its basename matches REF_DIR_PATTERN
445
+ // (omr-ref-<pid>-<16 hex>), and its parent IS one of the tmp roots:
446
+ // resolve(tmpdir) or realpath(tmpdir), compared case-insensitively on
447
+ // win32. It must be a direct child: never the tmp root itself, never
448
+ // deeper, and never under a tmp root that is a filesystem root.
449
+ // R4 Banned in this module: `git worktree remove` on a dir that exists,
450
+ // `git worktree unlock` of anything but an R3-valid omr-ref entry whose
451
+ // dir lstat shows is gone and whose lock reason is exactly
452
+ // referenceLockReason(<pid of its name>) or "initializing" (section 6
453
+ // step 4), `git worktree add` without --lock --reason except the
454
+ // git < 2.33 fallback (section 4 step 3),
455
+ // `git worktree prune`, `git clean`, any `git stash` other than `create`,
456
+ // `git reset/checkout/update-ref/gc`, fs.rm on a path that fails R2, any
457
+ // shell, and importing child_process.
458
+ //
459
+ // ----------------------------------------------------------------------------
460
+ // 8. THE UNREFERENCED STASH COMMIT (GC risk; D1)
461
+ // ----------------------------------------------------------------------------
462
+ // Spike E suggested pinning the commit with a ref, but that would violate the
463
+ // capture acceptance criterion "refs unchanged", so no ref is created.
464
+ // Protection comes from `git gc` itself: it prunes unreachable loose objects
465
+ // only once they are older than gc.pruneExpire (default 2 weeks), far beyond
466
+ // pendingTtlMs (1 h). Residual risk: a manual `git gc --prune=now`, or
467
+ // gc.pruneExpire=now combined with auto-gc, between capture and recheck
468
+ // (Spike E: --prune=now deleted it). Materialize step 1 detects this and
469
+ // returns ok:false "commit-missing", and the recheck reports unverifiable.
470
+ // Once the worktree exists, its HEAD pins the commit (Spike E: "cat-file:
471
+ // commit" after gc --prune=now).
472
+ //
473
+ // ----------------------------------------------------------------------------
474
+ // 9. SECRETS POLICY (untracked .env and similar)
475
+ // ----------------------------------------------------------------------------
476
+ // - Ignored files are never copied or linked; only node_modules directories
477
+ // are linked. An ignored .env is absent from the reference, is listed by
478
+ // path in `unreproduced`, and its contents are never read.
479
+ // - An untracked, NOT ignored file (e.g. a .env that is not ignored) is part
480
+ // of the dispatch state. It is copied only if it existed at dispatch and is
481
+ // byte-identical now; otherwise exact=false. Nothing that appeared after
482
+ // dispatch is copied.
483
+ // - dir, and capture's scratch dir, are created with mode 0o700 (plus an
484
+ // exact chmod on POSIX) before any content is written into them, so a
485
+ // shared /tmp never exposes the checkout (QA-1.5-10). On win32 the mode
486
+ // is not an ACL: the dir inherits the ACL of the tmp root. The default
487
+ // per-user %LOCALAPPDATA%\Temp is private; an injected or relocated TEMP
488
+ // (e.g. C:\Temp) usually grants broader access, and then so does dir.
489
+ // - Deferred to 2.1 (QA-1.5-10): materialize only inside the S3 slot, and
490
+ // run GC before each materialize, to bound concurrent references and
491
+ // temp-dir use; 1.5 caps only the untracked copy.
492
+ // - Lifetime: disposed right after the recheck. Crash leftovers are removed
493
+ // by GC once the owner is dead, or 1 h after the last heartbeat; a
494
+ // failed dispose is collected by this process's next GC (section 11).
495
+ // - Logs carry counts and reasons, never file contents. Paths appear only in
496
+ // the inexactReasons and unreproduced lists returned to the caller.
497
+ //
498
+ // ----------------------------------------------------------------------------
499
+ // 10. RELPATH RULES (applied to every git-reported path before any join)
500
+ // ----------------------------------------------------------------------------
501
+ // Non-empty, not absolute; splitting on "/" gives no "", "." or ".." segment
502
+ // and no ".git" segment (case-insensitive); on win32, no ":" (alternate data
503
+ // streams) and no "\". A violation makes capture return undefined; at
504
+ // materialize it makes the reference inexact (and the path is never used).
505
+ //
506
+ // ----------------------------------------------------------------------------
507
+ // 11. CRASH GC gcStaleReferences(root, deps) -> GcReport
508
+ // (called at plugin start, wired in 2.1)
509
+ // ----------------------------------------------------------------------------
510
+ // Never throws. Budget: deps.timeoutMs (default DEFAULT_MATERIALIZE_TIMEOUT_MS),
511
+ // checked before each candidate and before each cleanup retry (QA-1.5-11:
512
+ // a held dir used to keep GC inside fs.rm's nested retries for 66 s against
513
+ // a 30 s budget). A single fs call or git call already in flight is not
514
+ // interrupted; git calls keep CLEANUP_GIT_TIMEOUT_MS.
515
+ // 1. `git worktree list --porcelain` (cwd: root). No -z flag, to support git
516
+ // < 2.36; a path containing a newline can never pass R3. Parse the
517
+ // `worktree <path>`, `locked` and `prunable` lines. Measured in 1.5.1: a
518
+ // deleted worktree dir is listed with "prunable gitdir file points to
519
+ // non-existent location".
520
+ // 2. An entry is a candidate only if its basename matches REF_DIR_PATTERN
521
+ // and its parent is a tmp root (R3). Everything else is never touched:
522
+ // the main worktree and every user worktree. A `locked` entry is kept
523
+ // unless its reason is one this module writes for that dir (section 6
524
+ // step 4); then:
525
+ // - "initializing" (git < 2.33 fallback): collected only if its owner is
526
+ // dead or this process released the dir (QA-1.5-5; an alive owner may
527
+ // still be checking out);
528
+ // - referenceLockReason(pid) (QA-1.5-12): every live reference carries
529
+ // it, so the step 3 rules apply as to an unlocked entry; a missing dir
530
+ // is collected whatever the owner's liveness (QA-1.5-15: a reused pid
531
+ // kept it forever). Racing an alive owner between its fs.rm and its own
532
+ // unlock is benign: both sides only lift our reason and remove an entry
533
+ // whose dir is gone, and the loser logs a warning.
534
+ // Such an entry is unlocked by the section 6 pipeline once its dir is
535
+ // gone. A dir in the in-use set (ACTIVE) is kept. ACTIVE lives on
536
+ // globalThis under Symbol.for("omr.reference.active"), so every copy of
537
+ // this module in the process shares it (QA-1.5-4: the plugin loaded
538
+ // from two install paths; before, the second copy's GC removed the
539
+ // first copy's live reference).
540
+ // 3. A candidate is stale if any of these holds:
541
+ // - its dir is missing (prunable);
542
+ // - it is in RELEASED (Symbol.for("omr.reference.released")): a dir
543
+ // this process created, stopped using, and failed to remove (e.g.
544
+ // EBUSY from a process whose cwd is inside). Only this process can
545
+ // know that its own dir is abandoned, so it is collected at once;
546
+ // - its owner PID (taken from the name) is dead: deps.isAlive, default
547
+ // process.kill(pid, 0), where EPERM counts as alive;
548
+ // - its HEARTBEAT is older than STALE_REFERENCE_AGE_MS (1 h): age =
549
+ // now() - lstat(dir).mtimeMs. While a materialized handle is in use,
550
+ // a timer (unref'd, every deps.heartbeatMs, default
551
+ // HEARTBEAT_INTERVAL_MS = 5 min) sets the dir's mtime to now, and
552
+ // dispose stops it. So the age rule never fires for an alive owner
553
+ // that still uses the dir; it only covers PID reuse (the heartbeat
554
+ // stopped when the real owner died). Capture's scratch dir lives for
555
+ // at most one capture budget and needs no heartbeat. Before QA-1.5-4,
556
+ // age alone, or merely carrying this process's PID, made a live
557
+ // reference stale.
558
+ // 4. Each stale candidate goes through the section 6 pipeline with no
559
+ // recorded links. The sweep finds and unlinks every node_modules link,
560
+ // fs.rm removes the dir, step 4 then removes the missing-dir entry, and
561
+ // `git worktree prune` is never run.
562
+ // 5. Orphans are tmp-root entries matching REF_DIR_PATTERN that are not
563
+ // registered in root's list. An orphan is removed (sweep, then R2 fs.rm)
564
+ // only if it is stale AND it either has no `.git` file or its `gitdir:`
565
+ // line resolves inside root's .git directory. Orphans of other
566
+ // repositories are left alone. This limits temp-dir exhaustion (D7).
567
+ // Capture's private-index scratch dirs (section 3 step 4) and a
568
+ // reference dir that crashed before `git worktree add` registered it
569
+ // are such orphans without a `.git` file.
570
+ // 6. The report lists removed, kept and failed dirs; failures are also
571
+ // logged.
572
+ //
573
+ // ----------------------------------------------------------------------------
574
+ // DEVIATIONS FROM PLAN (evidence-driven; each makes behaviour stricter or safer)
575
+ // ----------------------------------------------------------------------------
576
+ // D1 No pinning ref for the stash commit (Spike E recommended one). The plan's
577
+ // capture acceptance criterion forbids ref changes. See section 8.
578
+ // D2 "Never modify the index": `git stash create` rewrites the stat cache of
579
+ // the index it runs on (measured in 1.5.1) and needs the mandatory index
580
+ // lock for it. That is NOT the same class as `git status`, whose refresh
581
+ // takes an optional lock and is skipped when the lock is busy: on the
582
+ // shared index, 27/120 producer `git add` calls failed against a capture
583
+ // loop (QA-1.5-2). So stash create and the drift `git diff` (which
584
+ // rewrites the index even under --no-optional-locks, section 4 step 7)
585
+ // run on a private copy of the index (section 3 step 4), and every git
586
+ // call carries --no-optional-locks. The user's index is never written.
587
+ // `git stash create` itself is kept because the plan's S2 row (§1.3)
588
+ // names it.
589
+ // D3 exact=false has more causes than §1.5-7: untracked symlinks, dependency
590
+ // drift, workspace-link drift, checkout conversion and index flags
591
+ // (section 2, b to f). These only make the check stricter, and
592
+ // approximate still never excuses.
593
+ // D4 materialize returns { ok: true, reference } | { ok: false, reason,
594
+ // detail } instead of the plan's { dir, exact, dispose() }, so a verdict
595
+ // can say why the reference is unavailable. The handle adds
596
+ // inexactReasons, unreproduced, links and toRefPath. currentTree is
597
+ // optional and only serves as a same-repository guard.
598
+ // D5 `git worktree prune` is never run (plan 1.5.2.c/d, Spike D step 3). The
599
+ // git docs say that unless a worktree is locked, prune removes its admin
600
+ // files when its directory is missing: "If a worktree is on a portable
601
+ // device or network share which is not always mounted, lock it to
602
+ // prevent its administrative files from being pruned". So prune would
603
+ // touch non-omr worktrees. Replacement: `git worktree remove --force
604
+ // <dir>` on an already-deleted dir. Measured in 1.5.1, it exited 0 and
605
+ // removed only that entry.
606
+ // D6 dispose adds a full link sweep before the recursive removal. Spike D
607
+ // proved the order for the links we create; tests may create others.
608
+ // Unlike Spike D method 8, the recursive removal is fs.rm, and
609
+ // `git worktree remove --force` runs only after the dir is gone
610
+ // (QA-1.5-3: git follows a junction that appears after the sweep).
611
+ // D7 capture refuses (returns undefined) above MAX_UNTRACKED_FILES /
612
+ // MAX_UNTRACKED_BYTES, and GC also removes this repository's stale
613
+ // orphan omr-ref dirs. Both address temp-dir exhaustion; the plan does
614
+ // not specify either.
615
+ // D8 The ExecOptions/ArgvSeam seam types now come from ./types (imported
616
+ // once vrb/p12 merged; the former local copies had the identical
617
+ // shape). This module does not re-export them; tests can type the seam
618
+ // as CaptureDeps["argv"].
619
+ // Truncation contract (QA-1.5-21): p12's runArgv caps each stream at its
620
+ // maxBuffer, keeps the child's exit code and appends the note line
621
+ // `[stdout truncated at <n> chars]` after git's stderr. runGit honours
622
+ // that note only in the trailing note block and only when stdout is n
623
+ // (or n-1) chars long (QA-1.5-23), and turns such a result (or a `-z`
624
+ // output without its closing NUL) into a failed call, so a cut listing
625
+ // can only make a reference approximate or failed, never falsely exact.
626
+ // D9 Hooks are disabled for `git worktree add` (core.hooksPath points at a
627
+ // random path in the tmp root that does not exist and lies outside the
628
+ // worktree, so the checkout cannot create it; QA-1.5-8).
629
+ // D10 The reference worktree is added locked (`--lock --reason`, git >= 2.33;
630
+ // QA-1.5-12). The plan does not lock it. Unlocked, a live or crashed
631
+ // reference was a registered worktree in `git worktree list` and IDE
632
+ // views, and a `git worktree remove --force` there would have emptied the
633
+ // live node_modules behind its junctions. Measured by QA: both `remove`
634
+ // and `remove --force` refuse a locked entry, and `prune --dry-run` lists
635
+ // nothing. Only `remove -f -f` or an explicit unlock overrides it.
636
+ //
637
+ // ----------------------------------------------------------------------------
638
+ // OPEN RISKS (not solvable in this module; owners named)
639
+ // ----------------------------------------------------------------------------
640
+ // - Python (2.x recheck): nothing is linked. `uv run pytest` at the reference
641
+ // may build a fresh venv, costing time and network, bounded by
642
+ // recheckTimeoutMs. An editable install in the active environment imports
643
+ // the LIVE tree's sources. Pytest reference runs must count as approximate
644
+ // unless the runner resolves sources from the worktree.
645
+ // - node_modules content generated from repository files (e.g. a Prisma
646
+ // client) reflects the live tree; check (c) only catches manifest and
647
+ // lockfile drift.
648
+ // - Checkout conversion of files git reports as CLEAN is detected through
649
+ // core.autocrlf and the eol-class comparison (section 2e, QA-1.5-13,
650
+ // QA-1.5-18), which sees any conversion that changes the `w/` class. What
651
+ // remains is a `filter` or `ident` smudge (or a working-tree-encoding
652
+ // change) whose output differs from the live bytes while keeping the eol
653
+ // class: such a clean file still
654
+ // differs at the reference while exact stays true. Hashing every tracked
655
+ // file at capture would close this, at a cost the capture budget cannot
656
+ // bound. Dirty files are always compared byte for byte.
657
+ // - False inexact (QA-1.5-19, safe direction): a file clean at capture and
658
+ // edited before materialize is flagged whenever the reference's checkout
659
+ // converts it (`w/` != `i/`), even if the live file already had those
660
+ // bytes. On win32 with `* text=auto` (native CRLF) any such edit makes the
661
+ // reference inexact. Avoiding it needs each path's `w/` class at capture,
662
+ // i.e. a full `ls-files --eol` inside the capture budget; not done, since
663
+ // the error only yields "unverifiable", never a wrong excuse.
664
+ // - Output cap (QA-1.5-24, owner 2.1): the seam caps each stream (p12
665
+ // runArgv default 10 M chars) and a cut listing is a failed call. Capture's
666
+ // `ls-files --stage` hits the cap first, at ~95-150k tracked paths (path
667
+ // length 60-20; SHA-1 ids, ~78-110k under SHA-256), so such a repository
668
+ // gets no reference at all (fail closed, recheck unverifiable). An `--eol`
669
+ // entry is always shorter than a `--stage` one, so the "" fallback of
670
+ // materialize step 7b applies only when the index grew after capture. If
671
+ // 2.1 needs large monorepos, pass a per-call maxBuffer through the seam
672
+ // for the listing calls.
673
+ // - An ignored file that tests need (.env, generated code) is absent at the
674
+ // reference. The recheck must classify the resulting failure as a setup
675
+ // failure (§1.5-8). `unreproduced` supports that decision but cannot make
676
+ // it.
677
+ // - POSIX directory-symlink behaviour of `git worktree remove` is unverified
678
+ // (Spike D ran on win32 only). It no longer matters for deletion: git only
679
+ // ever sees a dir that is already gone. The unlink-first order and the
680
+ // sweep apply on every platform. The 1.5.3 key safety test must run on
681
+ // POSIX CI.
682
+ // - On Node versions other than v24.21.0, fs.rm's non-following of junctions
683
+ // is not proven (Spike D). R2 limits this to a link created between the
684
+ // sweep and fs.rm (the QA-1.5-3 window), which only a process running
685
+ // after the dispose contract was broken can create.
686
+ // - Bun (owner: 3.1, which adds a Bun smoke). opencode runs the plugin under
687
+ // Bun 1.3.14, not Node, and the measurements above are Node's. Verified
688
+ // on Bun 1.3.14/win32 (global QA, attempt 3, E1/E2; QA-G-8):
689
+ // lstat(junction).isSymbolicLink() is true (isDirectory() false), a
690
+ // recursive fs.promises.rm of a dir holding a junction removes the
691
+ // junction without following it (the target's content survives), and the
692
+ // dispose path keeps the real node_modules and leaves no omr-ref dir (E2
693
+ // and the Bun smoke, test/smoke/bun-runtime.smoke.ts). Other Bun versions
694
+ // are unverified, and so is which code Bun's native rm reports for a held
695
+ // dir (EBUSY, EPERM, ...). The
696
+ // flat retry loop no longer relies on the engine honouring maxRetries or
697
+ // retryDelay (QA-1.5-11), but a code outside TRANSIENT_FS_CODES would end
698
+ // it at once (the dir is then left for GC). The heartbeat assumes
699
+ // setInterval(...).unref() and AbortSignal.any/timeout behave as in Node.
700
+ // ============================================================================
701
+
702
+ import * as fsp from "node:fs/promises";
703
+ import { createHash, randomBytes } from "node:crypto";
704
+ import { tmpdir as osTmpdir } from "node:os";
705
+ import { posix as pathPosix, win32 as pathWin32 } from "node:path";
706
+ import type { ArgvSeam, ExecOptions, ExecResult } from "./types";
707
+ import type { TreeSnapshot } from "./dispatch";
708
+ import type { PluginLogger } from "../router/logger";
709
+
710
+ // --- Seams --------------------------------------------------------------------
711
+
712
+ /** The subset of fs.Stats this module reads. */
713
+ export interface ReferenceStats {
714
+ isFile(): boolean;
715
+ isDirectory(): boolean;
716
+ isSymbolicLink(): boolean;
717
+ readonly size: number;
718
+ readonly mode: number;
719
+ readonly mtimeMs: number;
720
+ }
721
+
722
+ /**
723
+ * Narrow fs seam. Every method is non-following or single-entry except `rm`,
724
+ * which R2 restricts to link-free, assertSafeRefDir-approved directories.
725
+ * `node:fs/promises` satisfies it structurally (see nodeReferenceFs).
726
+ */
727
+ export interface ReferenceFs {
728
+ lstat(path: string): Promise<ReferenceStats>;
729
+ /**
730
+ * The NATIVE realpath (fs.promises.realpath, as nodeReferenceFs): it resolves links, junctions
731
+ * and win32 8.3 short names. The JS fs.realpathSync keeps 8.3 names, and the tmp root, the
732
+ * reference dir and every inside-dir check would then disagree on the spelling (E2E-2).
733
+ */
734
+ realpath(path: string): Promise<string>;
735
+ readFile(path: string, options: { signal?: AbortSignal }): Promise<Uint8Array>;
736
+ writeFile(path: string, data: Uint8Array, options: { mode: number; flag: "wx" }): Promise<void>;
737
+ /** `{ recursive: true }` for copy parents; `{ mode: 0o700 }` (non-recursive, fails on EEXIST) for our own dirs. */
738
+ mkdir(path: string, options: { recursive?: boolean; mode?: number }): Promise<unknown>;
739
+ chmod(path: string, mode: number): Promise<void>;
740
+ readdir(path: string): Promise<string[]>;
741
+ symlink(target: string, path: string, type: "junction" | "dir"): Promise<void>;
742
+ unlink(path: string): Promise<void>;
743
+ /** Only on files and dirs this module created (private index copy, heartbeat). */
744
+ utimes(path: string, atime: Date, mtime: Date): Promise<void>;
745
+ /** maxRetries is always 0: the module's flat retry loop retries (QA-1.5-11). */
746
+ rm(
747
+ path: string,
748
+ options: { recursive: true; force: true; maxRetries: 0; retryDelay: number },
749
+ ): Promise<void>;
750
+ }
751
+
752
+ /** Production fs seam; also a compile-time proof that node:fs/promises fits ReferenceFs. */
753
+ export const nodeReferenceFs: ReferenceFs = fsp;
754
+
755
+ export interface CaptureDeps {
756
+ argv: ArgvSeam;
757
+ fs: ReferenceFs;
758
+ /** Whole-operation budget in ms. capture: DEFAULT_CAPTURE_TIMEOUT_MS; materialize/GC: DEFAULT_MATERIALIZE_TIMEOUT_MS. */
759
+ timeoutMs?: number;
760
+ /**
761
+ * Default os.tmpdir(). Reference dirs and capture's scratch dir (private
762
+ * index, section 3 step 4) are created directly under realpath(tmpdir).
763
+ */
764
+ tmpdir?: string;
765
+ }
766
+
767
+ export interface ReferenceDeps extends CaptureDeps {
768
+ logger?: Pick<PluginLogger, "warn">;
769
+ /** Default process.pid; encoded in the dir name for crash GC. */
770
+ pid?: number;
771
+ /** Default Date.now. */
772
+ now?: () => number;
773
+ /** Default: process.kill(pid, 0) succeeds or fails with EPERM. */
774
+ isAlive?: (pid: number) => boolean;
775
+ /** Default process.platform. Selects junction vs dir symlink and path comparison rules. */
776
+ platform?: NodeJS.Platform;
777
+ /** Default randomBytes(8).toString("hex"); must match the 16-hex suffix of REF_DIR_PATTERN. */
778
+ randomSuffix?: () => string;
779
+ /** Default HEARTBEAT_INTERVAL_MS: how often a materialized dir's mtime is refreshed while in use. */
780
+ heartbeatMs?: number;
781
+ }
782
+
783
+ // --- Data types ---------------------------------------------------------------
784
+
785
+ export interface DispatchReference {
786
+ /** path.resolve(`git rev-parse --show-toplevel`) of the dispatch cwd. */
787
+ readonly root: string;
788
+ /** HEAD at capture time. */
789
+ readonly head: string;
790
+ /** `git stash create` commit, or `head` when tracked files were clean. */
791
+ readonly commit: string;
792
+ /** Untracked, not ignored files at dispatch: git relPath (forward slashes) -> sha256 hex, or UNTRACKED_SYMLINK. */
793
+ readonly untracked: ReadonlyMap<string, string>;
794
+ /** Tracked paths that differ between head and commit and were regular files: relPath -> sha256 of the live bytes (section 2e). */
795
+ readonly tracked: ReadonlyMap<string, string>;
796
+ /** Found at capture; every reference built from this capture is approximate for them (section 2f). */
797
+ readonly captureReasons: readonly InexactReason[];
798
+ /** now() when the capture resolved. */
799
+ readonly capturedAt: number;
800
+ }
801
+
802
+ export type InexactCause =
803
+ | "untracked-deleted"
804
+ | "untracked-modified"
805
+ | "untracked-not-file"
806
+ | "untracked-unreadable"
807
+ | "untracked-symlink"
808
+ | "untracked-unsafe-path"
809
+ | "dependency-drift"
810
+ | "workspace-link-drift"
811
+ | "index-flags"
812
+ | "checkout-conversion";
813
+
814
+ export interface InexactReason {
815
+ readonly cause: InexactCause;
816
+ /** Root-relative git path (forward slashes) the cause refers to; "" for a repository-wide cause. */
817
+ readonly path: string;
818
+ }
819
+
820
+ export interface MaterializedReference {
821
+ /** Absolute worktree dir: <realpath(tmpdir)>/omr-ref-<pid>-<16 hex>. */
822
+ readonly dir: string;
823
+ /** True only if inexactReasons is empty (section 2). Approximate never excuses (§1.5-7). */
824
+ readonly exact: boolean;
825
+ readonly inexactReasons: readonly InexactReason[];
826
+ /** Ignored live-tree entries (git relPath, dirs end in "/") absent from dir; node_modules excluded. */
827
+ readonly unreproduced: readonly string[];
828
+ /** Absolute paths of the node_modules links created inside dir. */
829
+ readonly links: readonly string[];
830
+ /**
831
+ * Maps an absolute live path under ref.root, or under the native realpath of ref.root, to the
832
+ * same relative path under dir; undefined outside both. Lexical below the root: pass the
833
+ * canonical (realpath'd) spelling, as the planner produces it.
834
+ */
835
+ toRefPath(livePath: string): string | undefined;
836
+ /** Section 6. Idempotent, never rejects; call only after the recheck process tree has exited. */
837
+ dispose(): Promise<void>;
838
+ }
839
+
840
+ export type MaterializeFailure =
841
+ | "aborted"
842
+ | "commit-missing"
843
+ | "worktree-add-failed"
844
+ | "unsafe-path"
845
+ | "error";
846
+
847
+ export type MaterializeResult =
848
+ | { readonly ok: true; readonly reference: MaterializedReference }
849
+ | { readonly ok: false; readonly reason: MaterializeFailure; readonly detail: string };
850
+
851
+ export interface GcReport {
852
+ readonly removed: readonly string[];
853
+ readonly kept: readonly string[];
854
+ readonly failed: readonly string[];
855
+ }
856
+
857
+ // --- Constants ----------------------------------------------------------------
858
+
859
+ export const REF_DIR_PREFIX = "omr-ref-";
860
+ /** omr-ref-<owner pid>-<16 lowercase hex>. Anything else is never removed. */
861
+ export const REF_DIR_PATTERN = /^omr-ref-(\d{1,10})-([0-9a-f]{16})$/;
862
+ /**
863
+ * Lock reason `git worktree add` without --lock writes until its checkout ends (untranslated:
864
+ * our add runs with LC_ALL=C). Only the git < 2.33 fallback of section 4 step 3 produces it now.
865
+ */
866
+ export const INITIALIZING_LOCK_REASON = "initializing";
867
+ /**
868
+ * Lock reason of a reference worktree for its whole life (QA-1.5-12): `git worktree add
869
+ * --lock --reason <this>` (git >= 2.33). The pid is the owner pid of the dir name.
870
+ * Git prints it, so a user's `git worktree remove [--force]` explains its refusal.
871
+ */
872
+ export function referenceLockReason(pid: number): string {
873
+ return `omr-verify-reference pid=${pid}: its node_modules links lead into the live repository, do not force-remove`;
874
+ }
875
+ /** `git worktree add` of git < 2.33 rejects --reason (and very old ones --lock) in its option parser. */
876
+ const ADD_LOCK_UNSUPPORTED = /unknown option\W+(?:reason|lock)\b/;
877
+ export const STALE_REFERENCE_AGE_MS = 60 * 60 * 1000;
878
+ /** A live reference dir's mtime is refreshed this often, far below STALE_REFERENCE_AGE_MS (QA-1.5-4). */
879
+ export const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
880
+ /** Equals the baselineTimeoutMs default (§1.4); callers pass the configured value. */
881
+ export const DEFAULT_CAPTURE_TIMEOUT_MS = 15_000;
882
+ export const DEFAULT_MATERIALIZE_TIMEOUT_MS = 30_000;
883
+ export const CLEANUP_GIT_TIMEOUT_MS = 15_000;
884
+ export const CLEANUP_RETRIES = 5;
885
+ export const CLEANUP_RETRY_BASE_MS = 100;
886
+ export const TRANSIENT_FS_CODES: ReadonlySet<string> = new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
887
+ export const MAX_UNTRACKED_FILES = 5_000;
888
+ export const MAX_UNTRACKED_BYTES = 64 * 1024 * 1024;
889
+ export const MAX_SWEEP_ENTRIES = 500_000;
890
+ /** Per-path "checkout-conversion" reasons from the eol comparison (section 2e); beyond it, one "" reason. */
891
+ export const MAX_CONVERSION_REASONS = 100;
892
+ /** Marker value for an untracked symbolic link (not a sha256, so it never matches a file hash). */
893
+ export const UNTRACKED_SYMLINK = "symlink";
894
+ /** Basenames whose drift between commit and the live tree makes a linked node_modules stale (section 2c). */
895
+ export const DEPENDENCY_FILES: ReadonlySet<string> = new Set([
896
+ "package.json",
897
+ "package-lock.json",
898
+ "npm-shrinkwrap.json",
899
+ "pnpm-lock.yaml",
900
+ "pnpm-workspace.yaml",
901
+ ".pnpmfile.cjs",
902
+ "yarn.lock",
903
+ ".yarnrc.yml",
904
+ "bun.lock",
905
+ "bun.lockb",
906
+ ".npmrc",
907
+ ]);
908
+
909
+ // --- Path guards (normative, R3; implemented now so 1.5.2 cannot weaken them) --
910
+
911
+ export class UnsafeReferencePathError extends Error {
912
+ constructor(message: string) {
913
+ super(message);
914
+ this.name = "UnsafeReferencePathError";
915
+ }
916
+ }
917
+
918
+ function pathFor(platform: NodeJS.Platform) {
919
+ return platform === "win32" ? pathWin32 : pathPosix;
920
+ }
921
+
922
+ function comparable(path: string, platform: NodeJS.Platform): string {
923
+ const resolved = pathFor(platform).resolve(path);
924
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
925
+ }
926
+
927
+ export function refDirName(pid: number, suffix: string): string {
928
+ const name = `${REF_DIR_PREFIX}${pid}-${suffix}`;
929
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !REF_DIR_PATTERN.test(name)) {
930
+ throw new UnsafeReferencePathError(`invalid reference dir name: ${name}`);
931
+ }
932
+ return name;
933
+ }
934
+
935
+ export function parseRefDirName(name: string): { pid: number; suffix: string } | undefined {
936
+ const match = REF_DIR_PATTERN.exec(name);
937
+ if (!match) return undefined;
938
+ const pid = Number(match[1]);
939
+ if (!Number.isSafeInteger(pid) || pid <= 0) return undefined;
940
+ return { pid, suffix: match[2] };
941
+ }
942
+
943
+ /** True when child is strictly below parent (never equal). Both must be absolute. */
944
+ export function isStrictlyInside(
945
+ child: string,
946
+ parent: string,
947
+ platform: NodeJS.Platform = process.platform,
948
+ ): boolean {
949
+ const p = pathFor(platform);
950
+ if (!p.isAbsolute(child) || !p.isAbsolute(parent)) return false;
951
+ const rel = p.relative(comparable(parent, platform), comparable(child, platform));
952
+ if (rel === "" || p.isAbsolute(rel)) return false;
953
+ return rel.split(p.sep)[0] !== "..";
954
+ }
955
+
956
+ /**
957
+ * R3 hard guard, called immediately before every destructive operation on a
958
+ * reference dir (`git worktree remove --force`, recursive fs.rm). Pure: callers
959
+ * additionally lstat the dir and require a real directory (R2).
960
+ */
961
+ export function assertSafeRefDir(
962
+ dir: string,
963
+ tmpRoots: readonly string[],
964
+ platform: NodeJS.Platform = process.platform,
965
+ ): void {
966
+ const p = pathFor(platform);
967
+ const fail = (why: string): never => {
968
+ throw new UnsafeReferencePathError(`refusing reference dir ${JSON.stringify(dir)}: ${why}`);
969
+ };
970
+ if (typeof dir !== "string" || dir.length === 0 || !p.isAbsolute(dir)) fail("not absolute");
971
+ if (dir.split(/[\\/]+/).some((segment) => segment === "." || segment === "..")) fail("dot segment");
972
+ const resolved = p.resolve(dir);
973
+ if (!parseRefDirName(p.basename(resolved))) fail("name does not match omr-ref-<pid>-<16 hex>");
974
+ const parent = comparable(p.dirname(resolved), platform);
975
+ const underTmpRoot = tmpRoots.some((root) => {
976
+ if (!p.isAbsolute(root)) return false;
977
+ const candidate = comparable(root, platform);
978
+ if (p.parse(candidate).root === candidate) return false; // a filesystem root is never a tmp root
979
+ return candidate === parent;
980
+ });
981
+ if (!underTmpRoot) fail("parent is not a temp root");
982
+ }
983
+
984
+ // --- Shared helpers -------------------------------------------------------------
985
+
986
+ /**
987
+ * A Set<string> shared by every copy of this module in the process (QA-1.5-4:
988
+ * the plugin can be loaded from two install paths). Kept on globalThis under a
989
+ * Symbol.for key; a foreign value under the key is replaced, never trusted.
990
+ */
991
+ function processWideSet(name: string): Set<string> {
992
+ const key = Symbol.for(name);
993
+ const existing: unknown = Reflect.get(globalThis, key);
994
+ if (existing instanceof Set) return existing as Set<string>;
995
+ const created = new Set<string>();
996
+ Reflect.set(globalThis, key, created);
997
+ return created;
998
+ }
999
+
1000
+ /** Reference and scratch dirs in use in this process (comparable form); GC never touches them. */
1001
+ const ACTIVE = processWideSet("omr.reference.active");
1002
+ /** Dirs this process created and stopped using but could not remove; GC treats them as stale at once. */
1003
+ const RELEASED = processWideSet("omr.reference.released");
1004
+
1005
+ type Logger = Pick<PluginLogger, "warn">;
1006
+
1007
+ function errorCode(error: unknown): string | undefined {
1008
+ if (typeof error === "object" && error !== null && "code" in error) {
1009
+ const code = (error as { code: unknown }).code;
1010
+ return typeof code === "string" ? code : undefined;
1011
+ }
1012
+ return undefined;
1013
+ }
1014
+
1015
+ function describeError(error: unknown): string {
1016
+ return error instanceof Error ? error.message : String(error);
1017
+ }
1018
+
1019
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
1020
+
1021
+ /** lstat that maps ENOENT (and ENOTDIR) to undefined; every other error propagates. */
1022
+ async function lstatOrMissing(fs: ReferenceFs, path: string): Promise<ReferenceStats | undefined> {
1023
+ try {
1024
+ return await fs.lstat(path);
1025
+ } catch (error) {
1026
+ const code = errorCode(error);
1027
+ if (code === "ENOENT" || code === "ENOTDIR") return undefined;
1028
+ throw error;
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * Section 6: the module's only retry loop. Retries TRANSIENT_FS_CODES with exponential
1034
+ * backoff, then rethrows. It is flat: `op` must not retry on its own (fs.rm runs with
1035
+ * maxRetries: 0, QA-1.5-11). No attempt starts at or after `deadline` (GC's budget).
1036
+ */
1037
+ async function withRetry<T>(op: () => Promise<T>, deadline = Number.POSITIVE_INFINITY): Promise<T> {
1038
+ for (let attempt = 0; ; attempt++) {
1039
+ try {
1040
+ return await op();
1041
+ } catch (error) {
1042
+ const code = errorCode(error);
1043
+ const delay = CLEANUP_RETRY_BASE_MS * 2 ** attempt;
1044
+ if (attempt >= CLEANUP_RETRIES || code === undefined || !TRANSIENT_FS_CODES.has(code)) throw error;
1045
+ if (Date.now() + delay >= deadline) throw error;
1046
+ await sleep(delay);
1047
+ }
1048
+ }
1049
+ }
1050
+
1051
+ /** Section 10. */
1052
+ function isSafeRelPath(rel: string, platform: NodeJS.Platform): boolean {
1053
+ if (rel.length === 0 || rel.startsWith("/") || pathFor(platform).isAbsolute(rel)) return false;
1054
+ if (platform === "win32" && (rel.includes(":") || rel.includes("\\"))) return false;
1055
+ return rel.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".." && segment.toLowerCase() !== ".git");
1056
+ }
1057
+
1058
+ function splitZ(stdout: string): string[] {
1059
+ return stdout.split("\0").filter((entry) => entry.length > 0);
1060
+ }
1061
+
1062
+ /**
1063
+ * `git ls-files --eol -z` -> path -> working-tree eol class (the `w/` column: lf, crlf,
1064
+ * mixed, none, -text, or "" for a missing or non-regular file). Each record is
1065
+ * "i/%-5s w/%-5s attr/%-17s\t<path>" (git's ls-files.c); only the path follows the tab.
1066
+ */
1067
+ function parseEolList(stdout: string): Map<string, { i: string; w: string }> {
1068
+ const result = new Map<string, { i: string; w: string }>();
1069
+ for (const record of splitZ(stdout)) {
1070
+ const tab = record.indexOf("\t");
1071
+ if (tab < 0) continue;
1072
+ const prefix = record.slice(0, tab);
1073
+ const w = /(?:^|\s)w\/(\S*)/.exec(prefix);
1074
+ const i = /^i\/(\S*)/.exec(prefix);
1075
+ if (w) result.set(record.slice(tab + 1), { i: i?.[1] ?? "", w: w[1] ?? "" });
1076
+ }
1077
+ return result;
1078
+ }
1079
+
1080
+ function stripNewline(stdout: string): string {
1081
+ return stdout.replace(/\r?\n$/, "");
1082
+ }
1083
+
1084
+ function sha256(bytes: Uint8Array): string {
1085
+ return createHash("sha256").update(bytes).digest("hex");
1086
+ }
1087
+
1088
+ interface Budget {
1089
+ readonly signal: AbortSignal;
1090
+ remaining(): number;
1091
+ spent(): boolean;
1092
+ }
1093
+
1094
+ function makeBudget(signal: AbortSignal, timeoutMs: number): Budget {
1095
+ const deadline = Date.now() + timeoutMs;
1096
+ const combined = AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, timeoutMs))]);
1097
+ return {
1098
+ signal: combined,
1099
+ remaining: () => deadline - Date.now(),
1100
+ spent: () => combined.aborted || deadline - Date.now() <= 0,
1101
+ };
1102
+ }
1103
+
1104
+ interface GitRun {
1105
+ readonly cwd: string;
1106
+ readonly timeoutMs: number;
1107
+ /** Omitted only for `stash create` (section 3 step 4): a kill must never land while git holds a lock. */
1108
+ readonly signal?: AbortSignal;
1109
+ /** Merged over process.env by the seam. */
1110
+ readonly env?: Record<string, string>;
1111
+ }
1112
+
1113
+ /** Overrides for the pathspec environment switches git would otherwise inherit (QA-1.5-18). */
1114
+ const PATHSPEC_ENV_RESET: Readonly<Record<string, string>> = {
1115
+ GIT_LITERAL_PATHSPECS: "0",
1116
+ GIT_GLOB_PATHSPECS: "0",
1117
+ GIT_NOGLOB_PATHSPECS: "0",
1118
+ GIT_ICASE_PATHSPECS: "0",
1119
+ };
1120
+
1121
+ /** One note line the p12 seam appends to stderr when it cut a stream at its maxBuffer (QA-1.5-21). */
1122
+ const TRUNCATION_NOTE = /^\[(stdout|stderr) truncated at (\d+) chars\]$/;
1123
+
1124
+ /**
1125
+ * Whether the seam cut stdout (QA-1.5-21, QA-1.5-23). p12's runArgv appends its
1126
+ * notes as whole lines after git's own stderr, so only the trailing block of
1127
+ * note lines counts: git messages quoting a path named like the note never
1128
+ * match. The stdout note must also agree with the cap, i.e. stdout is n chars,
1129
+ * or n-1 when the cut dropped half of a surrogate pair.
1130
+ */
1131
+ function stdoutTruncated(result: ExecResult): boolean {
1132
+ const lines = result.stderr.split("\n");
1133
+ if (lines.at(-1) === "") lines.pop();
1134
+ for (let i = lines.length - 1; i >= 0; i--) {
1135
+ const note = TRUNCATION_NOTE.exec(lines[i] ?? "");
1136
+ if (!note) return false;
1137
+ if (note[1] === "stdout") {
1138
+ const limit = Number(note[2]);
1139
+ return result.stdout.length === limit || result.stdout.length === limit - 1;
1140
+ }
1141
+ }
1142
+ return false;
1143
+ }
1144
+
1145
+ /**
1146
+ * One git run through the seam; undefined on timeout or abort. Every call is
1147
+ * `git --no-optional-locks ...` (QA-1.5-2): read-only commands never refresh
1148
+ * the user's index, and so never compete with the producer for index.lock.
1149
+ * A truncated stdout (QA-1.5-21) comes back as a failed call (code -1): the
1150
+ * seam's trailing stdout note in stderr (stdoutTruncated), or a non-empty
1151
+ * `-z` output that does not end in NUL. Every caller parses stdout only after `code === 0`.
1152
+ */
1153
+ async function runGit(argv: ArgvSeam, args: readonly string[], run: GitRun): Promise<ExecResult | undefined> {
1154
+ if (run.timeoutMs <= 0 || run.signal?.aborted) return undefined;
1155
+ const opts: ExecOptions = { cwd: run.cwd, timeoutMs: run.timeoutMs };
1156
+ if (run.signal) opts.signal = run.signal;
1157
+ // QA-1.5-18: pathspec env switches (literal/glob/noglob/icase) change what every pathspec
1158
+ // means; git reads them as booleans, so "0" neutralises them whatever the plugin inherited.
1159
+ opts.env = { ...PATHSPEC_ENV_RESET, ...run.env };
1160
+ try {
1161
+ const result = await argv("git", ["--no-optional-locks", ...args], opts);
1162
+ if (result.timedOut || run.signal?.aborted) return undefined;
1163
+ // QA-1.5-21: the p12 seam keeps exit code 0 when it cuts stdout at maxBuffer.
1164
+ const cut =
1165
+ stdoutTruncated(result) ||
1166
+ (args.includes("-z") && result.stdout !== "" && !result.stdout.endsWith("\0"));
1167
+ if (cut && result.code === 0) {
1168
+ return { ...result, code: -1, stderr: `${result.stderr}\n[omr: git output truncated]` };
1169
+ }
1170
+ return result;
1171
+ } catch (error) {
1172
+ // The seam reports spawn failures and aborts by rejecting; both mean "no result".
1173
+ return { code: -1, stdout: "", stderr: describeError(error), timedOut: run.signal?.aborted };
1174
+ }
1175
+ }
1176
+
1177
+ function isAliveDefault(pid: number): boolean {
1178
+ try {
1179
+ process.kill(pid, 0);
1180
+ return true;
1181
+ } catch (error) {
1182
+ return errorCode(error) === "EPERM";
1183
+ }
1184
+ }
1185
+
1186
+ async function tmpRootsFor(fs: ReferenceFs, tmp: string, platform: NodeJS.Platform): Promise<string[]> {
1187
+ const p = pathFor(platform);
1188
+ const roots = [p.resolve(tmp)];
1189
+ try {
1190
+ roots.push(p.resolve(await fs.realpath(tmp)));
1191
+ } catch {
1192
+ // realpath failed (e.g. tmp missing): only the resolved form can be a tmp root.
1193
+ return roots;
1194
+ }
1195
+ return roots;
1196
+ }
1197
+
1198
+ // --- Dispose pipeline (section 6) ---------------------------------------------
1199
+
1200
+ interface CleanupContext {
1201
+ readonly argv: ArgvSeam;
1202
+ readonly fs: ReferenceFs;
1203
+ readonly root: string;
1204
+ readonly tmpRoots: readonly string[];
1205
+ readonly platform: NodeJS.Platform;
1206
+ readonly logger?: Logger;
1207
+ /**
1208
+ * GC's budget end (Date.now() scale; QA-1.5-11): no cleanup retry starts after it,
1209
+ * and step 4 is skipped once it has passed. Unset for dispose, which CLEANUP_RETRIES
1210
+ * alone bounds, because cleanup must finish after an abort.
1211
+ */
1212
+ readonly deadline?: number;
1213
+ }
1214
+
1215
+ function leftInPlace(ctx: CleanupContext, dir: string, reason: string): false {
1216
+ ctx.logger?.warn(`reference worktree left in place: ${reason}`, { dir });
1217
+ return false;
1218
+ }
1219
+
1220
+ /** Step 2: unlink every link under dir without descending into links. Returns a failure reason or undefined. */
1221
+ async function sweepLinks(ctx: CleanupContext, dir: string): Promise<string | undefined> {
1222
+ const p = pathFor(ctx.platform);
1223
+ const root = await lstatOrMissing(ctx.fs, dir);
1224
+ if (!root) return undefined;
1225
+ if (root.isSymbolicLink() || !root.isDirectory()) return "reference dir is not a real directory";
1226
+ const realDir = p.resolve(await ctx.fs.realpath(dir));
1227
+ const stack = [dir];
1228
+ let entries = 0;
1229
+ while (stack.length > 0) {
1230
+ const current = stack.pop() as string;
1231
+ let names: string[];
1232
+ try {
1233
+ // The lexical check below cannot see a real dir swapped for a junction after
1234
+ // its lstat (QA-1.5-3); realpath narrows that window to this call and readdir.
1235
+ const real = p.resolve(await ctx.fs.realpath(current));
1236
+ if (!insideOrEqual(real, realDir, ctx.platform)) return `sweep reached ${current} resolving outside the dir`;
1237
+ names = await withRetry(() => ctx.fs.readdir(current), ctx.deadline);
1238
+ } catch (error) {
1239
+ if (errorCode(error) === "ENOENT") continue;
1240
+ return `sweep could not read ${current}: ${describeError(error)}`;
1241
+ }
1242
+ for (const name of names) {
1243
+ if (++entries > MAX_SWEEP_ENTRIES) return `sweep exceeded ${MAX_SWEEP_ENTRIES} entries`;
1244
+ const entry = p.join(current, name);
1245
+ if (!isStrictlyInside(entry, dir, ctx.platform)) return `sweep reached ${entry} outside the dir`;
1246
+ const stats = await lstatOrMissing(ctx.fs, entry);
1247
+ if (!stats) continue;
1248
+ if (stats.isSymbolicLink()) {
1249
+ try {
1250
+ await withRetry(() => ctx.fs.unlink(entry), ctx.deadline);
1251
+ } catch (error) {
1252
+ if (errorCode(error) !== "ENOENT") return `link ${entry} could not be unlinked: ${describeError(error)}`;
1253
+ }
1254
+ if (await lstatOrMissing(ctx.fs, entry)) return `link ${entry} survived unlink`;
1255
+ } else if (stats.isDirectory()) {
1256
+ stack.push(entry);
1257
+ }
1258
+ }
1259
+ }
1260
+ return undefined;
1261
+ }
1262
+
1263
+ /** dir's admin entry; null when not registered, undefined when the list failed. */
1264
+ async function registeredEntry(ctx: CleanupContext, dir: string): Promise<WorktreeEntry | null | undefined> {
1265
+ const list = await runGit(ctx.argv, ["worktree", "list", "--porcelain"], { cwd: ctx.root, timeoutMs: CLEANUP_GIT_TIMEOUT_MS });
1266
+ if (!list || list.code !== 0) return undefined;
1267
+ const wanted = comparable(dir, ctx.platform);
1268
+ return parseWorktreeList(list.stdout).find((entry) => comparable(entry.path, ctx.platform) === wanted) ?? null;
1269
+ }
1270
+
1271
+ interface RemoveOptions {
1272
+ /** Run step 4 (drop the admin entry); false for capture scratch dirs and unregistered orphans. */
1273
+ readonly git: boolean;
1274
+ /**
1275
+ * Section 6 step 4 (QA-1.5-5, QA-1.5-12): once the dir is gone, the entry may be
1276
+ * unlocked when its lock reason is one of ownLockReasons(dir). Only for our own
1277
+ * handle, or a GC candidate whose owner is done with it (section 11).
1278
+ */
1279
+ readonly unlockOwnLock: boolean;
1280
+ }
1281
+
1282
+ /**
1283
+ * The lock reasons this module itself writes for dir: referenceLockReason(<pid of its
1284
+ * name>) and, from the git < 2.33 fallback or a tree-killed add, INITIALIZING_LOCK_REASON.
1285
+ * Any other reason, including an omr reason naming another pid, is someone else's.
1286
+ */
1287
+ function isOwnLockReason(dir: string, reason: string | undefined, platform: NodeJS.Platform): boolean {
1288
+ const parsed = parseRefDirName(pathFor(platform).basename(dir));
1289
+ return parsed !== undefined && (reason === INITIALIZING_LOCK_REASON || reason === referenceLockReason(parsed.pid));
1290
+ }
1291
+
1292
+ /**
1293
+ * Section 6 steps 1-4. Returns true when dir is gone (and, with `git`, unregistered).
1294
+ * Never throws; every failure is logged and the leftover is left for GC.
1295
+ */
1296
+ async function removeReferenceDir(
1297
+ ctx: CleanupContext,
1298
+ dir: string,
1299
+ links: readonly string[],
1300
+ opts: RemoveOptions,
1301
+ ): Promise<boolean> {
1302
+ try {
1303
+ // 1. Recorded links, newest first. R1: lstat, then single-entry unlink only.
1304
+ for (const link of [...links].reverse()) {
1305
+ if (!isStrictlyInside(link, dir, ctx.platform)) return leftInPlace(ctx, dir, `recorded link ${link} is outside the dir`);
1306
+ const stats = await lstatOrMissing(ctx.fs, link);
1307
+ if (!stats || !stats.isSymbolicLink()) continue;
1308
+ try {
1309
+ await withRetry(() => ctx.fs.unlink(link), ctx.deadline);
1310
+ } catch (error) {
1311
+ if (errorCode(error) !== "ENOENT") return leftInPlace(ctx, dir, `link ${link} could not be unlinked: ${describeError(error)}`);
1312
+ }
1313
+ }
1314
+ // 2. Sweep: prove the tree link-free before any recursive removal (R2 iii).
1315
+ const sweepFailure = await sweepLinks(ctx, dir);
1316
+ if (sweepFailure) return leftInPlace(ctx, dir, sweepFailure);
1317
+ // 3. The only recursive deleter: guarded fs.rm (Spike D SAFE #5) on the link-free
1318
+ // tree. fs.rm never follows a link that appears after the sweep (QA-1.5-3);
1319
+ // `git worktree remove` on an existing dir would. maxRetries: 0 inside our flat
1320
+ // loop: Node's own retries nest once per directory level (QA-1.5-11).
1321
+ const stats = await lstatOrMissing(ctx.fs, dir);
1322
+ if (stats) {
1323
+ assertSafeRefDir(dir, ctx.tmpRoots, ctx.platform);
1324
+ if (stats.isSymbolicLink() || !stats.isDirectory()) return leftInPlace(ctx, dir, "not a real directory");
1325
+ try {
1326
+ await withRetry(() => ctx.fs.rm(dir, { recursive: true, force: true, maxRetries: 0, retryDelay: CLEANUP_RETRY_BASE_MS }), ctx.deadline);
1327
+ } catch (error) {
1328
+ return leftInPlace(ctx, dir, `fs.rm failed: ${describeError(error)}`);
1329
+ }
1330
+ if (await lstatOrMissing(ctx.fs, dir)) return leftInPlace(ctx, dir, "dir still exists after fs.rm");
1331
+ }
1332
+ // 4. Only now that the dir is gone: drop the admin entry with
1333
+ // `git worktree remove --force`, which then deletes no tree. Never prune (D5).
1334
+ if (opts.git && ctx.deadline !== undefined && Date.now() >= ctx.deadline) {
1335
+ ctx.logger?.warn("reference worktree admin entry left registered: GC budget spent", { dir });
1336
+ return false;
1337
+ }
1338
+ const entry = opts.git ? await registeredEntry(ctx, dir) : null;
1339
+ if (entry !== null) {
1340
+ assertSafeRefDir(dir, ctx.tmpRoots, ctx.platform);
1341
+ if (await lstatOrMissing(ctx.fs, dir)) return leftInPlace(ctx, dir, "dir reappeared before admin-entry removal");
1342
+ if (entry?.locked) {
1343
+ // Our add locks the entry for the reference's whole life (QA-1.5-12); the git < 2.33
1344
+ // fallback, killed mid-checkout, leaves "initializing" (QA-1.5-5). Lifted only here,
1345
+ // with the dir gone. Every other lock reason belongs to someone else and is respected.
1346
+ if (!opts.unlockOwnLock || !isOwnLockReason(dir, entry.lockReason, ctx.platform)) {
1347
+ ctx.logger?.warn("reference worktree admin entry left registered: locked", { dir, reason: entry.lockReason });
1348
+ return false;
1349
+ }
1350
+ const unlocked = await runGit(ctx.argv, ["worktree", "unlock", dir], { cwd: ctx.root, timeoutMs: CLEANUP_GIT_TIMEOUT_MS });
1351
+ if (!unlocked || unlocked.code !== 0) {
1352
+ ctx.logger?.warn("reference worktree admin entry left locked", { dir, stderr: unlocked?.stderr.trim() });
1353
+ return false;
1354
+ }
1355
+ }
1356
+ const removed = await runGit(ctx.argv, ["worktree", "remove", "--force", dir], { cwd: ctx.root, timeoutMs: CLEANUP_GIT_TIMEOUT_MS });
1357
+ if (!removed || removed.code !== 0) {
1358
+ ctx.logger?.warn("reference worktree admin entry left registered", { dir, stderr: removed?.stderr.trim() });
1359
+ return false;
1360
+ }
1361
+ }
1362
+ return true;
1363
+ } catch (error) {
1364
+ return leftInPlace(ctx, dir, describeError(error));
1365
+ }
1366
+ }
1367
+
1368
+ // --- captureReference (section 3) ---------------------------------------------
1369
+
1370
+ /** Section 3. Never throws; undefined = no reference (not a repo, submodules, abort, timeout, caps, error). */
1371
+ export async function captureReference(
1372
+ cwd: string,
1373
+ signal: AbortSignal,
1374
+ deps: CaptureDeps,
1375
+ ): Promise<DispatchReference | undefined> {
1376
+ try {
1377
+ return await captureInner(cwd, signal, deps);
1378
+ } catch {
1379
+ // Section 3 step 6: every error (unreadable file, concurrent deletion, abort) means "no reference".
1380
+ return undefined;
1381
+ }
1382
+ }
1383
+
1384
+ async function captureInner(cwd: string, signal: AbortSignal, deps: CaptureDeps): Promise<DispatchReference | undefined> {
1385
+ const platform = process.platform;
1386
+ const p = pathFor(platform);
1387
+ const budget = makeBudget(signal, deps.timeoutMs ?? DEFAULT_CAPTURE_TIMEOUT_MS);
1388
+ const git = async (args: readonly string[], at: string) => {
1389
+ if (budget.spent()) return undefined;
1390
+ const result = await runGit(deps.argv, args, { cwd: at, timeoutMs: budget.remaining(), signal: budget.signal });
1391
+ return result && result.code === 0 && !budget.spent() ? result : undefined;
1392
+ };
1393
+
1394
+ const top = await git(["rev-parse", "--show-toplevel"], cwd);
1395
+ if (!top) return undefined;
1396
+ const root = p.resolve(stripNewline(top.stdout));
1397
+ const stage = await git(["ls-files", "--stage"], root);
1398
+ if (!stage || /^160000 /m.test(stage.stdout)) return undefined;
1399
+ // Section 2f (QA-1.5-6): neither stash create nor the drift diff sees an edit to an
1400
+ // assume-unchanged (lowercase tag) or skip-worktree (`S`) entry.
1401
+ const tagged = await git(["ls-files", "-v", "-z"], root);
1402
+ if (!tagged) return undefined;
1403
+ const captureReasons: InexactReason[] = [];
1404
+ const flagged = splitZ(tagged.stdout)
1405
+ .filter((record) => /^(?:[a-z]|S) /.test(record))
1406
+ .map((record) => record.slice(record.indexOf(" ") + 1))
1407
+ .sort(byCodeUnit);
1408
+ if (flagged.length > 0) captureReasons.push({ cause: "index-flags", path: flagged[0] ?? "" });
1409
+ const headOut = await git(["rev-parse", "--verify", "HEAD^{commit}"], root);
1410
+ if (!headOut) return undefined;
1411
+ const head = headOut.stdout.trim();
1412
+ const scratchEnv: PrivateIndexEnv = {
1413
+ argv: deps.argv, fs: deps.fs, root, tmpdir: deps.tmpdir ?? osTmpdir(), platform, pid: process.pid,
1414
+ };
1415
+ const stashOut = await withPrivateIndex(scratchEnv, budget, async (copy) => {
1416
+ // No signal: an abort must never kill git while it holds a lock. The
1417
+ // timeout still bounds it, and can strand a lock only on the copy.
1418
+ const stash = await runGit(deps.argv, ["-c", "core.splitIndex=false", "stash", "create"], {
1419
+ cwd: root,
1420
+ timeoutMs: budget.remaining(),
1421
+ env: { GIT_INDEX_FILE: copy },
1422
+ });
1423
+ return stash && stash.code === 0 && !budget.spent() ? stash.stdout.trim() : undefined;
1424
+ });
1425
+ if (stashOut === undefined) return undefined;
1426
+ let commit: string;
1427
+ if (stashOut === "") commit = head;
1428
+ else if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(stashOut)) commit = stashOut;
1429
+ else return undefined;
1430
+
1431
+ // Section 2e (QA-1.5-6): live bytes of every dirty tracked file, to be compared with the
1432
+ // bytes the checkout produces (EOL conversion, text/eol/filter attributes).
1433
+ const tracked = new Map<string, string>();
1434
+ if (commit !== head) {
1435
+ const dirty = await git(["diff-tree", "-r", "-z", "--name-only", "--no-renames", head, commit], root);
1436
+ if (!dirty) return undefined;
1437
+ const dirtyPaths = splitZ(dirty.stdout).sort();
1438
+ if (dirtyPaths.length > MAX_UNTRACKED_FILES) return undefined;
1439
+ let dirtyBytes = 0;
1440
+ for (const rel of dirtyPaths) {
1441
+ if (budget.spent() || !isSafeRelPath(rel, platform)) return undefined;
1442
+ const absolute = p.join(root, rel);
1443
+ const stats = await lstatOrMissing(deps.fs, absolute);
1444
+ if (!stats || stats.isSymbolicLink() || !stats.isFile()) continue; // deleted or not a file: nothing to compare
1445
+ dirtyBytes += stats.size;
1446
+ if (dirtyBytes > MAX_UNTRACKED_BYTES) return undefined;
1447
+ tracked.set(rel, sha256(await deps.fs.readFile(absolute, { signal: budget.signal })));
1448
+ }
1449
+ }
1450
+
1451
+ const listed = await git(["ls-files", "--others", "--exclude-standard", "--full-name", "-z"], root);
1452
+ if (!listed) return undefined;
1453
+ const paths = splitZ(listed.stdout).sort();
1454
+ if (paths.length > MAX_UNTRACKED_FILES) return undefined;
1455
+ const untracked = new Map<string, string>();
1456
+ let bytes = 0;
1457
+ for (const rel of paths) {
1458
+ if (budget.spent() || !isSafeRelPath(rel, platform)) return undefined;
1459
+ const absolute = p.join(root, rel);
1460
+ const stats = await deps.fs.lstat(absolute);
1461
+ if (stats.isSymbolicLink()) {
1462
+ untracked.set(rel, UNTRACKED_SYMLINK);
1463
+ } else if (stats.isFile()) {
1464
+ bytes += stats.size;
1465
+ if (bytes > MAX_UNTRACKED_BYTES) return undefined;
1466
+ untracked.set(rel, sha256(await deps.fs.readFile(absolute, { signal: budget.signal })));
1467
+ } else {
1468
+ return undefined;
1469
+ }
1470
+ }
1471
+ if (budget.spent()) return undefined;
1472
+ return { root, head, commit, untracked, tracked, captureReasons, capturedAt: Date.now() };
1473
+ }
1474
+
1475
+ interface PrivateIndexEnv {
1476
+ readonly argv: ArgvSeam;
1477
+ readonly fs: ReferenceFs;
1478
+ readonly root: string;
1479
+ readonly tmpdir: string;
1480
+ readonly platform: NodeJS.Platform;
1481
+ readonly pid: number;
1482
+ readonly logger?: Logger;
1483
+ }
1484
+
1485
+ /**
1486
+ * Section 3 step 4 (QA-1.5-1/2): run `use` with a private copy of the user's
1487
+ * index, held in a scratch omr-ref dir that is removed afterwards. Every index
1488
+ * write of that git run (stat refresh, lock, temporary stash index) lands next
1489
+ * to the copy, never in the user's .git. Undefined when the copy cannot be made.
1490
+ */
1491
+ async function withPrivateIndex<T>(
1492
+ env: PrivateIndexEnv,
1493
+ budget: Budget,
1494
+ use: (copy: string) => Promise<T | undefined>,
1495
+ ): Promise<T | undefined> {
1496
+ const p = pathFor(env.platform);
1497
+ if (budget.spent()) return undefined;
1498
+ const indexOut = await runGit(env.argv, ["rev-parse", "--git-path", "index"], {
1499
+ cwd: env.root, timeoutMs: budget.remaining(), signal: budget.signal,
1500
+ });
1501
+ if (!indexOut || indexOut.code !== 0 || budget.spent()) return undefined;
1502
+ const indexFile = p.resolve(env.root, stripNewline(indexOut.stdout));
1503
+ const tmpRoots = await tmpRootsFor(env.fs, env.tmpdir, env.platform);
1504
+ const realTmp = p.resolve(await env.fs.realpath(env.tmpdir));
1505
+ const scratch = p.join(realTmp, refDirName(env.pid, randomBytes(8).toString("hex")));
1506
+ assertSafeRefDir(scratch, tmpRoots, env.platform);
1507
+ const key = comparable(scratch, env.platform);
1508
+ ACTIVE.add(key);
1509
+ let created = false;
1510
+ try {
1511
+ // Non-recursive: EEXIST throws, and a dir we did not create is never cleaned up.
1512
+ await env.fs.mkdir(scratch, { mode: 0o700 });
1513
+ created = true;
1514
+ if (env.platform !== "win32") await env.fs.chmod(scratch, 0o700);
1515
+ const copy = p.join(scratch, "index");
1516
+ const original = await env.fs.lstat(indexFile);
1517
+ const bytes = await env.fs.readFile(indexFile, { signal: budget.signal });
1518
+ await env.fs.writeFile(copy, bytes, { mode: 0o600, flag: "wx" });
1519
+ // Racy-git detection re-checks the content of entries whose mtime is not older than
1520
+ // the index FILE's mtime. A fresh copy's later mtime would make git trust stale stat
1521
+ // data and miss a same-size edit made in the index's second. The original mtime,
1522
+ // floored to ms (never later than the original), keeps that protection.
1523
+ const mtime = new Date(Math.floor(original.mtimeMs));
1524
+ await env.fs.utimes(copy, mtime, mtime);
1525
+ if (budget.spent()) return undefined;
1526
+ return await use(copy);
1527
+ } finally {
1528
+ try {
1529
+ if (created) {
1530
+ const ctx: CleanupContext = { argv: env.argv, fs: env.fs, root: env.root, tmpRoots, platform: env.platform, logger: env.logger };
1531
+ if (!(await removeReferenceDir(ctx, scratch, [], { git: false, unlockOwnLock: false }))) RELEASED.add(key);
1532
+ }
1533
+ } finally {
1534
+ ACTIVE.delete(key);
1535
+ }
1536
+ }
1537
+ }
1538
+
1539
+
1540
+ // --- materialize (sections 4 and 5) -------------------------------------------
1541
+
1542
+ function insideOrEqual(child: string, parent: string, platform: NodeJS.Platform): boolean {
1543
+ return comparable(child, platform) === comparable(parent, platform) || isStrictlyInside(child, parent, platform);
1544
+ }
1545
+
1546
+ function byCodeUnit(a: string, b: string): number {
1547
+ return a < b ? -1 : a > b ? 1 : 0;
1548
+ }
1549
+
1550
+ /** Section 2d: top-level entries of a node_modules dir plus one level under each `@scope`. */
1551
+ async function packageEntries(fs: ReferenceFs, nodeModules: string, platform: NodeJS.Platform): Promise<string[]> {
1552
+ const p = pathFor(platform);
1553
+ const readdirOrEmpty = async (dir: string) => {
1554
+ try {
1555
+ return await fs.readdir(dir);
1556
+ } catch {
1557
+ // Unreadable: nothing to inspect; drift through it cannot be detected (OPEN RISKS).
1558
+ return [];
1559
+ }
1560
+ };
1561
+ const result: string[] = [];
1562
+ for (const name of await readdirOrEmpty(nodeModules)) {
1563
+ const full = p.join(nodeModules, name);
1564
+ if (!name.startsWith("@")) {
1565
+ result.push(full);
1566
+ continue;
1567
+ }
1568
+ const stats = await lstatOrMissing(fs, full);
1569
+ if (stats && stats.isDirectory() && !stats.isSymbolicLink()) {
1570
+ for (const inner of await readdirOrEmpty(full)) result.push(p.join(full, inner));
1571
+ } else {
1572
+ result.push(full);
1573
+ }
1574
+ }
1575
+ return result;
1576
+ }
1577
+
1578
+ /** Section 4. Never throws; on failure nothing is left behind (the dispose pipeline has run). */
1579
+ export async function materialize(
1580
+ ref: DispatchReference,
1581
+ currentTree: TreeSnapshot | undefined,
1582
+ signal: AbortSignal,
1583
+ deps: ReferenceDeps,
1584
+ ): Promise<MaterializeResult> {
1585
+ const platform = deps.platform ?? process.platform;
1586
+ const p = pathFor(platform);
1587
+ const fs = deps.fs;
1588
+ const budget = makeBudget(signal, deps.timeoutMs ?? DEFAULT_MATERIALIZE_TIMEOUT_MS);
1589
+ const root = p.resolve(ref.root);
1590
+ const links: string[] = [];
1591
+ let dir: string | undefined;
1592
+ let ctx: CleanupContext | undefined;
1593
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
1594
+ const fail = (reason: MaterializeFailure, detail: string): MaterializeResult => ({ ok: false, reason, detail });
1595
+ const cleanup = async () => {
1596
+ clearInterval(heartbeat);
1597
+ if (!dir) return;
1598
+ const key = comparable(dir, platform);
1599
+ try {
1600
+ // Our own dir: its omr lock (or the fallback's "initializing") is our own add's.
1601
+ if (ctx && !(await removeReferenceDir(ctx, dir, links, { git: true, unlockOwnLock: true }))) RELEASED.add(key);
1602
+ } finally {
1603
+ ACTIVE.delete(key);
1604
+ }
1605
+ };
1606
+ const abandon = async (reason: MaterializeFailure, detail: string) => {
1607
+ await cleanup();
1608
+ return fail(reason, detail);
1609
+ };
1610
+ const git = async (args: readonly string[]) =>
1611
+ budget.spent() ? undefined : runGit(deps.argv, args, { cwd: root, timeoutMs: budget.remaining(), signal: budget.signal });
1612
+
1613
+ try {
1614
+ // 0. Same-repository guard.
1615
+ if (currentTree) {
1616
+ const cwd = p.resolve(currentTree.cwd);
1617
+ const realRoot = p.resolve(await fs.realpath(root));
1618
+ if (!insideOrEqual(cwd, root, platform) && !insideOrEqual(cwd, realRoot, platform)) {
1619
+ return fail("error", "currentTree is not inside the reference repository");
1620
+ }
1621
+ }
1622
+ // 1. The unreferenced stash commit may have been pruned (section 8).
1623
+ const exists = await git(["cat-file", "-e", `${ref.commit}^{commit}`]);
1624
+ if (budget.spent()) return fail("aborted", "aborted before the worktree was created");
1625
+ if (!exists || exists.code !== 0) return fail("commit-missing", `commit ${ref.commit} is not in the repository`);
1626
+ // 2. Name and guard the dir before anything is created.
1627
+ const tmp = deps.tmpdir ?? osTmpdir();
1628
+ const tmpRoots = await tmpRootsFor(fs, tmp, platform);
1629
+ const realTmp = p.resolve(await fs.realpath(tmp));
1630
+ const suffix = (deps.randomSuffix ?? (() => randomBytes(8).toString("hex")))();
1631
+ const candidate = p.join(realTmp, refDirName(deps.pid ?? process.pid, suffix));
1632
+ assertSafeRefDir(candidate, tmpRoots, platform);
1633
+ if (await lstatOrMissing(fs, candidate)) return fail("unsafe-path", `${candidate} already exists`);
1634
+ const key = comparable(candidate, platform);
1635
+ ACTIVE.add(key);
1636
+ try {
1637
+ // Private before the first checked-out byte (QA-1.5-10); git checks out into this
1638
+ // empty dir. Non-recursive: a racing creator makes it throw, and a dir we did not
1639
+ // create is never cleaned up.
1640
+ await fs.mkdir(candidate, { mode: 0o700 });
1641
+ } catch (error) {
1642
+ ACTIVE.delete(key);
1643
+ const code = errorCode(error);
1644
+ return fail(code === "EEXIST" ? "unsafe-path" : "error", `${candidate} could not be created: ${describeError(error)}`);
1645
+ }
1646
+ dir = candidate;
1647
+ ctx = { argv: deps.argv, fs, root, tmpRoots, platform, logger: deps.logger };
1648
+ // Heartbeat (QA-1.5-4): while the handle is in use, the dir's mtime stays younger than
1649
+ // STALE_REFERENCE_AGE_MS, so another process's GC never takes a live reference for a
1650
+ // PID-reuse leftover. Cleared first thing in cleanup().
1651
+ const beating = dir;
1652
+ heartbeat = setInterval(() => {
1653
+ const now = new Date();
1654
+ fs.utimes(beating, now, now).catch((error: unknown) =>
1655
+ deps.logger?.warn("reference heartbeat failed", { dir: beating, error: describeError(error) }));
1656
+ }, deps.heartbeatMs ?? HEARTBEAT_INTERVAL_MS);
1657
+ heartbeat.unref();
1658
+ if (platform !== "win32") await fs.chmod(dir, 0o700); // exact mode, whatever the umask
1659
+ // 3. Hooks disabled (D9): core.hooksPath names a fresh random path in the tmp root,
1660
+ // outside the worktree, so no committed content can create it (QA-1.5-8).
1661
+ // LC_ALL=C keeps the "initializing" lock reason untranslated, so an abort
1662
+ // mid-checkout leaves a lock that cleanup recognises (QA-1.5-5).
1663
+ const noHooks = p.join(realTmp, `omr-nohooks-${randomBytes(8).toString("hex")}`);
1664
+ if (await lstatOrMissing(fs, noHooks)) return await abandon("unsafe-path", `${noHooks} already exists`);
1665
+ // --lock --reason (QA-1.5-12): git writes our reason instead of "initializing" from
1666
+ // the start and keeps it after the checkout, so a user's `git worktree remove
1667
+ // [--force]` refuses this entry while its links lead into the live node_modules.
1668
+ const add = async (lock: readonly string[]) => budget.spent() ? undefined : runGit(deps.argv, [
1669
+ "-c", `core.hooksPath=${noHooks}`,
1670
+ "-c", "advice.detachedHead=false",
1671
+ "worktree", "add", "--detach", ...lock, candidate, ref.commit,
1672
+ ], { cwd: root, timeoutMs: budget.remaining(), signal: budget.signal, env: { LC_ALL: "C" } });
1673
+ let added = await add(["--lock", "--reason", referenceLockReason(deps.pid ?? process.pid)]);
1674
+ if (added && added.code !== 0 && !budget.spent() && ADD_LOCK_UNSUPPORTED.test(added.stderr)) {
1675
+ // git < 2.33: the option parser failed before anything was written; the dir must still be empty.
1676
+ if ((await fs.readdir(dir)).length > 0) return await abandon("worktree-add-failed", added.stderr.trim());
1677
+ deps.logger?.warn("git worktree add has no --lock --reason (git < 2.33): reference worktree left unlocked", { dir });
1678
+ added = await add([]);
1679
+ }
1680
+ if (budget.spent()) return await abandon("aborted", "aborted during git worktree add");
1681
+ if (!added || added.code !== 0) return await abandon("worktree-add-failed", added?.stderr.trim() ?? "");
1682
+
1683
+ // 3b. Byte-exactness of the checkout (section 2e/2f, QA-1.5-6).
1684
+ const reasons: InexactReason[] = [...ref.captureReasons];
1685
+ const autocrlf = await git(["config", "--get", "core.autocrlf"]);
1686
+ if (budget.spent()) return await abandon("aborted", "aborted while reading core.autocrlf");
1687
+ if (autocrlf && autocrlf.code === 0 && !/^(?:false|no|off|0|)$/i.test(autocrlf.stdout.trim())) {
1688
+ reasons.push({ cause: "checkout-conversion", path: "" });
1689
+ }
1690
+ for (const [rel, hash] of [...ref.tracked].sort(([a], [b]) => byCodeUnit(a, b))) {
1691
+ if (budget.spent()) return await abandon("aborted", "aborted while comparing tracked files");
1692
+ if (!isSafeRelPath(rel, platform)) {
1693
+ reasons.push({ cause: "checkout-conversion", path: rel });
1694
+ continue;
1695
+ }
1696
+ const checkedOut = p.join(dir, rel);
1697
+ const stats = await lstatOrMissing(fs, checkedOut);
1698
+ const same = stats !== undefined && stats.isFile() && !stats.isSymbolicLink() &&
1699
+ sha256(await fs.readFile(checkedOut, { signal: budget.signal })) === hash;
1700
+ if (!same) reasons.push({ cause: "checkout-conversion", path: rel });
1701
+ }
1702
+
1703
+ // 4. Untracked files: the hashed buffer is the written buffer.
1704
+ const changed = new Set<string>();
1705
+ const inexact = (cause: InexactCause, path: string) => {
1706
+ reasons.push({ cause, path });
1707
+ changed.add(path);
1708
+ };
1709
+ for (const [rel, hash] of [...ref.untracked].sort(([a], [b]) => byCodeUnit(a, b))) {
1710
+ if (budget.spent()) return await abandon("aborted", "aborted while copying untracked files");
1711
+ if (!isSafeRelPath(rel, platform)) {
1712
+ reasons.push({ cause: "untracked-unsafe-path", path: rel });
1713
+ continue;
1714
+ }
1715
+ if (hash === UNTRACKED_SYMLINK) {
1716
+ reasons.push({ cause: "untracked-symlink", path: rel });
1717
+ continue;
1718
+ }
1719
+ const source = p.join(root, rel);
1720
+ let stats: ReferenceStats | undefined;
1721
+ let bytes: Uint8Array;
1722
+ try {
1723
+ stats = await lstatOrMissing(fs, source);
1724
+ if (!stats) {
1725
+ inexact("untracked-deleted", rel);
1726
+ continue;
1727
+ }
1728
+ if (!stats.isFile() || stats.isSymbolicLink()) {
1729
+ inexact("untracked-not-file", rel);
1730
+ continue;
1731
+ }
1732
+ bytes = await fs.readFile(source, { signal: budget.signal });
1733
+ } catch (error) {
1734
+ if (budget.spent()) return await abandon("aborted", describeError(error));
1735
+ inexact("untracked-unreadable", rel);
1736
+ continue;
1737
+ }
1738
+ if (sha256(bytes) !== hash) {
1739
+ inexact("untracked-modified", rel);
1740
+ continue;
1741
+ }
1742
+ const dest = p.join(dir, rel);
1743
+ const parent = p.dirname(dest);
1744
+ await fs.mkdir(parent, { recursive: true });
1745
+ if (!insideOrEqual(p.resolve(await fs.realpath(parent)), dir, platform)) {
1746
+ inexact("untracked-unsafe-path", rel);
1747
+ continue;
1748
+ }
1749
+ await fs.writeFile(dest, bytes, { mode: stats.mode & 0o777, flag: "wx" });
1750
+ }
1751
+
1752
+ // 5. Discovery of ignored entries; nothing ignored is ever copied.
1753
+ const ignored = await git(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"]);
1754
+ if (budget.spent()) return await abandon("aborted", "aborted during ignored-file discovery");
1755
+ if (!ignored || ignored.code !== 0) return await abandon("error", ignored?.stderr.trim() ?? "ignored-file discovery failed");
1756
+ const unreproduced: string[] = [];
1757
+ const candidates: string[] = [];
1758
+ for (const entry of splitZ(ignored.stdout)) {
1759
+ const rel = entry.replace(/\/$/, "");
1760
+ if (rel.split("/").at(-1) === "node_modules" && isSafeRelPath(rel, platform)) candidates.push(entry);
1761
+ else unreproduced.push(entry);
1762
+ }
1763
+
1764
+ // 6. Link node_modules (section 5), parents before children (git's order).
1765
+ const linkTargets: string[] = [];
1766
+ for (const entry of candidates) {
1767
+ if (budget.spent()) return await abandon("aborted", "aborted while linking node_modules");
1768
+ const rel = entry.replace(/\/$/, "");
1769
+ const source = p.join(root, rel);
1770
+ const sourceStats = await lstatOrMissing(fs, source);
1771
+ let target: string | undefined;
1772
+ if (sourceStats && (sourceStats.isDirectory() || sourceStats.isSymbolicLink())) {
1773
+ try {
1774
+ target = p.resolve(await fs.realpath(source));
1775
+ } catch {
1776
+ // Dangling link: nothing to link to.
1777
+ target = undefined;
1778
+ }
1779
+ }
1780
+ const targetStats = target ? await lstatOrMissing(fs, target) : undefined;
1781
+ const linkPath = p.join(dir, rel);
1782
+ const parent = p.dirname(linkPath);
1783
+ const parentStats = await lstatOrMissing(fs, parent);
1784
+ const linkable =
1785
+ target !== undefined &&
1786
+ targetStats !== undefined && targetStats.isDirectory() && !targetStats.isSymbolicLink() &&
1787
+ parentStats !== undefined && parentStats.isDirectory() && !parentStats.isSymbolicLink() &&
1788
+ insideOrEqual(p.resolve(await fs.realpath(parent)), dir, platform) &&
1789
+ isStrictlyInside(linkPath, dir, platform) &&
1790
+ (await lstatOrMissing(fs, linkPath)) === undefined;
1791
+ if (!linkable || target === undefined) {
1792
+ unreproduced.push(entry);
1793
+ continue;
1794
+ }
1795
+ links.push(linkPath);
1796
+ await fs.symlink(target, linkPath, platform === "win32" ? "junction" : "dir");
1797
+ linkTargets.push(target);
1798
+ }
1799
+
1800
+ // 7. Drift checks (section 2 c and d). Porcelain `git diff` rewrites the index
1801
+ // it compares with even under --no-optional-locks, so it gets a private copy.
1802
+ const scratchEnv: PrivateIndexEnv = {
1803
+ argv: deps.argv, fs, root, tmpdir: tmp, platform, pid: deps.pid ?? process.pid, logger: deps.logger,
1804
+ };
1805
+ const diff = await withPrivateIndex(scratchEnv, budget, (copy) =>
1806
+ runGit(deps.argv, ["-c", "core.splitIndex=false", "diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", ref.commit, "--"], {
1807
+ cwd: root, timeoutMs: budget.remaining(), signal: budget.signal, env: { GIT_INDEX_FILE: copy },
1808
+ }));
1809
+ const nowUntracked = await git(["ls-files", "--others", "--exclude-standard", "-z"]);
1810
+ if (budget.spent()) return await abandon("aborted", "aborted during drift checks");
1811
+ if (!diff || diff.code !== 0 || !nowUntracked || nowUntracked.code !== 0) {
1812
+ return await abandon("error", (diff?.stderr ?? nowUntracked?.stderr ?? "drift check failed").trim());
1813
+ }
1814
+ for (const rel of splitZ(diff.stdout)) changed.add(rel);
1815
+ for (const rel of splitZ(nowUntracked.stdout)) if (!ref.untracked.has(rel)) changed.add(rel);
1816
+ const changedSorted = [...changed].sort(byCodeUnit);
1817
+ for (const rel of changedSorted) {
1818
+ if (DEPENDENCY_FILES.has(rel.split("/").at(-1) ?? "")) reasons.push({ cause: "dependency-drift", path: rel });
1819
+ }
1820
+ const realRoot = p.resolve(await fs.realpath(root));
1821
+ const workspaceDirs = new Set<string>();
1822
+ for (const target of linkTargets) {
1823
+ for (const entry of await packageEntries(fs, target, platform)) {
1824
+ const stats = await lstatOrMissing(fs, entry);
1825
+ if (!stats || !stats.isSymbolicLink()) continue;
1826
+ let real: string;
1827
+ try {
1828
+ real = p.resolve(await fs.realpath(entry));
1829
+ } catch {
1830
+ // Dangling package link: it cannot load code from the live tree.
1831
+ continue;
1832
+ }
1833
+ const base = [realRoot, root].find((candidateRoot) => isStrictlyInside(real, candidateRoot, platform));
1834
+ if (!base) continue;
1835
+ const rel = p.relative(base, real).split(p.sep).join("/");
1836
+ if (!rel.split("/").includes("node_modules")) workspaceDirs.add(rel);
1837
+ }
1838
+ }
1839
+ const fold = (s: string) => (platform === "win32" ? s.toLowerCase() : s);
1840
+ for (const rel of [...workspaceDirs].sort(byCodeUnit)) {
1841
+ const prefix = fold(rel) + "/";
1842
+ if (changedSorted.some((c) => fold(c) === fold(rel) || fold(c).startsWith(prefix))) {
1843
+ reasons.push({ cause: "workspace-link-drift", path: rel });
1844
+ }
1845
+ }
1846
+
1847
+ // 7b. Clean-file checkout conversion (section 2e, QA-1.5-13): the working-tree eol class
1848
+ // of every tracked path that is neither hashed above (ref.tracked) nor changed since
1849
+ // the commit must be the same in root and dir. Skipped when a repository-wide
1850
+ // conversion reason (core.autocrlf) already makes the reference approximate.
1851
+ const conversion = (path: string) => {
1852
+ if (!reasons.some((r) => r.cause === "checkout-conversion" && r.path === path)) reasons.push({ cause: "checkout-conversion", path });
1853
+ };
1854
+ if (!reasons.some((r) => r.cause === "checkout-conversion" && r.path === "")) {
1855
+ // The caller's signal, not the budget's: this is the last step, so a spent budget
1856
+ // leaves the reference approximate ("" reason) instead of failing it.
1857
+ const eolClasses = async (cwd: string) => {
1858
+ // QA-1.5-18: the full listing. No pathspec limit is sound: a clean file's live bytes come
1859
+ // from its last checkout (old core.autocrlf, legacy `crlf`, later working-tree-encoding).
1860
+ const listed = await runGit(deps.argv, ["ls-files", "--eol", "-z"], {
1861
+ cwd,
1862
+ timeoutMs: budget.remaining(),
1863
+ signal,
1864
+ });
1865
+ return listed && listed.code === 0 ? parseEolList(listed.stdout) : undefined;
1866
+ };
1867
+ // QA-1.5-17: both listings run concurrently, which halves the wall time; the bound
1868
+ // itself is budget.remaining() plus the "" fallback. A truncated listing is a failed
1869
+ // call (QA-1.5-21), so it also takes the "" fallback.
1870
+ const [liveEol, refEol] = await Promise.all([eolClasses(root), eolClasses(dir)]);
1871
+ if (signal.aborted) return await abandon("aborted", "aborted during the eol comparison");
1872
+ if (!liveEol || !refEol) {
1873
+ conversion(""); // not compared: budget spent or git failed
1874
+ } else {
1875
+ // QA-1.5-16: a path edited since capture (in changed, not in ref.tracked) has unknown
1876
+ // dispatch bytes; it is flagged when the reference's checkout converted it (w/ != i/).
1877
+ const differing = [...refEol]
1878
+ .filter(([rel, { i, w }]) => {
1879
+ if (ref.tracked.has(rel)) return false;
1880
+ if (changed.has(rel)) return i !== "" && w !== "" && i !== w;
1881
+ const live = liveEol.get(rel);
1882
+ return live !== undefined && live.w !== w;
1883
+ })
1884
+ .map(([rel]) => rel)
1885
+ .sort(byCodeUnit);
1886
+ for (const rel of differing.slice(0, MAX_CONVERSION_REASONS)) conversion(rel);
1887
+ if (differing.length > MAX_CONVERSION_REASONS) conversion("");
1888
+ }
1889
+ }
1890
+
1891
+ // 8. The handle.
1892
+ const refDir = dir;
1893
+ let disposing: Promise<void> | undefined;
1894
+ const reference: MaterializedReference = {
1895
+ dir: refDir,
1896
+ exact: reasons.length === 0,
1897
+ inexactReasons: reasons,
1898
+ unreproduced,
1899
+ links: [...links],
1900
+ toRefPath(livePath: string) {
1901
+ if (!p.isAbsolute(livePath)) return undefined;
1902
+ const absolute = p.resolve(livePath);
1903
+ // E2E-2: the root as git spelled it, or its native realpath. The recheck passes the
1904
+ // planner's canonical paths (runnerCwd, failing files), which are realpath'd: a root
1905
+ // reached through a junction, a subst drive or an 8.3 name matched neither otherwise.
1906
+ for (const base of [root, realRoot]) {
1907
+ if (comparable(absolute, platform) === comparable(base, platform)) return refDir;
1908
+ if (isStrictlyInside(absolute, base, platform)) return p.join(refDir, p.relative(base, absolute));
1909
+ }
1910
+ return undefined;
1911
+ },
1912
+ dispose() {
1913
+ disposing ??= cleanup();
1914
+ return disposing;
1915
+ },
1916
+ };
1917
+ return { ok: true, reference };
1918
+ } catch (error) {
1919
+ const reason: MaterializeFailure =
1920
+ error instanceof UnsafeReferencePathError ? "unsafe-path" : budget.spent() ? "aborted" : "error";
1921
+ return await abandon(reason, describeError(error));
1922
+ }
1923
+ }
1924
+
1925
+ // --- gcStaleReferences (section 11) -------------------------------------------
1926
+
1927
+ interface WorktreeEntry {
1928
+ path: string;
1929
+ locked: boolean;
1930
+ /** The text after "locked " ("" for a bare `locked` line); a C-quoted reason stays quoted and so never matches. */
1931
+ lockReason?: string;
1932
+ prunable: boolean;
1933
+ }
1934
+
1935
+ function parseWorktreeList(stdout: string): WorktreeEntry[] {
1936
+ const entries: WorktreeEntry[] = [];
1937
+ let current: WorktreeEntry | undefined;
1938
+ for (const line of stdout.split(/\r?\n/)) {
1939
+ if (line.startsWith("worktree ")) {
1940
+ current = { path: line.slice("worktree ".length), locked: false, prunable: false };
1941
+ entries.push(current);
1942
+ } else if (current && (line === "locked" || line.startsWith("locked "))) {
1943
+ current.locked = true;
1944
+ current.lockReason = line.slice("locked ".length);
1945
+ } else if (current && (line === "prunable" || line.startsWith("prunable "))) {
1946
+ current.prunable = true;
1947
+ }
1948
+ }
1949
+ return entries;
1950
+ }
1951
+
1952
+ /** Section 11. Never throws; touches only stale omr-ref-* dirs directly under a tmp root. */
1953
+ export async function gcStaleReferences(root: string, deps: ReferenceDeps): Promise<GcReport> {
1954
+ const report = { removed: [] as string[], kept: [] as string[], failed: [] as string[] };
1955
+ try {
1956
+ await gcInner(root, deps, report);
1957
+ } catch (error) {
1958
+ deps.logger?.warn("reference GC failed", { error: describeError(error) });
1959
+ }
1960
+ if (report.failed.length > 0) deps.logger?.warn("reference GC left dirs in place", { failed: report.failed.length });
1961
+ return report;
1962
+ }
1963
+
1964
+ async function gcInner(
1965
+ root: string,
1966
+ deps: ReferenceDeps,
1967
+ report: { removed: string[]; kept: string[]; failed: string[] },
1968
+ ): Promise<void> {
1969
+ const platform = deps.platform ?? process.platform;
1970
+ const p = pathFor(platform);
1971
+ const fs = deps.fs;
1972
+ const now = deps.now ?? Date.now;
1973
+ const isAlive = deps.isAlive ?? isAliveDefault;
1974
+ const budget = makeBudget(new AbortController().signal, deps.timeoutMs ?? DEFAULT_MATERIALIZE_TIMEOUT_MS);
1975
+ const absRoot = p.resolve(root);
1976
+ const tmpRoots = await tmpRootsFor(fs, deps.tmpdir ?? osTmpdir(), platform);
1977
+ const ctx: CleanupContext = {
1978
+ argv: deps.argv, fs, root: absRoot, tmpRoots, platform, logger: deps.logger, deadline: Date.now() + budget.remaining(),
1979
+ };
1980
+ // Section 11 step 3 (QA-1.5-4). The caller skips ACTIVE dirs first. An alive owner's dir
1981
+ // is stale only once its heartbeat (mtime) is older than STALE_REFERENCE_AGE_MS, i.e.
1982
+ // the PID was reused. Our own PID has no special case: RELEASED names our own leftovers.
1983
+ const released = (keys: readonly string[]) => keys.some((k) => RELEASED.has(k));
1984
+ const stale = (pid: number, stats: ReferenceStats | undefined, keys: readonly string[]) =>
1985
+ !stats || released(keys) || !isAlive(pid) || now() - stats.mtimeMs > STALE_REFERENCE_AGE_MS;
1986
+ const collected = (keys: readonly string[]) => {
1987
+ for (const k of keys) RELEASED.delete(k);
1988
+ };
1989
+ const isSafe = (dir: string) => {
1990
+ try {
1991
+ assertSafeRefDir(dir, tmpRoots, platform);
1992
+ return true;
1993
+ } catch {
1994
+ // Not an omr reference dir under a tmp root: never a candidate (R3).
1995
+ return false;
1996
+ }
1997
+ };
1998
+
1999
+ const gitRun = (): GitRun => ({ cwd: absRoot, timeoutMs: budget.remaining(), signal: budget.signal });
2000
+ const list = await runGit(deps.argv, ["worktree", "list", "--porcelain"], gitRun());
2001
+ if (!list || list.code !== 0) {
2002
+ deps.logger?.warn("reference GC skipped: git worktree list failed", { stderr: list?.stderr.trim() });
2003
+ return;
2004
+ }
2005
+ const entries = parseWorktreeList(list.stdout);
2006
+ const registered = new Set(entries.map((entry) => comparable(entry.path, platform)));
2007
+
2008
+ // 1-4. Registered candidates.
2009
+ for (const entry of entries) {
2010
+ if (budget.spent()) return;
2011
+ const dir = p.resolve(entry.path);
2012
+ const parsed = parseRefDirName(p.basename(dir));
2013
+ if (!parsed || !isSafe(dir)) continue;
2014
+ const key = comparable(dir, platform);
2015
+ const keys = [key];
2016
+ const ownLock = entry.locked && isOwnLockReason(dir, entry.lockReason, platform);
2017
+ if ((entry.locked && !ownLock) || ACTIVE.has(key)) {
2018
+ report.kept.push(dir);
2019
+ continue;
2020
+ }
2021
+ const stats = await lstatOrMissing(fs, dir);
2022
+ let collect: boolean;
2023
+ if (!entry.locked) {
2024
+ collect = stale(parsed.pid, stats, keys);
2025
+ } else if (entry.lockReason === INITIALIZING_LOCK_REASON) {
2026
+ // QA-1.5-5: left by a killed `git worktree add`; lifted only once no add can still
2027
+ // be running: our own released dir, or a dead owner.
2028
+ collect = released(keys) || !isAlive(parsed.pid);
2029
+ } else {
2030
+ // QA-1.5-12: our reference lock lasts the handle's whole life, so the section 11 rules
2031
+ // apply as to an unlocked entry, except a missing dir of an alive owner: that owner
2032
+ // may be between its fs.rm and its own unlock (section 6 step 4).
2033
+ // QA-1.5-15: a missing dir carrying our exact reason is collected whatever the pid's
2034
+ // liveness (a reused pid would otherwise keep it forever). Racing an alive owner between
2035
+ // its fs.rm and its unlock is benign: both sides only unlock our reason and remove an
2036
+ // entry whose dir is gone.
2037
+ collect =
2038
+ stats === undefined ||
2039
+ released(keys) ||
2040
+ !isAlive(parsed.pid) ||
2041
+ now() - stats.mtimeMs > STALE_REFERENCE_AGE_MS;
2042
+ }
2043
+ if (!collect) {
2044
+ report.kept.push(dir);
2045
+ continue;
2046
+ }
2047
+ if (await removeReferenceDir(ctx, dir, [], { git: true, unlockOwnLock: ownLock })) {
2048
+ collected(keys);
2049
+ report.removed.push(dir);
2050
+ } else {
2051
+ report.failed.push(dir);
2052
+ }
2053
+ }
2054
+
2055
+ // 5. Orphans of this repository (D7).
2056
+ const common = await runGit(deps.argv, ["rev-parse", "--git-common-dir"], gitRun());
2057
+ if (!common || common.code !== 0) return;
2058
+ const gitDir = p.resolve(absRoot, stripNewline(common.stdout));
2059
+ const gitDirs = [gitDir];
2060
+ try {
2061
+ gitDirs.push(p.resolve(await fs.realpath(gitDir)));
2062
+ } catch {
2063
+ // Only the resolved form is available.
2064
+ gitDirs.push(gitDir);
2065
+ }
2066
+ const seenRoots = new Set<string>();
2067
+ for (const tmpRoot of tmpRoots) {
2068
+ const key = comparable(tmpRoot, platform);
2069
+ if (seenRoots.has(key)) continue;
2070
+ seenRoots.add(key);
2071
+ let names: string[];
2072
+ try {
2073
+ names = await fs.readdir(tmpRoot);
2074
+ } catch {
2075
+ // Unreadable tmp root: no orphans can be found there.
2076
+ continue;
2077
+ }
2078
+ for (const name of names) {
2079
+ if (budget.spent()) return;
2080
+ const parsed = parseRefDirName(name);
2081
+ if (!parsed) continue;
2082
+ const dir = p.join(tmpRoot, name);
2083
+ if (!isSafe(dir)) continue;
2084
+ const stats = await lstatOrMissing(fs, dir);
2085
+ if (!stats || stats.isSymbolicLink() || !stats.isDirectory()) continue;
2086
+ let realDir = dir;
2087
+ try {
2088
+ realDir = p.resolve(await fs.realpath(dir));
2089
+ } catch {
2090
+ // Vanished meanwhile: nothing to collect.
2091
+ continue;
2092
+ }
2093
+ const keys = [comparable(dir, platform), comparable(realDir, platform)];
2094
+ if (keys.some((k) => registered.has(k) || ACTIVE.has(k))) continue;
2095
+ if (!stale(parsed.pid, stats, keys)) {
2096
+ report.kept.push(dir);
2097
+ continue;
2098
+ }
2099
+ const dotGit = p.join(dir, ".git");
2100
+ const dotGitStats = await lstatOrMissing(fs, dotGit);
2101
+ if (dotGitStats) {
2102
+ if (!dotGitStats.isFile() || dotGitStats.isSymbolicLink()) continue;
2103
+ const text = new TextDecoder().decode(await fs.readFile(dotGit, {}));
2104
+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(text);
2105
+ if (!match) continue;
2106
+ const target = p.resolve(dir, match[1]);
2107
+ if (!gitDirs.some((g) => isStrictlyInside(target, g, platform))) continue; // another repository's orphan
2108
+ }
2109
+ if (await removeReferenceDir(ctx, dir, [], { git: false, unlockOwnLock: false })) {
2110
+ collected(keys);
2111
+ report.removed.push(dir);
2112
+ } else {
2113
+ report.failed.push(dir);
2114
+ }
2115
+ }
2116
+ }
2117
+ }