cliprobe 0.8.0 → 0.10.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 (3) hide show
  1. package/README.md +41 -12
  2. package/dist/cli.js +200 -15
  3. package/package.json +4 -2
package/README.md CHANGED
@@ -31,7 +31,7 @@ npx cliprobe -- esbuild
31
31
  ```
32
32
 
33
33
  ```
34
- cliprobe 0.6.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, restore, control-chars checks for esbuild
34
+ cliprobe 0.10.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, sigterm, restore, control-chars checks for esbuild
35
35
 
36
36
  closed-pipe
37
37
  FAIL esbuild --version crashed when stdout was closed (exit 0 -> 1)
@@ -54,6 +54,9 @@ stdin
54
54
  ctrl-c
55
55
  SKIP esbuild needs probe args that keep it running, such as a watch or serve command, or --bare
56
56
 
57
+ sigterm
58
+ SKIP esbuild needs probe args that keep it running, such as a watch or serve command, or --bare
59
+
57
60
  restore
58
61
  PASS esbuild --version left no terminal mode switched on when it exited
59
62
  PASS esbuild --help left no terminal mode switched on when it exited
@@ -61,16 +64,16 @@ restore
61
64
  control-chars
62
65
  SKIP esbuild no {fixture} in the arguments; put it where the command takes a path, e.g. ls {fixture}
63
66
 
