cliprobe 0.4.1 → 0.6.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 +47 -21
  2. package/dist/cli.js +473 -79
  3. package/package.json +5 -3
package/README.md CHANGED
@@ -7,7 +7,7 @@ npx cliprobe -- esbuild
7
7
  ```
8
8
 
9
9
  ```
10
- cliprobe 0.4.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, control-chars checks for esbuild
10
+ cliprobe 0.6.0: closed-pipe, color, pipe-escapes, stdin, ctrl-c, restore, control-chars checks for esbuild
11
11
 
12
12
  closed-pipe
13
13
  FAIL esbuild --version crashed when stdout was closed (exit 0 -> 1)
@@ -28,12 +28,16 @@ stdin
28
28
  PASS esbuild --help finished without waiting for stdin
29
29
 
30
30
  ctrl-c
31
- SKIP esbuild needs probe args that keep it running, such as a watch or serve command
31
+ SKIP esbuild needs probe args that keep it running, such as a watch or serve command, or --bare
32
+
33
+ restore
34
+ PASS esbuild --version left no terminal mode switched on when it exited
35
+ PASS esbuild --help left no terminal mode switched on when it exited
32
36
 
33
37
  control-chars
34
38
  SKIP esbuild no {fixture} in the arguments; put it where the command takes a path, e.g. ls {fixture}
35
39
 
36
- 2 failed, 0 warned, 6 passed, 2 skipped
40
+ 2 failed, 0 warned, 8 passed, 2 skipped
37
41
  ```
38
42
 
39
43
  ## Why
@@ -42,7 +46,7 @@ When a program's output goes into a reader that stops early (`| head`, `grep -q`
42
46
 
43
47
  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/`.)
44
48
 
45
- 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, and file names that can send escape sequences to your terminal.
49
+ 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.
46
50
 
47
51
  ## Usage
48
52
 
@@ -53,20 +57,22 @@ npx cliprobe -- node ./dist/cli.js list # test your own CLI before publishing
53
57
  npx cliprobe --json -- <command> # machine-readable results
54
58
  npx cliprobe --format junit -o report.xml -- <command> # JUnit file for CI; human report on stdout
55
59
  npx cliprobe -- ls {fixture} # {fixture}: a directory of hostile file names
60
+ npx cliprobe --bare -- htop # the command alone: a REPL, a full-screen program, a server
56
61
  npx cliprobe --check startup,baseline -- node ./dist/cli.js # info checks, only when named
57
62
  ```
58
63
 
59
64
  | Option | Meaning |
60
65
  | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
66
+ | `--bare` | Probe the command with no arguments instead of `--version` and `--help`, as a probe you wrote |
61
67
  | `--check <name>` | Run only this check; repeat it or use commas for several |
62
68
  | `--format <name>` | Output format: `human` (default), `json`, `markdown` (a GitHub job summary or PR comment) or `junit` (XML for CI test reports) |
63
69
  | `--json` | Same as `--format json` |
64
70
  | `-o`, `--output-file <path>` | Write the `--format` report to a file (atomically, creating parent folders); the human report still prints |
65
- | `--timeout <ms>` | Kill a probe after this long (default 15000) |
71
+ | `--timeout <ms>` | Kill a probe after this long (default 15000); a command still running then is judged on what it did so far |
66
72
  | `-h`, `--help` | Show help |
67
73
  | `-v`, `--version` | Show the version |
68
74
 
69
- Exit codes: `0` no failures, `1` a check failed, `2` usage error or the command could not run. That makes it usable as a CI gate.
75
+ Exit codes: `0` no failures, `1` a check failed, `2` usage error or the command could not run. A command that isn't on `PATH` is reported once, before any check runs, with exit `2` and no report. That makes it usable as a CI gate.
70
76
 
71
77
  ### In CI
72
78
 
@@ -92,16 +98,18 @@ In JUnit, each check is a test suite and each probe a test case: `FAIL` is a fai
92
98
 
93
99
  ## Checks
94
100
 
95
- A default run does the six checks below: closed-pipe, color, pipe-escapes, stdin, ctrl-c and control-chars. Each one reports evidence, never a score. Two info checks, startup and baseline, run only when you name them with `--check`.
101
+ 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`.
102
+
103
+ 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 warns (for now; it becomes a failure once calibrated against real servers), 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.
96
104
 
97
105
  **closed-pipe**. cliprobe runs the command twice: once normally, then with stdout set to a pipe whose reading end is already closed, so the first write fails every time, even for fast native programs. Results:
98
106
 
99
- | Verdict | Meaning |
100
- | ------- | ------------------------------------------------------------------------------ |
101
- | `PASS` | Exited quietly, or was stopped by SIGPIPE (the Unix convention) |
102
- | `FAIL` | Printed an EPIPE error or stack trace and changed its exit code, or hung |
103
- | `WARN` | Printed a write error but kept its exit code |
104
- | `SKIP` | Wrote nothing to stdout for this invocation, so pass args that print something |
107
+ | Verdict | Meaning |
108
+ | ------- | ------------------------------------------------------------------------------------------------------ |
109
+ | `PASS` | Exited quietly, or was stopped by SIGPIPE (the Unix convention), or kept running without a write error |
110
+ | `FAIL` | Printed an EPIPE error or stack trace and changed its exit code, or hung |
111
+ | `WARN` | Printed a write error but kept its exit code, or crashed on it while a normal run kept running |
112
+ | `SKIP` | Wrote nothing to stdout for this invocation (or before the timeout), so pass args that print something |
105
113
 
