@yagyeshvyas/vibeguard 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +18 -2
  3. package/bin/cli.js +2753 -2753
  4. package/ci/vibeguard.yml +42 -42
  5. package/package.json +1 -1
  6. package/scripts/counts.js +93 -93
  7. package/scripts/postinstall.js +26 -26
  8. package/src/auto.js +427 -427
  9. package/src/daemon.js +343 -343
  10. package/src/dashboard.js +278 -278
  11. package/src/engine.js +297 -297
  12. package/src/hook.js +151 -151
  13. package/src/install.js +298 -298
  14. package/src/integrity.json +1 -1
  15. package/src/plugin.js +182 -182
  16. package/src/privacy-audit.js +272 -272
  17. package/src/repl.js +150 -150
  18. package/src/report.js +331 -331
  19. package/src/rules-pack.js +3068 -3068
  20. package/src/rules.js +1822 -1822
  21. package/src/sbom.js +193 -193
  22. package/src/scanner.js +1032 -1032
  23. package/src/shell-guard.js +302 -302
  24. package/src/slopsquat.js +144 -144
  25. package/src/trace.js +220 -220
  26. package/src/.vibeguard/cache/file-hashes.json +0 -60
  27. package/src/.vibeguard/latest-snapshot.json +0 -36
  28. package/src/.vibeguard/mcp-pins.json +0 -1
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +0 -428
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +0 -344
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +0 -279
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +0 -297
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +0 -151
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +0 -299
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +0 -65
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +0 -2051
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +0 -168
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +0 -362
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +0 -150
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +0 -1611
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +0 -164
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +0 -292
  43. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +0 -144
  44. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +0 -220
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +0 -428
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +0 -344
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +0 -297
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +0 -299
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +0 -37
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +0 -2055
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +0 -168
  52. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +0 -362
  53. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +0 -220
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +0 -428
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +0 -344
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +0 -279
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +0 -297
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +0 -151
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +0 -299
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +0 -65
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +0 -2055
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +0 -168
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +0 -362
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +0 -150
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +0 -1611
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +0 -164
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +0 -292
  68. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +0 -144
  69. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +0 -220
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +0 -428
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +0 -344
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +0 -279
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +0 -297
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +0 -151
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +0 -299
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +0 -65
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +0 -2054
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +0 -168
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +0 -362
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +0 -150
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +0 -1611
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +0 -164
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +0 -292
  84. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +0 -144
  85. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +0 -220
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +0 -428
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +0 -344
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +0 -297
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +0 -299
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +0 -37
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +0 -2055
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +0 -168
  93. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +0 -362
  94. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +0 -220
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +0 -428
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +0 -344
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +0 -297
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +0 -33
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +0 -2055
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +0 -1611
  101. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +0 -292
  102. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +0 -220
  103. package/src/.vibeguard-baseline.json +0 -5226
