debabble 0.0.0 → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bret Perry
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,5 +1,190 @@
1
1
  # debabble
2
2
 
3
- This name is held for an upcoming tool that keeps noisy command output out of a coding agent's context. It saves the full log to a file and prints a one-line result.
3
+ Run a command with its whole output in a log file. When it passes, you get one line. When it fails,
4
+ you get an excerpt: the lines that name the failure, and the end of the output.
4
5
 
5
- There is nothing to install yet. The first real release will replace this placeholder.
6
+ ```
7
+ $ debabble -- pnpm test
8
+ log: …/debabble/app-3f2a/20261121-142201-pnpm-test.log
9
+ ✓ pnpm test · 41.2s · log: …/debabble/app-3f2a/20261121-142201-pnpm-test.log
10
+ ```
11
+
12
+ ## Why
13
+
14
+ A test run or a build prints thousands of lines and one of them matters. Piping to `tail` hides a
15
+ failure that is not at the end, and `tee` loses order and bytes. debabble hands the command a log
16
+ file as stdout and stderr, so every byte lands in order, and reads the file afterwards.
17
+
18
+ ## Use
19
+
20
+ ```
21
+ debabble [--show verdict|excerpt] [--timeout <dur>] [--label <name>] [--log-dir <path>] -- <cmd> [args…]
22
+ ```
23
+
24
+ - `--` is required. The command runs with the arguments you gave, with no shell.
25
+ - `--show excerpt` is for log readers (`gh run view --log`): a green run still lists its failure-shaped lines.
26
+ - `--timeout 30m` (default 30m; `90s`, `1500ms`, `2h`; a bare number is seconds). The whole process tree is stopped.
27
+ - Green lines also name the first warning and the first error-shaped line in the log, if any.
28
+ - The first line printed is always `log: <path>`, so a reader that only sees a backgrounded run's start still has the path.
29
+
30
+ Exit codes: the command's own; `128+n` when signal `n` ended it (also when debabble is killed;
31
+ it stops the command's tree and prints the log path first); `124` timed out; `125` usage error;
32
+ `126` / `127` the command cannot run / was not found.
33
+
34
+ When debabble is killed during a passthrough (`DEBABBLE=off` or CI), it first sends the same signal to the
35
+ command and everything it started, so the command can shut down as it would without debabble (Ctrl-C
36
+ cleanup, a CI cancel). Whatever is still running after 5 seconds (`DEBABBLE_KILL_GRACE_MS`), or at a
37
+ second signal, is stopped.
38
+
39
+ | Variable | Effect |
40
+ |---|---|
41
+ | `DEBABBLE=off` | Pass output straight through. The exit code stays exact. |
42
+ | `DEBABBLE_LOG_DIR` | Where logs go (default `$XDG_STATE_HOME/debabble`, else `~/.local/state/debabble`). |
43
+ | `DEBABBLE_TIMEOUT_MS` | Default timeout in milliseconds. |
44
+ | `DEBABBLE_KILL_GRACE_MS` | How long a killed passthrough's command has to exit before it is stopped (default 5000). |
45
+ | `CI`, `GITHUB_ACTIONS` | Pass output straight through (the CI log is the record there). |
46
+
47
+ Library: `import { run, scan, excerpt } from "debabble"`.
48
+
49
+ ## Claude Code hook
50
+
51
+ ```
52
+ debabble hook claude [--list <file>]
53
+ ```
54
+
55
+ A PreToolUse hook on `Bash` that rewrites a noisy command to `debabble -- <the same line>`, so the
56
+ agent reads one line instead of the whole output. Settings entry: `{"type": "command", "command":
57
+ "debabble hook claude --list <file>", "timeout": 5}` under `PreToolUse` with matcher `Bash`.
58
+
59
+ It rewrites only when all of these hold; otherwise it prints nothing and the command runs as written:
60
+
61
+ - The line is one simple command: no `;`, `&&`, `||`, `|`, `&`, redirection, subshell, heredoc,
62
+ `$(…)`, backticks, newline, comment, or leading `VAR=value`. Quoted operators are fine.
63
+ It starts with a program, not a shell builtin or keyword (`cd`, `time`, `export`, `source`, `exec`, …).
64
+ - Its first words match an entry in the list file, and it is not already a `debabble` line.
65
+ - `DEBABBLE` is not `off`, and the call is not `run_in_background`.
66
+ - `bouncer` (shell-bouncer) and `debabble` are on `PATH`, each at or past its version in `requires`
67
+ (read from the package's `package.json`, else from `<bin> --version` within 1 second).
68
+ A list without both pins never rewrites.
69
+ - An allow rule in your user settings (`~/.claude/settings.json`, or `$CLAUDE_CONFIG_DIR/settings.json`),
70
+ the project's `.claude/settings.json` or a `.claude/settings.local.json` (in the project folder, the repo root,
71
+ or a worktree's main checkout) matches the rewritten line (for example `Bash(debabble -- pnpm test:*)`),
72
+ and no deny or ask rule in those files or in the managed settings files matches either the rewritten or the original line.
73
+ Claude Code checks allow rules against the rewritten line, so without that mirror the call would be refused.
74
+ - The hook can read every place a deny or ask rule could come from. Claude Code checks its rules against the
75
+ rewritten line only, so a deny the hook can't see, such as `Bash(git push:*)`, would not match
76
+ `debabble -- git push …`, and the push would run. So the hook never rewrites when any of these is true:
77
+ - The `claude` running the hook, or a process between it and the hook, was started with a flag that brings settings,
78
+ rules, agents, plugins or a permission judge: `--settings`, `--managed-settings`, `--client-data-url`, `--project-config-root`,
79
+ `--allowedTools`, `--disallowedTools`, `--tools`, `--agents`, `--agent`, `--plugin-dir`, `--plugin-url`,
80
+ `--input-format`, `--permission-prompt-tool` or `--permission-prompts`. Hosts that run Claude Code for you, such as the Claude
81
+ desktop app and Agent SDK apps, pass these flags, so **the hook never rewrites in those sessions**.
82
+ The hook reads the processes above it up to the nearest one it knows is `claude` (a `claude` binary, the desktop app's
83
+ `claude.app`, or `node`/`bun` running the `@anthropic-ai/claude-code` package); what runs above that one, such as an outer
84
+ `claude` session that ran `claude -p`, doesn't govern it. If it finds no `claude`, it checks every process up to the top.
85
+ - It runs in a background session (`claude --bg`). Measured 2026-11-23 on claude 2.1.285: the session's host argv carries
86
+ `--bg-spare` (the pty host's, `--bg-pty-host`), both read as rule flags, so the hook skips the rewrite. Claude Code strips its
87
+ background variables from the hook's env except `CLAUDE_JOB_DIR`; when that is set, the hook checks every process up to the top.
88
+ - A variable points Claude Code at settings the hook doesn't read: `CLAUDE_CODE_MANAGED_SETTINGS_PATH`,
89
+ `CLAUDE_CODE_REMOTE_SETTINGS_PATH`, `CLAUDE_CODE_CLIENT_DATA_URL` or `CLAUDE_CODE_PLUGIN_DIRS`, among others.
90
+ - A macOS MDM profile for Claude Code is installed, server-managed settings are cached
91
+ (`remote-settings.json` in your user settings folder), or a managed settings file names a `policyHelper` or `policyHelpers`.
92
+ - A settings file (user, project, local or managed) exists but can't be read or isn't a JSON object. A leading
93
+ byte-order mark is fine; comments and trailing commas are not.
94
+ - It runs on Windows or WSL, or it can't read the processes above it (it uses `/proc` on Linux and `ps` elsewhere).
95
+ On Linux, argv is read from `/proc/<pid>/cmdline`; a claude that rewrites its process title would hide `--settings` (untested on Linux).
96
+
97
+ **The built-in default list is a no-op.** Its `requires` is empty, so `debabble hook claude` without
98
+ `--list` never rewrites anything. Pass `--list <file>` with both pins to turn the hook on.
99
+ Without `--list` the hook reads the shipped default under your own list file (see [Manage the wrap list](#manage-the-wrap-list)).
100
+ `--list <file>` reads that one file and skips the layering.
101
+
102
+ The rewrite adds only the prefix; the rest is the original line, byte for byte. Any error prints
103
+ nothing (the command runs unwrapped). The hook always exits 0; a usage error adds one line on stderr.
104
+
105
+ List file:
106
+
107
+ ```json
108
+ {
109
+ "requires": { "bouncer": "0.2.0", "debabble": "0.1.0" },
110
+ "wrap": [
111
+ { "match": "pnpm test", "show": "verdict" },
112
+ { "match": "gh run view", "show": "excerpt" }
113
+ ]
114
+ }
115
+ ```
116
+
117
+ `match` is a word prefix: `pnpm test` matches `pnpm test --run x`, not `pnpm testx`. `show:
118
+ "excerpt"` rewrites to `debabble --show excerpt -- …`. `debabble --version` prints the version.
119
+
120
+ ## Manage the wrap list
121
+
122
+ ```
123
+ debabble list show
124
+ debabble list add <match> --show verdict|excerpt
125
+ debabble list disable <match>
126
+ debabble list enable <match>
127
+ ```
128
+
129
+ You never edit JSON by hand. Your entries live in `$XDG_CONFIG_HOME/debabble/wrap.json` (default
130
+ `~/.config/debabble/wrap.json`), laid over the list that ships with debabble.
131
+
132
+ - `show` prints every entry with its source (`default` or `user`) and whether it is enabled.
133
+ - `add` puts a new entry in your file. It refuses a `match` that is empty, a shell builtin or keyword
134
+ (`cd`, `export`, `if`, …), or holds a shell operator (`;`, `&`, `&&`, `|`, `||`, `<`, `>`, `$(`, a backtick,
135
+ a newline). The hook wraps simple commands only. It also refuses a `match` already on the list.
136
+ - `disable` turns an entry off; `enable` turns it back on. Disabling a shipped entry writes an entry for it in your
137
+ file with `"enabled": false`. There is no `remove`: you can switch a shipped entry off, never delete it.
138
+ - Your entry replaces a shipped entry with the same `match` (words compared with spaces collapsed); your other entries follow the shipped ones.
139
+ - `requires` (the version pins) stays in the shipped list; your file cannot change it.
140
+ - Writes are atomic (a temp file, then a rename). The file is `0600` and a folder debabble creates is `0700`.
141
+ - A file that is not valid JSON, or not `{"wrap": [...]}`, is reported with its path and left untouched.
142
+ The hook rewrites nothing while your file is broken, so a command you disabled never runs wrapped.
143
+ - Exit codes: 0 done, 1 refused or not found or a broken file, 125 usage error.
144
+
145
+ ## Redaction
146
+
147
+ What debabble prints (the `✓`/`✗` line, the excerpt, the label) has secret-shaped text masked as
148
+ `<redacted:shape>`. The log file is **not** touched: it holds the command's output byte for byte (mode
149
+ 0600, on your machine). To see unmasked text, read the log path debabble prints.
150
+
151
+ Masked (high-precision shapes only):
152
+
153
+ | Shape | Looks like |
154
+ |---|---|
155
+ | `pem-private-key` | a `-----BEGIN … PRIVATE KEY-----` block through its END line, line by line, even when the excerpt shows only part of it |
156
+ | `github-token` | `gh` + one of `pousr` + `_` + 20 or more letters and digits |
157
+ | `sk-key` | `sk-` + 20 or more letters, digits, `-` or `_` |
158
+ | `aws-access-key` | `AKIA` + 16 capitals and digits |
159
+ | `slack-token` | `xox` + one of `abprs` + `-` + 10 or more letters, digits or `-` |
160
+ | `jwt` | `eyJ…` header, `eyJ…` payload, and the signature |
161
+ | `url-credentials` | the `user:pass` in `scheme://user:pass@host` (scheme and host stay) |
162
+
163
+ Not masked, on purpose: loose patterns such as `secret=…`, `token: …`, `Authorization: Bearer …` and
164
+ `.env`-style lines. They match source code and docs far more often than real secrets, and masking them
165
+ would mangle ordinary output. Other token formats (GitHub fine-grained `github_pat_…`, AWS `ASIA…`,
166
+ Stripe, Google) are not masked either. A secret that has no shape above reaches the excerpt as written,
167
+ and the library (`scan`, `excerpt`) masks nothing unless you pass it a redactor.
168
+
169
+ ## Safety
170
+
171
+ - Logs can hold anything the command printed, secrets included (redaction masks only what debabble prints). They stay on your machine; nothing uploads them.
172
+ - The log folder is mode 0700 and each log 0600. At the start of each run debabble deletes its own
173
+ logs older than 7 days and the oldest past 200 per folder.
174
+ - If the log folder can't be used (it isn't writable, or another user owns it), debabble prints one line on
175
+ stderr naming the folder and the error, then logs to `debabble-<uid>` in your temp folder, which it prunes the same way.
176
+ If the temp folder fails too, the line says so and the command runs with its output passed straight through, with no log.
177
+ - debabble never changes the exit code and never hides a failure behind a green line: a non-zero
178
+ exit always prints an excerpt.
179
+
180
+ ## Limits
181
+
182
+ - Node 22 or newer. No dependencies.
183
+ - A progress line (test dots, `ok pkg`) is never shown, and a line that names a failure is never counted as progress.
184
+ Output that names no error is shown by its tail only.
185
+ - A process that was handed to init before a timeout is out of reach of the tree stop.
186
+ - If debabble is killed with SIGKILL it cannot clean up; the command may keep running.
187
+ - Windows is untested.
188
+ - Stdin is closed: not for interactive programs.
189
+
190
+ MIT licensed.
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // The `debabble` executable: `hook …` goes to src/hook.mjs, `list …` to src/list.mjs, `--version` prints the package version, anything else to src/cli.mjs; exits with its code.
3
+ // Run: `debabble [--show verdict|excerpt] [--timeout <dur>] [--label <name>] [--log-dir <path>] -- <cmd> [args…]`, `debabble hook claude [--list <file>]`, `debabble list show|add|disable|enable …`, `debabble --version`.
4
+ // When: see src/cli.mjs and src/hook.mjs.
5
+ // Env: see src/cli.mjs and src/hook.mjs.
6
+ // Writes: see src/cli.mjs and src/hook.mjs.
7
+ // Exit: see src/cli.mjs; the hook always exits 0; --version 0.
8
+ // Used by: npm's bin link.
9
+
10
+ // Each path imports only what it needs: the hook runs on every Bash call, so it must not load the runner.
11
+ const argv = process.argv.slice(2);
12
+ if (argv[0] === "hook") {
13
+ // Fail open: a broken install (a missing or bad src/hook.mjs) prints nothing and exits 0, so the command runs unwrapped.
14
+ try {
15
+ const { readFileSync } = await import("node:fs");
16
+ const { hookMain } = await import("../src/hook.mjs");
17
+ const result = hookMain(argv.slice(1), { stdin: () => readFileSync(0, "utf8") });
18
+ if (result.stdout) process.stdout.write(`${result.stdout}\n`);
19
+ if (result.stderr) process.stderr.write(`${result.stderr}\n`);
20
+ } catch {}
21
+ process.exitCode = 0;
22
+ } else if (argv[0] === "list") {
23
+ const { listMain } = await import("../src/list.mjs");
24
+ const result = listMain(argv.slice(1));
25
+ if (result.stdout) process.stdout.write(`${result.stdout}\n`);
26
+ if (result.stderr) process.stderr.write(`${result.stderr}\n`);
27
+ process.exitCode = result.code;
28
+ } else if (argv.length === 1 && argv[0] === "--version") {
29
+ const { readFileSync } = await import("node:fs");
30
+ process.stdout.write(`${JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version}\n`);
31
+ } else {
32
+ const { main } = await import("../src/cli.mjs");
33
+ // process.exit, not a returned code: a command that left a handle open must not keep the wrapper alive.
34
+ process.exit(await main(argv));
35
+ }
package/package.json CHANGED
@@ -1,7 +1,31 @@
1
1
  {
2
2
  "name": "debabble",
3
- "version": "0.0.0",
4
- "description": "Name held for debabble: quiet command output for coding agents. Nothing to install yet.",
3
+ "version": "0.1.0",
4
+ "description": "Run a command with its output in a log file; print one line when it passes and an excerpt when it fails.",
5
+ "type": "module",
6
+ "bin": {
7
+ "debabble": "bin/debabble.mjs"
8
+ },
9
+ "engines": {
10
+ "node": ">=22"
11
+ },
5
12
  "license": "MIT",
6
- "files": ["README.md"]
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/bretperry/debabble.git"
16
+ },
17
+ "homepage": "https://github.com/bretperry/debabble#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/bretperry/debabble/issues"
20
+ },
21
+ "exports": "./src/index.mjs",
22
+ "files": [
23
+ "src/",
24
+ "bin/"
25
+ ],
26
+ "scripts": {
27
+ "test": "node --test",
28
+ "bench": "node scripts/bench.mjs",
29
+ "bench:hook": "node scripts/bench-hook.mjs"
30
+ }
7
31
  }
