skillfit 0.10.0 → 0.10.1

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 (51) hide show
  1. package/README.md +10 -2
  2. package/README.zh-CN.md +10 -2
  3. package/dist/cli.js +19 -13
  4. package/dist/commands/bench.js +99 -91
  5. package/dist/commands/eval-component.js +8 -1
  6. package/dist/commands/eval-export.js +32 -6
  7. package/dist/commands/eval-export.test.js +165 -8
  8. package/dist/commands/eval-interruption.test.js +238 -0
  9. package/dist/commands/eval-preflight.js +61 -0
  10. package/dist/commands/eval-preflight.test.js +239 -0
  11. package/dist/commands/eval-report.js +44 -13
  12. package/dist/commands/eval-report.test.js +2 -2
  13. package/dist/commands/eval.js +81 -59
  14. package/dist/harness/eval-audit.js +3 -1
  15. package/dist/harness/eval-budget.test.js +4 -2
  16. package/dist/harness/eval-component.test.js +6 -6
  17. package/dist/harness/executors/api.js +10 -1
  18. package/dist/harness/executors/api.test.js +43 -0
  19. package/dist/harness/executors/cli.js +24 -3
  20. package/dist/harness/experiment-session.js +60 -9
  21. package/dist/harness/experiment-session.test.js +43 -1
  22. package/dist/harness/input-snapshot.js +150 -0
  23. package/dist/harness/interruption.js +48 -0
  24. package/dist/harness/interruption.test.js +31 -0
  25. package/dist/harness/runner.js +53 -15
  26. package/dist/harness/trigger.js +20 -4
  27. package/docs/bench-check-json.md +8 -1
  28. package/docs/eval-case-preflight.md +110 -0
  29. package/docs/eval-component.md +28 -0
  30. package/docs/eval-costs.md +9 -0
  31. package/docs/evaluation-input-snapshots.md +124 -0
  32. package/docs/evaluation-interruption.md +89 -0
  33. package/docs/evaluation-reports.md +49 -0
  34. package/docs/experiment-workflow.md +9 -2
  35. package/docs/first-real-eval.md +5 -2
  36. package/docs/growth-roadmap-2026-10.md +15 -10
  37. package/docs/metrics.md +31 -0
  38. package/docs/plans/2026-10-16-case-workflow-and-release.md +19 -0
  39. package/docs/releases/0.10.0-ci-registry-install.json +140 -0
  40. package/docs/releases/0.10.0-feature-smoke.json +22 -0
  41. package/docs/releases/0.10.0-feature-smoke.mjs +62 -0
  42. package/docs/releases/0.10.0-signatures.txt +7 -0
  43. package/docs/releases/0.10.0-verification.json +76 -0
  44. package/docs/releases/0.10.0.md +44 -8
  45. package/docs/releases/0.10.1-feature-smoke.mjs +95 -0
  46. package/docs/releases/0.10.1.md +38 -0
  47. package/docs/replay-packages.md +14 -5
  48. package/docs/schemas/eval-preflight.schema.json +57 -0
  49. package/docs/schemas/eval-result.schema.json +11 -0
  50. package/docs/sharing-results.md +5 -2
  51. package/package.json +1 -1
