@codyswann/lisa 4.93.0 → 4.94.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 (94) hide show
  1. package/all/copy-overwrite/scripts/lib/lisa-cleanup-sweep-processes.d.mts +74 -0
  2. package/all/copy-overwrite/scripts/lib/lisa-cleanup-sweep-processes.mjs +527 -0
  3. package/all/copy-overwrite/scripts/lib/lisa-cleanup-sweep.d.mts +80 -0
  4. package/all/copy-overwrite/scripts/lib/lisa-cleanup-sweep.mjs +639 -0
  5. package/all/copy-overwrite/scripts/lib/npm-update-helper-inventory.mjs +2 -0
  6. package/all/copy-overwrite/scripts/lisa-run-gates.mjs +14 -0
  7. package/all/copy-overwrite/scripts/npm-updater-helper-graph.json +27 -2
  8. package/dist/cli/lisa-test-run-sweep.d.ts +38 -0
  9. package/dist/cli/lisa-test-run-sweep.d.ts.map +1 -0
  10. package/dist/cli/lisa-test-run-sweep.js +101 -0
  11. package/dist/cli/lisa-test-run-sweep.js.map +1 -0
  12. package/dist/cli/lisa-test-run.d.ts.map +1 -1
  13. package/dist/cli/lisa-test-run.js +3 -0
  14. package/dist/cli/lisa-test-run.js.map +1 -1
  15. package/dist/core/lisa-owned-hash-ledger.d.ts.map +1 -1
  16. package/dist/core/lisa-owned-hash-ledger.js +60 -0
  17. package/dist/core/lisa-owned-hash-ledger.js.map +1 -1
  18. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  19. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  20. package/dist/core/upstream-evidence-manifest.js +32 -5
  21. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  22. package/package.json +5 -5
  23. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  24. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  25. package/plugins/lisa-agy/plugin.json +1 -1
  26. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  27. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  28. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  29. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  31. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  33. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  34. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  35. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  36. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  37. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  38. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  39. package/plugins/lisa-expo-agy/plugin.json +1 -1
  40. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  41. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  43. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  44. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  46. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  47. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  49. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  50. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  51. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  53. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  54. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  58. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  60. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  61. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  65. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  68. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-rails-agy/plugin.json +1 -1
  75. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  82. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  89. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  93. package/scripts/two-channel-couplings.json +1 -1
  94. package/typescript/copy-overwrite/.prettierignore +2 -0
