cliprobe 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Khaled Saeed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # cliprobe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Black-box tests any command-line program for terminal-edge bugs: the ones that only show up when output is piped, cut short, or read by a script or an AI agent.
4
+
5
+ ```sh
6
+ npx cliprobe -- esbuild
7
+ ```
8
+
9
+ ```
10
+ cliprobe 0.0.1: closed-pipe check for esbuild
11
+
12
+ FAIL esbuild --version crashed when stdout was closed (exit 0 -> 1)
13
+ Error: Command failed: .../esbuild --version (at node_modules/esbuild/bin/esbuild:222:28)
14
+ FAIL esbuild --help crashed when stdout was closed (exit 0 -> 1)
15
+ Error: Command failed: .../esbuild --help (at node_modules/esbuild/bin/esbuild:222:28)
16
+
17
+ 2 failed, 0 warned, 0 passed, 0 skipped
18
+ ```
19
+
20
+ ## Why
21
+
22
+ 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.
23
+
24
+ In a census of the 100 most-downloaded npm packages that ship a command, **8 crashed this way every time**: esbuild, browserslist, update-browserslist-db, autoprefixer, husky, tsconfck, ts-jest and rolldown. The best-known existing CLI auditor rated all 8 as passing its SIGPIPE check.
25
+
26
+ ## Usage
27
+
28
+ ```sh
29
+ npx cliprobe -- <command> # probes "<command> --version" and "<command> --help"
30
+ npx cliprobe -- <command> [args...] # probes exactly this invocation
31
+ npx cliprobe -- node ./dist/cli.js list # test your own CLI before publishing
32
+ npx cliprobe --json -- <command> # machine-readable results
33
+ ```
34
+
35
+ | Option | Meaning |
36
+ |---|---|
37
+ | `--json` | Print results as JSON |
38
+ | `--timeout <ms>` | Kill a probe after this long (default 15000) |
39
+ | `-h`, `--help` | Show help |
40
+ | `-v`, `--version` | Show the version |
41
+
42
+ 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.
43
+
44
+ ## Checks
45
+
46
+ **closed-pipe** (0.0.1). 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:
47
+
48
+ | Verdict | Meaning |
49
+ |---|---|
50
+ | `PASS` | Exited quietly, or was stopped by SIGPIPE (the Unix convention) |
51
+ | `FAIL` | Printed an EPIPE error or stack trace and changed its exit code, or hung |
52
+ | `WARN` | Printed a write error but kept its exit code |
53
+ | `SKIP` | Wrote nothing to stdout for this invocation, so pass args that print something |
54
+
55
+ Planned next: color handling under a real terminal vs a pipe vs `NO_COLOR`, Ctrl-C behavior, control characters in output, and startup time.
56
+
57
+ ## Fixing a failure in a Node.js CLI
58
+
59
+ Handle `EPIPE` on stdout once, near your entry point:
60
+
61
+ ```js
62
+ process.stdout.on("error", (error) => {
63
+ if (error.code === "EPIPE") process.exit(0);
64
+ throw error;
65
+ });
66
+ ```
67
+
68
+ ## Safety
69
+
70
+ cliprobe runs the target in your current directory without a shell, with stdin closed, a temporary `HOME`, and a minimal environment (no tokens from your shell). It still executes the program, so only probe programs you trust. macOS and Linux only for now.
71
+
72
+ ## License
73
+
74
+ MIT
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env node
2
+ // cliprobe: black-box tests a command-line program for terminal-edge bugs.
3
+ // 0.0.1 ships one check: does the program crash when its stdout is closed?
4
+ import { spawn, execFileSync } from "node:child_process";
5
+ import { closeSync, constants, mkdtempSync, openSync, readFileSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
10
+ const STDERR_CAP = 64 * 1024;
11
+ // Signs that a program reported a write failure or crashed with a stack trace.
12
+ const ERROR_RE = /EPIPE|broken ?pipe|BrokenPipeError|Unhandled 'error' event|^\s+at .+:\d+:\d+\)?$/im;
13
+
14
+ const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
15
+
16
+ Usage:
17
+ cliprobe [options] -- <command> [args...]
18
+
19
+ With no args after <command>, cliprobe probes "<command> --version" and
20
+ "<command> --help". With args, it probes exactly that invocation.
21
+
22
+ Checks (0.0.1):
23
+ closed-pipe Runs the command with stdout already closed, as when output is
24
+ piped into a reader that quits early (head, grep -q, an agent).
25
+ A well-behaved program exits quietly; a buggy one crashes with
26
+ an EPIPE error and a stack trace.
27
+
28
+ Options:
29
+ --json Print results as JSON
30
+ --timeout <ms> Kill a probe after this long (default 15000)
31
+ -h, --help Show this help
32
+ -v, --version Show the version
33
+
34
+ Exit codes: 0 no failures, 1 a check failed, 2 usage error or could not run.
35
+ Runs the target in the current directory without a shell, with stdin closed,
36
+ a temporary HOME and a minimal environment. Only run programs you trust.`;
37
+
38
+ function parseArgs(argv) {
39
+ const opts = { json: false, timeout: 15000, command: null, args: [] };
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const a = argv[i];
42
+ if (a === "--") {
43
+ [opts.command, ...opts.args] = argv.slice(i + 1);
44
+ break;
45
+ }
46
+ if (a === "--json") opts.json = true;
47
+ else if (a === "-h" || a === "--help") opts.help = true;
48
+ else if (a === "-v" || a === "--version") opts.version = true;
49
+ else if (a === "--timeout" || a.startsWith("--timeout=")) {
50
+ const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[++i];
51
+ opts.timeout = Number(value);
52
+ if (!Number.isInteger(opts.timeout) || opts.timeout <= 0) throw new UsageError(`--timeout needs a positive whole number of milliseconds, got "${value}"`);
53
+ } else if (a.startsWith("-")) throw new UsageError(`unknown option "${a}"`);
54
+ else {
55
+ // No "--": the first bare argument starts the command.
56
+ [opts.command, ...opts.args] = argv.slice(i);
57
+ break;
58
+ }
59
+ }
60
+ return opts;
61
+ }
62
+
63
+ class UsageError extends Error {}
64
+
65
+ /** Escapes control characters so a target's output cannot drive our terminal. */
66
+ function safe(text) {
67
+ return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
68
+ }
69
+
70
+ function sandbox() {
71
+ const dir = mkdtempSync(join(tmpdir(), "cliprobe-"));
72
+ const env = {
73
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
74
+ LANG: process.env.LANG ?? "C.UTF-8",
75
+ HOME: dir,
76
+ TMPDIR: dir,
77
+ TERM: "dumb",
78
+ CI: "1",
79
+ NO_UPDATE_NOTIFIER: "1",
80
+ };
81
+ return { dir, env };
82
+ }
83
+
84
+ /**
85
+ * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
86
+ * whose read end is closed before the program starts, so its first write to
87
+ * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
88
+ */
89
+ function run(command, args, { closedStdout, timeout }) {
90
+ const { dir, env } = sandbox();
91
+ let stdoutFd = "pipe";
92
+ if (closedStdout) {
93
+ const fifo = join(dir, "stdout.fifo");
94
+ execFileSync("mkfifo", [fifo]);
95
+ const reader = openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK);
96
+ stdoutFd = openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK);
97
+ closeSync(reader);
98
+ }
99
+
100
+ return new Promise((resolve) => {
101
+ let stdoutBytes = 0;
102
+ let stderr = "";
103
+ let timedOut = false;
104
+ let child;
105
+ let finished = false;
106
+ // A failed spawn emits both "error" and "close"; clean up and resolve once.
107
+ const finish = (result) => {
108
+ if (finished) return;
109
+ finished = true;
110
+ if (typeof stdoutFd === "number") closeSync(stdoutFd);
111
+ rmSync(dir, { recursive: true, force: true });
112
+ resolve({ stdoutBytes, stderr, timedOut, ...result });
113
+ };
114
+ try {
115
+ // Runs in the caller's directory, as if typed there, so relative paths such as
116
+ // `node ./dist/cli.js` work. HOME and TMPDIR point at a throwaway directory.
117
+ child = spawn(command, args, { env, stdio: ["ignore", stdoutFd, "pipe"], detached: true });
118
+ } catch (error) {
119
+ return finish({ spawnError: error.message });
120
+ }
121
+ const timer = setTimeout(() => {
122
+ timedOut = true;
123
+ try { process.kill(-child.pid, "SIGKILL"); } catch {}
124
+ }, timeout);
125
+ child.stdout?.on("data", (chunk) => { stdoutBytes += chunk.length; });
126
+ child.stderr.on("data", (chunk) => { if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8"); });
127
+ child.on("error", (error) => { clearTimeout(timer); finish({ spawnError: error.message }); });
128
+ child.on("close", (exitCode, signal) => { clearTimeout(timer); finish({ exitCode, signal }); });
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Picks the most useful evidence from a crash: the error message plus the first
134
+ * stack frame in the program's own code (not Node internals), which usually
135
+ * points at the unguarded write.
136
+ */
137
+ function crashEvidence(stderr) {
138
+ const lines = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
139
+ const message = lines.find((l) => /^(\w*Error\b|panic:)/.test(l)) ?? lines.find((l) => ERROR_RE.test(l)) ?? lines[0] ?? "";
140
+ const frame = lines.find((l) => l.startsWith("at ") && !/\bnode:/.test(l))?.match(/(?:file:\/\/)?(\/[^\s()]+:\d+:\d+)/)?.[1];
141
+ if (!frame) return message;
142
+ const cwd = process.cwd() + "/";
143
+ return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
144
+ }
145
+
146
+ function judge(base, closed) {
147
+ if (base.spawnError) return { verdict: "error", reason: `could not start: ${base.spawnError}` };
148
+ if (base.timedOut) return { verdict: "error", reason: "timed out on a normal run" };
149
+ if (base.stdoutBytes === 0) return { verdict: "skip", reason: "wrote nothing to stdout, so a closed stdout is never touched" };
150
+ if (closed.timedOut) return { verdict: "fail", reason: "hung after stdout was closed" };
151
+ if (closed.signal === "SIGPIPE") return { verdict: "pass", reason: "stopped by SIGPIPE, the conventional exit" };
152
+ const newError = ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
153
+ if (newError && closed.exitCode !== base.exitCode) {
154
+ return { verdict: "fail", reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`, evidence: crashEvidence(closed.stderr) };
155
+ }
156
+ if (newError) return { verdict: "warn", reason: "printed a write error but kept its exit code", evidence: crashEvidence(closed.stderr) };
157
+ if (closed.exitCode !== base.exitCode) return { verdict: "pass", reason: `exited quietly with code ${closed.exitCode}` };
158
+ return { verdict: "pass", reason: "exited quietly" };
159
+ }
160
+
161
+ async function probe(command, args, timeout) {
162
+ const base = await run(command, args, { closedStdout: false, timeout });
163
+ const closed = await run(command, args, { closedStdout: true, timeout });
164
+ return {
165
+ check: "closed-pipe",
166
+ invocation: [command, ...args],
167
+ ...judge(base, closed),
168
+ baseline: { exitCode: base.exitCode ?? null, signal: base.signal ?? null, stdoutBytes: base.stdoutBytes },
169
+ closed: { exitCode: closed.exitCode ?? null, signal: closed.signal ?? null, timedOut: closed.timedOut, stderr: closed.stderr.slice(-2000) },
170
+ };
171
+ }
172
+
173
+ const COLORS = { pass: 32, fail: 31, warn: 33, skip: 90, error: 35 };
174
+
175
+ function printHuman(command, results, useColor) {
176
+ const paint = (verdict) => {
177
+ const label = verdict.toUpperCase().padEnd(5);
178
+ return useColor ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
179
+ };
180
+ const width = Math.max(...results.map((r) => safe(r.invocation.join(" ")).length));
181
+ console.log(`cliprobe ${VERSION}: closed-pipe check for ${safe(command)}\n`);
182
+ for (const r of results) {
183
+ console.log(` ${paint(r.verdict)} ${safe(r.invocation.join(" ")).padEnd(width)} ${r.reason}`);
184
+ if (r.evidence) console.log(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
185
+ }
186
+ const count = (v) => results.filter((r) => r.verdict === v).length;
187
+ console.log(`\n${count("fail")} failed, ${count("warn")} warned, ${count("pass")} passed, ${count("skip")} skipped${count("error") ? `, ${count("error")} could not run` : ""}`);
188
+ }
189
+
190
+ async function main() {
191
+ let opts;
192
+ try {
193
+ opts = parseArgs(process.argv.slice(2));
194
+ } catch (error) {
195
+ if (!(error instanceof UsageError)) throw error;
196
+ console.error(`cliprobe: ${error.message}\nRun "cliprobe --help" for usage.`);
197
+ return 2;
198
+ }
199
+ if (opts.help) { console.log(HELP); return 0; }
200
+ if (opts.version) { console.log(VERSION); return 0; }
201
+ if (!opts.command) { console.error(`cliprobe: no command given\nUsage: cliprobe [options] -- <command> [args...]`); return 2; }
202
+ if (process.platform === "win32") { console.error("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo)."); return 2; }
203
+
204
+ const invocations = opts.args.length ? [opts.args] : [["--version"], ["--help"]];
205
+ const results = [];
206
+ for (const args of invocations) results.push(await probe(opts.command, args, opts.timeout));
207
+
208
+ if (opts.json) {
209
+ console.log(JSON.stringify({ tool: "cliprobe", version: VERSION, command: opts.command, results }, null, 2));
210
+ } else {
211
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
212
+ printHuman(opts.command, results, useColor);
213
+ }
214
+ if (results.some((r) => r.verdict === "fail")) return 1;
215
+ if (results.every((r) => r.verdict === "error")) return 2;
216
+ return 0;
217
+ }
218
+
219
+ // cliprobe practises what it checks: a closed stdout ends it quietly.
220
+ process.stdout.on("error", (error) => {
221
+ if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
222
+ throw error;
223
+ });
224
+
225
+ process.exitCode = await main();
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Black-box test any command-line program for terminal-edge bugs. 0.0.1 checks whether it crashes when its stdout is closed early (| head, grep -q, agents).",
5
+ "type": "module",
6
+ "bin": {
7
+ "cliprobe": "bin/cliprobe.js"
8
+ },
9
+ "files": [
10
+ "bin"
11
+ ],
12
+ "scripts": {
13
+ "test": "node --test test/*.test.js"
14
+ },
15
+ "keywords": [
16
+ "cli",
17
+ "testing",
18
+ "epipe",
19
+ "sigpipe",
20
+ "broken-pipe",
21
+ "black-box",
22
+ "conformance",
23
+ "terminal",
24
+ "agent-ready"
25
+ ],
26
+ "author": {
27
+ "name": "Khaled Saeed",
28
+ "url": "https://github.com/KhaledSaeed18"
29
+ },
30
+ "license": "MIT",
31
+ "engines": {
32
+ "node": ">=22.12.0"
33
+ },
34
+ "os": [
35
+ "darwin",
36
+ "linux"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/KhaledSaeed18/cliprobe.git"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/KhaledSaeed18/cliprobe/issues"
44
+ },
45
+ "homepage": "https://github.com/KhaledSaeed18/cliprobe#readme"
46
+ }