skillfit 0.10.1 → 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 (87) hide show
  1. package/README.md +18 -6
  2. package/README.zh-CN.md +18 -6
  3. package/benches/README.md +2 -2
  4. package/dist/cli.js +132 -28
  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 +63 -143
  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 +52 -28
  14. package/dist/commands/eval-export-modes.test.js +350 -0
  15. package/dist/commands/eval-export.js +12 -4
  16. package/dist/commands/eval-plan.js +37 -0
  17. package/dist/commands/eval-preflight.test.js +144 -1
  18. package/dist/commands/eval-report.js +18 -3
  19. package/dist/commands/eval-single-arm-replay.js +21 -0
  20. package/dist/commands/eval-single-arm-report.js +223 -0
  21. package/dist/commands/eval.js +106 -56
  22. package/dist/commands/evaluation-report.js +5 -0
  23. package/dist/commands/evaluation-report.test.js +243 -0
  24. package/dist/commands/replay-cancellation.test.js +105 -0
  25. package/dist/commands/workflow-entrypoints.test.js +137 -0
  26. package/dist/harness/agent-preflight.js +180 -0
  27. package/dist/harness/bench.js +2 -1
  28. package/dist/harness/command.js +49 -0
  29. package/dist/harness/eval-audit.js +161 -16
  30. package/dist/harness/eval-budget.js +46 -2
  31. package/dist/harness/eval-budget.test.js +26 -1
  32. package/dist/harness/eval-component.test.js +163 -0
  33. package/dist/harness/eval-contract.js +11 -5
  34. package/dist/harness/executors/api.js +4 -3
  35. package/dist/harness/executors/api.test.js +18 -0
  36. package/dist/harness/experiment-session.js +18 -10
  37. package/dist/harness/experiment-session.test.js +8 -0
  38. package/dist/harness/invocation-costs.js +72 -0
  39. package/dist/harness/judge-accounting.test.js +216 -0
  40. package/dist/harness/judge-audit.js +56 -0
  41. package/dist/harness/judge.js +86 -21
  42. package/dist/harness/replay-package.js +71 -5
  43. package/dist/harness/runner.js +40 -30
  44. package/dist/harness/runner.test.js +23 -0
  45. package/dist/harness/single-arm-audit.js +436 -0
  46. package/dist/harness/trigger.js +21 -3
  47. package/dist/harness/trigger.test.js +12 -0
  48. package/dist/harness/verifier-error.js +65 -0
  49. package/dist/harness/verifier.test.js +128 -0
  50. package/docs/bench-authoring.md +34 -9
  51. package/docs/bench-check-json.md +28 -5
  52. package/docs/eval-agent-preflight.md +101 -0
  53. package/docs/eval-case-preflight.md +5 -0
  54. package/docs/eval-component.md +38 -10
  55. package/docs/eval-costs.md +44 -0
  56. package/docs/eval-planning.md +153 -0
  57. package/docs/evaluation-input-snapshots.md +2 -1
  58. package/docs/evaluation-interruption.md +22 -10
  59. package/docs/evaluation-reports.md +97 -3
  60. package/docs/experiment-workflow.md +7 -0
  61. package/docs/first-real-eval.md +50 -3
  62. package/docs/growth-roadmap-2026-10.md +41 -9
  63. package/docs/metrics.md +40 -3
  64. package/docs/plans/2026-10-17-workflow-foundations.md +64 -0
  65. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  66. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  67. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  68. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  69. package/docs/releases/0.10.1-signatures.txt +7 -0
  70. package/docs/releases/0.10.1-verification.json +90 -0
  71. package/docs/releases/0.10.1.md +37 -4
  72. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  73. package/docs/releases/0.11.0.md +47 -0
  74. package/docs/replay-packages.md +38 -6
  75. package/docs/schemas/agent-preflight.schema.json +31 -0
  76. package/docs/schemas/calibration-plan.schema.json +22 -0
  77. package/docs/schemas/calibration-result.schema.json +17 -0
  78. package/docs/schemas/eval-request.schema.json +1 -1
  79. package/docs/schemas/eval-result.schema.json +3 -1
  80. package/docs/schemas/invocation-costs.schema.json +31 -0
  81. package/docs/schemas/judge-call.schema.json +22 -0
  82. package/docs/schemas/single-arm-report.schema.json +20 -0
  83. package/docs/schemas/verifier-error.schema.json +11 -0
  84. package/docs/sharing-results.md +3 -0
  85. package/docs/verifier-contract.md +99 -0
  86. package/package.json +1 -1
  87. package/skills/skillfit/SKILL.md +41 -8
