@clear-capabilities/agentic-security-scanner 0.124.0 → 0.127.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2395 @@
1
+ export const id = 435;
2
+ export const ids = [435,752];
3
+ export const modules = {
4
+
5
+ /***/ 2435:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+
9
+ // EXPORTS
10
+ __webpack_require__.d(__webpack_exports__, {
11
+ runStdio: () => (/* binding */ runStdio)
12
+ });
13
+
14
+ // EXTERNAL MODULE: external "node:fs"
15
+ var external_node_fs_ = __webpack_require__(3024);
16
+ // EXTERNAL MODULE: external "node:crypto"
17
+ var external_node_crypto_ = __webpack_require__(7598);
18
+ // EXTERNAL MODULE: external "node:path"
19
+ var external_node_path_ = __webpack_require__(6760);
20
+ // EXTERNAL MODULE: external "node:url"
21
+ var external_node_url_ = __webpack_require__(3136);
22
+ // EXTERNAL MODULE: external "node:fs/promises"
23
+ var promises_ = __webpack_require__(1455);
24
+ // EXTERNAL MODULE: ./src/posture/fix-history.js
25
+ var fix_history = __webpack_require__(4407);
26
+ ;// CONCATENATED MODULE: ./src/posture/deterministic-fix.js
27
+ // Deterministic fix synthesis (#1) — for the narrow set of vulnerability classes
28
+ // where a context-INDEPENDENT literal swap is a safe, correct fix, produce a
29
+ // full-file replacement from the current file content. No LLM, no guessing, no
30
+ // per-finding bloat in last-scan.json (the patch is materialized on demand by
31
+ // synthesize_fix from the live file, not stored on every finding).
32
+ //
33
+ // Safety: every patch this produces is still gated by verify_fix before apply_fix
34
+ // writes it (original finding gone + no new ≥medium + lint clean). So a swap that
35
+ // a rule mis-attributed simply fails verification instead of landing a bad edit —
36
+ // this module widens the deterministic-fix surface without weakening the gate.
37
+ //
38
+ // Returns { patch: { [relFile]: newContent }, ruleId } or null when no
39
+ // deterministic fix applies to the finding.
40
+
41
+ const JS_EXT = /\.(?:js|jsx|ts|tsx|mjs|cjs)$/i;
42
+ const PY_EXT = /\.py$/i;
43
+
44
+ // Each rule gates on the finding's cwe/family, then rewrites the whole-file
45
+ // content. transform() returns the new content, or null when nothing changed
46
+ // (e.g. the vulnerable token isn't literally present — then we don't claim a fix).
47
+ const RULES = [
48
+ {
49
+ id: 'weak-hash-sha256',
50
+ // md5 / sha1 → sha256. Every occurrence in the file is a weak hash, so
51
+ // swapping them all is safe; the verifier confirms the weak-hash finding is
52
+ // gone and nothing worse appeared.
53
+ applies: (f) => /CWE-(?:327|328|916)/.test(f.cwe || '') || /weak.?hash/i.test(f.family || ''),
54
+ transform: (content, file) => {
55
+ let out = content;
56
+ if (JS_EXT.test(file)) {
57
+ out = out.replace(/(\bcreateHash\s*\(\s*['"`])(?:md5|sha1)(['"`])/gi, '$1sha256$2');
58
+ } else if (PY_EXT.test(file)) {
59
+ out = out.replace(/\bhashlib\.(?:md5|sha1)\s*\(/g, 'hashlib.sha256(');
60
+ }
61
+ return out !== content ? out : null;
62
+ },
63
+ },
64
+ {
65
+ id: 'tls-verify-on',
66
+ // Disabled TLS verification → enabled. rejectUnauthorized:false → true (JS),
67
+ // verify=False → verify=True (Python requests).
68
+ applies: (f) => /CWE-295/.test(f.cwe || '') || /tls.?no.?verify|cert.?(?:none|verify)/i.test(f.family || ''),
69
+ transform: (content, file) => {
70
+ let out = content;
71
+ if (JS_EXT.test(file)) {
72
+ out = out.replace(/(\brejectUnauthorized\s*:\s*)false\b/g, '$1true');
73
+ } else if (PY_EXT.test(file)) {
74
+ out = out.replace(/(\bverify\s*=\s*)False\b/g, '$1True');
75
+ }
76
+ return out !== content ? out : null;
77
+ },
78
+ },
79
+ ];
80
+
81
+ function synthesizeDeterministicPatch(finding, fileContent) {
82
+ if (!finding || typeof fileContent !== 'string' || !finding.file) return null;
83
+ for (const rule of RULES) {
84
+ try {
85
+ if (!rule.applies(finding)) continue;
86
+ const next = rule.transform(fileContent, finding.file);
87
+ if (next && next !== fileContent) return { patch: { [finding.file]: next }, ruleId: rule.id };
88
+ } catch { /* a single rule failing must never break synthesis */ }
89
+ }
90
+ return null;
91
+ }
92
+
93
+ // EXTERNAL MODULE: ./src/posture/integrity.js
94
+ var integrity = __webpack_require__(1130);
95
+ // EXTERNAL MODULE: ./src/posture/cache-economics.js
96
+ var cache_economics = __webpack_require__(8752);
97
+ ;// CONCATENATED MODULE: ./src/mcp/redact.js
98
+ // Secret redactor for MCP tool outputs and audit log argument summaries.
99
+ //
100
+ // OWASP MCP01 + MCP10: the scanner reads source code, and findings carry
101
+ // `snippet` / `description` / `trace` strings that may contain hardcoded
102
+ // credentials, API keys, JWTs, private keys, etc. When those flow back to
103
+ // the agent through tools/call responses they land in the agent's context
104
+ // — exposing the secret to model logs, transcripts, and any downstream tool
105
+ // the agent passes them to.
106
+ //
107
+ // We replace high-confidence secret shapes with [REDACTED:<kind>] before
108
+ // emitting them. The original full content is still on disk (scanner
109
+ // findings); the MCP surface is the bottleneck we control.
110
+ //
111
+ // Patterns deliberately stay narrow: high-precision so we don't garble
112
+ // non-secret long strings (UUIDs, SHAs, base64-encoded scan IDs).
113
+
114
+ const PATTERNS = [
115
+ // Provider-specific high-entropy keys (anchored prefixes give very low FP)
116
+ [/AKIA[0-9A-Z]{16}/g, 'aws-access-key'],
117
+ [/ASIA[0-9A-Z]{16}/g, 'aws-temp-key'],
118
+ [/gh[pousr]_[A-Za-z0-9]{36,255}/g, 'github-token'],
119
+ [/xox[abprs]-[A-Za-z0-9-]{10,}/g, 'slack-token'],
120
+ [/sk-ant-[A-Za-z0-9_-]{20,}/g, 'anthropic-key'],
121
+ [/sk-proj-[A-Za-z0-9_-]{20,}/g, 'openai-project-key'],
122
+ [/sk-[A-Za-z0-9]{32,}/g, 'openai-or-stripe-key'],
123
+ [/sk_(?:live|test)_[A-Za-z0-9]{20,}/g, 'stripe-key'],
124
+ [/rk_(?:live|test)_[A-Za-z0-9]{20,}/g, 'stripe-restricted-key'],
125
+ [/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g, 'sendgrid-key'],
126
+ [/AIza[0-9A-Za-z_-]{35}/g, 'google-api-key'],
127
+ // JWT — three dot-separated b64url segments starting with eyJ
128
+ [/eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, 'jwt'],
129
+ // PEM-encoded private keys
130
+ [/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/g, 'private-key-block'],
131
+ // Authorization headers — common copy-paste shape
132
+ [/(?:Authorization|authorization)\s*:\s*Bearer\s+[A-Za-z0-9._~+/-]{20,}={0,2}/g, 'bearer-token'],
133
+ // Hardcoded password literals — assignment shape with quoted value
134
+ [/(password|passwd|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*["'][^"'\n]{6,}["']/gi, 'hardcoded-credential'],
135
+ ];
136
+
137
+ const SNIPPET_MAX = 2000;
138
+ // OWASP A03 — cap input before running 14 regex patterns over it. A forged
139
+ // last-scan.json could plant a 50MB description string; without this cap a
140
+ // single explain_finding/query_taint call would peg CPU. After truncation
141
+ // the snippet still gets the final SNIPPET_MAX trim downstream.
142
+ const INPUT_MAX = 100_000;
143
+
144
+ function redactString(s) {
145
+ if (typeof s !== 'string') return s;
146
+ let out = s;
147
+ if (out.length > INPUT_MAX) out = out.slice(0, INPUT_MAX) + `…(+${out.length - INPUT_MAX})`;
148
+ for (const [re, kind] of PATTERNS) {
149
+ out = out.replace(re, `[REDACTED:${kind}]`);
150
+ }
151
+ if (out.length > SNIPPET_MAX) out = out.slice(0, SNIPPET_MAX) + `…(+${out.length - SNIPPET_MAX})`;
152
+ return out;
153
+ }
154
+
155
+ // Deep-redact every string in a finding-like object (mutates returned copy).
156
+ function redactFinding(f) {
157
+ if (!f || typeof f !== 'object') return f;
158
+ const out = { ...f };
159
+ for (const k of ['snippet', 'description', 'remediation', 'title', 'vuln', 'message']) {
160
+ if (typeof out[k] === 'string') out[k] = redactString(out[k]);
161
+ }
162
+ if (out.trace) {
163
+ try { out.trace = JSON.parse(redactString(JSON.stringify(out.trace))); }
164
+ catch { /* keep as-is if not round-trippable */ }
165
+ }
166
+ return out;
167
+ }
168
+
169
+ // Redact a freeform JSON-stringified argument blob (used by audit log).
170
+ function redactArgsBlob(s) {
171
+ return redactString(s);
172
+ }
173
+
174
+ ;// CONCATENATED MODULE: ./src/posture/agents-memory.js
175
+ // AGENTS.md — writable continual-learning memory (harness-anatomy #2).
176
+ //
177
+ // LangChain post:
178
+ // "Harnesses support memory file standards like AGENTS.md which get
179
+ // injected into context on agent start. As agents add and edit this file,
180
+ // harnesses load the updated file into context. This is a form of
181
+ // continual learning where agents durably store knowledge from one
182
+ // session and inject that knowledge into future sessions."
183
+ //
184
+ // Distinct from CLAUDE.md:
185
+ // - CLAUDE.md = human-authored project conventions, gotchas, layout.
186
+ // - AGENTS.md = agent-authored notes ("what worked / didn't work / I'd try
187
+ // differently next time"). Append-only. Bounded.
188
+ //
189
+ // Lives at `<project>/.agentic-security/AGENTS.md`.
190
+ //
191
+ // Bounds:
192
+ // - MAX_BYTES (default 20 KB) — past this, the oldest entries rotate to
193
+ // `AGENTS.md.archive` (also bounded; oldest archive entries are dropped).
194
+ // - MAX_ENTRY_BYTES (default 2 KB) — caps a single appendage.
195
+ // - Entries are append-only with an ISO timestamp + section divider, so
196
+ // readers can grep / slice by date without parsing.
197
+ //
198
+ // We deliberately avoid tying AGENTS.md to a session-id namespace. The post's
199
+ // recommendation is FLAT continual learning — the whole project's agents see
200
+ // each other's notes. Subagents that want session-scoped scratch use the
201
+ // agent-scratchpad surface instead.
202
+
203
+
204
+
205
+
206
+ const MEMORY_FILE = '.agentic-security/AGENTS.md';
207
+ const ARCHIVE_FILE = '.agentic-security/AGENTS.md.archive';
208
+ const MAX_BYTES = 20 * 1024;
209
+ const MAX_ENTRY_BYTES = 2 * 1024;
210
+ const ARCHIVE_MAX_BYTES = 200 * 1024;
211
+ const HEADER = '# AGENTS.md\n\nAgent-authored continual-learning notes. Each entry: timestamp + agent name + one short paragraph. New entries appended at the bottom; oldest entries rotate to AGENTS.md.archive when this file exceeds 20 KB.\n\n';
212
+
213
+ function _resolve(scanRoot) { return external_node_path_.join(scanRoot, MEMORY_FILE); }
214
+ function _archivePath(scanRoot) { return external_node_path_.join(scanRoot, ARCHIVE_FILE); }
215
+
216
+ function readAgentsMemory(scanRoot) {
217
+ const fp = _resolve(scanRoot);
218
+ if (!external_node_fs_.existsSync(fp)) return '';
219
+ try { return external_node_fs_.readFileSync(fp, 'utf8'); } catch { return ''; }
220
+ }
221
+
222
+ function appendAgentsMemory(scanRoot, { agent, body }) {
223
+ if (typeof agent !== 'string' || !agent.length) {
224
+ return { ok: false, reason: 'agent: required string' };
225
+ }
226
+ if (!/^[A-Za-z0-9_.-]{1,64}$/.test(agent)) {
227
+ return { ok: false, reason: 'agent: must match [A-Za-z0-9_.-]{1,64}' };
228
+ }
229
+ if (typeof body !== 'string' || !body.trim().length) {
230
+ return { ok: false, reason: 'body: required non-empty string' };
231
+ }
232
+ let snippet = body.trim();
233
+ // Strip control chars and cap.
234
+ snippet = snippet.replace(/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/g, ' ');
235
+ if (snippet.length > MAX_ENTRY_BYTES) {
236
+ snippet = snippet.slice(0, MAX_ENTRY_BYTES) + '…';
237
+ }
238
+ const ts = new Date().toISOString();
239
+ const entry = `\n## ${ts} agent: ${agent}\n\n${snippet}\n`;
240
+ try {
241
+ const fp = _resolve(scanRoot);
242
+ external_node_fs_.mkdirSync(external_node_path_.dirname(fp), { recursive: true });
243
+ if (!external_node_fs_.existsSync(fp)) external_node_fs_.writeFileSync(fp, HEADER);
244
+ external_node_fs_.appendFileSync(fp, entry);
245
+ _maybeRotate(scanRoot);
246
+ const stat = external_node_fs_.statSync(fp);
247
+ return { ok: true, entryBytes: entry.length, fileSize: stat.size };
248
+ } catch (e) {
249
+ return { ok: false, reason: `write-failed: ${e.message}` };
250
+ }
251
+ }
252
+
253
+ function _maybeRotate(scanRoot) {
254
+ const fp = _resolve(scanRoot);
255
+ let body;
256
+ try { body = external_node_fs_.readFileSync(fp, 'utf8'); } catch { return; }
257
+ if (body.length <= MAX_BYTES) return;
258
+ // Split on the `## ` entry headers. Keep the most-recent N until the head
259
+ // (everything before the cut) drops below MAX_BYTES/2; move the head to
260
+ // the archive.
261
+ const head = HEADER;
262
+ const trailing = body.slice(head.length);
263
+ const sections = trailing.split(/(?=\n## )/g).filter(s => s.length);
264
+ // Walk from the end, accumulating until we have roughly MAX_BYTES/2 of
265
+ // recent entries. Everything else goes to the archive.
266
+ let kept = '', archive = '', accum = 0;
267
+ for (let i = sections.length - 1; i >= 0; i--) {
268
+ if (accum + sections[i].length <= MAX_BYTES / 2) {
269
+ kept = sections[i] + kept;
270
+ accum += sections[i].length;
271
+ } else {
272
+ archive = sections.slice(0, i + 1).join('') + archive;
273
+ break;
274
+ }
275
+ }
276
+ try {
277
+ external_node_fs_.writeFileSync(fp, head + kept);
278
+ if (archive.length) {
279
+ const arcFp = _archivePath(scanRoot);
280
+ let existing = '';
281
+ try { existing = external_node_fs_.existsSync(arcFp) ? external_node_fs_.readFileSync(arcFp, 'utf8') : ''; } catch {}
282
+ let next = existing + archive;
283
+ if (next.length > ARCHIVE_MAX_BYTES) {
284
+ // Drop oldest entries until under cap.
285
+ const oldestSplit = next.split(/(?=\n## )/g).filter(s => s.length);
286
+ while (oldestSplit.length && next.length > ARCHIVE_MAX_BYTES) {
287
+ oldestSplit.shift();
288
+ next = oldestSplit.join('');
289
+ }
290
+ }
291
+ external_node_fs_.writeFileSync(arcFp, next);
292
+ }
293
+ } catch { /* best-effort rotation */ }
294
+ }
295
+
296
+ // Public summary helper for the SessionStart hook. Returns a tail aligned
297
+ // to a section header (no leading partial entry, no leading newline).
298
+ function summarizeForSession(scanRoot, { maxBytes = 6 * 1024 } = {}) {
299
+ const body = readAgentsMemory(scanRoot);
300
+ if (!body) return null;
301
+ if (body.length <= maxBytes) return body;
302
+ const tail = body.slice(-maxBytes);
303
+ const firstSection = tail.indexOf('\n## ');
304
+ if (firstSection < 0) return tail;
305
+ // Slice past the leading `\n` so the result starts with `## `.
306
+ return tail.slice(firstSection + 1);
307
+ }
308
+
309
+ const _internals = { MAX_BYTES, MAX_ENTRY_BYTES, MEMORY_FILE, ARCHIVE_FILE };
310
+
311
+ // EXTERNAL MODULE: external "node:os"
312
+ var external_node_os_ = __webpack_require__(8161);
313
+ ;// CONCATENATED MODULE: ./src/posture/cve-lookup.js
314
+ // CVE lookup — read-only against the per-install OSV / KEV / EPSS caches.
315
+ //
316
+ // LangChain harness-anatomy post:
317
+ // "Knowledge cutoffs mean that models can't directly access new data like
318
+ // updated library versions without the user providing them directly."
319
+ //
320
+ // The validator and any subagent reasoning about an SCA finding can call
321
+ // `lookup_cve(cve_id)` to get the most recently-cached OSV advisory, the
322
+ // CISA KEV entry if listed, and the EPSS exploit-prediction percentile, all
323
+ // with `staleness` metadata so the caller can decide whether to trust the
324
+ // cached value.
325
+ //
326
+ // This module deliberately NEVER triggers a network fetch — the scan
327
+ // pipeline is the only thing that populates the cache. If a CVE isn't
328
+ // cached, we return `present: false` for that source rather than blocking
329
+ // on a fetch and risking a multi-second MCP timeout.
330
+
331
+
332
+
333
+
334
+
335
+
336
+ const CACHE_DIR = external_node_path_.join(external_node_os_.homedir(), '.claude', 'agentic-security', 'osv-cache');
337
+
338
+ function _keyToPath(key) {
339
+ const safe = external_node_crypto_.createHash('sha256').update(key).digest('hex');
340
+ return external_node_path_.join(CACHE_DIR, safe + '.json');
341
+ }
342
+
343
+ function _readCache(key) {
344
+ const fp = _keyToPath(key);
345
+ if (!external_node_fs_.existsSync(fp)) return { present: false };
346
+ let body;
347
+ try { body = external_node_fs_.readFileSync(fp, 'utf8'); }
348
+ catch { return { present: false, error: 'unreadable' }; }
349
+ let parsed;
350
+ try { parsed = JSON.parse(body); }
351
+ catch { return { present: false, error: 'unparseable' }; }
352
+ let mtime = null;
353
+ try { mtime = external_node_fs_.statSync(fp).mtimeMs; } catch {}
354
+ return { present: true, data: parsed, cachedAt: mtime, ageMs: mtime ? Date.now() - mtime : null };
355
+ }
356
+
357
+ function _stalenessTier(ageMs) {
358
+ if (ageMs === null || ageMs === undefined) return 'unknown';
359
+ if (ageMs < 24 * 3600 * 1000) return 'fresh'; // <1d
360
+ if (ageMs < 7 * 24 * 3600 * 1000) return 'recent'; // <1w
361
+ if (ageMs < 30 * 24 * 3600 * 1000) return 'stale'; // <1mo
362
+ return 'very-stale';
363
+ }
364
+
365
+ const CVE_RE = /^CVE-\d{4}-\d{1,7}$/i;
366
+
367
+ function lookupCve(rawId) {
368
+ if (typeof rawId !== 'string' || !CVE_RE.test(rawId)) {
369
+ return { ok: false, reason: 'invalid-cve-id', expected: 'CVE-YYYY-NNNN' };
370
+ }
371
+ const cve = rawId.toUpperCase();
372
+
373
+ // KEV catalog — single cached blob keyed at 'kev:catalog'.
374
+ const kevCacheRaw = _readCache('kev:catalog');
375
+ let kev = { present: false };
376
+ if (kevCacheRaw.present) {
377
+ // The blob shape from engine.js: { ts, byCve: { 'CVE-XXX': { ... } } }
378
+ // sessionStorage shim stores the value as the JSON-stringified inner
379
+ // object directly (no extra wrapper).
380
+ const blob = kevCacheRaw.data;
381
+ const byCve = blob?.byCve || null;
382
+ if (byCve && byCve[cve]) {
383
+ kev = {
384
+ present: true,
385
+ ...byCve[cve],
386
+ cachedAt: kevCacheRaw.cachedAt,
387
+ ageMs: kevCacheRaw.ageMs,
388
+ staleness: _stalenessTier(kevCacheRaw.ageMs),
389
+ };
390
+ } else if (byCve) {
391
+ // Catalog is cached but doesn't list this CVE — meaningful negative.
392
+ kev = {
393
+ present: false, listedInCatalog: false,
394
+ cachedAt: kevCacheRaw.cachedAt, ageMs: kevCacheRaw.ageMs,
395
+ staleness: _stalenessTier(kevCacheRaw.ageMs),
396
+ };
397
+ }
398
+ }
399
+
400
+ // EPSS — per-CVE cache at 'epss:CVE-XXX'.
401
+ const epssRaw = _readCache('epss:' + cve);
402
+ let epss = { present: false };
403
+ if (epssRaw.present) {
404
+ epss = {
405
+ present: epssRaw.data !== false, // engine stores `false` for "looked up, no record"
406
+ score: epssRaw.data?.score ?? null,
407
+ percentile: epssRaw.data?.percentile ?? null,
408
+ cachedAt: epssRaw.cachedAt,
409
+ ageMs: epssRaw.ageMs,
410
+ staleness: _stalenessTier(epssRaw.ageMs),
411
+ };
412
+ }
413
+
414
+ // OSV — entries are keyed by vuln id (GHSA-... or CVE-...). The engine
415
+ // caches them at 'vuln:<id>'. We do a direct CVE lookup AND a soft probe
416
+ // for any known alias the caller provided implicitly through the KEV
417
+ // hit's vendor/product (no — we keep this simple: direct lookup only).
418
+ const osvRaw = _readCache('vuln:' + cve);
419
+ let osv = { present: false };
420
+ if (osvRaw.present) {
421
+ osv = {
422
+ present: true,
423
+ data: osvRaw.data,
424
+ cachedAt: osvRaw.cachedAt, ageMs: osvRaw.ageMs,
425
+ staleness: _stalenessTier(osvRaw.ageMs),
426
+ };
427
+ }
428
+
429
+ return {
430
+ ok: true,
431
+ cve,
432
+ kev,
433
+ epss,
434
+ osv,
435
+ sourcesFound: [kev.present, epss.present, osv.present].filter(Boolean).length,
436
+ note: (kev.present || epss.present || osv.present)
437
+ ? 'cached values only; staleness tier per source. The MCP tool does NOT trigger a network fetch.'
438
+ : 'no cached data for this CVE on the current install. Run a scan against a project that depends on the affected package, or set $AGENTIC_SECURITY_OFFLINE=0 and run a scan to populate the cache.',
439
+ };
440
+ }
441
+
442
+ const cve_lookup_internals = { CACHE_DIR, CVE_RE, _stalenessTier };
443
+
444
+ ;// CONCATENATED MODULE: ./src/mcp/tools.js
445
+ // MCP tool implementations — PRD Feature 2, hardened against the OWASP MCP
446
+ // Top 10 (see ./redact.js, ./audit.js, ./server.js for sibling controls).
447
+ //
448
+ // Trust model:
449
+ // - Session root fixed at server boot. No per-call retargeting.
450
+ // - Path arguments lstat-checked (symlinks refused, OWASP MCP05) and
451
+ // realpath-confined to session root.
452
+ // - Tool outputs marked _meta.untrusted_excerpts:true (OWASP MCP03/MCP06)
453
+ // because they may contain text from scanned files, which is adversary-
454
+ // controlled in any context where the agent might read malicious code.
455
+ // - Secret-shaped strings redacted on the way out (OWASP MCP01/MCP10).
456
+ // - `apply_fix` requires confirm:true, valid HMAC signature on
457
+ // last-scan.json, non-shadow finding, and confined file path.
458
+
459
+
460
+
461
+
462
+
463
+
464
+
465
+
466
+
467
+
468
+
469
+ // Lazy-loaded: these transitively pull in npm packages (fast-glob,
470
+ // @babel/core) that aren't available in the plugin-cache install path
471
+ // (no node_modules). Deferring keeps the MCP server bootable everywhere;
472
+ // the import only runs when a tool that needs them is actually called.
473
+ let _runScan;
474
+ async function getRunScan() {
475
+ if (!_runScan) _runScan = (await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 9099))).runScan;
476
+ return _runScan;
477
+ }
478
+ let _verifyFixCore;
479
+ async function getVerifyFixCore() {
480
+ if (!_verifyFixCore) _verifyFixCore = (await __webpack_require__.e(/* import() */ 838).then(__webpack_require__.bind(__webpack_require__, 7838))).verifyFix;
481
+ return _verifyFixCore;
482
+ }
483
+
484
+ const MAX_FILES_PER_SCAN = 1024;
485
+ const MAX_FILE_BYTES = 500_000;
486
+ const MAX_TOTAL_SCAN_BYTES = 50_000_000;
487
+ const META = { source: 'agentic-security-mcp', untrusted_excerpts: true };
488
+
489
+ // OWASP A01 — refuse writes to paths that could subvert the security tool
490
+ // itself or the host's source-control / dependency state. A forged finding
491
+ // could otherwise tell apply_fix to overwrite our own rules.yml, our audit
492
+ // log, a .git/hooks/post-commit payload, a CI workflow, an IaC file, or a
493
+ // dependency manifest (premortem #3 expansion).
494
+ //
495
+ // Two kinds of guard:
496
+ // - DIR-prefix matches anywhere under one of these directories
497
+ // - FILE-suffix matches any path whose basename ends with one of these
498
+ const RESERVED_WRITE_PREFIXES = [
499
+ '.git/',
500
+ '.github/',
501
+ '.gitlab/',
502
+ '.circleci/',
503
+ '.buildkite/',
504
+ '.agentic-security/',
505
+ 'node_modules/',
506
+ '.terraform/',
507
+ '.aws/',
508
+ 'k8s/',
509
+ 'kubernetes/',
510
+ ];
511
+ const RESERVED_WRITE_BASENAMES = new Set([
512
+ 'Dockerfile',
513
+ 'Jenkinsfile',
514
+ '.gitlab-ci.yml',
515
+ '.gitlab-ci.yaml',
516
+ 'package.json',
517
+ 'package-lock.json',
518
+ 'yarn.lock',
519
+ 'pnpm-lock.yaml',
520
+ 'pyproject.toml',
521
+ 'Pipfile',
522
+ 'Pipfile.lock',
523
+ 'poetry.lock',
524
+ 'requirements.txt',
525
+ 'go.mod',
526
+ 'go.sum',
527
+ 'Cargo.toml',
528
+ 'Cargo.lock',
529
+ 'composer.json',
530
+ 'composer.lock',
531
+ 'Gemfile',
532
+ 'Gemfile.lock',
533
+ 'pom.xml',
534
+ 'build.gradle',
535
+ 'build.gradle.kts',
536
+ ]);
537
+ const RESERVED_WRITE_SUFFIXES = [
538
+ '.tf',
539
+ '.tfvars',
540
+ 'docker-compose.yml',
541
+ 'docker-compose.yaml',
542
+ ];
543
+ function _isReservedWritePath(sessionRoot, absFile) {
544
+ // Resolve sessionRoot symlinks so the relative path is computed against
545
+ // the same canonical root as `absFile` (which _confine already realpath'd).
546
+ // On macOS /tmp → /private/tmp; without this normalization the relative
547
+ // would contain "../" and the prefix check would miss the reserved path.
548
+ const rootReal = external_node_fs_.realpathSync(external_node_path_.resolve(sessionRoot));
549
+ const rel = external_node_path_.relative(rootReal, absFile).replace(/\\/g, '/');
550
+ if (RESERVED_WRITE_PREFIXES.some(p => rel === p.replace(/\/$/, '') || rel.startsWith(p))) return true;
551
+ const base = rel.split('/').pop() || '';
552
+ if (RESERVED_WRITE_BASENAMES.has(base)) return true;
553
+ if (RESERVED_WRITE_SUFFIXES.some(s => base === s || base.endsWith(s))) return true;
554
+ return false;
555
+ }
556
+
557
+ // LangChain harness-anatomy recommendation: the filesystem is the right
558
+ // collaboration / scratchpad surface for subagents. We carve out one writable
559
+ // directory inside the otherwise-reserved `.agentic-security/` tree —
560
+ // `.agentic-security/agent-scratchpad/<agent>/<session>/` — and expose
561
+ // `append_scratchpad` / `read_scratchpad` for in-progress agent state.
562
+ //
563
+ // Confinement rules:
564
+ // - relative path required (no absolute / no `..`)
565
+ // - must start with `agent-scratchpad/<agent>/<session>/`
566
+ // - `<agent>` and `<session>` are restricted to `[A-Za-z0-9_.-]{1,64}`
567
+ // (no slashes — keeps the prefix exactly three components deep)
568
+ // - file basename: same charset rules
569
+ // - max scratchpad bytes per file: SCRATCHPAD_MAX_FILE_BYTES
570
+ const SCRATCHPAD_PREFIX = '.agentic-security/agent-scratchpad/';
571
+ const SCRATCHPAD_NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
572
+ const SCRATCHPAD_MAX_FILE_BYTES = 2 * 1024 * 1024; // 2 MB per file
573
+ const SCRATCHPAD_MAX_TOTAL_BYTES = 50 * 1024 * 1024; // 50 MB per scan root
574
+
575
+ function _validateScratchpadPath(relPath) {
576
+ if (typeof relPath !== 'string' || !relPath.length) {
577
+ return { ok: false, reason: 'path: not a string' };
578
+ }
579
+ if (external_node_path_.isAbsolute(relPath)) return { ok: false, reason: 'path: must be relative' };
580
+ if (relPath.includes('..')) return { ok: false, reason: 'path: must not contain ..' };
581
+ const normalized = relPath.replace(/\\/g, '/');
582
+ if (!normalized.startsWith(SCRATCHPAD_PREFIX)) {
583
+ return { ok: false, reason: `path: must start with "${SCRATCHPAD_PREFIX}"` };
584
+ }
585
+ const rest = normalized.slice(SCRATCHPAD_PREFIX.length);
586
+ const parts = rest.split('/');
587
+ if (parts.length < 3) {
588
+ return { ok: false, reason: 'path: must be agent-scratchpad/<agent>/<session>/<file>' };
589
+ }
590
+ const [agent, session, ...fileParts] = parts;
591
+ if (!SCRATCHPAD_NAME_RE.test(agent)) return { ok: false, reason: `path: agent name "${agent}" not in [A-Za-z0-9_.-]{1,64}` };
592
+ if (!SCRATCHPAD_NAME_RE.test(session)) return { ok: false, reason: `path: session id "${session}" not in [A-Za-z0-9_.-]{1,64}` };
593
+ for (const p of fileParts) {
594
+ if (!SCRATCHPAD_NAME_RE.test(p)) return { ok: false, reason: `path: file part "${p}" not in [A-Za-z0-9_.-]{1,64}` };
595
+ }
596
+ return { ok: true, agent, session, fileParts };
597
+ }
598
+
599
+ function _scratchpadAbs(sessionRoot, relPath) {
600
+ return external_node_path_.resolve(sessionRoot, relPath.replace(/\\/g, '/'));
601
+ }
602
+
603
+ function _scratchpadTotalBytes(sessionRoot) {
604
+ const base = external_node_path_.join(sessionRoot, '.agentic-security', 'agent-scratchpad');
605
+ if (!external_node_fs_.existsSync(base)) return 0;
606
+ let total = 0;
607
+ const walk = (dir) => {
608
+ let entries;
609
+ try { entries = external_node_fs_.readdirSync(dir, { withFileTypes: true }); } catch { return; }
610
+ for (const e of entries) {
611
+ const fp = external_node_path_.join(dir, e.name);
612
+ try {
613
+ if (e.isFile()) { total += external_node_fs_.statSync(fp).size; }
614
+ else if (e.isDirectory()) walk(fp);
615
+ } catch { /* skip */ }
616
+ }
617
+ };
618
+ walk(base);
619
+ return total;
620
+ }
621
+
622
+ // ─── Path confinement ────────────────────────────────────────────────────────
623
+ // Lexical check + lstat symlink reject + realpath re-check. OWASP MCP05.
624
+ //
625
+ // For non-existent paths (apply_fix to a new file is a possible legitimate
626
+ // case; in practice we re-check existence at the use-site) we walk up the
627
+ // deepest existing ancestor and realpath that, so a parent-symlink can't
628
+ // silently relocate writes.
629
+ function _confine(sessionRoot, candidate, label) {
630
+ if (typeof candidate !== 'string' || !candidate) throw new Error(`${label}: not a string`);
631
+ const rootReal = external_node_fs_.realpathSync(external_node_path_.resolve(sessionRoot));
632
+ const abs = external_node_path_.isAbsolute(candidate) ? candidate : external_node_path_.resolve(rootReal, candidate);
633
+
634
+ // Lexical pre-check: rejects "../../etc/passwd" before any fs call.
635
+ const relLex = external_node_path_.relative(rootReal, external_node_path_.resolve(abs));
636
+ if (relLex === '' || relLex.startsWith('..') || external_node_path_.isAbsolute(relLex)) {
637
+ throw new Error(`${label}: path "${candidate}" escapes session root`);
638
+ }
639
+
640
+ // If the path exists, the leaf must not be a symlink and its realpath
641
+ // must still be under rootReal.
642
+ if (external_node_fs_.existsSync(abs)) {
643
+ if (external_node_fs_.lstatSync(abs).isSymbolicLink()) {
644
+ throw new Error(`${label}: path "${candidate}" is a symbolic link (refused)`);
645
+ }
646
+ const real = external_node_fs_.realpathSync(abs);
647
+ if (external_node_path_.relative(rootReal, real).startsWith('..')) {
648
+ throw new Error(`${label}: path "${candidate}" resolves outside session root via symlink`);
649
+ }
650
+ return real;
651
+ }
652
+
653
+ // Path doesn't exist — walk up to the deepest existing ancestor and
654
+ // realpath that. If a parent dir is a symlink pointing outside rootReal
655
+ // we catch it here.
656
+ let parent = external_node_path_.dirname(abs);
657
+ while (parent !== external_node_path_.dirname(parent) && !external_node_fs_.existsSync(parent)) {
658
+ parent = external_node_path_.dirname(parent);
659
+ }
660
+ const parentReal = external_node_fs_.realpathSync(parent);
661
+ if (external_node_path_.relative(rootReal, parentReal).startsWith('..')) {
662
+ throw new Error(`${label}: path "${candidate}" parent resolves outside session root`);
663
+ }
664
+ const suffix = external_node_path_.relative(parent, abs);
665
+ return external_node_path_.resolve(parentReal, suffix);
666
+ }
667
+
668
+ function _readLastScanVerified(sessionRoot, { allowUnsigned = false } = {}) {
669
+ const stateDir = external_node_path_.join(sessionRoot, '.agentic-security');
670
+ const scanFile = external_node_path_.join(stateDir, 'last-scan.json');
671
+ const sigFile = scanFile + '.sig';
672
+ if (!external_node_fs_.existsSync(scanFile)) return { scan: null, status: 'missing' };
673
+ const body = external_node_fs_.readFileSync(scanFile, 'utf8');
674
+ const ok = (0,integrity/* verifyLastScan */.Ef)(body, sigFile);
675
+ if (ok === false) return { scan: null, status: 'tampered' };
676
+ if (ok === null && !allowUnsigned) return { scan: null, status: 'unsigned' };
677
+ let parsed;
678
+ try { parsed = JSON.parse(body); }
679
+ catch { return { scan: null, status: 'unparseable' }; }
680
+ return { scan: parsed, status: ok ? 'verified' : 'unsigned' };
681
+ }
682
+
683
+ function _findById(scan, id) {
684
+ if (!scan) return null;
685
+ return (scan.findings || []).find(f => f.id === id)
686
+ || (scan.secrets || []).find(f => f.id === id)
687
+ || (scan.supplyChain || []).find(f => f.id === id)
688
+ || (scan.logicVulns || []).find(f => f.id === id)
689
+ || null;
690
+ }
691
+
692
+ // ─── Tool-output offloading (harness-anatomy #1) ────────────────────────────
693
+ // LangChain post: "the harness keeps the head and tail tokens of tool outputs
694
+ // above a threshold number of tokens and offloads the full output to the
695
+ // filesystem." We apply this to any MCP tool response whose findings array
696
+ // exceeds OFFLOAD_THRESHOLD entries: write the full list to a scratchpad
697
+ // file, return only head[0..3] + tail[-2..] + total + path. The agent can
698
+ // call `read_scratchpad(path)` to page through the rest.
699
+ //
700
+ // Design choices:
701
+ // - Threshold is conservative (10) — anything bigger than a casual UI page
702
+ // gets offloaded. Tunable via $AGENTIC_SECURITY_MCP_OFFLOAD_THRESHOLD.
703
+ // - Offload location is the agent-scratchpad (not a separate dir) so the
704
+ // same cleanup + size caps apply.
705
+ // - File names are deterministic per response (sha256 of JSON.stringify)
706
+ // so two identical responses share the same offload file.
707
+ // - The session id is process.pid + boot timestamp short hash — collides
708
+ // only across restarts within a millisecond, which is fine for cache.
709
+ const OFFLOAD_THRESHOLD = (() => {
710
+ const v = parseInt(process.env.AGENTIC_SECURITY_MCP_OFFLOAD_THRESHOLD || '10', 10);
711
+ return Number.isFinite(v) && v >= 1 ? v : 10;
712
+ })();
713
+ const MCP_SESSION_ID = `${process.pid}-${Date.now().toString(36).slice(-6)}`;
714
+
715
+ function _maybeOffload(sessionRoot, toolName, items) {
716
+ if (!Array.isArray(items) || items.length <= OFFLOAD_THRESHOLD) {
717
+ return { offloaded: false, items, total: items.length };
718
+ }
719
+ const head = items.slice(0, 3);
720
+ const tail = items.slice(-2);
721
+ const json = JSON.stringify({ tool: toolName, total: items.length, items }, null, 2);
722
+ const hashShort = external_node_crypto_.createHash('sha256').update(json).digest('hex').slice(0, 10);
723
+ const rel = `.agentic-security/agent-scratchpad/mcp-offload/${MCP_SESSION_ID}/${toolName}-${hashShort}.json`;
724
+ const abs = external_node_path_.resolve(sessionRoot, rel);
725
+ try {
726
+ external_node_fs_.mkdirSync(external_node_path_.dirname(abs), { recursive: true });
727
+ external_node_fs_.writeFileSync(abs, json);
728
+ } catch (e) {
729
+ // If we can't write to disk for some reason, fall back to returning
730
+ // everything — the alternative would be silently dropping data, which
731
+ // is worse than blowing the context.
732
+ return { offloaded: false, items, total: items.length, offloadError: e.message };
733
+ }
734
+ return {
735
+ offloaded: true,
736
+ head, tail, total: items.length,
737
+ scratchpadPath: rel,
738
+ pagingHint: `call read_scratchpad({ path: "${rel}", offset, limit }) to page through; the file is { tool, total, items: [...] } JSON`,
739
+ };
740
+ }
741
+
742
+ // ─── scan_diff ───────────────────────────────────────────────────────────────
743
+ const scan_diff = {
744
+ name: 'scan_diff',
745
+ description: 'Scan a list of files for security findings. Use BEFORE writing a Write/Edit to disk so the agent can self-correct. Returns findings with severity, file:line, title, remediation. Snippets are redacted of obvious secret patterns. Paths confined to the session root; symlinks are refused.',
746
+ inputSchema: {
747
+ type: 'object',
748
+ additionalProperties: false,
749
+ properties: {
750
+ files: {
751
+ type: 'array', minItems: 1, maxItems: MAX_FILES_PER_SCAN,
752
+ items: { type: 'string', minLength: 1, maxLength: 4096 },
753
+ },
754
+ severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },
755
+ },
756
+ required: ['files'],
757
+ },
758
+ async handler({ files, severity }, ctx) {
759
+ const sessionRoot = ctx.sessionRoot;
760
+ const abs = files.map(f => _confine(sessionRoot, f, 'files[]'));
761
+
762
+ const fileContents = {};
763
+ let totalBytes = 0;
764
+ for (const a of abs) {
765
+ let stat;
766
+ try { stat = external_node_fs_.statSync(a); } catch { continue; }
767
+ if (!stat.isFile()) continue;
768
+ if (stat.size > MAX_FILE_BYTES) continue;
769
+ totalBytes += stat.size;
770
+ if (totalBytes > MAX_TOTAL_SCAN_BYTES) {
771
+ throw new Error(`scan_diff: total scan size exceeds ${MAX_TOTAL_SCAN_BYTES} bytes`);
772
+ }
773
+ let content;
774
+ try { content = external_node_fs_.readFileSync(a, 'utf8'); } catch { continue; }
775
+ const rel = external_node_path_.relative(sessionRoot, a).replace(/\\/g, '/');
776
+ fileContents[rel] = content;
777
+ }
778
+
779
+ const runScan = await getRunScan();
780
+ const result = await runScan(sessionRoot, { network: false, fileContents });
781
+ const wantSet = new Set(Object.keys(fileContents));
782
+ const sevRank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
783
+ const min = sevRank[severity] ?? 0;
784
+ const findings = (result.scan.findings || [])
785
+ .filter(f => wantSet.has(String(f.file || '').replace(/\\/g, '/')) && (sevRank[f.severity] ?? 0) >= min)
786
+ .map(f => redactFinding({
787
+ id: f.id, severity: f.severity, file: f.file, line: f.line,
788
+ title: f.title || f.vuln, cwe: f.cwe,
789
+ description: f.description, remediation: f.remediation,
790
+ }));
791
+ // Harness-anatomy #1: offload when the result exceeds OFFLOAD_THRESHOLD.
792
+ // The agent gets a head+tail preview plus a path it can page through;
793
+ // the full finding list lives on disk. This is the documented fix for
794
+ // "context rot" — large tool outputs eat the model's attention budget.
795
+ const off = _maybeOffload(sessionRoot, 'scan_diff', findings);
796
+ if (off.offloaded) {
797
+ return {
798
+ _meta: META,
799
+ scannedFiles: Object.keys(fileContents).length,
800
+ findingCount: off.total,
801
+ offloaded: true,
802
+ head: off.head, tail: off.tail,
803
+ scratchpadPath: off.scratchpadPath,
804
+ pagingHint: off.pagingHint,
805
+ };
806
+ }
807
+ return {
808
+ _meta: META,
809
+ scannedFiles: Object.keys(fileContents).length,
810
+ findingCount: findings.length,
811
+ findings,
812
+ };
813
+ },
814
+ };
815
+
816
+ // ─── query_taint ─────────────────────────────────────────────────────────────
817
+ const query_taint = {
818
+ name: 'query_taint',
819
+ description: 'Query whether the last verified scan found a taint path involving a given source and sink. Paginated — returns up to `limit` matches (default 10, max 50) starting at `offset` (default 0); set `truncated:true` and `totalMatches` tell you when to page.',
820
+ inputSchema: {
821
+ type: 'object',
822
+ additionalProperties: false,
823
+ properties: {
824
+ source: { type: 'string', minLength: 1, maxLength: 256 },
825
+ sink: { type: 'string', minLength: 1, maxLength: 256 },
826
+ limit: { type: 'integer', minimum: 1, maximum: 50 },
827
+ offset: { type: 'integer', minimum: 0, maximum: 10000 },
828
+ },
829
+ required: ['source', 'sink'],
830
+ },
831
+ async handler({ source, sink, limit, offset }, ctx) {
832
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
833
+ if (!scan) {
834
+ return { _meta: META, hasResult: false, status, message: `No usable scan state (${status}).` };
835
+ }
836
+ const lim = Number.isInteger(limit) ? Math.min(50, Math.max(1, limit)) : 10;
837
+ const off = Number.isInteger(offset) ? Math.max(0, offset) : 0;
838
+ const srcL = String(source).toLowerCase();
839
+ const sinkL = String(sink).toLowerCase();
840
+ // Filter first (cheap), then paginate (so totalMatches is accurate).
841
+ // Harness-engineering note (post-derived): "context window != context
842
+ // attention." Returning hundreds of matches to the agent in one shot
843
+ // dilutes its reasoning; the agent receives a bounded slice plus the
844
+ // cursor to fetch the rest if it wants.
845
+ const all = (scan.findings || []).filter(f => {
846
+ const hay = [f.description, f.title, f.vuln, f.snippet, JSON.stringify(f.trace || '')].join(' ').toLowerCase();
847
+ return hay.includes(srcL) && hay.includes(sinkL);
848
+ });
849
+ const page = all.slice(off, off + lim).map(f => redactFinding({
850
+ id: f.id, severity: f.severity, file: f.file, line: f.line,
851
+ title: f.title || f.vuln, description: f.description,
852
+ trace: f.trace || null,
853
+ }));
854
+ return {
855
+ _meta: META,
856
+ hasResult: true,
857
+ integrity: status,
858
+ scanStartedAt: scan.startedAt || scan.meta?.startedAt || null,
859
+ totalMatches: all.length,
860
+ matchCount: page.length,
861
+ offset: off,
862
+ limit: lim,
863
+ truncated: off + page.length < all.length,
864
+ nextOffset: off + page.length < all.length ? off + page.length : null,
865
+ matches: page,
866
+ };
867
+ },
868
+ };
869
+
870
+ // ─── explain_finding ─────────────────────────────────────────────────────────
871
+ const explain_finding = {
872
+ name: 'explain_finding',
873
+ description: 'Return full details for a single finding from the last verified scan. Snippet/description redacted of secret patterns.',
874
+ inputSchema: {
875
+ type: 'object',
876
+ additionalProperties: false,
877
+ properties: {
878
+ finding_id: { type: 'string', minLength: 1, maxLength: 256 },
879
+ },
880
+ required: ['finding_id'],
881
+ },
882
+ async handler({ finding_id }, ctx) {
883
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
884
+ if (!scan) throw new Error(`No usable scan state (${status}).`);
885
+ const f = _findById(scan, finding_id);
886
+ if (!f) throw new Error(`Finding not found: ${finding_id}`);
887
+ const redacted = redactFinding({
888
+ id: f.id, severity: f.severity, file: f.file, line: f.line,
889
+ title: f.title || f.vuln, cwe: f.cwe,
890
+ description: f.description, remediation: f.remediation,
891
+ snippet: f.snippet || null,
892
+ trace: f.trace || null,
893
+ });
894
+ // Harness-anatomy #1: explain_finding's trace is the most-likely-large
895
+ // field on a single finding. Offload when it crosses the threshold so
896
+ // the agent gets a head/tail preview, not a 50-step trace dumped into
897
+ // its context.
898
+ let traceTrimmed = redacted.trace;
899
+ let traceMeta = null;
900
+ if (Array.isArray(redacted.trace) && redacted.trace.length > OFFLOAD_THRESHOLD) {
901
+ const off = _maybeOffload(ctx.sessionRoot, 'explain_finding-trace', redacted.trace);
902
+ if (off.offloaded) {
903
+ traceTrimmed = [...off.head, { _gap: `... ${off.total - off.head.length - off.tail.length} more steps elided; read scratchpad ...` }, ...off.tail];
904
+ traceMeta = {
905
+ totalSteps: off.total,
906
+ scratchpadPath: off.scratchpadPath,
907
+ pagingHint: off.pagingHint,
908
+ };
909
+ }
910
+ }
911
+ return {
912
+ _meta: META,
913
+ ...redacted,
914
+ trace: traceTrimmed,
915
+ traceOffload: traceMeta,
916
+ confidence: f.confidence ?? null,
917
+ hasReplacementFix: typeof f.fix?.replacement === 'string',
918
+ integrity: status,
919
+ // Risk-signal passthrough so agents can decide priority without
920
+ // re-reading last-scan.json or re-fetching OSV/KEV/EPSS. compositeRisk
921
+ // is the canonical sort key; the other fields are its provenance.
922
+ compositeRisk: f.compositeRisk ?? null,
923
+ compositeRiskTier: f.compositeRiskTier ?? null,
924
+ compositeRiskFactors: Array.isArray(f.compositeRiskFactors) ? f.compositeRiskFactors : [],
925
+ exploitability: f.exploitability ?? null,
926
+ exploitabilityTier: f.exploitabilityTier ?? null,
927
+ mitigationVerdict: f.mitigationVerdict ?? null,
928
+ kev: !!(f.kev || f.kevListed || f.weaponized),
929
+ epssScore: typeof f.epssScore === 'number' ? f.epssScore : null,
930
+ epssPercentile: typeof f.epssPercentile === 'number' ? f.epssPercentile : null,
931
+ exploitedNow: !!f.exploitedNow,
932
+ };
933
+ },
934
+ };
935
+
936
+ // ─── apply_fix ───────────────────────────────────────────────────────────────
937
+ const apply_fix = {
938
+ name: 'apply_fix',
939
+ description: 'Apply a fix for a finding. Two modes: (1) the stored fix.replacement, or (2) a caller-supplied `patch` (a files map) which is RE-VERIFIED inline (rescan-clean + no new ≥medium + lint) before any write — this unblocks findings that ship only a template or description. Refuses if last-scan.json fails its HMAC check, if the finding is shadow-marked, or if a path escapes the session root via lexical traversal OR a symlink. Requires confirm:true. Supports dry_run:true to preview without writing.',
940
+ inputSchema: {
941
+ type: 'object',
942
+ additionalProperties: false,
943
+ properties: {
944
+ finding_id: { type: 'string', minLength: 1, maxLength: 256 },
945
+ confirm: { type: 'boolean' },
946
+ dry_run: { type: 'boolean' },
947
+ patch: {
948
+ type: 'object',
949
+ additionalProperties: { type: 'string', maxLength: 500_000 },
950
+ minProperties: 1, maxProperties: 8,
951
+ },
952
+ },
953
+ required: ['finding_id', 'confirm'],
954
+ },
955
+ async handler({ finding_id, confirm, dry_run = false, patch = null }, ctx) {
956
+ if (confirm !== true) {
957
+ return { _meta: META, applied: false, reason: 'apply_fix requires confirm: true.' };
958
+ }
959
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
960
+ if (!scan) {
961
+ return { _meta: META, applied: false, reason: `last-scan.json failed integrity check: ${status}. Run a fresh scan.` };
962
+ }
963
+ const f = _findById(scan, finding_id);
964
+ if (!f) return { _meta: META, applied: false, reason: `Finding not found: ${finding_id}` };
965
+ if (f._shadow === true) {
966
+ return { _meta: META, applied: false, reason: 'shadow findings cannot be auto-applied' };
967
+ }
968
+
969
+ // #3 — verifier-approved patch path. When the caller supplies `patch` (a
970
+ // files map, same shape as verify_fix), apply_fix re-runs the verifier
971
+ // INLINE and writes only if it passes: the original finding's stableId is
972
+ // gone, no new ≥medium finding was introduced, and lint is clean. This lets
973
+ // a deterministic OR LLM-synthesized patch be applied for the ~100% of
974
+ // findings that ship only a template/description (no stored fix.replacement).
975
+ // Security: all existing gates hold (confirm, last-scan HMAC, reserved
976
+ // paths, confinement, fix-history backup + attempt budget); the write is
977
+ // additionally gated on a FRESH verification, so a stale/forged patch can't
978
+ // slip through — there is no token to replay, the verify runs here and now.
979
+ if (patch && typeof patch === 'object' && Object.keys(patch).length) {
980
+ if (!f.stableId) {
981
+ return { _meta: META, applied: false, reason: 'finding has no stableId — cannot verify a patch against it' };
982
+ }
983
+ const confinedAbs = {};
984
+ for (const [rel, content] of Object.entries(patch)) {
985
+ let abs;
986
+ try { abs = _confine(ctx.sessionRoot, rel, 'patch key'); }
987
+ catch (e) { return { _meta: META, applied: false, reason: `path-escape refused: ${e.message}` }; }
988
+ if (_isReservedWritePath(ctx.sessionRoot, abs)) {
989
+ return { _meta: META, applied: false, reason: `reserved path refused: ${rel}` };
990
+ }
991
+ confinedAbs[rel] = { abs, content: String(content) };
992
+ }
993
+ // Inline re-verify — the load-bearing gate. Must pass to write.
994
+ let verdict;
995
+ try {
996
+ const verifyFixCore = await getVerifyFixCore();
997
+ verdict = await verifyFixCore({
998
+ scanRoot: ctx.sessionRoot,
999
+ originalFindingStableId: f.stableId,
1000
+ files: Object.fromEntries(Object.entries(confinedAbs).map(([rel, v]) => [rel, v.content])),
1001
+ });
1002
+ } catch (e) {
1003
+ return { _meta: META, applied: false, reason: `patch verification failed: ${e.message}` };
1004
+ }
1005
+ if (!verdict.ok) {
1006
+ return {
1007
+ _meta: META, applied: false,
1008
+ reason: `patch rejected by verifier: ${verdict.summary || verdict.rescan?.reason || 'did not verify'}`,
1009
+ verify: { rescan: verdict.rescan, lint: { runner: verdict.lint?.runner, ok: verdict.lint?.ok } },
1010
+ };
1011
+ }
1012
+ if (dry_run) {
1013
+ return { _meta: META, applied: false, dryRun: true, verified: true, files: Object.keys(confinedAbs), summary: verdict.summary };
1014
+ }
1015
+ const written = [];
1016
+ try {
1017
+ for (const [rel, v] of Object.entries(confinedAbs)) {
1018
+ const originalContent = external_node_fs_.existsSync(v.abs) ? await promises_.readFile(v.abs, 'utf8') : '';
1019
+ const entry = await (0,fix_history/* applyFix */.oM)({
1020
+ scanRoot: ctx.sessionRoot, file: rel, originalContent, newContent: v.content,
1021
+ findingId: f.id, stableId: f.stableId, ruleId: f.rule || null, vuln: f.vuln || f.title || null,
1022
+ });
1023
+ written.push({ file: rel, historyId: entry.id, backupPath: entry.backupPath });
1024
+ }
1025
+ } catch (e) {
1026
+ if (e && e.name === 'FixAttemptBudgetExceededError') {
1027
+ return { _meta: META, applied: false, reason: `budget-exceeded: ${e.message}`, budgetExceeded: true, attempts: e.attempts, maxAttempts: e.max, key: e.key };
1028
+ }
1029
+ throw e;
1030
+ }
1031
+ let acceptance = null;
1032
+ try { acceptance = (0,fix_history/* fixAcceptanceRate */.XR)(ctx.sessionRoot); } catch { /* best-effort */ }
1033
+ return { _meta: META, applied: true, verified: true, patched: written, integrity: status, verify: { summary: verdict.summary }, acceptance };
1034
+ }
1035
+
1036
+ if (typeof f.fix?.replacement !== 'string') {
1037
+ // Premortem #2: templates are patch-shaped text. Same reasoning as
1038
+ // the replacement path — do NOT pass through redactString here.
1039
+ return {
1040
+ _meta: META, applied: false,
1041
+ reason: 'No full replacement available — only a template. Apply the template manually.',
1042
+ template: f.fix?.code || '',
1043
+ file: f.file, line: f.line,
1044
+ };
1045
+ }
1046
+ let absFile;
1047
+ try { absFile = _confine(ctx.sessionRoot, f.file, 'finding.file'); }
1048
+ catch (e) {
1049
+ return { _meta: META, applied: false, reason: `path-escape refused: ${e.message}` };
1050
+ }
1051
+ if (_isReservedWritePath(ctx.sessionRoot, absFile)) {
1052
+ return { _meta: META, applied: false, reason: `reserved path refused: writes to .git/, .agentic-security/, or node_modules/ are not permitted via apply_fix` };
1053
+ }
1054
+ if (!external_node_fs_.existsSync(absFile)) {
1055
+ return { _meta: META, applied: false, reason: `File not found: ${absFile}` };
1056
+ }
1057
+ const originalContent = await promises_.readFile(absFile, 'utf8');
1058
+
1059
+ if (dry_run) {
1060
+ return {
1061
+ _meta: META,
1062
+ applied: false, dryRun: true,
1063
+ file: f.file,
1064
+ originalSize: originalContent.length,
1065
+ newSize: f.fix.replacement.length,
1066
+ diffSummary: `${originalContent.length} → ${f.fix.replacement.length} bytes`,
1067
+ };
1068
+ }
1069
+
1070
+ let entry;
1071
+ try {
1072
+ entry = await (0,fix_history/* applyFix */.oM)({
1073
+ scanRoot: ctx.sessionRoot,
1074
+ file: f.file,
1075
+ originalContent,
1076
+ newContent: f.fix.replacement,
1077
+ findingId: f.id,
1078
+ stableId: f.stableId || null, // premortem 4R-8
1079
+ ruleId: f.rule || null,
1080
+ vuln: f.vuln || f.title || null,
1081
+ });
1082
+ } catch (e) {
1083
+ // Harness-engineering: step-budget refusal (post-derived). The
1084
+ // deterministic layer enforces at-most-N attempts per stableId. When
1085
+ // exceeded, surface it as a structured `budget-exceeded` outcome the
1086
+ // agent can recognize — not a generic error.
1087
+ if (e && e.name === 'FixAttemptBudgetExceededError') {
1088
+ return {
1089
+ _meta: META,
1090
+ applied: false,
1091
+ reason: `budget-exceeded: ${e.message}`,
1092
+ budgetExceeded: true,
1093
+ attempts: e.attempts,
1094
+ maxAttempts: e.max,
1095
+ key: e.key,
1096
+ };
1097
+ }
1098
+ throw e;
1099
+ }
1100
+ // R25 (PRD §5): surface the running auto-fix acceptance rate after each
1101
+ // applied fix, so the closed loop reports its own success metric.
1102
+ let acceptance = null;
1103
+ try { acceptance = (0,fix_history/* fixAcceptanceRate */.XR)(ctx.sessionRoot); } catch { /* metric is best-effort */ }
1104
+ return { _meta: META, applied: true, historyId: entry.id, file: f.file, backupPath: entry.backupPath, integrity: status, attemptOrdinal: entry.attemptOrdinal, acceptance };
1105
+ },
1106
+ };
1107
+
1108
+ // ─── verify_fix ──────────────────────────────────────────────────────────────
1109
+ // Closed-loop verification of a proposed patch BEFORE the agent applies it.
1110
+ // Re-scans the patched files in-memory (no disk write), confirms the original
1111
+ // stableId is gone, and runs the project's existing linter on the patched
1112
+ // files. Returns a structured verdict the agent can use to decide whether to
1113
+ // proceed with apply_fix.
1114
+ const verify_fix = {
1115
+ name: 'verify_fix',
1116
+ description: 'Verify a proposed patch before applying. Re-scans the patched files in memory and runs the project linter. Returns { ok, rescan, lint, summary }. No filesystem writes.',
1117
+ inputSchema: {
1118
+ type: 'object',
1119
+ additionalProperties: false,
1120
+ properties: {
1121
+ stable_id: { type: 'string', minLength: 8, maxLength: 64 },
1122
+ files: {
1123
+ type: 'object',
1124
+ additionalProperties: { type: 'string', maxLength: 500_000 },
1125
+ minProperties: 1,
1126
+ maxProperties: 8,
1127
+ },
1128
+ },
1129
+ required: ['stable_id', 'files'],
1130
+ },
1131
+ async handler({ stable_id, files }, ctx) {
1132
+ // Confine every file path before passing to the verifier.
1133
+ const confined = {};
1134
+ for (const [relPath, content] of Object.entries(files || {})) {
1135
+ try {
1136
+ _confine(ctx.sessionRoot, relPath, 'files key');
1137
+ } catch (e) {
1138
+ return { _meta: META, ok: false, reason: `path-escape refused: ${e.message}` };
1139
+ }
1140
+ confined[relPath] = String(content);
1141
+ }
1142
+ try {
1143
+ const verifyFixCore = await getVerifyFixCore();
1144
+ const r = await verifyFixCore({
1145
+ scanRoot: ctx.sessionRoot,
1146
+ originalFindingStableId: stable_id,
1147
+ files: confined,
1148
+ });
1149
+ return {
1150
+ _meta: META,
1151
+ ok: r.ok,
1152
+ rescan: { ok: r.rescan.ok, reason: r.rescan.reason, introduced: r.rescan.introduced || [] },
1153
+ lint: { runner: r.lint.runner, ok: r.lint.ok, skipped: r.lint.skipped || false, output: redactString(r.lint.output || '').slice(0, 1500) },
1154
+ summary: r.summary,
1155
+ };
1156
+ } catch (e) {
1157
+ return { _meta: META, ok: false, reason: `verify_fix failed: ${e.message}` };
1158
+ }
1159
+ },
1160
+ };
1161
+
1162
+ // ─── synthesize_fix ──────────────────────────────────────────────────────────
1163
+ // Return the stored fix replacement + regression-test scaffold for a finding,
1164
+ // WITHOUT applying anything. The agent can call verify_fix → apply_fix in
1165
+ // sequence with the returned blob.
1166
+ const synthesize_fix = {
1167
+ name: 'synthesize_fix',
1168
+ description: 'Return the stored fix replacement for a finding (replacement text + remediation + plan if the patch is too large). Read-only; never writes to disk. Use verify_fix → apply_fix to deploy.',
1169
+ inputSchema: {
1170
+ type: 'object',
1171
+ additionalProperties: false,
1172
+ properties: {
1173
+ finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1174
+ },
1175
+ required: ['finding_id'],
1176
+ },
1177
+ async handler({ finding_id }, ctx) {
1178
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
1179
+ if (!scan) {
1180
+ return { _meta: META, ok: false, reason: `last-scan.json failed integrity check: ${status}` };
1181
+ }
1182
+ const f = _findById(scan, finding_id);
1183
+ if (!f) return { _meta: META, ok: false, reason: `Finding not found: ${finding_id}` };
1184
+ if (f._shadow === true) return { _meta: META, ok: false, reason: 'shadow findings have no synthesized fix' };
1185
+ const fix = f.fix || {};
1186
+ const hasReplacement = typeof fix.replacement === 'string' && fix.replacement.length > 0;
1187
+ // Patch bounds: count files touched + LoC delta.
1188
+ let touchedFiles = 1;
1189
+ let locDelta = 0;
1190
+ if (hasReplacement) {
1191
+ let orig = '';
1192
+ try {
1193
+ const abs = _confine(ctx.sessionRoot, f.file, 'finding.file');
1194
+ orig = external_node_fs_.readFileSync(abs, 'utf8');
1195
+ } catch { /* ignore — counts will reflect new-only LoC */ }
1196
+ locDelta = Math.abs(fix.replacement.split('\n').length - orig.split('\n').length);
1197
+ }
1198
+ const oversized = touchedFiles > 3 || locDelta > 100;
1199
+ // #1 — deterministic autofix: for classes with a safe context-independent
1200
+ // swap (weak hash, TLS verify-off), materialize a full-file patch from the
1201
+ // live file. The agent passes `autofix.patch` straight to apply_fix, which
1202
+ // re-verifies it (rescan-clean + no new ≥medium + lint) before writing — so
1203
+ // even a mis-attributed swap can't land a bad edit. No stored replacement,
1204
+ // no per-finding bloat in last-scan.json.
1205
+ let autofix = null;
1206
+ if (!hasReplacement) {
1207
+ try {
1208
+ const abs = _confine(ctx.sessionRoot, f.file, 'finding.file');
1209
+ const det = synthesizeDeterministicPatch(f, external_node_fs_.readFileSync(abs, 'utf8'));
1210
+ if (det) autofix = { deterministic: true, ruleId: det.ruleId, patch: det.patch };
1211
+ } catch { /* best-effort — no file / no rule → no autofix */ }
1212
+ }
1213
+ // Premortem #2: `replacement` is a *patch* (the code we'll write to disk),
1214
+ // not a finding excerpt. Running it through redactString silently corrupts
1215
+ // valid patches whose content happens to match a secret-shape (e.g. a
1216
+ // placeholder like `password = "loadFromEnv"`). Patches MUST pass through
1217
+ // verbatim. Snippet/description/etc. continue to be redacted in
1218
+ // explain_finding / scan_diff — that's the right surface for redaction.
1219
+ return {
1220
+ _meta: META,
1221
+ ok: true,
1222
+ stable_id: f.stableId || null,
1223
+ file: f.file, line: f.line,
1224
+ vuln: f.vuln,
1225
+ severity: f.severity,
1226
+ hasReplacement,
1227
+ replacement: hasReplacement ? fix.replacement : null,
1228
+ template: fix.code || null,
1229
+ autofix,
1230
+ // #15 — the regression test the scan annotator already generated for this
1231
+ // finding (present when a PoC was built). Surfaced here so the fix flow
1232
+ // writes the test alongside the patch; fix-verify-loop then runs it, so an
1233
+ // applied fix ships with a test that fails pre-fix and passes post-fix.
1234
+ regression_test: f.regression_test || null,
1235
+ remediation: typeof fix.description === 'string' ? fix.description : (typeof fix === 'string' ? fix : null),
1236
+ patchBounds: { touchedFiles, locDelta, oversized },
1237
+ recommendsFixPlan: oversized && !hasReplacement && !autofix,
1238
+ };
1239
+ },
1240
+ };
1241
+
1242
+ // ─── find_rule_module ───────────────────────────────────────────────────────
1243
+ // Codebase-navigation helper (C.6). Answers "which file under scanner/src/
1244
+ // implements the detector for CWE-X / family Y" by scanning the SAST and
1245
+ // posture sources for `cwe:` / `family:` literals. Cheaper and more reliable
1246
+ // than asking the agent to grep — premortem note: "grep for a common function
1247
+ // name in a large codebase returns thousands of matches."
1248
+ //
1249
+ // Read-only; no findings consumed. Output is a list of file paths + the
1250
+ // matching literal lines so the agent can verify before editing.
1251
+ const find_rule_module = {
1252
+ name: 'find_rule_module',
1253
+ description: 'Find the file(s) under scanner/src/{sast,posture}/ that emit findings for a given CWE id or family name. Use BEFORE editing a rule — answers "where is the SQL-injection detector?" without grepping the whole tree. Returns at most 20 hits; refine the query if too broad.',
1254
+ inputSchema: {
1255
+ type: 'object',
1256
+ additionalProperties: false,
1257
+ properties: {
1258
+ cwe: { type: 'string', minLength: 5, maxLength: 16 },
1259
+ family: { type: 'string', minLength: 2, maxLength: 64 },
1260
+ },
1261
+ },
1262
+ async handler({ cwe, family }, ctx) {
1263
+ if (!cwe && !family) {
1264
+ return { _meta: META, ok: false, reason: 'provide cwe (e.g. "CWE-89") or family (e.g. "sql-injection")' };
1265
+ }
1266
+ // Pattern enforcement — the mini-schema validator doesn't do `pattern`.
1267
+ if (cwe && !/^CWE-\d+$/.test(cwe)) {
1268
+ return { _meta: META, ok: false, reason: 'cwe must match /^CWE-\\d+$/ (e.g. "CWE-89")' };
1269
+ }
1270
+ if (family && !/^[a-z][a-z0-9-]+$/.test(family)) {
1271
+ return { _meta: META, ok: false, reason: 'family must match /^[a-z][a-z0-9-]+$/ (e.g. "sql-injection")' };
1272
+ }
1273
+ const sessionRoot = ctx.sessionRoot;
1274
+ const roots = [
1275
+ external_node_path_.join(sessionRoot, 'scanner', 'src', 'sast'),
1276
+ external_node_path_.join(sessionRoot, 'scanner', 'src', 'posture'),
1277
+ ];
1278
+ const hits = [];
1279
+ const cweLit = cwe ? new RegExp(`['"\`]${cwe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"\`]`) : null;
1280
+ // Family match is broader on purpose: detectors often emit findings
1281
+ // without an explicit `family:` field (it's backfilled by
1282
+ // posture/finding-defaults.js). We match the family literal anywhere in
1283
+ // the file (vuln-name strings, comments, ids) so e.g. searching for "csrf"
1284
+ // surfaces sast/csrf.js even though it doesn't tag findings with the field.
1285
+ const famLit = family ? new RegExp(`\\b${family.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/-/g, '[-_ ]?')}\\b`, 'i') : null;
1286
+ // Also try a filename-stem match when only family is given.
1287
+ const famFilename = family ? family.toLowerCase() : null;
1288
+ for (const root of roots) {
1289
+ if (!external_node_fs_.existsSync(root)) continue;
1290
+ let entries;
1291
+ try { entries = external_node_fs_.readdirSync(root); } catch { continue; }
1292
+ for (const entry of entries) {
1293
+ if (!entry.endsWith('.js')) continue;
1294
+ const abs = external_node_path_.join(root, entry);
1295
+ let stat;
1296
+ try { stat = external_node_fs_.statSync(abs); } catch { continue; }
1297
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) continue;
1298
+ let body;
1299
+ try { body = external_node_fs_.readFileSync(abs, 'utf8'); } catch { continue; }
1300
+ const lines = body.split('\n');
1301
+ const matches = [];
1302
+ const stem = entry.replace(/\.js$/, '').toLowerCase();
1303
+ const filenameMatchesFamily = famFilename && (stem === famFilename || stem.includes(famFilename));
1304
+ if (filenameMatchesFamily) {
1305
+ matches.push({ line: 1, text: `<filename "${entry}" matches family>`, kind: 'filename' });
1306
+ }
1307
+ for (let i = 0; i < lines.length; i++) {
1308
+ const line = lines[i];
1309
+ if (cweLit && cweLit.test(line)) matches.push({ line: i + 1, text: line.trim().slice(0, 200), kind: 'cwe' });
1310
+ else if (famLit && famLit.test(line)) matches.push({ line: i + 1, text: line.trim().slice(0, 200), kind: 'family' });
1311
+ if (matches.length >= 5) break;
1312
+ }
1313
+ if (matches.length) {
1314
+ hits.push({
1315
+ file: external_node_path_.relative(sessionRoot, abs).replace(/\\/g, '/'),
1316
+ matchCount: matches.length,
1317
+ matches,
1318
+ });
1319
+ if (hits.length >= 20) break;
1320
+ }
1321
+ }
1322
+ if (hits.length >= 20) break;
1323
+ }
1324
+ return {
1325
+ _meta: META,
1326
+ ok: true,
1327
+ query: { cwe: cwe || null, family: family || null },
1328
+ hitCount: hits.length,
1329
+ hits,
1330
+ truncated: hits.length >= 20,
1331
+ };
1332
+ },
1333
+ };
1334
+
1335
+ // ─── append_scratchpad / read_scratchpad ───────────────────────────────────
1336
+ // LangChain harness-anatomy: the filesystem is the durable agent scratchpad.
1337
+ // These tools expose a tightly-confined slice of the project tree for
1338
+ // in-progress agent state: PLAN.md decompositions, offloaded tool outputs,
1339
+ // session notes that survive context resets.
1340
+ //
1341
+ // Confinement (validated in `_validateScratchpadPath`):
1342
+ // ALL paths must start with `.agentic-security/agent-scratchpad/<agent>/<session>/`
1343
+ // and consist of [A-Za-z0-9_.-]{1,64} path components — no `..`, no
1344
+ // absolute paths, no shell metacharacters. This is the ONE place inside
1345
+ // the otherwise-reserved `.agentic-security/` tree where agents can write.
1346
+ // Limits:
1347
+ // - 2 MB per file (write attempts beyond this are refused).
1348
+ // - 50 MB total across the scratchpad — protects against runaway agents.
1349
+ // Operators who want to clean up: `rm -rf .agentic-security/agent-scratchpad`.
1350
+ //
1351
+ // The post: "Agents can store intermediate outputs and maintain state that
1352
+ // outlasts a single session." This is that mechanism.
1353
+
1354
+ const append_scratchpad = {
1355
+ name: 'append_scratchpad',
1356
+ description: 'Append text to a file under .agentic-security/agent-scratchpad/<agent>/<session>/. The ONLY writable location for in-progress agent state (PLAN.md, notes, offloaded tool outputs, decision logs). Path must start with that prefix; <agent>/<session>/file parts are restricted to [A-Za-z0-9_.-]{1,64}. Caps: 2 MB per file, 50 MB total across the scratchpad.',
1357
+ inputSchema: {
1358
+ type: 'object',
1359
+ additionalProperties: false,
1360
+ properties: {
1361
+ path: { type: 'string', minLength: 1, maxLength: 256 },
1362
+ content: { type: 'string', minLength: 1, maxLength: 256 * 1024 },
1363
+ },
1364
+ required: ['path', 'content'],
1365
+ },
1366
+ async handler({ path: relPath, content }, ctx) {
1367
+ const v = _validateScratchpadPath(relPath);
1368
+ if (!v.ok) return { _meta: META, ok: false, reason: v.reason };
1369
+ const abs = _scratchpadAbs(ctx.sessionRoot, relPath);
1370
+ const total = _scratchpadTotalBytes(ctx.sessionRoot);
1371
+ if (total + content.length > SCRATCHPAD_MAX_TOTAL_BYTES) {
1372
+ return {
1373
+ _meta: META, ok: false,
1374
+ reason: `scratchpad-total-exceeded: ${total} + ${content.length} > ${SCRATCHPAD_MAX_TOTAL_BYTES}. Clean up via "rm -rf .agentic-security/agent-scratchpad" or rotate sessions.`,
1375
+ };
1376
+ }
1377
+ let existing = 0;
1378
+ try { if (external_node_fs_.existsSync(abs)) existing = external_node_fs_.statSync(abs).size; } catch {}
1379
+ if (existing + content.length > SCRATCHPAD_MAX_FILE_BYTES) {
1380
+ return {
1381
+ _meta: META, ok: false,
1382
+ reason: `scratchpad-file-exceeded: ${existing} + ${content.length} > ${SCRATCHPAD_MAX_FILE_BYTES}. Start a new file.`,
1383
+ };
1384
+ }
1385
+ try {
1386
+ external_node_fs_.mkdirSync(external_node_path_.dirname(abs), { recursive: true });
1387
+ external_node_fs_.appendFileSync(abs, content);
1388
+ return {
1389
+ _meta: META, ok: true,
1390
+ path: relPath, bytesWritten: content.length, fileSize: existing + content.length,
1391
+ scratchpadTotal: total + content.length,
1392
+ };
1393
+ } catch (e) {
1394
+ return { _meta: META, ok: false, reason: `write-failed: ${e.message}` };
1395
+ }
1396
+ },
1397
+ };
1398
+
1399
+ const read_scratchpad = {
1400
+ name: 'read_scratchpad',
1401
+ description: 'Read a file under .agentic-security/agent-scratchpad/<agent>/<session>/. Paginated for large files via `offset` (default 0) and `limit` (default 4096 bytes, max 64 KB). Returns bytesRead, truncated, nextOffset for paging.',
1402
+ inputSchema: {
1403
+ type: 'object',
1404
+ additionalProperties: false,
1405
+ properties: {
1406
+ path: { type: 'string', minLength: 1, maxLength: 256 },
1407
+ offset: { type: 'integer', minimum: 0, maximum: 100 * 1024 * 1024 },
1408
+ limit: { type: 'integer', minimum: 1, maximum: 64 * 1024 },
1409
+ },
1410
+ required: ['path'],
1411
+ },
1412
+ async handler({ path: relPath, offset, limit }, ctx) {
1413
+ const v = _validateScratchpadPath(relPath);
1414
+ if (!v.ok) return { _meta: META, ok: false, reason: v.reason };
1415
+ const abs = _scratchpadAbs(ctx.sessionRoot, relPath);
1416
+ if (!external_node_fs_.existsSync(abs)) return { _meta: META, ok: false, reason: 'not-found' };
1417
+ let stat;
1418
+ try { stat = external_node_fs_.statSync(abs); } catch (e) { return { _meta: META, ok: false, reason: `stat-failed: ${e.message}` }; }
1419
+ if (!stat.isFile()) return { _meta: META, ok: false, reason: 'not-a-file' };
1420
+ const off = Number.isInteger(offset) ? Math.max(0, offset) : 0;
1421
+ const lim = Number.isInteger(limit) ? Math.min(64 * 1024, Math.max(1, limit)) : 4096;
1422
+ let buf;
1423
+ try {
1424
+ const fd = external_node_fs_.openSync(abs, 'r');
1425
+ const tmp = Buffer.alloc(lim);
1426
+ const read = external_node_fs_.readSync(fd, tmp, 0, lim, off);
1427
+ external_node_fs_.closeSync(fd);
1428
+ buf = tmp.slice(0, read);
1429
+ } catch (e) { return { _meta: META, ok: false, reason: `read-failed: ${e.message}` }; }
1430
+ const text = buf.toString('utf8');
1431
+ return {
1432
+ _meta: META, ok: true,
1433
+ path: relPath,
1434
+ offset: off, limit: lim, bytesRead: buf.length,
1435
+ totalSize: stat.size,
1436
+ truncated: off + buf.length < stat.size,
1437
+ nextOffset: off + buf.length < stat.size ? off + buf.length : null,
1438
+ content: text,
1439
+ };
1440
+ },
1441
+ };
1442
+
1443
+ // ─── append_agents_memory / read_agents_memory ─────────────────────────────
1444
+ // LangChain harness-anatomy #2: AGENTS.md as continual-learning surface.
1445
+ // Lazy-import to keep the MCP module dependency-light.
1446
+
1447
+
1448
+
1449
+ const append_agents_memory = {
1450
+ name: 'append_agents_memory',
1451
+ description: 'Append a short narrative entry to AGENTS.md — agent-authored continual-learning notes. Use at session end to record "what worked / what didn\'t / what I\'d try differently next time" so the next agent can pick up the lesson. Bounded: 2 KB per entry, 20 KB total before rotation to AGENTS.md.archive. Use sparingly — narrative, not structured data.',
1452
+ inputSchema: {
1453
+ type: 'object',
1454
+ additionalProperties: false,
1455
+ properties: {
1456
+ agent: { type: 'string', minLength: 1, maxLength: 64 },
1457
+ body: { type: 'string', minLength: 1, maxLength: 4096 },
1458
+ },
1459
+ required: ['agent', 'body'],
1460
+ },
1461
+ async handler({ agent, body }, ctx) {
1462
+ const r = appendAgentsMemory(ctx.sessionRoot, { agent, body });
1463
+ return { _meta: META, ...r };
1464
+ },
1465
+ };
1466
+
1467
+ const read_agents_memory = {
1468
+ name: 'read_agents_memory',
1469
+ description: 'Read the AGENTS.md continual-learning file (and AGENTS.md.archive if needed). Returns the most-recent ~6 KB tail by default; pass `full: true` for everything. The SessionStart hook already surfaces a summary; use this when an agent wants to look up specifics mid-session.',
1470
+ inputSchema: {
1471
+ type: 'object',
1472
+ additionalProperties: false,
1473
+ properties: {
1474
+ full: { type: 'boolean' },
1475
+ },
1476
+ },
1477
+ async handler({ full }, ctx) {
1478
+ const body = readAgentsMemory(ctx.sessionRoot);
1479
+ if (!body) return { _meta: META, present: false };
1480
+ if (full) return { _meta: META, present: true, length: body.length, content: body };
1481
+ // Tail-only — same logic as summarizeForSession but inlined to avoid a
1482
+ // second import surface.
1483
+ const limit = 6 * 1024;
1484
+ if (body.length <= limit) return { _meta: META, present: true, length: body.length, content: body };
1485
+ const tail = body.slice(-limit);
1486
+ const firstSection = tail.indexOf('\n## ');
1487
+ const slice = firstSection >= 0 ? tail.slice(firstSection) : tail;
1488
+ return { _meta: META, present: true, length: body.length, truncated: true, content: slice };
1489
+ },
1490
+ };
1491
+
1492
+ // ─── query_triage_memory ───────────────────────────────────────────────────
1493
+ // Natural-language Q&A over past triage decisions (wont-fix / false-positive
1494
+ // markings + reasons). Backed by .agentic-security/triage-memory.jsonl, which
1495
+ // is auto-populated by triage.transition(). Returns at most 10 most-relevant
1496
+ // past decisions.
1497
+
1498
+ const query_triage_memory = {
1499
+ name: 'query_triage_memory',
1500
+ description: 'Search past triage decisions (wont-fix / false-positive) by natural-language query. Returns up to 10 most-relevant past decisions with their reasons. Use when you see a new finding and want to know "did we already decide on something like this?" — answers in seconds without re-reading the full AGENTS.md narrative.',
1501
+ inputSchema: {
1502
+ type: 'object',
1503
+ additionalProperties: false,
1504
+ properties: {
1505
+ query: { type: 'string', description: 'Free-text terms to match against past reasons / vuln text / file paths / family names.' },
1506
+ },
1507
+ },
1508
+ async handler({ query }, ctx) {
1509
+ const { queryMemory } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 1905));
1510
+ const results = queryMemory(ctx.sessionRoot, query || '');
1511
+ return {
1512
+ _meta: META,
1513
+ count: results.length,
1514
+ results,
1515
+ };
1516
+ },
1517
+ };
1518
+
1519
+ // ─── query_findings_memory ─────────────────────────────────────────────────
1520
+ // Natural-language Q&A across the scanner's accumulated institutional
1521
+ // memory: current findings + past triage decisions + scan history +
1522
+ // AGENTS.md narrative. Use to answer "have we seen something like this
1523
+ // before?" without reading multiple files.
1524
+
1525
+ const query_findings_memory = {
1526
+ name: 'query_findings_memory',
1527
+ description: 'Search the scanner accumulated memory (current scan findings + past wont-fix/false-positive decisions + scan history + AGENTS.md narrative) by natural-language terms. Returns top-10 results scored by term-match count and ranked finding > triage > history > AGENTS.md.',
1528
+ inputSchema: {
1529
+ type: 'object',
1530
+ additionalProperties: false,
1531
+ properties: {
1532
+ query: { type: 'string', description: 'Natural-language search terms (2+ chars each).' },
1533
+ },
1534
+ required: ['query'],
1535
+ },
1536
+ async handler({ query }, ctx) {
1537
+ const { queryFindingsMemory } = await __webpack_require__.e(/* import() */ 839).then(__webpack_require__.bind(__webpack_require__, 3839));
1538
+ return { _meta: META, ...queryFindingsMemory(ctx.sessionRoot, query || '') };
1539
+ },
1540
+ };
1541
+
1542
+ // ─── lookup_cve ────────────────────────────────────────────────────────────
1543
+ // LangChain harness-anatomy #8: bridge the knowledge-cutoff gap by exposing
1544
+ // the local OSV / KEV / EPSS cache as a structured tool. Read-only — never
1545
+ // triggers a network fetch from the MCP path.
1546
+ const lookup_cve = {
1547
+ name: 'lookup_cve',
1548
+ description: 'Look up a CVE id in the local OSV / KEV / EPSS caches. Returns staleness-tiered cached data (fresh / recent / stale / very-stale). Read-only — does NOT fetch fresh data; the scan pipeline is the only thing that populates the cache. Use to inform reasoning about an SCA finding without relying on the model\'s training cutoff.',
1549
+ inputSchema: {
1550
+ type: 'object',
1551
+ additionalProperties: false,
1552
+ properties: {
1553
+ cve: { type: 'string', minLength: 9, maxLength: 20 },
1554
+ },
1555
+ required: ['cve'],
1556
+ },
1557
+ async handler({ cve }, _ctx) {
1558
+ const r = lookupCve(cve);
1559
+ return { _meta: META, ...r };
1560
+ },
1561
+ };
1562
+
1563
+ const query_cache_telemetry = {
1564
+ name: 'query_cache_telemetry',
1565
+ description: 'Read prompt-cache economics for the current session from the Claude Code transcript: cache-hit %, $ saved by caching, $ wasted on avoidable cache misses (model switches / TTL gaps / prefix changes), and a per-model breakdown. Read-only, no network. Use to reason about token-cost efficiency and whether a model switch is worth the cache rewarm.',
1566
+ inputSchema: {
1567
+ type: 'object',
1568
+ additionalProperties: false,
1569
+ properties: {
1570
+ // Optional explicit transcript path; otherwise derived from the session root.
1571
+ transcript_path: { type: 'string', minLength: 1, maxLength: 4096 },
1572
+ },
1573
+ required: [],
1574
+ },
1575
+ async handler({ transcript_path } = {}, ctx) {
1576
+ const result = (0,cache_economics.analyzeTranscript)({ transcriptPath: transcript_path, projectDir: ctx?.sessionRoot || process.cwd() });
1577
+ if (!result.ok) return { _meta: META, ok: false, reason: result.reason };
1578
+ return {
1579
+ _meta: META,
1580
+ ok: true,
1581
+ metrics: result.metrics,
1582
+ leaks: result.leaks,
1583
+ report: (0,cache_economics.formatCacheReport)(result),
1584
+ statusline: (0,cache_economics.renderCacheStatusLine)(result.metrics),
1585
+ };
1586
+ },
1587
+ };
1588
+
1589
+ // ─── synthesize_sca_upgrade ───────────────────────────────────────────────
1590
+ // Phase 3 / Item 5 of the SCA improvement plan. Read-only counterpart to
1591
+ // apply_sca_upgrade — produces a structured upgrade plan via the
1592
+ // ecosystem's native --dry-run command. Safe to call any number of times.
1593
+ let _scaUpgrade;
1594
+ async function _getScaUpgrade() {
1595
+ if (!_scaUpgrade) _scaUpgrade = await __webpack_require__.e(/* import() */ 333).then(__webpack_require__.bind(__webpack_require__, 5333));
1596
+ return _scaUpgrade;
1597
+ }
1598
+ const synthesize_sca_upgrade = {
1599
+ name: 'synthesize_sca_upgrade',
1600
+ description: 'Generate an upgrade plan for a single SCA finding. Runs the ecosystem dry-run (npm install --dry-run, pip install --dry-run, cargo update --dry-run). Returns { ecosystem, package, currentVersion, targetVersion, isBreaking, command, manifestFiles, dryRun, testCommand }. No writes.',
1601
+ inputSchema: {
1602
+ type: 'object',
1603
+ additionalProperties: false,
1604
+ properties: {
1605
+ finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1606
+ },
1607
+ required: ['finding_id'],
1608
+ },
1609
+ async handler({ finding_id }, ctx) {
1610
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
1611
+ if (!scan) throw new Error(`No usable scan state (${status}).`);
1612
+ const f = _findById(scan, finding_id);
1613
+ if (!f) throw new Error(`Finding not found: ${finding_id}`);
1614
+ if (f.type !== 'vulnerable_dep') {
1615
+ return { _meta: META, ok: false, reason: 'finding is not an SCA vulnerable_dep — use synthesize_fix for SAST findings' };
1616
+ }
1617
+ const { planScaUpgrade } = await _getScaUpgrade();
1618
+ const plan = await planScaUpgrade({ scanRoot: ctx.sessionRoot, finding: f });
1619
+ return { _meta: META, ...plan };
1620
+ },
1621
+ };
1622
+
1623
+ // ─── apply_sca_upgrade ────────────────────────────────────────────────────
1624
+ // Phase 3 / Item 5 of the SCA improvement plan. The MCP `apply_fix` path
1625
+ // refuses every package-manager manifest by design. This tool bypasses
1626
+ // that ONLY for the install pathway — it shells out to the ecosystem's
1627
+ // native package manager (npm / pip / cargo / go) which is the right
1628
+ // surface for safely modifying manifests + lockfiles. Backs up affected
1629
+ // manifests before the install; runs the project's test command (if
1630
+ // detected); rolls back manifests if tests fail.
1631
+ const apply_sca_upgrade = {
1632
+ name: 'apply_sca_upgrade',
1633
+ description: 'Apply a vulnerable_dep upgrade. Backs up manifests, runs the package manager, runs the project test command, restores manifests on test failure. Requires confirm:true. Set run_tests:false to skip the test gate (NOT recommended).',
1634
+ inputSchema: {
1635
+ type: 'object',
1636
+ additionalProperties: false,
1637
+ properties: {
1638
+ finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1639
+ confirm: { type: 'boolean' },
1640
+ run_tests: { type: 'boolean' },
1641
+ },
1642
+ required: ['finding_id', 'confirm'],
1643
+ },
1644
+ async handler({ finding_id, confirm, run_tests = true }, ctx) {
1645
+ if (confirm !== true) {
1646
+ return { _meta: META, applied: false, reason: 'apply_sca_upgrade requires confirm: true.' };
1647
+ }
1648
+ const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
1649
+ if (!scan) {
1650
+ return { _meta: META, applied: false, reason: `last-scan.json failed integrity check: ${status}. Run a fresh scan.` };
1651
+ }
1652
+ const f = _findById(scan, finding_id);
1653
+ if (!f) return { _meta: META, applied: false, reason: `Finding not found: ${finding_id}` };
1654
+ if (f.type !== 'vulnerable_dep') {
1655
+ return { _meta: META, applied: false, reason: 'finding is not an SCA vulnerable_dep — use apply_fix for SAST findings' };
1656
+ }
1657
+ const { applyScaUpgrade } = await _getScaUpgrade();
1658
+ const result = await applyScaUpgrade({ scanRoot: ctx.sessionRoot, finding: f, runTests: run_tests });
1659
+ return { _meta: META, ...result };
1660
+ },
1661
+ };
1662
+
1663
+ const ALL_TOOLS = [scan_diff, query_taint, explain_finding, apply_fix, verify_fix, synthesize_fix, find_rule_module, append_scratchpad, read_scratchpad, append_agents_memory, read_agents_memory, lookup_cve, synthesize_sca_upgrade, apply_sca_upgrade, query_triage_memory, query_findings_memory, query_cache_telemetry];
1664
+
1665
+ ;// CONCATENATED MODULE: ./src/mcp/validate.js
1666
+ // Minimal JSON Schema validator — just the subset our tool schemas use.
1667
+ // No deps. Throws on invalid input with a path-prefixed error message.
1668
+ //
1669
+ // Supported keywords: type (object/array/string/boolean/number),
1670
+ // required, properties, items, enum, minItems, maxItems, maxLength,
1671
+ // minLength, additionalProperties (only as `false` — strict).
1672
+
1673
+ const TYPE_OF = (v) => {
1674
+ if (v === null) return 'null';
1675
+ if (Array.isArray(v)) return 'array';
1676
+ return typeof v;
1677
+ };
1678
+
1679
+ function validate(schema, value, path = 'arguments') {
1680
+ if (!schema) return;
1681
+ const t = schema.type;
1682
+ if (t === 'object') {
1683
+ if (TYPE_OF(value) !== 'object') throw new Error(`${path}: expected object, got ${TYPE_OF(value)}`);
1684
+ for (const req of schema.required || []) {
1685
+ if (!(req in value)) throw new Error(`${path}: missing required property "${req}"`);
1686
+ }
1687
+ if (schema.additionalProperties === false) {
1688
+ const allowed = new Set(Object.keys(schema.properties || {}));
1689
+ for (const k of Object.keys(value)) {
1690
+ if (!allowed.has(k)) throw new Error(`${path}: unexpected property "${k}"`);
1691
+ }
1692
+ }
1693
+ for (const [k, sub] of Object.entries(schema.properties || {})) {
1694
+ if (k in value) validate(sub, value[k], `${path}.${k}`);
1695
+ }
1696
+ } else if (t === 'array') {
1697
+ if (!Array.isArray(value)) throw new Error(`${path}: expected array, got ${TYPE_OF(value)}`);
1698
+ if (schema.minItems != null && value.length < schema.minItems) throw new Error(`${path}: minItems=${schema.minItems}, got length=${value.length}`);
1699
+ if (schema.maxItems != null && value.length > schema.maxItems) throw new Error(`${path}: maxItems=${schema.maxItems}, got length=${value.length}`);
1700
+ if (schema.items) for (let i = 0; i < value.length; i++) validate(schema.items, value[i], `${path}[${i}]`);
1701
+ } else if (t === 'string') {
1702
+ if (typeof value !== 'string') throw new Error(`${path}: expected string, got ${TYPE_OF(value)}`);
1703
+ if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: must be one of [${schema.enum.join(', ')}]`);
1704
+ if (schema.maxLength != null && value.length > schema.maxLength) throw new Error(`${path}: maxLength=${schema.maxLength}, got length=${value.length}`);
1705
+ if (schema.minLength != null && value.length < schema.minLength) throw new Error(`${path}: minLength=${schema.minLength}, got length=${value.length}`);
1706
+ } else if (t === 'boolean') {
1707
+ if (typeof value !== 'boolean') throw new Error(`${path}: expected boolean, got ${TYPE_OF(value)}`);
1708
+ } else if (t === 'number' || t === 'integer') {
1709
+ if (typeof value !== 'number') throw new Error(`${path}: expected number, got ${TYPE_OF(value)}`);
1710
+ if (t === 'integer' && !Number.isInteger(value)) throw new Error(`${path}: expected integer`);
1711
+ if (schema.minimum != null && value < schema.minimum) throw new Error(`${path}: < minimum (${schema.minimum})`);
1712
+ if (schema.maximum != null && value > schema.maximum) throw new Error(`${path}: > maximum (${schema.maximum})`);
1713
+ }
1714
+ }
1715
+
1716
+ ;// CONCATENATED MODULE: ./src/mcp/audit.js
1717
+ // Append-only audit log of MCP tool calls — OWASP MCP08.
1718
+ //
1719
+ // Format: one JSON object per line (NDJSON) at
1720
+ // <sessionRoot>/.agentic-security/mcp-audit.log
1721
+ //
1722
+ // Each entry carries `prev` — the SHA-256 of the previous entry's serialized
1723
+ // form. The first entry's prev is "GENESIS". Tampering with any line breaks
1724
+ // the chain from that point forward; a reader can detect partial truncation
1725
+ // or in-place edits.
1726
+ //
1727
+ // REMOTE SINK (post-recommendation #10). The local file alone cannot detect
1728
+ // a total rewrite — an attacker with FS write can re-author the whole log
1729
+ // with fresh hashes. Closing that blind spot requires an off-host witness.
1730
+ // Set $AGENTIC_SECURITY_AUDIT_WEBHOOK to a POST endpoint; every entry is
1731
+ // fire-and-forget POSTed there in addition to the local append. Failures
1732
+ // to reach the webhook are best-effort — they NEVER block a tool call,
1733
+ // because that would let a network outage become a denial of service. They
1734
+ // DO get recorded as `_remoteSinkErr` on the local entry, so an operator
1735
+ // reviewing the log later can spot a forging attempt that targeted the
1736
+ // remote (any gap between local-sequence and remote-sequence is evidence).
1737
+ //
1738
+ // Argument blobs are redacted (OWASP MCP01/MCP10) so credentials passed in
1739
+ // arguments cannot leak via the audit trail OR via the remote sink.
1740
+
1741
+
1742
+
1743
+
1744
+
1745
+
1746
+ const MAX_ARG_BYTES = 1024;
1747
+ const GENESIS = 'GENESIS';
1748
+ const REMOTE_TIMEOUT_MS = 1500;
1749
+
1750
+ // Per-process session ID (harness-anatomy #9). Stamped on every audit entry
1751
+ // so downstream metrics can aggregate by session and surface outliers like
1752
+ // "200 apply_fix calls in one session." The ID is `<pid>-<short-ts>` — not
1753
+ // cryptographically unique, but enough to disambiguate concurrent runs on
1754
+ // the same host. Stable for the lifetime of this Node process.
1755
+ const SESSION_ID = `${process.pid}-${Date.now().toString(36).slice(-6)}`;
1756
+
1757
+ function _summarize(args) {
1758
+ let s;
1759
+ try { s = JSON.stringify(args); } catch { s = '<unserializable>'; }
1760
+ s = redactArgsBlob(s);
1761
+ if (s.length > MAX_ARG_BYTES) s = s.slice(0, MAX_ARG_BYTES) + `…(+${s.length - MAX_ARG_BYTES})`;
1762
+ return s;
1763
+ }
1764
+
1765
+ function _sha(s) { return external_node_crypto_.createHash('sha256').update(s).digest('hex'); }
1766
+
1767
+ function _readLastEntryHash(logFile) {
1768
+ if (!external_node_fs_.existsSync(logFile)) return GENESIS;
1769
+ try {
1770
+ const all = external_node_fs_.readFileSync(logFile, 'utf8');
1771
+ const lines = all.split('\n').filter(Boolean);
1772
+ if (!lines.length) return GENESIS;
1773
+ return _sha(lines[lines.length - 1]);
1774
+ } catch { return GENESIS; }
1775
+ }
1776
+
1777
+ // Fire-and-forget POST to the remote sink. Resolves to null on success,
1778
+ // to a short error string on failure. Never throws; never blocks longer
1779
+ // than REMOTE_TIMEOUT_MS. The local audit append happens regardless.
1780
+ async function _postRemote(url, entry) {
1781
+ try {
1782
+ const controller = new AbortController();
1783
+ const t = setTimeout(() => controller.abort(), REMOTE_TIMEOUT_MS);
1784
+ const r = await fetch(url, {
1785
+ method: 'POST',
1786
+ headers: { 'Content-Type': 'application/json' },
1787
+ body: JSON.stringify(entry),
1788
+ signal: controller.signal,
1789
+ });
1790
+ clearTimeout(t);
1791
+ if (!r.ok) return `HTTP ${r.status}`;
1792
+ return null;
1793
+ } catch (e) {
1794
+ return String((e && e.message) || e).slice(0, 200);
1795
+ }
1796
+ }
1797
+
1798
+ function auditCall({ sessionRoot, tool, args, outcome, reason }) {
1799
+ if (!sessionRoot) return;
1800
+ try {
1801
+ // Safety: only write audit log if sessionRoot looks like a project root
1802
+ const MARKERS = ['.git', 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml', 'pom.xml', 'composer.json', 'Gemfile'];
1803
+ let hasMarker = false;
1804
+ for (const m of MARKERS) { try { if (external_node_fs_.existsSync(external_node_path_.join(sessionRoot, m))) { hasMarker = true; break; } } catch {} }
1805
+ if (!hasMarker) return;
1806
+ const dir = external_node_path_.join(sessionRoot, '.agentic-security');
1807
+ external_node_fs_.mkdirSync(dir, { recursive: true });
1808
+ const logFile = external_node_path_.join(dir, 'mcp-audit.log');
1809
+ const entry = {
1810
+ ts: new Date().toISOString(),
1811
+ sessionId: SESSION_ID,
1812
+ tool,
1813
+ outcome,
1814
+ ...(reason ? { reason } : {}),
1815
+ args: _summarize(args),
1816
+ prev: _readLastEntryHash(logFile),
1817
+ };
1818
+ external_node_fs_.appendFileSync(logFile, JSON.stringify(entry) + '\n');
1819
+ // Remote sink (post-recommendation #10). Fire-and-forget. We don't await
1820
+ // the promise so the tool call returns immediately; the remote POST runs
1821
+ // on its own microtask. Failures get logged to a sidecar file so the
1822
+ // operator can detect when the sink is unreachable.
1823
+ const webhook = process.env.AGENTIC_SECURITY_AUDIT_WEBHOOK;
1824
+ if (webhook) {
1825
+ _postRemote(webhook, entry).then((err) => {
1826
+ if (!err) return;
1827
+ try {
1828
+ const errFile = external_node_path_.join(dir, 'mcp-audit.remote-errors.log');
1829
+ external_node_fs_.appendFileSync(errFile, JSON.stringify({
1830
+ ts: new Date().toISOString(), entryTs: entry.ts, tool, err,
1831
+ }) + '\n');
1832
+ } catch { /* nothing else to do */ }
1833
+ });
1834
+ }
1835
+ } catch { /* audit failure must never break a tool call */ }
1836
+ }
1837
+
1838
+ // Verify the chain from start to end. Returns
1839
+ // { ok: true, entries: N } if intact
1840
+ // { ok: false, brokenAt: <line-index>, expected, got } if any link breaks
1841
+ // Reader/operator-facing tool.
1842
+ function verifyAuditLog(logFile) {
1843
+ if (!fs.existsSync(logFile)) return { ok: true, entries: 0 };
1844
+ const text = fs.readFileSync(logFile, 'utf8');
1845
+ const lines = text.split('\n').filter(Boolean);
1846
+ let expectedPrev = GENESIS;
1847
+ for (let i = 0; i < lines.length; i++) {
1848
+ let entry;
1849
+ try { entry = JSON.parse(lines[i]); }
1850
+ catch { return { ok: false, brokenAt: i, reason: 'not JSON' }; }
1851
+ if (entry.prev !== expectedPrev) {
1852
+ return { ok: false, brokenAt: i, expected: expectedPrev, got: entry.prev };
1853
+ }
1854
+ expectedPrev = _sha(lines[i]);
1855
+ }
1856
+ return { ok: true, entries: lines.length };
1857
+ }
1858
+
1859
+ ;// CONCATENATED MODULE: ./src/mcp/server.js
1860
+ // MCP server core — JSON-RPC 2.0 handler for the Model Context Protocol.
1861
+ //
1862
+ // Hardening posture (mapped to OWASP MCP Top 10):
1863
+ // - Session root chosen at server boot, no per-call retargeting (MCP02)
1864
+ // - Every tools/call argument validated against the tool's inputSchema (MCP02/MCP05)
1865
+ // - Every tools/call audited with a hash-chained log (MCP08)
1866
+ // - serverInfo.codeFingerprint = SHA-256 of MCP source files (MCP04/MCP09)
1867
+ // so a fleet can detect tampered or unauthorized server deployments
1868
+ // - AGENTIC_SECURITY_MCP_DISABLED=1 hard-disables all tool calls (MCP09)
1869
+ // - Stdio transport caps line/buffer size (./stdio.js) (MCP05 DoS)
1870
+
1871
+
1872
+
1873
+
1874
+
1875
+
1876
+
1877
+
1878
+
1879
+ const PROTOCOL_VERSION = '2025-03-26';
1880
+ const SERVER_NAME = 'agentic-security';
1881
+
1882
+ // Premortem #6: read version from scanner/package.json at module load so the
1883
+ // MCP `initialize` response can't silently drift from the shipped package
1884
+ // version. A hardcoded constant rotted from 0.39.2 → wrong for every release
1885
+ // that followed. Fall back to 'unknown' rather than a stale literal.
1886
+ const SERVER_VERSION = (() => {
1887
+ try {
1888
+ const here = external_node_path_.dirname((0,external_node_url_.fileURLToPath)(import.meta.url));
1889
+ // scanner/src/mcp/ → scanner/package.json
1890
+ const pkgPath = external_node_path_.resolve(here, '..', '..', 'package.json');
1891
+ const pkg = JSON.parse(external_node_fs_.readFileSync(pkgPath, 'utf8'));
1892
+ if (typeof pkg.version === 'string' && pkg.version.length) return pkg.version;
1893
+ } catch { /* fall through */ }
1894
+ return 'unknown';
1895
+ })();
1896
+
1897
+ const TOOLS_BY_NAME = Object.fromEntries(ALL_TOOLS.map(t => [t.name, t]));
1898
+
1899
+ // Code fingerprint — SHA-256 of the MCP source files concatenated in a
1900
+ // stable order. Embedded in `initialize` response so a fleet operator can
1901
+ // detect when an unapproved build is running (OWASP MCP04/MCP09).
1902
+ function _codeFingerprint() {
1903
+ try {
1904
+ const here = external_node_path_.dirname((0,external_node_url_.fileURLToPath)(import.meta.url));
1905
+ const files = ['server.js', 'tools.js', 'stdio.js', 'audit.js', 'validate.js', 'redact.js'];
1906
+ const h = external_node_crypto_.createHash('sha256');
1907
+ for (const f of files) {
1908
+ try { h.update(f); h.update(external_node_fs_.readFileSync(external_node_path_.join(here, f))); } catch {}
1909
+ }
1910
+ return h.digest('hex');
1911
+ } catch { return null; }
1912
+ }
1913
+ const CODE_FINGERPRINT = _codeFingerprint();
1914
+
1915
+ function _err(id, code, message, data) {
1916
+ const out = { jsonrpc: '2.0', id, error: { code, message } };
1917
+ if (data !== undefined) out.error.data = data;
1918
+ return out;
1919
+ }
1920
+
1921
+ function _ok(id, result) {
1922
+ return { jsonrpc: '2.0', id, result };
1923
+ }
1924
+
1925
+ function createServer({ sessionRoot = process.cwd() } = {}) {
1926
+ const ctx = { sessionRoot };
1927
+
1928
+ async function handleRequest(msg) {
1929
+ if (!msg || typeof msg !== 'object') return _err(null, -32600, 'Invalid Request');
1930
+ if (msg.jsonrpc !== '2.0') return _err(msg.id ?? null, -32600, 'Invalid Request: jsonrpc must be "2.0"');
1931
+
1932
+ const isNotification = msg.id === undefined || msg.id === null;
1933
+ const id = msg.id ?? null;
1934
+ const disabled = process.env.AGENTIC_SECURITY_MCP_DISABLED === '1';
1935
+
1936
+ switch (msg.method) {
1937
+ case 'initialize':
1938
+ return _ok(id, {
1939
+ protocolVersion: PROTOCOL_VERSION,
1940
+ capabilities: { tools: {} },
1941
+ serverInfo: {
1942
+ name: SERVER_NAME,
1943
+ version: SERVER_VERSION,
1944
+ codeFingerprint: CODE_FINGERPRINT,
1945
+ disabled,
1946
+ },
1947
+ });
1948
+
1949
+ case 'notifications/initialized':
1950
+ return null;
1951
+
1952
+ case 'ping':
1953
+ return _ok(id, {});
1954
+
1955
+ case 'tools/list':
1956
+ return _ok(id, {
1957
+ tools: ALL_TOOLS.map(t => ({
1958
+ name: t.name,
1959
+ description: t.description,
1960
+ inputSchema: t.inputSchema,
1961
+ })),
1962
+ });
1963
+
1964
+ case 'tools/call': {
1965
+ const name = msg.params?.name;
1966
+ const args = msg.params?.arguments ?? {};
1967
+ if (disabled) {
1968
+ auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: 'server-disabled' });
1969
+ return _ok(id, {
1970
+ content: [{ type: 'text', text: 'MCP server is disabled (AGENTIC_SECURITY_MCP_DISABLED=1).' }],
1971
+ isError: true,
1972
+ });
1973
+ }
1974
+ const tool = TOOLS_BY_NAME[name];
1975
+ if (!tool) {
1976
+ auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: 'unknown-tool' });
1977
+ return _err(id, -32602, `Unknown tool: ${name}`);
1978
+ }
1979
+ try { validate(tool.inputSchema, args); }
1980
+ catch (e) {
1981
+ auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: `invalid-args: ${e.message}` });
1982
+ return _ok(id, {
1983
+ content: [{ type: 'text', text: `Invalid arguments: ${e.message}` }],
1984
+ isError: true,
1985
+ });
1986
+ }
1987
+ try {
1988
+ const result = await tool.handler(args, ctx);
1989
+ auditCall({ sessionRoot, tool: name, args, outcome: 'ok' });
1990
+ return _ok(id, {
1991
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
1992
+ isError: false,
1993
+ });
1994
+ } catch (e) {
1995
+ auditCall({ sessionRoot, tool: name, args, outcome: 'error', reason: e.message });
1996
+ return _ok(id, {
1997
+ content: [{ type: 'text', text: `Error: ${e.message}` }],
1998
+ isError: true,
1999
+ });
2000
+ }
2001
+ }
2002
+
2003
+ default:
2004
+ if (isNotification) return null;
2005
+ return _err(id, -32601, `Method not found: ${msg.method}`);
2006
+ }
2007
+ }
2008
+
2009
+ return { handleRequest, sessionRoot };
2010
+ }
2011
+
2012
+ // NOTE: no default-singleton export. Callers must use createServer({...})
2013
+ // with an explicit sessionRoot. Removed because the prior default was bound
2014
+ // to process.cwd() at module-load time — a footgun for any caller that
2015
+ // imported `handleRequest` directly (OWASP A05).
2016
+
2017
+
2018
+
2019
+ ;// CONCATENATED MODULE: ./src/mcp/stdio.js
2020
+ // Stdio transport for the MCP server — newline-delimited JSON in/out.
2021
+ //
2022
+ // MCP's stdio transport is NDJSON: one JSON-RPC message per line on stdin,
2023
+ // one response per line on stdout. stderr is reserved for logging.
2024
+ //
2025
+ // Hardening:
2026
+ // - Per-message line cap (MAX_LINE_BYTES). A line over the cap is dropped
2027
+ // and the buffer state is reset so a long oversize payload can't peg
2028
+ // the parser via `buf += chunk` growth.
2029
+ // - Buffer hard cap (MAX_BUFFER_BYTES). Reached if input arrives with no
2030
+ // newlines (e.g., a peer streaming a 4GB stream of `a`). On overflow we
2031
+ // emit a parse-error response and reset.
2032
+
2033
+
2034
+
2035
+ const MAX_LINE_BYTES = 4 * 1024 * 1024; // 4 MB per JSON-RPC message
2036
+ const MAX_BUFFER_BYTES = 8 * 1024 * 1024; // 8 MB sliding buffer
2037
+
2038
+ function runStdio({
2039
+ stdin = process.stdin,
2040
+ stdout = process.stdout,
2041
+ stderr = process.stderr,
2042
+ sessionRoot = process.cwd(),
2043
+ } = {}) {
2044
+ const server = createServer({ sessionRoot });
2045
+ let buf = '';
2046
+ let overflowSkip = false; // true while we are dropping bytes until the next newline
2047
+
2048
+ stdin.setEncoding('utf8');
2049
+
2050
+ stdin.on('data', async (chunk) => {
2051
+ if (overflowSkip) {
2052
+ const nl = chunk.indexOf('\n');
2053
+ if (nl === -1) return;
2054
+ // Resume after the next newline.
2055
+ chunk = chunk.slice(nl + 1);
2056
+ overflowSkip = false;
2057
+ }
2058
+
2059
+ buf += chunk;
2060
+
2061
+ // Hard buffer cap — only triggers if a peer is streaming without newlines.
2062
+ if (buf.length > MAX_BUFFER_BYTES) {
2063
+ stderr.write(`mcp: input buffer exceeded ${MAX_BUFFER_BYTES} bytes — dropping until next newline\n`);
2064
+ const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error: input too large' } };
2065
+ stdout.write(JSON.stringify(errResponse) + '\n');
2066
+ buf = '';
2067
+ overflowSkip = true;
2068
+ return;
2069
+ }
2070
+
2071
+ let nl;
2072
+ while ((nl = buf.indexOf('\n')) !== -1) {
2073
+ const line = buf.slice(0, nl).trim();
2074
+ buf = buf.slice(nl + 1);
2075
+ if (!line) continue;
2076
+ if (line.length > MAX_LINE_BYTES) {
2077
+ stderr.write(`mcp: dropped oversize line (${line.length} > ${MAX_LINE_BYTES} bytes)\n`);
2078
+ const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error: line too large' } };
2079
+ stdout.write(JSON.stringify(errResponse) + '\n');
2080
+ continue;
2081
+ }
2082
+ let msg;
2083
+ try { msg = JSON.parse(line); }
2084
+ catch (e) {
2085
+ stderr.write(`mcp: failed to parse line as JSON: ${e.message}\n`);
2086
+ const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } };
2087
+ stdout.write(JSON.stringify(errResponse) + '\n');
2088
+ continue;
2089
+ }
2090
+ try {
2091
+ const response = await server.handleRequest(msg);
2092
+ if (response !== null) stdout.write(JSON.stringify(response) + '\n');
2093
+ } catch (e) {
2094
+ stderr.write(`mcp: handler threw: ${e.message}\n`);
2095
+ const errResponse = { jsonrpc: '2.0', id: msg.id ?? null, error: { code: -32603, message: 'Internal error', data: e.message } };
2096
+ stdout.write(JSON.stringify(errResponse) + '\n');
2097
+ }
2098
+ }
2099
+ });
2100
+
2101
+ stdin.on('end', () => { process.exit(0); });
2102
+ }
2103
+
2104
+
2105
+ /***/ }),
2106
+
2107
+ /***/ 8752:
2108
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2109
+
2110
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2111
+ /* harmony export */ analyzeTranscript: () => (/* binding */ analyzeTranscript),
2112
+ /* harmony export */ formatCacheReport: () => (/* binding */ formatCacheReport),
2113
+ /* harmony export */ renderCacheStatusLine: () => (/* binding */ renderCacheStatusLine)
2114
+ /* harmony export */ });
2115
+ /* unused harmony export _internal */
2116
+ /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
2117
+ /* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8161);
2118
+ /* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6760);
2119
+ // Prompt-cache economics — turn Claude Code's own transcript usage into a
2120
+ // dollarized report: how much prompt caching saved, how much was wasted on
2121
+ // avoidable cache misses, and what invalidated the cache.
2122
+ //
2123
+ // Source of truth: the Claude Code transcript at
2124
+ // ~/.claude/projects/<enc>/<session>.jsonl
2125
+ // where <enc> is CLAUDE_PROJECT_DIR with `/` and `.` replaced by `-`. Each
2126
+ // assistant turn carries `message.usage` with input/output/cache_read/
2127
+ // cache_creation token counts (and a 5m/1h write split). We price those against
2128
+ // per-model rates to compute real economics — no estimates, no network.
2129
+ //
2130
+ // Pure compute on parsed records; only `locateTranscript`/`parseTranscriptUsage`
2131
+ // touch the filesystem. ESM (scanner tree). A trimmed CJS twin lives at
2132
+ // hooks/lib/transcript.js for the CJS hooks; test/cache-economics.test.js asserts
2133
+ // the two agree.
2134
+
2135
+
2136
+
2137
+
2138
+ // Cents-scale money formatter (fmtUsd in risk-dollars.js targets five-figure
2139
+ // breach costs and won't round sub-dollar values).
2140
+ function money(n) {
2141
+ const v = Number(n) || 0;
2142
+ return Math.abs(v) >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;
2143
+ }
2144
+
2145
+ // Per-1M-token rates (input / output). Mirror hooks/model-cost-advisor.js MODELS.
2146
+ const MODEL_RATES = {
2147
+ fable: { label: 'Fable 5', in: 10, out: 50 },
2148
+ opus: { label: 'Opus 4.8', in: 5, out: 25 },
2149
+ sonnet5: { label: 'Sonnet 5', in: 3, out: 15 },
2150
+ sonnet: { label: 'Sonnet 4.6', in: 3, out: 15 },
2151
+ haiku: { label: 'Haiku 4.5', in: 1, out: 5 },
2152
+ };
2153
+ const CACHE_READ_MULT = 0.1; // cache read ≈ 0.1× input
2154
+ const CACHE_WRITE_MULT = 1.25; // 5-minute cache write ≈ 1.25× input
2155
+ const CACHE_WRITE_1H_MULT = 2.0; // 1-hour cache write ≈ 2× input
2156
+ const TTL_MS = 5 * 60 * 1000;
2157
+
2158
+ // Map any model string to a rate family. Returns null for unpriceable models
2159
+ // (e.g. "<synthetic>" sidechain/compaction turns) so they're skipped.
2160
+ function rateFor(model) {
2161
+ if (typeof model !== 'string') return null;
2162
+ const s = model.toLowerCase();
2163
+ if (s.includes('fable') || s.includes('mythos')) return MODEL_RATES.fable;
2164
+ if (s.includes('haiku')) return MODEL_RATES.haiku;
2165
+ if (s.includes('sonnet')) return (s.includes('sonnet-5') || s.includes('sonnet 5')) ? MODEL_RATES.sonnet5 : MODEL_RATES.sonnet;
2166
+ if (s.includes('opus')) return MODEL_RATES.opus;
2167
+ return null;
2168
+ }
2169
+
2170
+ // ── Transcript discovery + parse ─────────────────────────────────────────────
2171
+
2172
+ function encodeProjectDir(dir) {
2173
+ return String(dir).replace(/[/.]/g, '-');
2174
+ }
2175
+
2176
+ // Locate the session transcript. Prefer an explicit (hook-provided) path; else
2177
+ // derive the project's transcript dir and take the most-recently-modified jsonl.
2178
+ function locateTranscript({ transcriptPath, projectDir } = {}) {
2179
+ try {
2180
+ if (transcriptPath && node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(transcriptPath)) return transcriptPath;
2181
+ } catch { /* fall through */ }
2182
+ try {
2183
+ const dir = node_path__WEBPACK_IMPORTED_MODULE_2__.join(node_os__WEBPACK_IMPORTED_MODULE_1__.homedir(), '.claude', 'projects', encodeProjectDir(projectDir || process.cwd()));
2184
+ if (!node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(dir)) return null;
2185
+ const files = node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir)
2186
+ .filter(f => f.endsWith('.jsonl'))
2187
+ .map(f => ({ f: node_path__WEBPACK_IMPORTED_MODULE_2__.join(dir, f), m: node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(node_path__WEBPACK_IMPORTED_MODULE_2__.join(dir, f)).mtimeMs }))
2188
+ .sort((a, b) => b.m - a.m);
2189
+ return files.length ? files[0].f : null;
2190
+ } catch { return null; }
2191
+ }
2192
+
2193
+ // Parse a transcript jsonl into per-assistant-turn usage records. Skips lines
2194
+ // that aren't priceable assistant turns.
2195
+ function parseTranscriptUsage(jsonlPath) {
2196
+ let raw;
2197
+ try { raw = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(jsonlPath, 'utf8'); } catch { return []; }
2198
+ const records = [];
2199
+ for (const line of raw.split('\n')) {
2200
+ const t = line.trim();
2201
+ if (!t) continue;
2202
+ let o;
2203
+ try { o = JSON.parse(t); } catch { continue; }
2204
+ if (o.type !== 'assistant') continue;
2205
+ const msg = o.message;
2206
+ const u = msg && msg.usage;
2207
+ if (!u || !msg.model || !rateFor(msg.model)) continue;
2208
+ const cc = u.cache_creation || {};
2209
+ records.push({
2210
+ model: msg.model,
2211
+ input: u.input_tokens || 0,
2212
+ output: u.output_tokens || 0,
2213
+ cacheRead: u.cache_read_input_tokens || 0,
2214
+ cacheCreate: u.cache_creation_input_tokens || 0,
2215
+ cacheCreate5m: cc.ephemeral_5m_input_tokens || 0,
2216
+ cacheCreate1h: cc.ephemeral_1h_input_tokens || 0,
2217
+ ts: o.timestamp ? Date.parse(o.timestamp) : null,
2218
+ });
2219
+ }
2220
+ return records;
2221
+ }
2222
+
2223
+ // ── Pure economics ───────────────────────────────────────────────────────────
2224
+
2225
+ function writeCostUsd(r, inRate) {
2226
+ const m5 = r.cacheCreate5m || 0, m1 = r.cacheCreate1h || 0;
2227
+ if (m5 + m1 > 0) return (m5 * CACHE_WRITE_MULT + m1 * CACHE_WRITE_1H_MULT) * inRate;
2228
+ return (r.cacheCreate || 0) * CACHE_WRITE_MULT * inRate; // breakdown absent
2229
+ }
2230
+
2231
+ // Aggregate economics over parsed records.
2232
+ function computeCacheEconomics(records) {
2233
+ let turns = 0, inTok = 0, outTok = 0, cacheRead = 0, cacheCreate = 0;
2234
+ let actualUsd = 0, uncachedUsd = 0, writePremiumUsd = 0;
2235
+ const perModel = {};
2236
+
2237
+ for (const r of records) {
2238
+ const rate = rateFor(r.model);
2239
+ if (!rate) continue;
2240
+ turns++;
2241
+ const inRate = rate.in / 1e6, outRate = rate.out / 1e6;
2242
+
2243
+ const readCost = r.cacheRead * inRate * CACHE_READ_MULT;
2244
+ const writeCost = writeCostUsd(r, inRate);
2245
+ const inCost = r.input * inRate;
2246
+ const outCost = r.output * outRate;
2247
+ const turnActual = readCost + writeCost + inCost + outCost;
2248
+ // What this turn would have cost with NO caching: every input-side token full price.
2249
+ const turnUncached = (r.cacheRead + r.cacheCreate + r.input) * inRate + outCost;
2250
+
2251
+ actualUsd += turnActual;
2252
+ uncachedUsd += turnUncached;
2253
+ writePremiumUsd += writeCost - (r.cacheCreate * inRate); // the >1× premium paid to cache
2254
+
2255
+ inTok += r.input; outTok += r.output; cacheRead += r.cacheRead; cacheCreate += r.cacheCreate;
2256
+
2257
+ const key = rate.label;
2258
+ const pm = perModel[key] || (perModel[key] = { turns: 0, actualUsd: 0, cacheRead: 0, inputSide: 0 });
2259
+ pm.turns++; pm.actualUsd += turnActual; pm.cacheRead += r.cacheRead;
2260
+ pm.inputSide += r.cacheRead + r.cacheCreate + r.input;
2261
+ }
2262
+
2263
+ const inputSide = cacheRead + cacheCreate + inTok;
2264
+ return {
2265
+ turns,
2266
+ tokens: { input: inTok, output: outTok, cacheRead, cacheCreate },
2267
+ actualUsd,
2268
+ uncachedUsd,
2269
+ savedUsd: uncachedUsd - actualUsd, // net $ caching saved (can dip negative early)
2270
+ writePremiumUsd, // $ invested establishing caches
2271
+ cacheHitRatio: inputSide ? cacheRead / inputSide : 0,
2272
+ costPerTurnUsd: turns ? actualUsd / turns : 0,
2273
+ perModel,
2274
+ };
2275
+ }
2276
+
2277
+ // Attribute cache drops: a turn that re-ingests a large prefix cold after a warm
2278
+ // prior turn. Cause = model-switch | cache-expired | prefix-change.
2279
+ function detectInvalidators(records) {
2280
+ const leaks = [];
2281
+ const MIN_WARM = 2000;
2282
+ for (let i = 1; i < records.length; i++) {
2283
+ const prev = records[i - 1], cur = records[i];
2284
+ const prevWarm = prev.cacheRead + prev.input + prev.cacheCreate;
2285
+ if (prevWarm < MIN_WARM) continue;
2286
+ const curFresh = cur.input + cur.cacheCreate;
2287
+ const coldish = cur.cacheRead < prevWarm * 0.25 && curFresh > prevWarm * 0.5;
2288
+ if (!coldish) continue;
2289
+
2290
+ let cause;
2291
+ if (cur.model !== prev.model) cause = 'model-switch';
2292
+ else if (cur.ts && prev.ts && (cur.ts - prev.ts) > TTL_MS) cause = 'cache-expired';
2293
+ else cause = 'prefix-change';
2294
+
2295
+ const rate = rateFor(cur.model);
2296
+ const inRate = rate ? rate.in / 1e6 : 0;
2297
+ // Extra paid vs. having kept the prefix as a cheap cache read.
2298
+ const wastedUsd = prevWarm * inRate * (1 - CACHE_READ_MULT);
2299
+ leaks.push({ turn: i, cause, wastedUsd, model: cur.model });
2300
+ }
2301
+ return leaks;
2302
+ }
2303
+
2304
+ // Convenience: locate → parse → compute → detect. Returns { ok:false } when no
2305
+ // transcript is available.
2306
+ function analyzeTranscript(opts = {}) {
2307
+ const transcript = locateTranscript(opts);
2308
+ if (!transcript) return { ok: false, reason: 'no-transcript' };
2309
+ const records = parseTranscriptUsage(transcript);
2310
+ if (!records.length) return { ok: false, reason: 'no-priceable-turns', transcript };
2311
+ return {
2312
+ ok: true,
2313
+ transcript,
2314
+ metrics: computeCacheEconomics(records),
2315
+ leaks: detectInvalidators(records),
2316
+ };
2317
+ }
2318
+
2319
+ // ── Report formatting ────────────────────────────────────────────────────────
2320
+
2321
+ const CAUSE_LABEL = {
2322
+ 'model-switch': 'model switch (cache is model-scoped)',
2323
+ 'cache-expired': 'cache expired (gap > 5-min TTL)',
2324
+ 'prefix-change': 'prefix changed (system prompt / tools / context edit)',
2325
+ };
2326
+
2327
+ // F6 — one-line HUD for a Claude Code statusLine command (mirrors
2328
+ // watch-mode.js renderStatusLine). Takes the metrics from computeCacheEconomics.
2329
+ function renderCacheStatusLine(metrics) {
2330
+ if (!metrics || !metrics.turns) return 'agentic-security: no session cost yet';
2331
+ const hit = Math.round(metrics.cacheHitRatio * 100);
2332
+ return `agentic-security: ${money(metrics.actualUsd)} · ${hit}% cached · ${money(metrics.costPerTurnUsd)}/turn`;
2333
+ }
2334
+
2335
+ function formatCacheReport(result) {
2336
+ if (!result.ok) {
2337
+ return result.reason === 'no-transcript'
2338
+ ? 'agentic-security: no Claude Code transcript found for this project yet.'
2339
+ : 'agentic-security: transcript has no priceable model turns yet.';
2340
+ }
2341
+ const m = result.metrics;
2342
+ const lines = [];
2343
+ lines.push('');
2344
+ lines.push(' Prompt-cache economics — this session');
2345
+ lines.push(` ${result.turns ?? m.turns} model turns\n`);
2346
+ lines.push(` cache hit ratio ${(m.cacheHitRatio * 100).toFixed(1)}% (input-side tokens served from cache)`);
2347
+ lines.push(` spent ${money(m.actualUsd)} (~${money(m.costPerTurnUsd)}/turn)`);
2348
+ lines.push(` ▶ saved by caching ${money(m.savedUsd)} vs. ${money(m.uncachedUsd)} with no cache`);
2349
+ lines.push(` invested in caches ${money(m.writePremiumUsd)} (write premium over base input)`);
2350
+ lines.push('');
2351
+ lines.push(' tokens: '
2352
+ + `${m.tokens.cacheRead.toLocaleString()} cached-read · `
2353
+ + `${m.tokens.cacheCreate.toLocaleString()} cache-write · `
2354
+ + `${m.tokens.input.toLocaleString()} fresh-in · `
2355
+ + `${m.tokens.output.toLocaleString()} out`);
2356
+
2357
+ const models = Object.keys(m.perModel);
2358
+ if (models.length > 1) {
2359
+ lines.push('\n by model:');
2360
+ for (const k of models.sort()) {
2361
+ const pm = m.perModel[k];
2362
+ const hr = pm.inputSide ? (pm.cacheRead / pm.inputSide * 100).toFixed(0) : '0';
2363
+ lines.push(` ${k.padEnd(12)} ${pm.turns} turns · ${money(pm.actualUsd)} · ${hr}% cached`);
2364
+ }
2365
+ }
2366
+
2367
+ if (result.leaks && result.leaks.length) {
2368
+ const wasted = result.leaks.reduce((s, l) => s + l.wastedUsd, 0);
2369
+ lines.push(`\n ⚠ cache leaks (${result.leaks.length}, ~${money(wasted)} wasted re-ingesting context):`);
2370
+ const byCause = {};
2371
+ for (const l of result.leaks) {
2372
+ (byCause[l.cause] || (byCause[l.cause] = { n: 0, usd: 0 })).n++;
2373
+ byCause[l.cause].usd += l.wastedUsd;
2374
+ }
2375
+ for (const c of Object.keys(byCause).sort()) {
2376
+ lines.push(` · ${byCause[c].n}× ${CAUSE_LABEL[c] || c} — ~${money(byCause[c].usd)}`);
2377
+ }
2378
+ lines.push(' Keep one model + a stable system prompt within a working window to avoid these.');
2379
+ } else {
2380
+ lines.push('\n ✓ no cache leaks detected — your context stayed warm.');
2381
+ }
2382
+ lines.push('');
2383
+ return lines.join('\n');
2384
+ }
2385
+
2386
+ // Test surface (underscore export is exempt from the dead-module gate).
2387
+ const _internal = {
2388
+ MODEL_RATES, CACHE_READ_MULT, CACHE_WRITE_MULT, CACHE_WRITE_1H_MULT,
2389
+ rateFor, locateTranscript, parseTranscriptUsage, computeCacheEconomics, detectInvalidators,
2390
+ };
2391
+
2392
+
2393
+ /***/ })
2394
+
2395
+ };