@clear-capabilities/agentic-security-scanner 0.158.0 → 0.160.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/1919.index.js +5 -2
  3. package/dist/2862.index.js +29 -9
  4. package/dist/3531.index.js +1 -1
  5. package/dist/4171.index.js +4 -4
  6. package/dist/{8551.index.js → 7033.index.js} +415 -22
  7. package/dist/9560.index.js +3 -1
  8. package/dist/agentic-security.mjs +15 -15
  9. package/dist/agentic-security.mjs.sha256 +1 -1
  10. package/package.json +11 -6
  11. package/src/engine.js +6 -1
  12. package/src/language/CLAUDE.md +48 -1
  13. package/src/language/assurance.js +21 -4
  14. package/src/language/context.js +2 -0
  15. package/src/language/cvss.js +91 -0
  16. package/src/language/fix-lifecycle.js +114 -21
  17. package/src/language/haskell-adapter.js +4 -3
  18. package/src/language/haskell-advisory-feed.js +15 -0
  19. package/src/language/haskell-boundaries.js +220 -0
  20. package/src/language/haskell-cpp.js +460 -0
  21. package/src/language/haskell-ir.js +6 -3
  22. package/src/language/haskell-models.js +4 -3
  23. package/src/language/haskell-parser.js +122 -38
  24. package/src/language/haskell-sca.js +10 -6
  25. package/src/language/haskell-supply.js +42 -8
  26. package/src/language/haskell-web.js +128 -23
  27. package/src/language/nix-advisory-feed.js +275 -0
  28. package/src/language/nix-fix.js +162 -24
  29. package/src/language/nix-ir.js +16 -12
  30. package/src/language/nix-sca.js +71 -12
  31. package/src/language/nixos-eval-forms.js +162 -0
  32. package/src/language/nixos-module-resolver.js +346 -51
  33. package/src/language/resolved-pass.js +57 -3
  34. package/src/lsp/server.js +5 -2
  35. package/src/mcp/tools.js +3 -1
  36. package/src/posture/fix-history.js +30 -3
  37. package/src/report/index.js +4 -1
  38. package/dist/1310.index.js +0 -3161
  39. package/dist/2376.index.js +0 -3151
  40. package/dist/3526.index.js +0 -1019
  41. package/dist/7310.index.js +0 -520
  42. package/dist/8520.index.js +0 -13
  43. package/dist/9091.index.js +0 -3135
