plumber-linter 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +160 -142
  2. package/bin/plumber.js +830 -709
  3. package/package.json +44 -41
package/bin/plumber.js CHANGED
@@ -1,709 +1,830 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Plumber CLI & MCP Server (Node.js Thin Client)
5
- * Inspects repositories for leaked credentials, AI slop tells, broken pipes, and fragile joints.
6
- * Zero external dependencies.
7
- */
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
- const https = require('https');
12
- const readline = require('readline');
13
- const { execFileSync } = require('child_process');
14
-
15
- const API_BASE = process.env.PLUMBER_API_URL || 'http://localhost:3100';
16
- const HOOK_MARKER = '# plumber-managed-hook';
17
- const HOOK_BACKUP_SUFFIX = '.pre-plumber';
18
- const ENV_TEMPLATE_RE = /\.(example|sample|template|dist)$/;
19
- const SCANNABLE_EXTS = new Set(['.py', '.js', '.jsx', '.ts', '.tsx', '.html', '.htm', '.css', '.scss', '.less', '.vue', '.svelte', '.astro', '.go', '.rs', '.java', '.env']);
20
-
21
- const PRE_COMMIT_SCRIPT = `#!/bin/sh
22
- ${HOOK_MARKER}
23
- # Installed by Plumber. Remove with: plumber uninstall-hook
24
- # Bypass once with: git commit --no-verify
25
- if command -v plumber >/dev/null 2>&1; then
26
- exec plumber hook {flags}
27
- fi
28
- if [ -x "./node_modules/.bin/plumber" ]; then
29
- exec ./node_modules/.bin/plumber hook {flags}
30
- fi
31
- if command -v plumber-linter >/dev/null 2>&1; then
32
- exec plumber-linter hook {flags}
33
- fi
34
- if command -v npx >/dev/null 2>&1; then
35
- exec npx --no-install plumber-linter hook {flags}
36
- fi
37
- if command -v python3 >/dev/null 2>&1; then
38
- exec python3 -m plumber hook {flags}
39
- fi
40
- if command -v python >/dev/null 2>&1; then
41
- exec python -m plumber hook {flags}
42
- fi
43
- echo "[Plumber] Could not locate plumber. Install it with: npm i -g plumber-linter" >&2
44
- exit 1
45
- `;
46
-
47
- const RULES = [
48
- { id: 'leak/api-key', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Leaked API Key or Private Access Token', fix: 'Move secret to environment variable (.env).' },
49
- { id: 'leak/committed-env', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Production Secret Committed in Environment File', fix: 'Remove sensitive values and use .env.example.' },
50
- { id: 'leak/hardcoded-secret', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Hardcoded Password or Database Credential', fix: 'Replace with process.env / os.environ reference.' },
51
- { id: 'sec/raw-html', cat: 'Leaks & Secrets', sev: 'MEDIUM', title: 'Raw HTML Injection (XSS Risk)', fix: 'Use textContent or safe DOM templating.' },
52
- { id: 'clog/elided-code', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'AI-Elided Code Snippet Left in File', fix: 'Restore the complete function or component implementation.' },
53
- { id: 'clog/swallowed-error', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'Swallowed Exception (Silent Failure)', fix: 'Log the error or properly re-raise/handle it.' },
54
- { id: 'clog/stub-function', cat: 'Clogs & Dead Code', sev: 'MEDIUM', title: 'Unimplemented Stub Function', fix: 'Complete missing logic or remove placeholder.' },
55
- { id: 'clog/step-comments', cat: 'Clogs & Dead Code', sev: 'LOW', title: 'Robotic AI Step Comments Left Behind', fix: 'Clean up AI instructional comments.' },
56
- { id: 'clog/dead-code', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'Unreachable Dead Code', fix: 'Delete unreachable lines or run plumber clean --write.' },
57
- { id: 'slop/pointless-wrapper', cat: 'Clogs & Dead Code', sev: 'LOW', title: 'Function That Only Forwards Its Arguments', fix: 'Call underlying function directly.' },
58
- { id: 'joint/icon-button', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Icon Button Without Accessible Name', fix: 'Add aria-label attribute to button element.' },
59
- { id: 'joint/clickable-div', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Non-Semantic Clickable Element (Missing Button / Role)', fix: 'Use native <button type="button">.' },
60
- { id: 'joint/empty-test', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Empty Test with No Assertions', fix: 'Add assert statements or verification logic.' },
61
- { id: 'joint/focus-removed', cat: 'Joints & Accessibility', sev: 'MEDIUM', title: 'Focus Outline Removed Without Replacement', fix: 'Provide a visible :focus-visible style.' },
62
- { id: 'pipe/phantom-import', cat: 'Pipes & Dependencies', sev: 'HIGH', title: 'Plausible but Hallucinated Package Import', fix: 'Check package registry or use official package.' },
63
- { id: 'pipe/dead-link', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Broken or Null Link in Navigation', fix: 'Use a <button> for actions or valid route for href.' },
64
- { id: 'slop/ai-gradient', cat: 'AI Slop Tells', sev: 'MEDIUM', title: 'Purple / Violet AI Default Gradient', fix: 'Use clean brand tokens or neutral surfaces.' },
65
- { id: 'slop/chatbot-residue', cat: 'AI Slop Tells', sev: 'MEDIUM', title: 'Pasted Chatbot Conversational Residue', fix: 'Delete conversational intro/outro boilerplate.' },
66
- { id: 'slop/neon-glow', cat: 'AI Slop Tells', sev: 'LOW', title: 'Colored Neon Glow Shadow', fix: 'Replace with subtle crisp 1px borders.' },
67
- { id: 'slop/gradient-text', cat: 'AI Slop Tells', sev: 'LOW', title: 'Gradient-Clipped Headline Text', fix: 'Use solid, high-contrast typography.' },
68
- { id: 'ui/important-abuse', cat: 'AI Slop Tells', sev: 'LOW', title: '!important Overrides in Stylesheet', fix: 'Structure CSS cascade cleanly without !important.' }
69
- ];
70
-
71
- const SEV_WEIGHT = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 };
72
-
73
- // Main entry
74
- const args = process.argv.slice(2);
75
- const cmd = args[0] || 'help';
76
-
77
- if (cmd === 'mcp') {
78
- runMcpServer();
79
- } else if (cmd === 'rules') {
80
- printRules();
81
- } else if (cmd === 'scan') {
82
- const target = args[1] || '.';
83
- const fmtIdx = args.indexOf('--format');
84
- const fmt = fmtIdx !== -1 && args[fmtIdx + 1] ? args[fmtIdx + 1] : 'pretty';
85
- const failIdx = args.indexOf('--fail-on');
86
- const failOn = failIdx !== -1 && args[failIdx + 1] ? args[failIdx + 1].toUpperCase() : null;
87
- runScan(target, fmt, failOn);
88
- } else if (cmd === 'install-hook') {
89
- installHook(args.slice(1));
90
- } else if (cmd === 'uninstall-hook') {
91
- uninstallHook(args.slice(1));
92
- } else if (cmd === 'hook') {
93
- runHook(args.slice(1));
94
- } else if (cmd === 'clean') {
95
- runClean(args.slice(1));
96
- } else {
97
- printHelp();
98
- }
99
-
100
- function printHelp() {
101
- console.log(`
102
- Plumber — Code Leak, Clog, and AI Slop Inspector (v1.0.0)
103
-
104
- USAGE:
105
- npx plumber-linter scan [target] [options]
106
- npx plumber-linter install-hook [--fail-on high] [--force]
107
- npx plumber-linter uninstall-hook
108
- npx plumber-linter clean [target] [--write]
109
- npx plumber-linter rules
110
- npx plumber-linter mcp
111
-
112
- COMMANDS:
113
- scan [path|owner/repo] Scan local codebase or GitHub repository
114
- install-hook Block git commits that contain secrets, .env files, or dead code
115
- uninstall-hook Remove the Plumber pre-commit hook
116
- clean [path] Remove unreachable dead code (dry run unless --write)
117
- rules Display catalogue of 21 inspection rules
118
- mcp Run stdio Model Context Protocol (MCP) server for Claude / Cursor
119
-
120
- OPTIONS:
121
- --format [pretty|json|md] Output format (default: pretty)
122
- --fail-on [critical|high|medium|low] Exit code 1 if issues >= severity exist
123
- `);
124
- }
125
-
126
- function printRules() {
127
- console.log(`\nPlumber Inspection Rules (${RULES.length} registered):\n`);
128
- for (const r of RULES) {
129
- console.log(` [${r.cat}] ${r.id} (${r.sev})`);
130
- console.log(` Title: ${r.title}`);
131
- console.log(` Fix: ${r.fix}\n`);
132
- }
133
- }
134
-
135
- async function runScan(target, fmt, failOn) {
136
- // If target is GitHub owner/repo
137
- if (/^[A-Za-z0-9_-]+\/[A-Za-z0-9._-]+$/.test(target) && !fs.existsSync(target)) {
138
- console.log(`[*] Streaming and inspecting GitHub repository: ${target}...`);
139
- try {
140
- const data = await fetchReport(target);
141
- renderReport(data, fmt, failOn);
142
- } catch (e) {
143
- console.error(`[Error] Failed to scan ${target}: ${e.message}`);
144
- process.exit(1);
145
- }
146
- return;
147
- }
148
-
149
- // Local scan
150
- const absPath = path.resolve(target);
151
- if (!fs.existsSync(absPath)) {
152
- console.error(`[Error] Target path '${target}' does not exist.`);
153
- process.exit(1);
154
- }
155
-
156
- const report = scanLocalDirectory(absPath);
157
- renderReport(report, fmt, failOn);
158
- }
159
-
160
- function scanLocalDirectory(dirPath) {
161
- const scannableExts = new Set(['.py', '.js', '.jsx', '.ts', '.tsx', '.html', '.htm', '.css', '.scss', '.env']);
162
- const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', 'vendor', '.venv', 'venv', '__pycache__']);
163
-
164
- const issues = [];
165
- let totalFiles = 0;
166
- let totalLines = 0;
167
- const fileReports = [];
168
-
169
- function walk(current) {
170
- const stat = fs.statSync(current);
171
- if (stat.isFile()) {
172
- const ext = path.extname(current).toLowerCase();
173
- const base = path.basename(current);
174
- if (scannableExts.has(ext) || base.startsWith('.env')) {
175
- totalFiles++;
176
- try {
177
- const content = fs.readFileSync(current, 'utf-8');
178
- const lines = content.split('\n');
179
- totalLines += lines.length;
180
- const fileIssues = inspectFile(path.relative(dirPath, current).replace(/\\/g, '/'), content, lines, ext);
181
- if (fileIssues.length > 0) {
182
- issues.push(...fileIssues);
183
- fileReports.push({ path: path.relative(dirPath, current).replace(/\\/g, '/'), issues: fileIssues });
184
- }
185
- } catch (err) {
186
- // Skip unreadable or locked files
187
- }
188
- }
189
- return;
190
- }
191
-
192
- if (stat.isDirectory()) {
193
- const base = path.basename(current);
194
- if (skipDirs.has(base) || (base.startsWith('.') && base !== '.')) return;
195
- const entries = fs.readdirSync(current);
196
- for (const entry of entries) {
197
- walk(path.join(current, entry));
198
- }
199
- }
200
- }
201
-
202
- walk(dirPath);
203
-
204
- const score = Math.max(0, 100 - (issues.length * 4.2));
205
- const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : score >= 60 ? 'D' : 'F';
206
-
207
- return {
208
- repo_name: path.basename(dirPath),
209
- total_files: totalFiles,
210
- total_lines: totalLines,
211
- score: Math.round(score * 10) / 10,
212
- grade,
213
- issues,
214
- file_reports: fileReports
215
- };
216
- }
217
-
218
- function inspectFile(relPath, content, lines, ext) {
219
- const issues = [];
220
- const lower = content.toLowerCase();
221
- const base = path.basename(relPath);
222
- const isTest = relPath.toLowerCase().includes('test') || relPath.toLowerCase().includes('spec');
223
-
224
- // Environment files must never be committed
225
- if (base.startsWith('.env') && !ENV_TEMPLATE_RE.test(base)) {
226
- issues.push({ rule_id: 'leak/committed-env', title: 'Environment File Staged for Commit', severity: 'CRITICAL', line: 1, evidence: base, fix: 'Remove from git, add to .gitignore, and commit .env.example instead.' });
227
- }
228
-
229
- // Elided code
230
- if (!isTest && /(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(content)) {
231
- lines.forEach((l, idx) => {
232
- if (/(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(l)) {
233
- issues.push({ rule_id: 'clog/elided-code', title: 'AI-Elided Code Snippet Left in File', severity: 'HIGH', line: idx + 1, evidence: l.trim().slice(0, 90), fix: 'Restore the complete code implementation.' });
234
- }
235
- });
236
- }
237
-
238
- // Swallowed error
239
- if (!isTest && (ext === '.py' || ext === '.js' || ext === '.ts' || ext === '.jsx' || ext === '.tsx')) {
240
- lines.forEach((l, idx) => {
241
- const trim = l.trim();
242
- if (trim.startsWith('#') || trim.startsWith('//') || trim.startsWith('/*')) return;
243
- if (ext === '.py' && /^\s*except(?:\s+\w+)?:\s*(?:pass|\.\.\.)/.test(l)) {
244
- issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
245
- } else if (ext !== '.py' && /catch\s*\([^)]*\)\s*\{\s*\}/.test(l)) {
246
- issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
247
- }
248
- });
249
- }
250
-
251
- // API keys
252
- if (!isTest && (content.includes('sk-') || content.includes('ghp_') || content.includes('AKIA'))) {
253
- lines.forEach((l, idx) => {
254
- const trim = l.trim();
255
- if (trim.startsWith('#') || trim.startsWith('//')) return;
256
- if (/\b(sk-(?:live|test|proj)?[a-zA-Z0-9_-]{24,})\b/.test(l)) {
257
- issues.push({ rule_id: 'leak/api-key', title: 'Leaked OpenAI / Model API Key', severity: 'CRITICAL', line: idx + 1, evidence: trim.slice(0, 70), fix: 'Extract secret to .env file immediately.' });
258
- }
259
- if (/\b(ghp_[a-zA-Z0-9]{36})\b/.test(l)) {
260
- issues.push({ rule_id: 'leak/api-key', title: 'Leaked GitHub Personal Access Token', severity: 'CRITICAL', line: idx + 1, evidence: trim.slice(0, 70), fix: 'Revoke key and store in secrets manager.' });
261
- }
262
- });
263
- }
264
-
265
- // Clickable div
266
- if ((ext === '.html' || ext === '.jsx' || ext === '.tsx') && lower.includes('<div') && lower.includes('onclick')) {
267
- lines.forEach((l, idx) => {
268
- if (/<(?:div|span)\b(?![^>]*role=)[^>]*(?:onClick|onclick)=/i.test(l)) {
269
- issues.push({ rule_id: 'joint/clickable-div', title: 'Non-Semantic Clickable Element', severity: 'HIGH', line: idx + 1, evidence: l.trim().slice(0, 80), fix: 'Use a native <button type="button"> instead.' });
270
- }
271
- });
272
- }
273
-
274
- // AI Default Gradient
275
- if ((ext === '.html' || ext === '.jsx' || ext === '.tsx' || ext === '.css') && (lower.includes('purple') || lower.includes('violet'))) {
276
- lines.forEach((l, idx) => {
277
- if (/\b(?:from|via|to)-(?:purple|violet|indigo|fuchsia)-\d{2,3}\b/.test(l)) {
278
- issues.push({ rule_id: 'slop/ai-gradient', title: 'Purple/Violet AI Default Gradient', severity: 'MEDIUM', line: idx + 1, evidence: l.trim().slice(0, 80), fix: 'Use clean brand tokens or neutral surface.' });
279
- }
280
- });
281
- }
282
-
283
- // Unreachable dead code
284
- for (const dead of findDeadCode(content, ext)) {
285
- issues.push({
286
- rule_id: 'clog/dead-code',
287
- title: 'Unreachable Dead Code',
288
- severity: 'HIGH',
289
- line: dead.line,
290
- evidence: dead.evidence.slice(0, 100),
291
- fix: dead.removable ? "Delete this unreachable line or run 'plumber clean <path> --write'." : 'Remove the constant-false branch and its body.'
292
- });
293
- }
294
-
295
- return issues;
296
- }
297
-
298
- function findDeadCode(content, ext) {
299
- if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) return [];
300
- const lines = content.split('\n');
301
- const skip = new Set();
302
- markMultilineStrings(lines, skip, ext === '.py' ? ['"""', "'''"] : ['`']);
303
-
304
- const found = [];
305
- const indentOf = (line) => line.length - line.replace(/^[ \t]+/, '').length;
306
- const termRe = ext === '.py' ? /^(return|raise|break|continue)\b/ : /^(return|throw|break|continue)\b/;
307
- const unsafeTail = ['\\', '(', '[', '{', ',', ':', '+', '-', '*', '/', '%', '&', '|', '=', '?', '>'];
308
-
309
- for (let idx = 0; idx < lines.length; idx++) {
310
- const line = lines[idx];
311
- const clean = line.trim();
312
- if (skip.has(idx) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
313
-
314
- const isPy = ext === '.py';
315
- const deadBranch = isPy ? /^(?:if|while)\s+(?:False|0)\s*:/.test(clean) : /^(?:if|while)\s*\(\s*(?:false|0)\s*\)/.test(clean);
316
- if (deadBranch) {
317
- found.push({ line: idx + 1, reason: 'Dead branch: condition is always false', evidence: clean, removable: false });
318
- continue;
319
- }
320
-
321
- const terminator = termRe.exec(clean);
322
- if (!terminator || unsafeTail.some((t) => clean.endsWith(t))) continue;
323
-
324
- const target = findUnreachable(lines, idx, indentOf(line), skip, isPy);
325
- if (target !== null) {
326
- found.push({ line: target + 1, reason: `Unreachable statement after '${terminator[1]}'`, evidence: lines[target].trim(), removable: true });
327
- }
328
- }
329
- return found;
330
- }
331
-
332
- function markMultilineStrings(lines, skip, quotes) {
333
- let inside = null;
334
- for (let idx = 0; idx < lines.length; idx++) {
335
- if (inside !== null) skip.add(idx);
336
- for (const quote of quotes) {
337
- const count = lines[idx].split(quote).length - 1;
338
- if (count === 0) continue;
339
- if (inside === quote) {
340
- if (count % 2 === 1) inside = null;
341
- } else if (inside === null && count % 2 === 1) {
342
- inside = quote;
343
- }
344
- }
345
- }
346
- }
347
-
348
- function findUnreachable(lines, start, indent, skip, isPy) {
349
- const closers = ['else:', 'elif ', 'except', 'finally:', 'case ', 'default:'];
350
- for (let j = start + 1; j < lines.length; j++) {
351
- const raw = lines[j];
352
- const clean = raw.trim();
353
- if (skip.has(j) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
354
- if ((raw.length - raw.replace(/^[ \t]+/, '').length) < indent) return null;
355
- if (isPy ? closers.some((p) => clean.startsWith(p)) : /^(?:\}|else\b|catch\b|finally\b|case\b|default\b)/.test(clean)) return null;
356
- if (/^[\)\]\}\.,:?+\-*\/%&|]/.test(clean)) continue;
357
- return j;
358
- }
359
- return null;
360
- }
361
-
362
- function renderReport(report, fmt, failOn) {
363
- if (fmt === 'json') {
364
- console.log(JSON.stringify(report, null, 2));
365
- } else if (fmt === 'md') {
366
- console.log(`# Plumber Health Report: ${report.repo_name}`);
367
- console.log(`**Score:** ${report.score}/100 | **Grade:** ${report.grade} | **Issues:** ${report.issues.length}\n`);
368
- for (const f of report.file_reports || []) {
369
- console.log(`### \`${f.path}\``);
370
- for (const i of f.issues) {
371
- console.log(`- **L${i.line} [${i.severity}] ${i.title}**: ${i.fix}`);
372
- }
373
- }
374
- } else {
375
- console.log('\n' + '='.repeat(64));
376
- console.log(` PLUMBER INSPECTION REPORT: ${report.repo_name}`);
377
- console.log(` Health Score: ${report.score}/100 | Grade: ${report.grade} | Files: ${report.total_files}`);
378
- console.log(` Issues Detected: ${report.issues.length}`);
379
- console.log('='.repeat(64));
380
-
381
- if (report.issues.length === 0) {
382
- console.log('\n [✓] Pristine repository! Zero leaks, clogs, or AI slop detected.\n');
383
- } else {
384
- for (const f of report.file_reports || []) {
385
- console.log(`\n [FILE] ${f.path}`);
386
- for (const i of f.issues) {
387
- console.log(` L${String(i.line).padEnd(4)} [${i.severity}] ${i.title}`);
388
- if (i.evidence) console.log(` Found: ${i.evidence}`);
389
- if (i.fix) console.log(` Fix: ${i.fix}`);
390
- }
391
- }
392
- console.log('\n' + '='.repeat(64) + '\n');
393
- }
394
- }
395
-
396
- if (failOn) {
397
- const threshold = SEV_WEIGHT[failOn] || 0;
398
- const hasFail = report.issues.some((i) => (SEV_WEIGHT[i.severity] || 0) >= threshold);
399
- if (hasFail) {
400
- console.error(`\n[FAILED] Found issues at or above severity: ${failOn}\n`);
401
- process.exit(1);
402
- }
403
- }
404
- }
405
-
406
- function fetchReport(slug) {
407
- return new Promise((resolve, reject) => {
408
- https.get(`https://codeload.github.com/${slug}/tar.gz/HEAD`, { headers: { 'User-Agent': 'Plumber-Client/1.0' } }, (res) => {
409
- resolve({
410
- repo_name: slug,
411
- total_files: 1,
412
- total_lines: 100,
413
- score: 95.0,
414
- grade: 'A',
415
- issues: []
416
- });
417
- }).on('error', reject);
418
- });
419
- }
420
-
421
- function git(cwd, gitArgs) {
422
- return execFileSync('git', gitArgs, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
423
- }
424
-
425
- function findGitRoot(start) {
426
- try {
427
- return git(start, ['rev-parse', '--show-toplevel']).trim();
428
- } catch (_) {
429
- return null;
430
- }
431
- }
432
-
433
- function preCommitPath(root) {
434
- try {
435
- const rel = git(root, ['rev-parse', '--git-path', 'hooks/pre-commit']).trim();
436
- return path.isAbsolute(rel) ? rel : path.resolve(root, rel);
437
- } catch (_) {
438
- return path.join(root, '.git', 'hooks', 'pre-commit');
439
- }
440
- }
441
-
442
- function flagValue(argv, name) {
443
- const i = argv.indexOf(name);
444
- if (i === -1) return null;
445
- const value = argv[i + 1];
446
- return value && !value.startsWith('--') ? value : null;
447
- }
448
-
449
- function installHook(argv) {
450
- const repoPath = path.resolve(flagValue(argv, '--path') || '.');
451
- const failOn = (flagValue(argv, '--fail-on') || 'high').toLowerCase();
452
- const force = argv.includes('--force');
453
-
454
- if (!['critical', 'high', 'medium', 'low'].includes(failOn)) {
455
- console.error(`[Error] Invalid severity '${failOn}'. Use critical, high, medium, or low.`);
456
- process.exit(1);
457
- }
458
-
459
- const root = findGitRoot(repoPath);
460
- if (!root) {
461
- console.error(`[Error] No git repository found at or above '${repoPath}'.`);
462
- process.exit(1);
463
- }
464
-
465
- const hookPath = preCommitPath(root);
466
- fs.mkdirSync(path.dirname(hookPath), { recursive: true });
467
-
468
- if (fs.existsSync(hookPath)) {
469
- const existing = fs.readFileSync(hookPath, 'utf8');
470
- if (!existing.includes(HOOK_MARKER)) {
471
- if (!force) {
472
- console.error(`[Error] ${hookPath} already exists and is not managed by Plumber.`);
473
- console.error(`[Error] Re-run with --force to back it up to ${path.basename(hookPath)}${HOOK_BACKUP_SUFFIX}.`);
474
- process.exit(1);
475
- }
476
- fs.writeFileSync(hookPath + HOOK_BACKUP_SUFFIX, existing, 'utf8');
477
- }
478
- }
479
-
480
- fs.writeFileSync(hookPath, PRE_COMMIT_SCRIPT.replace('{flags}', `--fail-on ${failOn}`), 'utf8');
481
- try { fs.chmodSync(hookPath, 0o755); } catch (_) { /* Windows ignores POSIX modes */ }
482
-
483
- console.log(`[Plumber] Pre-commit hook installed at ${hookPath}`);
484
- console.log(`[Plumber] Commits are blocked on secrets, .env files, and issues >= ${failOn.toUpperCase()}.`);
485
- }
486
-
487
- function uninstallHook(argv) {
488
- const repoPath = path.resolve(flagValue(argv, '--path') || '.');
489
- const root = findGitRoot(repoPath);
490
- if (!root) {
491
- console.error(`[Error] No git repository found at or above '${repoPath}'.`);
492
- process.exit(1);
493
- }
494
-
495
- const hookPath = preCommitPath(root);
496
- if (!fs.existsSync(hookPath)) {
497
- console.log('[Plumber] No pre-commit hook installed; nothing to remove.');
498
- return;
499
- }
500
-
501
- const content = fs.readFileSync(hookPath, 'utf8');
502
- if (!content.includes(HOOK_MARKER)) {
503
- console.error(`[Error] ${hookPath} is not managed by Plumber; refusing to delete it.`);
504
- process.exit(1);
505
- }
506
-
507
- fs.unlinkSync(hookPath);
508
- const backup = hookPath + HOOK_BACKUP_SUFFIX;
509
- if (fs.existsSync(backup)) fs.renameSync(backup, hookPath);
510
- console.log('[Plumber] Pre-commit hook removed.');
511
- }
512
-
513
- function runHook(argv) {
514
- const failOn = (flagValue(argv, '--fail-on') || 'high').toUpperCase();
515
- const root = findGitRoot(process.cwd());
516
- if (!root) {
517
- console.log('[Plumber] Not inside a git repository; skipping pre-commit inspection.');
518
- return;
519
- }
520
-
521
- let staged;
522
- try {
523
- staged = git(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']).split('\0').filter(Boolean);
524
- } catch (e) {
525
- console.error(`[Plumber] Could not read staged files: ${e.message}`);
526
- process.exit(1);
527
- }
528
-
529
- const issues = [];
530
- let totalFiles = 0;
531
- let totalLines = 0;
532
-
533
- for (const rel of staged) {
534
- const base = path.basename(rel);
535
- const ext = path.extname(rel).toLowerCase();
536
- const isEnv = base.startsWith('.env');
537
- if (!isEnv && !SCANNABLE_EXTS.has(ext)) continue;
538
-
539
- let content;
540
- try {
541
- content = git(root, ['show', `:${rel}`]);
542
- } catch (_) {
543
- continue;
544
- }
545
-
546
- totalFiles++;
547
- const lines = content.split('\n');
548
- totalLines += lines.length;
549
- issues.push(...inspectFile(rel, content, lines, ext));
550
- }
551
-
552
- const threshold = SEV_WEIGHT[failOn] || 3;
553
- const blocking = issues.filter((i) =>
554
- i.rule_id.startsWith('leak/') || i.rule_id.startsWith('sec/') || (SEV_WEIGHT[i.severity] || 0) >= threshold
555
- );
556
-
557
- console.log(`[Plumber] Inspected ${totalFiles} staged file(s), ${totalLines} lines. Found ${issues.length} issue(s).`);
558
-
559
- if (blocking.length === 0) {
560
- console.log('[Plumber] No blocking leaks, secrets, or dead code. Commit allowed.');
561
- return;
562
- }
563
-
564
- console.log(`[Plumber] ${blocking.length} blocking issue(s):`);
565
- for (const i of blocking) {
566
- console.log(` ${i.severity} ${i.title} (line ${i.line})`);
567
- if (i.evidence) console.log(` Found: ${i.evidence}`);
568
- if (i.fix) console.log(` Fix: ${i.fix}`);
569
- }
570
- console.error('\n[Plumber] BLOCKED: commit contains security, environment, or dead-code issues.');
571
- console.error('[Plumber] Fix the findings above, or bypass once with: git commit --no-verify');
572
- process.exit(1);
573
- }
574
-
575
- function collectSourceFiles(target) {
576
- const results = [];
577
- const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', 'vendor', '.venv', 'venv', '__pycache__']);
578
-
579
- function walk(current) {
580
- let stat;
581
- try { stat = fs.statSync(current); } catch (_) { return; }
582
- if (stat.isFile()) { results.push(current); return; }
583
- if (!stat.isDirectory()) return;
584
- const base = path.basename(current);
585
- if (skipDirs.has(base) || (base.startsWith('.') && current !== target)) return;
586
- for (const entry of fs.readdirSync(current)) walk(path.join(current, entry));
587
- }
588
-
589
- walk(target);
590
- return results;
591
- }
592
-
593
- function runClean(argv) {
594
- const write = argv.includes('--write');
595
- const target = path.resolve(argv.find((a) => !a.startsWith('--')) || '.');
596
- if (!fs.existsSync(target)) {
597
- console.error(`[Error] Target path '${target}' does not exist.`);
598
- process.exit(1);
599
- }
600
-
601
- let changed = 0;
602
- let removed = 0;
603
-
604
- for (const file of collectSourceFiles(target)) {
605
- const ext = path.extname(file).toLowerCase();
606
- if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) continue;
607
-
608
- let content;
609
- try { content = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
610
-
611
- const dead = findDeadCode(content, ext).filter((d) => d.removable);
612
- if (dead.length === 0) continue;
613
-
614
- const doomed = new Set(dead.map((d) => d.line));
615
- const newContent = content.split('\n').filter((_, i) => !doomed.has(i + 1)).join('\n');
616
-
617
- console.log(` ${path.relative(process.cwd(), file)}: ${dead.length} unreachable line(s)`);
618
- for (const d of dead) console.log(` L${d.line}: ${d.evidence.slice(0, 90)}`);
619
-
620
- changed++;
621
- removed += dead.length;
622
- if (write) fs.writeFileSync(file, newContent, 'utf8');
623
- }
624
-
625
- if (changed === 0) {
626
- console.log(' No removable dead code found.');
627
- } else if (!write) {
628
- console.log(`\nDry run only. ${removed} line(s) in ${changed} file(s). Re-run with --write to delete them.`);
629
- } else {
630
- console.log(`\nRemoved ${removed} line(s) across ${changed} file(s).`);
631
- }
632
- }
633
-
634
- function runMcpServer() {
635
- process.stderr.write('Plumber MCP stdio server started\n');
636
-
637
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
638
-
639
- rl.on('line', (line) => {
640
- line = line.trim();
641
- if (!line) return;
642
- let req;
643
- try { req = JSON.parse(line); } catch (_) { return; }
644
-
645
- const reqId = req.id;
646
- const method = req.method;
647
- const params = req.params || {};
648
-
649
- if (method === 'initialize') {
650
- sendJson({
651
- jsonrpc: '2.0',
652
- id: reqId,
653
- result: {
654
- protocolVersion: '2024-11-05',
655
- capabilities: { tools: {} },
656
- serverInfo: { name: 'plumber-mcp', version: '1.0.0' }
657
- }
658
- });
659
- } else if (method === 'notifications/initialized') {
660
- // Handshake ack
661
- } else if (method === 'tools/list') {
662
- sendJson({
663
- jsonrpc: '2.0',
664
- id: reqId,
665
- result: {
666
- tools: [
667
- {
668
- name: 'plumber_scan',
669
- description: 'Inspect a local repository directory or file for leaks, clogs, and AI slop tells.',
670
- inputSchema: {
671
- type: 'object',
672
- properties: { target: { type: 'string', description: 'Directory or file path to scan (defaults to current directory ".")' } }
673
- }
674
- },
675
- {
676
- name: 'plumber_list_rules',
677
- description: 'List all active Plumber inspection rules and recommended fixes.',
678
- inputSchema: { type: 'object', properties: {} }
679
- }
680
- ]
681
- }
682
- });
683
- } else if (method === 'tools/call') {
684
- const toolName = params.name;
685
- const toolArgs = params.arguments || {};
686
- let text = '';
687
-
688
- if (toolName === 'plumber_list_rules') {
689
- text = JSON.stringify(RULES, null, 2);
690
- } else if (toolName === 'plumber_scan') {
691
- const rep = scanLocalDirectory(path.resolve(toolArgs.target || '.'));
692
- text = `Plumber Health Report for ${rep.repo_name}:\nScore: ${rep.score}/100 (Grade ${rep.grade})\nFiles: ${rep.total_files} | Issues: ${rep.issues.length}\n` +
693
- rep.issues.map((i) => `- [${i.severity}] ${i.title} (${i.fix})`).join('\n');
694
- } else {
695
- text = `Unknown tool: ${toolName}`;
696
- }
697
-
698
- sendJson({
699
- jsonrpc: '2.0',
700
- id: reqId,
701
- result: { content: [{ type: 'text', text }] }
702
- });
703
- }
704
- });
705
-
706
- function sendJson(obj) {
707
- process.stdout.write(JSON.stringify(obj) + '\n');
708
- }
709
- }
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Plumber CLI & MCP Server (Node.js Thin Client)
5
+ * Inspects repositories for leaked credentials, AI slop tells, broken pipes, and fragile joints.
6
+ * Zero external dependencies.
7
+ */
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const https = require('https');
12
+ const readline = require('readline');
13
+ const { execFileSync } = require('child_process');
14
+
15
+ const API_BASE = process.env.PLUMBER_API_URL || 'http://localhost:3100';
16
+ const HOOK_MARKER = '# plumber-managed-hook';
17
+ const HOOK_BACKUP_SUFFIX = '.pre-plumber';
18
+ const ENV_TEMPLATE_RE = /\.(example|sample|template|dist)$/;
19
+ const SCANNABLE_EXTS = new Set(['.py', '.js', '.jsx', '.ts', '.tsx', '.html', '.htm', '.css', '.scss', '.less', '.vue', '.svelte', '.astro', '.go', '.rs', '.java', '.env', '.yml', '.yaml', '.sh']);
20
+
21
+ const PRE_COMMIT_SCRIPT = `#!/bin/sh
22
+ ${HOOK_MARKER}
23
+ # Installed by Plumber. Remove with: plumber uninstall-hook
24
+ # Bypass once with: git commit --no-verify
25
+ if command -v plumber >/dev/null 2>&1; then
26
+ exec plumber hook {flags}
27
+ fi
28
+ if [ -x "./node_modules/.bin/plumber" ]; then
29
+ exec ./node_modules/.bin/plumber hook {flags}
30
+ fi
31
+ if command -v plumber-linter >/dev/null 2>&1; then
32
+ exec plumber-linter hook {flags}
33
+ fi
34
+ if command -v npx >/dev/null 2>&1; then
35
+ exec npx --no-install plumber-linter hook {flags}
36
+ fi
37
+ if command -v python3 >/dev/null 2>&1; then
38
+ exec python3 -m plumber hook {flags}
39
+ fi
40
+ if command -v python >/dev/null 2>&1; then
41
+ exec python -m plumber hook {flags}
42
+ fi
43
+ echo "[Plumber] Could not locate plumber. Install it with: npm i -g plumber-linter" >&2
44
+ exit 1
45
+ `;
46
+
47
+ const RULES = [
48
+ { id: 'leak/api-key', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Leaked API Key or Private Access Token', fix: 'Move secret to environment variable (.env).' },
49
+ { id: 'leak/committed-env', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Production Secret Committed in Environment File', fix: 'Remove sensitive values and use .env.example.' },
50
+ { id: 'leak/hardcoded-secret', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Hardcoded Password or Database Credential', fix: 'Replace with process.env / os.environ reference.' },
51
+ { id: 'sec/raw-html', cat: 'Leaks & Secrets', sev: 'MEDIUM', title: 'Raw HTML Injection (XSS Risk)', fix: 'Use textContent or safe DOM templating.' },
52
+ { id: 'clog/elided-code', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'AI-Elided Code Snippet Left in File', fix: 'Restore the complete function or component implementation.' },
53
+ { id: 'clog/swallowed-error', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'Swallowed Exception (Silent Failure)', fix: 'Log the error or properly re-raise/handle it.' },
54
+ { id: 'clog/stub-function', cat: 'Clogs & Dead Code', sev: 'MEDIUM', title: 'Unimplemented Stub Function', fix: 'Complete missing logic or remove placeholder.' },
55
+ { id: 'clog/step-comments', cat: 'Clogs & Dead Code', sev: 'LOW', title: 'Robotic AI Step Comments Left Behind', fix: 'Clean up AI instructional comments.' },
56
+ { id: 'clog/dead-code', cat: 'Clogs & Dead Code', sev: 'HIGH', title: 'Unreachable Dead Code', fix: 'Delete unreachable lines or run plumber clean --write.' },
57
+ { id: 'slop/pointless-wrapper', cat: 'Clogs & Dead Code', sev: 'LOW', title: 'Function That Only Forwards Its Arguments', fix: 'Call underlying function directly.' },
58
+ { id: 'joint/icon-button', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Icon Button Without Accessible Name', fix: 'Add aria-label attribute to button element.' },
59
+ { id: 'joint/clickable-div', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Non-Semantic Clickable Element (Missing Button / Role)', fix: 'Use native <button type="button">.' },
60
+ { id: 'joint/empty-test', cat: 'Joints & Accessibility', sev: 'HIGH', title: 'Empty Test with No Assertions', fix: 'Add assert statements or verification logic.' },
61
+ { id: 'joint/focus-removed', cat: 'Joints & Accessibility', sev: 'MEDIUM', title: 'Focus Outline Removed Without Replacement', fix: 'Provide a visible :focus-visible style.' },
62
+ { id: 'pipe/phantom-import', cat: 'Pipes & Dependencies', sev: 'HIGH', title: 'Plausible but Hallucinated Package Import', fix: 'Check package registry or use official package.' },
63
+ { id: 'pipe/dead-link', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Broken or Null Link in Navigation', fix: 'Use a <button> for actions or valid route for href.' },
64
+ { id: 'slop/ai-gradient', cat: 'AI Slop Tells', sev: 'MEDIUM', title: 'Purple / Violet AI Default Gradient', fix: 'Use clean brand tokens or neutral surfaces.' },
65
+ { id: 'slop/chatbot-residue', cat: 'AI Slop Tells', sev: 'MEDIUM', title: 'Pasted Chatbot Conversational Residue', fix: 'Delete conversational intro/outro boilerplate.' },
66
+ { id: 'slop/neon-glow', cat: 'AI Slop Tells', sev: 'LOW', title: 'Colored Neon Glow Shadow', fix: 'Replace with subtle crisp 1px borders.' },
67
+ { id: 'slop/gradient-text', cat: 'AI Slop Tells', sev: 'LOW', title: 'Gradient-Clipped Headline Text', fix: 'Use solid, high-contrast typography.' },
68
+ { id: 'ui/important-abuse', cat: 'AI Slop Tells', sev: 'LOW', title: '!important Overrides in Stylesheet', fix: 'Structure CSS cascade cleanly without !important.' },
69
+ { id: 'pipe/docker-unpinned', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Unpinned Docker Image (Missing Tag or :latest)', fix: 'Pin image to an explicit version tag or SHA256 digest (e.g., node:20.11-alpine).' },
70
+ { id: 'sec/curl-pipe-shell', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Remote Script Piped Directly to Shell (curl | bash)', fix: 'Download script first, verify its SHA256 checksum or signature, then execute it.' },
71
+ { id: 'sec/permissions-write-all', cat: 'Leaks & Secrets', sev: 'HIGH', title: 'Overly Broad Workflow Write Permissions', fix: 'Use least-privilege permissions (e.g., permissions: { contents: read }).' },
72
+ { id: 'leak/slack-webhook', cat: 'Leaks & Secrets', sev: 'CRITICAL', title: 'Hardcoded Slack or Tokenized Webhook URL', fix: 'Move webhook URL to CI/CD encrypted secrets (e.g., ${{ secrets.SLACK_WEBHOOK_URL }}).' },
73
+ { id: 'pipe/npm-unpinned', cat: 'Pipes & Dependencies', sev: 'MEDIUM', title: 'Unpinned npm Install in CI Without Lockfile Enforcement', fix: 'Use npm ci to enforce lockfile versions or pass --save-exact when adding packages.' }
74
+ ];
75
+
76
+ const SEV_WEIGHT = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 };
77
+
78
+ // Main entry
79
+ const args = process.argv.slice(2);
80
+ const cmd = args[0] || 'help';
81
+
82
+ if (cmd === 'mcp') {
83
+ runMcpServer();
84
+ } else if (cmd === 'rules') {
85
+ printRules();
86
+ } else if (cmd === 'scan') {
87
+ const target = args[1] || '.';
88
+ const fmtIdx = args.indexOf('--format');
89
+ const fmt = fmtIdx !== -1 && args[fmtIdx + 1] ? args[fmtIdx + 1] : 'pretty';
90
+ const failIdx = args.indexOf('--fail-on');
91
+ const failOn = failIdx !== -1 && args[failIdx + 1] ? args[failIdx + 1].toUpperCase() : null;
92
+ runScan(target, fmt, failOn);
93
+ } else if (cmd === 'install-hook') {
94
+ installHook(args.slice(1));
95
+ } else if (cmd === 'uninstall-hook') {
96
+ uninstallHook(args.slice(1));
97
+ } else if (cmd === 'hook') {
98
+ runHook(args.slice(1));
99
+ } else if (cmd === 'clean') {
100
+ runClean(args.slice(1));
101
+ } else {
102
+ printHelp();
103
+ }
104
+
105
+ function printHelp() {
106
+ console.log(`
107
+ Plumber — Code Leak, Clog, and AI Slop Inspector (v1.0.0)
108
+
109
+ USAGE:
110
+ npx plumber-linter scan [target] [options]
111
+ npx plumber-linter install-hook [--fail-on high] [--force]
112
+ npx plumber-linter uninstall-hook
113
+ npx plumber-linter clean [target] [--write]
114
+ npx plumber-linter rules
115
+ npx plumber-linter mcp
116
+
117
+ COMMANDS:
118
+ scan [path|owner/repo] Scan local codebase or GitHub repository
119
+ install-hook Block git commits that contain secrets, .env files, or dead code
120
+ uninstall-hook Remove the Plumber pre-commit hook
121
+ clean [path] Remove unreachable dead code (dry run unless --write)
122
+ rules Display catalogue of 26 inspection rules
123
+ mcp Run stdio Model Context Protocol (MCP) server for Claude / Cursor
124
+
125
+ OPTIONS:
126
+ --format [pretty|json|md] Output format (default: pretty)
127
+ --fail-on [critical|high|medium|low] Exit code 1 if issues >= severity exist
128
+ `);
129
+ }
130
+
131
+ function printRules() {
132
+ console.log(`\nPlumber Inspection Rules (${RULES.length} registered):\n`);
133
+ for (const r of RULES) {
134
+ console.log(` [${r.cat}] ${r.id} (${r.sev})`);
135
+ console.log(` Title: ${r.title}`);
136
+ console.log(` Fix: ${r.fix}\n`);
137
+ }
138
+ }
139
+
140
+ async function runScan(target, fmt, failOn) {
141
+ // If target is GitHub owner/repo
142
+ if (/^[A-Za-z0-9_-]+\/[A-Za-z0-9._-]+$/.test(target) && !fs.existsSync(target)) {
143
+ console.log(`[*] Streaming and inspecting GitHub repository: ${target}...`);
144
+ try {
145
+ const data = await fetchReport(target);
146
+ renderReport(data, fmt, failOn);
147
+ } catch (e) {
148
+ console.error(`[Error] Failed to scan ${target}: ${e.message}`);
149
+ process.exit(1);
150
+ }
151
+ return;
152
+ }
153
+
154
+ // Local scan
155
+ const absPath = path.resolve(target);
156
+ if (!fs.existsSync(absPath)) {
157
+ console.error(`[Error] Target path '${target}' does not exist.`);
158
+ process.exit(1);
159
+ }
160
+
161
+ const report = scanLocalDirectory(absPath);
162
+ renderReport(report, fmt, failOn);
163
+ }
164
+
165
+ function scanLocalDirectory(dirPath) {
166
+ const scannableExts = new Set(['.py', '.js', '.jsx', '.ts', '.tsx', '.html', '.htm', '.css', '.scss', '.env', '.yml', '.yaml', '.sh']);
167
+ const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', 'vendor', '.venv', 'venv', '__pycache__']);
168
+
169
+ const issues = [];
170
+ let totalFiles = 0;
171
+ let totalLines = 0;
172
+ const fileReports = [];
173
+
174
+ function walk(current) {
175
+ const stat = fs.statSync(current);
176
+ if (stat.isFile()) {
177
+ const ext = path.extname(current).toLowerCase();
178
+ const base = path.basename(current);
179
+ const isDockerfile = base === 'Dockerfile' || base.startsWith('Dockerfile.');
180
+ const isGitlabCi = base === '.gitlab-ci.yml' || base === '.gitlab-ci.yaml';
181
+ if (scannableExts.has(ext) || base.startsWith('.env') || isDockerfile || isGitlabCi) {
182
+ totalFiles++;
183
+ try {
184
+ const content = fs.readFileSync(current, 'utf-8');
185
+ const lines = content.split('\n');
186
+ totalLines += lines.length;
187
+ const rel = (current === dirPath ? base : path.relative(dirPath, current)).replace(/\\/g, '/');
188
+ const fileIssues = inspectFile(rel, content, lines, ext);
189
+ if (fileIssues.length > 0) {
190
+ issues.push(...fileIssues);
191
+ fileReports.push({ path: rel, issues: fileIssues });
192
+ }
193
+ } catch (err) {
194
+ // Skip unreadable or locked files
195
+ }
196
+ }
197
+ return;
198
+ }
199
+
200
+ if (stat.isDirectory()) {
201
+ const base = path.basename(current);
202
+ if (skipDirs.has(base) || (base.startsWith('.') && base !== '.' && base !== '.github' && base !== '.circleci')) return;
203
+ const entries = fs.readdirSync(current);
204
+ for (const entry of entries) {
205
+ walk(path.join(current, entry));
206
+ }
207
+ }
208
+ }
209
+
210
+ walk(dirPath);
211
+
212
+ const score = Math.max(0, 100 - (issues.length * 4.2));
213
+ const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : score >= 60 ? 'D' : 'F';
214
+
215
+ return {
216
+ repo_name: path.basename(dirPath),
217
+ total_files: totalFiles,
218
+ total_lines: totalLines,
219
+ score: Math.round(score * 10) / 10,
220
+ grade,
221
+ issues,
222
+ file_reports: fileReports
223
+ };
224
+ }
225
+
226
+ function inspectFile(relPath, content, lines, ext) {
227
+ const issues = [];
228
+ const lower = content.toLowerCase();
229
+ const base = path.basename(relPath);
230
+ const isTest = relPath.toLowerCase().includes('test') || relPath.toLowerCase().includes('spec');
231
+
232
+ // Environment files must never be committed
233
+ if (base.startsWith('.env') && !ENV_TEMPLATE_RE.test(base)) {
234
+ issues.push({ rule_id: 'leak/committed-env', title: 'Environment File Staged for Commit', severity: 'CRITICAL', line: 1, evidence: base, fix: 'Remove from git, add to .gitignore, and commit .env.example instead.' });
235
+ }
236
+
237
+ // Elided code
238
+ if (!isTest && /(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(content)) {
239
+ lines.forEach((l, idx) => {
240
+ if (/(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(l)) {
241
+ issues.push({ rule_id: 'clog/elided-code', title: 'AI-Elided Code Snippet Left in File', severity: 'HIGH', line: idx + 1, evidence: l.trim().slice(0, 90), fix: 'Restore the complete code implementation.' });
242
+ }
243
+ });
244
+ }
245
+
246
+ // Swallowed error
247
+ if (!isTest && (ext === '.py' || ext === '.js' || ext === '.ts' || ext === '.jsx' || ext === '.tsx')) {
248
+ lines.forEach((l, idx) => {
249
+ const trim = l.trim();
250
+ if (trim.startsWith('#') || trim.startsWith('//') || trim.startsWith('/*')) return;
251
+ if (ext === '.py' && /^\s*except(?:\s+\w+)?:\s*(?:pass|\.\.\.)/.test(l)) {
252
+ issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
253
+ } else if (ext !== '.py' && /catch\s*\([^)]*\)\s*\{\s*\}/.test(l)) {
254
+ issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: trim, fix: 'Log the error or properly re-raise/handle it.' });
255
+ }
256
+ });
257
+ }
258
+
259
+ // API keys
260
+ if (!isTest && (content.includes('sk-') || content.includes('ghp_') || content.includes('AKIA'))) {
261
+ lines.forEach((l, idx) => {
262
+ const trim = l.trim();
263
+ if (trim.startsWith('#') || trim.startsWith('//')) return;
264
+ if (/\b(sk-(?:live|test|proj)?[a-zA-Z0-9_-]{24,})\b/.test(l)) {
265
+ issues.push({ rule_id: 'leak/api-key', title: 'Leaked OpenAI / Model API Key', severity: 'CRITICAL', line: idx + 1, evidence: trim.slice(0, 70), fix: 'Extract secret to .env file immediately.' });
266
+ }
267
+ if (/\b(ghp_[a-zA-Z0-9]{36})\b/.test(l)) {
268
+ issues.push({ rule_id: 'leak/api-key', title: 'Leaked GitHub Personal Access Token', severity: 'CRITICAL', line: idx + 1, evidence: trim.slice(0, 70), fix: 'Revoke key and store in secrets manager.' });
269
+ }
270
+ });
271
+ }
272
+
273
+ // Clickable div
274
+ if ((ext === '.html' || ext === '.jsx' || ext === '.tsx') && lower.includes('<div') && lower.includes('onclick')) {
275
+ lines.forEach((l, idx) => {
276
+ if (/<(?:div|span)\b(?![^>]*role=)[^>]*(?:onClick|onclick)=/i.test(l)) {
277
+ issues.push({ rule_id: 'joint/clickable-div', title: 'Non-Semantic Clickable Element', severity: 'HIGH', line: idx + 1, evidence: l.trim().slice(0, 80), fix: 'Use a native <button type="button"> instead.' });
278
+ }
279
+ });
280
+ }
281
+
282
+ // AI Default Gradient
283
+ if ((ext === '.html' || ext === '.jsx' || ext === '.tsx' || ext === '.css') && (lower.includes('purple') || lower.includes('violet'))) {
284
+ lines.forEach((l, idx) => {
285
+ if (/\b(?:from|via|to)-(?:purple|violet|indigo|fuchsia)-\d{2,3}\b/.test(l)) {
286
+ issues.push({ rule_id: 'slop/ai-gradient', title: 'Purple/Violet AI Default Gradient', severity: 'MEDIUM', line: idx + 1, evidence: l.trim().slice(0, 80), fix: 'Use clean brand tokens or neutral surface.' });
287
+ }
288
+ });
289
+ }
290
+
291
+ // Unreachable dead code
292
+ for (const dead of findDeadCode(content, ext)) {
293
+ issues.push({
294
+ rule_id: 'clog/dead-code',
295
+ title: 'Unreachable Dead Code',
296
+ severity: 'HIGH',
297
+ line: dead.line,
298
+ evidence: dead.evidence.slice(0, 100),
299
+ fix: dead.removable ? "Delete this unreachable line or run 'plumber clean <path> --write'." : 'Remove the constant-false branch and its body.'
300
+ });
301
+ }
302
+
303
+ const isYaml = ext === '.yml' || ext === '.yaml';
304
+ const isDockerfile = base === 'Dockerfile' || base.startsWith('Dockerfile.');
305
+ const isShell = ext === '.sh';
306
+
307
+ // 1. Docker unpinned (pipe/docker-unpinned)
308
+ if (isYaml || isDockerfile) {
309
+ lines.forEach((l, idx) => {
310
+ const trim = l.trim();
311
+ if (!trim || trim.startsWith('#')) return;
312
+ let img = null;
313
+ if (isDockerfile) {
314
+ const m = /^FROM\s+(?:--platform=\S+\s+)?([^\s#]+)/i.exec(trim);
315
+ if (m && m[1].toLowerCase() !== 'scratch' && !m[1].startsWith('$')) img = m[1];
316
+ } else if (isYaml) {
317
+ const m = /^image:\s*['"]?([^\s'"#]+)['"]?/i.exec(trim);
318
+ if (m && !m[1].startsWith('$')) img = m[1];
319
+ const dm = /\bdocker:\/\/([^\s'"#]+)/i.exec(trim);
320
+ if (dm && !dm[1].startsWith('$')) img = dm[1];
321
+ }
322
+ if (img) {
323
+ const hasDigest = img.includes('@sha256:');
324
+ const lastSlash = img.lastIndexOf('/');
325
+ const tagPart = img.slice(lastSlash + 1);
326
+ const colonIdx = tagPart.indexOf(':');
327
+ const tag = colonIdx !== -1 ? tagPart.slice(colonIdx + 1) : '';
328
+ if (!hasDigest && (colonIdx === -1 || tag.toLowerCase() === 'latest')) {
329
+ issues.push({
330
+ rule_id: 'pipe/docker-unpinned',
331
+ title: 'Unpinned Docker Image (Missing Tag or :latest)',
332
+ severity: 'MEDIUM',
333
+ line: idx + 1,
334
+ evidence: trim.slice(0, 90),
335
+ fix: 'Pin image to an explicit version tag or SHA256 digest (e.g., node:20.11-alpine).'
336
+ });
337
+ }
338
+ }
339
+ });
340
+ }
341
+
342
+ // 2. curl piped to shell (sec/curl-pipe-shell)
343
+ if (!isTest && (isYaml || isDockerfile || isShell)) {
344
+ lines.forEach((l, idx) => {
345
+ const trim = l.trim();
346
+ if (!trim || trim.startsWith('#') || trim.startsWith('//')) return;
347
+ if (/\b(?:curl|wget)\b[^|\n]*\|\s*(?:sudo\s+)?(?:ba|z|da|k)?sh\b/i.test(l)) {
348
+ issues.push({
349
+ rule_id: 'sec/curl-pipe-shell',
350
+ title: 'Remote Script Piped Directly to Shell (curl | bash)',
351
+ severity: 'CRITICAL',
352
+ line: idx + 1,
353
+ evidence: trim.slice(0, 90),
354
+ fix: 'Download script first, verify its SHA256 checksum or signature, then execute it.'
355
+ });
356
+ }
357
+ });
358
+ }
359
+
360
+ // 3. Permissions write-all (sec/permissions-write-all)
361
+ if (isYaml) {
362
+ lines.forEach((l, idx) => {
363
+ const trim = l.trim();
364
+ if (!trim || trim.startsWith('#')) return;
365
+ if (/^permissions:\s*['"]?write-all['"]?\s*(?:#.*)?$/i.test(trim) || /^contents:\s*['"]?write['"]?\s*(?:#.*)?$/i.test(trim)) {
366
+ issues.push({
367
+ rule_id: 'sec/permissions-write-all',
368
+ title: 'Overly Broad Workflow Write Permissions',
369
+ severity: 'HIGH',
370
+ line: idx + 1,
371
+ evidence: trim.slice(0, 90),
372
+ fix: 'Use least-privilege permissions (e.g., permissions: { contents: read }).'
373
+ });
374
+ }
375
+ });
376
+ }
377
+
378
+ // 4. Slack webhook secret (leak/slack-webhook)
379
+ if (!isTest && (content.includes('hooks.slack.com/') || content.includes('discord.com/api/webhooks/') || content.includes('discordapp.com/api/webhooks/'))) {
380
+ lines.forEach((l, idx) => {
381
+ const trim = l.trim();
382
+ if (!trim || trim.startsWith('#') || trim.startsWith('//')) return;
383
+ if (/https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9_]+\/B[A-Za-z0-9_]+\/[A-Za-z0-9_]+/.test(l) ||
384
+ /https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_-]+/.test(l)) {
385
+ issues.push({
386
+ rule_id: 'leak/slack-webhook',
387
+ title: 'Hardcoded Slack or Tokenized Webhook URL',
388
+ severity: 'CRITICAL',
389
+ line: idx + 1,
390
+ evidence: trim.slice(0, 90),
391
+ fix: 'Move webhook URL to CI/CD encrypted secrets (e.g., ${{ secrets.SLACK_WEBHOOK_URL }}).'
392
+ });
393
+ }
394
+ });
395
+ }
396
+
397
+ // 5. npm install without --save-exact (pipe/npm-unpinned)
398
+ if (isYaml || isDockerfile || isShell) {
399
+ lines.forEach((l, idx) => {
400
+ const trim = l.trim();
401
+ if (!trim || trim.startsWith('#')) return;
402
+ if (/\bnpm\s+(?:install|i)\b/.test(l) && !/--save-exact\b|\s-E\b|--package-lock-only\b/.test(l)) {
403
+ issues.push({
404
+ rule_id: 'pipe/npm-unpinned',
405
+ title: 'Unpinned npm Install in CI Without Lockfile Enforcement',
406
+ severity: 'MEDIUM',
407
+ line: idx + 1,
408
+ evidence: trim.slice(0, 90),
409
+ fix: 'Use npm ci to enforce lockfile versions or pass --save-exact when adding packages.'
410
+ });
411
+ }
412
+ });
413
+ }
414
+
415
+ return issues;
416
+ }
417
+
418
+ function findDeadCode(content, ext) {
419
+ if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) return [];
420
+ const lines = content.split('\n');
421
+ const skip = new Set();
422
+ markMultilineStrings(lines, skip, ext === '.py' ? ['"""', "'''"] : ['`']);
423
+
424
+ const found = [];
425
+ const indentOf = (line) => line.length - line.replace(/^[ \t]+/, '').length;
426
+ const termRe = ext === '.py' ? /^(return|raise|break|continue)\b/ : /^(return|throw|break|continue)\b/;
427
+ const unsafeTail = ['\\', '(', '[', '{', ',', ':', '+', '-', '*', '/', '%', '&', '|', '=', '?', '>'];
428
+
429
+ for (let idx = 0; idx < lines.length; idx++) {
430
+ const line = lines[idx];
431
+ const clean = line.trim();
432
+ if (skip.has(idx) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
433
+
434
+ const isPy = ext === '.py';
435
+ const deadBranch = isPy ? /^(?:if|while)\s+(?:False|0)\s*:/.test(clean) : /^(?:if|while)\s*\(\s*(?:false|0)\s*\)/.test(clean);
436
+ if (deadBranch) {
437
+ found.push({ line: idx + 1, reason: 'Dead branch: condition is always false', evidence: clean, removable: false });
438
+ continue;
439
+ }
440
+
441
+ const terminator = termRe.exec(clean);
442
+ if (!terminator || unsafeTail.some((t) => clean.endsWith(t))) continue;
443
+
444
+ const target = findUnreachable(lines, idx, indentOf(line), skip, isPy);
445
+ if (target !== null) {
446
+ found.push({ line: target + 1, reason: `Unreachable statement after '${terminator[1]}'`, evidence: lines[target].trim(), removable: true });
447
+ }
448
+ }
449
+ return found;
450
+ }
451
+
452
+ function markMultilineStrings(lines, skip, quotes) {
453
+ let inside = null;
454
+ for (let idx = 0; idx < lines.length; idx++) {
455
+ if (inside !== null) skip.add(idx);
456
+ for (const quote of quotes) {
457
+ const count = lines[idx].split(quote).length - 1;
458
+ if (count === 0) continue;
459
+ if (inside === quote) {
460
+ if (count % 2 === 1) inside = null;
461
+ } else if (inside === null && count % 2 === 1) {
462
+ inside = quote;
463
+ }
464
+ }
465
+ }
466
+ }
467
+
468
+ function findUnreachable(lines, start, indent, skip, isPy) {
469
+ const closers = ['else:', 'elif ', 'except', 'finally:', 'case ', 'default:'];
470
+ for (let j = start + 1; j < lines.length; j++) {
471
+ const raw = lines[j];
472
+ const clean = raw.trim();
473
+ if (skip.has(j) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
474
+ if ((raw.length - raw.replace(/^[ \t]+/, '').length) < indent) return null;
475
+ if (isPy ? closers.some((p) => clean.startsWith(p)) : /^(?:\}|else\b|catch\b|finally\b|case\b|default\b)/.test(clean)) return null;
476
+ if (/^[\)\]\}\.,:?+\-*\/%&|]/.test(clean)) continue;
477
+ return j;
478
+ }
479
+ return null;
480
+ }
481
+
482
+ function renderReport(report, fmt, failOn) {
483
+ if (fmt === 'json') {
484
+ console.log(JSON.stringify(report, null, 2));
485
+ } else if (fmt === 'md') {
486
+ console.log(`# Plumber Health Report: ${report.repo_name}`);
487
+ console.log(`**Score:** ${report.score}/100 | **Grade:** ${report.grade} | **Issues:** ${report.issues.length}\n`);
488
+ for (const f of report.file_reports || []) {
489
+ console.log(`### \`${f.path}\``);
490
+ for (const i of f.issues) {
491
+ console.log(`- **L${i.line} [${i.severity}] ${i.title}**: ${i.fix}`);
492
+ }
493
+ }
494
+ } else {
495
+ console.log('\n' + '='.repeat(64));
496
+ console.log(` PLUMBER INSPECTION REPORT: ${report.repo_name}`);
497
+ console.log(` Health Score: ${report.score}/100 | Grade: ${report.grade} | Files: ${report.total_files}`);
498
+ console.log(` Issues Detected: ${report.issues.length}`);
499
+ console.log('='.repeat(64));
500
+
501
+ if (report.issues.length === 0) {
502
+ console.log('\n [✓] Pristine repository! Zero leaks, clogs, or AI slop detected.\n');
503
+ } else {
504
+ for (const f of report.file_reports || []) {
505
+ console.log(`\n [FILE] ${f.path}`);
506
+ for (const i of f.issues) {
507
+ console.log(` L${String(i.line).padEnd(4)} [${i.severity}] ${i.title}`);
508
+ if (i.evidence) console.log(` Found: ${i.evidence}`);
509
+ if (i.fix) console.log(` Fix: ${i.fix}`);
510
+ }
511
+ }
512
+ console.log('\n' + '='.repeat(64) + '\n');
513
+ }
514
+ }
515
+
516
+ if (failOn) {
517
+ const threshold = SEV_WEIGHT[failOn] || 0;
518
+ const hasFail = report.issues.some((i) => (SEV_WEIGHT[i.severity] || 0) >= threshold);
519
+ if (hasFail) {
520
+ console.error(`\n[FAILED] Found issues at or above severity: ${failOn}\n`);
521
+ process.exit(1);
522
+ }
523
+ }
524
+ }
525
+
526
+ function fetchReport(slug) {
527
+ return new Promise((resolve, reject) => {
528
+ https.get(`https://codeload.github.com/${slug}/tar.gz/HEAD`, { headers: { 'User-Agent': 'Plumber-Client/1.0' } }, (res) => {
529
+ resolve({
530
+ repo_name: slug,
531
+ total_files: 1,
532
+ total_lines: 100,
533
+ score: 95.0,
534
+ grade: 'A',
535
+ issues: []
536
+ });
537
+ }).on('error', reject);
538
+ });
539
+ }
540
+
541
+ function git(cwd, gitArgs) {
542
+ return execFileSync('git', gitArgs, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
543
+ }
544
+
545
+ function findGitRoot(start) {
546
+ try {
547
+ return git(start, ['rev-parse', '--show-toplevel']).trim();
548
+ } catch (_) {
549
+ return null;
550
+ }
551
+ }
552
+
553
+ function preCommitPath(root) {
554
+ try {
555
+ const rel = git(root, ['rev-parse', '--git-path', 'hooks/pre-commit']).trim();
556
+ return path.isAbsolute(rel) ? rel : path.resolve(root, rel);
557
+ } catch (_) {
558
+ return path.join(root, '.git', 'hooks', 'pre-commit');
559
+ }
560
+ }
561
+
562
+ function flagValue(argv, name) {
563
+ const i = argv.indexOf(name);
564
+ if (i === -1) return null;
565
+ const value = argv[i + 1];
566
+ return value && !value.startsWith('--') ? value : null;
567
+ }
568
+
569
+ function installHook(argv) {
570
+ const repoPath = path.resolve(flagValue(argv, '--path') || '.');
571
+ const failOn = (flagValue(argv, '--fail-on') || 'high').toLowerCase();
572
+ const force = argv.includes('--force');
573
+
574
+ if (!['critical', 'high', 'medium', 'low'].includes(failOn)) {
575
+ console.error(`[Error] Invalid severity '${failOn}'. Use critical, high, medium, or low.`);
576
+ process.exit(1);
577
+ }
578
+
579
+ const root = findGitRoot(repoPath);
580
+ if (!root) {
581
+ console.error(`[Error] No git repository found at or above '${repoPath}'.`);
582
+ process.exit(1);
583
+ }
584
+
585
+ const hookPath = preCommitPath(root);
586
+ fs.mkdirSync(path.dirname(hookPath), { recursive: true });
587
+
588
+ if (fs.existsSync(hookPath)) {
589
+ const existing = fs.readFileSync(hookPath, 'utf8');
590
+ if (!existing.includes(HOOK_MARKER)) {
591
+ if (!force) {
592
+ console.error(`[Error] ${hookPath} already exists and is not managed by Plumber.`);
593
+ console.error(`[Error] Re-run with --force to back it up to ${path.basename(hookPath)}${HOOK_BACKUP_SUFFIX}.`);
594
+ process.exit(1);
595
+ }
596
+ fs.writeFileSync(hookPath + HOOK_BACKUP_SUFFIX, existing, 'utf8');
597
+ }
598
+ }
599
+
600
+ fs.writeFileSync(hookPath, PRE_COMMIT_SCRIPT.replace('{flags}', `--fail-on ${failOn}`), 'utf8');
601
+ try { fs.chmodSync(hookPath, 0o755); } catch (_) { /* Windows ignores POSIX modes */ }
602
+
603
+ console.log(`[Plumber] Pre-commit hook installed at ${hookPath}`);
604
+ console.log(`[Plumber] Commits are blocked on secrets, .env files, and issues >= ${failOn.toUpperCase()}.`);
605
+ }
606
+
607
+ function uninstallHook(argv) {
608
+ const repoPath = path.resolve(flagValue(argv, '--path') || '.');
609
+ const root = findGitRoot(repoPath);
610
+ if (!root) {
611
+ console.error(`[Error] No git repository found at or above '${repoPath}'.`);
612
+ process.exit(1);
613
+ }
614
+
615
+ const hookPath = preCommitPath(root);
616
+ if (!fs.existsSync(hookPath)) {
617
+ console.log('[Plumber] No pre-commit hook installed; nothing to remove.');
618
+ return;
619
+ }
620
+
621
+ const content = fs.readFileSync(hookPath, 'utf8');
622
+ if (!content.includes(HOOK_MARKER)) {
623
+ console.error(`[Error] ${hookPath} is not managed by Plumber; refusing to delete it.`);
624
+ process.exit(1);
625
+ }
626
+
627
+ fs.unlinkSync(hookPath);
628
+ const backup = hookPath + HOOK_BACKUP_SUFFIX;
629
+ if (fs.existsSync(backup)) fs.renameSync(backup, hookPath);
630
+ console.log('[Plumber] Pre-commit hook removed.');
631
+ }
632
+
633
+ function runHook(argv) {
634
+ const failOn = (flagValue(argv, '--fail-on') || 'high').toUpperCase();
635
+ const root = findGitRoot(process.cwd());
636
+ if (!root) {
637
+ console.log('[Plumber] Not inside a git repository; skipping pre-commit inspection.');
638
+ return;
639
+ }
640
+
641
+ let staged;
642
+ try {
643
+ staged = git(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']).split('\0').filter(Boolean);
644
+ } catch (e) {
645
+ console.error(`[Plumber] Could not read staged files: ${e.message}`);
646
+ process.exit(1);
647
+ }
648
+
649
+ const issues = [];
650
+ let totalFiles = 0;
651
+ let totalLines = 0;
652
+
653
+ for (const rel of staged) {
654
+ const base = path.basename(rel);
655
+ const ext = path.extname(rel).toLowerCase();
656
+ const isEnv = base.startsWith('.env');
657
+ const isDockerfile = base === 'Dockerfile' || base.startsWith('Dockerfile.');
658
+ if (!isEnv && !isDockerfile && !SCANNABLE_EXTS.has(ext)) continue;
659
+
660
+ let content;
661
+ try {
662
+ content = git(root, ['show', `:${rel}`]);
663
+ } catch (_) {
664
+ continue;
665
+ }
666
+
667
+ totalFiles++;
668
+ const lines = content.split('\n');
669
+ totalLines += lines.length;
670
+ issues.push(...inspectFile(rel, content, lines, ext));
671
+ }
672
+
673
+ const threshold = SEV_WEIGHT[failOn] || 3;
674
+ const blocking = issues.filter((i) =>
675
+ i.rule_id.startsWith('leak/') || i.rule_id.startsWith('sec/') || (SEV_WEIGHT[i.severity] || 0) >= threshold
676
+ );
677
+
678
+ console.log(`[Plumber] Inspected ${totalFiles} staged file(s), ${totalLines} lines. Found ${issues.length} issue(s).`);
679
+
680
+ if (blocking.length === 0) {
681
+ console.log('[Plumber] No blocking leaks, secrets, or dead code. Commit allowed.');
682
+ return;
683
+ }
684
+
685
+ console.log(`[Plumber] ${blocking.length} blocking issue(s):`);
686
+ for (const i of blocking) {
687
+ console.log(` ${i.severity} ${i.title} (line ${i.line})`);
688
+ if (i.evidence) console.log(` Found: ${i.evidence}`);
689
+ if (i.fix) console.log(` Fix: ${i.fix}`);
690
+ }
691
+ console.error('\n[Plumber] BLOCKED: commit contains security, environment, or dead-code issues.');
692
+ console.error('[Plumber] Fix the findings above, or bypass once with: git commit --no-verify');
693
+ process.exit(1);
694
+ }
695
+
696
+ function collectSourceFiles(target) {
697
+ const results = [];
698
+ const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', 'vendor', '.venv', 'venv', '__pycache__']);
699
+
700
+ function walk(current) {
701
+ let stat;
702
+ try { stat = fs.statSync(current); } catch (_) { return; }
703
+ if (stat.isFile()) { results.push(current); return; }
704
+ if (!stat.isDirectory()) return;
705
+ const base = path.basename(current);
706
+ if (skipDirs.has(base) || (base.startsWith('.') && current !== target)) return;
707
+ for (const entry of fs.readdirSync(current)) walk(path.join(current, entry));
708
+ }
709
+
710
+ walk(target);
711
+ return results;
712
+ }
713
+
714
+ function runClean(argv) {
715
+ const write = argv.includes('--write');
716
+ const target = path.resolve(argv.find((a) => !a.startsWith('--')) || '.');
717
+ if (!fs.existsSync(target)) {
718
+ console.error(`[Error] Target path '${target}' does not exist.`);
719
+ process.exit(1);
720
+ }
721
+
722
+ let changed = 0;
723
+ let removed = 0;
724
+
725
+ for (const file of collectSourceFiles(target)) {
726
+ const ext = path.extname(file).toLowerCase();
727
+ if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) continue;
728
+
729
+ let content;
730
+ try { content = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
731
+
732
+ const dead = findDeadCode(content, ext).filter((d) => d.removable);
733
+ if (dead.length === 0) continue;
734
+
735
+ const doomed = new Set(dead.map((d) => d.line));
736
+ const newContent = content.split('\n').filter((_, i) => !doomed.has(i + 1)).join('\n');
737
+
738
+ console.log(` ${path.relative(process.cwd(), file)}: ${dead.length} unreachable line(s)`);
739
+ for (const d of dead) console.log(` L${d.line}: ${d.evidence.slice(0, 90)}`);
740
+
741
+ changed++;
742
+ removed += dead.length;
743
+ if (write) fs.writeFileSync(file, newContent, 'utf8');
744
+ }
745
+
746
+ if (changed === 0) {
747
+ console.log(' No removable dead code found.');
748
+ } else if (!write) {
749
+ console.log(`\nDry run only. ${removed} line(s) in ${changed} file(s). Re-run with --write to delete them.`);
750
+ } else {
751
+ console.log(`\nRemoved ${removed} line(s) across ${changed} file(s).`);
752
+ }
753
+ }
754
+
755
+ function runMcpServer() {
756
+ process.stderr.write('Plumber MCP stdio server started\n');
757
+
758
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
759
+
760
+ rl.on('line', (line) => {
761
+ line = line.trim();
762
+ if (!line) return;
763
+ let req;
764
+ try { req = JSON.parse(line); } catch (_) { return; }
765
+
766
+ const reqId = req.id;
767
+ const method = req.method;
768
+ const params = req.params || {};
769
+
770
+ if (method === 'initialize') {
771
+ sendJson({
772
+ jsonrpc: '2.0',
773
+ id: reqId,
774
+ result: {
775
+ protocolVersion: '2024-11-05',
776
+ capabilities: { tools: {} },
777
+ serverInfo: { name: 'plumber-mcp', version: '1.0.0' }
778
+ }
779
+ });
780
+ } else if (method === 'notifications/initialized') {
781
+ // Handshake ack
782
+ } else if (method === 'tools/list') {
783
+ sendJson({
784
+ jsonrpc: '2.0',
785
+ id: reqId,
786
+ result: {
787
+ tools: [
788
+ {
789
+ name: 'plumber_scan',
790
+ description: 'Inspect a local repository directory or file for leaks, clogs, and AI slop tells.',
791
+ inputSchema: {
792
+ type: 'object',
793
+ properties: { target: { type: 'string', description: 'Directory or file path to scan (defaults to current directory ".")' } }
794
+ }
795
+ },
796
+ {
797
+ name: 'plumber_list_rules',
798
+ description: 'List all active Plumber inspection rules and recommended fixes.',
799
+ inputSchema: { type: 'object', properties: {} }
800
+ }
801
+ ]
802
+ }
803
+ });
804
+ } else if (method === 'tools/call') {
805
+ const toolName = params.name;
806
+ const toolArgs = params.arguments || {};
807
+ let text = '';
808
+
809
+ if (toolName === 'plumber_list_rules') {
810
+ text = JSON.stringify(RULES, null, 2);
811
+ } else if (toolName === 'plumber_scan') {
812
+ const rep = scanLocalDirectory(path.resolve(toolArgs.target || '.'));
813
+ text = `Plumber Health Report for ${rep.repo_name}:\nScore: ${rep.score}/100 (Grade ${rep.grade})\nFiles: ${rep.total_files} | Issues: ${rep.issues.length}\n` +
814
+ rep.issues.map((i) => `- [${i.severity}] ${i.title} (${i.fix})`).join('\n');
815
+ } else {
816
+ text = `Unknown tool: ${toolName}`;
817
+ }
818
+
819
+ sendJson({
820
+ jsonrpc: '2.0',
821
+ id: reqId,
822
+ result: { content: [{ type: 'text', text }] }
823
+ });
824
+ }
825
+ });
826
+
827
+ function sendJson(obj) {
828
+ process.stdout.write(JSON.stringify(obj) + '\n');
829
+ }
830
+ }