skillfit 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +27 -7
  2. package/README.zh-CN.md +27 -7
  3. package/benches/README.md +2 -2
  4. package/dist/cli.js +146 -36
  5. package/dist/cli.test.js +94 -0
  6. package/dist/commands/bench-calibration.js +197 -0
  7. package/dist/commands/bench-calibration.test.js +237 -0
  8. package/dist/commands/bench-check-json.test.js +24 -3
  9. package/dist/commands/bench.js +69 -141
  10. package/dist/commands/calibration-cli.test.js +145 -0
  11. package/dist/commands/eval-agent-preflight.test.js +245 -0
  12. package/dist/commands/eval-cli.js +31 -0
  13. package/dist/commands/eval-component.js +59 -28
  14. package/dist/commands/eval-export-modes.test.js +350 -0
  15. package/dist/commands/eval-export.js +44 -10
  16. package/dist/commands/eval-export.test.js +165 -8
  17. package/dist/commands/eval-interruption.test.js +238 -0
  18. package/dist/commands/eval-plan.js +37 -0
  19. package/dist/commands/eval-preflight.js +61 -0
  20. package/dist/commands/eval-preflight.test.js +382 -0
  21. package/dist/commands/eval-report.js +60 -14
  22. package/dist/commands/eval-report.test.js +2 -2
  23. package/dist/commands/eval-single-arm-replay.js +21 -0
  24. package/dist/commands/eval-single-arm-report.js +223 -0
  25. package/dist/commands/eval.js +184 -112
  26. package/dist/commands/evaluation-report.js +5 -0
  27. package/dist/commands/evaluation-report.test.js +243 -0
  28. package/dist/commands/replay-cancellation.test.js +105 -0
  29. package/dist/commands/workflow-entrypoints.test.js +137 -0
  30. package/dist/harness/agent-preflight.js +180 -0
  31. package/dist/harness/bench.js +2 -1
  32. package/dist/harness/command.js +49 -0
  33. package/dist/harness/eval-audit.js +164 -17
  34. package/dist/harness/eval-budget.js +46 -2
  35. package/dist/harness/eval-budget.test.js +30 -3
  36. package/dist/harness/eval-component.test.js +169 -6
  37. package/dist/harness/eval-contract.js +11 -5
  38. package/dist/harness/executors/api.js +14 -4
  39. package/dist/harness/executors/api.test.js +61 -0
  40. package/dist/harness/executors/cli.js +24 -3
  41. package/dist/harness/experiment-session.js +77 -18
  42. package/dist/harness/experiment-session.test.js +51 -1
  43. package/dist/harness/input-snapshot.js +150 -0
  44. package/dist/harness/interruption.js +48 -0
  45. package/dist/harness/interruption.test.js +31 -0
  46. package/dist/harness/invocation-costs.js +72 -0
  47. package/dist/harness/judge-accounting.test.js +216 -0
  48. package/dist/harness/judge-audit.js +56 -0
  49. package/dist/harness/judge.js +86 -21
  50. package/dist/harness/replay-package.js +71 -5
  51. package/dist/harness/runner.js +92 -44
  52. package/dist/harness/runner.test.js +23 -0
  53. package/dist/harness/single-arm-audit.js +436 -0
  54. package/dist/harness/trigger.js +41 -7
  55. package/dist/harness/trigger.test.js +12 -0
  56. package/dist/harness/verifier-error.js +65 -0
  57. package/dist/harness/verifier.test.js +128 -0
  58. package/docs/bench-authoring.md +34 -9
  59. package/docs/bench-check-json.md +36 -6
  60. package/docs/eval-agent-preflight.md +101 -0
  61. package/docs/eval-case-preflight.md +115 -0
  62. package/docs/eval-component.md +65 -9
  63. package/docs/eval-costs.md +53 -0
  64. package/docs/eval-planning.md +153 -0
  65. package/docs/evaluation-input-snapshots.md +125 -0
  66. package/docs/evaluation-interruption.md +101 -0
  67. package/docs/evaluation-reports.md +143 -0
  68. package/docs/experiment-workflow.md +16 -2
  69. package/docs/first-real-eval.md +55 -5
  70. package/docs/growth-roadmap-2026-10.md +48 -11
  71. package/docs/metrics.md +71 -3
  72. package/docs/plans/2026-10-16-case-workflow-and-release.md +19 -0
  73. package/docs/plans/2026-10-17-workflow-foundations.md +64 -0
  74. package/docs/releases/0.10.0-ci-registry-install.json +140 -0
  75. package/docs/releases/0.10.0-feature-smoke.json +22 -0
  76. package/docs/releases/0.10.0-feature-smoke.mjs +62 -0
  77. package/docs/releases/0.10.0-signatures.txt +7 -0
  78. package/docs/releases/0.10.0-verification.json +76 -0
  79. package/docs/releases/0.10.0.md +44 -8
  80. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  81. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  82. package/docs/releases/0.10.1-feature-smoke.mjs +95 -0
  83. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  84. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  85. package/docs/releases/0.10.1-signatures.txt +7 -0
  86. package/docs/releases/0.10.1-verification.json +90 -0
  87. package/docs/releases/0.10.1.md +71 -0
  88. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  89. package/docs/releases/0.11.0.md +47 -0
  90. package/docs/replay-packages.md +52 -11
  91. package/docs/schemas/agent-preflight.schema.json +31 -0
  92. package/docs/schemas/calibration-plan.schema.json +22 -0
  93. package/docs/schemas/calibration-result.schema.json +17 -0
  94. package/docs/schemas/eval-preflight.schema.json +57 -0
  95. package/docs/schemas/eval-request.schema.json +1 -1
  96. package/docs/schemas/eval-result.schema.json +14 -1
  97. package/docs/schemas/invocation-costs.schema.json +31 -0
  98. package/docs/schemas/judge-call.schema.json +22 -0
  99. package/docs/schemas/single-arm-report.schema.json +20 -0
  100. package/docs/schemas/verifier-error.schema.json +11 -0
  101. package/docs/sharing-results.md +8 -2
  102. package/docs/verifier-contract.md +99 -0
  103. package/package.json +1 -1
  104. package/skills/skillfit/SKILL.md +41 -8
