@clear-capabilities/agentic-security-scanner 0.134.0 → 0.136.9

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 (170) hide show
  1. package/CHANGELOG.md +432 -0
  2. package/bin/agentic-security-audit.js +2 -1
  3. package/bin/agentic-security-consistency.js +2 -1
  4. package/bin/agentic-security.js +448 -74
  5. package/dist/113.index.js +16 -7
  6. package/dist/117.index.js +3 -1
  7. package/dist/178.index.js +1 -1
  8. package/dist/207.index.js +5 -4
  9. package/dist/220.index.js +5 -3
  10. package/dist/238.index.js +4 -4
  11. package/dist/317.index.js +300 -0
  12. package/dist/384.index.js +1 -1
  13. package/dist/435.index.js +196 -21
  14. package/dist/444.index.js +20 -11
  15. package/dist/449.index.js +8 -1
  16. package/dist/513.index.js +7 -3
  17. package/dist/526.index.js +6 -6
  18. package/dist/637.index.js +1 -1
  19. package/dist/675.index.js +7 -5
  20. package/dist/839.index.js +4 -3
  21. package/dist/905.index.js +1173 -0
  22. package/dist/agentic-security.mjs +14 -14
  23. package/dist/agentic-security.mjs.sha256 +1 -1
  24. package/dist/compliance-frameworks/ccpa.json +32 -0
  25. package/dist/compliance-frameworks/eu-ai-act.json +51 -0
  26. package/dist/compliance-frameworks/gdpr.json +45 -0
  27. package/dist/compliance-frameworks/hipaa-security-rule.json +56 -0
  28. package/dist/compliance-frameworks/nist-ai-600-1.json +51 -0
  29. package/dist/compliance-frameworks/nist-csf-2.json +73 -0
  30. package/dist/compliance-frameworks/nist-privacy-1-1.json +846 -0
  31. package/dist/compliance-frameworks/owasp-asvs-5.json +79 -0
  32. package/dist/compliance-frameworks/owasp-llm-top-10.json +69 -0
  33. package/package.json +24 -12
  34. package/src/badge.js +2 -1
  35. package/src/dataflow/CLAUDE.md +10 -4
  36. package/src/dataflow/builtin-summaries.js +1 -1
  37. package/src/dataflow/cross-service-taint.js +2 -1
  38. package/src/dataflow/engine.js +324 -60
  39. package/src/dataflow/ifds-precise.js +6 -4
  40. package/src/dataflow/implicit-flow.js +68 -36
  41. package/src/dataflow/incremental.js +25 -8
  42. package/src/dataflow/index.js +2 -1
  43. package/src/dataflow/proven-clean.js +41 -0
  44. package/src/dataflow/sanitizer-gate.js +35 -9
  45. package/src/dataflow/sanitizer-proof.js +21 -3
  46. package/src/dataflow/stub-aware-filter.js +36 -13
  47. package/src/dataflow/summaries.js +21 -2
  48. package/src/discovery/CLAUDE.md +10 -0
  49. package/src/discovery/index.js +175 -3
  50. package/src/discovery/llm-invoke.js +90 -1
  51. package/src/discovery/memory.js +163 -0
  52. package/src/engine.js +247 -50
  53. package/src/integrations/tickets.js +7 -6
  54. package/src/ir/CLAUDE.md +4 -1
  55. package/src/ir/balanced-call.js +55 -0
  56. package/src/ir/ir-stats.js +1 -1
  57. package/src/ir/parser-cpp.js +1 -1
  58. package/src/ir/parser-cs.js +62 -9
  59. package/src/ir/parser-go.js +29 -11
  60. package/src/ir/parser-java.js +96 -19
  61. package/src/ir/parser-js.js +151 -20
  62. package/src/ir/parser-php.js +44 -9
  63. package/src/ir/parser-rb.js +37 -7
  64. package/src/ir/ssa.js +6 -1
  65. package/src/leaderboard.js +3 -2
  66. package/src/llm-validator/consistency.js +6 -2
  67. package/src/llm-validator/index.js +1 -2
  68. package/src/lsp/server.js +28 -2
  69. package/src/mcp/CLAUDE.md +9 -2
  70. package/src/mcp/audit.js +2 -1
  71. package/src/mcp/redact.js +26 -0
  72. package/src/mcp/tools.js +159 -17
  73. package/src/posture/CLAUDE.md +45 -8
  74. package/src/posture/accuracy-scorecard.js +67 -1
  75. package/src/posture/agents-memory.js +5 -3
  76. package/src/posture/aibom.js +12 -8
  77. package/src/posture/auditor-walkthrough.js +111 -10
  78. package/src/posture/auth-posture-import.js +5 -4
  79. package/src/posture/autopilot.js +8 -1
  80. package/src/posture/calibration-drift.js +11 -5
  81. package/src/posture/calibration.js +24 -2
  82. package/src/posture/compliance-frameworks/nist-privacy-1-1.json +846 -0
  83. package/src/posture/compliance-frameworks/owasp-asvs-5.json +1 -1
  84. package/src/posture/compliance-policy.js +40 -10
  85. package/src/posture/confidence.js +44 -10
  86. package/src/posture/corpus-enroll.js +9 -5
  87. package/src/posture/corpus-match.js +19 -0
  88. package/src/posture/csharp-analysis.js +62 -3
  89. package/src/posture/custom-rules.js +7 -5
  90. package/src/posture/cve-alert-daemon.js +6 -5
  91. package/src/posture/dep-add-guard.js +2 -1
  92. package/src/posture/deploy-platform.js +4 -1
  93. package/src/posture/deterministic.js +3 -2
  94. package/src/posture/drift.js +7 -1
  95. package/src/posture/epss.js +13 -1
  96. package/src/posture/evidence-bundle.js +276 -0
  97. package/src/posture/exploitability-probability.js +15 -2
  98. package/src/posture/falsification.js +23 -2
  99. package/src/posture/feature-flags.js +3 -2
  100. package/src/posture/findings-memory.js +3 -3
  101. package/src/posture/fix-history.js +5 -2
  102. package/src/posture/fix-metrics.js +5 -5
  103. package/src/posture/fix-plan.js +2 -1
  104. package/src/posture/fix-verify-loop.js +10 -1
  105. package/src/posture/grader-calibration.js +3 -4
  106. package/src/posture/iac-reachability.js +14 -8
  107. package/src/posture/integrity.js +25 -7
  108. package/src/posture/intent-context.js +2 -1
  109. package/src/posture/learning.js +4 -3
  110. package/src/posture/license-attributions.js +5 -7
  111. package/src/posture/license-graph.js +2 -1
  112. package/src/posture/license-policy.js +2 -1
  113. package/src/posture/model-rescan.js +69 -3
  114. package/src/posture/mttr.js +5 -0
  115. package/src/posture/network-policy-import.js +3 -2
  116. package/src/posture/poc-inprocess.js +27 -8
  117. package/src/posture/pqc-migration-plan.js +7 -5
  118. package/src/posture/pr-augment.js +8 -5
  119. package/src/posture/privacy-framework.js +262 -0
  120. package/src/posture/regression-test-gen.js +23 -8
  121. package/src/posture/reverse-blast-radius.js +5 -1
  122. package/src/posture/risk-dollars.js +20 -3
  123. package/src/posture/router.js +5 -4
  124. package/src/posture/ruleset-version.js +2 -2
  125. package/src/posture/runtime-correlation.js +2 -1
  126. package/src/posture/sbom-diff.js +12 -3
  127. package/src/posture/sca-policy.js +7 -4
  128. package/src/posture/scan-checkpoint.js +15 -0
  129. package/src/posture/secret-history.js +20 -11
  130. package/src/posture/security-trend.js +7 -1
  131. package/src/posture/stack-playbook.js +22 -1
  132. package/src/posture/state-dir.js +34 -0
  133. package/src/posture/telemetry-ingest.js +4 -3
  134. package/src/posture/threat-model-auto.js +4 -1
  135. package/src/posture/threat-model-grounding.js +13 -3
  136. package/src/posture/time-to-fix.js +3 -2
  137. package/src/posture/triage-memory.js +3 -2
  138. package/src/posture/validator-metrics.js +10 -3
  139. package/src/posture/verifier.js +32 -57
  140. package/src/posture/waf-ingest.js +6 -5
  141. package/src/posture/watch-mode.js +4 -3
  142. package/src/report/index.js +183 -14
  143. package/src/runScan.js +1 -1
  144. package/src/sast/_comment-strip.js +15 -4
  145. package/src/sast/_secret-entropy.js +1 -1
  146. package/src/sast/authz.js +6 -4
  147. package/src/sast/bench-shape/index.js +2 -7
  148. package/src/sast/claude-md-prompt-injection.js +14 -3
  149. package/src/sast/cloud-iam.js +60 -7
  150. package/src/sast/code-injection-multilang.js +29 -0
  151. package/src/sast/cpp-bench-extras.js +1 -1
  152. package/src/sast/csrf.js +7 -5
  153. package/src/sast/env-hygiene.js +5 -2
  154. package/src/sast/iac-terraform.js +25 -0
  155. package/src/sast/java-bench-extras.js +1 -1
  156. package/src/sast/java-constant-fold.js +5 -5
  157. package/src/sast/llm-owasp.js +4 -2
  158. package/src/sast/mcp-audit.js +7 -0
  159. package/src/sast/pipeline.js +8 -0
  160. package/src/sast/prompt-template.js +8 -6
  161. package/src/sast/prototype-pollution.js +6 -2
  162. package/src/sast/redos-nfa.js +6 -6
  163. package/src/sast/secret-concat.js +13 -2
  164. package/src/sast/ssrf-cloud-metadata.js +6 -3
  165. package/src/sast/xss-reflected-multilang.js +1 -1
  166. package/src/sast/xxe.js +1 -1
  167. package/src/sca/CLAUDE.md +3 -4
  168. package/src/sca/container.js +35 -3
  169. package/src/sca/dep-confusion.js +9 -1
  170. package/src/sca/sarif-ingest.js +0 -187
