@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,74 @@
1
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
2
+ // Do not edit directly — durable changes belong upstream in Lisa.
3
+
4
+ /** The run that owns a test process. */
5
+ export interface RunOwner {
6
+ readonly pid: number;
7
+ readonly start: string;
8
+ }
9
+
10
+ /** One row of the current user's process table. */
11
+ export interface ProcessRow {
12
+ readonly pid: number;
13
+ readonly ppid: number;
14
+ readonly owner: RunOwner | null;
15
+ }
16
+
17
+ export const OWNER_ENV: "LISA_TEST_RUN_OWNER";
18
+ export const UNKNOWN_START: "0";
19
+ export const DEFAULT_GRACE_MS: number;
20
+
21
+ export function formatOwnerMarker(
22
+ pid: number,
23
+ start: string | undefined
24
+ ): string;
25
+ export function parseOwnerMarker(value: unknown): RunOwner | null;
26
+ /** Parse `ps -E` output, stripping each process's own arguments (from `argumentsOnly`) first. */
27
+ export function parseDarwinProcessTable(
28
+ withEnvironment: string,
29
+ argumentsOnly: string
30
+ ): ProcessRow[];
31
+ /** The owner from a NUL-separated `/proc/<pid>/environ`; whole entries only. */
32
+ export function parseLinuxEnviron(environ: string): RunOwner | null;
33
+ export function parseDarwinStartTimes(stdout: string): Map<number, string>;
34
+ export function parseLinuxStat(
35
+ stat: string
36
+ ): { ppid: number; start: string } | null;
37
+ export function listProcesses(options?: {
38
+ platform?: string;
39
+ procRoot?: string;
40
+ }): ProcessRow[];
41
+ export function processStartTimes(
42
+ pids: readonly number[],
43
+ options?: { platform?: string; procRoot?: string }
44
+ ): Map<number, string>;
45
+ /** The `<pid>:<start>` marker value a test run started by `pid` exports. */
46
+ export function ownerMarkerFor(pid?: number): string;
47
+ export function isAlive(pid: number): boolean;
48
+ /** The pid of the sweeper a `LISA_CLEANUP_SWEPT` value names, while it still runs. */
49
+ export function liveSweeper(
50
+ value: unknown,
51
+ lookups?: {
52
+ isAlive?: (pid: number) => boolean;
53
+ startTimesOf?: (pids: number[]) => Map<number, string>;
54
+ }
55
+ ): number | null;
56
+ export function selectOrphans(
57
+ rows: readonly ProcessRow[],
58
+ seams: {
59
+ selfPid: number;
60
+ isAlive: (pid: number) => boolean;
61
+ startTimesOf: (pids: number[]) => Map<number, string>;
62
+ }
63
+ ): number[];
64
+ /** Kill every orphaned test process: SIGTERM, a short grace, then SIGKILL. */
65
+ export function sweepOrphans(options?: {
66
+ selfPid?: number;
67
+ listProcesses?: () => readonly ProcessRow[];
68
+ isAlive?: (pid: number) => boolean;
69
+ startTimesOf?: (pids: number[]) => Map<number, string>;
70
+ kill?: (pid: number, signal: string) => void;
71
+ sleep?: (ms: number) => Promise<unknown>;
72
+ graceMs?: number;
73
+ dryRun?: boolean;
74
+ }): Promise<{ killed: number[]; errors: string[] }>;
@@ -0,0 +1,527 @@
1
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
2
+ // Do not edit directly — durable changes belong upstream in Lisa.
3
+
4
+ /**
5
+ * The orphaned-process half of the start-of-run cleanup sweep
6
+ * (CodySwannGT/lisa#4597).
7
+ *
8
+ * ## How a test process says who owns it
9
+ *
10
+ * `lisa-test-run` (and, for RSpec, the Rails pre-push) puts
11
+ * `LISA_TEST_RUN_OWNER=<pid>:<start>` in its own environment before it starts
12
+ * anything, so every test process and every descendant inherits it. `<start>`
13
+ * is the owner's process start time — Linux start ticks from `/proc`, or whole
14
+ * epoch seconds from `ps -o lstart=` on macOS — so a pid the kernel has since
15
+ * handed to an unrelated process is not mistaken for the owner. `0` means the
16
+ * start time could not be read when the marker was written.
17
+ *
18
+ * ## What is killed, and what never is
19
+ *
20
+ * A marked process is killed only when its owner is gone: the owner pid is
21
+ * dead, or it is alive with a start time that differs from the recorded one.
22
+ * Everything that cannot be proven gone is spared — an owner whose current or
23
+ * recorded start time is unknown, a process listing that failed, a pid that
24
+ * answers EPERM. The sweep itself and every one of its ancestors are spared
25
+ * unconditionally, so a nested run can never kill the run that launched it.
26
+ *
27
+ * Only the current user's processes are listed, and nothing but the pid, the
28
+ * parent pid and the marker is kept from a listing: `ps -E` prints the whole
29
+ * environment, which routinely holds tokens. A marker counts only where it is
30
+ * genuinely environment — a whole `/proc/<pid>/environ` entry, or the text
31
+ * `ps -E` prints after the process's own arguments — so a marker typed as an
32
+ * argument cannot get a process killed. Each orphan's start time is recorded
33
+ * before SIGTERM, and a pid whose start time changed during the grace (a new
34
+ * process that inherited the pid) gets no SIGKILL.
35
+ *
36
+ * ## A macOS visibility gap, and why it fails safe
37
+ *
38
+ * macOS withholds the environment of Apple-signed binaries (`/bin/sleep`,
39
+ * `/bin/sh`, `/bin/bash`, the system `ruby` and `perl`) from `ps -E`, even for
40
+ * the same user. Such a process shows no marker, so the sweep never selects
41
+ * it: an orphaned `sh -c` wrapper survives, while the `node`/`bun` test
42
+ * processes under it — whose environment IS shown — are killed. Linux reads
43
+ * `/proc/<pid>/environ` and has no such gap.
44
+ *
45
+ * `ps -E` also joins variables with bare spaces, so on macOS another
46
+ * variable whose VALUE contains ` LISA_TEST_RUN_OWNER=<pid>:<start>` is
47
+ * indistinguishable from the real variable. Only a process whose environment
48
+ * deliberately carries that text is exposed, and only to the same user's
49
+ * sweep; Linux reads whole environ entries and has no such ambiguity.
50
+ *
51
+ * Deliberately independent of `src/configs/vitest/scratch-*.ts`, which the
52
+ * per-test policing this sweep replaces (C2) will retire. The start-time
53
+ * reading mirrors `scratch-owner.ts` rather than importing it.
54
+ * @module scripts/lib/lisa-cleanup-sweep-processes
55
+ */
56
+ import { readdirSync, readFileSync, statSync } from "node:fs";
57
+ import { setTimeout as delay } from "node:timers/promises";
58
+
59
+ import { boundedSpawnSync } from "./bounded-spawn.mjs";
60
+
61
+ /** Environment variable every test run's processes inherit. */
62
+ export const OWNER_ENV = "LISA_TEST_RUN_OWNER";
63
+
64
+ /** Recorded start time meaning "could not be read when the marker was set". */
65
+ export const UNKNOWN_START = "0";
66
+
67
+ /** Default wait between SIGTERM and SIGKILL. */
68
+ export const DEFAULT_GRACE_MS = 500;
69
+
70
+ /** Deadline for each `ps` call; the sweep must stay inside seconds. */
71
+ const PS_TIMEOUT_MS = 5_000;
72
+
73
+ /** `ps -E` prints every environment; leave room for a busy desktop. */
74
+ const PS_MAX_BUFFER = 64 * 1024 * 1024;
75
+
76
+ /** Pids per `ps -p` call, matching the batching `scratch-owner.ts` uses. */
77
+ const PS_BATCH = 256;
78
+
79
+ /** Locale-independent `ps` output, so `lstart` parses the same everywhere. */
80
+ const PS_ENV = { ...process.env, LC_ALL: "C", LANG: "C" };
81
+
82
+ const MARKER_IN_TEXT = /(?:^|\s)LISA_TEST_RUN_OWNER=(\d+:\d+)(?=\s|$)/gu;
83
+
84
+ /** Prefix of the one environ entry that carries the owner. */
85
+ const MARKER_ENTRY = `${OWNER_ENV}=`;
86
+
87
+ /**
88
+ * Format the owner marker value.
89
+ * @param {number} pid - Owner process id.
90
+ * @param {string | undefined} start - Owner start time, when known.
91
+ * @returns {string} `<pid>:<start>`.
92
+ */
93
+ export function formatOwnerMarker(pid, start) {
94
+ return `${pid}:${start ?? UNKNOWN_START}`;
95
+ }
96
+
97
+ /**
98
+ * Parse an owner marker value.
99
+ * @param {unknown} value - Raw `LISA_TEST_RUN_OWNER` value.
100
+ * @returns {{pid: number, start: string} | null} The owner, or null when malformed.
101
+ */
102
+ export function parseOwnerMarker(value) {
103
+ const match = /^(\d+):(\d+)$/u.exec(typeof value === "string" ? value : "");
104
+ if (!match) return null;
105
+ const pid = Number(match[1]);
106
+ return Number.isSafeInteger(pid) && pid > 0 ? { pid, start: match[2] } : null;
107
+ }
108
+
109
+ /**
110
+ * Find the owner marker in the environment half of a `ps -E` line.
111
+ *
112
+ * Two different markers there mean something other than the real variable
113
+ * says so — another variable's value — and the row is spared.
114
+ * @param {string} environment - Space-separated environment text.
115
+ * @returns {{pid: number, start: string} | null} The owner, if unambiguous.
116
+ */
117
+ function ownerInEnvironment(environment) {
118
+ const found = new Set(
119
+ [...environment.matchAll(MARKER_IN_TEXT)].map(match => match[1])
120
+ );
121
+ return found.size === 1 ? parseOwnerMarker([...found][0]) : null;
122
+ }
123
+
124
+ /**
125
+ * Find the owner in a NUL-separated `/proc/<pid>/environ`.
126
+ *
127
+ * Only a whole entry counts, so a marker quoted inside another variable's
128
+ * value is not mistaken for the real one.
129
+ * @param {string} environ - Raw environ contents.
130
+ * @returns {{pid: number, start: string} | null} The owner, if marked.
131
+ */
132
+ export function parseLinuxEnviron(environ) {
133
+ const entry = environ.split("\0").find(item => item.startsWith(MARKER_ENTRY));
134
+ return entry ? parseOwnerMarker(entry.slice(MARKER_ENTRY.length)) : null;
135
+ }
136
+
137
+ /**
138
+ * Map pid to its arguments from `ps -ww -o pid=,command=` output.
139
+ * @param {string} stdout - Raw `ps` output, without `-E`.
140
+ * @returns {Map<number, string>} Arguments by pid.
141
+ */
142
+ function argumentsByPid(stdout) {
143
+ return new Map(
144
+ stdout.split("\n").flatMap(line => {
145
+ const match = /^\s*(\d+) (.*)$/u.exec(line);
146
+ return match ? [[Number(match[1]), match[2]]] : [];
147
+ })
148
+ );
149
+ }
150
+
151
+ /**
152
+ * Parse `ps -E` output, keeping only pid, ppid and owner.
153
+ *
154
+ * `ps -E -o command=` prints a process's ARGUMENTS and then its environment
155
+ * on one line, so a marker typed as an argument reads exactly like one in the
156
+ * environment. The same process's arguments, listed without `-E`, are stripped
157
+ * off the front first, and only what follows is searched. A row whose
158
+ * arguments do not line up — the process exec'd or exited between the two
159
+ * listings — is given no marker, which spares it.
160
+ * @param {string} withEnvironment - `ps -E -ww -o pid=,ppid=,command=` output.
161
+ * @param {string} argumentsOnly - `ps -ww -o pid=,command=` output.
162
+ * @returns {Array<{pid: number, ppid: number, owner: {pid: number, start: string} | null}>} Rows.
163
+ */
164
+ export function parseDarwinProcessTable(withEnvironment, argumentsOnly) {
165
+ const args = argumentsByPid(argumentsOnly);
166
+ return withEnvironment.split("\n").flatMap(line => {
167
+ const match = /^\s*(\d+)\s+(\d+)(?:\s(.*))?$/u.exec(line);
168
+ if (!match) return [];
169
+ const pid = Number(match[1]);
170
+ const command = match[3] ?? "";
171
+ const known = args.get(pid);
172
+ const aligned = known !== undefined && command.startsWith(known);
173
+ const owner = aligned
174
+ ? ownerInEnvironment(command.slice(known.length))
175
+ : null;
176
+ return [{ pid, ppid: Number(match[2]), owner }];
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Parse `ps -o pid= -o lstart=` output into whole epoch seconds.
182
+ * @param {string} stdout - Raw `ps` output.
183
+ * @returns {Map<number, string>} Start time by pid.
184
+ */
185
+ export function parseDarwinStartTimes(stdout) {
186
+ return new Map(
187
+ stdout.split("\n").flatMap(line => {
188
+ const match = /^\s*(\d+)\s+(\S.*\S)\s*$/u.exec(line);
189
+ const epochMs = match ? Date.parse(match[2].replace(/\s+/gu, " ")) : NaN;
190
+ if (!match || !Number.isFinite(epochMs)) return [];
191
+ return [[Number(match[1]), String(Math.floor(epochMs / 1000))]];
192
+ })
193
+ );
194
+ }
195
+
196
+ /**
197
+ * Read ppid and start ticks from a `/proc/<pid>/stat` line.
198
+ *
199
+ * Fields are counted from the LAST `)`, because the command name between the
200
+ * parentheses may itself contain spaces and parentheses.
201
+ * @param {string} stat - Contents of `/proc/<pid>/stat`.
202
+ * @returns {{ppid: number, start: string} | null} Parsed fields, or null.
203
+ */
204
+ export function parseLinuxStat(stat) {
205
+ const commEnd = stat.lastIndexOf(")");
206
+ if (commEnd < 0) return null;
207
+ const fields = stat
208
+ .slice(commEnd + 2)
209
+ .trim()
210
+ .split(/\s+/u);
211
+ const ppid = Number(fields[1]);
212
+ const start = fields[19];
213
+ if (!Number.isSafeInteger(ppid) || !start || !/^\d+$/u.test(start))
214
+ return null;
215
+ return { ppid, start };
216
+ }
217
+
218
+ /**
219
+ * Run `ps` under a deadline with a locale-independent environment.
220
+ * @param {readonly string[]} args - `ps` arguments.
221
+ * @returns {string} Its stdout; empty when it could not run.
222
+ */
223
+ function runPs(args) {
224
+ try {
225
+ const child = boundedSpawnSync("/bin/ps", args, {
226
+ encoding: "utf8",
227
+ env: PS_ENV,
228
+ maxBuffer: PS_MAX_BUFFER,
229
+ stdio: ["ignore", "pipe", "ignore"],
230
+ timeout: PS_TIMEOUT_MS,
231
+ });
232
+ // probe-direction: fail-closed — no rows means no process is selected and
233
+ // no owner is known, so nothing is killed. `ps -p` exits 1 when any listed
234
+ // pid is gone but still prints the rest, so the status is not consulted.
235
+ return child.error ? "" : String(child.stdout ?? "");
236
+ } catch {
237
+ // probe-direction: fail-closed — a killed `ps` selects nothing to kill.
238
+ return "";
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Read one Linux process's stat, or null when it has gone or is unreadable.
244
+ * @param {string} procRoot - Usually `/proc`.
245
+ * @param {number} pid - Process id.
246
+ * @returns {{ppid: number, start: string} | null} Parsed stat.
247
+ */
248
+ function linuxStat(procRoot, pid) {
249
+ try {
250
+ return parseLinuxStat(readFileSync(`${procRoot}/${pid}/stat`, "utf8"));
251
+ } catch {
252
+ // probe-direction: fail-closed — an unreadable process is never selected.
253
+ return null;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * One Linux row for a process this user owns, or null.
259
+ * @param {string} procRoot - Usually `/proc`.
260
+ * @param {number} pid - Process id.
261
+ * @param {number | undefined} uid - Current user id.
262
+ * @returns {{pid: number, ppid: number, owner: {pid: number, start: string} | null} | null} Row.
263
+ */
264
+ function linuxRow(procRoot, pid, uid) {
265
+ const stat = linuxStat(procRoot, pid);
266
+ if (!stat) return null;
267
+ try {
268
+ const mine =
269
+ uid === undefined || statSync(`${procRoot}/${pid}`).uid === uid;
270
+ const environ = mine
271
+ ? readFileSync(`${procRoot}/${pid}/environ`, "utf8")
272
+ : "";
273
+ return { pid, ppid: stat.ppid, owner: parseLinuxEnviron(environ) };
274
+ } catch {
275
+ // probe-direction: fail-closed — an unreadable environment carries no
276
+ // marker, so the process is kept for ancestry and never killed.
277
+ return { pid, ppid: stat.ppid, owner: null };
278
+ }
279
+ }
280
+
281
+ /**
282
+ * List this user's processes with their parent and owner marker.
283
+ * @param {object} [options] - Platform seams.
284
+ * @param {string} [options.platform] - Defaults to `process.platform`.
285
+ * @param {string} [options.procRoot] - Linux proc mount, defaults to `/proc`.
286
+ * @returns {Array<{pid: number, ppid: number, owner: {pid: number, start: string} | null}>} Rows.
287
+ */
288
+ export function listProcesses({
289
+ platform = process.platform,
290
+ procRoot = "/proc",
291
+ } = {}) {
292
+ const uid = process.getuid?.();
293
+ if (platform === "linux") {
294
+ return readdirSync(procRoot)
295
+ .filter(name => /^\d+$/u.test(name))
296
+ .map(name => linuxRow(procRoot, Number(name), uid))
297
+ .filter(row => row !== null);
298
+ }
299
+ if (platform !== "darwin") return [];
300
+ const user = uid === undefined ? ["-A"] : ["-U", String(uid)];
301
+ // Arguments first: a process that starts between the two calls is then
302
+ // missing from the arguments map and is spared, never misread.
303
+ const argumentsOnly = runPs(["-ww", ...user, "-o", "pid=,command="]);
304
+ return parseDarwinProcessTable(
305
+ runPs(["-E", "-ww", ...user, "-o", "pid=,ppid=,command="]),
306
+ argumentsOnly
307
+ );
308
+ }
309
+
310
+ /**
311
+ * Read start times for a set of pids.
312
+ * @param {readonly number[]} pids - Process ids to inspect.
313
+ * @param {object} [options] - Platform seams.
314
+ * @param {string} [options.platform] - Defaults to `process.platform`.
315
+ * @param {string} [options.procRoot] - Linux proc mount, defaults to `/proc`.
316
+ * @returns {Map<number, string>} Start time by pid; a missing pid is unknown.
317
+ */
318
+ export function processStartTimes(
319
+ pids,
320
+ { platform = process.platform, procRoot = "/proc" } = {}
321
+ ) {
322
+ const unique = [...new Set(pids)].filter(
323
+ pid => Number.isSafeInteger(pid) && pid > 0
324
+ );
325
+ if (platform === "linux") {
326
+ return new Map(
327
+ unique.flatMap(pid => {
328
+ const stat = linuxStat(procRoot, pid);
329
+ return stat ? [[pid, stat.start]] : [];
330
+ })
331
+ );
332
+ }
333
+ if (platform !== "darwin") return new Map();
334
+ const batches = Array.from(
335
+ { length: Math.ceil(unique.length / PS_BATCH) },
336
+ (_, i) => unique.slice(i * PS_BATCH, (i + 1) * PS_BATCH)
337
+ );
338
+ return new Map(
339
+ batches.flatMap(batch => [
340
+ ...parseDarwinStartTimes(
341
+ runPs(["-p", batch.join(","), "-o", "pid=", "-o", "lstart="])
342
+ ),
343
+ ])
344
+ );
345
+ }
346
+
347
+ /**
348
+ * The marker value a test run started by `pid` should export.
349
+ * @param {number} [pid] - Owner process id, defaults to this process.
350
+ * @returns {string} `<pid>:<start>`, with `0` when the start time is unknown.
351
+ */
352
+ export function ownerMarkerFor(pid = process.pid) {
353
+ return formatOwnerMarker(pid, processStartTimes([pid]).get(pid));
354
+ }
355
+
356
+ /**
357
+ * The pid of the sweeper a `LISA_CLEANUP_SWEPT` value names, if it still runs.
358
+ *
359
+ * The value is the sweeper's own `<pid>:<start>`. It proves "already swept"
360
+ * only while that exact process is alive: a dead pid, a reused pid (start
361
+ * time differs) or an unknown start time all mean nobody can vouch for a
362
+ * sweep, so the caller sweeps again — a second sweep is cheap, a silently
363
+ * disabled one is not.
364
+ * @param {unknown} value - The inherited `LISA_CLEANUP_SWEPT` value.
365
+ * @param {object} [lookups] - Liveness and start-time seams.
366
+ * @param {(pid: number) => boolean} [lookups.isAlive] - Liveness check.
367
+ * @param {(pids: number[]) => Map<number, string>} [lookups.startTimesOf] - Start-time lookup.
368
+ * @returns {number | null} The live sweeper's pid, or null.
369
+ */
370
+ export function liveSweeper(
371
+ value,
372
+ { isAlive: alive = isAlive, startTimesOf = processStartTimes } = {}
373
+ ) {
374
+ const sweeper = parseOwnerMarker(value);
375
+ if (!sweeper || sweeper.start === UNKNOWN_START || !alive(sweeper.pid)) {
376
+ return null;
377
+ }
378
+ const current = startTimesOf([sweeper.pid]).get(sweeper.pid);
379
+ return current === sweeper.start ? sweeper.pid : null;
380
+ }
381
+
382
+ /**
383
+ * Whether a pid names a live process. EPERM means alive but not ours.
384
+ * @param {number} pid - Process id.
385
+ * @returns {boolean} True when the process exists.
386
+ */
387
+ export function isAlive(pid) {
388
+ try {
389
+ process.kill(pid, 0);
390
+ return true;
391
+ } catch (error) {
392
+ return error?.code === "EPERM";
393
+ }
394
+ }
395
+
396
+ /**
397
+ * The sweep's own pid and every ancestor reachable through the table.
398
+ * @param {number} selfPid - The sweeping process.
399
+ * @param {ReadonlyArray<{pid: number, ppid: number}>} rows - Process table.
400
+ * @returns {Set<number>} Pids that must never be signalled.
401
+ */
402
+ function lineageOf(selfPid, rows) {
403
+ const parent = new Map(rows.map(row => [row.pid, row.ppid]));
404
+ const spared = new Set();
405
+ addLineage(selfPid, parent, spared);
406
+ addLineage(process.ppid, parent, spared);
407
+ return spared;
408
+ }
409
+
410
+ /**
411
+ * Add a pid and every ancestor the table knows to `spared`.
412
+ * @param {number | undefined} start - First pid of the walk.
413
+ * @param {Map<number, number>} parent - Parent pid by pid.
414
+ * @param {Set<number>} spared - Collector; the walk stops at a pid already in it.
415
+ * @returns {void}
416
+ */
417
+ function addLineage(start, parent, spared) {
418
+ for (let pid = start; pid && !spared.has(pid); pid = parent.get(pid)) {
419
+ spared.add(pid);
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Whether an owner is provably gone.
425
+ * @param {{start: string}} owner - Recorded owner.
426
+ * @param {boolean} alive - Whether the owner pid is alive now.
427
+ * @param {string | undefined} current - Its current start time, when known.
428
+ * @returns {boolean} True only when the owner is dead or its pid was reused.
429
+ */
430
+ function ownerIsGone(owner, alive, current) {
431
+ if (!alive) return true;
432
+ if (owner.start === UNKNOWN_START || current === undefined) return false;
433
+ return current !== owner.start;
434
+ }
435
+
436
+ /**
437
+ * Select the pids of marked processes whose owning run is gone.
438
+ * @param {ReadonlyArray<{pid: number, ppid: number, owner: {pid: number, start: string} | null}>} rows - Process table.
439
+ * @param {object} seams - Injected lookups.
440
+ * @param {number} seams.selfPid - The sweeping process.
441
+ * @param {(pid: number) => boolean} seams.isAlive - Liveness check.
442
+ * @param {(pids: number[]) => Map<number, string>} seams.startTimesOf - Start-time lookup.
443
+ * @returns {number[]} Orphan pids, in table order.
444
+ */
445
+ export function selectOrphans(rows, { selfPid, isAlive: alive, startTimesOf }) {
446
+ const spared = lineageOf(selfPid, rows);
447
+ const marked = rows.filter(row => row.owner && !spared.has(row.pid));
448
+ const owners = [...new Set(marked.map(row => row.owner.pid))];
449
+ const liveOwners = owners.filter(pid => alive(pid));
450
+ const starts = liveOwners.length > 0 ? startTimesOf(liveOwners) : new Map();
451
+ const live = new Set(liveOwners);
452
+ return marked
453
+ .filter(row =>
454
+ ownerIsGone(row.owner, live.has(row.owner.pid), starts.get(row.owner.pid))
455
+ )
456
+ .map(row => row.pid);
457
+ }
458
+
459
+ /**
460
+ * Send one signal, reporting whether it was delivered.
461
+ * @param {(pid: number, signal: string) => void} kill - Signal seam.
462
+ * @param {number} pid - Target.
463
+ * @param {string} signal - Signal name.
464
+ * @param {string[]} errors - Collector for undeliverable signals.
465
+ * @returns {boolean} True when the signal was delivered.
466
+ */
467
+ function signal(kill, pid, signal, errors) {
468
+ try {
469
+ kill(pid, signal);
470
+ return true;
471
+ } catch (error) {
472
+ if (error?.code !== "ESRCH")
473
+ errors.push(`could not ${signal} ${pid}: ${error?.code ?? error}`);
474
+ return false;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * Kill every orphaned test process: SIGTERM, a short grace, then SIGKILL.
480
+ * @param {object} [options] - Seams and switches; every one has a real default.
481
+ * @param {number} [options.selfPid] - The sweeping process.
482
+ * @param {() => ReturnType<typeof listProcesses>} [options.listProcesses] - Table source.
483
+ * @param {(pid: number) => boolean} [options.isAlive] - Liveness check.
484
+ * @param {(pids: number[]) => Map<number, string>} [options.startTimesOf] - Start-time lookup.
485
+ * @param {(pid: number, signal: string) => void} [options.kill] - Signal seam.
486
+ * @param {(ms: number) => Promise<unknown>} [options.sleep] - Grace wait.
487
+ * @param {number} [options.graceMs] - SIGTERM-to-SIGKILL grace.
488
+ * @param {boolean} [options.dryRun] - Select but signal nothing.
489
+ * @returns {Promise<{killed: number[], errors: string[]}>} What was terminated.
490
+ */
491
+ export async function sweepOrphans(options = {}) {
492
+ const {
493
+ selfPid = process.pid,
494
+ listProcesses: list = listProcesses,
495
+ isAlive: alive = isAlive,
496
+ startTimesOf = processStartTimes,
497
+ kill = (pid, sig) => process.kill(pid, sig),
498
+ sleep = delay,
499
+ graceMs = DEFAULT_GRACE_MS,
500
+ dryRun = false,
501
+ } = options;
502
+ const errors = [];
503
+ let orphans;
504
+ try {
505
+ orphans = selectOrphans(list(), { selfPid, isAlive: alive, startTimesOf });
506
+ } catch (error) {
507
+ return {
508
+ killed: [],
509
+ errors: [`process listing failed: ${error?.message ?? error}`],
510
+ };
511
+ }
512
+ if (dryRun || orphans.length === 0) return { killed: orphans, errors };
513
+ const recorded = startTimesOf(orphans);
514
+ const killed = orphans.filter(pid => signal(kill, pid, "SIGTERM", errors));
515
+ if (killed.length === 0) return { killed, errors };
516
+ await sleep(graceMs);
517
+ const survivors = killed.filter(pid => alive(pid));
518
+ const current = survivors.length > 0 ? startTimesOf(survivors) : new Map();
519
+ // A survivor whose start time changed during the grace is a NEW process
520
+ // that inherited the pid; it gets no SIGKILL. One whose start time was never
521
+ // recorded cannot be proven the same process, so it gets SIGTERM only.
522
+ const samePid = pid =>
523
+ recorded.has(pid) && current.get(pid) === recorded.get(pid);
524
+ for (const pid of survivors.filter(samePid))
525
+ signal(kill, pid, "SIGKILL", errors);
526
+ return { killed, errors };
527
+ }
@@ -0,0 +1,80 @@
1
+ // This file is managed by Lisa and IS replaced on each `lisa` run.
2
+ // Do not edit directly — durable changes belong upstream in Lisa.
3
+
4
+ /** What one cleanup sweep did. */
5
+ export interface SweepResult {
6
+ readonly removed: string[];
7
+ /** Stale Lisa-named entries kept because another user owns or could write them. */
8
+ readonly skippedUnsafe?: number;
9
+ readonly killed: number[];
10
+ readonly errors: string[];
11
+ readonly dryRun: boolean;
12
+ readonly durationMs: number;
13
+ }
14
+
15
+ /** Options for {@link sweep}; every one has a default. */
16
+ export interface SweepOptions {
17
+ readonly root?: string;
18
+ readonly maxAgeHours?: number;
19
+ readonly now?: number;
20
+ readonly dryRun?: boolean;
21
+ readonly uid?: number;
22
+ readonly home?: string;
23
+ readonly cwd?: string;
24
+ readonly orphans?: false | Record<string, unknown>;
25
+ }
26
+
27
+ export const LISA_OWNED_TEMP_PREFIXES: readonly string[];
28
+ export const LISA_PROTECTED_TEMP_NAMES: readonly string[];
29
+ export const LISA_PROTECTED_TEMP_PREFIXES: readonly string[];
30
+ export const SWEPT_ENV: "LISA_CLEANUP_SWEPT";
31
+ export const DEFAULT_MAX_AGE_HOURS: number;
32
+
33
+ /** Whether a top-level temp name is Lisa-owned and sweepable. */
34
+ export function isLisaOwnedTempName(name: string): boolean;
35
+
36
+ /** Remove stale Lisa temp entries from the top level of `root`. */
37
+ export function sweepTemp(options: {
38
+ root: string;
39
+ maxAgeHours: number;
40
+ now: number;
41
+ dryRun: boolean;
42
+ uid?: number;
43
+ home?: string;
44
+ cwd?: string;
45
+ }): Promise<{ removed: string[]; skippedUnsafe: number; errors: string[] }>;
46
+
47
+ /** Run the whole sweep: stale temp entries, then orphaned test processes. */
48
+ export function sweep(options?: SweepOptions): Promise<SweepResult>;
49
+
50
+ /** The one summary line a sweep prints. */
51
+ export function formatSummary(result: SweepResult): string;
52
+
53
+ /** Parse CLI flags; throws on an unknown flag or an invalid age. */
54
+ export function parseSweepArgs(argv: readonly string[]): {
55
+ dryRun: boolean;
56
+ json: boolean;
57
+ maxAgeHours: number;
58
+ processes: boolean;
59
+ };
60
+
61
+ /** The line printed when a live sweeper already swept. */
62
+ export function formatAlreadySwept(pid: number): string;
63
+
64
+ /** CLI entry point; resolves to the exit code. */
65
+ export function main(
66
+ argv?: readonly string[],
67
+ seams?: {
68
+ sweepOptions?: SweepOptions;
69
+ write?: (line: string) => void;
70
+ }
71
+ ): Promise<number>;
72
+
73
+ /** Sweep once from a synchronous caller, never failing it. */
74
+ export function runStartOfRunSweep(seams?: {
75
+ env?: Record<string, string | undefined>;
76
+ spawn?: (...args: never[]) => unknown;
77
+ log?: (line: string) => void;
78
+ ownerMarker?: () => string;
79
+ liveSweeper?: (value: unknown) => number | null;
80
+ }): void;