@clear-capabilities/agentic-security-scanner 0.165.1 → 0.167.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 (36) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/bin/agentic-security.js +39 -4
  3. package/dist/2199.index.js +348 -0
  4. package/dist/3740.index.js +722 -0
  5. package/dist/4113.index.js +1 -1
  6. package/dist/4142.index.js +929 -0
  7. package/dist/5738.index.js +240 -0
  8. package/dist/7838.index.js +1 -1
  9. package/dist/808.index.js +1330 -0
  10. package/dist/818.index.js +93 -0
  11. package/dist/9800.index.js +245 -0
  12. package/dist/9999.index.js +2 -2
  13. package/dist/agentic-security.mjs +2 -2
  14. package/dist/agentic-security.mjs.sha256 +1 -1
  15. package/package.json +4 -4
  16. package/src/capabilities/CLAUDE.md +8 -0
  17. package/src/posture/artifact-registry.js +3 -0
  18. package/src/posture/proof-fabric/cli.js +115 -0
  19. package/src/posture/proof-fabric/fix-proof.js +73 -0
  20. package/src/posture/proof-fabric/oracles.js +101 -0
  21. package/src/posture/proof-fabric/orchestrator.js +129 -0
  22. package/src/posture/proof-fabric/reproducer.js +108 -0
  23. package/src/posture/proof-fabric/runner.js +243 -0
  24. package/src/posture/proof-fabric/states.js +53 -0
  25. package/src/posture/proof-fabric/store.js +83 -0
  26. package/src/posture/rule-compiler/cli.js +141 -0
  27. package/src/posture/rule-compiler/corpus.js +61 -0
  28. package/src/posture/rule-compiler/eligibility.js +25 -0
  29. package/src/posture/rule-compiler/ir.js +87 -0
  30. package/src/posture/rule-compiler/lifecycle.js +57 -0
  31. package/src/posture/rule-compiler/mutation.js +60 -0
  32. package/src/posture/rule-compiler/promotion.js +47 -0
  33. package/src/posture/rule-compiler/store.js +96 -0
  34. package/src/sandbox/backend-userspace.js +7 -1
  35. package/src/sandbox/supervise.js +26 -16
  36. package/src/sandbox/trust-boundary.js +2 -1
