@clear-capabilities/agentic-security-scanner 0.175.0 → 0.176.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 (101) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/bin/agentic-security.js +199 -28
  3. package/dist/2066.index.js +850 -0
  4. package/dist/2199.index.js +1 -1
  5. package/dist/2584.index.js +3332 -0
  6. package/dist/2923.index.js +13 -0
  7. package/dist/2946.index.js +81 -0
  8. package/dist/3196.index.js +27 -0
  9. package/dist/3727.index.js +292 -0
  10. package/dist/4168.index.js +509 -0
  11. package/dist/4281.index.js +993 -0
  12. package/dist/4978bec8fdf5c733dc85.json +283 -0
  13. package/dist/5099.index.js +96 -0
  14. package/dist/5616.index.js +1471 -0
  15. package/dist/5620.index.js +2370 -0
  16. package/dist/5817.index.js +714 -0
  17. package/dist/6333.index.js +98 -0
  18. package/dist/6655.index.js +3221 -0
  19. package/dist/7838.index.js +446 -974
  20. package/dist/818.index.js +4 -3
  21. package/dist/83.index.js +159 -0
  22. package/dist/8551.index.js +82 -0
  23. package/dist/8633.index.js +93 -0
  24. package/dist/8714.index.js +76 -76
  25. package/dist/8825.index.js +84 -0
  26. package/dist/932.index.js +186 -0
  27. package/dist/9560.index.js +358 -19
  28. package/dist/9800.index.js +6 -1
  29. package/dist/agentic-security.mjs +10 -10
  30. package/dist/agentic-security.mjs.sha256 +1 -1
  31. package/dist/df1e8683e7eda7b2b79c.js +29 -0
  32. package/package.json +5 -4
  33. package/src/artifact/CLAUDE.md +4 -0
  34. package/src/artifact/artifact-evidence.js +63 -0
  35. package/src/artifact/cosign.js +61 -0
  36. package/src/artifact/engine-source.js +72 -0
  37. package/src/artifact/oci-layout.js +47 -0
  38. package/src/artifact/registry.js +213 -0
  39. package/src/capabilities/tool-registry.js +2 -0
  40. package/src/lineage/CLAUDE.md +4 -0
  41. package/src/lineage/identity-token.js +11 -0
  42. package/src/lineage/observation-adapters.js +13 -0
  43. package/src/lineage/runtime-edge-states.js +139 -0
  44. package/src/lineage/runtime-explorer-view.js +82 -0
  45. package/src/lineage/runtime-observation.js +11 -0
  46. package/src/mcp/CLAUDE.md +3 -1
  47. package/src/mcp/proof-tools.js +132 -0
  48. package/src/mcp/server.js +1 -1
  49. package/src/mcp/tools.js +3 -1
  50. package/src/posture/CLAUDE.md +23 -0
  51. package/src/posture/artifact-registry.js +4 -0
  52. package/src/posture/dnr/attack-facts.js +31 -0
  53. package/src/posture/dnr/cli.js +138 -0
  54. package/src/posture/dnr/detection-ir.js +123 -0
  55. package/src/posture/dnr/exposure-window.js +134 -0
  56. package/src/posture/dnr/hunt.js +84 -0
  57. package/src/posture/dnr/log-reader.js +189 -0
  58. package/src/posture/dnr/matchers.js +90 -0
  59. package/src/posture/dnr/outputs.js +262 -0
  60. package/src/posture/dnr/payload-classes.js +120 -0
  61. package/src/posture/dnr/redact.js +25 -0
  62. package/src/posture/dnr/store.js +57 -0
  63. package/src/posture/dnr/validate.js +64 -0
  64. package/src/posture/dnr/view.js +51 -0
  65. package/src/posture/evaluation/lab/arm-ollama.js +88 -0
  66. package/src/posture/evaluation/lab/arms.js +142 -0
  67. package/src/posture/evaluation/lab/cli.js +135 -0
  68. package/src/posture/evaluation/lab/dataset.js +139 -0
  69. package/src/posture/evaluation/lab/materialize.js +44 -0
  70. package/src/posture/evaluation/lab/neutralize.js +144 -0
  71. package/src/posture/evaluation/lab/report.js +176 -0
  72. package/src/posture/evaluation/lab/run.js +225 -0
  73. package/src/posture/evaluation/lab/score.js +135 -0
  74. package/src/posture/evaluation/lab/scoreboard.js +48 -0
  75. package/src/posture/evaluation/lab/stats.js +41 -0
  76. package/src/posture/evaluation/lab/store.js +53 -0
  77. package/src/posture/fleet/cli.js +248 -63
  78. package/src/posture/fleet/discover-edges.js +135 -0
  79. package/src/posture/fleet/enterprise-graph.js +148 -0
  80. package/src/posture/fleet/fleet-graph.js +9 -4
  81. package/src/posture/fleet/fleet-manifest.js +50 -5
  82. package/src/posture/fleet/job-runner.js +153 -0
  83. package/src/posture/fleet/job-store.js +136 -0
  84. package/src/posture/fleet/org-health.js +56 -0
  85. package/src/posture/fleet/scan-cache.js +112 -0
  86. package/src/posture/fleet/scan-child.js +29 -0
  87. package/src/posture/proof-fabric/cli.js +34 -6
  88. package/src/posture/proof-fabric/container.js +57 -0
  89. package/src/posture/proof-fabric/fix-proof.js +2 -1
  90. package/src/posture/proof-fabric/generate-python.js +129 -0
  91. package/src/posture/proof-fabric/generate.js +213 -0
  92. package/src/posture/proof-fabric/reproducer.js +3 -0
  93. package/src/posture/proof-fabric/runner.js +20 -11
  94. package/src/posture/proof-fabric/siblings.js +77 -0
  95. package/src/posture/routing/policy-router.js +103 -0
  96. package/src/posture/rule-compiler/cli.js +64 -6
  97. package/src/posture/rule-compiler/corpus.js +10 -2
  98. package/src/posture/rule-compiler/mutation.js +72 -1
  99. package/src/posture/rule-compiler/promotion.js +21 -5
  100. package/src/posture/rule-compiler/proposal.js +132 -0
  101. package/src/posture/rule-compiler/store.js +16 -0