@@ -0,0 +1,239 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, 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 { CasePreflightFailed } from './eval-preflight.js';
12
+ import { MockExecutor } from '../harness/executors/mock.js';
13
+ const read = (path) => JSON.parse(readFileSync(path, 'utf8'));
14
+ async function setup(t, kind = 'command') {
15
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-preflight-'));
16
+ t.after(() => rmSync(root, { recursive: true, force: true }));
17
+ const bench = join(root, 'bench'), skill = join(root, 'new'), old = join(root, 'old');
18
+ await runBenchInit({ dir: bench, kind, yes: true, log: () => { } });
19
+ for (const [dir, version] of [[skill, 'new'], [old, 'old']]) {
20
+ mkdirSync(dir);
21
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: preflight-test\ndescription: Offline test.\n---\n${version}\n`);
22
+ }
23
+ let calls = 0, judges = 0;
24
+ const mock = new MockExecutor();
25
+ const executor = { describe: () => mock.describe(), run: async (...args) => { calls++; return mock.run(...args); } };
26
+ const judge = { describe: () => mock.describe(), run: async () => { judges++; throw new Error('judge must not run'); } };
27
+ const raw = read(join(bench, 'bench.json'));
28
+ const save = () => writeFileSync(join(bench, 'bench.json'), JSON.stringify(raw));
29
+ const base = { bench, skillPath: skill, trials: 1, maxCalls: 2, executor, judgeExecutor: null,
30
+ runsRoot: join(root, 'runs'), runGroup: 'checked', yes: true, dryRun: false, log: () => { } };
31
+ return { root, bench, skill, old, raw, save, base, judge, calls: () => calls, judges: () => judges,
32
+ verifier: join(bench, 'verifiers/example-task.mjs'), oracle: join(bench, 'ground-truth/oracle-example-task.mjs') };
33
+ }
34
+ for (const mode of ['inject', 'installed', 'trigger'])
35
+ test(`${mode}: a broken NOP gate blocks all agent/judge calls before run creation`, async (t) => {
36
+ const f = await setup(t);
37
+ f.raw.tasks[0].shouldTrigger = true;
38
+ f.save();
39
+ writeFileSync(f.verifier, 'process.exit(0);');
40
+ await assert.rejects(runEval({ ...f.base, mode, skillInstallDir: 'project-skills',
41
+ ...(mode === 'installed' ? { baselineSkillPath: f.old } : {}),
42
+ ...(mode !== 'trigger' ? { judgeExecutor: f.judge, maxCalls: 4 } : {}) }), error => {
43
+ assert.ok(error instanceof CasePreflightFailed);
44
+ assert.equal(error.preflight.status, 'blocked');
45
+ assert.ok(error.preflight.checks.some(c => c.code === 'UNTOUCHED_FIXTURE' && c.status === 'FAIL' && c.evidence?.exitCode === 0));
46
+ assert.match(error.message, /already passes/);
47
+ assert.match(error.message, /Remedy:/);
48
+ return true;
49
+ });
50
+ assert.equal(f.calls(), 0);
51
+ assert.equal(f.judges(), 0);
52
+ assert.ok(!existsSync(f.base.runsRoot));
53
+ });
54
+ test('missing/empty output, unspawnable verifiers and failed oracles are hard gates with process evidence', async (t) => {
55
+ for (const issue of ['missing', 'empty', 'spawn', 'oracle-process', 'oracle-verifier'])
56
+ await t.test(issue, async (t) => {
57
+ const f = await setup(t, issue === 'missing' || issue === 'empty' ? 'output' : 'command');
58
+ let code;
59
+ if (issue === 'missing' || issue === 'empty') {
60
+ delete f.raw.tasks[0].oracle;
61
+ writeFileSync(f.verifier, issue === 'missing' ? 'process.exit(0);' :
62
+ "import{existsSync}from'node:fs';import{join}from'node:path';process.exit(existsSync(join(process.argv[2],'_output.md'))?0:1);");
63
+ code = issue === 'missing' ? 'MISSING_OUTPUT' : 'EMPTY_OUTPUT';
64
+ }
65
+ else if (issue === 'spawn') {
66
+ f.raw.tasks[0].verifier = 'skillfit-no-such-verifier';
67
+ code = 'UNTOUCHED_FIXTURE';
68
+ }
69
+ else {
70
+ writeFileSync(f.oracle, issue === 'oracle-process' ? "console.error('reference failed');process.exit(7);" : 'process.exit(0);');
71
+ code = 'ORACLE';
72
+ }
73
+ f.save();
74
+ await assert.rejects(runEval(f.base), error => {
75
+ assert.ok(error instanceof CasePreflightFailed);
76
+ const check = error.preflight.checks.find(c => c.code === code && c.status === 'FAIL');
77
+ assert.ok(check?.evidence);
78
+ assert.ok(check.remediation);
79
+ assert.equal(check.taskId, 'example-task');
80
+ if (issue === 'spawn') {
81
+ assert.equal(check.evidence.exitCode, null);
82
+ assert.ok(check.evidence.error);
83
+ }
84
+ if (issue === 'oracle-process') {
85
+ assert.equal(check.evidence.exitCode, 7);
86
+ assert.match(check.evidence.output, /reference failed/);
87
+ }
88
+ assert.equal(componentError(error).error.code, 'CASE_PREFLIGHT_FAILED');
89
+ return true;
90
+ });
91
+ assert.equal(f.calls(), 0);
92
+ assert.ok(!existsSync(f.base.runsRoot));
93
+ });
94
+ });
95
+ test('warnings and unknown coverage are distinct, nonblocking and frozen for offline reporting', async (t) => {
96
+ const f = await setup(t);
97
+ delete f.raw.tasks[0].oracle;
98
+ f.raw.tasks[0].shouldTrigger = true;
99
+ f.save();
100
+ writeFileSync(join(f.bench, 'fixtures/example-task/large.txt'), 'x'.repeat(66 * 1024));
101
+ const lines = [];
102
+ await runEval({ ...f.base, log: line => lines.push(line) });
103
+ assert.equal(f.calls(), 2);
104
+ const run = join(f.base.runsRoot, f.base.runGroup), report = read(join(run, '_plan.json')).details.casePreflight;
105
+ assert.equal(report.status, 'ready');
106
+ assert.equal(report.summary.failures, 0);
107
+ assert.ok(report.summary.warnings >= 2);
108
+ assert.ok(report.summary.unknown >= 2);
109
+ for (const [code, status] of [['ORACLE', 'UNKNOWN'], ['LIVE_DIFFICULTY', 'UNKNOWN'], ['FIXTURE_SIZE', 'WARN'], ['NEGATIVE_CONTROLS', 'WARN'], ['MOCK_COVERAGE', 'INFO']]) {
110
+ assert.equal(report.checks.find((c) => c.code === code).status, status);
111
+ }
112
+ assert.equal(report.cost.modelCalls, 0);
113
+ assert.ok(report.cost.durationMs >= 0);
114
+ assert.match(lines.join('\n'), /\[UNKNOWN\] ORACLE/);
115
+ assert.match(lines.join('\n'), /\[WARN\] FIXTURE_SIZE/);
116
+ const saved = await reportEvalComponent(run, { replay: true });
117
+ assert.ok('casePreflight' in saved);
118
+ assert.deepEqual(saved.casePreflight, report);
119
+ assert.equal(saved.acceptance.eligibleForUpgrade, false);
120
+ assert.equal(f.calls(), 2);
121
+ });
122
+ test('only selected tasks are probed; trigger mode also skips unlabelled tasks', async (t) => {
123
+ for (const trigger of [false, true])
124
+ await t.test(String(trigger), async (t) => {
125
+ const f = await setup(t);
126
+ writeFileSync(join(f.bench, 'verifiers/unselected.mjs'), "console.log('must not be probed');process.exit(0);");
127
+ f.raw.tasks.push({ ...f.raw.tasks[0], id: 'unselected', verifier: 'node verifiers/unselected.mjs' });
128
+ if (trigger)
129
+ f.raw.tasks[0].shouldTrigger = true;
130
+ f.save();
131
+ await runEval({ ...f.base, ...(trigger ? { mode: 'trigger', skillInstallDir: 'skills', maxCalls: 1,
132
+ executor: { describe: () => ({ kind: 'cli', model: 'offline-trigger' }),
133
+ run: async (...args) => ({ ...await f.base.executor.run(...args), skillTriggered: true }) } } : { taskIds: ['example-task'] }) });
134
+ const report = read(join(f.base.runsRoot, f.base.runGroup, '_plan.json')).details.casePreflight;
135
+ assert.deepEqual(report.bench.taskIds, ['example-task']);
136
+ assert.ok(!report.checks.some((c) => c.taskId === 'unselected'));
137
+ assert.equal(f.calls(), trigger ? 1 : 2);
138
+ });
139
+ });
140
+ test('dry-run stays side-effect-free and declares pending preflight rather than claiming checks passed', async (t) => {
141
+ const f = await setup(t), sentinel = join(f.root, 'probe-started');
142
+ writeFileSync(f.verifier, `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(0);`);
143
+ await runEval({ ...f.base, dryRun: true, onPlan: plan => {
144
+ assert.deepEqual(plan.casePreflight, { schemaVersion: 1, scope: 'offline-case-integrity', required: true, status: 'pending' });
145
+ } });
146
+ assert.equal(f.calls(), 0);
147
+ assert.ok(!existsSync(sentinel));
148
+ assert.ok(!existsSync(f.base.runsRoot));
149
+ });
150
+ test('missing mock coverage is unknown; malformed markers and overflowing mock probes block evaluation', async (t) => {
151
+ for (const issue of ['absent', 'omitted-arm', 'malformed', 'overflow-probe'])
152
+ await t.test(issue, async (t) => {
153
+ const f = await setup(t, 'output'), marker = join(f.bench, 'fixtures/example-task/.skillfit-mock.json');
154
+ if (issue === 'absent')
155
+ rmSync(marker);
156
+ else if (issue === 'omitted-arm')
157
+ writeFileSync(marker, '{}');
158
+ else if (issue === 'malformed')
159
+ writeFileSync(marker, '{');
160
+ else {
161
+ const source = readFileSync(f.verifier, 'utf8');
162
+ 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);
163
+ writeFileSync(marker, JSON.stringify({ baseline: { output: 'overflow' } }));
164
+ }
165
+ if (issue === 'malformed' || issue === 'overflow-probe') {
166
+ await assert.rejects(runEval(f.base), error => {
167
+ assert.ok(error instanceof CasePreflightFailed);
168
+ assert.ok(error.preflight.checks.some(c => c.code === (issue === 'malformed' ? 'MOCK_MARKER' : 'MOCK_BASELINE') && c.status === 'FAIL'));
169
+ return true;
170
+ });
171
+ assert.equal(f.calls(), 0);
172
+ assert.ok(!existsSync(f.base.runsRoot));
173
+ }
174
+ else {
175
+ await runEval(f.base);
176
+ const report = read(join(f.base.runsRoot, f.base.runGroup, '_plan.json')).details.casePreflight;
177
+ assert.equal(report.checks.find((c) => c.code === (issue === 'absent' ? 'MOCK_COVERAGE' : 'MOCK_BASELINE')).status, 'UNKNOWN');
178
+ assert.equal(f.calls(), 2);
179
+ }
180
+ });
181
+ });
182
+ test('existing run groups are rejected before executing any offline probe or overwriting evidence', async (t) => {
183
+ const f = await setup(t), run = join(f.base.runsRoot, f.base.runGroup), sentinel = join(f.root, 'probe-started');
184
+ mkdirSync(run, { recursive: true });
185
+ writeFileSync(join(run, 'kept'), 'original');
186
+ writeFileSync(f.verifier, `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(0);`);
187
+ await assert.rejects(runEval(f.base), /already exists/);
188
+ assert.equal(readFileSync(join(run, 'kept'), 'utf8'), 'original');
189
+ assert.ok(!existsSync(sentinel));
190
+ assert.equal(f.calls(), 0);
191
+ });
192
+ test('probe mutations of bench or either Skill cannot silently change the approved inputs', async (t) => {
193
+ for (const which of ['bench', 'candidate', 'baseline'])
194
+ await t.test(which, async (t) => {
195
+ const f = await setup(t);
196
+ const target = which === 'bench' ? join(f.bench, 'prompts/example-task.md') : join(which === 'candidate' ? f.skill : f.old, 'SKILL.md');
197
+ writeFileSync(f.verifier, `import{appendFileSync}from'node:fs';appendFileSync(${JSON.stringify(target)},'changed');process.exit(1);`);
198
+ delete f.raw.tasks[0].oracle;
199
+ f.save();
200
+ await assert.rejects(runEval({ ...f.base, mode: 'installed', baselineSkillPath: f.old, skillInstallDir: 'skills' }), error => {
201
+ assert.ok(error instanceof CasePreflightFailed);
202
+ assert.ok(error.preflight.checks.some(c => c.code === 'INPUT_CHANGED' && c.status === 'FAIL'));
203
+ return true;
204
+ });
205
+ assert.equal(f.calls(), 0);
206
+ assert.ok(!existsSync(f.base.runsRoot));
207
+ });
208
+ });
209
+ test('request preflight failures produce JSON-only per-case diagnostics without starting an agent CLI', async (t) => {
210
+ const f = await setup(t);
211
+ writeFileSync(f.verifier, 'process.exit(0);');
212
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url)), request = join(f.root, 'request.json');
213
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, baselineSkill: f.old, candidateSkill: f.skill,
214
+ bench: f.bench, agent: 'codex', purpose: 'development', trials: 1, maxCalls: 2, runsRoot: f.base.runsRoot, runGroup: f.base.runGroup }));
215
+ // Shadow the real agent even if the gate regresses; this test cannot reach it.
216
+ const bin = join(f.root, 'bin'), sentinel = join(f.root, 'fake-agent-started');
217
+ mkdirSync(bin);
218
+ const fake = join(bin, process.platform === 'win32' ? 'codex.cmd' : 'codex');
219
+ writeFileSync(fake, process.platform === 'win32' ? `@echo offline>"${sentinel}"\r\n@exit /b 1\r\n` :
220
+ `#!${process.execPath}\nimport{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(1);\n`);
221
+ chmodSync(fake, 0o755);
222
+ const invoke = (args) => spawnSync(process.execPath, [cli, 'eval', '--request', request, ...args], {
223
+ encoding: 'utf8', timeout: 20_000, env: { ...process.env, PATH: `${bin}${delimiter}${process.env.PATH ?? ''}` }
224
+ });
225
+ const preview = invoke(['--dry-run']);
226
+ assert.equal(preview.status, 0, preview.stderr);
227
+ const plan = JSON.parse(preview.stdout).plan;
228
+ const executed = invoke(['--yes', '--plan-sha', plan.sha256]);
229
+ assert.equal(executed.status, 2, executed.stderr);
230
+ assert.match(executed.stderr, /Case preflight: blocked/);
231
+ const result = JSON.parse(executed.stdout);
232
+ assert.equal(result.error.code, 'CASE_PREFLIGHT_FAILED');
233
+ assert.equal(result.casePreflight.status, 'blocked');
234
+ assert.ok(result.casePreflight.checks.some((c) => c.code === 'UNTOUCHED_FIXTURE' && c.status === 'FAIL'));
235
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
236
+ assert.equal(result.acceptance.automaticUpgrade, false);
237
+ assert.ok(!existsSync(f.base.runsRoot));
238
+ assert.ok(!existsSync(sentinel));
239
+ });
@@ -1,5 +1,4 @@
1
1
  import { readFileSync, statSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
2
  import { CONCLUSIVE_TASKS, CONCLUSIVE_TRIALS, formatP, formatPp1, verdictFor } from '../harness/report.js';
4
3
  import { mcnemarExactP } from '../harness/stats.js';
5
4
  import { validateSkillInstallDir } from '../harness/installed-skill.js';
@@ -593,16 +592,48 @@ export function renderEvalMarkdown(report) {
593
592
  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
593
  return lines.join('\n');
595
594
  }
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)));
595
+ export async function runEvalReport(inputPath, log = console.log, options = {}) {
596
+ // Import after module initialization: component assessment itself uses this
597
+ // module's manifest parser. Both CLI formats must share the same assessment.
598
+ const { reportEvalComponent } = await import('./eval-component.js');
599
+ const result = await reportEvalComponent(inputPath, options);
600
+ const root = result.evidence.runDir;
601
+ const safe = (message) => escapeMarkdown(message.replaceAll(root, '[run]'));
602
+ const lines = [];
603
+ if (result.manifest) {
604
+ const path = result.manifest.path;
605
+ if (statSync(path).size > MAX_MANIFEST_BYTES)
606
+ throw new Error(`Evaluation manifest exceeds ${MAX_MANIFEST_BYTES} bytes`);
607
+ lines.push(renderEvalMarkdown(parseEvalReport(JSON.parse(readFileSync(path, 'utf8')))));
608
+ }
609
+ else {
610
+ lines.push(`# skillfit evaluation: ${result.status} run`, '', `- State: ${result.status}`, '- No completed paired comparison is available. Retained spending is not a quality verdict.');
611
+ if (result.session?.stopReason)
612
+ lines.push(`- Stop reason: ${safe(String(result.session.stopReason))}`);
613
+ if ('startedAgentDispatches' in result.costs)
614
+ lines.push(`- Started agent dispatches: ${result.costs.startedAgentDispatches}`, `- Missing or invalid invocation receipts: ${result.costs.invocationsWithUnknownReceipts}`);
615
+ lines.push('', '## Retained costs', '', ...renderCostLines(result.costs.populations));
616
+ }
617
+ 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');
618
+ for (const reason of result.acceptance.reasons)
619
+ lines.push(`- ${reason.code}: ${safe(reason.message)}`);
620
+ for (const reason of result.evidence.reasons)
621
+ lines.push(`- Audit: ${safe(reason)}`);
622
+ if (result.casePreflight) {
623
+ const gate = result.casePreflight;
624
+ 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)) {
625
+ lines.push(`- Case preflight: ${safe(gate.status)}; ${gate.summary.failures} failure(s), ${gate.summary.warnings} warning(s), ${gate.summary.unknown} unknown(s)`);
626
+ }
627
+ else
628
+ lines.push('- Case preflight: invalid or unavailable metadata; inspect the unverified JSON record.');
629
+ }
630
+ if (result.inputSnapshot) {
631
+ const archive = result.inputSnapshot;
632
+ if (archive.cost && [archive.cost.files, archive.cost.bytes, archive.cost.durationMs].every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)) {
633
+ lines.push(`- Sealed input cost: ${archive.cost.files} files; ${archive.cost.bytes} bytes; ${archive.cost.durationMs}ms local sealing; 0 model calls`);
634
+ }
635
+ else
636
+ lines.push('- Sealed input cost: invalid or unavailable metadata; no copy-cost total inferred.');
637
+ }
638
+ log(lines.join('\n') + '\n');
608
639
  }
