cliprobe 1.3.0 → 1.4.1

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.
package/README.md CHANGED
@@ -150,7 +150,7 @@ npx cliprobe --strict --skip restore -- node ./dist/cli.js server # warnings f
150
150
  | `1` | A check failed, or warned with `--strict` |
151
151
  | `2` | Usage error, or the command could not run |
152
152
 
153
- A command that isn't on `PATH` is reported once, before any check runs, with exit `2` and no report. That makes cliprobe usable as a CI gate.
153
+ A command that can't run is reported once, before any check runs, with exit `2` and no report: one that isn't on `PATH`, a directory, a file without the execute bit (`chmod +x`), or a script whose `#!` interpreter is missing. A file this system can't execute at all, such as a binary built for another platform, makes every check say could-not-run (`ERROR`), so cliprobe exits `2` there too; on Linux, where `/bin/sh` tries such a file as a script, cliprobe recognizes the shell's complaint. That makes cliprobe usable as a CI gate.
154
154
 
155
155
  ## In CI
156
156
 
@@ -270,14 +270,14 @@ A carriage-return redraw only warns because some tools draw a progress meter on
270
270
 
271
271
  ### stdin
272
272
 
273
- Agents and CI runners often start a command with stdin as a pipe that stays open and never receives anything. A program that reads stdin, or asks a question, then waits forever. cliprobe runs the command three ways: with stdin closed (`/dev/null`), with an open pipe, and, if that hangs for 3 seconds, with a pipe it closes after 1 second. Finishing right after the close proves stdin was the cause. Results:
273
+ Agents and CI runners often start a command with stdin as a pipe that stays open and never receives anything. A program that reads stdin, or asks a question, then waits forever. cliprobe runs the command three ways: with stdin closed (`/dev/null`), with an open pipe, and, if that hangs, with a pipe it closes partway through. Finishing only after the close proves stdin was the cause. The open pipe gets 3 seconds, or twice the time the command took with stdin closed plus 1 second if that is longer, so a program that is just slow to answer isn't mistaken for one that waits. The pipe in the third run is closed after 1 second, or after that longer time for a slow command. Each run still stops at `--timeout`. Results:
274
274
 
275
- | Verdict | Meaning |
276
- | ------- | ------------------------------------------------------------------------------------------------------------------------- |
277
- | `PASS` | Finished without waiting for stdin |
278
- | `FAIL` | `--version` or `--help` waited for stdin before answering: they must never need input |
279
- | `WARN` | A probe you wrote printed an unfinished line, like a question, then waited: it prompts even though stdin isn't a terminal |
280
- | `SKIP` | A probe you wrote waited silently, like a filter (`grep pattern`), or the hang wasn't caused by stdin |
275
+ | Verdict | Meaning |
276
+ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
277
+ | `PASS` | Finished without waiting for stdin |
278
+ | `FAIL` | `--version` or `--help` waited for stdin before answering: they must never need input |
279
+ | `WARN` | A probe you wrote printed an unfinished line, like a question, then waited: it prompts even though stdin isn't a terminal |
280
+ | `SKIP` | A probe you wrote waited silently, like a filter (`grep pattern`), the hang wasn't caused by stdin, or the command is too slow for `--timeout` to tell |
281
281
 
282
282
  In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs failed, each confirmed by hand. he, cssesc and ansi-html read stdin before looking at their arguments. webpack and webpack-dev-server, when webpack-cli is missing, ask whether to install it and wait for an answer without checking for a terminal. With no arguments, 17 tools waited on stdin as filters by design, which is why probes you write never fail this check.
283
283
 
@@ -285,22 +285,24 @@ In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs fa
285
285
 
286
286
  cliprobe lets the command run for 1 second, then sends SIGINT to its process group, which is what a terminal does when you press Ctrl-C, and gives it 3 seconds to exit. stdin is left open, as a terminal leaves it, so a server that stops at the end of stdin (`esbuild --serve`) keeps running until the Ctrl-C. Results:
287
287
 
288
- | Verdict | Meaning |
289
- | ------- | ---------------------------------------------------------------------------------------------- |
290
- | `PASS` | Stopped by SIGINT, exited 130 (the convention), or exited with another failure code |
291
- | `FAIL` | Still running 3 seconds later, or printed a stack trace or traceback after the Ctrl-C |
292
- | `WARN` | Exited 0, so a script or an agent can't tell the work was interrupted |
293
- | `SKIP` | Finished before the Ctrl-C, as `--version` and `--help` do: probe a command that keeps running |
288
+ | Verdict | Meaning |
289
+ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
290
+ | `PASS` | Stopped by SIGINT, exited 130 (the convention), or exited with another failure code |
291
+ | `FAIL` | Still running 3 seconds later, or printed a stack trace or traceback after the Ctrl-C |
292
+ | `WARN` | Exited 0, so a script or an agent can't tell the work was interrupted, or exited but left processes running that ignored the Ctrl-C (the evidence names the first) |
293
+ | `SKIP` | Finished before the Ctrl-C, as `--version` and `--help` do: probe a command that keeps running |
294
294
 
295
295
  A stack trace printed before the Ctrl-C doesn't count. Python's default `KeyboardInterrupt` traceback is the classic failure here, so `python3 -c 'import time; time.sleep(30)'` fails. Across 42 watch modes, dev servers and long tasks run offline (vite, webpack, tsc, jest, Next.js, Nuxt, Astro, wrangler, nodemon and more), every one stopped within 60 ms of the Ctrl-C, whether it came after 1, 3 or 6 seconds, so the timing rarely matters. 13 of them exit 0 on purpose, among them `tsc --watch`, webpack, `next dev` and `nuxt dev`: that is a warn, not a fail.
296
296
 
297
+ The verdict is about the program itself: it passes once it exits, even if a child still holds its output open. What it leaves running gets 1 more second to follow, then is listed and killed. A process still there ignored the Ctrl-C, as a shell's background job does (`sh -c 'worker & server'`), so it would outlive the terminal's Ctrl-C too: that is a warn, added in 1.4.
298
+
297
299
  ### sigterm
298
300
 
