wtf-just-happened 0.0.0-stage → 1.0.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/README.md +144 -2
- package/dist/cli.js +1007 -0
- package/dist/cli.js.map +1 -0
- package/package.json +50 -3
package/README.md
CHANGED
|
@@ -1,3 +1,145 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wtf-just-happened (`wtf`)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> A transparent Pseudo-Terminal (PTY) wrapper for developer commands. When commands succeed, it stays completely invisible. When commands crash, it captures diagnostics, scrubs secrets, saves a local snapshot, and opens an interactive terminal menu with a copy-ready diagnostic Markdown report for LLMs (ChatGPT, Claude) and GitHub Issues.
|
|
4
|
+
|
|
5
|
+
[](https://www.typescriptlang.org/)
|
|
6
|
+
[](https://vitest.dev/)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Core Philosophy: Zero-Friction Transparency
|
|
12
|
+
|
|
13
|
+
- **Success (`exitCode === 0`):** `wtf` remains 100% invisible. Standard I/O flows normally, and `wtf` exits with code `0`.
|
|
14
|
+
- **Failure (`exitCode !== 0`):** Automatically captures the trailing 64KB terminal output, gathers system/Git/network context in parallel, scrubs sensitive secrets, stores an auto-pruned diagnostic bundle in `~/.wtf/crashes/`, and presents an interactive TUI to copy a formatted Markdown report or re-run the command.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Installation & Usage
|
|
19
|
+
|
|
20
|
+
### Binary Aliases
|
|
21
|
+
The package exposes both `wtf` and `wtf-just-happened`:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# Wrap any build, test, or deployment command
|
|
25
|
+
wtf npm run build
|
|
26
|
+
wtf docker compose up
|
|
27
|
+
wtf cargo test
|
|
28
|
+
wtf pnpm test:e2e
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### Subcommands & Flags
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
# Re-open the interactive menu for the most recent crash
|
|
35
|
+
wtf last
|
|
36
|
+
|
|
37
|
+
# Simulate a crash with fake secrets and stack trace to test the TUI
|
|
38
|
+
wtf --demo
|
|
39
|
+
|
|
40
|
+
# View help and usage options
|
|
41
|
+
wtf --help
|
|
42
|
+
|
|
43
|
+
# View CLI version
|
|
44
|
+
wtf --version
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Architecture & Features
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
wtf-just-happened/
|
|
53
|
+
├── package.json
|
|
54
|
+
├── tsconfig.json
|
|
55
|
+
├── tsup.config.ts
|
|
56
|
+
├── README.md
|
|
57
|
+
├── src/
|
|
58
|
+
│ ├── cli.ts # Entry point, subcommands (`last`, `--demo`, `--help`), exit-code propagation
|
|
59
|
+
│ ├── core/
|
|
60
|
+
│ │ ├── pty-runner.ts # PTY wrapper (node-pty with graceful fallback to child_process.spawn)
|
|
61
|
+
│ │ ├── ring-buffer.ts # Fixed 64KB byte-bounded circular buffer + ANSI stripping
|
|
62
|
+
│ │ └── collector.ts # Parallel Promise.allSettled context collector (200ms strict timeout)
|
|
63
|
+
│ ├── security/
|
|
64
|
+
│ │ └── redactor.ts # Two-pass secret scrubber (env keys + regex/entropy patterns)
|
|
65
|
+
│ ├── formatters/
|
|
66
|
+
│ │ ├── markdown.ts # Markdown diagnostic report generator (GitHub Issue & LLM optimized)
|
|
67
|
+
│ │ └── terminal-ui.ts # Post-crash @clack/prompts interactive menu
|
|
68
|
+
│ └── utils/
|
|
69
|
+
│ └── storage.ts # Saves/loads JSON crash bundles in ~/.wtf/crashes/ (auto-prunes > 20)
|
|
70
|
+
├── tests/
|
|
71
|
+
│ ├── ring-buffer.test.ts # 64KB byte eviction and ANSI stripping unit tests
|
|
72
|
+
│ ├── redactor.test.ts # AWS keys, JWTs, Bearer tokens, DB URIs redaction tests
|
|
73
|
+
│ └── cli.integration.test.ts # Silent exit 0 vs failing exit code propagation tests
|
|
74
|
+
└── playground/
|
|
75
|
+
├── package.json # Playground test scripts (fail:build, fail:port)
|
|
76
|
+
├── broken-build.js # Realistic build error with mock secrets & stack trace
|
|
77
|
+
└── port-conflict.js # Server collision simulating EADDRINUSE
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### 1. Robust PTY Runner (`src/core/pty-runner.ts`)
|
|
81
|
+
- Spawns using `node-pty` for real terminal I/O (handling raw mode stdin forwarding and terminal resize events).
|
|
82
|
+
- Graceful fallback to `child_process.spawn` if native PTY bindings are unavailable in constrained or container environments.
|
|
83
|
+
- Windows binary resolution preventing `DEP0190` warnings and Windows batch file security restrictions.
|
|
84
|
+
|
|
85
|
+
### 2. 64KB Bounded Ring Buffer (`src/core/ring-buffer.ts`)
|
|
86
|
+
- Keeps memory usage strictly bounded to 64KB of trailing log data.
|
|
87
|
+
- Dual-mode output: `getRaw()` preserves ANSI colors for re-displaying, while `getClean()` strips ANSI escape codes for clean Markdown logs.
|
|
88
|
+
|
|
89
|
+
### 3. Parallel Context Collector (`src/core/collector.ts`)
|
|
90
|
+
- Strict **200ms per-check timeout** prevents hanging on slow network or filesystem operations.
|
|
91
|
+
- Gathers system diagnostics (OS platform, release, arch, Node version, memory, CPU count).
|
|
92
|
+
- Gathers Git state (branch, commit hash, dirty tree summary).
|
|
93
|
+
- Active port detection: parses ports mentioned in terminal errors and probes candidate ports (e.g., 3000, 5000, 8080) for `EADDRINUSE` conflicts.
|
|
94
|
+
|
|
95
|
+
### 4. Two-Pass Secret Redactor (`src/security/redactor.ts`)
|
|
96
|
+
- **Pass 1:** Inspects environment variables for sensitive keys (`API_KEY`, `TOKEN`, `SECRET`, `PASSWORD`, etc.) and scrubs exact values.
|
|
97
|
+
- **Pass 2:** Regex patterns for:
|
|
98
|
+
- AWS Access Keys (`AKIA...`)
|
|
99
|
+
- JWT tokens (`eyJ...`)
|
|
100
|
+
- Bearer tokens (`Authorization: Bearer ...`)
|
|
101
|
+
- Database URI passwords (`postgres://user:password@host`, `mongodb://`, `mysql://`, `redis://`)
|
|
102
|
+
- Private Keys (`-----BEGIN ... PRIVATE KEY-----`)
|
|
103
|
+
- GitHub and Slack tokens
|
|
104
|
+
|
|
105
|
+
### 5. Interactive Post-Crash Terminal Menu (`src/formatters/terminal-ui.ts`)
|
|
106
|
+
- Powered by `@clack/prompts` and `picocolors`.
|
|
107
|
+
- Menu options:
|
|
108
|
+
- **Copy Markdown Report:** Copies LLM-optimized diagnostic prompt to system clipboard using `clipboardy`.
|
|
109
|
+
- **View Redacted Terminal Output:** Inspects trailing logs with secrets masked.
|
|
110
|
+
- **Print Full Markdown Report:** Dumps formatted report to console.
|
|
111
|
+
- **View Environment & System Context:** Displays system specs and safe environment variables.
|
|
112
|
+
- **Re-run Command:** Retries command execution immediately.
|
|
113
|
+
- **Exit:** Exits cleanly propagating the original exit code.
|
|
114
|
+
- Automatically falls back to a concise stderr summary in non-interactive CI environments.
|
|
115
|
+
|
|
116
|
+
### 6. Local Storage & Auto-Pruning (`src/utils/storage.ts`)
|
|
117
|
+
- Snapshots saved to `~/.wtf/crashes/crash-<timestamp>.json`.
|
|
118
|
+
- Automatic retention policy: auto-prunes older files to keep at most 20 recent crashes.
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## Interactive Playground Sandbox
|
|
123
|
+
|
|
124
|
+
Test the complete end-to-end failure capture with a single command:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
npm run try:playground
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
This runs `playground/broken-build.js`, which outputs colorful build logs containing fake credentials (`postgres://admin:supersecret123@localhost:5432/prod` and AWS key `AKIAIOSFODNN7EXAMPLE`) and crashes with a realistic stack trace.
|
|
131
|
+
|
|
132
|
+
You can also test port conflict detection:
|
|
133
|
+
```bash
|
|
134
|
+
node dist/cli.js npm --prefix playground run fail:port
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Testing
|
|
140
|
+
|
|
141
|
+
Run unit and integration tests with Vitest:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
npm test
|
|
145
|
+
```
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1007 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import pc2 from "picocolors";
|
|
5
|
+
|
|
6
|
+
// src/core/pty-runner.ts
|
|
7
|
+
import { spawn as childProcessSpawn } from "child_process";
|
|
8
|
+
|
|
9
|
+
// src/core/ring-buffer.ts
|
|
10
|
+
import stripAnsi from "strip-ansi";
|
|
11
|
+
var RingBuffer = class {
|
|
12
|
+
chunks = [];
|
|
13
|
+
currentBytes = 0;
|
|
14
|
+
maxBytes;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.maxBytes = options?.maxBytes ?? 64 * 1024;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Append a chunk of text or Buffer to the circular buffer.
|
|
20
|
+
*/
|
|
21
|
+
write(data) {
|
|
22
|
+
const text = typeof data === "string" ? data : data.toString("utf8");
|
|
23
|
+
if (!text) return;
|
|
24
|
+
const chunkBytes = Buffer.byteLength(text, "utf8");
|
|
25
|
+
if (chunkBytes >= this.maxBytes) {
|
|
26
|
+
const buf = Buffer.from(text, "utf8");
|
|
27
|
+
const tailBuf = buf.subarray(buf.length - this.maxBytes);
|
|
28
|
+
this.chunks = [tailBuf.toString("utf8")];
|
|
29
|
+
this.currentBytes = Buffer.byteLength(this.chunks[0], "utf8");
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
this.chunks.push(text);
|
|
33
|
+
this.currentBytes += chunkBytes;
|
|
34
|
+
while (this.chunks.length > 0 && this.currentBytes > this.maxBytes) {
|
|
35
|
+
const headChunk = this.chunks[0];
|
|
36
|
+
const headBytes = Buffer.byteLength(headChunk, "utf8");
|
|
37
|
+
const excess = this.currentBytes - this.maxBytes;
|
|
38
|
+
if (headBytes <= excess) {
|
|
39
|
+
this.chunks.shift();
|
|
40
|
+
this.currentBytes -= headBytes;
|
|
41
|
+
} else {
|
|
42
|
+
const headBuf = Buffer.from(headChunk, "utf8");
|
|
43
|
+
const trimmedBuf = headBuf.subarray(excess);
|
|
44
|
+
const trimmedStr = trimmedBuf.toString("utf8");
|
|
45
|
+
this.chunks[0] = trimmedStr;
|
|
46
|
+
this.currentBytes = this.currentBytes - headBytes + Buffer.byteLength(trimmedStr, "utf8");
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Get raw output including ANSI escape sequences.
|
|
53
|
+
*/
|
|
54
|
+
getRaw() {
|
|
55
|
+
return this.chunks.join("");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Get clean output with ANSI escape sequences stripped.
|
|
59
|
+
*/
|
|
60
|
+
getClean() {
|
|
61
|
+
return stripAnsi(this.getRaw());
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Get the current byte length of stored content.
|
|
65
|
+
*/
|
|
66
|
+
get byteLength() {
|
|
67
|
+
return this.currentBytes;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Clear the ring buffer.
|
|
71
|
+
*/
|
|
72
|
+
clear() {
|
|
73
|
+
this.chunks = [];
|
|
74
|
+
this.currentBytes = 0;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/core/pty-runner.ts
|
|
79
|
+
async function loadNodePty() {
|
|
80
|
+
try {
|
|
81
|
+
const ptyModule = await import("node-pty");
|
|
82
|
+
return ptyModule.default || ptyModule;
|
|
83
|
+
} catch {
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function runCommandWithPty(command, args = [], options) {
|
|
88
|
+
const ringBuffer = options?.ringBuffer ?? new RingBuffer();
|
|
89
|
+
const startTime = Date.now();
|
|
90
|
+
const cwd = options?.cwd ?? process.cwd();
|
|
91
|
+
const env = options?.env ?? process.env;
|
|
92
|
+
const nodePty = await loadNodePty();
|
|
93
|
+
if (nodePty && typeof nodePty.spawn === "function") {
|
|
94
|
+
try {
|
|
95
|
+
return await runWithNodePty(nodePty, command, args, ringBuffer, cwd, env, startTime);
|
|
96
|
+
} catch {
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return await runWithChildProcess(command, args, ringBuffer, cwd, env, startTime);
|
|
100
|
+
}
|
|
101
|
+
function runWithNodePty(pty, command, args, ringBuffer, cwd, env, startTime) {
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
const isWindows = process.platform === "win32";
|
|
104
|
+
const cols = process.stdout.columns || 80;
|
|
105
|
+
const rows = process.stdout.rows || 24;
|
|
106
|
+
let ptyProcess;
|
|
107
|
+
try {
|
|
108
|
+
const file = isWindows && ["npm", "npx", "pnpm", "yarn"].includes(command.toLowerCase()) ? `${command}.cmd` : command;
|
|
109
|
+
ptyProcess = pty.spawn(file, args, {
|
|
110
|
+
name: "xterm-256color",
|
|
111
|
+
cols,
|
|
112
|
+
rows,
|
|
113
|
+
cwd,
|
|
114
|
+
env,
|
|
115
|
+
useConpty: isWindows
|
|
116
|
+
});
|
|
117
|
+
} catch (err) {
|
|
118
|
+
reject(err);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
let userInterrupted = false;
|
|
122
|
+
const onSigInt = () => {
|
|
123
|
+
userInterrupted = true;
|
|
124
|
+
};
|
|
125
|
+
process.on("SIGINT", onSigInt);
|
|
126
|
+
const wasRaw = process.stdin.isRaw;
|
|
127
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
128
|
+
process.stdin.setRawMode(true);
|
|
129
|
+
process.stdin.resume();
|
|
130
|
+
}
|
|
131
|
+
const onStdinData = (data) => {
|
|
132
|
+
if (data.includes(3)) {
|
|
133
|
+
userInterrupted = true;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
ptyProcess.write(data.toString());
|
|
137
|
+
} catch {
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const onResize = () => {
|
|
141
|
+
try {
|
|
142
|
+
if (process.stdout.columns && process.stdout.rows) {
|
|
143
|
+
ptyProcess.resize(process.stdout.columns, process.stdout.rows);
|
|
144
|
+
}
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
process.stdin.on("data", onStdinData);
|
|
149
|
+
process.stdout.on("resize", onResize);
|
|
150
|
+
ptyProcess.onData((data) => {
|
|
151
|
+
ringBuffer.write(data);
|
|
152
|
+
process.stdout.write(data);
|
|
153
|
+
});
|
|
154
|
+
ptyProcess.onExit((event) => {
|
|
155
|
+
process.stdin.removeListener("data", onStdinData);
|
|
156
|
+
process.stdout.removeListener("resize", onResize);
|
|
157
|
+
process.removeListener("SIGINT", onSigInt);
|
|
158
|
+
if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
|
|
159
|
+
process.stdin.setRawMode(wasRaw || false);
|
|
160
|
+
process.stdin.pause();
|
|
161
|
+
}
|
|
162
|
+
const durationMs = Date.now() - startTime;
|
|
163
|
+
const isWindows2 = process.platform === "win32";
|
|
164
|
+
const code = event.exitCode;
|
|
165
|
+
const isInterrupt = userInterrupted || event.signal === 2 || event.signal === 15 || code === 130 || code === 143 || isWindows2 && (code === 3221225786 || code === -1073741510);
|
|
166
|
+
resolve({
|
|
167
|
+
exitCode: event.exitCode ?? (event.signal ? 128 + event.signal : 1),
|
|
168
|
+
durationMs,
|
|
169
|
+
outputTailRaw: ringBuffer.getRaw(),
|
|
170
|
+
outputTailClean: ringBuffer.getClean(),
|
|
171
|
+
userInterrupted: isInterrupt,
|
|
172
|
+
signal: event.signal
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function resolveBinary(command) {
|
|
178
|
+
if (process.platform !== "win32") {
|
|
179
|
+
return { file: command, shell: false };
|
|
180
|
+
}
|
|
181
|
+
const lower = command.toLowerCase();
|
|
182
|
+
if (lower.endsWith(".cmd") || lower.endsWith(".bat") || ["npm", "npx", "pnpm", "yarn", "corepack"].includes(lower)) {
|
|
183
|
+
return { file: command, shell: true };
|
|
184
|
+
}
|
|
185
|
+
if (lower.endsWith(".exe") || ["node", "git", "python", "cargo", "docker", "deno", "bun", "go", "rustc"].includes(lower)) {
|
|
186
|
+
return { file: command, shell: false };
|
|
187
|
+
}
|
|
188
|
+
return { file: command, shell: true };
|
|
189
|
+
}
|
|
190
|
+
function runWithChildProcess(command, args, ringBuffer, cwd, env, startTime) {
|
|
191
|
+
return new Promise((resolve) => {
|
|
192
|
+
const { file, shell } = resolveBinary(command);
|
|
193
|
+
let child;
|
|
194
|
+
try {
|
|
195
|
+
child = childProcessSpawn(file, args, {
|
|
196
|
+
cwd,
|
|
197
|
+
env,
|
|
198
|
+
shell,
|
|
199
|
+
stdio: ["inherit", "pipe", "pipe"]
|
|
200
|
+
});
|
|
201
|
+
} catch (err) {
|
|
202
|
+
const errorMsg = `
|
|
203
|
+
Failed to start process "${command}": ${err.message}
|
|
204
|
+
`;
|
|
205
|
+
ringBuffer.write(errorMsg);
|
|
206
|
+
process.stderr.write(errorMsg);
|
|
207
|
+
const durationMs = Date.now() - startTime;
|
|
208
|
+
resolve({
|
|
209
|
+
exitCode: 1,
|
|
210
|
+
durationMs,
|
|
211
|
+
outputTailRaw: ringBuffer.getRaw(),
|
|
212
|
+
outputTailClean: ringBuffer.getClean(),
|
|
213
|
+
userInterrupted: false
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (child.stdout) {
|
|
218
|
+
child.stdout.on("data", (chunk) => {
|
|
219
|
+
ringBuffer.write(chunk);
|
|
220
|
+
process.stdout.write(chunk);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
if (child.stderr) {
|
|
224
|
+
child.stderr.on("data", (chunk) => {
|
|
225
|
+
ringBuffer.write(chunk);
|
|
226
|
+
process.stderr.write(chunk);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
let userInterrupted = false;
|
|
230
|
+
const onSigInt = () => {
|
|
231
|
+
userInterrupted = true;
|
|
232
|
+
};
|
|
233
|
+
process.on("SIGINT", onSigInt);
|
|
234
|
+
child.on("error", (err) => {
|
|
235
|
+
process.removeListener("SIGINT", onSigInt);
|
|
236
|
+
const errorMsg = `
|
|
237
|
+
Failed to start process "${command}": ${err.message}
|
|
238
|
+
`;
|
|
239
|
+
ringBuffer.write(errorMsg);
|
|
240
|
+
process.stderr.write(errorMsg);
|
|
241
|
+
const durationMs = Date.now() - startTime;
|
|
242
|
+
resolve({
|
|
243
|
+
exitCode: 1,
|
|
244
|
+
durationMs,
|
|
245
|
+
outputTailRaw: ringBuffer.getRaw(),
|
|
246
|
+
outputTailClean: ringBuffer.getClean(),
|
|
247
|
+
userInterrupted: false
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
child.on("close", (code, signal) => {
|
|
251
|
+
process.removeListener("SIGINT", onSigInt);
|
|
252
|
+
const durationMs = Date.now() - startTime;
|
|
253
|
+
const isWindows = process.platform === "win32";
|
|
254
|
+
const isInterrupt = userInterrupted || signal === "SIGINT" || signal === "SIGTERM" || code === 130 || code === 143 || isWindows && (code === 3221225786 || code === -1073741510);
|
|
255
|
+
const exitCode = code !== null ? code : signal ? 128 : 1;
|
|
256
|
+
resolve({
|
|
257
|
+
exitCode,
|
|
258
|
+
durationMs,
|
|
259
|
+
outputTailRaw: ringBuffer.getRaw(),
|
|
260
|
+
outputTailClean: ringBuffer.getClean(),
|
|
261
|
+
userInterrupted: isInterrupt,
|
|
262
|
+
signal
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// src/core/collector.ts
|
|
269
|
+
import os from "os";
|
|
270
|
+
import { exec } from "child_process";
|
|
271
|
+
import net from "net";
|
|
272
|
+
|
|
273
|
+
// src/security/redactor.ts
|
|
274
|
+
var SENSITIVE_KEY_PATTERN = /(?:key|token|secret|password|passwd|auth|credential|api[_-]?key|private|access[_-]?key)/i;
|
|
275
|
+
var SECRET_PATTERNS = [
|
|
276
|
+
// Private Keys (RSA, EC, PGP, etc.)
|
|
277
|
+
{
|
|
278
|
+
name: "Private Key",
|
|
279
|
+
regex: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,
|
|
280
|
+
replace: () => "[REDACTED_PRIVATE_KEY]"
|
|
281
|
+
},
|
|
282
|
+
// Database connection URIs with password: protocol://user:password@host
|
|
283
|
+
{
|
|
284
|
+
name: "Database URI Password",
|
|
285
|
+
regex: /\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^:\s\/]+):(.+?)@([a-zA-Z0-9_.-]+(?::\d+)?(?:\/|[?#\s]|$))/g,
|
|
286
|
+
replace: (_match, proto, user, _pwd, host) => `${proto}${user}:[REDACTED]@${host}`
|
|
287
|
+
},
|
|
288
|
+
// AWS Access Key ID
|
|
289
|
+
{
|
|
290
|
+
name: "AWS Access Key",
|
|
291
|
+
regex: /\b(AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b/g,
|
|
292
|
+
replace: () => "[REDACTED_AWS_KEY]"
|
|
293
|
+
},
|
|
294
|
+
// GitHub Tokens (classic and fine-grained)
|
|
295
|
+
{
|
|
296
|
+
name: "GitHub Token",
|
|
297
|
+
regex: /\b(gh[pousr]_[A-Za-z0-9_]{36,255}|github_pat_[A-Za-z0-9_]{82})\b/g,
|
|
298
|
+
replace: () => "[REDACTED_GITHUB_TOKEN]"
|
|
299
|
+
},
|
|
300
|
+
// Slack Tokens
|
|
301
|
+
{
|
|
302
|
+
name: "Slack Token",
|
|
303
|
+
regex: /\bxox[baprs]-[0-9a-zA-Z]{10,48}\b/g,
|
|
304
|
+
replace: () => "[REDACTED_SLACK_TOKEN]"
|
|
305
|
+
},
|
|
306
|
+
// Stripe API Keys
|
|
307
|
+
{
|
|
308
|
+
name: "Stripe Key",
|
|
309
|
+
regex: /\b[rs]k_(?:test|live)_[0-9a-zA-Z]{24,99}\b/g,
|
|
310
|
+
replace: () => "[REDACTED_STRIPE_KEY]"
|
|
311
|
+
},
|
|
312
|
+
// JWT Tokens (3-part base64 url-safe strings)
|
|
313
|
+
{
|
|
314
|
+
name: "JWT Token",
|
|
315
|
+
regex: /\beyJ[a-zA-Z0-9_-]{10,}\.eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\b/g,
|
|
316
|
+
replace: () => "[REDACTED_JWT]"
|
|
317
|
+
},
|
|
318
|
+
// Bearer Authorization Header / Token
|
|
319
|
+
{
|
|
320
|
+
name: "Bearer Token",
|
|
321
|
+
regex: /\b(bearer\s+)([A-Za-z0-9\-._~+/]+=*)\b/gi,
|
|
322
|
+
replace: (_match, prefix) => `${prefix}[REDACTED_BEARER_TOKEN]`
|
|
323
|
+
},
|
|
324
|
+
// Generic key/secret assignments like apiKey = "...", secret: '...'
|
|
325
|
+
{
|
|
326
|
+
name: "Generic Secret Assignment",
|
|
327
|
+
regex: /\b((?:api[_-]?key|secret|password|passwd|auth[_-]?token|access[_-]?token)\s*[:=]\s*["']?)([^\s"';,]{8,})(["']?)/gi,
|
|
328
|
+
replace: (_match, prefix, _val, suffix) => `${prefix}[REDACTED]${suffix}`
|
|
329
|
+
}
|
|
330
|
+
];
|
|
331
|
+
function redactSecrets(text, options) {
|
|
332
|
+
if (!text) return text;
|
|
333
|
+
let result = text;
|
|
334
|
+
const env = options?.env ?? process.env;
|
|
335
|
+
if (env) {
|
|
336
|
+
const sensitiveValues = /* @__PURE__ */ new Set();
|
|
337
|
+
for (const [key, value] of Object.entries(env)) {
|
|
338
|
+
if (!value || typeof value !== "string") continue;
|
|
339
|
+
if (value.trim().length >= 6 && SENSITIVE_KEY_PATTERN.test(key)) {
|
|
340
|
+
const lower = value.toLowerCase().trim();
|
|
341
|
+
if (["true", "false", "null", "undefined", "default", "localhost", "127.0.0.1", "none"].includes(lower)) {
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
sensitiveValues.add(value);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const sortedValues = Array.from(sensitiveValues).sort((a, b) => b.length - a.length);
|
|
348
|
+
for (const val of sortedValues) {
|
|
349
|
+
const escaped = val.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
350
|
+
result = result.replace(new RegExp(escaped, "g"), "[REDACTED_ENV_SECRET]");
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
for (const { regex, replace } of SECRET_PATTERNS) {
|
|
354
|
+
result = result.replace(regex, replace);
|
|
355
|
+
}
|
|
356
|
+
return result;
|
|
357
|
+
}
|
|
358
|
+
function sanitizeEnvironment(env) {
|
|
359
|
+
const sanitized = {};
|
|
360
|
+
for (const [key, val] of Object.entries(env)) {
|
|
361
|
+
if (val === void 0) continue;
|
|
362
|
+
if (SENSITIVE_KEY_PATTERN.test(key)) {
|
|
363
|
+
sanitized[key] = "[REDACTED]";
|
|
364
|
+
} else {
|
|
365
|
+
sanitized[key] = redactSecrets(val, { env });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return sanitized;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// src/core/collector.ts
|
|
372
|
+
function withTimeout(promise, ms = 200, fallback) {
|
|
373
|
+
return new Promise((resolve) => {
|
|
374
|
+
let settled = false;
|
|
375
|
+
const timer = setTimeout(() => {
|
|
376
|
+
if (!settled) {
|
|
377
|
+
settled = true;
|
|
378
|
+
resolve(fallback);
|
|
379
|
+
}
|
|
380
|
+
}, ms);
|
|
381
|
+
promise.then((val) => {
|
|
382
|
+
if (!settled) {
|
|
383
|
+
settled = true;
|
|
384
|
+
clearTimeout(timer);
|
|
385
|
+
resolve(val);
|
|
386
|
+
}
|
|
387
|
+
}).catch(() => {
|
|
388
|
+
if (!settled) {
|
|
389
|
+
settled = true;
|
|
390
|
+
clearTimeout(timer);
|
|
391
|
+
resolve(fallback);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
function execAsync(cmd, timeoutMs = 180) {
|
|
397
|
+
return new Promise((resolve, reject) => {
|
|
398
|
+
exec(cmd, { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {
|
|
399
|
+
if (err) {
|
|
400
|
+
reject(err);
|
|
401
|
+
} else {
|
|
402
|
+
resolve(stdout.trim());
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
async function collectGit() {
|
|
408
|
+
try {
|
|
409
|
+
const [branchResult, commitResult, statusResult] = await Promise.allSettled([
|
|
410
|
+
execAsync("git rev-parse --abbrev-ref HEAD"),
|
|
411
|
+
execAsync("git log -1 --oneline"),
|
|
412
|
+
execAsync("git status --porcelain")
|
|
413
|
+
]);
|
|
414
|
+
const branch = branchResult.status === "fulfilled" ? branchResult.value : void 0;
|
|
415
|
+
const commit = commitResult.status === "fulfilled" ? commitResult.value : void 0;
|
|
416
|
+
const status = statusResult.status === "fulfilled" ? statusResult.value : "";
|
|
417
|
+
if (!branch && !commit) {
|
|
418
|
+
return void 0;
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
branch,
|
|
422
|
+
commit,
|
|
423
|
+
isDirty: status.length > 0,
|
|
424
|
+
statusSummary: status ? `${status.split("\n").length} modified files` : "clean"
|
|
425
|
+
};
|
|
426
|
+
} catch {
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
function checkPortInUse(port, timeoutMs = 150) {
|
|
431
|
+
return new Promise((resolve) => {
|
|
432
|
+
const socket = new net.Socket();
|
|
433
|
+
let isConnected = false;
|
|
434
|
+
socket.setTimeout(timeoutMs);
|
|
435
|
+
socket.once("connect", () => {
|
|
436
|
+
isConnected = true;
|
|
437
|
+
socket.destroy();
|
|
438
|
+
resolve(true);
|
|
439
|
+
});
|
|
440
|
+
socket.once("timeout", () => {
|
|
441
|
+
socket.destroy();
|
|
442
|
+
resolve(false);
|
|
443
|
+
});
|
|
444
|
+
socket.once("error", () => {
|
|
445
|
+
socket.destroy();
|
|
446
|
+
resolve(false);
|
|
447
|
+
});
|
|
448
|
+
socket.connect(port, "127.0.0.1");
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
async function collectPorts(cleanOutput) {
|
|
452
|
+
const candidatePorts = /* @__PURE__ */ new Set([3e3, 3001, 5173, 8080, 8e3, 5e3, 5432, 27017, 3306]);
|
|
453
|
+
const portRegex = /(?:port\s*[:=]?\s*|EADDRINUSE.*?|127\.0\.0\.1:|localhost:)(\d{2,5})\b/gi;
|
|
454
|
+
let match;
|
|
455
|
+
while ((match = portRegex.exec(cleanOutput)) !== null) {
|
|
456
|
+
const p2 = parseInt(match[1], 10);
|
|
457
|
+
if (p2 > 0 && p2 <= 65535) {
|
|
458
|
+
candidatePorts.add(p2);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
const results = [];
|
|
462
|
+
const checks = Array.from(candidatePorts).map(async (port) => {
|
|
463
|
+
try {
|
|
464
|
+
const inUse = await checkPortInUse(port, 150);
|
|
465
|
+
if (inUse) {
|
|
466
|
+
results.push({ port, inUse: true, details: `Port ${port} is currently bound/listening` });
|
|
467
|
+
}
|
|
468
|
+
} catch {
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
await Promise.allSettled(checks);
|
|
472
|
+
return results.sort((a, b) => a.port - b.port);
|
|
473
|
+
}
|
|
474
|
+
function collectRelevantEnv() {
|
|
475
|
+
const allowList = [
|
|
476
|
+
"NODE_ENV",
|
|
477
|
+
"CI",
|
|
478
|
+
"DEBUG",
|
|
479
|
+
"SHELL",
|
|
480
|
+
"TERM",
|
|
481
|
+
"TERM_PROGRAM",
|
|
482
|
+
"PATH",
|
|
483
|
+
"LANG",
|
|
484
|
+
"LC_ALL",
|
|
485
|
+
"PORT",
|
|
486
|
+
"HOST",
|
|
487
|
+
"PWD",
|
|
488
|
+
"NVM_BIN"
|
|
489
|
+
];
|
|
490
|
+
const filtered = {};
|
|
491
|
+
for (const key of allowList) {
|
|
492
|
+
if (process.env[key] !== void 0) {
|
|
493
|
+
filtered[key] = process.env[key];
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
for (const [key, val] of Object.entries(process.env)) {
|
|
497
|
+
if (/^(?:VITE_|NEXT_PUBLIC_|REACT_APP_|PUBLIC_|APP_)/i.test(key)) {
|
|
498
|
+
filtered[key] = val;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return sanitizeEnvironment(filtered);
|
|
502
|
+
}
|
|
503
|
+
async function collectCrashContext(options) {
|
|
504
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
505
|
+
const system = {
|
|
506
|
+
platform: os.platform(),
|
|
507
|
+
osRelease: os.release(),
|
|
508
|
+
arch: os.arch(),
|
|
509
|
+
nodeVersion: process.version,
|
|
510
|
+
cwd: process.cwd(),
|
|
511
|
+
totalMemoryMB: Math.round(os.totalmem() / (1024 * 1024)),
|
|
512
|
+
freeMemoryMB: Math.round(os.freemem() / (1024 * 1024)),
|
|
513
|
+
cpuCount: os.cpus().length
|
|
514
|
+
};
|
|
515
|
+
const [gitResult, portsResult, envResult] = await Promise.allSettled([
|
|
516
|
+
withTimeout(collectGit(), 200, void 0),
|
|
517
|
+
withTimeout(collectPorts(options.cleanOutputTail), 200, []),
|
|
518
|
+
withTimeout(Promise.resolve(collectRelevantEnv()), 200, {})
|
|
519
|
+
]);
|
|
520
|
+
const git = gitResult.status === "fulfilled" ? gitResult.value : void 0;
|
|
521
|
+
const activePorts = portsResult.status === "fulfilled" ? portsResult.value : [];
|
|
522
|
+
const environment = envResult.status === "fulfilled" ? envResult.value : {};
|
|
523
|
+
return {
|
|
524
|
+
command: options.command,
|
|
525
|
+
exitCode: options.exitCode,
|
|
526
|
+
durationMs: options.durationMs,
|
|
527
|
+
timestamp,
|
|
528
|
+
system,
|
|
529
|
+
git,
|
|
530
|
+
activePorts,
|
|
531
|
+
environment,
|
|
532
|
+
rawOutputTail: options.rawOutputTail,
|
|
533
|
+
cleanOutputTail: options.cleanOutputTail
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/utils/storage.ts
|
|
538
|
+
import os2 from "os";
|
|
539
|
+
import path from "path";
|
|
540
|
+
import fs from "fs/promises";
|
|
541
|
+
import { existsSync } from "fs";
|
|
542
|
+
var MAX_SAVED_CRASHES = 20;
|
|
543
|
+
function getCrashesDir() {
|
|
544
|
+
if (process.env.WTF_STORAGE_DIR) {
|
|
545
|
+
return process.env.WTF_STORAGE_DIR;
|
|
546
|
+
}
|
|
547
|
+
return path.join(os2.homedir(), ".wtf", "crashes");
|
|
548
|
+
}
|
|
549
|
+
function getFallbackDir() {
|
|
550
|
+
return path.join(process.cwd(), ".wtf", "crashes");
|
|
551
|
+
}
|
|
552
|
+
async function ensureCrashesDir() {
|
|
553
|
+
const dir = getCrashesDir();
|
|
554
|
+
try {
|
|
555
|
+
if (!existsSync(dir)) {
|
|
556
|
+
await fs.mkdir(dir, { recursive: true });
|
|
557
|
+
}
|
|
558
|
+
return dir;
|
|
559
|
+
} catch (err) {
|
|
560
|
+
if (err.code === "EPERM" || err.code === "EACCES") {
|
|
561
|
+
const fallback = getFallbackDir();
|
|
562
|
+
if (!existsSync(fallback)) {
|
|
563
|
+
await fs.mkdir(fallback, { recursive: true });
|
|
564
|
+
}
|
|
565
|
+
return fallback;
|
|
566
|
+
}
|
|
567
|
+
throw err;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
async function saveCrash(context, redactedOutput) {
|
|
571
|
+
const dir = await ensureCrashesDir();
|
|
572
|
+
const timestamp = Date.now();
|
|
573
|
+
const id = `crash-${timestamp}`;
|
|
574
|
+
const filePath = path.join(dir, `${id}.json`);
|
|
575
|
+
const bundle = {
|
|
576
|
+
id,
|
|
577
|
+
savedAt: new Date(timestamp).toISOString(),
|
|
578
|
+
context,
|
|
579
|
+
redactedOutput
|
|
580
|
+
};
|
|
581
|
+
await fs.writeFile(filePath, JSON.stringify(bundle, null, 2), "utf8");
|
|
582
|
+
await pruneCrashes(dir, MAX_SAVED_CRASHES);
|
|
583
|
+
return filePath;
|
|
584
|
+
}
|
|
585
|
+
async function pruneCrashes(dir, keepCount) {
|
|
586
|
+
try {
|
|
587
|
+
const files = await fs.readdir(dir);
|
|
588
|
+
const jsonFiles = files.filter((f) => f.startsWith("crash-") && f.endsWith(".json"));
|
|
589
|
+
if (jsonFiles.length <= keepCount) {
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
const filesWithStats = await Promise.all(
|
|
593
|
+
jsonFiles.map(async (name) => {
|
|
594
|
+
const fullPath = path.join(dir, name);
|
|
595
|
+
const stat = await fs.stat(fullPath);
|
|
596
|
+
return { name, fullPath, mtimeMs: stat.mtimeMs };
|
|
597
|
+
})
|
|
598
|
+
);
|
|
599
|
+
filesWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
600
|
+
const toDelete = filesWithStats.slice(keepCount);
|
|
601
|
+
await Promise.allSettled(toDelete.map((item) => fs.unlink(item.fullPath)));
|
|
602
|
+
} catch {
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
function resolveReadableCrashesDir() {
|
|
606
|
+
const primary = getCrashesDir();
|
|
607
|
+
if (existsSync(primary)) return primary;
|
|
608
|
+
const fallback = getFallbackDir();
|
|
609
|
+
if (existsSync(fallback)) return fallback;
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
async function getLastCrash() {
|
|
613
|
+
const dir = resolveReadableCrashesDir();
|
|
614
|
+
if (!dir) return null;
|
|
615
|
+
try {
|
|
616
|
+
const files = await fs.readdir(dir);
|
|
617
|
+
const jsonFiles = files.filter((f) => f.startsWith("crash-") && f.endsWith(".json"));
|
|
618
|
+
if (jsonFiles.length === 0) return null;
|
|
619
|
+
const filesWithStats = await Promise.all(
|
|
620
|
+
jsonFiles.map(async (name) => {
|
|
621
|
+
const fullPath = path.join(dir, name);
|
|
622
|
+
const stat = await fs.stat(fullPath);
|
|
623
|
+
return { name, fullPath, mtimeMs: stat.mtimeMs };
|
|
624
|
+
})
|
|
625
|
+
);
|
|
626
|
+
filesWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
627
|
+
const latest = filesWithStats[0];
|
|
628
|
+
const content = await fs.readFile(latest.fullPath, "utf8");
|
|
629
|
+
return JSON.parse(content);
|
|
630
|
+
} catch {
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// src/formatters/terminal-ui.ts
|
|
636
|
+
import * as p from "@clack/prompts";
|
|
637
|
+
import pc from "picocolors";
|
|
638
|
+
import clipboardy from "clipboardy";
|
|
639
|
+
|
|
640
|
+
// src/formatters/markdown.ts
|
|
641
|
+
function generateMarkdownReport(context, redactedOutput) {
|
|
642
|
+
const parts = [];
|
|
643
|
+
parts.push(`# Diagnostic Crash Report: \`${context.command}\``);
|
|
644
|
+
parts.push("");
|
|
645
|
+
parts.push("## Summary");
|
|
646
|
+
parts.push("| Metric | Value |");
|
|
647
|
+
parts.push("| :--- | :--- |");
|
|
648
|
+
parts.push(`| **Command** | \`${context.command}\` |`);
|
|
649
|
+
parts.push(`| **Exit Code** | \`${context.exitCode}\` |`);
|
|
650
|
+
parts.push(`| **Duration** | \`${context.durationMs}ms\` |`);
|
|
651
|
+
parts.push(`| **Timestamp** | ${context.timestamp} |`);
|
|
652
|
+
parts.push(`| **Platform** | \`${context.system.platform}\` (${context.system.arch}) |`);
|
|
653
|
+
parts.push(`| **Node Version** | \`${context.system.nodeVersion}\` |`);
|
|
654
|
+
parts.push(`| **Working Dir** | \`${context.system.cwd}\` |`);
|
|
655
|
+
if (context.git) {
|
|
656
|
+
const gitInfo = [
|
|
657
|
+
context.git.branch ? `Branch: \`${context.git.branch}\`` : "",
|
|
658
|
+
context.git.commit ? `Commit: \`${context.git.commit}\`` : "",
|
|
659
|
+
context.git.isDirty !== void 0 ? `Working Tree: ${context.git.isDirty ? "Dirty" : "Clean"}` : ""
|
|
660
|
+
].filter(Boolean).join(" | ");
|
|
661
|
+
parts.push(`| **Git Context** | ${gitInfo} |`);
|
|
662
|
+
}
|
|
663
|
+
if (context.activePorts.length > 0) {
|
|
664
|
+
parts.push("");
|
|
665
|
+
parts.push("## Active Network Ports");
|
|
666
|
+
parts.push("The following ports were detected as listening/active at the time of failure:");
|
|
667
|
+
for (const p2 of context.activePorts) {
|
|
668
|
+
parts.push(`- **Port ${p2.port}**: In use (${p2.details || "Active listener"})`);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
parts.push("");
|
|
672
|
+
parts.push("## Captured Terminal Output (Trailing 64KB)");
|
|
673
|
+
parts.push("*(All credentials, tokens, DB passwords, and sensitive environment variables have been automatically scrubbed)*");
|
|
674
|
+
parts.push("");
|
|
675
|
+
parts.push("```text");
|
|
676
|
+
parts.push(redactedOutput.trim() || "[No output captured]");
|
|
677
|
+
parts.push("```");
|
|
678
|
+
parts.push("");
|
|
679
|
+
parts.push("<details>");
|
|
680
|
+
parts.push("<summary><strong>System & Environment Diagnostics</strong></summary>");
|
|
681
|
+
parts.push("");
|
|
682
|
+
parts.push("### Hardware & OS");
|
|
683
|
+
parts.push(`- **OS Release:** ${context.system.osRelease}`);
|
|
684
|
+
parts.push(`- **CPUs:** ${context.system.cpuCount}`);
|
|
685
|
+
parts.push(`- **Memory:** ${context.system.freeMemoryMB} MB free / ${context.system.totalMemoryMB} MB total`);
|
|
686
|
+
parts.push("");
|
|
687
|
+
const envEntries = Object.entries(context.environment);
|
|
688
|
+
if (envEntries.length > 0) {
|
|
689
|
+
parts.push("### Relevant Environment Variables");
|
|
690
|
+
parts.push("| Variable | Value |");
|
|
691
|
+
parts.push("| :--- | :--- |");
|
|
692
|
+
for (const [key, val] of envEntries) {
|
|
693
|
+
parts.push(`| \`${key}\` | \`${val}\` |`);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
parts.push("</details>");
|
|
697
|
+
parts.push("");
|
|
698
|
+
parts.push("---");
|
|
699
|
+
parts.push("### Instructions for LLM");
|
|
700
|
+
parts.push(
|
|
701
|
+
"> Please analyze the crash log above, diagnose the root cause of the failure, highlight any missing dependencies or environment conflicts, and provide a concrete step-by-step fix."
|
|
702
|
+
);
|
|
703
|
+
return parts.join("\n");
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// src/formatters/terminal-ui.ts
|
|
707
|
+
async function showPostCrashUI(options) {
|
|
708
|
+
const { context, redactedOutput, snapshotPath } = options;
|
|
709
|
+
const markdownReport = generateMarkdownReport(context, redactedOutput);
|
|
710
|
+
if (!process.stdin.isTTY || process.stdin.destroyed || !process.stdin.readable) {
|
|
711
|
+
console.error(pc.red(`
|
|
712
|
+
[wtf] Command failed with exit code ${context.exitCode}: ${context.command}`));
|
|
713
|
+
if (snapshotPath) {
|
|
714
|
+
console.error(pc.dim(`[wtf] Diagnostic snapshot saved to: ${snapshotPath}`));
|
|
715
|
+
console.error(pc.cyan(`[wtf] Run 'wtf last' to view or copy the LLM diagnostic report.
|
|
716
|
+
`));
|
|
717
|
+
}
|
|
718
|
+
return "exit";
|
|
719
|
+
}
|
|
720
|
+
try {
|
|
721
|
+
if (process.stdin.isPaused()) {
|
|
722
|
+
process.stdin.resume();
|
|
723
|
+
}
|
|
724
|
+
p.intro(pc.bgRed(pc.white(pc.bold(" WTF Just Happened? Command Crashed "))));
|
|
725
|
+
p.note(
|
|
726
|
+
[
|
|
727
|
+
`${pc.bold("Command:")} ${pc.cyan(context.command)}`,
|
|
728
|
+
`${pc.bold("Exit Code:")} ${pc.red(String(context.exitCode))}`,
|
|
729
|
+
`${pc.bold("Duration:")} ${context.durationMs}ms`,
|
|
730
|
+
snapshotPath ? `${pc.bold("Snapshot:")} ${pc.dim(snapshotPath)}` : "",
|
|
731
|
+
context.activePorts.length > 0 ? `${pc.bold("Active Ports:")} ${pc.yellow(context.activePorts.map((p2) => p2.port).join(", "))}` : ""
|
|
732
|
+
].filter(Boolean).join("\n"),
|
|
733
|
+
"Crash Summary"
|
|
734
|
+
);
|
|
735
|
+
let active = true;
|
|
736
|
+
while (active) {
|
|
737
|
+
let choice;
|
|
738
|
+
try {
|
|
739
|
+
choice = await p.select({
|
|
740
|
+
message: "What would you like to do?",
|
|
741
|
+
options: [
|
|
742
|
+
{
|
|
743
|
+
value: "copy",
|
|
744
|
+
label: "Copy Markdown Report",
|
|
745
|
+
hint: "Ready-to-paste for ChatGPT, Claude, GitHub Issues"
|
|
746
|
+
},
|
|
747
|
+
{
|
|
748
|
+
value: "view-output",
|
|
749
|
+
label: "View Redacted Terminal Output",
|
|
750
|
+
hint: "Shows trailing captured logs"
|
|
751
|
+
},
|
|
752
|
+
{
|
|
753
|
+
value: "view-markdown",
|
|
754
|
+
label: "Print Full Markdown Report",
|
|
755
|
+
hint: "Outputs raw markdown in console"
|
|
756
|
+
},
|
|
757
|
+
{
|
|
758
|
+
value: "view-env",
|
|
759
|
+
label: "View Environment & System Context",
|
|
760
|
+
hint: "Inspect sanitized env vars and OS specs"
|
|
761
|
+
},
|
|
762
|
+
{
|
|
763
|
+
value: "rerun",
|
|
764
|
+
label: "Re-run Command",
|
|
765
|
+
hint: "Attempt executing the command again"
|
|
766
|
+
},
|
|
767
|
+
{
|
|
768
|
+
value: "exit",
|
|
769
|
+
label: "Exit",
|
|
770
|
+
hint: `Exits with code ${context.exitCode}`
|
|
771
|
+
}
|
|
772
|
+
]
|
|
773
|
+
});
|
|
774
|
+
} catch {
|
|
775
|
+
return "exit";
|
|
776
|
+
}
|
|
777
|
+
if (p.isCancel(choice) || choice === "exit") {
|
|
778
|
+
p.outro(pc.dim(`Exiting.`));
|
|
779
|
+
return "exit";
|
|
780
|
+
}
|
|
781
|
+
if (choice === "copy") {
|
|
782
|
+
try {
|
|
783
|
+
await clipboardy.write(markdownReport);
|
|
784
|
+
p.log.success(pc.green("Markdown diagnostic report copied to clipboard."));
|
|
785
|
+
} catch (err) {
|
|
786
|
+
p.log.error(pc.red(`Failed to copy to clipboard: ${err.message}`));
|
|
787
|
+
}
|
|
788
|
+
} else if (choice === "view-output") {
|
|
789
|
+
console.log("\n" + pc.dim("--- Captured Output (Redacted) ---"));
|
|
790
|
+
console.log(redactedOutput.trim() || pc.dim("[No output captured]"));
|
|
791
|
+
console.log(pc.dim("-----------------------------------\n"));
|
|
792
|
+
} else if (choice === "view-markdown") {
|
|
793
|
+
console.log("\n" + markdownReport + "\n");
|
|
794
|
+
} else if (choice === "view-env") {
|
|
795
|
+
console.log("\n" + pc.dim("--- Environment & System Context ---"));
|
|
796
|
+
console.log(`${pc.bold("Platform:")} ${context.system.platform} (${context.system.arch})`);
|
|
797
|
+
console.log(`${pc.bold("OS Release:")} ${context.system.osRelease}`);
|
|
798
|
+
console.log(`${pc.bold("Node:")} ${context.system.nodeVersion}`);
|
|
799
|
+
console.log(`${pc.bold("CWD:")} ${context.system.cwd}`);
|
|
800
|
+
console.log(`${pc.bold("Memory:")} ${context.system.freeMemoryMB}MB free / ${context.system.totalMemoryMB}MB total`);
|
|
801
|
+
console.log(pc.bold("\nSanitized Environment:"));
|
|
802
|
+
for (const [k, v] of Object.entries(context.environment)) {
|
|
803
|
+
console.log(` ${pc.cyan(k)}=${pc.yellow(v)}`);
|
|
804
|
+
}
|
|
805
|
+
console.log(pc.dim("------------------------------------\n"));
|
|
806
|
+
} else if (choice === "rerun") {
|
|
807
|
+
p.outro(pc.cyan(`Re-running: ${context.command}...`));
|
|
808
|
+
return "rerun";
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
return "exit";
|
|
812
|
+
} catch {
|
|
813
|
+
console.error(pc.red(`
|
|
814
|
+
[wtf] Command failed with exit code ${context.exitCode}: ${context.command}`));
|
|
815
|
+
if (snapshotPath) {
|
|
816
|
+
console.error(pc.dim(`[wtf] Diagnostic snapshot saved to: ${snapshotPath}`));
|
|
817
|
+
console.error(pc.cyan(`[wtf] Run 'wtf last' to view or copy the LLM diagnostic report.
|
|
818
|
+
`));
|
|
819
|
+
}
|
|
820
|
+
return "exit";
|
|
821
|
+
}
|
|
822
|
+
return "exit";
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// src/cli.ts
|
|
826
|
+
var VERSION = "1.0.0";
|
|
827
|
+
function printHelp() {
|
|
828
|
+
console.log(`
|
|
829
|
+
${pc2.bold(pc2.cyan("wtf-just-happened"))} ${pc2.dim(`v${VERSION}`)} (alias: ${pc2.bold("wtf")})
|
|
830
|
+
Transparent PTY wrapper for instant post-crash diagnostics and LLM reporting.
|
|
831
|
+
|
|
832
|
+
${pc2.bold("USAGE:")}
|
|
833
|
+
wtf <command> [args...]
|
|
834
|
+
wtf last
|
|
835
|
+
wtf --demo
|
|
836
|
+
wtf --help
|
|
837
|
+
|
|
838
|
+
${pc2.bold("EXAMPLES:")}
|
|
839
|
+
${pc2.dim("# Runs normally and stays completely invisible if successful")}
|
|
840
|
+
wtf npm run build
|
|
841
|
+
wtf docker compose up
|
|
842
|
+
wtf cargo test
|
|
843
|
+
|
|
844
|
+
${pc2.dim("# Re-open interactive menu for the most recent crash")}
|
|
845
|
+
wtf last
|
|
846
|
+
|
|
847
|
+
${pc2.dim("# Try an interactive demo crash simulation")}
|
|
848
|
+
wtf --demo
|
|
849
|
+
|
|
850
|
+
${pc2.bold("OPTIONS:")}
|
|
851
|
+
-h, --help Show this help message
|
|
852
|
+
-v, --version Show version number
|
|
853
|
+
--demo Simulate a crash to test the interactive diagnostic menu
|
|
854
|
+
last View or copy report from the most recent crash snapshot
|
|
855
|
+
`);
|
|
856
|
+
}
|
|
857
|
+
async function handleLast() {
|
|
858
|
+
const lastCrash = await getLastCrash();
|
|
859
|
+
if (!lastCrash) {
|
|
860
|
+
console.log(pc2.yellow("\n[!] No crash snapshots found in ~/.wtf/crashes/\n"));
|
|
861
|
+
process.exit(0);
|
|
862
|
+
}
|
|
863
|
+
console.log(pc2.dim(`
|
|
864
|
+
Loading last crash from ${lastCrash.savedAt}...`));
|
|
865
|
+
await showPostCrashUI({
|
|
866
|
+
context: lastCrash.context,
|
|
867
|
+
redactedOutput: lastCrash.redactedOutput
|
|
868
|
+
});
|
|
869
|
+
process.exit(0);
|
|
870
|
+
}
|
|
871
|
+
async function handleDemo() {
|
|
872
|
+
console.log(pc2.cyan("Simulating a realistic build failure...\n"));
|
|
873
|
+
const demoOutput = `
|
|
874
|
+
[INFO] Starting build for @acme/api-service...
|
|
875
|
+
[INFO] Loading configuration from .env.production
|
|
876
|
+
[DEBUG] Connecting to postgres://admin:supersecret123@localhost:5432/prod
|
|
877
|
+
[DEBUG] Initializing AWS S3 with key AKIAIOSFODNN7EXAMPLE
|
|
878
|
+
[ERROR] Build error: Unhandled exception in src/server.ts:42:15
|
|
879
|
+
Error: Database connection refused at 127.0.0.1:5432
|
|
880
|
+
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1605:16)
|
|
881
|
+
at runMicrotasks (<anonymous>)
|
|
882
|
+
at processTicksAndRejections (node:internal/process/task_queues:95:5)
|
|
883
|
+
[FATAL] Command exited with code 1
|
|
884
|
+
`;
|
|
885
|
+
const cleanOutput = demoOutput.trim();
|
|
886
|
+
const redactedOutput = redactSecrets(cleanOutput);
|
|
887
|
+
const context = await collectCrashContext({
|
|
888
|
+
command: "fake-build --prod",
|
|
889
|
+
exitCode: 1,
|
|
890
|
+
durationMs: 1420,
|
|
891
|
+
cleanOutputTail: cleanOutput,
|
|
892
|
+
rawOutputTail: cleanOutput
|
|
893
|
+
});
|
|
894
|
+
const snapshotPath = await saveCrash(context, redactedOutput);
|
|
895
|
+
await showPostCrashUI({
|
|
896
|
+
context,
|
|
897
|
+
redactedOutput,
|
|
898
|
+
snapshotPath
|
|
899
|
+
});
|
|
900
|
+
process.exit(1);
|
|
901
|
+
}
|
|
902
|
+
function hasErrorsInOutput(cleanOutput) {
|
|
903
|
+
if (!cleanOutput || cleanOutput.trim().length === 0) return false;
|
|
904
|
+
const errorIndicators = [
|
|
905
|
+
/\[vite\]\s*(?:internal\s*)?error/i,
|
|
906
|
+
/transform\s*failed/i,
|
|
907
|
+
/failed\s*to\s*(?:compile|bundle|resolve|load|parse|build)/i,
|
|
908
|
+
/syntaxerror:/i,
|
|
909
|
+
/typeerror:/i,
|
|
910
|
+
/referenceerror:/i,
|
|
911
|
+
/unhandled\s*rejection/i,
|
|
912
|
+
/uncaught\s*exception/i,
|
|
913
|
+
/eaddrinuse/i,
|
|
914
|
+
/error:\s*[A-Z]/i,
|
|
915
|
+
/fatal\s*error/i,
|
|
916
|
+
/\bERR!/i,
|
|
917
|
+
/at\s+[a-zA-Z0-9_$.<>]+\s+\([^)]+:\d+:\d+\)/i
|
|
918
|
+
];
|
|
919
|
+
return errorIndicators.some((pattern) => pattern.test(cleanOutput));
|
|
920
|
+
}
|
|
921
|
+
async function executeCommand(command, args) {
|
|
922
|
+
let shouldRun = true;
|
|
923
|
+
while (shouldRun) {
|
|
924
|
+
const ringBuffer = new RingBuffer({ maxBytes: 64 * 1024 });
|
|
925
|
+
const result = await runCommandWithPty(command, args, { ringBuffer });
|
|
926
|
+
if (result.exitCode === 0) {
|
|
927
|
+
process.exit(0);
|
|
928
|
+
}
|
|
929
|
+
if (result.userInterrupted) {
|
|
930
|
+
const hasErrors = hasErrorsInOutput(result.outputTailClean);
|
|
931
|
+
if (!hasErrors) {
|
|
932
|
+
process.exit(0);
|
|
933
|
+
}
|
|
934
|
+
const redactedOutput2 = redactSecrets(result.outputTailClean);
|
|
935
|
+
const context2 = await collectCrashContext({
|
|
936
|
+
command: `${command} ${args.join(" ")}`.trim(),
|
|
937
|
+
exitCode: result.exitCode,
|
|
938
|
+
durationMs: result.durationMs,
|
|
939
|
+
cleanOutputTail: result.outputTailClean,
|
|
940
|
+
rawOutputTail: result.outputTailRaw
|
|
941
|
+
});
|
|
942
|
+
let snapshotPath2;
|
|
943
|
+
try {
|
|
944
|
+
snapshotPath2 = await saveCrash(context2, redactedOutput2);
|
|
945
|
+
} catch {
|
|
946
|
+
}
|
|
947
|
+
await showPostCrashUI({
|
|
948
|
+
context: context2,
|
|
949
|
+
redactedOutput: redactedOutput2,
|
|
950
|
+
snapshotPath: snapshotPath2
|
|
951
|
+
});
|
|
952
|
+
process.exit(0);
|
|
953
|
+
}
|
|
954
|
+
const redactedOutput = redactSecrets(result.outputTailClean);
|
|
955
|
+
const context = await collectCrashContext({
|
|
956
|
+
command: `${command} ${args.join(" ")}`.trim(),
|
|
957
|
+
exitCode: result.exitCode,
|
|
958
|
+
durationMs: result.durationMs,
|
|
959
|
+
cleanOutputTail: result.outputTailClean,
|
|
960
|
+
rawOutputTail: result.outputTailRaw
|
|
961
|
+
});
|
|
962
|
+
let snapshotPath;
|
|
963
|
+
try {
|
|
964
|
+
snapshotPath = await saveCrash(context, redactedOutput);
|
|
965
|
+
} catch {
|
|
966
|
+
}
|
|
967
|
+
const action = await showPostCrashUI({
|
|
968
|
+
context,
|
|
969
|
+
redactedOutput,
|
|
970
|
+
snapshotPath
|
|
971
|
+
});
|
|
972
|
+
if (action === "rerun") {
|
|
973
|
+
console.log("\n" + pc2.dim("----------------------------------------") + "\n");
|
|
974
|
+
shouldRun = true;
|
|
975
|
+
} else {
|
|
976
|
+
shouldRun = false;
|
|
977
|
+
process.exit(result.exitCode);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
async function main() {
|
|
982
|
+
const rawArgs = process.argv.slice(2);
|
|
983
|
+
if (rawArgs.length === 0 || rawArgs.includes("--help") || rawArgs.includes("-h")) {
|
|
984
|
+
printHelp();
|
|
985
|
+
process.exit(0);
|
|
986
|
+
}
|
|
987
|
+
if (rawArgs.includes("--version") || rawArgs.includes("-v")) {
|
|
988
|
+
console.log(`wtf-just-happened v${VERSION}`);
|
|
989
|
+
process.exit(0);
|
|
990
|
+
}
|
|
991
|
+
if (rawArgs[0] === "last") {
|
|
992
|
+
await handleLast();
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
if (rawArgs.includes("--demo")) {
|
|
996
|
+
await handleDemo();
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
const [command, ...args] = rawArgs;
|
|
1000
|
+
await executeCommand(command, args);
|
|
1001
|
+
}
|
|
1002
|
+
main().catch((err) => {
|
|
1003
|
+
console.error(pc2.red(`
|
|
1004
|
+
[wtf] Unexpected error: ${err.message}`));
|
|
1005
|
+
process.exit(1);
|
|
1006
|
+
});
|
|
1007
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/core/pty-runner.ts","../src/core/ring-buffer.ts","../src/core/collector.ts","../src/security/redactor.ts","../src/utils/storage.ts","../src/formatters/terminal-ui.ts","../src/formatters/markdown.ts"],"sourcesContent":["import pc from \"picocolors\";\nimport { runCommandWithPty } from \"./core/pty-runner.js\";\nimport { RingBuffer } from \"./core/ring-buffer.js\";\nimport { collectCrashContext } from \"./core/collector.js\";\nimport { redactSecrets } from \"./security/redactor.js\";\nimport { saveCrash, getLastCrash } from \"./utils/storage.js\";\nimport { showPostCrashUI } from \"./formatters/terminal-ui.js\";\n\nconst VERSION = \"1.0.0\";\n\nfunction printHelp(): void {\n console.log(`\n${pc.bold(pc.cyan(\"wtf-just-happened\"))} ${pc.dim(`v${VERSION}`)} (alias: ${pc.bold(\"wtf\")})\nTransparent PTY wrapper for instant post-crash diagnostics and LLM reporting.\n\n${pc.bold(\"USAGE:\")}\n wtf <command> [args...]\n wtf last\n wtf --demo\n wtf --help\n\n${pc.bold(\"EXAMPLES:\")}\n ${pc.dim(\"# Runs normally and stays completely invisible if successful\")}\n wtf npm run build\n wtf docker compose up\n wtf cargo test\n\n ${pc.dim(\"# Re-open interactive menu for the most recent crash\")}\n wtf last\n\n ${pc.dim(\"# Try an interactive demo crash simulation\")}\n wtf --demo\n\n${pc.bold(\"OPTIONS:\")}\n -h, --help Show this help message\n -v, --version Show version number\n --demo Simulate a crash to test the interactive diagnostic menu\n last View or copy report from the most recent crash snapshot\n`);\n}\n\nasync function handleLast(): Promise<void> {\n const lastCrash = await getLastCrash();\n if (!lastCrash) {\n console.log(pc.yellow(\"\\n[!] No crash snapshots found in ~/.wtf/crashes/\\n\"));\n process.exit(0);\n }\n\n console.log(pc.dim(`\\nLoading last crash from ${lastCrash.savedAt}...`));\n await showPostCrashUI({\n context: lastCrash.context,\n redactedOutput: lastCrash.redactedOutput,\n });\n process.exit(0);\n}\n\nasync function handleDemo(): Promise<void> {\n console.log(pc.cyan(\"Simulating a realistic build failure...\\n\"));\n\n const demoOutput = `\n[INFO] Starting build for @acme/api-service...\n[INFO] Loading configuration from .env.production\n[DEBUG] Connecting to postgres://admin:supersecret123@localhost:5432/prod\n[DEBUG] Initializing AWS S3 with key AKIAIOSFODNN7EXAMPLE\n[ERROR] Build error: Unhandled exception in src/server.ts:42:15\nError: Database connection refused at 127.0.0.1:5432\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1605:16)\n at runMicrotasks (<anonymous>)\n at processTicksAndRejections (node:internal/process/task_queues:95:5)\n[FATAL] Command exited with code 1\n`;\n\n const cleanOutput = demoOutput.trim();\n const redactedOutput = redactSecrets(cleanOutput);\n\n const context = await collectCrashContext({\n command: \"fake-build --prod\",\n exitCode: 1,\n durationMs: 1420,\n cleanOutputTail: cleanOutput,\n rawOutputTail: cleanOutput,\n });\n\n const snapshotPath = await saveCrash(context, redactedOutput);\n await showPostCrashUI({\n context,\n redactedOutput,\n snapshotPath,\n });\n\n process.exit(1);\n}\n\nfunction hasErrorsInOutput(cleanOutput: string): boolean {\n if (!cleanOutput || cleanOutput.trim().length === 0) return false;\n const errorIndicators = [\n /\\[vite\\]\\s*(?:internal\\s*)?error/i,\n /transform\\s*failed/i,\n /failed\\s*to\\s*(?:compile|bundle|resolve|load|parse|build)/i,\n /syntaxerror:/i,\n /typeerror:/i,\n /referenceerror:/i,\n /unhandled\\s*rejection/i,\n /uncaught\\s*exception/i,\n /eaddrinuse/i,\n /error:\\s*[A-Z]/i,\n /fatal\\s*error/i,\n /\\bERR!/i,\n /at\\s+[a-zA-Z0-9_$.<>]+\\s+\\([^)]+:\\d+:\\d+\\)/i,\n ];\n return errorIndicators.some((pattern) => pattern.test(cleanOutput));\n}\n\nasync function executeCommand(command: string, args: string[]): Promise<void> {\n let shouldRun = true;\n\n while (shouldRun) {\n const ringBuffer = new RingBuffer({ maxBytes: 64 * 1024 });\n\n const result = await runCommandWithPty(command, args, { ringBuffer });\n\n // Transparent behavior: If command succeeded, exit cleanly with 0\n if (result.exitCode === 0) {\n process.exit(0);\n }\n\n // Check if the user manually terminated the command with Ctrl+C / SIGINT\n if (result.userInterrupted) {\n const hasErrors = hasErrorsInOutput(result.outputTailClean);\n if (!hasErrors) {\n // User stopped a clean process normally (e.g. closing dev server)\n process.exit(0);\n }\n\n // User stopped a dev server or command that had logged errors!\n const redactedOutput = redactSecrets(result.outputTailClean);\n const context = await collectCrashContext({\n command: `${command} ${args.join(\" \")}`.trim(),\n exitCode: result.exitCode,\n durationMs: result.durationMs,\n cleanOutputTail: result.outputTailClean,\n rawOutputTail: result.outputTailRaw,\n });\n\n let snapshotPath: string | undefined;\n try {\n snapshotPath = await saveCrash(context, redactedOutput);\n } catch {\n // Ignore storage errors\n }\n\n await showPostCrashUI({\n context,\n redactedOutput,\n snapshotPath,\n });\n\n process.exit(0);\n }\n\n // Command failed: Scrub secrets and collect diagnostics\n const redactedOutput = redactSecrets(result.outputTailClean);\n\n const context = await collectCrashContext({\n command: `${command} ${args.join(\" \")}`.trim(),\n exitCode: result.exitCode,\n durationMs: result.durationMs,\n cleanOutputTail: result.outputTailClean,\n rawOutputTail: result.outputTailRaw,\n });\n\n let snapshotPath: string | undefined;\n try {\n snapshotPath = await saveCrash(context, redactedOutput);\n } catch {\n // Storage error shouldn't crash the UI\n }\n\n const action = await showPostCrashUI({\n context,\n redactedOutput,\n snapshotPath,\n });\n\n if (action === \"rerun\") {\n console.log(\"\\n\" + pc.dim(\"----------------------------------------\") + \"\\n\");\n shouldRun = true;\n } else {\n shouldRun = false;\n process.exit(result.exitCode);\n }\n }\n}\n\nasync function main(): Promise<void> {\n const rawArgs = process.argv.slice(2);\n\n if (rawArgs.length === 0 || rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n printHelp();\n process.exit(0);\n }\n\n if (rawArgs.includes(\"--version\") || rawArgs.includes(\"-v\")) {\n console.log(`wtf-just-happened v${VERSION}`);\n process.exit(0);\n }\n\n if (rawArgs[0] === \"last\") {\n await handleLast();\n return;\n }\n\n if (rawArgs.includes(\"--demo\")) {\n await handleDemo();\n return;\n }\n\n const [command, ...args] = rawArgs;\n await executeCommand(command, args);\n}\n\nmain().catch((err) => {\n console.error(pc.red(`\\n[wtf] Unexpected error: ${err.message}`));\n process.exit(1);\n});\n","import { spawn as childProcessSpawn, type ChildProcess } from \"node:child_process\";\nimport { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface RunnerResult {\n exitCode: number;\n durationMs: number;\n outputTailRaw: string;\n outputTailClean: string;\n userInterrupted: boolean;\n signal?: string | number | null;\n}\n\nexport interface RunnerOptions {\n ringBuffer?: RingBuffer;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n}\n\n/**\n * Attempts to dynamically import `node-pty`. Returns undefined if unavailable or native bindings fail.\n */\nasync function loadNodePty(): Promise<any | undefined> {\n try {\n const ptyModule = await import(\"node-pty\");\n // Handle both default and named export\n return ptyModule.default || ptyModule;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Spawns a process using node-pty if available, or falls back to child_process.spawn.\n * Forwards I/O transparently and captures output in the ring buffer.\n */\nexport async function runCommandWithPty(\n command: string,\n args: string[] = [],\n options?: RunnerOptions\n): Promise<RunnerResult> {\n const ringBuffer = options?.ringBuffer ?? new RingBuffer();\n const startTime = Date.now();\n const cwd = options?.cwd ?? process.cwd();\n const env: NodeJS.ProcessEnv = options?.env ?? process.env;\n\n const nodePty = await loadNodePty();\n\n if (nodePty && typeof nodePty.spawn === \"function\") {\n try {\n return await runWithNodePty(nodePty, command, args, ringBuffer, cwd, env, startTime);\n } catch {\n // If node-pty fails during execution, fall through to fallback\n }\n }\n\n // Fallback to standard child_process.spawn\n return await runWithChildProcess(command, args, ringBuffer, cwd, env, startTime);\n}\n\n/**\n * PTY runner using node-pty\n */\nfunction runWithNodePty(\n pty: any,\n command: string,\n args: string[],\n ringBuffer: RingBuffer,\n cwd: string,\n env: NodeJS.ProcessEnv,\n startTime: number\n): Promise<RunnerResult> {\n return new Promise((resolve, reject) => {\n const isWindows = process.platform === \"win32\";\n const cols = process.stdout.columns || 80;\n const rows = process.stdout.rows || 24;\n\n let ptyProcess: any;\n try {\n const file = isWindows && [\"npm\", \"npx\", \"pnpm\", \"yarn\"].includes(command.toLowerCase())\n ? `${command}.cmd`\n : command;\n ptyProcess = pty.spawn(file, args, {\n name: \"xterm-256color\",\n cols,\n rows,\n cwd,\n env: env as Record<string, string>,\n useConpty: isWindows,\n });\n } catch (err) {\n reject(err);\n return;\n }\n\n let userInterrupted = false;\n const onSigInt = () => {\n userInterrupted = true;\n };\n process.on(\"SIGINT\", onSigInt);\n\n // Set stdin to raw mode to forward all keystrokes transparently\n const wasRaw = process.stdin.isRaw;\n if (process.stdin.isTTY && typeof process.stdin.setRawMode === \"function\") {\n process.stdin.setRawMode(true);\n process.stdin.resume();\n }\n\n const onStdinData = (data: Buffer) => {\n if (data.includes(3)) {\n // Ctrl+C in raw mode\n userInterrupted = true;\n }\n try {\n ptyProcess.write(data.toString());\n } catch {\n // Ignore write errors if process closed\n }\n };\n\n const onResize = () => {\n try {\n if (process.stdout.columns && process.stdout.rows) {\n ptyProcess.resize(process.stdout.columns, process.stdout.rows);\n }\n } catch {\n // Ignore resize errors\n }\n };\n\n process.stdin.on(\"data\", onStdinData);\n process.stdout.on(\"resize\", onResize);\n\n ptyProcess.onData((data: string) => {\n ringBuffer.write(data);\n process.stdout.write(data);\n });\n\n ptyProcess.onExit((event: { exitCode: number; signal?: number }) => {\n // Cleanup listeners and terminal state\n process.stdin.removeListener(\"data\", onStdinData);\n process.stdout.removeListener(\"resize\", onResize);\n process.removeListener(\"SIGINT\", onSigInt);\n\n if (process.stdin.isTTY && typeof process.stdin.setRawMode === \"function\") {\n process.stdin.setRawMode(wasRaw || false);\n process.stdin.pause();\n }\n\n const durationMs = Date.now() - startTime;\n const isWindows = process.platform === \"win32\";\n const code = event.exitCode;\n const isInterrupt =\n userInterrupted ||\n event.signal === 2 ||\n event.signal === 15 ||\n code === 130 ||\n code === 143 ||\n (isWindows && (code === 3221225786 || code === -1073741510));\n\n resolve({\n exitCode: event.exitCode ?? (event.signal ? 128 + event.signal : 1),\n durationMs,\n outputTailRaw: ringBuffer.getRaw(),\n outputTailClean: ringBuffer.getClean(),\n userInterrupted: isInterrupt,\n signal: event.signal,\n });\n });\n });\n}\n\nfunction resolveBinary(command: string): { file: string; shell: boolean } {\n if (process.platform !== \"win32\") {\n return { file: command, shell: false };\n }\n const lower = command.toLowerCase();\n // .cmd and .bat files REQUIRE shell: true in Node 20+ (CVE-2024-27980)\n if (\n lower.endsWith(\".cmd\") ||\n lower.endsWith(\".bat\") ||\n [\"npm\", \"npx\", \"pnpm\", \"yarn\", \"corepack\"].includes(lower)\n ) {\n return { file: command, shell: true };\n }\n if (\n lower.endsWith(\".exe\") ||\n [\"node\", \"git\", \"python\", \"cargo\", \"docker\", \"deno\", \"bun\", \"go\", \"rustc\"].includes(lower)\n ) {\n return { file: command, shell: false };\n }\n return { file: command, shell: true };\n}\n\n/**\n * Fallback runner using Node child_process.spawn\n */\nfunction runWithChildProcess(\n command: string,\n args: string[],\n ringBuffer: RingBuffer,\n cwd: string,\n env: NodeJS.ProcessEnv,\n startTime: number\n): Promise<RunnerResult> {\n return new Promise((resolve) => {\n const { file, shell } = resolveBinary(command);\n\n let child: ChildProcess;\n try {\n child = childProcessSpawn(file, args, {\n cwd,\n env,\n shell,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n });\n } catch (err: any) {\n const errorMsg = `\\nFailed to start process \"${command}\": ${err.message}\\n`;\n ringBuffer.write(errorMsg);\n process.stderr.write(errorMsg);\n const durationMs = Date.now() - startTime;\n resolve({\n exitCode: 1,\n durationMs,\n outputTailRaw: ringBuffer.getRaw(),\n outputTailClean: ringBuffer.getClean(),\n userInterrupted: false,\n });\n return;\n }\n\n if (child.stdout) {\n child.stdout.on(\"data\", (chunk: Buffer) => {\n ringBuffer.write(chunk);\n process.stdout.write(chunk);\n });\n }\n\n if (child.stderr) {\n child.stderr.on(\"data\", (chunk: Buffer) => {\n ringBuffer.write(chunk);\n process.stderr.write(chunk);\n });\n }\n\n let userInterrupted = false;\n const onSigInt = () => {\n userInterrupted = true;\n };\n process.on(\"SIGINT\", onSigInt);\n\n child.on(\"error\", (err: Error) => {\n process.removeListener(\"SIGINT\", onSigInt);\n const errorMsg = `\\nFailed to start process \"${command}\": ${err.message}\\n`;\n ringBuffer.write(errorMsg);\n process.stderr.write(errorMsg);\n const durationMs = Date.now() - startTime;\n resolve({\n exitCode: 1,\n durationMs,\n outputTailRaw: ringBuffer.getRaw(),\n outputTailClean: ringBuffer.getClean(),\n userInterrupted: false,\n });\n });\n\n child.on(\"close\", (code: number | null, signal: NodeJS.Signals | null) => {\n process.removeListener(\"SIGINT\", onSigInt);\n const durationMs = Date.now() - startTime;\n const isWindows = process.platform === \"win32\";\n\n const isInterrupt =\n userInterrupted ||\n signal === \"SIGINT\" ||\n signal === \"SIGTERM\" ||\n code === 130 ||\n code === 143 ||\n (isWindows && (code === 3221225786 || code === -1073741510));\n\n const exitCode = code !== null ? code : (signal ? 128 : 1);\n resolve({\n exitCode,\n durationMs,\n outputTailRaw: ringBuffer.getRaw(),\n outputTailClean: ringBuffer.getClean(),\n userInterrupted: isInterrupt,\n signal,\n });\n });\n });\n}\n","import stripAnsi from \"strip-ansi\";\n\nexport interface RingBufferOptions {\n maxBytes?: number;\n}\n\nexport class RingBuffer {\n private chunks: string[] = [];\n private currentBytes = 0;\n readonly maxBytes: number;\n\n constructor(options?: RingBufferOptions) {\n this.maxBytes = options?.maxBytes ?? 64 * 1024; // Default 64KB\n }\n\n /**\n * Append a chunk of text or Buffer to the circular buffer.\n */\n write(data: string | Buffer): void {\n const text = typeof data === \"string\" ? data : data.toString(\"utf8\");\n if (!text) return;\n\n const chunkBytes = Buffer.byteLength(text, \"utf8\");\n\n // If a single chunk is larger than maxBytes, keep only its tail\n if (chunkBytes >= this.maxBytes) {\n const buf = Buffer.from(text, \"utf8\");\n const tailBuf = buf.subarray(buf.length - this.maxBytes);\n this.chunks = [tailBuf.toString(\"utf8\")];\n this.currentBytes = Buffer.byteLength(this.chunks[0], \"utf8\");\n return;\n }\n\n this.chunks.push(text);\n this.currentBytes += chunkBytes;\n\n // Evict chunks from head until currentBytes <= maxBytes\n while (this.chunks.length > 0 && this.currentBytes > this.maxBytes) {\n const headChunk = this.chunks[0];\n const headBytes = Buffer.byteLength(headChunk, \"utf8\");\n const excess = this.currentBytes - this.maxBytes;\n\n if (headBytes <= excess) {\n this.chunks.shift();\n this.currentBytes -= headBytes;\n } else {\n // Trim head chunk\n const headBuf = Buffer.from(headChunk, \"utf8\");\n const trimmedBuf = headBuf.subarray(excess);\n const trimmedStr = trimmedBuf.toString(\"utf8\");\n this.chunks[0] = trimmedStr;\n this.currentBytes = this.currentBytes - headBytes + Buffer.byteLength(trimmedStr, \"utf8\");\n break;\n }\n }\n }\n\n /**\n * Get raw output including ANSI escape sequences.\n */\n getRaw(): string {\n return this.chunks.join(\"\");\n }\n\n /**\n * Get clean output with ANSI escape sequences stripped.\n */\n getClean(): string {\n return stripAnsi(this.getRaw());\n }\n\n /**\n * Get the current byte length of stored content.\n */\n get byteLength(): number {\n return this.currentBytes;\n }\n\n /**\n * Clear the ring buffer.\n */\n clear(): void {\n this.chunks = [];\n this.currentBytes = 0;\n }\n}\n","import os from \"node:os\";\nimport { exec } from \"node:child_process\";\nimport net from \"node:net\";\nimport { sanitizeEnvironment } from \"../security/redactor.js\";\n\nexport interface GitContext {\n branch?: string;\n commit?: string;\n isDirty?: boolean;\n statusSummary?: string;\n}\n\nexport interface SystemContext {\n platform: string;\n osRelease: string;\n arch: string;\n nodeVersion: string;\n cwd: string;\n totalMemoryMB: number;\n freeMemoryMB: number;\n cpuCount: number;\n}\n\nexport interface PortContext {\n port: number;\n inUse: boolean;\n details?: string;\n}\n\nexport interface CrashContext {\n command: string;\n exitCode: number;\n durationMs: number;\n timestamp: string;\n system: SystemContext;\n git?: GitContext;\n activePorts: PortContext[];\n environment: Record<string, string>;\n rawOutputTail: string;\n cleanOutputTail: string;\n}\n\n/**\n * Wraps any promise with a strict millisecond timeout.\n */\nfunction withTimeout<T>(promise: Promise<T>, ms = 200, fallback: T): Promise<T> {\n return new Promise<T>((resolve) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (!settled) {\n settled = true;\n resolve(fallback);\n }\n }, ms);\n\n promise\n .then((val) => {\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n resolve(val);\n }\n })\n .catch(() => {\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n resolve(fallback);\n }\n });\n });\n}\n\nfunction execAsync(cmd: string, timeoutMs = 180): Promise<string> {\n return new Promise((resolve, reject) => {\n exec(cmd, { timeout: timeoutMs, windowsHide: true }, (err, stdout) => {\n if (err) {\n reject(err);\n } else {\n resolve(stdout.trim());\n }\n });\n });\n}\n\n/**\n * Collect Git information within timeout.\n */\nasync function collectGit(): Promise<GitContext | undefined> {\n try {\n const [branchResult, commitResult, statusResult] = await Promise.allSettled([\n execAsync(\"git rev-parse --abbrev-ref HEAD\"),\n execAsync(\"git log -1 --oneline\"),\n execAsync(\"git status --porcelain\"),\n ]);\n\n const branch = branchResult.status === \"fulfilled\" ? branchResult.value : undefined;\n const commit = commitResult.status === \"fulfilled\" ? commitResult.value : undefined;\n const status = statusResult.status === \"fulfilled\" ? statusResult.value : \"\";\n\n if (!branch && !commit) {\n return undefined;\n }\n\n return {\n branch,\n commit,\n isDirty: status.length > 0,\n statusSummary: status ? `${status.split(\"\\n\").length} modified files` : \"clean\",\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Checks if a specific port is in use by attempting a quick connection.\n */\nfunction checkPortInUse(port: number, timeoutMs = 150): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let isConnected = false;\n\n socket.setTimeout(timeoutMs);\n\n socket.once(\"connect\", () => {\n isConnected = true;\n socket.destroy();\n resolve(true);\n });\n\n socket.once(\"timeout\", () => {\n socket.destroy();\n resolve(false);\n });\n\n socket.once(\"error\", () => {\n socket.destroy();\n resolve(false);\n });\n\n socket.connect(port, \"127.0.0.1\");\n });\n}\n\n/**\n * Inspect active ports, especially scanning ports mentioned in terminal output or standard dev ports.\n */\nasync function collectPorts(cleanOutput: string): Promise<PortContext[]> {\n const candidatePorts = new Set<number>([3000, 3001, 5173, 8080, 8000, 5000, 5432, 27017, 3306]);\n\n // Extract ports mentioned in error logs (e.g. \"port 3000\", \"EADDRINUSE :::3000\", \"localhost:3000\")\n const portRegex = /(?:port\\s*[:=]?\\s*|EADDRINUSE.*?|127\\.0\\.0\\.1:|localhost:)(\\d{2,5})\\b/gi;\n let match: RegExpExecArray | null;\n while ((match = portRegex.exec(cleanOutput)) !== null) {\n const p = parseInt(match[1], 10);\n if (p > 0 && p <= 65535) {\n candidatePorts.add(p);\n }\n }\n\n const results: PortContext[] = [];\n const checks = Array.from(candidatePorts).map(async (port) => {\n try {\n const inUse = await checkPortInUse(port, 150);\n if (inUse) {\n results.push({ port, inUse: true, details: `Port ${port} is currently bound/listening` });\n }\n } catch {\n // Ignore individual port check failures\n }\n });\n\n await Promise.allSettled(checks);\n return results.sort((a, b) => a.port - b.port);\n}\n\n/**\n * Filter relevant environment variables for debugging while excluding huge/noisy or sensitive ones.\n */\nfunction collectRelevantEnv(): Record<string, string> {\n const allowList = [\n \"NODE_ENV\",\n \"CI\",\n \"DEBUG\",\n \"SHELL\",\n \"TERM\",\n \"TERM_PROGRAM\",\n \"PATH\",\n \"LANG\",\n \"LC_ALL\",\n \"PORT\",\n \"HOST\",\n \"PWD\",\n \"NVM_BIN\",\n ];\n\n const filtered: Record<string, string | undefined> = {};\n for (const key of allowList) {\n if (process.env[key] !== undefined) {\n filtered[key] = process.env[key];\n }\n }\n\n // Also include any user-defined app variables starting with VITE_, NEXT_PUBLIC_, REACT_APP_, etc.\n for (const [key, val] of Object.entries(process.env)) {\n if (/^(?:VITE_|NEXT_PUBLIC_|REACT_APP_|PUBLIC_|APP_)/i.test(key)) {\n filtered[key] = val;\n }\n }\n\n return sanitizeEnvironment(filtered);\n}\n\nexport interface CollectOptions {\n command: string;\n exitCode: number;\n durationMs: number;\n cleanOutputTail: string;\n rawOutputTail: string;\n}\n\n/**\n * Parallel context collector running all checks concurrently with a strict 200ms timeout per check.\n */\nexport async function collectCrashContext(options: CollectOptions): Promise<CrashContext> {\n const timestamp = new Date().toISOString();\n\n const system: SystemContext = {\n platform: os.platform(),\n osRelease: os.release(),\n arch: os.arch(),\n nodeVersion: process.version,\n cwd: process.cwd(),\n totalMemoryMB: Math.round(os.totalmem() / (1024 * 1024)),\n freeMemoryMB: Math.round(os.freemem() / (1024 * 1024)),\n cpuCount: os.cpus().length,\n };\n\n const [gitResult, portsResult, envResult] = await Promise.allSettled([\n withTimeout(collectGit(), 200, undefined),\n withTimeout(collectPorts(options.cleanOutputTail), 200, []),\n withTimeout(Promise.resolve(collectRelevantEnv()), 200, {}),\n ]);\n\n const git = gitResult.status === \"fulfilled\" ? gitResult.value : undefined;\n const activePorts = portsResult.status === \"fulfilled\" ? portsResult.value : [];\n const environment = envResult.status === \"fulfilled\" ? envResult.value : {};\n\n return {\n command: options.command,\n exitCode: options.exitCode,\n durationMs: options.durationMs,\n timestamp,\n system,\n git,\n activePorts,\n environment,\n rawOutputTail: options.rawOutputTail,\n cleanOutputTail: options.cleanOutputTail,\n };\n}\n","/**\n * Two-pass secret scrubber:\n * Pass 1: Active environment variable values matching sensitive keys\n * Pass 2: High-confidence regex patterns for AWS keys, JWTs, Bearer tokens, DB URIs, and API tokens\n */\n\nexport interface RedactorOptions {\n env?: Record<string, string | undefined>;\n}\n\n// Keys that likely contain sensitive values\nconst SENSITIVE_KEY_PATTERN = /(?:key|token|secret|password|passwd|auth|credential|api[_-]?key|private|access[_-]?key)/i;\n\n// Regex patterns for known secret formats\nconst SECRET_PATTERNS: Array<{ name: string; regex: RegExp; replace: (match: string, ...args: any[]) => string }> = [\n // Private Keys (RSA, EC, PGP, etc.)\n {\n name: \"Private Key\",\n regex: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\\s\\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,\n replace: () => \"[REDACTED_PRIVATE_KEY]\",\n },\n // Database connection URIs with password: protocol://user:password@host\n {\n name: \"Database URI Password\",\n regex: /\\b([a-zA-Z][a-zA-Z0-9+.-]*:\\/\\/)([^:\\s\\/]+):(.+?)@([a-zA-Z0-9_.-]+(?::\\d+)?(?:\\/|[?#\\s]|$))/g,\n replace: (_match, proto, user, _pwd, host) => `${proto}${user}:[REDACTED]@${host}`,\n },\n // AWS Access Key ID\n {\n name: \"AWS Access Key\",\n regex: /\\b(AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\\b/g,\n replace: () => \"[REDACTED_AWS_KEY]\",\n },\n // GitHub Tokens (classic and fine-grained)\n {\n name: \"GitHub Token\",\n regex: /\\b(gh[pousr]_[A-Za-z0-9_]{36,255}|github_pat_[A-Za-z0-9_]{82})\\b/g,\n replace: () => \"[REDACTED_GITHUB_TOKEN]\",\n },\n // Slack Tokens\n {\n name: \"Slack Token\",\n regex: /\\bxox[baprs]-[0-9a-zA-Z]{10,48}\\b/g,\n replace: () => \"[REDACTED_SLACK_TOKEN]\",\n },\n // Stripe API Keys\n {\n name: \"Stripe Key\",\n regex: /\\b[rs]k_(?:test|live)_[0-9a-zA-Z]{24,99}\\b/g,\n replace: () => \"[REDACTED_STRIPE_KEY]\",\n },\n // JWT Tokens (3-part base64 url-safe strings)\n {\n name: \"JWT Token\",\n regex: /\\beyJ[a-zA-Z0-9_-]{10,}\\.eyJ[a-zA-Z0-9_-]{10,}\\.[a-zA-Z0-9_-]{10,}\\b/g,\n replace: () => \"[REDACTED_JWT]\",\n },\n // Bearer Authorization Header / Token\n {\n name: \"Bearer Token\",\n regex: /\\b(bearer\\s+)([A-Za-z0-9\\-._~+/]+=*)\\b/gi,\n replace: (_match, prefix) => `${prefix}[REDACTED_BEARER_TOKEN]`,\n },\n // Generic key/secret assignments like apiKey = \"...\", secret: '...'\n {\n name: \"Generic Secret Assignment\",\n regex: /\\b((?:api[_-]?key|secret|password|passwd|auth[_-]?token|access[_-]?token)\\s*[:=]\\s*[\"']?)([^\\s\"';,]{8,})([\"']?)/gi,\n replace: (_match, prefix, _val, suffix) => `${prefix}[REDACTED]${suffix}`,\n },\n];\n\n/**\n * Redacts secrets and sensitive information from text.\n */\nexport function redactSecrets(text: string, options?: RedactorOptions): string {\n if (!text) return text;\n let result = text;\n\n // PASS 1: Scrub values of sensitive environment variables\n const env = options?.env ?? process.env;\n if (env) {\n const sensitiveValues = new Set<string>();\n\n for (const [key, value] of Object.entries(env)) {\n if (!value || typeof value !== \"string\") continue;\n // Value must be at least 6 characters and not common generic words\n if (value.trim().length >= 6 && SENSITIVE_KEY_PATTERN.test(key)) {\n // Exclude common benign values\n const lower = value.toLowerCase().trim();\n if ([\"true\", \"false\", \"null\", \"undefined\", \"default\", \"localhost\", \"127.0.0.1\", \"none\"].includes(lower)) {\n continue;\n }\n sensitiveValues.add(value);\n }\n }\n\n // Replace sensitive env values (longest first to avoid partial replacements)\n const sortedValues = Array.from(sensitiveValues).sort((a, b) => b.length - a.length);\n for (const val of sortedValues) {\n // Escape for regex\n const escaped = val.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n result = result.replace(new RegExp(escaped, \"g\"), \"[REDACTED_ENV_SECRET]\");\n }\n }\n\n // PASS 2: Scrub pattern-based secrets\n for (const { regex, replace } of SECRET_PATTERNS) {\n result = result.replace(regex, replace);\n }\n\n return result;\n}\n\n/**\n * Redacts an environment variable dictionary for safe inspection / reporting.\n */\nexport function sanitizeEnvironment(env: Record<string, string | undefined>): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n for (const [key, val] of Object.entries(env)) {\n if (val === undefined) continue;\n if (SENSITIVE_KEY_PATTERN.test(key)) {\n sanitized[key] = \"[REDACTED]\";\n } else {\n sanitized[key] = redactSecrets(val, { env });\n }\n }\n\n return sanitized;\n}\n","import os from \"node:os\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport type { CrashContext } from \"../core/collector.js\";\n\nexport interface CrashBundle {\n id: string;\n savedAt: string;\n context: CrashContext;\n redactedOutput: string;\n}\n\nconst MAX_SAVED_CRASHES = 20;\n\n/**\n * Returns the default directory where crash snapshots are stored: ~/.wtf/crashes/\n * Supports override via WTF_STORAGE_DIR for testing and isolated environments.\n */\nexport function getCrashesDir(): string {\n if (process.env.WTF_STORAGE_DIR) {\n return process.env.WTF_STORAGE_DIR;\n }\n return path.join(os.homedir(), \".wtf\", \"crashes\");\n}\n\n/**\n * Returns fallback directory if home directory is restricted or read-only.\n */\nfunction getFallbackDir(): string {\n return path.join(process.cwd(), \".wtf\", \"crashes\");\n}\n\n/**\n * Ensures the crashes storage directory exists.\n */\nexport async function ensureCrashesDir(): Promise<string> {\n const dir = getCrashesDir();\n try {\n if (!existsSync(dir)) {\n await fs.mkdir(dir, { recursive: true });\n }\n return dir;\n } catch (err: any) {\n if (err.code === \"EPERM\" || err.code === \"EACCES\") {\n const fallback = getFallbackDir();\n if (!existsSync(fallback)) {\n await fs.mkdir(fallback, { recursive: true });\n }\n return fallback;\n }\n throw err;\n }\n}\n\n/**\n * Saves a crash bundle to ~/.wtf/crashes/ and automatically prunes older files to keep at most 20.\n */\nexport async function saveCrash(context: CrashContext, redactedOutput: string): Promise<string> {\n const dir = await ensureCrashesDir();\n const timestamp = Date.now();\n const id = `crash-${timestamp}`;\n const filePath = path.join(dir, `${id}.json`);\n\n const bundle: CrashBundle = {\n id,\n savedAt: new Date(timestamp).toISOString(),\n context,\n redactedOutput,\n };\n\n await fs.writeFile(filePath, JSON.stringify(bundle, null, 2), \"utf8\");\n\n // Prune older than MAX_SAVED_CRASHES\n await pruneCrashes(dir, MAX_SAVED_CRASHES);\n\n return filePath;\n}\n\n/**\n * Prunes the crashes directory keeping only the newest N files.\n */\nasync function pruneCrashes(dir: string, keepCount: number): Promise<void> {\n try {\n const files = await fs.readdir(dir);\n const jsonFiles = files.filter((f) => f.startsWith(\"crash-\") && f.endsWith(\".json\"));\n\n if (jsonFiles.length <= keepCount) {\n return;\n }\n\n // Get file stats to sort by mtime descending\n const filesWithStats = await Promise.all(\n jsonFiles.map(async (name) => {\n const fullPath = path.join(dir, name);\n const stat = await fs.stat(fullPath);\n return { name, fullPath, mtimeMs: stat.mtimeMs };\n })\n );\n\n filesWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);\n\n // Delete files beyond keepCount\n const toDelete = filesWithStats.slice(keepCount);\n await Promise.allSettled(toDelete.map((item) => fs.unlink(item.fullPath)));\n } catch {\n // Non-fatal: Pruning errors should never crash the tool\n }\n}\n\n/**\n * Retrieves the directory containing crash snapshots.\n */\nfunction resolveReadableCrashesDir(): string | null {\n const primary = getCrashesDir();\n if (existsSync(primary)) return primary;\n const fallback = getFallbackDir();\n if (existsSync(fallback)) return fallback;\n return null;\n}\n\n/**\n * Retrieves the most recent saved crash bundle, or null if none exist.\n */\nexport async function getLastCrash(): Promise<CrashBundle | null> {\n const dir = resolveReadableCrashesDir();\n if (!dir) return null;\n\n try {\n const files = await fs.readdir(dir);\n const jsonFiles = files.filter((f) => f.startsWith(\"crash-\") && f.endsWith(\".json\"));\n\n if (jsonFiles.length === 0) return null;\n\n const filesWithStats = await Promise.all(\n jsonFiles.map(async (name) => {\n const fullPath = path.join(dir, name);\n const stat = await fs.stat(fullPath);\n return { name, fullPath, mtimeMs: stat.mtimeMs };\n })\n );\n\n filesWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);\n const latest = filesWithStats[0];\n\n const content = await fs.readFile(latest.fullPath, \"utf8\");\n return JSON.parse(content) as CrashBundle;\n } catch {\n return null;\n }\n}\n\n/**\n * Lists all saved crash bundles (newest first).\n */\nexport async function listCrashes(limit = MAX_SAVED_CRASHES): Promise<CrashBundle[]> {\n const dir = resolveReadableCrashesDir();\n if (!dir) return [];\n\n try {\n const files = await fs.readdir(dir);\n const jsonFiles = files.filter((f) => f.startsWith(\"crash-\") && f.endsWith(\".json\"));\n\n const filesWithStats = await Promise.all(\n jsonFiles.map(async (name) => {\n const fullPath = path.join(dir, name);\n const stat = await fs.stat(fullPath);\n return { name, fullPath, mtimeMs: stat.mtimeMs };\n })\n );\n\n filesWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);\n\n const loaded = await Promise.all(\n filesWithStats.slice(0, limit).map(async (item) => {\n try {\n const content = await fs.readFile(item.fullPath, \"utf8\");\n return JSON.parse(content) as CrashBundle;\n } catch {\n return null;\n }\n })\n );\n\n return loaded.filter((item): item is CrashBundle => item !== null);\n } catch {\n return [];\n }\n}\n","import * as p from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport clipboardy from \"clipboardy\";\nimport type { CrashContext } from \"../core/collector.js\";\nimport { generateMarkdownReport } from \"./markdown.js\";\n\nexport type MenuAction = \"exit\" | \"rerun\";\n\nexport interface TerminalUIOptions {\n context: CrashContext;\n redactedOutput: string;\n snapshotPath?: string;\n}\n\n/**\n * Renders the post-crash interactive Clack TUI.\n * Returns the user's chosen next step: \"exit\" or \"rerun\".\n */\nexport async function showPostCrashUI(options: TerminalUIOptions): Promise<MenuAction> {\n const { context, redactedOutput, snapshotPath } = options;\n const markdownReport = generateMarkdownReport(context, redactedOutput);\n\n // If running in a non-interactive environment (CI, script pipes) or stdin is closed/destroyed\n if (!process.stdin.isTTY || process.stdin.destroyed || !process.stdin.readable) {\n console.error(pc.red(`\\n[wtf] Command failed with exit code ${context.exitCode}: ${context.command}`));\n if (snapshotPath) {\n console.error(pc.dim(`[wtf] Diagnostic snapshot saved to: ${snapshotPath}`));\n console.error(pc.cyan(`[wtf] Run 'wtf last' to view or copy the LLM diagnostic report.\\n`));\n }\n return \"exit\";\n }\n\n try {\n if (process.stdin.isPaused()) {\n process.stdin.resume();\n }\n\n p.intro(pc.bgRed(pc.white(pc.bold(\" WTF Just Happened? Command Crashed \"))));\n\n p.note(\n [\n `${pc.bold(\"Command:\")} ${pc.cyan(context.command)}`,\n `${pc.bold(\"Exit Code:\")} ${pc.red(String(context.exitCode))}`,\n `${pc.bold(\"Duration:\")} ${context.durationMs}ms`,\n snapshotPath ? `${pc.bold(\"Snapshot:\")} ${pc.dim(snapshotPath)}` : \"\",\n context.activePorts.length > 0\n ? `${pc.bold(\"Active Ports:\")} ${pc.yellow(context.activePorts.map((p) => p.port).join(\", \"))}`\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n \"Crash Summary\"\n );\n\n let active = true;\n\n while (active) {\n let choice: any;\n try {\n choice = await p.select({\n message: \"What would you like to do?\",\n options: [\n {\n value: \"copy\",\n label: \"Copy Markdown Report\",\n hint: \"Ready-to-paste for ChatGPT, Claude, GitHub Issues\",\n },\n {\n value: \"view-output\",\n label: \"View Redacted Terminal Output\",\n hint: \"Shows trailing captured logs\",\n },\n {\n value: \"view-markdown\",\n label: \"Print Full Markdown Report\",\n hint: \"Outputs raw markdown in console\",\n },\n {\n value: \"view-env\",\n label: \"View Environment & System Context\",\n hint: \"Inspect sanitized env vars and OS specs\",\n },\n {\n value: \"rerun\",\n label: \"Re-run Command\",\n hint: \"Attempt executing the command again\",\n },\n {\n value: \"exit\",\n label: \"Exit\",\n hint: `Exits with code ${context.exitCode}`,\n },\n ],\n });\n } catch {\n // Stdin was terminated or aborted\n return \"exit\";\n }\n\n if (p.isCancel(choice) || choice === \"exit\") {\n p.outro(pc.dim(`Exiting.`));\n return \"exit\";\n }\n\n if (choice === \"copy\") {\n try {\n await clipboardy.write(markdownReport);\n p.log.success(pc.green(\"Markdown diagnostic report copied to clipboard.\"));\n } catch (err: any) {\n p.log.error(pc.red(`Failed to copy to clipboard: ${err.message}`));\n }\n } else if (choice === \"view-output\") {\n console.log(\"\\n\" + pc.dim(\"--- Captured Output (Redacted) ---\"));\n console.log(redactedOutput.trim() || pc.dim(\"[No output captured]\"));\n console.log(pc.dim(\"-----------------------------------\\n\"));\n } else if (choice === \"view-markdown\") {\n console.log(\"\\n\" + markdownReport + \"\\n\");\n } else if (choice === \"view-env\") {\n console.log(\"\\n\" + pc.dim(\"--- Environment & System Context ---\"));\n console.log(`${pc.bold(\"Platform:\")} ${context.system.platform} (${context.system.arch})`);\n console.log(`${pc.bold(\"OS Release:\")} ${context.system.osRelease}`);\n console.log(`${pc.bold(\"Node:\")} ${context.system.nodeVersion}`);\n console.log(`${pc.bold(\"CWD:\")} ${context.system.cwd}`);\n console.log(`${pc.bold(\"Memory:\")} ${context.system.freeMemoryMB}MB free / ${context.system.totalMemoryMB}MB total`);\n console.log(pc.bold(\"\\nSanitized Environment:\"));\n for (const [k, v] of Object.entries(context.environment)) {\n console.log(` ${pc.cyan(k)}=${pc.yellow(v)}`);\n }\n console.log(pc.dim(\"------------------------------------\\n\"));\n } else if (choice === \"rerun\") {\n p.outro(pc.cyan(`Re-running: ${context.command}...`));\n return \"rerun\";\n }\n }\n\n return \"exit\";\n } catch {\n // Graceful fallback if TUI encounters an environment error\n console.error(pc.red(`\\n[wtf] Command failed with exit code ${context.exitCode}: ${context.command}`));\n if (snapshotPath) {\n console.error(pc.dim(`[wtf] Diagnostic snapshot saved to: ${snapshotPath}`));\n console.error(pc.cyan(`[wtf] Run 'wtf last' to view or copy the LLM diagnostic report.\\n`));\n }\n return \"exit\";\n }\n\n return \"exit\";\n}\n","import type { CrashContext } from \"../core/collector.js\";\n\n/**\n * Generates an optimized Markdown diagnostic report formatted for GitHub Issues and LLM analysis.\n */\nexport function generateMarkdownReport(context: CrashContext, redactedOutput: string): string {\n const parts: string[] = [];\n\n parts.push(`# Diagnostic Crash Report: \\`${context.command}\\``);\n parts.push(\"\");\n parts.push(\"## Summary\");\n parts.push(\"| Metric | Value |\");\n parts.push(\"| :--- | :--- |\");\n parts.push(`| **Command** | \\`${context.command}\\` |`);\n parts.push(`| **Exit Code** | \\`${context.exitCode}\\` |`);\n parts.push(`| **Duration** | \\`${context.durationMs}ms\\` |`);\n parts.push(`| **Timestamp** | ${context.timestamp} |`);\n parts.push(`| **Platform** | \\`${context.system.platform}\\` (${context.system.arch}) |`);\n parts.push(`| **Node Version** | \\`${context.system.nodeVersion}\\` |`);\n parts.push(`| **Working Dir** | \\`${context.system.cwd}\\` |`);\n\n if (context.git) {\n const gitInfo = [\n context.git.branch ? `Branch: \\`${context.git.branch}\\`` : \"\",\n context.git.commit ? `Commit: \\`${context.git.commit}\\`` : \"\",\n context.git.isDirty !== undefined ? `Working Tree: ${context.git.isDirty ? \"Dirty\" : \"Clean\"}` : \"\",\n ]\n .filter(Boolean)\n .join(\" | \");\n parts.push(`| **Git Context** | ${gitInfo} |`);\n }\n\n // Active Ports section if any were detected\n if (context.activePorts.length > 0) {\n parts.push(\"\");\n parts.push(\"## Active Network Ports\");\n parts.push(\"The following ports were detected as listening/active at the time of failure:\");\n for (const p of context.activePorts) {\n parts.push(`- **Port ${p.port}**: In use (${p.details || \"Active listener\"})`);\n }\n }\n\n // Captured Terminal Logs\n parts.push(\"\");\n parts.push(\"## Captured Terminal Output (Trailing 64KB)\");\n parts.push(\"*(All credentials, tokens, DB passwords, and sensitive environment variables have been automatically scrubbed)*\");\n parts.push(\"\");\n parts.push(\"```text\");\n parts.push(redactedOutput.trim() || \"[No output captured]\");\n parts.push(\"```\");\n\n // System & Environment Details\n parts.push(\"\");\n parts.push(\"<details>\");\n parts.push(\"<summary><strong>System & Environment Diagnostics</strong></summary>\");\n parts.push(\"\");\n parts.push(\"### Hardware & OS\");\n parts.push(`- **OS Release:** ${context.system.osRelease}`);\n parts.push(`- **CPUs:** ${context.system.cpuCount}`);\n parts.push(`- **Memory:** ${context.system.freeMemoryMB} MB free / ${context.system.totalMemoryMB} MB total`);\n parts.push(\"\");\n\n const envEntries = Object.entries(context.environment);\n if (envEntries.length > 0) {\n parts.push(\"### Relevant Environment Variables\");\n parts.push(\"| Variable | Value |\");\n parts.push(\"| :--- | :--- |\");\n for (const [key, val] of envEntries) {\n parts.push(`| \\`${key}\\` | \\`${val}\\` |`);\n }\n }\n\n parts.push(\"</details>\");\n\n // Suggested LLM Prompt\n parts.push(\"\");\n parts.push(\"---\");\n parts.push(\"### Instructions for LLM\");\n parts.push(\n \"> Please analyze the crash log above, diagnose the root cause of the failure, highlight any missing dependencies or environment conflicts, and provide a concrete step-by-step fix.\"\n );\n\n return parts.join(\"\\n\");\n}\n"],"mappings":";;;AAAA,OAAOA,SAAQ;;;ACAf,SAAS,SAAS,yBAA4C;;;ACA9D,OAAO,eAAe;AAMf,IAAM,aAAN,MAAiB;AAAA,EACd,SAAmB,CAAC;AAAA,EACpB,eAAe;AAAA,EACd;AAAA,EAET,YAAY,SAA6B;AACvC,SAAK,WAAW,SAAS,YAAY,KAAK;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAA6B;AACjC,UAAM,OAAO,OAAO,SAAS,WAAW,OAAO,KAAK,SAAS,MAAM;AACnE,QAAI,CAAC,KAAM;AAEX,UAAM,aAAa,OAAO,WAAW,MAAM,MAAM;AAGjD,QAAI,cAAc,KAAK,UAAU;AAC/B,YAAM,MAAM,OAAO,KAAK,MAAM,MAAM;AACpC,YAAM,UAAU,IAAI,SAAS,IAAI,SAAS,KAAK,QAAQ;AAC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U;AACV,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,MAAI,QAAQ,SAAS,WAAW,KAAK,QAAQ,SAAS,IAAI,GAAG;AAC3D,YAAQ,IAAI,sBAAsB,OAAO,EAAE;AAC3C,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,MAAI,QAAQ,CAAC,MAAM,QAAQ;AACzB,UAAM,WAAW;AACjB;AAAA,EACF;AAEA,MAAI,QAAQ,SAAS,QAAQ,GAAG;AAC9B,UAAM,WAAW;AACjB;AAAA,EACF;AAEA,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAC3B,QAAM,eAAe,SAAS,IAAI;AACpC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAMA,IAAG,IAAI;AAAA,0BAA6B,IAAI,OAAO,EAAE,CAAC;AAChE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["pc","isWindows","p","os","p","p","pc","redactedOutput","context","snapshotPath"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wtf-just-happened",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Transparent PTY crash capture & diagnostic report CLI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"wtf": "./dist/cli.js",
|
|
8
|
+
"wtf-just-happened": "./dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsup",
|
|
17
|
+
"dev": "tsup --watch",
|
|
18
|
+
"test": "vitest run",
|
|
19
|
+
"try:playground": "node dist/cli.js npm --prefix playground run fail:build",
|
|
20
|
+
"prepublishOnly": "npm test && npm run build"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"cli",
|
|
24
|
+
"pty",
|
|
25
|
+
"crash-reporter",
|
|
26
|
+
"diagnostics",
|
|
27
|
+
"developer-tools"
|
|
28
|
+
],
|
|
29
|
+
"author": "Oskar Labuda",
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=18.0.0"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/oskaruwu1/wtf-just-happened.git"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@clack/prompts": "^0.9.1",
|
|
40
|
+
"clipboardy": "^4.0.0",
|
|
41
|
+
"picocolors": "^1.1.1",
|
|
42
|
+
"strip-ansi": "^7.1.0"
|
|
43
|
+
},
|
|
44
|
+
"optionalDependencies": {
|
|
45
|
+
"node-pty": "^1.0.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^22.13.1",
|
|
49
|
+
"tsup": "^8.3.6",
|
|
50
|
+
"typescript": "^5.7.3",
|
|
51
|
+
"vitest": "^3.0.5"
|
|
52
|
+
}
|
|
6
53
|
}
|