@@ -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] ?? '';
@@ -19,6 +19,9 @@ import { installedUserSkills } from '../harness/receipts.js';
19
19
  import { collectEvaluationTarget } from '../harness/target.js';
20
20
  import { renderTriggerSummary, runTriggerExperiment, } from '../harness/trigger.js';
21
21
  import { parseSpendingBudget } from '../harness/eval-budget.js';
22
+ import { withEvaluationInterrupts, throwIfEvaluationInterrupted } from '../harness/interruption.js';
23
+ import { CASE_PREFLIGHT_POLICY, checkEvalCases } from './eval-preflight.js';
24
+ import { INPUT_SNAPSHOT_POLICY } from '../harness/input-snapshot.js';
22
25
  export const DEFAULT_EVAL_TRIALS = 5;
23
26
  function bundledBenchesRoot() {
24
27
  return fileURLToPath(new URL('../../benches', import.meta.url));
@@ -235,6 +238,7 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
235
238
  : `Compete : ${competitors.map((entry) => entry.name).join(', ')}`;
236
239
  if (options.dryRun) {
237
240
  log(renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, installDir));
241
+ log('Case preflight: pending; required before execution. Dry run does not execute verifiers or oracles.');
238
242
  log(competeLine);
239
243
  log(`Calls : ${plannedCalls} planned; ceiling ${maxCalls} (agent calls only)`);
240
244
  return null;
@@ -245,32 +249,40 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
245
249
  if (!installDir) {
246
250
  throw new Error('trigger mode needs a skill install directory: pass --agent (the matrix provides one) or skillInstallDir.');
247
251
  }
248
- log(renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, installDir).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
249
- log(competeLine);
250
- const session = sessionFor(options, bench, skill, trials, runsRoot, runGroup, ['installed'], plannedCalls, { mode: 'trigger', trials, executor: executor.describe() });
251
- let manifest;
252
- try {
253
- manifest = await runTriggerExperiment({
254
- bench,
255
- skill,
256
- executor: session.wrap(executor, 'agent'),
257
- session,
258
- trials,
259
- runsRoot,
260
- runGroup,
261
- skillInstallDir: installDir,
262
- competitors,
263
- detection,
264
- log,
265
- });
266
- }
267
- catch (error) {
268
- session.finish(error);
269
- throw error;
270
- }
271
- session.finish(undefined, manifest);
272
- log(renderTriggerSummary(manifest, join(runsRoot, runGroup, 'manifest.json')));
273
- return manifest;
252
+ return withEvaluationInterrupts(async () => {
253
+ if (existsSync(join(runsRoot, runGroup)))
254
+ throw new Error(`Run group directory already exists: ${join(runsRoot, runGroup)}`);
255
+ const eligible = { ...bench, tasks: bench.tasks.filter(t => t.shouldTrigger !== undefined) };
256
+ const casePreflight = await checkEvalCases(eligible, [skill], false, log);
257
+ throwIfEvaluationInterrupted();
258
+ log(renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, installDir).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
259
+ log(competeLine);
260
+ const session = sessionFor(options, bench, skill, trials, runsRoot, runGroup, ['installed'], plannedCalls, { mode: 'trigger', trials, executor: executor.describe(), casePreflight });
261
+ let manifest;
262
+ try {
263
+ manifest = await runTriggerExperiment({
264
+ bench,
265
+ skill,
266
+ executor: session.wrap(executor, 'agent'),
267
+ session,
268
+ trials,
269
+ runsRoot,
270
+ runGroup,
271
+ skillInstallDir: installDir,
272
+ competitors,
273
+ detection,
274
+ log,
275
+ });
276
+ throwIfEvaluationInterrupted();
277
+ }
278
+ catch (error) {
279
+ session.finish(error);
280
+ throw error;
281
+ }
282
+ session.finish(undefined, manifest);
283
+ log(renderTriggerSummary(manifest, join(runsRoot, runGroup, 'manifest.json')));
284
+ return manifest;
285
+ });
274
286
  }
