@clear-capabilities/agentic-security-scanner 0.184.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 (228) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/bin/agentic-security.js +111 -1
  3. package/dist/1128.index.js +912 -0
  4. package/dist/1665.index.js +828 -0
  5. package/dist/2584.index.js +1 -1
  6. package/dist/4171.index.js +2 -2
  7. package/dist/5752.index.js +466 -0
  8. package/dist/7405.index.js +1 -1
  9. package/dist/8158.index.js +1713 -0
  10. package/dist/8798.index.js +1 -1
  11. package/dist/9382.index.js +2 -2
  12. package/dist/9579.index.js +1 -1
  13. package/dist/agentic-security.mjs +29 -29
  14. package/dist/agentic-security.mjs.sha256 +1 -1
  15. package/dist/{dad58d1113a12c23a142.json → ca62ee93079be4c24eee.json} +29 -12
  16. package/dist/frontend/src/shell.js +12 -2
  17. package/package.json +29 -12
  18. package/src/dataflow/CLAUDE.md +46 -1
  19. package/src/dataflow/access-paths.js +12 -2
  20. package/src/dataflow/backward.js +42 -7
  21. package/src/dataflow/cross-service-taint.js +83 -1
  22. package/src/dataflow/demand-query.js +1168 -0
  23. package/src/dataflow/dep-fingerprint.js +718 -0
  24. package/src/dataflow/engine.js +48 -6
  25. package/src/dataflow/exploit-prover.js +6 -2
  26. package/src/dataflow/ifds-precise.js +22 -0
  27. package/src/dataflow/incremental-replay.js +118 -0
  28. package/src/dataflow/incremental-session.js +257 -0
  29. package/src/dataflow/incremental.js +237 -35
  30. package/src/dataflow/index.js +25 -94
  31. package/src/dataflow/ir-cache.js +268 -0
  32. package/src/dataflow/privacy-taint.js +7 -0
  33. package/src/dataflow/summaries.js +72 -6
  34. package/src/dataflow/tabulation.js +80 -24
  35. package/src/engine.js +113 -8
  36. package/src/graph/CLAUDE.md +31 -0
  37. package/src/graph/adapters/artifact.js +81 -0
  38. package/src/graph/adapters/crossrepo.js +75 -0
  39. package/src/graph/adapters/dataflow.js +76 -0
  40. package/src/graph/adapters/provenance.js +92 -0
  41. package/src/graph/adapters/semantic.js +89 -0
  42. package/src/graph/crosswalk-builders.js +152 -0
  43. package/src/graph/crosswalk.js +146 -0
  44. package/src/graph/index.js +15 -0
  45. package/src/graph/observation.js +57 -0
  46. package/src/graph/refs.js +105 -0
  47. package/src/graph/registry.js +129 -0
  48. package/src/graph/relations.js +81 -0
  49. package/src/graph/scc.js +241 -0
  50. package/src/graph/view.js +254 -0
  51. package/src/ir/CLAUDE.md +4 -0
  52. package/src/ir/callgraph.js +36 -8
  53. package/src/ir/index.js +18 -4
  54. package/src/ir/parser-js.js +10 -0
  55. package/src/language/CLAUDE.md +13 -0
  56. package/src/language/nix-option-types.js +170 -0
  57. package/src/language/nix-script-taint.js +46 -3
  58. package/src/language/nix-secrets.js +20 -2
  59. package/src/lineage/CLAUDE.md +72 -8
  60. package/src/lineage/DESIGN_GRAPH_BUILDER.md +1 -1
  61. package/src/lineage/DESIGN_PATH_PROVENANCE.md +6 -0
  62. package/src/lineage/boundary-contract.js +273 -0
  63. package/src/lineage/completion.js +205 -0
  64. package/src/lineage/continuation.js +140 -0
  65. package/src/lineage/control-credit.js +313 -0
  66. package/src/lineage/correlation.js +199 -0
  67. package/src/lineage/coverage.js +8 -1
  68. package/src/lineage/cross-repo-link.js +22 -0
  69. package/src/lineage/cut-planner.js +548 -0
  70. package/src/lineage/driver.js +219 -66
  71. package/src/lineage/engine.js +166 -21
  72. package/src/lineage/export-json.js +5 -0
  73. package/src/lineage/graph-builder.js +84 -7
  74. package/src/lineage/haskell-view.js +59 -0
  75. package/src/lineage/index.js +3 -0
  76. package/src/lineage/nix-view.js +35 -0
  77. package/src/lineage/owned-build.js +77 -0
  78. package/src/lineage/owned-worker-entry.js +22 -0
  79. package/src/lineage/owned-worker.js +95 -0
  80. package/src/lineage/path-evidence.js +123 -0
  81. package/src/lineage/path-predicates.js +529 -0
  82. package/src/lineage/path-query.js +189 -20
  83. package/src/lineage/path-store.js +191 -17
  84. package/src/lineage/scc-solver.js +186 -0
  85. package/src/lineage/smt-orchestrator.js +174 -0
  86. package/src/lineage/smt-z3-backend.js +294 -0
  87. package/src/lineage/source-seeding.js +36 -2
  88. package/src/lineage/summaries.js +66 -4
  89. package/src/lineage/value-versions.js +130 -0
  90. package/src/lineage/witness-selection.js +95 -0
  91. package/src/pipeline/scan-health.js +18 -0
  92. package/src/posture/CLAUDE.md +17 -0
  93. package/src/posture/business-logic.js +16 -7
  94. package/src/posture/dag-commands.js +442 -0
  95. package/src/posture/evidence-bundle.js +1 -1
  96. package/src/posture/finding-defaults.js +19 -0
  97. package/src/posture/git-history.js +91 -1
  98. package/src/posture/witness-bundle.js +573 -0
  99. package/src/posture/witness-runtime.js +276 -0
  100. package/src/report/index.js +2 -0
  101. package/src/sast/CLAUDE.md +2 -0
  102. package/src/sast/_call-args.js +70 -0
  103. package/src/sast/init-scope.js +87 -0
  104. package/src/sast/listen-bind-address.js +49 -0
  105. package/src/sast/redirect-target.js +106 -0
  106. package/src/sast/reflected-input.js +76 -0
  107. package/src/sast/send-file-root.js +27 -0
  108. package/src/sast/sensitive-data-logging.js +38 -1
  109. package/dist/119.index.js +0 -197
  110. package/dist/128.index.js +0 -129
  111. package/dist/1293.index.js +0 -5689
  112. package/dist/1336.index.js +0 -16182
  113. package/dist/1351.index.js +0 -133
  114. package/dist/1387.index.js +0 -271
  115. package/dist/1437.index.js +0 -23
  116. package/dist/1445.index.js +0 -110
  117. package/dist/1505.index.js +0 -151
  118. package/dist/1557.index.js +0 -293
  119. package/dist/1621.index.js +0 -311
  120. package/dist/1751.index.js +0 -160
  121. package/dist/1765.index.js +0 -727
  122. package/dist/1861.index.js +0 -690
  123. package/dist/1906.index.js +0 -433
  124. package/dist/208.index.js +0 -1631
  125. package/dist/2223.index.js +0 -159
  126. package/dist/2238.index.js +0 -295
  127. package/dist/2530.index.js +0 -152
  128. package/dist/2565.index.js +0 -116
  129. package/dist/2574.index.js +0 -127
  130. package/dist/2620.index.js +0 -345
  131. package/dist/2773.index.js +0 -98
  132. package/dist/2775.index.js +0 -32
  133. package/dist/2966.index.js +0 -171
  134. package/dist/2972.index.js +0 -87
  135. package/dist/2991.index.js +0 -131
  136. package/dist/3063.index.js +0 -833
  137. package/dist/3075.index.js +0 -227
  138. package/dist/3121.index.js +0 -297
  139. package/dist/3314.index.js +0 -263
  140. package/dist/3480.index.js +0 -1822
  141. package/dist/3481.index.js +0 -24
  142. package/dist/3506.index.js +0 -268
  143. package/dist/3533.index.js +0 -591
  144. package/dist/3653.index.js +0 -450
  145. package/dist/3740.index.js +0 -722
  146. package/dist/3822.index.js +0 -131
  147. package/dist/3868.index.js +0 -292
  148. package/dist/3918.index.js +0 -192
  149. package/dist/4090.index.js +0 -288
  150. package/dist/4113.index.js +0 -1286
  151. package/dist/4121.index.js +0 -1190
  152. package/dist/4142.index.js +0 -690
  153. package/dist/4168.index.js +0 -509
  154. package/dist/4281.index.js +0 -993
  155. package/dist/4336.index.js +0 -436
  156. package/dist/4387.index.js +0 -532
  157. package/dist/4413.index.js +0 -302
  158. package/dist/4476.index.js +0 -4510
  159. package/dist/4491.index.js +0 -133
  160. package/dist/4538.index.js +0 -185
  161. package/dist/4684.index.js +0 -319
  162. package/dist/4740.index.js +0 -165
  163. package/dist/4780.index.js +0 -209
  164. package/dist/4802.index.js +0 -225
  165. package/dist/4812.index.js +0 -379
  166. package/dist/4835.index.js +0 -126
  167. package/dist/494.index.js +0 -226
  168. package/dist/4991.index.js +0 -549
  169. package/dist/5199.index.js +0 -305
  170. package/dist/5216.index.js +0 -109
  171. package/dist/5439.index.js +0 -301
  172. package/dist/5443.index.js +0 -97
  173. package/dist/5496.index.js +0 -377
  174. package/dist/5738.index.js +0 -240
  175. package/dist/5801.index.js +0 -588
  176. package/dist/5817.index.js +0 -714
  177. package/dist/5858.index.js +0 -223
  178. package/dist/5933.index.js +0 -143
  179. package/dist/601.index.js +0 -23
  180. package/dist/6173.index.js +0 -273
  181. package/dist/6291.index.js +0 -1871
  182. package/dist/6312.index.js +0 -666
  183. package/dist/634.index.js +0 -16182
  184. package/dist/644.index.js +0 -87
  185. package/dist/6508.index.js +0 -283
  186. package/dist/6560.index.js +0 -645
  187. package/dist/6576.index.js +0 -422
  188. package/dist/6579.index.js +0 -271
  189. package/dist/6655.index.js +0 -3221
  190. package/dist/6745.index.js +0 -305
  191. package/dist/6818.index.js +0 -21642
  192. package/dist/6932.index.js +0 -1190
  193. package/dist/6972.index.js +0 -167
  194. package/dist/6995.index.js +0 -163
  195. package/dist/7249.index.js +0 -191
  196. package/dist/7372.index.js +0 -1197
  197. package/dist/7546.index.js +0 -541
  198. package/dist/76.index.js +0 -448
  199. package/dist/7879.index.js +0 -163
  200. package/dist/8025.index.js +0 -130
  201. package/dist/8054.index.js +0 -248
  202. package/dist/808.index.js +0 -1330
  203. package/dist/8097.index.js +0 -201
  204. package/dist/8126.index.js +0 -191
  205. package/dist/8178.index.js +0 -78
  206. package/dist/8382.index.js +0 -93
  207. package/dist/8408.index.js +0 -261
  208. package/dist/8540.index.js +0 -174
  209. package/dist/8635.index.js +0 -802
  210. package/dist/8688.index.js +0 -410
  211. package/dist/8699.index.js +0 -779
  212. package/dist/8891.index.js +0 -457
  213. package/dist/8916.index.js +0 -885
  214. package/dist/9146.index.js +0 -170
  215. package/dist/9168.index.js +0 -841
  216. package/dist/9292.index.js +0 -369
  217. package/dist/9422.index.js +0 -866
  218. package/dist/9440.index.js +0 -453
  219. package/dist/9479.index.js +0 -152
  220. package/dist/9481.index.js +0 -220
  221. package/dist/9539.index.js +0 -100
  222. package/dist/9547.index.js +0 -103
  223. package/dist/9692.index.js +0 -90
  224. package/dist/9800.index.js +0 -462
  225. package/dist/9899.index.js +0 -138
  226. package/dist/9981.index.js +0 -206
  227. package/dist/999.index.js +0 -117
  228. package/dist/9999.index.js +0 -1698