64
- 2 failed, 0 warned, 8 passed, 2 skipped
67
+ 2 failed, 0 warned, 8 passed, 3 skipped
65
68
  ```
66
69
 
67
70
  ## Why cliprobe?
68
71
 
69
72
  When a program's output goes into a reader that stops early (`| head`, `grep -q`, a closed agent pipe), its next write to stdout fails. A well-behaved program exits quietly. Many Node.js CLIs instead crash with `Error: write EPIPE`, a stack trace, and exit code 1. That breaks scripts running under `set -o pipefail` and confuses agents that read stderr.
70
73
 
71
- In a census of the 100 most-downloaded npm packages that ship a command (119 commands, run offline in a throwaway container), **9 crashed this way every time**: esbuild, browserslist, update-browserslist-db, autoprefixer, husky, tsconfck, ts-jest, rolldown, and tsx on `--version`. The best-known existing CLI auditor rated the first 8 as passing its SIGPIPE check. The same census found two commands that print color codes into a pipe (`giget --help`, `tsx --help`), five whose `--help` or `--version` waits for stdin (he, cssesc, ansi-html, webpack and webpack-dev-server), and no false failures: every `FAIL` reproduced by hand. (A census of `--help` and `--version` can't exercise ctrl-c or control-chars, which need a command that keeps running or takes a path; their fixtures and real-tool tests are in `test/`.)
74
+ In a census of the 100 most-downloaded npm packages that ship a command (119 commands, run offline in a throwaway container), **9 crashed this way every time**: esbuild, browserslist, update-browserslist-db, autoprefixer, husky, tsconfck, ts-jest, rolldown, and tsx on `--version`. The best-known existing CLI auditor rated the first 8 as passing its SIGPIPE check. The same census found two commands that print color codes into a pipe (`giget --help`, `tsx --help`), five whose `--help` or `--version` waits for stdin (he, cssesc, ansi-html, webpack and webpack-dev-server), and no false failures: every `FAIL` reproduced by hand. (A census of `--help` and `--version` can't exercise ctrl-c, sigterm or control-chars, which need a command that keeps running or takes a path; their fixtures and real-tool tests are in `test/`.)
72
75
 
73
- The other checks cover the rest of what goes wrong between a program and the thing reading it: color codes leaking into logs and agent transcripts, Ctrl-C that is ignored or ends in a stack trace, a terminal left with a hidden cursor or no line wrapping after Ctrl-C, and file names that can send escape sequences to your terminal.
76
+ The other checks cover the rest of what goes wrong between a program and the thing reading it: color codes leaking into logs and agent transcripts, Ctrl-C that is ignored or ends in a stack trace, child processes left running after `kill` or `docker stop`, a terminal left with a hidden cursor or no line wrapping after Ctrl-C, and file names that can send escape sequences to your terminal.
74
77
 
75
78
  - **Evidence, never a score.** Every result is a verdict with the error line, the first stack frame in the target's own code, or the escape sequence that leaked.
76
79
  - **No false fails.** A new check starts as warn-only and is calibrated against real tools before it may fail.
@@ -84,7 +87,7 @@ The other checks cover the rest of what goes wrong between a program and the thi
84
87
  - [Usage](#usage)
85
88
  - [Exit codes](#exit-codes)
86
89
  - [In CI](#in-ci)
87
- - [Checks](#checks): [closed-pipe](#closed-pipe), [color](#color), [pipe-escapes](#pipe-escapes), [stdin](#stdin), [ctrl-c](#ctrl-c), [restore](#restore), [control-chars](#control-chars), [info checks](#info-checks)
90
+ - [Checks](#checks): [closed-pipe](#closed-pipe), [color](#color), [pipe-escapes](#pipe-escapes), [stdin](#stdin), [ctrl-c](#ctrl-c), [sigterm](#sigterm), [restore](#restore), [control-chars](#control-chars), [info checks](#info-checks)
88
91
  - [Fixing a failure in a Node.js CLI](#fixing-a-failure-in-a-nodejs-cli)
89
92
  - [Safety](#safety)
90
93
  - [Contributing](#contributing)
@@ -162,9 +165,9 @@ In JUnit, each check is a test suite and each probe a test case: `FAIL` is a fai
162
165
 
163
166
  ## Checks
164
167
 
165
- A default run does the seven checks below: closed-pipe, color, pipe-escapes, stdin, ctrl-c, restore and control-chars. Each one reports evidence, never a score. Two info checks, startup and baseline, run only when you name them with `--check`.
168
+ A default run does the eight checks below: closed-pipe, color, pipe-escapes, stdin, ctrl-c, sigterm, restore and control-chars. Each one reports evidence, never a score. Two info checks, startup and baseline, run only when you name them with `--check`.
166
169
 
167
- A command that keeps running, such as a server, a watcher or a full-screen program, is what ctrl-c and restore need. The other checks judge it on what it did before the timeout (`--timeout`, 15 seconds by default): a crash once stdout is closed still fails, color or a spinner in a pipe still counts, and stdin is skipped. The timeout is paid once: after the first check sees the command still running, the others watch it for 3 seconds.
170
+ A command that keeps running, such as a server, a watcher or a full-screen program, is what ctrl-c, sigterm and restore need. The other checks judge it on what it did before the timeout (`--timeout`, 15 seconds by default): a crash once stdout is closed still fails, color or a spinner in a pipe still counts, and stdin is skipped. The timeout is paid once: after the first check sees the command still running, the others watch it for 3 seconds.
168
171
 
169
172
  ### closed-pipe
170
173
 
@@ -220,7 +223,7 @@ In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs fa
220
223
 
221
224
  ### ctrl-c
222
225
 
223
- 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. Results:
226
+ 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:
224
227
 
225
228
  | Verdict | Meaning |
226
229
  | ------- | ---------------------------------------------------------------------------------------------- |
@@ -229,7 +232,19 @@ cliprobe lets the command run for 1 second, then sends SIGINT to its process gro
229
232
  | `WARN` | Exited 0, so a script or an agent can't tell the work was interrupted |
230
233
  | `SKIP` | Finished before the Ctrl-C, as `--version` and `--help` do: probe a command that keeps running |
231
234
 
232
- 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.
235
+ 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.
236
+
237
+ ### sigterm
238
+
239
+ `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:
240
+
241
+ | Verdict | Meaning |
242
+ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
243
+ | `PASS` | Exited, by the signal or with any exit code, and left nothing running in its process group |
244
+ | `WARN` | Exited but left processes running (the evidence names the first), still running 3 seconds later, or printed a stack trace after the SIGTERM |
245
+ | `SKIP` | Finished before the SIGTERM, as `--version` and `--help` do: probe a command that keeps running |
246
+
247
+ It only warns for now. Across 44 watch modes, dev servers and long tasks run offline, every one exited within 90 ms of the SIGTERM, and 37 left nothing behind: vite, webpack, tsc, jest, Next.js, Nuxt, Astro, wrangler, nodemon, concurrently and more stop their own children. All 7 warnings were real, with the process still running 5 seconds later: `npm run dev`, `npm run serve` and `npx vite`, because npm dies on SIGTERM without passing it on (run `node` directly in a container or a process manager), and shell wrappers such as `sh -c 'node server.js'` or `bash -c 'sleep 30; echo done'`. Nothing ignored SIGTERM or printed a stack trace.
233
248
 
