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,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
+ });
@@ -1,9 +1,10 @@
1
- import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
3
  import { loadBench } from '../harness/bench.js';
4
4
  import { hashFileSet, sha256File } from '../harness/hash.js';
5
5
  import { packageFiles, packageMember, portableReproducer, verifyReplayPackage } from '../harness/replay-package.js';
6
6
  import { reportEvalComponent } from './eval-component.js';
7
+ import { verifyInputSnapshot } from '../harness/input-snapshot.js';
7
8
  function overlaps(root, path) {
8
9
  const rel = relative(root, path);
9
10
  return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
@@ -12,8 +13,11 @@ function physical(path) {
12
13
  let parent = resolve(path);
13
14
  const parts = [];
14
15
  while (!existsSync(parent)) {
16
+ const next = dirname(parent);
17
+ if (next === parent)
18
+ return resolve(path); // An original Windows drive can be absent after moving a run.
15
19
  parts.unshift(basename(parent));
16
- parent = dirname(parent);
20
+ parent = next;
17
21
  }
18
22
  return join(realpathSync(parent), ...parts);
19
23
  }
@@ -51,26 +55,47 @@ export async function exportEvaluation(input, output, options = {}) {
51
55
  throw new Error(`Native evidence hash mismatch: ${path}`);
52
56
  const report = await reportEvalComponent(run);
53
57
  const hasManifest = existsSync(join(run, 'manifest.json'));
54
- 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))
55
60
  throw new Error(`Native evidence audit failed; cannot export a complete replay package: ${'evidence' in report ? JSON.stringify(report.evidence) : 'missing audit'}`);
56
- if (plan.details?.mode === 'trigger' || plan.details?.judge != null)
57
- throw new Error('Portable replay currently requires paired native runs without a judge; separate judge spending is not fully recorded.');
58
61
  if (!Array.isArray(plan.inputs) || typeof plan.packageVersion !== 'string')
59
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
+ }
72
+ const snapshot = verifyInputSnapshot(run, plan);
60
73
  const copies = [];
74
+ const directories = new Set();
75
+ for (const entry of snapshot?.entries ?? [])
76
+ if (entry.label !== 'request') {
77
+ directories.add(`run/${entry.path}`);
78
+ for (const dir of entry.directories)
79
+ directories.add(`run/${entry.path}/${dir}`);
80
+ }
61
81
  for (const path of [...files, '_artifacts.json'])
62
82
  copies.push({ source: packageMember(run, path), target: `run/${path}`, sha256: sha256File(join(run, path)) });
63
83
  const required = ['bench', 'target', 'implementation'];
64
84
  if (plan.details?.baselineTarget)
65
85
  required.push('baseline Skill');
66
86
  const roots = [run];
