@clear-capabilities/agentic-security-scanner 0.149.4 → 0.150.2

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