234
249
  ### restore
235
250
 
@@ -302,15 +317,29 @@ if (process.stdin.isTTY) askTheQuestion();
302
317
  else useTheDefault(); // or fail with a message saying which flag to pass
303
318
  ```
304
319
 
305
- **ctrl-c:** Node's default already does the right thing, dying by SIGINT. If you add a handler to clean up, finish by exiting 130 rather than 0, and don't throw from it:
320
+ **ctrl-c:** Node's default already does the right thing, dying by SIGINT. If you add a handler to clean up, finish by dying the same way, and don't throw from it:
306
321
 
307
322
  ```js
308
323
  process.once('SIGINT', async () => {
309
324
  await cleanUp();
310
- process.exit(130);
325
+ process.kill(process.pid, 'SIGINT'); // the handler is gone, so this ends the process
311
326
  });
312
327
  ```
313
328
 
329
+ That matters to the shell that started you: bash stops a script on Ctrl-C only when the program died by the signal. After an exit with 130 or 0, the script carries on to its next command; 130 at least stops `&&` chains and `set -e`, which 0 doesn't.
330
+
331
+ **sigterm:** stop what you started before you exit. Pass the signal on to each child and wait for it:
332
+
333
+ ```js
334
+ const server = spawn(process.execPath, ['server.js'], { stdio: 'inherit' });
335
+ process.once('SIGTERM', () => {
336
+ server.once('exit', () => process.exit(0));
337
+ server.kill('SIGTERM');
338
+ });
339
+ ```
340
+
341
+ A shell wrapper should `exec` its last command (`sh -c 'exec node server.js'`), so the signal goes straight to it instead of to a shell that dies and leaves it running.
342
+
314
343
  **restore:** switch every mode back off on the way out, including after Ctrl-C. Node runs `exit` handlers on `process.exit()` but not when a signal kills it, so turn SIGINT into an exit, and in raw mode, where Ctrl-C arrives as the key `\x03`, exit on that key too:
315
344
 
316
345
  ```js
@@ -332,7 +361,7 @@ Also escape U+2028, U+2029 and the bidi controls (U+202A to U+202E, U+2066 to U+
332
361
 
333
362
  ## Safety
334
363
 
335
- cliprobe runs the target in your current directory without a shell, with stdin closed (`/dev/null`; the stdin check also uses a pipe that it never writes 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, 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, to probes you write. It kills each run's whole process group on timeout, including under a pseudo-terminal. 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.
364
+ 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, 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.
336
365
 
337
366
  ## Contributing
338
367
 
package/dist/cli.js CHANGED
@@ -1,9 +1,68 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
4
+ import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, 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
8
+ /**
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.
12
+ */
13
+ function groupMembers(pgid) {
14
+ return process.platform === "linux" ? membersFromProc(pgid) : membersFromPs(pgid);
15
+ }
16
+ /** Linux: reads `<root>/<pid>/stat` and `cmdline` for every process. */
17
+ function membersFromProc(pgid, root = "/proc") {
18
+ const members = [];
19
+ for (const entry of readdirSync(root)) {
20
+ if (!/^\d+$/.test(entry)) continue;
21
+ try {
22
+ const stat = parseProcStat(readFileSync(`${root}/${entry}/stat`, "utf8"));
23
+ if (stat.pgid !== pgid || isGone(stat.state)) continue;
24
+ const cmdline = readFileSync(`${root}/${entry}/cmdline`, "utf8").split("\0").filter(Boolean).join(" ");
25
+ members.push({
26
+ pid: Number(entry),
27
+ command: cmdline || stat.name
28
+ });
29
+ } catch {}
30
+ }
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);
40
+ }
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 = [];
56
+ 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({
60
+ pid: Number(m[1]),
61
+ command: (m[4] ?? "").trim()
62
+ });
63
+ }
64
+ return members.sort((a, b) => a.pid - b.pid);
65
+ }
7
66
  // src/core/sandbox.ts