@@ -1,3135 +0,0 @@
1
- export const id = 9091;
2
- export const ids = [9091,8218,8752];
3
- export const modules = {
4
-
5
- /***/ 9091:
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
- // EXTERNAL MODULE: ./src/fix/apply-fix-service.js
27
- var apply_fix_service = __webpack_require__(7730);
28
- // EXTERNAL MODULE: ./src/posture/material-change.js
29
- var material_change = __webpack_require__(4629);
30
- // EXTERNAL MODULE: ./src/fix/approver-registry.js
31
- var approver_registry = __webpack_require__(437);
32
- ;// CONCATENATED MODULE: ./src/posture/deterministic-fix.js
33
- // Deterministic fix synthesis (#1) — for the narrow set of vulnerability classes
34
- // where a context-INDEPENDENT literal swap is a safe, correct fix, produce a
35
- // full-file replacement from the current file content. No LLM, no guessing, no
36
- // per-finding bloat in last-scan.json (the patch is materialized on demand by
37
- // synthesize_fix from the live file, not stored on every finding).
38
- //
39
- // Safety: every patch this produces is still gated by verify_fix before apply_fix
40
- // writes it (original finding gone + no new ≥medium + lint clean). So a swap that
41
- // a rule mis-attributed simply fails verification instead of landing a bad edit —
42
- // this module widens the deterministic-fix surface without weakening the gate.
43
- //
44
- // Returns { patch: { [relFile]: newContent }, ruleId } or null when no
45
- // deterministic fix applies to the finding.
46
-
47
- const JS_EXT = /\.(?:js|jsx|ts|tsx|mjs|cjs)$/i;
48
- const PY_EXT = /\.py$/i;
49
-
50
- // Each rule gates on the finding's cwe/family, then rewrites the whole-file
51
- // content. transform() returns the new content, or null when nothing changed
52
- // (e.g. the vulnerable token isn't literally present — then we don't claim a fix).
53
- const RULES = [
54
- {
55
- id: 'weak-hash-sha256',
56
- // md5 / sha1 → sha256. Every occurrence in the file is a weak hash, so
57
- // swapping them all is safe; the verifier confirms the weak-hash finding is
58
- // gone and nothing worse appeared.
59
- applies: (f) => /CWE-(?:327|328|916)/.test(f.cwe || '') || /weak.?hash/i.test(f.family || ''),
60
- transform: (content, file) => {
61
- let out = content;
62
- if (JS_EXT.test(file)) {
63
- out = out.replace(/(\bcreateHash\s*\(\s*['"`])(?:md5|sha1)(['"`])/gi, '$1sha256$2');
64
- } else if (PY_EXT.test(file)) {
65
- out = out.replace(/\bhashlib\.(?:md5|sha1)\s*\(/g, 'hashlib.sha256(');
66
- }
67
- return out !== content ? out : null;
68
- },
69
- },
70
- {
71
- id: 'tls-verify-on',
72
- // Disabled TLS verification → enabled. rejectUnauthorized:false → true (JS),
73
- // verify=False → verify=True (Python requests).
74
- applies: (f) => /CWE-295/.test(f.cwe || '') || /tls.?no.?verify|cert.?(?:none|verify)/i.test(f.family || ''),
75
- transform: (content, file) => {
76
- let out = content;
77
- if (JS_EXT.test(file)) {
78
- out = out.replace(/(\brejectUnauthorized\s*:\s*)false\b/g, '$1true');
79
- } else if (PY_EXT.test(file)) {
80
- out = out.replace(/(\bverify\s*=\s*)False\b/g, '$1True');
81
- }
82
- return out !== content ? out : null;
83
- },
84
- },
85
- ];
86
-
87
- function synthesizeDeterministicPatch(finding, fileContent) {
88
- if (!finding || typeof fileContent !== 'string' || !finding.file) return null;
89
- for (const rule of RULES) {
90
- try {
91
- if (!rule.applies(finding)) continue;
92
- const next = rule.transform(fileContent, finding.file);
93
- if (next && next !== fileContent) return { patch: { [finding.file]: next }, ruleId: rule.id };
94
- } catch { /* a single rule failing must never break synthesis */ }
95
- }
96
- return null;
97
- }
98
-
99
- // EXTERNAL MODULE: ./src/posture/integrity.js
100
- var integrity = __webpack_require__(1130);
101
- // EXTERNAL MODULE: ./src/posture/state-dir.js
102
- var state_dir = __webpack_require__(1174);
103
- // EXTERNAL MODULE: ./src/posture/cache-economics.js
104
- var cache_economics = __webpack_require__(8752);
105
- // EXTERNAL MODULE: ./src/mcp/redact.js
106
- var redact = __webpack_require__(3468);
107
- // EXTERNAL MODULE: ./src/report/index.js + 3 modules
108
- var report = __webpack_require__(457);
109
- // EXTERNAL MODULE: ./src/posture/provenance/schema.js
110
- var schema = __webpack_require__(4594);
111
- // EXTERNAL MODULE: ./src/server/graph-loader.js
112
- var graph_loader = __webpack_require__(8218);
113
- // EXTERNAL MODULE: ./src/server/routes.js
114
- var routes = __webpack_require__(4268);
115
- // EXTERNAL MODULE: ./src/lineage/redact-graph.js
116
- var redact_graph = __webpack_require__(334);
117
- // EXTERNAL MODULE: ./src/lineage/export-json.js
118
- var export_json = __webpack_require__(859);
119
- ;// CONCATENATED MODULE: ./src/mcp/dataflow-tools.js
120
- // dataflow-tools.js — Milestone 4, sub-project MCP tools.
121
- //
122
- // Thin, read-only MCP adapter over the DataFlowGraph v1 artifact. Every
123
- // piece of actual graph-loading and graph-query logic here is REUSED,
124
- // unmodified, from scanner/src/server/ (built for the `explore` HTTP
125
- // server, Milestone 3): loadSignedGraph does the signed-artifact
126
- // load+verify, the four handleX functions do the lookups. This module
127
- // adds nothing but MCP tool shape (name/description/inputSchema/handler)
128
- // and MCP-appropriate error handling — no new graph-query logic is
129
- // written here, on purpose (see this sub-project's own scoping doc).
130
-
131
-
132
-
133
-
134
-
135
-
136
- const META = { source: 'agentic-security-mcp', untrusted_excerpts: true };
137
-
138
- function _loadOrFailure(sessionRoot) {
139
- const loaded = (0,graph_loader.loadSignedGraph)(sessionRoot);
140
- if (loaded.ok) return { graph: loaded.graph };
141
- return {
142
- failure: {
143
- _meta: META,
144
- hasResult: false,
145
- reason: loaded.reason,
146
- message: loaded.message,
147
- },
148
- };
149
- }
150
-
151
- // Milestone 5, large-graph pagination: an optional `filter` input narrows the
152
- // returned graph via the exact same `validateFilterShape`/`_filterGraph`
153
- // pair the CLI's own `--filter` and the `explore` server's new
154
- // `POST /api/v1/query` endpoint both already use — one real, shared
155
- // primitive, not a third drifting copy. KNOWN, DISCLOSED GAP (still open):
156
- // an OMITTED filter still returns the whole graph inline, with the same
157
- // stdio.js MAX_LINE_BYTES (4MB) risk on a very large, unfiltered scan as
158
- // before this change — this increment adds an opt-in capability for a
159
- // caller that supplies a filter, it does not add a forced fallback/offload
160
- // for a caller that doesn't. That remains a follow-up increment.
161
- // Final whole-branch review finding: `filter: {}` is NOT the same as
162
- // omitting `filter` — `_filterGraph` treats an empty (but well-formed)
163
- // filter object as "narrow to nothing" (empty nodeIds/edgeIds Sets), so
164
- // `filter: {}` returns an EMPTY graph (zero nodes/edges/flows), not the
165
- // whole one. Called out explicitly in this tool's own `description` below
166
- // so an agent reaching for "no restriction" reaches for OMITTING the
167
- // argument, never for `{}`.
168
- const dataflow_get_graph = {
169
- name: 'dataflow_get_graph',
170
- description: 'Return the DataFlowGraph v1 artifact from the last signed, verified deep-mode scan: nodes, edges, flows, scope, coverage, and limitations. Requires a prior `AGENTIC_SECURITY_LINEAGE_DEEP=1 agentic-security scan`. Optional `filter: {nodeIds, edgeIds}` narrows the returned nodes/edges/flows/dataElements (same primitive as the CLI\'s `--filter` and the `explore` server\'s `POST /api/v1/query`). IMPORTANT: omit `filter` entirely for the whole graph — passing `filter: {}` returns an EMPTY graph (zero nodes/edges/flows), not the whole one, since an empty filter narrows to nothing rather than meaning "no restriction". KNOWN GAP: an OMITTED filter still returns the whole graph inline with no pagination/offload — may exceed the stdio transport line cap on a very large, unfiltered graph; supply a real, non-empty filter to narrow the response.',
171
- inputSchema: {
172
- type: 'object',
173
- additionalProperties: false,
174
- properties: {
175
- filter: {
176
- type: 'object',
177
- additionalProperties: false,
178
- properties: {
179
- nodeIds: { type: 'array', items: { type: 'string' } },
180
- edgeIds: { type: 'array', items: { type: 'string' } },
181
- },
182
- },
183
- },
184
- },
185
- async handler(args, ctx) {
186
- const { graph, failure } = _loadOrFailure(ctx.sessionRoot);
187
- if (failure) return failure;
188
- // Milestone 5, large-graph pagination: reuses the exact same
189
- // validateFilterShape/_filterGraph pair the new POST /api/v1/query
190
- // server endpoint and the CLI's own --filter both use — one real,
191
- // shared primitive, not a third drifting copy.
192
- const filterCheck = (0,export_json.validateFilterShape)(args?.filter);
193
- if (!filterCheck.valid) {
194
- return { _meta: META, hasResult: false, reason: 'invalid-filter', message: filterCheck.error };
195
- }
196
- const { status, body } = (0,routes/* handleGraph */.fn)(graph);
197
- return {
198
- _meta: META,
199
- hasResult: true,
200
- status,
201
- data: (0,redact_graph/* _redactGraph */.zl)(args?.filter ? (0,export_json/* _filterGraph */.e)(body.data, args.filter) : body.data),
202
- digest: body.digest,
203
- schemaVersion: body.schemaVersion,
204
- extensions: body.extensions,
205
- scope: body.scope,
206
- coverage: body.coverage,
207
- limitations: body.limitations,
208
- };
209
- },
210
- };
211
-
212
- const dataflow_get_node = {
213
- name: 'dataflow_get_node',
214
- description: 'Look up one node by canonical id in the DataFlowGraph v1 artifact.',
215
- inputSchema: {
216
- type: 'object',
217
- additionalProperties: false,
218
- properties: { id: { type: 'string', minLength: 1, maxLength: 512 } },
219
- required: ['id'],
220
- },
221
- async handler({ id }, ctx) {
222
- const { graph, failure } = _loadOrFailure(ctx.sessionRoot);
223
- if (failure) return failure;
224
- const { status, body } = (0,routes/* handleNode */.d5)(graph, id);
225
- return {
226
- _meta: META,
227
- hasResult: true,
228
- notFound: status === 404,
229
- data: (0,redact_graph/* _redactNode */.T2)(body.data),
230
- canonicalIds: body.canonicalIds,
231
- };
232
- },
233
- };
234
-
235
- const dataflow_get_edge = {
236
- name: 'dataflow_get_edge',
237
- description: 'Look up one edge by canonical id in the DataFlowGraph v1 artifact.',
238
- inputSchema: {
239
- type: 'object',
240
- additionalProperties: false,
241
- properties: { id: { type: 'string', minLength: 1, maxLength: 512 } },
242
- required: ['id'],
243
- },
244
- async handler({ id }, ctx) {
245
- const { graph, failure } = _loadOrFailure(ctx.sessionRoot);
246
- if (failure) return failure;
247
- const { status, body } = (0,routes/* handleEdge */.Yu)(graph, id);
248
- return {
249
- _meta: META,
250
- hasResult: true,
251
- notFound: status === 404,
252
- data: body.data,
253
- canonicalIds: body.canonicalIds,
254
- };
255
- },
256
- };
257
-
258
- const dataflow_get_flow = {
259
- name: 'dataflow_get_flow',
260
- description: 'Look up one flow by canonical id in the DataFlowGraph v1 artifact, including its contributing node/edge canonical ids.',
261
- inputSchema: {
262
- type: 'object',
263
- additionalProperties: false,
264
- properties: { id: { type: 'string', minLength: 1, maxLength: 512 } },
265
- required: ['id'],
266
- },
267
- async handler({ id }, ctx) {
268
- const { graph, failure } = _loadOrFailure(ctx.sessionRoot);
269
- if (failure) return failure;
270
- const { status, body } = (0,routes/* handleFlow */.jg)(graph, id);
271
- return {
272
- _meta: META,
273
- hasResult: true,
274
- notFound: status === 404,
275
- data: body.data,
276
- canonicalIds: body.canonicalIds,
277
- };
278
- },
279
- };
280
-
281
- ;// CONCATENATED MODULE: ./src/posture/agents-memory.js
282
- // AGENTS.md — writable continual-learning memory (harness-anatomy #2).
283
- //
284
- // LangChain post:
285
- // "Harnesses support memory file standards like AGENTS.md which get
286
- // injected into context on agent start. As agents add and edit this file,
287
- // harnesses load the updated file into context. This is a form of
288
- // continual learning where agents durably store knowledge from one
289
- // session and inject that knowledge into future sessions."
290
- //
291
- // Distinct from CLAUDE.md:
292
- // - CLAUDE.md = human-authored project conventions, gotchas, layout.
293
- // - AGENTS.md = agent-authored notes ("what worked / didn't work / I'd try
294
- // differently next time"). Append-only. Bounded.
295
- //
296
- // Lives at `<project>/.agentic-security/AGENTS.md`.
297
- //
298
- // Bounds:
299
- // - MAX_BYTES (default 20 KB) — past this, the oldest entries rotate to
300
- // `AGENTS.md.archive` (also bounded; oldest archive entries are dropped).
301
- // - MAX_ENTRY_BYTES (default 2 KB) — caps a single appendage.
302
- // - Entries are append-only with an ISO timestamp + section divider, so
303
- // readers can grep / slice by date without parsing.
304
- //
305
- // We deliberately avoid tying AGENTS.md to a session-id namespace. The post's
306
- // recommendation is FLAT continual learning — the whole project's agents see
307
- // each other's notes. Subagents that want session-scoped scratch use the
308
- // agent-scratchpad surface instead.
309
-
310
-
311
-
312
-
313
-
314
- const MEMORY_FILE = '.agentic-security/AGENTS.md';
315
- const ARCHIVE_FILE = '.agentic-security/AGENTS.md.archive';
316
- const MAX_BYTES = 20 * 1024;
317
- const MAX_ENTRY_BYTES = 2 * 1024;
318
- const ARCHIVE_MAX_BYTES = 200 * 1024;
319
- 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';
320
-
321
- function _resolve(scanRoot) { return (0,state_dir/* statePath */.BQ)(scanRoot, 'AGENTS.md'); }
322
- function _archivePath(scanRoot) { return (0,state_dir/* statePath */.BQ)(scanRoot, 'AGENTS.md.archive'); }
323
-
324
- function readAgentsMemory(scanRoot) {
325
- const fp = _resolve(scanRoot);
326
- if (!external_node_fs_.existsSync(fp)) return '';
327
- try { return external_node_fs_.readFileSync(fp, 'utf8'); } catch { return ''; }
328
- }
329
-
330
- function appendAgentsMemory(scanRoot, { agent, body }) {
331
- if (typeof agent !== 'string' || !agent.length) {
332
- return { ok: false, reason: 'agent: required string' };
333
- }
334
- if (!/^[A-Za-z0-9_.-]{1,64}$/.test(agent)) {
335
- return { ok: false, reason: 'agent: must match [A-Za-z0-9_.-]{1,64}' };
336
- }
337
- if (typeof body !== 'string' || !body.trim().length) {
338
- return { ok: false, reason: 'body: required non-empty string' };
339
- }
340
- let snippet = body.trim();
341
- // Strip control chars and cap.
342
- snippet = snippet.replace(/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/g, ' ');
343
- if (snippet.length > MAX_ENTRY_BYTES) {
344
- snippet = snippet.slice(0, MAX_ENTRY_BYTES) + '…';
345
- }
346
- const ts = new Date().toISOString();
347
- const entry = `\n## ${ts} agent: ${agent}\n\n${snippet}\n`;
348
- try {
349
- const fp = _resolve(scanRoot);
350
- if (!(0,state_dir.stateWritesEnabled)()) return;
351
- external_node_fs_.mkdirSync(external_node_path_.dirname(fp), { recursive: true });
352
- if (!external_node_fs_.existsSync(fp)) external_node_fs_.writeFileSync(fp, HEADER);
353
- external_node_fs_.appendFileSync(fp, entry);
354
- _maybeRotate(scanRoot);
355
- const stat = external_node_fs_.statSync(fp);
356
- return { ok: true, entryBytes: entry.length, fileSize: stat.size };
357
- } catch (e) {
358
- return { ok: false, reason: `write-failed: ${e.message}` };
359
- }
360
- }
361
-
362
- function _maybeRotate(scanRoot) {
363
- const fp = _resolve(scanRoot);
364
- let body;
365
- try { body = external_node_fs_.readFileSync(fp, 'utf8'); } catch { return; }
366
- if (body.length <= MAX_BYTES) return;
367
- // Split on the `## ` entry headers. Keep the most-recent N until the head
368
- // (everything before the cut) drops below MAX_BYTES/2; move the head to
369
- // the archive.
370
- const head = HEADER;
371
- const trailing = body.slice(head.length);
372
- const sections = trailing.split(/(?=\n## )/g).filter(s => s.length);
373
- // Walk from the end, accumulating until we have roughly MAX_BYTES/2 of
374
- // recent entries. Everything else goes to the archive.
375
- let kept = '', archive = '', accum = 0;
376
- for (let i = sections.length - 1; i >= 0; i--) {
377
- if (accum + sections[i].length <= MAX_BYTES / 2) {
378
- kept = sections[i] + kept;
379
- accum += sections[i].length;
380
- } else {
381
- archive = sections.slice(0, i + 1).join('') + archive;
382
- break;
383
- }
384
- }
385
- try {
386
- external_node_fs_.writeFileSync(fp, head + kept);
387
- if (archive.length) {
388
- const arcFp = _archivePath(scanRoot);
389
- let existing = '';
390
- try { existing = external_node_fs_.existsSync(arcFp) ? external_node_fs_.readFileSync(arcFp, 'utf8') : ''; } catch {}
391
- let next = existing + archive;
392
- if (next.length > ARCHIVE_MAX_BYTES) {
393
- // Drop oldest entries until under cap.
394
- const oldestSplit = next.split(/(?=\n## )/g).filter(s => s.length);
395
- while (oldestSplit.length && next.length > ARCHIVE_MAX_BYTES) {
396
- oldestSplit.shift();
397
- next = oldestSplit.join('');
398
- }
399
- }
400
- external_node_fs_.writeFileSync(arcFp, next);
401
- }
402
- } catch { /* best-effort rotation */ }
403
- }
404
-
405
- // Public summary helper for the SessionStart hook. Returns a tail aligned
406
- // to a section header (no leading partial entry, no leading newline).
407
- function summarizeForSession(scanRoot, { maxBytes = 6 * 1024 } = {}) {
408
- const body = readAgentsMemory(scanRoot);
409
- if (!body) return null;
410
- if (body.length <= maxBytes) return body;
411
- const tail = body.slice(-maxBytes);
412
- const firstSection = tail.indexOf('\n## ');
413
- if (firstSection < 0) return tail;
414
- // Slice past the leading `\n` so the result starts with `## `.
415
- return tail.slice(firstSection + 1);
416
- }
417
-
418
- const _internals = { MAX_BYTES, MAX_ENTRY_BYTES, MEMORY_FILE, ARCHIVE_FILE };
419
-
420
- // EXTERNAL MODULE: external "node:os"
421
- var external_node_os_ = __webpack_require__(8161);
422
- ;// CONCATENATED MODULE: ./src/posture/cve-lookup.js
423
- // CVE lookup — read-only against the per-install OSV / KEV / EPSS caches.
424
- //
425
- // LangChain harness-anatomy post:
426
- // "Knowledge cutoffs mean that models can't directly access new data like
427
- // updated library versions without the user providing them directly."
428
- //
429
- // The validator and any subagent reasoning about an SCA finding can call
430
- // `lookup_cve(cve_id)` to get the most recently-cached OSV advisory, the
431
- // CISA KEV entry if listed, and the EPSS exploit-prediction percentile, all
432
- // with `staleness` metadata so the caller can decide whether to trust the
433
- // cached value.
434
- //
435
- // This module deliberately NEVER triggers a network fetch — the scan
436
- // pipeline is the only thing that populates the cache. If a CVE isn't
437
- // cached, we return `present: false` for that source rather than blocking
438
- // on a fetch and risking a multi-second MCP timeout.
439
-
440
-
441
-
442
-
443
-
444
-
445
- const CACHE_DIR = external_node_path_.join(external_node_os_.homedir(), '.claude', 'agentic-security', 'osv-cache');
446
-
447
- function _keyToPath(key) {
448
- const safe = external_node_crypto_.createHash('sha256').update(key).digest('hex');
449
- return external_node_path_.join(CACHE_DIR, safe + '.json');
450
- }
451
-
452
- function _readCache(key) {
453
- const fp = _keyToPath(key);
454
- if (!external_node_fs_.existsSync(fp)) return { present: false };
455
- let body;
456
- try { body = external_node_fs_.readFileSync(fp, 'utf8'); }
457
- catch { return { present: false, error: 'unreadable' }; }
458
- let parsed;
459
- try { parsed = JSON.parse(body); }
460
- catch { return { present: false, error: 'unparseable' }; }
461
- let mtime = null;
462
- try { mtime = external_node_fs_.statSync(fp).mtimeMs; } catch {}
463
- return { present: true, data: parsed, cachedAt: mtime, ageMs: mtime ? Date.now() - mtime : null };
464
- }
465
-
466
- function _stalenessTier(ageMs) {
467
- if (ageMs === null || ageMs === undefined) return 'unknown';
468
- if (ageMs < 24 * 3600 * 1000) return 'fresh'; // <1d
469
- if (ageMs < 7 * 24 * 3600 * 1000) return 'recent'; // <1w
470
- if (ageMs < 30 * 24 * 3600 * 1000) return 'stale'; // <1mo
471
- return 'very-stale';
472
- }
473
-
474
- const CVE_RE = /^CVE-\d{4}-\d{1,7}$/i;
475
-
476
- function lookupCve(rawId) {
477
- if (typeof rawId !== 'string' || !CVE_RE.test(rawId)) {
478
- return { ok: false, reason: 'invalid-cve-id', expected: 'CVE-YYYY-NNNN' };
479
- }
480
- const cve = rawId.toUpperCase();
481
-
482
- // KEV catalog — single cached blob keyed at 'kev:catalog'.
483
- const kevCacheRaw = _readCache('kev:catalog');
484
- let kev = { present: false };
485
- if (kevCacheRaw.present) {
486
- // The blob shape from engine.js: { ts, byCve: { 'CVE-XXX': { ... } } }
487
- // sessionStorage shim stores the value as the JSON-stringified inner
488
- // object directly (no extra wrapper).
489
- const blob = kevCacheRaw.data;
490
- const byCve = blob?.byCve || null;
491
- if (byCve && byCve[cve]) {
492
- kev = {
493
- present: true,
494
- ...byCve[cve],
495
- cachedAt: kevCacheRaw.cachedAt,
496
- ageMs: kevCacheRaw.ageMs,
497
- staleness: _stalenessTier(kevCacheRaw.ageMs),
498
- };
499
- } else if (byCve) {
500
- // Catalog is cached but doesn't list this CVE — meaningful negative.
501
- kev = {
502
- present: false, listedInCatalog: false,
503
- cachedAt: kevCacheRaw.cachedAt, ageMs: kevCacheRaw.ageMs,
504
- staleness: _stalenessTier(kevCacheRaw.ageMs),
505
- };
506
- }
507
- }
508
-
509
- // EPSS — per-CVE cache at 'epss:CVE-XXX'.
510
- const epssRaw = _readCache('epss:' + cve);
511
- let epss = { present: false };
512
- if (epssRaw.present) {
513
- epss = {
514
- present: epssRaw.data !== false, // engine stores `false` for "looked up, no record"
515
- score: epssRaw.data?.score ?? null,
516
- percentile: epssRaw.data?.percentile ?? null,
517
- cachedAt: epssRaw.cachedAt,
518
- ageMs: epssRaw.ageMs,
519
- staleness: _stalenessTier(epssRaw.ageMs),
520
- };
521
- }
522
-
523
- // OSV — entries are keyed by vuln id (GHSA-... or CVE-...). The engine
524
- // caches them at 'vuln:<id>'. We do a direct CVE lookup AND a soft probe
525
- // for any known alias the caller provided implicitly through the KEV
526
- // hit's vendor/product (no — we keep this simple: direct lookup only).
527
- const osvRaw = _readCache('vuln:' + cve);
528
- let osv = { present: false };
529
- if (osvRaw.present) {
530
- osv = {
531
- present: true,
532
- data: osvRaw.data,
533
- cachedAt: osvRaw.cachedAt, ageMs: osvRaw.ageMs,
534
- staleness: _stalenessTier(osvRaw.ageMs),
535
- };
536
- }
537
-
538
- return {
539
- ok: true,
540
- cve,
541
- kev,
542
- epss,
543
- osv,
544
- sourcesFound: [kev.present, epss.present, osv.present].filter(Boolean).length,
545
- note: (kev.present || epss.present || osv.present)
546
- ? 'cached values only; staleness tier per source. The MCP tool does NOT trigger a network fetch.'
547
- : '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.',
548
- };
549
- }
550
-
551
- const cve_lookup_internals = { CACHE_DIR, CVE_RE, _stalenessTier };
552
-
553
- ;// CONCATENATED MODULE: ./src/mcp/tools.js
554
- // MCP tool implementations — PRD Feature 2, hardened against the OWASP MCP
555
- // Top 10 (see ./redact.js, ./audit.js, ./server.js for sibling controls).
556
- //
557
- // Trust model:
558
- // - Session root fixed at server boot. No per-call retargeting.
559
- // - Path arguments lstat-checked (symlinks refused, OWASP MCP05) and
560
- // realpath-confined to session root.
561
- // - Tool outputs marked _meta.untrusted_excerpts:true (OWASP MCP03/MCP06)
562
- // because they may contain text from scanned files, which is adversary-
563
- // controlled in any context where the agent might read malicious code.
564
- // - Secret-shaped strings redacted on the way out (OWASP MCP01/MCP10).
565
- // - `apply_fix` requires confirm:true, valid HMAC signature on
566
- // last-scan.json, non-shadow finding, and confined file path.
567
-
568
-
569
-
570
-
571
-
572
-
573
-
574
-
575
-
576
-
577
-
578
-
579
-
580
-
581
-
582
- // Git-origin provenance (Finding Provenance M0/M1). Distinct from
583
- // `finding.provenance` (AI-authorship) and from an SCA entry's `provenance`
584
- // (Sigstore/SLSA attestation) — see report/index.js's import comment.
585
-
586
-
587
-
588
- // Lazy-loaded: these transitively pull in npm packages (@babel/core and
589
- // friends) that aren't available in the plugin-cache install path
590
- // (no node_modules). Deferring keeps the MCP server bootable everywhere;
591
- // the import only runs when a tool that needs them is actually called.
592
- let _runScan;
593
- async function getRunScan() {
594
- if (!_runScan) _runScan = (await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 454))).runScan;
595
- return _runScan;
596
- }
597
- let _verifyFixCore;
598
- async function getVerifyFixCore() {
599
- if (!_verifyFixCore) _verifyFixCore = (await __webpack_require__.e(/* import() */ 3526).then(__webpack_require__.bind(__webpack_require__, 3526))).verifyFix;
600
- return _verifyFixCore;
601
- }
602
-
603
- const MAX_FILES_PER_SCAN = 1024;
604
- const MAX_FILE_BYTES = 500_000;
605
- const MAX_TOTAL_SCAN_BYTES = 50_000_000;
606
- const tools_META = { source: 'agentic-security-mcp', untrusted_excerpts: true };
607
-
608
- // OWASP A01 — refuse writes to paths that could subvert the security tool
609
- // itself or the host's source-control / dependency state. A forged finding
610
- // could otherwise tell apply_fix to overwrite our own rules.yml, our audit
611
- // log, a .git/hooks/post-commit payload, a CI workflow, an IaC file, or a
612
- // dependency manifest (premortem #3 expansion).
613
- //
614
- // Two kinds of guard:
615
- // - DIR-prefix matches anywhere under one of these directories
616
- // - FILE-suffix matches any path whose basename ends with one of these
617
- const RESERVED_WRITE_PREFIXES = [
618
- '.git/',
619
- '.github/',
620
- '.gitlab/',
621
- '.circleci/',
622
- '.buildkite/',
623
- '.agentic-security/',
624
- 'node_modules/',
625
- '.terraform/',
626
- '.aws/',
627
- 'k8s/',
628
- 'kubernetes/',
629
- ];
630
- const RESERVED_WRITE_BASENAMES = new Set([
631
- 'Dockerfile',
632
- 'Jenkinsfile',
633
- '.gitlab-ci.yml',
634
- '.gitlab-ci.yaml',
635
- 'package.json',
636
- 'package-lock.json',
637
- 'yarn.lock',
638
- 'pnpm-lock.yaml',
639
- 'pyproject.toml',
640
- 'Pipfile',
641
- 'Pipfile.lock',
642
- 'poetry.lock',
643
- 'requirements.txt',
644
- 'go.mod',
645
- 'go.sum',
646
- 'Cargo.toml',
647
- 'Cargo.lock',
648
- 'composer.json',
649
- 'composer.lock',
650
- 'Gemfile',
651
- 'Gemfile.lock',
652
- 'pom.xml',
653
- 'build.gradle',
654
- 'build.gradle.kts',
655
- ]);
656
- const RESERVED_WRITE_SUFFIXES = [
657
- '.tf',
658
- '.tfvars',
659
- 'docker-compose.yml',
660
- 'docker-compose.yaml',
661
- // _CONFINEMENT rule 3 — backup and lock files. The specific lock BASENAMES
662
- // above cover the ecosystems we know; this catches the rest (`deps.lock`,
663
- // `foo.bak`) without needing to enumerate them. Nothing an autofix should
664
- // ever be rewriting: a `.bak` is someone's safety copy and a `.lock` is
665
- // generated state.
666
- '.bak',
667
- '.lock',
668
- ];
669
- // _CONFINEMENT rule 3 — build output. Matched as a PATH SEGMENT at any depth,
670
- // not as a top-level prefix, because build output is routinely nested
671
- // (`packages/web/dist/`, `services/api/target/`) and a top-level-only check
672
- // would refuse the monorepo root and allow every package inside it.
673
- //
674
- // This matters most in THIS repository: `scanner/dist/` holds the shipped
675
- // bundle, which carries its own SHA-256 integrity sidecar precisely because
676
- // what it contains matters. Before this, `apply_fix` would rewrite it and
677
- // report success.
678
- //
679
- // NOTE for a future change, deliberately not made here: the PREFIX list above
680
- // (`node_modules/`, `.git/`, …) is still top-level-only, so a nested
681
- // `packages/a/node_modules/` is not covered by it. That is a separate widening
682
- // with its own blast radius and belongs in its own change with its own tests.
683
- const RESERVED_WRITE_DIR_SEGMENTS = new Set(['dist', 'build', 'target']);
684
- function _isReservedWritePath(sessionRoot, absFile) {
685
- // Resolve sessionRoot symlinks so the relative path is computed against
686
- // the same canonical root as `absFile` (which _confine already realpath'd).
687
- // On macOS /tmp → /private/tmp; without this normalization the relative
688
- // would contain "../" and the prefix check would miss the reserved path.
689
- const rootReal = external_node_fs_.realpathSync(external_node_path_.resolve(sessionRoot));
690
- const rel = external_node_path_.relative(rootReal, absFile).replace(/\\/g, '/');
691
- if (RESERVED_WRITE_PREFIXES.some(p => rel === p.replace(/\/$/, '') || rel.startsWith(p))) return true;
692
- const segments = rel.split('/');
693
- const base = segments[segments.length - 1] || '';
694
- if (RESERVED_WRITE_BASENAMES.has(base)) return true;
695
- if (RESERVED_WRITE_SUFFIXES.some(s => base === s || base.endsWith(s))) return true;
696
- // Any DIRECTORY segment that names build output — checked over
697
- // `segments.length - 1` so a source file legitimately called `build` or
698
- // `dist` is not refused for its own name; only living inside such a
699
- // directory counts.
700
- if (segments.slice(0, -1).some(seg => RESERVED_WRITE_DIR_SEGMENTS.has(seg))) return true;
701
- return false;
702
- }
703
-
704
- // LangChain harness-anatomy recommendation: the filesystem is the right
705
- // collaboration / scratchpad surface for subagents. We carve out one writable
706
- // directory inside the otherwise-reserved `.agentic-security/` tree —
707
- // `.agentic-security/agent-scratchpad/<agent>/<session>/` — and expose
708
- // `append_scratchpad` / `read_scratchpad` for in-progress agent state.
709
- //
710
- // Confinement rules:
711
- // - relative path required (no absolute / no `..`)
712
- // - must start with `agent-scratchpad/<agent>/<session>/`
713
- // - `<agent>` and `<session>` are restricted to `[A-Za-z0-9_.-]{1,64}`
714
- // (no slashes — keeps the prefix exactly three components deep)
715
- // - file basename: same charset rules
716
- // - max scratchpad bytes per file: SCRATCHPAD_MAX_FILE_BYTES
717
- const SCRATCHPAD_PREFIX = '.agentic-security/agent-scratchpad/';
718
- const SCRATCHPAD_NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
719
- const SCRATCHPAD_MAX_FILE_BYTES = 2 * 1024 * 1024; // 2 MB per file
720
- const SCRATCHPAD_MAX_TOTAL_BYTES = 50 * 1024 * 1024; // 50 MB per scan root
721
-
722
- function _validateScratchpadPath(relPath) {
723
- if (typeof relPath !== 'string' || !relPath.length) {
724
- return { ok: false, reason: 'path: not a string' };
725
- }
726
- if (external_node_path_.isAbsolute(relPath)) return { ok: false, reason: 'path: must be relative' };
727
- if (relPath.includes('..')) return { ok: false, reason: 'path: must not contain ..' };
728
- const normalized = relPath.replace(/\\/g, '/');
729
- if (!normalized.startsWith(SCRATCHPAD_PREFIX)) {
730
- return { ok: false, reason: `path: must start with "${SCRATCHPAD_PREFIX}"` };
731
- }
732
- const rest = normalized.slice(SCRATCHPAD_PREFIX.length);
733
- const parts = rest.split('/');
734
- if (parts.length < 3) {
735
- return { ok: false, reason: 'path: must be agent-scratchpad/<agent>/<session>/<file>' };
736
- }
737
- const [agent, session, ...fileParts] = parts;
738
- if (!SCRATCHPAD_NAME_RE.test(agent)) return { ok: false, reason: `path: agent name "${agent}" not in [A-Za-z0-9_.-]{1,64}` };
739
- if (!SCRATCHPAD_NAME_RE.test(session)) return { ok: false, reason: `path: session id "${session}" not in [A-Za-z0-9_.-]{1,64}` };
740
- for (const p of fileParts) {
741
- if (!SCRATCHPAD_NAME_RE.test(p)) return { ok: false, reason: `path: file part "${p}" not in [A-Za-z0-9_.-]{1,64}` };
742
- }
743
- return { ok: true, agent, session, fileParts };
744
- }
745
-
746
- // Routes through the same lstat+realpath confinement every other write/
747
- // path-taking tool uses (OWASP MCP05) — a lexical prefix/charset check
748
- // alone doesn't stop a pre-planted symlink at any path component from
749
- // relocating the write/read outside the session root. Throws on escape;
750
- // callers must catch (see append_scratchpad / read_scratchpad).
751
- function _scratchpadAbs(sessionRoot, relPath) {
752
- return _confine(sessionRoot, relPath.replace(/\\/g, '/'), 'scratchpad path');
753
- }
754
-
755
- function _scratchpadTotalBytes(sessionRoot) {
756
- const base = (0,state_dir/* statePath */.BQ)(sessionRoot, 'agent-scratchpad');
757
- if (!external_node_fs_.existsSync(base)) return 0;
758
- let total = 0;
759
- const walk = (dir) => {
760
- let entries;
761
- try { entries = external_node_fs_.readdirSync(dir, { withFileTypes: true }); } catch { return; }
762
- for (const e of entries) {
763
- const fp = external_node_path_.join(dir, e.name);
764
- try {
765
- if (e.isFile()) { total += external_node_fs_.statSync(fp).size; }
766
- else if (e.isDirectory()) walk(fp);
767
- } catch { /* skip */ }
768
- }
769
- };
770
- walk(base);
771
- return total;
772
- }
773
-
774
- // ─── Path confinement ────────────────────────────────────────────────────────
775
- // Lexical check + lstat symlink reject + realpath re-check. OWASP MCP05.
776
- //
777
- // For non-existent paths (apply_fix to a new file is a possible legitimate
778
- // case; in practice we re-check existence at the use-site) we walk up the
779
- // deepest existing ancestor and realpath that, so a parent-symlink can't
780
- // silently relocate writes.
781
- function _confine(sessionRoot, candidate, label) {
782
- if (typeof candidate !== 'string' || !candidate) throw new Error(`${label}: not a string`);
783
- const rootReal = external_node_fs_.realpathSync(external_node_path_.resolve(sessionRoot));
784
- const abs = external_node_path_.isAbsolute(candidate) ? candidate : external_node_path_.resolve(rootReal, candidate);
785
-
786
- // Lexical pre-check: rejects "../../etc/passwd" before any fs call.
787
- const relLex = external_node_path_.relative(rootReal, external_node_path_.resolve(abs));
788
- if (relLex === '' || relLex.startsWith('..') || external_node_path_.isAbsolute(relLex)) {
789
- throw new Error(`${label}: path "${candidate}" escapes session root`);
790
- }
791
-
792
- // If the path exists, the leaf must not be a symlink and its realpath
793
- // must still be under rootReal.
794
- if (external_node_fs_.existsSync(abs)) {
795
- if (external_node_fs_.lstatSync(abs).isSymbolicLink()) {
796
- throw new Error(`${label}: path "${candidate}" is a symbolic link (refused)`);
797
- }
798
- const real = external_node_fs_.realpathSync(abs);
799
- if (external_node_path_.relative(rootReal, real).startsWith('..')) {
800
- throw new Error(`${label}: path "${candidate}" resolves outside session root via symlink`);
801
- }
802
- return real;
803
- }
804
-
805
- // Path doesn't exist — walk up to the deepest existing ancestor and
806
- // realpath that. If a parent dir is a symlink pointing outside rootReal
807
- // we catch it here.
808
- let parent = external_node_path_.dirname(abs);
809
- while (parent !== external_node_path_.dirname(parent) && !external_node_fs_.existsSync(parent)) {
810
- parent = external_node_path_.dirname(parent);
811
- }
812
- const parentReal = external_node_fs_.realpathSync(parent);
813
- if (external_node_path_.relative(rootReal, parentReal).startsWith('..')) {
814
- throw new Error(`${label}: path "${candidate}" parent resolves outside session root`);
815
- }
816
- const suffix = external_node_path_.relative(parent, abs);
817
- return external_node_path_.resolve(parentReal, suffix);
818
- }
819
-
820
- function _readLastScanVerified(sessionRoot, { allowUnsigned = false } = {}) {
821
- const stateDirPath = (0,state_dir/* stateDir */.Pn)(sessionRoot);
822
- const scanFile = external_node_path_.join(stateDirPath, 'last-scan.json');
823
- const sigFile = scanFile + '.sig';
824
- if (!external_node_fs_.existsSync(scanFile)) return { scan: null, status: 'missing' };
825
- const body = external_node_fs_.readFileSync(scanFile, 'utf8');
826
- const ok = (0,integrity/* verifyLastScan */.Ef)(body, sigFile);
827
- if (ok === false) return { scan: null, status: 'tampered' };
828
- if (ok === null && !allowUnsigned) return { scan: null, status: 'unsigned' };
829
- let parsed;
830
- try { parsed = JSON.parse(body); }
831
- catch { return { scan: null, status: 'unparseable' }; }
832
- return { scan: parsed, status: ok ? 'verified' : 'unsigned' };
833
- }
834
-
835
- function _findById(scan, id) {
836
- if (!scan) return null;
837
- return (scan.findings || []).find(f => f.id === id)
838
- || (scan.secrets || []).find(f => f.id === id)
839
- || (scan.supplyChain || []).find(f => f.id === id)
840
- || (scan.logicVulns || []).find(f => f.id === id)
841
- || null;
842
- }
843
-
844
- // ─── Tool-output offloading (harness-anatomy #1) ────────────────────────────
845
- // LangChain post: "the harness keeps the head and tail tokens of tool outputs
846
- // above a threshold number of tokens and offloads the full output to the
847
- // filesystem." We apply this to any MCP tool response whose findings array
848
- // exceeds OFFLOAD_THRESHOLD entries: write the full list to a scratchpad
849
- // file, return only head[0..3] + tail[-2..] + total + path. The agent can
850
- // call `read_scratchpad(path)` to page through the rest.
851
- //
852
- // Design choices:
853
- // - Threshold is conservative (10) — anything bigger than a casual UI page
854
- // gets offloaded. Tunable via $AGENTIC_SECURITY_MCP_OFFLOAD_THRESHOLD.
855
- // - Offload location is the agent-scratchpad (not a separate dir) so the
856
- // same cleanup + size caps apply.
857
- // - File names are deterministic per response (sha256 of JSON.stringify)
858
- // so two identical responses share the same offload file.
859
- // - The session id is process.pid + boot timestamp short hash — collides
860
- // only across restarts within a millisecond, which is fine for cache.
861
- const OFFLOAD_THRESHOLD = (() => {
862
- const v = parseInt(process.env.AGENTIC_SECURITY_MCP_OFFLOAD_THRESHOLD || '10', 10);
863
- return Number.isFinite(v) && v >= 1 ? v : 10;
864
- })();
865
- const MCP_SESSION_ID = `${process.pid}-${Date.now().toString(36).slice(-6)}`;
866
-
867
- function _maybeOffload(sessionRoot, toolName, items) {
868
- if (!Array.isArray(items) || items.length <= OFFLOAD_THRESHOLD) {
869
- return { offloaded: false, items, total: items.length };
870
- }
871
- const head = items.slice(0, 3);
872
- const tail = items.slice(-2);
873
- const json = JSON.stringify({ tool: toolName, total: items.length, items }, null, 2);
874
- const hashShort = external_node_crypto_.createHash('sha256').update(json).digest('hex').slice(0, 10);
875
- const rel = `.agentic-security/agent-scratchpad/mcp-offload/${MCP_SESSION_ID}/${toolName}-${hashShort}.json`;
876
- const abs = external_node_path_.resolve(sessionRoot, rel);
877
- try {
878
- external_node_fs_.mkdirSync(external_node_path_.dirname(abs), { recursive: true });
879
- external_node_fs_.writeFileSync(abs, json);
880
- } catch (e) {
881
- // If we can't write to disk for some reason, fall back to returning
882
- // everything — the alternative would be silently dropping data, which
883
- // is worse than blowing the context.
884
- return { offloaded: false, items, total: items.length, offloadError: e.message };
885
- }
886
- return {
887
- offloaded: true,
888
- head, tail, total: items.length,
889
- scratchpadPath: rel,
890
- pagingHint: `call read_scratchpad({ path: "${rel}", offset, limit }) to page through; the file is { tool, total, items: [...] } JSON`,
891
- };
892
- }
893
-
894
- // ─── scan_diff ───────────────────────────────────────────────────────────────
895
- // Test seam for the write boundary (PRD F6.4).
896
- //
897
- // `_confine` and `isReservedWrite` ARE the confinement contract in
898
- // agents/_CONFINEMENT.md. A boundary is only worth what its refusals are worth,
899
- // and refusals cannot be adversarially tested through the public tools without
900
- // also exercising a real scan, a real patch and a real filesystem write — so
901
- // the check would be measuring four things and attributing failure to one.
902
- //
903
- // Exported under the `_internals` convention this codebase already uses
904
- // (see posture/poc-inprocess.js). Not part of the MCP tool surface.
905
- const tools_internals = { _confine, isReservedWrite: _isReservedWritePath };
906
-
907
- const scan_diff = {
908
- name: 'scan_diff',
909
- 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.',
910
- inputSchema: {
911
- type: 'object',
912
- additionalProperties: false,
913
- properties: {
914
- files: {
915
- type: 'array', minItems: 1, maxItems: MAX_FILES_PER_SCAN,
916
- items: { type: 'string', minLength: 1, maxLength: 4096 },
917
- },
918
- severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low', 'info'] },
919
- },
920
- required: ['files'],
921
- },
922
- async handler({ files, severity }, ctx) {
923
- const sessionRoot = ctx.sessionRoot;
924
- const abs = files.map(f => _confine(sessionRoot, f, 'files[]'));
925
-
926
- const fileContents = {};
927
- let totalBytes = 0;
928
- for (const a of abs) {
929
- let stat;
930
- try { stat = external_node_fs_.statSync(a); } catch { continue; }
931
- if (!stat.isFile()) continue;
932
- if (stat.size > MAX_FILE_BYTES) continue;
933
- totalBytes += stat.size;
934
- if (totalBytes > MAX_TOTAL_SCAN_BYTES) {
935
- throw new Error(`scan_diff: total scan size exceeds ${MAX_TOTAL_SCAN_BYTES} bytes`);
936
- }
937
- let content;
938
- try { content = external_node_fs_.readFileSync(a, 'utf8'); } catch { continue; }
939
- const rel = external_node_path_.relative(sessionRoot, a).replace(/\\/g, '/');
940
- fileContents[rel] = content;
941
- }
942
-
943
- // PRD R1 (docs/DETECTION_GAP_REMEDIATION_PRD.md): deep mode is default-on
944
- // for the interactive CLI scan but was never requested here, so an
945
- // agent's pre-write self-correction scan was regex/AST-only — blind to
946
- // any bug whose source and sink are connected only through a call
947
- // (`fileContents` scopes the deep engine's IR to exactly the files
948
- // passed in, same bound this tool already enforces via MAX_FILES_PER_SCAN
949
- // / MAX_TOTAL_SCAN_BYTES, so this does not turn scan_diff into a
950
- // full-project deep scan).
951
- const runScan = await getRunScan();
952
- // FR-704 (assurance-hardening PRD): this tool's own description promises
953
- // "runs scan in memory" — without this, runFullScan's own state writers
954
- // (dpia.md, ropa.md, privacy-framework.json, threat-model.json, and
955
- // others) fire unconditionally on every call, silently mutating the
956
- // user's real project on every pre-write self-correction scan. Confirmed
957
- // by direct execution before this fix (11 state artifacts written by a
958
- // single scan_diff-shaped call).
959
- const result = await (0,state_dir/* withStateWritesDisabled */.Ao)(() =>
960
- runScan(sessionRoot, { network: false, fileContents, deep: true, deepInCi: true }));
961
- const wantSet = new Set(Object.keys(fileContents));
962
- const sevRank = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
963
- const min = sevRank[severity] ?? 0;
964
- // Stage 6 correctness audit (historical): this used to only read
965
- // result.scan.findings (the SAST channel) — scan.secrets and
966
- // scan.logicVulns are separate arrays on the raw runScan() result, and a
967
- // hand-rolled 3-channel concat here was a second, divergent copy of the
968
- // merge report/index.js's normalizeFindings() already does (four
969
- // channels, plus per-channel defaulting and remediation-string
970
- // resolution the old concat re-implemented separately and could drift
971
- // from). Assurance-hardening PRD FR-105 ("JSON, SARIF, HTML, CSV, JUnit,
972
- // and MCP outputs derive from the same validated object"): route through
973
- // the same canonical merge every other output format uses.
974
- //
975
- // This closes the field-mapping/dedup divergence, but does NOT make
976
- // scan_diff surface SCA/supply-chain findings end to end: this handler
977
- // never builds a `depFileContents` map (everything a caller passes in
978
- // `files`, manifests included, lands in `fileContents`), and manifest-
979
- // based supply-chain detection in engine.js reads only `depFileContents`
980
- // — so `result.scan.supplyChain` is always empty for this tool today
981
- // regardless of this fix. That is a separate, real limitation (scan_diff
982
- // was designed for pre-write code self-correction, not manifest
983
- // scanning), left as-is rather than silently claimed fixed here.
984
- const findings = (0,report.normalizeFindings)(result.scan)
985
- .filter(f => wantSet.has(String(f.file || '').replace(/\\/g, '/')) && (sevRank[f.severity] ?? 0) >= min)
986
- .map(f => (0,redact/* redactFinding */.lE)({
987
- id: f.id, severity: f.severity, file: f.file, line: f.line,
988
- title: f.vuln, cwe: f.cwe,
989
- description: f.description, remediation: f.remediation,
990
- }));
991
- // Harness-anatomy #1: offload when the result exceeds OFFLOAD_THRESHOLD.
992
- // The agent gets a head+tail preview plus a path it can page through;
993
- // the full finding list lives on disk. This is the documented fix for
994
- // "context rot" — large tool outputs eat the model's attention budget.
995
- const off = _maybeOffload(sessionRoot, 'scan_diff', findings);
996
- if (off.offloaded) {
997
- return {
998
- _meta: tools_META,
999
- scannedFiles: Object.keys(fileContents).length,
1000
- findingCount: off.total,
1001
- offloaded: true,
1002
- head: off.head, tail: off.tail,
1003
- scratchpadPath: off.scratchpadPath,
1004
- pagingHint: off.pagingHint,
1005
- };
1006
- }
1007
- return {
1008
- _meta: tools_META,
1009
- scannedFiles: Object.keys(fileContents).length,
1010
- findingCount: findings.length,
1011
- findings,
1012
- };
1013
- },
1014
- };
1015
-
1016
- // ─── query_taint ─────────────────────────────────────────────────────────────
1017
- const query_taint = {
1018
- name: 'query_taint',
1019
- 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.',
1020
- inputSchema: {
1021
- type: 'object',
1022
- additionalProperties: false,
1023
- properties: {
1024
- source: { type: 'string', minLength: 1, maxLength: 256 },
1025
- sink: { type: 'string', minLength: 1, maxLength: 256 },
1026
- limit: { type: 'integer', minimum: 1, maximum: 50 },
1027
- offset: { type: 'integer', minimum: 0, maximum: 10000 },
1028
- },
1029
- required: ['source', 'sink'],
1030
- },
1031
- async handler({ source, sink, limit, offset }, ctx) {
1032
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
1033
- if (!scan) {
1034
- return { _meta: tools_META, hasResult: false, status, message: `No usable scan state (${status}).` };
1035
- }
1036
- const lim = Number.isInteger(limit) ? Math.min(50, Math.max(1, limit)) : 10;
1037
- const off = Number.isInteger(offset) ? Math.max(0, offset) : 0;
1038
- const srcL = String(source).toLowerCase();
1039
- const sinkL = String(sink).toLowerCase();
1040
- // Filter first (cheap), then paginate (so totalMatches is accurate).
1041
- // Harness-engineering note (post-derived): "context window != context
1042
- // attention." Returning hundreds of matches to the agent in one shot
1043
- // dilutes its reasoning; the agent receives a bounded slice plus the
1044
- // cursor to fetch the rest if it wants.
1045
- const all = (scan.findings || []).filter(f => {
1046
- const hay = [f.description, f.title, f.vuln, f.snippet, JSON.stringify(f.trace || '')].join(' ').toLowerCase();
1047
- return hay.includes(srcL) && hay.includes(sinkL);
1048
- });
1049
- const page = all.slice(off, off + lim).map(f => (0,redact/* redactFinding */.lE)({
1050
- id: f.id, severity: f.severity, file: f.file, line: f.line,
1051
- title: f.title || f.vuln, description: f.description,
1052
- trace: f.trace || null,
1053
- }));
1054
- return {
1055
- _meta: tools_META,
1056
- hasResult: true,
1057
- integrity: status,
1058
- scanStartedAt: scan.startedAt || scan.meta?.startedAt || null,
1059
- totalMatches: all.length,
1060
- matchCount: page.length,
1061
- offset: off,
1062
- limit: lim,
1063
- truncated: off + page.length < all.length,
1064
- nextOffset: off + page.length < all.length ? off + page.length : null,
1065
- matches: page,
1066
- };
1067
- },
1068
- };
1069
-
1070
- // ─── explain_finding ─────────────────────────────────────────────────────────
1071
- const explain_finding = {
1072
- name: 'explain_finding',
1073
- description: 'Return full details for a single finding from the last verified scan. Snippet/description redacted of secret patterns.',
1074
- inputSchema: {
1075
- type: 'object',
1076
- additionalProperties: false,
1077
- properties: {
1078
- finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1079
- },
1080
- required: ['finding_id'],
1081
- },
1082
- async handler({ finding_id }, ctx) {
1083
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
1084
- if (!scan) throw new Error(`No usable scan state (${status}).`);
1085
- const f = _findById(scan, finding_id);
1086
- if (!f) throw new Error(`Finding not found: ${finding_id}`);
1087
- const redacted = (0,redact/* redactFinding */.lE)({
1088
- id: f.id, severity: f.severity, file: f.file, line: f.line,
1089
- title: f.title || f.vuln, cwe: f.cwe,
1090
- description: f.description, remediation: f.remediation,
1091
- snippet: f.snippet || null,
1092
- trace: f.trace || null,
1093
- });
1094
- // Harness-anatomy #1: explain_finding's trace is the most-likely-large
1095
- // field on a single finding. Offload when it crosses the threshold so
1096
- // the agent gets a head/tail preview, not a 50-step trace dumped into
1097
- // its context.
1098
- let traceTrimmed = redacted.trace;
1099
- let traceMeta = null;
1100
- if (Array.isArray(redacted.trace) && redacted.trace.length > OFFLOAD_THRESHOLD) {
1101
- const off = _maybeOffload(ctx.sessionRoot, 'explain_finding-trace', redacted.trace);
1102
- if (off.offloaded) {
1103
- traceTrimmed = [...off.head, { _gap: `... ${off.total - off.head.length - off.tail.length} more steps elided; read scratchpad ...` }, ...off.tail];
1104
- traceMeta = {
1105
- totalSteps: off.total,
1106
- scratchpadPath: off.scratchpadPath,
1107
- pagingHint: off.pagingHint,
1108
- };
1109
- }
1110
- }
1111
- return {
1112
- _meta: tools_META,
1113
- ...redacted,
1114
- trace: traceTrimmed,
1115
- traceOffload: traceMeta,
1116
- confidence: f.confidence ?? null,
1117
- hasReplacementFix: typeof f.fix?.replacement === 'string',
1118
- integrity: status,
1119
- // Risk-signal passthrough so agents can decide priority without
1120
- // re-reading last-scan.json or re-fetching OSV/KEV/EPSS. compositeRisk
1121
- // is the canonical sort key; the other fields are its provenance.
1122
- compositeRisk: f.compositeRisk ?? null,
1123
- compositeRiskTier: f.compositeRiskTier ?? null,
1124
- compositeRiskFactors: Array.isArray(f.compositeRiskFactors) ? f.compositeRiskFactors : [],
1125
- exploitability: f.exploitability ?? null,
1126
- exploitabilityTier: f.exploitabilityTier ?? null,
1127
- mitigationVerdict: f.mitigationVerdict ?? null,
1128
- kev: !!(f.kev || f.kevListed || f.weaponized),
1129
- epssScore: typeof f.epssScore === 'number' ? f.epssScore : null,
1130
- epssPercentile: typeof f.epssPercentile === 'number' ? f.epssPercentile : null,
1131
- exploitedNow: !!f.exploitedNow,
1132
- // Which commit introduced this finding. `includeEmail` stays at its
1133
- // DEFAULT (false) unconditionally — unlike the JSON report there is no
1134
- // operator-set env escape for it here, because the consumer is an
1135
- // agent that has no business receiving a committer's email address.
1136
- // `pseudonymize`, by contrast, IS read back from the same env var
1137
- // report/index.js's `_normalizedProvenance` reads
1138
- // (AGENTIC_SECURITY_PSEUDONYMIZE_AUTHORS=1 / --pseudonymize-authors) —
1139
- // fix-round item 4: an operator who set that policy was still getting
1140
- // raw committer names (and, via providerEnrichment, raw reviewer
1141
- // logins/CODEOWNERS lines) through this MCP surface because this call
1142
- // passed no options object at all, silently defeating their policy at
1143
- // this one output boundary while report/index.js honoured it.
1144
- findingProvenance: f.findingProvenance ? (0,schema/* redactFindingProvenance */.As)(f.findingProvenance, {
1145
- pseudonymize: process.env.AGENTIC_SECURITY_PSEUDONYMIZE_AUTHORS === '1',
1146
- }) : null,
1147
- };
1148
- },
1149
- };
1150
-
1151
- // ─── apply_fix ───────────────────────────────────────────────────────────────
1152
- const apply_fix = {
1153
- name: 'apply_fix',
1154
- 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. On success, `verified:true` means verification passed but `verifiedFull:true` is the honest signal that every required leg (lint when configured, tests when a runner exists) genuinely ran — a false `verifiedFull` with `verified:true` means the pass is real but degraded (see `verify.degradedLegs`), not a full verification.',
1155
- inputSchema: {
1156
- type: 'object',
1157
- additionalProperties: false,
1158
- properties: {
1159
- finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1160
- confirm: { type: 'boolean' },
1161
- dry_run: { type: 'boolean' },
1162
- patch: {
1163
- type: 'object',
1164
- additionalProperties: { type: 'string', maxLength: 500_000 },
1165
- minProperties: 1, maxProperties: 8,
1166
- },
1167
- // Stage 6 correctness audit: same gap and same fix as verify_fix — the
1168
- // honesty gate is reachable but was never wired to any real caller.
1169
- // Here it's stronger than advisory: the inline re-verify below already
1170
- // gates the WRITE on `verdict.ok`, and verifyFixCore's own `ok`
1171
- // formula already folds in `honesty.ok` when fixMeta is supplied — so
1172
- // passing it through here makes a dishonest fixMeta (hand-wave
1173
- // residual, uncited false-positive verdict) block the write itself,
1174
- // not just report a verdict.
1175
- fixMeta: {
1176
- type: 'object',
1177
- additionalProperties: false,
1178
- properties: {
1179
- residual: { type: 'string', maxLength: 2000 },
1180
- verdict: { type: 'string', maxLength: 64 },
1181
- evidence: { type: 'array', items: { type: 'string', maxLength: 500 }, maxItems: 20 },
1182
- signals: {
1183
- type: 'object',
1184
- additionalProperties: false,
1185
- properties: {
1186
- sinkSignatureChanged: { type: 'boolean' },
1187
- allCallersRouted: { type: 'boolean' },
1188
- testDiscriminates: { type: 'boolean' },
1189
- rateLimitOnly: { type: 'boolean' },
1190
- docsOnly: { type: 'boolean' },
1191
- logOnlyNoReject: { type: 'boolean' },
1192
- partialSanitization: { type: 'boolean' },
1193
- },
1194
- },
1195
- // FR-307/FR-1002: this schema had `additionalProperties: false`
1196
- // and never declared `approval` — the property apply-fix-
1197
- // service.js's high-impact-change gate has required since FR-307
1198
- // was built. A real MCP caller supplying fixMeta.approval was
1199
- // rejected by validate.js at the schema layer before the handler
1200
- // ever ran, silently making the approval gate (and FR-1002's
1201
- // identity check layered on it) unreachable from this tool's
1202
- // only real production entry point. See D-0024.
1203
- approval: {
1204
- type: 'object',
1205
- additionalProperties: false,
1206
- properties: {
1207
- approvedBy: { type: 'string', minLength: 1, maxLength: 200 },
1208
- reason: { type: 'string', minLength: 1, maxLength: 1000 },
1209
- },
1210
- },
1211
- // FR-1003: separation-of-duties. Self-reported the same way
1212
- // approvedBy is — this tool has no way to determine who actually
1213
- // wrote a patch, so `author` is a claim, checked against a
1214
- // configurable policy the same way `approval` is.
1215
- author: { type: 'string', minLength: 1, maxLength: 200 },
1216
- },
1217
- },
1218
- },
1219
- required: ['finding_id', 'confirm'],
1220
- },
1221
- async handler({ finding_id, confirm, dry_run = false, patch = null, fixMeta = null }, ctx) {
1222
- if (confirm !== true) {
1223
- return { _meta: tools_META, applied: false, reason: 'apply_fix requires confirm: true.' };
1224
- }
1225
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
1226
- if (!scan) {
1227
- return { _meta: tools_META, applied: false, reason: `last-scan.json failed integrity check: ${status}. Run a fresh scan.` };
1228
- }
1229
- const f = _findById(scan, finding_id);
1230
- if (!f) return { _meta: tools_META, applied: false, reason: `Finding not found: ${finding_id}` };
1231
- if (f._shadow === true) {
1232
- return { _meta: tools_META, applied: false, reason: 'shadow findings cannot be auto-applied' };
1233
- }
1234
-
1235
- // #3 — verifier-approved patch path. When the caller supplies `patch` (a
1236
- // files map, same shape as verify_fix), apply_fix re-runs the verifier
1237
- // INLINE and writes only if it passes: the original finding's stableId is
1238
- // gone, no new ≥medium finding was introduced, and lint is clean. This lets
1239
- // a deterministic OR LLM-synthesized patch be applied for the ~100% of
1240
- // findings that ship only a template/description (no stored fix.replacement).
1241
- // Security: all existing gates hold (confirm, last-scan HMAC, reserved
1242
- // paths, confinement, fix-history backup + attempt budget); the write is
1243
- // additionally gated on a FRESH verification, so a stale/forged patch can't
1244
- // slip through — there is no token to replay, the verify runs here and now.
1245
- if (patch && typeof patch === 'object' && Object.keys(patch).length) {
1246
- if (!f.stableId) {
1247
- return { _meta: tools_META, applied: false, reason: 'finding has no stableId — cannot verify a patch against it' };
1248
- }
1249
- const confinedAbs = {};
1250
- for (const [rel, content] of Object.entries(patch)) {
1251
- let abs;
1252
- try { abs = _confine(ctx.sessionRoot, rel, 'patch key'); }
1253
- catch (e) { return { _meta: tools_META, applied: false, reason: `path-escape refused: ${e.message}` }; }
1254
- if (_isReservedWritePath(ctx.sessionRoot, abs)) {
1255
- return { _meta: tools_META, applied: false, reason: `reserved path refused: ${rel}` };
1256
- }
1257
- confinedAbs[rel] = { abs, content: String(content) };
1258
- }
1259
- // Inline re-verify — the load-bearing gate. Must pass to write.
1260
- let verdict;
1261
- try {
1262
- const _files = Object.fromEntries(Object.entries(confinedAbs).map(([rel, v]) => [rel, v.content]));
1263
- if (process.env.AGENTIC_SECURITY_FIX_RUN_TESTS === '1') {
1264
- // Addition #7 — connect the closed-loop verifier: add the project test
1265
- // suite as a fourth verification leg (scan + lint + tests). Opt-in
1266
- // because many repos have no runner and we must not fail-closed by
1267
- // default. Normalized to the scan+lint verdict shape used below.
1268
- const { verifyFixWithTests } = await __webpack_require__.e(/* import() */ 4113).then(__webpack_require__.bind(__webpack_require__, 4113));
1269
- const t = await verifyFixWithTests({ scanRoot: ctx.sessionRoot, originalFindingStableId: f.stableId, files: _files });
1270
- verdict = { ok: t.ok, summary: t.summary, rescan: t.legs?.scan?.detail, lint: t.legs?.lint?.detail, tests: t.legs?.tests, testVerdict: t.verdict };
1271
- } else {
1272
- const verifyFixCore = await getVerifyFixCore();
1273
- verdict = await verifyFixCore({
1274
- scanRoot: ctx.sessionRoot,
1275
- originalFindingStableId: f.stableId,
1276
- files: _files,
1277
- fixMeta,
1278
- });
1279
- }
1280
- } catch (e) {
1281
- return { _meta: tools_META, applied: false, reason: `patch verification failed: ${e.message}` };
1282
- }
1283
- if (!verdict.ok) {
1284
- return {
1285
- _meta: tools_META, applied: false,
1286
- reason: `patch rejected by verifier: ${verdict.summary || verdict.rescan?.reason || 'did not verify'}`,
1287
- verify: { rescan: verdict.rescan, lint: { runner: verdict.lint?.runner, ok: verdict.lint?.ok }, honesty: verdict.honesty || null },
1288
- };
1289
- }
1290
- // FR-307/FR-1002/D-0024: this caller-supplied-patch branch writes via
1291
- // applyFixHistory() directly and never called applyVerifiedFix() — so
1292
- // the high-impact-change approval gate (auth/authZ/crypto/PII/schema/
1293
- // infra-privilege/public-API) built for the OTHER apply_fix branch
1294
- // (stored fix.replacement) never ran here at all, for any input. Since
1295
- // this is the branch the tool's own description calls the one that
1296
- // covers "~100% of findings that ship only a template," that gap was
1297
- // the larger of the two found this cycle. Same before/after content
1298
- // shape `apply-fix-service.js` already uses — read-first-in-try/catch
1299
- // (D-0012), never existsSync-then-readFileSync.
1300
- const filesForMaterialClassification = {};
1301
- for (const [rel, v] of Object.entries(confinedAbs)) {
1302
- let before = '';
1303
- try { before = await promises_.readFile(v.abs, 'utf8'); } catch { /* new file — before stays '' */ }
1304
- filesForMaterialClassification[rel] = { before, after: v.content };
1305
- }
1306
- const materialClassification = (0,material_change/* classifyFixMaterialRisk */.kz)(filesForMaterialClassification);
1307
- if (dry_run) {
1308
- return { _meta: tools_META, applied: false, dryRun: true, verified: true, files: Object.keys(confinedAbs), summary: verdict.summary, materialClassification };
1309
- }
1310
- if (materialClassification.highImpactCategories.length) {
1311
- const approval = fixMeta && typeof fixMeta === 'object' ? fixMeta.approval : null;
1312
- const hasApprovalEvidence = !!(approval && typeof approval === 'object' &&
1313
- typeof approval.approvedBy === 'string' && approval.approvedBy.trim().length > 0 &&
1314
- typeof approval.reason === 'string' && approval.reason.trim().length > 0);
1315
- if (!hasApprovalEvidence) {
1316
- return {
1317
- _meta: tools_META, applied: false,
1318
- reason: `high-impact change (${materialClassification.highImpactCategories.join(', ')}) requires approval evidence — pass fixMeta.approval: {approvedBy, reason} — before it can be applied`,
1319
- materialClassification,
1320
- };
1321
- }
1322
- const approverRegistry = (0,approver_registry/* loadApproverRegistry */.P4)(ctx.sessionRoot);
1323
- const requiredRoles = (0,approver_registry/* requiredRolesFor */.Kq)(approverRegistry, materialClassification.highImpactCategories);
1324
- const identityCheck = (0,approver_registry/* verifyApprover */.$N)(approverRegistry, approval.approvedBy, requiredRoles);
1325
- if (!identityCheck.verified) {
1326
- return {
1327
- _meta: tools_META, applied: false,
1328
- reason: `high-impact change (${materialClassification.highImpactCategories.join(', ')}) approval rejected: ${identityCheck.reason}`,
1329
- materialClassification,
1330
- };
1331
- }
1332
- // FR-1003: separation-of-duties, same no-op-unless-configured gate
1333
- // as apply-fix-service.js's own copy — see approver-registry.js.
1334
- const sodCheck = (0,approver_registry/* checkSeparationOfDuties */.I0)(approverRegistry, fixMeta?.author, approval.approvedBy);
1335
- if (!sodCheck.ok) {
1336
- return {
1337
- _meta: tools_META, applied: false,
1338
- reason: `high-impact change (${materialClassification.highImpactCategories.join(', ')}) approval rejected: ${sodCheck.reason}`,
1339
- materialClassification,
1340
- };
1341
- }
1342
- }
1343
- const written = [];
1344
- try {
1345
- for (const [rel, v] of Object.entries(confinedAbs)) {
1346
- const fileExisted = external_node_fs_.existsSync(v.abs);
1347
- const originalContent = fileExisted ? await promises_.readFile(v.abs, 'utf8') : '';
1348
- const entry = await (0,fix_history/* applyFix */.oM)({
1349
- scanRoot: ctx.sessionRoot, file: rel, originalContent, newContent: v.content, fileExisted,
1350
- findingId: f.id, stableId: f.stableId, ruleId: f.ruleId || f.cwe || f.family || null, vuln: f.vuln || f.title || null,
1351
- findingProvenance: f.findingProvenance || null,
1352
- });
1353
- written.push({ file: rel, historyId: entry.id, backupPath: entry.backupPath });
1354
- }
1355
- } catch (e) {
1356
- // FR-306: roll back every file THIS batch already wrote before the
1357
- // failure — applyFixHistory already restored the one file that just
1358
- // failed; this covers the rest, so a multi-file patch never leaves
1359
- // some files patched and others not.
1360
- for (const w of written) {
1361
- try { await (0,fix_history/* revertEntryById */.rJ)(ctx.sessionRoot, w.historyId); } catch { /* best-effort; original error still propagates below */ }
1362
- }
1363
- if (e && e.name === 'FixAttemptBudgetExceededError') {
1364
- return { _meta: tools_META, applied: false, reason: `budget-exceeded: ${e.message}`, budgetExceeded: true, attempts: e.attempts, maxAttempts: e.max, key: e.key };
1365
- }
1366
- throw e;
1367
- }
1368
- let acceptance = null;
1369
- try { acceptance = (0,fix_history/* fixAcceptanceRate */.XR)(ctx.sessionRoot); } catch { /* best-effort */ }
1370
- return { _meta: tools_META, applied: true, verified: true, patched: written, integrity: status, verify: { summary: verdict.summary }, acceptance, materialClassification };
1371
- }
1372
-
1373
- if (typeof f.fix?.replacement !== 'string') {
1374
- // Premortem #2: templates are patch-shaped text. Same reasoning as
1375
- // the replacement path — do NOT pass through redactString here.
1376
- return {
1377
- _meta: tools_META, applied: false,
1378
- reason: 'No full replacement available — only a template. Apply the template manually.',
1379
- template: f.fix?.code || '',
1380
- file: f.file, line: f.line,
1381
- };
1382
- }
1383
- let absFile;
1384
- try { absFile = _confine(ctx.sessionRoot, f.file, 'finding.file'); }
1385
- catch (e) {
1386
- return { _meta: tools_META, applied: false, reason: `path-escape refused: ${e.message}` };
1387
- }
1388
- if (_isReservedWritePath(ctx.sessionRoot, absFile)) {
1389
- return { _meta: tools_META, applied: false, reason: `reserved path refused: writes to .git/, .agentic-security/, or node_modules/ are not permitted via apply_fix` };
1390
- }
1391
- if (!external_node_fs_.existsSync(absFile)) {
1392
- return { _meta: tools_META, applied: false, reason: `File not found: ${absFile}` };
1393
- }
1394
- const originalContent = await promises_.readFile(absFile, 'utf8');
1395
-
1396
- if (dry_run) {
1397
- return {
1398
- _meta: tools_META,
1399
- applied: false, dryRun: true,
1400
- file: f.file,
1401
- originalSize: originalContent.length,
1402
- newSize: f.fix.replacement.length,
1403
- diffSummary: `${originalContent.length} → ${f.fix.replacement.length} bytes`,
1404
- };
1405
- }
1406
-
1407
- // FR-301/A-08 (assurance-hardening PRD): this branch used to write
1408
- // f.fix.replacement straight to disk with NO fresh verification — no
1409
- // rescan, no lint, nothing confirming the stored replacement actually
1410
- // closes the finding it claims to fix. The caller-patch branch above
1411
- // already required this; there is no reason a STORED fix should be
1412
- // trusted more than a caller-supplied one just because it shipped with
1413
- // the finding. Routed through the same applyVerifiedFix() service the
1414
- // CLI's `fix --apply` now also uses (src/fix/apply-fix-service.js) —
1415
- // confinement/reserved-path are re-checked there too (harmless
1416
- // redundancy with the dry_run preview above, kept for that preview's
1417
- // size-diff shape) but the load-bearing addition is the verification
1418
- // gate before the write.
1419
- if (!f.stableId) {
1420
- return { _meta: tools_META, applied: false, reason: 'finding has no stableId — cannot verify a stored fix against it' };
1421
- }
1422
- const result = await (0,apply_fix_service/* applyVerifiedFix */.On)({
1423
- scanRoot: ctx.sessionRoot,
1424
- finding: f,
1425
- files: { [f.file]: f.fix.replacement },
1426
- fixMeta,
1427
- });
1428
- if (!result.ok) {
1429
- if (result.budgetExceeded) {
1430
- return { _meta: tools_META, applied: false, reason: result.reason, budgetExceeded: true, attempts: result.attempts, maxAttempts: result.maxAttempts, key: result.key };
1431
- }
1432
- return { _meta: tools_META, applied: false, reason: result.reason, verify: result.verify || null };
1433
- }
1434
- // R25 (PRD §5): surface the running auto-fix acceptance rate after each
1435
- // applied fix, so the closed loop reports its own success metric.
1436
- let acceptance = null;
1437
- try { acceptance = (0,fix_history/* fixAcceptanceRate */.XR)(ctx.sessionRoot); } catch { /* metric is best-effort */ }
1438
- const entry = result.written[0];
1439
- return {
1440
- // FR-305: verifiedFull distinguishes "every required leg (lint, tests)
1441
- // genuinely ran and passed" from "passed, but a required leg was
1442
- // skipped or unavailable" — verified:true alone conflates them.
1443
- _meta: tools_META, applied: true, verified: true, verifiedFull: result.verifiedFull,
1444
- historyId: entry.historyId, file: entry.file, backupPath: entry.backupPath,
1445
- integrity: status, attemptOrdinal: entry.attemptOrdinal, acceptance,
1446
- verify: result.verify,
1447
- };
1448
- },
1449
- };
1450
-
1451
- // ─── verify_fix ──────────────────────────────────────────────────────────────
1452
- // Closed-loop verification of a proposed patch BEFORE the agent applies it.
1453
- // Re-scans the patched files in-memory (no disk write), confirms the original
1454
- // stableId is gone, and runs the project's existing linter on the patched
1455
- // files. Returns a structured verdict the agent can use to decide whether to
1456
- // proceed with apply_fix.
1457
- const verify_fix = {
1458
- name: 'verify_fix',
1459
- description: 'Verify a proposed patch before applying. Re-scans the patched files in memory, runs the project linter, runs the project test suite, checks fix honesty (FULL/MITIGATION/WORKAROUND) when fixMeta is supplied, and re-runs the PoC when one exists. Returns { ok, rescan, lint, tests, honesty, poc, summary }. Does not write to the target project’s own files, but DOES append one record per attempt to .agentic-security/fix-metrics.jsonl for the measured fix-loop.',
1460
- inputSchema: {
1461
- type: 'object',
1462
- additionalProperties: false,
1463
- properties: {
1464
- stable_id: { type: 'string', minLength: 8, maxLength: 64 },
1465
- files: {
1466
- type: 'object',
1467
- additionalProperties: { type: 'string', maxLength: 500_000 },
1468
- minProperties: 1,
1469
- maxProperties: 8,
1470
- },
1471
- // Stage 6 correctness audit: posture/fix-honesty-gate.js's deterministic
1472
- // honesty checks (vague-assurance residual prose, unbacked false-
1473
- // positive verdicts, tier/residual consistency) were fully built and
1474
- // fix-verify.js already consulted them when given a `fixMeta` — but
1475
- // this schema never had a `fixMeta` property, so no call through the
1476
- // MCP surface could ever supply one. The gate can only run against
1477
- // claims the AGENT self-reports (residual risk, verdict, evidence,
1478
- // completeness signals) — nothing here is server-computable — so
1479
- // fixing this meant exposing the property, not inventing a lookup.
1480
- fixMeta: {
1481
- type: 'object',
1482
- additionalProperties: false,
1483
- properties: {
1484
- residual: { type: 'string', maxLength: 2000 },
1485
- verdict: { type: 'string', maxLength: 64 },
1486
- evidence: { type: 'array', items: { type: 'string', maxLength: 500 }, maxItems: 20 },
1487
- signals: {
1488
- type: 'object',
1489
- additionalProperties: false,
1490
- properties: {
1491
- sinkSignatureChanged: { type: 'boolean' },
1492
- allCallersRouted: { type: 'boolean' },
1493
- testDiscriminates: { type: 'boolean' },
1494
- rateLimitOnly: { type: 'boolean' },
1495
- docsOnly: { type: 'boolean' },
1496
- logOnlyNoReject: { type: 'boolean' },
1497
- partialSanitization: { type: 'boolean' },
1498
- },
1499
- },
1500
- },
1501
- },
1502
- },
1503
- required: ['stable_id', 'files'],
1504
- },
1505
- async handler({ stable_id, files, fixMeta }, ctx) {
1506
- // Confine every file path before passing to the verifier.
1507
- const confined = {};
1508
- for (const [relPath, content] of Object.entries(files || {})) {
1509
- try {
1510
- _confine(ctx.sessionRoot, relPath, 'files key');
1511
- } catch (e) {
1512
- return { _meta: tools_META, ok: false, reason: `path-escape refused: ${e.message}` };
1513
- }
1514
- confined[relPath] = String(content);
1515
- }
1516
- try {
1517
- // The PoC-re-check leg (verifyFixCore's `pocLeg`) needs a `poc` param
1518
- // to do anything — until now nothing supplied one, so it always
1519
- // reported {status:'not-requested'} through this surface (see
1520
- // posture/CLAUDE.md's disclosure). Rather than widening inputSchema
1521
- // to make the CALLER pass PoC data back, look it up server-side: the
1522
- // scan pipeline already attaches an HTTP-shaped f.poc to matching
1523
- // findings by default (engine.js's annotatePocs), and last-scan.json
1524
- // already carries it under the same stableId this handler receives.
1525
- // Best-effort: a missing/unsigned/tampered scan just means no PoC is
1526
- // available to re-check, not a verify_fix failure — the rescan/lint/
1527
- // tests legs below are independent of this and still apply.
1528
- let poc = null;
1529
- try {
1530
- const { scan: lastScan } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
1531
- const orig = lastScan && (lastScan.findings || []).find(f => f.stableId === stable_id);
1532
- if (orig && orig.poc && orig.poc.code) poc = { ...orig.poc, finding: orig };
1533
- } catch { /* best-effort lookup; poc stays null */ }
1534
-
1535
- const verifyFixCore = await getVerifyFixCore();
1536
- const r = await verifyFixCore({
1537
- scanRoot: ctx.sessionRoot,
1538
- originalFindingStableId: stable_id,
1539
- files: confined,
1540
- poc,
1541
- fixMeta,
1542
- });
1543
- return {
1544
- _meta: tools_META,
1545
- ok: r.ok,
1546
- rescan: { ok: r.rescan.ok, reason: r.rescan.reason, introduced: r.rescan.introduced || [] },
1547
- lint: { runner: r.lint.runner, ok: r.lint.ok, skipped: r.lint.skipped || false, output: (0,redact/* redactString */.rd)(r.lint.output || '').slice(0, 1500) },
1548
- // verifyFix computes five legs, not two — tests/honesty/poc were
1549
- // being silently dropped here, leaving an agent with no structured
1550
- // way to see WHY verification failed when the failure was in one
1551
- // of those three (only the free-text summary carried it).
1552
- // test-runner.js's runProjectTests never returns raw stdout/stderr,
1553
- // so no redaction is needed there; honesty.violations are static,
1554
- // code-generated strings; poc.reason is redacted defensively since
1555
- // it can echo proof-harness detail derived from scanned source.
1556
- tests: r.tests,
1557
- honesty: r.honesty,
1558
- poc: r.poc ? { ...r.poc, reason: r.poc.reason ? (0,redact/* redactString */.rd)(r.poc.reason) : r.poc.reason } : r.poc,
1559
- summary: r.summary,
1560
- };
1561
- } catch (e) {
1562
- return { _meta: tools_META, ok: false, reason: `verify_fix failed: ${e.message}` };
1563
- }
1564
- },
1565
- };
1566
-
1567
- // ─── synthesize_fix ──────────────────────────────────────────────────────────
1568
- // Return the stored fix replacement + regression-test scaffold for a finding,
1569
- // WITHOUT applying anything. The agent can call verify_fix → apply_fix in
1570
- // sequence with the returned blob.
1571
- const synthesize_fix = {
1572
- name: 'synthesize_fix',
1573
- 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.',
1574
- inputSchema: {
1575
- type: 'object',
1576
- additionalProperties: false,
1577
- properties: {
1578
- finding_id: { type: 'string', minLength: 1, maxLength: 256 },
1579
- },
1580
- required: ['finding_id'],
1581
- },
1582
- async handler({ finding_id }, ctx) {
1583
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
1584
- if (!scan) {
1585
- return { _meta: tools_META, ok: false, reason: `last-scan.json failed integrity check: ${status}` };
1586
- }
1587
- const f = _findById(scan, finding_id);
1588
- if (!f) return { _meta: tools_META, ok: false, reason: `Finding not found: ${finding_id}` };
1589
- if (f._shadow === true) return { _meta: tools_META, ok: false, reason: 'shadow findings have no synthesized fix' };
1590
- const fix = f.fix || {};
1591
- const hasReplacement = typeof fix.replacement === 'string' && fix.replacement.length > 0;
1592
- // Patch bounds: count files touched + LoC delta.
1593
- let touchedFiles = 1;
1594
- let locDelta = 0;
1595
- if (hasReplacement) {
1596
- let orig = '';
1597
- try {
1598
- const abs = _confine(ctx.sessionRoot, f.file, 'finding.file');
1599
- orig = external_node_fs_.readFileSync(abs, 'utf8');
1600
- } catch { /* ignore — counts will reflect new-only LoC */ }
1601
- locDelta = Math.abs(fix.replacement.split('\n').length - orig.split('\n').length);
1602
- }
1603
- const oversized = touchedFiles > 3 || locDelta > 100;
1604
- // #1 — deterministic autofix: for classes with a safe context-independent
1605
- // swap (weak hash, TLS verify-off), materialize a full-file patch from the
1606
- // live file. The agent passes `autofix.patch` straight to apply_fix, which
1607
- // re-verifies it (rescan-clean + no new ≥medium + lint) before writing — so
1608
- // even a mis-attributed swap can't land a bad edit. No stored replacement,
1609
- // no per-finding bloat in last-scan.json.
1610
- let autofix = null;
1611
- if (!hasReplacement) {
1612
- try {
1613
- const abs = _confine(ctx.sessionRoot, f.file, 'finding.file');
1614
- const det = synthesizeDeterministicPatch(f, external_node_fs_.readFileSync(abs, 'utf8'));
1615
- if (det) autofix = { deterministic: true, ruleId: det.ruleId, patch: det.patch };
1616
- } catch { /* best-effort — no file / no rule → no autofix */ }
1617
- }
1618
- // Premortem #2: `replacement` is a *patch* (the code we'll write to disk),
1619
- // not a finding excerpt. Running it through redactString silently corrupts
1620
- // valid patches whose content happens to match a secret-shape (e.g. a
1621
- // placeholder like `password = "loadFromEnv"`). Patches MUST pass through
1622
- // verbatim. Snippet/description/etc. continue to be redacted in
1623
- // explain_finding / scan_diff — that's the right surface for redaction.
1624
- return {
1625
- _meta: tools_META,
1626
- ok: true,
1627
- stable_id: f.stableId || null,
1628
- file: f.file, line: f.line,
1629
- vuln: f.vuln,
1630
- severity: f.severity,
1631
- hasReplacement,
1632
- replacement: hasReplacement ? fix.replacement : null,
1633
- template: fix.code || null,
1634
- autofix,
1635
- // #15 — the regression test the scan annotator already generated for this
1636
- // finding (present when a PoC was built). Surfaced here so the fix flow
1637
- // writes the test alongside the patch; fix-verify-loop then runs it, so an
1638
- // applied fix ships with a test that fails pre-fix and passes post-fix.
1639
- regression_test: f.regression_test || null,
1640
- remediation: typeof fix.description === 'string' ? fix.description : (typeof fix === 'string' ? fix : null),
1641
- patchBounds: { touchedFiles, locDelta, oversized },
1642
- // oversized can only be true when hasReplacement is true (locDelta is
1643
- // only computed in that branch, and touchedFiles never varies) — a
1644
- // `!hasReplacement` conjunct here was a structural contradiction that
1645
- // made this permanently false. The correct signal: the stored
1646
- // replacement itself is too big to trust auto-applying, and there's
1647
- // no safer deterministic alternative.
1648
- recommendsFixPlan: oversized && !autofix,
1649
- };
1650
- },
1651
- };
1652
-
1653
- // ─── find_rule_module ───────────────────────────────────────────────────────
1654
- // Codebase-navigation helper (C.6). Answers "which file under scanner/src/
1655
- // implements the detector for CWE-X / family Y" by scanning the SAST and
1656
- // posture sources for `cwe:` / `family:` literals. Cheaper and more reliable
1657
- // than asking the agent to grep — premortem note: "grep for a common function
1658
- // name in a large codebase returns thousands of matches."
1659
- //
1660
- // Read-only; no findings consumed. Output is a list of file paths + the
1661
- // matching literal lines so the agent can verify before editing.
1662
- const find_rule_module = {
1663
- name: 'find_rule_module',
1664
- 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.',
1665
- inputSchema: {
1666
- type: 'object',
1667
- additionalProperties: false,
1668
- properties: {
1669
- cwe: { type: 'string', minLength: 5, maxLength: 16 },
1670
- family: { type: 'string', minLength: 2, maxLength: 64 },
1671
- },
1672
- },
1673
- async handler({ cwe, family }, ctx) {
1674
- if (!cwe && !family) {
1675
- return { _meta: tools_META, ok: false, reason: 'provide cwe (e.g. "CWE-89") or family (e.g. "sql-injection")' };
1676
- }
1677
- // Pattern enforcement — the mini-schema validator doesn't do `pattern`.
1678
- if (cwe && !/^CWE-\d+$/.test(cwe)) {
1679
- return { _meta: tools_META, ok: false, reason: 'cwe must match /^CWE-\\d+$/ (e.g. "CWE-89")' };
1680
- }
1681
- if (family && !/^[a-z][a-z0-9-]+$/.test(family)) {
1682
- return { _meta: tools_META, ok: false, reason: 'family must match /^[a-z][a-z0-9-]+$/ (e.g. "sql-injection")' };
1683
- }
1684
- const sessionRoot = ctx.sessionRoot;
1685
- const roots = [
1686
- external_node_path_.join(sessionRoot, 'scanner', 'src', 'sast'),
1687
- external_node_path_.join(sessionRoot, 'scanner', 'src', 'posture'),
1688
- ];
1689
- const hits = [];
1690
- const cweLit = cwe ? new RegExp(`['"\`]${cwe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"\`]`) : null;
1691
- // Family match is broader on purpose: detectors often emit findings
1692
- // without an explicit `family:` field (it's backfilled by
1693
- // posture/finding-defaults.js). We match the family literal anywhere in
1694
- // the file (vuln-name strings, comments, ids) so e.g. searching for "csrf"
1695
- // surfaces sast/csrf.js even though it doesn't tag findings with the field.
1696
- const famLit = family ? new RegExp(`\\b${family.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/-/g, '[-_ ]?')}\\b`, 'i') : null;
1697
- // Also try a filename-stem match when only family is given.
1698
- const famFilename = family ? family.toLowerCase() : null;
1699
- for (const root of roots) {
1700
- if (!external_node_fs_.existsSync(root)) continue;
1701
- let entries;
1702
- try { entries = external_node_fs_.readdirSync(root); } catch { continue; }
1703
- for (const entry of entries) {
1704
- if (!entry.endsWith('.js')) continue;
1705
- const abs = external_node_path_.join(root, entry);
1706
- let stat;
1707
- try { stat = external_node_fs_.statSync(abs); } catch { continue; }
1708
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) continue;
1709
- let body;
1710
- try { body = external_node_fs_.readFileSync(abs, 'utf8'); } catch { continue; }
1711
- const lines = body.split('\n');
1712
- const matches = [];
1713
- const stem = entry.replace(/\.js$/, '').toLowerCase();
1714
- const filenameMatchesFamily = famFilename && (stem === famFilename || stem.includes(famFilename));
1715
- if (filenameMatchesFamily) {
1716
- matches.push({ line: 1, text: `<filename "${entry}" matches family>`, kind: 'filename' });
1717
- }
1718
- for (let i = 0; i < lines.length; i++) {
1719
- const line = lines[i];
1720
- if (cweLit && cweLit.test(line)) matches.push({ line: i + 1, text: line.trim().slice(0, 200), kind: 'cwe' });
1721
- else if (famLit && famLit.test(line)) matches.push({ line: i + 1, text: line.trim().slice(0, 200), kind: 'family' });
1722
- if (matches.length >= 5) break;
1723
- }
1724
- if (matches.length) {
1725
- hits.push({
1726
- file: external_node_path_.relative(sessionRoot, abs).replace(/\\/g, '/'),
1727
- matchCount: matches.length,
1728
- matches,
1729
- });
1730
- if (hits.length >= 20) break;
1731
- }
1732
- }
1733
- if (hits.length >= 20) break;
1734
- }
1735
- return {
1736
- _meta: tools_META,
1737
- ok: true,
1738
- query: { cwe: cwe || null, family: family || null },
1739
- hitCount: hits.length,
1740
- hits,
1741
- truncated: hits.length >= 20,
1742
- };
1743
- },
1744
- };
1745
-
1746
- // ─── append_scratchpad / read_scratchpad ───────────────────────────────────
1747
- // LangChain harness-anatomy: the filesystem is the durable agent scratchpad.
1748
- // These tools expose a tightly-confined slice of the project tree for
1749
- // in-progress agent state: PLAN.md decompositions, offloaded tool outputs,
1750
- // session notes that survive context resets.
1751
- //
1752
- // Confinement (validated in `_validateScratchpadPath`):
1753
- // ALL paths must start with `.agentic-security/agent-scratchpad/<agent>/<session>/`
1754
- // and consist of [A-Za-z0-9_.-]{1,64} path components — no `..`, no
1755
- // absolute paths, no shell metacharacters. This is the ONE place inside
1756
- // the otherwise-reserved `.agentic-security/` tree where agents can write.
1757
- // Limits:
1758
- // - 2 MB per file (write attempts beyond this are refused).
1759
- // - 50 MB total across the scratchpad — protects against runaway agents.
1760
- // Operators who want to clean up: `rm -rf .agentic-security/agent-scratchpad`.
1761
- //
1762
- // The post: "Agents can store intermediate outputs and maintain state that
1763
- // outlasts a single session." This is that mechanism.
1764
-
1765
- const append_scratchpad = {
1766
- name: 'append_scratchpad',
1767
- 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.',
1768
- inputSchema: {
1769
- type: 'object',
1770
- additionalProperties: false,
1771
- properties: {
1772
- path: { type: 'string', minLength: 1, maxLength: 256 },
1773
- content: { type: 'string', minLength: 1, maxLength: 256 * 1024 },
1774
- },
1775
- required: ['path', 'content'],
1776
- },
1777
- async handler({ path: relPath, content }, ctx) {
1778
- const v = _validateScratchpadPath(relPath);
1779
- if (!v.ok) return { _meta: tools_META, ok: false, reason: v.reason };
1780
- let abs;
1781
- try { abs = _scratchpadAbs(ctx.sessionRoot, relPath); }
1782
- catch (e) { return { _meta: tools_META, ok: false, reason: `path-escape refused: ${e.message}` }; }
1783
- const total = _scratchpadTotalBytes(ctx.sessionRoot);
1784
- if (total + content.length > SCRATCHPAD_MAX_TOTAL_BYTES) {
1785
- return {
1786
- _meta: tools_META, ok: false,
1787
- reason: `scratchpad-total-exceeded: ${total} + ${content.length} > ${SCRATCHPAD_MAX_TOTAL_BYTES}. Clean up via "rm -rf .agentic-security/agent-scratchpad" or rotate sessions.`,
1788
- };
1789
- }
1790
- let existing = 0;
1791
- try { if (external_node_fs_.existsSync(abs)) existing = external_node_fs_.statSync(abs).size; } catch {}
1792
- if (existing + content.length > SCRATCHPAD_MAX_FILE_BYTES) {
1793
- return {
1794
- _meta: tools_META, ok: false,
1795
- reason: `scratchpad-file-exceeded: ${existing} + ${content.length} > ${SCRATCHPAD_MAX_FILE_BYTES}. Start a new file.`,
1796
- };
1797
- }
1798
- try {
1799
- external_node_fs_.mkdirSync(external_node_path_.dirname(abs), { recursive: true });
1800
- external_node_fs_.appendFileSync(abs, content);
1801
- return {
1802
- _meta: tools_META, ok: true,
1803
- path: relPath, bytesWritten: content.length, fileSize: existing + content.length,
1804
- scratchpadTotal: total + content.length,
1805
- };
1806
- } catch (e) {
1807
- return { _meta: tools_META, ok: false, reason: `write-failed: ${e.message}` };
1808
- }
1809
- },
1810
- };
1811
-
1812
- const read_scratchpad = {
1813
- name: 'read_scratchpad',
1814
- 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.',
1815
- inputSchema: {
1816
- type: 'object',
1817
- additionalProperties: false,
1818
- properties: {
1819
- path: { type: 'string', minLength: 1, maxLength: 256 },
1820
- offset: { type: 'integer', minimum: 0, maximum: 100 * 1024 * 1024 },
1821
- limit: { type: 'integer', minimum: 1, maximum: 64 * 1024 },
1822
- },
1823
- required: ['path'],
1824
- },
1825
- async handler({ path: relPath, offset, limit }, ctx) {
1826
- const v = _validateScratchpadPath(relPath);
1827
- if (!v.ok) return { _meta: tools_META, ok: false, reason: v.reason };
1828
- let abs;
1829
- try { abs = _scratchpadAbs(ctx.sessionRoot, relPath); }
1830
- catch (e) { return { _meta: tools_META, ok: false, reason: `path-escape refused: ${e.message}` }; }
1831
- if (!external_node_fs_.existsSync(abs)) return { _meta: tools_META, ok: false, reason: 'not-found' };
1832
- let stat;
1833
- try { stat = external_node_fs_.statSync(abs); } catch (e) { return { _meta: tools_META, ok: false, reason: `stat-failed: ${e.message}` }; }
1834
- if (!stat.isFile()) return { _meta: tools_META, ok: false, reason: 'not-a-file' };
1835
- const off = Number.isInteger(offset) ? Math.max(0, offset) : 0;
1836
- const lim = Number.isInteger(limit) ? Math.min(64 * 1024, Math.max(1, limit)) : 4096;
1837
- let buf;
1838
- try {
1839
- const fd = external_node_fs_.openSync(abs, 'r');
1840
- const tmp = Buffer.alloc(lim);
1841
- const read = external_node_fs_.readSync(fd, tmp, 0, lim, off);
1842
- external_node_fs_.closeSync(fd);
1843
- buf = tmp.slice(0, read);
1844
- } catch (e) { return { _meta: tools_META, ok: false, reason: `read-failed: ${e.message}` }; }
1845
- const text = buf.toString('utf8');
1846
- return {
1847
- _meta: tools_META, ok: true,
1848
- path: relPath,
1849
- offset: off, limit: lim, bytesRead: buf.length,
1850
- totalSize: stat.size,
1851
- truncated: off + buf.length < stat.size,
1852
- nextOffset: off + buf.length < stat.size ? off + buf.length : null,
1853
- content: text,
1854
- };
1855
- },
1856
- };
1857
-
1858
- // ─── append_agents_memory / read_agents_memory ─────────────────────────────
1859
- // LangChain harness-anatomy #2: AGENTS.md as continual-learning surface.
1860
- // Lazy-import to keep the MCP module dependency-light.
1861
-
1862
-
1863
-
1864
-
1865
- const append_agents_memory = {
1866
- name: 'append_agents_memory',
1867
- 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.',
1868
- inputSchema: {
1869
- type: 'object',
1870
- additionalProperties: false,
1871
- properties: {
1872
- agent: { type: 'string', minLength: 1, maxLength: 64 },
1873
- body: { type: 'string', minLength: 1, maxLength: 4096 },
1874
- },
1875
- required: ['agent', 'body'],
1876
- },
1877
- async handler({ agent, body }, ctx) {
1878
- const r = appendAgentsMemory(ctx.sessionRoot, { agent, body });
1879
- return { _meta: tools_META, ...r };
1880
- },
1881
- };
1882
-
1883
- const read_agents_memory = {
1884
- name: 'read_agents_memory',
1885
- 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.',
1886
- inputSchema: {
1887
- type: 'object',
1888
- additionalProperties: false,
1889
- properties: {
1890
- full: { type: 'boolean' },
1891
- },
1892
- },
1893
- async handler({ full }, ctx) {
1894
- const body = readAgentsMemory(ctx.sessionRoot);
1895
- if (!body) return { _meta: tools_META, present: false };
1896
- if (full) return { _meta: tools_META, present: true, length: body.length, content: body };
1897
- // Tail-only — same logic as summarizeForSession but inlined to avoid a
1898
- // second import surface.
1899
- const limit = 6 * 1024;
1900
- if (body.length <= limit) return { _meta: tools_META, present: true, length: body.length, content: body };
1901
- const tail = body.slice(-limit);
1902
- const firstSection = tail.indexOf('\n## ');
1903
- const slice = firstSection >= 0 ? tail.slice(firstSection) : tail;
1904
- return { _meta: tools_META, present: true, length: body.length, truncated: true, content: slice };
1905
- },
1906
- };
1907
-
1908
- // ─── query_triage_memory ───────────────────────────────────────────────────
1909
- // Natural-language Q&A over past triage decisions (wont-fix / false-positive
1910
- // markings + reasons). Backed by .agentic-security/triage-memory.jsonl, which
1911
- // is auto-populated by triage.transition(). Returns at most 10 most-relevant
1912
- // past decisions.
1913
-
1914
- const query_triage_memory = {
1915
- name: 'query_triage_memory',
1916
- 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.',
1917
- inputSchema: {
1918
- type: 'object',
1919
- additionalProperties: false,
1920
- properties: {
1921
- query: { type: 'string', description: 'Free-text terms to match against past reasons / vuln text / file paths / family names.' },
1922
- },
1923
- },
1924
- async handler({ query }, ctx) {
1925
- const { queryMemory } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 1905));
1926
- const raw = queryMemory(ctx.sessionRoot, query || '');
1927
- // Stage 6 correctness audit: this returned queryMemory's output
1928
- // verbatim, with no redaction pass — every other tool that echoes
1929
- // scanned-source-derived text redacts it (mcp/CLAUDE.md's "Adding a new
1930
- // tool" step 3). Round-trip through redactString the same way
1931
- // redactFinding already does for its own opaque `.trace` field: results
1932
- // here mix shapes (a triage decision's free-text `reason`, a finding's
1933
- // `vuln`/`family`/file path), so scrubbing the whole serialized
1934
- // structure catches secret-shaped substrings regardless of which field
1935
- // they landed in, rather than hardcoding a field allowlist that could
1936
- // miss one.
1937
- let results;
1938
- try { results = JSON.parse((0,redact/* redactString */.rd)(JSON.stringify(raw))); }
1939
- catch { results = raw; }
1940
- return {
1941
- _meta: tools_META,
1942
- count: results.length,
1943
- results,
1944
- };
1945
- },
1946
- };
1947
-
1948
- // ─── query_findings_memory ─────────────────────────────────────────────────
1949
- // Natural-language Q&A across the scanner's accumulated institutional
1950
- // memory: current findings + past triage decisions + scan history +
1951
- // AGENTS.md narrative. Use to answer "have we seen something like this
1952
- // before?" without reading multiple files.
1953
-
1954
- const query_findings_memory = {
1955
- name: 'query_findings_memory',
1956
- 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.',
1957
- inputSchema: {
1958
- type: 'object',
1959
- additionalProperties: false,
1960
- properties: {
1961
- query: { type: 'string', description: 'Natural-language search terms (2+ chars each).' },
1962
- },
1963
- required: ['query'],
1964
- },
1965
- async handler({ query }, ctx) {
1966
- const { queryFindingsMemory } = await __webpack_require__.e(/* import() */ 3839).then(__webpack_require__.bind(__webpack_require__, 3839));
1967
- const raw = queryFindingsMemory(ctx.sessionRoot, query || '');
1968
- // Stage 6 correctness audit — same redaction gap and same fix as
1969
- // query_triage_memory just above: this mixes four differently-shaped
1970
- // result kinds (finding / triage / history / AGENTS.md text), so a
1971
- // whole-structure redactString round-trip is applied rather than a
1972
- // per-field allowlist that could miss one of the four shapes.
1973
- let body;
1974
- try { body = JSON.parse((0,redact/* redactString */.rd)(JSON.stringify(raw))); }
1975
- catch { body = raw; }
1976
- return { _meta: tools_META, ...body };
1977
- },
1978
- };
1979
-
1980
- // ─── lookup_cve ────────────────────────────────────────────────────────────
1981
- // LangChain harness-anatomy #8: bridge the knowledge-cutoff gap by exposing
1982
- // the local OSV / KEV / EPSS cache as a structured tool. Read-only — never
1983
- // triggers a network fetch from the MCP path.
1984
- const lookup_cve = {
1985
- name: 'lookup_cve',
1986
- 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.',
1987
- inputSchema: {
1988
- type: 'object',
1989
- additionalProperties: false,
1990
- properties: {
1991
- cve: { type: 'string', minLength: 9, maxLength: 20 },
1992
- },
1993
- required: ['cve'],
1994
- },
1995
- async handler({ cve }, _ctx) {
1996
- const r = lookupCve(cve);
1997
- return { _meta: tools_META, ...r };
1998
- },
1999
- };
2000
-
2001
- const query_cache_telemetry = {
2002
- name: 'query_cache_telemetry',
2003
- 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.',
2004
- inputSchema: {
2005
- type: 'object',
2006
- additionalProperties: false,
2007
- properties: {
2008
- // Optional explicit transcript path; otherwise derived from the session root.
2009
- transcript_path: { type: 'string', minLength: 1, maxLength: 4096 },
2010
- },
2011
- required: [],
2012
- },
2013
- async handler({ transcript_path } = {}, ctx) {
2014
- const result = (0,cache_economics.analyzeTranscript)({ transcriptPath: transcript_path, projectDir: ctx?.sessionRoot || process.cwd() });
2015
- if (!result.ok) return { _meta: tools_META, ok: false, reason: result.reason };
2016
- return {
2017
- _meta: tools_META,
2018
- ok: true,
2019
- metrics: result.metrics,
2020
- leaks: result.leaks,
2021
- report: (0,cache_economics.formatCacheReport)(result),
2022
- statusline: (0,cache_economics.renderCacheStatusLine)(result.metrics),
2023
- };
2024
- },
2025
- };
2026
-
2027
- // ─── synthesize_sca_upgrade ───────────────────────────────────────────────
2028
- // Phase 3 / Item 5 of the SCA improvement plan. Read-only counterpart to
2029
- // apply_sca_upgrade — produces a structured upgrade plan via the
2030
- // ecosystem's native --dry-run command. Safe to call any number of times.
2031
- let _scaUpgrade;
2032
- async function _getScaUpgrade() {
2033
- if (!_scaUpgrade) _scaUpgrade = await __webpack_require__.e(/* import() */ 5333).then(__webpack_require__.bind(__webpack_require__, 5333));
2034
- return _scaUpgrade;
2035
- }
2036
- const synthesize_sca_upgrade = {
2037
- name: 'synthesize_sca_upgrade',
2038
- 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.',
2039
- inputSchema: {
2040
- type: 'object',
2041
- additionalProperties: false,
2042
- properties: {
2043
- finding_id: { type: 'string', minLength: 1, maxLength: 256 },
2044
- },
2045
- required: ['finding_id'],
2046
- },
2047
- async handler({ finding_id }, ctx) {
2048
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: true });
2049
- if (!scan) throw new Error(`No usable scan state (${status}).`);
2050
- const f = _findById(scan, finding_id);
2051
- if (!f) throw new Error(`Finding not found: ${finding_id}`);
2052
- if (f.type !== 'vulnerable_dep') {
2053
- return { _meta: tools_META, ok: false, reason: 'finding is not an SCA vulnerable_dep — use synthesize_fix for SAST findings' };
2054
- }
2055
- const { planScaUpgrade } = await _getScaUpgrade();
2056
- const plan = await planScaUpgrade({ scanRoot: ctx.sessionRoot, finding: f });
2057
- return { _meta: tools_META, ...plan };
2058
- },
2059
- };
2060
-
2061
- // ─── apply_sca_upgrade ────────────────────────────────────────────────────
2062
- // Phase 3 / Item 5 of the SCA improvement plan. The MCP `apply_fix` path
2063
- // refuses every package-manager manifest by design. This tool bypasses
2064
- // that ONLY for the install pathway — it shells out to the ecosystem's
2065
- // native package manager (npm / pip / cargo / go) which is the right
2066
- // surface for safely modifying manifests + lockfiles. Backs up affected
2067
- // manifests before the install; runs the project's test command (if
2068
- // detected); rolls back manifests if tests fail.
2069
- const apply_sca_upgrade = {
2070
- name: 'apply_sca_upgrade',
2071
- 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).',
2072
- inputSchema: {
2073
- type: 'object',
2074
- additionalProperties: false,
2075
- properties: {
2076
- finding_id: { type: 'string', minLength: 1, maxLength: 256 },
2077
- confirm: { type: 'boolean' },
2078
- run_tests: { type: 'boolean' },
2079
- },
2080
- required: ['finding_id', 'confirm'],
2081
- },
2082
- async handler({ finding_id, confirm, run_tests = true }, ctx) {
2083
- if (confirm !== true) {
2084
- return { _meta: tools_META, applied: false, reason: 'apply_sca_upgrade requires confirm: true.' };
2085
- }
2086
- const { scan, status } = _readLastScanVerified(ctx.sessionRoot, { allowUnsigned: false });
2087
- if (!scan) {
2088
- return { _meta: tools_META, applied: false, reason: `last-scan.json failed integrity check: ${status}. Run a fresh scan.` };
2089
- }
2090
- const f = _findById(scan, finding_id);
2091
- if (!f) return { _meta: tools_META, applied: false, reason: `Finding not found: ${finding_id}` };
2092
- if (f.type !== 'vulnerable_dep') {
2093
- return { _meta: tools_META, applied: false, reason: 'finding is not an SCA vulnerable_dep — use apply_fix for SAST findings' };
2094
- }
2095
- const { applyScaUpgrade } = await _getScaUpgrade();
2096
- const result = await applyScaUpgrade({ scanRoot: ctx.sessionRoot, finding: f, runTests: run_tests });
2097
- return { _meta: tools_META, ...result };
2098
- },
2099
- };
2100
-
2101
- 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, dataflow_get_graph, dataflow_get_node, dataflow_get_edge, dataflow_get_flow];
2102
-
2103
- ;// CONCATENATED MODULE: ./src/mcp/validate.js
2104
- // Minimal JSON Schema validator — just the subset our tool schemas use.
2105
- // No deps. Throws on invalid input with a path-prefixed error message.
2106
- //
2107
- // Supported keywords: type (object/array/string/boolean/number),
2108
- // required, properties, items, enum, minItems, maxItems, maxLength,
2109
- // minLength, additionalProperties (only as `false` — strict).
2110
-
2111
- const TYPE_OF = (v) => {
2112
- if (v === null) return 'null';
2113
- if (Array.isArray(v)) return 'array';
2114
- return typeof v;
2115
- };
2116
-
2117
- function validate(schema, value, path = 'arguments') {
2118
- if (!schema) return;
2119
- const t = schema.type;
2120
- if (t === 'object') {
2121
- if (TYPE_OF(value) !== 'object') throw new Error(`${path}: expected object, got ${TYPE_OF(value)}`);
2122
- for (const req of schema.required || []) {
2123
- if (!(req in value)) throw new Error(`${path}: missing required property "${req}"`);
2124
- }
2125
- if (schema.additionalProperties === false) {
2126
- const allowed = new Set(Object.keys(schema.properties || {}));
2127
- for (const k of Object.keys(value)) {
2128
- if (!allowed.has(k)) throw new Error(`${path}: unexpected property "${k}"`);
2129
- }
2130
- }
2131
- for (const [k, sub] of Object.entries(schema.properties || {})) {
2132
- if (k in value) validate(sub, value[k], `${path}.${k}`);
2133
- }
2134
- } else if (t === 'array') {
2135
- if (!Array.isArray(value)) throw new Error(`${path}: expected array, got ${TYPE_OF(value)}`);
2136
- if (schema.minItems != null && value.length < schema.minItems) throw new Error(`${path}: minItems=${schema.minItems}, got length=${value.length}`);
2137
- if (schema.maxItems != null && value.length > schema.maxItems) throw new Error(`${path}: maxItems=${schema.maxItems}, got length=${value.length}`);
2138
- if (schema.items) for (let i = 0; i < value.length; i++) validate(schema.items, value[i], `${path}[${i}]`);
2139
- } else if (t === 'string') {
2140
- if (typeof value !== 'string') throw new Error(`${path}: expected string, got ${TYPE_OF(value)}`);
2141
- if (schema.enum && !schema.enum.includes(value)) throw new Error(`${path}: must be one of [${schema.enum.join(', ')}]`);
2142
- if (schema.maxLength != null && value.length > schema.maxLength) throw new Error(`${path}: maxLength=${schema.maxLength}, got length=${value.length}`);
2143
- if (schema.minLength != null && value.length < schema.minLength) throw new Error(`${path}: minLength=${schema.minLength}, got length=${value.length}`);
2144
- } else if (t === 'boolean') {
2145
- if (typeof value !== 'boolean') throw new Error(`${path}: expected boolean, got ${TYPE_OF(value)}`);
2146
- } else if (t === 'number' || t === 'integer') {
2147
- if (typeof value !== 'number') throw new Error(`${path}: expected number, got ${TYPE_OF(value)}`);
2148
- if (t === 'integer' && !Number.isInteger(value)) throw new Error(`${path}: expected integer`);
2149
- if (schema.minimum != null && value < schema.minimum) throw new Error(`${path}: < minimum (${schema.minimum})`);
2150
- if (schema.maximum != null && value > schema.maximum) throw new Error(`${path}: > maximum (${schema.maximum})`);
2151
- }
2152
- }
2153
-
2154
- ;// CONCATENATED MODULE: ./src/mcp/audit.js
2155
- // Append-only audit log of MCP tool calls — OWASP MCP08.
2156
- //
2157
- // Format: one JSON object per line (NDJSON) at
2158
- // <sessionRoot>/.agentic-security/mcp-audit.log
2159
- //
2160
- // Each entry carries `prev` — the SHA-256 of the previous entry's serialized
2161
- // form. The first entry's prev is "GENESIS". Tampering with any line breaks
2162
- // the chain from that point forward; a reader can detect partial truncation
2163
- // or in-place edits.
2164
- //
2165
- // REMOTE SINK (post-recommendation #10). The local file alone cannot detect
2166
- // a total rewrite — an attacker with FS write can re-author the whole log
2167
- // with fresh hashes. Closing that blind spot requires an off-host witness.
2168
- // Set $AGENTIC_SECURITY_AUDIT_WEBHOOK to a POST endpoint; every entry is
2169
- // fire-and-forget POSTed there in addition to the local append. Failures
2170
- // to reach the webhook are best-effort — they NEVER block a tool call,
2171
- // because that would let a network outage become a denial of service. They
2172
- // DO get recorded as `_remoteSinkErr` on the local entry, so an operator
2173
- // reviewing the log later can spot a forging attempt that targeted the
2174
- // remote (any gap between local-sequence and remote-sequence is evidence).
2175
- //
2176
- // Argument blobs are redacted (OWASP MCP01/MCP10) so credentials passed in
2177
- // arguments cannot leak via the audit trail OR via the remote sink.
2178
-
2179
-
2180
-
2181
-
2182
-
2183
-
2184
-
2185
- const MAX_ARG_BYTES = 1024;
2186
- const GENESIS = 'GENESIS';
2187
- const REMOTE_TIMEOUT_MS = 1500;
2188
-
2189
- // Per-process session ID (harness-anatomy #9). Stamped on every audit entry
2190
- // so downstream metrics can aggregate by session and surface outliers like
2191
- // "200 apply_fix calls in one session." The ID is `<pid>-<short-ts>` — not
2192
- // cryptographically unique, but enough to disambiguate concurrent runs on
2193
- // the same host. Stable for the lifetime of this Node process.
2194
- const SESSION_ID = `${process.pid}-${Date.now().toString(36).slice(-6)}`;
2195
-
2196
- function _summarize(args) {
2197
- let s;
2198
- try { s = JSON.stringify(args); } catch { s = '<unserializable>'; }
2199
- s = (0,redact/* redactArgsBlob */.MC)(s);
2200
- if (s.length > MAX_ARG_BYTES) s = s.slice(0, MAX_ARG_BYTES) + `…(+${s.length - MAX_ARG_BYTES})`;
2201
- return s;
2202
- }
2203
-
2204
- function _sha(s) { return external_node_crypto_.createHash('sha256').update(s).digest('hex'); }
2205
-
2206
- function _readLastEntryHash(logFile) {
2207
- if (!external_node_fs_.existsSync(logFile)) return GENESIS;
2208
- try {
2209
- const all = external_node_fs_.readFileSync(logFile, 'utf8');
2210
- const lines = all.split('\n').filter(Boolean);
2211
- if (!lines.length) return GENESIS;
2212
- return _sha(lines[lines.length - 1]);
2213
- } catch { return GENESIS; }
2214
- }
2215
-
2216
- // Fire-and-forget POST to the remote sink. Resolves to null on success,
2217
- // to a short error string on failure. Never throws; never blocks longer
2218
- // than REMOTE_TIMEOUT_MS. The local audit append happens regardless.
2219
- async function _postRemote(url, entry) {
2220
- try {
2221
- const controller = new AbortController();
2222
- const t = setTimeout(() => controller.abort(), REMOTE_TIMEOUT_MS);
2223
- const r = await fetch(url, {
2224
- method: 'POST',
2225
- headers: { 'Content-Type': 'application/json' },
2226
- body: JSON.stringify(entry),
2227
- signal: controller.signal,
2228
- });
2229
- clearTimeout(t);
2230
- if (!r.ok) return `HTTP ${r.status}`;
2231
- return null;
2232
- } catch (e) {
2233
- return String((e && e.message) || e).slice(0, 200);
2234
- }
2235
- }
2236
-
2237
- function auditCall({ sessionRoot, tool, args, outcome, reason }) {
2238
- if (!sessionRoot) return;
2239
- try {
2240
- // Safety: only write audit log if sessionRoot looks like a project root
2241
- const MARKERS = ['.git', 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml', 'pom.xml', 'composer.json', 'Gemfile'];
2242
- let hasMarker = false;
2243
- for (const m of MARKERS) { try { if (external_node_fs_.existsSync(external_node_path_.join(sessionRoot, m))) { hasMarker = true; break; } } catch {} }
2244
- if (!hasMarker) return;
2245
- const dir = (0,state_dir/* stateDir */.Pn)(sessionRoot);
2246
- external_node_fs_.mkdirSync(dir, { recursive: true });
2247
- const logFile = external_node_path_.join(dir, 'mcp-audit.log');
2248
- const entry = {
2249
- ts: new Date().toISOString(),
2250
- sessionId: SESSION_ID,
2251
- tool,
2252
- outcome,
2253
- ...(reason ? { reason } : {}),
2254
- args: _summarize(args),
2255
- prev: _readLastEntryHash(logFile),
2256
- };
2257
- external_node_fs_.appendFileSync(logFile, JSON.stringify(entry) + '\n');
2258
- // Remote sink (post-recommendation #10). Fire-and-forget. We don't await
2259
- // the promise so the tool call returns immediately; the remote POST runs
2260
- // on its own microtask. Failures get logged to a sidecar file so the
2261
- // operator can detect when the sink is unreachable.
2262
- const webhook = process.env.AGENTIC_SECURITY_AUDIT_WEBHOOK;
2263
- if (webhook) {
2264
- _postRemote(webhook, entry).then((err) => {
2265
- if (!err) return;
2266
- try {
2267
- const errFile = external_node_path_.join(dir, 'mcp-audit.remote-errors.log');
2268
- external_node_fs_.appendFileSync(errFile, JSON.stringify({
2269
- ts: new Date().toISOString(), entryTs: entry.ts, tool, err,
2270
- }) + '\n');
2271
- } catch { /* nothing else to do */ }
2272
- });
2273
- }
2274
- } catch { /* audit failure must never break a tool call */ }
2275
- }
2276
-
2277
- // Verify the chain from start to end. Returns
2278
- // { ok: true, entries: N } if intact
2279
- // { ok: false, brokenAt: <line-index>, expected, got } if any link breaks
2280
- // Reader/operator-facing tool.
2281
- function verifyAuditLog(logFile) {
2282
- if (!fs.existsSync(logFile)) return { ok: true, entries: 0 };
2283
- const text = fs.readFileSync(logFile, 'utf8');
2284
- const lines = text.split('\n').filter(Boolean);
2285
- let expectedPrev = GENESIS;
2286
- for (let i = 0; i < lines.length; i++) {
2287
- let entry;
2288
- try { entry = JSON.parse(lines[i]); }
2289
- catch { return { ok: false, brokenAt: i, reason: 'not JSON' }; }
2290
- if (entry.prev !== expectedPrev) {
2291
- return { ok: false, brokenAt: i, expected: expectedPrev, got: entry.prev };
2292
- }
2293
- expectedPrev = _sha(lines[i]);
2294
- }
2295
- return { ok: true, entries: lines.length };
2296
- }
2297
-
2298
- ;// CONCATENATED MODULE: ./src/mcp/server.js
2299
- // MCP server core — JSON-RPC 2.0 handler for the Model Context Protocol.
2300
- //
2301
- // Hardening posture (mapped to OWASP MCP Top 10):
2302
- // - Session root chosen at server boot, no per-call retargeting (MCP02)
2303
- // - Every tools/call argument validated against the tool's inputSchema (MCP02/MCP05)
2304
- // - Every tools/call audited with a hash-chained log (MCP08)
2305
- // - serverInfo.codeFingerprint = SHA-256 of MCP source files (MCP04/MCP09)
2306
- // so a fleet can detect tampered or unauthorized server deployments
2307
- // - AGENTIC_SECURITY_MCP_DISABLED=1 hard-disables all tool calls (MCP09)
2308
- // - Stdio transport caps line/buffer size (./stdio.js) (MCP05 DoS)
2309
-
2310
-
2311
-
2312
-
2313
-
2314
-
2315
-
2316
-
2317
-
2318
- const PROTOCOL_VERSION = '2025-03-26';
2319
- const SERVER_NAME = 'agentic-security';
2320
-
2321
- // Premortem #6: read version from scanner/package.json at module load so the
2322
- // MCP `initialize` response can't silently drift from the shipped package
2323
- // version. A hardcoded constant rotted from 0.39.2 → wrong for every release
2324
- // that followed. Fall back to 'unknown' rather than a stale literal.
2325
- const SERVER_VERSION = (() => {
2326
- try {
2327
- const here = external_node_path_.dirname((0,external_node_url_.fileURLToPath)(import.meta.url));
2328
- // scanner/src/mcp/ → scanner/package.json
2329
- const pkgPath = external_node_path_.resolve(here, '..', '..', 'package.json');
2330
- const pkg = JSON.parse(external_node_fs_.readFileSync(pkgPath, 'utf8'));
2331
- if (typeof pkg.version === 'string' && pkg.version.length) return pkg.version;
2332
- } catch { /* fall through */ }
2333
- return 'unknown';
2334
- })();
2335
-
2336
- const TOOLS_BY_NAME = Object.fromEntries(ALL_TOOLS.map(t => [t.name, t]));
2337
-
2338
- // Code fingerprint — SHA-256 of the MCP source files concatenated in a
2339
- // stable order. Embedded in `initialize` response so a fleet operator can
2340
- // detect when an unapproved build is running (OWASP MCP04/MCP09).
2341
- function _codeFingerprint() {
2342
- try {
2343
- const here = external_node_path_.dirname((0,external_node_url_.fileURLToPath)(import.meta.url));
2344
- const files = ['server.js', 'tools.js', 'dataflow-tools.js', 'stdio.js', 'audit.js', 'validate.js', 'redact.js'];
2345
- const h = external_node_crypto_.createHash('sha256');
2346
- for (const f of files) {
2347
- try { h.update(f); h.update(external_node_fs_.readFileSync(external_node_path_.join(here, f))); } catch {}
2348
- }
2349
- return h.digest('hex');
2350
- } catch { return null; }
2351
- }
2352
- const CODE_FINGERPRINT = _codeFingerprint();
2353
-
2354
- function _err(id, code, message, data) {
2355
- const out = { jsonrpc: '2.0', id, error: { code, message } };
2356
- if (data !== undefined) out.error.data = data;
2357
- return out;
2358
- }
2359
-
2360
- function _ok(id, result) {
2361
- return { jsonrpc: '2.0', id, result };
2362
- }
2363
-
2364
- function createServer({ sessionRoot = process.cwd() } = {}) {
2365
- const ctx = { sessionRoot };
2366
-
2367
- async function handleRequest(msg) {
2368
- if (!msg || typeof msg !== 'object') return _err(null, -32600, 'Invalid Request');
2369
- if (msg.jsonrpc !== '2.0') return _err(msg.id ?? null, -32600, 'Invalid Request: jsonrpc must be "2.0"');
2370
-
2371
- const isNotification = msg.id === undefined || msg.id === null;
2372
- const id = msg.id ?? null;
2373
- const disabled = process.env.AGENTIC_SECURITY_MCP_DISABLED === '1';
2374
-
2375
- switch (msg.method) {
2376
- case 'initialize':
2377
- return _ok(id, {
2378
- protocolVersion: PROTOCOL_VERSION,
2379
- capabilities: { tools: {} },
2380
- serverInfo: {
2381
- name: SERVER_NAME,
2382
- version: SERVER_VERSION,
2383
- codeFingerprint: CODE_FINGERPRINT,
2384
- disabled,
2385
- },
2386
- });
2387
-
2388
- case 'notifications/initialized':
2389
- return null;
2390
-
2391
- case 'ping':
2392
- return _ok(id, {});
2393
-
2394
- case 'tools/list':
2395
- return _ok(id, {
2396
- tools: ALL_TOOLS.map(t => ({
2397
- name: t.name,
2398
- description: t.description,
2399
- inputSchema: t.inputSchema,
2400
- })),
2401
- });
2402
-
2403
- case 'tools/call': {
2404
- const name = msg.params?.name;
2405
- const args = msg.params?.arguments ?? {};
2406
- if (disabled) {
2407
- auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: 'server-disabled' });
2408
- return _ok(id, {
2409
- content: [{ type: 'text', text: 'MCP server is disabled (AGENTIC_SECURITY_MCP_DISABLED=1).' }],
2410
- isError: true,
2411
- });
2412
- }
2413
- const tool = TOOLS_BY_NAME[name];
2414
- if (!tool) {
2415
- auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: 'unknown-tool' });
2416
- return _err(id, -32602, `Unknown tool: ${name}`);
2417
- }
2418
- try { validate(tool.inputSchema, args); }
2419
- catch (e) {
2420
- auditCall({ sessionRoot, tool: name, args, outcome: 'rejected', reason: `invalid-args: ${e.message}` });
2421
- return _ok(id, {
2422
- content: [{ type: 'text', text: `Invalid arguments: ${e.message}` }],
2423
- isError: true,
2424
- });
2425
- }
2426
- try {
2427
- const result = await tool.handler(args, ctx);
2428
- auditCall({ sessionRoot, tool: name, args, outcome: 'ok' });
2429
- return _ok(id, {
2430
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
2431
- isError: false,
2432
- });
2433
- } catch (e) {
2434
- auditCall({ sessionRoot, tool: name, args, outcome: 'error', reason: e.message });
2435
- return _ok(id, {
2436
- content: [{ type: 'text', text: `Error: ${e.message}` }],
2437
- isError: true,
2438
- });
2439
- }
2440
- }
2441
-
2442
- default:
2443
- if (isNotification) return null;
2444
- return _err(id, -32601, `Method not found: ${msg.method}`);
2445
- }
2446
- }
2447
-
2448
- return { handleRequest, sessionRoot };
2449
- }
2450
-
2451
- // NOTE: no default-singleton export. Callers must use createServer({...})
2452
- // with an explicit sessionRoot. Removed because the prior default was bound
2453
- // to process.cwd() at module-load time — a footgun for any caller that
2454
- // imported `handleRequest` directly (OWASP A05).
2455
-
2456
-
2457
-
2458
- ;// CONCATENATED MODULE: ./src/mcp/stdio.js
2459
- // Stdio transport for the MCP server — newline-delimited JSON in/out.
2460
- //
2461
- // MCP's stdio transport is NDJSON: one JSON-RPC message per line on stdin,
2462
- // one response per line on stdout. stderr is reserved for logging.
2463
- //
2464
- // Hardening:
2465
- // - Per-message line cap (MAX_LINE_BYTES). A line over the cap is dropped
2466
- // and the buffer state is reset so a long oversize payload can't peg
2467
- // the parser via `buf += chunk` growth.
2468
- // - Buffer hard cap (MAX_BUFFER_BYTES). Reached if input arrives with no
2469
- // newlines (e.g., a peer streaming a 4GB stream of `a`). On overflow we
2470
- // emit a parse-error response and reset.
2471
-
2472
-
2473
-
2474
- const MAX_LINE_BYTES = 4 * 1024 * 1024; // 4 MB per JSON-RPC message
2475
- const MAX_BUFFER_BYTES = 8 * 1024 * 1024; // 8 MB sliding buffer
2476
-
2477
- function runStdio({
2478
- stdin = process.stdin,
2479
- stdout = process.stdout,
2480
- stderr = process.stderr,
2481
- sessionRoot = process.cwd(),
2482
- } = {}) {
2483
- const server = createServer({ sessionRoot });
2484
- let buf = '';
2485
- let overflowSkip = false; // true while we are dropping bytes until the next newline
2486
-
2487
- stdin.setEncoding('utf8');
2488
-
2489
- stdin.on('data', async (chunk) => {
2490
- if (overflowSkip) {
2491
- const nl = chunk.indexOf('\n');
2492
- if (nl === -1) return;
2493
- // Resume after the next newline.
2494
- chunk = chunk.slice(nl + 1);
2495
- overflowSkip = false;
2496
- }
2497
-
2498
- buf += chunk;
2499
-
2500
- // Hard buffer cap — only triggers if a peer is streaming without newlines.
2501
- if (buf.length > MAX_BUFFER_BYTES) {
2502
- stderr.write(`mcp: input buffer exceeded ${MAX_BUFFER_BYTES} bytes — dropping until next newline\n`);
2503
- const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error: input too large' } };
2504
- stdout.write(JSON.stringify(errResponse) + '\n');
2505
- buf = '';
2506
- overflowSkip = true;
2507
- return;
2508
- }
2509
-
2510
- let nl;
2511
- while ((nl = buf.indexOf('\n')) !== -1) {
2512
- const line = buf.slice(0, nl).trim();
2513
- buf = buf.slice(nl + 1);
2514
- if (!line) continue;
2515
- if (line.length > MAX_LINE_BYTES) {
2516
- stderr.write(`mcp: dropped oversize line (${line.length} > ${MAX_LINE_BYTES} bytes)\n`);
2517
- const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error: line too large' } };
2518
- stdout.write(JSON.stringify(errResponse) + '\n');
2519
- continue;
2520
- }
2521
- let msg;
2522
- try { msg = JSON.parse(line); }
2523
- catch (e) {
2524
- stderr.write(`mcp: failed to parse line as JSON: ${e.message}\n`);
2525
- const errResponse = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } };
2526
- stdout.write(JSON.stringify(errResponse) + '\n');
2527
- continue;
2528
- }
2529
- try {
2530
- const response = await server.handleRequest(msg);
2531
- if (response !== null) stdout.write(JSON.stringify(response) + '\n');
2532
- } catch (e) {
2533
- stderr.write(`mcp: handler threw: ${e.message}\n`);
2534
- const errResponse = { jsonrpc: '2.0', id: msg.id ?? null, error: { code: -32603, message: 'Internal error', data: e.message } };
2535
- stdout.write(JSON.stringify(errResponse) + '\n');
2536
- }
2537
- }
2538
- });
2539
-
2540
- stdin.on('end', () => { process.exit(0); });
2541
- }
2542
-
2543
-
2544
- /***/ }),
2545
-
2546
- /***/ 8752:
2547
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2548
-
2549
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2550
- /* harmony export */ analyzeTranscript: () => (/* binding */ analyzeTranscript),
2551
- /* harmony export */ formatCacheReport: () => (/* binding */ formatCacheReport),
2552
- /* harmony export */ renderCacheStatusLine: () => (/* binding */ renderCacheStatusLine)
2553
- /* harmony export */ });
2554
- /* unused harmony export _internal */
2555
- /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
2556
- /* harmony import */ var node_os__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8161);
2557
- /* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6760);
2558
- // Prompt-cache economics — turn Claude Code's own transcript usage into a
2559
- // dollarized report: how much prompt caching saved, how much was wasted on
2560
- // avoidable cache misses, and what invalidated the cache.
2561
- //
2562
- // Source of truth: the Claude Code transcript at
2563
- // ~/.claude/projects/<enc>/<session>.jsonl
2564
- // where <enc> is CLAUDE_PROJECT_DIR with `/` and `.` replaced by `-`. Each
2565
- // assistant turn carries `message.usage` with input/output/cache_read/
2566
- // cache_creation token counts (and a 5m/1h write split). We price those against
2567
- // per-model rates to compute real economics — no estimates, no network.
2568
- //
2569
- // Pure compute on parsed records; only `locateTranscript`/`parseTranscriptUsage`
2570
- // touch the filesystem. ESM (scanner tree). A trimmed CJS twin lives at
2571
- // hooks/lib/transcript.js for the CJS hooks; test/cache-economics.test.js asserts
2572
- // the two agree.
2573
-
2574
-
2575
-
2576
-
2577
- // Cents-scale money formatter (fmtUsd in risk-dollars.js targets five-figure
2578
- // breach costs and won't round sub-dollar values).
2579
- function money(n) {
2580
- const v = Number(n) || 0;
2581
- return Math.abs(v) >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;
2582
- }
2583
-
2584
- // Per-1M-token rates (input / output). Mirror hooks/model-cost-advisor.js MODELS.
2585
- const MODEL_RATES = {
2586
- fable: { label: 'Fable 5', in: 10, out: 50 },
2587
- opus: { label: 'Opus 4.8', in: 5, out: 25 },
2588
- sonnet5: { label: 'Sonnet 5', in: 3, out: 15 },
2589
- sonnet: { label: 'Sonnet 4.6', in: 3, out: 15 },
2590
- haiku: { label: 'Haiku 4.5', in: 1, out: 5 },
2591
- };
2592
- const CACHE_READ_MULT = 0.1; // cache read ≈ 0.1× input
2593
- const CACHE_WRITE_MULT = 1.25; // 5-minute cache write ≈ 1.25× input
2594
- const CACHE_WRITE_1H_MULT = 2.0; // 1-hour cache write ≈ 2× input
2595
- const TTL_MS = 5 * 60 * 1000;
2596
-
2597
- // Map any model string to a rate family. Returns null for unpriceable models
2598
- // (e.g. "<synthetic>" sidechain/compaction turns) so they're skipped.
2599
- function rateFor(model) {
2600
- if (typeof model !== 'string') return null;
2601
- const s = model.toLowerCase();
2602
- if (s.includes('fable') || s.includes('mythos')) return MODEL_RATES.fable;
2603
- if (s.includes('haiku')) return MODEL_RATES.haiku;
2604
- if (s.includes('sonnet')) return (s.includes('sonnet-5') || s.includes('sonnet 5')) ? MODEL_RATES.sonnet5 : MODEL_RATES.sonnet;
2605
- if (s.includes('opus')) return MODEL_RATES.opus;
2606
- return null;
2607
- }
2608
-
2609
- // ── Transcript discovery + parse ─────────────────────────────────────────────
2610
-
2611
- function encodeProjectDir(dir) {
2612
- return String(dir).replace(/[/.]/g, '-');
2613
- }
2614
-
2615
- // Locate the session transcript. Prefer an explicit (hook-provided) path; else
2616
- // derive the project's transcript dir and take the most-recently-modified jsonl.
2617
- function locateTranscript({ transcriptPath, projectDir } = {}) {
2618
- try {
2619
- if (transcriptPath && node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(transcriptPath)) return transcriptPath;
2620
- } catch { /* fall through */ }
2621
- try {
2622
- const dir = node_path__WEBPACK_IMPORTED_MODULE_2__.join(node_os__WEBPACK_IMPORTED_MODULE_1__.homedir(), '.claude', 'projects', encodeProjectDir(projectDir || process.cwd()));
2623
- if (!node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(dir)) return null;
2624
- const files = node_fs__WEBPACK_IMPORTED_MODULE_0__.readdirSync(dir)
2625
- .filter(f => f.endsWith('.jsonl'))
2626
- .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 }))
2627
- .sort((a, b) => b.m - a.m);
2628
- return files.length ? files[0].f : null;
2629
- } catch { return null; }
2630
- }
2631
-
2632
- // Parse a transcript jsonl into per-assistant-turn usage records. Skips lines
2633
- // that aren't priceable assistant turns.
2634
- function parseTranscriptUsage(jsonlPath) {
2635
- let raw;
2636
- try { raw = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(jsonlPath, 'utf8'); } catch { return []; }
2637
- const records = [];
2638
- for (const line of raw.split('\n')) {
2639
- const t = line.trim();
2640
- if (!t) continue;
2641
- let o;
2642
- try { o = JSON.parse(t); } catch { continue; }
2643
- if (o.type !== 'assistant') continue;
2644
- const msg = o.message;
2645
- const u = msg && msg.usage;
2646
- if (!u || !msg.model || !rateFor(msg.model)) continue;
2647
- const cc = u.cache_creation || {};
2648
- records.push({
2649
- model: msg.model,
2650
- input: u.input_tokens || 0,
2651
- output: u.output_tokens || 0,
2652
- cacheRead: u.cache_read_input_tokens || 0,
2653
- cacheCreate: u.cache_creation_input_tokens || 0,
2654
- cacheCreate5m: cc.ephemeral_5m_input_tokens || 0,
2655
- cacheCreate1h: cc.ephemeral_1h_input_tokens || 0,
2656
- ts: o.timestamp ? Date.parse(o.timestamp) : null,
2657
- });
2658
- }
2659
- return records;
2660
- }
2661
-
2662
- // ── Pure economics ───────────────────────────────────────────────────────────
2663
-
2664
- function writeCostUsd(r, inRate) {
2665
- const m5 = r.cacheCreate5m || 0, m1 = r.cacheCreate1h || 0;
2666
- if (m5 + m1 > 0) return (m5 * CACHE_WRITE_MULT + m1 * CACHE_WRITE_1H_MULT) * inRate;
2667
- return (r.cacheCreate || 0) * CACHE_WRITE_MULT * inRate; // breakdown absent
2668
- }
2669
-
2670
- // Aggregate economics over parsed records.
2671
- function computeCacheEconomics(records) {
2672
- let turns = 0, inTok = 0, outTok = 0, cacheRead = 0, cacheCreate = 0;
2673
- let actualUsd = 0, uncachedUsd = 0, writePremiumUsd = 0;
2674
- const perModel = {};
2675
-
2676
- for (const r of records) {
2677
- const rate = rateFor(r.model);
2678
- if (!rate) continue;
2679
- turns++;
2680
- const inRate = rate.in / 1e6, outRate = rate.out / 1e6;
2681
-
2682
- const readCost = r.cacheRead * inRate * CACHE_READ_MULT;
2683
- const writeCost = writeCostUsd(r, inRate);
2684
- const inCost = r.input * inRate;
2685
- const outCost = r.output * outRate;
2686
- const turnActual = readCost + writeCost + inCost + outCost;
2687
- // What this turn would have cost with NO caching: every input-side token full price.
2688
- const turnUncached = (r.cacheRead + r.cacheCreate + r.input) * inRate + outCost;
2689
-
2690
- actualUsd += turnActual;
2691
- uncachedUsd += turnUncached;
2692
- writePremiumUsd += writeCost - (r.cacheCreate * inRate); // the >1× premium paid to cache
2693
-
2694
- inTok += r.input; outTok += r.output; cacheRead += r.cacheRead; cacheCreate += r.cacheCreate;
2695
-
2696
- const key = rate.label;
2697
- const pm = perModel[key] || (perModel[key] = { turns: 0, actualUsd: 0, cacheRead: 0, inputSide: 0 });
2698
- pm.turns++; pm.actualUsd += turnActual; pm.cacheRead += r.cacheRead;
2699
- pm.inputSide += r.cacheRead + r.cacheCreate + r.input;
2700
- }
2701
-
2702
- const inputSide = cacheRead + cacheCreate + inTok;
2703
- return {
2704
- turns,
2705
- tokens: { input: inTok, output: outTok, cacheRead, cacheCreate },
2706
- actualUsd,
2707
- uncachedUsd,
2708
- savedUsd: uncachedUsd - actualUsd, // net $ caching saved (can dip negative early)
2709
- writePremiumUsd, // $ invested establishing caches
2710
- cacheHitRatio: inputSide ? cacheRead / inputSide : 0,
2711
- costPerTurnUsd: turns ? actualUsd / turns : 0,
2712
- perModel,
2713
- };
2714
- }
2715
-
2716
- // Attribute cache drops: a turn that re-ingests a large prefix cold after a warm
2717
- // prior turn. Cause = model-switch | cache-expired | prefix-change.
2718
- function detectInvalidators(records) {
2719
- const leaks = [];
2720
- const MIN_WARM = 2000;
2721
- for (let i = 1; i < records.length; i++) {
2722
- const prev = records[i - 1], cur = records[i];
2723
- const prevWarm = prev.cacheRead + prev.input + prev.cacheCreate;
2724
- if (prevWarm < MIN_WARM) continue;
2725
- const curFresh = cur.input + cur.cacheCreate;
2726
- const coldish = cur.cacheRead < prevWarm * 0.25 && curFresh > prevWarm * 0.5;
2727
- if (!coldish) continue;
2728
-
2729
- let cause;
2730
- if (cur.model !== prev.model) cause = 'model-switch';
2731
- else if (cur.ts && prev.ts && (cur.ts - prev.ts) > TTL_MS) cause = 'cache-expired';
2732
- else cause = 'prefix-change';
2733
-
2734
- const rate = rateFor(cur.model);
2735
- const inRate = rate ? rate.in / 1e6 : 0;
2736
- // Extra paid vs. having kept the prefix as a cheap cache read.
2737
- const wastedUsd = prevWarm * inRate * (1 - CACHE_READ_MULT);
2738
- leaks.push({ turn: i, cause, wastedUsd, model: cur.model });
2739
- }
2740
- return leaks;
2741
- }
2742
-
2743
- // Convenience: locate → parse → compute → detect. Returns { ok:false } when no
2744
- // transcript is available.
2745
- function analyzeTranscript(opts = {}) {
2746
- const transcript = locateTranscript(opts);
2747
- if (!transcript) return { ok: false, reason: 'no-transcript' };
2748
- const records = parseTranscriptUsage(transcript);
2749
- if (!records.length) return { ok: false, reason: 'no-priceable-turns', transcript };
2750
- return {
2751
- ok: true,
2752
- transcript,
2753
- metrics: computeCacheEconomics(records),
2754
- leaks: detectInvalidators(records),
2755
- };
2756
- }
2757
-
2758
- // ── Report formatting ────────────────────────────────────────────────────────
2759
-
2760
- const CAUSE_LABEL = {
2761
- 'model-switch': 'model switch (cache is model-scoped)',
2762
- 'cache-expired': 'cache expired (gap > 5-min TTL)',
2763
- 'prefix-change': 'prefix changed (system prompt / tools / context edit)',
2764
- };
2765
-
2766
- // F6 — one-line HUD for a Claude Code statusLine command (mirrors
2767
- // watch-mode.js renderStatusLine). Takes the metrics from computeCacheEconomics.
2768
- function renderCacheStatusLine(metrics) {
2769
- if (!metrics || !metrics.turns) return 'agentic-security: no session cost yet';
2770
- const hit = Math.round(metrics.cacheHitRatio * 100);
2771
- return `agentic-security: ${money(metrics.actualUsd)} · ${hit}% cached · ${money(metrics.costPerTurnUsd)}/turn`;
2772
- }
2773
-
2774
- function formatCacheReport(result) {
2775
- if (!result.ok) {
2776
- return result.reason === 'no-transcript'
2777
- ? 'agentic-security: no Claude Code transcript found for this project yet.'
2778
- : 'agentic-security: transcript has no priceable model turns yet.';
2779
- }
2780
- const m = result.metrics;
2781
- const lines = [];
2782
- lines.push('');
2783
- lines.push(' Prompt-cache economics — this session');
2784
- lines.push(` ${result.turns ?? m.turns} model turns\n`);
2785
- lines.push(` cache hit ratio ${(m.cacheHitRatio * 100).toFixed(1)}% (input-side tokens served from cache)`);
2786
- lines.push(` spent ${money(m.actualUsd)} (~${money(m.costPerTurnUsd)}/turn)`);
2787
- lines.push(` ▶ saved by caching ${money(m.savedUsd)} vs. ${money(m.uncachedUsd)} with no cache`);
2788
- lines.push(` invested in caches ${money(m.writePremiumUsd)} (write premium over base input)`);
2789
- lines.push('');
2790
- lines.push(' tokens: '
2791
- + `${m.tokens.cacheRead.toLocaleString()} cached-read · `
2792
- + `${m.tokens.cacheCreate.toLocaleString()} cache-write · `
2793
- + `${m.tokens.input.toLocaleString()} fresh-in · `
2794
- + `${m.tokens.output.toLocaleString()} out`);
2795
-
2796
- const models = Object.keys(m.perModel);
2797
- if (models.length > 1) {
2798
- lines.push('\n by model:');
2799
- for (const k of models.sort()) {
2800
- const pm = m.perModel[k];
2801
- const hr = pm.inputSide ? (pm.cacheRead / pm.inputSide * 100).toFixed(0) : '0';
2802
- lines.push(` ${k.padEnd(12)} ${pm.turns} turns · ${money(pm.actualUsd)} · ${hr}% cached`);
2803
- }
2804
- }
2805
-
2806
- if (result.leaks && result.leaks.length) {
2807
- const wasted = result.leaks.reduce((s, l) => s + l.wastedUsd, 0);
2808
- lines.push(`\n ⚠ cache leaks (${result.leaks.length}, ~${money(wasted)} wasted re-ingesting context):`);
2809
- const byCause = {};
2810
- for (const l of result.leaks) {
2811
- (byCause[l.cause] || (byCause[l.cause] = { n: 0, usd: 0 })).n++;
2812
- byCause[l.cause].usd += l.wastedUsd;
2813
- }
2814
- for (const c of Object.keys(byCause).sort()) {
2815
- lines.push(` · ${byCause[c].n}× ${CAUSE_LABEL[c] || c} — ~${money(byCause[c].usd)}`);
2816
- }
2817
- lines.push(' Keep one model + a stable system prompt within a working window to avoid these.');
2818
- } else {
2819
- lines.push('\n ✓ no cache leaks detected — your context stayed warm.');
2820
- }
2821
- lines.push('');
2822
- return lines.join('\n');
2823
- }
2824
-
2825
- // Test surface (underscore export is exempt from the dead-module gate).
2826
- const _internal = {
2827
- MODEL_RATES, CACHE_READ_MULT, CACHE_WRITE_MULT, CACHE_WRITE_1H_MULT,
2828
- rateFor, locateTranscript, parseTranscriptUsage, computeCacheEconomics, detectInvalidators,
2829
- };
2830
-
2831
-
2832
- /***/ }),
2833
-
2834
- /***/ 8218:
2835
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2836
-
2837
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2838
- /* harmony export */ loadFreshLineageGraph: () => (/* binding */ loadFreshLineageGraph),
2839
- /* harmony export */ loadSignedGraph: () => (/* binding */ loadSignedGraph)
2840
- /* harmony export */ });
2841
- /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
2842
- /* harmony import */ var _posture_state_dir_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1174);
2843
- /* harmony import */ var _posture_integrity_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1130);
2844
- // graph-loader.js — Milestone 3, sub-project Server, increment 1.
2845
- //
2846
- // Reads and VERIFIES the `.agentic-security/lineage-graph.json` artifact
2847
- // before `explore` is allowed to serve a single byte of it. Reuses
2848
- // `posture/integrity.js`'s `verifyLastScan` DIRECTLY (per the plan and the
2849
- // root CLAUDE.md's own instruction) — this module does not implement any
2850
- // signature comparison of its own. `verifyLastScan` already uses
2851
- // `crypto.timingSafeEqual` internally.
2852
- //
2853
- // Loaded ONCE at server startup (see bin/agentic-security.js's cmdExplore)
2854
- // and held in memory for the life of the process — this is a read-only,
2855
- // single-scan-snapshot server; a change to the graph on disk mid-session is
2856
- // out of scope for this increment (threat-model doc's own "P0 is
2857
- // read-only" framing).
2858
-
2859
-
2860
-
2861
-
2862
-
2863
- /**
2864
- * @param {string} scanRoot
2865
- * @returns {{ok:true, graph:object} | {ok:false, reason:'missing'|'unsigned'|'tampered'|'malformed', message:string}}
2866
- *
2867
- * Four, and only four, distinct failure reasons — each with its own clear
2868
- * message so an operator knows exactly what to do next:
2869
- * - 'missing' — no lineage-graph.json at all. Run a scan with
2870
- * AGENTIC_SECURITY_LINEAGE_DEEP=1 first.
2871
- * - 'unsigned' — the graph exists but its .sig sibling does not
2872
- * (verifyLastScan returns null). Refuse to serve an
2873
- * unverifiable graph.
2874
- * - 'tampered' — the graph exists and has a .sig, but the signature does
2875
- * not match the body (verifyLastScan returns false). The
2876
- * file was modified after signing, or signed under a
2877
- * different install key.
2878
- * - 'malformed' — the body passed signature verification but is not
2879
- * valid JSON. Should not happen from a normal scan; the
2880
- * file may be corrupted on disk after signing.
2881
- */
2882
- function loadSignedGraph(scanRoot) {
2883
- const graphPath = (0,_posture_state_dir_js__WEBPACK_IMPORTED_MODULE_1__/* .statePath */ .BQ)(scanRoot, 'lineage-graph.json');
2884
- const sigPath = graphPath + '.sig';
2885
-
2886
- if (!node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(graphPath)) {
2887
- return {
2888
- ok: false,
2889
- reason: 'missing',
2890
- message: `No lineage graph found at ${graphPath}. Run a scan with AGENTIC_SECURITY_LINEAGE_DEEP=1 first (e.g. \`AGENTIC_SECURITY_LINEAGE_DEEP=1 agentic-security scan\`), then re-run \`agentic-security explore\`.`,
2891
- };
2892
- }
2893
-
2894
- let body;
2895
- try {
2896
- body = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(graphPath, 'utf8');
2897
- } catch (e) {
2898
- return {
2899
- ok: false,
2900
- reason: 'missing',
2901
- message: `Lineage graph found at ${graphPath} but could not be read: ${e && e.message ? e.message : e}.`,
2902
- };
2903
- }
2904
-
2905
- const verified = (0,_posture_integrity_js__WEBPACK_IMPORTED_MODULE_2__/* .verifyLastScan */ .Ef)(body, sigPath);
2906
- if (verified === null) {
2907
- return {
2908
- ok: false,
2909
- reason: 'unsigned',
2910
- message: `Lineage graph at ${graphPath} has no signature file (${sigPath} is missing). Refusing to serve an unverifiable graph. Re-run the scan (AGENTIC_SECURITY_LINEAGE_DEEP=1) to regenerate both files together.`,
2911
- };
2912
- }
2913
- if (verified === false) {
2914
- return {
2915
- ok: false,
2916
- reason: 'tampered',
2917
- message: `Lineage graph at ${graphPath} FAILED signature verification — its contents do not match ${sigPath}. The file may have been modified after the scan, or signed under a different install key. Refusing to serve a tampered graph. Re-run the scan to regenerate it.`,
2918
- };
2919
- }
2920
-
2921
- let graph;
2922
- try {
2923
- graph = JSON.parse(body);
2924
- } catch (e) {
2925
- return {
2926
- ok: false,
2927
- reason: 'malformed',
2928
- message: `Lineage graph at ${graphPath} passed signature verification but is not valid JSON (${e && e.message ? e.message : e}). This should not happen from a normal scan — the file may be corrupted. Re-run the scan to regenerate it.`,
2929
- };
2930
- }
2931
-
2932
- return { ok: true, graph };
2933
- }
2934
-
2935
- /**
2936
- * Load .agentic-security/lineage-graph.json ONLY when it is genuinely
2937
- * fresh for THIS scan — never merely because a file happens to exist on
2938
- * disk. Shared by every caller that signs or narrates a graph:-derived
2939
- * compliance claim (M4 sub-project 6c's final whole-branch review found
2940
- * the identical staleness gap independently reachable from
2941
- * `attest --obligations` AND `compliance --walkthrough`, and required
2942
- * this predicate to live in exactly one place rather than being
2943
- * copy-pasted per caller — a safety check that drifts between two
2944
- * near-identical inline copies is worse than one shared bug).
2945
- *
2946
- * `.agentic-security/lineage-graph.json` is only rewritten when a scan
2947
- * actually finishes building a graph (`if (scan.lineageGraph)` in
2948
- * bin/agentic-security.js's persistence code) — an ordinary non-deep
2949
- * rescan, or a deep scan whose lineage build fails, leaves whatever file
2950
- * was there from an earlier successful deep scan untouched. Loading that
2951
- * stale graph and joining it to the CURRENT scan's other data would let a
2952
- * caller assert a graph-derived fact (e.g. "transit protected") about
2953
- * code that has since changed.
2954
- *
2955
- * `enabled: true` in `scan.scanHealth.lineageAnalysis` does NOT by itself
2956
- * mean the build succeeded — engine.js sets it the moment
2957
- * AGENTIC_SECURITY_LINEAGE_DEEP=1 is read, before the build even starts,
2958
- * and leaves it `true` even when the build later throws (only `failure`
2959
- * gets set in that case). `requested && enabled` alone therefore still
2960
- * accepts a stale graph after a failed rebuild — reproduced live via the
2961
- * scan's own already-shipped fault-injection fixture
2962
- * (test/lineage-fault-injection.test.js) before this `failure === null`
2963
- * check was added.
2964
- *
2965
- * @param {string} scanRoot
2966
- * @param {object} scan - the parsed last-scan.json for the CURRENT scan
2967
- * @returns {{graph:object|null, fresh:boolean, loaded:ReturnType<typeof loadSignedGraph>}}
2968
- * `fresh` is true only when a signed graph loaded successfully AND this
2969
- * scan's own scanHealth confirms lineage analysis was requested,
2970
- * enabled, and did not fail. `graph` is `loaded.graph` when fresh, else
2971
- * `null` — never the stale file, even when one exists on disk.
2972
- * `loaded` is the raw `loadSignedGraph` result, so a caller can still
2973
- * distinguish "no file at all" from "a file exists but isn't fresh" for
2974
- * its own disclosure message.
2975
- */
2976
- function loadFreshLineageGraph(scanRoot, scan) {
2977
- const la = scan?.scanHealth?.lineageAnalysis;
2978
- const requested = la?.requested === true;
2979
- const enabled = la?.enabled === true;
2980
- const failure = la?.failure ?? null;
2981
- const loaded = loadSignedGraph(scanRoot);
2982
- const fresh = loaded.ok && requested && enabled && failure === null;
2983
- return { graph: fresh ? loaded.graph : null, fresh, loaded };
2984
- }
2985
-
2986
-
2987
- /***/ }),
2988
-
2989
- /***/ 4268:
2990
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2991
-
2992
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2993
- /* harmony export */ Yo: () => (/* binding */ handleScan),
2994
- /* harmony export */ Yu: () => (/* binding */ handleEdge),
2995
- /* harmony export */ d5: () => (/* binding */ handleNode),
2996
- /* harmony export */ fn: () => (/* binding */ handleGraph),
2997
- /* harmony export */ jg: () => (/* binding */ handleFlow),
2998
- /* harmony export */ rR: () => (/* binding */ handleQuery)
2999
- /* harmony export */ });
3000
- /* unused harmony export wrapResponse */
3001
- /* harmony import */ var _lineage_export_json_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(859);
3002
- // routes.js — Milestone 3, sub-project Server, increment 1.
3003
- //
3004
- // Five pure GET-endpoint handlers, each `(graph, ...) -> {status, body}`.
3005
- // No req/res access anywhere in this file — that is what makes these
3006
- // handlers unit-testable without an HTTP layer at all. http-server.js is
3007
- // the only module that touches node:http and calls into these.
3008
- //
3009
- // Every response body is wrapped in `wrapResponse`, which adds the exact
3010
- // envelope fields PRD line 1326 names (quoted in the implementation plan):
3011
- // "base graph/snapshot digest, schema/extension versions, scope, coverage,
3012
- // limitations, and contributing canonical IDs."
3013
-
3014
-
3015
-
3016
- /**
3017
- * Shared response envelope. Maps PRD line 1326's required fields onto the
3018
- * graph's own real fields:
3019
- * - digest -> graph.graphId (the base graph/snapshot digest)
3020
- * - schemaVersion -> graph.schemaVersion
3021
- * - extensions -> graph.extensions (schema/extension versions —
3022
- * today always `{}`; see schema.js)
3023
- * - scope -> graph.scope
3024
- * - coverage -> graph.coverage
3025
- * - limitations -> graph.limitations
3026
- * - canonicalIds -> see the design note below
3027
- *
3028
- * "contributing canonical IDs" design decision (disclosed per the plan):
3029
- * for `handleScan`/`handleGraph`, which describe the WHOLE graph rather
3030
- * than one entity, `canonicalIds` is `null` — the response body for
3031
- * `handleGraph` already IS the full nodes/edges/flows arrays, so echoing
3032
- * every id again here would be pure duplication with no informational
3033
- * gain, and for a large graph would materially bloat the response for
3034
- * zero benefit. For `handleNode`/`handleEdge`, `canonicalIds` is the
3035
- * single id the response is about. For `handleFlow`, `canonicalIds` is
3036
- * the flow's own id PLUS the node/edge ids that flow's evidence draws
3037
- * from (source, sink, edgeIds) — a flow is a derived record referencing
3038
- * several underlying entities, and naming all of them here is genuinely
3039
- * useful metadata a client would otherwise have to re-derive from the
3040
- * flow body itself.
3041
- */
3042
- function wrapResponse(data, graph, { canonicalIds = null } = {}) {
3043
- return {
3044
- digest: graph?.graphId ?? null,
3045
- schemaVersion: graph?.schemaVersion ?? null,
3046
- extensions: graph?.extensions ?? {},
3047
- scope: graph?.scope ?? null,
3048
- coverage: graph?.coverage ?? null,
3049
- limitations: graph?.limitations ?? [],
3050
- canonicalIds,
3051
- data,
3052
- };
3053
- }
3054
-
3055
- function _findById(list, id) {
3056
- if (!Array.isArray(list)) return null;
3057
- return list.find((item) => item && item.id === id) ?? null;
3058
- }
3059
-
3060
- /** Scan/graph metadata — NOT the full node/edge arrays. */
3061
- function handleScan(graph) {
3062
- const data = {
3063
- schemaVersion: graph?.schemaVersion ?? null,
3064
- graphId: graph?.graphId ?? null,
3065
- generatedAt: graph?.generatedAt ?? null,
3066
- scope: graph?.scope ?? null,
3067
- scanHealth: graph?.scanHealth ?? null,
3068
- coverage: graph?.coverage ?? null,
3069
- };
3070
- return { status: 200, body: wrapResponse(data, graph, { canonicalIds: null }) };
3071
- }
3072
-
3073
- /** The full graph document, unfiltered. For a scoped/narrowed projection, use `handleQuery` (`POST /api/v1/query`, Milestone 5) below instead. */
3074
- function handleGraph(graph) {
3075
- return { status: 200, body: wrapResponse(graph, graph, { canonicalIds: null }) };
3076
- }
3077
-
3078
- /**
3079
- * A deterministic typed projection query — Milestone 5's own
3080
- * `POST /api/v1/query`, the S2 endpoint `handleGraph`'s own header
3081
- * comment named and deferred. `filter` is the exact `{nodeIds, edgeIds}`
3082
- * shape `dataflow export --filter`/`exportGraphJSON` already use — reused
3083
- * via `_filterGraph`, never reimplemented. Final whole-branch review
3084
- * finding: `undefined` (filter omitted entirely) returns the WHOLE graph,
3085
- * identical to `handleGraph` — but `{}` (an empty, well-formed filter
3086
- * object) is NOT the same thing, and does NOT mean "no restriction": both
3087
- * `nodeIds`/`edgeIds` default to empty Sets inside `_filterGraph`, so `{}`
3088
- * narrows the graph down to EMPTY node/edge/flow/dataElement arrays. A
3089
- * caller that wants the whole graph must omit `filter` entirely, never
3090
- * pass `{}` meaning "everything." A malformed filter is a 400, never a
3091
- * thrown exception reaching the caller.
3092
- */
3093
- function handleQuery(graph, filter) {
3094
- const check = (0,_lineage_export_json_js__WEBPACK_IMPORTED_MODULE_0__.validateFilterShape)(filter);
3095
- if (!check.valid) {
3096
- return { status: 400, body: { error: check.error } };
3097
- }
3098
- return { status: 200, body: wrapResponse((0,_lineage_export_json_js__WEBPACK_IMPORTED_MODULE_0__/* ._filterGraph */ .e)(graph, filter), graph, { canonicalIds: null }) };
3099
- }
3100
-
3101
- /** Look up one node by id. 404 with a clear body if not found. */
3102
- function handleNode(graph, id) {
3103
- const node = _findById(graph?.nodes, id);
3104
- if (!node) {
3105
- return { status: 404, body: wrapResponse({ error: `node not found: ${id}` }, graph, { canonicalIds: [] }) };
3106
- }
3107
- return { status: 200, body: wrapResponse(node, graph, { canonicalIds: [id] }) };
3108
- }
3109
-
3110
- /** Look up one edge by id. 404 with a clear body if not found. */
3111
- function handleEdge(graph, id) {
3112
- const edge = _findById(graph?.edges, id);
3113
- if (!edge) {
3114
- return { status: 404, body: wrapResponse({ error: `edge not found: ${id}` }, graph, { canonicalIds: [] }) };
3115
- }
3116
- return { status: 200, body: wrapResponse(edge, graph, { canonicalIds: [id] }) };
3117
- }
3118
-
3119
- /** Look up one flow by id. 404 with a clear body if not found. */
3120
- function handleFlow(graph, id) {
3121
- const flow = _findById(graph?.flows, id);
3122
- if (!flow) {
3123
- return { status: 404, body: wrapResponse({ error: `flow not found: ${id}` }, graph, { canonicalIds: [] }) };
3124
- }
3125
- const contributing = new Set([id]);
3126
- if (flow.source) contributing.add(flow.source);
3127
- if (flow.sink) contributing.add(flow.sink);
3128
- for (const eid of (flow.edgeIds || [])) contributing.add(eid);
3129
- return { status: 200, body: wrapResponse(flow, graph, { canonicalIds: [...contributing] }) };
3130
- }
3131
-
3132
-
3133
- /***/ })
3134
-
3135
- };