brl-subagent 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/AGENT.md +1 -1
  2. package/README.md +3 -3
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +3 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +1 -1
  11. package/src/git.ts +220 -8
  12. package/src/headstate.ts +3 -3
  13. package/src/history.ts +21 -3
  14. package/src/index.ts +109 -4473
  15. package/src/loader.ts +1 -1
  16. package/src/logging.ts +1 -1
  17. package/src/mode-prologue.ts +4 -10
  18. package/src/mode-runners.ts +1575 -0
  19. package/src/notify-completion.ts +35 -8
  20. package/src/params.ts +14 -13
  21. package/src/preflight.ts +123 -16
  22. package/src/prelude.ts +14 -5
  23. package/src/presets.ts +3 -5
  24. package/src/proc.ts +2 -3
  25. package/src/recovery-engine.ts +1 -1
  26. package/src/recovery-surface.ts +1 -2
  27. package/src/recovery.ts +2 -3
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +2 -3
  30. package/src/runner.ts +47 -18
  31. package/src/runtime.ts +50 -0
  32. package/src/sanitize.ts +20 -2
  33. package/src/scheduler.ts +1 -2
  34. package/src/scratch-root.ts +909 -0
  35. package/src/scratch-spawn.ts +256 -0
  36. package/src/session-manager.ts +75 -7
  37. package/src/state.ts +12 -14
  38. package/src/templates.ts +3 -5
  39. package/src/terminal-notifier.ts +405 -0
  40. package/src/transcript.ts +1 -1
  41. package/src/tui-format.ts +3 -1
  42. package/src/tui.ts +42 -32
  43. package/src/types.ts +29 -3
  44. package/src/unit-params.ts +113 -0
  45. package/src/unit-run.ts +35 -15
  46. package/src/validate.ts +2 -3
  47. package/src/worktree-report.ts +142 -0