@@ -1,220 +0,0 @@
1
- 'use strict';
2
-
3
- /*
4
- * Prompt tracing — link findings back to the AI prompt that generated them.
5
- *
6
- * Reads Cursor (.cursor/), Claude Code, and Windsurf session history files.
7
- * Scans for security-relevant behavior patterns in AI agent transcripts.
8
- *
9
- * Two capabilities:
10
- * 1. Trace a finding back to the AI prompt that likely generated the code
11
- * 2. Behavior analysis: detect blind approvals, high delegation, risky patterns
12
- */
13
-
14
- const fs = require('fs');
15
- const path = require('path');
16
-
17
- const SESSION_DIRS = [
18
- '.cursor',
19
- '.cursor/projects',
20
- '.windsurf',
21
- '.claude',
22
- '.continue',
23
- ];
24
-
25
- function findSessionFiles(root) {
26
- const files = [];
27
- for (const dir of SESSION_DIRS) {
28
- const absDir = path.join(root, dir);
29
- if (!fs.existsSync(absDir)) continue;
30
- try {
31
- walkAndCollect(absDir, files, /\.(?:json|jsonl|md|txt)$/i);
32
- } catch (err) { console.error(err); }
33
- }
34
- return files;
35
- }
36
-
37
- function walkAndCollect(dir, out, extRe) {
38
- let entries;
39
- try {
40
- entries = fs.readdirSync(dir, { withFileTypes: true });
41
- } catch { return; }
42
- for (const e of entries) {
43
- const full = path.join(dir, e.name);
44
- if (e.isDirectory()) walkAndCollect(full, out, extRe);
45
- else if (e.isFile() && extRe.test(e.name)) out.push(full);
46
- }
47
- }
48
-
49
- function parseSession(filepath) {
50
- const content = fs.readFileSync(filepath, 'utf8');
51
- const messages = [];
52
-
53
- // Try JSONL format (one JSON object per line)
54
- if (filepath.endsWith('.jsonl')) {
55
- for (const line of content.split('\n')) {
56
- try {
57
- const obj = JSON.parse(line);
58
- if (obj.role || obj.type || obj.message) messages.push(obj);
59
- } catch {}
60
- }
61
- }
62
-
63
- // Try JSON array
64
- if (messages.length === 0 && filepath.endsWith('.json')) {
65
- try {
66
- const arr = JSON.parse(content);
67
- if (Array.isArray(arr)) messages.push(...arr);
68
- else messages.push(arr);
69
- } catch {}
70
- }
71
-
72
- // Try markdown/text (split by user/assistant markers)
73
- if (messages.length === 0) {
74
- const parts = content.split(/^(?:User|Human|Assistant|AI|>>>)[:\s]/m);
75
- parts.forEach((p, i) => {
76
- if (p.trim()) messages.push({ role: i % 2 === 0 ? 'user' : 'assistant', content: p.trim() });
77
- });
78
- }
79
-
80
- return { file: filepath, messages };
81
- }
82
-
83
- const RISKY_BEHAVIORS = [
84
- {
85
- id: 'behavior.blind-approval',
86
- re: /(?:yes|ok|sure|go ahead|do it|approve|sounds good|perfect|great)\s*[!.?\s]*$/i,
87
- risk: 'medium',
88
- desc: 'Blind approval of AI suggestion without review',
89
- },
90
- {
91
- id: 'behavior.high-delegation',
92
- re: /(?:do\s+(?:all|everything|the\s+whole)|build\s+(?:the\s+entire|all)|write\s+(?:all|every|the\s+complete)|implement\s+(?:all|everything|the\s+entire))/i,
93
- risk: 'medium',
94
- desc: 'High delegation — asking AI to do everything at once reduces review quality',
95
- },
96
- {
97
- id: 'behavior.skip-tests',
98
- re: /(?:skip|don'?t\s+need|no\s+need\s+for)\s+(?:tests?|testing|validation)/i,
99
- risk: 'high',
100
- desc: 'Requesting code without tests',
101
- },
102
- {
103
- id: 'behavior.skip-auth',
104
- re: /(?:skip|don'?t\s+(?:need|worry\s+about)|no\s+need\s+for)\s+(?:auth|authentication|authorization|security)/i,
105
- risk: 'high',
106
- desc: 'Explicitly requesting to skip authentication/security',
107
- },
108
- {
109
- id: 'behavior.hardcode-secrets',
110
- re: /(?:just\s+)?(?:hardcode|hard-code|put\s+(?:the\s+)?(?:password|secret|token|key|api\s+key)\s+(?:directly\s+)?(?:in|here))/i,
111
- risk: 'high',
112
- desc: 'Asking AI to hardcode secrets',
113
- },
114
- {
115
- id: 'behavior.disable-security',
116
- re: /(?:disable|turn\s+off|remove|skip|bypass)\s+(?:security|validation|sanitization|escaping|CORS|helmet|CSRF)/i,
117
- risk: 'high',
118
- desc: 'Asking AI to disable security features',
119
- },
120
- {
121
- id: 'behavior.trust-input',
122
- re: /(?:trust\s+the\s+(?:user|client|input)|user\s+input\s+is\s+(?:safe|trusted|fine)|don'?t\s+validate)/i,
123
- risk: 'high',
124
- desc: 'Expressing trust in user/client input without validation',
125
- },
126
- {
127
- id: 'behavior.excessive-iter',
128
- re: /(?:again|redo|try\s+again|different\s+approach|start\s+over)/i,
129
- risk: 'low',
130
- desc: 'Excessive iteration on AI output — possible degradation of review quality',
131
- threshold: 10,
132
- },
133
- ];
134
-
135
- function analyzeBehavior(messages) {
136
- const behaviors = [];
137
- let userMessages = 0;
138
- let approvals = 0;
139
- let iterations = 0;
140
-
141
- for (const msg of messages) {
142
- const role = msg.role || msg.type || '';
143
- const content = msg.content || msg.message || msg.text || '';
144
- if (typeof content !== 'string') continue;
145
- if (!/user|human/i.test(role)) continue;
146
- userMessages++;
147
-
148
- for (const b of RISKY_BEHAVIORS) {
149
- if (b.re.test(content)) {
150
- if (b.id === 'behavior.blind-approval') approvals++;
151
- if (b.id === 'behavior.excessive-iter') iterations++;
152
- if (b.id === 'behavior.excessive-iter' && iterations < (b.threshold || 10)) continue;
153
- behaviors.push({
154
- id: b.id,
155
- risk: b.risk,
156
- message: b.desc,
157
- snippet: content.slice(0, 200),
158
- });
159
- }
160
- }
161
- }
162
-
163
- const delegationRatio = userMessages > 0 ? approvals / userMessages : 0;
164
- const risk = delegationRatio > 0.6 ? 'high' : delegationRatio > 0.3 ? 'medium' : 'low';
165
-
166
- return {
167
- totalUserMessages: userMessages,
168
- approvals,
169
- iterations,
170
- delegationRatio: Math.round(delegationRatio * 100) / 100,
171
- risk,
172
- behaviors,
173
- recommendation:
174
- risk === 'high'
175
- ? 'High blind-approval ratio — review AI suggestions more carefully before accepting'
176
- : risk === 'medium'
177
- ? 'Moderate delegation — ensure each AI suggestion is reviewed'
178
- : 'Good review discipline — keep validating AI output',
179
- };
180
- }
181
-
182
- function traceFindingsToPrompts(findings, sessions) {
183
- const traces = [];
184
- for (const f of findings) {
185
- const matching = [];
186
- for (const session of sessions) {
187
- for (const msg of session.messages) {
188
- const content = msg.content || msg.message || '';
189
- if (typeof content !== 'string') continue;
190
- const snippet = f.snippet || '';
191
- if (snippet && content.includes(snippet.slice(0, 30))) {
192
- matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
193
- }
194
- const titleWords = (f.title || '').split(/\s+/).filter((w) => w.length > 4);
195
- if (titleWords.length > 0 && titleWords.every((w) => content.toLowerCase().includes(w.toLowerCase()))) {
196
- matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
197
- }
198
- }
199
- }
200
- if (matching.length > 0) {
201
- traces.push({ finding: f.ruleId, file: f.file, line: f.line, matches: matching });
202
- }
203
- }
204
- return traces;
205
- }
206
-
207
- function trace(root, findings) {
208
- const sessionFiles = findSessionFiles(root);
209
- if (sessionFiles.length === 0) {
210
- return { sessions: 0, behavior: null, traces: [] };
211
- }
212
-
213
- const sessions = sessionFiles.map(parseSession);
214
- const behavior = analyzeBehavior(sessions.flatMap((s) => s.messages));
215
- const traces = traceFindingsToPrompts(findings, sessions);
216
-
217
- return { sessions: sessions.length, behavior, traces };
218
- }
219
-
220
- module.exports = { trace, analyzeBehavior, findSessionFiles, parseSession, RISKY_BEHAVIORS };
@@ -1,428 +0,0 @@
1
- 'use strict';
2
-
3
- /*
4
- * src/auto.js — One-command autonomous protection orchestrator.
5
- *
6
- * `vibeguard auto` → scan + daemon + hooks + shell guard (idempotent)
7
- * `vibeguard auto --stop` → reverse everything, restore backups
8
- * `vibeguard auto --status` → show what's active
9
- *
10
- * Composes existing modules: scanner, daemon, hook, shell-guard.
11
- * All state under .vibeguard/auto.json.
12
- */
13
-
14
- const fs = require('fs');
15
- const path = require('path');
16
- const os = require('os');
17
- const { spawn, execSync } = require('child_process');
18
-
19
- const STATE_DIR = '.vibeguard';
20
- const STATE_FILE = path.join(STATE_DIR, 'auto.json');
21
- const REPORT_FILE = path.join(STATE_DIR, 'report.json');
22
- const SARIF_FILE = path.join(STATE_DIR, 'report.sarif');
23
- const EVENTS_LOG = path.join(STATE_DIR, 'events.log');
24
- const BACKUP_DIR = path.join(STATE_DIR, 'backups');
25
-
26
- // ─── Helpers ──────────────────────────────────────────────────────────────
27
-
28
- function findProjectRoot(startDir) {
29
- let dir = path.resolve(startDir);
30
- for (let i = 0; i < 20; i++) {
31
- if (fs.existsSync(path.join(dir, 'package.json')) || fs.existsSync(path.join(dir, '.git'))) {
32
- return dir;
33
- }
34
- const parent = path.dirname(dir);
35
- if (parent === dir) break;
36
- dir = parent;
37
- }
38
- return null;
39
- }
40
-
41
- function ensureStateDir(root) {
42
- const dir = path.join(root, STATE_DIR);
43
- fs.mkdirSync(dir, { recursive: true });
44
- fs.mkdirSync(path.join(root, BACKUP_DIR), { recursive: true });
45
- return dir;
46
- }
47
-
48
- function readState(root) {
49
- const p = path.join(root, STATE_FILE);
50
- if (!fs.existsSync(p)) return null;
51
- try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; }
52
- }
53
-
54
- function writeState(root, state) {
55
- ensureStateDir(root);
56
- fs.writeFileSync(path.join(root, STATE_FILE), JSON.stringify(state, null, 2));
57
- }
58
-
59
- function removeState(root) {
60
- try { fs.unlinkSync(path.join(root, STATE_FILE)); } catch (err) { console.error(err); }
61
- }
62
-
63
- function logEvent(root, msg) {
64
- const logPath = path.join(root, EVENTS_LOG);
65
- const ts = new Date().toISOString();
66
- fs.appendFileSync(logPath, `[${ts}] ${msg}\n`);
67
- }
68
-
69
- function backupFile(src, dst) {
70
- if (fs.existsSync(src)) {
71
- fs.copyFileSync(src, dst);
72
- return true;
73
- }
74
- return false;
75
- }
76
-
77
- function restoreFile(dst, src) {
78
- if (fs.existsSync(src)) {
79
- fs.copyFileSync(src, dst);
80
- return true;
81
- }
82
- return false;
83
- }
84
-
85
- function isProcessAlive(pid) {
86
- try { process.kill(pid, 0); return true; } catch { return false; }
87
- }
88
-
89
- // ─── Auto Start ────────────────────────────────────────────────────────────
90
-
91
- function autoStart(rootDir, opts) {
92
- opts = opts || {};
93
- const root = findProjectRoot(rootDir);
94
- if (!root) {
95
- return { ok: false, reason: 'No project root found (no package.json or .git). Run from a project directory.' };
96
- }
97
-
98
- // Idempotent: if already running, report status
99
- const existing = readState(root);
100
- if (existing && existing.pid && isProcessAlive(existing.pid)) {
101
- return { ok: true, alreadyRunning: true, state: existing };
102
- }
103
-
104
- ensureStateDir(root);
105
- const state = {
106
- pid: process.pid,
107
- root,
108
- startedAt: new Date().toISOString(),
109
- features: {},
110
- backups: {},
111
- lastScan: null,
112
- findingsSinceStart: 0,
113
- };
114
-
115
- const steps = [];
116
-
117
- // 1. Initial full scan (always run — CI mode needs it too)
118
- const { scan } = require('./scanner');
119
- const result = scan(root, { deps: true, deep: !!opts.deep });
120
- state.lastScan = new Date().toISOString();
121
- state.findingsSinceStart = result.findings.length;
122
-
123
- // Write report + SARIF
124
- ensureStateDir(root);
125
- fs.writeFileSync(path.join(root, REPORT_FILE), JSON.stringify(result, null, 2));
126
- try {
127
- const { renderSarif } = require('./report');
128
- fs.writeFileSync(path.join(root, SARIF_FILE), renderSarif(result));
129
- } catch (err) { console.error(err); }
130
-
131
- steps.push({
132
- step: 'scan',
133
- grade: result.grade,
134
- counts: result.counts,
135
- findings: result.findings.length,
136
- });
137
-
138
- // CI mode: exit non-zero on critical, no daemon
139
- if (opts.ci) {
140
- writeState(root, state);
141
- return { ok: true, ci: true, steps, exitCode: result.counts.critical > 0 ? 1 : 0 };
142
- }
143
-
144
- // --fix: apply safe auto-fixes
145
- if (opts.fix) {
146
- try {
147
- const { computeAutoFixes } = require('./autofix');
148
- const fixes = computeAutoFixes(result.findings, result.root);
149
- if (fixes && fixes.length > 0) {
150
- steps.push({ step: 'fix', fixes: fixes.length, reversible: true });
151
- }
152
- } catch {}
153
- }
154
-
155
- // 2. Start daemon (file watcher)
156
- if (!opts.ci) {
157
- try {
158
- const { startDaemon, isDaemonRunning } = require('./daemon');
159
- if (!isDaemonRunning(root)) {
160
- startDaemon(root, { verbose: opts.verbose }).then((r) => {
161
- if (r.started) {
162
- state.features.daemon = true;
163
- state.daemonPid = r.pid;
164
- logEvent(root, `daemon started (PID ${r.pid})`);
165
- writeState(root, state);
166
- }
167
- }).catch(() => {});
168
- } else {
169
- state.features.daemon = true;
170
- }
171
- steps.push({ step: 'daemon', started: state.features.daemon });
172
- } catch (e) {
173
- steps.push({ step: 'daemon', error: e.message });
174
- }
175
- }
176
-
177
- // 3. Install git pre-commit hook (if .git exists)
178
- const gitDir = path.join(root, '.git');
179
- if (fs.existsSync(gitDir) && !opts.ci) {
180
- const hooksDir = path.join(gitDir, 'hooks');
181
- fs.mkdirSync(hooksDir, { recursive: true });
182
- const preCommit = path.join(hooksDir, 'pre-commit');
183
- const backupPath = path.join(root, BACKUP_DIR, 'pre-commit.bak');
184
-
185
- // Backup existing hook if present
186
- if (fs.existsSync(preCommit)) {
187
- backupFile(preCommit, backupPath);
188
- state.backups.preCommit = backupPath;
189
- }
190
-
191
- // Write the hook
192
- const nodeBin = process.execPath.replace(/\\/g, '/');
193
- const cliPath = path.join(__dirname, '..', 'bin', 'cli.js').replace(/\\/g, '/');
194
- const strictFlag = opts.strict ? ' --strict' : '';
195
- const hook = `#!/usr/bin/env sh\n# VibeGuard pre-commit hook (auto-installed).\nNODE="${nodeBin}"\nCLI="${cliPath}"\nif [ ! -f "$CLI" ]; then exit 0; fi\n"$NODE" "$CLI" scan . --precommit${strictFlag}\nSTATUS=$?\nif [ "$STATUS" -eq 2 ]; then\n echo "VibeGuard: commit blocked — CRITICAL issue(s). Fix or use --no-verify."\n exit 1\nfi\nexit 0\n`;
196
- fs.writeFileSync(preCommit, hook);
197
- try { fs.chmodSync(preCommit, 0o755); } catch {}
198
- state.features.preCommitHook = true;
199
- steps.push({ step: 'pre-commit-hook', installed: true, backedUp: state.backups.preCommit ? true : false });
200
- }
201
-
202
- // 4. Install PostToolUse hook (for AI agent edit scanning)
203
- if (!opts.ci) {
204
- try {
205
- const hookMod = require('./hook');
206
- const r = hookMod.installPostEditHook(root);
207
- state.features.postEditHook = r.installed;
208
- steps.push({ step: 'post-edit-hook', installed: r.installed, file: r.file });
209
- } catch (e) {
210
- steps.push({ step: 'post-edit-hook', error: e.message });
211
- }
212
- }
213
-
214
- // 5. Arm shell guard (install shell hook) — requires consent
215
- if (!opts.noShell && !opts.ci) {
216
- // Skip shell guard in auto unless --yes is passed (consent).
217
- if (!opts.yes) {
218
- steps.push({ step: 'shell-guard', installed: false, reason: 'skipped (use --yes to enable)' });
219
- } else {
220
- try {
221
- const srcDir = path.join(__dirname);
222
- const home = os.homedir();
223
- const marker = '# >>> VibeGuard shell hook >>>';
224
- const endMarker = '# <<< VibeGuard shell hook <<<';
225
- const psMarker = '### >>> VibeGuard shell hook >>>';
226
- const psEndMarker = '### <<< VibeGuard shell hook <<<';
227
- const hookContent = `${marker}\nVG_SCRIPT_DIR="${srcDir.replace(/\\/g, '\\\\')}"\nsource "${path.join(srcDir, 'shell-hook.sh').replace(/\\/g, '\\\\')}"\n${endMarker}`;
228
-
229
- // bash
230
- const bashrc = path.join(home, '.bashrc');
231
- if (fs.existsSync(bashrc) || true) {
232
- let content = fs.existsSync(bashrc) ? fs.readFileSync(bashrc, 'utf8') : '';
233
- if (!content.includes(marker)) {
234
- const backupPath = path.join(root, BACKUP_DIR, 'bashrc.bak');
235
- if (fs.existsSync(bashrc)) backupFile(bashrc, backupPath);
236
- state.backups.bashrc = backupPath;
237
- content = content.trimEnd() + '\n' + hookContent + '\n';
238
- fs.writeFileSync(bashrc, content);
239
- }
240
- }
241
-
242
- // zsh
243
- const zshrc = path.join(home, '.zshrc');
244
- if (fs.existsSync(zshrc)) {
245
- let content = fs.readFileSync(zshrc, 'utf8');
246
- if (!content.includes(marker)) {
247
- const backupPath = path.join(root, BACKUP_DIR, 'zshrc.bak');
248
- backupFile(zshrc, backupPath);
249
- state.backups.zshrc = backupPath;
250
- content = content.trimEnd() + '\n' + hookContent + '\n';
251
- fs.writeFileSync(zshrc, content);
252
- }
253
- }
254
-
255
- // PowerShell (Windows)
256
- if (process.platform === 'win32') {
257
- const psDir = path.join(home, 'Documents', 'WindowsPowerShell');
258
- fs.mkdirSync(psDir, { recursive: true });
259
- const psProfile = path.join(psDir, 'Microsoft.PowerShell_profile.ps1');
260
- let content = fs.existsSync(psProfile) ? fs.readFileSync(psProfile, 'utf8') : '';
261
- if (!content.includes(psMarker)) {
262
- const backupPath = path.join(root, BACKUP_DIR, 'ps-profile.bak');
263
- if (fs.existsSync(psProfile)) backupFile(psProfile, backupPath);
264
- state.backups.psProfile = backupPath;
265
- const psHook = `${psMarker}\n$VG_SCRIPT_DIR = "${srcDir.replace(/\\/g, '\\\\')}"\n. "${path.join(srcDir, 'shell-hook.ps1').replace(/\\/g, '\\\\')}"\n${psEndMarker}`;
266
- content = content.trimEnd() + '\n' + psHook + '\n';
267
- fs.writeFileSync(psProfile, content);
268
- }
269
- }
270
-
271
- state.features.shellGuard = true;
272
- steps.push({ step: 'shell-guard', installed: true });
273
- } catch (e) {
274
- steps.push({ step: 'shell-guard', error: e.message });
275
- }
276
- }
277
- }
278
-
279
- // Add .vibeguard/ to .gitignore
280
- const gitignore = path.join(root, '.gitignore');
281
- try {
282
- let content = fs.existsSync(gitignore) ? fs.readFileSync(gitignore, 'utf8') : '';
283
- if (!content.includes('.vibeguard/')) {
284
- content = content.trimEnd() + '\n.vibeguard/\n';
285
- fs.writeFileSync(gitignore, content);
286
- }
287
- } catch {}
288
-
289
- writeState(root, state);
290
- logEvent(root, 'auto started');
291
-
292
- return { ok: true, steps, state };
293
- }
294
-
295
- // ─── Auto Stop ─────────────────────────────────────────────────────────────
296
-
297
- function autoStop(rootDir) {
298
- const root = findProjectRoot(rootDir) || path.resolve(rootDir);
299
- const state = readState(root);
300
- if (!state) {
301
- return { ok: false, reason: 'No auto state found. Was `vibeguard auto` run?' };
302
- }
303
-
304
- const reversed = [];
305
-
306
- // 1. Kill daemon
307
- if (state.daemonPid) {
308
- try { process.kill(state.daemonPid, 'SIGTERM'); } catch {}
309
- reversed.push('daemon stopped');
310
- }
311
-
312
- // 2. Remove pre-commit hook (restore backup if exists)
313
- const preCommit = path.join(root, '.git', 'hooks', 'pre-commit');
314
- if (fs.existsSync(preCommit) && state.backups && state.backups.preCommit) {
315
- restoreFile(preCommit, state.backups.preCommit);
316
- reversed.push('pre-commit hook restored from backup');
317
- } else if (fs.existsSync(preCommit)) {
318
- // Only remove if we installed it
319
- const content = fs.readFileSync(preCommit, 'utf8');
320
- if (content.includes('VibeGuard')) {
321
- fs.unlinkSync(preCommit);
322
- reversed.push('pre-commit hook removed');
323
- }
324
- }
325
-
326
- // 3. Remove PostToolUse hook
327
- try {
328
- const hookMod = require('./hook');
329
- const r = hookMod.uninstallPostEditHook(root);
330
- if (r.uninstalled) reversed.push('post-edit hook removed');
331
- } catch {}
332
-
333
- // 4. Disarm shell guard (remove from shell profiles)
334
- const marker = '# >>> VibeGuard shell hook >>>';
335
- const endMarker = '# <<< VibeGuard shell hook <<<';
336
- const psMarker = '### >>> VibeGuard shell hook >>>';
337
- const psEndMarker = '### <<< VibeGuard shell hook <<<';
338
- const home = os.homedir();
339
-
340
- for (const profile of ['.bashrc', '.zshrc']) {
341
- const p = path.join(home, profile);
342
- try {
343
- if (fs.existsSync(p)) {
344
- let content = fs.readFileSync(p, 'utf8');
345
- // Restore from backup if available
346
- const backupKey = profile === '.bashrc' ? 'bashrc' : 'zshrc';
347
- if (state.backups && state.backups[backupKey] && fs.existsSync(state.backups[backupKey])) {
348
- content = fs.readFileSync(state.backups[backupKey], 'utf8');
349
- fs.writeFileSync(p, content);
350
- reversed.push(`${profile} restored from backup`);
351
- } else {
352
- // Just remove our block
353
- const before = content;
354
- content = content.replace(new RegExp(marker + '[\\s\\S]*?' + endMarker + '\\n?', 'g'), '');
355
- if (content !== before) {
356
- fs.writeFileSync(p, content);
357
- reversed.push(`${profile} hook removed`);
358
- }
359
- }
360
- }
361
- } catch {}
362
- }
363
-
364
- if (process.platform === 'win32') {
365
- try {
366
- const psProfile = path.join(home, 'Documents', 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1');
367
- if (fs.existsSync(psProfile)) {
368
- let content = fs.readFileSync(psProfile, 'utf8');
369
- if (state.backups && state.backups.psProfile && fs.existsSync(state.backups.psProfile)) {
370
- content = fs.readFileSync(state.backups.psProfile, 'utf8');
371
- fs.writeFileSync(psProfile, content);
372
- reversed.push('PowerShell profile restored from backup');
373
- } else {
374
- const before = content;
375
- content = content.replace(new RegExp(psMarker + '[\\s\\S]*?' + psEndMarker + '\\n?', 'g'), '');
376
- if (content !== before) {
377
- fs.writeFileSync(psProfile, content);
378
- reversed.push('PowerShell profile hook removed');
379
- }
380
- }
381
- }
382
- } catch {}
383
- }
384
-
385
- // 5. Remove state file
386
- removeState(root);
387
- reversed.push('state file removed');
388
-
389
- logEvent(root, 'auto stopped');
390
-
391
- return { ok: true, reversed };
392
- }
393
-
394
- // ─── Auto Status ──────────────────────────────────────────────────────────
395
-
396
- function autoStatus(rootDir) {
397
- const root = findProjectRoot(rootDir) || path.resolve(rootDir);
398
- const state = readState(root);
399
- if (!state) {
400
- return { running: false, reason: 'No auto state found' };
401
- }
402
-
403
- const daemonAlive = state.daemonPid ? isProcessAlive(state.daemonPid) : false;
404
- const uptime = state.startedAt ? Date.now() - new Date(state.startedAt).getTime() : 0;
405
-
406
- return {
407
- running: true,
408
- pid: state.pid,
409
- daemonPid: state.daemonPid,
410
- daemonAlive,
411
- startedAt: state.startedAt,
412
- uptimeMs: uptime,
413
- features: state.features || {},
414
- findingsSinceStart: state.findingsSinceStart || 0,
415
- lastScan: state.lastScan,
416
- root: state.root,
417
- };
418
- }
419
-
420
- // ─── CI Mode ────────────────────────────────────────────────────────────────
421
-
422
- function autoCI(rootDir, opts) {
423
- opts = opts || {};
424
- opts.ci = true;
425
- return autoStart(rootDir, opts);
426
- }
427
-
428
- module.exports = { autoStart, autoStop, autoStatus, autoCI, findProjectRoot };