@clear-capabilities/agentic-security-scanner 0.128.1 → 0.132.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +223 -0
  2. package/bin/agentic-security.js +52 -2
  3. package/dist/11.index.js +2 -2
  4. package/dist/113.index.js +498 -7
  5. package/dist/178.index.js +1 -1
  6. package/dist/207.index.js +220 -0
  7. package/dist/238.index.js +218 -0
  8. package/dist/259.index.js +975 -0
  9. package/dist/384.index.js +1 -1
  10. package/dist/415.index.js +1 -1
  11. package/dist/435.index.js +4 -4
  12. package/dist/526.index.js +844 -0
  13. package/dist/637.index.js +1 -1
  14. package/dist/830.index.js +1 -1
  15. package/dist/agentic-security.mjs +106 -194
  16. package/dist/agentic-security.mjs.sha256 +1 -1
  17. package/package.json +33 -17
  18. package/src/dataflow/CLAUDE.md +4 -1
  19. package/src/dataflow/async-sequencing.js +8 -3
  20. package/src/dataflow/catalog.js +278 -11
  21. package/src/dataflow/cross-repo.js +1 -1
  22. package/src/dataflow/cross-service-taint.js +1 -1
  23. package/src/dataflow/engine.js +182 -61
  24. package/src/dataflow/ifds.js +10 -5
  25. package/src/dataflow/index.js +15 -3
  26. package/src/dataflow/points-to.js +8 -2
  27. package/src/dataflow/proof-gate.js +7 -0
  28. package/src/dataflow/sanitizer-gate.js +89 -0
  29. package/src/dataflow/tabulation.js +14 -3
  30. package/src/engine.js +170 -7
  31. package/src/integrations/index.js +1 -1
  32. package/src/ir/CLAUDE.md +49 -4
  33. package/src/ir/call-sites.js +66 -0
  34. package/src/ir/callgraph.js +174 -7
  35. package/src/ir/class-hierarchy.js +22 -2
  36. package/src/ir/index.js +138 -51
  37. package/src/ir/ir-stats.js +126 -0
  38. package/src/ir/parser-cpp.js +829 -0
  39. package/src/ir/parser-cs.js +4 -1
  40. package/src/ir/parser-go.js +4 -1
  41. package/src/ir/parser-js.js +13 -1
  42. package/src/ir/parser-kt.js +4 -1
  43. package/src/ir/parser-php.js +10 -3
  44. package/src/ir/parser-py-cst.js +62 -10
  45. package/src/ir/tree-sitter-loader.js +13 -1
  46. package/src/llm-validator/index.js +9 -2
  47. package/src/llm-validator/redact.js +157 -0
  48. package/src/mcp/tools.js +2 -2
  49. package/src/posture/CLAUDE.md +193 -1
  50. package/src/posture/accuracy-scorecard.js +317 -0
  51. package/src/posture/api-contract.js +1 -1
  52. package/src/posture/attestation.js +202 -0
  53. package/src/posture/auditor-walkthrough.js +12 -3
  54. package/src/posture/compliance-policy.js +1 -1
  55. package/src/posture/corpus-enroll.js +303 -0
  56. package/src/posture/corpus-match.js +52 -0
  57. package/src/posture/cross-lang-openapi.js +1 -1
  58. package/src/posture/custom-rules.js +3 -3
  59. package/src/posture/execution-proof.js +92 -0
  60. package/src/posture/exploitability-probability.js +1 -1
  61. package/src/posture/falsification.js +45 -1
  62. package/src/posture/fix-metrics.js +197 -0
  63. package/src/posture/fix-verify.js +129 -2
  64. package/src/posture/license-policy.js +1 -1
  65. package/src/posture/profile.js +1 -1
  66. package/src/posture/proof-tier.js +33 -0
  67. package/src/posture/relevance.js +379 -0
  68. package/src/posture/root-cause-sweep.js +0 -0
  69. package/src/posture/rule-overrides.js +1 -1
  70. package/src/posture/sca-policy.js +1 -1
  71. package/src/posture/scan-checkpoint.js +277 -0
  72. package/src/posture/suppressions.js +1 -1
  73. package/src/posture/test-runner.js +147 -0
  74. package/src/posture/verification-separation.js +131 -0
  75. package/src/report/index.js +11 -0
  76. package/src/runScan.js +5 -7
  77. package/src/sandbox/CLAUDE.md +340 -0
  78. package/src/sandbox/backend-disabled.js +14 -0
  79. package/src/sandbox/backend-namespace.js +335 -0
  80. package/src/sandbox/backend-userspace.js +83 -0
  81. package/src/sandbox/capabilities.js +181 -0
  82. package/src/sandbox/index.js +30 -0
  83. package/src/sandbox/limits.js +63 -0
  84. package/src/sandbox/result.js +104 -0
  85. package/src/sca/dep-confusion.js +1 -1
  86. package/src/util/glob.js +173 -0
  87. package/src/util/yaml.js +24 -0
