@yagyeshvyas/vibeguard 1.3.0 → 1.11.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 (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
@@ -0,0 +1,579 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * TLAP — Token-Lean Agent Protocol.
5
+ *
6
+ * Why this exists
7
+ * ---------------
8
+ * VibeGuard's primary consumer is not a human terminal, it is an AI agent
9
+ * reading tool output through a context window. Every scanner in this space
10
+ * (Semgrep, Snyk, Trivy, Strix) answers an agent with pretty-printed JSON:
11
+ * two-space indentation, repeated object keys, the same `message` and `fix`
12
+ * string duplicated once per occurrence, and full repo-relative paths on every
13
+ * line. On a real repository that is thousands of tokens of pure redundancy,
14
+ * paid for on every single tool call, in both directions of the loop.
15
+ *
16
+ * TLAP encodes the same information — no findings dropped silently — in a
17
+ * line-oriented, de-duplicated, dictionary-compressed form, and can hold the
18
+ * whole thing under a hard token budget by spending the budget on the findings
19
+ * that actually matter first (risk-ranked), then emitting an explicit rollup of
20
+ * whatever did not fit. An agent is never told "clean" because output was cut.
21
+ *
22
+ * Four compression levers, in order of how much they win:
23
+ * 1. No pretty JSON. Structural punctuation + repeated keys are ~55% of
24
+ * a `JSON.stringify(x, null, 2)` payload.
25
+ * 2. Cluster by rule. `message` + `fix` are properties of the RULE, not
26
+ * of the occurrence. Emit once, list the locations.
27
+ * 3. Path dictionary. `src/components/dashboard/` repeated 40 times
28
+ * becomes `p3`.
29
+ * 4. Risk-ranked budget. Truncate the tail, never the head, and always say
30
+ * what was truncated.
31
+ *
32
+ * Plus delta mode: if nothing changed since the previous scan snapshot, the
33
+ * whole answer is one line (~20 tokens instead of ~4000).
34
+ *
35
+ * Zero dependencies. Deterministic: identical input produces byte-identical
36
+ * output, which is what makes it safe to diff and to cache.
37
+ */
38
+
39
+ const crypto = require('crypto');
40
+ const fs = require('fs');
41
+ const path = require('path');
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Token estimation
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /*
48
+ * Offline token estimator.
49
+ *
50
+ * This is an ESTIMATE, not a tokenizer. Shipping a real BPE table would mean a
51
+ * dependency and a multi-megabyte vocab file, and VibeGuard is zero-dependency
52
+ * and offline by contract. The model below approximates BPE behaviour on
53
+ * code-shaped text closely enough to drive a budget:
54
+ *
55
+ * - alphabetic runs ~4 chars/token (BPE merges common subwords)
56
+ * - digit runs ~3 chars/token (digits tokenize worse than letters)
57
+ * - punctuation 1 token each (rarely merges in code)
58
+ * - newlines 1 token each
59
+ * - inline spaces usually absorbed into the following token
60
+ *
61
+ * Measured against published tokenizer counts on source/JSON samples this lands
62
+ * within roughly ±10%. Budgets are enforced with headroom to absorb that.
63
+ */
64
+ function estimateTokens(str) {
65
+ if (!str) return 0;
66
+ const s = String(str);
67
+ let tokens = 0;
68
+ let i = 0;
69
+ const n = s.length;
70
+ while (i < n) {
71
+ const c = s.charCodeAt(i);
72
+ // alphabetic run
73
+ if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) {
74
+ let j = i + 1;
75
+ while (j < n) {
76
+ const d = s.charCodeAt(j);
77
+ if ((d >= 65 && d <= 90) || (d >= 97 && d <= 122)) j++;
78
+ else break;
79
+ }
80
+ tokens += Math.ceil((j - i) / 4);
81
+ i = j;
82
+ continue;
83
+ }
84
+ // digit run
85
+ if (c >= 48 && c <= 57) {
86
+ let j = i + 1;
87
+ while (j < n && s.charCodeAt(j) >= 48 && s.charCodeAt(j) <= 57) j++;
88
+ tokens += Math.ceil((j - i) / 3);
89
+ i = j;
90
+ continue;
91
+ }
92
+ // newline run: each newline is its own token
93
+ if (c === 10 || c === 13) {
94
+ let j = i;
95
+ while (j < n && (s.charCodeAt(j) === 10 || s.charCodeAt(j) === 13)) {
96
+ if (s.charCodeAt(j) === 10) tokens += 1;
97
+ j++;
98
+ }
99
+ i = j;
100
+ continue;
101
+ }
102
+ // inline whitespace: absorbed into the next token, except long indent runs
103
+ if (c === 32 || c === 9) {
104
+ let j = i;
105
+ while (j < n && (s.charCodeAt(j) === 32 || s.charCodeAt(j) === 9)) j++;
106
+ const run = j - i;
107
+ if (run > 2) tokens += Math.ceil(run / 4);
108
+ i = j;
109
+ continue;
110
+ }
111
+ // everything else: one token per character (punctuation, symbols, unicode)
112
+ tokens += 1;
113
+ i += 1;
114
+ }
115
+ return tokens;
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Risk ranking — decides what survives a tight budget
120
+ // ---------------------------------------------------------------------------
121
+
122
+ const SEV_WEIGHT = { critical: 1000, high: 400, medium: 120, low: 30 };
123
+ const CONF_WEIGHT = { high: 1.0, medium: 0.75, low: 0.45 };
124
+
125
+ // Rules whose findings are dataflow-confirmed or directly exploitable outrank
126
+ // pattern-only matches of the same severity — that is what an agent should
127
+ // spend a constrained budget on first.
128
+ const EXPLOITABLE_RE = /^(taint|secret|injection|backdoor|idor|auth|ssrf|rce|deser|web\.ssrf)/;
129
+ const HOTSPOT_RE =
130
+ /(auth|login|signin|signup|password|session|token|jwt|payment|billing|checkout|charge|admin|role|permission|account|api|route|controller|middleware|webhook|upload)/i;
131
+
132
+ /*
133
+ * Score a single finding. Higher = shown first, and last to be dropped.
134
+ * Pure function of the finding, so ordering is stable across runs.
135
+ */
136
+ function riskScore(f) {
137
+ const sev = SEV_WEIGHT[f.severity] || 10;
138
+ const conf = CONF_WEIGHT[f.confidence] || CONF_WEIGHT.high;
139
+ let score = sev * conf;
140
+ if (EXPLOITABLE_RE.test(f.ruleId || '')) score += 150;
141
+ if (HOTSPOT_RE.test(f.file || '')) score += 60;
142
+ // Dataflow-confirmed findings state so in the message; trust them more.
143
+ if (/dataflow-confirmed|reachable|proof|callback observed/i.test(f.message || '')) score += 100;
144
+ return score;
145
+ }
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // Path dictionary
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /*
152
+ * Build a prefix dictionary for the directory parts of the finding paths.
153
+ * A prefix earns a slot only when substituting it actually saves characters:
154
+ * (prefixLength - tokenLength) * occurrences must clear a floor, otherwise the
155
+ * legend line costs more than the substitution saves.
156
+ */
157
+ function buildPathDict(files) {
158
+ const counts = new Map();
159
+ for (const file of files) {
160
+ const norm = String(file).replace(/\\/g, '/');
161
+ const idx = norm.lastIndexOf('/');
162
+ if (idx <= 0) continue;
163
+ const prefix = norm.slice(0, idx + 1);
164
+ counts.set(prefix, (counts.get(prefix) || 0) + 1);
165
+ }
166
+ const candidates = [];
167
+ for (const [prefix, count] of counts) {
168
+ // Saving per use ≈ prefix length - "pN" length (2-3 chars).
169
+ const saving = (prefix.length - 3) * count - (prefix.length + 5);
170
+ if (count >= 2 && prefix.length >= 6 && saving > 0) {
171
+ candidates.push({ prefix, count, saving });
172
+ }
173
+ }
174
+ candidates.sort((a, b) => b.saving - a.saving || a.prefix.localeCompare(b.prefix));
175
+ const dict = [];
176
+ // Cap the legend: beyond ~12 entries the legend itself starts to cost more
177
+ // than the long tail of rare prefixes saves.
178
+ for (const c of candidates.slice(0, 12)) {
179
+ dict.push({ token: 'p' + (dict.length + 1), prefix: c.prefix });
180
+ }
181
+ return dict;
182
+ }
183
+
184
+ function applyDict(file, dict) {
185
+ const norm = String(file).replace(/\\/g, '/');
186
+ // Longest prefix wins, so nested directories compress fully.
187
+ let best = null;
188
+ for (const d of dict) {
189
+ if (norm.startsWith(d.prefix) && (!best || d.prefix.length > best.prefix.length)) best = d;
190
+ }
191
+ return best ? best.token + norm.slice(best.prefix.length) : norm;
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // Clustering
196
+ // ---------------------------------------------------------------------------
197
+
198
+ const SEV_TAG = { critical: 'CRIT', high: 'HIGH', medium: 'MED', low: 'LOW' };
199
+ const SEV_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
200
+
201
+ /*
202
+ * Group findings that share a rule + message + fix. Those three strings are
203
+ * properties of the rule, so emitting them once per cluster instead of once per
204
+ * occurrence is lossless. Locations are kept in full.
205
+ */
206
+ function clusterFindings(findings) {
207
+ const groups = new Map();
208
+ for (const f of findings) {
209
+ const key = JSON.stringify([f.ruleId, f.severity, f.message || '', f.fix || '']);
210
+ let g = groups.get(key);
211
+ if (!g) {
212
+ g = {
213
+ ruleId: f.ruleId,
214
+ severity: f.severity,
215
+ message: f.message || '',
216
+ fix: f.fix || '',
217
+ locations: [],
218
+ count: 0,
219
+ score: 0,
220
+ };
221
+ groups.set(key, g);
222
+ }
223
+ g.locations.push({ file: String(f.file || '').replace(/\\/g, '/'), line: f.line || 0 });
224
+ g.count++;
225
+ // A cluster is ranked by its strongest member, not its average: one
226
+ // confirmed critical in a cluster must not be buried by weak siblings.
227
+ g.score = Math.max(g.score, riskScore(f));
228
+ }
229
+ const clusters = [...groups.values()];
230
+ for (const c of clusters) {
231
+ // Collapse locations to file -> sorted unique lines.
232
+ const byFile = new Map();
233
+ for (const loc of c.locations) {
234
+ if (!byFile.has(loc.file)) byFile.set(loc.file, new Set());
235
+ byFile.get(loc.file).add(loc.line);
236
+ }
237
+ c.files = [...byFile.entries()]
238
+ .map(([file, lines]) => ({ file, lines: [...lines].sort((a, b) => a - b) }))
239
+ .sort((a, b) => a.file.localeCompare(b.file));
240
+ }
241
+ clusters.sort(
242
+ (a, b) =>
243
+ SEV_ORDER[a.severity] - SEV_ORDER[b.severity] ||
244
+ b.score - a.score ||
245
+ a.ruleId.localeCompare(b.ruleId)
246
+ );
247
+ return clusters;
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // Rendering
252
+ // ---------------------------------------------------------------------------
253
+
254
+ function renderCluster(c, dict, opts) {
255
+ const locs = c.files
256
+ .map((fl) => applyDict(fl.file, dict) + ':' + fl.lines.join(','))
257
+ .join(' ');
258
+ const head =
259
+ `${SEV_TAG[c.severity] || c.severity.toUpperCase()} ${c.ruleId}` +
260
+ (c.count > 1 ? ` x${c.count}` : '') +
261
+ ' ' +
262
+ locs;
263
+ const lines = [head];
264
+ if (c.message && !opts.noMessage) lines.push(' ' + truncOneLine(c.message, opts.maxMsg));
265
+ if (c.fix && !opts.noFix) lines.push(' fix: ' + truncOneLine(c.fix, opts.maxFix));
266
+ return lines.join('\n');
267
+ }
268
+
269
+ function truncOneLine(s, max) {
270
+ const one = String(s).replace(/\s+/g, ' ').trim();
271
+ if (!max || one.length <= max) return one;
272
+ return one.slice(0, max - 1) + '…';
273
+ }
274
+
275
+ function countsLine(counts) {
276
+ const parts = [];
277
+ if (counts.critical) parts.push(counts.critical + 'C');
278
+ if (counts.high) parts.push(counts.high + 'H');
279
+ if (counts.medium) parts.push(counts.medium + 'M');
280
+ if (counts.low) parts.push(counts.low + 'L');
281
+ return parts.length ? parts.join(' ') : 'clean';
282
+ }
283
+
284
+ /*
285
+ * Render a scan result in TLAP form.
286
+ *
287
+ * opts:
288
+ * budget number hard token ceiling for the whole payload (default: none)
289
+ * maxMsg number per-message character cap (default 160)
290
+ * maxFix number per-fix character cap (default 140)
291
+ * noFix bool drop remediation text entirely (agent already knows it)
292
+ *
293
+ * Returns { text, tokens, clusters, shown, omitted }.
294
+ */
295
+ function renderLean(result, opts) {
296
+ const o = Object.assign({ maxMsg: 160, maxFix: 140, noFix: false }, opts || {});
297
+ const findings = result.findings || [];
298
+ const counts = result.counts || { critical: 0, high: 0, medium: 0, low: 0 };
299
+
300
+ // The header stays spelled out rather than sigil-coded. "Grade" costs about
301
+ // two tokens per call; an agent misreading the verdict of a security scan
302
+ // costs considerably more than that.
303
+ const header =
304
+ `VG Grade ${result.grade || '?'} | ${countsLine(counts)} | ` +
305
+ `${findings.length} findings in ${result.scannedFiles || 0} files`;
306
+
307
+ // Coverage transparency survives compression. A lean payload must never let
308
+ // an agent read a degraded scan as an all-clear.
309
+ const warn = [];
310
+ if (result.engine && result.engine.mode === 'regex-only') {
311
+ warn.push('! engine=regex-only (no AST/taint) — not an all-clear');
312
+ }
313
+ if (result.diagnostics && result.diagnostics.degradedFileCount > 0) {
314
+ warn.push(`! ${result.diagnostics.degradedFileCount} file(s) partially analyzed`);
315
+ }
316
+
317
+ if (findings.length === 0) {
318
+ const text = [header, ...warn].join('\n');
319
+ return { text, tokens: estimateTokens(text), clusters: 0, shown: 0, omitted: 0 };
320
+ }
321
+
322
+ const clusters = clusterFindings(findings);
323
+ const dict = buildPathDict(findings.map((f) => f.file));
324
+ const dictLine = dict.length ? dict.map((d) => `${d.token}=${d.prefix}`).join(' ') : '';
325
+
326
+ const fixed = [header, ...warn];
327
+ if (dictLine) fixed.push(dictLine);
328
+ const fixedText = fixed.join('\n');
329
+
330
+ const budget = o.budget && o.budget > 0 ? o.budget : Infinity;
331
+ // Reserve room for the omitted-rollup line so the truncation notice itself
332
+ // can never be the thing that gets truncated.
333
+ const reserve = budget === Infinity ? 0 : 40;
334
+ let used = estimateTokens(fixedText) + reserve;
335
+
336
+ const body = [];
337
+ const omitted = [];
338
+ for (const c of clusters) {
339
+ const rendered = renderCluster(c, dict, o);
340
+ const cost = estimateTokens(rendered) + 1;
341
+ if (used + cost > budget) {
342
+ omitted.push(c);
343
+ continue;
344
+ }
345
+ body.push(rendered);
346
+ used += cost;
347
+ }
348
+
349
+ const out = [fixedText];
350
+ if (body.length) out.push('', body.join('\n'));
351
+
352
+ if (omitted.length) {
353
+ const bySev = { critical: 0, high: 0, medium: 0, low: 0 };
354
+ let n = 0;
355
+ for (const c of omitted) {
356
+ bySev[c.severity] = (bySev[c.severity] || 0) + c.count;
357
+ n += c.count;
358
+ }
359
+ const topIds = omitted.slice(0, 6).map((c) => c.ruleId).join(' ');
360
+ out.push(
361
+ '',
362
+ `+ ${n} more finding(s) over budget [${countsLine(bySev)}] rules: ${topIds}` +
363
+ (omitted.length > 6 ? ` +${omitted.length - 6} rules` : '') +
364
+ ' — raise budget to see them. NOT an all-clear.'
365
+ );
366
+ }
367
+
368
+ const text = out.join('\n');
369
+ return {
370
+ text,
371
+ tokens: estimateTokens(text),
372
+ clusters: clusters.length,
373
+ shown: clusters.length - omitted.length,
374
+ omitted: omitted.length,
375
+ };
376
+ }
377
+
378
+ /*
379
+ * A fix plan in the lean dialect.
380
+ *
381
+ * The prose fix prompt repeats the finding message and the remediation text
382
+ * once per occurrence plus a paragraph of instructions. In a fix loop an agent
383
+ * pays for that on every iteration. Here the instruction is one line, the
384
+ * remediation is stated once per rule, and the message is dropped entirely —
385
+ * when the task is "apply the fix", the diagnosis is not what the agent needs.
386
+ */
387
+ function renderLeanFixPlan(result, opts) {
388
+ const o = Object.assign({ maxFix: 200, noMessage: true }, opts || {});
389
+ const findings = result.findings || [];
390
+ if (findings.length === 0) return 'VG Grade ' + (result.grade || 'A') + ' | clean — nothing to fix.';
391
+
392
+ const clusters = clusterFindings(findings);
393
+ const dict = buildPathDict(findings.map((f) => f.file));
394
+ const out = [
395
+ `VG fix plan | Grade ${result.grade} | ${clusters.length} rules, ${findings.length} sites`,
396
+ 'Apply the minimal safe change at each site. Rotate any leaked secret. Touch nothing else.',
397
+ ];
398
+ if (dict.length) out.push(dict.map((d) => `${d.token}=${d.prefix}`).join(' '));
399
+ out.push('');
400
+
401
+ const budget = o.budget && o.budget > 0 ? o.budget : Infinity;
402
+ let used = estimateTokens(out.join('\n')) + (budget === Infinity ? 0 : 40);
403
+ const omitted = [];
404
+ for (const c of clusters) {
405
+ const rendered = renderCluster(c, dict, o);
406
+ const cost = estimateTokens(rendered) + 1;
407
+ if (used + cost > budget) {
408
+ omitted.push(c);
409
+ continue;
410
+ }
411
+ out.push(rendered);
412
+ used += cost;
413
+ }
414
+ if (omitted.length) {
415
+ const n = omitted.reduce((a, c) => a + c.count, 0);
416
+ out.push('', `+ ${n} more site(s) over budget — fix these first, then re-run. NOT a complete plan.`);
417
+ }
418
+ return out.join('\n');
419
+ }
420
+
421
+ // ---------------------------------------------------------------------------
422
+ // Savings measurement — the number we publish, computed honestly
423
+ // ---------------------------------------------------------------------------
424
+
425
+ /*
426
+ * Compare TLAP against the baseline every other scanner sends an agent:
427
+ * pretty-printed JSON of the findings array.
428
+ */
429
+ function leanStats(result, opts) {
430
+ const baselinePayload = {
431
+ grade: result.grade,
432
+ counts: result.counts,
433
+ scannedFiles: result.scannedFiles,
434
+ findings: (result.findings || []).map((f) => ({
435
+ severity: f.severity,
436
+ ruleId: f.ruleId,
437
+ file: f.file,
438
+ line: f.line,
439
+ message: f.message,
440
+ fix: f.fix,
441
+ })),
442
+ };
443
+ const jsonText = JSON.stringify(baselinePayload, null, 2);
444
+ const jsonTokens = estimateTokens(jsonText);
445
+ const lean = renderLean(result, opts);
446
+ const saved = jsonTokens - lean.tokens;
447
+ return {
448
+ jsonTokens,
449
+ jsonChars: jsonText.length,
450
+ leanTokens: lean.tokens,
451
+ leanChars: lean.text.length,
452
+ saved,
453
+ savedPct: jsonTokens > 0 ? Math.round((saved / jsonTokens) * 1000) / 10 : 0,
454
+ findings: (result.findings || []).length,
455
+ clusters: lean.clusters,
456
+ text: lean.text,
457
+ };
458
+ }
459
+
460
+ // ---------------------------------------------------------------------------
461
+ // Delta mode — the cheapest possible answer is "nothing changed"
462
+ // ---------------------------------------------------------------------------
463
+
464
+ /*
465
+ * A stable fingerprint of the finding set. Fingerprints already exist per
466
+ * finding; hashing the sorted set gives a scan identity that ignores ordering
467
+ * and file-walk nondeterminism.
468
+ */
469
+ function snapshotOf(result) {
470
+ const ids = (result.findings || [])
471
+ .map((f) => f.fingerprint || `${f.ruleId}:${f.file}:${f.line}`)
472
+ .sort();
473
+ return {
474
+ hash: crypto.createHash('sha256').update(ids.join('\n')).digest('hex').slice(0, 16),
475
+ grade: result.grade,
476
+ count: ids.length,
477
+ ids,
478
+ };
479
+ }
480
+
481
+ /*
482
+ * Render only what changed against a previous snapshot.
483
+ * Unchanged => a single line, which is the entire point.
484
+ */
485
+ function deltaReport(result, prev, opts) {
486
+ const snap = snapshotOf(result);
487
+ if (prev && prev.hash === snap.hash) {
488
+ const text = `VG Grade ${result.grade} unchanged (${snap.count} known finding(s), fp ${snap.hash}) — no new issues.`;
489
+ return { unchanged: true, snapshot: snap, text, tokens: estimateTokens(text) };
490
+ }
491
+ const prevIds = new Set((prev && prev.ids) || []);
492
+ const fresh = (result.findings || []).filter(
493
+ (f) => !prevIds.has(f.fingerprint || `${f.ruleId}:${f.file}:${f.line}`)
494
+ );
495
+ const resolved = prev ? (prev.ids || []).filter((id) => !snap.ids.includes(id)).length : 0;
496
+ const sub = Object.assign({}, result, { findings: fresh });
497
+ const lean = renderLean(sub, opts);
498
+ const head = prev
499
+ ? `VG Grade ${result.grade} delta: ${fresh.length} new, ${resolved} resolved, ${snap.count} total`
500
+ : `VG Grade ${result.grade} baseline: ${snap.count} finding(s)`;
501
+ const text = head + (fresh.length ? '\n' + lean.text : '');
502
+ return { unchanged: false, snapshot: snap, text, tokens: estimateTokens(text), newCount: fresh.length, resolved };
503
+ }
504
+
505
+ /*
506
+ * Snapshot persistence.
507
+ *
508
+ * Owned here rather than duplicated in the CLI and the MCP server so both
509
+ * speak to one notion of "what I have already reported". The path is always
510
+ * built from a resolved root plus a constant relative path — the scan root is
511
+ * never concatenated with anything caller-supplied.
512
+ */
513
+ const SNAPSHOT_REL = path.join('.vibeguard', 'tlap-snapshot.json');
514
+
515
+ function snapshotPath(root) {
516
+ return path.join(path.resolve(root || '.'), SNAPSHOT_REL);
517
+ }
518
+
519
+ function readSnapshot(root) {
520
+ try {
521
+ return JSON.parse(fs.readFileSync(snapshotPath(root), 'utf8'));
522
+ } catch {
523
+ return null;
524
+ }
525
+ }
526
+
527
+ /* A snapshot is a cache. Failing to write one must never fail a scan. */
528
+ function writeSnapshot(root, snap) {
529
+ try {
530
+ const file = snapshotPath(root);
531
+ fs.mkdirSync(path.dirname(file), { recursive: true });
532
+ fs.writeFileSync(file, JSON.stringify(snap));
533
+ return true;
534
+ } catch {
535
+ return false;
536
+ }
537
+ }
538
+
539
+ // ---------------------------------------------------------------------------
540
+ // Generic budget guard for arbitrary tool text
541
+ // ---------------------------------------------------------------------------
542
+
543
+ /*
544
+ * Last-resort ceiling applied to any tool payload that is not a scan result.
545
+ * Keeps the head (summaries lead in every VibeGuard tool) and states exactly
546
+ * how much was cut, so the agent knows the answer is partial.
547
+ */
548
+ function compactText(text, budget) {
549
+ if (!budget || budget <= 0) return text;
550
+ const s = String(text == null ? '' : text);
551
+ const tokens = estimateTokens(s);
552
+ if (tokens <= budget) return s;
553
+ // ~4 chars/token, with 5% headroom for estimator error.
554
+ const keepChars = Math.max(200, Math.floor(budget * 4 * 0.95));
555
+ const head = s.slice(0, keepChars);
556
+ const cutTokens = tokens - estimateTokens(head);
557
+ return (
558
+ head +
559
+ `\n\n… [truncated ~${cutTokens} tokens of ${tokens} to fit a ${budget}-token budget. ` +
560
+ 'Output is PARTIAL — not an all-clear. Raise VIBEGUARD_TOKEN_BUDGET or pass a larger budget.]'
561
+ );
562
+ }
563
+
564
+ module.exports = {
565
+ estimateTokens,
566
+ riskScore,
567
+ buildPathDict,
568
+ applyDict,
569
+ clusterFindings,
570
+ renderLean,
571
+ renderLeanFixPlan,
572
+ leanStats,
573
+ snapshotOf,
574
+ snapshotPath,
575
+ readSnapshot,
576
+ writeSnapshot,
577
+ deltaReport,
578
+ compactText,
579
+ };