275
287
  export async function runEval(options) {
276
288
  if (options.spendingBudget !== undefined && options.mode === 'trigger')
@@ -390,6 +402,8 @@ export async function runEval(options) {
390
402
  if (!RUN_GROUP_PATTERN.test(runGroup))
391
403
  throw new Error(`Invalid run group: ${runGroup}`);
392
404
  options.onPlan?.({
405
+ casePreflight: { ...CASE_PREFLIGHT_POLICY, status: 'pending' },
406
+ inputSnapshot: { ...INPUT_SNAPSHOT_POLICY },
393
407
  target: { name: target.name, sourceDir: target.sourceDir, sha256: target.sha256, files: target.files },
394
408
  baseline: baselineTarget ? { name: baselineTarget.name, sourceDir: baselineTarget.sourceDir, sha256: baselineTarget.sha256, files: baselineTarget.files } : null,
395
409
  bench: { name: bench.name, dir: bench.dir, sha256: bench.contentSha256, taskIds: bench.tasks.map(t => t.id) },
@@ -401,6 +415,7 @@ export async function runEval(options) {
401
415
  });
402
416
  if (options.dryRun) {
403
417
  log(renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup, inputMode, baselineTarget));
418
+ log('Case preflight: pending; required before execution. Dry run does not execute verifiers or oracles.');
404
419
  log(`Calls : ${plannedCalls} planned; ceiling ${maxCalls} (includes both judge orders when enabled)`);
405
420
  log(`Pair order: ${pairOrder}; arms remain adjacent`);
406
421
  if (spendingBudget)
@@ -417,38 +432,45 @@ export async function runEval(options) {
417
432
  if (!executor) {
418
433
  throw new Error('No executor available; pass --agent or set SKILLFIT_API_KEY.');
419
434
  }
420
- log(renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup, inputMode, baselineTarget).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
421
- const session = sessionFor(options, bench, target, trials, runsRoot, runGroup, ['baseline', 'treatment'], plannedCalls, { mode: installed ? 'installed' : 'inject', inputMode, trials, pairOrder,
422
- ...(spendingBudget ? { spendingBudget } : {}),
423
- ...(installed ? { nativeDiffTool: nativeDiffDescriptor() } : {}),
424
- ...(options.agent || options.executorTimeoutSeconds !== undefined ? { executorTimeoutSeconds } : {}), executor: executor.describe(), judge: judge?.describe() ?? null,
425
- ...(options.component ? { component: options.component } : {}),
426
- ...(baselineTarget ? { baselineTarget: { name: baselineTarget.name, sourceDir: baselineTarget.sourceDir, bundleSha256: baselineTarget.sha256, files: baselineTarget.files } } : {}) }, baselineTarget);
427
- let manifest;
428
- try {
429
- manifest = await runExperiment({
430
- bench,
431
- target,
432
- baselineTarget,
433
- component: options.component,
434
- pairOrder,
435
+ return withEvaluationInterrupts(async () => {
436
+ if (existsSync(join(runsRoot, runGroup)))
437
+ throw new Error(`Run group directory already exists: ${join(runsRoot, runGroup)}`);
438
+ const casePreflight = await checkEvalCases(bench, [target, ...(baselineTarget ? [baselineTarget] : [])], installed, log);
439
+ throwIfEvaluationInterrupted();
440
+ log(renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup, inputMode, baselineTarget).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
441
+ const session = sessionFor(options, bench, target, trials, runsRoot, runGroup, ['baseline', 'treatment'], plannedCalls, { mode: installed ? 'installed' : 'inject', inputMode, trials, pairOrder, casePreflight,
435
442
  ...(spendingBudget ? { spendingBudget } : {}),
436
- inputMode,
437
- ...(skillInstallDir ? { skillInstallDir, skillSearchDirs } : {}),
438
- executor: session.wrap(executor, 'agent'),
439
- judge: judge ? session.wrap(judge, 'judge') : null,
440
- session,
441
- trials,
442
- runsRoot,
443
- runGroup,
444
- log,
445
- });
446
- }
447
- catch (error) {
448
- session.finish(error);
449
- throw error;
450
- }
451
- session.finish(undefined, manifest);
452
- log(renderSummary(manifest, join(runsRoot, runGroup, 'manifest.json')));
453
- return manifest;
443
+ ...(installed ? { nativeDiffTool: nativeDiffDescriptor() } : {}),
444
+ ...(options.agent || options.executorTimeoutSeconds !== undefined ? { executorTimeoutSeconds } : {}), executor: executor.describe(), judge: judge?.describe() ?? null,
445
+ ...(options.component ? { component: options.component } : {}),
446
+ ...(baselineTarget ? { baselineTarget: { name: baselineTarget.name, sourceDir: baselineTarget.sourceDir, bundleSha256: baselineTarget.sha256, files: baselineTarget.files } } : {}) }, baselineTarget);
447
+ let manifest;
448
+ try {
449
+ manifest = await runExperiment({
450
+ bench,
451
+ target,
452
+ baselineTarget,
453
+ component: options.component,
454
+ pairOrder,
455
+ ...(spendingBudget ? { spendingBudget } : {}),
456
+ inputMode,
457
+ ...(skillInstallDir ? { skillInstallDir, skillSearchDirs } : {}),
458
+ executor: session.wrap(executor, 'agent'),
459
+ judge: judge ? session.wrap(judge, 'judge') : null,
460
+ session,
461
+ trials,
462
+ runsRoot,
463
+ runGroup,
464
+ log,
465
+ });
466
+ throwIfEvaluationInterrupted();
467
+ }
468
+ catch (error) {
469
+ session.finish(error);
470
+ throw error;
471
+ }
472
+ session.finish(undefined, manifest);
473
+ log(renderSummary(manifest, join(runsRoot, runGroup, 'manifest.json')));
474
+ return manifest;
475
+ });
454
476
  }
@@ -14,6 +14,7 @@ import { parseEvalReport } from '../commands/eval-report.js';
14
14
  import { pairConditions } from './types.js';
15
15
  import { NATIVE_DIFF_PATH, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
16
16
  import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
17
+ import { verifyInputSnapshot } from './input-snapshot.js';
17
18
  function inside(root, path) {
18
19
  const rel = relative(root, path);
19
20
  return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
@@ -99,6 +100,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
99
100
  assert.equal(index.planSha256, report.experiment.planSha256);
100
101
  assert.deepEqual(readComponentJson(join(root, '_session.json')).value, report.experiment);
101
102
  const plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
103
+ const inputSnapshot = verifyInputSnapshot(root, plan);
102
104
  const details = record(plan.details, 'native plan details');
103
105
  let pairOrder = null;
104
106
  if (raw.pairOrder !== undefined || details.pairOrder !== undefined) {
@@ -139,7 +141,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
139
141
  const all = { baseline: [], treatment: [] }, paired = { baseline: [], treatment: [] };
140
142
  if (details.taskIds !== undefined)
141
143
  assert.deepEqual(details.taskIds, report.tasks.map(task => task.id), 'Selected task IDs differ from the frozen plan.');
142
- const bench = options.replay ? loadBench(options.benchDir ?? String(record(raw.bench, 'bench').dir)) : null;
144
+ const bench = options.replay ? loadBench(options.benchDir ?? inputSnapshot?.roots.get('bench') ?? String(record(raw.bench, 'bench').dir)) : null;
143
145
  if (bench)
144
146
  assert.equal(bench.contentSha256, report.bench.sha256, 'Replay bench differs from the frozen task set.');
145
147
  let invoked = 0;
@@ -47,7 +47,7 @@ function setup(t, change = {}, result, functionalFailure = false) {
47
47
  mkdirSync(join(bench, 'fixture'), { recursive: true });
48
48
  writeFileSync(join(bench, 'fixture/answer.txt'), 'pending');
49
49
  writeFileSync(join(bench, 'prompt.md'), 'Repair the answer.');
50
- writeFileSync(join(bench, 'check.mjs'), `const passed=${!functionalFailure};console.log(JSON.stringify({passed,checks:[{name:'answer',pass:passed}]}));process.exit(passed?0:1);\n`);
50
+ writeFileSync(join(bench, 'check.mjs'), `import{readFileSync}from'node:fs';import{join}from'node:path';const passed=readFileSync(join(process.argv[2],'answer.txt'),'utf8')==='fixed';console.log(JSON.stringify({passed,checks:[{name:'answer',pass:passed}]}));process.exit(passed?0:1);\n`);
51
51
  writeFileSync(join(bench, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'budget', tasks: [
52
52
  { id: 'first', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs', verifierKind: 'command' },
53
53
  { id: 'second', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs', verifierKind: 'command' },
@@ -57,7 +57,9 @@ function setup(t, change = {}, result, functionalFailure = false) {
57
57
  const request = join(root, 'request.json');
58
58
  writeFileSync(request, JSON.stringify(body));
59
59
  let count = 0;
60
- const executor = { describe: () => ({ kind: 'mock', model: 'offline-budget' }), run: async () => {
60
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-budget' }), run: async (_prompt, workdir) => {
61
+ if (!functionalFailure)
62
+ writeFileSync(join(workdir, 'answer.txt'), 'fixed');
61
63
  count++;
62
64
  return result ? result() : { output: 'done', tokens: { input: 10, cachedInput: 6, output: 3 } };
63
65
  } };
@@ -68,15 +68,15 @@ test('component exports include the frozen request and both complete Skills and
68
68
  const f = await run(t), output = join(f.root, 'portable');
69
69
  const originalRequest = readFileSync(f.requestPath, 'utf8');
70
70
  writeFileSync(f.requestPath, '{}');
71
- await assert.rejects(() => exportEvaluation(f.runDir, output, { yes: true, log: () => { } }), /request changed/);
72
- const recovered = join(f.root, 'recovered-request.json');
73
- writeFileSync(recovered, originalRequest);
74
- await exportEvaluation(f.runDir, output, { yes: true, inputRoots: [`request=${recovered}`], log: () => { } });
71
+ for (const path of ['bench', 'old', 'new'])
72
+ rmSync(join(f.root, path), { recursive: true });
73
+ const nativeReplay = await reportEvalComponent(f.runDir, { replay: true });
74
+ assert.ok('evidence' in nativeReplay && nativeReplay.evidence.verified);
75
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
75
76
  assert.equal(readFileSync(join(output, 'inputs/request.json'), 'utf8'), originalRequest);
76
77
  assert.equal(readFileSync(join(output, 'inputs/baseline-skill/answer.txt'), 'utf8'), '1');
77
78
  assert.equal(readFileSync(join(output, 'inputs/target/answer.txt'), 'utf8'), '2');
78
- for (const path of ['bench', 'old', 'new', 'runs'])
79
- rmSync(join(f.root, path), { recursive: true });
79
+ rmSync(join(f.root, 'runs'), { recursive: true });
80
80
  const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
81
81
  assert.equal(child.status, 0, child.stderr);
82
82
  const replay = JSON.parse(child.stdout);
@@ -1,3 +1,4 @@
1
+ import { evaluationSignal } from '../interruption.js';
1
2
  function tokenCount(value) {
2
3
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
3
4
  }
@@ -6,11 +7,17 @@ function tokenUsage(usage) {
6
7
  return undefined;
7
8
  const input = tokenCount(usage.prompt_tokens);
8
9
  const output = tokenCount(usage.completion_tokens);
10
+ const details = usage.prompt_tokens_details;
11
+ const cached = details && typeof details === 'object' && !Array.isArray(details)
12
+ ? tokenCount(details.cached_tokens) : undefined;
13
+ const cachedInput = input !== undefined && Number.isSafeInteger(input) && cached !== undefined && Number.isSafeInteger(cached) && cached <= input
14
+ ? cached : undefined;
9
15
  if (input === undefined && output === undefined)
10
16
  return undefined;
11
17
  return {
12
18
  ...(input !== undefined ? { input } : {}),
13
19
  ...(output !== undefined ? { output } : {}),
20
+ ...(cachedInput !== undefined ? { cachedInput } : {}),
14
21
  };
15
22
  }
16
23
  const DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
@@ -41,6 +48,8 @@ export class ApiExecutor {
41
48
  return { kind: 'api', model: this.model, detail: this.baseUrl, sampling: null };
42
49
  }
43
50
  async run(prompt, _workdir) {
51
+ const interrupted = evaluationSignal();
52
+ interrupted?.throwIfAborted();
44
53
  const response = await this.fetchImpl(`${this.baseUrl}/chat/completions`, {
45
54
  method: 'POST',
46
55
  headers: {
@@ -51,7 +60,7 @@ export class ApiExecutor {
51
60
  model: this.model,
52
61
  messages: [{ role: 'user', content: prompt }],
53
62
  }),
54
- signal: AbortSignal.timeout(this.timeoutMs),
63
+ signal: interrupted ? AbortSignal.any([interrupted, AbortSignal.timeout(this.timeoutMs)]) : AbortSignal.timeout(this.timeoutMs),
55
64
  });
56
65
  if (!response.ok) {
57
66
  const body = (await response.text()).slice(0, 300);