@clear-capabilities/agentic-security-scanner 0.185.0 → 0.186.1

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 (167) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bin/agentic-security.js +24 -1
  3. package/dist/1128.index.js +25 -21
  4. package/dist/2584.index.js +1 -1
  5. package/dist/4171.index.js +2 -2
  6. package/dist/5752.index.js +466 -0
  7. package/dist/7405.index.js +1 -1
  8. package/dist/8158.index.js +1713 -0
  9. package/dist/8798.index.js +1 -1
  10. package/dist/9382.index.js +2 -2
  11. package/dist/9579.index.js +1 -1
  12. package/dist/agentic-security.mjs +29 -29
  13. package/dist/agentic-security.mjs.sha256 +1 -1
  14. package/dist/{0b301d45b231f144a1b4.json → ca62ee93079be4c24eee.json} +7 -7
  15. package/package.json +7 -7
  16. package/src/dataflow/CLAUDE.md +6 -3
  17. package/src/dataflow/access-paths.js +12 -2
  18. package/src/dataflow/demand-query.js +279 -40
  19. package/src/dataflow/dep-fingerprint.js +1 -1
  20. package/src/dataflow/exploit-prover.js +6 -2
  21. package/src/dataflow/ir-cache.js +268 -0
  22. package/src/dataflow/privacy-taint.js +7 -0
  23. package/src/engine.js +62 -5
  24. package/src/ir/CLAUDE.md +4 -0
  25. package/src/ir/callgraph.js +36 -8
  26. package/src/ir/index.js +18 -4
  27. package/src/ir/parser-js.js +10 -0
  28. package/src/language/CLAUDE.md +13 -0
  29. package/src/language/nix-option-types.js +170 -0
  30. package/src/language/nix-script-taint.js +46 -3
  31. package/src/language/nix-secrets.js +20 -2
  32. package/src/lineage/CLAUDE.md +2 -1
  33. package/src/lineage/smt-orchestrator.js +47 -11
  34. package/src/lineage/smt-z3-backend.js +294 -0
  35. package/src/posture/CLAUDE.md +5 -1
  36. package/src/posture/business-logic.js +16 -7
  37. package/src/posture/dag-commands.js +442 -0
  38. package/src/posture/finding-defaults.js +19 -0
  39. package/src/posture/git-history.js +91 -1
  40. package/src/sast/CLAUDE.md +2 -0
  41. package/src/sast/_call-args.js +70 -0
  42. package/src/sast/init-scope.js +87 -0
  43. package/src/sast/listen-bind-address.js +49 -0
  44. package/src/sast/redirect-target.js +106 -0
  45. package/src/sast/reflected-input.js +76 -0
  46. package/src/sast/send-file-root.js +27 -0
  47. package/src/sast/sensitive-data-logging.js +38 -1
  48. package/dist/119.index.js +0 -197
  49. package/dist/128.index.js +0 -129
  50. package/dist/1293.index.js +0 -5689
  51. package/dist/1336.index.js +0 -16331
  52. package/dist/1351.index.js +0 -133
  53. package/dist/1387.index.js +0 -271
  54. package/dist/1437.index.js +0 -23
  55. package/dist/1445.index.js +0 -110
  56. package/dist/1505.index.js +0 -151
  57. package/dist/1557.index.js +0 -293
  58. package/dist/1621.index.js +0 -311
  59. package/dist/1751.index.js +0 -160
  60. package/dist/1765.index.js +0 -727
  61. package/dist/1861.index.js +0 -690
  62. package/dist/1906.index.js +0 -433
  63. package/dist/208.index.js +0 -1631
  64. package/dist/2223.index.js +0 -159
  65. package/dist/2238.index.js +0 -295
  66. package/dist/2530.index.js +0 -152
  67. package/dist/2565.index.js +0 -116
  68. package/dist/2574.index.js +0 -127
  69. package/dist/2620.index.js +0 -345
  70. package/dist/2773.index.js +0 -98
  71. package/dist/2775.index.js +0 -32
  72. package/dist/2966.index.js +0 -171
  73. package/dist/2972.index.js +0 -87
  74. package/dist/2991.index.js +0 -131
  75. package/dist/3063.index.js +0 -833
  76. package/dist/3075.index.js +0 -227
  77. package/dist/3121.index.js +0 -297
  78. package/dist/3314.index.js +0 -263
  79. package/dist/3480.index.js +0 -1822
  80. package/dist/3481.index.js +0 -24
  81. package/dist/3506.index.js +0 -268
  82. package/dist/3533.index.js +0 -591
  83. package/dist/3653.index.js +0 -450
  84. package/dist/3740.index.js +0 -722
  85. package/dist/3822.index.js +0 -131
  86. package/dist/3868.index.js +0 -292
  87. package/dist/3918.index.js +0 -192
  88. package/dist/4090.index.js +0 -288
  89. package/dist/4113.index.js +0 -1286
  90. package/dist/4121.index.js +0 -1190
  91. package/dist/4142.index.js +0 -690
  92. package/dist/4168.index.js +0 -509
  93. package/dist/4281.index.js +0 -993
  94. package/dist/4336.index.js +0 -436
  95. package/dist/4387.index.js +0 -532
  96. package/dist/4413.index.js +0 -302
  97. package/dist/4476.index.js +0 -4510
  98. package/dist/4491.index.js +0 -133
  99. package/dist/4538.index.js +0 -185
  100. package/dist/4684.index.js +0 -319
  101. package/dist/4740.index.js +0 -165
  102. package/dist/4780.index.js +0 -209
  103. package/dist/4802.index.js +0 -225
  104. package/dist/4812.index.js +0 -379
  105. package/dist/4835.index.js +0 -126
  106. package/dist/494.index.js +0 -226
  107. package/dist/4991.index.js +0 -549
  108. package/dist/5199.index.js +0 -305
  109. package/dist/5216.index.js +0 -109
  110. package/dist/5439.index.js +0 -301
  111. package/dist/5443.index.js +0 -97
  112. package/dist/5496.index.js +0 -377
  113. package/dist/5738.index.js +0 -240
  114. package/dist/5801.index.js +0 -588
  115. package/dist/5817.index.js +0 -714
  116. package/dist/5858.index.js +0 -223
  117. package/dist/5933.index.js +0 -143
  118. package/dist/601.index.js +0 -23
  119. package/dist/6173.index.js +0 -273
  120. package/dist/6291.index.js +0 -1871
  121. package/dist/6312.index.js +0 -666
  122. package/dist/634.index.js +0 -16182
  123. package/dist/644.index.js +0 -87
  124. package/dist/6508.index.js +0 -283
  125. package/dist/6560.index.js +0 -645
  126. package/dist/6576.index.js +0 -422
  127. package/dist/6579.index.js +0 -271
  128. package/dist/6655.index.js +0 -3221
  129. package/dist/6745.index.js +0 -305
  130. package/dist/6818.index.js +0 -21642
  131. package/dist/6932.index.js +0 -1190
  132. package/dist/6972.index.js +0 -167
  133. package/dist/6995.index.js +0 -163
  134. package/dist/7249.index.js +0 -191
  135. package/dist/7372.index.js +0 -1197
  136. package/dist/7546.index.js +0 -541
  137. package/dist/76.index.js +0 -448
  138. package/dist/7879.index.js +0 -163
  139. package/dist/8025.index.js +0 -130
  140. package/dist/8054.index.js +0 -248
  141. package/dist/808.index.js +0 -1330
  142. package/dist/8097.index.js +0 -201
  143. package/dist/8126.index.js +0 -191
  144. package/dist/8178.index.js +0 -78
  145. package/dist/8382.index.js +0 -93
  146. package/dist/8408.index.js +0 -261
  147. package/dist/8540.index.js +0 -174
  148. package/dist/8635.index.js +0 -802
  149. package/dist/8688.index.js +0 -410
  150. package/dist/8699.index.js +0 -779
  151. package/dist/8891.index.js +0 -457
  152. package/dist/8916.index.js +0 -885
  153. package/dist/9146.index.js +0 -170
  154. package/dist/9168.index.js +0 -841
  155. package/dist/9292.index.js +0 -369
  156. package/dist/9422.index.js +0 -866
  157. package/dist/9440.index.js +0 -453
  158. package/dist/9479.index.js +0 -152
  159. package/dist/9481.index.js +0 -220
  160. package/dist/9539.index.js +0 -100
  161. package/dist/9547.index.js +0 -103
  162. package/dist/9692.index.js +0 -90
  163. package/dist/9800.index.js +0 -462
  164. package/dist/9899.index.js +0 -138
  165. package/dist/9981.index.js +0 -206
  166. package/dist/999.index.js +0 -117
  167. package/dist/9999.index.js +0 -1698
@@ -1,509 +0,0 @@
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
- };