8
67
  /** A minimal environment: no tokens or config from the caller's shell. */
9
68
  function sandbox() {
@@ -29,7 +88,7 @@ const STDOUT_CAP = 1048576;
29
88
  * whose read end is closed before the program starts, so its first write to
30
89
  * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
31
90
  */
32
- function run$1(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal, stdin = "null" }) {
91
+ function run$1(command, args, { closedStdout = false, timeout, env: overrides = {}, beforeKill, signal, stdin = "null", leftoversMs }) {
33
92
  const { dir, env: base } = sandbox();
34
93
  const env = { ...base };
35
94
  for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
@@ -51,6 +110,9 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
51
110
  let exited = false;
52
111
  let signalSentMs;
53
112
  let stderrAtSignal;
113
+ let leftRunning;
114
+ let afterExit = Promise.resolve();
115
+ let exitMs;
54
116
  const start = performance.now();
55
117
  const finish = (outcome) => {
56
118
  if (finished) return;
@@ -66,11 +128,12 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
66
128
  stdout,
67
129
  stderr,
68
130
  timedOut,
69
- durationMs: Math.round(performance.now() - start),
131
+ durationMs: exitMs ?? Math.round(performance.now() - start),
70
132
  ...signalSentMs === void 0 ? {} : {
71
133
  signalSentMs,
72
134
  stderrAtSignal: stderrAtSignal ?? 0
73
135
  },
136
+ ...leftRunning === void 0 ? {} : { leftRunning },
74
137
  ...outcome
75
138
  });
76
139
  };
@@ -105,7 +168,7 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
105
168
  signalSentMs = Math.round(performance.now() - start);
106
169
  stderrAtSignal = stderr.length;
107
170
  try {
108
- process.kill(-child.pid, signal.name);
171
+ process.kill(signal.to === "process" ? child.pid : -child.pid, signal.name);
109
172
  } catch {}
110
173
  }, signal.afterMs);
111
174
  const closeTimer = typeof stdin === "object" ? setTimeout(() => child.stdin?.destroy(), stdin.closeAfterMs) : void 0;
@@ -114,6 +177,14 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
114
177
  clearTimeout(signalTimer);
115
178
  clearTimeout(closeTimer);
116
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
+ }
117
188
  });
118
189
  child.stdout?.on("data", (chunk) => {
119
190
  if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
@@ -134,13 +205,31 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
134
205
  child.on("close", (exitCode, exitSignal) => {
135
206
  clearTimeout(timer);
136
207
  clearTimeout(signalTimer);
137
- finish({
208
+ afterExit.then(() => finish({
138
209
  exitCode,
139
210
  signal: exitSignal
140
- });
211
+ }));
141
212
  });
142
213
  });
143
214
  }
215
+ /** How often to look at the group while waiting for it to empty. */
216
+ const GROUP_POLL_MS = 50;
217
+ /**
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.
220
+ */
221
+ async function watchLeftovers(pgid, ms) {
222
+ 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);
227
+ }
228
+ if (members.length > 0) try {
229
+ process.kill(-pgid, "SIGKILL");
230
+ } catch {}
231
+ return members;
232
+ }
144
233
  // src/checks/baseline.ts
145
234
  /** A flag no real program defines. */
146
235
  const UNKNOWN_FLAG = "--cliprobe-unknown-flag";
@@ -1153,7 +1242,7 @@ const CTRL_C_DELAY_MS = 1e3;
1153
1242
  /** How long it gets to exit after Ctrl-C. */
1154
1243
  const CTRL_C_GRACE_MS = 3e3;
1155
1244
  /** Lines worth quoting from a trace printed on Ctrl-C, best first. */
