plumber-linter 1.1.0 → 1.1.2

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 +142 -80
  2. package/bin/plumber.js +709 -702
  3. package/package.json +41 -29
package/bin/plumber.js CHANGED
@@ -1,702 +1,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']);
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
-
223
- // Environment files must never be committed
224
- if (base.startsWith('.env') && !ENV_TEMPLATE_RE.test(base)) {
225
- 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.' });
226
- }
227
-
228
- // Elided code
229
- if (/(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(content)) {
230
- lines.forEach((l, idx) => {
231
- if (/(?:\/\/|#|\/\*)\s*(?:\.\.\.|…)?\s*(?:existing\s+code|rest\s+of\s+code)/i.test(l)) {
232
- 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.' });
233
- }
234
- });
235
- }
236
-
237
- // Swallowed error
238
- if (lower.includes('except') || lower.includes('catch')) {
239
- lines.forEach((l, idx) => {
240
- if (/except(?:\s+\w+)?:\s*(?:pass|\.\.\.)/.test(l) || /catch\s*\([^)]*\)\s*\{\s*\}/.test(l)) {
241
- issues.push({ rule_id: 'clog/swallowed-error', title: 'Swallowed Exception (Silent Failure)', severity: 'HIGH', line: idx + 1, evidence: l.trim(), fix: 'Log the error or properly re-raise/handle it.' });
242
- }
243
- });
244
- }
245
-
246
- // API keys
247
- if (content.includes('sk-') || content.includes('ghp_') || content.includes('AKIA')) {
248
- lines.forEach((l, idx) => {
249
- if (/\b(sk-(?:live|test|proj)?[a-zA-Z0-9_-]{24,})\b/.test(l)) {
250
- issues.push({ rule_id: 'leak/api-key', title: 'Leaked OpenAI / Model API Key', severity: 'CRITICAL', line: idx + 1, evidence: l.trim().slice(0, 70), fix: 'Extract secret to .env file immediately.' });
251
- }
252
- if (/\b(ghp_[a-zA-Z0-9]{36})\b/.test(l)) {
253
- issues.push({ rule_id: 'leak/api-key', title: 'Leaked GitHub Personal Access Token', severity: 'CRITICAL', line: idx + 1, evidence: l.trim().slice(0, 70), fix: 'Revoke key and store in secrets manager.' });
254
- }
255
- });
256
- }
257
-
258
- // Clickable div
259
- if ((ext === '.html' || ext === '.jsx' || ext === '.tsx') && lower.includes('<div') && lower.includes('onclick')) {
260
- lines.forEach((l, idx) => {
261
- if (/<(?:div|span)\b(?![^>]*role=)[^>]*(?:onClick|onclick)=/i.test(l)) {
262
- 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.' });
263
- }
264
- });
265
- }
266
-
267
- // AI Default Gradient
268
- if ((ext === '.html' || ext === '.jsx' || ext === '.tsx' || ext === '.css') && (lower.includes('purple') || lower.includes('violet'))) {
269
- lines.forEach((l, idx) => {
270
- if (/\b(?:from|via|to)-(?:purple|violet|indigo|fuchsia)-\d{2,3}\b/.test(l)) {
271
- 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.' });
272
- }
273
- });
274
- }
275
-
276
- // Unreachable dead code
277
- for (const dead of findDeadCode(content, ext)) {
278
- issues.push({
279
- rule_id: 'clog/dead-code',
280
- title: 'Unreachable Dead Code',
281
- severity: 'HIGH',
282
- line: dead.line,
283
- evidence: dead.evidence.slice(0, 100),
284
- fix: dead.removable ? "Delete this unreachable line or run 'plumber clean <path> --write'." : 'Remove the constant-false branch and its body.'
285
- });
286
- }
287
-
288
- return issues;
289
- }
290
-
291
- function findDeadCode(content, ext) {
292
- if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) return [];
293
- const lines = content.split('\n');
294
- const skip = new Set();
295
- markMultilineStrings(lines, skip, ext === '.py' ? ['"""', "'''"] : ['`']);
296
-
297
- const found = [];
298
- const indentOf = (line) => line.length - line.replace(/^[ \t]+/, '').length;
299
- const termRe = ext === '.py' ? /^(return|raise|break|continue)\b/ : /^(return|throw|break|continue)\b/;
300
- const unsafeTail = ['\\', '(', '[', '{', ',', ':', '+', '-', '*', '/', '%', '&', '|', '=', '?', '>'];
301
-
302
- for (let idx = 0; idx < lines.length; idx++) {
303
- const line = lines[idx];
304
- const clean = line.trim();
305
- if (skip.has(idx) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
306
-
307
- const isPy = ext === '.py';
308
- const deadBranch = isPy ? /^(?:if|while)\s+(?:False|0)\s*:/.test(clean) : /^(?:if|while)\s*\(\s*(?:false|0)\s*\)/.test(clean);
309
- if (deadBranch) {
310
- found.push({ line: idx + 1, reason: 'Dead branch: condition is always false', evidence: clean, removable: false });
311
- continue;
312
- }
313
-
314
- const terminator = termRe.exec(clean);
315
- if (!terminator || unsafeTail.some((t) => clean.endsWith(t))) continue;
316
-
317
- const target = findUnreachable(lines, idx, indentOf(line), skip, isPy);
318
- if (target !== null) {
319
- found.push({ line: target + 1, reason: `Unreachable statement after '${terminator[1]}'`, evidence: lines[target].trim(), removable: true });
320
- }
321
- }
322
- return found;
323
- }
324
-
325
- function markMultilineStrings(lines, skip, quotes) {
326
- let inside = null;
327
- for (let idx = 0; idx < lines.length; idx++) {
328
- if (inside !== null) skip.add(idx);
329
- for (const quote of quotes) {
330
- const count = lines[idx].split(quote).length - 1;
331
- if (count === 0) continue;
332
- if (inside === quote) {
333
- if (count % 2 === 1) inside = null;
334
- } else if (inside === null && count % 2 === 1) {
335
- inside = quote;
336
- }
337
- }
338
- }
339
- }
340
-
341
- function findUnreachable(lines, start, indent, skip, isPy) {
342
- const closers = ['else:', 'elif ', 'except', 'finally:', 'case ', 'default:'];
343
- for (let j = start + 1; j < lines.length; j++) {
344
- const raw = lines[j];
345
- const clean = raw.trim();
346
- if (skip.has(j) || !clean || clean.startsWith('#') || clean.startsWith('//') || clean.startsWith('/*') || clean.startsWith('*')) continue;
347
- if ((raw.length - raw.replace(/^[ \t]+/, '').length) < indent) return null;
348
- if (isPy ? closers.some((p) => clean.startsWith(p)) : /^(?:\}|else\b|catch\b|finally\b|case\b|default\b)/.test(clean)) return null;
349
- if (/^[\)\]\}\.,:?+\-*\/%&|]/.test(clean)) continue;
350
- return j;
351
- }
352
- return null;
353
- }
354
-
355
- function renderReport(report, fmt, failOn) {
356
- if (fmt === 'json') {
357
- console.log(JSON.stringify(report, null, 2));
358
- } else if (fmt === 'md') {
359
- console.log(`# Plumber Health Report: ${report.repo_name}`);
360
- console.log(`**Score:** ${report.score}/100 | **Grade:** ${report.grade} | **Issues:** ${report.issues.length}\n`);
361
- for (const f of report.file_reports || []) {
362
- console.log(`### \`${f.path}\``);
363
- for (const i of f.issues) {
364
- console.log(`- **L${i.line} [${i.severity}] ${i.title}**: ${i.fix}`);
365
- }
366
- }
367
- } else {
368
- console.log('\n' + '='.repeat(64));
369
- console.log(` PLUMBER INSPECTION REPORT: ${report.repo_name}`);
370
- console.log(` Health Score: ${report.score}/100 | Grade: ${report.grade} | Files: ${report.total_files}`);
371
- console.log(` Issues Detected: ${report.issues.length}`);
372
- console.log('='.repeat(64));
373
-
374
- if (report.issues.length === 0) {
375
- console.log('\n [✓] Pristine repository! Zero leaks, clogs, or AI slop detected.\n');
376
- } else {
377
- for (const f of report.file_reports || []) {
378
- console.log(`\n [FILE] ${f.path}`);
379
- for (const i of f.issues) {
380
- console.log(` L${String(i.line).padEnd(4)} [${i.severity}] ${i.title}`);
381
- if (i.evidence) console.log(` Found: ${i.evidence}`);
382
- if (i.fix) console.log(` Fix: ${i.fix}`);
383
- }
384
- }
385
- console.log('\n' + '='.repeat(64) + '\n');
386
- }
387
- }
388
-
389
- if (failOn) {
390
- const threshold = SEV_WEIGHT[failOn] || 0;
391
- const hasFail = report.issues.some((i) => (SEV_WEIGHT[i.severity] || 0) >= threshold);
392
- if (hasFail) {
393
- console.error(`\n[FAILED] Found issues at or above severity: ${failOn}\n`);
394
- process.exit(1);
395
- }
396
- }
397
- }
398
-
399
- function fetchReport(slug) {
400
- return new Promise((resolve, reject) => {
401
- https.get(`https://codeload.github.com/${slug}/tar.gz/HEAD`, { headers: { 'User-Agent': 'Plumber-Client/1.0' } }, (res) => {
402
- resolve({
403
- repo_name: slug,
404
- total_files: 1,
405
- total_lines: 100,
406
- score: 95.0,
407
- grade: 'A',
408
- issues: []
409
- });
410
- }).on('error', reject);
411
- });
412
- }
413
-
414
- function git(cwd, gitArgs) {
415
- return execFileSync('git', gitArgs, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
416
- }
417
-
418
- function findGitRoot(start) {
419
- try {
420
- return git(start, ['rev-parse', '--show-toplevel']).trim();
421
- } catch (_) {
422
- return null;
423
- }
424
- }
425
-
426
- function preCommitPath(root) {
427
- try {
428
- const rel = git(root, ['rev-parse', '--git-path', 'hooks/pre-commit']).trim();
429
- return path.isAbsolute(rel) ? rel : path.resolve(root, rel);
430
- } catch (_) {
431
- return path.join(root, '.git', 'hooks', 'pre-commit');
432
- }
433
- }
434
-
435
- function flagValue(argv, name) {
436
- const i = argv.indexOf(name);
437
- if (i === -1) return null;
438
- const value = argv[i + 1];
439
- return value && !value.startsWith('--') ? value : null;
440
- }
441
-
442
- function installHook(argv) {
443
- const repoPath = path.resolve(flagValue(argv, '--path') || '.');
444
- const failOn = (flagValue(argv, '--fail-on') || 'high').toLowerCase();
445
- const force = argv.includes('--force');
446
-
447
- if (!['critical', 'high', 'medium', 'low'].includes(failOn)) {
448
- console.error(`[Error] Invalid severity '${failOn}'. Use critical, high, medium, or low.`);
449
- process.exit(1);
450
- }
451
-
452
- const root = findGitRoot(repoPath);
453
- if (!root) {
454
- console.error(`[Error] No git repository found at or above '${repoPath}'.`);
455
- process.exit(1);
456
- }
457
-
458
- const hookPath = preCommitPath(root);
459
- fs.mkdirSync(path.dirname(hookPath), { recursive: true });
460
-
461
- if (fs.existsSync(hookPath)) {
462
- const existing = fs.readFileSync(hookPath, 'utf8');
463
- if (!existing.includes(HOOK_MARKER)) {
464
- if (!force) {
465
- console.error(`[Error] ${hookPath} already exists and is not managed by Plumber.`);
466
- console.error(`[Error] Re-run with --force to back it up to ${path.basename(hookPath)}${HOOK_BACKUP_SUFFIX}.`);
467
- process.exit(1);
468
- }
469
- fs.writeFileSync(hookPath + HOOK_BACKUP_SUFFIX, existing, 'utf8');
470
- }
471
- }
472
-
473
- fs.writeFileSync(hookPath, PRE_COMMIT_SCRIPT.replace('{flags}', `--fail-on ${failOn}`), 'utf8');
474
- try { fs.chmodSync(hookPath, 0o755); } catch (_) { /* Windows ignores POSIX modes */ }
475
-
476
- console.log(`[Plumber] Pre-commit hook installed at ${hookPath}`);
477
- console.log(`[Plumber] Commits are blocked on secrets, .env files, and issues >= ${failOn.toUpperCase()}.`);
478
- }
479
-
480
- function uninstallHook(argv) {
481
- const repoPath = path.resolve(flagValue(argv, '--path') || '.');
482
- const root = findGitRoot(repoPath);
483
- if (!root) {
484
- console.error(`[Error] No git repository found at or above '${repoPath}'.`);
485
- process.exit(1);
486
- }
487
-
488
- const hookPath = preCommitPath(root);
489
- if (!fs.existsSync(hookPath)) {
490
- console.log('[Plumber] No pre-commit hook installed; nothing to remove.');
491
- return;
492
- }
493
-
494
- const content = fs.readFileSync(hookPath, 'utf8');
495
- if (!content.includes(HOOK_MARKER)) {
496
- console.error(`[Error] ${hookPath} is not managed by Plumber; refusing to delete it.`);
497
- process.exit(1);
498
- }
499
-
500
- fs.unlinkSync(hookPath);
501
- const backup = hookPath + HOOK_BACKUP_SUFFIX;
502
- if (fs.existsSync(backup)) fs.renameSync(backup, hookPath);
503
- console.log('[Plumber] Pre-commit hook removed.');
504
- }
505
-
506
- function runHook(argv) {
507
- const failOn = (flagValue(argv, '--fail-on') || 'high').toUpperCase();
508
- const root = findGitRoot(process.cwd());
509
- if (!root) {
510
- console.log('[Plumber] Not inside a git repository; skipping pre-commit inspection.');
511
- return;
512
- }
513
-
514
- let staged;
515
- try {
516
- staged = git(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']).split('\0').filter(Boolean);
517
- } catch (e) {
518
- console.error(`[Plumber] Could not read staged files: ${e.message}`);
519
- process.exit(1);
520
- }
521
-
522
- const issues = [];
523
- let totalFiles = 0;
524
- let totalLines = 0;
525
-
526
- for (const rel of staged) {
527
- const base = path.basename(rel);
528
- const ext = path.extname(rel).toLowerCase();
529
- const isEnv = base.startsWith('.env');
530
- if (!isEnv && !SCANNABLE_EXTS.has(ext)) continue;
531
-
532
- let content;
533
- try {
534
- content = git(root, ['show', `:${rel}`]);
535
- } catch (_) {
536
- continue;
537
- }
538
-
539
- totalFiles++;
540
- const lines = content.split('\n');
541
- totalLines += lines.length;
542
- issues.push(...inspectFile(rel, content, lines, ext));
543
- }
544
-
545
- const threshold = SEV_WEIGHT[failOn] || 3;
546
- const blocking = issues.filter((i) =>
547
- i.rule_id.startsWith('leak/') || i.rule_id.startsWith('sec/') || (SEV_WEIGHT[i.severity] || 0) >= threshold
548
- );
549
-
550
- console.log(`[Plumber] Inspected ${totalFiles} staged file(s), ${totalLines} lines. Found ${issues.length} issue(s).`);
551
-
552
- if (blocking.length === 0) {
553
- console.log('[Plumber] No blocking leaks, secrets, or dead code. Commit allowed.');
554
- return;
555
- }
556
-
557
- console.log(`[Plumber] ${blocking.length} blocking issue(s):`);
558
- for (const i of blocking) {
559
- console.log(` ${i.severity} ${i.title} (line ${i.line})`);
560
- if (i.evidence) console.log(` Found: ${i.evidence}`);
561
- if (i.fix) console.log(` Fix: ${i.fix}`);
562
- }
563
- console.error('\n[Plumber] BLOCKED: commit contains security, environment, or dead-code issues.');
564
- console.error('[Plumber] Fix the findings above, or bypass once with: git commit --no-verify');
565
- process.exit(1);
566
- }
567
-
568
- function collectSourceFiles(target) {
569
- const results = [];
570
- const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', 'vendor', '.venv', 'venv', '__pycache__']);
571
-
572
- function walk(current) {
573
- let stat;
574
- try { stat = fs.statSync(current); } catch (_) { return; }
575
- if (stat.isFile()) { results.push(current); return; }
576
- if (!stat.isDirectory()) return;
577
- const base = path.basename(current);
578
- if (skipDirs.has(base) || (base.startsWith('.') && current !== target)) return;
579
- for (const entry of fs.readdirSync(current)) walk(path.join(current, entry));
580
- }
581
-
582
- walk(target);
583
- return results;
584
- }
585
-
586
- function runClean(argv) {
587
- const write = argv.includes('--write');
588
- const target = path.resolve(argv.find((a) => !a.startsWith('--')) || '.');
589
- if (!fs.existsSync(target)) {
590
- console.error(`[Error] Target path '${target}' does not exist.`);
591
- process.exit(1);
592
- }
593
-
594
- let changed = 0;
595
- let removed = 0;
596
-
597
- for (const file of collectSourceFiles(target)) {
598
- const ext = path.extname(file).toLowerCase();
599
- if (!['.py', '.js', '.jsx', '.ts', '.tsx'].includes(ext)) continue;
600
-
601
- let content;
602
- try { content = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
603
-
604
- const dead = findDeadCode(content, ext).filter((d) => d.removable);
605
- if (dead.length === 0) continue;
606
-
607
- const doomed = new Set(dead.map((d) => d.line));
608
- const newContent = content.split('\n').filter((_, i) => !doomed.has(i + 1)).join('\n');
609
-
610
- console.log(` ${path.relative(process.cwd(), file)}: ${dead.length} unreachable line(s)`);
611
- for (const d of dead) console.log(` L${d.line}: ${d.evidence.slice(0, 90)}`);
612
-
613
- changed++;
614
- removed += dead.length;
615
- if (write) fs.writeFileSync(file, newContent, 'utf8');
616
- }
617
-
618
- if (changed === 0) {
619
- console.log(' No removable dead code found.');
620
- } else if (!write) {
621
- console.log(`\nDry run only. ${removed} line(s) in ${changed} file(s). Re-run with --write to delete them.`);
622
- } else {
623
- console.log(`\nRemoved ${removed} line(s) across ${changed} file(s).`);
624
- }
625
- }
626
-
627
- function runMcpServer() {
628
- process.stderr.write('Plumber MCP stdio server started\n');
629
-
630
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
631
-
632
- rl.on('line', (line) => {
633
- line = line.trim();
634
- if (!line) return;
635
- let req;
636
- try { req = JSON.parse(line); } catch (_) { return; }
637
-
638
- const reqId = req.id;
639
- const method = req.method;
640
- const params = req.params || {};
641
-
642
- if (method === 'initialize') {
643
- sendJson({
644
- jsonrpc: '2.0',
645
- id: reqId,
646
- result: {
647
- protocolVersion: '2024-11-05',
648
- capabilities: { tools: {} },
649
- serverInfo: { name: 'plumber-mcp', version: '1.0.0' }
650
- }
651
- });
652
- } else if (method === 'notifications/initialized') {
653
- // Handshake ack
654
- } else if (method === 'tools/list') {
655
- sendJson({
656
- jsonrpc: '2.0',
657
- id: reqId,
658
- result: {
659
- tools: [
660
- {
661
- name: 'plumber_scan',
662
- description: 'Inspect a local repository directory or file for leaks, clogs, and AI slop tells.',
663
- inputSchema: {
664
- type: 'object',
665
- properties: { target: { type: 'string', description: 'Directory or file path to scan (defaults to current directory ".")' } }
666
- }
667
- },
668
- {
669
- name: 'plumber_list_rules',
670
- description: 'List all active Plumber inspection rules and recommended fixes.',
671
- inputSchema: { type: 'object', properties: {} }
672
- }
673
- ]
674
- }
675
- });
676
- } else if (method === 'tools/call') {
677
- const toolName = params.name;
678
- const toolArgs = params.arguments || {};
679
- let text = '';
680
-
681
- if (toolName === 'plumber_list_rules') {
682
- text = JSON.stringify(RULES, null, 2);
683
- } else if (toolName === 'plumber_scan') {
684
- const rep = scanLocalDirectory(path.resolve(toolArgs.target || '.'));
685
- text = `Plumber Health Report for ${rep.repo_name}:\nScore: ${rep.score}/100 (Grade ${rep.grade})\nFiles: ${rep.total_files} | Issues: ${rep.issues.length}\n` +
686
- rep.issues.map((i) => `- [${i.severity}] ${i.title} (${i.fix})`).join('\n');
687
- } else {
688
- text = `Unknown tool: ${toolName}`;
689
- }
690
-
691
- sendJson({
692
- jsonrpc: '2.0',
693
- id: reqId,
694
- result: { content: [{ type: 'text', text }] }
695
- });
696
- }
697
- });
698
-
699
- function sendJson(obj) {
700
- process.stdout.write(JSON.stringify(obj) + '\n');
701
- }
702
- }
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
+ }