@@ -0,0 +1,1330 @@
1
+ export const id = 808;
2
+ export const ids = [808];
3
+ export const modules = {
4
+
5
+ /***/ 25517:
6
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7
+
8
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
9
+ /* harmony export */ $: () => (/* binding */ ORACLE_TYPES),
10
+ /* harmony export */ U: () => (/* binding */ evaluateOracle)
11
+ /* harmony export */ });
12
+ // Deterministic security oracles. A model may SELECT an oracle and propose its parameters; it may never decide that the
13
+ // oracle succeeded. Each oracle is a pure function of an Observation gathered by the TRUSTED runner (never by the model):
14
+ //
15
+ // Observation = {
16
+ // exitCode, signal, timedOut, stdout, stderr,
17
+ // canaries: { <name>: { exists, digestBefore, digestAfter } } // checked by the runner on disk, after the run
18
+ // callbacks: [{ nonce }] // hits recorded by the runner's loopback listener
19
+ // nonce // per-run random token the target cannot predict
20
+ // }
21
+ //
22
+ // An oracle returns { fired, reason }. `fired:false` with `inconclusive:true` means the observation could not decide
23
+ // (for example a timeout); it is never treated as "not exploitable".
24
+ const ORACLE_TYPES = Object.freeze([
25
+ 'crash_sanitizer', 'command_execution', 'unauthorized_http_access', 'unauthorized_db_read', 'database_mutation',
26
+ 'filesystem_mutation', 'outbound_callback', 'authentication_bypass', 'arbitrary_assertion',
27
+ ]);
28
+
29
+ const SANITIZER_RE = /(AddressSanitizer|UndefinedBehaviorSanitizer|stack-buffer-overflow|heap-buffer-overflow|SEGV on unknown address|stack smashing detected|buffer overflow detected)/i;
30
+ const CRASH_SIGNALS = new Set(['SIGSEGV', 'SIGABRT', 'SIGBUS', 'SIGILL', 'SIGFPE']);
31
+
32
+ const out = (fired, reason, extra = {}) => ({ fired, reason, ...extra });
33
+ const inconclusive = (reason) => ({ fired: false, inconclusive: true, reason });
34
+ const has = (obs, text) => typeof text === 'string' && text.length > 0 && `${obs.stdout || ''}${obs.stderr || ''}`.includes(text);
35
+
36
+ const IMPL = {
37
+ crash_sanitizer(obs) {
38
+ if (SANITIZER_RE.test(obs.stderr || '')) return out(true, 'sanitizer or runtime memory-safety report on stderr');
39
+ if (obs.signal && CRASH_SIGNALS.has(obs.signal)) return out(true, `process terminated by ${obs.signal}`);
40
+ if (obs.timedOut) return inconclusive('run timed out before a crash could be judged');
41
+ return out(false, 'no crash signal and no sanitizer report');
42
+ },
43
+ // The injected payload asks the shell/interpreter to create a file named after the per-run nonce inside the
44
+ // watched canary directory. The target cannot create it unless attacker data reached a command.
45
+ command_execution(obs, p) {
46
+ const c = obs.canaries?.[p.canary || 'command'];
47
+ if (!c) return inconclusive('command canary was not armed by the runner');
48
+ if (c.exists && !c.existedBefore) return out(true, 'nonce-named canary file created by an injected command');
49
+ if (obs.timedOut) return inconclusive('run timed out before the canary could be judged');
50
+ return out(false, 'canary file not created');
51
+ },
52
+ // A secret planted behind authorization (never shown to the exploit client). Seeing the nonce-bearing secret in the
53
+ // client's output while the actor held no credential is the violation.
54
+ unauthorized_http_access(obs, p) {
55
+ const secret = obs.secrets?.[p.secret || 'http'];
56
+ if (!secret) return inconclusive('protected secret was not armed by the runner');
57
+ if (has(obs, secret)) return out(true, 'protected resource content returned to an unauthenticated actor');
58
+ if (obs.timedOut) return inconclusive('run timed out');
59
+ return out(false, 'protected content not observed');
60
+ },
61
+ unauthorized_db_read(obs, p) {
62
+ const secret = obs.secrets?.[p.secret || 'db'];
63
+ if (!secret) return inconclusive('database canary row was not armed by the runner');
64
+ if (has(obs, secret)) return out(true, 'row the actor may not read was returned');
65
+ if (obs.timedOut) return inconclusive('run timed out');
66
+ return out(false, 'canary row value not observed');
67
+ },
68
+ database_mutation(obs, p) {
69
+ const c = obs.canaries?.[p.canary || 'db'];
70
+ if (!c) return inconclusive('database canary was not armed by the runner');
71
+ if (c.digestBefore && c.digestAfter && c.digestBefore !== c.digestAfter) return out(true, 'protected database state changed');
72
+ if (obs.timedOut) return inconclusive('run timed out');
73
+ return out(false, 'protected database state unchanged');
74
+ },
75
+ filesystem_mutation(obs, p) {
76
+ const c = obs.canaries?.[p.canary || 'fs'];
77
+ if (!c) return inconclusive('filesystem canary was not armed by the runner');
78
+ if ((c.exists && !c.existedBefore) || (c.digestBefore && c.digestAfter && c.digestBefore !== c.digestAfter)) return out(true, 'file outside the permitted area was created or modified');
79
+ if (obs.timedOut) return inconclusive('run timed out');
80
+ return out(false, 'protected path unchanged');
81
+ },
82
+ outbound_callback(obs) {
83
+ if (obs.callbackUnavailable) return { fired: false, unsupported: true, reason: 'loopback callback listener is not available on this backend' };
84
+ const hit = (obs.callbacks || []).some((c) => c && c.nonce && c.nonce === obs.nonce);
85
+ if (hit) return out(true, 'nonce-bearing request reached the runner-controlled listener');
86
+ if (obs.timedOut) return inconclusive('run timed out');
87
+ return out(false, 'no nonce-bearing callback received');
88
+ },
89
+ authentication_bypass(obs, p) {
90
+ const secret = obs.secrets?.[p.secret || 'auth'];
91
+ if (!secret) return inconclusive('protected secret was not armed by the runner');
92
+ if (has(obs, secret)) return out(true, 'privileged content returned without valid credentials');
93
+ if (obs.timedOut) return inconclusive('run timed out');
94
+ return out(false, 'privileged content not observed without credentials');
95
+ },
96
+ // Declarative only: no code, no regex supplied by a model. Operators are a closed set.
97
+ arbitrary_assertion(obs, p) {
98
+ const a = p.assert;
99
+ if (!a || typeof a !== 'object') return inconclusive('assertion missing');
100
+ if (obs.timedOut) return inconclusive('run timed out');
101
+ if ('exitCode' in a) return a.exitCode === obs.exitCode ? out(true, `exit code was ${obs.exitCode}`) : out(false, `exit code was ${obs.exitCode}`);
102
+ if ('stdoutIncludes' in a) return has({ stdout: obs.stdout }, String(a.stdoutIncludes)) ? out(true, 'stdout contained the asserted text') : out(false, 'stdout did not contain the asserted text');
103
+ if ('stderrIncludes' in a) return has({ stderr: obs.stderr }, String(a.stderrIncludes)) ? out(true, 'stderr contained the asserted text') : out(false, 'stderr did not contain the asserted text');
104
+ return inconclusive('unsupported assertion operator');
105
+ },
106
+ };
107
+
108
+ function evaluateOracle(spec, observation) {
109
+ if (!spec || !ORACLE_TYPES.includes(spec.type)) return { fired: false, unsupported: true, reason: `unknown oracle type: ${String(spec?.type)}` };
110
+ if (!observation || typeof observation !== 'object') return inconclusive('no observation');
111
+ try { return IMPL[spec.type](observation, spec.params || {}); } catch (e) { return inconclusive(`oracle error: ${e.message}`); }
112
+ }
113
+
114
+
115
+ /***/ }),
116
+
117
+ /***/ 37055:
118
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
119
+
120
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
121
+ /* harmony export */ IW: () => (/* binding */ verifierView),
122
+ /* harmony export */ V2: () => (/* binding */ substitute),
123
+ /* harmony export */ Yj: () => (/* binding */ LANGUAGES),
124
+ /* harmony export */ dw: () => (/* binding */ canonicalize),
125
+ /* harmony export */ mC: () => (/* binding */ validateReproducer),
126
+ /* harmony export */ sc: () => (/* binding */ sha256),
127
+ /* harmony export */ we: () => (/* binding */ reproducerDigest)
128
+ /* harmony export */ });
129
+ /* unused harmony exports MAX_FILES, MAX_FILE_BYTES, isSafeRelPath */
130
+ /* harmony import */ var node_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77598);
131
+ /* harmony import */ var _oracles_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(25517);
132
+ // Serialized reproducer: the ONLY thing an independent verifier receives (besides revision, finding id and oracle).
133
+ // It carries no reasoning, no model output and no prior results. Everything per-run (nonce, secrets, canary paths,
134
+ // callback URL) is a placeholder substituted fresh by the trusted runner, so a replay can never reuse a stale value
135
+ // and a target cannot learn the values in advance.
136
+
137
+
138
+
139
+ const REPRODUCER_SCHEMA = 'agentic-security/reproducer';
140
+ const REPRODUCER_VERSION = 1;
141
+ const LANGUAGES = Object.freeze(['javascript', 'typescript', 'python', 'java', 'c', 'cpp', 'csharp']);
142
+ const MAX_FILES = 64;
143
+ const MAX_FILE_BYTES = 256 * 1024;
144
+ const MAX_TOTAL_BYTES = 1024 * 1024;
145
+ const PLACEHOLDER_RE = /\{\{([A-Z_]+)(?::([a-z0-9_-]{1,32}))?\}\}/g;
146
+ const ALLOWED_PLACEHOLDERS = new Set(['NONCE', 'SECRET', 'CANARY', 'CALLBACK_URL', 'CALLBACK_PORT', 'ROOT', 'NODE', 'PYTHON', 'JAVA', 'JAVAC', 'CC']);
147
+
148
+ function isSafeRelPath(rel) {
149
+ if (typeof rel !== 'string' || !rel || rel.length > 200) return false;
150
+ if (rel.startsWith('/') || rel.includes('\0') || rel.includes('\\')) return false;
151
+ if (['canary', 'tmp'].includes(rel.split('/')[0])) return false;
152
+ return rel.split('/').every((seg) => seg && seg !== '.' && seg !== '..' && !seg.startsWith('__oracle_'));
153
+ }
154
+
155
+ /** Canonical JSON (sorted keys) so identical reproducers hash identically regardless of key order. */
156
+ function canonicalize(v) {
157
+ if (Array.isArray(v)) return `[${v.map(canonicalize).join(',')}]`;
158
+ if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonicalize(v[k])}`).join(',')}}`;
159
+ return JSON.stringify(v);
160
+ }
161
+ const sha256 = (s) => (0,node_crypto__WEBPACK_IMPORTED_MODULE_0__.createHash)('sha256').update(s).digest('hex');
162
+ const reproducerDigest = (r) => sha256(canonicalize(r));
163
+
164
+ function validateReproducer(r) {
165
+ const errs = [];
166
+ if (!r || typeof r !== 'object' || Array.isArray(r)) return ['reproducer must be an object'];
167
+ if (r.schema !== REPRODUCER_SCHEMA) errs.push('unknown schema');
168
+ if (r.version !== REPRODUCER_VERSION) errs.push('unsupported reproducer version');
169
+ if (typeof r.findingId !== 'string' || !r.findingId || r.findingId.length > 200) errs.push('findingId required');
170
+ if (!LANGUAGES.includes(r.lang)) errs.push(`unsupported language: ${String(r.lang)}`);
171
+ if (!r.oracle || !_oracles_js__WEBPACK_IMPORTED_MODULE_1__/* .ORACLE_TYPES */ .$.includes(r.oracle.type)) errs.push(`unknown oracle: ${String(r.oracle?.type)}`);
172
+ const files = r.files ?? {};
173
+ if (typeof files !== 'object' || Array.isArray(files)) errs.push('files must be an object');
174
+ else {
175
+ const names = Object.keys(files);
176
+ if (names.length > MAX_FILES) errs.push(`file count must be at most ${MAX_FILES}`);
177
+ let total = 0;
178
+ for (const n of names) {
179
+ if (!isSafeRelPath(n)) { errs.push(`unsafe file path: ${n}`); continue; }
180
+ if (typeof files[n] !== 'string') { errs.push(`file ${n} must be a string`); continue; }
181
+ const b = Buffer.byteLength(files[n]);
182
+ total += b;
183
+ if (b > MAX_FILE_BYTES) errs.push(`file ${n} exceeds ${MAX_FILE_BYTES} bytes`);
184
+ }
185
+ if (total > MAX_TOTAL_BYTES) errs.push('reproducer exceeds total size limit');
186
+ }
187
+ const sourceNames = r.sources && typeof r.sources === 'object' && !Array.isArray(r.sources) ? Object.keys(r.sources) : [];
188
+ if (Object.keys(files).length + sourceNames.length === 0) errs.push('reproducer must declare at least one file or source');
189
+ for (const key of ['build', 'run']) {
190
+ const a = r[key];
191
+ if (a == null && key === 'build') continue;
192
+ if (!Array.isArray(a) || !a.length || !a.every((x) => typeof x === 'string' && x.length < 2000 && !x.includes('\0'))) errs.push(`${key} must be a non-empty argv array of strings (no shell string)`);
193
+ }
194
+ for (const text of [...Object.values(files || {}), ...(r.build || []), ...(r.run || [])]) {
195
+ if (typeof text !== 'string') continue;
196
+ for (const m of text.matchAll(PLACEHOLDER_RE)) if (!ALLOWED_PLACEHOLDERS.has(m[1])) errs.push(`unknown placeholder {{${m[1]}}}`);
197
+ }
198
+ if (r.watch != null) {
199
+ if (typeof r.watch !== 'object' || Array.isArray(r.watch)) errs.push('watch must be an object');
200
+ else for (const [k, v] of Object.entries(r.watch)) if (!/^[a-z0-9_-]{1,32}$/.test(k) || !isSafeRelPath(v)) errs.push(`bad watch entry: ${k}`);
201
+ }
202
+ if (r.env != null) {
203
+ if (typeof r.env !== 'object' || Array.isArray(r.env)) errs.push('env must be an object');
204
+ else for (const [k, v] of Object.entries(r.env)) {
205
+ if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(k)) errs.push(`bad env var name: ${k}`);
206
+ if (typeof v !== 'string' || v.length > 4096) errs.push(`env value for ${k} must be a short string`);
207
+ }
208
+ }
209
+ if (r.sources != null) {
210
+ if (typeof r.sources !== 'object' || Array.isArray(r.sources)) errs.push('sources must be an object');
211
+ else for (const [dest, src] of Object.entries(r.sources)) if (!isSafeRelPath(dest) || !isSafeRelPath(src)) errs.push(`bad sources entry: ${dest}`);
212
+ }
213
+ if (r.network != null && !['none', 'callback'].includes(r.network)) errs.push('network must be none or callback');
214
+ return errs;
215
+ }
216
+
217
+ /** The view handed to an independent verifier: exactly the reproducer, plus identifiers. Nothing else. */
218
+ function verifierView({ revision, reproducer, findingId, oracle }) {
219
+ return Object.freeze({ revision: revision ?? null, findingId, oracle, reproducer: structuredClone(reproducer) });
220
+ }
221
+
222
+ function substitute(text, ctx) {
223
+ return text.replace(PLACEHOLDER_RE, (whole, name, arg) => {
224
+ switch (name) {
225
+ case 'NONCE': return ctx.nonce;
226
+ case 'SECRET': return ctx.secret(arg || 'default');
227
+ case 'CANARY': return ctx.canary(arg || 'default');
228
+ case 'CALLBACK_URL': return ctx.callbackUrl ?? whole;
229
+ case 'CALLBACK_PORT': return String(ctx.callbackPort ?? '');
230
+ case 'ROOT': return ctx.root;
231
+ case 'NODE': return ctx.tools.node;
232
+ case 'PYTHON': return ctx.tools.python ?? whole;
233
+ case 'JAVA': return ctx.tools.java ?? whole;
234
+ case 'JAVAC': return ctx.tools.javac ?? whole;
235
+ case 'CC': return ctx.tools.cc ?? whole;
236
+ default: return whole;
237
+ }
238
+ });
239
+ }
240
+
241
+
242
+ /***/ }),
243
+
244
+ /***/ 12090:
245
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
246
+
247
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
248
+ /* harmony export */ KF: () => (/* binding */ toProofTier),
249
+ /* harmony export */ g3: () => (/* binding */ stateRank),
250
+ /* harmony export */ jn: () => (/* binding */ fromProofTier),
251
+ /* harmony export */ np: () => (/* binding */ advance)
252
+ /* harmony export */ });
253
+ /* unused harmony exports EVIDENCE_STATES, COMPLETENESS */
254
+ // Evidence state ladder for the Universal Exploit Proof Fabric.
255
+ //
256
+ // Evidence state is SEPARATE from severity and confidence. It extends, never replaces, the vocabulary that already
257
+ // exists: `proof-tier.js` (execution-proven / proof-failed / taint-proven / unproven) and the fix-verify legs
258
+ // (`verifiedFull`, `degradedLegs`). `toProofTier` / `fromProofTier` are the explicit bridges.
259
+ //
260
+ // Transitions are guarded: a state can only be reached from the state directly before it (or by dropping back), so no
261
+ // caller can jump a finding to EXPLOIT_CONFIRMED without passing REPRODUCED, or to FIX_VERIFIED without
262
+ // FIX_REPLAY_BLOCKED. A degraded or incomplete run NEVER advances a state.
263
+ const EVIDENCE_STATES = Object.freeze([
264
+ 'CANDIDATE',
265
+ 'STATICALLY_CORROBORATED',
266
+ 'REPRODUCER_GENERATED',
267
+ 'REPRODUCED',
268
+ 'EXPLOIT_CONFIRMED',
269
+ 'FIX_REPLAY_BLOCKED',
270
+ 'FIX_VERIFIED',
271
+ ]);
272
+
273
+ const stateRank = (s) => EVIDENCE_STATES.indexOf(s);
274
+
275
+ const REQUIRES_PREDECESSOR = Object.freeze(Object.fromEntries(EVIDENCE_STATES.map((s, i) => [s, i === 0 ? null : EVIDENCE_STATES[i - 1]])));
276
+
277
+ /**
278
+ * Advance `from` to `to`. Returns { ok, state, reason }. Moving up requires `to` to be exactly the next rung; moving
279
+ * down or staying is always allowed (evidence can be lost, never invented). Unknown states are rejected.
280
+ */
281
+ function advance(from, to) {
282
+ if (!EVIDENCE_STATES.includes(from)) return { ok: false, state: 'CANDIDATE', reason: `unknown current state: ${String(from)}` };
283
+ if (!EVIDENCE_STATES.includes(to)) return { ok: false, state: from, reason: `unknown target state: ${String(to)}` };
284
+ if (stateRank(to) <= stateRank(from)) return { ok: true, state: to, reason: null };
285
+ if (REQUIRES_PREDECESSOR[to] !== from) return { ok: false, state: from, reason: `cannot reach ${to} from ${from}: ${REQUIRES_PREDECESSOR[to]} is required first` };
286
+ return { ok: true, state: to, reason: null };
287
+ }
288
+
289
+ // Bridges to the older vocabulary so existing consumers keep working.
290
+ function toProofTier(state) {
291
+ const r = stateRank(state);
292
+ if (r >= stateRank('EXPLOIT_CONFIRMED')) return 'execution-proven';
293
+ if (r >= stateRank('STATICALLY_CORROBORATED')) return 'taint-proven';
294
+ return 'unproven';
295
+ }
296
+
297
+ function fromProofTier(tier) {
298
+ if (tier === 'taint-proven') return 'STATICALLY_CORROBORATED';
299
+ // execution-proven under the older single-run marker path is one run, not the 3/3 + independent replay the fabric
300
+ // requires, so it maps to REPRODUCED and never to EXPLOIT_CONFIRMED.
301
+ if (tier === 'execution-proven') return 'REPRODUCED';
302
+ return 'CANDIDATE';
303
+ }
304
+
305
+ // Completeness vocabulary shared with fix-verify: FULL only when nothing was skipped.
306
+ const COMPLETENESS = Object.freeze(['FULL', 'DEGRADED', 'INCOMPLETE']);
307
+
308
+
309
+ /***/ }),
310
+
311
+ /***/ 30808:
312
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
313
+
314
+ // ESM COMPAT FLAG
315
+ __webpack_require__.r(__webpack_exports__);
316
+
317
+ // EXPORTS
318
+ __webpack_require__.d(__webpack_exports__, {
319
+ cmdRules: () => (/* binding */ cmdRules)
320
+ });
321
+
322
+ // EXTERNAL MODULE: external "node:fs"
323
+ var external_node_fs_ = __webpack_require__(73024);
324
+ // EXTERNAL MODULE: ./src/posture/state-dir.js
325
+ var state_dir = __webpack_require__(31174);
326
+ // EXTERNAL MODULE: ./src/posture/proof-fabric/reproducer.js
327
+ var reproducer = __webpack_require__(37055);
328
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/ir.js
329
+ // Rule intermediate representation: compiles DOWN into the existing pattern-rule engine
330
+ // (`../custom-rules.js`), never a parallel matcher. "Compile" here means "emit a
331
+ // custom-rules.js-compatible document" — detection at runtime is 100% the already-proven
332
+ // regex/allOf/notMatch/window engine; this module only adds PROVENANCE metadata around it.
333
+ //
334
+ // A rule's match semantics are deliberately the same closed vocabulary custom-rules.js
335
+ // already supports (pattern | allOf+window | notMatch) — no new matching primitive is
336
+ // introduced, so a promoted rule is exactly as auditable as a hand-written one.
337
+
338
+
339
+ const RULE_IR_SCHEMA = 'agentic-security/rule-ir';
340
+ const RULE_IR_VERSION = 1;
341
+ const RULE_STATES = Object.freeze(['DRAFT', 'CANDIDATE', 'VALIDATED', 'PROMOTED', 'DEPRECATED', 'ROLLED_BACK']);
342
+ const VALID_LANGS = new Set(['javascript', 'typescript', 'python', 'go', 'ruby', 'java', 'rust', 'csharp', 'php', 'any']);
343
+
344
+ const isStr = (v) => typeof v === 'string' && v.length > 0;
345
+
346
+ /** Problems with a draft rule IR; an empty list means it is well-formed (not yet validated/promoted). */
347
+ function validateRuleIR(ir) {
348
+ const errs = [];
349
+ if (!ir || typeof ir !== 'object') return ['rule IR must be an object'];
350
+ if (ir.schema !== RULE_IR_SCHEMA) errs.push('unknown schema');
351
+ if (ir.version !== RULE_IR_VERSION) errs.push('unsupported rule IR version');
352
+ if (!isStr(ir.id) || !/^[a-z][a-z0-9-]{2,79}$/.test(ir.id)) errs.push('id must be a lowercase kebab-case string');
353
+ if (!isStr(ir.title)) errs.push('title required');
354
+ if (!['critical', 'high', 'medium', 'low'].includes(ir.severity)) errs.push('severity must be critical|high|medium|low');
355
+ if (!isStr(ir.cwe) || !/^CWE-\d+$/.test(ir.cwe)) errs.push('cwe must look like CWE-###');
356
+ if (!isStr(ir.family)) errs.push('family required');
357
+ 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');
358
+ const m = ir.match;
359
+ if (!m || typeof m !== 'object') errs.push('match required');
360
+ else {
361
+ const hasPattern = isStr(m.pattern);
362
+ const hasAllOf = Array.isArray(m.allOf) && m.allOf.length > 0 && m.allOf.every(isStr);
363
+ if (!hasPattern && !hasAllOf) errs.push('match needs a pattern or a non-empty allOf');
364
+ if (m.notMatch != null && !isStr(m.notMatch)) errs.push('notMatch must be a string');
365
+ if (m.window != null && !(Number.isInteger(m.window) && m.window > 0 && m.window <= 200)) errs.push('window must be an integer in 1..200');
366
+ for (const re of [m.pattern, ...(m.allOf || []), m.notMatch].filter(isStr)) {
367
+ try { new RegExp(re); } catch { errs.push(`invalid regex: ${re}`); }
368
+ }
369
+ }
370
+ // Declarative-only hint fields (sink/source/propagator/sanitizer/dominatingGuard/frameworkConstraint): free text,
371
+ // never executable, carried for provenance/review only and NOT consulted by the matcher.
372
+ for (const k of ['sink', 'source', 'propagator', 'sanitizer', 'dominatingGuard', 'frameworkConstraint']) {
373
+ if (ir[k] != null && !isStr(ir[k])) errs.push(`${k} must be a string when present`);
374
+ }
375
+ if (ir.exclusions != null && !(Array.isArray(ir.exclusions) && ir.exclusions.every(isStr))) errs.push('exclusions must be an array of strings');
376
+ if (!ir.provenance || typeof ir.provenance !== 'object') errs.push('provenance required');
377
+ else {
378
+ if (!isStr(ir.provenance.originatingFindingId)) errs.push('provenance.originatingFindingId required');
379
+ if (ir.provenance.originatingCommit != null && !isStr(ir.provenance.originatingCommit)) errs.push('provenance.originatingCommit must be a string');
380
+ if (!['execution-proven', 'taint-proven', 'deterministic-corroboration'].includes(ir.provenance.evidenceState)) errs.push('provenance.evidenceState must be execution-proven|taint-proven|deterministic-corroboration');
381
+ }
382
+ return errs;
383
+ }
384
+
385
+ function ruleIRDigest(ir) {
386
+ const { state: _s, ...rest } = ir;
387
+ return (0,reproducer/* sha256 */.sc)(JSON.stringify(rest, Object.keys(rest).sort()));
388
+ }
389
+
390
+ /** Build a DRAFT rule IR. Caller supplies the candidate pattern — this module never invents one. */
391
+ function draftRuleIR({ id, title, severity, cwe, family, languages, match, remediation, originatingFindingId, originatingCommit, evidenceState, model = null, promptConfigVersion = null, ...hints }) {
392
+ const ir = {
393
+ schema: RULE_IR_SCHEMA, version: RULE_IR_VERSION, id, title, severity, cwe, family, languages, match,
394
+ remediation: remediation ?? null, state: 'DRAFT',
395
+ ...hints,
396
+ provenance: { originatingFindingId, originatingCommit: originatingCommit ?? null, evidenceState, model, promptConfigVersion },
397
+ };
398
+ return ir;
399
+ }
400
+
401
+ /** Compile a rule IR into a custom-rules.js-compatible document. Caller writes the YAML. */
402
+ function compileToCustomRule(ir) {
403
+ const errs = validateRuleIR(ir);
404
+ if (errs.length) return { ok: false, errs };
405
+ const doc = {
406
+ id: `rule-compiler/${ir.id}`,
407
+ title: ir.title,
408
+ severity: ir.severity,
409
+ cwe: ir.cwe,
410
+ languages: ir.languages,
411
+ 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 } : {}) },
412
+ message: ir.remediation || `${ir.title} (${ir.cwe}, compiled from ${ir.provenance.originatingFindingId})`,
413
+ };
414
+ return { ok: true, doc };
415
+ }
416
+
417
+ // EXTERNAL MODULE: ./src/posture/proof-fabric/states.js
418
+ var states = __webpack_require__(12090);
419
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/eligibility.js
420
+ // X-eligibility (PRD 3 "Eligibility"): a finding may enter synthesis only with a stable id, a vulnerable span, a
421
+ // CWE/family, code-flow evidence, and deterministic corroboration OR exploit proof. Reuses the existing
422
+ // vocabularies rather than inventing a third: proof-fabric's evidence-state ladder when present, else the older
423
+ // proof-tier (`taint-proven`/`execution-proven`), else the finding's own `parser` (an IR-TAINT/MULTI-SINK parser
424
+ // origin is code-flow evidence even with no execution).
425
+
426
+
427
+ const ANALYSED_PARSERS = new Set(['IR-TAINT', 'MULTI-SINK']);
428
+
429
+ function checkEligibility(finding, { proofState = null } = {}) {
430
+ const reasons = [];
431
+ if (!finding?.stableId && !finding?.id) reasons.push('no stable id');
432
+ if (finding?.file == null || finding?.line == null) reasons.push('no vulnerable span (file:line)');
433
+ if (!finding?.cwe && !finding?.family) reasons.push('no CWE or family');
434
+ const hasFlowEvidence = ANALYSED_PARSERS.has(finding?.parser) || !!finding?.snippet;
435
+ if (!hasFlowEvidence) reasons.push('no code-flow evidence (parser not IR-TAINT/MULTI-SINK, no snippet)');
436
+
437
+ let evidenceState = 'none';
438
+ if (proofState && (0,states/* stateRank */.g3)(proofState) >= (0,states/* stateRank */.g3)('EXPLOIT_CONFIRMED')) evidenceState = 'execution-proven';
439
+ else if (finding?.proofTier === 'execution-proven') evidenceState = 'execution-proven';
440
+ else if (finding?.proofTier === 'taint-proven' || ANALYSED_PARSERS.has(finding?.parser)) evidenceState = 'taint-proven';
441
+ if (evidenceState === 'none') reasons.push('no deterministic corroboration or exploit proof');
442
+
443
+ return { eligible: reasons.length === 0, reasons, evidenceState };
444
+ }
445
+
446
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/mutation.js
447
+ // Bounded structural mutation for ONE candidate rule's own corpus — not bench/mutation's engine-wide verdict-flip
448
+ // harness (a different scope: the whole deterministic+taint engine against curated adversarial cases). This module
449
+ // exists only to answer PRD 3's "unseen sibling" question for a single rule: does the candidate still fire on a
450
+ // structurally different variant of the same vulnerable shape, and does it still decline on a structurally
451
+ // different variant of a mitigated shape.
452
+ //
453
+ // Mutations are SYNTACTIC, deterministic, seed-free and language-agnostic: variable rename, wrap-in-function,
454
+ // reorder-adjacent-statements, insert-indirection (a pass-through local variable). No semantics are changed on
455
+ // purpose — a mutation that silently changed behavior would make a "same vulnerability, different shape" claim
456
+ // false.
457
+ const RESERVED = new Set(['if', 'else', 'for', 'while', 'return', 'function', 'const', 'let', 'var', 'import', 'from', 'def', 'class', 'req', 'res']);
458
+
459
+ function identifiers(code) {
460
+ const seen = new Set();
461
+ 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]);
462
+ return [...seen];
463
+ }
464
+
465
+ function renameOne(code, from, to) {
466
+ if (!from || code.includes(to)) return null;
467
+ return code.replace(new RegExp(`\\b${from}\\b`, 'g'), to);
468
+ }
469
+
470
+ function variableRename(code, { suffix = '_v2' } = {}) {
471
+ const ids = identifiers(code);
472
+ const target = ids.find((id) => id.length > 1);
473
+ if (!target) return null;
474
+ return renameOne(code, target, `${target}${suffix}`);
475
+ }
476
+
477
+ function wrapInFunction(code, { name = 'wrapped_v2' } = {}) {
478
+ const indented = code.split('\n').map((l) => (l ? ` ${l}` : l)).join('\n');
479
+ return `function ${name}() {\n${indented}\n}\n${name}();\n`;
480
+ }
481
+
482
+ /** Insert a pass-through local for the first simple right-hand-side identifier assigned with `=` (indirection,
483
+ * no behavior change): `x = y;` becomes `const indirectN = y; x = indirectN;`. */
484
+ function insertIndirection(code) {
485
+ const m = /^(\s*)([A-Za-z_][A-Za-z0-9_.]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*;/m.exec(code);
486
+ if (!m) return null;
487
+ const [whole, indent, lhs, rhs] = m;
488
+ const varName = `indirect_${Math.abs(_hash(rhs)) % 1000}`;
489
+ if (code.includes(varName)) return null;
490
+ return code.replace(whole, `${indent}const ${varName} = ${rhs};\n${indent}${lhs} = ${varName};`);
491
+ }
492
+
493
+ function _hash(s) { let h = 0; for (const c of s) h = (h * 31 + c.charCodeAt(0)) | 0; return h; }
494
+
495
+ const MUTATORS = Object.freeze({ 'variable-rename': variableRename, 'wrap-in-function': wrapInFunction, 'insert-indirection': insertIndirection });
496
+
497
+ /** Every mutator applied to `code`; mutators that don't apply (return null) are omitted, never silently skipped without saying so. */
498
+ function generateVariants(code) {
499
+ const out = [];
500
+ for (const [name, fn] of Object.entries(MUTATORS)) {
501
+ let variant = null;
502
+ try { variant = fn(code); } catch { variant = null; }
503
+ if (variant && variant !== code) out.push({ mutator: name, code: variant });
504
+ }
505
+ return out;
506
+ }
507
+
508
+ // EXTERNAL MODULE: ./src/posture/custom-rules.js + 1 modules
509
+ var custom_rules = __webpack_require__(9049);
510
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/corpus.js
511
+ // Automatic corpus creation and scoring for ONE candidate rule.
512
+ //
513
+ // Positive corpus: the original vulnerable snippet plus its generated sibling variants (mutation.js).
514
+ // Negative corpus: an explicit patched/clean variant the caller supplies, nearby clean patterns, protected
515
+ // (sanitizer/guard) variants, and the NEGATIVE mutations of those (same mutators, applied to the safe side) — a
516
+ // candidate rule must decline on ALL of them, not just the one hand-picked negative.
517
+ //
518
+ // Scoring reuses the exact runtime matcher (`runRule` in `../custom-rules.js`), never a second implementation —
519
+ // the score a rule gets here is the score it will actually produce once promoted.
520
+
521
+
522
+
523
+
524
+ function toRuntimeRule(ir) {
525
+ const { ok, doc, errs } = compileToCustomRule(ir);
526
+ if (!ok) throw new Error(`cannot build corpus for an invalid rule IR: ${errs.join('; ')}`);
527
+ const regexes = doc.match.allOf ? doc.match.allOf.map((p) => new RegExp(p, 'g')) : [new RegExp(doc.match.pattern, 'g')];
528
+ return {
529
+ id: doc.id, title: doc.title, severity: doc.severity, cwe: doc.cwe, languages: doc.languages, message: doc.message,
530
+ regexes, requireAll: !!doc.match.allOf, windowLines: doc.match.window ?? 5,
531
+ notMatch: doc.match.notMatch ? new RegExp(doc.match.notMatch) : null,
532
+ };
533
+ }
534
+
535
+ 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' };
536
+
537
+ function buildCorpus(ir, { originalCode, patchedCode = null, nearbyCleanCode = [], protectedVariantsCode = [] } = {}) {
538
+ const positives = [{ label: 'original', code: originalCode }];
539
+ for (const v of generateVariants(originalCode)) positives.push({ label: `sibling:${v.mutator}`, code: v.code });
540
+
541
+ const negatives = [];
542
+ if (patchedCode) {
543
+ negatives.push({ label: 'patched', code: patchedCode });
544
+ for (const v of generateVariants(patchedCode)) negatives.push({ label: `patched-sibling:${v.mutator}`, code: v.code });
545
+ }
546
+ nearbyCleanCode.forEach((code, i) => negatives.push({ label: `nearby-clean-${i}`, code }));
547
+ protectedVariantsCode.forEach((code, i) => negatives.push({ label: `protected-${i}`, code }));
548
+
549
+ return { positives, negatives };
550
+ }
551
+
552
+ function scoreRule(ir, corpus) {
553
+ const rule = toRuntimeRule(ir);
554
+ const lang = ir.languages[0] || 'javascript';
555
+ const file = EXT[lang] || 'x.txt';
556
+ const run = (code) => (0,custom_rules/* runRule */.OA)(rule, file, code).length > 0;
557
+
558
+ const posResults = corpus.positives.map((p) => ({ ...p, fired: run(p.code) }));
559
+ const negResults = corpus.negatives.map((n) => ({ ...n, fired: run(n.code) }));
560
+
561
+ const tp = posResults.filter((p) => p.fired).length;
562
+ const fn = posResults.length - tp;
563
+ const fp = negResults.filter((n) => n.fired).length;
564
+ const tn = negResults.length - fp;
565
+ const precision = tp + fp === 0 ? null : tp / (tp + fp);
566
+ const recall = corpus.positives.length === 0 ? null : tp / corpus.positives.length;
567
+ // "Protected negative failures" per PRD 3: a rule firing on a sanitizer/guard-carrying variant specifically.
568
+ const protectedFailures = negResults.filter((n) => n.label.startsWith('protected-') && n.fired).length;
569
+
570
+ return { precision, recall, tp, fp, tn, fn, protectedFailures, positives: posResults, negatives: negResults };
571
+ }
572
+
573
+ // EXTERNAL MODULE: external "node:path"
574
+ var external_node_path_ = __webpack_require__(76760);
575
+ // EXTERNAL MODULE: ./src/sandbox/trust-domains.js
576
+ var trust_domains = __webpack_require__(38832);
577
+ // EXTERNAL MODULE: ./src/posture/assurance/identity.js
578
+ var identity = __webpack_require__(41877);
579
+ // EXTERNAL MODULE: ./src/posture/assurance/schema-kit.js
580
+ var schema_kit = __webpack_require__(53353);
581
+ // EXTERNAL MODULE: ./src/posture/assurance/verification-record.js
582
+ var verification_record = __webpack_require__(29668);
583
+ ;// CONCATENATED MODULE: ./src/posture/evaluation/labels.js
584
+ // Adjudicated defect labels, reviewed negatives and finding-to-label matching
585
+ // (QA-002.AC01, QA-002.AC02).
586
+ //
587
+ // Advisory records are CANDIDATE ground truth. A label becomes scoreable only
588
+ // after adjudication: at least two distinct reviewers other than whoever
589
+ // proposed it, with evidence produced by a human or an independent verifier. A
590
+ // CWE alone never identifies a defect: a label needs a reviewed location range,
591
+ // and a finding matches only by location (plus family or CWE agreement).
592
+ //
593
+ // This module can validate that a label SAYS it was independently adjudicated.
594
+ // It cannot establish that it was. `synthetic: true` labels are accepted for
595
+ // tooling tests and are excluded from every real-code population count
596
+ // (`populationCounts`, gates.js).
597
+ //
598
+ // Pure: no fs, no clock, no network.
599
+
600
+
601
+
602
+
603
+
604
+ const DEFECT_LABEL_SCHEMA = 'agentic-security/adjudicated-defect-label';
605
+ const NEGATIVE_LABEL_SCHEMA = 'agentic-security/adjudicated-negative';
606
+ const ADJUDICATION_STATUSES = Object.freeze(['candidate', 'adjudicated', 'disputed', 'rejected']);
607
+ const NEGATIVE_KINDS = Object.freeze(['safe-real', 'patched', 'near-miss']);
608
+ const VARIANTS = Object.freeze(['pre', 'post']);
609
+ const INDEPENDENT_PRODUCERS = (/* unused pure expression or super */ null && (['human', 'independent-verifier']));
610
+
611
+ const DEFECT_ID_FIELDS = Object.freeze(['targetId', 'rootCauseId', 'language', 'family', 'location', 'affected']);
612
+ const NEGATIVE_ID_FIELDS = Object.freeze(['targetId', 'variant', 'kind', 'language', 'family', 'scope', 'pairedDefectId']);
613
+
614
+ const defectLabelId = (l) => semanticId('dlab', l, DEFECT_ID_FIELDS);
615
+ const negativeLabelId = (l) => semanticId('nlab', l, NEGATIVE_ID_FIELDS);
616
+
617
+ const DL_ALLOWED = (/* unused pure expression or super */ null && (['schema', 'schemaVersion', 'id', 'targetId', 'rootCauseId', 'affected', 'language', 'family', 'cwe', 'location', 'evidence', 'adjudication', 'proposedBy', 'advisoryRefs', 'synthetic', 'createdAt']));
618
+ const DL_REQUIRED = (/* unused pure expression or super */ null && (['schema', 'schemaVersion', 'id', 'targetId', 'rootCauseId', 'affected', 'language', 'family', 'location', 'evidence', 'adjudication', 'proposedBy', 'synthetic']));
619
+ const NL_ALLOWED = (/* unused pure expression or super */ null && (['schema', 'schemaVersion', 'id', 'targetId', 'variant', 'kind', 'language', 'family', 'scope', 'pairedDefectId', 'rationale', 'adjudication', 'proposedBy', 'synthetic', 'createdAt']));
620
+ const NL_REQUIRED = (/* unused pure expression or super */ null && (['schema', 'schemaVersion', 'id', 'targetId', 'variant', 'kind', 'language', 'family', 'scope', 'rationale', 'adjudication', 'proposedBy', 'synthetic']));
621
+
622
+ function checkAdjudication(ctx, label) {
623
+ const a = label.adjudication;
624
+ if (!isPlainObject(a)) { ctx.err('BAD_TYPE', 'adjudication', 'must be an object'); return; }
625
+ if (!checkEnum(ctx, 'adjudication.status', a.status, ADJUDICATION_STATUSES)) return;
626
+ if (!Array.isArray(a.reviewers)) { ctx.err('BAD_TYPE', 'adjudication.reviewers', 'must be an array'); return; }
627
+ if (a.status !== 'adjudicated') return;
628
+ const ids = new Set();
629
+ a.reviewers.forEach((r, i) => {
630
+ if (!isPlainObject(r) || !r.reviewerId) { ctx.err('BAD_TYPE', `adjudication.reviewers[${i}]`, 'a reviewer record names reviewerId and verdict'); return; }
631
+ ids.add(r.reviewerId);
632
+ if (r.verdict !== 'confirmed') ctx.err('RULE_VIOLATION', `adjudication.reviewers[${i}].verdict`, 'an adjudicated label needs every reviewer verdict to be confirmed');
633
+ if (isPlainObject(label.proposedBy) && r.reviewerId === label.proposedBy.id) ctx.err('RULE_VIOLATION', `adjudication.reviewers[${i}]`, 'a proposer cannot adjudicate its own label');
634
+ });
635
+ if (ids.size < 2) ctx.err('RULE_VIOLATION', 'adjudication.reviewers', 'an adjudicated label needs at least two distinct reviewers');
636
+ if (a.independent !== true) ctx.err('RULE_VIOLATION', 'adjudication.independent', 'adjudication must be recorded as independent of the label proposer and the detector authors');
637
+ }
638
+
639
+ function checkEvidence(ctx, label) {
640
+ if (!Array.isArray(label.evidence)) { ctx.err('BAD_TYPE', 'evidence', 'must be an array'); return; }
641
+ label.evidence.forEach((e, i) => {
642
+ if (!isPlainObject(e)) { ctx.err('BAD_TYPE', `evidence[${i}]`, 'must be an object'); return; }
643
+ checkString(ctx, `evidence[${i}].ref`, e.ref);
644
+ checkEnum(ctx, `evidence[${i}].producer`, e.producer, EVIDENCE_PRODUCERS);
645
+ });
646
+ if (label.adjudication?.status === 'adjudicated' && !label.evidence.some((e) => INDEPENDENT_PRODUCERS.includes(e?.producer))) {
647
+ ctx.err('RULE_VIOLATION', 'evidence', 'an adjudicated label needs evidence produced by a human or an independent verifier; model output alone is not adjudication');
648
+ }
649
+ }
650
+
651
+ function labels_validateDefectLabel(l) {
652
+ const g = guardObject(l);
653
+ const ctx = g.ctx;
654
+ if (!g.ok) return result(ctx);
655
+ if (!checkHeader(ctx, l, DEFECT_LABEL_SCHEMA)) return result(ctx);
656
+ checkFields(ctx, l, DL_ALLOWED, DL_REQUIRED);
657
+ checkString(ctx, 'targetId', l.targetId);
658
+ checkString(ctx, 'rootCauseId', l.rootCauseId);
659
+ checkString(ctx, 'language', l.language);
660
+ checkString(ctx, 'family', l.family);
661
+ if (typeof l.synthetic !== 'boolean') ctx.err('BAD_TYPE', 'synthetic', 'must be a boolean');
662
+ if (!isPlainObject(l.affected)) ctx.err('BAD_TYPE', 'affected', 'must name the affected build/commit');
663
+ else checkCommit(ctx, 'affected.commit', l.affected.commit, { nullable: false });
664
+ // The reviewed vulnerable location is mandatory: a CWE-only label cannot exist.
665
+ const loc = l.location;
666
+ if (!isPlainObject(loc)) ctx.err('MISSING_FIELD', 'location', 'a reviewed vulnerable location range is required; a CWE alone does not identify a defect');
667
+ else {
668
+ checkString(ctx, 'location.file', loc.file);
669
+ if (!Number.isInteger(loc.startLine) || !Number.isInteger(loc.endLine) || loc.startLine < 1 || loc.endLine < loc.startLine) {
670
+ ctx.err('BAD_TYPE', 'location', 'startLine/endLine must be positive integers with endLine >= startLine');
671
+ }
672
+ }
673
+ checkAdjudication(ctx, l);
674
+ checkEvidence(ctx, l);
675
+ if (!isPlainObject(l.proposedBy) || !l.proposedBy.id) ctx.err('MISSING_FIELD', 'proposedBy', 'the proposer must be recorded');
676
+ checkId(ctx, l, defectLabelId(l));
677
+ return result(ctx);
678
+ }
679
+
680
+ function labels_validateNegativeLabel(l) {
681
+ const g = guardObject(l);
682
+ const ctx = g.ctx;
683
+ if (!g.ok) return result(ctx);
684
+ if (!checkHeader(ctx, l, NEGATIVE_LABEL_SCHEMA)) return result(ctx);
685
+ checkFields(ctx, l, NL_ALLOWED, NL_REQUIRED);
686
+ checkString(ctx, 'targetId', l.targetId);
687
+ checkString(ctx, 'language', l.language);
688
+ checkString(ctx, 'family', l.family);
689
+ checkString(ctx, 'rationale', l.rationale);
690
+ checkEnum(ctx, 'variant', l.variant, VARIANTS);
691
+ const kindOk = checkEnum(ctx, 'kind', l.kind, NEGATIVE_KINDS);
692
+ if (typeof l.synthetic !== 'boolean') ctx.err('BAD_TYPE', 'synthetic', 'must be a boolean');
693
+ if (!isPlainObject(l.scope) || !Array.isArray(l.scope.files) || l.scope.files.length === 0) ctx.err('MISSING_FIELD', 'scope', 'a negative must name the files it is negative for');
694
+ if (kindOk && l.kind === 'patched') {
695
+ if (l.variant !== 'post') ctx.err('RULE_VIOLATION', 'variant', 'a patched negative is the fixed (post) variant');
696
+ checkString(ctx, 'pairedDefectId', l.pairedDefectId);
697
+ }
698
+ checkAdjudication(ctx, l);
699
+ if (!isPlainObject(l.proposedBy) || !l.proposedBy.id) ctx.err('MISSING_FIELD', 'proposedBy', 'the proposer must be recorded');
700
+ checkId(ctx, l, negativeLabelId(l));
701
+ return result(ctx);
702
+ }
703
+
704
+ function buildDefectLabel(fields) {
705
+ const l = { schema: DEFECT_LABEL_SCHEMA, schemaVersion: SCHEMA_VERSION, synthetic: false, evidence: [], ...fields };
706
+ l.id = defectLabelId(l);
707
+ return l;
708
+ }
709
+ function buildNegativeLabel(fields) {
710
+ const l = { schema: NEGATIVE_LABEL_SCHEMA, schemaVersion: SCHEMA_VERSION, synthetic: false, ...fields };
711
+ l.id = negativeLabelId(l);
712
+ return l;
713
+ }
714
+
715
+ /** Scoreable = structurally valid AND adjudicated. A candidate (advisory-only) label is never scored. */
716
+ function isScoreable(label) {
717
+ return !!label && label.adjudication?.status === 'adjudicated' && validateAny(label).ok;
718
+ }
719
+
720
+ function validateAny(label) {
721
+ return label?.schema === NEGATIVE_LABEL_SCHEMA ? labels_validateNegativeLabel(label) : labels_validateDefectLabel(label);
722
+ }
723
+
724
+ // ---------------------------------------------------------------- matching
725
+
726
+ const norm = (p) => String(p || '').replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
727
+
728
+ /**
729
+ * Does a finding identify the labelled defect? It must (1) sit in the labelled
730
+ * file, (2) carry a line inside the reviewed range widened by `lineWindow`, and
731
+ * (3) agree on family or CWE. CWE agreement alone, a right-file-wrong-line
732
+ * finding and a finding with no line all fail, each with a distinct reason.
733
+ */
734
+ function matchFinding(finding, label, policy) {
735
+ const lineWindow = Number.isInteger(policy?.lineWindow) ? policy.lineWindow : 3;
736
+ const sameFile = norm(finding?.file) === norm(label?.location?.file);
737
+ const familyOk = !!finding?.family && finding.family === label?.family;
738
+ const cweOk = !!finding?.cwe && !!label?.cwe && String(finding.cwe).toUpperCase() === String(label.cwe).toUpperCase();
739
+ if (!sameFile) return { matched: false, reason: cweOk ? 'cwe-only' : 'wrong-file' };
740
+ const line = Number(finding.line);
741
+ if (!Number.isFinite(line) || line <= 0) return { matched: false, reason: 'no-line' };
742
+ const { startLine, endLine } = label.location;
743
+ if (line < startLine - lineWindow || line > endLine + lineWindow) return { matched: false, reason: cweOk || familyOk ? 'outside-range' : 'wrong-location' };
744
+ if (!familyOk && !cweOk) return { matched: false, reason: 'family-mismatch' };
745
+ return { matched: true, reason: 'location-and-family' };
746
+ }
747
+
748
+ /** Does a finding fall in a negative's scope for the family it is negative for? */
749
+ function matchNegative(finding, negative) {
750
+ const inScope = (negative?.scope?.files || []).map(norm).includes(norm(finding?.file));
751
+ if (!inScope) return { matched: false, reason: 'out-of-scope' };
752
+ if (!finding?.family || finding.family !== negative.family) return { matched: false, reason: 'other-family' };
753
+ return { matched: true, reason: 'family-in-negative-scope' };
754
+ }
755
+
756
+ /**
757
+ * Findings on a target that no adjudicated label accounts for. These are NOT
758
+ * false positives: a genuine, previously unlabelled defect would be hiding
759
+ * among them. They go to a review queue and stay out of precision.
760
+ */
761
+ function reviewQueue(entries) {
762
+ return entries.map((e) => ({ targetId: e.targetId, variant: e.variant, findingId: e.finding?.id || null, file: e.finding?.file || null, line: e.finding?.line ?? null, family: e.finding?.family || null, status: 'needs-adjudication', reason: e.reason }));
763
+ }
764
+
765
+ /** Counts of scoreable, real (non-synthetic) labels by language and family, for population gates. */
766
+ function populationCounts(defects, negatives) {
767
+ const out = { positivesByLanguage: {}, negativesByLanguage: {}, positivesByFamily: {}, syntheticPositives: 0, syntheticNegatives: 0, unadjudicated: 0 };
768
+ for (const l of defects || []) {
769
+ if (!isScoreable(l)) { out.unadjudicated++; continue; }
770
+ if (l.synthetic) { out.syntheticPositives++; continue; }
771
+ out.positivesByLanguage[l.language] = (out.positivesByLanguage[l.language] || 0) + 1;
772
+ out.positivesByFamily[l.family] = (out.positivesByFamily[l.family] || 0) + 1;
773
+ }
774
+ for (const n of negatives || []) {
775
+ if (!isScoreable(n)) { out.unadjudicated++; continue; }
776
+ if (n.synthetic) { out.syntheticNegatives++; continue; }
777
+ out.negativesByLanguage[n.language] = (out.negativesByLanguage[n.language] || 0) + 1;
778
+ }
779
+ return out;
780
+ }
781
+
782
+ ;// CONCATENATED MODULE: ./src/posture/evaluation/custody.js
783
+ // Label custody and leakage controls (QA-002.AC03).
784
+ //
785
+ // Two trust domains meet here. The CUSTODIAN (verifier domain) holds adjudicated
786
+ // labels. The engine under test, and any worker or model prompt, is on the other
787
+ // side and must never see an answer key. This module provides the custodian's
788
+ // store, the workspace staging that builds what the engine is allowed to read,
789
+ // and the audits that fail a run when anything label-shaped crosses over.
790
+ //
791
+ // Enforcement, honestly stated:
792
+ // - role checks use the existing trust-domain policy (`mayDo`): workers and
793
+ // targets are denied sealed-label read AND write;
794
+ // - staging and prompt audits are PATTERN checks over known protected terms and
795
+ // file names. They catch planted and accidental leaks of the kinds listed in
796
+ // `leakFixtures`; they are not a proof that no paraphrase gets through;
797
+ // - process-level read denial of the label directory is the sandbox trust
798
+ // boundary's job (`runInBoundary({ labelDirs })`), which this module only
799
+ // feeds. Where no backend proves that control the boundary reports `blocked`.
800
+
801
+
802
+
803
+
804
+
805
+
806
+
807
+
808
+ const LABEL_FILE = 'adjudicated-labels.json';
809
+
810
+ // File names that look like an answer key. Regexes, not literals, so this file
811
+ // is not itself a reference to any particular key file.
812
+ const LEAK_FILENAME_PATTERNS = Object.freeze([
813
+ /(^|\/)(labels?|answers?|expected|ground[-_]?truth|answer[-_]?key|adjudicat\w*|oracle)[^/]*\.(json|jsonl|ya?ml|csv|txt)$/i,
814
+ /(^|\/)result\.json$/i,
815
+ /(^|\/)corpus-baseline[^/]*$/i,
816
+ /(^|\/)(advisory|advisories|ghsa|osv)[^/]*\.(json|md|txt|ya?ml)$/i,
817
+ ]);
818
+
819
+ const BENCHMARK_NAMES = Object.freeze(['owasp benchmark', 'juliet', 'sard test', 'cve-replay', 'corpus-baseline', 'answer key', 'ground truth']);
820
+ const ADVISORY_ID = /\b(CVE-\d{4}-\d{4,}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})\b/i;
821
+ const MIN_TERM = 8;
822
+
823
+ /**
824
+ * Terms that must never reach the engine or a prompt: reviewer evidence refs and
825
+ * rationale, advisory ids and prose, root-cause ids, and fixed-source hints.
826
+ */
827
+ function protectedTermsFrom({ defects = [], negatives = [], advisoryText = [], fixedSourceHints = [], benchmarkNames = BENCHMARK_NAMES } = {}) {
828
+ const terms = new Set();
829
+ const add = (s) => { if (typeof s === 'string' && s.trim().length >= MIN_TERM) terms.add(s.trim().toLowerCase()); };
830
+ for (const d of defects) {
831
+ add(d.rootCauseId);
832
+ for (const e of d.evidence || []) add(e.ref);
833
+ for (const a of d.advisoryRefs || []) add(a);
834
+ }
835
+ for (const n of negatives) add(n.rationale);
836
+ for (const s of [...advisoryText, ...fixedSourceHints, ...benchmarkNames]) add(s);
837
+ return [...terms].sort();
838
+ }
839
+
840
+ /** Leaks in a piece of text (a prompt, a file body). */
841
+ function auditText(text, terms, { strictAdvisoryIds = true } = {}) {
842
+ const hay = String(text ?? '');
843
+ const lower = hay.toLowerCase();
844
+ const leaks = [];
845
+ for (const t of terms || []) if (lower.includes(t)) leaks.push({ kind: 'protected-term', detail: t.length > 60 ? `${t.slice(0, 57)}...` : t });
846
+ if (strictAdvisoryIds) {
847
+ const m = ADVISORY_ID.exec(hay);
848
+ if (m) leaks.push({ kind: 'advisory-id', detail: m[1] });
849
+ }
850
+ return leaks;
851
+ }
852
+
853
+ /** Gate a model/scanner prompt. `ok:false` means the call must not be made. */
854
+ function guardPrompt(prompt, terms, opts) {
855
+ const leaks = auditText(prompt, terms, opts);
856
+ return { ok: leaks.length === 0, leaks };
857
+ }
858
+
859
+ const SKIP_DIRS = new Set(['.git', state_dir/* STATE_DIR_NAME */.Ky, 'node_modules']);
860
+
861
+ /**
862
+ * Audit a directory the engine may read: no answer-key file names, no symlinks
863
+ * (which could point outside it), no protected term or advisory id in content.
864
+ * Bounded so a hostile tree cannot make the audit itself the problem.
865
+ */
866
+ function auditWorkspace(dir, terms, { strictAdvisoryIds = true, maxFiles = 20000, maxFileBytes = 2 * 1024 * 1024 } = {}) {
867
+ const leaks = [];
868
+ let scanned = 0; let skippedLarge = 0; let truncated = false;
869
+ const walk = (d, rel) => {
870
+ let entries = [];
871
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
872
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
873
+ if (truncated) return;
874
+ const r = rel ? `${rel}/${e.name}` : e.name;
875
+ if (e.isSymbolicLink()) { leaks.push({ kind: 'symlink', file: r, detail: 'symlinks are refused in an engine workspace' }); continue; }
876
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) walk(path.join(d, e.name), r); continue; }
877
+ if (!e.isFile()) continue;
878
+ if (++scanned > maxFiles) { truncated = true; leaks.push({ kind: 'audit-truncated', file: r, detail: `more than ${maxFiles} files; the audit cannot vouch for the rest` }); return; }
879
+ if (LEAK_FILENAME_PATTERNS.some((re) => re.test(r))) { leaks.push({ kind: 'answer-key-file', file: r, detail: 'file name looks like a label, answer key or advisory record' }); continue; }
880
+ let st; try { st = fs.statSync(path.join(d, e.name)); } catch { continue; }
881
+ if (st.size > maxFileBytes) { skippedLarge++; continue; }
882
+ let body; try { body = fs.readFileSync(path.join(d, e.name), 'utf8'); } catch { continue; }
883
+ for (const l of auditText(body, terms, { strictAdvisoryIds })) leaks.push({ ...l, file: r });
884
+ }
885
+ };
886
+ walk(dir, '');
887
+ return { ok: leaks.length === 0, leaks, scannedFiles: scanned, skippedLargeFiles: skippedLarge };
888
+ }
889
+
890
+ /**
891
+ * Copy a target tree into a fresh workspace for the engine, then audit it. On any
892
+ * leak the workspace is removed and the target is reported quarantined; the run
893
+ * must record that as a failure, never silently scan the tree anyway.
894
+ */
895
+ function stageWorkspace({ srcDir, destDir, terms, strictAdvisoryIds = true }) {
896
+ fs.rmSync(destDir, { recursive: true, force: true });
897
+ fs.cpSync(srcDir, destDir, {
898
+ recursive: true, dereference: false,
899
+ filter: (s) => !SKIP_DIRS.has(path.basename(s)) || s === srcDir,
900
+ });
901
+ const audit = auditWorkspace(destDir, terms, { strictAdvisoryIds });
902
+ if (!audit.ok) {
903
+ fs.rmSync(destDir, { recursive: true, force: true });
904
+ return { ok: false, quarantined: true, leaks: audit.leaks, destDir: null };
905
+ }
906
+ return { ok: true, quarantined: false, leaks: [], destDir };
907
+ }
908
+
909
+ // ---------------------------------------------------------------- the custodian's store
910
+
911
+ /** Content hash binding a label set: key-order independent, order independent. */
912
+ function sealLabels(defects, negatives) {
913
+ const sortById = (xs) => [...xs].sort((a, b) => String(a.id).localeCompare(String(b.id)));
914
+ return digestOf({ kind: 'evaluation-labels', defects: sortById(defects || []), negatives: sortById(negatives || []) });
915
+ }
916
+
917
+ const isCustodian = (actor) => actor?.domain === DOMAINS.VERIFIER && actor?.role === 'custodian' && !isUntrusted(actor.domain);
918
+
919
+ function denied(code, message) { return { ok: false, errors: [{ code, path: '', message }] }; }
920
+
921
+ /**
922
+ * Write the label set. Only the custodian may; a worker or the target is denied
923
+ * by the trust-domain policy. Every label is validated first: one invalid label
924
+ * rejects the whole write.
925
+ */
926
+ function custodianWriteLabels(labelDir, actor, { defects = [], negatives = [] } = {}) {
927
+ if (!isCustodian(actor)) return denied('CUSTODY_DENIED', `domain '${actor?.domain}' role '${actor?.role}' may not write sealed labels`);
928
+ const errors = [];
929
+ for (const d of defects) { const v = validateDefectLabel(d); if (!v.ok) errors.push(...v.errors.map((e) => ({ ...e, path: `${d?.id}.${e.path}` }))); }
930
+ for (const n of negatives) { const v = validateNegativeLabel(n); if (!v.ok) errors.push(...v.errors.map((e) => ({ ...e, path: `${n?.id}.${e.path}` }))); }
931
+ if (errors.length) return { ok: false, errors };
932
+ fs.mkdirSync(labelDir, { recursive: true, mode: 0o700 });
933
+ try { fs.chmodSync(labelDir, 0o700); } catch { /* best effort */ }
934
+ const file = path.join(labelDir, LABEL_FILE);
935
+ fs.writeFileSync(file, JSON.stringify({ defects, negatives }), { mode: 0o600 });
936
+ return { ok: true, errors: [], labelsHash: sealLabels(defects, negatives), count: { defects: defects.length, negatives: negatives.length } };
937
+ }
938
+
939
+ /** Read the label set. Allowed only where the policy grants sealed-label read, and only if it still matches the sealed hash. */
940
+ function custodianReadLabels(labelDir, actor, { expectedHash } = {}) {
941
+ if (!mayDo(actor?.domain, RESOURCES.SEALED_LABELS, 'read')) return denied('CUSTODY_DENIED', `domain '${actor?.domain}' may not read sealed labels`);
942
+ let data;
943
+ try { data = JSON.parse(fs.readFileSync(path.join(labelDir, LABEL_FILE), 'utf8')); } catch (e) { return denied('LABELS_UNREADABLE', `cannot read labels: ${e.code || e.message}`); }
944
+ const defects = Array.isArray(data?.defects) ? data.defects : []; const negatives = Array.isArray(data?.negatives) ? data.negatives : [];
945
+ const labelsHash = sealLabels(defects, negatives);
946
+ if (expectedHash && labelsHash !== expectedHash) return denied('LABELS_HASH_MISMATCH', 'labels changed after they were sealed');
947
+ return { ok: true, errors: [], defects, negatives, labelsHash };
948
+ }
949
+
950
+ // realpath of the nearest existing ancestor plus the not-yet-existing remainder, so a path that does not exist
951
+ // yet still compares correctly against one reached through a symlinked parent (macOS /var -> /private/var).
952
+ function real(p) {
953
+ let cur = path.resolve(p); const rest = [];
954
+ for (;;) {
955
+ try { return path.join(fs.realpathSync(cur), ...rest.reverse()); } catch { /* climb */ }
956
+ const parent = path.dirname(cur);
957
+ if (parent === cur) return path.resolve(p);
958
+ rest.push(path.basename(cur)); cur = parent;
959
+ }
960
+ }
961
+
962
+ /** A workspace that contains, or sits inside, the label directory would hand the engine the answer key by construction. */
963
+ function assertCustodyIsolation(labelDir, workspaceDir) {
964
+ const a = real(labelDir); const b = real(workspaceDir);
965
+ if (a === b || a.startsWith(b + path.sep) || b.startsWith(a + path.sep)) {
966
+ return denied('CUSTODY_OVERLAP', `workspace ${workspaceDir} overlaps the label directory ${labelDir}`);
967
+ }
968
+ return { ok: true, errors: [] };
969
+ }
970
+
971
+ /** Environment for the engine under test: secret-looking variables, evaluation variables and anything naming the label directory are removed. */
972
+ function engineEnvironment(base, { labelDir } = {}) {
973
+ const scrubbed = scrubEnv(base || {});
974
+ const out = {};
975
+ const labelReal = labelDir ? real(labelDir) : null;
976
+ for (const [k, v] of Object.entries(scrubbed)) {
977
+ if (/^AGENTIC_(SECURITY_)?EVAL/i.test(k)) continue;
978
+ if (labelDir && typeof v === 'string' && (v.includes(labelDir) || v.includes(labelReal))) continue;
979
+ out[k] = v;
980
+ }
981
+ return out;
982
+ }
983
+
984
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/promotion.js
985
+ // Promotion gate (PRD 3 "Promotion Gate"): precision/recall thresholds, zero protected-negative failures, zero
986
+ // benchmark leakage. A candidate rule does NOT automatically become a production rule — `evaluateRule` only
987
+ // scores; `gatePromotion` only judges; the lifecycle ledger (`lifecycle.js`) is the one place a PROMOTED state is
988
+ // actually recorded, and nothing in this module writes to it.
989
+
990
+
991
+
992
+ const PROMOTION_DEFAULTS = Object.freeze({ minPrecision: 0.95, minRecall: 0.80, maxProtectedFailures: 0 });
993
+
994
+ /** Anti-cheating: the synthesis agent must never see benchmark answer keys, hidden labels, CWE-bearing hidden
995
+ * filenames, vulnerability comments or protected test metadata. Reuses the evaluation custodian's own term list
996
+ * and guard (QA-002.AC03) rather than inventing a second leakage checker. */
997
+ function checkLeakage(promptText, { benchmarkNames = [] } = {}) {
998
+ const terms = protectedTermsFrom({ advisoryText: [], benchmarkNames });
999
+ const g = guardPrompt(promptText, terms);
1000
+ return { ok: g.ok, offendingTerms: g.ok ? [] : g.leaks.map((l) => l.detail) };
1001
+ }
1002
+
1003
+ function evaluateRule(ir, corpus, thresholds = PROMOTION_DEFAULTS) {
1004
+ const score = scoreRule(ir, corpus);
1005
+ const t = { ...PROMOTION_DEFAULTS, ...thresholds };
1006
+ const reasons = [];
1007
+ if (score.precision === null) reasons.push('precision unmeasured (no positive or negative corpus fired)');
1008
+ else if (score.precision < t.minPrecision) reasons.push(`precision ${(score.precision * 100).toFixed(1)}% below ${(t.minPrecision * 100).toFixed(0)}%`);
1009
+ if (score.recall === null) reasons.push('recall unmeasured (empty positive corpus)');
1010
+ else if (score.recall < t.minRecall) reasons.push(`recall ${(score.recall * 100).toFixed(1)}% below ${(t.minRecall * 100).toFixed(0)}%`);
1011
+ if (score.protectedFailures > t.maxProtectedFailures) reasons.push(`${score.protectedFailures} protected-negative failure(s) (max ${t.maxProtectedFailures})`);
1012
+ return { pass: reasons.length === 0, reasons, score, thresholds: t };
1013
+ }
1014
+
1015
+ /** The one promotion decision. Never auto-applied: a caller still has to act on `pass:true` by recording a
1016
+ * lifecycle transition. Localization ("acceptable") is a human/caller judgment this function cannot make from
1017
+ * line/column alone; it is surfaced for review, never silently assumed. */
1018
+ function gatePromotion({ ir, corpus, leakageCheck, thresholds } = {}) {
1019
+ const evalResult = evaluateRule(ir, corpus, thresholds);
1020
+ const reasons = [...evalResult.reasons];
1021
+ if (!leakageCheck || leakageCheck.ok !== true) reasons.push(leakageCheck ? `leakage check failed: ${leakageCheck.offendingTerms.join(', ')}` : 'leakage check was not run');
1022
+ return { pass: reasons.length === 0, reasons, evaluation: evalResult };
1023
+ }
1024
+
1025
+ // EXTERNAL MODULE: external "node:crypto"
1026
+ var external_node_crypto_ = __webpack_require__(77598);
1027
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/lifecycle.js
1028
+ // Rule lifecycle ledger: DRAFT -> CANDIDATE -> VALIDATED -> PROMOTED -> DEPRECATED/ROLLED_BACK.
1029
+ //
1030
+ // Append-only, hash-chained (same idiom as remediation-ledger.js / invariants/lifecycle.js): each entry links the
1031
+ // previous entry's hash, so a dropped or edited middle record breaks the chain and `verifyLedger` catches it. A
1032
+ // rule cannot promote itself: `transition` only records a transition a caller already decided; `advance`-style
1033
+ // guarding on VALID edges lives here so no caller can jump DRAFT straight to PROMOTED.
1034
+
1035
+
1036
+
1037
+ const LEDGER_SCHEMA = 'agentic-security/rule-lifecycle-ledger';
1038
+ const EDGES = Object.freeze({
1039
+ DRAFT: ['CANDIDATE'], CANDIDATE: ['VALIDATED', 'DRAFT'], VALIDATED: ['PROMOTED', 'DRAFT'],
1040
+ PROMOTED: ['DEPRECATED', 'ROLLED_BACK'], DEPRECATED: [], ROLLED_BACK: ['CANDIDATE'],
1041
+ });
1042
+
1043
+ const hashOf = (entry) => (0,external_node_crypto_.createHash)('sha256').update(JSON.stringify(entry)).digest('hex');
1044
+
1045
+ function newLedger() { return { schema: LEDGER_SCHEMA, entries: [] }; }
1046
+
1047
+ function currentState(ledger, ruleId) {
1048
+ for (let i = ledger.entries.length - 1; i >= 0; i--) if (ledger.entries[i].ruleId === ruleId) return ledger.entries[i].to;
1049
+ return null;
1050
+ }
1051
+
1052
+ /**
1053
+ * Record a transition. Refuses an edge not in EDGES, and refuses DRAFT->DRAFT re-entry for a rule that has never
1054
+ * existed (the first entry for a rule id must be `from: null, to: 'DRAFT'`).
1055
+ */
1056
+ function recordTransition(ledger, { ruleId, from, to, reason, evidence = null, actor }) {
1057
+ if (!RULE_STATES.includes(to)) return { ok: false, reason: `unknown target state: ${to}` };
1058
+ const cur = currentState(ledger, ruleId);
1059
+ if (cur === null) {
1060
+ if (from !== null || to !== 'DRAFT') return { ok: false, reason: 'first transition for a rule must be null -> DRAFT' };
1061
+ } else {
1062
+ if (from !== cur) return { ok: false, reason: `stale transition: current state is ${cur}, not ${from}` };
1063
+ if (!EDGES[cur].includes(to)) return { ok: false, reason: `cannot go from ${cur} to ${to}` };
1064
+ }
1065
+ const prevHash = ledger.entries.length ? ledger.entries[ledger.entries.length - 1].entryHash : null;
1066
+ const entry = { ruleId, from: cur, to, reason: reason ?? null, evidence, actor: actor ?? 'unknown', at: new Date().toISOString(), prevHash };
1067
+ entry.entryHash = hashOf({ ...entry, entryHash: undefined });
1068
+ ledger.entries.push(entry);
1069
+ return { ok: true, entry };
1070
+ }
1071
+
1072
+ function verifyLedger(ledger) {
1073
+ let prevHash = null;
1074
+ for (const e of ledger.entries) {
1075
+ if (e.prevHash !== prevHash) return { ok: false, reason: 'chain broken: prevHash mismatch' };
1076
+ const recomputed = hashOf({ ...e, entryHash: undefined });
1077
+ if (recomputed !== e.entryHash) return { ok: false, reason: `entry hash mismatch for ${e.ruleId} at ${e.at}` };
1078
+ prevHash = e.entryHash;
1079
+ }
1080
+ return { ok: true };
1081
+ }
1082
+
1083
+ function historyFor(ledger, ruleId) { return ledger.entries.filter((e) => e.ruleId === ruleId); }
1084
+ function stateOf(ledger, ruleId) { return currentState(ledger, ruleId); }
1085
+
1086
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/store.js
1087
+ // Persistence for the rule compiler: one directory per rule under `.agentic-security/rule-compiler/<id>/`
1088
+ // (`ir.json`, `ledger.json`, `evaluation.json`), the promoted custom-rule document at
1089
+ // `.agentic-security/rules/<id>.yml` (so the EXISTING `loadCustomRules`/`rule test` machinery picks it up with no
1090
+ // change), and a regression fixture pair at `.agentic-security/rule-compiler/fixtures/<id>/{vulnerable,clean}/`
1091
+ // using the SAME filename convention `runRuleTests` already reads (`vulnerable`/`clean` in the path).
1092
+
1093
+
1094
+
1095
+
1096
+
1097
+
1098
+ const DIR = 'rule-compiler';
1099
+ const store_EXT = { javascript: 'js', typescript: 'ts', python: 'py', go: 'go', ruby: 'rb', java: 'java', rust: 'rs', csharp: 'cs', php: 'php', any: 'txt' };
1100
+
1101
+ function ruleDir(scanRoot, id) { return (0,state_dir.statePath)(scanRoot, DIR, id); }
1102
+
1103
+ function loadLedger(scanRoot) {
1104
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
1105
+ if (!external_node_fs_.existsSync(f)) return newLedger();
1106
+ try {
1107
+ const ledger = JSON.parse(external_node_fs_.readFileSync(f, 'utf8'));
1108
+ const v = verifyLedger(ledger);
1109
+ return v.ok ? ledger : { ...newLedger(), tampered: true, tamperReason: v.reason };
1110
+ } catch { return newLedger(); }
1111
+ }
1112
+
1113
+ function saveLedger(scanRoot, ledger) {
1114
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
1115
+ const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
1116
+ return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(ledger, null, 2)) };
1117
+ }
1118
+
1119
+ function saveIR(scanRoot, ir) {
1120
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
1121
+ const f = external_node_path_.join(ruleDir(scanRoot, ir.id), 'ir.json');
1122
+ return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(ir, null, 2)), file: f };
1123
+ }
1124
+
1125
+ function loadIR(scanRoot, id) {
1126
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'ir.json');
1127
+ try { return JSON.parse(external_node_fs_.readFileSync(f, 'utf8')); } catch { return null; }
1128
+ }
1129
+
1130
+ function saveEvaluation(scanRoot, id, evaluation) {
1131
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
1132
+ const f = external_node_path_.join(ruleDir(scanRoot, id), 'evaluation.json');
1133
+ return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(evaluation, null, 2)) };
1134
+ }
1135
+
1136
+ /** Write the regression fixtures a promoted rule needs: the SAME vulnerable/clean convention `runRuleTests`
1137
+ * already reads, scored against the exact corpus the rule was promoted on. */
1138
+ function writeFixtures(scanRoot, ir, corpus) {
1139
+ const ext = store_EXT[ir.languages[0]] || 'txt';
1140
+ const base = external_node_path_.join(ruleDir(scanRoot, ir.id), 'fixtures');
1141
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
1142
+ const written = [];
1143
+ for (const p of corpus.positives) {
1144
+ const f = external_node_path_.join(base, 'vulnerable', `${p.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
1145
+ if ((0,state_dir/* safeWriteState */.Ep)(f, p.code)) written.push(f);
1146
+ }
1147
+ for (const n of corpus.negatives) {
1148
+ const f = external_node_path_.join(base, 'clean', `${n.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
1149
+ if ((0,state_dir/* safeWriteState */.Ep)(f, n.code)) written.push(f);
1150
+ }
1151
+ return { ok: true, written, glob: external_node_path_.join(base, '**', '*') };
1152
+ }
1153
+
1154
+ /** Promote: write the compiled custom-rule document to the live rules directory. Does not touch the ledger —
1155
+ * the caller records the PROMOTED transition itself, so a failed write here can never produce an inconsistent
1156
+ * "promoted but not live" or "live but not recorded" state silently. */
1157
+ function publishCustomRule(scanRoot, ir) {
1158
+ const { ok, doc, errs } = compileToCustomRule(ir);
1159
+ if (!ok) return { ok: false, reason: `invalid rule IR: ${errs.join('; ')}` };
1160
+ if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
1161
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${ir.id}.yml`);
1162
+ const yamlText = [
1163
+ `# Compiled by the rule compiler from finding ${ir.provenance.originatingFindingId} (${ir.provenance.evidenceState}).`,
1164
+ `- id: ${doc.id}`,
1165
+ ` title: ${JSON.stringify(doc.title)}`,
1166
+ ` severity: ${doc.severity}`,
1167
+ ` cwe: ${doc.cwe}`,
1168
+ ` languages: [${doc.languages.join(', ')}]`,
1169
+ ` match:`,
1170
+ ...(doc.match.pattern ? [` pattern: ${JSON.stringify(doc.match.pattern)}`] : []),
1171
+ ...(doc.match.allOf ? [` allOf:`, ...doc.match.allOf.map((p) => ` - ${JSON.stringify(p)}`), ` window: ${doc.match.window}`] : []),
1172
+ ...(doc.match.notMatch ? [` notMatch: ${JSON.stringify(doc.match.notMatch)}`] : []),
1173
+ ` message: ${JSON.stringify(doc.message)}`,
1174
+ '',
1175
+ ].join('\n');
1176
+ return { ok: (0,state_dir/* safeWriteState */.Ep)(f, yamlText), file: f };
1177
+ }
1178
+
1179
+ function unpublishCustomRule(scanRoot, id) {
1180
+ const f = (0,state_dir.statePath)(scanRoot, 'rules', `${id}.yml`);
1181
+ try { if (external_node_fs_.existsSync(f)) external_node_fs_.unlinkSync(f); return { ok: true }; } catch (e) { return { ok: false, reason: e.message }; }
1182
+ }
1183
+
1184
+ ;// CONCATENATED MODULE: ./src/posture/rule-compiler/cli.js
1185
+ // CLI surface: `agentic-security rules synthesize|evaluate|promote|status|rollback`.
1186
+ //
1187
+ // Distinct from the pre-existing `labs synthesize-rule` (posture/rule-synthesis.js), which proposes SUPPRESSION
1188
+ // rules from repeated false-positive triage verdicts — a different input, a different output and a different
1189
+ // command group on purpose, so the two are never confused at the CLI.
1190
+ //
1191
+ // Non-interactive by construction: no command reads stdin, every corpus evaluation is bounded (no network, no
1192
+ // model call — this is the deterministic half; a model may PROPOSE the candidate pattern this CLI is handed, but
1193
+ // it never decides promotion).
1194
+
1195
+
1196
+
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+
1203
+ function loadFinding(root, id) {
1204
+ const p = (0,state_dir.statePath)(root, 'last-scan.json');
1205
+ if (!external_node_fs_.existsSync(p)) return null;
1206
+ const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
1207
+ return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
1208
+ }
1209
+
1210
+ function readJsonArg(pathOrInline) {
1211
+ if (!pathOrInline) return null;
1212
+ try { return JSON.parse(external_node_fs_.existsSync(pathOrInline) ? external_node_fs_.readFileSync(pathOrInline, 'utf8') : pathOrInline); } catch { return null; }
1213
+ }
1214
+
1215
+ async function cmdRules(args, root) {
1216
+ const sub = args._[1];
1217
+ if (sub === 'synthesize') return cmdSynthesize(args, root);
1218
+ if (sub === 'evaluate') return cmdEvaluate(args, root);
1219
+ if (sub === 'promote') return cmdPromote(args, root);
1220
+ if (sub === 'status') return cmdStatus(args, root);
1221
+ if (sub === 'rollback') return cmdRollback(args, root);
1222
+ console.error('usage: rules synthesize <finding-id> --spec <file.json> | evaluate <rule-id> | promote <rule-id> | status [rule-id] | rollback <rule-id>');
1223
+ return 4;
1224
+ }
1225
+
1226
+ // `--spec` carries exactly what a model or a human proposed: id/title/severity/cwe/family/languages/match/
1227
+ // remediation plus the corpus inputs (originalCode/patchedCode/nearbyCleanCode/protectedVariantsCode). This
1228
+ // command never invents a pattern; it only drafts the IR, checks eligibility and records DRAFT->CANDIDATE.
1229
+ async function cmdSynthesize(args, root) {
1230
+ const findingId = args._[2];
1231
+ const spec = readJsonArg(args.flags.spec);
1232
+ if (!findingId || !spec) { console.error('usage: rules synthesize <finding-id> --spec <file.json>'); return 4; }
1233
+ const finding = loadFinding(root, findingId);
1234
+ if (!finding) { console.error(`Finding ${findingId} not found in last scan.`); return 4; }
1235
+ const elig = checkEligibility(finding, { proofState: args.flags['proof-state'] || null });
1236
+ if (!elig.eligible) { console.error(`Not eligible for rule synthesis: ${elig.reasons.join('; ')}`); return 4; }
1237
+
1238
+ const ir = draftRuleIR({ ...spec, originatingFindingId: finding.stableId ?? finding.id, originatingCommit: spec.originatingCommit ?? null, evidenceState: elig.evidenceState });
1239
+ const errs = validateRuleIR(ir);
1240
+ if (errs.length) { console.error(`Invalid rule: ${errs.join('; ')}`); return 4; }
1241
+
1242
+ const ledger = loadLedger(root);
1243
+ const draft = recordTransition(ledger, { ruleId: ir.id, from: null, to: 'DRAFT', reason: `drafted from ${findingId}`, actor: args.flags.actor || 'agent' });
1244
+ if (!draft.ok) { console.error(draft.reason); return 4; }
1245
+ const cand = recordTransition(ledger, { ruleId: ir.id, from: 'DRAFT', to: 'CANDIDATE', reason: 'eligibility passed', evidence: { eligibility: elig }, actor: args.flags.actor || 'agent' });
1246
+ saveLedger(root, ledger);
1247
+ saveIR(root, { ...ir, state: 'CANDIDATE' });
1248
+ console.log(`Rule ${ir.id}: DRAFT -> CANDIDATE (digest ${ruleIRDigest(ir).slice(0, 12)})`);
1249
+ if (!cand.ok) console.error(cand.reason);
1250
+ return 0;
1251
+ }
1252
+
1253
+ async function cmdEvaluate(args, root) {
1254
+ const id = args._[2];
1255
+ if (!id) { console.error('usage: rules evaluate <rule-id> --corpus <file.json>'); return 4; }
1256
+ const ir = loadIR(root, id);
1257
+ if (!ir) { console.error(`No rule IR found for ${id}. Run rules synthesize first.`); return 4; }
1258
+ const corpusSpec = readJsonArg(args.flags.corpus);
1259
+ if (!corpusSpec) { console.error('No corpus supplied. Pass --corpus <file.json> with originalCode (and optionally patchedCode/nearbyCleanCode/protectedVariantsCode).'); return 4; }
1260
+ const corpus = buildCorpus(ir, corpusSpec);
1261
+ const leakage = checkLeakage(JSON.stringify(corpusSpec), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [] });
1262
+ const gate = gatePromotion({ ir, corpus, leakageCheck: leakage, thresholds: args.flags.thresholds ? readJsonArg(args.flags.thresholds) : PROMOTION_DEFAULTS });
1263
+
1264
+ const ledger = loadLedger(root);
1265
+ const cur = stateOf(ledger, id);
1266
+ 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' });
1267
+ saveLedger(root, ledger);
1268
+ saveEvaluation(root, id, gate);
1269
+ if (args.flags.json) console.log(JSON.stringify(gate, null, 2));
1270
+ else {
1271
+ console.log(`Rule ${id}: ${gate.pass ? 'VALIDATED' : 'gate FAILED'}`);
1272
+ console.log(` precision ${fmtPct(gate.evaluation.score.precision)} recall ${fmtPct(gate.evaluation.score.recall)} protected-failures ${gate.evaluation.score.protectedFailures}`);
1273
+ for (const r of gate.reasons) console.log(` - ${r}`);
1274
+ }
1275
+ 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/`); }
1276
+ return gate.pass ? 0 : 1;
1277
+ }
1278
+ const fmtPct = (n) => (n == null ? 'unmeasured' : `${(n * 100).toFixed(1)}%`);
1279
+
1280
+ async function cmdPromote(args, root) {
1281
+ const id = args._[2];
1282
+ if (!id) { console.error('usage: rules promote <rule-id>'); return 4; }
1283
+ const ledger = loadLedger(root);
1284
+ if (ledger.tampered) { console.error(`Refusing: rule lifecycle ledger failed its integrity check (${ledger.tamperReason}).`); return 4; }
1285
+ if (stateOf(ledger, id) !== 'VALIDATED') { console.error(`Rule ${id} is not VALIDATED (run rules evaluate first); refusing to promote.`); return 4; }
1286
+ const ir = loadIR(root, id);
1287
+ if (!ir) { console.error(`No rule IR found for ${id}.`); return 4; }
1288
+ const pub = publishCustomRule(root, ir);
1289
+ if (!pub.ok) { console.error(`Promotion refused: ${pub.reason}`); return 4; }
1290
+ const t = recordTransition(ledger, { ruleId: id, from: 'VALIDATED', to: 'PROMOTED', reason: args.flags.reason || 'promoted', actor: args.flags.actor || 'operator' });
1291
+ saveLedger(root, ledger);
1292
+ console.log(`Rule ${id}: VALIDATED -> PROMOTED. Published to ${pub.file}.`);
1293
+ if (!t.ok) console.error(t.reason);
1294
+ return 0;
1295
+ }
1296
+
1297
+ async function cmdRollback(args, root) {
1298
+ const id = args._[2];
1299
+ if (!id) { console.error('usage: rules rollback <rule-id> [--reason text]'); return 4; }
1300
+ const ledger = loadLedger(root);
1301
+ const cur = stateOf(ledger, id);
1302
+ if (cur !== 'PROMOTED') { console.error(`Rule ${id} is not PROMOTED (current: ${cur ?? 'unknown'}); nothing to roll back.`); return 4; }
1303
+ const un = unpublishCustomRule(root, id);
1304
+ const t = recordTransition(ledger, { ruleId: id, from: 'PROMOTED', to: 'ROLLED_BACK', reason: args.flags.reason || 'operator rollback', actor: args.flags.actor || 'operator' });
1305
+ saveLedger(root, ledger);
1306
+ console.log(`Rule ${id}: PROMOTED -> ROLLED_BACK.${un.ok ? '' : ` (warning: could not remove published rule file: ${un.reason})`}`);
1307
+ return t.ok ? 0 : 1;
1308
+ }
1309
+
1310
+ async function cmdStatus(args, root) {
1311
+ const ledger = loadLedger(root);
1312
+ const id = args._[2];
1313
+ if (id) {
1314
+ const h = historyFor(ledger, id);
1315
+ if (!h.length) { console.error(`No history for rule ${id}.`); return 4; }
1316
+ if (args.flags.json) console.log(JSON.stringify(h, null, 2));
1317
+ else { console.log(`Rule ${id}: ${stateOf(ledger, id)}`); for (const e of h) console.log(` ${e.at} ${e.from ?? '(new)'} -> ${e.to} (${e.reason || ''})`); }
1318
+ return 0;
1319
+ }
1320
+ const ids = [...new Set(ledger.entries.map((e) => e.ruleId))];
1321
+ if (args.flags.json) { console.log(JSON.stringify(ids.map((rid) => ({ id: rid, state: stateOf(ledger, rid) })), null, 2)); return 0; }
1322
+ if (!ids.length) { console.log('No rules in the lifecycle ledger yet.'); return 0; }
1323
+ for (const rid of ids) console.log(` ${rid.padEnd(40)} ${stateOf(ledger, rid)}`);
1324
+ return 0;
1325
+ }
1326
+
1327
+
1328
+ /***/ })
1329
+
1330
+ };