1156
- const TRACE_MESSAGES = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1245
+ const TRACE_MESSAGES$1 = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1157
1246
  function judgeCtrlC(r) {
1158
1247
  if (r.spawnError) return {
1159
1248
  verdict: "error",
@@ -1172,7 +1261,7 @@ function judgeCtrlC(r) {
1172
1261
  if (TRACE_RE.test(after)) return {
1173
1262
  verdict: "fail",
1174
1263
  reason: "printed a stack trace on Ctrl-C",
1175
- evidence: crashEvidence(after, TRACE_MESSAGES)
1264
+ evidence: crashEvidence(after, TRACE_MESSAGES$1)
1176
1265
  };
1177
1266
  if (r.signal) return {
1178
1267
  verdict: "pass",
@@ -1197,7 +1286,8 @@ async function ctrlC(command, args) {
1197
1286
  signal: {
1198
1287
  name: "SIGINT",
1199
1288
  afterMs: CTRL_C_DELAY_MS
1200
- }
1289
+ },
1290
+ stdin: "open"
1201
1291
  });
1202
1292
  const sent = r.signalSentMs;
1203
1293
  return {
@@ -1423,6 +1513,94 @@ const restoreCheck = {
1423
1513
  return results;
1424
1514
  }
1425
1515
  };
1516
+ // src/checks/sigterm.ts
1517
+ /** How long the program runs before SIGTERM. */
1518
+ const SIGTERM_DELAY_MS = 1e3;
1519
+ /** How long it gets to exit after SIGTERM. */
1520
+ const SIGTERM_GRACE_MS = 3e3;
1521
+ /** How long its children get to follow it once it has exited. */
1522
+ const SIGTERM_LEFTOVERS_MS = 1e3;
1523
+ /** Lines worth quoting from a trace printed on SIGTERM, best first. */
1524
+ const TRACE_MESSAGES = [/^(\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1525
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "es"}`;
1526
+ function judgeSigterm(r) {
1527
+ if (r.spawnError) return {
1528
+ verdict: "error",
1529
+ reason: `could not start: ${r.spawnError}`
1530
+ };
1531
+ if (r.signalSentMs === void 0) return {
1532
+ verdict: "skip",
1533
+ reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1534
+ };
1535
+ if (r.timedOut) return {
1536
+ verdict: "warn",
1537
+ reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
1538
+ };
1539
+ const left = r.leftRunning ?? [];
1540
+ const [firstLeft] = left;
1541
+ if (firstLeft) return {
1542
+ verdict: "warn",
1543
+ reason: `exited on SIGTERM but left ${plural(left.length, "process")} running, which keep ports and files busy`,
1544
+ evidence: `still running: ${firstLeft.command}${left.length > 1 ? ` (and ${left.length - 1} more)` : ""}`
1545
+ };
1546
+ const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1547
+ if (TRACE_RE.test(after)) return {
1548
+ verdict: "warn",
1549
+ reason: "printed a stack trace on SIGTERM",
1550
+ evidence: crashEvidence(after, TRACE_MESSAGES)
1551
+ };
1552
+ const ms = `${r.durationMs - r.signalSentMs} ms`;
1553
+ return {
1554
+ verdict: "pass",
1555
+ reason: `${r.signal ? `stopped by ${r.signal}` : `exited with code ${r.exitCode}`} in ${ms} and left nothing running`
1556
+ };
1557
+ }
1558
+ async function sigterm(command, args) {
1559
+ const r = await run$1(command, args, {
1560
+ timeout: 4e3,
1561
+ signal: {
1562
+ name: "SIGTERM",
1563
+ afterMs: SIGTERM_DELAY_MS,
1564
+ to: "process"
1565
+ },
1566
+ stdin: "open",
1567
+ leftoversMs: SIGTERM_LEFTOVERS_MS
1568
+ });
1569
+ const sent = r.signalSentMs;
1570
+ return {
1571
+ check: "sigterm",
1572
+ invocation: [command, ...args],
1573
+ ...judgeSigterm(r),
1574
+ sentAfterMs: sent ?? null,
1575
+ exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1576
+ exitCode: r.exitCode,
1577
+ signal: r.signal,
1578
+ leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1579
+ stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1580
+ };
1581
+ }
1582
+ const sigtermCheck = {
1583
+ name: "sigterm",
1584
+ kind: "check",
1585
+ summary: "ignores SIGTERM, or exits on it and leaves its child processes running",
1586
+ async run(target) {
1587
+ if (!target.explicit) return [{
1588
+ check: "sigterm",
1589
+ invocation: [target.command],
1590
+ verdict: "skip",
1591
+ reason: "needs probe args that keep it running, such as a watch or serve command, or --bare",
1592
+ sentAfterMs: null,
1593
+ exitedAfterMs: null,
1594
+ exitCode: null,
1595
+ signal: null,
1596
+ leftRunning: [],
1597
+ stderrAfter: ""
1598
+ }];
1599
+ const results = [];
1600
+ for (const args of target.invocations) results.push(await sigterm(target.command, args));
1601
+ return results;
1602
+ }
1603
+ };
1426
1604
  function median(values) {
1427
1605
  const sorted = [...values].sort((a, b) => a - b);
1428
1606
  const mid = Math.floor(sorted.length / 2);
@@ -1602,6 +1780,7 @@ const CHECKS = [
1602
1780
  }
1603
1781
  },
1604
1782
  ctrlCCheck,
1783
+ sigtermCheck,
1605
1784
  restoreCheck,
1606
1785
  controlCharsCheck,
1607
1786
  startupCheck,
@@ -1932,10 +2111,16 @@ Checks:
1932
2111
  as agents and CI runners often leave it. Fails if --version or
1933
2112
  --help waits for input; for your own probes, warns if it
1934
2113
  prompts and skips if it reads stdin like a filter.
1935
- ctrl-c Sends Ctrl-C (SIGINT) after 1 s. Fails if the command is still
1936
- running 3 s later or prints a stack trace; warns if it exits 0.
1937
- Skipped when the command finishes first, so probe a command
1938
- that keeps running (a watcher, a server, a long task).
2114
+ ctrl-c Sends Ctrl-C (SIGINT) after 1 s, with stdin left open as in a
2115
+ terminal. Fails if the command is still running 3 s later or
2116
+ prints a stack trace; warns if it exits 0. Skipped when the
2117
+ command finishes first, so probe a command that keeps running
2118
+ (a watcher, a server, a long task).
2119
+ sigterm Sends SIGTERM to the command alone after 1 s, as kill, docker
2120
+ stop and process managers do. Warns if it is still running 3 s
2121
+ later, prints a stack trace, or exits and leaves child
2122
+ processes running (a dev server holding its port). Skipped
2123
+ when the command finishes first, as for ctrl-c.
1939
2124
  restore Runs the command under a terminal and, for your own probes,
1940
2125
  types Ctrl-C after 1 s, as a person would. Warns if it leaves
1941
2126
  the cursor hidden, the alternate screen, mouse or focus
@@ -1973,8 +2158,8 @@ Options:
1973
2158
 
1974
2159
  Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
1975
2160
  Runs the target in the current directory without a shell, with stdin closed
1976
- (the stdin check uses a pipe it never writes to), a temporary HOME and a
1977
- minimal environment. Only run programs you trust.`;
2161
+ (the stdin, ctrl-c and sigterm checks use a pipe they never write to), a
2162
+ temporary HOME and a minimal environment. Only run programs you trust.`;
1978
2163
  // src/cli/program.ts
1979
2164
  /** 0 no failures, 1 a check failed, 2 nothing could be judged because something could not run. */
1980
2165
  function exitCodeFor(results) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "0.8.0",
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, a terminal left broken after Ctrl-C, and control characters from file names reaching your terminal.",
3
+ "version": "0.10.0",
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": {
7
7
  "cliprobe": "dist/cli.js"
@@ -38,6 +38,8 @@
38
38
  "no-color",
39
39
  "sigint",
40
40
  "ctrl-c",
41
+ "sigterm",
42
+ "graceful-shutdown",
41
43
  "terminal-injection",
42
44
  "pty",
43
45
  "stdin",