@@ -0,0 +1,909 @@
1
+ // Purpose: The shipped scratch root — platform cache resolution, the validated owner-only root, per-run directories, the settle marker, and retention pruning.
2
+
3
+ /**
4
+ * brl-subagent — the shipped scratch root (issue #511, U1)
5
+ *
6
+ * WHY THIS MODULE EXISTS. The extension used to tell agents to bank progress in
7
+ * `/tmp/brl-<label>-bank.md`. `/tmp` is world-writable (anyone can pre-create the path, and rename
8
+ * authority over our file comes from write permission on its PARENT), ambiguous about who wrote it,
9
+ * and on most Linux hosts a `tmpfs` — a bank that does not survive a reboot, which is the one
10
+ * property a progress bank exists for. This module replaces the convention with one validated root
11
+ * under the user's cache directory, and it is the only place a shipped scratch path is decided.
12
+ *
13
+ * MIRRORED, NOT IMPORTED. The tooling half (`scripts/lib/scratch-root.mjs`, #512/#516) owns the same
14
+ * rules for the cockpit, but it is not shipped and it lives on a different surface (untyped `.mjs`
15
+ * plus a CLI). The RULES are mirrored here: the two-zone chain predicate (every ancestor must be a real
16
+ * directory owned by root or by us — a FOREIGN OWNER is refused — and the root itself must be ours), an
17
+ * explicit `chmod` after `mkdir` so the mode does not depend on the umask, and `lstat` as the first read
18
+ * on every component. FOUR DELIBERATE differences: the first two narrow the shipped contract, the third
19
+ * relaxes one clause and says why, and the fourth is the LINK rule, which is not shared at all.
20
+ *
21
+ * 1. a Linux `tmpfs` root is a WARNING, not a refusal. A user may legitimately keep `$HOME` (and
22
+ * therefore `~/.cache`) on a `tmpfs` — a live session does exactly that — and refusing would
23
+ * break delegation for them. The bank is then announced as not surviving a reboot instead.
24
+ * 2. the root is PLATFORM-SPECIFIC, because `~/.cache` is an XDG convention and not a portable
25
+ * one (see `rootLayout`). `XDG_CACHE_HOME` is deliberately ignored: a path from a user-writable
26
+ * environment variable is a path an attacker chooses, and this module's whole job is that the
27
+ * location is ours.
28
+ * 3. a GROUP/OTHER-WRITABLE ANCESTOR is a WARNING, not a refusal (the tooling half still refuses it).
29
+ * A shipped extension must not refuse to run on a shared or corporate machine whose home — or
30
+ * whose `~/.cache` — is group-writable (`0775`/`0770`), and the bank is a CONVENIENCE: the tmpfs
31
+ * warning (difference 1) already accepts a stated risk rather than refusing to work. What is NOT
32
+ * relaxed is OWNERSHIP: an ancestor owned by a third uid is a different trust boundary (its owner
33
+ * can rename what is below it whatever the mode), so it keeps refusing under its own code,
34
+ * `ancestor-not-owned`.
35
+ * 4. the LINK rule is NOT the tooling's. The tooling refuses EVERY symlink and never resolves one
36
+ * (`scripts/lib/scratch-root.mjs:198`; its `checkComponent` cannot walk above a target it never
37
+ * follows). This module refuses a link at the ROOT (`root-symlink`, because the `chmod` would
38
+ * follow it) and RESOLVES — then validates — a link ABOVE it, walking the resolved target's own
39
+ * chain (`checkResolvedAncestor`, `checkTargetAncestors`): a user who moved `~/.cache` to another
40
+ * disk must still be able to delegate, and the parent question is answered by where the link lands.
41
+ *
42
+ * STRICTER, NOT MIRRORED — the ROOT's mode clause. Both surfaces refuse a shareable root, but the
43
+ * tooling refuses group/other access only (`(mode & 0o077) !== 0`, `scripts/lib/scratch-root.mjs:224`),
44
+ * so a `4700` root passes it, while this module demands exactly `0700` (`(mode & 0o7777) !== 0o700`) and
45
+ * refuses that root. The strictness is deliberate and is not relaxed (the clause in `checkComponent`
46
+ * carries the same reason in place): the root is the CONFIDENTIALITY BOUNDARY for the bank's bytes
47
+ * (every run directory and marker is reachable only through it), this module creates it at `0700` and
48
+ * never repairs a mode it did not set, so any setuid/setgid/sticky bit on it is a state this module
49
+ * cannot account for — worth refusing rather than interpreting.
50
+ *
51
+ * NO TEMP FALLBACK, EVER. A root that cannot be placed is `home-unresolvable`, a named error. Falling
52
+ * back to `os.tmpdir()` would reintroduce exactly the defect this module removes.
53
+ *
54
+ * THE POLARITY IS A NAMED RESULT, NEVER A THROW: `{ ok: true, … } | { ok: false, code, message }`.
55
+ * `pruneRuns` is the one best-effort operation (a sweep must not break a run), so a removal failure is
56
+ * reported in its return value and never thrown. `markRunDone`/`ensureRunDir` report their failures.
57
+ *
58
+ * LIMITS, stated rather than implied: group/other write on an ancestor (WARNED here — difference 3 — and
59
+ * refused by the tooling half, so a co-worker with write on that parent can still replace the run
60
+ * directory, and the bank path with it; the warning names the path, the mode and that consequence); a
61
+ * mount-namespace substitution by a user who already holds
62
+ * privileges; NFS, where ownership and `chmod` semantics belong to the server; a root that becomes a
63
+ * mount point, or is renamed by its owner, AFTER it was validated; a symlinked ancestor whose resolved
64
+ * directory is renamed or re-pointed between the `realpath` and the `mkdir` (the TOCTOU window, one
65
+ * link further out, and not closable without an `openat`-style primitive that holds the directory open
66
+ * while it is judged); and Windows, where `fs` reports no meaningful `uid` and synthesized mode bits —
67
+ * the ownership and 0700 clauses are POSIX-only and are skipped there (the symlink and directory
68
+ * clauses still hold, above a resolved target's chain exactly as along the literal one).
69
+ */
70
+
71
+ import {
72
+ chmodSync,
73
+ closeSync,
74
+ constants as fsConstants,
75
+ fchmodSync,
76
+ lstatSync,
77
+ mkdirSync,
78
+ openSync,
79
+ realpathSync,
80
+ readdirSync,
81
+ rmdirSync,
82
+ rmSync,
83
+ statfsSync,
84
+ statSync,
85
+ type Stats,
86
+ } from "node:fs";
87
+ import { homedir } from "node:os";
88
+ import { dirname, join, resolve } from "node:path";
89
+
90
+ /** The one directory below the root that holds per-run scratch directories. */
91
+ export const RUNS_DIR = "runs";
92
+
93
+ /** The progress-bank filename inside a run directory. One name, so the producer and the reader agree. */
94
+ export const BANK_FILENAME = "bank.md";
95
+
96
+ /** The settle marker: present means the run finished, so its directory is prunable once it ages out. */
97
+ export const DONE_MARKER = ".done";
98
+
99
+ /** Retention: a settled run directory older than this many days is pruned. */
100
+ export const KEEP_DAYS = 14;
101
+
102
+ /** The root's mode — owner-only, the confidentiality boundary for the bank's bytes. Every directory
103
+ * this module creates is created at this mode too. */
104
+ export const ROOT_MODE = 0o700;
105
+
106
+ /** The settle marker's mode: owner-only read/write, no group or other bits. */
107
+ export const FILE_MODE = 0o600;
108
+
109
+ /**
110
+ * Linux `TMPFS_MAGIC` — the `f_type` `statfs` reports for a `tmpfs` mount (`/tmp`, `/dev/shm`,
111
+ * `/run/user/<uid>`). A magic number is a per-filesystem constant, never a portable one, which is why
112
+ * the check that reads it runs on Linux alone.
113
+ */
114
+ export const TMPFS_MAGIC = 0x01021994;
115
+
116
+ /** The named refusal codes. One spelling, so the caller, the messages and the tests cannot disagree. */
117
+ export const SCRATCH_ROOT_CODES = Object.freeze([
118
+ "home-unresolvable",
119
+ "root-symlink",
120
+ "root-not-dir",
121
+ "root-not-owned",
122
+ "root-mode",
123
+ // RETAINED, though this surface no longer produces it: the tooling half still refuses under this
124
+ // spelling (difference 3 in the header), and the relaxed clause here is the warning KIND of the same
125
+ // name. Dropping the spelling would split one vocabulary across two surfaces for no gain.
126
+ "ancestor-writable",
127
+ "ancestor-not-owned",
128
+ "ancestor-not-dir",
129
+ // The SAME clause as `ancestor-not-dir`/`root-not-dir`, spelled for the zone it fires in: a link or
130
+ // non-directory at `runs` or `runs/<runId>` is BELOW the root, and a caller matching on the code must
131
+ // not be told a zone the refused component is not in (#527 item 3).
132
+ "below-not-dir",
133
+ "bad-run-id",
134
+ "create-failed",
135
+ ] as const);
136
+
137
+ /** The small, closed taxonomy: every refusal this module can produce is one of these spellings. */
138
+ export type ScratchRootCode = (typeof SCRATCH_ROOT_CODES)[number];
139
+
140
+ /** A refusal. `code` is the contract; `message` names the path and the clause that failed. */
141
+ export interface ScratchRootError {
142
+ ok: false;
143
+ code: ScratchRootCode;
144
+ message: string;
145
+ }
146
+
147
+ /**
148
+ * The kinds of advisory a valid root can carry. One kind is one sentence inside the joined `warning`
149
+ * string — `tmpfs` (the bank does not survive a reboot) and `ancestor-writable` (a co-worker with write
150
+ * on a parent can replace the run directory). A separate field because the SENTENCE is not a stable key:
151
+ * the mount sentence gains a "does not exist yet" clause when the root is created between two calls, so
152
+ * a log-once rule keyed on the text would print the same advisory twice under two spellings.
153
+ */
154
+ export const ROOT_WARNING_KINDS = Object.freeze(["tmpfs", "ancestor-writable"] as const);
155
+
156
+ /** The kind of an advisory, as the caller dedupes it: one kind, one log line per process. */
157
+ export type RootWarningKind = (typeof ROOT_WARNING_KINDS)[number];
158
+
159
+ /**
160
+ * `resolveRoot`: the root to use, plus the advisory a valid root can carry — a `tmpfs` mount warning, an
161
+ * ancestor-writability warning, or both joined with `"; "`. One string, because a valid root has one
162
+ * advisory report; the caller logs it, never parses it, and `warningKinds` names what is inside it so a
163
+ * caller can dedupe by KIND rather than by wording.
164
+ */
165
+ export type ResolveRootResult =
166
+ | { ok: true; root: string; warning?: string; warningKinds?: RootWarningKind[] }
167
+ | ScratchRootError;
168
+
169
+ /** `ensureRunDir`: the run's own directory, and what this call had to create to get there. */
170
+ export type EnsureRunDirResult =
171
+ | { ok: true; root: string; runDir: string; created: string[] }
172
+ | ScratchRootError;
173
+
174
+ /** `markRunDone`: the marker that was written. */
175
+ export type MarkRunDoneResult = { ok: true; path: string } | ScratchRootError;
176
+
177
+ /** Every seam `resolveRoot` needs, injected so the module is testable without the real home. */
178
+ export interface RootOptions {
179
+ platform?: NodeJS.Platform;
180
+ env?: Record<string, string | undefined>;
181
+ /** Injectable; defaults to `os.homedir()` (which may itself fall back to the passwd entry). */
182
+ home?: string;
183
+ /** Injectable `statfs` (the mount-type probe). Defaults to `fs.statfsSync`. */
184
+ statfs?: (path: string) => { type: number };
185
+ /** Where the advisory goes (the same joined string the result carries). No logger import: the caller decides. */
186
+ warn?: (message: string) => void;
187
+ }
188
+
189
+ /** `pruneRuns`'s inputs. `now` is injected so the retention boundary is testable. */
190
+ export interface PruneOptions {
191
+ now?: Date;
192
+ keepDays?: number;
193
+ /** The current run's directory — never pruned, whatever its age. */
194
+ exclude?: string;
195
+ /** Test seam for the one best-effort operation: the default is a recursive, forced remove. */
196
+ remove?: (path: string) => void;
197
+ }
198
+
199
+ /** `pruneRuns` is best-effort: `failed` is the report, not an exception. */
200
+ export interface PruneResult {
201
+ removed: string[];
202
+ kept: string[];
203
+ failed: { path: string; message: string }[];
204
+ }
205
+
206
+ const DAY_MS = 24 * 60 * 60 * 1000;
207
+
208
+ function fail(code: ScratchRootCode, message: string): ScratchRootError {
209
+ return { ok: false, code, message };
210
+ }
211
+
212
+ function describe(error: unknown): string {
213
+ return error instanceof Error ? error.message : String(error);
214
+ }
215
+
216
+ function codeOf(error: unknown): string {
217
+ return typeof error === "object" && error !== null && typeof (error as { code?: unknown }).code === "string"
218
+ ? (error as { code: string }).code
219
+ : "";
220
+ }
221
+
222
+ /**
223
+ * A mode as the four octal digits that are ON DISK — `1777`, not `0777`. A refusal is the line a
224
+ * reviewer reads as proof, and masking with `0o777` silently drops the sticky, setgid and setuid bits.
225
+ */
226
+ export function formatMode(mode: number): string {
227
+ return (mode & 0o7777).toString(8).padStart(4, "0");
228
+ }
229
+
230
+ /** The current uid, or `null` on a host with no uid at all (Windows, and then no ownership clause). */
231
+ function currentUid(platform: NodeJS.Platform): number | null {
232
+ if (platform === "win32") return null;
233
+ const uid = process.getuid?.();
234
+ return typeof uid === "number" ? uid : null;
235
+ }
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // The platform map — where the root lives
239
+ // ---------------------------------------------------------------------------
240
+
241
+ /**
242
+ * `<cache>/brl-subagent`, resolved per platform:
243
+ *
244
+ * linux `<home>/.cache/brl-subagent` (and every other POSIX, as the documented default)
245
+ * darwin `<home>/Library/Caches/brl-subagent`
246
+ * win32 `<env.LOCALAPPDATA>/brl-subagent`
247
+ *
248
+ * `XDG_CACHE_HOME` is IGNORED on purpose: it is an environment variable, so it is a path the caller's
249
+ * environment chooses, and a root chosen by the environment is the class of defect this module exists
250
+ * to remove. Path arithmetic uses `node:path`, so on a real Windows host the separators are Windows'.
251
+ */
252
+ function rootLayout(options: {
253
+ platform: NodeJS.Platform;
254
+ env: Record<string, string | undefined>;
255
+ home: string | undefined;
256
+ }): { ok: true; root: string } | ScratchRootError {
257
+ const { platform, env } = options;
258
+ if (platform === "win32") {
259
+ const localAppData = env.LOCALAPPDATA;
260
+ if (typeof localAppData !== "string" || localAppData.trim() === "") {
261
+ return fail(
262
+ "home-unresolvable",
263
+ "LOCALAPPDATA is not set — the Windows scratch root is <LOCALAPPDATA>/brl-subagent, and there is no passwd fallback and no system-temp fallback (a temp root is the defect this module removes)",
264
+ );
265
+ }
266
+ return { ok: true, root: resolve(localAppData, "brl-subagent") };
267
+ }
268
+ const home = options.home;
269
+ if (typeof home !== "string" || home.trim() === "") {
270
+ return fail(
271
+ "home-unresolvable",
272
+ "the home directory could not be resolved — the scratch root is <home>/.cache/brl-subagent (POSIX) or <home>/Library/Caches/brl-subagent (macOS), and there is no system-temp fallback (a temp root is the defect this module removes)",
273
+ );
274
+ }
275
+ if (platform === "darwin") return { ok: true, root: resolve(home, "Library", "Caches", "brl-subagent") };
276
+ return { ok: true, root: resolve(home, ".cache", "brl-subagent") };
277
+ }
278
+
279
+ // ---------------------------------------------------------------------------
280
+ // The chain predicate — one component rule, three zones
281
+ // ---------------------------------------------------------------------------
282
+
283
+ /**
284
+ * `/a/b/c` → [`/`, `/a`, `/a/b`, `/a/b/c`] by repeated `dirname`, which is separator-agnostic (a
285
+ * `split(sep)` would need to know whether the host is POSIX or Windows and would still get a drive
286
+ * letter wrong).
287
+ */
288
+ function directoryChain(absolute: string): string[] {
289
+ const chain = [absolute];
290
+ let current = absolute;
291
+ for (;;) {
292
+ const parent = dirname(current);
293
+ if (parent === current) break;
294
+ chain.push(parent);
295
+ current = parent;
296
+ }
297
+ return chain.reverse();
298
+ }
299
+
300
+ type Zone = "ancestor" | "root" | "below";
301
+
302
+ /**
303
+ * A component's (or a walk's) verdict. The `ok` arm can carry an ADVISORY: a chain can be safe to use
304
+ * and still be worth a sentence (group/other write on a parent), so the warning travels with the verdict
305
+ * that produced it rather than being re-derived by the caller — one place decides what a warning says.
306
+ */
307
+ type Verdict = { ok: true; warning?: string } | ScratchRootError;
308
+
309
+ /** One warning string out of several sentences, or `undefined` when there are none. Never reorders. */
310
+ function combineWarnings(parts: (string | undefined)[]): string | undefined {
311
+ const kept = parts.filter((part): part is string => part !== undefined && part !== "");
312
+ return kept.length === 0 ? undefined : kept.join("; ");
313
+ }
314
+
315
+ type Inspection = { kind: "found"; stats: Stats } | { kind: "missing" } | { kind: "unreadable"; error: unknown };
316
+
317
+ /** `lstat` without throwing: found, missing (`ENOENT`), or unreadable for another reason. */
318
+ function inspect(path: string): Inspection {
319
+ try {
320
+ return { kind: "found", stats: lstatSync(path) };
321
+ } catch (error) {
322
+ return codeOf(error) === "ENOENT" ? { kind: "missing" } : { kind: "unreadable", error };
323
+ }
324
+ }
325
+
326
+ /**
327
+ * The ANCESTOR's two clauses, shared by a real directory, by the directory a link resolves to, and by the
328
+ * directories ABOVE that resolved target (`checkTargetAncestors`). `label` is how a message names the
329
+ * component: the path itself, `<link> (a symlink to <target>)`, or `<link> (a symlink to <target>),
330
+ * whose parent <dir>`, so the reader is never sent to a mode the link does not have.
331
+ *
332
+ * The two clauses have DIFFERENT polarities on purpose (difference 3 in the header). OWNERSHIP refuses:
333
+ * a third-party owner can rename the validated root afterwards and substitute a symlink whatever the
334
+ * mode, so a foreign owner is `ancestor-not-owned` — a different trust boundary, not a different mode.
335
+ * WRITABILITY WARNS: a group/other write bit on a machine shared with co-workers is ordinary
336
+ * (`0775`/`0770` homes, the `1777` `/tmp` shape), the bank is a convenience, and refusing would refuse to
337
+ * run at all on such a host. The sentence names the path, the on-disk mode and the consequence — and the
338
+ * consequence is stated per shape, because the sticky bit changes it.
339
+ *
340
+ * Ownership is still checked BEFORE the mode: a `0755` directory owned by a third party passes a
341
+ * mode-only rule, and that owner can rename the validated root afterwards.
342
+ */
343
+ function checkAncestorClauses(label: string, stats: Stats, uid: number): Verdict {
344
+ if (stats.uid !== 0 && stats.uid !== uid) {
345
+ return fail(
346
+ "ancestor-not-owned",
347
+ `${label} is owned by uid ${stats.uid}, not by root or by you (uid ${uid}) — ownership of a parent is write (and therefore rename) authority over the root below it`,
348
+ );
349
+ }
350
+ if ((stats.mode & 0o022) !== 0) {
351
+ // One consequence, stated per shape: on a plain writable parent the write bit IS rename authority
352
+ // over our child, while the sticky bit (`1777`, the `/tmp` shape) stops a co-worker replacing what
353
+ // we already own and leaves only pre-creation — which the root's own ownership and 0700 clauses
354
+ // then refuse. A single sentence for both would over-claim on the sticky shape.
355
+ const consequence =
356
+ (stats.mode & 0o1000) !== 0
357
+ ? "group/other write on a parent lets a co-worker create that path before you do, though the sticky bit stops them replacing the run directory once you own it (and the bank path with it)"
358
+ : "group/other write on a parent is rename authority: a co-worker with write on this parent can replace the run directory, and the bank path with it";
359
+ return { ok: true, warning: `${label} is mode ${formatMode(stats.mode)} — ${consequence}` };
360
+ }
361
+ return { ok: true };
362
+ }
363
+
364
+ /**
365
+ * A symlinked ANCESTOR is resolved, and the directory it lands on is judged by the SAME clause. The
366
+ * rule is "follow it, then validate where it lands", not "never follow": a user who moved `~/.cache`
367
+ * to another disk — a symlink to a real `0700` directory they own — must still be able to delegate,
368
+ * and the question a parent is asked ("can someone else rename what is below you?") is answered by
369
+ * the target exactly as a real directory in the same place would answer it.
370
+ *
371
+ * The ROOT is never resolved (see the `root-symlink` clause): there the link would carry the `chmod`
372
+ * too, and a `chmod` through a link retargets the LINK's choice of where the bytes land.
373
+ *
374
+ * `realpathSync` walks the whole chain in one call, so a nested link or a LOOP is refused here rather
375
+ * than walked component by component (`ELOOP` on `a -> b -> a`, `ENOENT` on a broken link): a link that
376
+ * names no directory names no parent, and there is nothing for the clause below to be true of.
377
+ *
378
+ * THE TARGET IS NOT THE WHOLE STORY: the directories ABOVE the target carry the same rename authority
379
+ * over it that the target carries over the root, so they are judged by the same clauses (see
380
+ * `checkTargetAncestors`).
381
+ */
382
+ function checkResolvedAncestor(link: string, uid: number | null): Verdict {
383
+ let target: string;
384
+ try {
385
+ target = realpathSync(link);
386
+ } catch (error) {
387
+ return fail(
388
+ "ancestor-not-dir",
389
+ `${link} is a symlink that does not resolve to a directory (${codeOf(error) || describe(error)}) — a broken or looping link names nothing, so it cannot be the parent of the root`,
390
+ );
391
+ }
392
+ let stats: Stats;
393
+ try {
394
+ stats = statSync(target);
395
+ } catch (error) {
396
+ return fail(
397
+ "ancestor-not-dir",
398
+ `${link} is a symlink to ${target}, which cannot be inspected (${codeOf(error) || describe(error)})`,
399
+ );
400
+ }
401
+ if (!stats.isDirectory()) return fail("ancestor-not-dir", `${link} is a symlink to ${target}, which is not a directory`);
402
+ // No uid means no ownership model to judge (Windows), exactly as for a real ancestor in this zone.
403
+ if (uid === null) return { ok: true };
404
+ const targetVerdict = checkAncestorClauses(`${link} (a symlink to ${target})`, stats, uid);
405
+ if (!targetVerdict.ok) return targetVerdict;
406
+ const aboveVerdict = checkTargetAncestors(link, target, uid);
407
+ if (!aboveVerdict.ok) return aboveVerdict;
408
+ // Both levels can be worth a sentence, and neither may swallow the other.
409
+ return { ok: true, warning: combineWarnings([targetVerdict.warning, aboveVerdict.warning]) };
410
+ }
411
+
412
+ /*
413
+ * THE INSPECT LADDER IS TRIPLICATED ON PURPOSE — accepted, not refactored (#527 item 5). Three walks ask
414
+ * the same four questions of every component they visit (missing? unreadable? a link? a directory?):
415
+ *
416
+ * - `checkTargetAncestors` (this function) — the chain ABOVE a resolved symlink target, NEAREST-first,
417
+ * zone `ancestor`, reached only from `checkResolvedAncestor`;
418
+ * - `validateChain` (below) — the LITERAL chain from `/` down to the root, ROOT-MOST-first, zones
419
+ * `ancestor` and `root`;
420
+ * - `validateBelow` (below) — the two fixed paths under the root (`runs`, then `runs/<runId>`), in
421
+ * that order, zone `below`.
422
+ *
423
+ * Each has its own ZONE, its own refusal spelling for the same clause (`ancestor-not-dir` /
424
+ * `root-not-dir` / `below-not-dir`), its own labels (the two symlink label forms, the path itself) and
425
+ * its own traversal order — because those are what the caller's code matches on and what the reader's
426
+ * message names. A shared table would have to flatten the zone-specific sentences into one, which is
427
+ * exactly the loss the repetition avoids; two occurrences is the DRY threshold, and these are one ladder
428
+ * written out three times against three contracts. Accepted deliberately — do not "simplify" it into a
429
+ * table without deciding what each zone's message should then stop saying.
430
+ */
431
+ /**
432
+ * The directories ABOVE a resolved target, judged by the ancestor clauses — the residual the target
433
+ * clause alone does not see. A link into a non-sticky world-writable directory (`/srv/shared` at
434
+ * `0777`) whose child is our own `0700` directory is re-pointable by any local user: write authority
435
+ * over `shared` is rename authority over the child the link lands on, one hop past the resolution. On
436
+ * this surface that is WARNED (difference 3), and a foreign owner here is refused as
437
+ * `ancestor-not-owned`, exactly as along the literal chain.
438
+ *
439
+ * The target itself is EXCLUDED (its own clauses just ran, and its parents are what this walks). The
440
+ * walk goes from the target's PARENT up to `/`, nearest first: the closest writable parent is the one
441
+ * whose ordinary rename reaches the validated directory, so that is the name the message prints.
442
+ *
443
+ * `realpathSync` canonicalised the target, so every component of its chain is a real directory; the
444
+ * clauses are still applied through `inspect` because the tree can change between that call and this
445
+ * walk, and a component that has become a link (or vanished) is a change to fail closed on — the
446
+ * resolved chain is not re-resolved here, since re-resolving it would judge a path the root is no
447
+ * longer reached through.
448
+ */
449
+ function checkTargetAncestors(link: string, target: string, uid: number): Verdict {
450
+ const chain = directoryChain(target);
451
+ const warnings: string[] = [];
452
+ for (let index = chain.length - 2; index >= 0; index -= 1) {
453
+ const path = chain[index];
454
+ // One label for both clauses, so a message always names the LINK, the TARGET and the DIRECTORY.
455
+ const label = `${link} (a symlink to ${target}), whose parent ${path}`;
456
+ const found = inspect(path);
457
+ if (found.kind === "missing") {
458
+ return fail(
459
+ "ancestor-not-dir",
460
+ `${label} no longer exists — the target was canonicalised a moment ago, so the tree changed under this check (a chain that moved is not one to trust)`,
461
+ );
462
+ }
463
+ if (found.kind === "unreadable") {
464
+ return fail("ancestor-not-dir", `${label} cannot be inspected (${codeOf(found.error) || describe(found.error)})`);
465
+ }
466
+ if (found.stats.isSymbolicLink()) {
467
+ return fail(
468
+ "ancestor-not-dir",
469
+ `${label} is a symlink — the target's chain was canonicalised, so a link here means it was re-pointed under this check, and the re-pointed chain is not the one the target was validated against`,
470
+ );
471
+ }
472
+ if (!found.stats.isDirectory()) return fail("ancestor-not-dir", `${label} is not a directory`);
473
+ const verdict = checkAncestorClauses(label, found.stats, uid);
474
+ if (!verdict.ok) return verdict;
475
+ if (verdict.warning !== undefined) warnings.push(verdict.warning);
476
+ }
477
+ return { ok: true, warning: combineWarnings(warnings) };
478
+ }
479
+
480
+ /**
481
+ * One component's verdict. The symlink and non-directory clauses come first in every zone, because
482
+ * every later clause is a statement about a REAL directory.
483
+ */
484
+ function checkComponent(path: string, stats: Stats, zone: Zone, uid: number | null): Verdict {
485
+ if (stats.isSymbolicLink()) {
486
+ // Above the root a link is RESOLVED and its target judged; at and below it the link is refused,
487
+ // because there the chmod (and the bank) would follow it.
488
+ if (zone === "ancestor") return checkResolvedAncestor(path, uid);
489
+ return zone === "root"
490
+ ? fail(
491
+ "root-symlink",
492
+ `${path} is a symlink — the root is inspected with lstat and never followed (and never chmod-ed through: a chmod on a link retargets the link's target, which is someone else's choice of where the bank lands)`,
493
+ )
494
+ : fail(
495
+ "below-not-dir",
496
+ `${path} is a symlink — at and below the root nothing is followed (a chmod, a create or a marker write would land wherever the link points), so a link there is refused rather than resolved`,
497
+ );
498
+ }
499
+ if (!stats.isDirectory()) {
500
+ // One spelling per zone: the code names where the refused component sits, so `root-not-dir`,
501
+ // `ancestor-not-dir` and `below-not-dir` are the same clause reported three ways.
502
+ if (zone === "root") return fail("root-not-dir", `${path} is not a directory`);
503
+ return zone === "ancestor"
504
+ ? fail("ancestor-not-dir", `${path} is not a directory`)
505
+ : fail("below-not-dir", `${path} is not a directory`);
506
+ }
507
+ // No uid means no ownership model to judge (Windows). The directory and symlink clauses above are
508
+ // the whole predicate there; `fs` synthesizes mode bits on Windows, so a mode clause would be noise.
509
+ if (uid === null) return { ok: true };
510
+ if (zone === "root") {
511
+ if (stats.uid !== uid) {
512
+ return fail(
513
+ "root-not-owned",
514
+ `${path} is owned by uid ${stats.uid}, not by you (uid ${uid}) — the root and everything below it must be yours`,
515
+ );
516
+ }
517
+ // WHY EXACTLY 0700, WHEN THE TOOLING HALF ACCEPTS ANY MODE WITHOUT GROUP/OTHER BITS
518
+ // (`(mode & 0o077) !== 0`, `scripts/lib/scratch-root.mjs:224`, which a `4700` root satisfies)?
519
+ // The root is the confidentiality boundary for the bank's bytes — every run directory and every
520
+ // marker is reachable only through it — so its mode is judged WHOLE (`0o7777`), not as a write
521
+ // check: setuid, setgid or sticky on this directory is a state nothing here sets, and an
522
+ // unexpected state on the boundary is refused rather than interpreted. That is a deliberate
523
+ // strictness gap against the tooling half (the header states it), not a relaxed clause, so do not
524
+ // "align" the mask with the tooling's without a decision to make the shipped root shareable.
525
+ if ((stats.mode & 0o7777) !== ROOT_MODE) {
526
+ return fail(
527
+ "root-mode",
528
+ `${path} is mode ${formatMode(stats.mode)} — the root must be exactly ${formatMode(ROOT_MODE)}, the confidentiality boundary for the bank's bytes`,
529
+ );
530
+ }
531
+ return { ok: true };
532
+ }
533
+ if (zone === "ancestor") return checkAncestorClauses(path, stats, uid);
534
+ // Below the root: no mode clause (a group-writable subdirectory is still only reachable through a
535
+ // 0700 root, and refusing it would refuse `mktemp -d`-style directories for no gain).
536
+ return stats.uid === uid ? { ok: true } : fail("root-not-owned", `${path} is owned by uid ${stats.uid}, not by you (uid ${uid})`);
537
+ }
538
+
539
+ /**
540
+ * Walk from `/` down to `root`, applying the zone rule to every component. Never creates. A MISSING
541
+ * component ends the judgement — everything below it is missing too, and a missing root is not a
542
+ * failure here (creation is `ensureRunDir`'s job): what has been read is the part that exists, and the
543
+ * part that exists is the part whose ownership and writability decide whether the rest is safe.
544
+ *
545
+ * One of the three deliberately-repeated walks: see the ladder note above `checkTargetAncestors`.
546
+ *
547
+ * The walk COLLECTS advisories (one per group/other-writable ancestor, root-most first) instead of
548
+ * dropping them, so a chain with two writable parents reports both. A refusal is returned, never joined
549
+ * with a warning: what fails does not also get an advisory.
550
+ */
551
+ type ChainWalk = { ok: true; warnings: string[] } | ScratchRootError;
552
+
553
+ function validateChain(root: string, uid: number | null): ChainWalk {
554
+ const chain = directoryChain(root);
555
+ const warnings: string[] = [];
556
+ for (let index = 0; index < chain.length; index += 1) {
557
+ const path = chain[index];
558
+ const zone: Zone = index === chain.length - 1 ? "root" : "ancestor";
559
+ const found = inspect(path);
560
+ if (found.kind === "missing") return { ok: true, warnings };
561
+ if (found.kind === "unreadable") {
562
+ const error = codeOf(found.error) || describe(found.error);
563
+ return zone === "root"
564
+ ? fail("root-not-dir", `cannot inspect ${path} (${error}) — the root must be a directory you own and can read`)
565
+ : fail("ancestor-not-dir", `cannot inspect ${path} (${error})`);
566
+ }
567
+ const verdict = checkComponent(path, found.stats, zone, uid);
568
+ if (!verdict.ok) return verdict;
569
+ if (verdict.warning !== undefined) warnings.push(verdict.warning);
570
+ }
571
+ return { ok: true, warnings };
572
+ }
573
+
574
+ /**
575
+ * `<root>/runs` and `<root>/runs/<runId>`, re-read after creation. One of the three deliberately-repeated
576
+ * walks (see the ladder note above `checkTargetAncestors`); fixed paths, in this order, zone `below`.
577
+ */
578
+ function validateBelow(root: string, runId: string, uid: number | null): ScratchRootError | undefined {
579
+ for (const path of [join(root, RUNS_DIR), join(root, RUNS_DIR, runId)]) {
580
+ const found = inspect(path);
581
+ if (found.kind === "missing") return fail("create-failed", `${path} does not exist after creation`);
582
+ if (found.kind === "unreadable") {
583
+ return fail("create-failed", `cannot inspect ${path} after creation (${codeOf(found.error) || describe(found.error)})`);
584
+ }
585
+ const verdict = checkComponent(path, found.stats, "below", uid);
586
+ if (!verdict.ok) return verdict;
587
+ }
588
+ return undefined;
589
+ }
590
+
591
+ // ---------------------------------------------------------------------------
592
+ // The mount probe — advisory on the shipped surface
593
+ // ---------------------------------------------------------------------------
594
+
595
+ /** `realpathSync` without throwing: the canonical path, or `null` when it does not resolve. */
596
+ function canonical(path: string): string | null {
597
+ try {
598
+ return realpathSync(path);
599
+ } catch {
600
+ return null;
601
+ }
602
+ }
603
+
604
+ /**
605
+ * The deepest existing component on `root`'s chain, CANONICALISED — the path whose filesystem a
606
+ * directory we create would inherit. `null` means nothing on the chain resolves (the deepest existing
607
+ * component is a broken link), and then there is no mount to name.
608
+ *
609
+ * A symlink is NOT a reason to stop: a cache directory reached through a link is exactly the setup the
610
+ * link support exists for, and returning `null` there would silently drop the durability advisory for
611
+ * those users. So the walk keeps the deepest component that EXISTS (link or not), and the answer is
612
+ * resolved before it is returned: `statfs` must be asked about the canonical path, because that is the
613
+ * directory the kernel will put a new child in, and the warning has to name the path the user can act
614
+ * on rather than a link whose own mount is the link's parent's.
615
+ *
616
+ * A FILE component ends the walk without being recorded: a directory cannot be created inside it, so
617
+ * the prefix above it is the deepest component whose filesystem a new directory would inherit.
618
+ */
619
+ function deepestExisting(root: string): string | null {
620
+ let deepest: string | null = null;
621
+ for (const path of directoryChain(root)) {
622
+ const inspected = inspect(path);
623
+ if (inspected.kind !== "found") break;
624
+ if (!inspected.stats.isSymbolicLink() && !inspected.stats.isDirectory()) break;
625
+ deepest = path;
626
+ }
627
+ if (deepest === null) return null;
628
+ return canonical(deepest);
629
+ }
630
+
631
+ /**
632
+ * A `tmpfs` root is a WARNING on this surface, not a refusal (difference 1 in the header): the bank
633
+ * does not survive a reboot, and the user is told so. The probe is the deepest existing component, so
634
+ * a root that does not exist yet is judged by the ancestor it would be created in — and a root reached
635
+ * through a symlinked ancestor is judged by the directory the link lands on, which is the filesystem
636
+ * the refused-to-be-dropped advisory would otherwise be missing.
637
+ *
638
+ * LINUX ONLY, documented inline: `f_type` magic numbers are not portable and this module does not
639
+ * guess another platform's. An unreadable mount type yields no warning either — the property is
640
+ * advisory here, and a warning nobody can act on is noise (the tooling half refuses instead).
641
+ */
642
+ function mountWarning(root: string, platform: NodeJS.Platform, statfs: (path: string) => { type: number }): string | undefined {
643
+ if (platform !== "linux") return undefined;
644
+ const probe = deepestExisting(root);
645
+ if (probe === null) return undefined;
646
+ let type: number;
647
+ try {
648
+ type = statfs(probe).type;
649
+ } catch {
650
+ return undefined;
651
+ }
652
+ if (type !== TMPFS_MAGIC) return undefined;
653
+ // "Does the root exist yet" asked canonically: `probe` is canonical, so a root that resolves to it
654
+ // exists (through a link or not) and there is nothing to explain. No new import, and no second read.
655
+ const inherited =
656
+ canonical(resolve(root)) === probe
657
+ ? ""
658
+ : ` (${resolve(root)} does not exist yet, and a directory created inside ${probe} inherits its filesystem)`;
659
+ return `${probe} is on a tmpfs — the progress bank will not survive a reboot${inherited}`;
660
+ }
661
+
662
+ // ---------------------------------------------------------------------------
663
+ // The public surface
664
+ // ---------------------------------------------------------------------------
665
+
666
+ /**
667
+ * Resolve the root for this platform and validate its chain WITHOUT creating anything:
668
+ * `{ ok: true, root }` (plus `warning` for a `tmpfs` mount, a group/other-writable ancestor, or both), or
669
+ * a named refusal.
670
+ *
671
+ * A root that does not exist yet is valid — `ensureRunDir` creates it — as long as the components that
672
+ * DO exist pass the predicate.
673
+ */
674
+ export function resolveRoot(options: RootOptions = {}): ResolveRootResult {
675
+ const platform = options.platform ?? process.platform;
676
+ const layout = rootLayout({
677
+ platform,
678
+ env: options.env ?? process.env,
679
+ home: options.home ?? homedir(),
680
+ });
681
+ if (!layout.ok) return layout;
682
+ const uid = currentUid(platform);
683
+ const chain = validateChain(layout.root, uid);
684
+ if (!chain.ok) return chain;
685
+ // Both kinds at once: a writable ancestor AND a tmpfs root is a real host shape, and the one string
686
+ // carries both sentences (joined with "; ") so neither drops the other.
687
+ const mount = mountWarning(layout.root, platform, options.statfs ?? statfsSync);
688
+ const warning = combineWarnings([...chain.warnings, mount]);
689
+ if (warning === undefined) return { ok: true, root: layout.root };
690
+ const warningKinds: RootWarningKind[] = [];
691
+ if (chain.warnings.length > 0) warningKinds.push("ancestor-writable");
692
+ if (mount !== undefined) warningKinds.push("tmpfs");
693
+ options.warn?.(warning);
694
+ return { ok: true, root: layout.root, warning, warningKinds };
695
+ }
696
+
697
+ /**
698
+ * WHY a run id is refused, or `undefined` when it is ONE path segment. The REASON is the message rather
699
+ * than the value: the value is whatever bytes the caller sent, and a refusal line is not the place to
700
+ * print a NUL or a newline. Nothing about the name's LENGTH is here on purpose — `NAME_MAX` (255 on
701
+ * most filesystems, not on all of them) belongs to the filesystem, so a `mkdir` that fails
702
+ * `ENAMETOOLONG` is the authority and reports `create-failed`; that is a real fs failure, not an
703
+ * invalid id.
704
+ */
705
+ function runIdDefect(runId: unknown): string | undefined {
706
+ if (typeof runId !== "string") return `it is not a string (it is ${typeof runId})`;
707
+ if (runId === "") return "it is empty";
708
+ if (runId === "." || runId === "..") return `it is ${runId}, which names a directory rather than a run`;
709
+ if (runId.includes("\0")) return "it contains a NUL byte";
710
+ if (runId.includes("/") || runId.includes("\\")) return "it contains a path separator";
711
+ return undefined;
712
+ }
713
+
714
+ /**
715
+ * Remove what THIS call created, deepest first, and hand the refusal back. `rmdir` rather than a
716
+ * recursive remove on purpose: only EMPTY directories go, so a directory another process has since
717
+ * written into is left alone — "remove what we created" must not become "delete someone else's work".
718
+ */
719
+ function rollback(created: string[], refusal: ScratchRootError): ScratchRootError {
720
+ for (const path of [...created].reverse()) {
721
+ try {
722
+ rmdirSync(path);
723
+ } catch {
724
+ // Not empty, already gone, or not ours any more: leaving it is the safe half of best-effort.
725
+ }
726
+ }
727
+ return refusal;
728
+ }
729
+
730
+ /**
731
+ * Create one component at `ROOT_MODE`, validating every existing one on the way down. `mkdirSync`'s
732
+ * mode is MASKED by the umask (a `0777` umask produces a `0000` directory), so the explicit `chmod` is
733
+ * what makes `0700` true — and it runs only after `lstat` says a real directory is standing there,
734
+ * because a `chmod` through a link would retarget the LINK's target instead.
735
+ */
736
+ function createComponent(path: string, zone: Zone, uid: number | null, created: string[]): Verdict {
737
+ const found = inspect(path);
738
+ if (found.kind === "found") return checkComponent(path, found.stats, zone, uid);
739
+ if (found.kind === "unreadable") {
740
+ return fail("create-failed", `cannot inspect ${path} (${codeOf(found.error) || describe(found.error)})`);
741
+ }
742
+ try {
743
+ mkdirSync(path, { mode: ROOT_MODE });
744
+ } catch (error) {
745
+ if (codeOf(error) !== "EEXIST") {
746
+ return fail("create-failed", `cannot create ${path} (${codeOf(error) || describe(error)})`);
747
+ }
748
+ // Another process won the race: the directory exists, so it is VALIDATED, never chmod-ed — a
749
+ // mode we did not set is not ours to repair.
750
+ const raced = inspect(path);
751
+ if (raced.kind !== "found") return fail("create-failed", `${path} vanished after mkdir`);
752
+ return checkComponent(path, raced.stats, zone, uid);
753
+ }
754
+ created.push(path);
755
+ const made = inspect(path);
756
+ if (made.kind !== "found") return fail("create-failed", `${path} vanished after mkdir`);
757
+ // DEFENCE IN DEPTH, NOT AN ATTACKER PATH, AND DELIBERATELY UNTESTED (#527 item 4). To lose this race
758
+ // someone needs rename authority over `path` — write permission on its PARENT, which is a component
759
+ // this same call created at `0700` or validated as ours on the way down. A parent that is still
760
+ // group/other-writable is one of the relaxations this module states rather than hides (an ancestor
761
+ // warns — difference 3; the below zone has no mode clause, since it is reachable only through the
762
+ // `0700` root), and that is a stated consequence rather than something this guard could close. So the
763
+ // window is not a gap the chain predicate left open, and no deterministic test can construct the swap
764
+ // without an fs seam this security core deliberately does not have (a seam on this path would be a
765
+ // hook into the `chmod`). Deleting these three lines leaves the suite green — which is exactly why the
766
+ // guard states its unverifiable status here rather than implying a test pins it.
767
+ if (made.stats.isSymbolicLink()) {
768
+ return fail("create-failed", `${path} is a symlink immediately after mkdir — refusing to chmod through it`);
769
+ }
770
+ try {
771
+ chmodSync(path, ROOT_MODE);
772
+ } catch (error) {
773
+ return fail("create-failed", `cannot set mode ${formatMode(ROOT_MODE)} on ${path} (${codeOf(error) || describe(error)})`);
774
+ }
775
+ return { ok: true };
776
+ }
777
+
778
+ /**
779
+ * Create `<root>`, `<root>/runs` and `<root>/runs/<runId>` at `0700` (umask-independent), validating
780
+ * the chain BEFORE (nothing is created inside a directory that has not passed) and AFTER (the bytes on
781
+ * disk are what the predicate is asked about). A failed check removes only what this call created.
782
+ *
783
+ * Missing components above `<root>` (`~/.cache`, for instance, on a fresh account) are created too —
784
+ * they are part of the same chain, and a root cannot be created without them. An EXISTING component is
785
+ * validated and never repaired: changing a mode we did not set would be a silent privilege grab. A
786
+ * validated symlink ANCESTOR is one such existing component — nothing is created inside a directory
787
+ * that has not passed, and the directory a link resolves to has passed before `mkdir` runs through it.
788
+ * The RETURNED paths are the caller's (the link's), because the preamble has to name what the user
789
+ * sees, and `realpath` is not what they typed.
790
+ *
791
+ * THIS FUNCTION CARRIES NO ADVISORY, on purpose: its result type reports what it created, and the
792
+ * advisory belongs to `resolveRoot` (the seam's one report per spawn, logged once per process). A
793
+ * writable ancestor is therefore not re-derived here — the chain is validated for SAFETY, and the
794
+ * sentence was already emitted by the call that resolved the root.
795
+ */
796
+ export function ensureRunDir(root: string, runId: string, options: { platform?: NodeJS.Platform } = {}): EnsureRunDirResult {
797
+ const defect = runIdDefect(runId);
798
+ if (defect !== undefined) {
799
+ return fail(
800
+ "bad-run-id",
801
+ `refusing the run id: ${defect} — a run id is one path segment joined onto the root, so it must not be able to name anything outside it`,
802
+ );
803
+ }
804
+ const base = resolve(root);
805
+ const platform = options.platform ?? process.platform;
806
+ const uid = currentUid(platform);
807
+ const before = validateChain(base, uid);
808
+ if (!before.ok) return before;
809
+
810
+ const created: string[] = [];
811
+ const chain = directoryChain(base);
812
+ for (let index = 0; index < chain.length; index += 1) {
813
+ const verdict = createComponent(chain[index], index === chain.length - 1 ? "root" : "ancestor", uid, created);
814
+ if (!verdict.ok) return rollback(created, verdict);
815
+ }
816
+ const runDir = join(base, RUNS_DIR, runId);
817
+ for (const path of [join(base, RUNS_DIR), runDir]) {
818
+ const verdict = createComponent(path, "below", uid, created);
819
+ if (!verdict.ok) return rollback(created, verdict);
820
+ }
821
+
822
+ const revalidated = validateChain(base, uid);
823
+ const after = revalidated.ok ? validateBelow(base, runId, uid) : revalidated;
824
+ if (after !== undefined) return rollback(created, after);
825
+ return { ok: true, root: base, runDir, created };
826
+ }
827
+
828
+ /**
829
+ * Write the settle marker (`.done`, mode `0600`, empty — the content is irrelevant, its MTIME is the
830
+ * retention clock). The flag set is explicit and carries `O_NOFOLLOW` where the host defines it, so a
831
+ * planted link is never followed; `fchmod` on the open descriptor then makes `0600` true regardless of
832
+ * the umask.
833
+ */
834
+ export function markRunDone(runDir: string): MarkRunDoneResult {
835
+ const path = join(runDir, DONE_MARKER);
836
+ const flags = fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_TRUNC | (fsConstants.O_NOFOLLOW ?? 0);
837
+ let fd: number;
838
+ try {
839
+ fd = openSync(path, flags, FILE_MODE);
840
+ } catch (error) {
841
+ return fail("create-failed", `cannot write ${path} (${codeOf(error) || describe(error)})`);
842
+ }
843
+ try {
844
+ fchmodSync(fd, FILE_MODE);
845
+ return { ok: true, path };
846
+ } catch (error) {
847
+ return fail("create-failed", `cannot set mode ${formatMode(FILE_MODE)} on ${path} (${codeOf(error) || describe(error)})`);
848
+ } finally {
849
+ closeSync(fd);
850
+ }
851
+ }
852
+
853
+ /** The settle marker's mtime, or `undefined` when there is no marker (or it is a planted symlink). */
854
+ function settledAt(runDir: string): number | undefined {
855
+ try {
856
+ const stats = lstatSync(join(runDir, DONE_MARKER));
857
+ return stats.isSymbolicLink() ? undefined : stats.mtimeMs;
858
+ } catch {
859
+ return undefined;
860
+ }
861
+ }
862
+
863
+ /**
864
+ * Prune settled run directories: only a directory that contains a `.done` marker whose MTIME is older
865
+ * than `keepDays` is removed, and never `exclude` (the current run). An UNMARKED directory — live,
866
+ * queued, or crashed — is never pruned: "no marker" is not evidence of death, and deleting a live
867
+ * run's bank is worse than a cache that grows.
868
+ *
869
+ * Best effort by construction: a missing `runs` directory, an unreadable entry and a failed removal are
870
+ * all reported, never thrown, because this sweep runs on the settle path where an exception would be a
871
+ * failure unrelated to the user's task.
872
+ */
873
+ export function pruneRuns(root: string, options: PruneOptions = {}): PruneResult {
874
+ const now = options.now ?? new Date();
875
+ const keepDays = options.keepDays ?? KEEP_DAYS;
876
+ const cutoff = now.getTime() - keepDays * DAY_MS;
877
+ const exclude = options.exclude === undefined ? undefined : resolve(options.exclude);
878
+ const remove = options.remove ?? ((path: string) => rmSync(path, { recursive: true, force: true }));
879
+ const runsDir = join(resolve(root), RUNS_DIR);
880
+ const result: PruneResult = { removed: [], kept: [], failed: [] };
881
+ let entries;
882
+ try {
883
+ // `withFileTypes`: a dirent never follows a link, so a symlink named like a run is not a run.
884
+ entries = readdirSync(runsDir, { withFileTypes: true });
885
+ } catch {
886
+ return result;
887
+ }
888
+ for (const entry of entries) {
889
+ if (!entry.isDirectory()) continue;
890
+ const runDir = join(runsDir, entry.name);
891
+ const settled = settledAt(runDir);
892
+ if (settled === undefined || settled > cutoff || (exclude !== undefined && resolve(runDir) === exclude)) {
893
+ result.kept.push(runDir);
894
+ continue;
895
+ }
896
+ try {
897
+ remove(runDir);
898
+ result.removed.push(runDir);
899
+ } catch (error) {
900
+ result.failed.push({ path: runDir, message: codeOf(error) || describe(error) });
901
+ }
902
+ }
903
+ return result;
904
+ }
905
+
906
+ /** The bank's path inside a run directory — one definition, so the writer and the reader cannot drift. */
907
+ export function bankPath(runDir: string): string {
908
+ return join(runDir, BANK_FILENAME);
909
+ }