@clear-capabilities/agentic-security-scanner 0.166.0 → 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.
- package/CHANGELOG.md +49 -0
- package/bin/agentic-security.js +39 -4
- package/dist/2199.index.js +348 -0
- package/dist/3740.index.js +722 -0
- package/dist/4113.index.js +1 -1
- package/dist/4142.index.js +929 -0
- package/dist/5738.index.js +240 -0
- package/dist/7838.index.js +1 -1
- package/dist/808.index.js +1330 -0
- package/dist/818.index.js +93 -0
- package/dist/9800.index.js +245 -0
- package/dist/9999.index.js +2 -2
- package/dist/agentic-security.mjs +2 -2
- package/dist/agentic-security.mjs.sha256 +1 -1
- package/package.json +2 -2
- package/src/posture/artifact-registry.js +3 -0
- package/src/posture/proof-fabric/cli.js +115 -0
- package/src/posture/proof-fabric/fix-proof.js +73 -0
- package/src/posture/proof-fabric/oracles.js +101 -0
- package/src/posture/proof-fabric/orchestrator.js +129 -0
- package/src/posture/proof-fabric/reproducer.js +108 -0
- package/src/posture/proof-fabric/runner.js +243 -0
- package/src/posture/proof-fabric/states.js +53 -0
- package/src/posture/proof-fabric/store.js +83 -0
- package/src/posture/rule-compiler/cli.js +141 -0
- package/src/posture/rule-compiler/corpus.js +61 -0
- package/src/posture/rule-compiler/eligibility.js +25 -0
- package/src/posture/rule-compiler/ir.js +87 -0
- package/src/posture/rule-compiler/lifecycle.js +57 -0
- package/src/posture/rule-compiler/mutation.js +60 -0
- package/src/posture/rule-compiler/promotion.js +47 -0
- package/src/posture/rule-compiler/store.js +96 -0
- package/src/sandbox/backend-userspace.js +7 -1
- package/src/sandbox/trust-boundary.js +2 -1
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
export const id = 4142;
|
|
2
|
+
export const ids = [4142];
|
|
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
|
+
/***/ 94142:
|
|
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
|
+
;// CONCATENATED MODULE: ./src/posture/rule-compiler/promotion.js
|
|
574
|
+
// Promotion gate (PRD 3 "Promotion Gate"): precision/recall thresholds, zero protected-negative failures, zero
|
|
575
|
+
// benchmark leakage. A candidate rule does NOT automatically become a production rule — `evaluateRule` only
|
|
576
|
+
// scores; `gatePromotion` only judges; the lifecycle ledger (`lifecycle.js`) is the one place a PROMOTED state is
|
|
577
|
+
// actually recorded, and nothing in this module writes to it.
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
const PROMOTION_DEFAULTS = Object.freeze({ minPrecision: 0.95, minRecall: 0.80, maxProtectedFailures: 0 });
|
|
581
|
+
|
|
582
|
+
// Deliberately independent of posture/evaluation/custody.js: that module's term list and guard are reserved for
|
|
583
|
+
// the evaluation custodian's sealed-label boundary (QA-002.AC03), and a test enforces that nothing outside
|
|
584
|
+
// posture/evaluation/ may import it. The anti-cheating need here is smaller and different in kind — a rule
|
|
585
|
+
// synthesis prompt/corpus must not embed a benchmark name or an advisory id — so it gets its own small, independent
|
|
586
|
+
// checker rather than reaching across that isolation boundary.
|
|
587
|
+
const ADVISORY_ID = /\b(?:CVE|GHSA|CWE)-[A-Za-z0-9-]+\b/i;
|
|
588
|
+
|
|
589
|
+
/** Anti-cheating: the synthesis agent must never see benchmark answer keys, hidden labels, CWE-bearing hidden
|
|
590
|
+
* filenames or vulnerability-comment metadata. */
|
|
591
|
+
function checkLeakage(promptText, { benchmarkNames = [] } = {}) {
|
|
592
|
+
const hay = String(promptText ?? '');
|
|
593
|
+
const offending = [];
|
|
594
|
+
for (const name of benchmarkNames) if (name && hay.toLowerCase().includes(String(name).toLowerCase())) offending.push(name);
|
|
595
|
+
const m = ADVISORY_ID.exec(hay);
|
|
596
|
+
if (m) offending.push(m[0]);
|
|
597
|
+
return { ok: offending.length === 0, offendingTerms: offending };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function evaluateRule(ir, corpus, thresholds = PROMOTION_DEFAULTS) {
|
|
601
|
+
const score = scoreRule(ir, corpus);
|
|
602
|
+
const t = { ...PROMOTION_DEFAULTS, ...thresholds };
|
|
603
|
+
const reasons = [];
|
|
604
|
+
if (score.precision === null) reasons.push('precision unmeasured (no positive or negative corpus fired)');
|
|
605
|
+
else if (score.precision < t.minPrecision) reasons.push(`precision ${(score.precision * 100).toFixed(1)}% below ${(t.minPrecision * 100).toFixed(0)}%`);
|
|
606
|
+
if (score.recall === null) reasons.push('recall unmeasured (empty positive corpus)');
|
|
607
|
+
else if (score.recall < t.minRecall) reasons.push(`recall ${(score.recall * 100).toFixed(1)}% below ${(t.minRecall * 100).toFixed(0)}%`);
|
|
608
|
+
if (score.protectedFailures > t.maxProtectedFailures) reasons.push(`${score.protectedFailures} protected-negative failure(s) (max ${t.maxProtectedFailures})`);
|
|
609
|
+
return { pass: reasons.length === 0, reasons, score, thresholds: t };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** The one promotion decision. Never auto-applied: a caller still has to act on `pass:true` by recording a
|
|
613
|
+
* lifecycle transition. Localization ("acceptable") is a human/caller judgment this function cannot make from
|
|
614
|
+
* line/column alone; it is surfaced for review, never silently assumed. */
|
|
615
|
+
function gatePromotion({ ir, corpus, leakageCheck, thresholds } = {}) {
|
|
616
|
+
const evalResult = evaluateRule(ir, corpus, thresholds);
|
|
617
|
+
const reasons = [...evalResult.reasons];
|
|
618
|
+
if (!leakageCheck || leakageCheck.ok !== true) reasons.push(leakageCheck ? `leakage check failed: ${leakageCheck.offendingTerms.join(', ')}` : 'leakage check was not run');
|
|
619
|
+
return { pass: reasons.length === 0, reasons, evaluation: evalResult };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// EXTERNAL MODULE: external "node:crypto"
|
|
623
|
+
var external_node_crypto_ = __webpack_require__(77598);
|
|
624
|
+
;// CONCATENATED MODULE: ./src/posture/rule-compiler/lifecycle.js
|
|
625
|
+
// Rule lifecycle ledger: DRAFT -> CANDIDATE -> VALIDATED -> PROMOTED -> DEPRECATED/ROLLED_BACK.
|
|
626
|
+
//
|
|
627
|
+
// Append-only, hash-chained (same idiom as remediation-ledger.js / invariants/lifecycle.js): each entry links the
|
|
628
|
+
// previous entry's hash, so a dropped or edited middle record breaks the chain and `verifyLedger` catches it. A
|
|
629
|
+
// rule cannot promote itself: `transition` only records a transition a caller already decided; `advance`-style
|
|
630
|
+
// guarding on VALID edges lives here so no caller can jump DRAFT straight to PROMOTED.
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
const LEDGER_SCHEMA = 'agentic-security/rule-lifecycle-ledger';
|
|
635
|
+
const EDGES = Object.freeze({
|
|
636
|
+
DRAFT: ['CANDIDATE'], CANDIDATE: ['VALIDATED', 'DRAFT'], VALIDATED: ['PROMOTED', 'DRAFT'],
|
|
637
|
+
PROMOTED: ['DEPRECATED', 'ROLLED_BACK'], DEPRECATED: [], ROLLED_BACK: ['CANDIDATE'],
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
const hashOf = (entry) => (0,external_node_crypto_.createHash)('sha256').update(JSON.stringify(entry)).digest('hex');
|
|
641
|
+
|
|
642
|
+
function newLedger() { return { schema: LEDGER_SCHEMA, entries: [] }; }
|
|
643
|
+
|
|
644
|
+
function currentState(ledger, ruleId) {
|
|
645
|
+
for (let i = ledger.entries.length - 1; i >= 0; i--) if (ledger.entries[i].ruleId === ruleId) return ledger.entries[i].to;
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Record a transition. Refuses an edge not in EDGES, and refuses DRAFT->DRAFT re-entry for a rule that has never
|
|
651
|
+
* existed (the first entry for a rule id must be `from: null, to: 'DRAFT'`).
|
|
652
|
+
*/
|
|
653
|
+
function recordTransition(ledger, { ruleId, from, to, reason, evidence = null, actor }) {
|
|
654
|
+
if (!RULE_STATES.includes(to)) return { ok: false, reason: `unknown target state: ${to}` };
|
|
655
|
+
const cur = currentState(ledger, ruleId);
|
|
656
|
+
if (cur === null) {
|
|
657
|
+
if (from !== null || to !== 'DRAFT') return { ok: false, reason: 'first transition for a rule must be null -> DRAFT' };
|
|
658
|
+
} else {
|
|
659
|
+
if (from !== cur) return { ok: false, reason: `stale transition: current state is ${cur}, not ${from}` };
|
|
660
|
+
if (!EDGES[cur].includes(to)) return { ok: false, reason: `cannot go from ${cur} to ${to}` };
|
|
661
|
+
}
|
|
662
|
+
const prevHash = ledger.entries.length ? ledger.entries[ledger.entries.length - 1].entryHash : null;
|
|
663
|
+
const entry = { ruleId, from: cur, to, reason: reason ?? null, evidence, actor: actor ?? 'unknown', at: new Date().toISOString(), prevHash };
|
|
664
|
+
entry.entryHash = hashOf({ ...entry, entryHash: undefined });
|
|
665
|
+
ledger.entries.push(entry);
|
|
666
|
+
return { ok: true, entry };
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function verifyLedger(ledger) {
|
|
670
|
+
let prevHash = null;
|
|
671
|
+
for (const e of ledger.entries) {
|
|
672
|
+
if (e.prevHash !== prevHash) return { ok: false, reason: 'chain broken: prevHash mismatch' };
|
|
673
|
+
const recomputed = hashOf({ ...e, entryHash: undefined });
|
|
674
|
+
if (recomputed !== e.entryHash) return { ok: false, reason: `entry hash mismatch for ${e.ruleId} at ${e.at}` };
|
|
675
|
+
prevHash = e.entryHash;
|
|
676
|
+
}
|
|
677
|
+
return { ok: true };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function historyFor(ledger, ruleId) { return ledger.entries.filter((e) => e.ruleId === ruleId); }
|
|
681
|
+
function stateOf(ledger, ruleId) { return currentState(ledger, ruleId); }
|
|
682
|
+
|
|
683
|
+
// EXTERNAL MODULE: external "node:path"
|
|
684
|
+
var external_node_path_ = __webpack_require__(76760);
|
|
685
|
+
;// CONCATENATED MODULE: ./src/posture/rule-compiler/store.js
|
|
686
|
+
// Persistence for the rule compiler: one directory per rule under `.agentic-security/rule-compiler/<id>/`
|
|
687
|
+
// (`ir.json`, `ledger.json`, `evaluation.json`), the promoted custom-rule document at
|
|
688
|
+
// `.agentic-security/rules/<id>.yml` (so the EXISTING `loadCustomRules`/`rule test` machinery picks it up with no
|
|
689
|
+
// change), and a regression fixture pair at `.agentic-security/rule-compiler/fixtures/<id>/{vulnerable,clean}/`
|
|
690
|
+
// using the SAME filename convention `runRuleTests` already reads (`vulnerable`/`clean` in the path).
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
const DIR = 'rule-compiler';
|
|
698
|
+
const store_EXT = { javascript: 'js', typescript: 'ts', python: 'py', go: 'go', ruby: 'rb', java: 'java', rust: 'rs', csharp: 'cs', php: 'php', any: 'txt' };
|
|
699
|
+
|
|
700
|
+
function ruleDir(scanRoot, id) { return (0,state_dir.statePath)(scanRoot, DIR, id); }
|
|
701
|
+
|
|
702
|
+
function loadLedger(scanRoot) {
|
|
703
|
+
const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
|
|
704
|
+
if (!external_node_fs_.existsSync(f)) return newLedger();
|
|
705
|
+
try {
|
|
706
|
+
const ledger = JSON.parse(external_node_fs_.readFileSync(f, 'utf8'));
|
|
707
|
+
const v = verifyLedger(ledger);
|
|
708
|
+
return v.ok ? ledger : { ...newLedger(), tampered: true, tamperReason: v.reason };
|
|
709
|
+
} catch { return newLedger(); }
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function saveLedger(scanRoot, ledger) {
|
|
713
|
+
if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
714
|
+
const f = (0,state_dir.statePath)(scanRoot, DIR, 'ledger.json');
|
|
715
|
+
return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(ledger, null, 2)) };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function saveIR(scanRoot, ir) {
|
|
719
|
+
if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
720
|
+
const f = external_node_path_.join(ruleDir(scanRoot, ir.id), 'ir.json');
|
|
721
|
+
return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(ir, null, 2)), file: f };
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function loadIR(scanRoot, id) {
|
|
725
|
+
const f = external_node_path_.join(ruleDir(scanRoot, id), 'ir.json');
|
|
726
|
+
try { return JSON.parse(external_node_fs_.readFileSync(f, 'utf8')); } catch { return null; }
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function saveEvaluation(scanRoot, id, evaluation) {
|
|
730
|
+
if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
731
|
+
const f = external_node_path_.join(ruleDir(scanRoot, id), 'evaluation.json');
|
|
732
|
+
return { ok: (0,state_dir/* safeWriteState */.Ep)(f, JSON.stringify(evaluation, null, 2)) };
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** Write the regression fixtures a promoted rule needs: the SAME vulnerable/clean convention `runRuleTests`
|
|
736
|
+
* already reads, scored against the exact corpus the rule was promoted on. */
|
|
737
|
+
function writeFixtures(scanRoot, ir, corpus) {
|
|
738
|
+
const ext = store_EXT[ir.languages[0]] || 'txt';
|
|
739
|
+
const base = external_node_path_.join(ruleDir(scanRoot, ir.id), 'fixtures');
|
|
740
|
+
if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
741
|
+
const written = [];
|
|
742
|
+
for (const p of corpus.positives) {
|
|
743
|
+
const f = external_node_path_.join(base, 'vulnerable', `${p.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
|
|
744
|
+
if ((0,state_dir/* safeWriteState */.Ep)(f, p.code)) written.push(f);
|
|
745
|
+
}
|
|
746
|
+
for (const n of corpus.negatives) {
|
|
747
|
+
const f = external_node_path_.join(base, 'clean', `${n.label.replace(/[^a-z0-9_-]/gi, '_')}.${ext}`);
|
|
748
|
+
if ((0,state_dir/* safeWriteState */.Ep)(f, n.code)) written.push(f);
|
|
749
|
+
}
|
|
750
|
+
return { ok: true, written, glob: external_node_path_.join(base, '**', '*') };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** Promote: write the compiled custom-rule document to the live rules directory. Does not touch the ledger —
|
|
754
|
+
* the caller records the PROMOTED transition itself, so a failed write here can never produce an inconsistent
|
|
755
|
+
* "promoted but not live" or "live but not recorded" state silently. */
|
|
756
|
+
function publishCustomRule(scanRoot, ir) {
|
|
757
|
+
const { ok, doc, errs } = compileToCustomRule(ir);
|
|
758
|
+
if (!ok) return { ok: false, reason: `invalid rule IR: ${errs.join('; ')}` };
|
|
759
|
+
if (!(0,state_dir/* ensureStateDir */.xH)(scanRoot)) return { ok: false, reason: 'no safe state directory for this project' };
|
|
760
|
+
const f = (0,state_dir.statePath)(scanRoot, 'rules', `${ir.id}.yml`);
|
|
761
|
+
const yamlText = [
|
|
762
|
+
`# Compiled by the rule compiler from finding ${ir.provenance.originatingFindingId} (${ir.provenance.evidenceState}).`,
|
|
763
|
+
`- id: ${doc.id}`,
|
|
764
|
+
` title: ${JSON.stringify(doc.title)}`,
|
|
765
|
+
` severity: ${doc.severity}`,
|
|
766
|
+
` cwe: ${doc.cwe}`,
|
|
767
|
+
` languages: [${doc.languages.join(', ')}]`,
|
|
768
|
+
` match:`,
|
|
769
|
+
...(doc.match.pattern ? [` pattern: ${JSON.stringify(doc.match.pattern)}`] : []),
|
|
770
|
+
...(doc.match.allOf ? [` allOf:`, ...doc.match.allOf.map((p) => ` - ${JSON.stringify(p)}`), ` window: ${doc.match.window}`] : []),
|
|
771
|
+
...(doc.match.notMatch ? [` notMatch: ${JSON.stringify(doc.match.notMatch)}`] : []),
|
|
772
|
+
` message: ${JSON.stringify(doc.message)}`,
|
|
773
|
+
'',
|
|
774
|
+
].join('\n');
|
|
775
|
+
return { ok: (0,state_dir/* safeWriteState */.Ep)(f, yamlText), file: f };
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function unpublishCustomRule(scanRoot, id) {
|
|
779
|
+
const f = (0,state_dir.statePath)(scanRoot, 'rules', `${id}.yml`);
|
|
780
|
+
try { if (external_node_fs_.existsSync(f)) external_node_fs_.unlinkSync(f); return { ok: true }; } catch (e) { return { ok: false, reason: e.message }; }
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
;// CONCATENATED MODULE: ./src/posture/rule-compiler/cli.js
|
|
784
|
+
// CLI surface: `agentic-security rules synthesize|evaluate|promote|status|rollback`.
|
|
785
|
+
//
|
|
786
|
+
// Distinct from the pre-existing `labs synthesize-rule` (posture/rule-synthesis.js), which proposes SUPPRESSION
|
|
787
|
+
// rules from repeated false-positive triage verdicts — a different input, a different output and a different
|
|
788
|
+
// command group on purpose, so the two are never confused at the CLI.
|
|
789
|
+
//
|
|
790
|
+
// Non-interactive by construction: no command reads stdin, every corpus evaluation is bounded (no network, no
|
|
791
|
+
// model call — this is the deterministic half; a model may PROPOSE the candidate pattern this CLI is handed, but
|
|
792
|
+
// it never decides promotion).
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
function loadFinding(root, id) {
|
|
803
|
+
const p = (0,state_dir.statePath)(root, 'last-scan.json');
|
|
804
|
+
if (!external_node_fs_.existsSync(p)) return null;
|
|
805
|
+
const last = JSON.parse(external_node_fs_.readFileSync(p, 'utf8'));
|
|
806
|
+
return (last.findings || []).find((f) => f.id === id || f.stableId === id) ?? null;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function readJsonArg(pathOrInline) {
|
|
810
|
+
if (!pathOrInline) return null;
|
|
811
|
+
try { return JSON.parse(external_node_fs_.existsSync(pathOrInline) ? external_node_fs_.readFileSync(pathOrInline, 'utf8') : pathOrInline); } catch { return null; }
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
async function cmdRules(args, root) {
|
|
815
|
+
const sub = args._[1];
|
|
816
|
+
if (sub === 'synthesize') return cmdSynthesize(args, root);
|
|
817
|
+
if (sub === 'evaluate') return cmdEvaluate(args, root);
|
|
818
|
+
if (sub === 'promote') return cmdPromote(args, root);
|
|
819
|
+
if (sub === 'status') return cmdStatus(args, root);
|
|
820
|
+
if (sub === 'rollback') return cmdRollback(args, root);
|
|
821
|
+
console.error('usage: rules synthesize <finding-id> --spec <file.json> | evaluate <rule-id> | promote <rule-id> | status [rule-id] | rollback <rule-id>');
|
|
822
|
+
return 4;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// `--spec` carries exactly what a model or a human proposed: id/title/severity/cwe/family/languages/match/
|
|
826
|
+
// remediation plus the corpus inputs (originalCode/patchedCode/nearbyCleanCode/protectedVariantsCode). This
|
|
827
|
+
// command never invents a pattern; it only drafts the IR, checks eligibility and records DRAFT->CANDIDATE.
|
|
828
|
+
async function cmdSynthesize(args, root) {
|
|
829
|
+
const findingId = args._[2];
|
|
830
|
+
const spec = readJsonArg(args.flags.spec);
|
|
831
|
+
if (!findingId || !spec) { console.error('usage: rules synthesize <finding-id> --spec <file.json>'); return 4; }
|
|
832
|
+
const finding = loadFinding(root, findingId);
|
|
833
|
+
if (!finding) { console.error(`Finding ${findingId} not found in last scan.`); return 4; }
|
|
834
|
+
const elig = checkEligibility(finding, { proofState: args.flags['proof-state'] || null });
|
|
835
|
+
if (!elig.eligible) { console.error(`Not eligible for rule synthesis: ${elig.reasons.join('; ')}`); return 4; }
|
|
836
|
+
|
|
837
|
+
const ir = draftRuleIR({ ...spec, originatingFindingId: finding.stableId ?? finding.id, originatingCommit: spec.originatingCommit ?? null, evidenceState: elig.evidenceState });
|
|
838
|
+
const errs = validateRuleIR(ir);
|
|
839
|
+
if (errs.length) { console.error(`Invalid rule: ${errs.join('; ')}`); return 4; }
|
|
840
|
+
|
|
841
|
+
const ledger = loadLedger(root);
|
|
842
|
+
const draft = recordTransition(ledger, { ruleId: ir.id, from: null, to: 'DRAFT', reason: `drafted from ${findingId}`, actor: args.flags.actor || 'agent' });
|
|
843
|
+
if (!draft.ok) { console.error(draft.reason); return 4; }
|
|
844
|
+
const cand = recordTransition(ledger, { ruleId: ir.id, from: 'DRAFT', to: 'CANDIDATE', reason: 'eligibility passed', evidence: { eligibility: elig }, actor: args.flags.actor || 'agent' });
|
|
845
|
+
saveLedger(root, ledger);
|
|
846
|
+
saveIR(root, { ...ir, state: 'CANDIDATE' });
|
|
847
|
+
console.log(`Rule ${ir.id}: DRAFT -> CANDIDATE (digest ${ruleIRDigest(ir).slice(0, 12)})`);
|
|
848
|
+
if (!cand.ok) console.error(cand.reason);
|
|
849
|
+
return 0;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
async function cmdEvaluate(args, root) {
|
|
853
|
+
const id = args._[2];
|
|
854
|
+
if (!id) { console.error('usage: rules evaluate <rule-id> --corpus <file.json>'); return 4; }
|
|
855
|
+
const ir = loadIR(root, id);
|
|
856
|
+
if (!ir) { console.error(`No rule IR found for ${id}. Run rules synthesize first.`); return 4; }
|
|
857
|
+
const corpusSpec = readJsonArg(args.flags.corpus);
|
|
858
|
+
if (!corpusSpec) { console.error('No corpus supplied. Pass --corpus <file.json> with originalCode (and optionally patchedCode/nearbyCleanCode/protectedVariantsCode).'); return 4; }
|
|
859
|
+
const corpus = buildCorpus(ir, corpusSpec);
|
|
860
|
+
const leakage = checkLeakage(JSON.stringify(corpusSpec), { benchmarkNames: args.flags['benchmark-names'] ? String(args.flags['benchmark-names']).split(',') : [] });
|
|
861
|
+
const gate = gatePromotion({ ir, corpus, leakageCheck: leakage, thresholds: args.flags.thresholds ? readJsonArg(args.flags.thresholds) : PROMOTION_DEFAULTS });
|
|
862
|
+
|
|
863
|
+
const ledger = loadLedger(root);
|
|
864
|
+
const cur = stateOf(ledger, id);
|
|
865
|
+
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' });
|
|
866
|
+
saveLedger(root, ledger);
|
|
867
|
+
saveEvaluation(root, id, gate);
|
|
868
|
+
if (args.flags.json) console.log(JSON.stringify(gate, null, 2));
|
|
869
|
+
else {
|
|
870
|
+
console.log(`Rule ${id}: ${gate.pass ? 'VALIDATED' : 'gate FAILED'}`);
|
|
871
|
+
console.log(` precision ${fmtPct(gate.evaluation.score.precision)} recall ${fmtPct(gate.evaluation.score.recall)} protected-failures ${gate.evaluation.score.protectedFailures}`);
|
|
872
|
+
for (const r of gate.reasons) console.log(` - ${r}`);
|
|
873
|
+
}
|
|
874
|
+
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/`); }
|
|
875
|
+
return gate.pass ? 0 : 1;
|
|
876
|
+
}
|
|
877
|
+
const fmtPct = (n) => (n == null ? 'unmeasured' : `${(n * 100).toFixed(1)}%`);
|
|
878
|
+
|
|
879
|
+
async function cmdPromote(args, root) {
|
|
880
|
+
const id = args._[2];
|
|
881
|
+
if (!id) { console.error('usage: rules promote <rule-id>'); return 4; }
|
|
882
|
+
const ledger = loadLedger(root);
|
|
883
|
+
if (ledger.tampered) { console.error(`Refusing: rule lifecycle ledger failed its integrity check (${ledger.tamperReason}).`); return 4; }
|
|
884
|
+
if (stateOf(ledger, id) !== 'VALIDATED') { console.error(`Rule ${id} is not VALIDATED (run rules evaluate first); refusing to promote.`); return 4; }
|
|
885
|
+
const ir = loadIR(root, id);
|
|
886
|
+
if (!ir) { console.error(`No rule IR found for ${id}.`); return 4; }
|
|
887
|
+
const pub = publishCustomRule(root, ir);
|
|
888
|
+
if (!pub.ok) { console.error(`Promotion refused: ${pub.reason}`); return 4; }
|
|
889
|
+
const t = recordTransition(ledger, { ruleId: id, from: 'VALIDATED', to: 'PROMOTED', reason: args.flags.reason || 'promoted', actor: args.flags.actor || 'operator' });
|
|
890
|
+
saveLedger(root, ledger);
|
|
891
|
+
console.log(`Rule ${id}: VALIDATED -> PROMOTED. Published to ${pub.file}.`);
|
|
892
|
+
if (!t.ok) console.error(t.reason);
|
|
893
|
+
return 0;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
async function cmdRollback(args, root) {
|
|
897
|
+
const id = args._[2];
|
|
898
|
+
if (!id) { console.error('usage: rules rollback <rule-id> [--reason text]'); return 4; }
|
|
899
|
+
const ledger = loadLedger(root);
|
|
900
|
+
const cur = stateOf(ledger, id);
|
|
901
|
+
if (cur !== 'PROMOTED') { console.error(`Rule ${id} is not PROMOTED (current: ${cur ?? 'unknown'}); nothing to roll back.`); return 4; }
|
|
902
|
+
const un = unpublishCustomRule(root, id);
|
|
903
|
+
const t = recordTransition(ledger, { ruleId: id, from: 'PROMOTED', to: 'ROLLED_BACK', reason: args.flags.reason || 'operator rollback', actor: args.flags.actor || 'operator' });
|
|
904
|
+
saveLedger(root, ledger);
|
|
905
|
+
console.log(`Rule ${id}: PROMOTED -> ROLLED_BACK.${un.ok ? '' : ` (warning: could not remove published rule file: ${un.reason})`}`);
|
|
906
|
+
return t.ok ? 0 : 1;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function cmdStatus(args, root) {
|
|
910
|
+
const ledger = loadLedger(root);
|
|
911
|
+
const id = args._[2];
|
|
912
|
+
if (id) {
|
|
913
|
+
const h = historyFor(ledger, id);
|
|
914
|
+
if (!h.length) { console.error(`No history for rule ${id}.`); return 4; }
|
|
915
|
+
if (args.flags.json) console.log(JSON.stringify(h, null, 2));
|
|
916
|
+
else { console.log(`Rule ${id}: ${stateOf(ledger, id)}`); for (const e of h) console.log(` ${e.at} ${e.from ?? '(new)'} -> ${e.to} (${e.reason || ''})`); }
|
|
917
|
+
return 0;
|
|
918
|
+
}
|
|
919
|
+
const ids = [...new Set(ledger.entries.map((e) => e.ruleId))];
|
|
920
|
+
if (args.flags.json) { console.log(JSON.stringify(ids.map((rid) => ({ id: rid, state: stateOf(ledger, rid) })), null, 2)); return 0; }
|
|
921
|
+
if (!ids.length) { console.log('No rules in the lifecycle ledger yet.'); return 0; }
|
|
922
|
+
for (const rid of ids) console.log(` ${rid.padEnd(40)} ${stateOf(ledger, rid)}`);
|
|
923
|
+
return 0;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
/***/ })
|
|
928
|
+
|
|
929
|
+
};
|