87
+ // Even when copies come from the archive, preserve the existing boundary
88
+ // against writing an export into any original input directory.
89
+ const protectedRoots = [run];
67
90
  for (const label of required) {
68
91
  const fingerprint = plan.inputs.find((entry) => entry.label === label);
69
92
  if (!fingerprint || !Array.isArray(fingerprint.files) || typeof fingerprint.root !== 'string')
70
93
  throw new Error(`Missing pinned input: ${label}`);
71
94
  const alias = label === 'baseline Skill' ? 'baseline-skill' : label;
72
- const root = overrides.get(alias) ?? (label === 'bench' && options.benchDir ? resolve(options.benchDir) : fingerprint.root);
95
+ protectedRoots.push(fingerprint.root);
96
+ const root = overrides.get(alias) ?? (label === 'bench' && options.benchDir ? resolve(options.benchDir) : snapshot?.roots.get(alias) ?? fingerprint.root);
73
97
  roots.push(root);
98
+ protectedRoots.push(root);
74
99
  const prefix = label === 'implementation' ? 'runtime/dist' : `inputs/${label === 'baseline Skill' ? 'baseline-skill' : label}`;
75
100
  const paths = fingerprint.files;
76
101
  // Every path must be safe before it is read; no configuration or global Skill roots are copied.
@@ -78,6 +103,12 @@ export async function exportEvaluation(input, output, options = {}) {
78
103
  packageMember(root, path);
79
104
  if (hashFileSet(root, paths) !== fingerprint.sha256)
80
105
  throw new Error(`Pinned ${label} input changed or is unavailable; recover the original files before exporting.`);
106
+ const archived = snapshot?.entries.find(entry => entry.label === alias);
107
+ if (archived) {
108
+ directories.add(prefix);
109
+ for (const dir of archived.directories)
110
+ directories.add(`${prefix}/${dir}`);
111
+ }
81
112
  for (const path of paths)
82
113
  copies.push({ source: packageMember(root, path), target: `${prefix}/${path}`, sha256: sha256File(join(root, path)) });
83
114
  }
@@ -86,19 +117,19 @@ export async function exportEvaluation(input, output, options = {}) {
86
117
  if (!(label === 'request' && request) && !required.includes(label === 'baseline-skill' ? 'baseline Skill' : label))
87
118
  throw new Error(`Input root is not part of this run: ${label}`);
88
119
  if (request) {
89
- const path = overrides.get('request') ?? request.path;
120
+ const path = overrides.get('request') ?? snapshot?.roots.get('request') ?? request.path;
90
121
  if (!lstatSync(path).isFile() || sha256File(path) !== request.sha256)
91
122
  throw new Error('Frozen request changed; recover the original request before exporting.');
92
123
  copies.push({ source: path, target: 'inputs/request.json', sha256: request.sha256 });
93
124
  }
94
- if (roots.some(root => overlaps(physical(root), physical(destination))))
125
+ if (protectedRoots.some(root => overlaps(physical(root), physical(destination))))
95
126
  throw new Error('Export destination must be outside the native run and pinned input roots.');
96
127
  const log = options.log ?? console.log;
97
128
  const apply = options.yes === true && !options.dryRun;
98
129
  const preview = { schemaVersion: 1, kind: 'skillfit.eval-export', status: apply ? 'exported' : 'planned',
99
130
  source: run, destination, sourcePlanSha256: planSha256, nativeStatus: session.status, hasManifest,
100
131
  files: copies.length + 3, bytes: copies.reduce((sum, file) => sum + lstatSync(file.source).size, 0),
101
- inputs: roots, modelCalls: 0, sharingReviewRequired: true };
132
+ inputs: roots, inputSource: snapshot ? 'sealed-snapshot' : 'original-or-recovered', modelCalls: 0, sharingReviewRequired: true };
102
133
  log(`Portable export: ${run} -> ${destination}`);
103
134
  for (const root of roots)
104
135
  log(` source: ${root}`);
@@ -110,6 +141,8 @@ export async function exportEvaluation(input, output, options = {}) {
110
141
  mkdirSync(dirname(destination), { recursive: true });
111
142
  const stage = mkdtempSync(join(dirname(destination), '.skillfit-export-'));
112
143
  try {
144
+ for (const dir of directories)
145
+ mkdirSync(join(stage, dir), { recursive: true });
113
146
  for (const file of copies) {
114
147
  const bytes = readFileSync(file.source);
115
148
  if (sha256File(file.source) !== file.sha256)
@@ -117,6 +150,7 @@ export async function exportEvaluation(input, output, options = {}) {
117
150
  const target = join(stage, file.target);
118
151
  mkdirSync(dirname(target), { recursive: true });
119
152
  writeFileSync(target, bytes, { flag: 'wx' });
153
+ chmodSync(target, lstatSync(file.source).mode & 0o777);
120
154
  if (sha256File(target) !== file.sha256)
121
155
  throw new Error(`Export copy verification failed: ${file.target}`);
122
156
  }
@@ -131,7 +165,7 @@ export async function exportEvaluation(input, output, options = {}) {
131
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');
132
166
  const payload = packageFiles(stage);
133
167
  writeFileSync(join(stage, 'replay-package.json'), JSON.stringify({ schemaVersion: 1, kind: 'skillfit.replay-package',
134
- sourcePlanSha256: planSha256, hasManifest, nativeStatus: session.status,
168
+ sourcePlanSha256: planSha256, hasManifest, nativeStatus: session.status, evaluationType: singleArm ? plan.details.mode : 'paired',
135
169
  files: Object.fromEntries(payload.map(path => [path, sha256File(join(stage, path))])) }, null, 2) + '\n');
136
170
  verifyReplayPackage(stage);
137
171
  // Exclusive mkdir protects even empty directories and dangling symlinks that