@@ -0,0 +1,350 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { test } from 'node:test';
8
+ import { runBenchCheck, runBenchInit } from './bench.js';
9
+ import { runEval } from './eval.js';
10
+ import { exportEvaluation } from './eval-export.js';
11
+ import { readEvaluationReport } from './evaluation-report.js';
12
+ import { ExperimentSession } from '../harness/experiment-session.js';
13
+ import { loadBench } from '../harness/bench.js';
14
+ import { collectEvaluationTarget } from '../harness/target.js';
15
+ import { packageFiles, verifyReplayPackage } from '../harness/replay-package.js';
16
+ import { sha256File, sha256Text } from '../harness/hash.js';
17
+ import { createSpendingBudgetRecorder } from '../harness/eval-budget.js';
18
+ import { summarizeCosts } from '../harness/costs.js';
19
+ async function fixture(t, classified = true) {
20
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-export-modes-'));
21
+ t.after(() => rmSync(root, { recursive: true, force: true }));
22
+ const bench = join(root, 'bench'), skill = join(root, 'skill'), runsRoot = join(root, 'runs');
23
+ await runBenchInit({ dir: bench, yes: true, log: () => { } });
24
+ const file = join(bench, 'bench.json'), definition = JSON.parse(readFileSync(file, 'utf8'));
25
+ definition.tasks[0].shouldTrigger = true;
26
+ if (classified)
27
+ definition.tasks[0].triggerClass = 'explicit';
28
+ writeFileSync(file, JSON.stringify(definition));
29
+ mkdirSync(skill);
30
+ writeFileSync(join(skill, 'SKILL.md'), '# Offline export test\n');
31
+ let calls = 0;
32
+ const executor = { describe: () => ({ kind: 'stub', model: 'offline-only' }), run: async () => {
33
+ calls++;
34
+ return { output: 'skillfit-ok', skillTriggered: true, tokens: { input: 10, output: 3 }, usageStatus: 'partial' };
35
+ } };
36
+ return { root, bench, skill, runsRoot, executor, calls: () => calls };
37
+ }
38
+ function replay(root, verifyOnly = false) {
39
+ const result = spawnSync(process.execPath, [join(root, 'reproduce.mjs'), ...(verifyOnly ? ['--verify-only'] : [])], { encoding: 'utf8', timeout: 30_000, maxBuffer: 8 * 1024 * 1024 });
40
+ assert.equal(result.status, 0, result.stderr);
41
+ return JSON.parse(result.stdout);
42
+ }
43
+ function reseal(run) {
44
+ const index = JSON.parse(readFileSync(join(run, '_artifacts.json'), 'utf8'));
45
+ index.files = Object.fromEntries(packageFiles(run).filter(path => path !== '_artifacts.json').map(path => [path, sha256File(join(run, path))]));
46
+ writeFileSync(join(run, '_artifacts.json'), JSON.stringify(index));
47
+ }
48
+ function rewritePlan(run, change) {
49
+ const plan = JSON.parse(readFileSync(join(run, '_plan.json'), 'utf8'));
50
+ change(plan);
51
+ const bytes = JSON.stringify(plan, null, 2) + '\n', sha256 = sha256Text(bytes);
52
+ writeFileSync(join(run, '_plan.json'), bytes);
53
+ const session = JSON.parse(readFileSync(join(run, '_session.json'), 'utf8'));
54
+ session.planSha256 = sha256;
55
+ writeFileSync(join(run, '_session.json'), JSON.stringify(session));
56
+ const summaryName = plan.details.mode === 'calibration' ? '_calibration.json' : 'manifest.json';
57
+ const summary = JSON.parse(readFileSync(join(run, summaryName), 'utf8'));
58
+ summary.experiment = session;
59
+ writeFileSync(join(run, summaryName), JSON.stringify(summary));
60
+ const index = JSON.parse(readFileSync(join(run, '_artifacts.json'), 'utf8'));
61
+ index.planSha256 = sha256;
62
+ writeFileSync(join(run, '_artifacts.json'), JSON.stringify(index));
63
+ reseal(run);
64
+ }
65
+ test('calibration and trigger export/replay survive deleted inputs and retain single-arm observations, unknown cache and partial costs', async (t) => {
66
+ for (const variant of ['calibration', 'trigger', 'trigger-unclassified'])
67
+ await t.test(variant, async (t) => {
68
+ const mode = variant === 'calibration' ? 'calibration' : 'trigger';
69
+ const f = await fixture(t, variant !== 'trigger-unclassified'), run = join(f.runsRoot, mode), output = join(f.root, 'portable');
70
+ if (mode === 'calibration')
71
+ await runBenchCheck({ dir: f.bench, calibrate: { executor: f.executor, trials: 1, maxCalls: 1, runsRoot: f.runsRoot, runGroup: mode }, log: () => { } });
72
+ else
73
+ await runEval({ skillPath: f.skill, bench: f.bench, mode, skillInstallDir: '.test-skills', executor: f.executor, trials: 1, maxCalls: 1, runsRoot: f.runsRoot, runGroup: mode, dryRun: false, yes: true, log: () => { } });
74
+ const before = await readEvaluationReport(run);
75
+ assert.ok('evaluationType' in before && before.evaluationType === mode);
76
+ assert.equal(before.evidence.verified, true, JSON.stringify(before.evidence));
77
+ assert.equal(before.usage?.metrics.input.knownTotal, 10);
78
+ assert.equal(before.usage?.metrics.input.coverage.partial, 1);
79
+ assert.equal(before.usage?.metrics.cachedInput.coverage.unknown, 1);
80
+ const nativeFiles = packageFiles(run).map(file => [file, sha256File(join(run, file))]);
81
+ rmSync(f.bench, { recursive: true });
82
+ rmSync(f.skill, { recursive: true });
83
+ assert.equal((await exportEvaluation(run, output, { log: () => { } })).status, 'planned');
84
+ assert.equal(existsSync(output), false);
85
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
86
+ assert.deepEqual(packageFiles(run).map(file => [file, sha256File(join(run, file))]), nativeFiles, 'Native receipts and ledgers remain untouched.');
87
+ const moved = join(f.root, 'received offline package');
88
+ renameSync(output, moved);
89
+ rmSync(run, { recursive: true });
90
+ assert.equal(verifyReplayPackage(moved).evaluationType, mode);
91
+ assert.equal(replay(moved, true).modelCalls, 0);
92
+ const result = replay(moved);
93
+ assert.equal(result.evaluationType, mode);
94
+ assert.equal(result.evidence.verified, true);
95
+ assert.equal(result.evidence.replayedDeliveries, 1);
96
+ assert.deepEqual(result.summary, JSON.parse(JSON.stringify(before.summary)));
97
+ assert.deepEqual(result.usage, before.usage);
98
+ assert.equal(result.acceptance.decision, 'inconclusive');
99
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
100
+ assert.equal(result.acceptance.automaticUpgrade, false);
101
+ assert.equal(result.portableReplay.modelCalls, 0);
102
+ assert.equal(f.calls(), 1);
103
+ const inspected = await readEvaluationReport(moved);
104
+ assert.ok('portablePackage' in inspected && inspected.portablePackage.integrityVerified);
105
+ });
106
+ });
107
+ test('stopped single-arm exports preserve missing invocation receipt as unknown and never invent a summary', async (t) => {
108
+ for (const mode of ['calibration', 'trigger'])
109
+ await t.test(mode, async (t) => {
110
+ const f = await fixture(t), run = join(f.runsRoot, mode), arm = mode === 'calibration' ? 'baseline' : 'installed', workspace = join(run, 'example-task', arm, 'trial-1');
111
+ const session = new ExperimentSession({ bench: loadBench(f.bench), target: collectEvaluationTarget(f.skill), groupDir: run, workspaces: [workspace], plannedCalls: 1, maxCalls: 1, injected: true, details: { mode, trials: 1 } });
112
+ mkdirSync(workspace, { recursive: true });
113
+ const prompt = 'Saved invocation with a lost receipt';
114
+ writeFileSync(join(workspace, '_prompt.txt'), prompt);
115
+ await session.wrap(f.executor, 'agent').run(prompt, workspace);
116
+ session.finish(new Error('Synthetic interruption before receipt persistence'));
117
+ const before = await readEvaluationReport(run);
118
+ assert.ok('evaluationType' in before);
119
+ assert.equal(before.status, 'stopped');
120
+ assert.equal(before.summary, null);
121
+ assert.equal(before.evidence.verified, true, JSON.stringify(before.evidence));
122
+ assert.equal(before.usage?.invocationsWithUnknownReceipts, 1);
123
+ assert.equal(before.usage?.metrics.input.coverage.unknown, 1);
124
+ assert.equal(before.usage?.metrics.durationSeconds.coverage.unknown, 1);
125
+ const output = join(f.root, 'portable');
126
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
127
+ rmSync(f.bench, { recursive: true });
128
+ rmSync(f.skill, { recursive: true });
129
+ rmSync(run, { recursive: true });
130
+ const result = replay(output);
131
+ assert.equal(result.status, 'stopped');
132
+ assert.equal(result.summary, null);
133
+ assert.deepEqual(result.usage, before.usage);
134
+ assert.equal(result.evidence.replayedDeliveries, 0);
135
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
136
+ assert.equal(f.calls(), 1);
137
+ });
138
+ });
139
+ test('single-arm semantic audit rejects resealed wrong summary and changed local verdicts', async (t) => {
140
+ const f = await fixture(t), run = join(f.runsRoot, 'calibration');
141
+ await runBenchCheck({ dir: f.bench, calibrate: { executor: f.executor, trials: 1, runsRoot: f.runsRoot, runGroup: 'calibration' }, log: () => { } });
142
+ const file = join(run, '_calibration.json'), original = readFileSync(file, 'utf8'), summary = JSON.parse(original);
143
+ summary.tasks[0].passes = 0;
144
+ writeFileSync(file, JSON.stringify(summary));
145
+ reseal(run);
146
+ const bad = await readEvaluationReport(run);
147
+ assert.equal(bad.evidence.verified, false);
148
+ assert.match(JSON.stringify(bad.evidence), /summary differs from receipts/);
149
+ await assert.rejects(exportEvaluation(run, join(f.root, 'bad'), { yes: true, log: () => { } }), /audit failed/);
150
+ writeFileSync(file, original);
151
+ reseal(run);
152
+ const output = join(f.root, 'portable');
153
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
154
+ const delivery = join(output, 'run/example-task/baseline/trial-1/_output.md');
155
+ writeFileSync(delivery, 'wrong delivery');
156
+ const index = JSON.parse(readFileSync(join(output, 'run/_artifacts.json'), 'utf8'));
157
+ index.files['example-task/baseline/trial-1/_output.md'] = sha256File(delivery);
158
+ writeFileSync(join(output, 'run/_artifacts.json'), JSON.stringify(index));
159
+ const metadata = JSON.parse(readFileSync(join(output, 'replay-package.json'), 'utf8'));
160
+ for (const file of Object.keys(metadata.files))
161
+ metadata.files[file] = sha256File(join(output, file));
162
+ writeFileSync(join(output, 'replay-package.json'), JSON.stringify(metadata));
163
+ const replayed = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
164
+ assert.equal(replayed.status, 2);
165
+ assert.match(replayed.stderr, /verdict differs/);
166
+ assert.equal(f.calls(), 1);
167
+ });
168
+ test('paired judge portable replay retains both review calls and full costs without invoking judge again', async (t) => {
169
+ const f = await fixture(t);
170
+ let judgeCalls = 0;
171
+ const judge = { describe: () => ({ kind: 'stub', model: 'offline-judge' }), run: async () => {
172
+ judgeCalls++;
173
+ return { output: JSON.stringify({ A: { correct: true, complete: true, grounded: true }, B: { correct: true, complete: true, grounded: true } }), tokens: { input: 20, cachedInput: 4, output: 5 }, usageStatus: 'final' };
174
+ } };
175
+ const run = join(f.runsRoot, 'judge');
176
+ await runEval({ skillPath: f.skill, bench: f.bench, executor: f.executor, judgeExecutor: judge,
177
+ trials: 1, maxCalls: 4, runsRoot: f.runsRoot, runGroup: 'judge', dryRun: false, yes: true, log: () => { } });
178
+ const before = await readEvaluationReport(run);
179
+ assert.equal(before.evidence.verified, true, JSON.stringify(before.evidence));
180
+ const output = join(f.root, 'portable');
181
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
182
+ rmSync(f.bench, { recursive: true });
183
+ rmSync(f.skill, { recursive: true });
184
+ rmSync(run, { recursive: true });
185
+ const result = replay(output);
186
+ assert.equal(result.evidence.verified, true);
187
+ assert.equal(result.evidence.replayedDeliveries, 2);
188
+ assert.deepEqual(result.invocationCosts, 'invocationCosts' in before ? before.invocationCosts : null);
189
+ assert.equal(result.invocationCosts.judge.runs, 2);
190
+ assert.equal(result.invocationCosts.judge.metrics.input.knownTotal, 40);
191
+ assert.equal(result.invocationCosts.agent.metrics.input.coverage.partial, 2);
192
+ assert.equal(result.invocationCosts.total.runs, 4);
193
+ assert.equal(result.acceptance.automaticUpgrade, false);
194
+ assert.equal(f.calls(), 2);
195
+ assert.equal(judgeCalls, 2);
196
+ });
197
+ test('resealing an outer inventory cannot hide missing plan inputs, a changed approval or a mismatched prompt', async (t) => {
198
+ for (const damage of ['inputs', 'approval', 'prompt', 'invoked'])
199
+ await t.test(damage, async (t) => {
200
+ const f = await fixture(t), run = join(f.runsRoot, 'calibration');
201
+ await runBenchCheck({ dir: f.bench, calibrate: { executor: f.executor, trials: 1, runsRoot: f.runsRoot, runGroup: 'calibration' }, log: () => { } });
202
+ if (damage === 'inputs')
203
+ rewritePlan(run, plan => { delete plan.inputs; });
204
+ if (damage === 'approval')
205
+ rewritePlan(run, plan => { plan.details.executorTimeoutSeconds += 1; });
206
+ if (damage === 'prompt') {
207
+ writeFileSync(join(run, 'example-task/baseline/trial-1/_prompt.txt'), 'different invocation');
208
+ reseal(run);
209
+ }
210
+ if (damage === 'invoked') {
211
+ const path = join(run, 'example-task/baseline/trial-1/_result.json'), receipt = JSON.parse(readFileSync(path, 'utf8'));
212
+ receipt.executorInvoked = false;
213
+ writeFileSync(path, JSON.stringify(receipt));
214
+ reseal(run);
215
+ }
216
+ const report = await readEvaluationReport(run);
217
+ assert.equal(report.evidence.verified, false, damage);
218
+ assert.ok(report.evidence.reasons.length);
219
+ await assert.rejects(exportEvaluation(run, join(f.root, 'refused'), { yes: true, log: () => { } }), /audit failed/);
220
+ assert.equal(existsSync(join(f.root, 'refused')), false);
221
+ assert.equal(f.calls(), 1);
222
+ });
223
+ });
224
+ test('single-arm budget replay includes setup attempts that never invoked an Agent', async (t) => {
225
+ const f = await fixture(t), run = join(f.runsRoot, 'calibration'), workspace = join(run, 'example-task/baseline/trial-1');
226
+ const limits = { input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 };
227
+ const session = new ExperimentSession({ bench: loadBench(f.bench), target: collectEvaluationTarget(f.skill), groupDir: run,
228
+ workspaces: [workspace], plannedCalls: 1, maxCalls: 1, injected: true,
229
+ details: { mode: 'calibration', inputMode: 'snapshot', trials: 1, spendingBudget: limits } });
230
+ mkdirSync(workspace, { recursive: true });
231
+ const observation = { executorInvoked: false, passed: false, error: 'Synthetic Git setup refusal', durationSeconds: 0, tokens: null, usageStatus: 'unknown' };
232
+ writeFileSync(join(workspace, '_result.json'), JSON.stringify({ schemaVersion: 2, taskId: 'example-task', trial: 1, condition: 'baseline', ...observation }));
233
+ const budget = createSpendingBudgetRecorder({ budget: limits, groupDir: run }), identity = { taskId: 'example-task', condition: 'baseline', trial: 1 };
234
+ budget.before(identity);
235
+ let failure;
236
+ try {
237
+ budget.after(identity, observation);
238
+ }
239
+ catch (error) {
240
+ failure = error;
241
+ }
242
+ assert.ok(failure);
243
+ const summary = { schemaVersion: 1, runGroup: 'calibration', inputMode: 'snapshot', trials: 1,
244
+ tasks: [{ id: 'example-task', passes: 0, completed: 0, errors: 1 }], costs: summarizeCosts({ baseline: [observation], treatment: [] }, { baseline: [], treatment: [] }), experiment: session.summary() };
245
+ writeFileSync(join(run, '_calibration.json'), JSON.stringify(summary));
246
+ session.finish(failure, summary, '_calibration.json');
247
+ const before = await readEvaluationReport(run);
248
+ assert.ok('evaluationType' in before);
249
+ assert.equal(before.evidence.verified, true, JSON.stringify(before.evidence));
250
+ assert.equal(before.usage?.runs, 0);
251
+ assert.equal(before.status, 'stopped');
252
+ const output = join(f.root, 'portable');
253
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
254
+ const result = replay(output);
255
+ assert.equal(result.evidence.verified, true);
256
+ assert.equal(result.usage.runs, 0);
257
+ assert.equal(result.summary.metrics.errors, 1);
258
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
259
+ assert.equal(f.calls(), 0);
260
+ });
261
+ test('portable replay forwards interruption and waits for verifier cleanup before exiting', async (t) => {
262
+ for (const signal of ['SIGINT', 'SIGTERM'])
263
+ await t.test(signal, async (t) => {
264
+ const f = await fixture(t), enabled = join(f.root, 'enable-hanging-verifier'), pidFile = join(f.root, 'verifier.pid');
265
+ writeFileSync(join(f.bench, 'verifiers/example-task.mjs'), `import{existsSync,readFileSync,writeFileSync}from'node:fs';import{join}from'node:path';if(existsSync(${JSON.stringify(enabled)})){writeFileSync(${JSON.stringify(pidFile)},String(process.pid));setInterval(()=>{},1000);}else{const file=join(process.argv[2],'_output.md');const passed=existsSync(file)&&readFileSync(file,'utf8').includes('skillfit-ok');console.log(JSON.stringify({passed}));process.exit(passed?0:1);}`);
266
+ const run = join(f.runsRoot, 'cancel');
267
+ await runEval({ skillPath: f.skill, bench: f.bench, executor: f.executor, judgeExecutor: null,
268
+ trials: 1, runsRoot: f.runsRoot, runGroup: 'cancel', dryRun: false, yes: true, log: () => { } });
269
+ const output = join(f.root, 'portable');
270
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
271
+ const before = packageFiles(output).map(path => [path, sha256File(join(output, path))]);
272
+ writeFileSync(enabled, 'hang only replay');
273
+ const entry = join(output, 'reproduce.mjs');
274
+ const argv = process.platform === 'win32' ? ['--input-type=module', '--eval', `process.on('message',message=>{if(message?.signal)process.emit(message.signal);});process.channel?.unref();await import(${JSON.stringify(pathToFileURL(entry).href)});`] : [entry];
275
+ const child = spawn(process.execPath, argv, { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true });
276
+ let stdout = '', stderr = '', verifierPid;
277
+ child.stdout.on('data', chunk => { stdout += String(chunk); });
278
+ child.stderr.on('data', chunk => { stderr += String(chunk); });
279
+ const closed = new Promise((resolve, reject) => { child.once('close', resolve); child.once('error', reject); });
280
+ t.after(() => { child.kill('SIGKILL'); if (verifierPid)
281
+ try {
282
+ process.kill(verifierPid, 'SIGKILL');
283
+ }
284
+ catch { /* Already cleaned. */ } });
285
+ const until = Date.now() + 15_000;
286
+ while (!existsSync(pidFile) && Date.now() < until)
287
+ await new Promise(resolve => setTimeout(resolve, 20));
288
+ assert.ok(existsSync(pidFile), `Pinned replay verifier did not start: ${stderr}`);
289
+ verifierPid = Number(readFileSync(pidFile, 'utf8'));
290
+ assert.doesNotThrow(() => process.kill(verifierPid, 0));
291
+ if (process.platform === 'win32')
292
+ child.send({ signal });
293
+ else
294
+ child.kill(signal);
295
+ let timer;
296
+ try {
297
+ const code = await Promise.race([closed, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Portable replay did not finish verifier cleanup after interruption.')), 15_000); })]);
298
+ assert.equal(code, signal === 'SIGINT' ? 130 : 143, stderr);
299
+ }
300
+ finally {
301
+ if (timer)
302
+ clearTimeout(timer);
303
+ }
304
+ assert.equal(stdout, '', 'Interrupted replay must not emit a successful JSON assessment.');
305
+ assert.match(stderr, /waited for the pinned CLI/);
306
+ let alive = true;
307
+ try {
308
+ process.kill(verifierPid, 0);
309
+ }
310
+ catch {
311
+ alive = false;
312
+ }
313
+ assert.equal(alive, false, 'Local verifier must have exited before reproduce.mjs exits.');
314
+ verifierPid = undefined;
315
+ assert.deepEqual(packageFiles(output).map(path => [path, sha256File(join(output, path))]), before, 'Replay cancellation never alters sealed input evidence.');
316
+ assert.equal(f.calls(), 2);
317
+ });
318
+ });
319
+ test('broken single-arm inventory preserves readable costs and counts lost or invalid receipts as unknown', async (t) => {
320
+ for (const mode of ['calibration', 'trigger'])
321
+ await t.test(mode, async (t) => {
322
+ const f = await fixture(t), run = join(f.runsRoot, mode), arm = mode === 'calibration' ? 'baseline' : 'installed';
323
+ if (mode === 'calibration')
324
+ await runBenchCheck({ dir: f.bench, calibrate: { executor: f.executor, trials: 2, runsRoot: f.runsRoot, runGroup: mode }, log: () => { } });
325
+ else
326
+ await runEval({ skillPath: f.skill, bench: f.bench, mode, skillInstallDir: '.test-skills', executor: f.executor,
327
+ trials: 2, runsRoot: f.runsRoot, runGroup: mode, dryRun: false, yes: true, log: () => { } });
328
+ const first = join(run, 'example-task', arm, 'trial-1/_result.json'), second = join(run, 'example-task', arm, 'trial-2/_result.json');
329
+ rmSync(first);
330
+ const missing = await readEvaluationReport(run);
331
+ assert.ok('evaluationType' in missing);
332
+ assert.equal(missing.evidence.verified, false);
333
+ assert.equal(missing.usage?.runs, 2);
334
+ assert.equal(missing.usage?.invocationsWithUnknownReceipts, 1);
335
+ assert.equal(missing.usage?.metrics.input.knownTotal, 10);
336
+ assert.equal(missing.usage?.metrics.input.coverage.partial, 1);
337
+ assert.equal(missing.usage?.metrics.input.coverage.unknown, 1);
338
+ writeFileSync(second, '{invalid raw receipt');
339
+ const invalid = await readEvaluationReport(run);
340
+ assert.ok('evaluationType' in invalid);
341
+ assert.equal(invalid.evidence.verified, false);
342
+ assert.equal(invalid.usage?.runs, 2);
343
+ assert.equal(invalid.usage?.invocationsWithUnknownReceipts, 2);
344
+ assert.equal(invalid.usage?.metrics.input.coverage.unknown, 2);
345
+ assert.match(invalid.usage?.scope ?? '', /Unaudited/);
346
+ assert.equal(invalid.acceptance.eligibleForUpgrade, false);
347
+ await assert.rejects(exportEvaluation(run, join(f.root, 'invalid'), { yes: true, log: () => { } }), /Native evidence inventory changed/);
348
+ assert.equal(f.calls(), 2);
349
+ });
350
+ });
@@ -55,12 +55,20 @@ export async function exportEvaluation(input, output, options = {}) {
55
55
  throw new Error(`Native evidence hash mismatch: ${path}`);
56
56
  const report = await reportEvalComponent(run);
57
57
  const hasManifest = existsSync(join(run, 'manifest.json'));
58
- if (hasManifest && (!('evidence' in report) || !report.evidence.verified))
58
+ const singleArm = plan.details?.mode === 'calibration' || plan.details?.mode === 'trigger';
59
+ if ((hasManifest || singleArm) && (!('evidence' in report) || !report.evidence.verified))
59
60
  throw new Error(`Native evidence audit failed; cannot export a complete replay package: ${'evidence' in report ? JSON.stringify(report.evidence) : 'missing audit'}`);
60
- if (plan.details?.mode === 'trigger' || plan.details?.judge != null)
61
- throw new Error('Portable replay currently requires paired native runs without a judge; separate judge spending is not fully recorded.');
62
61
  if (!Array.isArray(plan.inputs) || typeof plan.packageVersion !== 'string')
63
62
  throw new Error('Native input fingerprints or version are missing.');
63
+ const pinnedImplementation = plan.inputs.find((entry) => entry.label === 'implementation');
64
+ if (!pinnedImplementation?.files?.includes('harness/interruption.js'))
65
+ throw new Error('The original pinned runtime lacks replay cancellation support. Keep the native record; exporting must not silently replace its implementation.');
66
+ if (singleArm) {
67
+ for (const path of ['commands/eval-single-arm-replay.js', 'harness/single-arm-audit.js']) {
68
+ if (!pinnedImplementation?.files?.includes(path))
69
+ throw new Error('The original pinned runtime lacks single-arm replay support. Keep the native record; exporting must not silently replace its implementation.');
70
+ }
71
+ }
64
72
  const snapshot = verifyInputSnapshot(run, plan);
65
73
  const copies = [];
66
74
  const directories = new Set();
@@ -157,7 +165,7 @@ export async function exportEvaluation(input, output, options = {}) {
157
165
  writeFileSync(join(stage, 'README.md'), '# Offline evaluation replay\n\nRun `node reproduce.mjs --verify-only` to check files, or `node reproduce.mjs` to regrade saved deliveries with the pinned implementation. No agent or model is started. Local verifiers are executable code; use trusted packages. Node.js 22+ and any external verifier toolchains are required.\n\nNative receipts are unchanged. Unknown/partial costs stay unknown/partial; a stopped run remains stopped. Checksums detect changes, not publisher identity. Review project data and paths before sharing. Runtime package metadata is reconstructed from the frozen native package version; compiled implementation bytes are copied unchanged.\n');
158
166
  const payload = packageFiles(stage);
159
167
  writeFileSync(join(stage, 'replay-package.json'), JSON.stringify({ schemaVersion: 1, kind: 'skillfit.replay-package',
160
- sourcePlanSha256: planSha256, hasManifest, nativeStatus: session.status,
168
+ sourcePlanSha256: planSha256, hasManifest, nativeStatus: session.status, evaluationType: singleArm ? plan.details.mode : 'paired',
161
169
  files: Object.fromEntries(payload.map(path => [path, sha256File(join(stage, path))])) }, null, 2) + '\n');
162
170
  verifyReplayPackage(stage);
163
171
  // Exclusive mkdir protects even empty directories and dangling symlinks that
@@ -0,0 +1,37 @@
1
+ import { basename, dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { existsSync } from 'node:fs';
4
+ import { hashFileSet, listFilesRecursive, sha256Text } from '../harness/hash.js';
5
+ import { runEval } from './eval.js';
6
+ /** Shared read-only planning and confirmation for command-line and file requests. */
7
+ export async function prepareEvalPlan(options, context) {
8
+ const implementationDir = fileURLToPath(new URL('../../dist', import.meta.url));
9
+ const implementationSha256 = hashFileSet(implementationDir, listFilesRecursive(implementationDir));
10
+ const lines = [];
11
+ let evaluation;
12
+ await runEval({ ...options, dryRun: true, log: line => lines.push(line), onPlan: preview => { evaluation = preview; } });
13
+ if (!evaluation)
14
+ throw new Error('No paired evaluation plan is available.');
15
+ if (existsSync(evaluation.outputDir))
16
+ throw new Error('Run group already exists; declare a fresh group without overwriting evidence.');
17
+ const describe = (preview) => ({ schemaVersion: 1, kind: 'skillfit.eval-plan',
18
+ ...context, implementationSha256, evaluation: preview });
19
+ const data = describe(evaluation), sha256 = sha256Text(JSON.stringify(data));
20
+ const plan = { ...data, sha256 };
21
+ const resolved = { ...options, runsRoot: dirname(evaluation.outputDir), runGroup: basename(evaluation.outputDir) };
22
+ return { plan, lines, options: resolved,
23
+ assertCurrent: (preview) => {
24
+ if (sha256Text(JSON.stringify(describe(preview))) !== sha256)
25
+ throw new Error('Plan changed before execution; no calls allowed.');
26
+ } };
27
+ }
28
+ export function confirmEvalPlan(expected, actual) {
29
+ if (!expected || !/^[0-9a-f]{64}$/i.test(expected) || expected.toLowerCase() !== actual) {
30
+ throw new Error('Execution requires --plan-sha matching the current dry-run plan; inputs, policy, executor or implementation changed.');
31
+ }
32
+ }
33
+ export function plannedEvalResult(plan) {
34
+ return { schemaVersion: 1, kind: 'skillfit.eval-result', status: 'planned', plan,
35
+ acceptance: { decision: 'inconclusive', eligibleForUpgrade: false, automaticUpgrade: false,
36
+ reasons: [{ code: 'PLAN_ONLY', message: 'No agent call or outcome is available.' }] } };
37
+ }
@@ -1,6 +1,6 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { spawnSync } from 'node:child_process';
3
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { delimiter, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
@@ -8,6 +8,8 @@ import { test } from 'node:test';
8
8
  import { runBenchInit } from './bench.js';
9
9
  import { componentError, reportEvalComponent } from './eval-component.js';
10
10
  import { runEval } from './eval.js';
11
+ import { runEvalCli } from './eval-cli.js';
12
+ import { exportEvaluation } from './eval-export.js';
11
13
  import { CasePreflightFailed } from './eval-preflight.js';
12
14
  import { MockExecutor } from '../harness/executors/mock.js';
13
15
  const read = (path) => JSON.parse(readFileSync(path, 'utf8'));
@@ -31,6 +33,147 @@ async function setup(t, kind = 'command') {
31
33
  return { root, bench, skill, old, raw, save, base, judge, calls: () => calls, judges: () => judges,
32
34
  verifier: join(bench, 'verifiers/example-task.mjs'), oracle: join(bench, 'ground-truth/oracle-example-task.mjs') };
33
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
+ });
34
177
  for (const mode of ['inject', 'installed', 'trigger'])
35
178
  test(`${mode}: a broken NOP gate blocks all agent/judge calls before run creation`, async (t) => {
36
179
  const f = await setup(t);