@clear-capabilities/agentic-security-scanner 0.174.0 → 0.176.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/bin/agentic-security.js +199 -28
  3. package/dist/2066.index.js +850 -0
  4. package/dist/2199.index.js +1 -1
  5. package/dist/2584.index.js +3332 -0
  6. package/dist/2923.index.js +13 -0
  7. package/dist/2946.index.js +81 -0
  8. package/dist/3196.index.js +27 -0
  9. package/dist/3727.index.js +292 -0
  10. package/dist/4168.index.js +509 -0
  11. package/dist/4281.index.js +993 -0
  12. package/dist/4978bec8fdf5c733dc85.json +283 -0
  13. package/dist/5099.index.js +96 -0
  14. package/dist/5616.index.js +1471 -0
  15. package/dist/5620.index.js +2370 -0
  16. package/dist/5817.index.js +714 -0
  17. package/dist/6333.index.js +98 -0
  18. package/dist/6655.index.js +3221 -0
  19. package/dist/7838.index.js +446 -974
  20. package/dist/818.index.js +4 -3
  21. package/dist/83.index.js +159 -0
  22. package/dist/8551.index.js +82 -0
  23. package/dist/8633.index.js +93 -0
  24. package/dist/8714.index.js +76 -76
  25. package/dist/8825.index.js +84 -0
  26. package/dist/932.index.js +186 -0
  27. package/dist/9560.index.js +358 -19
  28. package/dist/9800.index.js +6 -1
  29. package/dist/agentic-security.mjs +10 -10
  30. package/dist/agentic-security.mjs.sha256 +1 -1
  31. package/dist/df1e8683e7eda7b2b79c.js +29 -0
  32. package/package.json +7 -6
  33. package/src/artifact/CLAUDE.md +4 -0
  34. package/src/artifact/artifact-evidence.js +63 -0
  35. package/src/artifact/cosign.js +61 -0
  36. package/src/artifact/engine-source.js +72 -0
  37. package/src/artifact/oci-layout.js +47 -0
  38. package/src/artifact/registry.js +213 -0
  39. package/src/capabilities/tool-registry.js +2 -0
  40. package/src/language/haskell-security-rules.js +1 -1
  41. package/src/language/nixos-hardening.js +37 -0
  42. package/src/lineage/CLAUDE.md +4 -0
  43. package/src/lineage/identity-token.js +11 -0
  44. package/src/lineage/observation-adapters.js +13 -0
  45. package/src/lineage/runtime-edge-states.js +139 -0
  46. package/src/lineage/runtime-explorer-view.js +82 -0
  47. package/src/lineage/runtime-observation.js +11 -0
  48. package/src/mcp/CLAUDE.md +3 -1
  49. package/src/mcp/proof-tools.js +132 -0
  50. package/src/mcp/server.js +1 -1
  51. package/src/mcp/tools.js +3 -1
  52. package/src/posture/CLAUDE.md +23 -0
  53. package/src/posture/artifact-registry.js +4 -0
  54. package/src/posture/dnr/attack-facts.js +31 -0
  55. package/src/posture/dnr/cli.js +138 -0
  56. package/src/posture/dnr/detection-ir.js +123 -0
  57. package/src/posture/dnr/exposure-window.js +134 -0
  58. package/src/posture/dnr/hunt.js +84 -0
  59. package/src/posture/dnr/log-reader.js +189 -0
  60. package/src/posture/dnr/matchers.js +90 -0
  61. package/src/posture/dnr/outputs.js +262 -0
  62. package/src/posture/dnr/payload-classes.js +120 -0
  63. package/src/posture/dnr/redact.js +25 -0
  64. package/src/posture/dnr/store.js +57 -0
  65. package/src/posture/dnr/validate.js +64 -0
  66. package/src/posture/dnr/view.js +51 -0
  67. package/src/posture/evaluation/lab/arm-ollama.js +88 -0
  68. package/src/posture/evaluation/lab/arms.js +142 -0
  69. package/src/posture/evaluation/lab/cli.js +135 -0
  70. package/src/posture/evaluation/lab/dataset.js +139 -0
  71. package/src/posture/evaluation/lab/materialize.js +44 -0
  72. package/src/posture/evaluation/lab/neutralize.js +144 -0
  73. package/src/posture/evaluation/lab/report.js +176 -0
  74. package/src/posture/evaluation/lab/run.js +225 -0
  75. package/src/posture/evaluation/lab/score.js +135 -0
  76. package/src/posture/evaluation/lab/scoreboard.js +48 -0
  77. package/src/posture/evaluation/lab/stats.js +41 -0
  78. package/src/posture/evaluation/lab/store.js +53 -0
  79. package/src/posture/fleet/cli.js +248 -63
  80. package/src/posture/fleet/discover-edges.js +135 -0
  81. package/src/posture/fleet/enterprise-graph.js +148 -0
  82. package/src/posture/fleet/fleet-graph.js +9 -4
  83. package/src/posture/fleet/fleet-manifest.js +50 -5
  84. package/src/posture/fleet/job-runner.js +153 -0
  85. package/src/posture/fleet/job-store.js +136 -0
  86. package/src/posture/fleet/org-health.js +56 -0
  87. package/src/posture/fleet/scan-cache.js +112 -0
  88. package/src/posture/fleet/scan-child.js +29 -0
  89. package/src/posture/proof-fabric/cli.js +34 -6
  90. package/src/posture/proof-fabric/container.js +57 -0
  91. package/src/posture/proof-fabric/fix-proof.js +2 -1
  92. package/src/posture/proof-fabric/generate-python.js +129 -0
  93. package/src/posture/proof-fabric/generate.js +213 -0
  94. package/src/posture/proof-fabric/reproducer.js +3 -0
  95. package/src/posture/proof-fabric/runner.js +20 -11
  96. package/src/posture/proof-fabric/siblings.js +77 -0
  97. package/src/posture/routing/policy-router.js +103 -0
  98. package/src/posture/rule-compiler/cli.js +64 -6
  99. package/src/posture/rule-compiler/corpus.js +10 -2
  100. package/src/posture/rule-compiler/mutation.js +72 -1
  101. package/src/posture/rule-compiler/promotion.js +21 -5
  102. package/src/posture/rule-compiler/proposal.js +132 -0
  103. package/src/posture/rule-compiler/store.js +16 -0