106
114
  **color**. cliprobe runs the command up to three times: into a pipe, under a real terminal (a pseudo-terminal through the system's `script` command, 80×24), and under a terminal with `NO_COLOR=1`. Every run gets `TERM=xterm-256color` and no `CI` variable, so a program can't pass just because the terminal type looks colorless, and color libraries that force color in CI don't fail it. Color codes in piped output end up in log files and agent transcripts as `\x1b[31m` noise. Results:
107
115
 
@@ -122,7 +130,7 @@ Many classic tools (git, BSD `ls` and `grep`) color correctly but don't implemen
122
130
  | `WARN` | One or more reached stdout or stderr; the reason lists which kinds |
123
131
  | `SKIP` | Printed nothing |
124
132
 
125
- It only warns for now, never fails. In the census of the top 100 npm CLIs, no `--help` or `--version` printed any of these codes, which says nothing about their spinners: probe a command that does real work, such as an install or a build.
133
+ It only warns for now, never fails. In the census of the top 100 npm CLIs, no `--help` or `--version` printed any of these codes, which says nothing about their spinners: probe a command that does real work, such as an install or a build. With `{fixture}` in the args, the hostile file names themselves are left to the control-chars check: a lister that prints them raw into a pipe, as `ls` does, isn't warned about.
126
134
 
127
135
  **stdin**. 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:
128
136
 
@@ -146,14 +154,24 @@ In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs fa
146
154
 
147
155
  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.
148
156
 
157
+ **restore**. Spinners, prompts and full-screen programs switch terminal modes on: they hide the cursor, open the alternate screen, turn on mouse reporting or bracketed paste, or turn line wrapping off. If they don't switch them back off on the way out, the shell they return to is broken until you run `reset`: no cursor, a blank screen, mouse clicks typed as junk, long lines cut off at the edge. cliprobe runs the command under a terminal and, for probes you write, types Ctrl-C after 1 second, as a person would. The keystroke goes through the terminal, so a program in raw mode gets it as a key rather than a signal, just as it would from a keyboard. `--version` and `--help` aren't interrupted; they're judged as they exit. Results:
158
+
159
+ | Verdict | Meaning |
160
+ | ------- | --------------------------------------------------------------------------------------------------------------------------- |
161
+ | `PASS` | Left no mode switched on, either because it never switched one or because it switched each back off (or reset the terminal) |
162
+ | `WARN` | Left one or more on; the evidence quotes each sequence that was never undone and its line |
163
+ | `SKIP` | Still running 3 seconds after Ctrl-C (REPLs quit on a second one), more than 1 MiB of output, or no usable `script` command |
164
+
165
+ It only warns: a terminal left in the wrong mode is a nuisance you can undo, not a failure of the program's job. Across the top 100 npm CLIs, their watch modes and servers, and popular prompt and spinner libraries (about 300 runs), nothing warned falsely, and one tool really did break the terminal: `taze -I` turns line wrapping off for its progress bars and leaves it off after Ctrl-C.
166
+
149
167
  **control-chars**. Put `{fixture}` in the arguments where your command takes a path, for example `npx cliprobe -- ls {fixture}` or `npx cliprobe -- node ./dist/cli.js scan --dir={fixture}`. cliprobe replaces it with a temporary directory of file names holding escape sequences (one sets the window title, one clears the screen), a C1 control character, a carriage return, a newline and a bidirectional override. It runs the command under a terminal and looks for those characters, unescaped, in what reaches it. A file name that can clear someone's screen or retitle their window is a terminal injection, the same bug class as the `ls`/`find` escaping that GNU coreutils added years ago. Reports show `{fixture}`, never the temporary path, and the directory is removed afterwards. Results:
150
168
 
151
- | Verdict | Meaning |
152
- | ------- | ----------------------------------------------------------------------------------------------------------- |
153
- | `PASS` | Escaped or replaced the control characters (a raw bidi override is mentioned, not judged) |
154
- | `FAIL` | Sent an escape sequence from a file name to the terminal unescaped |
155
- | `WARN` | Printed a C1 control, carriage return or newline from a file name unescaped, which can hide or forge output |
156
- | `SKIP` | No `{fixture}` in the arguments, the command never printed the file names, or no usable `script` |
169
+ | Verdict | Meaning |
170
+ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `PASS` | Escaped or replaced the control characters (a raw bidi override is mentioned, not judged) |
172
+ | `FAIL` | Sent an escape sequence from a file name to the terminal unescaped |
173
+ | `WARN` | Printed a C1 control, carriage return or newline from a file name unescaped, which can hide or forge output |
174
+ | `SKIP` | No `{fixture}` in the arguments, the command never printed the file names (before the timeout, for one that keeps running), or no usable `script` |
157
175
 
158
176
  Only the terminal run is judged. Into a pipe, `ls` and `find` print names exactly, by design; that is recorded in the JSON (`pipeRaw`) but doesn't affect the verdict. BSD `find` on macOS fails this check: unlike GNU `find`, it prints names raw even to a terminal.
159
177
 
@@ -200,6 +218,14 @@ process.once('SIGINT', async () => {
200
218
  });
201
219
  ```
202
220
 
221
+ **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:
222
+
223
+ ```js
224
+ process.stdout.write('\x1b[?25l'); // hide the cursor
225
+ process.on('exit', () => process.stdout.write('\x1b[?25h')); // and always show it again
226
+ process.once('SIGINT', () => process.exit(130));
227
+ ```
228
+
203
229
  **control-chars:** escape names (and any other text you didn't write) before printing them for a person. `JSON.stringify` alone isn't enough: it leaves C1 controls and bidi overrides raw.
204
230
 
205
231
  ```js
@@ -213,7 +239,7 @@ Also escape U+2028, U+2029 and the bidi controls (U+202A to U+202E, U+2066 to U+
213
239
 
214
240
  ## Safety
215
241
 
216
- 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`; only the baseline check, when you name it, adds an unknown flag. 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.
242
+ 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.
217
243
 
218
244
  ## License
219
245
 
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { execFileSync, spawn } from "node:child_process";
4
- import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
- import { dirname, join } from "node:path";
4
+ import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
+ import { delimiter, dirname, join } from "node:path";
6
6
  import { tmpdir } from "node:os";
7
7
  // src/core/sandbox.ts
8
8
  /** A minimal environment: no tokens or config from the caller's shell. */
@@ -147,7 +147,13 @@ const UNKNOWN_FLAG = "--cliprobe-unknown-flag";
147
147
  /** A program that ignores unknown flags may start its default action; don't wait long. */
148
148
  const UNKNOWN_FLAG_TIMEOUT_MS = 5e3;
149
149
  const lines = (text) => text.split("\n").filter((l) => l.trim() !== "");
150
- const firstLine = (r) => lines(r.stdout.toString("utf8"))[0] ?? lines(r.stderr)[0] ?? "";
150
+ /** The first line printed, labelled with its stream, as evidence. */
151
+ function firstLine(r) {
152
+ const out = lines(r.stdout.toString("utf8"))[0];
153
+ if (out !== void 0) return `stdout: ${out}`;
154
+ const err = lines(r.stderr)[0];
155
+ return err === void 0 ? "" : `stderr: ${err}`;
156
+ }
151
157
  const exitText = (r) => r.signal ? `was stopped by ${r.signal}` : `exited ${r.exitCode}`;
152
158
  /** Each describes one convention scripts and agents rely on; observations, never verdicts. */
153
159
  function describeVersion(r) {
@@ -162,7 +168,7 @@ function describeVersion(r) {
162
168
  };
163
169
  if (out.length > 1) return {
164
170
  reason: `printed ${out.length} lines to stdout; one line is easier for scripts to parse`,
165
- evidence: out[0] ?? ""
171
+ evidence: `first line: ${out[0] ?? ""}`
166
172
  };
167
173
  if (lines(r.stderr).length) return {
168
174
  reason: "printed the version to stderr, not stdout",
@@ -256,17 +262,68 @@ function crashEvidence(stderr, messages = CRASH_MESSAGES) {
256
262
  const cwd = process.cwd() + "/";
257
263
  return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
258
264
  }
265
+ // src/core/long-running.ts
266
+ /**
267
+ * Once one check has seen a probe still running at the timeout (a server, a
268
+ * watcher, a full-screen program), later checks watch it this long instead, so
269
+ * the timeout is paid once rather than once per check.
270
+ */
271
+ const LONG_RUN_WINDOW_MS = 3e3;
272
+ const key = (command, args) => JSON.stringify([command, ...args]);
273
+ function isLongRunning(ctx, command, args) {
274
+ return ctx.longRunning?.has(key(command, args)) === true;
275
+ }
276
+ /** How long to let a normal run of this probe go: the timeout, or the short window once it is known to keep running. */
277
+ function probeTimeout(ctx, command, args) {
278
+ return isLongRunning(ctx, command, args) ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout;
279
+ }
280
+ function markLongRunning(ctx, command, args) {
281
+ ctx.longRunning?.add(key(command, args));
282
+ }
283
+ /** "still running after 15 s", from a run that was stopped at its timeout. */
284
+ const stillRunning = (durationMs) => `still running after ${Math.round(durationMs / 1e3)} s`;
259
285
  // src/checks/closed-pipe.ts
286
+ /** A program that writes an error to stderr only once its stdout is closed. */
287
+ const newWriteError = (base, closed) => ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
288
+ /**
289
+ * For a program that keeps running (a server, a watcher): there is no normal exit
290
+ * to compare with, but a crash once stdout is closed is still a crash.
291
+ */
292
+ function judgeLongRunning(base, closed) {
293
+ if (!closed.timedOut && newWriteError(base, closed)) return {
294
+ verdict: "warn",
295
+ reason: `crashed when stdout was closed, while a normal run kept running (exit ${closed.exitCode})`,
296
+ evidence: crashEvidence(closed.stderr)
297
+ };
298
+ if (closed.signal === "SIGPIPE") return {
299
+ verdict: "pass",
300
+ reason: "stopped by SIGPIPE, the conventional exit"
301
+ };
302
+ if (base.stdoutBytes === 0) return {
303
+ verdict: "skip",
304
+ reason: `${stillRunning(base.durationMs)} without writing to stdout, so a closed stdout was never touched`
305
+ };
306
+ if (!closed.timedOut) return {
307
+ verdict: "pass",
308
+ reason: "exited quietly when stdout was closed"
309
+ };
310
+ if (newWriteError(base, closed)) return {
311
+ verdict: "warn",
312
+ reason: "printed a write error when stdout was closed, and kept running",
313
+ evidence: crashEvidence(closed.stderr)
314
+ };
315
+ return {
316
+ verdict: "pass",
317
+ reason: `${stillRunning(base.durationMs)}; with stdout closed it kept running without a write error`
318
+ };
319
+ }
260
320
  /** Compares a normal run with a closed-stdout run of the same invocation. */
261
321
  function judge(base, closed) {
262
322
  if (base.spawnError) return {
263
323
  verdict: "error",
264
324
  reason: `could not start: ${base.spawnError}`
265
325
  };
266
- if (base.timedOut) return {
267
- verdict: "error",
268
- reason: "timed out on a normal run"
269
- };
326
+ if (base.timedOut) return judgeLongRunning(base, closed);
270
327
  if (base.stdoutBytes === 0) return {
271
328
  verdict: "skip",
272
329
  reason: "wrote nothing to stdout, so a closed stdout is never touched"
@@ -279,7 +336,7 @@ function judge(base, closed) {
279
336
  verdict: "pass",
280
337
  reason: "stopped by SIGPIPE, the conventional exit"
281
338
  };
282
- const newError = ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
339
+ const newError = newWriteError(base, closed);
283
340
  if (newError && closed.exitCode !== base.exitCode) return {
284
341
  verdict: "fail",
285
342
  reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`,
@@ -299,14 +356,15 @@ function judge(base, closed) {
299
356
  reason: "exited quietly"
300
357
  };
301
358
  }
302
- async function closedPipe(command, args, timeout) {
359
+ async function closedPipe(command, args, ctx) {
303
360
  const base = await run$1(command, args, {
304
361
  closedStdout: false,
305
- timeout
362
+ timeout: probeTimeout(ctx, command, args)
306
363
  });
364
+ if (base.timedOut) markLongRunning(ctx, command, args);
307
365
  const closed = await run$1(command, args, {
308
366
  closedStdout: true,
309
- timeout
367
+ timeout: base.timedOut ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout
310
368
  });
311
369
  return {
312
370
  check: "closed-pipe",
@@ -331,7 +389,7 @@ const closedPipeCheck = {
331
389
  summary: "crashes or hangs when stdout is closed early (| head, grep -q, an agent)",
332
390
  async run(target, ctx) {
333
391
  const results = [];
334
- for (const args of target.invocations) results.push(await closedPipe(target.command, args, ctx.timeout));
392
+ for (const args of target.invocations) results.push(await closedPipe(target.command, args, ctx));
335
393
  return results;
336
394
  }
337
395
  };
@@ -441,6 +499,84 @@ const ANY_ESCAPE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
441
499
  function stripEscapes(text) {
442
500
  return text.replace(ANY_ESCAPE, "");
443
501
  }
502
+ /** The modes that leave a shell broken when a program forgets them. */
503
+ const TERMINAL_MODES = [
504
+ {
505
+ label: "hidden cursor",
506
+ codes: [25],
507
+ inverted: true
508
+ },
509
+ {
510
+ label: "alternate screen",
511
+ codes: [
512
+ 47,
513
+ 1047,
514
+ 1049
515
+ ]
516
+ },
517
+ {
518
+ label: "mouse reporting",
519
+ codes: [
520
+ 9,
521
+ 1e3,
522
+ 1001,
523
+ 1002,
524
+ 1003,
525
+ 1005,
526
+ 1006,
527
+ 1015
528
+ ]
529
+ },
530
+ {
531
+ label: "focus reporting",
532
+ codes: [1004]
533
+ },
534
+ {
535
+ label: "bracketed paste",
536
+ codes: [2004]
537
+ },
538
+ {
539
+ label: "line wrapping off",
540
+ codes: [7],
541
+ inverted: true
542
+ }
543
+ ];
544
+ /** DEC private mode set or reset (ESC [ ? numbers h|l), or a full reset (ESC c). */
545
+ const DEC_MODE = /\x1b\[\?([\d;]+)([hl])|\x1bc/g;
546
+ /**
547
+ * The terminal modes the text leaves switched on, in the order they were
548
+ * switched on. A mode counts as on from its first switch-on until a later
549
+ * switch-off or a full reset, so a program that restores everything leaves none.
550
+ */
551
+ function findOpenModes(text) {
552
+ const open = /* @__PURE__ */ new Map();
553
+ for (const m of text.matchAll(DEC_MODE)) {
554
+ if (m[2] === void 0) {
555
+ open.clear();
556
+ continue;
557
+ }
558
+ const set = m[2] === "h";
559
+ for (const code of (m[1] ?? "").split(";").map(Number)) {
560
+ const mode = TERMINAL_MODES.find((t) => t.codes.includes(code));
561
+ if (!mode) continue;
562
+ if (!(mode.inverted ? !set : set)) open.delete(mode);
563
+ else if (!open.has(mode)) {
564
+ const line = text.slice(0, m.index).split("\n").length;
565
+ open.set(mode, {
566
+ label: mode.label,
567
+ sequence: m[0],
568
+ line,
569
+ index: m.index
570
+ });
571
+ }
572
+ }
573
+ }
574
+ return [...open.values()].sort((a, b) => a.index - b.index).map(({ label, sequence, line }) => ({
575
+ label,
576
+ sequence,
577
+ line
578
+ }));
579
+ }
444
580
  let cached;
445
581
  /** Whether this machine can run a program under a PTY, detected once. */
446
582
  function ptySupport() {
@@ -542,16 +678,52 @@ function cleanPtyOutput(raw, flavor) {
542
678
  }
543
679
  /**
544
680
  * Runs a program with stdin, stdout and stderr on a PTY, an 80x24 window and
545
- * TERM=xterm-256color. stdin is /dev/null behind the PTY: the program reads one
546
- * EOF, and a second read blocks until the timeout.
681
+ * TERM=xterm-256color. Without `input`, stdin is /dev/null behind the PTY: the
682
+ * program reads one EOF, and a second read blocks until the timeout. With it,
683
+ * the terminal's line discipline handles what is typed, so Ctrl-C (\x03) becomes
684
+ * SIGINT for the program, or a keypress if the program turned that off.
547
685
  */
548
- async function runPty(command, args, { timeout, env = {} }) {
686
+ async function runPty(command, args, { timeout, env = {}, input }) {
549
687
  const support = ptySupport();
550
688
  if (!support.ok) throw new Error(`no PTY: ${support.reason}`);
551
689
  const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
552
690
  const pidFile = join(dir, "pid");
691
+ let launcher = "script";
692
+ let argv = ptyArgs(support.flavor, pidFile, command, args);
693
+ let keyboard;
694
+ let inputSentMs;
695
+ let typeTimer;
696
+ let watchTimer;
697
+ const closeKeyboard = () => {
698
+ if (keyboard !== void 0) closeSync(keyboard);
699
+ keyboard = void 0;
700
+ };
701
+ const start = performance.now();
702
+ if (input) {
703
+ const fifo = join(dir, "keyboard");
704
+ execFileSync("mkfifo", [fifo]);
705
+ keyboard = openSync(fifo, constants.O_RDWR);
706
+ argv = [
707
+ "-c",
708
+ "cat -- \"$1\" 2>/dev/null | { shift; exec script \"$@\"; }",
709
+ "sh",
710
+ fifo,
711
+ ...argv
712
+ ];
713
+ launcher = "/bin/sh";
714
+ typeTimer = setTimeout(() => {
715
+ if (programState(pidFile) !== "running") return;
716
+ inputSentMs = Math.round(performance.now() - start);
717
+ if (keyboard !== void 0) writeSync(keyboard, input.data);
718
+ }, input.afterMs);
719
+ watchTimer = setInterval(() => {
720
+ if (programState(pidFile) !== "gone") return;
721
+ clearInterval(watchTimer);
722
+ closeKeyboard();
723
+ }, EXIT_POLL_MS);
724
+ }
553
725
  try {
554
- const result = await run$1("script", ptyArgs(support.flavor, pidFile, command, args), {
726
+ const result = await run$1(launcher, argv, {
555
727
  timeout,
556
728
  env: {
557
729
  TERM: "xterm-256color",
@@ -565,19 +737,50 @@ async function runPty(command, args, { timeout, env = {} }) {
565
737
  exitCode: result.exitCode,
566
738
  timedOut: result.timedOut,
567
739
  ...result.spawnError === void 0 ? {} : { spawnError: result.spawnError },
568
- scriptStderr: result.stderr
740
+ scriptStderr: result.stderr,
741
+ truncated: result.stdoutBytes > result.stdout.length,
742
+ ...inputSentMs === void 0 ? {} : { inputSentMs }
569
743
  };
570
744
  } finally {
745
+ clearTimeout(typeTimer);
746
+ clearInterval(watchTimer);
747
+ closeKeyboard();
571
748
  rmSync(dir, {
572
749
  recursive: true,
573
750
  force: true
574
751
  });
575
752
  }
576
753
  }
577
- function killGroupFromPidFile(pidFile) {
754
+ /** How often to look for the end of a program that is being typed to. */
755
+ const EXIT_POLL_MS = 50;
756
+ function programGroup(pidFile) {
578
757
  try {
579
758
  const pid = Number(readFileSync(pidFile, "utf8").trim());
580
- if (Number.isInteger(pid) && pid > 1) process.kill(-pid, "SIGKILL");
759
+ return Number.isInteger(pid) && pid > 1 ? pid : void 0;
760
+ } catch {
761
+ return;
762
+ }
763
+ }
764
+ /**
765
+ * Whether the program under the PTY has started, is running, or has exited.
766
+ * Asks about the program itself, which script(1) reaps, not its group: a child
767
+ * it left behind can stay a zombie for good where nothing reaps orphans, as in
768
+ * a container without an init process.
769
+ */
770
+ function programState(pidFile) {
771
+ const pid = programGroup(pidFile);
772
+ if (pid === void 0) return "starting";
773
+ try {
774
+ process.kill(pid, 0);
775
+ return "running";
776
+ } catch {
777
+ return "gone";
778
+ }
779
+ }
780
+ function killGroupFromPidFile(pidFile) {
781
+ const pid = programGroup(pidFile);
782
+ try {
783
+ if (pid !== void 0) process.kill(-pid, "SIGKILL");
581
784
  } catch {}
582
785
  }
583
786
  // src/checks/color.ts
@@ -597,10 +800,6 @@ function judgePipe(pipe) {
597
800
  verdict: "error",
598
801
  reason: `could not start: ${pipe.spawnError}`
599
802
  };
600
- if (pipe.timedOut) return {
601
- verdict: "error",
602
- reason: "timed out on a normal run"
603
- };
604
803
  const stdoutHit = findStyle(pipe.stdout.toString("utf8"));
605
804
  if (stdoutHit) return {
606
805
  verdict: "fail",
@@ -613,6 +812,10 @@ function judgePipe(pipe) {
613
812
  reason: "printed color codes to stderr when it was a pipe",
614
813
  evidence: describeHit("stderr", stderrHit)
615
814
  };
815
+ if (pipe.timedOut) return {
816
+ verdict: "skip",
817
+ reason: `${stillRunning(pipe.durationMs)} with no color in a pipe so far; a terminal is compared only for a command that finishes`
818
+ };
616
819
  }
617
820
  function judgeColor(runs) {
618
821
  const fromPipe = judgePipe(runs.pipe);
@@ -652,11 +855,13 @@ function judgeColor(runs) {
652
855
  };
653
856
  }
654
857
  /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
655
- async function colorRuns(command, args, timeout) {
858
+ async function colorRuns(command, args, ctx) {
859
+ const { timeout } = ctx;
656
860
  const pipe = await run$1(command, args, {
657
- timeout,
861
+ timeout: probeTimeout(ctx, command, args),
658
862
  env: COLOR_ENV
659
863
  });
864
+ if (pipe.timedOut) markLongRunning(ctx, command, args);
660
865
  if (judgePipe(pipe)) return { pipe };
661
866
  const support = ptySupport();
662
867
  if (!support.ok) return {
@@ -688,8 +893,8 @@ const summarize = (r) => r ? {
688
893
  timedOut: r.timedOut,
689
894
  styled: findStyle(r.output) !== void 0
690
895
  } : null;
691
- async function color(command, args, timeout) {
692
- const runs = await colorRuns(command, args, timeout);
896
+ async function color(command, args, ctx) {
897
+ const runs = await colorRuns(command, args, ctx);
693
898
  return {
694
899
  check: "color",
695
900
  invocation: [command, ...args],
@@ -709,7 +914,7 @@ const colorCheck = {
709
914
  summary: "prints color codes into pipes, or ignores NO_COLOR in a terminal",
710
915
  async run(target, ctx) {
711
916
  const results = [];
712
- for (const args of target.invocations) results.push(await color(target.command, args, ctx.timeout));
917
+ for (const args of target.invocations) results.push(await color(target.command, args, ctx));
713
918
  return results;
714
919
  }
715
920
  };
@@ -800,6 +1005,37 @@ function expandFixture(args, dir) {
800
1005
  function collapseFixture(text, fixture) {
801
1006
  return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
802
1007
  }
1008
+ /**
1009
+ * Removes the hostile names' dangerous parts from output, for checks other than
1010
+ * control-chars: a lister that prints them raw into a pipe is doing its job, and
1011
+ * control-chars judges how they reach a terminal.
1012
+ */
1013
+ function withoutHostileNames(text) {
1014
+ let out = text;
1015
+ for (const { marker } of HOSTILE_NAMES) out = out.replaceAll(marker, "");
1016
+ return out;
1017
+ }
1018
+ function collapseValue(value, fixture) {
1019
+ if (typeof value === "string") return collapseFixture(value, fixture);
1020
+ if (Array.isArray(value)) return value.map((v) => collapseValue(v, fixture));
1021
+ if (value && typeof value === "object" && !Buffer.isBuffer(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, collapseValue(v, fixture)]));
1022
+ return value;
1023
+ }
1024
+ /** collapseFixture applied to every string in the results: invocation, reason, evidence and data. */
1025
+ function collapseResults(results, fixture) {
1026
+ return results.map((r) => {
1027
+ const data = Object.fromEntries(Object.entries(r).map(([k, v]) => [k, collapseValue(v, fixture)]));
1028
+ const c = (text) => collapseFixture(text, fixture);
1029
+ return {
1030
+ ...data,
1031
+ check: r.check,
1032
+ invocation: r.invocation.map(c),
1033
+ verdict: r.verdict,
1034
+ reason: c(r.reason),
1035
+ ...r.evidence === void 0 ? {} : { evidence: c(r.evidence) }
1036
+ };
1037
+ });
1038
+ }
803
1039
  // src/checks/control-chars.ts
804
1040
  const ENV$1 = {
805
1041
  TERM: "xterm-256color",
@@ -809,7 +1045,7 @@ const ENV$1 = {
809
1045
  function rawNames(output) {
810
1046
  return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
811
1047
  }
812
- const listLabels$1 = (names) => {
1048
+ const listLabels$2 = (names) => {
813
1049
  const labels = names.map((h) => h.label);
814
1050
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
815
1051
  };
@@ -824,17 +1060,13 @@ function judgeControlChars(runs) {
824
1060
  verdict: "error",
825
1061
  reason: `could not start: ${pipe.spawnError}`
826
1062
  };
827
- if (pipe?.timedOut) return {
828
- verdict: "error",
829
- reason: "timed out on a normal run"
830
- };
831
1063
  if (!tty) return {
832
1064
  verdict: "skip",
833
1065
  reason: `no terminal to check with (${runs.noPty ?? "no PTY"})`
834
1066
  };
835
- if (tty.timedOut) return {
1067
+ if (tty.timedOut && !tty.output.includes("plain.txt")) return {
836
1068
  verdict: "skip",
837
- reason: "waited for input in a terminal"
1069
+ reason: "still running in a terminal at the timeout, and had not printed the file names in {fixture}"
838
1070
  };
839
1071
  if (!tty.output.includes("plain.txt")) return {
840
1072
  verdict: "skip",
@@ -850,26 +1082,27 @@ function judgeControlChars(runs) {
850
1082
  const warning = raw.filter((h) => h.severity === "warn");
851
1083
  if (warning.length) return {
852
1084
  verdict: "warn",
853
- reason: `printed ${listLabels$1(warning)} from file names unescaped, which can hide or forge output`,
1085
+ reason: `printed ${listLabels$2(warning)} from file names unescaped, which can hide or forge output`,
854
1086
  evidence: evidenceFor(warning)
855
1087
  };
856
1088
  const noted = raw.filter((h) => h.severity === "note");
857
1089
  return {
858
1090
  verdict: "pass",
859
- reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$1(noted)} as is` : ""}`
1091
+ reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$2(noted)} as is` : ""}`
860
1092
  };
861
1093
  }
862
- async function controlCharsRuns(command, args, fixtureDir, timeout) {
1094
+ async function controlCharsRuns(command, args, fixtureDir, ctx) {
863
1095
  const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
864
1096
  if (!usesFixture) return { usesFixture };
865
1097
  const pipe = await run$1(command, args, {
866
- timeout,
1098
+ timeout: probeTimeout(ctx, command, args),
867
1099
  env: ENV$1
868
1100
  });
869
- if (pipe.spawnError || pipe.timedOut) return {
1101
+ if (pipe.spawnError) return {
870
1102
  usesFixture,
871
1103
  pipe
872
1104
  };
1105
+ if (pipe.timedOut) markLongRunning(ctx, command, args);
873
1106
  const support = ptySupport();
874
1107
  if (!support.ok) return {
875
1108
  usesFixture,
@@ -880,14 +1113,14 @@ async function controlCharsRuns(command, args, fixtureDir, timeout) {
880
1113
  usesFixture,
881
1114
  pipe,
882
1115
  tty: await runPty(command, args, {
883
- timeout,
1116
+ timeout: probeTimeout(ctx, command, args),
884
1117
  env: ENV$1
885
1118
  })
886
1119
  };
887
1120
  }
888
1121
  const kinds = (output) => output === void 0 ? [] : rawNames(output).map((h) => h.kind);
889
- async function controlChars(command, args, fixtureDir, timeout) {
890
- const runs = await controlCharsRuns(command, args, fixtureDir, timeout);
1122
+ async function controlChars(command, args, fixtureDir, ctx) {
1123
+ const runs = await controlCharsRuns(command, args, fixtureDir, ctx);
891
1124
  const pipeOutput = runs.pipe && runs.pipe.stdout.toString("utf8") + runs.pipe.stderr;
892
1125
  return {
893
1126
  check: "control-chars",
@@ -910,7 +1143,7 @@ const controlCharsCheck = {
910
1143
  pipeRaw: []
911
1144
  }];
912
1145
  const results = [];
913
- for (const args of target.invocations) results.push(await controlChars(target.command, args, target.fixtureDir, ctx.timeout));
1146
+ for (const args of target.invocations) results.push(await controlChars(target.command, args, target.fixtureDir, ctx));
914
1147
  return results;
915
1148
  }
916
1149
  };
@@ -987,7 +1220,7 @@ const ctrlCCheck = {
987
1220
  check: "ctrl-c",
988
1221
  invocation: [target.command],
989
1222
  verdict: "skip",
990
- reason: "needs probe args that keep it running, such as a watch or serve command",
1223
+ reason: "needs probe args that keep it running, such as a watch or serve command, or --bare",
991
1224
  sentAfterMs: null,
992
1225
  exitedAfterMs: null,
993
1226
  exitCode: null,
@@ -1006,7 +1239,7 @@ const ENV = {
1006
1239
  CI: void 0
1007
1240
  };
1008
1241
  const kindsOf = (hits) => [...new Set(hits.map((h) => h.kind))];
1009
- function listLabels(kinds) {
1242
+ function listLabels$1(kinds) {
1010
1243
  const labels = kinds.map((k) => CONTROL_LABELS[k]);
1011
1244
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1012
1245
  }
@@ -1015,10 +1248,6 @@ function judgePipeEscapes(r) {
1015
1248
  verdict: "error",
1016
1249
  reason: `could not start: ${r.spawnError}`
1017
1250
  };
1018
- if (r.timedOut) return {
1019
- verdict: "error",
1020
- reason: "timed out on a normal run"
1021
- };
1022
1251
  const stdout = r.stdout.toString("utf8");
1023
1252
  const outHits = findControls(stdout);
1024
1253
  const errHits = findControls(r.stderr);
@@ -1031,23 +1260,36 @@ function judgePipeEscapes(r) {
1031
1260
  };
1032
1261
  if (first) return {
1033
1262
  verdict: "warn",
1034
- reason: `printed terminal control codes into a pipe: ${listLabels([.../* @__PURE__ */ new Set([...kindsOf(outHits), ...kindsOf(errHits)])])}`,
1263
+ reason: `printed terminal control codes into a pipe: ${listLabels$1([.../* @__PURE__ */ new Set([...kindsOf(outHits), ...kindsOf(errHits)])])}`,
1035
1264
  evidence: `${first.stream} line ${first.hit.line}: ${first.hit.text}`
1036
1265
  };
1037
- if (!stdout && !r.stderr) return {
1266
+ if (!stdout && !r.stderr) return r.timedOut ? {
1267
+ verdict: "skip",
1268
+ reason: `${stillRunning(r.durationMs)} and printed nothing so far`
1269
+ } : {
1038
1270
  verdict: "skip",
1039
1271
  reason: "printed nothing, so there is nothing to check"
1040
1272
  };
1273
+ if (r.timedOut) return {
1274
+ verdict: "pass",
1275
+ reason: `no cursor, erase, hyperlink, title or redraw codes in a pipe (${stillRunning(r.durationMs)})`
1276
+ };
1041
1277
  return {
1042
1278
  verdict: "pass",
1043
1279
  reason: "no cursor, erase, hyperlink, title or redraw codes in a pipe"
1044
1280
  };
1045
1281
  }
1046
- async function pipeEscapes(command, args, timeout) {
1047
- const r = await run$1(command, args, {
1048
- timeout,
1282
+ async function pipeEscapes(command, args, ctx, fixture = false) {
1283
+ const raw = await run$1(command, args, {
1284
+ timeout: probeTimeout(ctx, command, args),
1049
1285
  env: ENV
1050
1286
  });
1287
+ if (raw.timedOut) markLongRunning(ctx, command, args);
1288
+ const r = fixture ? {
1289
+ ...raw,
1290
+ stdout: Buffer.from(withoutHostileNames(raw.stdout.toString("utf8"))),
1291
+ stderr: withoutHostileNames(raw.stderr)
1292
+ } : raw;
1051
1293
  return {
1052
1294
  check: "pipe-escapes",
1053
1295
  invocation: [command, ...args],
@@ -1062,7 +1304,114 @@ const pipeEscapesCheck = {
1062
1304
  summary: "prints spinners, cursor codes, hyperlinks or titles into a pipe",
1063
1305
  async run(target, ctx) {
1064
1306
  const results = [];
1065
- for (const args of target.invocations) results.push(await pipeEscapes(target.command, args, ctx.timeout));
1307
+ for (const args of target.invocations) results.push(await pipeEscapes(target.command, args, ctx, target.fixtureDir !== void 0));
1308
+ return results;
1309
+ }
1310
+ };
1311
+ // src/core/which.ts
1312
+ function isExecutableFile(path) {
1313
+ try {
1314
+ accessSync(path, constants.X_OK);
1315
+ return statSync(path).isFile();
1316
+ } catch {
1317
+ return false;
1318
+ }
1319
+ }
1320
+ /**
1321
+ * Where `command` would be found, as spawn() looks for it: a path with a slash
1322
+ * as given, otherwise each PATH entry in turn (an empty entry is the current
1323
+ * directory). Under a PTY, a missing command is only a line of shell output, so
1324
+ * the terminal checks ask first.
1325
+ */
1326
+ function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
1327
+ if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
1328
+ for (const dir of path.split(delimiter)) {
1329
+ const candidate = join(dir || ".", command);
1330
+ if (isExecutableFile(candidate)) return candidate;
1331
+ }
1332
+ }
1333
+ // src/checks/restore.ts
1334
+ function listLabels(modes) {
1335
+ const labels = modes.map((m) => m.label);
1336
+ return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1337
+ }
1338
+ /** What the Ctrl-C key sends to a terminal. */
1339
+ const CTRL_C_KEY = "";
1340
+ const showSequence = (sequence) => sequence.replaceAll("\x1B", "ESC");
1341
+ function judgeRestore(r) {
1342
+ if (r.spawnError) return {
1343
+ verdict: "error",
1344
+ reason: `could not start: ${r.spawnError}`
1345
+ };
1346
+ const interrupted = r.inputSentMs !== void 0;
1347
+ if (r.timedOut) return {
1348
+ verdict: "skip",
1349
+ reason: interrupted ? `still running ${CTRL_C_GRACE_MS / 1e3} s after Ctrl-C, so how it leaves the terminal wasn't seen (REPLs and some full-screen programs quit only on a second Ctrl-C)` : "waited for input in a terminal, so it never finished"
1350
+ };
1351
+ if (r.truncated) return {
1352
+ verdict: "skip",
1353
+ reason: "printed more than 1 MiB in a terminal, so the end of its output, where it would restore the terminal, was not kept"
1354
+ };
1355
+ const when = interrupted ? "after Ctrl-C" : "when it exited";
1356
+ const open = findOpenModes(r.output);
1357
+ if (open.length > 0) return {
1358
+ verdict: "warn",
1359
+ reason: `left the terminal with ${listLabels(open)} ${when}`,
1360
+ evidence: open.map((m) => `${showSequence(m.sequence)} on line ${m.line}, never undone`).join("; ")
1361
+ };
1362
+ return {
1363
+ verdict: "pass",
1364
+ reason: `left no terminal mode switched on ${when}`
1365
+ };
1366
+ }
1367
+ async function restore(command, args, { timeout, interrupt }) {
1368
+ const r = await runPty(command, args, {
1369
+ timeout: interrupt ? 4e3 : timeout,
1370
+ ...interrupt ? { input: {
1371
+ data: CTRL_C_KEY,
1372
+ afterMs: CTRL_C_DELAY_MS
1373
+ } } : {}
1374
+ });
1375
+ const judgement = judgeRestore(r);
1376
+ return {
1377
+ check: "restore",
1378
+ invocation: [command, ...args],
1379
+ ...judgement,
1380
+ interrupted: r.inputSentMs !== void 0,
1381
+ openModes: judgement.verdict === "warn" ? findOpenModes(r.output) : []
1382
+ };
1383
+ }
1384
+ const restoreCheck = {
1385
+ name: "restore",
1386
+ kind: "check",
1387
+ summary: "leaves the cursor hidden, the alternate screen or mouse mode on after Ctrl-C",
1388
+ async run(target, ctx) {
1389
+ const support = ptySupport();
1390
+ const notRun = findCommand(target.command) === void 0 ? {
1391
+ verdict: "error",
1392
+ reason: "could not start: command not found"
1393
+ } : support.ok ? void 0 : {
1394
+ verdict: "skip",
1395
+ reason: `needs a terminal (${support.reason})`
1396
+ };
1397
+ const results = [];
1398
+ for (const args of target.invocations) {
1399
+ if (notRun) {
1400
+ const result = {
1401
+ check: "restore",
1402
+ invocation: [target.command, ...args],
1403
+ ...notRun,
1404
+ interrupted: false,
1405
+ openModes: []
1406
+ };
1407
+ results.push(result);
1408
+ continue;
1409
+ }
1410
+ results.push(await restore(target.command, args, {
1411
+ timeout: ctx.timeout,
1412
+ interrupt: target.explicit
1413
+ }));
1414
+ }
1066
1415
  return results;
1067
1416
  }
1068
1417
  };
@@ -1187,7 +1536,8 @@ function judgeStdin(runs, defaultProbe) {
1187
1536
  }
1188
1537
  async function stdinRuns(command, args, timeout) {
1189
1538
  const closed = await run$1(command, args, { timeout });
1190
- if (closed.spawnError || closed.timedOut) return { closed };
1539
+ if (closed.timedOut) return { closed };
1540
+ if (closed.spawnError) return { closed };
1191
1541
  const open = await run$1(command, args, {
1192
1542
  timeout: STDIN_WAIT_MS,
1193
1543
  stdin: "open"
@@ -1205,8 +1555,18 @@ async function stdinRuns(command, args, timeout) {
1205
1555
  })
1206
1556
  };
1207
1557
  }
1208
- async function stdinCheck(command, args, defaultProbe, timeout) {
1209
- const runs = await stdinRuns(command, args, timeout);
1558
+ async function stdinCheck(command, args, defaultProbe, ctx) {
1559
+ if (isLongRunning(ctx, command, args)) return {
1560
+ check: "stdin",
1561
+ invocation: [command, ...args],
1562
+ verdict: "skip",
1563
+ reason: "keeps running even with stdin closed, so stdin isn't what it waits for",
1564
+ closedMs: null,
1565
+ waitedForStdin: false,
1566
+ finishedAfterCloseMs: null
1567
+ };
1568
+ const runs = await stdinRuns(command, args, ctx.timeout);
1569
+ if (runs.closed.timedOut) markLongRunning(ctx, command, args);
1210
1570
  const proven = runs.open?.timedOut === true && runs.closing !== void 0 && !runs.closing.timedOut;
1211
1571
  return {
1212
1572
  check: "stdin",
@@ -1229,11 +1589,12 @@ const CHECKS = [
1229
1589
  summary: "waits for stdin when it is an open pipe, as agents and CI runners leave it",
1230
1590
  async run(target, ctx) {
1231
1591
  const results = [];
1232
- for (const args of target.invocations) results.push(await stdinCheck(target.command, args, !target.explicit, ctx.timeout));
1592
+ for (const args of target.invocations) results.push(await stdinCheck(target.command, args, !target.explicit, ctx));
1233
1593
  return results;
1234
1594
  }
1235
1595
  },
1236
1596
  ctrlCCheck,
1597
+ restoreCheck,
1237
1598
  controlCharsCheck,
1238
1599
  startupCheck,
1239
1600
  baselineCheck
@@ -1275,6 +1636,18 @@ function safe(text) {
1275
1636
  function safeJson(value) {
1276
1637
  return JSON.stringify(value, null, 2).replace(JSON_UNSAFE, (c) => `\\u${hex(c, 4)}`);
1277
1638
  }
1639
+ // src/core/quote.ts
1640
+ /** Characters a POSIX shell takes literally in a word; `{fixture}` stays readable. */
1641
+ const PLAIN = /^[\w@%+=:,./{}-]+$/;
1642
+ /**
1643
+ * Joins a command and its arguments the way you would type them in a shell,
1644
+ * single-quoting any argument with spaces, quotes or other special characters,
1645
+ * so `python3 -c 'import time; time.sleep(30)'` doesn't read as five words.
1646
+ * Only for display: cliprobe never runs a shell.
1647
+ */
1648
+ function shellJoin(args) {
1649
+ return args.map((a) => PLAIN.test(a) ? a : `'${a.replaceAll("'", `'\\''`)}'`).join(" ");
1650
+ }
1278
1651
  // src/report/summary.ts
1279
1652
  function countVerdicts(results) {
1280
1653
  const counts = {
@@ -1308,14 +1681,14 @@ function formatHuman({ version, command, checks, results }, { color }) {
1308
1681
  const label = verdict.toUpperCase().padEnd(5);
1309
1682
  return color ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
1310
1683
  };
1311
- const width = Math.max(0, ...results.map((r) => safe(r.invocation.join(" ")).length));
1684
+ const width = Math.max(0, ...results.map((r) => safe(shellJoin(r.invocation)).length));
1312
1685
  const noun = checks.length === 1 ? "check" : "checks";
1313
1686
  const lines = [`cliprobe ${version}: ${checks.join(", ")} ${noun} for ${safe(command)}`];
1314
1687
  for (const check of checks) {
1315
1688
  lines.push("");
1316
1689
  if (checks.length > 1) lines.push(check);
1317
1690
  for (const r of results.filter((result) => result.check === check)) {
1318
- lines.push(` ${paint(r.verdict)} ${safe(r.invocation.join(" ")).padEnd(width)} ${r.reason}`);
1691
+ lines.push(` ${paint(r.verdict)} ${safe(shellJoin(r.invocation)).padEnd(width)} ${r.reason}`);
1319
1692
  if (r.evidence) lines.push(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
1320
1693
  }
1321
1694
  }
@@ -1354,7 +1727,7 @@ function totals(results) {
1354
1727
  return `tests="${results.length}" failures="${c.fail}" errors="${c.error}" skipped="${c.skip}"`;
1355
1728
  }
1356
1729
  function testcase(r) {
1357
- const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(r.invocation.join(" "))}"`;
1730
+ const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(shellJoin(r.invocation))}"`;
1358
1731
  const message = `message="${xml(r.reason)}"`;
1359
1732
  const body = r.evidence ? xml(r.evidence) : "";
1360
1733
  switch (r.verdict) {
@@ -1411,7 +1784,7 @@ function row(r) {
1411
1784
  return `| ${[
1412
1785
  prose(r.check),
1413
1786
  verdict,
1414
- code(r.invocation.join(" "), { inTable: true }),
1787
+ code(shellJoin(r.invocation), { inTable: true }),
1415
1788
  prose(r.reason) + evidence
1416
1789
  ].join(" | ")} |`;
1417
1790
  }
@@ -1481,6 +1854,7 @@ function parseArgs(argv) {
1481
1854
  format: "human",
1482
1855
  outputFile: void 0,
1483
1856
  timeout: 15e3,
1857
+ bare: false,
1484
1858
  help: false,
1485
1859
  version: false,
1486
1860
  checks: [],
@@ -1494,6 +1868,7 @@ function parseArgs(argv) {
1494
1868
  break;
1495
1869
  }
1496
1870
  if (a === "--json") opts.format = "json";
1871
+ else if (a === "--bare") opts.bare = true;
1497
1872
  else if (a === "-o" || a === "--output-file" || a.startsWith("--output-file=")) {
1498
1873
  const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
1499
1874
  if (!value) throw new UsageError(`${a.split("=")[0] ?? a} needs a file path`);
@@ -1518,6 +1893,7 @@ function parseArgs(argv) {
1518
1893
  break;
1519
1894
  }
1520
1895
  }
1896
+ if (opts.bare && opts.args.length) throw new UsageError("--bare probes the command with no arguments, so give none after it");
1521
1897
  return opts;
1522
1898
  }
1523
1899
  // src/cli/help.ts
@@ -1527,9 +1903,10 @@ Usage:
1527
1903
  cliprobe [options] -- <command> [args...]
1528
1904
 
1529
1905
  With no args after <command>, cliprobe probes "<command> --version" and
1530
- "<command> --help". With args, it probes exactly that invocation. An argument
1531
- containing {fixture} gets the path of a temporary directory of file names with
1532
- control characters in them, for the control-chars check.
1906
+ "<command> --help". With args, it probes exactly that invocation; with --bare,
1907
+ the command alone. An argument containing {fixture} gets the path of a
1908
+ temporary directory of file names with control characters in them, for the
1909
+ control-chars check.
1533
1910
 
1534
1911
  Checks:
1535
1912
  closed-pipe Runs the command with stdout already closed, as when output is
@@ -1550,6 +1927,11 @@ Checks:
1550
1927
  running 3 s later or prints a stack trace; warns if it exits 0.
1551
1928
  Skipped when the command finishes first, so probe a command
1552
1929
  that keeps running (a watcher, a server, a long task).
1930
+ restore Runs the command under a terminal and, for your own probes,
1931
+ types Ctrl-C after 1 s, as a person would. Warns if it leaves
1932
+ the cursor hidden, the alternate screen, mouse or focus
1933
+ reporting, bracketed paste or line wrapping off, which breaks
1934
+ the shell it returns to.
1553
1935
  control-chars Runs the command under a terminal with {fixture} replaced by a
1554
1936
  directory of file names holding escape sequences, a carriage
1555
1937
  return, a newline and more. Fails if an escape sequence reaches
@@ -1565,6 +1947,8 @@ Info checks (never fail; run only when named with --check):
1565
1947
  flags runs its default action, cut off after 5 s.
1566
1948
 
1567
1949
  Options:
1950
+ --bare Probe the command with no arguments (a REPL, a full-screen
1951
+ program, a server) instead of --version and --help
1568
1952
  --check <name> Run only this check; repeat it or use commas for several
1569
1953
  --format <name> Output format: human (default), json, markdown (a CI job
1570
1954
  summary or PR comment) or junit (XML for CI test reports)
@@ -1572,13 +1956,16 @@ Options:
1572
1956
  -o, --output-file <path>
1573
1957
  Write the --format report to a file (created atomically,
1574
1958
  with parent folders); the human report still prints
1575
- --timeout <ms> Kill a probe after this long (default 15000)
1959
+ --timeout <ms> Kill a probe after this long (default 15000). A command
1960
+ still running then (a server, a watcher) is judged on
1961
+ what it did so far, and later checks watch it for 3 s
1576
1962
  -h, --help Show this help
1577
1963
  -v, --version Show the version
1578
1964
 
1579
1965
  Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
1580
- Runs the target in the current directory without a shell, with stdin closed,
1581
- a temporary HOME and a minimal environment. Only run programs you trust.`;
1966
+ Runs the target in the current directory without a shell, with stdin closed
1967
+ (the stdin check uses a pipe it never writes to), a temporary HOME and a
1968
+ minimal environment. Only run programs you trust.`;
1582
1969
  // src/cli/program.ts
1583
1970
  /** 0 no failures, 1 a check failed, 2 nothing could be judged because something could not run. */
1584
1971
  function exitCodeFor(results) {
@@ -1620,38 +2007,45 @@ async function run(argv, io) {
1620
2007
  err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
1621
2008
  return 2;
1622
2009
  }
1623
- const invocations = opts.args.length ? [opts.args] : [["--version"], ["--help"]];
2010
+ if (findCommand(opts.command) === void 0) {
2011
+ err(`cliprobe: command not found: ${safe(opts.command)}\n`);
2012
+ return 2;
2013
+ }
2014
+ const invocations = opts.bare ? [[]] : opts.args.length ? [opts.args] : [["--version"], ["--help"]];
1624
2015
  const fixture = usesFixture(opts.args) ? createFixture() : void 0;
1625
2016
  const results = [];
1626
2017
  try {
1627
2018
  const target = {
1628
2019
  command: opts.command,
1629
- explicit: opts.args.length > 0,
2020
+ explicit: opts.bare || opts.args.length > 0,
1630
2021
  invocations: fixture ? invocations.map((a) => expandFixture(a, fixture.dir)) : invocations,
1631
2022
  ...fixture ? { fixtureDir: fixture.dir } : {}
1632
2023
  };
1633
- for (const check of checks) results.push(...await check.run(target, { timeout: opts.timeout }));
2024
+ const ctx = {
2025
+ timeout: opts.timeout,
2026
+ longRunning: /* @__PURE__ */ new Set()
2027
+ };
2028
+ for (const check of checks) results.push(...await check.run(target, ctx));
1634
2029
  } finally {
1635
2030
  fixture?.cleanup();
1636
2031
  }
1637
- const collapse = (text) => fixture ? collapseFixture(text, fixture) : text;
1638
2032
  const report = {
1639
2033
  version: VERSION,
1640
2034
  command: opts.command,
1641
2035
  checks: checks.map((c) => c.name),
1642
- results
2036
+ results: fixture ? collapseResults(results, fixture) : results
1643
2037
  };
1644
2038
  const { color } = io;
1645
2039
  if (opts.outputFile) {
1646
2040
  try {
1647
- writeReportFile(opts.outputFile, collapse(FORMATS[opts.format](report, { color: false })));
2041
+ writeReportFile(opts.outputFile, FORMATS[opts.format](report, { color: false }));
1648
2042
  } catch (error) {
1649
2043
  const reason = error instanceof Error ? error.message : String(error);
1650
2044
  err(`cliprobe: could not write ${safe(opts.outputFile)}: ${safe(reason)}\n`);
1651
2045
  return 2;
1652
2046
  }
1653
- out(collapse(FORMATS.human(report, { color })));
1654
- } else out(collapse(FORMATS[opts.format](report, { color })));
2047
+ out(FORMATS.human(report, { color }));
2048
+ } else out(FORMATS[opts.format](report, { color }));
1655
2049
  return exitCodeFor(results);
1656
2050
  }
1657
2051
  // src/cli/main.ts
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "0.4.1",
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, and control characters from file names reaching your terminal.",
3
+ "version": "0.6.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.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "cliprobe": "dist/cli.js"
@@ -41,7 +41,9 @@
41
41
  "terminal-injection",
42
42
  "pty",
43
43
  "stdin",
44
- "hang"
44
+ "hang",
45
+ "cursor",
46
+ "tui"
45
47
  ],
46
48
  "author": {
47
49
  "name": "Khaled Saeed",