@@ -0,0 +1,509 @@
1
+ export const id = 4168;
2
+ export const ids = [4168];
3
+ export const modules = {
4
+
5
+ /***/ 12090:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
+ /* harmony export */ KF: () => (/* binding */ toProofTier),
10
+ /* harmony export */ g3: () => (/* binding */ stateRank),
11
+ /* harmony export */ jn: () => (/* binding */ fromProofTier),
12
+ /* harmony export */ np: () => (/* binding */ advance)
13
+ /* harmony export */ });
14
+ /* unused harmony exports EVIDENCE_STATES, COMPLETENESS */
15
+ // Evidence state ladder for the Universal Exploit Proof Fabric.
16
+ //
17
+ // Evidence state is SEPARATE from severity and confidence. It extends, never replaces, the vocabulary that already
18
+ // exists: `proof-tier.js` (execution-proven / proof-failed / taint-proven / unproven) and the fix-verify legs
19
+ // (`verifiedFull`, `degradedLegs`). `toProofTier` / `fromProofTier` are the explicit bridges.
20
+ //
21
+ // Transitions are guarded: a state can only be reached from the state directly before it (or by dropping back), so no
22
+ // caller can jump a finding to EXPLOIT_CONFIRMED without passing REPRODUCED, or to FIX_VERIFIED without
23
+ // FIX_REPLAY_BLOCKED. A degraded or incomplete run NEVER advances a state.
24
+ const EVIDENCE_STATES = Object.freeze([
25
+ 'CANDIDATE',
26
+ 'STATICALLY_CORROBORATED',
27
+ 'REPRODUCER_GENERATED',
28
+ 'REPRODUCED',
29
+ 'EXPLOIT_CONFIRMED',
30
+ 'FIX_REPLAY_BLOCKED',
31
+ 'FIX_VERIFIED',
32
+ ]);
33
+
34
+ const stateRank = (s) => EVIDENCE_STATES.indexOf(s);
35
+
36
+ const REQUIRES_PREDECESSOR = Object.freeze(Object.fromEntries(EVIDENCE_STATES.map((s, i) => [s, i === 0 ? null : EVIDENCE_STATES[i - 1]])));
37
+
38
+ /**
39
+ * Advance `from` to `to`. Returns { ok, state, reason }. Moving up requires `to` to be exactly the next rung; moving
40
+ * down or staying is always allowed (evidence can be lost, never invented). Unknown states are rejected.
41
+ */
42
+ function advance(from, to) {
43
+ if (!EVIDENCE_STATES.includes(from)) return { ok: false, state: 'CANDIDATE', reason: `unknown current state: ${String(from)}` };
44
+ if (!EVIDENCE_STATES.includes(to)) return { ok: false, state: from, reason: `unknown target state: ${String(to)}` };
45
+ if (stateRank(to) <= stateRank(from)) return { ok: true, state: to, reason: null };
46
+ if (REQUIRES_PREDECESSOR[to] !== from) return { ok: false, state: from, reason: `cannot reach ${to} from ${from}: ${REQUIRES_PREDECESSOR[to]} is required first` };
47
+ return { ok: true, state: to, reason: null };
48
+ }
49
+
50
+ // Bridges to the older vocabulary so existing consumers keep working.
51
+ function toProofTier(state) {
52
+ const r = stateRank(state);
53
+ if (r >= stateRank('EXPLOIT_CONFIRMED')) return 'execution-proven';
54
+ if (r >= stateRank('STATICALLY_CORROBORATED')) return 'taint-proven';
55
+ return 'unproven';
56
+ }
57
+
58
+ function fromProofTier(tier) {
59
+ if (tier === 'taint-proven') return 'STATICALLY_CORROBORATED';
60
+ // execution-proven under the older single-run marker path is one run, not the 3/3 + independent replay the fabric
61
+ // requires, so it maps to REPRODUCED and never to EXPLOIT_CONFIRMED.
62
+ if (tier === 'execution-proven') return 'REPRODUCED';
63
+ return 'CANDIDATE';
64
+ }
65
+
66
+ // Completeness vocabulary shared with fix-verify: FULL only when nothing was skipped.
67
+ const COMPLETENESS = Object.freeze(['FULL', 'DEGRADED', 'INCOMPLETE']);
68
+
69
+
70
+ /***/ }),
71
+
72
+ /***/ 44168:
73
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
74
+
75
+ // ESM COMPAT FLAG
76
+ __webpack_require__.r(__webpack_exports__);
77
+
78
+ // EXPORTS
79
+ __webpack_require__.d(__webpack_exports__, {
80
+ cmdRules: () => (/* binding */ cmdRules)
81
+ });
82
+
83
+ // EXTERNAL MODULE: external "node:fs"
84
+ var external_node_fs_ = __webpack_require__(73024);
85
+ // EXTERNAL MODULE: ./src/posture/state-dir.js
86
+ var state_dir = __webpack_require__(31174);
87
+ // EXTERNAL MODULE: ./src/posture/rule-compiler/ir.js
88
+ var rule_compiler_ir = __webpack_require__(87539);
89
+ // EXTERNAL MODULE: ./src/posture/proof-fabric/states.js
90
+ var states = __webpack_require__(12090);
91
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/eligibility.js
92
+ // X-eligibility (PRD 3 "Eligibility"): a finding may enter synthesis only with a stable id, a vulnerable span, a
93
+ // CWE/family, code-flow evidence, and deterministic corroboration OR exploit proof. Reuses the existing
94
+ // vocabularies rather than inventing a third: proof-fabric's evidence-state ladder when present, else the older
95
+ // proof-tier (`taint-proven`/`execution-proven`), else the finding's own `parser` (an IR-TAINT/MULTI-SINK parser
96
+ // origin is code-flow evidence even with no execution).
97
+
98
+
99
+ const ANALYSED_PARSERS = new Set(['IR-TAINT', 'MULTI-SINK']);
100
+
101
+ function checkEligibility(finding, { proofState = null } = {}) {
102
+ const reasons = [];
103
+ if (!finding?.stableId && !finding?.id) reasons.push('no stable id');
104
+ if (finding?.file == null || finding?.line == null) reasons.push('no vulnerable span (file:line)');
105
+ if (!finding?.cwe && !finding?.family) reasons.push('no CWE or family');
106
+ const hasFlowEvidence = ANALYSED_PARSERS.has(finding?.parser) || !!finding?.snippet;
107
+ if (!hasFlowEvidence) reasons.push('no code-flow evidence (parser not IR-TAINT/MULTI-SINK, no snippet)');
108
+
109
+ let evidenceState = 'none';
110
+ if (proofState && (0,states/* stateRank */.g3)(proofState) >= (0,states/* stateRank */.g3)('EXPLOIT_CONFIRMED')) evidenceState = 'execution-proven';
111
+ else if (finding?.proofTier === 'execution-proven') evidenceState = 'execution-proven';
112
+ else if (finding?.proofTier === 'taint-proven' || ANALYSED_PARSERS.has(finding?.parser)) evidenceState = 'taint-proven';
113
+ if (evidenceState === 'none') reasons.push('no deterministic corroboration or exploit proof');
114
+
115
+ return { eligible: reasons.length === 0, reasons, evidenceState };
116
+ }
117
+
118
+ // EXTERNAL MODULE: ./src/posture/rule-compiler/corpus.js
119
+ var rule_compiler_corpus = __webpack_require__(43556);
120
+ // EXTERNAL MODULE: ./src/posture/rule-compiler/promotion.js
121
+ var promotion = __webpack_require__(57711);
122
+ // EXTERNAL MODULE: external "node:crypto"
123
+ var external_node_crypto_ = __webpack_require__(77598);
124
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/lifecycle.js
125
+ // Rule lifecycle ledger: DRAFT -> CANDIDATE -> VALIDATED -> PROMOTED -> DEPRECATED/ROLLED_BACK.
126
+ //
127
+ // Append-only, hash-chained (same idiom as remediation-ledger.js / invariants/lifecycle.js): each entry links the
128
+ // previous entry's hash, so a dropped or edited middle record breaks the chain and `verifyLedger` catches it. A
129
+ // rule cannot promote itself: `transition` only records a transition a caller already decided; `advance`-style
130
+ // guarding on VALID edges lives here so no caller can jump DRAFT straight to PROMOTED.
131
+
132
+
133
+
134
+ const LEDGER_SCHEMA = 'agentic-security/rule-lifecycle-ledger';
135
+ const EDGES = Object.freeze({
136
+ DRAFT: ['CANDIDATE'], CANDIDATE: ['VALIDATED', 'DRAFT'], VALIDATED: ['PROMOTED', 'DRAFT'],
137
+ PROMOTED: ['DEPRECATED', 'ROLLED_BACK'], DEPRECATED: [], ROLLED_BACK: ['CANDIDATE'],
138
+ });
139
+
140
+ const hashOf = (entry) => (0,external_node_crypto_.createHash)('sha256').update(JSON.stringify(entry)).digest('hex');
141
+
142
+ function newLedger() { return { schema: LEDGER_SCHEMA, entries: [] }; }
143
+
144
+ function currentState(ledger, ruleId) {
145
+ for (let i = ledger.entries.length - 1; i >= 0; i--) if (ledger.entries[i].ruleId === ruleId) return ledger.entries[i].to;
146
+ return null;
147
+ }
148
+
149
+ /**
150
+ * Record a transition. Refuses an edge not in EDGES, and refuses DRAFT->DRAFT re-entry for a rule that has never
151
+ * existed (the first entry for a rule id must be `from: null, to: 'DRAFT'`).
152
+ */
153
+ function recordTransition(ledger, { ruleId, from, to, reason, evidence = null, actor }) {
154
+ if (!rule_compiler_ir/* RULE_STATES */.UQ.includes(to)) return { ok: false, reason: `unknown target state: ${to}` };
155
+ const cur = currentState(ledger, ruleId);
156
+ if (cur === null) {
157
+ if (from !== null || to !== 'DRAFT') return { ok: false, reason: 'first transition for a rule must be null -> DRAFT' };
158
+ } else {
159
+ if (from !== cur) return { ok: false, reason: `stale transition: current state is ${cur}, not ${from}` };
160
+ if (!EDGES[cur].includes(to)) return { ok: false, reason: `cannot go from ${cur} to ${to}` };
161
+ }
162
+ const prevHash = ledger.entries.length ? ledger.entries[ledger.entries.length - 1].entryHash : null;
163
+ const entry = { ruleId, from: cur, to, reason: reason ?? null, evidence, actor: actor ?? 'unknown', at: new Date().toISOString(), prevHash };
164
+ entry.entryHash = hashOf({ ...entry, entryHash: undefined });
165
+ ledger.entries.push(entry);
166
+ return { ok: true, entry };
167
+ }
168
+
169
+ function verifyLedger(ledger) {
170
+ let prevHash = null;
171
+ for (const e of ledger.entries) {
172
+ if (e.prevHash !== prevHash) return { ok: false, reason: 'chain broken: prevHash mismatch' };
173
+ const recomputed = hashOf({ ...e, entryHash: undefined });
174
+ if (recomputed !== e.entryHash) return { ok: false, reason: `entry hash mismatch for ${e.ruleId} at ${e.at}` };
175
+ prevHash = e.entryHash;
176
+ }
177
+ return { ok: true };
178
+ }
179
+
180
+ function historyFor(ledger, ruleId) { return ledger.entries.filter((e) => e.ruleId === ruleId); }
181
+ function stateOf(ledger, ruleId) { return currentState(ledger, ruleId); }
182
+
183
+ // EXTERNAL MODULE: external "node:path"
184
+ var external_node_path_ = __webpack_require__(76760);
185
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/store.js
186
+ // Persistence for the rule compiler: one directory per rule under `.agentic-security/rule-compiler/<id>/`
187
+ // (`ir.json`, `ledger.json`, `evaluation.json`), the promoted custom-rule document at
188
+ // `.agentic-security/rules/<id>.yml` (so the EXISTING `loadCustomRules`/`rule test` machinery picks it up with no
189
+ // change), and a regression fixture pair at `.agentic-security/rule-compiler/fixtures/<id>/{vulnerable,clean}/`
190
+ // using the SAME filename convention `runRuleTests` already reads (`vulnerable`/`clean` in the path).
191
+
192
+
193
+
194
+
195
+
196
+
197
+ const DIR = 'rule-compiler';
198
+ const EXT = { javascript: 'js', typescript: 'ts', python: 'py', go: 'go', ruby: 'rb', java: 'java', rust: 'rs', csharp: 'cs', php: 'php', any: 'txt' };
199
+
200
+ function ruleDir(scanRoot, id) { return (0,state_dir.statePath)(scanRoot, DIR, id); }
201
+
202
+ function loadLedger(scanRoot) {
203
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
204
+ if (!external_node_fs_.existsSync(f)) return newLedger();
205
+ try {
206
+ const ledger = JSON.parse(external_node_fs_.readFileSync(f, 'utf8'));
207
+ const v = verifyLedger(ledger);
208
+ return v.ok ? ledger : { ...newLedger(), tampered: true, tamperReason: v.reason };
209
+ } catch { return newLedger(); }
210
+ }
211
+
212
+ function saveLedger(scanRoot, ledger) {
213
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
214
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
215
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ledger, null, 2)) };
216
+ }
217
+
218
+ function saveIR(scanRoot, ir) {
219
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
220
+ const f = external_node_path_.join(ruleDir(scanRoot, ir.id), 'ir.json');
221
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ir, null, 2)), file: f };
222
+ }
223
+
224
+ function loadIR(scanRoot, id) {
225
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'ir.json');
226
+ try { return JSON.parse(external_node_fs_.readFileSync(f, 'utf8')); } catch { return null; }
227
+ }
228
+
229
+ function saveJson(scanRoot, id, name, doc) {
230
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
231
+ const f = external_node_path_.join(ruleDir(scanRoot, id), name);
232
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(doc, null, 2)), file: f };
233
+ }
234
+ function loadJson(scanRoot, id, name) { try { return JSON.parse(external_node_fs_.readFileSync(external_node_path_.join(ruleDir(scanRoot, id), name), 'utf8')); } catch { return null; } }
235
+ /** The corpus a rule was synthesized on, kept so `rules evaluate <id>` needs no flag and the evidence is the same corpus. */
236
+ const saveCorpus = (r, id, spec) => saveJson(r, id, 'corpus.json', spec);
237
+ const loadCorpus = (r, id) => loadJson(r, id, 'corpus.json');
238
+ /** Every synthesis attempt: strategy, match, score and why it did not pass. */
239
+ const saveSynthesis = (r, id, syn) => saveJson(r, id, 'synthesis.json', syn);
240
+ const loadSynthesis = (r, id) => loadJson(r, id, 'synthesis.json');
241
+ /** The rule's provenance record (PRD 3 requirement 7). */
242
+ const saveProvenance = (r, id, doc) => saveJson(r, id, 'provenance.json', doc);
243
+ const loadProvenance = (r, id) => loadJson(r, id, 'provenance.json');
244
+
245
+ function saveEvaluation(scanRoot, id, evaluation) {
246
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
247
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'evaluation.json');
248
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(evaluation, null, 2)) };
249
+ }
250
+
251
+ /** Write the regression fixtures a promoted rule needs: the SAME vulnerable/clean convention `runRuleTests`
252
+ * already reads, scored against the exact corpus the rule was promoted on. */
253
+ function writeFixtures(scanRoot, ir, corpus) {
254
+ const ext = EXT[ir.languages[0]] || 'txt';
255
+ const base = external_node_path_.join(ruleDir(scanRoot, ir.id), 'fixtures');
256
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
257
+ const written = [];
258
+ for (const p of corpus.positives) {
259
+ const f = external_node_path_.join(base, 'vulnerable', `${p.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
260
+ if ((0,state_dir.safeWriteState)(f, p.code)) written.push(f);
261
+ }
262
+ for (const n of corpus.negatives) {
263
+ const f = external_node_path_.join(base, 'clean', `${n.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
264
+ if ((0,state_dir.safeWriteState)(f, n.code)) written.push(f);
265
+ }
266
+ return { ok: true, written, glob: external_node_path_.join(base, '**', '*') };
267
+ }
268
+
269
+ /** Promote: write the compiled custom-rule document to the live rules directory. Does not touch the ledger —
270
+ * the caller records the PROMOTED transition itself, so a failed write here can never produce an inconsistent
271
+ * "promoted but not live" or "live but not recorded" state silently. */
272
+ function publishCustomRule(scanRoot, ir) {
273
+ const { ok, doc, errs } = (0,rule_compiler_ir/* compileToCustomRule */.Mo)(ir);
274
+ if (!ok) return { ok: false, reason: `invalid rule IR: ${errs.join('; ')}` };
275
+ if (!(0,state_dir.ensureStateDir)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
276
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${ir.id}.yml`);
277
+ const yamlText = [
278
+ `# Compiled by the rule compiler from finding ${ir.provenance.originatingFindingId} (${ir.provenance.evidenceState}).`,
279
+ `- id: ${doc.id}`,
280
+ ` title: ${JSON.stringify(doc.title)}`,
281
+ ` severity: ${doc.severity}`,
282
+ ` cwe: ${doc.cwe}`,
283
+ ` languages: [${doc.languages.join(', ')}]`,
284
+ ` match:`,
285
+ ...(doc.match.pattern ? [` pattern: ${JSON.stringify(doc.match.pattern)}`] : []),
286
+ ...(doc.match.allOf ? [` allOf:`, ...doc.match.allOf.map((p) => ` - ${JSON.stringify(p)}`), ` window: ${doc.match.window}`] : []),
287
+ ...(doc.match.notMatch ? [` notMatch: ${JSON.stringify(doc.match.notMatch)}`] : []),
288
+ ` message: ${JSON.stringify(doc.message)}`,
289
+ '',
290
+ ].join('\n');
291
+ return { ok: (0,state_dir.safeWriteState)(f, yamlText), file: f };
292
+ }
293
+
294
+ function unpublishCustomRule(scanRoot, id) {
295
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${id}.yml`);
296
+ try { if (external_node_fs_.existsSync(f)) external_node_fs_.unlinkSync(f); return { ok: true }; } catch (e) { return { ok: false, reason: e.message }; }
297
+ }
298
+
299
+ // EXTERNAL MODULE: ./src/posture/rule-compiler/proposal.js
300
+ var proposal = __webpack_require__(47838);
301
+ // EXTERNAL MODULE: ./src/posture/rule-compiler/mutation.js
302
+ var mutation = __webpack_require__(85127);
303
+ // EXTERNAL MODULE: ./src/posture/proof-fabric/reproducer.js
304
+ var reproducer = __webpack_require__(37055);
305
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/cli.js
306
+ // CLI surface: `agentic-security rules synthesize|evaluate|promote|status|rollback`.
307
+ //
308
+ // Distinct from the pre-existing `labs synthesize-rule` (posture/rule-synthesis.js), which proposes SUPPRESSION
309
+ // rules from repeated false-positive triage verdicts — a different input, a different output and a different
310
+ // command group on purpose, so the two are never confused at the CLI.
311
+ //
312
+ // Non-interactive by construction: no command reads stdin, every corpus evaluation is bounded (no network, no
313
+ // model call — this is the deterministic half; a model may PROPOSE the candidate pattern this CLI is handed, but
314
+ // it never decides promotion).
315
+
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+ function loadFinding(root, id) {
328
+ const p = (0,state_dir.statePath)(root, 'last-scan.json');
329
+ if (!external_node_fs_.existsSync(p)) return null;
330
+ const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
331
+ return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
332
+ }
333
+
334
+ function readJsonArg(pathOrInline) {
335
+ if (!pathOrInline) return null;
336
+ try { return JSON.parse(external_node_fs_.existsSync(pathOrInline) ? external_node_fs_.readFileSync(pathOrInline, 'utf8') : pathOrInline); } catch { return null; }
337
+ }
338
+
339
+ async function cmdRules(args, root) {
340
+ const sub = args._[1];
341
+ if (sub === 'synthesize') return cmdSynthesize(args, root);
342
+ if (sub === 'evaluate') return cmdEvaluate(args, root);
343
+ if (sub === 'promote') return cmdPromote(args, root);
344
+ if (sub === 'status') return cmdStatus(args, root);
345
+ if (sub === 'rollback') return cmdRollback(args, root);
346
+ if (sub === 'cost') return cmdCost(args, root);
347
+ console.error('usage: rules synthesize <finding-id> --spec <file.json> [--auto] [--max-attempts N] | evaluate <rule-id> | promote <rule-id> | status [rule-id] | rollback <rule-id> | cost <rule-id>');
348
+ return 4;
349
+ }
350
+
351
+ // `--spec` carries exactly what a model or a human proposed: id/title/severity/cwe/family/languages/match/
352
+ // remediation plus the corpus inputs (originalCode/patchedCode/nearbyCleanCode/protectedVariantsCode). This
353
+ // command never invents a pattern; it only drafts the IR, checks eligibility and records DRAFT->CANDIDATE.
354
+ async function cmdSynthesize(args, root) {
355
+ const findingId = args._[2];
356
+ const spec = readJsonArg(args.flags.spec);
357
+ if (!findingId || !spec) { console.error('usage: rules synthesize <finding-id> --spec <file.json>'); return 4; }
358
+ const finding = loadFinding(root, findingId);
359
+ if (!finding) { console.error(`Finding ${findingId} not found in last scan.`); return 4; }
360
+ const elig = checkEligibility(finding, { proofState: args.flags['proof-state'] || null });
361
+ if (!elig.eligible) { console.error(`Not eligible for rule synthesis: ${elig.reasons.join('; ')}`); return 4; }
362
+
363
+ // The candidate pattern is the model's or the person's, when they gave one. Without one, or with --auto, the synthesis loop proposes
364
+ // from the vulnerable and patched code, scores each attempt on the real corpus and its mutations, and revises (see proposal.js).
365
+ let finalSpec = spec; let synthesis = null;
366
+ const corpusSpec = { originalCode: spec.originalCode, patchedCode: spec.patchedCode ?? null, nearbyCleanCode: spec.nearbyCleanCode ?? [], protectedVariantsCode: spec.protectedVariantsCode ?? [] };
367
+ const leak = (0,promotion/* checkLeakage */.r_)(JSON.stringify(corpusSpec), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [], fileNames: spec.fileNames ?? [] });
368
+ if (!leak.ok) { console.error(`Refusing: the material for this rule shows benchmark or answer-key signals (${leak.offendingTerms.join('; ')}). Nothing was written.`); return 4; }
369
+ if (args.flags.auto || !spec.match) {
370
+ if (!isStr(spec.originalCode)) { console.error('Automatic proposal needs originalCode (the vulnerable snippet) in the spec.'); return 4; }
371
+ const { id, title, severity, cwe, family, languages, remediation } = spec;
372
+ synthesis = (0,proposal/* synthesizeCandidate */._7)({ base: { id, title, severity, cwe, family, languages, remediation, originatingFindingId: finding.stableId ?? finding.id, evidenceState: elig.evidenceState }, corpusSpec, proposed: spec.match ?? null, maxAttempts: Number(args.flags['max-attempts']) || 6, leakageOk: true });
373
+ for (const a of synthesis.attempts) console.log(` attempt ${a.n}: ${a.strategy.padEnd(34)} ${a.valid ? `precision ${fmtPct(a.score.precision)} recall ${fmtPct(a.score.recall)} protected-failures ${a.score.protectedFailures}${a.pass ? ' PASS' : ''}` : `invalid (${a.errors[0]})`}`);
374
+ if (!synthesis.best) { console.error('No valid candidate could be proposed from this material.'); return 1; }
375
+ finalSpec = { ...spec, match: synthesis.best.match };
376
+ console.log(synthesis.best.pass ? ` candidate meets the promotion gate on this corpus (not yet recorded as VALIDATED).` : ` no attempt met the gate; the best is kept as a CANDIDATE only: ${synthesis.best.reasons.join('; ')}`);
377
+ }
378
+ const ir = (0,rule_compiler_ir/* draftRuleIR */.pc)({ ...finalSpec, originatingFindingId: finding.stableId ?? finding.id, originatingCommit: spec.originatingCommit ?? null, evidenceState: elig.evidenceState });
379
+ const errs = (0,rule_compiler_ir/* validateRuleIR */.g)(ir);
380
+ if (errs.length) { console.error(`Invalid rule: ${errs.join('; ')}`); return 4; }
381
+
382
+ const ledger = loadLedger(root);
383
+ const draft = recordTransition(ledger, { ruleId: ir.id, from: null, to: 'DRAFT', reason: `drafted from ${findingId}`, actor: args.flags.actor || 'agent' });
384
+ if (!draft.ok) { console.error(draft.reason); return 4; }
385
+ const cand = recordTransition(ledger, { ruleId: ir.id, from: 'DRAFT', to: 'CANDIDATE', reason: 'eligibility passed', evidence: { eligibility: elig }, actor: args.flags.actor || 'agent' });
386
+ saveLedger(root, ledger);
387
+ saveIR(root, { ...ir, state: 'CANDIDATE' });
388
+ saveCorpus(root, ir.id, { ...corpusSpec, fileNames: spec.fileNames ?? [], discoveryCost: spec.discoveryCost ?? (args.flags['discovery-cost-usd'] ? { usd: Number(args.flags['discovery-cost-usd']), tokens: Number(args.flags['discovery-tokens']) || null, model: spec.model ?? null } : null) });
389
+ if (synthesis) saveSynthesis(root, ir.id, { attempts: synthesis.attempts, best: synthesis.best });
390
+ console.log(`Rule ${ir.id}: DRAFT -> CANDIDATE (digest ${(0,rule_compiler_ir/* ruleIRDigest */.GE)(ir).slice(0, 12)})`);
391
+ if (!cand.ok) console.error(cand.reason);
392
+ return 0;
393
+ }
394
+
395
+ async function cmdEvaluate(args, root) {
396
+ const id = args._[2];
397
+ if (!id) { console.error('usage: rules evaluate <rule-id> --corpus <file.json>'); return 4; }
398
+ const ir = loadIR(root, id);
399
+ if (!ir) { console.error(`No rule IR found for ${id}. Run rules synthesize first.`); return 4; }
400
+ const corpusSpec = readJsonArg(args.flags.corpus) ?? loadCorpus(root, id);
401
+ if (!corpusSpec) { console.error('No corpus supplied. Pass --corpus <file.json> with originalCode (and optionally patchedCode/nearbyCleanCode/protectedVariantsCode).'); return 4; }
402
+ const corpus = (0,rule_compiler_corpus/* buildCorpus */.F)(ir, corpusSpec);
403
+ const leakage = (0,promotion/* checkLeakage */.r_)(JSON.stringify({ ...corpusSpec, fileNames: undefined, discoveryCost: undefined }), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [], fileNames: corpusSpec.fileNames ?? [] });
404
+ const gate = (0,promotion/* gatePromotion */.z)({ ir, corpus, leakageCheck: leakage, thresholds: args.flags.thresholds ? readJsonArg(args.flags.thresholds) : promotion/* PROMOTION_DEFAULTS */.V2 });
405
+
406
+ const ledger = loadLedger(root);
407
+ const cur = stateOf(ledger, id);
408
+ if (gate.pass && cur === 'CANDIDATE') recordTransition(ledger, { ruleId: id, from: 'CANDIDATE', to: 'VALIDATED', reason: 'promotion gate passed', evidence: { score: gate.evaluation.score }, actor: args.flags.actor || 'agent' });
409
+ saveLedger(root, ledger);
410
+ saveEvaluation(root, id, gate);
411
+ const corpusHash = (list) => (0,reproducer/* sha256 */.sc)(JSON.stringify(list.map((x) => [x.label, x.code]).sort()));
412
+ const prev = loadProvenance(root, id);
413
+ saveProvenance(root, id, {
414
+ schema: 'agentic-security/rule-provenance', version: 1, ruleId: id, ruleVersion: 1, ruleHash: (0,rule_compiler_ir/* ruleIRDigest */.GE)(ir),
415
+ originatingFinding: ir.provenance.originatingFindingId, originatingCommit: ir.provenance.originatingCommit, evidenceState: ir.provenance.evidenceState,
416
+ generatingModel: ir.provenance.model, promptConfigVersion: ir.provenance.promptConfigVersion,
417
+ positiveCorpusHash: corpusHash(corpus.positives), negativeCorpusHash: corpusHash(corpus.negatives),
418
+ benchmarkResults: { precision: gate.evaluation.score.precision, recall: gate.evaluation.score.recall, tp: gate.evaluation.score.tp, fp: gate.evaluation.score.fp, fn: gate.evaluation.score.fn, tn: gate.evaluation.score.tn, protectedFailures: gate.evaluation.score.protectedFailures, thresholds: gate.evaluation.thresholds, gate: gate.pass ? 'passed' : 'failed', reasons: gate.reasons },
419
+ leakageCheck: leakage, mutatorCoverage: (0,mutation/* mutatorCoverage */.xv)(corpusSpec.originalCode), discoveryCost: corpusSpec.discoveryCost ?? prev?.discoveryCost ?? null,
420
+ promotionEvent: prev?.promotionEvent ?? null, evaluatedAt: new Date().toISOString(),
421
+ });
422
+ if (args.flags.json) console.log(JSON.stringify(gate, null, 2));
423
+ else {
424
+ console.log(`Rule ${id}: ${gate.pass ? 'VALIDATED' : 'gate FAILED'}`);
425
+ console.log(` precision ${fmtPct(gate.evaluation.score.precision)} recall ${fmtPct(gate.evaluation.score.recall)} protected-failures ${gate.evaluation.score.protectedFailures}`);
426
+ for (const r of gate.reasons) console.log(` - ${r}`);
427
+ }
428
+ if (gate.pass) { const f = writeFixtures(root, ir, corpus); if (f.ok) console.log(` regression fixtures written: ${f.written.length} file(s) under .agentic-security/rule-compiler/${id}/fixtures/`); }
429
+ return gate.pass ? 0 : 1;
430
+ }
431
+ function isStr(v) { return typeof v === 'string' && v.length > 0; }
432
+ const fmtPct = (n) => (n == null ? 'unmeasured' : `${(n * 100).toFixed(1)}%`);
433
+
434
+ async function cmdPromote(args, root) {
435
+ const id = args._[2];
436
+ if (!id) { console.error('usage: rules promote <rule-id>'); return 4; }
437
+ const ledger = loadLedger(root);
438
+ if (ledger.tampered) { console.error(`Refusing: rule lifecycle ledger failed its integrity check (${ledger.tamperReason}).`); return 4; }
439
+ if (stateOf(ledger, id) !== 'VALIDATED') { console.error(`Rule ${id} is not VALIDATED (run rules evaluate first); refusing to promote.`); return 4; }
440
+ const ir = loadIR(root, id);
441
+ if (!ir) { console.error(`No rule IR found for ${id}.`); return 4; }
442
+ const pub = publishCustomRule(root, ir);
443
+ if (!pub.ok) { console.error(`Promotion refused: ${pub.reason}`); return 4; }
444
+ const t = recordTransition(ledger, { ruleId: id, from: 'VALIDATED', to: 'PROMOTED', reason: args.flags.reason || 'promoted', actor: args.flags.actor || 'operator' });
445
+ saveLedger(root, ledger);
446
+ const prov = loadProvenance(root, id);
447
+ if (prov) saveProvenance(root, id, { ...prov, promotionEvent: { at: new Date().toISOString(), actor: args.flags.actor || 'operator', reason: args.flags.reason || 'promoted', ruleHash: (0,rule_compiler_ir/* ruleIRDigest */.GE)(ir) } });
448
+ console.log(`Rule ${id}: VALIDATED -> PROMOTED. Published to ${pub.file}.`);
449
+ if (!t.ok) console.error(t.reason);
450
+ return 0;
451
+ }
452
+
453
+ async function cmdRollback(args, root) {
454
+ const id = args._[2];
455
+ if (!id) { console.error('usage: rules rollback <rule-id> [--reason text]'); return 4; }
456
+ const ledger = loadLedger(root);
457
+ const cur = stateOf(ledger, id);
458
+ if (cur !== 'PROMOTED') { console.error(`Rule ${id} is not PROMOTED (current: ${cur ?? 'unknown'}); nothing to roll back.`); return 4; }
459
+ const un = unpublishCustomRule(root, id);
460
+ const t = recordTransition(ledger, { ruleId: id, from: 'PROMOTED', to: 'ROLLED_BACK', reason: args.flags.reason || 'operator rollback', actor: args.flags.actor || 'operator' });
461
+ saveLedger(root, ledger);
462
+ console.log(`Rule ${id}: PROMOTED -> ROLLED_BACK.${un.ok ? '' : ` (warning: could not remove published rule file: ${un.reason})`}`);
463
+ return t.ok ? 0 : 1;
464
+ }
465
+
466
+ async function cmdStatus(args, root) {
467
+ const ledger = loadLedger(root);
468
+ const id = args._[2];
469
+ if (id) {
470
+ const h = historyFor(ledger, id);
471
+ if (!h.length) { console.error(`No history for rule ${id}.`); return 4; }
472
+ if (args.flags.json) console.log(JSON.stringify(h, null, 2));
473
+ else { console.log(`Rule ${id}: ${stateOf(ledger, id)}`); for (const e of h) console.log(` ${e.at} ${e.from ?? '(new)'} -> ${e.to} (${e.reason || ''})`);
474
+ const syn = loadSynthesis(root, id);
475
+ if (syn?.attempts?.length) { console.log(` synthesis: ${syn.attempts.length} attempt(s), best ${syn.best ? `${syn.best.strategy}${syn.best.pass ? ' (met the gate)' : ' (did not meet the gate)'}` : 'none'}`); }
476
+ }
477
+ return 0;
478
+ }
479
+ const ids = [...new Set(ledger.entries.map((e) => e.ruleId))];
480
+ if (args.flags.json) { console.log(JSON.stringify(ids.map((rid) => ({ id: rid, state: stateOf(ledger, rid) })), null, 2)); return 0; }
481
+ if (!ids.length) { console.log('No rules in the lifecycle ledger yet.'); return 0; }
482
+ for (const rid of ids) console.log(` ${rid.padEnd(40)} ${stateOf(ledger, rid)}`);
483
+ return 0;
484
+ }
485
+
486
+ // PRD 3 business metric: what the first, model-assisted discovery cost, against what every later deterministic detection costs.
487
+ // The discovery cost is whatever the agent run reported for it (recorded at synthesis); a deterministic detection makes no model
488
+ // call and is $0 of model spend. The count of later detections is read from the LAST scan only, so it is a floor, not a history.
489
+ async function cmdCost(args, root) {
490
+ const id = args._[2];
491
+ if (!id) { console.error('usage: rules cost <rule-id>'); return 4; }
492
+ const prov = loadProvenance(root, id);
493
+ if (!prov) { console.error(`No provenance for ${id}. Run rules evaluate first.`); return 4; }
494
+ let detections = null;
495
+ try { const last = JSON.parse(external_node_fs_.readFileSync((0,state_dir.statePath)(root, 'last-scan.json'), 'utf8')); detections = (last.findings || []).filter((f) => String(f.id || '').startsWith(`custom:rule-compiler/${id}:`)).length; } catch { /* no scan */ }
496
+ const first = prov.discoveryCost;
497
+ const out = { ruleId: id, firstDiscovery: first ? { usd: first.usd ?? null, tokens: first.tokens ?? null, model: first.model ?? null } : null, laterDeterministicDetections: detections, laterDeterministicModelUsd: 0, state: prov.promotionEvent ? 'promoted' : 'not promoted' };
498
+ if (args.flags.json) { console.log(JSON.stringify(out, null, 2)); return 0; }
499
+ console.log(`Rule ${id} (${out.state})`);
500
+ console.log(first ? ` first discovery: ${first.usd != null ? `$${first.usd}` : 'cost not recorded'}${first.tokens ? `, ${first.tokens} tokens` : ''}${first.model ? `, ${first.model}` : ''}` : ' first discovery: cost was not recorded for this rule');
501
+ console.log(` later detections by this rule in the last scan: ${detections ?? 'no scan available'}, each at $0 of model spend`);
502
+ if (first?.usd != null && detections) console.log(` discovery cost spread over ${detections + 1} detection(s): $${(first.usd / (detections + 1)).toFixed(4)} each, falling with every further one`);
503
+ return 0;
504
+ }
505
+
506
+
507
+ /***/ })
508
+
509
+ };