@multileaf/ai-workflow 0.14.0 → 0.16.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 +17 -0
- package/README.md +11 -0
- package/dist/adapter.js +3 -3
- package/dist/artifact-paths.d.ts +16 -0
- package/dist/artifact-paths.js +51 -0
- package/dist/completion-report.d.ts +17 -0
- package/dist/completion-report.js +42 -0
- package/dist/dashboard.js +7 -1
- package/dist/decision.d.ts +15 -0
- package/dist/decision.js +63 -0
- package/dist/eval/brief.d.ts +7 -0
- package/dist/eval/brief.js +28 -0
- package/dist/eval/generated.d.ts +17 -0
- package/dist/eval/generated.js +41 -0
- package/dist/eval/git.d.ts +13 -0
- package/dist/eval/git.js +70 -0
- package/dist/eval/monitor.d.ts +32 -0
- package/dist/eval/monitor.js +66 -0
- package/dist/eval/policy.d.ts +8 -0
- package/dist/eval/policy.js +9 -0
- package/dist/eval/proposals.d.ts +48 -0
- package/dist/eval/proposals.js +202 -0
- package/dist/eval/scenarios.d.ts +100 -0
- package/dist/eval/scenarios.js +374 -0
- package/dist/eval/signals.d.ts +21 -0
- package/dist/eval/signals.js +155 -0
- package/dist/eval/types.d.ts +38 -0
- package/dist/eval/types.js +1 -0
- package/dist/eval/validate.d.ts +28 -0
- package/dist/eval/validate.js +66 -0
- package/dist/generator.d.ts +8 -1
- package/dist/generator.js +24 -1
- package/dist/risk-assess.d.ts +1 -1
- package/dist/risk-assess.js +26 -2
- package/dist/semantic.d.ts +19 -0
- package/dist/semantic.js +57 -0
- package/dist/services.d.ts +3 -0
- package/dist/telemetry.d.ts +6 -0
- package/dist/telemetry.js +14 -7
- package/dist/workflow.js +532 -68
- package/docs/backlog.md +13 -3
- package/docs/decision-model-evaluation.md +7 -2
- package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
- package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
- package/docs/opportunities/OPP-016-behavioral-eval-scenarios.md +1 -1
- package/docs/quality.md +15 -0
- package/docs/semantic-mapping.md +9 -0
- package/package.json +1 -1
- package/resources/evals/README.md +59 -0
- package/resources/evals/scenarios/approval-boundary-full.yml +42 -0
- package/resources/evals/scenarios/bugfix-process-entry.yml +41 -0
- package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
- package/resources/evals/scenarios/light-lane-skips-durable-artifacts.yml +40 -0
- package/resources/evals/scenarios/rejection-regate.yml +74 -0
- package/resources/evals/scenarios/risk-escalation-high-risk-area.yml +45 -0
- package/resources/package.yaml +1 -0
- package/resources/skills/resource-evaluator.md +24 -0
- package/resources/skills/review-judge-a.md +4 -0
- package/resources/skills/review-judge-b.md +4 -0
- package/resources/skills/review-refuter.md +4 -0
- package/resources/skills/ticket.md +1 -1
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OPP-016: Behavioral evaluation phase 2 — the scenario registry replayed
|
|
3
|
+
* against real harness CLIs.
|
|
4
|
+
*
|
|
5
|
+
* OPP-011 proves generated artifacts *say* the right things (text invariants);
|
|
6
|
+
* this module proves agents *do* them: each scenario declares a fixture
|
|
7
|
+
* repository, a bounded harness command, and deterministic state-outcome
|
|
8
|
+
* expectations (exit code + `.aiw/` state files). No prose assertions, no
|
|
9
|
+
* LLM-as-judge — the layer stays deterministic where it judges.
|
|
10
|
+
*
|
|
11
|
+
* Trust boundaries honored (NFR-3): a missing harness CLI yields an explicit
|
|
12
|
+
* `skipped-harness-unavailable` marker (never a silent pass); token usage is
|
|
13
|
+
* recorded only when the harness reports it (never fabricated); scenarios are
|
|
14
|
+
* advisory-first — nothing in this module gates a release until the declared
|
|
15
|
+
* two-cycle ratchet elapses.
|
|
16
|
+
*/
|
|
17
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { tmpdir } from "node:os";
|
|
19
|
+
import { join, resolve } from "node:path";
|
|
20
|
+
import { spawn } from "node:child_process";
|
|
21
|
+
import { parse as parseYaml } from "yaml";
|
|
22
|
+
const SCENARIO_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
23
|
+
export function parseScenarioRegistry(entries) {
|
|
24
|
+
const scenarios = [];
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
const value = parseYaml(entry.content);
|
|
27
|
+
if (!value || typeof value !== "object")
|
|
28
|
+
throw new Error(`Scenario ${entry.path} is not a YAML mapping.`);
|
|
29
|
+
const scenario = value;
|
|
30
|
+
if (scenario.schema !== 1)
|
|
31
|
+
throw new Error(`Scenario ${entry.path} must declare schema: 1.`);
|
|
32
|
+
const id = String(scenario.id ?? "");
|
|
33
|
+
if (!SCENARIO_ID_PATTERN.test(id))
|
|
34
|
+
throw new Error(`Scenario ${entry.path} has an invalid id: ${JSON.stringify(id)}`);
|
|
35
|
+
if (scenarios.some((existing) => existing.id === id))
|
|
36
|
+
throw new Error(`Duplicate scenario id: ${id}`);
|
|
37
|
+
const command = String(scenario.command ?? "");
|
|
38
|
+
if (!command.includes("{prompt}"))
|
|
39
|
+
throw new Error(`Scenario ${id} command must contain the {prompt} placeholder.`);
|
|
40
|
+
const prompt = String(scenario.prompt ?? "");
|
|
41
|
+
if (!prompt.trim())
|
|
42
|
+
throw new Error(`Scenario ${id} has an empty prompt.`);
|
|
43
|
+
const fixture = (scenario.fixture ?? {});
|
|
44
|
+
const files = Array.isArray(fixture.files) ? fixture.files : [];
|
|
45
|
+
for (const file of files) {
|
|
46
|
+
const path = String(file.path ?? "");
|
|
47
|
+
if (path.includes("..") || resolve("/", path) === "/")
|
|
48
|
+
throw new Error(`Scenario ${id} fixture path escapes the fixture: ${path}`);
|
|
49
|
+
}
|
|
50
|
+
scenarios.push({
|
|
51
|
+
schema: 1,
|
|
52
|
+
id,
|
|
53
|
+
family: String(scenario.family ?? "general"),
|
|
54
|
+
description: String(scenario.description ?? ""),
|
|
55
|
+
harness: String(scenario.harness ?? ""),
|
|
56
|
+
command,
|
|
57
|
+
prompt,
|
|
58
|
+
fixture: {
|
|
59
|
+
files: files.map((file) => ({
|
|
60
|
+
path: String(file.path),
|
|
61
|
+
content: String(file.content ?? ""),
|
|
62
|
+
})),
|
|
63
|
+
setup: Array.isArray(fixture.setup) ? fixture.setup.map(String) : [],
|
|
64
|
+
git: fixture.git !== false,
|
|
65
|
+
},
|
|
66
|
+
expected: (scenario.expected ?? {}),
|
|
67
|
+
budget: (scenario.budget ?? {}),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return scenarios;
|
|
71
|
+
}
|
|
72
|
+
/** Replaces {prompt} with a safely single-quoted shell literal. */
|
|
73
|
+
export function expandCommand(template, prompt) {
|
|
74
|
+
const quoted = `'${prompt.replaceAll("'", "'\\''")}'`;
|
|
75
|
+
return template.replaceAll("{prompt}", quoted);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Best-effort usage sidecar: parses harness stdout for known usage shapes
|
|
79
|
+
* (codex `token_usage`, claude `usage`). Absence returns undefined — usage is
|
|
80
|
+
* never fabricated.
|
|
81
|
+
*/
|
|
82
|
+
export function extractUsage(output) {
|
|
83
|
+
let tokensIn;
|
|
84
|
+
let tokensOut;
|
|
85
|
+
for (const line of output.split("\n")) {
|
|
86
|
+
const trimmed = line.trim();
|
|
87
|
+
if (!trimmed.startsWith("{"))
|
|
88
|
+
continue;
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = JSON.parse(trimmed);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (!parsed || typeof parsed !== "object")
|
|
97
|
+
continue;
|
|
98
|
+
const usage = parsed.token_usage ??
|
|
99
|
+
parsed.usage;
|
|
100
|
+
if (!usage || typeof usage !== "object")
|
|
101
|
+
continue;
|
|
102
|
+
const input = Number(usage.input_tokens);
|
|
103
|
+
const output_ = Number(usage.output_tokens);
|
|
104
|
+
if (Number.isFinite(input) && input >= 0)
|
|
105
|
+
tokensIn = (tokensIn ?? 0) + input;
|
|
106
|
+
if (Number.isFinite(output_) && output_ >= 0)
|
|
107
|
+
tokensOut = (tokensOut ?? 0) + output_;
|
|
108
|
+
}
|
|
109
|
+
if (tokensIn === undefined && tokensOut === undefined)
|
|
110
|
+
return undefined;
|
|
111
|
+
return { tokensIn: tokensIn ?? 0, tokensOut: tokensOut ?? 0 };
|
|
112
|
+
}
|
|
113
|
+
/** PATH probe for a harness CLI binary; injectable for tests. */
|
|
114
|
+
export function isHarnessAvailable(harness, pathEnv) {
|
|
115
|
+
if (!harness)
|
|
116
|
+
return false;
|
|
117
|
+
const path = pathEnv ?? process.env.PATH ?? "";
|
|
118
|
+
for (const dir of path.split(":")) {
|
|
119
|
+
if (!dir)
|
|
120
|
+
continue;
|
|
121
|
+
if (existsSync(join(dir, harness)))
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
export function outcomeFingerprint(report) {
|
|
127
|
+
return report.results
|
|
128
|
+
.map((result) => `${result.scenario}:${result.status}`)
|
|
129
|
+
.sort((a, b) => a.localeCompare(b));
|
|
130
|
+
}
|
|
131
|
+
function yamlScalar(value) {
|
|
132
|
+
return /^[A-Za-z0-9][A-Za-z0-9._ -]*$/.test(value) ? value : JSON.stringify(value);
|
|
133
|
+
}
|
|
134
|
+
export function serializeScenarioResults(report) {
|
|
135
|
+
const counts = new Map();
|
|
136
|
+
for (const result of report.results)
|
|
137
|
+
counts.set(result.status, (counts.get(result.status) ?? 0) + 1);
|
|
138
|
+
const lines = [
|
|
139
|
+
"schema: aiw.scenario-results/v1",
|
|
140
|
+
`harness: ${JSON.stringify(report.harness)}`,
|
|
141
|
+
`startedAt: ${JSON.stringify(report.startedAt)}`,
|
|
142
|
+
`finishedAt: ${JSON.stringify(report.finishedAt)}`,
|
|
143
|
+
];
|
|
144
|
+
if (report.poolBudget)
|
|
145
|
+
lines.push(`poolBudget:\\n tokenCeiling: ${report.poolBudget.tokenCeiling}\\n tokensSpent: ${report.poolBudget.tokensSpent}`);
|
|
146
|
+
lines.push(`missingHarnesses: ${report.missingHarnesses.length ? JSON.stringify(report.missingHarnesses) : "[]"}`);
|
|
147
|
+
lines.push("results:");
|
|
148
|
+
for (const result of [...report.results].sort((a, b) => a.scenario.localeCompare(b.scenario))) {
|
|
149
|
+
lines.push(` - scenario: ${yamlScalar(result.scenario)}`);
|
|
150
|
+
lines.push(` family: ${yamlScalar(result.family)}`);
|
|
151
|
+
lines.push(` status: ${result.status}`);
|
|
152
|
+
lines.push(` attempts: ${result.attempts}`);
|
|
153
|
+
lines.push(` durationMs: ${result.durationMs}`);
|
|
154
|
+
if (result.usage)
|
|
155
|
+
lines.push(` usage:\\n tokensIn: ${result.usage.tokensIn}\\n tokensOut: ${result.usage.tokensOut}`);
|
|
156
|
+
lines.push(` detail: ${JSON.stringify(result.detail)}`);
|
|
157
|
+
}
|
|
158
|
+
lines.push("summary:");
|
|
159
|
+
for (const [status, count] of [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0])))
|
|
160
|
+
lines.push(` ${status}: ${count}`);
|
|
161
|
+
return `${lines.join("\\n")}\\n`;
|
|
162
|
+
}
|
|
163
|
+
/** Transport-level failure: timeout, signal kill, or harness-specific crash codes. */
|
|
164
|
+
function isTransportFailure(result) {
|
|
165
|
+
return Boolean(result.timedOut) || Boolean(result.signal) || result.exitCode >= 250;
|
|
166
|
+
}
|
|
167
|
+
function evaluateExpectations(fixtureDir, expected, result) {
|
|
168
|
+
const failures = [];
|
|
169
|
+
const wantedExit = expected.exitCode ?? 0;
|
|
170
|
+
if (result.exitCode !== wantedExit)
|
|
171
|
+
failures.push(`exit code ${result.exitCode} (expected ${wantedExit})`);
|
|
172
|
+
for (const [path, assertion] of Object.entries(expected.files ?? {})) {
|
|
173
|
+
const absolute = join(fixtureDir, path);
|
|
174
|
+
if (assertion.absent) {
|
|
175
|
+
if (existsSync(absolute))
|
|
176
|
+
failures.push(`${path} exists (expected absent)`);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (!existsSync(absolute)) {
|
|
180
|
+
failures.push(`${path} missing`);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const content = readFileSync(absolute, "utf8");
|
|
184
|
+
if (assertion.contains && !content.includes(assertion.contains))
|
|
185
|
+
failures.push(`${path} does not contain ${JSON.stringify(assertion.contains)}`);
|
|
186
|
+
if (assertion.notContains && content.includes(assertion.notContains))
|
|
187
|
+
failures.push(`${path} must not contain ${JSON.stringify(assertion.notContains)}`);
|
|
188
|
+
if (assertion.matches && !new RegExp(assertion.matches, "m").test(content))
|
|
189
|
+
failures.push(`${path} does not match /${assertion.matches}/`);
|
|
190
|
+
}
|
|
191
|
+
for (const [path, assertion] of Object.entries(expected.dirs ?? {})) {
|
|
192
|
+
const absolute = join(fixtureDir, path);
|
|
193
|
+
if (assertion.absent && existsSync(absolute))
|
|
194
|
+
failures.push(`${path}/ exists (expected absent)`);
|
|
195
|
+
}
|
|
196
|
+
return failures;
|
|
197
|
+
}
|
|
198
|
+
function buildFixtureDefault(scenario, runShell) {
|
|
199
|
+
const root = mkdtempSync(join(tmpdir(), "aiw-scenario-"));
|
|
200
|
+
const dir = join(root, scenario.id);
|
|
201
|
+
mkdirSync(dir, { recursive: true });
|
|
202
|
+
for (const file of scenario.fixture.files) {
|
|
203
|
+
const absolute = join(dir, file.path);
|
|
204
|
+
mkdirSync(join(absolute, ".."), { recursive: true });
|
|
205
|
+
writeFileSync(absolute, file.content);
|
|
206
|
+
}
|
|
207
|
+
const prepare = async () => {
|
|
208
|
+
if (scenario.fixture.git !== false) {
|
|
209
|
+
const init = await runShell(dir, "git init -q", 15000);
|
|
210
|
+
if (init.exitCode !== 0)
|
|
211
|
+
throw new Error(`git init failed: ${init.stderr.slice(0, 200)}`);
|
|
212
|
+
const config = await runShell(dir, 'git config user.email "scenario@aiw.local" && git config user.name scenario', 15000);
|
|
213
|
+
if (config.exitCode !== 0)
|
|
214
|
+
throw new Error(`git config failed: ${config.stderr.slice(0, 200)}`);
|
|
215
|
+
const commit = await runShell(dir, "git add -A && git commit -qm fixture", 15000);
|
|
216
|
+
if (commit.exitCode !== 0)
|
|
217
|
+
throw new Error(`git commit failed: ${commit.stderr.slice(0, 200)}`);
|
|
218
|
+
}
|
|
219
|
+
for (const command of scenario.fixture.setup ?? []) {
|
|
220
|
+
const result = await runShell(dir, command, 120000);
|
|
221
|
+
if (result.exitCode !== 0)
|
|
222
|
+
throw new Error(`setup command failed (exit ${result.exitCode}): ${command} — ${result.stderr.slice(0, 200)}`);
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
return prepare().then(() => ({ dir, cleanup: () => rmSync(root, { recursive: true, force: true }) }), (error) => {
|
|
226
|
+
rmSync(root, { recursive: true, force: true });
|
|
227
|
+
throw error;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
export async function runScenarios(options) {
|
|
231
|
+
const available = options.isAvailable ?? ((harness) => isHarnessAvailable(harness));
|
|
232
|
+
const buildFixture = options.buildFixture ??
|
|
233
|
+
((scenario) => buildFixtureDefault(scenario, options.runShell));
|
|
234
|
+
const now = options.now ?? (() => new Date());
|
|
235
|
+
const startedAt = now().toISOString();
|
|
236
|
+
const results = [];
|
|
237
|
+
const missing = new Set();
|
|
238
|
+
let tokensSpent = 0;
|
|
239
|
+
for (const scenario of options.scenarios) {
|
|
240
|
+
if (options.poolTokenCeiling !== undefined && tokensSpent >= options.poolTokenCeiling) {
|
|
241
|
+
results.push({
|
|
242
|
+
scenario: scenario.id,
|
|
243
|
+
family: scenario.family,
|
|
244
|
+
status: "aborted-pool",
|
|
245
|
+
attempts: 0,
|
|
246
|
+
durationMs: 0,
|
|
247
|
+
detail: `pooled token budget exhausted (${tokensSpent}/${options.poolTokenCeiling})`,
|
|
248
|
+
});
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (!available(scenario.harness)) {
|
|
252
|
+
missing.add(scenario.harness);
|
|
253
|
+
results.push({
|
|
254
|
+
scenario: scenario.id,
|
|
255
|
+
family: scenario.family,
|
|
256
|
+
status: "skipped-harness-unavailable",
|
|
257
|
+
attempts: 0,
|
|
258
|
+
durationMs: 0,
|
|
259
|
+
detail: `harness CLI "${scenario.harness}" not found on PATH`,
|
|
260
|
+
});
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const started = now();
|
|
264
|
+
let fixture;
|
|
265
|
+
try {
|
|
266
|
+
fixture = await buildFixture(scenario);
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
results.push({
|
|
270
|
+
scenario: scenario.id,
|
|
271
|
+
family: scenario.family,
|
|
272
|
+
status: "failed",
|
|
273
|
+
attempts: 0,
|
|
274
|
+
durationMs: 0,
|
|
275
|
+
detail: `fixture setup failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
276
|
+
});
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
let status = "failed";
|
|
280
|
+
let usage;
|
|
281
|
+
let detail = "";
|
|
282
|
+
let attempts = 0;
|
|
283
|
+
const wallClockMs = (scenario.budget?.wallClockS ?? 300) * 1000;
|
|
284
|
+
try {
|
|
285
|
+
for (let attempt = 1; attempt <= 2; attempt += 1) {
|
|
286
|
+
attempts = attempt;
|
|
287
|
+
const command = expandCommand(scenario.command, scenario.prompt);
|
|
288
|
+
const result = await options.runShell(fixture.dir, command, wallClockMs);
|
|
289
|
+
usage = extractUsage(result.stdout) ?? usage;
|
|
290
|
+
const expectationFailures = evaluateExpectations(fixture.dir, scenario.expected, result);
|
|
291
|
+
const transport = isTransportFailure(result);
|
|
292
|
+
if (expectationFailures.length === 0 && !transport) {
|
|
293
|
+
status = attempt === 1 ? "passed" : "flaky-suspect";
|
|
294
|
+
detail =
|
|
295
|
+
attempt === 1
|
|
296
|
+
? "outcome matched expectations"
|
|
297
|
+
: "passed on retry after transport failure";
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
if (result.timedOut) {
|
|
301
|
+
status = "aborted-timeout";
|
|
302
|
+
detail = `wall clock exceeded ${scenario.budget?.wallClockS ?? 300}s`;
|
|
303
|
+
}
|
|
304
|
+
else if (transport) {
|
|
305
|
+
status = "failed";
|
|
306
|
+
detail = `harness transport failure (exit ${result.exitCode}${result.signal ? `, signal ${result.signal}` : ""})`;
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
status = "failed";
|
|
310
|
+
detail = expectationFailures.join("; ");
|
|
311
|
+
}
|
|
312
|
+
if (attempt === 2)
|
|
313
|
+
break;
|
|
314
|
+
if (!transport && status === "failed" && !result.timedOut)
|
|
315
|
+
break; // expectation failure: no retry
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
fixture?.cleanup();
|
|
320
|
+
}
|
|
321
|
+
const durationMs = Math.max(0, now().getTime() - started.getTime());
|
|
322
|
+
if (usage)
|
|
323
|
+
tokensSpent += usage.tokensIn + usage.tokensOut;
|
|
324
|
+
if (usage &&
|
|
325
|
+
scenario.budget?.tokenCeiling !== undefined &&
|
|
326
|
+
usage.tokensIn + usage.tokensOut > scenario.budget.tokenCeiling) {
|
|
327
|
+
status = "aborted-budget";
|
|
328
|
+
detail = `token usage ${usage.tokensIn + usage.tokensOut} exceeded per-scenario ceiling ${scenario.budget.tokenCeiling}`;
|
|
329
|
+
}
|
|
330
|
+
results.push({
|
|
331
|
+
scenario: scenario.id,
|
|
332
|
+
family: scenario.family,
|
|
333
|
+
status,
|
|
334
|
+
attempts,
|
|
335
|
+
durationMs,
|
|
336
|
+
usage,
|
|
337
|
+
detail,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
const finishedAt = now().toISOString();
|
|
341
|
+
return {
|
|
342
|
+
schema: "aiw.scenario-results/v1",
|
|
343
|
+
harness: [...new Set(options.scenarios.map((scenario) => scenario.harness))].join(","),
|
|
344
|
+
startedAt,
|
|
345
|
+
finishedAt,
|
|
346
|
+
poolBudget: options.poolTokenCeiling !== undefined
|
|
347
|
+
? { tokenCeiling: options.poolTokenCeiling, tokensSpent }
|
|
348
|
+
: undefined,
|
|
349
|
+
missingHarnesses: [...missing].sort(),
|
|
350
|
+
results,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
export function defaultShellRunner(cwd, command, timeoutMs) {
|
|
354
|
+
return new Promise((resolvePromise) => {
|
|
355
|
+
const child = spawn("sh", ["-c", command], { cwd, timeout: timeoutMs, env: process.env });
|
|
356
|
+
let stdout = "";
|
|
357
|
+
let stderr = "";
|
|
358
|
+
child.stdout.on("data", (chunk) => {
|
|
359
|
+
stdout += String(chunk);
|
|
360
|
+
});
|
|
361
|
+
child.stderr.on("data", (chunk) => {
|
|
362
|
+
stderr += String(chunk);
|
|
363
|
+
});
|
|
364
|
+
const finish = (result) => resolvePromise(result);
|
|
365
|
+
child.on("error", (error) => finish({ exitCode: 255, stdout, stderr: `${stderr}${error}` }));
|
|
366
|
+
child.on("close", (code, signal) => finish({
|
|
367
|
+
exitCode: code ?? (signal ? 255 : 1),
|
|
368
|
+
stdout,
|
|
369
|
+
stderr,
|
|
370
|
+
timedOut: Boolean(signal && signal === "SIGTERM"),
|
|
371
|
+
signal: signal ?? undefined,
|
|
372
|
+
}));
|
|
373
|
+
});
|
|
374
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export declare const EVIDENCE_BUNDLE_SCHEMA = 1;
|
|
2
|
+
export type GitSummary = {
|
|
3
|
+
available: boolean;
|
|
4
|
+
topPaths: string[];
|
|
5
|
+
commitTypeRatio: Record<string, number>;
|
|
6
|
+
hotspots: string[];
|
|
7
|
+
};
|
|
8
|
+
export type SignalFact = {
|
|
9
|
+
id: string;
|
|
10
|
+
key: string;
|
|
11
|
+
value: string;
|
|
12
|
+
evidence: string[];
|
|
13
|
+
};
|
|
14
|
+
export type EvidenceBundle = {
|
|
15
|
+
schema: 1;
|
|
16
|
+
facts: SignalFact[];
|
|
17
|
+
limitations: string[];
|
|
18
|
+
};
|
|
19
|
+
export declare function collectSignals(files: string[], git?: GitSummary, readFile?: (path: string) => string): EvidenceBundle;
|
|
20
|
+
export declare function serializeEvidenceBundle(bundle: EvidenceBundle): string;
|
|
21
|
+
export declare function parseEvidenceBundle(content: string): EvidenceBundle;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { parseDocument } from "yaml";
|
|
2
|
+
export const EVIDENCE_BUNDLE_SCHEMA = 1;
|
|
3
|
+
/**
|
|
4
|
+
* Deterministic stack detection over a sorted file listing. Evidence always
|
|
5
|
+
* names real files so downstream proposals cannot cite imaginary tooling.
|
|
6
|
+
* `evidenceFiles` are filtered by presence, so a rule matched by any of its
|
|
7
|
+
* files (for example gradlew without build.gradle.kts) still cites what exists.
|
|
8
|
+
*/
|
|
9
|
+
const BUILD_RULES = [
|
|
10
|
+
{
|
|
11
|
+
match: (files) => files.some((file) => /^build\.gradle(\.kts)?$/.test(file) || file === "gradlew"),
|
|
12
|
+
rule: {
|
|
13
|
+
keys: [
|
|
14
|
+
["build.system", "gradle"],
|
|
15
|
+
["test.command", "./gradlew test"],
|
|
16
|
+
],
|
|
17
|
+
evidenceFiles: ["build.gradle.kts", "build.gradle", "gradlew"],
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
match: (files) => files.includes("pom.xml"),
|
|
22
|
+
rule: {
|
|
23
|
+
keys: [
|
|
24
|
+
["build.system", "maven"],
|
|
25
|
+
["test.command", "mvn test"],
|
|
26
|
+
],
|
|
27
|
+
evidenceFiles: ["pom.xml"],
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
match: (files) => files.includes("pyproject.toml") || files.includes("setup.py") || files.includes("setup.cfg"),
|
|
32
|
+
rule: {
|
|
33
|
+
keys: [
|
|
34
|
+
["build.system", "python-pyproject"],
|
|
35
|
+
["test.command", "pytest"],
|
|
36
|
+
],
|
|
37
|
+
evidenceFiles: ["pyproject.toml", "setup.py", "setup.cfg"],
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
match: (files) => files.includes("CMakeLists.txt"),
|
|
42
|
+
rule: {
|
|
43
|
+
keys: [
|
|
44
|
+
["build.system", "cmake"],
|
|
45
|
+
["language", "cpp"],
|
|
46
|
+
["test.command", "ctest --output-on-failure"],
|
|
47
|
+
],
|
|
48
|
+
evidenceFiles: ["CMakeLists.txt"],
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
match: (files) => files.includes("go.mod"),
|
|
53
|
+
rule: {
|
|
54
|
+
keys: [
|
|
55
|
+
["build.system", "go-modules"],
|
|
56
|
+
["test.command", "go test ./..."],
|
|
57
|
+
],
|
|
58
|
+
evidenceFiles: ["go.mod"],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
match: (files) => files.includes("package.json"),
|
|
63
|
+
rule: {
|
|
64
|
+
keys: [
|
|
65
|
+
["build.system", "node-npm"],
|
|
66
|
+
["test.command", "npm test"],
|
|
67
|
+
],
|
|
68
|
+
evidenceFiles: ["package.json"],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
];
|
|
72
|
+
const PYTHON_FRAMEWORKS = ["django", "flask", "fastapi"];
|
|
73
|
+
/**
|
|
74
|
+
* Framework facts come from declared dependencies (file content), never from
|
|
75
|
+
* file presence alone — a plain pyproject or Gradle project gets no framework
|
|
76
|
+
* fact instead of a guess.
|
|
77
|
+
*/
|
|
78
|
+
function frameworkFor(files, readFile) {
|
|
79
|
+
if (!readFile)
|
|
80
|
+
return undefined;
|
|
81
|
+
const pythonManifest = ["pyproject.toml", "requirements.txt", "setup.py"].find((file) => files.includes(file));
|
|
82
|
+
if (pythonManifest) {
|
|
83
|
+
const content = readFile(pythonManifest).toLowerCase();
|
|
84
|
+
const match = PYTHON_FRAMEWORKS.find((framework) => content.includes(framework));
|
|
85
|
+
if (match)
|
|
86
|
+
return { value: match, evidence: pythonManifest };
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
const jvmManifest = ["build.gradle.kts", "build.gradle", "pom.xml"].find((file) => files.includes(file));
|
|
90
|
+
if (jvmManifest && readFile(jvmManifest).toLowerCase().includes("spring"))
|
|
91
|
+
return { value: "spring", evidence: jvmManifest };
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
export function collectSignals(files, git, readFile) {
|
|
95
|
+
const sorted = [...files].sort();
|
|
96
|
+
const facts = [];
|
|
97
|
+
let index = 0;
|
|
98
|
+
const push = (key, value, evidence) => {
|
|
99
|
+
index += 1;
|
|
100
|
+
facts.push({ id: `fact-${String(index).padStart(3, "0")}`, key, value, evidence });
|
|
101
|
+
};
|
|
102
|
+
for (const { match, rule } of BUILD_RULES) {
|
|
103
|
+
if (!match(sorted))
|
|
104
|
+
continue;
|
|
105
|
+
const evidence = rule.evidenceFiles.filter((file) => sorted.includes(file));
|
|
106
|
+
for (const [key, value] of rule.keys)
|
|
107
|
+
push(key, value, evidence);
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
const framework = frameworkFor(sorted, readFile);
|
|
111
|
+
if (framework)
|
|
112
|
+
push("framework", framework.value, [framework.evidence]);
|
|
113
|
+
if (sorted.some((file) => file.startsWith(".github/workflows/") && file.endsWith(".yml")))
|
|
114
|
+
push("ci.provider", "github-actions", [".github/workflows"]);
|
|
115
|
+
const limitations = [];
|
|
116
|
+
if (git?.available) {
|
|
117
|
+
for (const path of git.topPaths.slice(0, 5))
|
|
118
|
+
push("git.top-path", path, ["git log"]);
|
|
119
|
+
for (const [type, ratio] of Object.entries(git.commitTypeRatio).sort(([a], [b]) => a.localeCompare(b)))
|
|
120
|
+
push(`git.commit-ratio.${type}`, String(ratio), ["git log"]);
|
|
121
|
+
for (const hotspot of git.hotspots.slice(0, 5))
|
|
122
|
+
push("git.hotspot", hotspot, ["git log"]);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
limitations.push("git-history-unavailable");
|
|
126
|
+
}
|
|
127
|
+
return { schema: EVIDENCE_BUNDLE_SCHEMA, facts, limitations };
|
|
128
|
+
}
|
|
129
|
+
function scalar(value) {
|
|
130
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n")}"`;
|
|
131
|
+
}
|
|
132
|
+
export function serializeEvidenceBundle(bundle) {
|
|
133
|
+
const lines = [`schema: ${bundle.schema}`];
|
|
134
|
+
if (bundle.limitations.length)
|
|
135
|
+
lines.push(`limitations: [${bundle.limitations.map(scalar).join(", ")}]`);
|
|
136
|
+
lines.push("facts:");
|
|
137
|
+
for (const fact of bundle.facts)
|
|
138
|
+
lines.push(` - id: ${fact.id}`, ` key: ${fact.key}`, ` value: ${scalar(fact.value)}`, ` evidence: [${fact.evidence.map(scalar).join(", ")}]`);
|
|
139
|
+
return `${lines.join("\n")}\n`;
|
|
140
|
+
}
|
|
141
|
+
export function parseEvidenceBundle(content) {
|
|
142
|
+
const raw = parseDocument(content).toJS();
|
|
143
|
+
if (!raw || Number(raw.schema) !== EVIDENCE_BUNDLE_SCHEMA)
|
|
144
|
+
throw new Error(`Unsupported evidence bundle schema: ${String(raw?.schema)}`);
|
|
145
|
+
const facts = Array.isArray(raw.facts)
|
|
146
|
+
? raw.facts.map((entry) => ({
|
|
147
|
+
id: String(entry.id ?? ""),
|
|
148
|
+
key: String(entry.key ?? ""),
|
|
149
|
+
value: String(entry.value ?? ""),
|
|
150
|
+
evidence: Array.isArray(entry.evidence) ? entry.evidence.map(String) : [],
|
|
151
|
+
}))
|
|
152
|
+
: [];
|
|
153
|
+
const limitations = Array.isArray(raw.limitations) ? raw.limitations.map(String) : [];
|
|
154
|
+
return { schema: EVIDENCE_BUNDLE_SCHEMA, facts, limitations };
|
|
155
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export declare const PROPOSAL_KINDS: readonly ["skill", "agent", "rule", "hook", "template"];
|
|
2
|
+
export type ProposalKind = (typeof PROPOSAL_KINDS)[number];
|
|
3
|
+
export type ProposalStatus = "proposed" | "approved" | "rejected" | "suppressed";
|
|
4
|
+
export type ProposalOrigin = "onboarding" | "monitor";
|
|
5
|
+
export type ProposalRecord = {
|
|
6
|
+
id: string;
|
|
7
|
+
kind: ProposalKind;
|
|
8
|
+
origin: ProposalOrigin;
|
|
9
|
+
signature: string;
|
|
10
|
+
status: ProposalStatus;
|
|
11
|
+
title: string;
|
|
12
|
+
outline: string;
|
|
13
|
+
evidence: string[];
|
|
14
|
+
occurrences: number;
|
|
15
|
+
lastSeq: number;
|
|
16
|
+
rejectReason: string | null;
|
|
17
|
+
rejectedAtOccurrences: number | null;
|
|
18
|
+
provenance: string;
|
|
19
|
+
/** Content hash of the last imported draft; identical re-imports are no-ops. */
|
|
20
|
+
draftHash: string | null;
|
|
21
|
+
};
|
|
22
|
+
export type ProposalPolicy = {
|
|
23
|
+
threshold: number;
|
|
24
|
+
cooldown: number;
|
|
25
|
+
suppressed: string[];
|
|
26
|
+
};
|
|
27
|
+
export type ProposalStore = {
|
|
28
|
+
schema: 1;
|
|
29
|
+
/** Monotonic sequence number: every mutation advances it (no wall timestamps). */
|
|
30
|
+
seq: number;
|
|
31
|
+
lastSurfacedSeq: number;
|
|
32
|
+
policy: ProposalPolicy;
|
|
33
|
+
proposals: ProposalRecord[];
|
|
34
|
+
};
|
|
35
|
+
export type SurfaceVerdict = {
|
|
36
|
+
surface: boolean;
|
|
37
|
+
reason: string;
|
|
38
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const PROPOSAL_KINDS = ["skill", "agent", "rule", "hook", "template"];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type ProposalKind } from "./types.js";
|
|
2
|
+
import type { EvidenceBundle } from "./signals.js";
|
|
3
|
+
export type DraftRecord = {
|
|
4
|
+
kind: ProposalKind | string;
|
|
5
|
+
signature: string;
|
|
6
|
+
title: string;
|
|
7
|
+
outline: string;
|
|
8
|
+
evidence: string[];
|
|
9
|
+
};
|
|
10
|
+
export type DraftFailure = {
|
|
11
|
+
record: string;
|
|
12
|
+
reason: string[];
|
|
13
|
+
};
|
|
14
|
+
export type DraftValidation = {
|
|
15
|
+
records: DraftRecord[];
|
|
16
|
+
errors: DraftFailure[];
|
|
17
|
+
overlaps: {
|
|
18
|
+
signature: string;
|
|
19
|
+
catalogId: string;
|
|
20
|
+
}[];
|
|
21
|
+
};
|
|
22
|
+
export declare function parseDrafts(content: string): DraftRecord[];
|
|
23
|
+
/**
|
|
24
|
+
* Contract check run after the host agent writes its drafts: required fields,
|
|
25
|
+
* evidence refs must resolve into the EvidenceBundle, kinds must be known, and
|
|
26
|
+
* overlap with existing catalog resources is annotated for the reviewer.
|
|
27
|
+
*/
|
|
28
|
+
export declare function validateDrafts(drafts: DraftRecord[], bundle: EvidenceBundle, catalogIds: string[]): DraftValidation;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { parseDocument } from "yaml";
|
|
2
|
+
import { PROPOSAL_KINDS } from "./types.js";
|
|
3
|
+
const REQUIRED = ["kind", "signature", "title", "outline", "evidence"];
|
|
4
|
+
function slugTokens(value) {
|
|
5
|
+
return value
|
|
6
|
+
.toLowerCase()
|
|
7
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
8
|
+
.trim()
|
|
9
|
+
.split(/\s+/)
|
|
10
|
+
.filter(Boolean);
|
|
11
|
+
}
|
|
12
|
+
export function parseDrafts(content) {
|
|
13
|
+
const trimmed = content.trim();
|
|
14
|
+
if (!trimmed)
|
|
15
|
+
return [];
|
|
16
|
+
const raw = parseDocument(trimmed).toJS();
|
|
17
|
+
if (!Array.isArray(raw))
|
|
18
|
+
throw new Error("Drafts file must contain a YAML list of records");
|
|
19
|
+
return raw.map((entry) => ({
|
|
20
|
+
kind: String(entry.kind ?? ""),
|
|
21
|
+
signature: String(entry.signature ?? ""),
|
|
22
|
+
title: String(entry.title ?? ""),
|
|
23
|
+
outline: String(entry.outline ?? ""),
|
|
24
|
+
evidence: Array.isArray(entry.evidence) ? entry.evidence.map(String) : [],
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Contract check run after the host agent writes its drafts: required fields,
|
|
29
|
+
* evidence refs must resolve into the EvidenceBundle, kinds must be known, and
|
|
30
|
+
* overlap with existing catalog resources is annotated for the reviewer.
|
|
31
|
+
*/
|
|
32
|
+
export function validateDrafts(drafts, bundle, catalogIds) {
|
|
33
|
+
const knownFactIds = new Set(bundle.facts.map((fact) => fact.id));
|
|
34
|
+
const records = [];
|
|
35
|
+
const errors = [];
|
|
36
|
+
const overlaps = [];
|
|
37
|
+
for (const draft of drafts) {
|
|
38
|
+
const reason = [];
|
|
39
|
+
for (const field of REQUIRED)
|
|
40
|
+
if (field === "evidence"
|
|
41
|
+
? draft.evidence.length === 0
|
|
42
|
+
: draft[field] === undefined || draft[field] === null || !String(draft[field]).trim())
|
|
43
|
+
reason.push(`missing required field: ${field}`);
|
|
44
|
+
if (!PROPOSAL_KINDS.includes(draft.kind))
|
|
45
|
+
reason.push(`unknown kind: ${draft.kind}`);
|
|
46
|
+
const dangling = draft.evidence.filter((ref) => !knownFactIds.has(ref));
|
|
47
|
+
if (dangling.length)
|
|
48
|
+
reason.push(`evidence refs not present in bundle: ${dangling.join(", ")}`);
|
|
49
|
+
if (reason.length) {
|
|
50
|
+
errors.push({ record: draft.signature || "(unnamed)", reason });
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
records.push(draft);
|
|
54
|
+
const tokens = slugTokens(draft.title);
|
|
55
|
+
for (const catalogId of catalogIds) {
|
|
56
|
+
const [type, ...rest] = catalogId.split("/");
|
|
57
|
+
const slug = rest.join(" ").replaceAll("-", " ");
|
|
58
|
+
const slugTokensList = slugTokens(slug);
|
|
59
|
+
if (type.replace(/s$/, "") === draft.kind &&
|
|
60
|
+
slugTokensList.length > 0 &&
|
|
61
|
+
slugTokensList.every((token) => tokens.includes(token)))
|
|
62
|
+
overlaps.push({ signature: draft.signature, catalogId });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { records, errors, overlaps };
|
|
66
|
+
}
|