@@ -1,690 +0,0 @@
1
- export const id = 1861;
2
- export const ids = [1861];
3
- export const modules = {
4
-
5
- /***/ 58355:
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
- /***/ 71861:
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__(69259);
87
- // EXTERNAL MODULE: ./src/posture/proof-fabric/reproducer.js
88
- var reproducer = __webpack_require__(82034);
89
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/ir.js
90
- // Rule intermediate representation: compiles DOWN into the existing pattern-rule engine
91
- // (`../custom-rules.js`), never a parallel matcher. "Compile" here means "emit a
92
- // custom-rules.js-compatible document" — detection at runtime is 100% the already-proven
93
- // regex/allOf/notMatch/window engine; this module only adds PROVENANCE metadata around it.
94
- //
95
- // A rule's match semantics are deliberately the same closed vocabulary custom-rules.js
96
- // already supports (pattern | allOf+window | notMatch) — no new matching primitive is
97
- // introduced, so a promoted rule is exactly as auditable as a hand-written one.
98
-
99
-
100
- const RULE_IR_SCHEMA = 'agentic-security/rule-ir';
101
- const RULE_IR_VERSION = 1;
102
- const RULE_STATES = Object.freeze(['DRAFT', 'CANDIDATE', 'VALIDATED', 'PROMOTED', 'DEPRECATED', 'ROLLED_BACK']);
103
- const VALID_LANGS = new Set(['javascript', 'typescript', 'python', 'go', 'ruby', 'java', 'rust', 'csharp', 'php', 'any']);
104
-
105
- const isStr = (v) => typeof v === 'string' && v.length > 0;
106
-
107
- /** Problems with a draft rule IR; an empty list means it is well-formed (not yet validated/promoted). */
108
- function validateRuleIR(ir) {
109
- const errs = [];
110
- if (!ir || typeof ir !== 'object') return ['rule IR must be an object'];
111
- if (ir.schema !== RULE_IR_SCHEMA) errs.push('unknown schema');
112
- if (ir.version !== RULE_IR_VERSION) errs.push('unsupported rule IR version');
113
- if (!isStr(ir.id) || !/^[a-z][a-z0-9-]{2,79}$/.test(ir.id)) errs.push('id must be a lowercase kebab-case string');
114
- if (!isStr(ir.title)) errs.push('title required');
115
- if (!['critical', 'high', 'medium', 'low'].includes(ir.severity)) errs.push('severity must be critical|high|medium|low');
116
- if (!isStr(ir.cwe) || !/^CWE-\d+$/.test(ir.cwe)) errs.push('cwe must look like CWE-###');
117
- if (!isStr(ir.family)) errs.push('family required');
118
- if (!Array.isArray(ir.languages) || !ir.languages.length || !ir.languages.every((l) => VALID_LANGS.has(l))) errs.push('languages must be a non-empty array from the supported set');
119
- const m = ir.match;
120
- if (!m || typeof m !== 'object') errs.push('match required');
121
- else {
122
- const hasPattern = isStr(m.pattern);
123
- const hasAllOf = Array.isArray(m.allOf) && m.allOf.length > 0 && m.allOf.every(isStr);
124
- if (!hasPattern && !hasAllOf) errs.push('match needs a pattern or a non-empty allOf');
125
- if (m.notMatch != null && !isStr(m.notMatch)) errs.push('notMatch must be a string');
126
- if (m.window != null && !(Number.isInteger(m.window) && m.window > 0 && m.window <= 200)) errs.push('window must be an integer in 1..200');
127
- for (const re of [m.pattern, ...(m.allOf || []), m.notMatch].filter(isStr)) {
128
- try { new RegExp(re); } catch { errs.push(`invalid regex: ${re}`); }
129
- }
130
- }
131
- // Declarative-only hint fields (sink/source/propagator/sanitizer/dominatingGuard/frameworkConstraint): free text,
132
- // never executable, carried for provenance/review only and NOT consulted by the matcher.
133
- for (const k of ['sink', 'source', 'propagator', 'sanitizer', 'dominatingGuard', 'frameworkConstraint']) {
134
- if (ir[k] != null && !isStr(ir[k])) errs.push(`${k} must be a string when present`);
135
- }
136
- if (ir.exclusions != null && !(Array.isArray(ir.exclusions) && ir.exclusions.every(isStr))) errs.push('exclusions must be an array of strings');
137
- if (!ir.provenance || typeof ir.provenance !== 'object') errs.push('provenance required');
138
- else {
139
- if (!isStr(ir.provenance.originatingFindingId)) errs.push('provenance.originatingFindingId required');
140
- if (ir.provenance.originatingCommit != null && !isStr(ir.provenance.originatingCommit)) errs.push('provenance.originatingCommit must be a string');
141
- if (!['execution-proven', 'taint-proven', 'deterministic-corroboration'].includes(ir.provenance.evidenceState)) errs.push('provenance.evidenceState must be execution-proven|taint-proven|deterministic-corroboration');
142
- }
143
- return errs;
144
- }
145
-
146
- function ruleIRDigest(ir) {
147
- const { state: _s, ...rest } = ir;
148
- return (0,reproducer/* sha256 */.sc)(JSON.stringify(rest, Object.keys(rest).sort()));
149
- }
150
-
151
- /** Build a DRAFT rule IR. Caller supplies the candidate pattern — this module never invents one. */
152
- function draftRuleIR({ id, title, severity, cwe, family, languages, match, remediation, originatingFindingId, originatingCommit, evidenceState, model = null, promptConfigVersion = null, ...hints }) {
153
- const ir = {
154
- schema: RULE_IR_SCHEMA, version: RULE_IR_VERSION, id, title, severity, cwe, family, languages, match,
155
- remediation: remediation ?? null, state: 'DRAFT',
156
- ...hints,
157
- provenance: { originatingFindingId, originatingCommit: originatingCommit ?? null, evidenceState, model, promptConfigVersion },
158
- };
159
- return ir;
160
- }
161
-
162
- /** Compile a rule IR into a custom-rules.js-compatible document. Caller writes the YAML. */
163
- function compileToCustomRule(ir) {
164
- const errs = validateRuleIR(ir);
165
- if (errs.length) return { ok: false, errs };
166
- const doc = {
167
- id: `rule-compiler/${ir.id}`,
168
- title: ir.title,
169
- severity: ir.severity,
170
- cwe: ir.cwe,
171
- languages: ir.languages,
172
- match: { ...(ir.match.pattern ? { pattern: ir.match.pattern } : {}), ...(ir.match.allOf ? { allOf: ir.match.allOf, window: ir.match.window ?? 5 } : {}), ...(ir.match.notMatch ? { notMatch: ir.match.notMatch } : {}) },
173
- message: ir.remediation || `${ir.title} (${ir.cwe}, compiled from ${ir.provenance.originatingFindingId})`,
174
- };
175
- return { ok: true, doc };
176
- }
177
-
178
- // EXTERNAL MODULE: ./src/posture/proof-fabric/states.js
179
- var states = __webpack_require__(58355);
180
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/eligibility.js
181
- // X-eligibility (PRD 3 "Eligibility"): a finding may enter synthesis only with a stable id, a vulnerable span, a
182
- // CWE/family, code-flow evidence, and deterministic corroboration OR exploit proof. Reuses the existing
183
- // vocabularies rather than inventing a third: proof-fabric's evidence-state ladder when present, else the older
184
- // proof-tier (`taint-proven`/`execution-proven`), else the finding's own `parser` (an IR-TAINT/MULTI-SINK parser
185
- // origin is code-flow evidence even with no execution).
186
-
187
-
188
- const ANALYSED_PARSERS = new Set(['IR-TAINT', 'MULTI-SINK']);
189
-
190
- function checkEligibility(finding, { proofState = null } = {}) {
191
- const reasons = [];
192
- if (!finding?.stableId && !finding?.id) reasons.push('no stable id');
193
- if (finding?.file == null || finding?.line == null) reasons.push('no vulnerable span (file:line)');
194
- if (!finding?.cwe && !finding?.family) reasons.push('no CWE or family');
195
- const hasFlowEvidence = ANALYSED_PARSERS.has(finding?.parser) || !!finding?.snippet;
196
- if (!hasFlowEvidence) reasons.push('no code-flow evidence (parser not IR-TAINT/MULTI-SINK, no snippet)');
197
-
198
- let evidenceState = 'none';
199
- if (proofState && (0,states/* stateRank */.g3)(proofState) >= (0,states/* stateRank */.g3)('EXPLOIT_CONFIRMED')) evidenceState = 'execution-proven';
200
- else if (finding?.proofTier === 'execution-proven') evidenceState = 'execution-proven';
201
- else if (finding?.proofTier === 'taint-proven' || ANALYSED_PARSERS.has(finding?.parser)) evidenceState = 'taint-proven';
202
- if (evidenceState === 'none') reasons.push('no deterministic corroboration or exploit proof');
203
-
204
- return { eligible: reasons.length === 0, reasons, evidenceState };
205
- }
206
-
207
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/mutation.js
208
- // Bounded structural mutation for ONE candidate rule's own corpus — not bench/mutation's engine-wide verdict-flip
209
- // harness (a different scope: the whole deterministic+taint engine against curated adversarial cases). This module
210
- // exists only to answer PRD 3's "unseen sibling" question for a single rule: does the candidate still fire on a
211
- // structurally different variant of the same vulnerable shape, and does it still decline on a structurally
212
- // different variant of a mitigated shape.
213
- //
214
- // Mutations are SYNTACTIC, deterministic, seed-free and language-agnostic: variable rename, wrap-in-function,
215
- // reorder-adjacent-statements, insert-indirection (a pass-through local variable). No semantics are changed on
216
- // purpose — a mutation that silently changed behavior would make a "same vulnerability, different shape" claim
217
- // false.
218
- const RESERVED = new Set(['if', 'else', 'for', 'while', 'return', 'function', 'const', 'let', 'var', 'import', 'from', 'def', 'class', 'req', 'res']);
219
-
220
- function identifiers(code) {
221
- const seen = new Set();
222
- for (const m of code.matchAll(/\b([A-Za-z_][A-Za-z0-9_]*)\b/g)) if (!RESERVED.has(m[1]) && !/^[A-Z_]+$/.test(m[1])) seen.add(m[1]);
223
- return [...seen];
224
- }
225
-
226
- function renameOne(code, from, to) {
227
- if (!from || code.includes(to)) return null;
228
- return code.replace(new RegExp(`\\b${from}\\b`, 'g'), to);
229
- }
230
-
231
- function variableRename(code, { suffix = '_v2' } = {}) {
232
- const ids = identifiers(code);
233
- const target = ids.find((id) => id.length > 1);
234
- if (!target) return null;
235
- return renameOne(code, target, `${target}${suffix}`);
236
- }
237
-
238
- function wrapInFunction(code, { name = 'wrapped_v2' } = {}) {
239
- const indented = code.split('\n').map((l) => (l ? ` ${l}` : l)).join('\n');
240
- return `function ${name}() {\n${indented}\n}\n${name}();\n`;
241
- }
242
-
243
- /** Insert a pass-through local for the first simple right-hand-side identifier assigned with `=` (indirection,
244
- * no behavior change): `x = y;` becomes `const indirectN = y; x = indirectN;`. */
245
- function insertIndirection(code) {
246
- const m = /^(\s*)([A-Za-z_][A-Za-z0-9_.]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*;/m.exec(code);
247
- if (!m) return null;
248
- const [whole, indent, lhs, rhs] = m;
249
- const varName = `indirect_${Math.abs(_hash(rhs)) % 1000}`;
250
- if (code.includes(varName)) return null;
251
- return code.replace(whole, `${indent}const ${varName} = ${rhs};\n${indent}${lhs} = ${varName};`);
252
- }
253
-
254
- function _hash(s) { let h = 0; for (const c of s) h = (h * 31 + c.charCodeAt(0)) | 0; return h; }
255
-
256
- const MUTATORS = Object.freeze({ 'variable-rename': variableRename, 'wrap-in-function': wrapInFunction, 'insert-indirection': insertIndirection });
257
-
258
- /** Every mutator applied to `code`; mutators that don't apply (return null) are omitted, never silently skipped without saying so. */
259
- function generateVariants(code) {
260
- const out = [];
261
- for (const [name, fn] of Object.entries(MUTATORS)) {
262
- let variant = null;
263
- try { variant = fn(code); } catch { variant = null; }
264
- if (variant && variant !== code) out.push({ mutator: name, code: variant });
265
- }
266
- return out;
267
- }
268
-
269
- // EXTERNAL MODULE: ./src/posture/custom-rules.js + 1 modules
270
- var custom_rules = __webpack_require__(36885);
271
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/corpus.js
272
- // Automatic corpus creation and scoring for ONE candidate rule.
273
- //
274
- // Positive corpus: the original vulnerable snippet plus its generated sibling variants (mutation.js).
275
- // Negative corpus: an explicit patched/clean variant the caller supplies, nearby clean patterns, protected
276
- // (sanitizer/guard) variants, and the NEGATIVE mutations of those (same mutators, applied to the safe side) — a
277
- // candidate rule must decline on ALL of them, not just the one hand-picked negative.
278
- //
279
- // Scoring reuses the exact runtime matcher (`runRule` in `../custom-rules.js`), never a second implementation —
280
- // the score a rule gets here is the score it will actually produce once promoted.
281
-
282
-
283
-
284
-
285
- function toRuntimeRule(ir) {
286
- const { ok, doc, errs } = compileToCustomRule(ir);
287
- if (!ok) throw new Error(`cannot build corpus for an invalid rule IR: ${errs.join('; ')}`);
288
- const regexes = doc.match.allOf ? doc.match.allOf.map((p) => new RegExp(p, 'g')) : [new RegExp(doc.match.pattern, 'g')];
289
- return {
290
- id: doc.id, title: doc.title, severity: doc.severity, cwe: doc.cwe, languages: doc.languages, message: doc.message,
291
- regexes, requireAll: !!doc.match.allOf, windowLines: doc.match.window ?? 5,
292
- notMatch: doc.match.notMatch ? new RegExp(doc.match.notMatch) : null,
293
- };
294
- }
295
-
296
- const EXT = { javascript: 'x.js', typescript: 'x.ts', python: 'x.py', go: 'x.go', ruby: 'x.rb', java: 'x.java', rust: 'x.rs', csharp: 'x.cs', php: 'x.php', any: 'x.txt' };
297
-
298
- function buildCorpus(ir, { originalCode, patchedCode = null, nearbyCleanCode = [], protectedVariantsCode = [] } = {}) {
299
- const positives = [{ label: 'original', code: originalCode }];
300
- for (const v of generateVariants(originalCode)) positives.push({ label: `sibling:${v.mutator}`, code: v.code });
301
-
302
- const negatives = [];
303
- if (patchedCode) {
304
- negatives.push({ label: 'patched', code: patchedCode });
305
- for (const v of generateVariants(patchedCode)) negatives.push({ label: `patched-sibling:${v.mutator}`, code: v.code });
306
- }
307
- nearbyCleanCode.forEach((code, i) => negatives.push({ label: `nearby-clean-${i}`, code }));
308
- protectedVariantsCode.forEach((code, i) => negatives.push({ label: `protected-${i}`, code }));
309
-
310
- return { positives, negatives };
311
- }
312
-
313
- function scoreRule(ir, corpus) {
314
- const rule = toRuntimeRule(ir);
315
- const lang = ir.languages[0] || 'javascript';
316
- const file = EXT[lang] || 'x.txt';
317
- const run = (code) => (0,custom_rules/* runRule */.OA)(rule, file, code).length > 0;
318
-
319
- const posResults = corpus.positives.map((p) => ({ ...p, fired: run(p.code) }));
320
- const negResults = corpus.negatives.map((n) => ({ ...n, fired: run(n.code) }));
321
-
322
- const tp = posResults.filter((p) => p.fired).length;
323
- const fn = posResults.length - tp;
324
- const fp = negResults.filter((n) => n.fired).length;
325
- const tn = negResults.length - fp;
326
- const precision = tp + fp === 0 ? null : tp / (tp + fp);
327
- const recall = corpus.positives.length === 0 ? null : tp / corpus.positives.length;
328
- // "Protected negative failures" per PRD 3: a rule firing on a sanitizer/guard-carrying variant specifically.
329
- const protectedFailures = negResults.filter((n) => n.label.startsWith('protected-') && n.fired).length;
330
-
331
- return { precision, recall, tp, fp, tn, fn, protectedFailures, positives: posResults, negatives: negResults };
332
- }
333
-
334
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/promotion.js
335
- // Promotion gate (PRD 3 "Promotion Gate"): precision/recall thresholds, zero protected-negative failures, zero
336
- // benchmark leakage. A candidate rule does NOT automatically become a production rule — `evaluateRule` only
337
- // scores; `gatePromotion` only judges; the lifecycle ledger (`lifecycle.js`) is the one place a PROMOTED state is
338
- // actually recorded, and nothing in this module writes to it.
339
-
340
-
341
- const PROMOTION_DEFAULTS = Object.freeze({ minPrecision: 0.95, minRecall: 0.80, maxProtectedFailures: 0 });
342
-
343
- // Deliberately independent of posture/evaluation/custody.js: that module's term list and guard are reserved for
344
- // the evaluation custodian's sealed-label boundary (QA-002.AC03), and a test enforces that nothing outside
345
- // posture/evaluation/ may import it. The anti-cheating need here is smaller and different in kind — a rule
346
- // synthesis prompt/corpus must not embed a benchmark name or an advisory id — so it gets its own small, independent
347
- // checker rather than reaching across that isolation boundary.
348
- const ADVISORY_ID = /\b(?:CVE|GHSA|CWE)-[A-Za-z0-9-]+\b/i;
349
-
350
- /** Anti-cheating: the synthesis agent must never see benchmark answer keys, hidden labels, CWE-bearing hidden
351
- * filenames or vulnerability-comment metadata. */
352
- function checkLeakage(promptText, { benchmarkNames = [] } = {}) {
353
- const hay = String(promptText ?? '');
354
- const offending = [];
355
- for (const name of benchmarkNames) if (name && hay.toLowerCase().includes(String(name).toLowerCase())) offending.push(name);
356
- const m = ADVISORY_ID.exec(hay);
357
- if (m) offending.push(m[0]);
358
- return { ok: offending.length === 0, offendingTerms: offending };
359
- }
360
-
361
- function evaluateRule(ir, corpus, thresholds = PROMOTION_DEFAULTS) {
362
- const score = scoreRule(ir, corpus);
363
- const t = { ...PROMOTION_DEFAULTS, ...thresholds };
364
- const reasons = [];
365
- if (score.precision === null) reasons.push('precision unmeasured (no positive or negative corpus fired)');
366
- else if (score.precision < t.minPrecision) reasons.push(`precision ${(score.precision * 100).toFixed(1)}% below ${(t.minPrecision * 100).toFixed(0)}%`);
367
- if (score.recall === null) reasons.push('recall unmeasured (empty positive corpus)');
368
- else if (score.recall < t.minRecall) reasons.push(`recall ${(score.recall * 100).toFixed(1)}% below ${(t.minRecall * 100).toFixed(0)}%`);
369
- if (score.protectedFailures > t.maxProtectedFailures) reasons.push(`${score.protectedFailures} protected-negative failure(s) (max ${t.maxProtectedFailures})`);
370
- return { pass: reasons.length === 0, reasons, score, thresholds: t };
371
- }
372
-
373
- /** The one promotion decision. Never auto-applied: a caller still has to act on `pass:true` by recording a
374
- * lifecycle transition. Localization ("acceptable") is a human/caller judgment this function cannot make from
375
- * line/column alone; it is surfaced for review, never silently assumed. */
376
- function gatePromotion({ ir, corpus, leakageCheck, thresholds } = {}) {
377
- const evalResult = evaluateRule(ir, corpus, thresholds);
378
- const reasons = [...evalResult.reasons];
379
- if (!leakageCheck || leakageCheck.ok !== true) reasons.push(leakageCheck ? `leakage check failed: ${leakageCheck.offendingTerms.join(', ')}` : 'leakage check was not run');
380
- return { pass: reasons.length === 0, reasons, evaluation: evalResult };
381
- }
382
-
383
- // EXTERNAL MODULE: external "node:crypto"
384
- var external_node_crypto_ = __webpack_require__(77598);
385
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/lifecycle.js
386
- // Rule lifecycle ledger: DRAFT -> CANDIDATE -> VALIDATED -> PROMOTED -> DEPRECATED/ROLLED_BACK.
387
- //
388
- // Append-only, hash-chained (same idiom as remediation-ledger.js / invariants/lifecycle.js): each entry links the
389
- // previous entry's hash, so a dropped or edited middle record breaks the chain and `verifyLedger` catches it. A
390
- // rule cannot promote itself: `transition` only records a transition a caller already decided; `advance`-style
391
- // guarding on VALID edges lives here so no caller can jump DRAFT straight to PROMOTED.
392
-
393
-
394
-
395
- const LEDGER_SCHEMA = 'agentic-security/rule-lifecycle-ledger';
396
- const EDGES = Object.freeze({
397
- DRAFT: ['CANDIDATE'], CANDIDATE: ['VALIDATED', 'DRAFT'], VALIDATED: ['PROMOTED', 'DRAFT'],
398
- PROMOTED: ['DEPRECATED', 'ROLLED_BACK'], DEPRECATED: [], ROLLED_BACK: ['CANDIDATE'],
399
- });
400
-
401
- const hashOf = (entry) => (0,external_node_crypto_.createHash)('sha256').update(JSON.stringify(entry)).digest('hex');
402
-
403
- function newLedger() { return { schema: LEDGER_SCHEMA, entries: [] }; }
404
-
405
- function currentState(ledger, ruleId) {
406
- for (let i = ledger.entries.length - 1; i >= 0; i--) if (ledger.entries[i].ruleId === ruleId) return ledger.entries[i].to;
407
- return null;
408
- }
409
-
410
- /**
411
- * Record a transition. Refuses an edge not in EDGES, and refuses DRAFT->DRAFT re-entry for a rule that has never
412
- * existed (the first entry for a rule id must be `from: null, to: 'DRAFT'`).
413
- */
414
- function recordTransition(ledger, { ruleId, from, to, reason, evidence = null, actor }) {
415
- if (!RULE_STATES.includes(to)) return { ok: false, reason: `unknown target state: ${to}` };
416
- const cur = currentState(ledger, ruleId);
417
- if (cur === null) {
418
- if (from !== null || to !== 'DRAFT') return { ok: false, reason: 'first transition for a rule must be null -> DRAFT' };
419
- } else {
420
- if (from !== cur) return { ok: false, reason: `stale transition: current state is ${cur}, not ${from}` };
421
- if (!EDGES[cur].includes(to)) return { ok: false, reason: `cannot go from ${cur} to ${to}` };
422
- }
423
- const prevHash = ledger.entries.length ? ledger.entries[ledger.entries.length - 1].entryHash : null;
424
- const entry = { ruleId, from: cur, to, reason: reason ?? null, evidence, actor: actor ?? 'unknown', at: new Date().toISOString(), prevHash };
425
- entry.entryHash = hashOf({ ...entry, entryHash: undefined });
426
- ledger.entries.push(entry);
427
- return { ok: true, entry };
428
- }
429
-
430
- function verifyLedger(ledger) {
431
- let prevHash = null;
432
- for (const e of ledger.entries) {
433
- if (e.prevHash !== prevHash) return { ok: false, reason: 'chain broken: prevHash mismatch' };
434
- const recomputed = hashOf({ ...e, entryHash: undefined });
435
- if (recomputed !== e.entryHash) return { ok: false, reason: `entry hash mismatch for ${e.ruleId} at ${e.at}` };
436
- prevHash = e.entryHash;
437
- }
438
- return { ok: true };
439
- }
440
-
441
- function historyFor(ledger, ruleId) { return ledger.entries.filter((e) => e.ruleId === ruleId); }
442
- function stateOf(ledger, ruleId) { return currentState(ledger, ruleId); }
443
-
444
- // EXTERNAL MODULE: external "node:path"
445
- var external_node_path_ = __webpack_require__(76760);
446
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/store.js
447
- // Persistence for the rule compiler: one directory per rule under `.agentic-security/rule-compiler/<id>/`
448
- // (`ir.json`, `ledger.json`, `evaluation.json`), the promoted custom-rule document at
449
- // `.agentic-security/rules/<id>.yml` (so the EXISTING `loadCustomRules`/`rule test` machinery picks it up with no
450
- // change), and a regression fixture pair at `.agentic-security/rule-compiler/fixtures/<id>/{vulnerable,clean}/`
451
- // using the SAME filename convention `runRuleTests` already reads (`vulnerable`/`clean` in the path).
452
-
453
-
454
-
455
-
456
-
457
-
458
- const DIR = 'rule-compiler';
459
- const store_EXT = { javascript: 'js', typescript: 'ts', python: 'py', go: 'go', ruby: 'rb', java: 'java', rust: 'rs', csharp: 'cs', php: 'php', any: 'txt' };
460
-
461
- function ruleDir(scanRoot, id) { return (0,state_dir.statePath)(scanRoot, DIR, id); }
462
-
463
- function loadLedger(scanRoot) {
464
- const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
465
- if (!external_node_fs_.existsSync(f)) return newLedger();
466
- try {
467
- const ledger = JSON.parse(external_node_fs_.readFileSync(f, 'utf8'));
468
- const v = verifyLedger(ledger);
469
- return v.ok ? ledger : { ...newLedger(), tampered: true, tamperReason: v.reason };
470
- } catch { return newLedger(); }
471
- }
472
-
473
- function saveLedger(scanRoot, ledger) {
474
- if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
475
- const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
476
- return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ledger, null, 2)) };
477
- }
478
-
479
- function saveIR(scanRoot, ir) {
480
- if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
481
- const f = external_node_path_.join(ruleDir(scanRoot, ir.id), 'ir.json');
482
- return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ir, null, 2)), file: f };
483
- }
484
-
485
- function loadIR(scanRoot, id) {
486
- const f = external_node_path_.join(ruleDir(scanRoot, id), 'ir.json');
487
- try { return JSON.parse(external_node_fs_.readFileSync(f, 'utf8')); } catch { return null; }
488
- }
489
-
490
- function saveEvaluation(scanRoot, id, evaluation) {
491
- if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
492
- const f = external_node_path_.join(ruleDir(scanRoot, id), 'evaluation.json');
493
- return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(evaluation, null, 2)) };
494
- }
495
-
496
- /** Write the regression fixtures a promoted rule needs: the SAME vulnerable/clean convention `runRuleTests`
497
- * already reads, scored against the exact corpus the rule was promoted on. */
498
- function writeFixtures(scanRoot, ir, corpus) {
499
- const ext = store_EXT[ir.languages[0]] || 'txt';
500
- const base = external_node_path_.join(ruleDir(scanRoot, ir.id), 'fixtures');
501
- if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
502
- const written = [];
503
- for (const p of corpus.positives) {
504
- const f = external_node_path_.join(base, 'vulnerable', `${p.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
505
- if ((0,state_dir.safeWriteState)(f, p.code)) written.push(f);
506
- }
507
- for (const n of corpus.negatives) {
508
- const f = external_node_path_.join(base, 'clean', `${n.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
509
- if ((0,state_dir.safeWriteState)(f, n.code)) written.push(f);
510
- }
511
- return { ok: true, written, glob: external_node_path_.join(base, '**', '*') };
512
- }
513
-
514
- /** Promote: write the compiled custom-rule document to the live rules directory. Does not touch the ledger —
515
- * the caller records the PROMOTED transition itself, so a failed write here can never produce an inconsistent
516
- * "promoted but not live" or "live but not recorded" state silently. */
517
- function publishCustomRule(scanRoot, ir) {
518
- const { ok, doc, errs } = compileToCustomRule(ir);
519
- if (!ok) return { ok: false, reason: `invalid rule IR: ${errs.join('; ')}` };
520
- if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
521
- const f = (0,state_dir.statePath)(scanRoot, 'rules', `${ir.id}.yml`);
522
- const yamlText = [
523
- `# Compiled by the rule compiler from finding ${ir.provenance.originatingFindingId} (${ir.provenance.evidenceState}).`,
524
- `- id: ${doc.id}`,
525
- ` title: ${JSON.stringify(doc.title)}`,
526
- ` severity: ${doc.severity}`,
527
- ` cwe: ${doc.cwe}`,
528
- ` languages: [${doc.languages.join(', ')}]`,
529
- ` match:`,
530
- ...(doc.match.pattern ? [` pattern: ${JSON.stringify(doc.match.pattern)}`] : []),
531
- ...(doc.match.allOf ? [` allOf:`, ...doc.match.allOf.map((p) => ` - ${JSON.stringify(p)}`), ` window: ${doc.match.window}`] : []),
532
- ...(doc.match.notMatch ? [` notMatch: ${JSON.stringify(doc.match.notMatch)}`] : []),
533
- ` message: ${JSON.stringify(doc.message)}`,
534
- '',
535
- ].join('\n');
536
- return { ok: (0,state_dir.safeWriteState)(f, yamlText), file: f };
537
- }
538
-
539
- function unpublishCustomRule(scanRoot, id) {
540
- const f = (0,state_dir.statePath)(scanRoot, 'rules', `${id}.yml`);
541
- try { if (external_node_fs_.existsSync(f)) external_node_fs_.unlinkSync(f); return { ok: true }; } catch (e) { return { ok: false, reason: e.message }; }
542
- }
543
-
544
- ;// CONCATENATED MODULE: ./src/posture/rule-compiler/cli.js
545
- // CLI surface: `agentic-security rules synthesize|evaluate|promote|status|rollback`.
546
- //
547
- // Distinct from the pre-existing `labs synthesize-rule` (posture/rule-synthesis.js), which proposes SUPPRESSION
548
- // rules from repeated false-positive triage verdicts — a different input, a different output and a different
549
- // command group on purpose, so the two are never confused at the CLI.
550
- //
551
- // Non-interactive by construction: no command reads stdin, every corpus evaluation is bounded (no network, no
552
- // model call — this is the deterministic half; a model may PROPOSE the candidate pattern this CLI is handed, but
553
- // it never decides promotion).
554
-
555
-
556
-
557
-
558
-
559
-
560
-
561
-
562
-
563
- function loadFinding(root, id) {
564
- const p = (0,state_dir.statePath)(root, 'last-scan.json');
565
- if (!external_node_fs_.existsSync(p)) return null;
566
- const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
567
- return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
568
- }
569
-
570
- function readJsonArg(pathOrInline) {
571
- if (!pathOrInline) return null;
572
- try { return JSON.parse(external_node_fs_.existsSync(pathOrInline) ? external_node_fs_.readFileSync(pathOrInline, 'utf8') : pathOrInline); } catch { return null; }
573
- }
574
-
575
- async function cmdRules(args, root) {
576
- const sub = args._[1];
577
- if (sub === 'synthesize') return cmdSynthesize(args, root);
578
- if (sub === 'evaluate') return cmdEvaluate(args, root);
579
- if (sub === 'promote') return cmdPromote(args, root);
580
- if (sub === 'status') return cmdStatus(args, root);
581
- if (sub === 'rollback') return cmdRollback(args, root);
582
- console.error('usage: rules synthesize <finding-id> --spec <file.json> | evaluate <rule-id> | promote <rule-id> | status [rule-id] | rollback <rule-id>');
583
- return 4;
584
- }
585
-
586
- // `--spec` carries exactly what a model or a human proposed: id/title/severity/cwe/family/languages/match/
587
- // remediation plus the corpus inputs (originalCode/patchedCode/nearbyCleanCode/protectedVariantsCode). This
588
- // command never invents a pattern; it only drafts the IR, checks eligibility and records DRAFT->CANDIDATE.
589
- async function cmdSynthesize(args, root) {
590
- const findingId = args._[2];
591
- const spec = readJsonArg(args.flags.spec);
592
- if (!findingId || !spec) { console.error('usage: rules synthesize <finding-id> --spec <file.json>'); return 4; }
593
- const finding = loadFinding(root, findingId);
594
- if (!finding) { console.error(`Finding ${findingId} not found in last scan.`); return 4; }
595
- const elig = checkEligibility(finding, { proofState: args.flags['proof-state'] || null });
596
- if (!elig.eligible) { console.error(`Not eligible for rule synthesis: ${elig.reasons.join('; ')}`); return 4; }
597
-
598
- const ir = draftRuleIR({ ...spec, originatingFindingId: finding.stableId ?? finding.id, originatingCommit: spec.originatingCommit ?? null, evidenceState: elig.evidenceState });
599
- const errs = validateRuleIR(ir);
600
- if (errs.length) { console.error(`Invalid rule: ${errs.join('; ')}`); return 4; }
601
-
602
- const ledger = loadLedger(root);
603
- const draft = recordTransition(ledger, { ruleId: ir.id, from: null, to: 'DRAFT', reason: `drafted from ${findingId}`, actor: args.flags.actor || 'agent' });
604
- if (!draft.ok) { console.error(draft.reason); return 4; }
605
- const cand = recordTransition(ledger, { ruleId: ir.id, from: 'DRAFT', to: 'CANDIDATE', reason: 'eligibility passed', evidence: { eligibility: elig }, actor: args.flags.actor || 'agent' });
606
- saveLedger(root, ledger);
607
- saveIR(root, { ...ir, state: 'CANDIDATE' });
608
- console.log(`Rule ${ir.id}: DRAFT -> CANDIDATE (digest ${ruleIRDigest(ir).slice(0, 12)})`);
609
- if (!cand.ok) console.error(cand.reason);
610
- return 0;
611
- }
612
-
613
- async function cmdEvaluate(args, root) {
614
- const id = args._[2];
615
- if (!id) { console.error('usage: rules evaluate <rule-id> --corpus <file.json>'); return 4; }
616
- const ir = loadIR(root, id);
617
- if (!ir) { console.error(`No rule IR found for ${id}. Run rules synthesize first.`); return 4; }
618
- const corpusSpec = readJsonArg(args.flags.corpus);
619
- if (!corpusSpec) { console.error('No corpus supplied. Pass --corpus <file.json> with originalCode (and optionally patchedCode/nearbyCleanCode/protectedVariantsCode).'); return 4; }
620
- const corpus = buildCorpus(ir, corpusSpec);
621
- const leakage = checkLeakage(JSON.stringify(corpusSpec), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [] });
622
- const gate = gatePromotion({ ir, corpus, leakageCheck: leakage, thresholds: args.flags.thresholds ? readJsonArg(args.flags.thresholds) : PROMOTION_DEFAULTS });
623
-
624
- const ledger = loadLedger(root);
625
- const cur = stateOf(ledger, id);
626
- 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' });
627
- saveLedger(root, ledger);
628
- saveEvaluation(root, id, gate);
629
- if (args.flags.json) console.log(JSON.stringify(gate, null, 2));
630
- else {
631
- console.log(`Rule ${id}: ${gate.pass ? 'VALIDATED' : 'gate FAILED'}`);
632
- console.log(` precision ${fmtPct(gate.evaluation.score.precision)} recall ${fmtPct(gate.evaluation.score.recall)} protected-failures ${gate.evaluation.score.protectedFailures}`);
633
- for (const r of gate.reasons) console.log(` - ${r}`);
634
- }
635
- 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/`); }
636
- return gate.pass ? 0 : 1;
637
- }
638
- const fmtPct = (n) => (n == null ? 'unmeasured' : `${(n * 100).toFixed(1)}%`);
639
-
640
- async function cmdPromote(args, root) {
641
- const id = args._[2];
642
- if (!id) { console.error('usage: rules promote <rule-id>'); return 4; }
643
- const ledger = loadLedger(root);
644
- if (ledger.tampered) { console.error(`Refusing: rule lifecycle ledger failed its integrity check (${ledger.tamperReason}).`); return 4; }
645
- if (stateOf(ledger, id) !== 'VALIDATED') { console.error(`Rule ${id} is not VALIDATED (run rules evaluate first); refusing to promote.`); return 4; }
646
- const ir = loadIR(root, id);
647
- if (!ir) { console.error(`No rule IR found for ${id}.`); return 4; }
648
- const pub = publishCustomRule(root, ir);
649
- if (!pub.ok) { console.error(`Promotion refused: ${pub.reason}`); return 4; }
650
- const t = recordTransition(ledger, { ruleId: id, from: 'VALIDATED', to: 'PROMOTED', reason: args.flags.reason || 'promoted', actor: args.flags.actor || 'operator' });
651
- saveLedger(root, ledger);
652
- console.log(`Rule ${id}: VALIDATED -> PROMOTED. Published to ${pub.file}.`);
653
- if (!t.ok) console.error(t.reason);
654
- return 0;
655
- }
656
-
657
- async function cmdRollback(args, root) {
658
- const id = args._[2];
659
- if (!id) { console.error('usage: rules rollback <rule-id> [--reason text]'); return 4; }
660
- const ledger = loadLedger(root);
661
- const cur = stateOf(ledger, id);
662
- if (cur !== 'PROMOTED') { console.error(`Rule ${id} is not PROMOTED (current: ${cur ?? 'unknown'}); nothing to roll back.`); return 4; }
663
- const un = unpublishCustomRule(root, id);
664
- const t = recordTransition(ledger, { ruleId: id, from: 'PROMOTED', to: 'ROLLED_BACK', reason: args.flags.reason || 'operator rollback', actor: args.flags.actor || 'operator' });
665
- saveLedger(root, ledger);
666
- console.log(`Rule ${id}: PROMOTED -> ROLLED_BACK.${un.ok ? '' : ` (warning: could not remove published rule file: ${un.reason})`}`);
667
- return t.ok ? 0 : 1;
668
- }
669
-
670
- async function cmdStatus(args, root) {
671
- const ledger = loadLedger(root);
672
- const id = args._[2];
673
- if (id) {
674
- const h = historyFor(ledger, id);
675
- if (!h.length) { console.error(`No history for rule ${id}.`); return 4; }
676
- if (args.flags.json) console.log(JSON.stringify(h, null, 2));
677
- else { console.log(`Rule ${id}: ${stateOf(ledger, id)}`); for (const e of h) console.log(` ${e.at} ${e.from ?? '(new)'} -> ${e.to} (${e.reason || ''})`); }
678
- return 0;
679
- }
680
- const ids = [...new Set(ledger.entries.map((e) => e.ruleId))];
681
- if (args.flags.json) { console.log(JSON.stringify(ids.map((rid) => ({ id: rid, state: stateOf(ledger, rid) })), null, 2)); return 0; }
682
- if (!ids.length) { console.log('No rules in the lifecycle ledger yet.'); return 0; }
683
- for (const rid of ids) console.log(` ${rid.padEnd(40)} ${stateOf(ledger, rid)}`);
684
- return 0;
685
- }
686
-
687
-
688
- /***/ })
689
-
690
- };