@@ -0,0 +1,993 @@
1
+ export const id = 4281;
2
+ export const ids = [4281];
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
+ /***/ 84281:
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/proof-fabric/reproducer.js
88
+ var reproducer = __webpack_require__(37055);
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__(12090);
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
+ if (!String(code).trim()) return null;
240
+ const indented = code.split('\n').map((l) => (l ? ` ${l}` : l)).join('\n');
241
+ return `function ${name}() {\n${indented}\n}\n${name}();\n`;
242
+ }
243
+
244
+ /** Insert a pass-through local for the first simple right-hand-side identifier assigned with `=` (indirection,
245
+ * no behavior change): `x = y;` becomes `const indirectN = y; x = indirectN;`. */
246
+ function insertIndirection(code) {
247
+ const m = /^(\s*)([A-Za-z_][A-Za-z0-9_.]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*;/m.exec(code);
248
+ if (!m) return null;
249
+ const [whole, indent, lhs, rhs] = m;
250
+ const varName = `indirect_${Math.abs(_hash(rhs)) % 1000}`;
251
+ if (code.includes(varName)) return null;
252
+ return code.replace(whole, `${indent}const ${varName} = ${rhs};\n${indent}${lhs} = ${varName};`);
253
+ }
254
+
255
+ function _hash(s) { let h = 0; for (const c of s) h = (h * 31 + c.charCodeAt(0)) | 0; return h; }
256
+
257
+ // ---- the four mutators the PRD lists beyond rename / wrapper / indirection --------------------------------------------------
258
+ // Each is a deterministic, table-driven textual rewrite that returns null when it does not apply. Tables are deliberately
259
+ // small and conservative: an entry is here only when both sides are the same API family used the same way, so the claim "same
260
+ // vulnerability, different shape" stays true. They are applied to the vulnerable side (does the rule still fire?) and to the safe
261
+ // side (does it still decline?); the safe side is where a rule keyed to ONE sanitizer's name is caught.
262
+
263
+ // equivalent APIs: the same operation through a sibling entry point
264
+ const EQUIVALENT_APIS = Object.freeze([
265
+ [/\bchild_process\.exec\(/, 'child_process.execSync('], [/\bexecSync\(/, 'exec('], [/\bos\.system\(/, 'os.popen('],
266
+ [/\bdb\.query\(/, 'db.execute('], [/\bconnection\.query\(/, 'connection.execute('], [/\bcursor\.execute\(/, 'cursor.executemany('],
267
+ [/\bfs\.readFile\(/, 'fs.readFileSync('], [/\bfs\.readFileSync\(/, 'fs.readFile('], [/\bfs\.writeFile\(/, 'fs.writeFileSync('],
268
+ [/\bhttp\.get\(/, 'https.get('], [/\baxios\.get\(/, 'axios.request('], [/\bres\.send\(/, 'res.end('],
269
+ [/\bos\.Open\(/, 'os.OpenFile('], [/\bsubprocess\.call\(/, 'subprocess.run('], [/\bsubprocess\.run\(/, 'subprocess.call('],
270
+ ]);
271
+ function equivalentApi(code) {
272
+ for (const [from, to] of EQUIVALENT_APIS) if (from.test(code)) return code.replace(from, to);
273
+ return null;
274
+ }
275
+
276
+ // alternate sanitizers: a different, equally valid way to neutralize the same input
277
+ const ALTERNATE_SANITIZERS = Object.freeze([
278
+ [/\bescapeHtml\(/, 'validator.escape('], [/\bvalidator\.escape\(/, 'escapeHtml('], [/\bDOMPurify\.sanitize\(/, 'sanitizeHtml('], [/\bsanitizeHtml\(/, 'DOMPurify.sanitize('],
279
+ [/\bshlex\.quote\(/, 'pipes.quote('], [/\bhtml\.escape\(/, 'markupsafe.escape('], [/\bhtml\.EscapeString\(/, 'template.HTMLEscapeString('],
280
+ [/\bencodeURIComponent\(/, 'encodeURI('], [/\bpath\.basename\(/, 'path.parse('], [/\bparseInt\(/, 'Number('], [/\bNumber\(/, 'parseInt('],
281
+ [/\bstrconv\.Atoi\(/, 'strconv.ParseInt('], [/\bint\(/, 'abs('],
282
+ ]);
283
+ function alternateSanitizer(code) {
284
+ for (const [from, to] of ALTERNATE_SANITIZERS) if (from.test(code)) return code.replace(from, to);
285
+ return null;
286
+ }
287
+
288
+ // framework variants: the same untrusted input reached through another framework's accessor
289
+ const FRAMEWORK_VARIANTS = Object.freeze([
290
+ [/\breq\.body\./g, 'ctx.request.body.'], [/\breq\.query\./g, 'ctx.query.'], [/\breq\.params\./g, 'ctx.params.'],
291
+ [/\brequest\.args\.get\(/g, 'request.form.get('], [/\brequest\.form\.get\(/g, 'request.args.get('], [/\$_GET\[/g, '$_REQUEST['], [/\$_POST\[/g, '$_REQUEST['],
292
+ [/\br\.URL\.Query\(\)\.Get\(/g, 'r.FormValue('], [/\brequest\.getParameter\(/g, 'request.getHeader('],
293
+ ]);
294
+ function frameworkVariant(code) {
295
+ for (const [from, to] of FRAMEWORK_VARIANTS) if (from.test(code)) { from.lastIndex = 0; return code.replace(from, to); }
296
+ return null;
297
+ }
298
+
299
+ // reordering: swap the first pair of ADJACENT simple statements that share no identifier, so neither feeds the other. This is a
300
+ // syntactic independence test, not a data-flow proof; it is applied to rule-corpus snippets, where a swap of two unrelated
301
+ // statements is what a different author's version of the same code would plausibly look like.
302
+ const CONTROL = /^\s*(?:if|else|for|while|switch|case|return|try|catch|finally|do|break|continue|throw|function|def|class|import|from|package|\}|\{|@|\/\/|#)\b|^\s*[}{]\s*$/;
303
+ function reorderStatements(code) {
304
+ const lines = code.split('\n');
305
+ const simple = (l) => l.trim() && !CONTROL.test(l) && /[;)]\s*$|^[^=]*=[^=].*[^{]$/.test(l.trim()) && !/[{]\s*$/.test(l);
306
+ const ids = (l) => new Set([...l.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*\b/g)].map((m) => m[0]).filter((x) => !RESERVED.has(x)));
307
+ for (let i = 0; i + 1 < lines.length; i++) {
308
+ if (!simple(lines[i]) || !simple(lines[i + 1])) continue;
309
+ const a = ids(lines[i]); const b = ids(lines[i + 1]);
310
+ if ([...a].some((x) => b.has(x))) continue;
311
+ const out = [...lines]; [out[i], out[i + 1]] = [out[i + 1], out[i]];
312
+ return out.join('\n');
313
+ }
314
+ return null;
315
+ }
316
+
317
+ const MUTATORS = Object.freeze({
318
+ 'variable-rename': variableRename, 'wrap-in-function': wrapInFunction, 'insert-indirection': insertIndirection,
319
+ 'equivalent-api': equivalentApi, 'reorder-statements': reorderStatements, 'alternate-sanitizer': alternateSanitizer, 'framework-variant': frameworkVariant,
320
+ });
321
+ const MUTATOR_NAMES = Object.freeze(Object.keys(MUTATORS));
322
+
323
+ /** Every mutator applied to `code`; mutators that don't apply (return null) are omitted, never silently skipped without saying so. */
324
+ function generateVariants(code) {
325
+ const out = [];
326
+ for (const [name, fn] of Object.entries(MUTATORS)) {
327
+ let variant = null;
328
+ try { variant = fn(code); } catch { variant = null; }
329
+ if (variant && variant !== code) out.push({ mutator: name, code: variant });
330
+ }
331
+ return out;
332
+ }
333
+
334
+ /** Which of the seven mutators produced a variant for this code, and which did not (so a report can say what was not exercised). */
335
+ function mutatorCoverage(code) {
336
+ const applied = new Set(generateVariants(code).map((v) => v.mutator));
337
+ return { applied: MUTATOR_NAMES.filter((n) => applied.has(n)), notApplicable: MUTATOR_NAMES.filter((n) => !applied.has(n)) };
338
+ }
339
+
340
+ // EXTERNAL MODULE: ./src/posture/custom-rules.js + 1 modules
341
+ var custom_rules = __webpack_require__(9049);
342
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/corpus.js
343
+ // Automatic corpus creation and scoring for ONE candidate rule.
344
+ //
345
+ // Positive corpus: the original vulnerable snippet plus its generated sibling variants (mutation.js).
346
+ // Negative corpus: an explicit patched/clean variant the caller supplies, nearby clean patterns, protected
347
+ // (sanitizer/guard) variants, and the NEGATIVE mutations of those (same mutators, applied to the safe side) — a
348
+ // candidate rule must decline on ALL of them, not just the one hand-picked negative.
349
+ //
350
+ // Scoring reuses the exact runtime matcher (`runRule` in `../custom-rules.js`), never a second implementation —
351
+ // the score a rule gets here is the score it will actually produce once promoted.
352
+
353
+
354
+
355
+
356
+ function toRuntimeRule(ir) {
357
+ const { ok, doc, errs } = compileToCustomRule(ir);
358
+ if (!ok) throw new Error(`cannot build corpus for an invalid rule IR: ${errs.join('; ')}`);
359
+ const regexes = doc.match.allOf ? doc.match.allOf.map((p) => new RegExp(p, 'g')) : [new RegExp(doc.match.pattern, 'g')];
360
+ return {
361
+ id: doc.id, title: doc.title, severity: doc.severity, cwe: doc.cwe, languages: doc.languages, message: doc.message,
362
+ regexes, requireAll: !!doc.match.allOf, windowLines: doc.match.window ?? 5,
363
+ notMatch: doc.match.notMatch ? new RegExp(doc.match.notMatch) : null,
364
+ };
365
+ }
366
+
367
+ 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' };
368
+
369
+ function buildCorpus(ir, { originalCode, patchedCode = null, nearbyCleanCode = [], protectedVariantsCode = [] } = {}) {
370
+ const positives = [{ label: 'original', code: originalCode }];
371
+ for (const v of generateVariants(originalCode)) positives.push({ label: `sibling:${v.mutator}`, code: v.code });
372
+
373
+ const negatives = [];
374
+ if (patchedCode) {
375
+ negatives.push({ label: 'patched', code: patchedCode });
376
+ for (const v of generateVariants(patchedCode)) negatives.push({ label: `patched-sibling:${v.mutator}`, code: v.code });
377
+ }
378
+ // The safe side is mutated too (rename, wrapper, equivalent API, ALTERNATE SANITIZER, framework variant, ...): a rule keyed to one
379
+ // sanitizer's name or one framework's accessor fires on the sibling that uses another, and that is a protected-negative failure.
380
+ nearbyCleanCode.forEach((code, i) => {
381
+ negatives.push({ label: `nearby-clean-${i}`, code });
382
+ for (const v of generateVariants(code)) negatives.push({ label: `nearby-clean-${i}-sibling:${v.mutator}`, code: v.code });
383
+ });
384
+ protectedVariantsCode.forEach((code, i) => {
385
+ negatives.push({ label: `protected-${i}`, code });
386
+ for (const v of generateVariants(code)) negatives.push({ label: `protected-${i}-sibling:${v.mutator}`, code: v.code });
387
+ });
388
+
389
+ return { positives, negatives };
390
+ }
391
+
392
+ function scoreRule(ir, corpus) {
393
+ const rule = toRuntimeRule(ir);
394
+ const lang = ir.languages[0] || 'javascript';
395
+ const file = EXT[lang] || 'x.txt';
396
+ const run = (code) => (0,custom_rules/* runRule */.OA)(rule, file, code).length > 0;
397
+
398
+ const posResults = corpus.positives.map((p) => ({ ...p, fired: run(p.code) }));
399
+ const negResults = corpus.negatives.map((n) => ({ ...n, fired: run(n.code) }));
400
+
401
+ const tp = posResults.filter((p) => p.fired).length;
402
+ const fn = posResults.length - tp;
403
+ const fp = negResults.filter((n) => n.fired).length;
404
+ const tn = negResults.length - fp;
405
+ const precision = tp + fp === 0 ? null : tp / (tp + fp);
406
+ const recall = corpus.positives.length === 0 ? null : tp / corpus.positives.length;
407
+ // "Protected negative failures" per PRD 3: a rule firing on a sanitizer/guard-carrying variant specifically.
408
+ const protectedFailures = negResults.filter((n) => n.label.startsWith('protected-') && n.fired).length;
409
+
410
+ return { precision, recall, tp, fp, tn, fn, protectedFailures, positives: posResults, negatives: negResults };
411
+ }
412
+
413
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/promotion.js
414
+ // Promotion gate (PRD 3 "Promotion Gate"): precision/recall thresholds, zero protected-negative failures, zero
415
+ // benchmark leakage. A candidate rule does NOT automatically become a production rule — `evaluateRule` only
416
+ // scores; `gatePromotion` only judges; the lifecycle ledger (`lifecycle.js`) is the one place a PROMOTED state is
417
+ // actually recorded, and nothing in this module writes to it.
418
+
419
+
420
+ const PROMOTION_DEFAULTS = Object.freeze({ minPrecision: 0.95, minRecall: 0.80, maxProtectedFailures: 0 });
421
+
422
+ // Deliberately independent of posture/evaluation/custody.js: that module's term list and guard are reserved for
423
+ // the evaluation custodian's sealed-label boundary (QA-002.AC03), and a test enforces that nothing outside
424
+ // posture/evaluation/ may import it. The anti-cheating need here is smaller and different in kind — a rule
425
+ // synthesis prompt/corpus must not embed a benchmark name or an advisory id — so it gets its own small, independent
426
+ // checker rather than reaching across that isolation boundary.
427
+ const ADVISORY_ID = /\b(?:CVE|GHSA|CWE)-[A-Za-z0-9-]+\b/i;
428
+
429
+ // What a synthesis agent must never see (PRD 3, anti-cheating): benchmark answer keys, hidden test labels, CWE-bearing hidden file
430
+ // names, vulnerability comments and protected test metadata. These defaults are always applied; a caller adds its own benchmark names.
431
+ const DEFAULT_BENCHMARK_NAMES = Object.freeze(['owasp benchmark', 'juliet', 'sard test', 'cve-replay', 'corpus-baseline', 'answer key', 'ground truth', 'adjudicated', 'hidden test', 'expectedresults']);
432
+ const CWE_FILENAME = /(^|[\\/])[^\\/]*cwe[-_]?\d+[^\\/]*$/i;
433
+ const ANSWER_KEY_FILENAME = /(^|[\\/])(?:labels?|answers?|expected|ground[-_]?truth|answer[-_]?key|oracle|result)[^\\/]*\.(?:json|jsonl|ya?ml|csv|txt)$/i;
434
+ const VULNERABILITY_COMMENT = /(?:\/\/|#|\/\*|^\s*\*)\s*(?:POTENTIAL FLAW|FLAW\b|INCIDENTAL|BAD\b|GOOD\b|vulnerab\w*|insecure|exploit\w*)/im;
435
+
436
+ /**
437
+ * Anti-cheating gate. Fails closed: any hit makes `ok` false, and the synthesis loop will not report a pass.
438
+ * @param {string} promptText everything the synthesis agent would be shown (corpus code, spec text)
439
+ * @param {{benchmarkNames?: string[], fileNames?: string[]}} opts
440
+ */
441
+ function checkLeakage(promptText, { benchmarkNames = [], fileNames = [] } = {}) {
442
+ const hay = String(promptText ?? '');
443
+ const lower = hay.toLowerCase();
444
+ const offending = [];
445
+ for (const name of [...DEFAULT_BENCHMARK_NAMES, ...benchmarkNames]) if (name && lower.includes(String(name).toLowerCase())) offending.push(`benchmark name: ${name}`);
446
+ const m = ADVISORY_ID.exec(hay);
447
+ if (m) offending.push(`identifier: ${m[0]}`);
448
+ if (VULNERABILITY_COMMENT.test(hay)) offending.push('a comment that describes the vulnerability');
449
+ for (const f of fileNames) {
450
+ if (CWE_FILENAME.test(String(f))) offending.push(`weakness-bearing file name: ${f}`);
451
+ if (ANSWER_KEY_FILENAME.test(String(f))) offending.push(`answer-key file name: ${f}`);
452
+ }
453
+ return { ok: offending.length === 0, offendingTerms: offending };
454
+ }
455
+
456
+ function evaluateRule(ir, corpus, thresholds = PROMOTION_DEFAULTS) {
457
+ const score = scoreRule(ir, corpus);
458
+ const t = { ...PROMOTION_DEFAULTS, ...thresholds };
459
+ const reasons = [];
460
+ if (score.precision === null) reasons.push('precision unmeasured (no positive or negative corpus fired)');
461
+ else if (score.precision < t.minPrecision) reasons.push(`precision ${(score.precision * 100).toFixed(1)}% below ${(t.minPrecision * 100).toFixed(0)}%`);
462
+ if (score.recall === null) reasons.push('recall unmeasured (empty positive corpus)');
463
+ else if (score.recall < t.minRecall) reasons.push(`recall ${(score.recall * 100).toFixed(1)}% below ${(t.minRecall * 100).toFixed(0)}%`);
464
+ if (score.protectedFailures > t.maxProtectedFailures) reasons.push(`${score.protectedFailures} protected-negative failure(s) (max ${t.maxProtectedFailures})`);
465
+ return { pass: reasons.length === 0, reasons, score, thresholds: t };
466
+ }
467
+
468
+ /** The one promotion decision. Never auto-applied: a caller still has to act on `pass:true` by recording a
469
+ * lifecycle transition. Localization ("acceptable") is a human/caller judgment this function cannot make from
470
+ * line/column alone; it is surfaced for review, never silently assumed. */
471
+ function gatePromotion({ ir, corpus, leakageCheck, thresholds } = {}) {
472
+ const evalResult = evaluateRule(ir, corpus, thresholds);
473
+ const reasons = [...evalResult.reasons];
474
+ if (!leakageCheck || leakageCheck.ok !== true) reasons.push(leakageCheck ? `leakage check failed: ${leakageCheck.offendingTerms.join(', ')}` : 'leakage check was not run');
475
+ return { pass: reasons.length === 0, reasons, evaluation: evalResult };
476
+ }
477
+
478
+ // EXTERNAL MODULE: external "node:crypto"
479
+ var external_node_crypto_ = __webpack_require__(77598);
480
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/lifecycle.js
481
+ // Rule lifecycle ledger: DRAFT -> CANDIDATE -> VALIDATED -> PROMOTED -> DEPRECATED/ROLLED_BACK.
482
+ //
483
+ // Append-only, hash-chained (same idiom as remediation-ledger.js / invariants/lifecycle.js): each entry links the
484
+ // previous entry's hash, so a dropped or edited middle record breaks the chain and `verifyLedger` catches it. A
485
+ // rule cannot promote itself: `transition` only records a transition a caller already decided; `advance`-style
486
+ // guarding on VALID edges lives here so no caller can jump DRAFT straight to PROMOTED.
487
+
488
+
489
+
490
+ const LEDGER_SCHEMA = 'agentic-security/rule-lifecycle-ledger';
491
+ const EDGES = Object.freeze({
492
+ DRAFT: ['CANDIDATE'], CANDIDATE: ['VALIDATED', 'DRAFT'], VALIDATED: ['PROMOTED', 'DRAFT'],
493
+ PROMOTED: ['DEPRECATED', 'ROLLED_BACK'], DEPRECATED: [], ROLLED_BACK: ['CANDIDATE'],
494
+ });
495
+
496
+ const hashOf = (entry) => (0,external_node_crypto_.createHash)('sha256').update(JSON.stringify(entry)).digest('hex');
497
+
498
+ function newLedger() { return { schema: LEDGER_SCHEMA, entries: [] }; }
499
+
500
+ function currentState(ledger, ruleId) {
501
+ for (let i = ledger.entries.length - 1; i >= 0; i--) if (ledger.entries[i].ruleId === ruleId) return ledger.entries[i].to;
502
+ return null;
503
+ }
504
+
505
+ /**
506
+ * Record a transition. Refuses an edge not in EDGES, and refuses DRAFT->DRAFT re-entry for a rule that has never
507
+ * existed (the first entry for a rule id must be `from: null, to: 'DRAFT'`).
508
+ */
509
+ function recordTransition(ledger, { ruleId, from, to, reason, evidence = null, actor }) {
510
+ if (!RULE_STATES.includes(to)) return { ok: false, reason: `unknown target state: ${to}` };
511
+ const cur = currentState(ledger, ruleId);
512
+ if (cur === null) {
513
+ if (from !== null || to !== 'DRAFT') return { ok: false, reason: 'first transition for a rule must be null -> DRAFT' };
514
+ } else {
515
+ if (from !== cur) return { ok: false, reason: `stale transition: current state is ${cur}, not ${from}` };
516
+ if (!EDGES[cur].includes(to)) return { ok: false, reason: `cannot go from ${cur} to ${to}` };
517
+ }
518
+ const prevHash = ledger.entries.length ? ledger.entries[ledger.entries.length - 1].entryHash : null;
519
+ const entry = { ruleId, from: cur, to, reason: reason ?? null, evidence, actor: actor ?? 'unknown', at: new Date().toISOString(), prevHash };
520
+ entry.entryHash = hashOf({ ...entry, entryHash: undefined });
521
+ ledger.entries.push(entry);
522
+ return { ok: true, entry };
523
+ }
524
+
525
+ function verifyLedger(ledger) {
526
+ let prevHash = null;
527
+ for (const e of ledger.entries) {
528
+ if (e.prevHash !== prevHash) return { ok: false, reason: 'chain broken: prevHash mismatch' };
529
+ const recomputed = hashOf({ ...e, entryHash: undefined });
530
+ if (recomputed !== e.entryHash) return { ok: false, reason: `entry hash mismatch for ${e.ruleId} at ${e.at}` };
531
+ prevHash = e.entryHash;
532
+ }
533
+ return { ok: true };
534
+ }
535
+
536
+ function historyFor(ledger, ruleId) { return ledger.entries.filter((e) => e.ruleId === ruleId); }
537
+ function stateOf(ledger, ruleId) { return currentState(ledger, ruleId); }
538
+
539
+ // EXTERNAL MODULE: external "node:path"
540
+ var external_node_path_ = __webpack_require__(76760);
541
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/store.js
542
+ // Persistence for the rule compiler: one directory per rule under `.agentic-security/rule-compiler/<id>/`
543
+ // (`ir.json`, `ledger.json`, `evaluation.json`), the promoted custom-rule document at
544
+ // `.agentic-security/rules/<id>.yml` (so the EXISTING `loadCustomRules`/`rule test` machinery picks it up with no
545
+ // change), and a regression fixture pair at `.agentic-security/rule-compiler/fixtures/<id>/{vulnerable,clean}/`
546
+ // using the SAME filename convention `runRuleTests` already reads (`vulnerable`/`clean` in the path).
547
+
548
+
549
+
550
+
551
+
552
+
553
+ const DIR = 'rule-compiler';
554
+ const store_EXT = { javascript: 'js', typescript: 'ts', python: 'py', go: 'go', ruby: 'rb', java: 'java', rust: 'rs', csharp: 'cs', php: 'php', any: 'txt' };
555
+
556
+ function ruleDir(scanRoot, id) { return (0,state_dir.statePath)(scanRoot, DIR, id); }
557
+
558
+ function loadLedger(scanRoot) {
559
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
560
+ if (!external_node_fs_.existsSync(f)) return newLedger();
561
+ try {
562
+ const ledger = JSON.parse(external_node_fs_.readFileSync(f, 'utf8'));
563
+ const v = verifyLedger(ledger);
564
+ return v.ok ? ledger : { ...newLedger(), tampered: true, tamperReason: v.reason };
565
+ } catch { return newLedger(); }
566
+ }
567
+
568
+ function saveLedger(scanRoot, ledger) {
569
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
570
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
571
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ledger, null, 2)) };
572
+ }
573
+
574
+ function saveIR(scanRoot, ir) {
575
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
576
+ const f = external_node_path_.join(ruleDir(scanRoot, ir.id), 'ir.json');
577
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(ir, null, 2)), file: f };
578
+ }
579
+
580
+ function loadIR(scanRoot, id) {
581
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'ir.json');
582
+ try { return JSON.parse(external_node_fs_.readFileSync(f, 'utf8')); } catch { return null; }
583
+ }
584
+
585
+ function saveJson(scanRoot, id, name, doc) {
586
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
587
+ const f = external_node_path_.join(ruleDir(scanRoot, id), name);
588
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(doc, null, 2)), file: f };
589
+ }
590
+ 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; } }
591
+ /** The corpus a rule was synthesized on, kept so `rules evaluate <id>` needs no flag and the evidence is the same corpus. */
592
+ const saveCorpus = (r, id, spec) => saveJson(r, id, 'corpus.json', spec);
593
+ const loadCorpus = (r, id) => loadJson(r, id, 'corpus.json');
594
+ /** Every synthesis attempt: strategy, match, score and why it did not pass. */
595
+ const saveSynthesis = (r, id, syn) => saveJson(r, id, 'synthesis.json', syn);
596
+ const loadSynthesis = (r, id) => loadJson(r, id, 'synthesis.json');
597
+ /** The rule's provenance record (PRD 3 requirement 7). */
598
+ const saveProvenance = (r, id, doc) => saveJson(r, id, 'provenance.json', doc);
599
+ const loadProvenance = (r, id) => loadJson(r, id, 'provenance.json');
600
+
601
+ function saveEvaluation(scanRoot, id, evaluation) {
602
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
603
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'evaluation.json');
604
+ return { ok: (0,state_dir.safeWriteState)(f, JSON.stringify(evaluation, null, 2)) };
605
+ }
606
+
607
+ /** Write the regression fixtures a promoted rule needs: the SAME vulnerable/clean convention `runRuleTests`
608
+ * already reads, scored against the exact corpus the rule was promoted on. */
609
+ function writeFixtures(scanRoot, ir, corpus) {
610
+ const ext = store_EXT[ir.languages[0]] || 'txt';
611
+ const base = external_node_path_.join(ruleDir(scanRoot, ir.id), 'fixtures');
612
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
613
+ const written = [];
614
+ for (const p of corpus.positives) {
615
+ const f = external_node_path_.join(base, 'vulnerable', `${p.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
616
+ if ((0,state_dir.safeWriteState)(f, p.code)) written.push(f);
617
+ }
618
+ for (const n of corpus.negatives) {
619
+ const f = external_node_path_.join(base, 'clean', `${n.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
620
+ if ((0,state_dir.safeWriteState)(f, n.code)) written.push(f);
621
+ }
622
+ return { ok: true, written, glob: external_node_path_.join(base, '**', '*') };
623
+ }
624
+
625
+ /** Promote: write the compiled custom-rule document to the live rules directory. Does not touch the ledger —
626
+ * the caller records the PROMOTED transition itself, so a failed write here can never produce an inconsistent
627
+ * "promoted but not live" or "live but not recorded" state silently. */
628
+ function publishCustomRule(scanRoot, ir) {
629
+ const { ok, doc, errs } = compileToCustomRule(ir);
630
+ if (!ok) return { ok: false, reason: `invalid rule IR: ${errs.join('; ')}` };
631
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
632
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${ir.id}.yml`);
633
+ const yamlText = [
634
+ `# Compiled by the rule compiler from finding ${ir.provenance.originatingFindingId} (${ir.provenance.evidenceState}).`,
635
+ `- id: ${doc.id}`,
636
+ ` title: ${JSON.stringify(doc.title)}`,
637
+ ` severity: ${doc.severity}`,
638
+ ` cwe: ${doc.cwe}`,
639
+ ` languages: [${doc.languages.join(', ')}]`,
640
+ ` match:`,
641
+ ...(doc.match.pattern ? [` pattern: ${JSON.stringify(doc.match.pattern)}`] : []),
642
+ ...(doc.match.allOf ? [` allOf:`, ...doc.match.allOf.map((p) => ` - ${JSON.stringify(p)}`), ` window: ${doc.match.window}`] : []),
643
+ ...(doc.match.notMatch ? [` notMatch: ${JSON.stringify(doc.match.notMatch)}`] : []),
644
+ ` message: ${JSON.stringify(doc.message)}`,
645
+ '',
646
+ ].join('\n');
647
+ return { ok: (0,state_dir.safeWriteState)(f, yamlText), file: f };
648
+ }
649
+
650
+ function unpublishCustomRule(scanRoot, id) {
651
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${id}.yml`);
652
+ try { if (external_node_fs_.existsSync(f)) external_node_fs_.unlinkSync(f); return { ok: true }; } catch (e) { return { ok: false, reason: e.message }; }
653
+ }
654
+
655
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/proposal.js
656
+ // The synthesis loop for the rule compiler (PRD 3, requirement 5): propose, compile, test positives, test negatives, mutation test,
657
+ // score, revise, repeat with bounded attempts, emit a candidate.
658
+ //
659
+ // "Models propose rules. Evidence promotes rules." A model's proposal (a `match` in the spec) is tried first when there is one.
660
+ // When there is none, or it fails, this module proposes deterministically from the two pieces of evidence it has: the vulnerable
661
+ // code and its patched twin. The lines that exist only in the vulnerable version say what the flaw looks like; the calls that exist
662
+ // only in the patched version say what a safe version looks like (and become the `notMatch` that keeps the rule quiet on safe files).
663
+ // No model is consulted here and nothing here promotes a rule: the loop returns attempts and a best candidate, and promotion stays
664
+ // with the gate and the lifecycle ledger.
665
+ //
666
+ // Every attempt is scored against the real corpus (positives with their mutations, negatives with theirs) by the same matcher the
667
+ // rule will run on once promoted. An attempt that does not clear the gate is revised from WHY it failed: low recall generalizes,
668
+ // a negative that fires adds the safe version's names to `notMatch`.
669
+
670
+
671
+
672
+
673
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\\/]/g, '\\$&');
674
+ const KEYWORDS = new Set(['if', 'else', 'for', 'while', 'return', 'function', 'const', 'let', 'var', 'new', 'await', 'async', 'try', 'catch', 'throw', 'typeof', 'def', 'class', 'import', 'from', 'with', 'in', 'of', 'and', 'or', 'not', 'is', 'func', 'fn', 'public', 'private', 'static', 'void', 'int', 'string']);
675
+ const SOURCES = [
676
+ String.raw`req(?:uest)?\.(?:body|query|params|headers|cookies)\b`, String.raw`ctx\.(?:query|params|request\.body)\b`, String.raw`request\.(?:args|form|values|json|GET|POST)\b`,
677
+ String.raw`\$_(?:GET|POST|REQUEST|COOKIE)\b`, String.raw`process\.argv\b`, String.raw`os\.Args\b`, String.raw`\bgetParameter\s*\(`, String.raw`r\.(?:URL\.Query\(\)|FormValue)\b`,
678
+ ];
679
+
680
+ const meaningful = (l) => { const t = l.trim(); return t.length >= 8 && !/^(?:\/\/|#|\/\*|\*|[{}()\];,]+$)/.test(t); };
681
+
682
+ /** Lines (trimmed) present only in `a`. */
683
+ function onlyIn(a, b) {
684
+ const bs = new Set(String(b ?? '').split('\n').map((l) => l.trim()));
685
+ return String(a ?? '').split('\n').filter((l) => meaningful(l) && !bs.has(l.trim())).map((l) => l.trim());
686
+ }
687
+
688
+ /** Call names (a.b.c) in some code, in order of appearance, without keywords. */
689
+ function callNames(code) {
690
+ const out = [];
691
+ for (const m of String(code).matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g)) if (!KEYWORDS.has(m[1]) && !out.includes(m[1])) out.push(m[1]);
692
+ return out;
693
+ }
694
+
695
+ /** A regular expression for one source line: the call names stay, strings and the other identifiers become classes. */
696
+ function generalizeLine(line) {
697
+ const keep = new Set(callNames(line));
698
+ let out = ''; let i = 0;
699
+ while (i < line.length) {
700
+ const c = line[i];
701
+ if (/\s/.test(c)) { const before = line[i - 1] ?? ''; while (/\s/.test(line[i] ?? '')) i++; out += /[\w$]/.test(before) && /[\w$]/.test(line[i] ?? '') ? String.raw`\s+` : String.raw`\s*`; continue; }
702
+ if (c === '"' || c === "'" || c === '`') { const q = c; let j = i + 1; while (j < line.length && line[j] !== q) j += line[j] === '\\' ? 2 : 1; out += q === '`' ? '`[^`]*`' : `(?:'[^']*'|"[^"]*")`; i = j + 1; continue; }
703
+ const id = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*/.exec(line.slice(i));
704
+ if (id) { const tok = id[0]; const isCall = line[i + tok.length] === '(' || keep.has(tok); out += isCall || KEYWORDS.has(tok) ? esc(tok) : String.raw`[A-Za-z_$][\w$.]*`; i += tok.length; continue; }
705
+ const num = /^\d+(?:\.\d+)?/.exec(line.slice(i));
706
+ if (num) { out += String.raw`\d+(?:\.\d+)?`; i += num[0].length; continue; }
707
+ out += esc(c); i++;
708
+ }
709
+ return out;
710
+ }
711
+
712
+ const sinkOf = (line) => callNames(line).filter((n) => !/^(?:console|logger|log)\b/.test(n))[0] ?? null;
713
+ const interpolation = String.raw`(?:\+|\$\{|%s|%d|\.format\s*\(|\bf["']|\|\|)`;
714
+
715
+ /** Ordered proposals, most specific first. Each is {strategy, match}; `match.notMatch` is added by `withSafeNames`. */
716
+ function proposeCandidates({ vulnerableCode, patchedCode = null }) {
717
+ const vuln = onlyIn(vulnerableCode, patchedCode);
718
+ const lines = vuln.length ? vuln : String(vulnerableCode).split('\n').filter(meaningful).map((l) => l.trim()).filter((l) => callNames(l).length);
719
+ const out = []; const seen = new Set();
720
+ const add = (strategy, match) => { const k = JSON.stringify(match); if (!seen.has(k)) { seen.add(k); out.push({ strategy, match }); } };
721
+ for (const l of lines.slice(0, 3)) add('line-shape', { pattern: generalizeLine(l) });
722
+ for (const l of lines.slice(0, 3)) {
723
+ const sink = sinkOf(l);
724
+ if (sink) add('sink-with-interpolation', { pattern: `${esc(sink)}\\s*\\([^)\\n]*${interpolation}` });
725
+ }
726
+ const sink = lines.map(sinkOf).find(Boolean);
727
+ const src = SOURCES.find((s) => new RegExp(s).test(vulnerableCode));
728
+ if (sink && src) add('source-and-sink', { allOf: [`${esc(sink)}\\s*\\(`, src], window: 6 });
729
+ if (sink) add('sink-call', { pattern: `${esc(sink)}\\s*\\(` });
730
+ return out;
731
+ }
732
+
733
+ /** Names that appear in the patched code and not in the vulnerable code: the safe version's vocabulary. */
734
+ function safeNames({ vulnerableCode, patchedCode }) {
735
+ if (!patchedCode) return [];
736
+ const v = new Set(callNames(vulnerableCode));
737
+ const names = callNames(patchedCode).filter((n) => !v.has(n));
738
+ if (/\?['"`]?\s*[,)]/.test(patchedCode) && !/\?['"`]?\s*[,)]/.test(vulnerableCode)) names.push('?');
739
+ return names;
740
+ }
741
+
742
+ const PLACEHOLDER_RE = '\\?[\'"`]?\\s*[,)]';
743
+ const safeRegex = (names) => (names.length ? names.map((n) => (n === '?' ? PLACEHOLDER_RE : esc(n))).join('|') : null);
744
+
745
+ const summary = (score) => ({ precision: score.precision, recall: score.recall, tp: score.tp, fp: score.fp, fn: score.fn, tn: score.tn, protectedFailures: score.protectedFailures });
746
+ const quality = (e) => (e.pass ? 10 : 0) + (e.score.precision ?? 0) * (e.score.recall ?? 0) - e.score.protectedFailures * 0.5;
747
+
748
+ /**
749
+ * @param {object} o
750
+ * @param {object} o.base the IR fields that are not the match: id, title, severity, cwe, family, languages, remediation, evidence
751
+ * @param {object} o.corpusSpec { originalCode, patchedCode?, nearbyCleanCode?, protectedVariantsCode? }
752
+ * @param {object|null} o.proposed a match supplied by a model or a person, tried first
753
+ * @returns {{attempts: object[], best: object|null, exhausted: boolean}}
754
+ */
755
+ function synthesizeCandidate({ base, corpusSpec, proposed = null, maxAttempts = 6, thresholds, leakageOk = true }) {
756
+ const cap = Math.max(1, Math.min(12, maxAttempts));
757
+ const queue = [];
758
+ if (proposed) queue.push({ strategy: 'proposed', match: proposed });
759
+ for (const p of proposeCandidates({ vulnerableCode: corpusSpec.originalCode, patchedCode: corpusSpec.patchedCode })) queue.push(p);
760
+ const names = safeNames({ vulnerableCode: corpusSpec.originalCode, patchedCode: corpusSpec.patchedCode });
761
+ const attempts = []; const tried = new Set();
762
+ const tryOne = (strategy, match) => {
763
+ const key = JSON.stringify(match);
764
+ if (tried.has(key) || attempts.length >= cap) return null;
765
+ tried.add(key);
766
+ const ir = draftRuleIR({ ...base, match });
767
+ const errs = validateRuleIR(ir);
768
+ if (errs.length) { attempts.push({ n: attempts.length + 1, strategy, match, valid: false, errors: errs, pass: false, reasons: errs }); return null; }
769
+ const corpus = buildCorpus(ir, corpusSpec);
770
+ const ev = evaluateRule(ir, corpus, thresholds);
771
+ const rec = { n: attempts.length + 1, strategy, match, valid: true, pass: ev.pass && leakageOk, reasons: ev.reasons, score: summary(ev.score), ir, corpusSizes: { positives: corpus.positives.length, negatives: corpus.negatives.length } };
772
+ attempts.push(rec);
773
+ return { rec, ev };
774
+ };
775
+ for (let qi = 0; qi < queue.length && attempts.length < cap; qi++) {
776
+ const first = tryOne(queue[qi].strategy, queue[qi].match);
777
+ if (!first) continue;
778
+ if (first.rec.pass) break;
779
+ // revise from the failure: a negative that fired means the safe version is not excluded yet
780
+ const fired = first.ev.score.negatives.filter((n) => n.fired);
781
+ const rx = safeRegex(names);
782
+ if (fired.length && rx && !queue[qi].match.notMatch) { const r = tryOne(`${queue[qi].strategy}+exclude-safe`, { ...queue[qi].match, notMatch: rx }); if (r?.rec.pass) break; }
783
+ }
784
+ const valid = attempts.filter((a) => a.valid);
785
+ const best = valid.length ? [...valid].sort((a, b) => quality({ pass: b.pass, score: b.score }) - quality({ pass: a.pass, score: a.score }))[0] : null;
786
+ return { attempts: attempts.map(({ ir, ...rest }) => rest), best: best ? { strategy: best.strategy, match: best.match, pass: best.pass, score: best.score, reasons: best.reasons } : null, exhausted: !attempts.some((a) => a.pass) };
787
+ }
788
+
789
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/cli.js
790
+ // CLI surface: `agentic-security rules synthesize|evaluate|promote|status|rollback`.
791
+ //
792
+ // Distinct from the pre-existing `labs synthesize-rule` (posture/rule-synthesis.js), which proposes SUPPRESSION
793
+ // rules from repeated false-positive triage verdicts — a different input, a different output and a different
794
+ // command group on purpose, so the two are never confused at the CLI.
795
+ //
796
+ // Non-interactive by construction: no command reads stdin, every corpus evaluation is bounded (no network, no
797
+ // model call — this is the deterministic half; a model may PROPOSE the candidate pattern this CLI is handed, but
798
+ // it never decides promotion).
799
+
800
+
801
+
802
+
803
+
804
+
805
+
806
+
807
+
808
+
809
+
810
+
811
+ function loadFinding(root, id) {
812
+ const p = (0,state_dir.statePath)(root, 'last-scan.json');
813
+ if (!external_node_fs_.existsSync(p)) return null;
814
+ const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
815
+ return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
816
+ }
817
+
818
+ function readJsonArg(pathOrInline) {
819
+ if (!pathOrInline) return null;
820
+ try { return JSON.parse(external_node_fs_.existsSync(pathOrInline) ? external_node_fs_.readFileSync(pathOrInline, 'utf8') : pathOrInline); } catch { return null; }
821
+ }
822
+
823
+ async function cmdRules(args, root) {
824
+ const sub = args._[1];
825
+ if (sub === 'synthesize') return cmdSynthesize(args, root);
826
+ if (sub === 'evaluate') return cmdEvaluate(args, root);
827
+ if (sub === 'promote') return cmdPromote(args, root);
828
+ if (sub === 'status') return cmdStatus(args, root);
829
+ if (sub === 'rollback') return cmdRollback(args, root);
830
+ if (sub === 'cost') return cmdCost(args, root);
831
+ 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>');
832
+ return 4;
833
+ }
834
+
835
+ // `--spec` carries exactly what a model or a human proposed: id/title/severity/cwe/family/languages/match/
836
+ // remediation plus the corpus inputs (originalCode/patchedCode/nearbyCleanCode/protectedVariantsCode). This
837
+ // command never invents a pattern; it only drafts the IR, checks eligibility and records DRAFT->CANDIDATE.
838
+ async function cmdSynthesize(args, root) {
839
+ const findingId = args._[2];
840
+ const spec = readJsonArg(args.flags.spec);
841
+ if (!findingId || !spec) { console.error('usage: rules synthesize <finding-id> --spec <file.json>'); return 4; }
842
+ const finding = loadFinding(root, findingId);
843
+ if (!finding) { console.error(`Finding ${findingId} not found in last scan.`); return 4; }
844
+ const elig = checkEligibility(finding, { proofState: args.flags['proof-state'] || null });
845
+ if (!elig.eligible) { console.error(`Not eligible for rule synthesis: ${elig.reasons.join('; ')}`); return 4; }
846
+
847
+ // The candidate pattern is the model's or the person's, when they gave one. Without one, or with --auto, the synthesis loop proposes
848
+ // from the vulnerable and patched code, scores each attempt on the real corpus and its mutations, and revises (see proposal.js).
849
+ let finalSpec = spec; let synthesis = null;
850
+ const corpusSpec = { originalCode: spec.originalCode, patchedCode: spec.patchedCode ?? null, nearbyCleanCode: spec.nearbyCleanCode ?? [], protectedVariantsCode: spec.protectedVariantsCode ?? [] };
851
+ const leak = checkLeakage(JSON.stringify(corpusSpec), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [], fileNames: spec.fileNames ?? [] });
852
+ 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; }
853
+ if (args.flags.auto || !spec.match) {
854
+ if (!cli_isStr(spec.originalCode)) { console.error('Automatic proposal needs originalCode (the vulnerable snippet) in the spec.'); return 4; }
855
+ const { id, title, severity, cwe, family, languages, remediation } = spec;
856
+ synthesis = synthesizeCandidate({ 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 });
857
+ 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]})`}`);
858
+ if (!synthesis.best) { console.error('No valid candidate could be proposed from this material.'); return 1; }
859
+ finalSpec = { ...spec, match: synthesis.best.match };
860
+ 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('; ')}`);
861
+ }
862
+ const ir = draftRuleIR({ ...finalSpec, originatingFindingId: finding.stableId ?? finding.id, originatingCommit: spec.originatingCommit ?? null, evidenceState: elig.evidenceState });
863
+ const errs = validateRuleIR(ir);
864
+ if (errs.length) { console.error(`Invalid rule: ${errs.join('; ')}`); return 4; }
865
+
866
+ const ledger = loadLedger(root);
867
+ const draft = recordTransition(ledger, { ruleId: ir.id, from: null, to: 'DRAFT', reason: `drafted from ${findingId}`, actor: args.flags.actor || 'agent' });
868
+ if (!draft.ok) { console.error(draft.reason); return 4; }
869
+ const cand = recordTransition(ledger, { ruleId: ir.id, from: 'DRAFT', to: 'CANDIDATE', reason: 'eligibility passed', evidence: { eligibility: elig }, actor: args.flags.actor || 'agent' });
870
+ saveLedger(root, ledger);
871
+ saveIR(root, { ...ir, state: 'CANDIDATE' });
872
+ 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) });
873
+ if (synthesis) saveSynthesis(root, ir.id, { attempts: synthesis.attempts, best: synthesis.best });
874
+ console.log(`Rule ${ir.id}: DRAFT -> CANDIDATE (digest ${ruleIRDigest(ir).slice(0, 12)})`);
875
+ if (!cand.ok) console.error(cand.reason);
876
+ return 0;
877
+ }
878
+
879
+ async function cmdEvaluate(args, root) {
880
+ const id = args._[2];
881
+ if (!id) { console.error('usage: rules evaluate <rule-id> --corpus <file.json>'); return 4; }
882
+ const ir = loadIR(root, id);
883
+ if (!ir) { console.error(`No rule IR found for ${id}. Run rules synthesize first.`); return 4; }
884
+ const corpusSpec = readJsonArg(args.flags.corpus) ?? loadCorpus(root, id);
885
+ if (!corpusSpec) { console.error('No corpus supplied. Pass --corpus <file.json> with originalCode (and optionally patchedCode/nearbyCleanCode/protectedVariantsCode).'); return 4; }
886
+ const corpus = buildCorpus(ir, corpusSpec);
887
+ const leakage = checkLeakage(JSON.stringify({ ...corpusSpec, fileNames: undefined, discoveryCost: undefined }), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [], fileNames: corpusSpec.fileNames ?? [] });
888
+ const gate = gatePromotion({ ir, corpus, leakageCheck: leakage, thresholds: args.flags.thresholds ? readJsonArg(args.flags.thresholds) : PROMOTION_DEFAULTS });
889
+
890
+ const ledger = loadLedger(root);
891
+ const cur = stateOf(ledger, id);
892
+ 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' });
893
+ saveLedger(root, ledger);
894
+ saveEvaluation(root, id, gate);
895
+ const corpusHash = (list) => (0,reproducer/* sha256 */.sc)(JSON.stringify(list.map((x) => [x.label, x.code]).sort()));
896
+ const prev = loadProvenance(root, id);
897
+ saveProvenance(root, id, {
898
+ schema: 'agentic-security/rule-provenance', version: 1, ruleId: id, ruleVersion: 1, ruleHash: ruleIRDigest(ir),
899
+ originatingFinding: ir.provenance.originatingFindingId, originatingCommit: ir.provenance.originatingCommit, evidenceState: ir.provenance.evidenceState,
900
+ generatingModel: ir.provenance.model, promptConfigVersion: ir.provenance.promptConfigVersion,
901
+ positiveCorpusHash: corpusHash(corpus.positives), negativeCorpusHash: corpusHash(corpus.negatives),
902
+ 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 },
903
+ leakageCheck: leakage, mutatorCoverage: mutatorCoverage(corpusSpec.originalCode), discoveryCost: corpusSpec.discoveryCost ?? prev?.discoveryCost ?? null,
904
+ promotionEvent: prev?.promotionEvent ?? null, evaluatedAt: new Date().toISOString(),
905
+ });
906
+ if (args.flags.json) console.log(JSON.stringify(gate, null, 2));
907
+ else {
908
+ console.log(`Rule ${id}: ${gate.pass ? 'VALIDATED' : 'gate FAILED'}`);
909
+ console.log(` precision ${fmtPct(gate.evaluation.score.precision)} recall ${fmtPct(gate.evaluation.score.recall)} protected-failures ${gate.evaluation.score.protectedFailures}`);
910
+ for (const r of gate.reasons) console.log(` - ${r}`);
911
+ }
912
+ 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/`); }
913
+ return gate.pass ? 0 : 1;
914
+ }
915
+ function cli_isStr(v) { return typeof v === 'string' && v.length > 0; }
916
+ const fmtPct = (n) => (n == null ? 'unmeasured' : `${(n * 100).toFixed(1)}%`);
917
+
918
+ async function cmdPromote(args, root) {
919
+ const id = args._[2];
920
+ if (!id) { console.error('usage: rules promote <rule-id>'); return 4; }
921
+ const ledger = loadLedger(root);
922
+ if (ledger.tampered) { console.error(`Refusing: rule lifecycle ledger failed its integrity check (${ledger.tamperReason}).`); return 4; }
923
+ if (stateOf(ledger, id) !== 'VALIDATED') { console.error(`Rule ${id} is not VALIDATED (run rules evaluate first); refusing to promote.`); return 4; }
924
+ const ir = loadIR(root, id);
925
+ if (!ir) { console.error(`No rule IR found for ${id}.`); return 4; }
926
+ const pub = publishCustomRule(root, ir);
927
+ if (!pub.ok) { console.error(`Promotion refused: ${pub.reason}`); return 4; }
928
+ const t = recordTransition(ledger, { ruleId: id, from: 'VALIDATED', to: 'PROMOTED', reason: args.flags.reason || 'promoted', actor: args.flags.actor || 'operator' });
929
+ saveLedger(root, ledger);
930
+ const prov = loadProvenance(root, id);
931
+ if (prov) saveProvenance(root, id, { ...prov, promotionEvent: { at: new Date().toISOString(), actor: args.flags.actor || 'operator', reason: args.flags.reason || 'promoted', ruleHash: ruleIRDigest(ir) } });
932
+ console.log(`Rule ${id}: VALIDATED -> PROMOTED. Published to ${pub.file}.`);
933
+ if (!t.ok) console.error(t.reason);
934
+ return 0;
935
+ }
936
+
937
+ async function cmdRollback(args, root) {
938
+ const id = args._[2];
939
+ if (!id) { console.error('usage: rules rollback <rule-id> [--reason text]'); return 4; }
940
+ const ledger = loadLedger(root);
941
+ const cur = stateOf(ledger, id);
942
+ if (cur !== 'PROMOTED') { console.error(`Rule ${id} is not PROMOTED (current: ${cur ?? 'unknown'}); nothing to roll back.`); return 4; }
943
+ const un = unpublishCustomRule(root, id);
944
+ const t = recordTransition(ledger, { ruleId: id, from: 'PROMOTED', to: 'ROLLED_BACK', reason: args.flags.reason || 'operator rollback', actor: args.flags.actor || 'operator' });
945
+ saveLedger(root, ledger);
946
+ console.log(`Rule ${id}: PROMOTED -> ROLLED_BACK.${un.ok ? '' : ` (warning: could not remove published rule file: ${un.reason})`}`);
947
+ return t.ok ? 0 : 1;
948
+ }
949
+
950
+ async function cmdStatus(args, root) {
951
+ const ledger = loadLedger(root);
952
+ const id = args._[2];
953
+ if (id) {
954
+ const h = historyFor(ledger, id);
955
+ if (!h.length) { console.error(`No history for rule ${id}.`); return 4; }
956
+ if (args.flags.json) console.log(JSON.stringify(h, null, 2));
957
+ else { console.log(`Rule ${id}: ${stateOf(ledger, id)}`); for (const e of h) console.log(` ${e.at} ${e.from ?? '(new)'} -> ${e.to} (${e.reason || ''})`);
958
+ const syn = loadSynthesis(root, id);
959
+ 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'}`); }
960
+ }
961
+ return 0;
962
+ }
963
+ const ids = [...new Set(ledger.entries.map((e) => e.ruleId))];
964
+ if (args.flags.json) { console.log(JSON.stringify(ids.map((rid) => ({ id: rid, state: stateOf(ledger, rid) })), null, 2)); return 0; }
965
+ if (!ids.length) { console.log('No rules in the lifecycle ledger yet.'); return 0; }
966
+ for (const rid of ids) console.log(` ${rid.padEnd(40)} ${stateOf(ledger, rid)}`);
967
+ return 0;
968
+ }
969
+
970
+ // PRD 3 business metric: what the first, model-assisted discovery cost, against what every later deterministic detection costs.
971
+ // The discovery cost is whatever the agent run reported for it (recorded at synthesis); a deterministic detection makes no model
972
+ // 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.
973
+ async function cmdCost(args, root) {
974
+ const id = args._[2];
975
+ if (!id) { console.error('usage: rules cost <rule-id>'); return 4; }
976
+ const prov = loadProvenance(root, id);
977
+ if (!prov) { console.error(`No provenance for ${id}. Run rules evaluate first.`); return 4; }
978
+ let detections = null;
979
+ 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 */ }
980
+ const first = prov.discoveryCost;
981
+ 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' };
982
+ if (args.flags.json) { console.log(JSON.stringify(out, null, 2)); return 0; }
983
+ console.log(`Rule ${id} (${out.state})`);
984
+ 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');
985
+ console.log(` later detections by this rule in the last scan: ${detections ?? 'no scan available'}, each at $0 of model spend`);
986
+ 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`);
987
+ return 0;
988
+ }
989
+
990
+
991
+ /***/ })
992
+
993
+ };