@@ -0,0 +1,1173 @@
1
+ export const id = 905;
2
+ export const ids = [905,499];
3
+ export const modules = {
4
+
5
+ /***/ 4286:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+
9
+ // EXPORTS
10
+ __webpack_require__.d(__webpack_exports__, {
11
+ runDiscovery: () => (/* binding */ runDiscovery)
12
+ });
13
+
14
+ // UNUSED EXPORTS: makeBudget, makeTaintProbe
15
+
16
+ // EXTERNAL MODULE: external "node:crypto"
17
+ var external_node_crypto_ = __webpack_require__(7598);
18
+ ;// CONCATENATED MODULE: ./src/discovery/partition.js
19
+ //
20
+ // Split the codebase into disjoint focus areas so parallel hunters cannot
21
+ // converge on the same code.
22
+ //
23
+ // WHY THE CALL GRAPH AND NOT DIRECTORIES: a directory split hands one
24
+ // subsystem to several hunters whenever a feature spans folders, and hands
25
+ // unrelated code to one hunter whenever a folder is a grab bag. Weakly-
26
+ // connected components over call edges group code that actually talks to
27
+ // itself, which is the unit a hunter can reason about end to end.
28
+ //
29
+ // FILES, NOT FUNCTIONS, ARE THE ATOM. A hunter reads whole files. If two
30
+ // components share a file they are merged, otherwise the same source lands in
31
+ // two hunters' context and the convergence this module exists to prevent
32
+ // comes straight back.
33
+
34
+
35
+ function focusAreaId(files) {
36
+ const canon = [...new Set(files || [])].sort().join('\n');
37
+ return external_node_crypto_.createHash('sha256').update(canon).digest('hex').slice(0, 12);
38
+ }
39
+
40
+ // Union-find over file paths.
41
+ function makeDSU() {
42
+ const parent = new Map();
43
+ const find = (x) => {
44
+ if (!parent.has(x)) parent.set(x, x);
45
+ let r = x;
46
+ while (parent.get(r) !== r) r = parent.get(r);
47
+ while (parent.get(x) !== r) { const n = parent.get(x); parent.set(x, r); x = n; }
48
+ return r;
49
+ };
50
+ const union = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb) parent.set(ra, rb); };
51
+ return { find, union };
52
+ }
53
+
54
+ function labelFor(files) {
55
+ if (files.length === 1) return files[0];
56
+ const parts = files[0].split('/');
57
+ for (let i = parts.length - 1; i > 0; i--) {
58
+ const prefix = parts.slice(0, i).join('/') + '/';
59
+ if (files.every(f => f.startsWith(prefix))) return prefix;
60
+ }
61
+ return files[0] + ` (+${files.length - 1})`;
62
+ }
63
+
64
+ function partitionCallGraph(callGraph, opts = {}) {
65
+ const fns = callGraph?.functions;
66
+ if (!fns || typeof fns.get !== 'function' || fns.size === 0) return [];
67
+ const maxAreas = Number.isInteger(opts.maxAreas) && opts.maxAreas > 0 ? opts.maxAreas : 8;
68
+
69
+ const dsu = makeDSU();
70
+ for (const fn of fns.values()) if (fn?.file) dsu.find(fn.file);
71
+ for (const e of callGraph.edges || []) {
72
+ const a = fns.get(e?.caller)?.file;
73
+ const b = fns.get(e?.callee)?.file;
74
+ if (a && b) dsu.union(a, b);
75
+ }
76
+
77
+ const filesByRoot = new Map();
78
+ for (const fn of fns.values()) {
79
+ if (!fn?.file) continue;
80
+ const root = dsu.find(fn.file);
81
+ if (!filesByRoot.has(root)) filesByRoot.set(root, new Set());
82
+ filesByRoot.get(root).add(fn.file);
83
+ }
84
+
85
+ const fnsByFile = new Map();
86
+ for (const fn of fns.values()) {
87
+ if (!fn?.file) continue;
88
+ if (!fnsByFile.has(fn.file)) fnsByFile.set(fn.file, []);
89
+ fnsByFile.get(fn.file).push(fn.qid);
90
+ }
91
+
92
+ const build = (files, label) => {
93
+ const sorted = [...files].sort();
94
+ const functions = sorted.flatMap(f => (fnsByFile.get(f) || [])).sort();
95
+ return { id: focusAreaId(sorted), label: label ?? labelFor(sorted), files: sorted, functions, size: functions.length };
96
+ };
97
+
98
+ let areas = [...filesByRoot.values()].map(s => build(s));
99
+ // Deterministic ranking: biggest first, ties broken by id so two runs on the
100
+ // same graph produce the same order.
101
+ areas.sort((a, b) => b.size - a.size || (a.id < b.id ? -1 : 1));
102
+
103
+ if (areas.length > maxAreas) {
104
+ const kept = areas.slice(0, maxAreas - 1);
105
+ const tail = areas.slice(maxAreas - 1);
106
+ kept.push(build(tail.flatMap(a => a.files), 'misc'));
107
+ areas = kept;
108
+ }
109
+ return areas;
110
+ }
111
+
112
+ // EXTERNAL MODULE: ./src/discovery/lenses.js
113
+ var discovery_lenses = __webpack_require__(3499);
114
+ ;// CONCATENATED MODULE: ./src/discovery/llm-invoke.js
115
+ //
116
+ // Shared LLM endpoint caller. Both the hunter and the refutation panel need
117
+ // the same default endpoint caller when tests don't inject a mock. Two copies
118
+ // of a network call is one copy too many — if one path gets fixed and the
119
+ // other does not, the bug stays buried in one direction.
120
+ //
121
+
122
+ const DEFAULT_TIMEOUT_MS = 60000;
123
+
124
+ async function defaultLlmInvoke(prompt, opts = {}) {
125
+ const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
126
+ // The URL is the operator's own configured endpoint, read from an environment
127
+ // variable they set. Reaching it is this module's entire purpose; no
128
+ // request-controlled input exists anywhere on this path, and an operator who
129
+ // can set this variable can already run code.
130
+ // `opts.endpoint` lets the consensus caller target one specific provider.
131
+ // Absent, it falls back to the single configured endpoint — so the ordinary
132
+ // single-model path is byte-identical to what it was before consensus existed.
133
+ const endpoint = opts.endpoint || process.env.AGENTIC_SECURITY_LLM_ENDPOINT;
134
+ const res = await fetch(endpoint, { // agentic-security-ignore: CWE-918
135
+ method: 'POST',
136
+ headers: { 'content-type': 'application/json' },
137
+ body: JSON.stringify({ prompt }),
138
+ signal: AbortSignal.timeout(timeoutMs),
139
+ });
140
+ if (!res.ok) throw new Error(`llm endpoint returned ${res.status}`);
141
+ const body = await res.json();
142
+ return typeof body === 'string' ? body : (body?.text ?? JSON.stringify(body));
143
+ }
144
+
145
+ // --- PRD Phase 3 / C2: multi-model consensus --------------------------------
146
+ //
147
+ // One model's opinion is one model's opinion. Asking several INDEPENDENT
148
+ // endpoints the same question and keeping only what a majority agree on
149
+ // collapses the idiosyncratic failures of any single one — a model that
150
+ // hallucinates a sink, or that is simply having a bad day on a prompt shape.
151
+ //
152
+ // WHY IT LIVES HERE AND NOWHERE ELSE. Every LLM call in the discovery layer
153
+ // already funnels through `resolveLlmInvoke`. Consensus is therefore a property
154
+ // of the seam, not of the hunter or the panel, and adding a provider cannot
155
+ // require touching either.
156
+ //
157
+ // WHAT CONSENSUS DOES AND DOES NOT MEAN. It reduces variance. It does NOT make
158
+ // the answer true — three models can agree and all be wrong, which is precisely
159
+ // why the deterministic confirmation gate still runs afterwards and still sets
160
+ // severity. Consensus is a noise filter in front of the real check, never a
161
+ // replacement for it.
162
+ //
163
+ // A provider that errors is EXCLUDED from the vote, not counted as dissent —
164
+ // the same rule `disprove.js` applies to its voters, for the same reason: an
165
+ // outage must never look like disagreement.
166
+ // Internal: read by resolveLlmInvoke below. Exporting it with no external
167
+ // caller is shipped dead code by the dead-module guard's definition.
168
+ const DEFAULT_CONSENSUS_ENV = 'AGENTIC_SECURITY_LLM_ENDPOINTS';
169
+
170
+ /** Split a comma-separated endpoint list into distinct URLs. */
171
+ function parseEndpoints(raw) {
172
+ return String(raw || '')
173
+ .split(',')
174
+ .map(s => s.trim())
175
+ .filter(Boolean)
176
+ .filter((v, i, a) => a.indexOf(v) === i); // duplicates would fake agreement
177
+ }
178
+
179
+ /**
180
+ * Combine N responses into one, keeping the most common answer.
181
+ *
182
+ * Ties are resolved towards the FIRST endpoint listed, deterministically, rather
183
+ * than arbitrarily — a caller ordering their endpoints by trust should get the
184
+ * behaviour that ordering implies, and a random tie-break would make the whole
185
+ * pipeline non-reproducible.
186
+ */
187
+ function consensusOf(responses) {
188
+ const usable = (responses || []).filter(r => typeof r === 'string' && r.trim());
189
+ if (usable.length === 0) return { value: null, agreement: 0, voters: 0 };
190
+ const counts = new Map();
191
+ for (const r of usable) counts.set(r, (counts.get(r) || 0) + 1);
192
+ let best = usable[0];
193
+ let bestCount = counts.get(best);
194
+ for (const r of usable) {
195
+ const c = counts.get(r);
196
+ if (c > bestCount) { best = r; bestCount = c; }
197
+ }
198
+ return { value: best, agreement: bestCount / usable.length, voters: usable.length };
199
+ }
200
+
201
+ /**
202
+ * An llmInvoke that queries several endpoints and returns the consensus answer.
203
+ * Returns null when no endpoint answered — the callers already treat a null or
204
+ * a throw as degradation, so an all-providers-down run degrades honestly.
205
+ */
206
+ function makeConsensusInvoke(endpoints, { timeoutMs } = {}) {
207
+ const list = parseEndpoints(endpoints);
208
+ if (list.length === 0) return null;
209
+ return async (prompt) => {
210
+ const answers = await Promise.all(list.map(async (url) => {
211
+ try { return await defaultLlmInvoke(prompt, { timeoutMs, endpoint: url }); }
212
+ catch { return null; } // excluded from the vote, never counted as dissent
213
+ }));
214
+ const { value } = consensusOf(answers);
215
+ if (value === null) throw new Error('no LLM endpoint answered');
216
+ return value;
217
+ };
218
+ }
219
+
220
+ function resolveLlmInvoke(opts = {}) {
221
+ // Precedence, most explicit first: an injected callback beats configuration,
222
+ // and a multi-endpoint list beats a single endpoint. A caller who supplied
223
+ // their own function must always get exactly that function.
224
+ if (opts.llmInvoke) return opts.llmInvoke;
225
+
226
+ const multi = opts.endpoints || process.env[DEFAULT_CONSENSUS_ENV];
227
+ if (multi) {
228
+ const consensus = makeConsensusInvoke(multi, { timeoutMs: opts.timeoutMs });
229
+ if (consensus) return consensus;
230
+ }
231
+
232
+ if (!process.env.AGENTIC_SECURITY_LLM_ENDPOINT) return null;
233
+ return (prompt) => defaultLlmInvoke(prompt, { timeoutMs: opts.timeoutMs });
234
+ }
235
+
236
+ ;// CONCATENATED MODULE: ./src/discovery/hunter.js
237
+ //
238
+ // One bounded hunter run = one focus area seen through one lens.
239
+ //
240
+ // A hunter PROPOSES. Nothing here is a finding: every candidate must survive
241
+ // `confirm.js` and `disprove.js` first. That separation is the whole design —
242
+ // the model is allowed to be imaginative precisely because something
243
+ // deterministic checks it afterwards.
244
+ //
245
+ // FAILURE IS ALWAYS DEGRADATION, NEVER AN EXCEPTION. A missing endpoint, a
246
+ // rate limit, or unparseable output yields `degraded:true` with a reason. A
247
+ // discovery pass that cannot run must leave the rest of the scan intact.
248
+
249
+
250
+
251
+
252
+ function appendEntry(transcript, entry) {
253
+ const prev = transcript.length ? transcript[transcript.length - 1].hash : null;
254
+ // Named `serialized`, not `body`: this is the canonical serialisation of a
255
+ // transcript entry being fed to a hash, and calling it `body` made the
256
+ // mass-assignment detector read it as a request payload. The name was simply
257
+ // wrong for what it holds, so this is a fix at the source rather than a
258
+ // suppression — and that detector's finding carries no line number, so a
259
+ // line-scoped ignore pragma could not have matched it anyway.
260
+ const serialized = JSON.stringify({ ...entry, prev });
261
+ const hash = external_node_crypto_.createHash('sha256').update(serialized).digest('hex');
262
+ transcript.push({ ...entry, prev, hash });
263
+ return transcript;
264
+ }
265
+
266
+ function extractJsonWithFlag(raw) {
267
+ if (typeof raw !== 'string') return { parsed: null, found: false };
268
+ const start = raw.indexOf('{');
269
+ const end = raw.lastIndexOf('}');
270
+ if (start < 0 || end <= start) return { parsed: null, found: false };
271
+ try { return { parsed: JSON.parse(raw.slice(start, end + 1)), found: true }; } catch { return { parsed: null, found: false }; }
272
+ }
273
+
274
+ function candidateId(focusAreaId, lensKey, file, line, title) {
275
+ return external_node_crypto_.createHash('sha256')
276
+ .update(`${focusAreaId}|${lensKey}|${file}|${line}|${title}`)
277
+ .digest('hex').slice(0, 12);
278
+ }
279
+
280
+ function candidatesFromParsed(parsed, focusArea, lens) {
281
+ const list = Array.isArray(parsed?.candidates) ? parsed.candidates : [];
282
+ const out = [];
283
+ for (const c of list) {
284
+ const file = typeof c?.file === 'string' ? c.file : null;
285
+ const line = Number.isInteger(c?.line) ? c.line : Number.parseInt(c?.line, 10);
286
+ if (!file || !Number.isInteger(line)) continue; // no location, no candidate
287
+ const title = typeof c?.title === 'string' && c.title ? c.title : `${lens.title} candidate`;
288
+ out.push({
289
+ id: candidateId(focusArea.id, lens.key, file, line, title),
290
+ focusAreaId: focusArea.id,
291
+ lens: lens.key,
292
+ title,
293
+ file,
294
+ line,
295
+ family: lens.family,
296
+ cwe: lens.cwe,
297
+ rationale: typeof c?.rationale === 'string' ? c.rationale : '',
298
+ entryPoint: typeof c?.entryPoint === 'string' ? c.entryPoint : '',
299
+ sink: typeof c?.sink === 'string' ? c.sink : '',
300
+ });
301
+ }
302
+ return out;
303
+ }
304
+
305
+ function parseCandidates(raw, focusArea, lens) {
306
+ const { parsed } = extractJsonWithFlag(raw);
307
+ return candidatesFromParsed(parsed, focusArea, lens);
308
+ }
309
+
310
+ async function runHunter(focusArea, lens, ctx = {}, opts = {}) {
311
+ const transcript = [];
312
+ const lensKey = lens?.key || 'unknown';
313
+ const base = { focusAreaId: focusArea.id, lens: lensKey, transcript };
314
+ const llmInvoke = resolveLlmInvoke(opts);
315
+
316
+ if (typeof llmInvoke !== 'function') {
317
+ const reason = 'no llmInvoke supplied and AGENTIC_SECURITY_LLM_ENDPOINT not set';
318
+ appendEntry(transcript, { phase: 'init', reason });
319
+ return { ...base, candidates: [], degraded: true, reason };
320
+ }
321
+
322
+ let prompt;
323
+ try {
324
+ prompt = (0,discovery_lenses/* buildHunterPrompt */.j)(focusArea, lens, ctx);
325
+ } catch (err) {
326
+ const reason = `failed to build hunter prompt: ${err?.message || String(err)}`;
327
+ appendEntry(transcript, { phase: 'prompt_error', reason });
328
+ return { ...base, candidates: [], degraded: true, reason };
329
+ }
330
+
331
+ appendEntry(transcript, { phase: 'prompt', promptChars: prompt.length, files: focusArea.files.length });
332
+
333
+ let raw;
334
+ try {
335
+ raw = await llmInvoke(prompt);
336
+ } catch (err) {
337
+ const reason = `hunter llm call failed: ${err?.message || String(err)}`;
338
+ appendEntry(transcript, { phase: 'error', reason });
339
+ return { ...base, candidates: [], degraded: true, reason };
340
+ }
341
+
342
+ const { parsed, found } = extractJsonWithFlag(raw);
343
+ if (!found) {
344
+ const reason = 'hunter output was not parseable JSON';
345
+ appendEntry(transcript, { phase: 'parse_error', reason });
346
+ return { ...base, candidates: [], degraded: true, reason };
347
+ }
348
+
349
+ const candidates = candidatesFromParsed(parsed, focusArea, lens);
350
+ appendEntry(transcript, { phase: 'result', candidateCount: candidates.length });
351
+ return { ...base, candidates, degraded: false, reason: null };
352
+ }
353
+
354
+ ;// CONCATENATED MODULE: ./src/discovery/confirm.js
355
+ //
356
+ // Route every model-proposed candidate back through the deterministic layer.
357
+ //
358
+ // WHY THIS EXISTS. A hunter's output is a hypothesis. The engine underneath it
359
+ // can already decide, for a given file and line, whether tainted data reaches a
360
+ // modelled sink there. Asking it turns "the model thinks so" into "the model
361
+ // thinks so AND the taint engine agrees", which is a materially stronger claim
362
+ // than either layer makes alone.
363
+ //
364
+ // THE ASYMMETRY IS DELIBERATE. Confirmation raises standing; the absence of
365
+ // confirmation NEVER lowers it below `unconfirmed` and is never recorded as a
366
+ // refutation. The taint engine models a subset of the program — an
367
+ // unconfirmed candidate may be a real bug in a construct the engine does not
368
+ // model, and calling that a false positive would launder a coverage gap into a
369
+ // verdict. Refutation is `disprove.js`'s job, and it must be argued, not
370
+ // inferred from silence.
371
+ const CONFIRMATION_TIERS = Object.freeze(['taint-confirmed', 'sink-adjacent', 'unconfirmed']);
372
+
373
+ function unconfirmed(probedBy, reason) {
374
+ return { tier: 'unconfirmed', evidence: null, probedBy, reason: reason || null };
375
+ }
376
+
377
+ async function confirmCandidate(candidate, opts = {}) {
378
+ const probe = typeof opts.taintProbe === 'function' ? opts.taintProbe : null;
379
+ if (!probe) return { ...candidate, confirmation: unconfirmed(null, 'no taintProbe supplied') };
380
+
381
+ let res;
382
+ try {
383
+ res = await probe(candidate);
384
+ } catch (err) {
385
+ return { ...candidate, confirmation: unconfirmed('taintProbe', `probe failed: ${err?.message || String(err)}`) };
386
+ }
387
+ if (!res) return { ...candidate, confirmation: unconfirmed('taintProbe', null) };
388
+ if (!CONFIRMATION_TIERS.includes(res.tier)) {
389
+ return { ...candidate, confirmation: unconfirmed('taintProbe', `unknown tier: ${res.tier}`) };
390
+ }
391
+ return {
392
+ ...candidate,
393
+ confirmation: { tier: res.tier, evidence: res.evidence ?? null, probedBy: 'taintProbe', reason: null },
394
+ };
395
+ }
396
+
397
+ async function confirmAll(candidates, opts = {}) {
398
+ const out = [];
399
+ for (const c of candidates || []) out.push(await confirmCandidate(c, opts));
400
+ return out;
401
+ }
402
+
403
+ ;// CONCATENATED MODULE: ./src/discovery/disprove.js
404
+ //
405
+ // Adversarial refutation. Each voter is told to REFUTE the candidate, not to
406
+ // assess it: a model asked "is this real?" agrees with the premise far more
407
+ // often than one asked "show me why this cannot happen", and the second
408
+ // question is the one that kills plausible-but-wrong findings.
409
+ //
410
+ // THREE ANGLES, NOT THREE COPIES. A candidate can fail in more than one way,
411
+ // and three identical voters mostly measure sampling noise. Reachability,
412
+ // attacker preconditions, and sanitization are the three ways these candidates
413
+ // actually die.
414
+ //
415
+ // SILENCE NEVER REFUTES. A voter that errors or returns unparseable output did
416
+ // not vote, and is excluded from the denominator rather than counted as
417
+ // agreement. If nobody votes the panel is `undecided` and the candidate
418
+ // SURVIVES — an outage must not quietly delete findings.
419
+
420
+
421
+ const DEFAULT_ANGLES = ['reachability', 'preconditions', 'sanitization'];
422
+ const REFUTE_ANGLES = Object.freeze([...DEFAULT_ANGLES]);
423
+
424
+ const ANGLE_BRIEF = {
425
+ reachability: 'Can attacker-controlled data actually reach this line at runtime? Name the caller chain or show there is none.',
426
+ preconditions: 'What must the attacker already have — a session, a role, a tenant, a race window? If the prerequisites exceed the impact, it is refuted.',
427
+ sanitization: 'Is the value validated, escaped, parameterised, or type-constrained anywhere on the path? A framework default counts.',
428
+ };
429
+
430
+ function buildRefutePrompt(candidate, angle) {
431
+ return [
432
+ `Your job is to REFUTE the security finding below. Assume it is wrong and look for the reason.`,
433
+ `Refute it on this angle only: ${angle}. ${ANGLE_BRIEF[angle] || ''}`,
434
+ ``,
435
+ `Finding: ${candidate.title}`,
436
+ `Location: ${candidate.file}:${candidate.line}`,
437
+ `Claimed reason: ${candidate.rationale || '(none given)'}`,
438
+ `Deterministic confirmation: ${candidate.confirmation?.tier || 'unknown'}`,
439
+ ``,
440
+ `If you cannot refute it on this angle, say so honestly.`,
441
+ `Return JSON: {"refuted":true|false,"reason":"..."}`,
442
+ ].join('\n');
443
+ }
444
+
445
+ function parseVote(raw) {
446
+ if (typeof raw !== 'string') return null;
447
+ const s = raw.indexOf('{'), e = raw.lastIndexOf('}');
448
+ if (s < 0 || e <= s) return null;
449
+ let p;
450
+ try { p = JSON.parse(raw.slice(s, e + 1)); } catch { return null; }
451
+ if (typeof p?.refuted !== 'boolean') return null;
452
+ return { refuted: p.refuted, reason: typeof p.reason === 'string' ? p.reason : '' };
453
+ }
454
+
455
+ async function disproveCandidate(candidate, opts = {}) {
456
+ const angles = Array.isArray(opts.angles) && opts.angles.length ? opts.angles : DEFAULT_ANGLES;
457
+ const llmInvoke = resolveLlmInvoke(opts);
458
+
459
+ const votes = [];
460
+ if (typeof llmInvoke === 'function') {
461
+ for (const angle of angles) {
462
+ let vote = null;
463
+ try { vote = parseVote(await llmInvoke(buildRefutePrompt(candidate, angle))); } catch { vote = null; }
464
+ if (vote) votes.push({ angle, ...vote });
465
+ }
466
+ }
467
+
468
+ const voterCount = votes.length;
469
+ const refuteCount = votes.filter(v => v.refuted).length;
470
+ const undecided = voterCount === 0;
471
+ const refuted = !undecided && refuteCount * 2 > voterCount;
472
+ return { ...candidate, refutation: { votes, voterCount, refuteCount, refuted, undecided } };
473
+ }
474
+
475
+ async function disprovePanel(candidates, opts = {}) {
476
+ const survivors = [], refuted = [];
477
+ for (const c of candidates || []) {
478
+ const judged = await disproveCandidate(c, opts);
479
+ (judged.refutation.refuted ? refuted : survivors).push(judged);
480
+ }
481
+ return { survivors, refuted };
482
+ }
483
+
484
+ // EXTERNAL MODULE: ./src/posture/stable-id.js
485
+ var stable_id = __webpack_require__(838);
486
+ ;// CONCATENATED MODULE: ./src/discovery/judge.js
487
+ //
488
+ // Turn surviving candidates into findings, then decide which are actually new.
489
+ //
490
+ // SEVERITY IS DRIVEN BY EVIDENCE, NOT BY THE MODEL'S ADJECTIVES. A hunter has
491
+ // no calibrated view of impact and will call everything critical. What we can
492
+ // defend is how well-evidenced the candidate is, so the confirmation tier sets
493
+ // the ceiling: taint-confirmed → high, sink-adjacent → medium, unconfirmed →
494
+ // low. A human or the existing triage path can raise it; the discovery layer
495
+ // never claims critical on its own.
496
+ //
497
+ // A PRIOR TRUE POSITIVE IS NOT A DUPLICATE. Triage feedback suppresses only
498
+ // `fp` verdicts. A `tp` verdict means the finding was real, and re-reporting it
499
+ // while it is still in the code is correct behaviour.
500
+ //
501
+ // STABLE IDS ARE LOCATION-FUZZY BY DESIGN, AND THAT MATTERS HERE. `stable-id.js`
502
+ // hashes ruleId, snippet, path shape, and BASENAME — deliberately not the line,
503
+ // so an id survives code moving down a file. The consequence for this layer:
504
+ // two different candidates of the same lens in the same file collide on one
505
+ // stableId. That is why file+line+family is the PRIMARY duplicate key and the
506
+ // stableId check is only a secondary net. It also means an `fp` verdict
507
+ // suppresses the whole (lens, file) pair rather than one line — the same
508
+ // breadth the rest of the engine already has, kept rather than silently
509
+ // diverged from. `ruleId` is set explicitly so ids partition by lens rather
510
+ // than falling back to the CWE.
511
+
512
+
513
+ const SEVERITY_BY_TIER = { 'taint-confirmed': 'high', 'sink-adjacent': 'medium', 'unconfirmed': 'low' };
514
+
515
+ // Guards against a malformed candidate producing a schema-invalid finding
516
+ // (root CLAUDE.md requires { id, severity, file, line, vuln, cwe, ... } on
517
+ // every finding). `hunter.js` already filters out candidates with no usable
518
+ // file/line before they reach here, so this should never trigger in the
519
+ // normal pipeline — but toFindingShape is exported and callable directly, and
520
+ // degrading with `null` (rather than throwing) matches this subsystem's
521
+ // degrade-don't-throw style everywhere else. Callers must skip a `null`.
522
+ function toFindingShape(candidate) {
523
+ const file = typeof candidate?.file === 'string' && candidate.file ? candidate.file : null;
524
+ const line = Number.isInteger(candidate?.line) ? candidate.line : null;
525
+ if (!file || line === null) return null;
526
+
527
+ const tier = candidate?.confirmation?.tier || 'unconfirmed';
528
+ const lensTitle = candidate?.lens ? `${candidate.lens} candidate` : 'discovery candidate';
529
+ const title = typeof candidate?.title === 'string' && candidate.title ? candidate.title : lensTitle;
530
+ const base = {
531
+ id: `discovery-${candidate.lens}-${candidate.id}`,
532
+ severity: SEVERITY_BY_TIER[tier] || 'low',
533
+ file,
534
+ line,
535
+ vuln: title,
536
+ cwe: candidate.cwe || 'CWE-710',
537
+ description: candidate.rationale
538
+ ? `${candidate.rationale} (entry point: ${candidate.entryPoint || 'unstated'}; sink: ${candidate.sink || 'unstated'})`
539
+ : `Proposed by the ${candidate.lens} lens; no rationale supplied.`,
540
+ remediation: `Review ${candidate.file}:${candidate.line}. Confirm whether ${candidate.entryPoint || 'attacker-controlled input'} can reach ${candidate.sink || 'this operation'}, and constrain it at the boundary if so.`,
541
+ parser: 'DISCOVERY',
542
+ family: candidate.family || 'other',
543
+ ruleId: `discovery:${candidate.lens}`,
544
+ // snippet discriminates findings so computeStableId has material to hash. An empty
545
+ // snippet collapses distinct findings of the same lens in the same file onto one id.
546
+ snippet: candidate.sink || candidate.entryPoint || candidate.title || '',
547
+ };
548
+ return {
549
+ ...base,
550
+ stableId: (0,stable_id/* computeStableId */._)(base),
551
+ discovery: {
552
+ lens: candidate.lens,
553
+ focusAreaId: candidate.focusAreaId,
554
+ confirmation: candidate.confirmation || null,
555
+ refutation: candidate.refutation || null,
556
+ },
557
+ };
558
+ }
559
+
560
+ function judgeCandidates(candidates, priorScan, triageFeedback) {
561
+ const prior = Array.isArray(priorScan?.findings) ? priorScan.findings : [];
562
+ const priorByLoc = new Map();
563
+ const priorIds = new Set();
564
+ for (const p of prior) {
565
+ if (p?.stableId) priorIds.add(p.stableId);
566
+ priorByLoc.set(`${p?.file}|${p?.line}|${p?.family}`, p?.stableId || null);
567
+ }
568
+ const feedback = triageFeedback && typeof triageFeedback === 'object' ? triageFeedback : {};
569
+
570
+ const fresh = [], duplicates = [], suppressed = [];
571
+ for (const c of candidates || []) {
572
+ const f = toFindingShape(c);
573
+ if (!f) continue; // malformed candidate (no usable file/line) — degrade by skipping, never throw
574
+ if (feedback[f.stableId] === 'fp') { suppressed.push({ ...f, suppressedBy: 'triage-fp' }); continue; }
575
+ const locKey = `${f.file}|${f.line}|${f.family}`;
576
+ // Location key is PRIMARY: same file, line, and family match existing findings.
577
+ if (priorByLoc.has(locKey)) { duplicates.push({ ...f, duplicateOf: priorByLoc.get(locKey) }); continue; }
578
+ // stableId is SECONDARY: same lens, file, and sink at a moved line is likely the same bug.
579
+ if (priorIds.has(f.stableId)) { duplicates.push({ ...f, duplicateOf: f.stableId }); continue; }
580
+ fresh.push(f);
581
+ }
582
+ return { fresh, duplicates, suppressed };
583
+ }
584
+
585
+ // EXTERNAL MODULE: external "node:fs"
586
+ var external_node_fs_ = __webpack_require__(3024);
587
+ // EXTERNAL MODULE: external "node:path"
588
+ var external_node_path_ = __webpack_require__(6760);
589
+ // EXTERNAL MODULE: ./src/posture/state-dir.js
590
+ var state_dir = __webpack_require__(1174);
591
+ ;// CONCATENATED MODULE: ./src/discovery/memory.js
592
+ // Cross-run discovery memory — PRD Phase 3 / C4.
593
+ //
594
+ // WHAT WAS MISSING
595
+ // ----------------
596
+ // `judge.js` dedupes a hunt against `last-scan.json` and the triage ledger, so
597
+ // it knows what the RULE ENGINE found and what a human dismissed. It has never
598
+ // known what a PREVIOUS HUNT found. Two consequences, both bad:
599
+ //
600
+ // 1. Every run re-proposes, re-confirms and re-refutes the same candidates.
601
+ // That is three LLM calls per candidate per run, spent to rediscover
602
+ // something already judged — the exact waste the Phase 0 budget exists to
603
+ // bound, being incurred deliberately.
604
+ // 2. A second run cannot be *additive*. Without a record of what was already
605
+ // examined, "hunt again" means "hunt the same thing again" rather than
606
+ // "hunt what we missed".
607
+ //
608
+ // This is that record. It turns a sequence of independent runs into a campaign.
609
+ //
610
+ // WHAT IS AND IS NOT REMEMBERED
611
+ // -----------------------------
612
+ // Remembered: every candidate ever JUDGED, with the verdict and the run that
613
+ // produced it. Also every focus area ever hunted, so coverage can become a plan
614
+ // instead of a report.
615
+ //
616
+ // NOT remembered: refuted candidates as if they were settled forever. A
617
+ // refutation is a majority opinion from three prompts on one day, not a proof.
618
+ // It suppresses re-reporting, and `--forget-refuted` exists precisely because a
619
+ // verdict made by a weaker model, or before a sanitiser was removed, must be
620
+ // re-openable. A memory you cannot clear is a memory that eventually lies.
621
+ //
622
+ // THE PRECEDENT THIS FOLLOWS
623
+ // --------------------------
624
+ // `judge.js` deliberately suppresses only `fp` triage verdicts and re-reports
625
+ // `tp` ones, because a prior true positive that is still in the code is still a
626
+ // bug. The same asymmetry holds here: a candidate previously judged FRESH is
627
+ // re-reported (it was never fixed), while one previously REFUTED is held back
628
+ // until something changes.
629
+
630
+
631
+
632
+
633
+
634
+ const MEMORY_SCHEMA = 'agentic-security/discovery-memory@1';
635
+ const MEMORY_FILE = external_node_path_.join('.agentic-security', 'discovery-memory.json');
636
+
637
+ function emptyMemory() {
638
+ return { schema: MEMORY_SCHEMA, runs: 0, candidates: {}, areas: {} };
639
+ }
640
+
641
+ /** A stable identity for a candidate across runs. */
642
+ function memoryKey(candidate) {
643
+ // Location + family, matching judge.js's PRIMARY duplicate key. Deliberately
644
+ // NOT stableId: that is location-fuzzy by design and collides across distinct
645
+ // findings in one file, which is tolerable for a single scan's dedupe and
646
+ // corrosive when it accumulates across every run ever made.
647
+ const file = candidate?.file ?? '?';
648
+ const line = candidate?.line ?? '?';
649
+ const family = candidate?.family ?? candidate?.lens ?? '?';
650
+ return `${file}:${line}:${family}`;
651
+ }
652
+
653
+ /** Read the memory. Anything unreadable or unrecognised yields an empty one. */
654
+ function loadMemory(scanRoot) {
655
+ try {
656
+ const doc = JSON.parse(external_node_fs_.readFileSync(external_node_path_.join(scanRoot, MEMORY_FILE), 'utf8'));
657
+ if (doc?.schema !== MEMORY_SCHEMA) return emptyMemory();
658
+ return { ...emptyMemory(), ...doc };
659
+ } catch {
660
+ // A corrupt memory must degrade to "remember nothing", never to a crash and
661
+ // never to a partially-trusted record. Re-hunting is cheap next to acting on
662
+ // a half-read ledger.
663
+ return emptyMemory();
664
+ }
665
+ }
666
+
667
+ /** Persist. Failure is non-fatal — the run still produced its report. */
668
+ function saveMemory(scanRoot, memory) {
669
+ try {
670
+ const p = external_node_path_.join(scanRoot, MEMORY_FILE);
671
+ if (!(0,state_dir.stateWritesEnabled)()) return;
672
+ external_node_fs_.mkdirSync(external_node_path_.dirname(p), { recursive: true });
673
+ external_node_fs_.writeFileSync(p, JSON.stringify(memory, null, 2) + '\n');
674
+ return true;
675
+ } catch {
676
+ return false;
677
+ }
678
+ }
679
+
680
+ /**
681
+ * Should this candidate be held back because a previous run already judged it?
682
+ *
683
+ * Only a REFUTED verdict suppresses. Everything else — fresh, duplicate,
684
+ * suppressed-by-triage — is re-evaluated, because those states are about the
685
+ * code and the code may have changed.
686
+ */
687
+ function previouslyRefuted(memory, candidate) {
688
+ const rec = memory?.candidates?.[memoryKey(candidate)];
689
+ return Boolean(rec && rec.verdict === 'refuted');
690
+ }
691
+
692
+ /** Fold this run's outcome into the memory. Returns a NEW memory object. */
693
+ function rememberRun(memory, { fresh = [], refutedCandidates = [], areas = [], at }) {
694
+ const next = {
695
+ ...emptyMemory(),
696
+ ...memory,
697
+ candidates: { ...(memory?.candidates || {}) },
698
+ areas: { ...(memory?.areas || {}) },
699
+ };
700
+ next.runs = (memory?.runs || 0) + 1;
701
+ const stamp = at || new Date().toISOString();
702
+
703
+ for (const f of fresh) {
704
+ next.candidates[memoryKey(f)] = { verdict: 'fresh', run: next.runs, at: stamp };
705
+ }
706
+ for (const c of refutedCandidates) {
707
+ next.candidates[memoryKey(c)] = { verdict: 'refuted', run: next.runs, at: stamp };
708
+ }
709
+ for (const a of areas) {
710
+ const prev = next.areas[a.id] || { hunts: 0 };
711
+ next.areas[a.id] = {
712
+ label: a.label,
713
+ hunts: prev.hunts + (a.hunted ? 1 : 0),
714
+ lastRun: a.hunted ? next.runs : (prev.lastRun ?? null),
715
+ files: a.files ?? prev.files ?? null,
716
+ };
717
+ }
718
+ return next;
719
+ }
720
+
721
+ /**
722
+ * Turn the memory into a PLAN: which areas have never been successfully hunted.
723
+ *
724
+ * This is the half that makes a second run additive rather than repetitive. A
725
+ * coverage report says what happened; this says what to do next.
726
+ */
727
+ function nextWavePlan(memory, areas) {
728
+ const unhunted = [];
729
+ const stale = [];
730
+ for (const a of areas || []) {
731
+ const rec = memory?.areas?.[a.id];
732
+ if (!rec || rec.hunts === 0) unhunted.push(a.label || a.id);
733
+ else if (rec.lastRun !== memory.runs) stale.push(a.label || a.id);
734
+ }
735
+ return {
736
+ unhunted,
737
+ stale,
738
+ // Stated as a sentence because this lands in a report a human reads, and
739
+ // "3 areas" without saying which ones is not actionable.
740
+ summary: unhunted.length
741
+ ? `${unhunted.length} focus area(s) have NEVER been successfully hunted: ${unhunted.slice(0, 5).join(', ')}` +
742
+ (unhunted.length > 5 ? `, +${unhunted.length - 5} more` : '')
743
+ : 'every focus area has been hunted at least once',
744
+ };
745
+ }
746
+
747
+ /** Drop refuted verdicts so they can be re-examined. */
748
+ function forgetRefuted(memory) {
749
+ const candidates = {};
750
+ for (const [k, v] of Object.entries(memory?.candidates || {})) {
751
+ if (v?.verdict !== 'refuted') candidates[k] = v;
752
+ }
753
+ return { ...emptyMemory(), ...memory, candidates };
754
+ }
755
+
756
+ ;// CONCATENATED MODULE: ./src/discovery/index.js
757
+ //
758
+ // Compose the discovery pipeline:
759
+ //
760
+ // partition → (area × lens) hunters → confirm → disprove → judge
761
+ //
762
+ // COVERAGE IS PART OF THE OUTPUT. Every report states how many areas were
763
+ // planned versus hunted and how many runs degraded, with reasons. A discovery
764
+ // pass that half failed and reports "no findings" is indistinguishable from a
765
+ // clean codebase unless it says so.
766
+
767
+
768
+
769
+
770
+
771
+
772
+
773
+
774
+ // Bridge a candidate to the deterministic layer. A taint finding at or within
775
+ // two lines of the candidate corroborates it; a modelled sink on the line
776
+ // without a full path is weaker corroboration ("sink-adjacent").
777
+ //
778
+ // NOTE: `runDeepAnalysis(perFileIR, callGraph, opts)` returns a BARE ARRAY of
779
+ // findings (see scanner/src/dataflow/index.js), not an object with a
780
+ // `.findings` property. Treat anything else defensively.
781
+ function makeTaintProbe(perFileIR, callGraph) {
782
+ let cache = null;
783
+ return async (candidate) => {
784
+ if (!callGraph || !perFileIR) return null;
785
+ try {
786
+ if (!cache) cache = runDeepAnalysisSafe(perFileIR, callGraph);
787
+ const deep = await cache;
788
+ if (!Array.isArray(deep)) return null;
789
+ const hits = deep.filter(f => f.file === candidate.file);
790
+ const exact = hits.find(f => Math.abs((f.line ?? -1) - candidate.line) <= 2);
791
+ if (exact) {
792
+ return { tier: 'taint-confirmed', evidence: { matchedFinding: exact.id ?? null, line: exact.line, vuln: exact.vuln ?? null } };
793
+ }
794
+ return hits.length ? { tier: 'sink-adjacent', evidence: { sameFileFindings: hits.length } } : null;
795
+ } catch {
796
+ return null;
797
+ }
798
+ };
799
+ }
800
+
801
+ async function runDeepAnalysisSafe(perFileIR, callGraph) {
802
+ try {
803
+ const { runDeepAnalysis } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 6732));
804
+ return runDeepAnalysis(perFileIR, callGraph, {});
805
+ } catch {
806
+ return null;
807
+ }
808
+ }
809
+
810
+ // ctx = { perFileIR, callGraph, fileContents, priorScan, triageFeedback }
811
+ // where { perFileIR, callGraph } come from buildProjectIR(fileContents),
812
+ // which returns { perFile, callGraph } — callers must pass perFile as
813
+ // perFileIR (see scanner/src/ir/index.js).
814
+ /**
815
+ * PRD Phase 0 / C3 — the run budget.
816
+ *
817
+ * This pipeline is multiplicative and was, until now, unbounded. Eight focus
818
+ * areas × seven lenses is 56 hunter calls before a single candidate exists, and
819
+ * every surviving candidate then costs three more calls in the refutation
820
+ * panel. Nothing capped any of it, so the cost of a run was a function of how
821
+ * large the repository happened to be — which is not a property you want to
822
+ * discover from an invoice.
823
+ *
824
+ * ENFORCED AT THE ONE SEAM EVERY CALL PASSES THROUGH. Rather than thread checks
825
+ * through the hunter and the panel, the budget wraps `llmInvoke` itself. When
826
+ * it is spent the wrapper throws, and both callers already treat a throwing
827
+ * llmInvoke as ordinary degradation with a stated reason. So exhaustion arrives
828
+ * through the same path as a rate limit or a dead endpoint, and lands in
829
+ * `coverage.reasons` like any other coverage gap. No new failure mode.
830
+ *
831
+ * CALLS AND WALL CLOCK, NOT TOKENS. `llmInvoke` is an injected callback that
832
+ * returns a string; it carries no usage metadata, so counting tokens here would
833
+ * mean inventing a number. Calls are exactly countable and wall clock is
834
+ * exactly observable. A caller who knows their per-call cost can pass
835
+ * `costPerCallUsd` and get a `maxCostUsd` ceiling expressed in calls, which is
836
+ * honest about being an estimate derived from their figure rather than ours.
837
+ */
838
+ // Internal, not exported: the dead-module guard treats an export with no
839
+ // external call site as shipped dead code, and these are read only by
840
+ // makeBudget below. A consumer sets a ceiling by passing opts, not by importing
841
+ // a constant.
842
+ const DEFAULT_MAX_LLM_CALLS = 200;
843
+ const DEFAULT_MAX_WALL_MS = 15 * 60 * 1000;
844
+ const DEFAULT_MAX_CANDIDATES = 50;
845
+
846
+ function makeBudget(opts = {}, now = Date.now) {
847
+ const startedAt = now();
848
+ let maxCalls = Number.isInteger(opts.maxLlmCalls) && opts.maxLlmCalls >= 0
849
+ ? opts.maxLlmCalls : DEFAULT_MAX_LLM_CALLS;
850
+ // A dollar ceiling is only meaningful with a caller-supplied per-call cost.
851
+ // Converting it to a call count keeps one enforcement mechanism rather than
852
+ // two that can disagree.
853
+ if (Number.isFinite(opts.maxCostUsd) && Number.isFinite(opts.costPerCallUsd) && opts.costPerCallUsd > 0) {
854
+ maxCalls = Math.min(maxCalls, Math.floor(opts.maxCostUsd / opts.costPerCallUsd));
855
+ }
856
+ const maxWallMs = Number.isInteger(opts.maxWallMs) && opts.maxWallMs > 0
857
+ ? opts.maxWallMs : DEFAULT_MAX_WALL_MS;
858
+
859
+ let calls = 0;
860
+ let exhaustedReason = null;
861
+
862
+ const check = () => {
863
+ if (exhaustedReason) return exhaustedReason;
864
+ if (calls >= maxCalls) return (exhaustedReason = `LLM call budget spent (${calls}/${maxCalls} calls)`);
865
+ if (now() - startedAt >= maxWallMs) {
866
+ return (exhaustedReason = `wall-clock budget spent (${Math.round(maxWallMs / 1000)}s)`);
867
+ }
868
+ return null;
869
+ };
870
+
871
+ return {
872
+ get calls() { return calls; },
873
+ get maxCalls() { return maxCalls; },
874
+ get exhaustedReason() { return exhaustedReason; },
875
+ spent: () => check() !== null,
876
+ /** Wrap an llmInvoke so every call is counted and the ceiling is enforced. */
877
+ wrap(llmInvoke) {
878
+ if (typeof llmInvoke !== 'function') return llmInvoke;
879
+ return async (prompt) => {
880
+ const stop = check();
881
+ if (stop) throw new Error(`discovery budget exhausted: ${stop}`);
882
+ calls += 1;
883
+ return llmInvoke(prompt);
884
+ };
885
+ },
886
+ };
887
+ }
888
+
889
+ async function runDiscovery(ctx = {}, opts = {}) {
890
+ const areas = partitionCallGraph(ctx.callGraph, { maxAreas: opts.maxAreas ?? 8 });
891
+
892
+ const reasons = [];
893
+ const budget = makeBudget(opts);
894
+ // PRD C4 — what previous runs already judged. scanRoot absent => no memory,
895
+ // which is the correct default for a library call with nowhere to persist.
896
+ const memory = opts.scanRoot ? loadMemory(opts.scanRoot) : null;
897
+ // Every LLM call in this pipeline goes through this one wrapped callback.
898
+ const llmInvoke = budget.wrap(opts.llmInvoke);
899
+
900
+ // An explicit array (including an empty one) is honoured exactly — a caller
901
+ // narrowing a run to no lenses must get no lenses, not a silent fallback to
902
+ // all seven. Only an absent/non-array value falls back to the full set.
903
+ const lensKeys = Array.isArray(opts.lenses) ? opts.lenses : discovery_lenses.LENSES.map(l => l.key);
904
+
905
+ const lenses = [];
906
+ for (const key of lensKeys) {
907
+ const lens = (0,discovery_lenses/* lensByKey */.H)(key);
908
+ // An unknown key must degrade visibly, not vanish via a silent filter.
909
+ if (lens) lenses.push(lens);
910
+ else reasons.push(`unresolved lens key: "${key}"`);
911
+ }
912
+ if (lenses.length === 0) {
913
+ reasons.push('no lenses resolved for this run (empty or fully-unresolved lens selection); nothing was hunted');
914
+ }
915
+
916
+ const runs = [];
917
+ let candidates = [];
918
+ // areasHunted: areas where AT LEAST ONE lens run completed without degrading.
919
+ const hunted = new Set();
920
+ // areasFullyHunted: areas where EVERY lens run completed without degrading.
921
+ // Distinct from areasHunted so a partially-degraded area (e.g. 6 of 7 lenses
922
+ // failed) cannot be read as fully covered from a single number.
923
+ const fullyHunted = new Set();
924
+
925
+ for (const area of areas) {
926
+ let areaDegradedCount = 0;
927
+ for (const lens of lenses) {
928
+ const run = await runHunter(area, lens, { fileContents: ctx.fileContents || {} }, { llmInvoke });
929
+ runs.push({ focusAreaId: run.focusAreaId, lens: run.lens, degraded: run.degraded, reason: run.reason, candidateCount: run.candidates.length });
930
+ if (run.degraded && run.reason) reasons.push(`${area.label} × ${lens.key}: ${run.reason}`);
931
+ if (run.degraded) areaDegradedCount += 1;
932
+ else hunted.add(area.id);
933
+ candidates = candidates.concat(run.candidates);
934
+ }
935
+ if (lenses.length > 0 && areaDegradedCount === 0) fullyHunted.add(area.id);
936
+ }
937
+
938
+ // PRD Phase 0 / C3.2 — the candidate cap.
939
+ //
940
+ // Every candidate that reaches the panel costs three more LLM calls, so an
941
+ // unusually productive hunt multiplies straight into spend. Cap it, and
942
+ // REPORT the cap rather than applying it silently: a run that quietly
943
+ // examined the first N candidates and said nothing would look identical to a
944
+ // run that found only N. Same precedent as prove-findings.js's `capped`.
945
+ // PRD C4 — drop what a previous run already refuted, BEFORE spending the
946
+ // panel's three calls per candidate on it again. Only refutals suppress: a
947
+ // candidate previously judged fresh is re-reported, because it was never
948
+ // fixed, which is the same asymmetry judge.js applies to tp/fp triage.
949
+ let rememberedRefutals = 0;
950
+ if (memory) {
951
+ const before = candidates.length;
952
+ candidates = candidates.filter(c => !previouslyRefuted(memory, c));
953
+ rememberedRefutals = before - candidates.length;
954
+ if (rememberedRefutals > 0) {
955
+ reasons.push(`${rememberedRefutals} candidate(s) were refuted by an earlier run and not re-examined ` +
956
+ '(clear with --forget-refuted if a model, ruleset or the code has changed since)');
957
+ }
958
+ }
959
+
960
+ const maxCandidates = Number.isInteger(opts.maxCandidates) && opts.maxCandidates >= 0
961
+ ? opts.maxCandidates : DEFAULT_MAX_CANDIDATES;
962
+ let candidatesCapped = 0;
963
+ if (candidates.length > maxCandidates) {
964
+ candidatesCapped = candidates.length - maxCandidates;
965
+ // Deterministic: candidates arrive in a stable (area, lens) order, so the
966
+ // cap keeps the same prefix on every run over the same inputs.
967
+ candidates = candidates.slice(0, maxCandidates);
968
+ reasons.push(`candidate cap: ${candidatesCapped} candidate(s) were NOT confirmed or refuted ` +
969
+ `(cap ${maxCandidates}); they are neither findings nor cleared — they were not examined`);
970
+ }
971
+
972
+ // PRD D3 — the hybrid-loop uplift measurement.
973
+ //
974
+ // `confirm: false` runs the pipeline with the deterministic gate switched OFF,
975
+ // so every candidate reaches the panel as `unconfirmed`. Running a population
976
+ // both ways and diffing the result isolates what the taint engine contributes
977
+ // on top of the model — a number no surveyed competitor can compute, because
978
+ // none of them has a deterministic layer to switch off.
979
+ //
980
+ // It exists ONLY to be measured against. It is not a performance switch, and
981
+ // a run with it disabled is strictly weaker: severity collapses to `low` for
982
+ // everything, since the confirmation tier is what sets it.
983
+ const confirmationEnabled = opts.confirm !== false;
984
+ const taintProbe = confirmationEnabled ? makeTaintProbe(ctx.perFileIR, ctx.callGraph) : null;
985
+ if (!confirmationEnabled) {
986
+ reasons.push('deterministic confirmation was DISABLED for this run (uplift measurement); ' +
987
+ 'every candidate is reported unconfirmed and severity is not evidence-derived');
988
+ }
989
+ const confirmed = await confirmAll(candidates, { taintProbe });
990
+ const { survivors, refuted } = await disprovePanel(confirmed, { llmInvoke });
991
+ const { fresh, duplicates, suppressed } = judgeCandidates(survivors, ctx.priorScan, ctx.triageFeedback);
992
+
993
+ // A spent budget is a coverage gap, stated once at the top level rather than
994
+ // left to be inferred from N identical per-run degradation reasons.
995
+ if (budget.exhaustedReason) {
996
+ reasons.push(`RUN INCOMPLETE — ${budget.exhaustedReason}. Work remained when the budget ran ` +
997
+ 'out, so absence of a finding below is not evidence of absence. Raise maxLlmCalls / ' +
998
+ 'maxWallMs, or narrow the scope with --root or --lens, and re-run.');
999
+ }
1000
+
1001
+ // Coverage must not stop at the hunter stage. `confirm.js` correctly never
1002
+ // lowers a candidate below `unconfirmed`, and `disprove.js` correctly lets
1003
+ // a candidate survive when no voter votes — each rule is right on its own,
1004
+ // but composed, a run where BOTH later stages died silently would still
1005
+ // report clean hunter coverage while 100% of raw, uncorroborated model
1006
+ // output landed in `fresh`. These counters and reasons make that visible.
1007
+ const confirmedByTier = { 'taint-confirmed': 0, 'sink-adjacent': 0, 'unconfirmed': 0 };
1008
+ for (const c of confirmed) {
1009
+ const tier = c?.confirmation?.tier;
1010
+ if (tier && Object.prototype.hasOwnProperty.call(confirmedByTier, tier)) confirmedByTier[tier] += 1;
1011
+ }
1012
+ if (confirmed.length > 0 && confirmedByTier['taint-confirmed'] === 0 && confirmedByTier['sink-adjacent'] === 0) {
1013
+ reasons.push(`confirmation stage corroborated nothing for ${confirmed.length} candidate(s) — all remain "unconfirmed"; the deterministic gate may not have run, and the findings below are uncorroborated, not vetted`);
1014
+ }
1015
+
1016
+ const panelled = [...survivors, ...refuted];
1017
+ const panelsRun = panelled.length;
1018
+ const undecidedPanels = panelled.filter(c => c?.refutation?.undecided === true).length;
1019
+ if (panelsRun > 0 && undecidedPanels === panelsRun) {
1020
+ reasons.push(`refutation panel returned no votes for any of ${panelsRun} candidate(s) — every finding below survived unrefuted, not because it withstood scrutiny`);
1021
+ }
1022
+
1023
+ // PRD C4 — fold this run into the memory so the next one can be additive
1024
+ // rather than a repeat. Persistence failure is non-fatal: the report is still
1025
+ // valid, it just will not inform the next run.
1026
+ if (memory && opts.scanRoot) {
1027
+ saveMemory(opts.scanRoot, rememberRun(memory, {
1028
+ fresh, refutedCandidates: refuted,
1029
+ areas: areas.map(a => ({ id: a.id, label: a.label, files: a.files.length, hunted: hunted.has(a.id) })),
1030
+ }));
1031
+ }
1032
+
1033
+ return {
1034
+ schema: 'agentic-security/discovery@1',
1035
+ focusAreas: areas.map(a => ({ id: a.id, label: a.label, files: a.files.length, size: a.size })),
1036
+ runs,
1037
+ fresh,
1038
+ duplicates,
1039
+ suppressed,
1040
+ // `refutedCandidates` holds RAW candidates straight from `disprovePanel`,
1041
+ // NOT findings — no `vuln`, `severity`, `parser`, or `stableId`. It is
1042
+ // deliberately not run through `toFindingShape`: a refuted candidate is
1043
+ // deliberately not promoted to a finding, and giving it finding shape
1044
+ // would misrepresent it as one. Unlike `fresh`/`duplicates`/`suppressed`,
1045
+ // do not iterate this array as if it were finding-shaped.
1046
+ refutedCandidates: refuted,
1047
+ coverage: {
1048
+ areasPlanned: areas.length,
1049
+ // At least one lens run completed for the area. Does NOT mean every
1050
+ // lens succeeded there — see areasFullyHunted for that stronger claim.
1051
+ areasHunted: hunted.size,
1052
+ // Every lens run for the area completed without degrading.
1053
+ areasFullyHunted: fullyHunted.size,
1054
+ lensesPerArea: lenses.length,
1055
+ degradedRuns: runs.filter(r => r.degraded).length,
1056
+ // Per-tier count of every candidate that went through confirm.js.
1057
+ confirmedByTier,
1058
+ // How many candidates went through the refutation panel, and how many
1059
+ // of those came back with no votes at all (undecided, not refuted).
1060
+ panelsRun,
1061
+ undecidedPanels,
1062
+ // PRD Phase 0 / C3 — what the run cost and whether the budget stopped it.
1063
+ // `budgetExhausted` true means the report is INCOMPLETE by construction:
1064
+ // work remained and was not done. Reading it as a clean result is the
1065
+ // exact misreading the coverage block exists to prevent.
1066
+ // PRD C4 — what history contributed, and what to hunt next. A coverage
1067
+ // report says what happened; `nextWave` says what to do about it.
1068
+ rememberedRefutals,
1069
+ priorRuns: memory ? memory.runs : null,
1070
+ nextWave: memory ? nextWavePlan(memory, areas.map(a => ({ id: a.id, label: a.label }))) : null,
1071
+ llmCalls: budget.calls,
1072
+ maxLlmCalls: budget.maxCalls,
1073
+ // PRD N4 — the standing cost metric. C3 bounded the worst case and C4
1074
+ // moved the typical case by 4x, so cost is a property that drifts across
1075
+ // several workstreams rather than one that a phase finishes. A number
1076
+ // that only appears when somebody goes looking regresses silently, so it
1077
+ // is reported every run and carries its denominator like every other rate
1078
+ // in this engine. `null` when nothing was found — dividing by zero
1079
+ // findings would print Infinity and read as a catastrophe rather than as
1080
+ // "there is nothing to divide".
1081
+ callsPerFinding: fresh.length > 0 ? Number((budget.calls / fresh.length).toFixed(1)) : null,
1082
+ budgetExhausted: Boolean(budget.exhaustedReason),
1083
+ candidatesCapped,
1084
+ reasons,
1085
+ },
1086
+ };
1087
+ }
1088
+
1089
+
1090
+ /***/ }),
1091
+
1092
+ /***/ 3499:
1093
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1094
+
1095
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1096
+ /* harmony export */ H: () => (/* binding */ lensByKey),
1097
+ /* harmony export */ LENSES: () => (/* binding */ LENSES),
1098
+ /* harmony export */ j: () => (/* binding */ buildHunterPrompt)
1099
+ /* harmony export */ });
1100
+ //
1101
+ // The seven hunting lenses. Each hunter run is one (focus area × lens) pair.
1102
+ //
1103
+ // WHY DIVERSE LENSES RATHER THAN N IDENTICAL HUNTERS: redundancy raises
1104
+ // confidence in what was already found and adds nothing to coverage. A lens
1105
+ // that is told to look only at authorization asks different questions of the
1106
+ // same code than one told to look at crypto, so the union covers failure modes
1107
+ // no single prompt reaches. `wildcard` exists because a fixed taxonomy is a
1108
+ // ceiling, and the classes worth finding are the ones not on the list.
1109
+ const LENSES = Object.freeze([
1110
+ { key: 'injection', title: 'Injection', family: 'injection', cwe: 'CWE-74',
1111
+ brief: 'Untrusted input reaching an interpreter: SQL, shell, template, XPath, LDAP, or deserialization. Follow the value, not the function name.' },
1112
+ { key: 'authz', title: 'Authorization', family: 'access-control', cwe: 'CWE-285',
1113
+ brief: 'Missing, partial, or bypassable authorization: object references not scoped to the caller, tier checks applied on one path but not another, checks performed after the effect.' },
1114
+ { key: 'crypto', title: 'Cryptography', family: 'crypto', cwe: 'CWE-327',
1115
+ brief: 'Misuse rather than choice of primitive: reused nonces, unauthenticated ciphertext, comparisons that are not constant time, keys derived from guessable material.' },
1116
+ { key: 'business-logic', title: 'Business logic', family: 'business-logic', cwe: 'CWE-840',
1117
+ brief: 'The code does what it says and what it says is wrong: state machines that accept out-of-order transitions, quantities that may be negative, refunds that exceed charges, limits enforced client side.' },
1118
+ { key: 'feature-abuse', title: 'Feature abuse', family: 'abuse', cwe: 'CWE-799',
1119
+ brief: 'A working feature used as a weapon: unbounded fan-out, expensive endpoints with no cost to the caller, invitations or exports that leak across tenants.' },
1120
+ { key: 'chained', title: 'Chained', family: 'attack-chain', cwe: 'CWE-1173',
1121
+ brief: 'Two behaviours that are each acceptable alone and unacceptable together. State the chain as an ordered sequence of steps with the attacker capability required at each.' },
1122
+ { key: 'wildcard', title: 'Wildcard', family: 'other', cwe: 'CWE-710',
1123
+ brief: 'Anything the other lenses do not cover. Prefer the surprising and specific over the generic; report nothing rather than something already obvious.' },
1124
+ ]);
1125
+
1126
+ function lensByKey(key) {
1127
+ if (typeof key !== 'string') return null;
1128
+ return LENSES.find(l => l.key === key) || null;
1129
+ }
1130
+
1131
+ const DEFAULT_MAX_CHARS = 60_000;
1132
+
1133
+ function buildHunterPrompt(focusArea, lens, ctx = {}) {
1134
+ const maxChars = Number.isInteger(ctx.maxChars) && ctx.maxChars > 0 ? ctx.maxChars : DEFAULT_MAX_CHARS;
1135
+ const contents = ctx.fileContents || {};
1136
+ const files = (focusArea?.files || []).filter(f => typeof contents[f] === 'string');
1137
+
1138
+ let budget = maxChars;
1139
+ const blocks = [];
1140
+ for (const f of files) {
1141
+ const src = contents[f];
1142
+ const slice = src.length > budget ? src.slice(0, Math.max(0, budget)) : src;
1143
+ const truncated = slice.length < src.length;
1144
+ blocks.push(`--- ${f}${truncated ? ' (truncated)' : ''} ---\n${slice}`);
1145
+ budget -= slice.length;
1146
+ if (budget <= 0) break;
1147
+ }
1148
+ const omitted = files.length - blocks.length;
1149
+
1150
+ return [
1151
+ `You are hunting for security vulnerabilities in one area of a codebase.`,
1152
+ `Area: ${focusArea?.label ?? 'unknown'} (${files.length} files)`,
1153
+ ``,
1154
+ `Your lens is ${lens.title}. ${lens.brief}`,
1155
+ `Report ONLY through this lens. Another hunter covers the others.`,
1156
+ ``,
1157
+ `Rules:`,
1158
+ `- Report a candidate only if you can name the entry point an attacker controls and the effect they achieve.`,
1159
+ `- Do not report defence-in-depth gaps, style, or "could be hardened". Those are not candidates.`,
1160
+ `- Cite a real file and line from the source below. A candidate with no location is discarded.`,
1161
+ ``,
1162
+ `Return JSON: {"candidates":[{"title","file","line","rationale","entryPoint","sink"}]}`,
1163
+ `Return {"candidates":[]} if you find nothing. An empty result is a valid and useful answer.`,
1164
+ ``,
1165
+ omitted > 0 ? `NOTE: ${omitted} file(s) omitted, prompt budget exhausted (truncated context).\n` : ``,
1166
+ ...blocks,
1167
+ ].join('\n');
1168
+ }
1169
+
1170
+
1171
+ /***/ })
1172
+
1173
+ };