@@ -0,0 +1,382 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { delimiter, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { test } from 'node:test';
8
+ import { runBenchInit } from './bench.js';
9
+ import { componentError, reportEvalComponent } from './eval-component.js';
10
+ import { runEval } from './eval.js';
11
+ import { runEvalCli } from './eval-cli.js';
12
+ import { exportEvaluation } from './eval-export.js';
13
+ import { CasePreflightFailed } from './eval-preflight.js';
14
+ import { MockExecutor } from '../harness/executors/mock.js';
15
+ const read = (path) => JSON.parse(readFileSync(path, 'utf8'));
16
+ async function setup(t, kind = 'command') {
17
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-preflight-'));
18
+ t.after(() => rmSync(root, { recursive: true, force: true }));
19
+ const bench = join(root, 'bench'), skill = join(root, 'new'), old = join(root, 'old');
20
+ await runBenchInit({ dir: bench, kind, yes: true, log: () => { } });
21
+ for (const [dir, version] of [[skill, 'new'], [old, 'old']]) {
22
+ mkdirSync(dir);
23
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: preflight-test\ndescription: Offline test.\n---\n${version}\n`);
24
+ }
25
+ let calls = 0, judges = 0;
26
+ const mock = new MockExecutor();
27
+ const executor = { describe: () => mock.describe(), run: async (...args) => { calls++; return mock.run(...args); } };
28
+ const judge = { describe: () => mock.describe(), run: async () => { judges++; throw new Error('judge must not run'); } };
29
+ const raw = read(join(bench, 'bench.json'));
30
+ const save = () => writeFileSync(join(bench, 'bench.json'), JSON.stringify(raw));
31
+ const base = { bench, skillPath: skill, trials: 1, maxCalls: 2, executor, judgeExecutor: null,
32
+ runsRoot: join(root, 'runs'), runGroup: 'checked', yes: true, dryRun: false, log: () => { } };
33
+ return { root, bench, skill, old, raw, save, base, judge, calls: () => calls, judges: () => judges,
34
+ verifier: join(bench, 'verifiers/example-task.mjs'), oracle: join(bench, 'ground-truth/oracle-example-task.mjs') };
35
+ }
36
+ test('grader load/runtime/reported errors block output and command tasks without an oracle or any executor call', async (t) => {
37
+ for (const kind of ['command', 'output'])
38
+ for (const [name, source] of [
39
+ ['syntax', 'const broken = ;'], ['runtime', 'missingGraderFunction();'],
40
+ ['dependency', "import './absent-grader-dependency.mjs';"],
41
+ ['reported-zero-exit', "console.log(JSON.stringify({schemaVersion:1,kind:'skillfit.verifier-error',message:'grader unavailable'}));"],
42
+ ])
43
+ await t.test(`${kind}: ${name}`, async (t) => {
44
+ const f = await setup(t, kind);
45
+ delete f.raw.tasks[0].oracle;
46
+ writeFileSync(f.verifier, source);
47
+ f.save();
48
+ await assert.rejects(runEval(f.base), error => {
49
+ assert.ok(error instanceof CasePreflightFailed);
50
+ const gate = error.preflight.checks.find(c => c.code === (kind === 'command' ? 'UNTOUCHED_FIXTURE' : 'MISSING_OUTPUT'));
51
+ assert.equal(gate?.status, 'FAIL');
52
+ assert.match(gate.evidence.error, /VERIFIER_(RUNTIME|REPORTED)_ERROR/);
53
+ assert.notEqual(gate.evidence.exitCode, null);
54
+ return true;
55
+ });
56
+ assert.equal(f.calls(), 0);
57
+ assert.equal(f.judges(), 0);
58
+ assert.ok(!existsSync(f.base.runsRoot));
59
+ });
60
+ });
61
+ test('an oracle explicitly reporting an infrastructure error cannot pass by exiting zero', async (t) => {
62
+ const f = await setup(t);
63
+ writeFileSync(f.oracle, "console.log(JSON.stringify({schemaVersion:1,kind:'skillfit.verifier-error',message:'reference environment unavailable'}));");
64
+ await assert.rejects(runEval(f.base), error => {
65
+ assert.ok(error instanceof CasePreflightFailed);
66
+ const gate = error.preflight.checks.find(c => c.code === 'ORACLE');
67
+ assert.equal(gate?.status, 'FAIL');
68
+ assert.equal(gate.evidence.exitCode, 0);
69
+ assert.match(gate.evidence.error, /VERIFIER_REPORTED_ERROR/);
70
+ return true;
71
+ });
72
+ assert.equal(f.calls(), 0);
73
+ assert.ok(!existsSync(f.base.runsRoot));
74
+ });
75
+ test('quoted verifier/oracle paths grade a real file repair, preserve failure/pass and replay without originals', async (t) => {
76
+ const f = await setup(t);
77
+ renameSync(f.verifier, join(f.bench, 'verifiers/check answer.mjs'));
78
+ renameSync(f.oracle, join(f.bench, 'ground-truth/repair answer.mjs'));
79
+ f.raw.tasks[0].verifier = 'node "verifiers/check answer.mjs"';
80
+ f.raw.tasks[0].oracle = "node 'ground-truth/repair answer.mjs'";
81
+ f.save();
82
+ let calls = 0;
83
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-quoted-repair' }), run: async (_p, dir) => {
84
+ if (++calls === 2)
85
+ writeFileSync(join(dir, 'index.js'), 'export const add = (a,b) => a+b;\n');
86
+ return { output: 'done', tokens: { input: 10, cachedInput: 4, output: 2 } };
87
+ } };
88
+ const base = { ...f.base, executor }, preview = await runEvalCli({ ...base, dryRun: true });
89
+ assert.ok('plan' in preview);
90
+ const result = await runEvalCli(base, preview.plan.sha256);
91
+ assert.equal(result.status, 'completed');
92
+ assert.ok('quality' in result);
93
+ assert.equal(result.evidence.verified, true);
94
+ assert.equal(result.quality.improvedPairs, 1);
95
+ assert.equal(result.quality.regressedPairs, 0);
96
+ const run = join(base.runsRoot, base.runGroup);
97
+ const before = read(join(run, 'example-task/baseline/trial-1/_result.json')), after = read(join(run, 'example-task/treatment/trial-1/_result.json'));
98
+ assert.equal(before.error, null);
99
+ assert.equal(before.passed, false);
100
+ assert.equal(after.error, null);
101
+ assert.equal(after.passed, true);
102
+ for (const dir of [f.bench, f.skill, f.old])
103
+ rmSync(dir, { recursive: true });
104
+ const replay = await reportEvalComponent(run, { replay: true });
105
+ assert.equal(replay.evidence.verified, true);
106
+ assert.ok('costs' in replay);
107
+ assert.deepEqual(replay.costs, result.costs);
108
+ assert.ok('replayedDeliveries' in replay.evidence);
109
+ assert.equal(replay.evidence.replayedDeliveries, 2);
110
+ const output = join(f.root, 'portable');
111
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
112
+ rmSync(run, { recursive: true });
113
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
114
+ assert.equal(child.status, 0, child.stderr);
115
+ assert.equal(JSON.parse(child.stdout).evidence.verified, true);
116
+ assert.deepEqual(JSON.parse(child.stdout).costs, result.costs);
117
+ assert.equal(calls, 2);
118
+ });
119
+ test('a grader exception after an invoked repair stops a budgeted run and retains final invocation costs', async (t) => {
120
+ const f = await setup(t);
121
+ delete f.raw.tasks[0].oracle;
122
+ f.save();
123
+ writeFileSync(f.verifier, "import{readFileSync}from'node:fs';import{join}from'node:path';if(readFileSync(join(process.argv[2],'index.js'),'utf8').includes('a + b'))throw new TypeError('grader broke on repaired input');console.log(JSON.stringify({passed:false}));process.exit(1);");
124
+ let calls = 0;
125
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-grader-crash' }), run: async (_p, dir) => {
126
+ calls++;
127
+ writeFileSync(join(dir, 'index.js'), 'export const add = (a,b) => a + b;\n');
128
+ return { output: 'fixed', tokens: { input: 10, cachedInput: 4, output: 2 } };
129
+ } };
130
+ const result = await runEvalCli({ ...f.base, executor, spendingBudget: { input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 } });
131
+ assert.equal(result.status, 'stopped');
132
+ assert.equal(calls, 1);
133
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
134
+ const receipt = read(join(f.base.runsRoot, f.base.runGroup, 'example-task/baseline/trial-1/_result.json'));
135
+ assert.match(receipt.error, /VERIFIER_RUNTIME_ERROR/);
136
+ assert.equal(receipt.usageStatus, 'final');
137
+ assert.deepEqual(receipt.tokens, { input: 10, cachedInput: 4, output: 2 });
138
+ assert.ok('costs' in result);
139
+ assert.equal(result.costs.populations.attempts.baseline.metrics.input.knownTotal, 10);
140
+ assert.equal(result.costs.populations.attempts.baseline.metrics.input.coverage.final, 1);
141
+ assert.ok(!existsSync(join(f.base.runsRoot, f.base.runGroup, 'example-task/treatment/trial-1')));
142
+ });
143
+ test('offline replay refuses a new verifier infrastructure error even when its nonzero exit matches the saved failure', async (t) => {
144
+ const f = await setup(t), name = 'SKILLFIT_OFFLINE_VERIFIER_ERROR', previous = process.env[name];
145
+ delete f.raw.tasks[0].oracle;
146
+ f.save();
147
+ writeFileSync(f.verifier, `if(process.env.${name})throw new Error('replay grader unavailable');console.log(JSON.stringify({passed:false}));process.exit(1);`);
148
+ delete process.env[name];
149
+ let calls = 0;
150
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-replay-grader' }), run: async () => {
151
+ calls++;
152
+ return { output: 'done', tokens: { input: 10, cachedInput: 4, output: 2 } };
153
+ } };
154
+ try {
155
+ await runEval({ ...f.base, executor });
156
+ const run = join(f.base.runsRoot, f.base.runGroup), path = join(run, 'manifest.json'), original = readFileSync(path, 'utf8');
157
+ const saved = await reportEvalComponent(run);
158
+ assert.equal(saved.evidence.verified, true);
159
+ assert.ok('costs' in saved);
160
+ process.env[name] = '1';
161
+ const replay = await reportEvalComponent(run, { replay: true });
162
+ assert.equal(replay.evidence.verified, false);
163
+ assert.ok('costs' in replay);
164
+ assert.match(replay.evidence.reasons.join(' '), /Replay verifier failed: VERIFIER_RUNTIME_ERROR/);
165
+ assert.equal(replay.acceptance.eligibleForUpgrade, false);
166
+ assert.deepEqual(replay.costs, saved.costs);
167
+ assert.equal(readFileSync(path, 'utf8'), original);
168
+ assert.equal(calls, 2);
169
+ }
170
+ finally {
171
+ if (previous === undefined)
172
+ delete process.env[name];
173
+ else
174
+ process.env[name] = previous;
175
+ }
176
+ });
177
+ for (const mode of ['inject', 'installed', 'trigger'])
178
+ test(`${mode}: a broken NOP gate blocks all agent/judge calls before run creation`, async (t) => {
179
+ const f = await setup(t);
180
+ f.raw.tasks[0].shouldTrigger = true;
181
+ f.save();
182
+ writeFileSync(f.verifier, 'process.exit(0);');
183
+ await assert.rejects(runEval({ ...f.base, mode, skillInstallDir: 'project-skills',
184
+ ...(mode === 'installed' ? { baselineSkillPath: f.old } : {}),
185
+ ...(mode !== 'trigger' ? { judgeExecutor: f.judge, maxCalls: 4 } : {}) }), error => {
186
+ assert.ok(error instanceof CasePreflightFailed);
187
+ assert.equal(error.preflight.status, 'blocked');
188
+ assert.ok(error.preflight.checks.some(c => c.code === 'UNTOUCHED_FIXTURE' && c.status === 'FAIL' && c.evidence?.exitCode === 0));
189
+ assert.match(error.message, /already passes/);
190
+ assert.match(error.message, /Remedy:/);
191
+ return true;
192
+ });
193
+ assert.equal(f.calls(), 0);
194
+ assert.equal(f.judges(), 0);
195
+ assert.ok(!existsSync(f.base.runsRoot));
196
+ });
197
+ test('missing/empty output, unspawnable verifiers and failed oracles are hard gates with process evidence', async (t) => {
198
+ for (const issue of ['missing', 'empty', 'spawn', 'oracle-process', 'oracle-verifier'])
199
+ await t.test(issue, async (t) => {
200
+ const f = await setup(t, issue === 'missing' || issue === 'empty' ? 'output' : 'command');
201
+ let code;
202
+ if (issue === 'missing' || issue === 'empty') {
203
+ delete f.raw.tasks[0].oracle;
204
+ writeFileSync(f.verifier, issue === 'missing' ? 'process.exit(0);' :
205
+ "import{existsSync}from'node:fs';import{join}from'node:path';process.exit(existsSync(join(process.argv[2],'_output.md'))?0:1);");
206
+ code = issue === 'missing' ? 'MISSING_OUTPUT' : 'EMPTY_OUTPUT';
207
+ }
208
+ else if (issue === 'spawn') {
209
+ f.raw.tasks[0].verifier = 'skillfit-no-such-verifier';
210
+ code = 'UNTOUCHED_FIXTURE';
211
+ }
212
+ else {
213
+ writeFileSync(f.oracle, issue === 'oracle-process' ? "console.error('reference failed');process.exit(7);" : 'process.exit(0);');
214
+ code = 'ORACLE';
215
+ }
216
+ f.save();
217
+ await assert.rejects(runEval(f.base), error => {
218
+ assert.ok(error instanceof CasePreflightFailed);
219
+ const check = error.preflight.checks.find(c => c.code === code && c.status === 'FAIL');
220
+ assert.ok(check?.evidence);
221
+ assert.ok(check.remediation);
222
+ assert.equal(check.taskId, 'example-task');
223
+ if (issue === 'spawn') {
224
+ assert.equal(check.evidence.exitCode, null);
225
+ assert.ok(check.evidence.error);
226
+ }
227
+ if (issue === 'oracle-process') {
228
+ assert.equal(check.evidence.exitCode, 7);
229
+ assert.match(check.evidence.output, /reference failed/);
230
+ }
231
+ assert.equal(componentError(error).error.code, 'CASE_PREFLIGHT_FAILED');
232
+ return true;
233
+ });
234
+ assert.equal(f.calls(), 0);
235
+ assert.ok(!existsSync(f.base.runsRoot));
236
+ });
237
+ });
238
+ test('warnings and unknown coverage are distinct, nonblocking and frozen for offline reporting', async (t) => {
239
+ const f = await setup(t);
240
+ delete f.raw.tasks[0].oracle;
241
+ f.raw.tasks[0].shouldTrigger = true;
242
+ f.save();
243
+ writeFileSync(join(f.bench, 'fixtures/example-task/large.txt'), 'x'.repeat(66 * 1024));
244
+ const lines = [];
245
+ await runEval({ ...f.base, log: line => lines.push(line) });
246
+ assert.equal(f.calls(), 2);
247
+ const run = join(f.base.runsRoot, f.base.runGroup), report = read(join(run, '_plan.json')).details.casePreflight;
248
+ assert.equal(report.status, 'ready');
249
+ assert.equal(report.summary.failures, 0);
250
+ assert.ok(report.summary.warnings >= 2);
251
+ assert.ok(report.summary.unknown >= 2);
252
+ for (const [code, status] of [['ORACLE', 'UNKNOWN'], ['LIVE_DIFFICULTY', 'UNKNOWN'], ['FIXTURE_SIZE', 'WARN'], ['NEGATIVE_CONTROLS', 'WARN'], ['MOCK_COVERAGE', 'INFO']]) {
253
+ assert.equal(report.checks.find((c) => c.code === code).status, status);
254
+ }
255
+ assert.equal(report.cost.modelCalls, 0);
256
+ assert.ok(report.cost.durationMs >= 0);
257
+ assert.match(lines.join('\n'), /\[UNKNOWN\] ORACLE/);
258
+ assert.match(lines.join('\n'), /\[WARN\] FIXTURE_SIZE/);
259
+ const saved = await reportEvalComponent(run, { replay: true });
260
+ assert.ok('casePreflight' in saved);
261
+ assert.deepEqual(saved.casePreflight, report);
262
+ assert.equal(saved.acceptance.eligibleForUpgrade, false);
263
+ assert.equal(f.calls(), 2);
264
+ });
265
+ test('only selected tasks are probed; trigger mode also skips unlabelled tasks', async (t) => {
266
+ for (const trigger of [false, true])
267
+ await t.test(String(trigger), async (t) => {
268
+ const f = await setup(t);
269
+ writeFileSync(join(f.bench, 'verifiers/unselected.mjs'), "console.log('must not be probed');process.exit(0);");
270
+ f.raw.tasks.push({ ...f.raw.tasks[0], id: 'unselected', verifier: 'node verifiers/unselected.mjs' });
271
+ if (trigger)
272
+ f.raw.tasks[0].shouldTrigger = true;
273
+ f.save();
274
+ await runEval({ ...f.base, ...(trigger ? { mode: 'trigger', skillInstallDir: 'skills', maxCalls: 1,
275
+ executor: { describe: () => ({ kind: 'cli', model: 'offline-trigger' }),
276
+ run: async (...args) => ({ ...await f.base.executor.run(...args), skillTriggered: true }) } } : { taskIds: ['example-task'] }) });
277
+ const report = read(join(f.base.runsRoot, f.base.runGroup, '_plan.json')).details.casePreflight;
278
+ assert.deepEqual(report.bench.taskIds, ['example-task']);
279
+ assert.ok(!report.checks.some((c) => c.taskId === 'unselected'));
280
+ assert.equal(f.calls(), trigger ? 1 : 2);
281
+ });
282
+ });
283
+ test('dry-run stays side-effect-free and declares pending preflight rather than claiming checks passed', async (t) => {
284
+ const f = await setup(t), sentinel = join(f.root, 'probe-started');
285
+ writeFileSync(f.verifier, `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(0);`);
286
+ await runEval({ ...f.base, dryRun: true, onPlan: plan => {
287
+ assert.deepEqual(plan.casePreflight, { schemaVersion: 1, scope: 'offline-case-integrity', required: true, status: 'pending' });
288
+ } });
289
+ assert.equal(f.calls(), 0);
290
+ assert.ok(!existsSync(sentinel));
291
+ assert.ok(!existsSync(f.base.runsRoot));
292
+ });
293
+ test('missing mock coverage is unknown; malformed markers and overflowing mock probes block evaluation', async (t) => {
294
+ for (const issue of ['absent', 'omitted-arm', 'malformed', 'overflow-probe'])
295
+ await t.test(issue, async (t) => {
296
+ const f = await setup(t, 'output'), marker = join(f.bench, 'fixtures/example-task/.skillfit-mock.json');
297
+ if (issue === 'absent')
298
+ rmSync(marker);
299
+ else if (issue === 'omitted-arm')
300
+ writeFileSync(marker, '{}');
301
+ else if (issue === 'malformed')
302
+ writeFileSync(marker, '{');
303
+ else {
304
+ const source = readFileSync(f.verifier, 'utf8');
305
+ writeFileSync(f.verifier, "import{readFileSync as readProbe}from'node:fs';import{join as probePath}from'node:path';let overflow=false;try{overflow=readProbe(probePath(process.argv[2],'_output.md'),'utf8')==='overflow';}catch{}if(overflow){process.stdout.write('x'.repeat(9*1024*1024));setInterval(()=>{},1000);await new Promise(()=>{});}\n" + source);
306
+ writeFileSync(marker, JSON.stringify({ baseline: { output: 'overflow' } }));
307
+ }
308
+ if (issue === 'malformed' || issue === 'overflow-probe') {
309
+ await assert.rejects(runEval(f.base), error => {
310
+ assert.ok(error instanceof CasePreflightFailed);
311
+ assert.ok(error.preflight.checks.some(c => c.code === (issue === 'malformed' ? 'MOCK_MARKER' : 'MOCK_BASELINE') && c.status === 'FAIL'));
312
+ return true;
313
+ });
314
+ assert.equal(f.calls(), 0);
315
+ assert.ok(!existsSync(f.base.runsRoot));
316
+ }
317
+ else {
318
+ await runEval(f.base);
319
+ const report = read(join(f.base.runsRoot, f.base.runGroup, '_plan.json')).details.casePreflight;
320
+ assert.equal(report.checks.find((c) => c.code === (issue === 'absent' ? 'MOCK_COVERAGE' : 'MOCK_BASELINE')).status, 'UNKNOWN');
321
+ assert.equal(f.calls(), 2);
322
+ }
323
+ });
324
+ });
325
+ test('existing run groups are rejected before executing any offline probe or overwriting evidence', async (t) => {
326
+ const f = await setup(t), run = join(f.base.runsRoot, f.base.runGroup), sentinel = join(f.root, 'probe-started');
327
+ mkdirSync(run, { recursive: true });
328
+ writeFileSync(join(run, 'kept'), 'original');
329
+ writeFileSync(f.verifier, `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(0);`);
330
+ await assert.rejects(runEval(f.base), /already exists/);
331
+ assert.equal(readFileSync(join(run, 'kept'), 'utf8'), 'original');
332
+ assert.ok(!existsSync(sentinel));
333
+ assert.equal(f.calls(), 0);
334
+ });
335
+ test('probe mutations of bench or either Skill cannot silently change the approved inputs', async (t) => {
336
+ for (const which of ['bench', 'candidate', 'baseline'])
337
+ await t.test(which, async (t) => {
338
+ const f = await setup(t);
339
+ const target = which === 'bench' ? join(f.bench, 'prompts/example-task.md') : join(which === 'candidate' ? f.skill : f.old, 'SKILL.md');
340
+ writeFileSync(f.verifier, `import{appendFileSync}from'node:fs';appendFileSync(${JSON.stringify(target)},'changed');process.exit(1);`);
341
+ delete f.raw.tasks[0].oracle;
342
+ f.save();
343
+ await assert.rejects(runEval({ ...f.base, mode: 'installed', baselineSkillPath: f.old, skillInstallDir: 'skills' }), error => {
344
+ assert.ok(error instanceof CasePreflightFailed);
345
+ assert.ok(error.preflight.checks.some(c => c.code === 'INPUT_CHANGED' && c.status === 'FAIL'));
346
+ return true;
347
+ });
348
+ assert.equal(f.calls(), 0);
349
+ assert.ok(!existsSync(f.base.runsRoot));
350
+ });
351
+ });
352
+ test('request preflight failures produce JSON-only per-case diagnostics without starting an agent CLI', async (t) => {
353
+ const f = await setup(t);
354
+ writeFileSync(f.verifier, 'process.exit(0);');
355
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url)), request = join(f.root, 'request.json');
356
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, baselineSkill: f.old, candidateSkill: f.skill,
357
+ bench: f.bench, agent: 'codex', purpose: 'development', trials: 1, maxCalls: 2, runsRoot: f.base.runsRoot, runGroup: f.base.runGroup }));
358
+ // Shadow the real agent even if the gate regresses; this test cannot reach it.
359
+ const bin = join(f.root, 'bin'), sentinel = join(f.root, 'fake-agent-started');
360
+ mkdirSync(bin);
361
+ const fake = join(bin, process.platform === 'win32' ? 'codex.cmd' : 'codex');
362
+ writeFileSync(fake, process.platform === 'win32' ? `@echo offline>"${sentinel}"\r\n@exit /b 1\r\n` :
363
+ `#!${process.execPath}\nimport{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(1);\n`);
364
+ chmodSync(fake, 0o755);
365
+ const invoke = (args) => spawnSync(process.execPath, [cli, 'eval', '--request', request, ...args], {
366
+ encoding: 'utf8', timeout: 20_000, env: { ...process.env, PATH: `${bin}${delimiter}${process.env.PATH ?? ''}` }
367
+ });
368
+ const preview = invoke(['--dry-run']);
369
+ assert.equal(preview.status, 0, preview.stderr);
370
+ const plan = JSON.parse(preview.stdout).plan;
371
+ const executed = invoke(['--yes', '--plan-sha', plan.sha256]);
372
+ assert.equal(executed.status, 2, executed.stderr);
373
+ assert.match(executed.stderr, /Case preflight: blocked/);
374
+ const result = JSON.parse(executed.stdout);
375
+ assert.equal(result.error.code, 'CASE_PREFLIGHT_FAILED');
376
+ assert.equal(result.casePreflight.status, 'blocked');
377
+ assert.ok(result.casePreflight.checks.some((c) => c.code === 'UNTOUCHED_FIXTURE' && c.status === 'FAIL'));
378
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
379
+ assert.equal(result.acceptance.automaticUpgrade, false);
380
+ assert.ok(!existsSync(f.base.runsRoot));
381
+ assert.ok(!existsSync(sentinel));
382
+ });
@@ -1,9 +1,11 @@
1
1
  import { readFileSync, statSync } from 'node:fs';
2
- import { resolve } from 'node:path';
2
+ import { agentEnvironmentReportLines } from '../harness/agent-preflight.js';
3
+ import { renderSingleArmReport } from './eval-single-arm-report.js';
3
4
  import { CONCLUSIVE_TASKS, CONCLUSIVE_TRIALS, formatP, formatPp1, verdictFor } from '../harness/report.js';
4
5
  import { mcnemarExactP } from '../harness/stats.js';
5
6
  import { validateSkillInstallDir } from '../harness/installed-skill.js';
6
7
  import { assertCostTotals, COST_METRICS, renderCostLines } from '../harness/costs.js';
8
+ import { parseInvocationCosts, renderInvocationCostLines } from '../harness/invocation-costs.js';
7
9
  const MAX_MANIFEST_BYTES = 16 * 1024 * 1024;
8
10
  function object(value, label) {
9
11
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
@@ -54,6 +56,8 @@ function experiment(value) {
54
56
  const callsStarted = integer(item['callsStarted'], 'experiment.callsStarted');
55
57
  const callsFinished = integer(item['callsFinished'], 'experiment.callsFinished');
56
58
  const stopReason = item['stopReason'] === null ? null : string(item['stopReason'], 'experiment.stopReason');
59
+ if (item['stopCode'] !== undefined && !['EXECUTION_FAILED', 'FINAL_USAGE_MISSING', 'SPENDING_BUDGET_REACHED'].includes(String(item['stopCode'])))
60
+ throw new Error('Invalid experiment.stopCode');
57
61
  if (![plannedCalls, maxCalls, callsStarted, callsFinished].every(Number.isSafeInteger) ||
58
62
  maxCalls < plannedCalls || callsStarted > plannedCalls || callsFinished > callsStarted ||
59
63
  (status === 'completed' && (stopReason !== null || callsFinished !== plannedCalls)) ||
@@ -62,7 +66,8 @@ function experiment(value) {
62
66
  throw new Error('experiment status, call counts, ceiling, and stop reason contradict each other');
63
67
  }
64
68
  return { schemaVersion: 1, status, plannedCalls, maxCalls, callsStarted, callsFinished, stopReason,
65
- planSha256: hash(item['planSha256'], 'experiment.planSha256') };
69
+ planSha256: hash(item['planSha256'], 'experiment.planSha256'),
70
+ ...(item['stopCode'] === undefined ? {} : { stopCode: item['stopCode'] }) };
66
71
  }
67
72
  function counts(value, label) {
68
73
  const item = object(value, label);
@@ -426,6 +431,7 @@ export function parseEvalReport(value) {
426
431
  }
427
432
  return {
428
433
  runGroup: string(manifest['runGroup'], 'runGroup'),
434
+ ...(manifest['invocationCosts'] === undefined ? {} : { invocationCosts: parseInvocationCosts(manifest['invocationCosts']) }),
429
435
  createdAt,
430
436
  target: { kind, name: string(target['name'], 'target.name'), sha256: hash(target['bundleSha256'], 'target.bundleSha256') },
431
437
  baselineTarget,
@@ -585,6 +591,8 @@ export function renderEvalMarkdown(report) {
585
591
  lines.push(...renderCostLines(report.overall.costs));
586
592
  else
587
593
  lines.push('Cache partitions and all-invocation costs were not recorded in this legacy manifest. Missing usage is unknown; the report does not infer it from prompt size or treat it as zero.');
594
+ if (report.invocationCosts)
595
+ lines.push('', ...renderInvocationCostLines(report.invocationCosts));
588
596
  lines.push('', '## Warnings', '');
589
597
  if (report.warnings.length === 0)
590
598
  lines.push('- None');
@@ -593,16 +601,54 @@ export function renderEvalMarkdown(report) {
593
601
  lines.push('', 'The verdict follows [the skillfit metrics protocol](https://github.com/remote-controlled-man/skillfit/blob/main/docs/metrics.md). Review the pinned manifest before comparing runs.', '');
594
602
  return lines.join('\n');
595
603
  }
596
- export function runEvalReport(manifestPath, log = console.log) {
597
- const path = resolve(manifestPath);
598
- if (statSync(path).size > MAX_MANIFEST_BYTES)
599
- throw new Error(`Evaluation manifest exceeds ${MAX_MANIFEST_BYTES} bytes`);
600
- let value;
601
- try {
602
- value = JSON.parse(readFileSync(path, 'utf8'));
603
- }
604
- catch (error) {
605
- throw new Error(`Cannot read evaluation manifest: ${error.message}`);
606
- }
607
- log(renderEvalMarkdown(parseEvalReport(value)));
604
+ export async function runEvalReport(inputPath, log = console.log, options = {}) {
605
+ // Import after module initialization: component assessment itself uses this
606
+ // module's manifest parser. Both CLI formats must share the same assessment.
607
+ const { readEvaluationReport } = await import('./evaluation-report.js');
608
+ const result = await readEvaluationReport(inputPath, options);
609
+ if ('evaluationType' in result) {
610
+ log(renderSingleArmReport(result));
611
+ return;
612
+ }
613
+ const root = result.evidence.runDir;
614
+ const safe = (message) => escapeMarkdown(message.replaceAll(root, '[run]'));
615
+ const lines = [];
616
+ if (result.manifest) {
617
+ const path = result.manifest.path;
618
+ if (statSync(path).size > MAX_MANIFEST_BYTES)
619
+ throw new Error(`Evaluation manifest exceeds ${MAX_MANIFEST_BYTES} bytes`);
620
+ lines.push(renderEvalMarkdown(parseEvalReport(JSON.parse(readFileSync(path, 'utf8')))));
621
+ }
622
+ else {
623
+ lines.push(`# skillfit evaluation: ${result.status} run`, '', `- State: ${result.status}`, '- No completed paired comparison is available. Retained spending is not a quality verdict.');
624
+ if (result.session?.stopReason)
625
+ lines.push(`- Stop reason: ${safe(String(result.session.stopReason))}`);
626
+ if ('startedAgentDispatches' in result.costs)
627
+ lines.push(`- Started agent dispatches: ${result.costs.startedAgentDispatches}`, `- Missing or invalid invocation receipts: ${result.costs.invocationsWithUnknownReceipts}`);
628
+ lines.push('', '## Retained costs', '', ...renderCostLines(result.costs.populations));
629
+ lines.push('', ...renderInvocationCostLines(result.invocationCosts));
630
+ }
631
+ lines.push('', '## Evidence and acceptance', '', `- State: ${result.status}`, `- Native evidence: ${result.evidence.verified ? 'verified' : 'unverified'}`, `- Acceptance: ${result.acceptance.decision}`, `- Eligible for upgrade: ${result.acceptance.eligibleForUpgrade ? 'yes' : 'no'}`, '- Automatic upgrade: no');
632
+ for (const reason of result.acceptance.reasons)
633
+ lines.push(`- ${reason.code}: ${safe(reason.message)}`);
634
+ for (const reason of result.evidence.reasons)
635
+ lines.push(`- Audit: ${safe(reason)}`);
636
+ lines.push(...agentEnvironmentReportLines(result.agentPreflight).map(line => `- ${safe(line)}`));
637
+ if (result.casePreflight) {
638
+ const gate = result.casePreflight;
639
+ if (typeof gate.status === 'string' && gate.summary && [gate.summary.failures, gate.summary.warnings, gate.summary.unknown].every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)) {
640
+ lines.push(`- Case preflight: ${safe(gate.status)}; ${gate.summary.failures} failure(s), ${gate.summary.warnings} warning(s), ${gate.summary.unknown} unknown(s)`);
641
+ }
642
+ else
643
+ lines.push('- Case preflight: invalid or unavailable metadata; inspect the unverified JSON record.');
644
+ }
645
+ if (result.inputSnapshot) {
646
+ const archive = result.inputSnapshot;
647
+ if (archive.cost && [archive.cost.files, archive.cost.bytes, archive.cost.durationMs].every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)) {
648
+ lines.push(`- Sealed input cost: ${archive.cost.files} files; ${archive.cost.bytes} bytes; ${archive.cost.durationMs}ms local sealing; 0 model calls`);
649
+ }
650
+ else
651
+ lines.push('- Sealed input cost: invalid or unavailable metadata; no copy-cost total inferred.');
652
+ }
653
+ log(lines.join('\n') + '\n');
608
654
  }
@@ -95,14 +95,14 @@ test('report eval keeps legacy manifests readable and does not infer missing cac
95
95
  assert.match(output, /all-invocation costs were not recorded in this legacy manifest/);
96
96
  assert.ok(!output.includes('| Cached input tokens | 0'));
97
97
  });
98
- test('report eval renders a v4 manifest without executing an agent or writing a file', () => {
98
+ test('report eval renders a v4 manifest without executing an agent or writing a file', async () => {
99
99
  const dir = mkdtempSync(join(tmpdir(), 'skillfit-eval-report-'));
100
100
  try {
101
101
  const path = join(dir, 'manifest.json');
102
102
  const original = `${JSON.stringify(manifest(), null, 2)}\n`;
103
103
  writeFileSync(path, original);
104
104
  const output = [];
105
- runEvalReport(path, (line) => output.push(line));
105
+ await runEvalReport(path, (line) => output.push(line));
106
106
  assert.equal(readFileSync(path, 'utf8'), original);
107
107
  assert.equal(output.length, 1);
108
108
  const markdown = output[0] ?? '';
@@ -0,0 +1,21 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { readSingleArmReport } from './eval-single-arm-report.js';
4
+ import { auditSingleArmEvaluation } from '../harness/single-arm-audit.js';
5
+ /** Shared async single-arm report reader; only native evidence can be replayed. */
6
+ export async function reportSingleArmEvaluation(path, options = {}) {
7
+ const report = readSingleArmReport(path);
8
+ if (!report)
9
+ return null;
10
+ if (options.policyPath || options.recordsPath)
11
+ throw new Error('Single-arm reports do not support paired --policy or external --records overrides.');
12
+ if (options.benchDir && !options.replay)
13
+ throw new Error('--bench is only used with --replay for a single-arm report.');
14
+ const input = resolve(path), root = statSync(input).isDirectory() ? input : dirname(input);
15
+ if (!existsSync(join(root, '_plan.json')) || !existsSync(join(root, '_session.json')) || !existsSync(join(root, '_artifacts.json'))) {
16
+ if (options.replay)
17
+ throw new Error('Offline single-arm replay requires a sealed native run, not a standalone historical summary.');
18
+ return report;
19
+ }
20
+ return { ...report, ...await auditSingleArmEvaluation(root, options) };
21
+ }