@@ -0,0 +1,639 @@
1
+ #!/usr/bin/env node
2
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
3
+ // Do not edit directly — durable changes belong upstream in Lisa.
4
+
5
+ /**
6
+ * lisa-cleanup-sweep — one cheap sweep at the start of a test run or push that
7
+ * removes stale Lisa temp entries and kills orphaned test processes
8
+ * (CodySwannGT/lisa#4597).
9
+ *
10
+ * Leftover temp folders and orphaned fixture processes are real (#2902 found
11
+ * 227 orphaned process trees; #3206 found unowned temp output piling up), but
12
+ * preventing every leak per test is what cost about a quarter of unit time.
13
+ * Sweeping once per run keeps the machine clean for a fraction of that.
14
+ *
15
+ * node scripts/lib/lisa-cleanup-sweep.mjs [--dry-run] [--json] [--max-age-hours N]
16
+ *
17
+ * prints one line, e.g. `🧹 swept 37 stale temp dirs, 2 orphaned test processes
18
+ * (412 ms)`, or with `--json` one JSON object. It exits 0 even when something
19
+ * went wrong — errors are reported, never raised — because a sweep must never
20
+ * fail the run it precedes.
21
+ *
22
+ * ## What counts as a stale Lisa temp entry
23
+ *
24
+ * A TOP-LEVEL entry of `os.tmpdir()` (no recursion while selecting) whose name
25
+ * starts with a {@link LISA_OWNED_TEMP_PREFIXES} prefix, is not protected, is
26
+ * not a symlink, is not a git checkout, and whose own mtime is older than the
27
+ * age limit (24 h by default). Files count as well as folders: `mktemp`
28
+ * without `-d` leaves files such as `lisa-pushed-refs.XXXXXXXX`.
29
+ *
30
+ * The ticket pointed at four prefix sources: `scratchPrefixes` in
31
+ * `vitest.config.local.ts`, `LISA_TEST_SCRATCH_PREFIXES` in the mutation
32
+ * scripts, the paths `check-orphan-test-processes.mjs` matches, and the
33
+ * `mkdtemp` prefixes under `tests/`. Only the `lisa` ones are used, on
34
+ * purpose. The generic ones (`node-`, `worker-`, `state-`, `review-`, `e2e-`,
35
+ * `wiki-`, …) name entries INSIDE a per-run scratch root
36
+ * (`$TMPDIR/lisa-scratch/run-*`), where the scratch authority owns them. At the
37
+ * top of a shared temp directory those same names belong to anything —
38
+ * another tool, another user's build — so matching them there would delete
39
+ * what Lisa does not own. Every Lisa `mkdtemp`/`mktemp` that lands at the top
40
+ * level is spelled `lisa-…` or `lisa.…`.
41
+ *
42
+ * {@link LISA_PROTECTED_TEMP_NAMES}, `lisa-preserve-*` and `lisa-backup-*` are
43
+ * never swept, whatever their age: they are persistent state, live run roots,
44
+ * patch backups of an agent's work, or `lisa apply`'s rollback copy. Nor is an
45
+ * entry another user owns, a directory group or other can open, or a file
46
+ * group or other can write: in a shared temp directory a Lisa-looking name
47
+ * proves nothing about who made it. And the whole temp half is refused when
48
+ * the root is `/`, the home directory, or an ancestor of the home directory —
49
+ * a misconfigured `TMPDIR` must not become a sweep of real files. A root that
50
+ * merely contains the working directory is swept, except for the one
51
+ * top-level entry that holds it. A git checkout, or a folder whose direct
52
+ * child is one, is kept. A folder holding a `.git` entry is kept too,
53
+ * because agents put worktrees in the temp directory and a directory's own
54
+ * mtime says nothing about edits deeper inside it.
55
+ *
56
+ * ## Once per run
57
+ *
58
+ * The gate runner sweeps at `--moment=push` and then starts `test:*:push`
59
+ * scripts, each of which starts `lisa-test-run`; Lisa's own suite also starts
60
+ * nested `lisa-test-run` fixtures. Whoever sweeps first writes its own
61
+ * `<pid>:<start>` into {@link SWEPT_ENV}, everything it starts inherits it, and
62
+ * an entry point skips the sweep — saying so in one line — only while that
63
+ * exact process is still alive. A stale or copied value cannot disable the
64
+ * sweep for good. A nested `lisa-test-run` still sets its own owner marker.
65
+ * @module scripts/lib/lisa-cleanup-sweep
66
+ */
67
+ import { lstat, opendir, realpath, rm } from "node:fs/promises";
68
+ import { homedir, tmpdir } from "node:os";
69
+ import path from "node:path";
70
+ import { fileURLToPath } from "node:url";
71
+
72
+ import { boundedSpawnSync, isChildTimeout } from "./bounded-spawn.mjs";
73
+ import { invokedAsScript } from "./invoked-as-script.mjs";
74
+ import {
75
+ liveSweeper,
76
+ ownerMarkerFor,
77
+ sweepOrphans,
78
+ } from "./lisa-cleanup-sweep-processes.mjs";
79
+
80
+ /** Name prefixes Lisa uses for top-level temp entries. */
81
+ export const LISA_OWNED_TEMP_PREFIXES = Object.freeze(["lisa-", "lisa."]);
82
+
83
+ /**
84
+ * Lisa-prefixed top-level names that are never swept, whatever their age.
85
+ *
86
+ * `lisa-scratch` holds every live run root; `lisa-kill-marks` is the
87
+ * cross-run kill record (`kill-marks.mjs`); `lisa-team-enforce` and
88
+ * `lisa-verification-gate` are hook state directories.
89
+ */
90
+ export const LISA_PROTECTED_TEMP_NAMES = Object.freeze([
91
+ "lisa-scratch",
92
+ "lisa-kill-marks",
93
+ "lisa-team-enforce",
94
+ "lisa-verification-gate",
95
+ ]);
96
+
97
+ /**
98
+ * Prefixes that are never swept: `lisa-preserve-*` holds patch backups of an
99
+ * agent's work, and `lisa-backup-*` is the rollback copy `lisa apply` takes
100
+ * (`src/transaction/backup.ts`).
101
+ */
102
+ export const LISA_PROTECTED_TEMP_PREFIXES = Object.freeze([
103
+ "lisa-preserve-",
104
+ "lisa-backup-",
105
+ ]);
106
+
107
+ /**
108
+ * Set by whoever swept first to its own `<pid>:<start>`; everything it starts
109
+ * skips the sweep while that process is still alive with that start time.
110
+ */
111
+ export const SWEPT_ENV = "LISA_CLEANUP_SWEPT";
112
+
113
+ /** Default age, in hours, past which a Lisa temp entry is stale. */
114
+ export const DEFAULT_MAX_AGE_HOURS = 24;
115
+
116
+ /** Concurrent removals; enough to hide latency without flooding the disk. */
117
+ const REMOVE_CONCURRENCY = 16;
118
+
119
+ /** Deadline for the launcher's child; the sweep should take seconds. */
120
+ const LAUNCH_TIMEOUT_MS = 15_000;
121
+
122
+ const HOUR_MS = 60 * 60 * 1000;
123
+ const SELF = fileURLToPath(import.meta.url);
124
+ const USAGE =
125
+ "usage: lisa-cleanup-sweep.mjs [--dry-run] [--json] [--no-processes] [--max-age-hours N]";
126
+
127
+ /**
128
+ * Whether a top-level temp name is Lisa-owned and sweepable.
129
+ * @param {string} name - Entry name.
130
+ * @returns {boolean} True for an unprotected Lisa-prefixed name.
131
+ */
132
+ export function isLisaOwnedTempName(name) {
133
+ if (!LISA_OWNED_TEMP_PREFIXES.some(prefix => name.startsWith(prefix)))
134
+ return false;
135
+ if (LISA_PROTECTED_TEMP_NAMES.includes(name)) return false;
136
+ return !LISA_PROTECTED_TEMP_PREFIXES.some(prefix => name.startsWith(prefix));
137
+ }
138
+
139
+ /**
140
+ * Whether `directory` holds a `.git` entry. Any answer but "absent" is yes.
141
+ * @param {string} directory - Absolute path.
142
+ * @returns {Promise<boolean>} True unless `.git` is provably absent.
143
+ */
144
+ async function holdsGit(directory) {
145
+ try {
146
+ await lstat(path.join(directory, ".git"));
147
+ return true;
148
+ } catch (error) {
149
+ return error?.code !== "ENOENT";
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Whether a stale candidate directory is, or directly holds, a git checkout.
155
+ *
156
+ * Agents keep worktrees in the temp directory, sometimes one level down
157
+ * (`lisa-<n>-workspace/repo`), and a folder's own mtime says nothing about
158
+ * edits deeper inside it. Unknown — an unreadable folder or child — keeps it.
159
+ * @param {string} entry - Absolute path of a directory.
160
+ * @returns {Promise<boolean>} True when it must be kept as a checkout.
161
+ */
162
+ async function isGitCheckout(entry) {
163
+ if (await holdsGit(entry)) return true;
164
+ try {
165
+ const children = [];
166
+ for await (const child of await opendir(entry)) {
167
+ if (child.isDirectory()) children.push(path.join(entry, child.name));
168
+ }
169
+ const verdicts = await Promise.all(children.map(holdsGit));
170
+ return verdicts.includes(true);
171
+ } catch {
172
+ return true;
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Whether this user alone could have created and filled an entry.
178
+ *
179
+ * A Lisa-looking name in a shared temp directory proves nothing: another user
180
+ * can create `lisa-anything`, or leave a group- or world-writable one for this
181
+ * user's sweep to recurse into. So an entry is removable only when this user
182
+ * owns it and nobody else could have written into it — a directory closed to
183
+ * group and other (`mkdtemp` makes them 0700), a file not writable by group or
184
+ * other. Skipped where there is no uid to compare (Windows).
185
+ * @param {import("node:fs").Stats} stats - The entry's own lstat.
186
+ * @param {number | undefined} uid - This user's id.
187
+ * @returns {boolean} True when the entry is safe to remove.
188
+ */
189
+ function isOwnedAndPrivate(stats, uid) {
190
+ if (uid === undefined) return true;
191
+ if (stats.uid !== uid) return false;
192
+ const openBits = stats.isDirectory() ? 0o077 : 0o022;
193
+ return (stats.mode & openBits) === 0;
194
+ }
195
+
196
+ /**
197
+ * Decide what to do with one Lisa-named entry.
198
+ * @param {string} entry - Absolute path, a direct child of the root.
199
+ * @param {number} cutoffMs - Entries modified before this are stale.
200
+ * @param {number | undefined} uid - This user's id.
201
+ * @returns {Promise<"remove" | "keep" | "unsafe">} The verdict.
202
+ */
203
+ async function verdictFor(entry, cutoffMs, uid) {
204
+ const stats = await lstat(entry);
205
+ if (stats.isSymbolicLink() || stats.mtimeMs >= cutoffMs) return "keep";
206
+ if (!isOwnedAndPrivate(stats, uid)) return "unsafe";
207
+ if (stats.isDirectory() && (await isGitCheckout(entry))) return "keep";
208
+ return "remove";
209
+ }
210
+
211
+ /**
212
+ * Canonical spelling of a path, or its resolved spelling when it cannot be read.
213
+ * @param {string} target - Path.
214
+ * @returns {Promise<string>} Absolute path.
215
+ */
216
+ async function canonical(target) {
217
+ try {
218
+ return await realpath(target);
219
+ } catch {
220
+ return path.resolve(target);
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Whether `outer` is `inner` or one of its ancestors.
226
+ * @param {string} outer - Candidate ancestor.
227
+ * @param {string} inner - Candidate descendant.
228
+ * @returns {boolean} True when `inner` lies at or below `outer`.
229
+ */
230
+ function contains(outer, inner) {
231
+ const relative = path.relative(outer, inner);
232
+ return (
233
+ relative === "" ||
234
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
235
+ );
236
+ }
237
+
238
+ /**
239
+ * Why a root must not be swept, or null when it may be.
240
+ *
241
+ * A misconfigured `TMPDIR` (`/`, `$HOME`, `$HOME`'s parent) would otherwise
242
+ * turn a temp sweep into a sweep of the user's own files.
243
+ * @param {string} resolved - Canonical sweep root.
244
+ * @param {string} home - Canonical home directory.
245
+ * @returns {string | null} The refusal reason, or null.
246
+ */
247
+ function rootRefusal(resolved, home) {
248
+ if (path.dirname(resolved) === resolved) return "it is the filesystem root";
249
+ if (contains(resolved, home)) return "it is or contains the home directory";
250
+ return null;
251
+ }
252
+
253
+ /**
254
+ * The top-level entry name that holds the working directory, if any.
255
+ *
256
+ * A temp root may legitimately contain the cwd — an agent worktree under
257
+ * `/tmp/lisa-…/` — and the sweep must never delete the folder it runs in.
258
+ * @param {string} resolved - Canonical sweep root.
259
+ * @param {string} cwd - Canonical working directory.
260
+ * @returns {string | null} That entry's name, or null.
261
+ */
262
+ function entryHolding(resolved, cwd) {
263
+ if (!contains(resolved, cwd) || resolved === cwd) return null;
264
+ return path.relative(resolved, cwd).split(path.sep)[0] ?? null;
265
+ }
266
+
267
+ /**
268
+ * Map `worker` over `items` with at most `limit` in flight, in order.
269
+ * @template T, R
270
+ * @param {readonly T[]} items - Work items.
271
+ * @param {number} limit - Maximum concurrency.
272
+ * @param {(item: T) => Promise<R>} worker - Async worker; must not throw.
273
+ * @returns {Promise<R[]>} Results, index-aligned with `items`.
274
+ */
275
+ async function mapPool(items, limit, worker) {
276
+ const lanes = Math.min(limit, items.length);
277
+ const laneResults = await Promise.all(
278
+ Array.from({ length: lanes }, async (_, lane) => {
279
+ const mine = [];
280
+ for (let index = lane; index < items.length; index += lanes) {
281
+ mine.push([index, await worker(items[index])]);
282
+ }
283
+ return mine;
284
+ })
285
+ );
286
+ return laneResults
287
+ .flat()
288
+ .sort(([left], [right]) => left - right)
289
+ .map(([, result]) => result);
290
+ }
291
+
292
+ /**
293
+ * Classify one Lisa-named entry, turning a failure into a reported verdict.
294
+ * @param {string} entry - Absolute path.
295
+ * @param {number} cutoffMs - Staleness cutoff.
296
+ * @param {number | undefined} uid - This user's id.
297
+ * @returns {Promise<{entry: string, verdict: string, error?: string}>} Verdict.
298
+ */
299
+ async function classify(entry, cutoffMs, uid) {
300
+ try {
301
+ return { entry, verdict: await verdictFor(entry, cutoffMs, uid) };
302
+ } catch (error) {
303
+ // An entry that vanished mid-sweep is simply gone; anything else is kept
304
+ // and reported.
305
+ if (error?.code === "ENOENT") return { entry, verdict: "keep" };
306
+ return {
307
+ entry,
308
+ verdict: "error",
309
+ error: `${entry}: ${error?.message ?? error}`,
310
+ };
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Classify the Lisa-named entries at the top level of `root`.
316
+ * @param {string} resolvedRoot - Canonical temp root.
317
+ * @param {string | null} holding - Name of the entry holding the cwd.
318
+ * @param {number} cutoffMs - Staleness cutoff.
319
+ * @param {number | undefined} uid - This user's id.
320
+ * @returns {Promise<Array<{entry: string, verdict: string, error?: string}>>} Verdicts.
321
+ */
322
+ async function classifyEntries(resolvedRoot, holding, cutoffMs, uid) {
323
+ const candidates = [];
324
+ for await (const dirent of await opendir(resolvedRoot)) {
325
+ if (dirent.isSymbolicLink() || !isLisaOwnedTempName(dirent.name)) continue;
326
+ if (dirent.name === holding) continue;
327
+ const entry = path.join(resolvedRoot, dirent.name);
328
+ if (path.dirname(entry) === resolvedRoot) candidates.push(entry);
329
+ }
330
+ return mapPool(candidates, REMOVE_CONCURRENCY, entry =>
331
+ classify(entry, cutoffMs, uid)
332
+ );
333
+ }
334
+
335
+ /**
336
+ * Remove one entry, reporting instead of throwing.
337
+ * @param {string} entry - Absolute path.
338
+ * @returns {Promise<{entry: string, error?: string}>} Outcome.
339
+ */
340
+ async function removeEntry(entry) {
341
+ try {
342
+ await rm(entry, { recursive: true, force: true });
343
+ return { entry };
344
+ } catch (error) {
345
+ return {
346
+ entry,
347
+ error: `could not remove ${entry}: ${error?.message ?? error}`,
348
+ };
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Remove stale Lisa temp entries from the top level of `root`.
354
+ * @param {object} options - Sweep options.
355
+ * @param {string} options.root - Temp root.
356
+ * @param {number} options.maxAgeHours - Age limit.
357
+ * @param {number} options.now - Clock, epoch milliseconds.
358
+ * @param {boolean} options.dryRun - Select but remove nothing.
359
+ * @param {number} [options.uid] - This user's id; defaults to `process.getuid()`.
360
+ * @param {string} [options.home] - Home directory; defaults to `os.homedir()`.
361
+ * @param {string} [options.cwd] - Working directory; defaults to `process.cwd()`.
362
+ * @returns {Promise<{removed: string[], skippedUnsafe: number, errors: string[]}>} What was removed.
363
+ */
364
+ export async function sweepTemp({
365
+ root,
366
+ maxAgeHours,
367
+ now,
368
+ dryRun,
369
+ uid = process.getuid?.(),
370
+ home = homedir(),
371
+ cwd = process.cwd(),
372
+ }) {
373
+ const resolvedRoot = await canonical(root);
374
+ const refusal = rootRefusal(resolvedRoot, await canonical(home));
375
+ if (refusal) {
376
+ return {
377
+ removed: [],
378
+ skippedUnsafe: 0,
379
+ errors: [`refusing to sweep ${root}: ${refusal}`],
380
+ };
381
+ }
382
+ let verdicts;
383
+ try {
384
+ const holding = entryHolding(resolvedRoot, await canonical(cwd));
385
+ const cutoffMs = now - maxAgeHours * HOUR_MS;
386
+ verdicts = await classifyEntries(resolvedRoot, holding, cutoffMs, uid);
387
+ } catch (error) {
388
+ return {
389
+ removed: [],
390
+ skippedUnsafe: 0,
391
+ errors: [`cannot read ${root}: ${error?.message ?? error}`],
392
+ };
393
+ }
394
+ const stale = verdicts.filter(v => v.verdict === "remove").map(v => v.entry);
395
+ const skippedUnsafe = verdicts.filter(v => v.verdict === "unsafe").length;
396
+ const classifyErrors = verdicts.flatMap(v => (v.error ? [v.error] : []));
397
+ if (dryRun) return { removed: stale, skippedUnsafe, errors: classifyErrors };
398
+ const outcomes = await mapPool(stale, REMOVE_CONCURRENCY, removeEntry);
399
+ return {
400
+ removed: outcomes.filter(o => !o.error).map(o => o.entry),
401
+ skippedUnsafe,
402
+ errors: [
403
+ ...classifyErrors,
404
+ ...outcomes.flatMap(o => (o.error ? [o.error] : [])),
405
+ ],
406
+ };
407
+ }
408
+
409
+ /**
410
+ * Run the whole sweep: stale temp entries, then orphaned test processes.
411
+ * @param {object} [options] - Options; every one has a default.
412
+ * @param {string} [options.root] - Temp root, defaults to `os.tmpdir()`.
413
+ * @param {number} [options.maxAgeHours] - Age limit, defaults to 24.
414
+ * @param {number} [options.now] - Clock for ages, defaults to `Date.now()`.
415
+ * @param {boolean} [options.dryRun] - Select but change nothing.
416
+ * @param {number} [options.uid] - This user's id, for the ownership check.
417
+ * @param {string} [options.home] - Home directory, for the root refusal.
418
+ * @param {string} [options.cwd] - Working directory, for the root refusal.
419
+ * @param {false | object} [options.orphans] - `false` to skip processes, or
420
+ * seams for `sweepOrphans`.
421
+ * @returns {Promise<{removed: string[], skippedUnsafe: number, killed: number[], errors: string[], dryRun: boolean, durationMs: number}>} Result.
422
+ */
423
+ export async function sweep(options = {}) {
424
+ const started = performance.now();
425
+ const {
426
+ root = tmpdir(),
427
+ maxAgeHours = DEFAULT_MAX_AGE_HOURS,
428
+ now = Date.now(),
429
+ dryRun = false,
430
+ orphans = {},
431
+ ...identity
432
+ } = options;
433
+ const temp = await sweepTemp({ root, maxAgeHours, now, dryRun, ...identity });
434
+ const processes =
435
+ orphans === false
436
+ ? { killed: [], errors: [] }
437
+ : await sweepOrphans({ ...orphans, dryRun });
438
+ return {
439
+ removed: temp.removed,
440
+ skippedUnsafe: temp.skippedUnsafe,
441
+ killed: processes.killed,
442
+ errors: [...temp.errors, ...processes.errors],
443
+ dryRun,
444
+ durationMs: Math.round(performance.now() - started),
445
+ };
446
+ }
447
+
448
+ /**
449
+ * Pluralise a count.
450
+ * @param {number} count - How many.
451
+ * @param {string} one - Singular noun phrase.
452
+ * @param {string} many - Plural noun phrase.
453
+ * @returns {string} e.g. `2 orphaned test processes`.
454
+ */
455
+ function counted(count, one, many) {
456
+ return `${count} ${count === 1 ? one : many}`;
457
+ }
458
+
459
+ /**
460
+ * The one summary line a sweep prints.
461
+ * @param {{removed: string[], killed: number[], errors: string[], dryRun: boolean, durationMs: number}} result - Sweep result.
462
+ * @returns {string} A single line, no trailing newline.
463
+ */
464
+ export function formatSummary(result) {
465
+ const verb = result.dryRun ? "would sweep" : "swept";
466
+ const dirs = counted(
467
+ result.removed.length,
468
+ "stale temp dir",
469
+ "stale temp dirs"
470
+ );
471
+ const procs = counted(
472
+ result.killed.length,
473
+ "orphaned test process",
474
+ "orphaned test processes"
475
+ );
476
+ const unsafe = result.skippedUnsafe ?? 0;
477
+ const kept =
478
+ unsafe > 0
479
+ ? `; kept ${counted(unsafe, "entry", "entries")} not private to this user`
480
+ : "";
481
+ const line = `🧹 ${verb} ${dirs}, ${procs} (${Math.round(result.durationMs)} ms)${kept}`;
482
+ if (result.errors.length === 0) return line;
483
+ const first = String(result.errors[0]).replace(/\s+/gu, " ");
484
+ return `${line}; ${counted(result.errors.length, "error", "errors")}, first: ${first}`;
485
+ }
486
+
487
+ /**
488
+ * Parse CLI flags.
489
+ * @param {readonly string[]} argv - Arguments after the script path.
490
+ * @returns {{dryRun: boolean, json: boolean, maxAgeHours: number, processes: boolean}} Parsed flags.
491
+ * @throws {Error} On an unknown flag or an invalid age.
492
+ */
493
+ export function parseSweepArgs(argv) {
494
+ const parsed = {
495
+ dryRun: false,
496
+ json: false,
497
+ maxAgeHours: DEFAULT_MAX_AGE_HOURS,
498
+ processes: true,
499
+ };
500
+ for (let index = 0; index < argv.length; index += 1) {
501
+ const arg = argv[index];
502
+ if (arg === "--dry-run") parsed.dryRun = true;
503
+ else if (arg === "--json") parsed.json = true;
504
+ else if (arg === "--no-processes") parsed.processes = false;
505
+ else if (arg === "--max-age-hours" || arg.startsWith("--max-age-hours=")) {
506
+ const inline = arg.includes("=");
507
+ const raw = inline ? arg.slice(arg.indexOf("=") + 1) : argv[index + 1];
508
+ if (!inline) index += 1;
509
+ parsed.maxAgeHours = parseAge(raw);
510
+ } else throw new Error(`unknown flag ${arg}`);
511
+ }
512
+ return parsed;
513
+ }
514
+
515
+ /**
516
+ * Validate an age in hours.
517
+ * @param {string | undefined} raw - The flag's value.
518
+ * @returns {number} The age.
519
+ * @throws {Error} When it is not a non-negative number.
520
+ */
521
+ function parseAge(raw) {
522
+ const hours = Number(raw);
523
+ if (raw === undefined || raw === "" || !Number.isFinite(hours) || hours < 0) {
524
+ throw new Error(`--max-age-hours needs a non-negative number, got ${raw}`);
525
+ }
526
+ return hours;
527
+ }
528
+
529
+ /**
530
+ * CLI entry point.
531
+ * @param {readonly string[]} [argv] - Arguments after the script path.
532
+ * @param {object} [seams] - Test seams.
533
+ * @param {object} [seams.sweepOptions] - Extra options merged into `sweep`.
534
+ * @param {(line: string) => void} [seams.write] - Output sink.
535
+ * @returns {Promise<number>} 0, or 2 on a usage error.
536
+ */
537
+ export async function main(argv = process.argv.slice(2), seams = {}) {
538
+ const write = seams.write ?? (line => process.stdout.write(`${line}\n`));
539
+ let flags;
540
+ try {
541
+ flags = parseSweepArgs(argv);
542
+ } catch (error) {
543
+ write(`lisa-cleanup-sweep: ${error.message}\n${USAGE}`);
544
+ return 2;
545
+ }
546
+ const result = await sweep({
547
+ dryRun: flags.dryRun,
548
+ maxAgeHours: flags.maxAgeHours,
549
+ ...seams.sweepOptions,
550
+ ...(flags.processes ? {} : { orphans: false }),
551
+ });
552
+ write(flags.json ? JSON.stringify(result) : formatSummary(result));
553
+ return 0;
554
+ }
555
+
556
+ /**
557
+ * The line printed when a live sweeper already swept.
558
+ * @param {number} pid - The sweeper's pid.
559
+ * @returns {string} One line, no trailing newline.
560
+ */
561
+ export function formatAlreadySwept(pid) {
562
+ return `🧹 cleanup sweep already ran (pid ${pid}); skipping`;
563
+ }
564
+
565
+ /**
566
+ * Sweep once from a synchronous caller (the gate runner), never failing it.
567
+ *
568
+ * Runs this file as a bounded child because the caller cannot await, forwards
569
+ * its one summary line, and on any failure prints one line and returns. Skips,
570
+ * with one line, when {@link SWEPT_ENV} names a sweeper that is still alive;
571
+ * otherwise writes the CALLER's own `<pid>:<start>` there first, so everything
572
+ * the caller starts afterwards skips for as long as the caller runs.
573
+ * @param {object} [seams] - Test seams.
574
+ * @param {Record<string, string | undefined>} [seams.env] - Environment, defaults to `process.env`.
575
+ * @param {typeof boundedSpawnSync} [seams.spawn] - Child launcher.
576
+ * @param {(line: string) => void} [seams.log] - Output sink.
577
+ * @param {() => string} [seams.ownerMarker] - This process's `<pid>:<start>`.
578
+ * @param {(value: unknown) => number | null} [seams.liveSweeper] - Who already swept.
579
+ * @returns {void}
580
+ */
581
+ export function runStartOfRunSweep(seams = {}) {
582
+ const {
583
+ env = process.env,
584
+ spawn = boundedSpawnSync,
585
+ log = console.log,
586
+ ownerMarker = () => ownerMarkerFor(process.pid),
587
+ liveSweeper: sweptBy = liveSweeper,
588
+ } = seams;
589
+ const sweeper = sweptBy(env[SWEPT_ENV]);
590
+ if (sweeper !== null) {
591
+ log(formatAlreadySwept(sweeper));
592
+ return;
593
+ }
594
+ env[SWEPT_ENV] = ownerMarker();
595
+ launchSweep(spawn, env, log);
596
+ }
597
+
598
+ /**
599
+ * Run the sweep CLI as a bounded child and forward its one line.
600
+ * @param {typeof boundedSpawnSync} spawn - Child launcher.
601
+ * @param {Record<string, string | undefined>} env - Child environment.
602
+ * @param {(line: string) => void} log - Output sink.
603
+ * @returns {void}
604
+ */
605
+ function launchSweep(spawn, env, log) {
606
+ const didNotFinish = why =>
607
+ log(`🧹 cleanup sweep did not finish (${why}); continuing`);
608
+ try {
609
+ const child = spawn(process.execPath, [SELF], {
610
+ encoding: "utf8",
611
+ env: { ...env },
612
+ stdio: ["ignore", "pipe", "pipe"],
613
+ timeout: LAUNCH_TIMEOUT_MS,
614
+ });
615
+ const line = String(child.stdout ?? "")
616
+ .trim()
617
+ .split("\n")
618
+ .pop();
619
+ if (child.error) didNotFinish(child.error.message);
620
+ else if (child.status !== 0 || !line) didNotFinish(`exit ${child.status}`);
621
+ else log(line);
622
+ } catch (error) {
623
+ didNotFinish(
624
+ isChildTimeout(error)
625
+ ? `timed out after ${LAUNCH_TIMEOUT_MS / 1000} s`
626
+ : error?.message
627
+ );
628
+ }
629
+ }
630
+
631
+ if (invokedAsScript(import.meta.url)) {
632
+ main().then(
633
+ code => process.exit(code),
634
+ error => {
635
+ console.log(`🧹 cleanup sweep failed: ${error?.message ?? error}`);
636
+ process.exit(0);
637
+ }
638
+ );
639
+ }
@@ -35,6 +35,8 @@ const COMMON = [
35
35
  "lib/kill-marks.mjs",
36
36
  "lib/gate-failure-diagnosis.mjs",
37
37
  "lib/worktree-dependencies.mjs",
38
+ "lib/lisa-cleanup-sweep.mjs",
39
+ "lib/lisa-cleanup-sweep-processes.mjs",
38
40
  "lib/history-secret-git.mjs",
39
41
  "lib/history-secret-scanner.mjs",
40
42
  "lib/history-secret-evidence.mjs",
@@ -58,6 +58,7 @@ import {
58
58
  } from "./lib/kill-marks.mjs";
59
59
  import { boundedSpawnSync, isChildTimeout } from "./lib/bounded-spawn.mjs";
60
60
  import { invokedAsScript } from "./lib/invoked-as-script.mjs";
61
+ import { runStartOfRunSweep } from "./lib/lisa-cleanup-sweep.mjs";
61
62
  import { worktreeDependencyProblem } from "./lib/worktree-dependencies.mjs";
62
63
  import {
63
64
  interruptionReason,
@@ -1897,6 +1898,19 @@ export function main(argv = process.argv.slice(2)) {
1897
1898
  const wired = wiredConditionalFloor({ moment });
1898
1899
  const missing = undeclaredFloor({ gates: config.gates, moment, wired });
1899
1900
 
1901
+ // One cleanup sweep per push (CodySwannGT/lisa#4597), before the first gate
1902
+ // and before the built-in fallback below, which runs tests too. It never
1903
+ // fails the run: whatever goes wrong is printed and the gates run.
1904
+ if (moment === "push") {
1905
+ try {
1906
+ runStartOfRunSweep();
1907
+ } catch (err) {
1908
+ console.log(
1909
+ `🧹 cleanup sweep did not finish (${err.message}); continuing`
1910
+ );
1911
+ }
1912
+ }
1913
+
1900
1914
  // `--coverage` is how a caller says "I skip my built-in steps ONE AT A TIME,
1901
1915
  // against the names in this file". Such a caller does not need the moment
1902
1916
  // withheld from it: a property it never sees named keeps its own step, so a