299
- `kill <pid>`, `docker stop`, systemd, pm2 and CI runners that cancel a job send SIGTERM to the program alone, not to its process group as a terminal sends Ctrl-C. So a program that started children (a dev server, a worker pool, a shell running a command) has to stop them itself. If it exits without doing so, they keep running with nobody to stop them, holding their ports and files. cliprobe lets the command run for 1 second, sends SIGTERM to it alone, and gives it 3 seconds to exit and 1 more second for its children to follow, then lists what is still running in its process group and kills it. stdin is left open, as for ctrl-c. Results:
301
+ `kill <pid>`, `docker stop`, systemd, pm2 and CI runners that cancel a job send SIGTERM to the program alone, not to its process group as a terminal sends Ctrl-C. So a program that started children (a dev server, a worker pool, a shell running a command) has to stop them itself. If it exits without doing so, they keep running with nobody to stop them, holding their ports and files. cliprobe lets the command run for 1 second, sends SIGTERM to it alone, and gives it 3 seconds to exit and 1 more second for its children to follow, then lists what is still running and kills it: in its process group, and the processes it started in a group or session of their own (Node's `detached`, `setsid`, daemons). stdin is left open, as for ctrl-c. Results:
300
302
 
301
303
  | Verdict | Meaning |
302
304
  | ------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
303
- | `PASS` | Exited, by the signal or with any exit code, and left nothing running in its process group |
305
+ | `PASS` | Exited, by the signal or with any exit code, and left nothing running |
304
306
  | `WARN` | Exited but left processes running (the evidence names the first), still running 3 seconds later, or printed a stack trace after the SIGTERM |
305
307
  | `SKIP` | Finished before the SIGTERM, as `--version` and `--help` do: probe a command that keeps running |
306
308
 
@@ -431,7 +433,7 @@ Then ask in your own words, for example "check my CLI for pipe and Ctrl-C bugs b
431
433
 
432
434
  ## Safety
433
435
 
434
- cliprobe runs the target in your current directory without a shell, with stdin closed (`/dev/null`; the stdin, ctrl-c and sigterm checks use a pipe that they never write to), a temporary `HOME`, and a minimal environment (no tokens from your shell). It still executes the program, so only probe programs you trust. By default cliprobe passes only the arguments you give, after the command or with `--probe`, or `--version` and `--help`, or none with `--bare`; only the baseline check, when you name it, adds an unknown flag. The only input it ever sends is Ctrl-C, from the ctrl-c and restore checks, and SIGTERM, from the sigterm check, to probes you write. It kills each run's whole process group on timeout, including under a pseudo-terminal, and kills whatever a program leaves running in its group when it exits under the sigterm check. It runs on macOS and Linux, including Alpine; the terminal checks need the `script` command, which Alpine ships in `util-linux-misc`. Windows isn't supported yet.
436
+ cliprobe runs the target in your current directory without a shell, with stdin closed (`/dev/null`; the stdin, ctrl-c and sigterm checks use a pipe that they never write to), a temporary `HOME`, and a minimal environment (no tokens from your shell). It still executes the program, so only probe programs you trust. By default cliprobe passes only the arguments you give, after the command or with `--probe`, or `--version` and `--help`, or none with `--bare`; only the baseline check, when you name it, adds an unknown flag. The only input it ever sends is Ctrl-C, from the ctrl-c and restore checks, and SIGTERM, from the sigterm check, to probes you write. It kills each run's whole process group on timeout, including under a pseudo-terminal, and when a program exits it kills whatever it left running, in its group or started in another one, in every check. If cliprobe itself is stopped by Ctrl-C, SIGTERM or SIGHUP, it first kills the probe it is running and removes its temporary directories, then exits by the same signal (130, 143 or 129). It runs on macOS and Linux, including Alpine; the terminal checks need the `script` command, which Alpine ships in `util-linux-misc`. Windows isn't supported yet.
435
437
 
436
438
  ## FAQ
437
439
 
package/dist/cli.js CHANGED
@@ -1,67 +1,205 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
3
+ import { execFile, execFileSync, spawn } from "node:child_process";
4
+ import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
5
  import { delimiter, dirname, join } from "node:path";
6
6
  import { tmpdir } from "node:os";
7
- // src/core/group.ts
7
+ // src/core/interrupt.ts
8
+ const cleanups = /* @__PURE__ */ new Set();
9
+ /** Registers `cleanup` until the returned function is called. */
10
+ function onInterrupt(cleanup) {
11
+ cleanups.add(cleanup);
12
+ return () => {
13
+ cleanups.delete(cleanup);
14
+ };
15
+ }
16
+ /** Runs every registered cleanup, newest first, so processes die before their directories go. */
17
+ function runInterruptCleanups() {
18
+ const pending = [...cleanups].reverse();
19
+ cleanups.clear();
20
+ for (const cleanup of pending) try {
21
+ cleanup();
22
+ } catch {}
23
+ }
24
+ /** The signals that stop cliprobe and how a shell reports each: 128 plus its number. */
25
+ const INTERRUPT_SIGNALS = /* @__PURE__ */ new Map([
26
+ ["SIGHUP", 129],
27
+ ["SIGINT", 130],
28
+ ["SIGTERM", 143]
29
+ ]);
8
30
  /**
9
- * The processes of group `pgid` that are still running. Zombies are left out:
10
- * where nothing reaps orphans, as in a container without an init process, they
11
- * stay in the group for good although they have exited.
31
+ * On SIGINT, SIGTERM or SIGHUP: cleans up, then dies by the same signal, so the
32
+ * shell or CI runner sees 130, 143 or 129 as for any other program.
12
33
  */
13
- function groupMembers(pgid) {
14
- return process.platform === "linux" ? membersFromProc(pgid) : membersFromPs(pgid);
34
+ function handleInterrupts(target = process) {
35
+ const signals = [...INTERRUPT_SIGNALS.keys()];
36
+ for (const [signal, code] of INTERRUPT_SIGNALS) target.once(signal, () => {
37
+ runInterruptCleanups();
38
+ for (const s of signals) target.removeAllListeners(s);
39
+ try {
40
+ target.kill(target.pid, signal);
41
+ } catch {
42
+ target.exit(code);
43
+ }
44
+ });
45
+ }
46
+ // src/core/group.ts
47
+ const isGone = (state) => state.startsWith("Z") || state.startsWith("X");
48
+ /** Fields of a /proc/<pid>/stat line; the name may hold spaces and parentheses. */
49
+ function parseProcStat(line) {
50
+ const open = line.indexOf("(");
51
+ const close = line.lastIndexOf(")");
52
+ const fields = line.slice(close + 1).trim().split(" ");
53
+ return {
54
+ name: line.slice(open + 1, close),
55
+ state: fields[0] ?? "",
56
+ ppid: Number(fields[1] ?? ""),
57
+ pgid: Number(fields[2] ?? ""),
58
+ start: fields[19] ?? ""
59
+ };
15
60
  }
16
- /** Linux: reads `<root>/<pid>/stat` and `cmdline` for every process. */
17
- function membersFromProc(pgid, root = "/proc") {
18
- const members = [];
61
+ /** Every running process, without zombies, read from `<root>`. */
62
+ function tableFromProc(root = "/proc", keep = () => true) {
63
+ const table = [];
19
64
  for (const entry of readdirSync(root)) {
20
65
  if (!/^\d+$/.test(entry)) continue;
21
66
  try {
22
67
  const stat = parseProcStat(readFileSync(`${root}/${entry}/stat`, "utf8"));
23
- if (stat.pgid !== pgid || isGone(stat.state)) continue;
68
+ if (isGone(stat.state) || !keep(stat)) continue;
24
69
  const cmdline = readFileSync(`${root}/${entry}/cmdline`, "utf8").split("\0").filter(Boolean).join(" ");
25
- members.push({
70
+ table.push({
26
71
  pid: Number(entry),
72
+ ppid: stat.ppid,
73
+ pgid: stat.pgid,
74
+ start: stat.start,
27
75
  command: cmdline || stat.name
28
76
  });
29
77
  } catch {}
30
78
  }
31
- return members.sort((a, b) => a.pid - b.pid);
32
- }
33
- /** macOS and other systems without /proc: asks ps. */
34
- function membersFromPs(pgid) {
35
- return parsePs(execFileSync("ps", [
36
- "-A",
37
- "-o",
38
- "pid=,pgid=,stat=,args="
39
- ], { encoding: "utf8" }), pgid);
79
+ return table.sort((a, b) => a.pid - b.pid);
40
80
  }
41
- const isGone = (state) => state.startsWith("Z") || state.startsWith("X");
42
- /** Name, state and group from a /proc/<pid>/stat line; the name may hold spaces and parentheses. */
43
- function parseProcStat(line) {
44
- const open = line.indexOf("(");
45
- const close = line.lastIndexOf(")");
46
- const [state = "", , pgid = ""] = line.slice(close + 1).trim().split(" ");
47
- return {
48
- name: line.slice(open + 1, close),
49
- state,
50
- pgid: Number(pgid)
51
- };
52
- }
53
- /** Running members of group `pgid` from `ps -A -o pid=,pgid=,stat=,args=` output. */
54
- function parsePs(out, pgid) {
55
- const members = [];
81
+ /** lstart is the only start time macOS ps gives; LC_ALL=C keeps its format fixed. */
82
+ const PS_ARGS = [
83
+ "-A",
84
+ "-o",
85
+ "pid=,ppid=,pgid=,lstart=,stat=,args="
86
+ ];
87
+ const PS_ENV = {
88
+ ...process.env,
89
+ LC_ALL: "C"
90
+ };
91
+ const PS_LINE = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+(\S+)\s+(.*)$/;
92
+ /** Running processes from `ps -A -o pid=,ppid=,pgid=,lstart=,stat=,args=` output. */
93
+ function parsePsTable(out) {
94
+ const table = [];
56
95
  for (const line of out.split("\n")) {
57
- const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
58
- if (!m || Number(m[2]) !== pgid || isGone(m[3] ?? "")) continue;
59
- members.push({
96
+ const m = PS_LINE.exec(line);
97
+ if (!m || isGone(m[5] ?? "")) continue;
98
+ table.push({
60
99
  pid: Number(m[1]),
61
- command: (m[4] ?? "").trim()
100
+ ppid: Number(m[2]),
101
+ pgid: Number(m[3]),
102
+ start: m[4] ?? "",
103
+ command: (m[6] ?? "").trim()
62
104
  });
63
105
  }
64
- return members.sort((a, b) => a.pid - b.pid);
106
+ return table.sort((a, b) => a.pid - b.pid);
107
+ }
108
+ /**
109
+ * A snapshot of every running process, read at once: from /proc on Linux, from
110
+ * ps elsewhere. `platform` and `ps` are parameters so tests can take the ps path
111
+ * on Linux and see it fail.
112
+ */
113
+ function processTable(platform = process.platform, ps = "ps") {
114
+ if (platform === "linux") return tableFromProc();
115
+ try {
116
+ return parsePsTable(execFileSync(ps, PS_ARGS, {
117
+ encoding: "utf8",
118
+ env: PS_ENV
119
+ }));
120
+ } catch {
121
+ return [];
122
+ }
123
+ }
124
+ /** processTable() without blocking: on macOS, ps takes a few milliseconds. */
125
+ function processTableAsync(platform = process.platform, ps = "ps") {
126
+ if (platform === "linux") return Promise.resolve(tableFromProc());
127
+ return new Promise((resolve) => {
128
+ execFile(ps, PS_ARGS, {
129
+ encoding: "utf8",
130
+ env: PS_ENV
131
+ }, (error, out) => {
132
+ resolve(error ? [] : parsePsTable(out));
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * What one run started, followed by parent PID as well as by process group: a
138
+ * child in its own group or session (Node's `detached`, setsid, daemons) leaves
139
+ * the program's group, and once the program exits it is reparented, so only a
140
+ * snapshot taken while the program runs links it to the program.
141
+ */
142
+ var ProcessTree = class {
143
+ #root;
144
+ #groups;
145
+ /** Descendants seen so far, by PID, with their start time. */
146
+ #seen = /* @__PURE__ */ new Map();
147
+ /**
148
+ * @param root the program's PID
149
+ * @param groups the process groups whose members belong to the run, read
150
+ * each time: the program's own, and the one under a pseudo-terminal
151
+ */
152
+ constructor(root, groups) {
153
+ this.#root = root;
154
+ this.#groups = groups;
155
+ }
156
+ /** Once the program has exited and been reaped, its PID may belong to another process. */
157
+ programExited() {
158
+ this.#root = void 0;
159
+ }
160
+ /** Records the program's descendants from a snapshot taken while it runs. */
161
+ record(table) {
162
+ for (const p of this.running(table)) this.#seen.set(p.pid, p.start);
163
+ }
164
+ /**
165
+ * The run's processes in `table`: the program, the members of its groups,
166
+ * the descendants recorded earlier (the same PID and start time), and
167
+ * everything below any of them. cliprobe itself is never one of them.
168
+ */
169
+ running(table) {
170
+ const groups = new Set(this.#groups());
171
+ const found = /* @__PURE__ */ new Map();
172
+ const candidates = table.filter((p) => p.pid !== 1 && p.pid !== process.pid);
173
+ for (const p of candidates) if (p.pid === this.#root || groups.has(p.pgid) || this.#seen.has(p.pid) && this.#seen.get(p.pid) === p.start) found.set(p.pid, p);
174
+ let grew = true;
175
+ while (grew) {
176
+ grew = false;
177
+ for (const p of candidates) if (!found.has(p.pid) && found.has(p.ppid)) {
178
+ found.set(p.pid, p);
179
+ grew = true;
180
+ }
181
+ }
182
+ return [...found.values()].sort((a, b) => a.pid - b.pid);
183
+ }
184
+ };
185
+ /**
186
+ * SIGKILLs the given processes, the run's groups, and every group that one of
187
+ * the processes leads, so what they started after the snapshot goes too.
188
+ */
189
+ function killAll(processes, groups) {
190
+ const targets = new Set(groups.map((g) => -g));
191
+ for (const p of processes) {
192
+ targets.add(p.pid);
193
+ if (p.pgid === p.pid) targets.add(-p.pid);
194
+ }
195
+ targets.delete(-process.pid);
196
+ targets.delete(process.pid);
197
+ targets.delete(-1);
198
+ targets.delete(1);
199
+ targets.delete(0);
200
+ for (const target of targets) try {
201
+ process.kill(target, "SIGKILL");
202
+ } catch {}
65
203
  }
66
204
  // src/core/sandbox.ts
67
205
  /** A minimal environment: no tokens or config from the caller's shell. */
@@ -80,15 +218,128 @@ function sandbox() {
80
218
  }
81
219
  };
82
220
  }
221
+ // src/core/which.ts
222
+ function isExecutableFile(path) {
223
+ try {
224
+ accessSync(path, constants.X_OK);
225
+ return statSync(path).isFile();
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+ /**
231
+ * Where `command` would be found, as spawn() looks for it: a path with a slash
232
+ * as given, otherwise each PATH entry in turn (an empty entry is the current
233
+ * directory). Under a PTY, a missing command is only a line of shell output, so
234
+ * the terminal checks ask first.
235
+ */
236
+ function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
237
+ if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
238
+ for (const dir of path.split(delimiter)) {
239
+ const candidate = join(dir || ".", command);
240
+ if (isExecutableFile(candidate)) return candidate;
241
+ }
242
+ }
243
+ /** The first bytes of a file, or nothing when it can't be read (execute-only, say). */
244
+ function head(path, bytes = 512) {
245
+ let fd;
246
+ try {
247
+ fd = openSync(path, "r");
248
+ const buffer = Buffer.alloc(bytes);
249
+ return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0));
250
+ } catch {
251
+ return Buffer.alloc(0);
252
+ } finally {
253
+ if (fd !== void 0) closeSync(fd);
254
+ }
255
+ }
256
+ /** Why the interpreter named on a `#!` line can't run, if it can't. */
257
+ function interpreterProblem(command, file, path) {
258
+ const start = head(file, 256);
259
+ if (start.subarray(0, 2).toString("latin1") !== "#!") return void 0;
260
+ const [interpreter = "", first] = (start.toString("utf8").slice(2).split("\n")[0] ?? "").trim().split(/[ \t]+/);
261
+ if (interpreter === "") return void 0;
262
+ try {
263
+ statSync(interpreter);
264
+ } catch {
265
+ return `${command}: interpreter ${interpreter} not found`;
266
+ }
267
+ if (!isExecutableFile(interpreter)) return `${command}: interpreter ${interpreter} is not executable`;
268
+ if (/(^|\/)env$/.test(interpreter) && first !== void 0 && !first.startsWith("-")) {
269
+ if (!first.includes("=") && findCommand(first, path) === void 0) return `${command}: interpreter ${first} not found (${interpreter} ${first})`;
270
+ }
271
+ }
272
+ /**
273
+ * Why `command` can't run, or undefined if it looks runnable: not found, a
274
+ * directory, not executable, or a `#!` interpreter that is missing. Asked before
275
+ * any check, so the user sees the cause once instead of an error per probe.
276
+ */
277
+ function commandProblem(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
278
+ if (command.includes("/")) {
279
+ let isFile;
280
+ try {
281
+ const stat = statSync(command);
282
+ if (stat.isDirectory()) return `${command} is a directory`;
283
+ isFile = stat.isFile();
284
+ } catch {
285
+ return `command not found: ${command}`;
286
+ }
287
+ if (!isFile) return `${command} is not a regular file`;
288
+ if (!isExecutableFile(command)) return `${command} is not executable (chmod +x?)`;
289
+ return interpreterProblem(command, command, path);
290
+ }
291
+ const file = findCommand(command, path);
292
+ if (file === void 0) return `command not found: ${command}`;
293
+ return interpreterProblem(command, file, path);
294
+ }
295
+ /** The reason given for a file this system can't run as a program. */
296
+ const notAProgram = (command, how) => `${command} is not a program this system can run (${how})`;
297
+ /**
298
+ * Whether `command` resolves to a file that no shell or kernel would run as a
299
+ * program of this system: no `#!` line, and a NUL byte near its start, which no
300
+ * script has. Alone this could be a binary run through binfmt_misc, so callers
301
+ * also need the run to have exited 126 or 127.
302
+ */
303
+ function cannotExecute(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
304
+ const file = findCommand(command, path);
305
+ if (file === void 0) return false;
306
+ const start = head(file);
307
+ return start.subarray(0, 2).toString("latin1") !== "#!" && start.includes(0);
308
+ }
309
+ /**
310
+ * Whether a run ended because the system could not run the file at all. On
311
+ * Linux, spawn() hands a file the kernel can't execute (ENOEXEC) to /bin/sh,
312
+ * as execvp() does, so a binary that isn't one for this system "runs" and exits
313
+ * 126 or 127 with the shell's complaint, prefixed by the file's path. Only a
314
+ * file with no `#!` line and a NUL byte near its start counts, as no script has
315
+ * one: a binary run through binfmt_misc, or a script without `#!`, is left alone.
316
+ * Returns the reason, or undefined.
317
+ */
318
+ function shellFallbackError(command, exitCode, stderr, path = process.env["PATH"] ?? "/usr/bin:/bin") {
319
+ if (exitCode !== 126 && exitCode !== 127) return void 0;
320
+ const file = findCommand(command, path);
321
+ if (file === void 0 || !cannotExecute(command, path)) return void 0;
322
+ if (!stderr.startsWith(`${command}: `) && !stderr.startsWith(`${file}: `)) return void 0;
323
+ return notAProgram(command, `/bin/sh tried it as a script and exited ${exitCode}`);
324
+ }
83
325
  // src/core/run.ts
84
326
  const STDERR_CAP = 65536;
85
327
  const STDOUT_CAP = 1048576;
328
+ /** How often the process table is read while the program runs, to learn its descendants. */
329
+ const TREE_POLL_MS = 200;
330
+ /** How long to wait for the output pipes to close once everything the run started is gone. */
331
+ const CLOSE_WAIT_MS = 1e3;
332
+ /** How often to look for leftovers while waiting for them to finish. */
333
+ const LEFTOVER_POLL_MS = 50;
334
+ const delay = (ms) => new Promise((resolve) => {
335
+ setTimeout(resolve, ms);
336
+ });
86
337
  /**
87
338
  * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
88
339
  * whose read end is closed before the program starts, so its first write to
89
340
  * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
90
341
  */
91
- function run$1(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal, stdin = "null", leftoversMs }) {
342
+ function run$1(command, args, { closedStdout = false, timeout, env: overrides = {}, extraGroup, signal, stdin = "null", leftoversMs = 250 }) {
92
343
  const { dir, env: base } = sandbox();
93
344
  const env = { ...base };
94
345
  for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
@@ -111,12 +362,30 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
111
362
  let signalSentMs;
112
363
  let stderrAtSignal;
113
364
  let leftRunning;
114
- let afterExit = Promise.resolve();
115
365
  let exitMs;
366
+ let tree;
367
+ let pollTimer;
116
368
  const start = performance.now();
369
+ const groups = () => {
370
+ const extra = extraGroup?.();
371
+ return [...child?.pid === void 0 ? [] : [child.pid], ...extra === void 0 ? [] : [extra]];
372
+ };
373
+ /** Kills everything the run started, from a fresh look at the process table. */
374
+ const killRun = () => {
375
+ if (tree) killAll(tree.running(processTable()), groups());
376
+ };
377
+ const unregister = onInterrupt(() => {
378
+ killRun();
379
+ rmSync(dir, {
380
+ recursive: true,
381
+ force: true
382
+ });
383
+ });
117
384
  const finish = (outcome) => {
118
385
  if (finished) return;
119
386
  finished = true;
387
+ clearInterval(pollTimer);
388
+ unregister();
120
389
  if (typeof stdoutFd === "number") closeSync(stdoutFd);
121
390
  rmSync(dir, {
122
391
  recursive: true,
@@ -152,83 +421,123 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
152
421
  finish({
153
422
  exitCode: null,
154
423
  signal: null,
155
- spawnError: error instanceof Error ? error.message : String(error)
424
+ spawnError: spawnMessage(command, error)
156
425
  });
157
426
  return;
158
427
  }
428
+ const proc = child;
429
+ if (proc.pid !== void 0) {
430
+ tree = new ProcessTree(proc.pid, groups);
431
+ let polling = false;
432
+ pollTimer = setInterval(() => {
433
+ if (polling || exited) return;
434
+ polling = true;
435
+ (async () => {
436
+ const table = await processTableAsync();
437
+ polling = false;
438
+ if (!exited) tree?.record(table);
439
+ })();
440
+ }, TREE_POLL_MS);
441
+ }
442
+ const recordTree = () => {
443
+ tree?.record(processTable());
444
+ };
159
445
  const timer = setTimeout(() => {
160
446
  timedOut = true;
161
- beforeKill?.();
162
- try {
163
- if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
164
- } catch {}
447
+ recordTree();
448
+ killRun();
165
449
  }, timeout);
166
450
  const signalTimer = signal && setTimeout(() => {
167
- if (exited || child.pid === void 0) return;
451
+ if (exited || proc.pid === void 0) return;
452
+ recordTree();
168
453
  signalSentMs = Math.round(performance.now() - start);
169
454
  stderrAtSignal = stderr.length;
170
455
  try {
171
- process.kill(signal.to === "process" ? child.pid : -child.pid, signal.name);
456
+ process.kill(signal.to === "process" ? proc.pid : -proc.pid, signal.name);
172
457
  } catch {}
173
458
  }, signal.afterMs);
174
- const closeTimer = typeof stdin === "object" ? setTimeout(() => child.stdin?.destroy(), stdin.closeAfterMs) : void 0;
175
- child.on("exit", () => {
459
+ const closeTimer = typeof stdin === "object" ? setTimeout(() => proc.stdin?.destroy(), stdin.closeAfterMs) : void 0;
460
+ let closed = false;
461
+ let onClosed;
462
+ const outputClosed = new Promise((resolveClosed) => {
463
+ onClosed = resolveClosed;
464
+ });
465
+ proc.on("exit", (exitCode, exitSignal) => {
176
466
  exited = true;
467
+ exitMs = Math.round(performance.now() - start);
468
+ clearTimeout(timer);
177
469
  clearTimeout(signalTimer);
178
470
  clearTimeout(closeTimer);
179
- child.stdin?.destroy();
180
- if (leftoversMs !== void 0 && !timedOut && child.pid !== void 0) {
181
- clearTimeout(timer);
182
- exitMs = Math.round(performance.now() - start);
183
- const pgid = child.pid;
184
- afterExit = (async () => {
185
- leftRunning = await watchLeftovers(pgid, leftoversMs);
186
- })();
187
- }
471
+ clearInterval(pollTimer);
472
+ tree?.programExited();
473
+ proc.stdin?.destroy();
474
+ (async () => {
475
+ if (tree) {
476
+ const left = await watchLeftovers(tree, timedOut ? 0 : leftoversMs);
477
+ killAll(left, groups());
478
+ leftRunning = left.map((p) => ({
479
+ pid: p.pid,
480
+ command: p.command
481
+ }));
482
+ }
483
+ if (!closed) {
484
+ let giveUp;
485
+ const gaveUp = new Promise((resolveWait) => {
486
+ giveUp = setTimeout(resolveWait, CLOSE_WAIT_MS);
487
+ });
488
+ await Promise.race([outputClosed, gaveUp]);
489
+ clearTimeout(giveUp);
490
+ }
491
+ proc.stdout?.destroy();
492
+ proc.stderr?.destroy();
493
+ const notRun = timedOut ? void 0 : shellFallbackError(command, exitCode, stderr);
494
+ finish({
495
+ exitCode,
496
+ signal: exitSignal,
497
+ ...notRun === void 0 ? {} : { spawnError: notRun }
498
+ });
499
+ })();
188
500
  });
189
- child.stdout?.on("data", (chunk) => {
501
+ proc.stdout?.on("data", (chunk) => {
190
502
  if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
191
503
  stdoutBytes += chunk.length;
192
504
  });
193
- child.stderr?.on("data", (chunk) => {
505
+ proc.stderr?.on("data", (chunk) => {
194
506
  if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8");
195
507
  });
196
- child.on("error", (error) => {
508
+ proc.on("error", (error) => {
197
509
  clearTimeout(timer);
198
510
  clearTimeout(signalTimer);
199
511
  finish({
200
512
  exitCode: null,
201
513
  signal: null,
202
- spawnError: error.message
514
+ spawnError: spawnMessage(command, error)
203
515
  });
204
516
  });
205
- child.on("close", (exitCode, exitSignal) => {
206
- clearTimeout(timer);
207
- clearTimeout(signalTimer);
208
- afterExit.then(() => finish({
209
- exitCode,
210
- signal: exitSignal
211
- }));
517
+ proc.on("close", () => {
518
+ closed = true;
519
+ onClosed?.();
212
520
  });
213
521
  });
214
522
  }
215
- /** How often to look at the group while waiting for it to empty. */
216
- const GROUP_POLL_MS = 50;
523
+ /** Why spawn() failed; "spawn ENOEXEC" names neither the file nor the problem. */
524
+ function spawnMessage(command, error) {
525
+ if (!(error instanceof Error)) return String(error);
526
+ return "code" in error && error.code === "ENOEXEC" ? notAProgram(command, "exec format error") : error.message;
527
+ }
217
528
  /**
218
- * Waits up to `ms` for group `pgid` to empty, as children stopped by their
219
- * parent take a moment to exit, then kills whatever is left and returns it.
529
+ * Waits up to `ms` for what the program left running to finish on its own, as
530
+ * children stopped by their parent take a moment to exit, and returns what is
531
+ * still running then.
220
532
  */
221
- async function watchLeftovers(pgid, ms) {
533
+ async function watchLeftovers(tree, ms) {
222
534
  const deadline = performance.now() + ms;
223
- let members = groupMembers(pgid);
224
- while (members.length > 0 && performance.now() < deadline) {
225
- await new Promise((resolve) => setTimeout(resolve, GROUP_POLL_MS));
226
- members = groupMembers(pgid);
535
+ let left = tree.running(processTable());
536
+ while (left.length > 0 && performance.now() < deadline) {
537
+ await delay(LEFTOVER_POLL_MS);
538
+ left = tree.running(processTable());
227
539
  }
228
- if (members.length > 0) try {
229
- process.kill(-pgid, "SIGKILL");
230
- } catch {}
231
- return members;
540
+ return left;
232
541
  }
233
542
  // src/checks/baseline.ts
234
543
  /** A flag no real program defines. */
@@ -777,6 +1086,10 @@ async function runPty(command, args, { timeout, env = {}, input }) {
777
1086
  const support = ptySupport();
778
1087
  if (!support.ok) throw new Error(`no PTY: ${support.reason}`);
779
1088
  const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
1089
+ const unregister = onInterrupt(() => rmSync(dir, {
1090
+ recursive: true,
1091
+ force: true
1092
+ }));
780
1093
  const pidFile = join(dir, "pid");
781
1094
  let launcher = "script";
782
1095
  let argv = ptyArgs(support.flavor, pidFile, command, args);
@@ -820,7 +1133,7 @@ async function runPty(command, args, { timeout, env = {}, input }) {
820
1133
  SHELL: "/bin/sh",
821
1134
  ...env
822
1135
  },
823
- beforeKill: () => killGroupFromPidFile(pidFile)
1136
+ extraGroup: () => programGroup(pidFile)
824
1137
  });
825
1138
  return {
826
1139
  output: cleanPtyOutput(result.stdout, support.flavor),
@@ -835,6 +1148,7 @@ async function runPty(command, args, { timeout, env = {}, input }) {
835
1148
  clearTimeout(typeTimer);
836
1149
  clearInterval(watchTimer);
837
1150
  closeKeyboard();
1151
+ unregister();
838
1152
  rmSync(dir, {
839
1153
  recursive: true,
840
1154
  force: true
@@ -867,12 +1181,6 @@ function programState(pidFile) {
867
1181
  return "gone";
868
1182
  }
869
1183
  }
870
- function killGroupFromPidFile(pidFile) {
871
- const pid = programGroup(pidFile);
872
- try {
873
- if (pid !== void 0) process.kill(-pid, "SIGKILL");
874
- } catch {}
875
- }
876
1184
  // src/checks/color.ts
877
1185
  /**
878
1186
  * Every color run gets a terminal type that supports color, so a program cannot
@@ -1238,13 +1546,115 @@ const controlCharsCheck = {
1238
1546
  return results;
1239
1547
  }
1240
1548
  };
1549
+ // src/checks/sigterm.ts
1550
+ /** How long the program runs before SIGTERM. */
1551
+ const SIGTERM_DELAY_MS = 1e3;
1552
+ /** How long it gets to exit after SIGTERM. */
1553
+ const SIGTERM_GRACE_MS = 3e3;
1554
+ /** How long its children get to follow it once it has exited. */
1555
+ const SIGTERM_LEFTOVERS_MS = 1e3;
1556
+ /** Lines worth quoting from a trace printed on SIGTERM, best first. */
1557
+ const TRACE_MESSAGES$1 = [/^(\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1558
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "es"}`;
1559
+ /** "1 process" or "3 processes", and the evidence naming the first one, for a check that reports leftovers. */
1560
+ function describeLeftovers(left) {
1561
+ const [first] = left;
1562
+ const more = left.length > 1 ? ` (and ${left.length - 1} more)` : "";
1563
+ return {
1564
+ count: plural(left.length, "process"),
1565
+ evidence: `still running: ${first?.command ?? ""}${more}`
1566
+ };
1567
+ }
1568
+ function judgeSigterm(r) {
1569
+ if (r.spawnError) return {
1570
+ verdict: "error",
1571
+ reason: `could not start: ${r.spawnError}`
1572
+ };
1573
+ if (r.signalSentMs === void 0) return {
1574
+ verdict: "skip",
1575
+ reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1576
+ };
1577
+ if (r.timedOut) return {
1578
+ verdict: "warn",
1579
+ reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
1580
+ };
1581
+ const left = r.leftRunning ?? [];
1582
+ if (left.length > 0) {
1583
+ const { count, evidence } = describeLeftovers(left);
1584
+ return {
1585
+ verdict: "warn",
1586
+ reason: `exited on SIGTERM but left ${count} running, which keep ports and files busy`,
1587
+ evidence
1588
+ };
1589
+ }
1590
+ const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1591
+ if (TRACE_RE.test(after)) return {
1592
+ verdict: "warn",
1593
+ reason: "printed a stack trace on SIGTERM",
1594
+ evidence: crashEvidence(after, TRACE_MESSAGES$1)
1595
+ };
1596
+ const ms = `${r.durationMs - r.signalSentMs} ms`;
1597
+ return {
1598
+ verdict: "pass",
1599
+ reason: `${r.signal ? `stopped by ${r.signal}` : `exited with code ${r.exitCode}`} in ${ms} and left nothing running`
1600
+ };
1601
+ }
1602
+ async function sigterm(command, args) {
1603
+ const r = await run$1(command, args, {
1604
+ timeout: 4e3,
1605
+ signal: {
1606
+ name: "SIGTERM",
1607
+ afterMs: SIGTERM_DELAY_MS,
1608
+ to: "process"
1609
+ },
1610
+ stdin: "open",
1611
+ leftoversMs: SIGTERM_LEFTOVERS_MS
1612
+ });
1613
+ const sent = r.signalSentMs;
1614
+ return {
1615
+ check: "sigterm",
1616
+ invocation: [command, ...args],
1617
+ ...judgeSigterm(r),
1618
+ sentAfterMs: sent ?? null,
1619
+ exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1620
+ exitCode: r.exitCode,
1621
+ signal: r.signal,
1622
+ leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1623
+ stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1624
+ };
1625
+ }
1626
+ const sigtermCheck = {
1627
+ name: "sigterm",
1628
+ kind: "check",
1629
+ summary: "ignores SIGTERM, or exits on it and leaves its child processes running",
1630
+ async run(target) {
1631
+ const own = target.probes.filter((p) => p.own);
1632
+ if (own.length === 0) return [{
1633
+ check: "sigterm",
1634
+ invocation: [target.command],
1635
+ verdict: "skip",
1636
+ reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1637
+ sentAfterMs: null,
1638
+ exitedAfterMs: null,
1639
+ exitCode: null,
1640
+ signal: null,
1641
+ leftRunning: [],
1642
+ stderrAfter: ""
1643
+ }];
1644
+ const results = [];
1645
+ for (const { args } of own) results.push(await sigterm(target.command, args));
1646
+ return results;
1647
+ }
1648
+ };
1241
1649
  // src/checks/ctrl-c.ts
1242
1650
  /** How long the program runs before Ctrl-C. */
1243
1651
  const CTRL_C_DELAY_MS = 1e3;
1244
1652
  /** How long it gets to exit after Ctrl-C. */
1245
1653
  const CTRL_C_GRACE_MS = 3e3;
1654
+ /** How long the rest of its group gets to follow it once it has exited. */
1655
+ const CTRL_C_LEFTOVERS_MS = 1e3;
1246
1656
  /** Lines worth quoting from a trace printed on Ctrl-C, best first. */
1247
- const TRACE_MESSAGES$1 = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1657
+ const TRACE_MESSAGES = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1248
1658
  function judgeCtrlC(r) {
1249
1659
  if (r.spawnError) return {
1250
1660
  verdict: "error",
@@ -1263,8 +1673,17 @@ function judgeCtrlC(r) {
1263
1673
  if (TRACE_RE.test(after)) return {
1264
1674
  verdict: "fail",
1265
1675
  reason: "printed a stack trace on Ctrl-C",
1266
- evidence: crashEvidence(after, TRACE_MESSAGES$1)
1676
+ evidence: crashEvidence(after, TRACE_MESSAGES)
1267
1677
  };
1678
+ const left = r.leftRunning ?? [];
1679
+ if (left.length > 0) {
1680
+ const { count, evidence } = describeLeftovers(left);
1681
+ return {
1682
+ verdict: "warn",
1683
+ reason: `exited on Ctrl-C in ${ms} but left ${count} running that ignored it`,
1684
+ evidence
1685
+ };
1686
+ }
1268
1687
  if (r.signal) return {
1269
1688
  verdict: "pass",
1270
1689
  reason: `stopped by ${r.signal} in ${ms}`
@@ -1289,7 +1708,8 @@ async function ctrlC(command, args) {
1289
1708
  name: "SIGINT",
1290
1709
  afterMs: CTRL_C_DELAY_MS
1291
1710
  },
1292
- stdin: "open"
1711
+ stdin: "open",
1712
+ leftoversMs: CTRL_C_LEFTOVERS_MS
1293
1713
  });
1294
1714
  const sent = r.signalSentMs;
1295
1715
  return {
@@ -1300,6 +1720,7 @@ async function ctrlC(command, args) {
1300
1720
  exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1301
1721
  exitCode: r.exitCode,
1302
1722
  signal: r.signal,
1723
+ leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1303
1724
  stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1304
1725
  };
1305
1726
  }
@@ -1318,6 +1739,7 @@ const ctrlCCheck = {
1318
1739
  exitedAfterMs: null,
1319
1740
  exitCode: null,
1320
1741
  signal: null,
1742
+ leftRunning: [],
1321
1743
  stderrAfter: ""
1322
1744
  }];
1323
1745
  const results = [];
@@ -1409,33 +1831,13 @@ const pipeEscapesCheck = {
1409
1831
  return results;
1410
1832
  }
1411
1833
  };
1412
- // src/core/which.ts
1413
- function isExecutableFile(path) {
1414
- try {
1415
- accessSync(path, constants.X_OK);
1416
- return statSync(path).isFile();
1417
- } catch {
1418
- return false;
1419
- }
1420
- }
1421
- /**
1422
- * Where `command` would be found, as spawn() looks for it: a path with a slash
1423
- * as given, otherwise each PATH entry in turn (an empty entry is the current
1424
- * directory). Under a PTY, a missing command is only a line of shell output, so
1425
- * the terminal checks ask first.
1426
- */
1427
- function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
1428
- if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
1429
- for (const dir of path.split(delimiter)) {
1430
- const candidate = join(dir || ".", command);
1431
- if (isExecutableFile(candidate)) return candidate;
1432
- }
1433
- }
1434
1834
  // src/checks/restore.ts
1435
1835
  function listLabels(modes) {
1436
1836
  const labels = modes.map((m) => m.label);
1437
1837
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1438
1838
  }
1839
+ /** The PTY wrapper's own complaint when it can't exec the program. */
1840
+ const WRAPPER_EXEC_FAILED = /^sh: [^\n]*(cannot execute|exec format error)/i;
1439
1841
  /** What the Ctrl-C key sends to a terminal. */
1440
1842
  const CTRL_C_KEY = "";
1441
1843
  const showSequence = (sequence) => sequence.replaceAll("\x1B", "ESC");
@@ -1473,7 +1875,10 @@ async function restore(command, args, { timeout, interrupt }) {
1473
1875
  afterMs: CTRL_C_DELAY_MS
1474
1876
  } } : {}
1475
1877
  });
1476
- const judgement = judgeRestore(r);
1878
+ const judgement = judgeRestore(r.spawnError === void 0 && (r.exitCode === 126 || r.exitCode === 127 || WRAPPER_EXEC_FAILED.test(r.output)) && cannotExecute(command) ? {
1879
+ ...r,
1880
+ spawnError: notAProgram(command, "the terminal's shell could not exec it")
1881
+ } : r);
1477
1882
  return {
1478
1883
  check: "restore",
1479
1884
  invocation: [command, ...args],
@@ -1516,95 +1921,6 @@ const restoreCheck = {
1516
1921
  return results;
1517
1922
  }
1518
1923
  };
1519
- // src/checks/sigterm.ts
1520
- /** How long the program runs before SIGTERM. */
1521
- const SIGTERM_DELAY_MS = 1e3;
1522
- /** How long it gets to exit after SIGTERM. */
1523
- const SIGTERM_GRACE_MS = 3e3;
1524
- /** How long its children get to follow it once it has exited. */
1525
- const SIGTERM_LEFTOVERS_MS = 1e3;
1526
- /** Lines worth quoting from a trace printed on SIGTERM, best first. */
1527
- const TRACE_MESSAGES = [/^(\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1528
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "es"}`;
1529
- function judgeSigterm(r) {
1530
- if (r.spawnError) return {
1531
- verdict: "error",
1532
- reason: `could not start: ${r.spawnError}`
1533
- };
1534
- if (r.signalSentMs === void 0) return {
1535
- verdict: "skip",
1536
- reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1537
- };
1538
- if (r.timedOut) return {
1539
- verdict: "warn",
1540
- reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
1541
- };
1542
- const left = r.leftRunning ?? [];
1543
- const [firstLeft] = left;
1544
- if (firstLeft) return {
1545
- verdict: "warn",
1546
- reason: `exited on SIGTERM but left ${plural(left.length, "process")} running, which keep ports and files busy`,
1547
- evidence: `still running: ${firstLeft.command}${left.length > 1 ? ` (and ${left.length - 1} more)` : ""}`
1548
- };
1549
- const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1550
- if (TRACE_RE.test(after)) return {
1551
- verdict: "warn",
1552
- reason: "printed a stack trace on SIGTERM",
1553
- evidence: crashEvidence(after, TRACE_MESSAGES)
1554
- };
1555
- const ms = `${r.durationMs - r.signalSentMs} ms`;
1556
- return {
1557
- verdict: "pass",
1558
- reason: `${r.signal ? `stopped by ${r.signal}` : `exited with code ${r.exitCode}`} in ${ms} and left nothing running`
1559
- };
1560
- }
1561
- async function sigterm(command, args) {
1562
- const r = await run$1(command, args, {
1563
- timeout: 4e3,
1564
- signal: {
1565
- name: "SIGTERM",
1566
- afterMs: SIGTERM_DELAY_MS,
1567
- to: "process"
1568
- },
1569
- stdin: "open",
1570
- leftoversMs: SIGTERM_LEFTOVERS_MS
1571
- });
1572
- const sent = r.signalSentMs;
1573
- return {
1574
- check: "sigterm",
1575
- invocation: [command, ...args],
1576
- ...judgeSigterm(r),
1577
- sentAfterMs: sent ?? null,
1578
- exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1579
- exitCode: r.exitCode,
1580
- signal: r.signal,
1581
- leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1582
- stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1583
- };
1584
- }
1585
- const sigtermCheck = {
1586
- name: "sigterm",
1587
- kind: "check",
1588
- summary: "ignores SIGTERM, or exits on it and leaves its child processes running",
1589
- async run(target) {
1590
- const own = target.probes.filter((p) => p.own);
1591
- if (own.length === 0) return [{
1592
- check: "sigterm",
1593
- invocation: [target.command],
1594
- verdict: "skip",
1595
- reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1596
- sentAfterMs: null,
1597
- exitedAfterMs: null,
1598
- exitCode: null,
1599
- signal: null,
1600
- leftRunning: [],
1601
- stderrAfter: ""
1602
- }];
1603
- const results = [];
1604
- for (const { args } of own) results.push(await sigterm(target.command, args));
1605
- return results;
1606
- }
1607
- };
1608
1924
  function median(values) {
1609
1925
  const sorted = [...values].sort((a, b) => a - b);
1610
1926
  const mid = Math.floor(sorted.length / 2);
@@ -1674,10 +1990,29 @@ const startupCheck = {
1674
1990
  }
1675
1991
  };
1676
1992
  // src/checks/stdin.ts
1677
- /** How long the program gets with stdin left open before it counts as waiting. */
1993
+ /** The least time the program gets with stdin left open before it counts as waiting. */
1678
1994
  const STDIN_WAIT_MS = 3e3;
1679
- /** When the confirming run closes stdin, and how long it then gets to finish. */
1995
+ /** The earliest the confirming run closes stdin, and the least time it then gets to finish. */
1680
1996
  const STDIN_CLOSE_AFTER_MS = 1e3;
1997
+ const STDIN_GRACE_MS = 3e3;
1998
+ /**
1999
+ * How long a run must go past the one with stdin closed before stdin can be
2000
+ * blamed: twice that time and a second more, so a program that is merely slow
2001
+ * (3 to 4 s to answer) finishes well within it.
2002
+ */
2003
+ const stdinMargin = (closedMs) => 2 * closedMs + 1e3;
2004
+ /**
2005
+ * Whether the runs prove the program waited for stdin: it hung with stdin open
2006
+ * for well past the time it needed with stdin closed, and in the confirming run
2007
+ * it finished after stdin was closed, not before.
2008
+ */
2009
+ function provenByClose(runs) {
2010
+ const { closed, open, closing } = runs;
2011
+ const openMs = runs.openMs ?? 3e3;
2012
+ const closeAfterMs = runs.closeAfterMs ?? 1e3;
2013
+ return open?.timedOut === true && openMs >= stdinMargin(closed.durationMs) && closing !== void 0 && !closing.timedOut && closing.durationMs >= closeAfterMs;
2014
+ }
2015
+ const seconds = (ms) => `${Math.round(ms / 100) / 10} s`;
1681
2016
  /** The last line printed before waiting, when it reads like a question left on the line. */
1682
2017
  function promptLine(r) {
1683
2018
  const last = stripEscapes(r.stdout.toString("utf8") + r.stderr).split("\n").at(-1) ?? "";
@@ -1703,11 +2038,21 @@ function judgeStdin(runs, defaultProbe) {
1703
2038
  verdict: "pass",
1704
2039
  reason: "finished without waiting for stdin"
1705
2040
  };
2041
+ const openMs = runs.openMs ?? 3e3;
2042
+ const closeAfterMs = runs.closeAfterMs ?? 1e3;
2043
+ if (openMs < stdinMargin(closed.durationMs)) return {
2044
+ verdict: "skip",
2045
+ reason: `takes ${closed.durationMs} ms even with stdin closed, too close to --timeout to tell whether an open stdin makes it wait; raise --timeout`
2046
+ };
1706
2047
  if (!closing || closing.timedOut) return {
1707
2048
  verdict: "skip",
1708
2049
  reason: "hung with stdin open, but closing stdin didn't end it, so the cause isn't proven"
1709
2050
  };
1710
- const evidence = `${closed.durationMs} ms with stdin closed; still running after ${STDIN_WAIT_MS / 1e3} s with stdin open; finished ${closing.durationMs - STDIN_CLOSE_AFTER_MS} ms after stdin closed`;
2051
+ if (!provenByClose(runs)) return {
2052
+ verdict: "skip",
2053
+ reason: "hung once with stdin open, but finished before stdin was closed the next time, so the cause isn't proven"
2054
+ };
2055
+ const evidence = `${closed.durationMs} ms with stdin closed; still running after ${seconds(openMs)} with stdin open; finished ${closing.durationMs - closeAfterMs} ms after stdin closed`;
1711
2056
  if (defaultProbe) return {
1712
2057
  verdict: "fail",
1713
2058
  reason: "waited for stdin before answering, so an agent or CI step that leaves stdin open hangs forever",
@@ -1729,21 +2074,27 @@ async function stdinRuns(command, args, timeout) {
1729
2074
  const closed = await run$1(command, args, { timeout });
1730
2075
  if (closed.timedOut) return { closed };
1731
2076
  if (closed.spawnError) return { closed };
2077
+ const margin = stdinMargin(closed.durationMs);
2078
+ const openMs = Math.min(timeout, Math.max(STDIN_WAIT_MS, margin));
1732
2079
  const open = await run$1(command, args, {
1733
- timeout: STDIN_WAIT_MS,
2080
+ timeout: openMs,
1734
2081
  stdin: "open"
1735
2082
  });
1736
- if (!open.timedOut) return {
2083
+ if (!open.timedOut || openMs < margin) return {
1737
2084
  closed,
1738
- open
2085
+ open,
2086
+ openMs
1739
2087
  };
2088
+ const closeAfterMs = Math.max(STDIN_CLOSE_AFTER_MS, margin);
1740
2089
  return {
1741
2090
  closed,
1742
2091
  open,
2092
+ openMs,
1743
2093
  closing: await run$1(command, args, {
1744
- timeout: 4e3,
1745
- stdin: { closeAfterMs: STDIN_CLOSE_AFTER_MS }
1746
- })
2094
+ timeout: closeAfterMs + Math.max(STDIN_GRACE_MS, margin),
2095
+ stdin: { closeAfterMs }
2096
+ }),
2097
+ closeAfterMs
1747
2098
  };
1748
2099
  }
1749
2100
  async function stdinCheck(command, args, defaultProbe, ctx) {
@@ -1758,14 +2109,14 @@ async function stdinCheck(command, args, defaultProbe, ctx) {
1758
2109
  };
1759
2110
  const runs = await stdinRuns(command, args, ctx.timeout);
1760
2111
  if (runs.closed.timedOut) markLongRunning(ctx, command, args);
1761
- const proven = runs.open?.timedOut === true && runs.closing !== void 0 && !runs.closing.timedOut;
2112
+ const proven = provenByClose(runs);
1762
2113
  return {
1763
2114
  check: "stdin",
1764
2115
  invocation: [command, ...args],
1765
2116
  ...judgeStdin(runs, defaultProbe),
1766
2117
  closedMs: runs.closed.spawnError ? null : runs.closed.durationMs,
1767
2118
  waitedForStdin: proven,
1768
- finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - STDIN_CLOSE_AFTER_MS : null
2119
+ finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - (runs.closeAfterMs ?? 1e3) : null
1769
2120
  };
1770
2121
  }
1771
2122
  // src/checks/index.ts
@@ -1929,7 +2280,7 @@ function formatHuman({ version, command, checks, strict, results }, { color }) {
1929
2280
  lines.push("");
1930
2281
  if (checks.length > 1) lines.push(check);
1931
2282
  for (const r of results.filter((result) => result.check === check)) {
1932
- lines.push(` ${paint(r.verdict)} ${safe(shellJoin(r.invocation)).padEnd(width)} ${r.reason}`);
2283
+ lines.push(` ${paint(r.verdict)} ${safe(shellJoin(r.invocation)).padEnd(width)} ${safe(r.reason)}`);
1933
2284
  if (r.evidence) lines.push(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
1934
2285
  }
1935
2286
  }
@@ -2206,7 +2557,8 @@ Checks:
2206
2557
  prompts and skips if it reads stdin like a filter.
2207
2558
  ctrl-c Sends Ctrl-C (SIGINT) after 1 s, with stdin left open as in a
2208
2559
  terminal. Fails if the command is still running 3 s later or
2209
- prints a stack trace; warns if it exits 0. Skipped when the
2560
+ prints a stack trace; warns if it exits 0, or exits and leaves
2561
+ processes running that ignored the Ctrl-C. Skipped when the
2210
2562
  command finishes first, so probe a command that keeps running
2211
2563
  (a watcher, a server, a long task), e.g. with --probe "serve".
2212
2564
  sigterm Sends SIGTERM to the command alone after 1 s, as kill, docker
@@ -2259,7 +2611,9 @@ Exit codes: 0 no failures, 1 a check failed (or warned, with --strict), 2 usage
2259
2611
  error or could not run.
2260
2612
  Runs the target in the current directory without a shell, with stdin closed
2261
2613
  (the stdin, ctrl-c and sigterm checks use a pipe they never write to), a
2262
- temporary HOME and a minimal environment. Only run programs you trust.`;
2614
+ temporary HOME and a minimal environment. Only run programs you trust. When a
2615
+ probe exits, or when cliprobe is stopped, it kills whatever the probe left
2616
+ running and removes its temporary files.`;
2263
2617
  // src/cli/program.ts
2264
2618
  /**
2265
2619
  * 0 no failures, 1 a check failed (or, with `strict`, warned), 2 nothing could be
@@ -2308,8 +2662,9 @@ async function run(argv, io) {
2308
2662
  err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
2309
2663
  return 2;
2310
2664
  }
2311
- if (findCommand(opts.command) === void 0) {
2312
- err(`cliprobe: command not found: ${safe(opts.command)}\n`);
2665
+ const problem = commandProblem(opts.command);
2666
+ if (problem !== void 0) {
2667
+ err(`cliprobe: ${safe(problem)}\n`);
2313
2668
  return 2;
2314
2669
  }
2315
2670
  const own = opts.bare || opts.args.length > 0;
@@ -2321,6 +2676,7 @@ async function run(argv, io) {
2321
2676
  own: true
2322
2677
  }))];
2323
2678
  const fixture = probes.some((p) => usesFixture(p.args)) ? createFixture() : void 0;
2679
+ const unregister = fixture && onInterrupt(() => fixture.cleanup());
2324
2680
  const results = [];
2325
2681
  try {
2326
2682
  const target = {
@@ -2337,6 +2693,7 @@ async function run(argv, io) {
2337
2693
  };
2338
2694
  for (const check of checks) results.push(...await check.run(target, ctx));
2339
2695
  } finally {
2696
+ unregister?.();
2340
2697
  fixture?.cleanup();
2341
2698
  }
2342
2699
  const report = {
@@ -2364,6 +2721,7 @@ process.stdout.on("error", (error) => {
2364
2721
  if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
2365
2722
  throw error;
2366
2723
  });
2724
+ handleInterrupts();
2367
2725
  process.exitCode = await run(process.argv.slice(2), {
2368
2726
  stdout: (text) => process.stdout.write(text),
2369
2727
  stderr: (text) => process.stderr.write(text),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Black-box test any command-line program for terminal-edge bugs: crashes on a closed pipe (| head), color and control codes leaking into pipes, hangs waiting on stdin, broken Ctrl-C handling, child processes left running after SIGTERM, a terminal left broken after Ctrl-C, and control characters from file names reaching your terminal.",
5
5
  "type": "module",
6
6
  "bin": {
package/schema.json CHANGED
@@ -454,6 +454,13 @@
454
454
  "type": ["string", "null"],
455
455
  "description": "Signal that ended it, such as \"SIGPIPE\"; null if it exited."
456
456
  },
457
+ "leftRunning": {
458
+ "type": "array",
459
+ "items": {
460
+ "type": "string"
461
+ },
462
+ "description": "Command lines of the processes still running after it exited, in its group or started by it; they ignored the Ctrl-C too. Added in 1.4; absent from earlier reports."
463
+ },
457
464
  "stderrAfter": {
458
465
  "type": "string",
459
466
  "description": "The last 2000 characters it printed to stderr after SIGINT."
@@ -495,7 +502,7 @@
495
502
  "items": {
496
503
  "type": "string"
497
504
  },
498
- "description": "Command lines of the processes still running in its group after it exited."
505
+ "description": "Command lines of the processes still running after it exited, in its group or started by it in another group or session."
499
506
  },
500
507
  "stderrAfter": {
501
508
  "type": "string",