package/src/cli.mjs ADDED
@@ -0,0 +1,211 @@
1
+ // The debabble command: runs a command with all its output in a log file and prints one line when it passes, an excerpt when it fails.
2
+ // In the app: bin/debabble.mjs calls `main`; the library (src/index.mjs) exposes the same pieces without the printing.
3
+ // Run: `debabble [--show verdict|excerpt] [--timeout <dur>] [--label <name>] [--log-dir <path>] -- <cmd> [args…]`
4
+ // When: in front of a command whose output is long and mostly noise (test runs, builds, log readers); not for interactive programs (stdin is closed).
5
+ // Env: DEBABBLE=off (run the command with its output passed straight through); DEBABBLE_LOG_DIR (log base folder); DEBABBLE_TIMEOUT_MS (default timeout in ms); XDG_STATE_HOME (log base when no other is set); CI, GITHUB_ACTIONS (passthrough, as `off`);
6
+ // DEBABBLE_KILL_GRACE_MS (how long a killed passthrough's command has to exit before its tree is stopped; default 5000).
7
+ // Prints: the label, verdict line and excerpt with secret-shaped text masked as `<redacted:shape>` (src/redact.mjs); the log keeps the command's bytes as written.
8
+ // Writes: one log file per run under the log folder (0600 in a 0700 folder, pruned to 200 files and 7 days); stdout lines only; stderr only for a
9
+ // usage error, a command that did not start in the passthrough, or a log folder it can't use (one line naming it and the fallback folder;
10
+ // when no temp folder works either, the line says so and the command runs as the passthrough, with no log).
11
+ // Exit: the command's code; 128+n when signal n ended it (also when debabble itself is killed); 124 timed out (as timeout(1)); 125 usage error; 127 not found; 126 not runnable.
12
+ // Used by: bin/debabble.mjs; tested by test/cli.test.mjs.
13
+ // Uses: src/scan.mjs, src/run.mjs, src/logs.mjs, src/redact.mjs.
14
+ // Exports: parseArgs(argv, env), main(argv, { env, cwd }) → exit code.
15
+ //
16
+ // Output (stdout): first `log: <path>` (so a reader that only sees the start of a backgrounded run still has the path), then, for a green run, one line
17
+ // `✓ <label> · 41.2s · log: <path>` (with `· 1 warning: "…"` and `· 1 error-like line: "…"` before the path when the log holds any), or for a red run
18
+ // `✗ <label> · exit 1 · 38.9s`, the excerpt indented two spaces, and a last line `log: <path>`. A timeout or kill is one line ending ` · log: <path>`.
19
+ // `--show excerpt` is for log readers (`gh run view --log`): green prints `✓ … · N failure lines of M` and those lines, red as above.
20
+ // `--` is required so a guard that reads the line can find the command without knowing debabble's flags.
21
+
22
+ import { writeSync } from "node:fs";
23
+ import { constants } from "node:os";
24
+ import { EXCERPT_MAX_LINES, excerptLines, scanLog } from "./scan.mjs";
25
+ import { DEFAULT_TIMEOUT_MS, MAX_TIMER_MS, run, signalTree, stopTree } from "./run.mjs";
26
+ import { logDirFor, openLog } from "./logs.mjs";
27
+ import { lineRedactor, redactText } from "./redact.mjs";
28
+
29
+ // How long a killed passthrough's command has to exit on the signal it was sent before its tree is stopped; DEBABBLE_KILL_GRACE_MS overrides.
30
+ const KILL_GRACE_MS = 5000;
31
+ const killGraceMs = (env) => {
32
+ const ms = Number(env.DEBABBLE_KILL_GRACE_MS);
33
+ return (env.DEBABBLE_KILL_GRACE_MS ?? "") !== "" && Number.isFinite(ms) && ms >= 0 ? Math.min(ms, MAX_TIMER_MS) : KILL_GRACE_MS;
34
+ };
35
+
36
+ const USAGE = "usage: debabble [--show verdict|excerpt] [--timeout <dur>] [--label <name>] [--log-dir <path>] -- <cmd> [args…]";
37
+ const UNITS = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
38
+
39
+ // A duration as written (`90s`, `30m`, `1500ms`, `2h`; a bare number is seconds) in ms, or null when it is not one.
40
+ const parseDuration = (text) => {
41
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(text);
42
+ if (!match) return null;
43
+ const ms = Number(match[1]) * UNITS[match[2] ?? "s"];
44
+ return ms > 0 ? Math.min(Math.round(ms), MAX_TIMER_MS) : null;
45
+ };
46
+
47
+ // Parses argv: { flags, command, args } or { error }. Nothing before the `--` may be anything but a flag with its value.
48
+ export const parseArgs = (argv, env = process.env) => {
49
+ const flags = { show: "verdict", label: undefined, logDir: undefined, timeoutMs: undefined };
50
+ const dash = argv.indexOf("--");
51
+ if (dash === -1) return { error: argv.length === 0 ? USAGE : `no \`--\` before the command; ${USAGE}` };
52
+ const before = argv.slice(0, dash);
53
+ for (let i = 0; i < before.length; i += 1) {
54
+ const name = before[i];
55
+ const value = before[i + 1];
56
+ if (!["--show", "--timeout", "--label", "--log-dir"].includes(name)) return { error: `unknown flag ${name}; ${USAGE}` };
57
+ if (value === undefined) return { error: `${name} needs a value; ${USAGE}` };
58
+ i += 1;
59
+ if (name === "--show") {
60
+ if (value !== "verdict" && value !== "excerpt") return { error: `--show takes verdict or excerpt, not ${value}` };
61
+ flags.show = value;
62
+ } else if (name === "--timeout") {
63
+ flags.timeoutMs = parseDuration(value);
64
+ if (flags.timeoutMs === null) return { error: `--timeout takes a duration like 90s, 30m or 1500ms, not ${value}` };
65
+ } else if (name === "--label") flags.label = value;
66
+ else flags.logDir = value;
67
+ }
68
+ const [command, ...args] = argv.slice(dash + 1);
69
+ if (command === undefined || command === "") return { error: `no command after \`--\`; ${USAGE}` };
70
+ if (flags.timeoutMs === undefined) {
71
+ const fromEnv = Number(env.DEBABBLE_TIMEOUT_MS);
72
+ flags.timeoutMs = Number.isFinite(fromEnv) && fromEnv > 0 ? Math.min(fromEnv, MAX_TIMER_MS) : DEFAULT_TIMEOUT_MS;
73
+ }
74
+ return { flags, command, args };
75
+ };
76
+
77
+ // Whether this is a CI run: CI set and not "false", or GitHub Actions. Its log is the only record there, so debabble steps aside.
78
+ const inCi = (env) => ((env.CI ?? "") !== "" && env.CI.toLowerCase() !== "false") || env.GITHUB_ACTIONS === "true";
79
+
80
+ const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
81
+ // Elapsed time as the lines show it: `3.1s`, `41.2s`, `1m47s`.
82
+ const elapsed = (ms) => (ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m${String(Math.round((ms % 60_000) / 1000)).padStart(2, "0")}s`);
83
+ // A limit as `timeout(1)` people write it: `30m0s`, `90s`, `1h2m3s`, `500ms`.
84
+ const span = (ms) => {
85
+ if (ms < 1000) return `${ms}ms`;
86
+ const s = Math.round(ms / 1000);
87
+ const [h, m, r] = [Math.floor(s / 3600), Math.floor((s % 3600) / 60), s % 60];
88
+ return h > 0 ? `${h}h${m}m${r}s` : m > 0 ? `${m}m${r}s` : `${r}s`;
89
+ };
90
+ const signalNumber = (name) => constants.signals[name] ?? 0;
91
+ // The exit code for a command that did not start: 126 when it exists but cannot run, 127 when it is not found (as a shell).
92
+ const notStartedCode = (error) => (error.code === "EACCES" ? 126 : 127);
93
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
94
+
95
+ // Writes text to fd 1 or 2 synchronously, so nothing is pending at `process.exit` and lines to both keep their order under `2>&1`.
96
+ // A full non-blocking pipe (EAGAIN) is waited out; any other failure (a closed pipe) drops the text rather than crash.
97
+ const emit = (fd, text) => {
98
+ const buffer = Buffer.from(text.endsWith("\n") ? text : `${text}\n`);
99
+ let done = 0;
100
+ let spins = 0;
101
+ while (done < buffer.length) {
102
+ try {
103
+ done += writeSync(fd, buffer, done);
104
+ spins = 0;
105
+ } catch (error) {
106
+ if (error.code !== "EAGAIN" || ++spins > 50_000) return;
107
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2);
108
+ }
109
+ }
110
+ };
111
+
112
+ // The full CLI, as a function: returns the exit code instead of exiting.
113
+ export const main = async (argv, { env = process.env, cwd = process.cwd() } = {}) => {
114
+ const parsed = parseArgs(argv, env);
115
+ if (parsed.error) {
116
+ emit(2, `debabble: ${parsed.error}`);
117
+ return 125;
118
+ }
119
+ const { flags, command, args } = parsed;
120
+ // CI and DEBABBLE=off: the passthrough, with no log (logFile stays undefined) and no lines of ours; timeout, kill and exit codes as below.
121
+ let passthrough = env.DEBABBLE === "off" || inCi(env);
122
+
123
+ // The label is printed and names the log file, so it is masked too (a command line can carry `https://user:pass@host`).
124
+ const label = clip(redactText(flags.label ?? [command, ...args].join(" ")), 120);
125
+ let logFile;
126
+ if (!passthrough) {
127
+ const dir = logDirFor(cwd, env, flags.logDir);
128
+ try {
129
+ const opened = openLog(dir, label);
130
+ logFile = opened.logFile;
131
+ if (opened.fallback) emit(2, `debabble: can't use log folder ${opened.fallback.dir} (${opened.fallback.error}); logging to ${opened.dir}`);
132
+ emit(1, `log: ${logFile}`);
133
+ } catch (error) {
134
+ // No folder at all can take a log (the temp folder fails too): the command still runs, as the passthrough.
135
+ emit(2, `debabble: can't use log folder ${dir} or a temp folder (${error.code ?? error.message}); running without a log`);
136
+ passthrough = true;
137
+ }
138
+ }
139
+ const running = run({ command, args, cwd, logFile, env, timeoutMs: flags.timeoutMs });
140
+ const started = Date.now();
141
+
142
+ // A kill of debabble itself (a task runner's timeout, Ctrl-C): stop the command's tree, say where the log is (if any), and exit 128+n.
143
+ const stop = (signal) => {
144
+ stopTree(running.child.pid);
145
+ if (!passthrough) emit(1, `✗ ${label} · killed by ${signal} · ${elapsed(Date.now() - started)} · log: ${logFile}`);
146
+ process.exit(128 + signalNumber(signal));
147
+ };
148
+ // The passthrough (CI, DEBABBLE=off) stands in for the command, so the command gets the chance to shut down as it would unwrapped (Ctrl-C
149
+ // cleanup, a CI cancel): the same signal goes to its whole tree first, and the tree stop follows after the grace period, or at once on a
150
+ // second signal. Exit 128+n either way.
151
+ let killedBy = null;
152
+ let escalate;
153
+ const onKill = (signal) => {
154
+ if (!passthrough || killedBy !== null) return stop(killedBy ?? signal);
155
+ killedBy = signal;
156
+ signalTree(running.child.pid, signal);
157
+ escalate = setTimeout(() => stop(signal), killGraceMs(env));
158
+ };
159
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
160
+ for (const signal of signals) process.on(signal, onKill);
161
+
162
+ const ran = await running;
163
+ clearTimeout(escalate);
164
+ for (const signal of signals) process.off(signal, onKill);
165
+ if (killedBy !== null) return 128 + signalNumber(killedBy);
166
+ if (passthrough) {
167
+ if (ran.timedOut) return 124;
168
+ if (ran.error) {
169
+ emit(2, `debabble: ${redactText(`${command}: ${ran.error.message}`)}`);
170
+ return notStartedCode(ran.error);
171
+ }
172
+ return ran.signal ? 128 + signalNumber(ran.signal) : (ran.status ?? 1);
173
+ }
174
+ const time = elapsed(ran.ms);
175
+
176
+ if (ran.timedOut) {
177
+ emit(1, `✗ ${label} · timed out after ${span(flags.timeoutMs)} (stopped the process tree) · log: ${logFile}`);
178
+ return 124;
179
+ }
180
+ if (ran.error) {
181
+ emit(1, `✗ ${label} · did not start: ${redactText(ran.error.message)} · log: ${logFile}`);
182
+ return notStartedCode(ran.error);
183
+ }
184
+ if (ran.signal) {
185
+ emit(1, `✗ ${label} · killed by ${ran.signal} · ${time} · log: ${logFile}`);
186
+ return 128 + signalNumber(ran.signal);
187
+ }
188
+ if (ran.status === null) {
189
+ emit(1, `✗ ${label} · ended without an exit code · ${time} · log: ${logFile}`);
190
+ return 1;
191
+ }
192
+
193
+ // Everything shown from the log passes through the line redactor; the log file itself is never touched.
194
+ const scan = scanLog(logFile, { redact: lineRedactor() });
195
+ if (ran.status === 0) {
196
+ if (flags.show === "excerpt") {
197
+ const found = `${plural(scan.failures, "failure line")} of ${scan.total.toLocaleString("en-US")}`;
198
+ if (scan.failures === 0) emit(1, `✓ ${label} · ${time} · ${found} · log: ${logFile}`);
199
+ else emit(1, [`✓ ${label} · ${time} · ${found}`, ...excerptLines(scan).map((text) => ` ${text}`), `log: ${logFile}`].join("\n"));
200
+ return 0;
201
+ }
202
+ // A green run can still print what looks like a failure (a tolerated error) or a warning: say so on its line, first one only.
203
+ const errors = scan.failures > 0 ? ` · ${scan.failures === 1 ? "1 error-like line:" : `${scan.failures} error-like lines, first:`} "${clip(scan.firstFailure, 100)}"` : "";
204
+ const warnings = scan.warnings > 0 ? ` · ${scan.warnings === 1 ? "1 warning:" : `${scan.warnings} warnings, first:`} "${clip(scan.firstWarning, 100)}"` : "";
205
+ emit(1, `✓ ${label} · ${time}${errors}${warnings} · log: ${logFile}`);
206
+ return 0;
207
+ }
208
+ const shown = excerptLines(scan).slice(0, EXCERPT_MAX_LINES);
209
+ emit(1, [`✗ ${label} · exit ${ran.status} · ${time}`, ...shown.map((text) => ` ${text}`), `log: ${logFile}`].join("\n"));
210
+ return ran.status;
211
+ };
@@ -0,0 +1,8 @@
1
+ {
2
+ "requires": {},
3
+ "wrap": [
4
+ { "match": "git fetch", "show": "verdict" },
5
+ { "match": "node --test", "show": "verdict" },
6
+ { "match": "ssh", "show": "excerpt" }
7
+ ]
8
+ }