@@ -0,0 +1,844 @@
1
+ export const id = 526;
2
+ export const ids = [526,238];
3
+ export const modules = {
4
+
5
+ /***/ 2238:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
+ /* harmony export */ I3: () => (/* binding */ recordFixAttempt),
10
+ /* harmony export */ fixDurationReport: () => (/* binding */ fixDurationReport),
11
+ /* harmony export */ renderFixDurationSummary: () => (/* binding */ renderFixDurationSummary)
12
+ /* harmony export */ });
13
+ /* unused harmony exports FIX_STAGES, loadFixAttempts, bucketOf, summarizeFixDurations, _internals */
14
+ /* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3024);
15
+ /* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6760);
16
+ /* harmony import */ var _state_dir_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1174);
17
+ // Time-to-validated-fix (R5, the reporting half).
18
+ //
19
+ // `verifyFix` already RUNS the stages and `test-runner.js` already times the
20
+ // slowest one. What did not exist was anything durable to read afterwards, so
21
+ // "how long does a fix actually take to validate" had no answer from real runs
22
+ // — only an estimate (`time-to-fix.js` guesses engineering hours from family
23
+ // and patch shape, before anything runs). This module is the opposite: it
24
+ // records what the pipeline observed and reports the distribution.
25
+ //
26
+ // THE HONESTY RULES, which are most of why this file is longer than a mean:
27
+ //
28
+ // 1. A failed attempt is NOT a data point about how long a fix takes. Fixes
29
+ // that fail verification fail fast (a re-scan that still sees the finding
30
+ // never reaches the test suite), so blending them into one average makes
31
+ // the pipeline look faster the worse it performs. Validated and failed
32
+ // attempts are summarised separately and never merged.
33
+ //
34
+ // 2. "Tests skipped" is not "tests passed". A project with no detectable
35
+ // suite can reach `ok:true` having run only the re-scan and the linter.
36
+ // That is a weaker claim than a fix whose suite executed, and it is also
37
+ // much faster, so counting the two together would quietly deflate the
38
+ // headline. They get their own bucket: `validated` means the suite ran and
39
+ // passed, `validatedWithoutTests` means there was no suite to run.
40
+ //
41
+ // 3. Every figure carries its `n`, and a percentile computed from too few
42
+ // samples is labelled unreliable rather than omitted or silently reported.
43
+ // Same precedent as the accuracy scorecard's `{n, d}` rates: a number
44
+ // without its denominator is not a measurement.
45
+ //
46
+ // Storage is append-only JSONL at `<scanRoot>/.agentic-security/fix-metrics.jsonl`,
47
+ // one record per verification attempt. Nothing here throws (posture
48
+ // convention) — an unwritable or corrupt log degrades to "no metrics", never
49
+ // to a failed verification.
50
+
51
+
52
+
53
+
54
+
55
+ const STATE_DIR = '.agentic-security';
56
+ const LOG_FILE = 'fix-metrics.jsonl';
57
+
58
+ // Below this many samples a percentile is an artifact of the sample, not a
59
+ // property of the pipeline. Reported anyway (hiding it invites re-deriving it
60
+ // wrong downstream) but flagged, so a caller cannot quote it as settled.
61
+ const RELIABLE_N = 10;
62
+
63
+ // The stages verifyFix runs, in execution order. Kept here so the recorder and
64
+ // the summariser cannot drift apart on stage naming.
65
+ const FIX_STAGES = Object.freeze(['rescan', 'lint', 'tests', 'honesty', 'poc']);
66
+
67
+ function _logPath(scanRoot) {
68
+ return node_path__WEBPACK_IMPORTED_MODULE_1__.join(scanRoot, STATE_DIR, LOG_FILE);
69
+ }
70
+
71
+ /**
72
+ * Append one verification attempt. Best-effort and silent on failure: metrics
73
+ * must never be able to fail a fix that otherwise verified.
74
+ *
75
+ * @returns {boolean} whether the record was written (for tests, not callers).
76
+ */
77
+ function recordFixAttempt(scanRoot, record) {
78
+ if (!scanRoot || !record || typeof record !== 'object') return false;
79
+ try {
80
+ const dir = node_path__WEBPACK_IMPORTED_MODULE_1__.join(scanRoot, STATE_DIR);
81
+ if (!(0,_state_dir_js__WEBPACK_IMPORTED_MODULE_2__.isSafeStateDir)(dir)) return false;
82
+ node_fs__WEBPACK_IMPORTED_MODULE_0__.mkdirSync(dir, { recursive: true });
83
+ // One writeSync of one newline-terminated line: a concurrent reader sees
84
+ // whole records or nothing, and a torn tail is dropped on read.
85
+ node_fs__WEBPACK_IMPORTED_MODULE_0__.appendFileSync(_logPath(scanRoot), JSON.stringify(record) + '\n', 'utf8');
86
+ return true;
87
+ } catch { return false; }
88
+ }
89
+
90
+ /**
91
+ * Read every well-formed attempt. A line that does not parse is skipped, not
92
+ * fatal — the last line of an interrupted write is the expected case.
93
+ */
94
+ function loadFixAttempts(scanRoot) {
95
+ try {
96
+ const raw = node_fs__WEBPACK_IMPORTED_MODULE_0__.readFileSync(_logPath(scanRoot), 'utf8');
97
+ const out = [];
98
+ for (const line of raw.split('\n')) {
99
+ if (!line.trim()) continue;
100
+ try {
101
+ const rec = JSON.parse(line);
102
+ if (rec && typeof rec === 'object' && typeof rec.totalMs === 'number') out.push(rec);
103
+ } catch { /* torn or hand-edited line — drop it, keep the rest */ }
104
+ }
105
+ return out;
106
+ } catch { return []; }
107
+ }
108
+
109
+ // Nearest-rank percentile over an ascending array. Nearest-rank rather than
110
+ // interpolated because these are observed durations, and an interpolated p50
111
+ // reports a duration that no run actually took.
112
+ function _pct(sorted, p) {
113
+ if (!sorted.length) return null;
114
+ const rank = Math.ceil((p / 100) * sorted.length);
115
+ return sorted[Math.min(sorted.length - 1, Math.max(0, rank - 1))];
116
+ }
117
+
118
+ function _dist(values) {
119
+ const v = values.filter(x => typeof x === 'number' && Number.isFinite(x) && x >= 0).sort((a, b) => a - b);
120
+ if (!v.length) return { n: 0, minMs: null, p50Ms: null, p90Ms: null, maxMs: null, meanMs: null, reliable: false };
121
+ const sum = v.reduce((a, b) => a + b, 0);
122
+ return {
123
+ n: v.length,
124
+ minMs: v[0],
125
+ p50Ms: _pct(v, 50),
126
+ p90Ms: _pct(v, 90),
127
+ maxMs: v[v.length - 1],
128
+ meanMs: Math.round(sum / v.length),
129
+ // Says whether the percentiles above may be quoted, not whether the count
130
+ // is real. n and min/max/mean are exact at any sample size.
131
+ reliable: v.length >= RELIABLE_N,
132
+ };
133
+ }
134
+
135
+ // Which bucket an attempt belongs to. Deliberately total: every attempt lands
136
+ // in exactly one, so the bucket counts always sum to the attempt count and a
137
+ // mis-shaped record cannot silently vanish from the denominator.
138
+ function bucketOf(a) {
139
+ if (!a?.ok) return 'failed';
140
+ return a.testsRan ? 'validated' : 'validatedWithoutTests';
141
+ }
142
+
143
+ /**
144
+ * Summarise a set of attempts into the reported distribution.
145
+ *
146
+ * `validated` is the headline: attempts that verified AND whose test suite
147
+ * actually ran and passed. The other two buckets exist so that headline cannot
148
+ * be inflated by counting weaker or faster outcomes inside it.
149
+ */
150
+ function summarizeFixDurations(attempts) {
151
+ const all = Array.isArray(attempts) ? attempts : [];
152
+ const buckets = { validated: [], validatedWithoutTests: [], failed: [] };
153
+ for (const a of all) buckets[bucketOf(a)].push(a);
154
+
155
+ const byStage = {};
156
+ for (const stage of FIX_STAGES) {
157
+ // Per-stage timings come from validated runs only. A stage's duration in a
158
+ // failed run is truncated by the failure (the pipeline stops), so mixing
159
+ // them in would understate every stage after the first failure point.
160
+ byStage[stage] = _dist(buckets.validated.map(a => a?.stages?.[stage]));
161
+ }
162
+
163
+ return {
164
+ attempts: all.length,
165
+ counts: {
166
+ validated: buckets.validated.length,
167
+ validatedWithoutTests: buckets.validatedWithoutTests.length,
168
+ failed: buckets.failed.length,
169
+ },
170
+ timeToValidatedFix: _dist(buckets.validated.map(a => a.totalMs)),
171
+ timeToValidatedFixWithoutTests: _dist(buckets.validatedWithoutTests.map(a => a.totalMs)),
172
+ timeToFailure: _dist(buckets.failed.map(a => a.totalMs)),
173
+ byStage,
174
+ reliableAtOrAbove: RELIABLE_N,
175
+ };
176
+ }
177
+
178
+ /** Read + summarise in one step. */
179
+ function fixDurationReport(scanRoot) {
180
+ return summarizeFixDurations(loadFixAttempts(scanRoot));
181
+ }
182
+
183
+ function _ms(v) {
184
+ if (v == null) return '—';
185
+ return v >= 1000 ? `${(v / 1000).toFixed(1)}s` : `${v}ms`;
186
+ }
187
+
188
+ /**
189
+ * One-paragraph human summary. Returns null when there is nothing measured —
190
+ * callers print nothing rather than printing an empty table.
191
+ */
192
+ function renderFixDurationSummary(sum) {
193
+ if (!sum || !sum.attempts) return null;
194
+ const d = sum.timeToValidatedFix;
195
+ const parts = [];
196
+ if (d.n) {
197
+ parts.push(
198
+ `time-to-validated-fix: median ${_ms(d.p50Ms)}, p90 ${_ms(d.p90Ms)} `
199
+ + `(n=${d.n}${d.reliable ? '' : `, below ${sum.reliableAtOrAbove} — percentiles not yet reliable`})`,
200
+ );
201
+ } else {
202
+ parts.push('time-to-validated-fix: no fix has both verified and had its test suite run yet');
203
+ }
204
+ if (sum.counts.validatedWithoutTests) {
205
+ parts.push(`${sum.counts.validatedWithoutTests} verified with no detectable test suite (excluded from the median above)`);
206
+ }
207
+ if (sum.counts.failed) {
208
+ parts.push(`${sum.counts.failed} failed verification, median ${_ms(sum.timeToFailure.p50Ms)} (counted separately)`);
209
+ }
210
+ return parts.join('; ') + '.';
211
+ }
212
+
213
+ const _internals = { _dist, _pct, RELIABLE_N };
214
+
215
+
216
+ /***/ }),
217
+
218
+ /***/ 3526:
219
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
220
+
221
+ // ESM COMPAT FLAG
222
+ __webpack_require__.r(__webpack_exports__);
223
+
224
+ // EXPORTS
225
+ __webpack_require__.d(__webpack_exports__, {
226
+ runProjectLinter: () => (/* binding */ runProjectLinter),
227
+ verifyFix: () => (/* binding */ verifyFix),
228
+ verifyPatch: () => (/* binding */ verifyPatch)
229
+ });
230
+
231
+ // EXTERNAL MODULE: external "node:child_process"
232
+ var external_node_child_process_ = __webpack_require__(1421);
233
+ // EXTERNAL MODULE: external "node:fs"
234
+ var external_node_fs_ = __webpack_require__(3024);
235
+ // EXTERNAL MODULE: external "node:path"
236
+ var external_node_path_ = __webpack_require__(6760);
237
+ // EXTERNAL MODULE: ./src/engine.js + 595 modules
238
+ var engine = __webpack_require__(4660);
239
+ ;// CONCATENATED MODULE: ./src/posture/fix-honesty-gate.js
240
+ // Deterministic honesty gates on fix / finding output (#7).
241
+ //
242
+ // The project's verification discipline (scanner/CLAUDE.md) exists because
243
+ // several releases shipped broken or false because work was reported as done
244
+ // without confirming the artifact changed. Two of those failure modes are
245
+ // *textual* — they live in the prose an agent emits alongside a fix — and can
246
+ // be caught deterministically, with no LLM and no network:
247
+ //
248
+ // 1. Hand-wave residual-risk prose. "The input is adequately handled",
249
+ // "future work", "tbd", "later" — vague assurances that claim safety
250
+ // without naming a concrete remaining vector. A residual you can't name
251
+ // is a residual you're guessing about; reject the guess.
252
+ //
253
+ // 2. An unbacked "this is a false positive / provably safe" verdict. Marking
254
+ // a finding safe is a coverage *reduction* — it must cite a `file:line`
255
+ // that shows why, exactly like the rules-override gate refuses to silently
256
+ // shrink coverage.
257
+ //
258
+ // Plus a conservative fix-tier classifier so a partial remediation can never be
259
+ // labelled FULL: any workaround-only signal (rate-limit, docs, log-without-
260
+ // reject) is WORKAROUND; anything short of (sink signature changed + all callers
261
+ // routed + a discriminating test) is at most MITIGATION; only the full set with
262
+ // no partial-sanitization caveat earns FULL.
263
+ //
264
+ // Pure functions, no side effects, no throwing — safe to call from a command,
265
+ // a hook, or the MCP verify_fix path.
266
+
267
+ // Vague-assurance phrases that a real residual must never hide behind. Matched
268
+ // case-insensitively with word boundaries so "later" doesn't trip on
269
+ // "collateral" and "tbd" doesn't trip on a longer token.
270
+ const BANNED_RESIDUAL_PHRASES = Object.freeze([
271
+ 'adequately handled',
272
+ 'adequately handles',
273
+ 'properly validated',
274
+ 'properly handled',
275
+ 'handled properly',
276
+ 'handled safely',
277
+ 'future work',
278
+ 'more work needed',
279
+ 'to be done',
280
+ 'tbd',
281
+ 'later',
282
+ ]);
283
+
284
+ // A citation shaped like `file:line` — one or more non-space, non-colon chars,
285
+ // a colon, then digits. Unanchored: it need only appear somewhere in the item.
286
+ const CITATION_RE = /[^\s:]+:\d+/;
287
+
288
+ // Verdicts that assert the finding is not real and therefore demand a citation.
289
+ // Compared after normalizing separators (`_`/space → `-`) and lowercasing, so
290
+ // FALSE_POSITIVE, false-positive, and "provably safe" all land here.
291
+ const FP_VERDICTS = Object.freeze(new Set(['false-positive', 'provably-safe', 'safe']));
292
+
293
+ function _escapeRe(s) {
294
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
295
+ }
296
+
297
+ /**
298
+ * Reject vague-assurance / hand-wave residual-risk prose.
299
+ *
300
+ * An empty or whitespace-only residual is ok — there is no residual to lie
301
+ * about. A non-empty residual is rejected when it contains any banned phrase;
302
+ * each match yields one violation naming the offending phrase.
303
+ *
304
+ * @param {string} residualText
305
+ * @returns {{ ok: boolean, violations: string[] }}
306
+ */
307
+ function checkResidualHonesty(residualText) {
308
+ const text = typeof residualText === 'string' ? residualText : '';
309
+ if (text.trim() === '') return { ok: true, violations: [] };
310
+
311
+ const violations = [];
312
+ for (const phrase of BANNED_RESIDUAL_PHRASES) {
313
+ const re = new RegExp(`\\b${_escapeRe(phrase)}\\b`, 'i');
314
+ if (re.test(text)) {
315
+ violations.push(`vague-assurance phrase: "${phrase}"`);
316
+ }
317
+ }
318
+ return { ok: violations.length === 0, violations };
319
+ }
320
+
321
+ function _isCitation(item) {
322
+ if (typeof item === 'string') return CITATION_RE.test(item);
323
+ if (item && typeof item === 'object' && typeof item.location === 'string') {
324
+ return CITATION_RE.test(item.location);
325
+ }
326
+ return false;
327
+ }
328
+
329
+ function _normalizeVerdict(verdict) {
330
+ return String(verdict).trim().toLowerCase().replace(/[_\s]+/g, '-');
331
+ }
332
+
333
+ /**
334
+ * Require a file:line citation behind a "this is not real" verdict.
335
+ *
336
+ * For a false-positive / provably-safe / safe verdict (case-insensitive; also
337
+ * accepts FALSE_POSITIVE), at least one evidence item must be a `file:line`
338
+ * citation — either a string matching /[^\s:]+:\d+/ or an object
339
+ * `{ location: "file:line" }`. Any other verdict passes unconditionally.
340
+ *
341
+ * @param {string} verdict
342
+ * @param {Array|string|object} evidence
343
+ * @returns {{ ok: boolean, violations: string[] }}
344
+ */
345
+ function requireCitedEvidence(verdict, evidence) {
346
+ if (typeof verdict !== 'string' || !FP_VERDICTS.has(_normalizeVerdict(verdict))) {
347
+ return { ok: true, violations: [] };
348
+ }
349
+ const items = Array.isArray(evidence)
350
+ ? evidence
351
+ : evidence == null
352
+ ? []
353
+ : [evidence];
354
+ if (items.some(_isCitation)) return { ok: true, violations: [] };
355
+ return {
356
+ ok: false,
357
+ violations: ['false-positive/safe verdict requires a file:line citation'],
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Classify a fix into FULL | MITIGATION | WORKAROUND, conservative-first.
363
+ *
364
+ * @param {object} signals
365
+ * @param {boolean} signals.sinkSignatureChanged
366
+ * @param {boolean} signals.allCallersRouted
367
+ * @param {boolean} signals.testDiscriminates - a test that fails pre-fix, passes post-fix
368
+ * @param {boolean} [signals.rateLimitOnly]
369
+ * @param {boolean} [signals.docsOnly]
370
+ * @param {boolean} [signals.logOnlyNoReject]
371
+ * @param {boolean} [signals.partialSanitization]
372
+ * @returns {'FULL'|'MITIGATION'|'WORKAROUND'}
373
+ */
374
+ function computeFixTier(signals) {
375
+ const s = signals && typeof signals === 'object' ? signals : {};
376
+ if (s.rateLimitOnly || s.docsOnly || s.logOnlyNoReject) return 'WORKAROUND';
377
+ const complete = s.sinkSignatureChanged && s.allCallersRouted && s.testDiscriminates;
378
+ if (s.partialSanitization || !complete) return 'MITIGATION';
379
+ return 'FULL';
380
+ }
381
+
382
+ /**
383
+ * Compose the three gates for a single fix's output.
384
+ *
385
+ * ok = residual-honesty ok AND evidence-citation ok, further constrained by the
386
+ * tier/residual consistency invariant:
387
+ * - a FULL tier must NOT carry a residual (a full fix has nothing left);
388
+ * - a non-FULL tier MUST document a residual (say what's still open).
389
+ *
390
+ * @param {{ residual?: string, verdict?: string, evidence?: any, signals?: object }} input
391
+ * @returns {{ ok: boolean, tier: string, violations: string[] }}
392
+ */
393
+ function gateFixOutput({ residual, verdict, evidence, signals } = {}) {
394
+ const tier = computeFixTier(signals);
395
+ const residualCheck = checkResidualHonesty(residual);
396
+ const evidenceCheck = requireCitedEvidence(verdict, evidence);
397
+
398
+ const violations = [...residualCheck.violations, ...evidenceCheck.violations];
399
+ let ok = residualCheck.ok && evidenceCheck.ok;
400
+
401
+ const residualEmpty = typeof residual !== 'string' || residual.trim() === '';
402
+ if (tier === 'FULL' && !residualEmpty) {
403
+ violations.push('FULL tier cannot carry a residual');
404
+ ok = false;
405
+ }
406
+ if (tier !== 'FULL' && residualEmpty) {
407
+ violations.push('non-FULL tier must document a residual');
408
+ ok = false;
409
+ }
410
+
411
+ return { ok, tier, violations };
412
+ }
413
+
414
+ const _internals = Object.freeze({ BANNED_RESIDUAL_PHRASES, CITATION_RE, FP_VERDICTS });
415
+
416
+ ;// CONCATENATED MODULE: ./src/posture/test-runner.js
417
+ // R5 (partial, roadmap) — the project's own test suite as a verification
418
+ // stage for `verifyFix()` (see `fix-verify.js`). Closes the gap where a
419
+ // "verified" fix only proved a finding's stableId stopped firing — a patch
420
+ // that deletes the feature entirely would satisfy that just as well as a
421
+ // real fix. Running the project's own tests is the cheapest available check
422
+ // that the application still works.
423
+ //
424
+ // Execution-safety note: this spawns the TARGET PROJECT's own test command
425
+ // in the target project's own directory. That is deliberately NOT routed
426
+ // through the R1 confinement sandbox (`../sandbox/`). That sandbox exists to
427
+ // contain untrusted proof-of-concept exploit code the scanner itself
428
+ // synthesizes — code nobody has vetted, being run for the first time. A
429
+ // project's pre-existing test suite is the opposite case: it is the
430
+ // project's own trusted source, already sitting on disk, and running it is
431
+ // exactly what a human developer does by hand before trusting a fix.
432
+ // Wrapping "npm test" / "pytest" / "go test" in the PoC sandbox's
433
+ // syscall/network/filesystem restrictions would break the large majority of
434
+ // real test suites (they bind local ports, spawn child processes, write temp
435
+ // fixtures, etc.) for no corresponding security benefit.
436
+
437
+
438
+
439
+
440
+
441
+ const DEFAULT_TIMEOUT_MS = 300_000;
442
+ const NPM_PLACEHOLDER = /Error: no test specified/i;
443
+
444
+ function _exists(scanRoot, rel) {
445
+ try { return external_node_fs_.existsSync(external_node_path_.join(scanRoot, rel)); } catch { return false; }
446
+ }
447
+
448
+ function _isDir(scanRoot, rel) {
449
+ try { return external_node_fs_.statSync(external_node_path_.join(scanRoot, rel)).isDirectory(); } catch { return false; }
450
+ }
451
+
452
+ function _binaryAvailable(cmd) {
453
+ try {
454
+ const r = (0,external_node_child_process_.spawnSync)(cmd, ['--version'], { timeout: 5_000, stdio: 'ignore' });
455
+ return !(r.error && r.error.code === 'ENOENT');
456
+ } catch {
457
+ return false;
458
+ }
459
+ }
460
+
461
+ // Detect the project's test command. Read-only — never spawns the actual
462
+ // test run, only (optionally) a cheap `--version` probe to confirm a tool
463
+ // like `pytest` is actually installed before committing to it. Returns
464
+ // `null` when nothing detectable is found — most scanned repos will hit
465
+ // this path, and that must not be treated as a failure by callers.
466
+ function detectTestCommand(scanRoot) {
467
+ if (!scanRoot) return null;
468
+
469
+ // JS/TS — package.json with a real (non-placeholder) `scripts.test`.
470
+ let pkg = null;
471
+ try { pkg = JSON.parse(external_node_fs_.readFileSync(external_node_path_.join(scanRoot, 'package.json'), 'utf8')); } catch { pkg = null; }
472
+ const testScript = pkg && pkg.scripts && pkg.scripts.test;
473
+ if (testScript && !NPM_PLACEHOLDER.test(String(testScript))) {
474
+ if (_exists(scanRoot, 'pnpm-lock.yaml')) return { cmd: 'pnpm', args: ['test'], kind: 'pnpm' };
475
+ if (_exists(scanRoot, 'yarn.lock')) return { cmd: 'yarn', args: ['test'], kind: 'yarn' };
476
+ if (_exists(scanRoot, 'bun.lockb') || _exists(scanRoot, 'bun.lock')) return { cmd: 'bun', args: ['test'], kind: 'bun' };
477
+ return { cmd: 'npm', args: ['test', '--silent'], kind: 'npm' };
478
+ }
479
+
480
+ // Python — pytest.ini / pyproject.toml / tox.ini / a tests/ dir, and the
481
+ // `pytest` binary actually available. If pytest isn't installed we do NOT
482
+ // report a python test command — falling through lets a later language
483
+ // marker (e.g. go.mod in a polyglot repo) still be detected.
484
+ const pyMarker = _exists(scanRoot, 'pytest.ini') || _exists(scanRoot, 'pyproject.toml') ||
485
+ _exists(scanRoot, 'tox.ini') || _isDir(scanRoot, 'tests');
486
+ if (pyMarker && _binaryAvailable('pytest')) {
487
+ return { cmd: 'pytest', args: ['-q'], kind: 'pytest' };
488
+ }
489
+
490
+ // Go
491
+ if (_exists(scanRoot, 'go.mod')) {
492
+ return { cmd: 'go', args: ['test', './...'], kind: 'go' };
493
+ }
494
+
495
+ return null;
496
+ }
497
+
498
+ // Run the detected test command with a walltime budget. Always returns a
499
+ // result object — never throws. Distinguishes four outcomes:
500
+ // - no detectable/runnable command -> status: 'skipped' (does NOT fail)
501
+ // - ran and exited 0 -> status: 'passed'
502
+ // - ran and exited non-zero -> status: 'failed'
503
+ // - ran past the timeout budget -> status: 'failed', timedOut: true
504
+ function runProjectTests(scanRoot, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
505
+ const startedAt = Date.now();
506
+ const command = detectTestCommand(scanRoot);
507
+ if (!command) {
508
+ return {
509
+ status: 'skipped', passed: null, skipped: true,
510
+ reason: 'no-test-command-detected', exitCode: null, timedOut: false,
511
+ durationMs: Date.now() - startedAt,
512
+ };
513
+ }
514
+
515
+ let r;
516
+ try {
517
+ r = (0,external_node_child_process_.spawnSync)(command.cmd, command.args, {
518
+ cwd: scanRoot,
519
+ encoding: 'utf8',
520
+ timeout: timeoutMs,
521
+ env: { ...process.env, CI: '1' },
522
+ });
523
+ } catch (e) {
524
+ // The spawn call itself threw (rare — e.g. cwd vanished). Treat as
525
+ // "could not run", not "ran and failed".
526
+ return {
527
+ status: 'skipped', passed: null, skipped: true,
528
+ reason: `spawn-error: ${e.message}`, exitCode: null, timedOut: false,
529
+ durationMs: Date.now() - startedAt,
530
+ };
531
+ }
532
+ const durationMs = Date.now() - startedAt;
533
+
534
+ if (r.error && r.error.code === 'ENOENT') {
535
+ // The detected tool isn't actually installed on this machine. Not a
536
+ // test failure — the suite never ran.
537
+ return {
538
+ status: 'skipped', passed: null, skipped: true,
539
+ reason: `${command.kind}-not-installed`, exitCode: null, timedOut: false, durationMs,
540
+ };
541
+ }
542
+
543
+ if (r.status === null) {
544
+ // spawnSync sets status:null both on timeout-kill and on being killed by
545
+ // another signal; either way the run did not complete, which is a
546
+ // verification failure, never a skip — we asked for a result and the
547
+ // process was terminated before producing one.
548
+ return {
549
+ status: 'failed', passed: false, skipped: false,
550
+ reason: 'timed-out', exitCode: null, timedOut: true, durationMs,
551
+ };
552
+ }
553
+
554
+ return {
555
+ status: r.status === 0 ? 'passed' : 'failed',
556
+ passed: r.status === 0,
557
+ skipped: false,
558
+ reason: r.status === 0 ? null : 'test-failures',
559
+ exitCode: r.status,
560
+ timedOut: false,
561
+ durationMs,
562
+ };
563
+ }
564
+
565
+ // EXTERNAL MODULE: ./src/posture/fix-metrics.js
566
+ var fix_metrics = __webpack_require__(2238);
567
+ ;// CONCATENATED MODULE: ./src/posture/fix-verify.js
568
+ // Closed-loop /fix verification (Sentinel-parity FR-L4-4, FR-L4-5).
569
+ //
570
+ // Given a candidate patch (the new file content + the finding stableId being
571
+ // fixed), verify it:
572
+ //
573
+ // 1. The original finding's stableId no longer fires on the patched file.
574
+ // 2. No new findings at severity ≥ medium were introduced by the patch.
575
+ // 3. The project's existing linter (when present) passes on the patched file.
576
+ // 4. The project's own test suite (when detectable) still passes. This is
577
+ // the R5 gap-closer: a patch that silently deletes the feature would
578
+ // satisfy (1) and (2) just as well as a real fix — only running the
579
+ // tests catches that. See `test-runner.js` for detection + execution.
580
+ //
581
+ // If any of those fail, the caller is expected to NOT apply the patch and
582
+ // instead surface a "fix plan" — a numbered list of steps the engineer can
583
+ // follow — rather than dump a broken patch on the user.
584
+
585
+
586
+
587
+
588
+
589
+
590
+
591
+
592
+
593
+ const SEVERITY_RANK = { critical: 0, high: 1, medium: 2, low: 3, info: 4 };
594
+
595
+ // Run a focused re-scan over just the patched file(s) using the in-memory
596
+ // engine. No filesystem write needed — we hand the new content in via the
597
+ // fileContents map.
598
+ async function verifyPatch({
599
+ scanRoot,
600
+ originalFindingStableId,
601
+ files, // { [relPath]: newContent }
602
+ depFileContents = {},
603
+ } = {}) {
604
+ if (!files || typeof files !== 'object') return { ok: false, reason: 'no-files-provided' };
605
+ const fileContents = { ...files };
606
+ let scan;
607
+ try {
608
+ scan = await (0,engine/* runFullScan */.wW)({ fileContents, depFileContents, scanRoot }, () => {});
609
+ } catch (e) {
610
+ return { ok: false, reason: 'rescan-failed', error: e.message };
611
+ }
612
+ const findings = (scan && scan.findings) || [];
613
+ const stillHasOriginal = !!originalFindingStableId &&
614
+ findings.some(f => f.stableId === originalFindingStableId);
615
+ if (stillHasOriginal) {
616
+ return { ok: false, reason: 'original-finding-still-present', stableId: originalFindingStableId };
617
+ }
618
+ const introducedHighOrAbove = findings.filter(f =>
619
+ (SEVERITY_RANK[f.severity] ?? 9) <= SEVERITY_RANK.medium);
620
+ // Don't count findings on lines outside the patched files — but our
621
+ // fileContents map IS the patched files, so every finding is in-scope.
622
+ return {
623
+ ok: introducedHighOrAbove.length === 0,
624
+ reason: introducedHighOrAbove.length === 0 ? 'verified' : 'introduced-new-findings',
625
+ introduced: introducedHighOrAbove.map(f => ({
626
+ vuln: f.vuln, file: f.file, line: f.line, severity: f.severity,
627
+ stableId: f.stableId,
628
+ })),
629
+ };
630
+ }
631
+
632
+ // Detect which linter the project uses and run it on the patched files.
633
+ // Returns { ok, runner, output } or { ok: true, runner: 'none' } when no
634
+ // linter is configured (silent pass).
635
+ function runProjectLinter(scanRoot, filePaths) {
636
+ if (!scanRoot || !Array.isArray(filePaths) || filePaths.length === 0) {
637
+ return { ok: true, runner: 'none' };
638
+ }
639
+ const has = (p) => { try { return external_node_fs_.existsSync(external_node_path_.join(scanRoot, p)); } catch { return false; } };
640
+ // Pick the linter by config file present in the repo root.
641
+ const jsFiles = filePaths.filter(f => /\.(?:js|jsx|ts|tsx|mjs|cjs)$/i.test(f));
642
+ const pyFiles = filePaths.filter(f => /\.py$/i.test(f));
643
+ const goFiles = filePaths.filter(f => /\.go$/i.test(f));
644
+ const javaFiles = filePaths.filter(f => /\.java$/i.test(f));
645
+
646
+ if (jsFiles.length && (has('.eslintrc') || has('.eslintrc.json') || has('.eslintrc.js') || has('eslint.config.js') || has('eslint.config.mjs'))) {
647
+ return runLinter(scanRoot, 'eslint', ['--no-error-on-unmatched-pattern', ...jsFiles]);
648
+ }
649
+ if (pyFiles.length && (has('pyproject.toml') || has('ruff.toml') || has('.ruff.toml'))) {
650
+ return runLinter(scanRoot, 'ruff', ['check', ...pyFiles]);
651
+ }
652
+ if (pyFiles.length && has('.flake8')) {
653
+ return runLinter(scanRoot, 'flake8', pyFiles);
654
+ }
655
+ if (goFiles.length && (has('.golangci.yml') || has('.golangci.yaml'))) {
656
+ return runLinter(scanRoot, 'golangci-lint', ['run', ...goFiles]);
657
+ }
658
+ if (javaFiles.length && has('checkstyle.xml')) {
659
+ return runLinter(scanRoot, 'checkstyle', ['-c', 'checkstyle.xml', ...javaFiles]);
660
+ }
661
+ return { ok: true, runner: 'none' };
662
+ }
663
+
664
+ function runLinter(cwd, cmd, args) {
665
+ let r;
666
+ try {
667
+ r = (0,external_node_child_process_.spawnSync)(cmd, args, { cwd, encoding: 'utf8', timeout: 60_000 });
668
+ } catch (e) {
669
+ return { ok: true, runner: cmd, skipped: true, reason: 'binary-missing', error: e.message };
670
+ }
671
+ if (r.error && r.error.code === 'ENOENT') {
672
+ return { ok: true, runner: cmd, skipped: true, reason: 'binary-missing' };
673
+ }
674
+ if (r.status === null) {
675
+ return { ok: false, runner: cmd, reason: 'timed-out', output: (r.stderr || r.stdout || '').slice(-2000) };
676
+ }
677
+ return {
678
+ ok: r.status === 0,
679
+ runner: cmd,
680
+ exitCode: r.status,
681
+ output: ((r.stderr || '') + (r.stdout || '')).slice(-2000),
682
+ };
683
+ }
684
+
685
+ // Top-level verify: re-scan + lint. Returns the combined verdict + a
686
+ // human-readable summary string suitable for surfacing to the user.
687
+ // Addition #7 — deterministic honesty gates on fix output. When the caller
688
+ // supplies `fixMeta` ({ residual, verdict, evidence, signals }) — e.g. the
689
+ // security-fixer agent's residual-risk text + completeness signals — the fix's
690
+ // claims are checked mechanically (no hand-wave residual prose, a cited
691
+ // file:line for any FP/safe verdict, and a FULL/MITIGATION/WORKAROUND tier). A
692
+ // dishonest or over-claiming fix fails the gate. When `fixMeta` is absent
693
+ // (the deterministic MCP write path, which has no claims to check) the honesty
694
+ // gate is skipped and behavior is unchanged.
695
+ // R5 (partial) — the test-suite stage. Runs the target project's own tests,
696
+ // in the target project's own directory, against whatever is currently on
697
+ // disk there. See `test-runner.js`'s header comment for why that run is
698
+ // deliberately NOT routed through the R1 PoC-confinement sandbox: this is
699
+ // the project's own already-trusted suite, not untrusted synthesized code.
700
+ //
701
+ // Caveat that matters for callers: `verifyPatch` above re-scans the
702
+ // candidate patch purely in memory (no write to disk), but a test runner
703
+ // needs real files — there is no cheap way to hand a runner an in-memory
704
+ // overlay. So this leg reports on the CURRENT on-disk tree, not the
705
+ // candidate `files` map, when `verifyFix` is used as a pre-write preview
706
+ // (e.g. the `verify_fix` MCP tool). Callers that apply the patch first and
707
+ // then re-verify get the strongest signal; that ordering is not enforced
708
+ // here — it's the caller's responsibility, same as it already is for the
709
+ // closed-loop `fix-verify-loop.js` path.
710
+ // Does the caller's candidate patch differ from what is on disk right now?
711
+ // If so, any test run necessarily exercised the pre-patch tree. Compared by
712
+ // content so a patch that happens to match disk (already applied) is correctly
713
+ // treated as NOT pre-patch.
714
+ function _candidateDiffersFromDisk(scanRoot, files) {
715
+ if (!files || typeof files !== 'object') return false;
716
+ for (const [rel, content] of Object.entries(files)) {
717
+ if (typeof content !== 'string') continue;
718
+ try {
719
+ const abs = external_node_path_.resolve(scanRoot, rel);
720
+ if (external_node_fs_.readFileSync(abs, 'utf8') !== content) return true;
721
+ } catch {
722
+ return true; // candidate file absent on disk -> definitely not applied
723
+ }
724
+ }
725
+ return false;
726
+ }
727
+
728
+ async function verifyFix({
729
+ scanRoot,
730
+ originalFindingStableId,
731
+ files,
732
+ depFileContents,
733
+ fixMeta,
734
+ testTimeoutMs,
735
+ recordMetrics = true,
736
+ poc,
737
+ } = {}) {
738
+ // R5 (reporting half) — time each stage as it runs. Measured here rather
739
+ // than inside each stage because only this function knows the boundaries of
740
+ // one verification ATTEMPT, which is the unit the distribution is over.
741
+ const stages = {};
742
+ const t0 = Date.now();
743
+ let mark = t0;
744
+ const _lap = (name) => { const now = Date.now(); stages[name] = now - mark; mark = now; };
745
+
746
+ const rescan = await verifyPatch({ scanRoot, originalFindingStableId, files, depFileContents });
747
+ _lap('rescan');
748
+ const lint = runProjectLinter(scanRoot, Object.keys(files || {}));
749
+ _lap('lint');
750
+ const tests = runProjectTests(scanRoot, testTimeoutMs != null ? { timeoutMs: testTimeoutMs } : {});
751
+ _lap('tests');
752
+ // True when a candidate patch was supplied but has not been written, so the
753
+ // suite necessarily ran against the pre-patch tree. Surfaced in the summary
754
+ // and on the result so a caller cannot mistake it for a verified patch.
755
+ const _testedPrePatch = !tests.skipped && _candidateDiffersFromDisk(scanRoot, files);
756
+ const testsOk = tests.skipped ? true : tests.passed === true;
757
+ let honesty = null;
758
+ if (fixMeta && typeof fixMeta === 'object') {
759
+ try { honesty = gateFixOutput(fixMeta); } catch { honesty = null; }
760
+ }
761
+ _lap('honesty');
762
+
763
+ // R5 — the PoC leg. Re-run the finding's proof-of-concept against the
764
+ // CANDIDATE patch inside R1's sandbox. A patch that still lets the PoC
765
+ // demonstrate the predicted effect has not fixed anything, however green the
766
+ // re-scan looks: the re-scan only proves the DETECTOR stopped firing, which
767
+ // a cosmetic edit can achieve. Execution is the stronger claim.
768
+ //
769
+ // Direction matters and is asymmetric on purpose. `execution-proven` after
770
+ // the patch is a hard FAIL. Anything else is NOT a pass — a PoC that failed
771
+ // to run, or a sandbox that could not start, is recorded as `inconclusive`
772
+ // and left out of the verdict entirely. Treating "could not prove it" as
773
+ // "fixed" is exactly the false confidence this leg exists to prevent.
774
+ let pocLeg = { status: 'not-requested', reason: null, tier: null };
775
+ if (poc?.code) {
776
+ try {
777
+ const { proveFinding } = await __webpack_require__.e(/* import() */ 259).then(__webpack_require__.bind(__webpack_require__, 8259));
778
+ const proved = await proveFinding({ ...(poc.finding || {}), poc }, { files });
779
+ const tier = proved.proofTier;
780
+ pocLeg = tier === 'execution-proven'
781
+ ? { status: 'still-exploitable', tier, reason: proved.proofEvidence?.observed || null }
782
+ : proved.proofEvidence?.ran
783
+ ? { status: 'no-longer-proven', tier, reason: proved.proofEvidence?.reason || null }
784
+ : { status: 'inconclusive', tier, reason: proved.proofEvidence?.reason || null };
785
+ } catch (e) {
786
+ pocLeg = { status: 'inconclusive', tier: null, reason: `proof harness error: ${e.message}` };
787
+ }
788
+ }
789
+ _lap('poc');
790
+ const pocOk = pocLeg.status !== 'still-exploitable';
791
+
792
+ const ok = rescan.ok && (lint.ok || lint.skipped) && testsOk && pocOk && (honesty ? honesty.ok : true);
793
+ const durations = { ...stages, totalMs: Date.now() - t0 };
794
+ const summary = [
795
+ `re-scan: ${rescan.ok ? 'PASS' : 'FAIL — ' + rescan.reason}`,
796
+ `linter: ${lint.runner === 'none' ? 'skipped (no linter config)'
797
+ : lint.skipped ? `${lint.runner} not installed`
798
+ : lint.ok ? `${lint.runner} PASS`
799
+ : `${lint.runner} FAIL (exit ${lint.exitCode})`}`,
800
+ // Say which tree the suite actually ran against. `files` is a candidate
801
+ // patch held in memory; the runner needs real files, so it sees whatever is
802
+ // on disk. Reporting a bare "PASS" here would let a caller believe the
803
+ // PATCH passed the tests when the suite may have run on unpatched code.
804
+ `tests: ${tests.skipped ? `skipped (${tests.reason})`
805
+ : tests.timedOut ? 'FAIL (timed out)'
806
+ : tests.passed ? `PASS${_testedPrePatch ? ' — on the CURRENT on-disk tree, NOT the candidate patch' : ''}`
807
+ : `FAIL (exit ${tests.exitCode})`}`,
808
+ honesty ? `honesty: ${honesty.ok ? `PASS (${honesty.tier})` : 'FAIL — ' + honesty.violations.join('; ')}` : null,
809
+ // Never render `inconclusive` as a pass — say plainly that nothing was proven.
810
+ pocLeg.status === 'not-requested' ? null
811
+ : pocLeg.status === 'still-exploitable' ? `poc: FAIL — the proof-of-concept still demonstrates the vulnerability against the patch`
812
+ : pocLeg.status === 'no-longer-proven' ? 'poc: PASS (ran against the patch and no longer demonstrates the vulnerability)'
813
+ : `poc: inconclusive — not counted either way (${pocLeg.reason || 'no detail reported'})`,
814
+ ].filter(Boolean).join('\n');
815
+ // Persist the attempt so the distribution can be reported from real runs.
816
+ // `testsRan` is the load-bearing field: it is what keeps "verified with no
817
+ // test suite to run" out of the headline time-to-validated-fix bucket.
818
+ // A patch that was never written to disk is recorded too, but flagged — its
819
+ // suite ran against the pre-patch tree, so its timing is real while its
820
+ // verdict is about a different tree.
821
+ if (recordMetrics && scanRoot) {
822
+ (0,fix_metrics/* recordFixAttempt */.I3)(scanRoot, {
823
+ at: new Date().toISOString(),
824
+ stableId: originalFindingStableId || null,
825
+ ok,
826
+ testsRan: !tests.skipped,
827
+ testsPassed: tests.skipped ? null : tests.passed === true,
828
+ testedPrePatch: _testedPrePatch,
829
+ lintRan: !(lint.skipped || lint.runner === 'none'),
830
+ honestyGated: honesty != null,
831
+ pocStatus: pocLeg.status,
832
+ files: Object.keys(files || {}).length,
833
+ stages,
834
+ totalMs: durations.totalMs,
835
+ });
836
+ }
837
+
838
+ return { ok, rescan, lint, tests, testedPrePatch: _testedPrePatch, honesty, poc: pocLeg, durations, summary };
839
+ }
840
+
841
+
842
+ /***/ })
843
+
844
+ };