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,245 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { test } from 'node:test';
8
+ import { getAgent } from '../agents.js';
9
+ import { findExecutable, globalSkillRoots, inspectAgentEnvironment, AgentPreflightFailed, assertRecordedAgentEnvironment } from '../harness/agent-preflight.js';
10
+ import { collectEvaluationTarget } from '../harness/target.js';
11
+ import { runEval } from './eval.js';
12
+ import { runEvalCli } from './eval-cli.js';
13
+ import { runEvalComponent, reportEvalComponent, componentError } from './eval-component.js';
14
+ import { exportEvaluation } from './eval-export.js';
15
+ import { runEvalReport } from './eval-report.js';
16
+ const CLI = fileURLToPath(new URL('../cli.js', import.meta.url));
17
+ function setup(t) {
18
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-agent-env-'));
19
+ t.after(() => rmSync(root, { recursive: true, force: true }));
20
+ const home = join(root, 'home'), profile = join(root, 'profile'), bin = join(root, 'bin'), skill = join(root, 'candidate'), bench = join(root, 'bench');
21
+ for (const dir of [home, profile, bin, skill, join(bench, 'fixture')])
22
+ mkdirSync(dir, { recursive: true });
23
+ writeFileSync(join(skill, 'SKILL.md'), '---\nname: actual-skill-name\ndescription: Test a local answer.\n---\nReturn OK.\n');
24
+ writeFileSync(join(bench, 'fixture/input.txt'), 'input');
25
+ writeFileSync(join(bench, 'prompt.md'), 'Return OK.');
26
+ const verifier = join(bench, 'verify.mjs');
27
+ writeFileSync(verifier, "import{existsSync,readFileSync}from'node:fs';import{join}from'node:path';const file=join(process.argv[2],'_output.md');const passed=existsSync(file)&&readFileSync(file,'utf8').trim()==='OK';console.log(JSON.stringify({passed}));process.exit(passed?0:1);");
28
+ writeFileSync(join(bench, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'agent-preflight', tasks: [{ id: 't', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node verify.mjs', shouldTrigger: true }] }));
29
+ const env = { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: profile, PATH: bin, SKILLFIT_JUDGE: '0' };
30
+ // Native OS home resolution is not used by direct tests; child CLI tests use both home overrides.
31
+ const binary = join(bin, process.platform === 'win32' ? 'codex.CMD' : 'codex');
32
+ writeFileSync(binary, 'synthetic executable; must never be run');
33
+ chmodSync(binary, 0o755);
34
+ const target = collectEvaluationTarget(skill), definition = getAgent('codex');
35
+ const role = { role: 'agent', definition, executor: { kind: 'cli', model: 'cli-configured' }, injected: false };
36
+ const inspect = (roles = [role]) => inspectAgentEnvironment({ roles, target, mode: 'inject', homeDir: home, env });
37
+ const conflict = (folder = 'alias-folder', name = 'actual-skill-name') => {
38
+ const dir = join(globalSkillRoots(definition, home, env).at(-1), folder);
39
+ mkdirSync(dir, { recursive: true });
40
+ writeFileSync(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: A synthetic global Skill.\n---\nPrivate body must not appear in the report.\n`);
41
+ return dir;
42
+ };
43
+ let calls = 0;
44
+ const base = { skillPath: skill, bench, agent: 'codex', trials: 1, maxCalls: 2, dryRun: false, yes: true,
45
+ runsRoot: join(root, 'runs'), runGroup: 'env', judgeExecutor: null, sessionOptions: { homeDir: home, env, versionProbe: () => null },
46
+ executor: { describe: () => ({ kind: 'mock', model: 'offline-agent-env' }), run: async () => {
47
+ calls++;
48
+ return { output: 'OK', tokens: { input: 10, cachedInput: 4, output: 2 } };
49
+ } }, log: () => { } };
50
+ return { root, home, profile, bin, binary, env, target, role, inspect, conflict, base, bench, skill, verifier, calls: () => calls };
51
+ }
52
+ test('PATH lookup inspects executable files without running a CLI or accepting config directories as installation', t => {
53
+ const f = setup(t);
54
+ assert.equal(findExecutable('codex', f.env), findExecutable(f.binary, f.env));
55
+ assert.equal(findExecutable('missing-agent', f.env), null);
56
+ assert.equal(findExecutable('codex', { ...f.env, PATH: '' }), null);
57
+ mkdirSync(join(f.bin, 'directory-agent'));
58
+ assert.equal(findExecutable('directory-agent', f.env), null);
59
+ if (process.platform !== 'win32') {
60
+ chmodSync(f.binary, 0o644);
61
+ assert.equal(findExecutable('codex', f.env), null);
62
+ }
63
+ const report = inspectAgentEnvironment({ roles: [f.role], target: f.target, mode: 'inject', homeDir: f.home, env: { ...f.env, PATH: '' } });
64
+ assert.equal(report.status, 'blocked');
65
+ assert.equal(report.checks.find(c => c.code === 'CLI_AVAILABLE').status, 'FAIL');
66
+ assert.deepEqual(report.cost, { modelCalls: 0, cliInvocations: 0 });
67
+ });
68
+ test('Windows PATH/PATHEXT lookup accepts command shims and case-insensitive environment keys', t => {
69
+ const f = setup(t), file = join(f.bin, 'offline.CMD');
70
+ writeFileSync(file, 'must never execute');
71
+ const path = findExecutable('offline', { Path: `"${f.bin}"`, PathExt: '.CMD;.EXE' }, 'win32');
72
+ assert.ok(path?.endsWith('offline.CMD'));
73
+ assert.equal(findExecutable('absent', { Path: f.bin, PATHEXT: '.CMD' }, 'win32'), null);
74
+ assert.equal(findExecutable('offline', { Path: 'missing', PATH: f.bin, PATHEXT: '.CMD' }, 'win32'), path);
75
+ });
76
+ test('local readiness never claims login even with credentials/config files present, and emits no secret values', t => {
77
+ const f = setup(t), secret = 'synthetic-secret-never-report';
78
+ writeFileSync(join(f.profile, 'auth.json'), JSON.stringify({ access_token: secret }));
79
+ const report = inspectAgentEnvironment({ roles: [f.role], target: f.target, mode: 'installed', homeDir: f.home,
80
+ env: { ...f.env, OPENAI_API_KEY: secret } });
81
+ assert.equal(report.status, 'ready');
82
+ assert.equal(report.checks.find(c => c.code === 'AUTHENTICATION').status, 'UNKNOWN');
83
+ assertRecordedAgentEnvironment(report);
84
+ assert.equal(JSON.stringify(report).includes(secret), false);
85
+ assert.deepEqual(f.inspect(), f.inspect());
86
+ assert.equal(f.calls(), 0);
87
+ });
88
+ test('capability checks use matrix declarations and cover trigger support, installation paths and the judge CLI', t => {
89
+ const f = setup(t), claude = getAgent('claude-code');
90
+ const trigger = inspectAgentEnvironment({ roles: [{ ...f.role, definition: claude }], target: f.target, mode: 'trigger', homeDir: f.home, env: f.env });
91
+ assert.equal(trigger.status, 'blocked');
92
+ assert.match(trigger.checks.find(c => c.code === 'MATRIX_CAPABILITY').message, /streamJson/);
93
+ const missingDirs = structuredClone(f.role.definition);
94
+ missingDirs.skills.projectDirs = [];
95
+ const installed = inspectAgentEnvironment({ roles: [{ ...f.role, definition: missingDirs }], target: f.target, mode: 'installed', homeDir: f.home, env: f.env });
96
+ assert.match(installed.checks.find(c => c.code === 'MATRIX_CAPABILITY').message, /project Skill directory/);
97
+ const judge = structuredClone(f.role.definition);
98
+ judge.headless.argv = ['missing-offline-judge'];
99
+ const judged = f.inspect([f.role, { ...f.role, role: 'judge', definition: judge }]);
100
+ assert.equal(judged.status, 'blocked');
101
+ assert.equal(judged.checks.find(c => c.role === 'judge' && c.code === 'CLI_AVAILABLE').status, 'FAIL');
102
+ assert.equal(judged.checks.filter(c => c.code === 'AUTHENTICATION').length, 2);
103
+ });
104
+ test('global conflicts include frontmatter aliases and configured home overrides without exposing Skill bodies', t => {
105
+ const f = setup(t), dir = f.conflict();
106
+ const report = f.inspect(), conflict = report.checks.find(c => c.code === 'GLOBAL_SKILL_CONFLICT');
107
+ assert.equal(report.status, 'blocked');
108
+ assert.equal(conflict.status, 'FAIL');
109
+ assert.deepEqual(conflict.paths, [dir]);
110
+ assert.match(conflict.message, /Baseline contamination risk/);
111
+ assert.equal(JSON.stringify(report).includes('Private body'), false);
112
+ rmSync(dir, { recursive: true });
113
+ f.conflict(f.target.name, 'different-frontmatter-name');
114
+ assert.equal(f.inspect().status, 'blocked', 'directory-name conflicts remain blocked too');
115
+ });
116
+ test('global alias directories are inspected, and unreadable roots remain explicitly unknown', t => {
117
+ const f = setup(t), real = join(f.root, 'external-skill');
118
+ mkdirSync(real);
119
+ writeFileSync(join(real, 'SKILL.md'), '---\nname: actual-skill-name\ndescription: Alias test.\n---\n');
120
+ const root = globalSkillRoots(f.role.definition, f.home, f.env)[0];
121
+ mkdirSync(root, { recursive: true });
122
+ symlinkSync(real, join(root, 'linked'), process.platform === 'win32' ? 'junction' : 'dir');
123
+ assert.equal(f.inspect().status, 'blocked');
124
+ rmSync(join(root, 'linked'));
125
+ rmSync(root, { recursive: true });
126
+ writeFileSync(root, 'not a directory');
127
+ const unknown = f.inspect().checks.find(c => c.code === 'GLOBAL_SKILL_SCAN');
128
+ assert.equal(unknown.status, 'UNKNOWN');
129
+ assert.ok(unknown.paths.includes(root));
130
+ });
131
+ test('injected executors cannot attest real CLI readiness and API execution does not require a CLI', t => {
132
+ const f = setup(t), injected = f.inspect([{ ...f.role, injected: true }]);
133
+ assert.equal(injected.checks.find(c => c.code === 'EXECUTOR_INJECTED').status, 'UNKNOWN');
134
+ const api = f.inspect([{ role: 'agent', injected: false, executor: { kind: 'api', model: 'offline-not-called' } }]);
135
+ assert.equal(api.status, 'ready');
136
+ assert.equal(api.checks.find(c => c.code === 'CLI_AVAILABLE').status, 'INFO');
137
+ const invalid = structuredClone(api);
138
+ invalid.checks.find(c => c.code === 'AUTHENTICATION').status = 'PASS';
139
+ assert.throws(() => assertRecordedAgentEnvironment(invalid), /environment check/);
140
+ });
141
+ test('capability mismatch is structured and blocks both preview and live execution without invoking API/agent', async (t) => {
142
+ const f = setup(t);
143
+ for (const dryRun of [true, false])
144
+ await assert.rejects(runEval({ ...f.base, dryRun, inputMode: 'workspace',
145
+ executor: { describe: () => ({ kind: 'api', model: 'offline-api' }), run: async () => { throw new Error('must never run'); } } }), error => {
146
+ assert.ok(error instanceof AgentPreflightFailed);
147
+ assert.equal(componentError(error).error.code, 'AGENT_PREFLIGHT_FAILED');
148
+ assert.equal(error.agentPreflight.checks.find(c => c.code === 'MATRIX_CAPABILITY').status, 'FAIL');
149
+ return true;
150
+ });
151
+ assert.equal(f.calls(), 0);
152
+ assert.equal(existsSync(f.base.runsRoot), false);
153
+ });
154
+ test('global conflict blocks before any case verifier, executor, version probe or native directory is created', async (t) => {
155
+ const f = setup(t), sentinel = join(f.root, 'verifier-started'), conflict = f.conflict();
156
+ writeFileSync(f.verifier, `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'called');process.exit(1);`);
157
+ await assert.rejects(runEval({ ...f.base, sessionOptions: { ...f.base.sessionOptions,
158
+ versionProbe: () => { throw new Error('must not probe the CLI'); } } }), error => {
159
+ assert.ok(error instanceof AgentPreflightFailed);
160
+ assert.equal(error.agentPreflight.status, 'blocked');
161
+ assert.ok(error.message.includes(conflict));
162
+ return true;
163
+ });
164
+ assert.equal(existsSync(sentinel), false);
165
+ assert.equal(f.calls(), 0);
166
+ assert.equal(existsSync(f.base.runsRoot), false);
167
+ });
168
+ test('case probes cannot silently change Agent readiness before first dispatch', async (t) => {
169
+ const f = setup(t), globalDir = join(globalSkillRoots(f.role.definition, f.home, f.env)[0], 'new-global');
170
+ writeFileSync(f.verifier, `import{mkdirSync,writeFileSync}from'node:fs';import{join}from'node:path';mkdirSync(${JSON.stringify(globalDir)},{recursive:true});writeFileSync(join(${JSON.stringify(globalDir)},'SKILL.md'),${JSON.stringify('---\nname: actual-skill-name\ndescription: Changed during probe.\n---\n')});console.log(JSON.stringify({passed:false}));process.exit(1);`);
171
+ await assert.rejects(runEval(f.base), AgentPreflightFailed);
172
+ assert.equal(f.calls(), 0);
173
+ assert.equal(existsSync(f.base.runsRoot), false);
174
+ });
175
+ test('ordinary and request plans bind the same checks and stale global-readiness plans cannot execute', async (t) => {
176
+ const f = setup(t), request = join(f.root, 'request.json');
177
+ const body = { schemaVersion: 1, baselineSkill: null, candidateSkill: f.skill, bench: f.bench, agent: 'codex', purpose: 'development',
178
+ trials: 1, maxCalls: 2, runsRoot: f.base.runsRoot, runGroup: f.base.runGroup };
179
+ writeFileSync(request, JSON.stringify(body));
180
+ const ordinary = { ...f.base, mode: 'installed', inputMode: 'workspace', skillInstallDir: 'project-skills' };
181
+ const a = await runEvalCli({ ...ordinary, dryRun: true });
182
+ const b = await runEvalComponent(request, { ...f.base, dryRun: true, skillInstallDir: 'project-skills' });
183
+ assert.deepEqual(a.plan.evaluation.agentPreflight, b.plan.evaluation.agentPreflight);
184
+ f.conflict();
185
+ await assert.rejects(runEvalCli(ordinary, a.plan.sha256), /--plan-sha/);
186
+ assert.equal(f.calls(), 0);
187
+ assert.equal(existsSync(f.base.runsRoot), false);
188
+ });
189
+ test('public CLI previews expose blocked readiness and both human/confirmed JSON execution refuse a missing CLI', t => {
190
+ const f = setup(t), env = { ...f.env, PATH: '' }, args = ['eval', f.skill, '--bench', f.bench, '--agent', 'codex', '--trials', '1',
191
+ '--runs-root', f.base.runsRoot, '--run-group', f.base.runGroup, '--json'];
192
+ const preview = spawnSync(process.execPath, [CLI, ...args, '--dry-run'], { env, encoding: 'utf8', timeout: 30_000 });
193
+ assert.equal(preview.status, 0, preview.stderr);
194
+ const plan = JSON.parse(preview.stdout).plan;
195
+ assert.equal(plan.evaluation.agentPreflight.status, 'blocked');
196
+ const live = spawnSync(process.execPath, [CLI, ...args, '--plan-sha', plan.sha256], { env, encoding: 'utf8', timeout: 30_000 });
197
+ assert.equal(live.status, 2);
198
+ assert.equal(JSON.parse(live.stdout).error.code, 'AGENT_PREFLIGHT_FAILED');
199
+ const human = spawnSync(process.execPath, [CLI, ...args.slice(0, -1)], { env, encoding: 'utf8', timeout: 30_000 });
200
+ assert.equal(human.status, 1);
201
+ assert.match(human.stderr, /CLI executable is missing/);
202
+ assert.equal(existsSync(f.base.runsRoot), false);
203
+ const trigger = spawnSync(process.execPath, [CLI, ...args.slice(0, -1), '--mode', 'trigger'], { env, encoding: 'utf8', timeout: 30_000 });
204
+ assert.equal(trigger.status, 1);
205
+ assert.match(trigger.stderr, /CLI executable is missing/);
206
+ assert.equal(existsSync(f.base.runsRoot), false);
207
+ });
208
+ test('a missing judge CLI blocks before spending on the primary injected executor', async (t) => {
209
+ const f = setup(t);
210
+ await assert.rejects(runEval({ ...f.base, judgeExecutor: undefined, judgeAgent: 'claude-code', maxCalls: 4 }), error => {
211
+ assert.ok(error instanceof AgentPreflightFailed);
212
+ assert.equal(error.agentPreflight.checks.find(c => c.role === 'judge' && c.code === 'CLI_AVAILABLE').status, 'FAIL');
213
+ return true;
214
+ });
215
+ assert.equal(f.calls(), 0);
216
+ assert.equal(existsSync(f.base.runsRoot), false);
217
+ });
218
+ test('saved preflight survives changed machine inputs and portable replay without new readiness/auth probes', async (t) => {
219
+ const f = setup(t), preview = await runEvalCli({ ...f.base, dryRun: true });
220
+ const result = await runEvalCli(f.base, preview.plan.sha256);
221
+ assert.ok('agentPreflight' in result);
222
+ assert.ok('costs' in result);
223
+ assert.equal(result.status, 'completed');
224
+ assert.equal(result.evidence.verified, true);
225
+ assert.deepEqual(result.agentPreflight, preview.plan.evaluation.agentPreflight);
226
+ f.conflict();
227
+ rmSync(f.binary);
228
+ rmSync(f.skill, { recursive: true });
229
+ rmSync(f.bench, { recursive: true });
230
+ const run = join(f.base.runsRoot, f.base.runGroup), replay = await reportEvalComponent(run, { replay: true });
231
+ assert.equal(replay.evidence.verified, true);
232
+ assert.deepEqual(replay.agentPreflight, result.agentPreflight);
233
+ const lines = [];
234
+ await runEvalReport(run, line => lines.push(line));
235
+ assert.match(lines.join('\n'), /authentication remains unknown offline/);
236
+ assert.equal(lines.join('\n').includes(f.profile), false);
237
+ const output = join(f.root, 'portable');
238
+ await exportEvaluation(run, output, { yes: true, log: () => { } });
239
+ rmSync(run, { recursive: true });
240
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
241
+ assert.equal(child.status, 0, child.stderr);
242
+ assert.deepEqual(JSON.parse(child.stdout).agentPreflight, result.agentPreflight);
243
+ assert.deepEqual(JSON.parse(child.stdout).costs, result.costs);
244
+ assert.equal(f.calls(), 2);
245
+ });
@@ -0,0 +1,31 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { prepareEvalPlan, confirmEvalPlan, plannedEvalResult } from './eval-plan.js';
4
+ import { reportEvalComponent } from './eval-component.js';
5
+ import { runEval } from './eval.js';
6
+ /** Preserve human CLI behavior while using the same reviewed plan as Agent requests. */
7
+ export async function runEvalCli(options, expectedPlanSha256) {
8
+ const prepared = await prepareEvalPlan(options, {}), { plan } = prepared;
9
+ if (options.dryRun) {
10
+ for (const line of prepared.lines)
11
+ options.log?.(line);
12
+ options.log?.(`Plan SHA : ${plan.sha256}`);
13
+ return plannedEvalResult(plan);
14
+ }
15
+ if (expectedPlanSha256 !== undefined)
16
+ confirmEvalPlan(expectedPlanSha256, plan.sha256);
17
+ const runDir = plan.evaluation.outputDir;
18
+ try {
19
+ await runEval({ ...prepared.options, dryRun: false, reviewedPlan: plan,
20
+ onPlan: preview => { prepared.assertCurrent(preview); options.onPlan?.(preview); } });
21
+ }
22
+ catch (error) {
23
+ if (!existsSync(join(runDir, '_plan.json')))
24
+ throw error;
25
+ const result = await reportEvalComponent(runDir);
26
+ return { ...result, status: 'stopped', plan, executionError: error instanceof Error ? error.message : String(error),
27
+ acceptance: { ...result.acceptance, decision: result.acceptance.decision === 'reject' ? 'reject' : 'inconclusive', eligibleForUpgrade: false,
28
+ reasons: [...result.acceptance.reasons, { code: 'EXECUTION_STOPPED', message: 'Execution stopped; retained receipts do not authorize an upgrade.' }] } };
29
+ }
30
+ return { ...await reportEvalComponent(runDir), plan };
31
+ }
@@ -1,31 +1,44 @@
1
1
  import { existsSync, statSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
3
  import { assessEvaluation } from '../harness/eval-acceptance.js';
5
4
  import { auditEvaluation, stoppedAccounting } from '../harness/eval-audit.js';
6
5
  import { loadEvalRequest, parseAcceptancePolicy, policyHash, readComponentJson, record } from '../harness/eval-contract.js';
7
- import { hashFileSet, listFilesRecursive, sha256Text } from '../harness/hash.js';
8
6
  import { runEval } from './eval.js';
7
+ import { prepareEvalPlan, confirmEvalPlan, plannedEvalResult } from './eval-plan.js';
9
8
  import { spendingBudgetReport } from '../harness/eval-budget.js';
10
9
  import { verifyReplayPackage } from '../harness/replay-package.js';
11
10
  import { CasePreflightFailed } from './eval-preflight.js';
11
+ import { AgentPreflightFailed } from '../harness/agent-preflight.js';
12
+ import { reportSingleArmEvaluation } from './eval-single-arm-replay.js';
13
+ import { historicalInvocationCosts, parseInvocationCosts } from '../harness/invocation-costs.js';
14
+ import { withEvaluationInterrupts } from '../harness/interruption.js';
12
15
  export function componentError(error, code = 'INVALID_OR_FAILED_EVALUATION') {
13
16
  return { schemaVersion: 1, kind: 'skillfit.eval-error', status: 'error',
14
- error: { code: error instanceof CasePreflightFailed ? 'CASE_PREFLIGHT_FAILED' : code, message: error instanceof Error ? error.message : String(error) },
17
+ error: { code: error instanceof CasePreflightFailed ? 'CASE_PREFLIGHT_FAILED' : error instanceof AgentPreflightFailed ? 'AGENT_PREFLIGHT_FAILED' : code, message: error instanceof Error ? error.message : String(error) },
18
+ ...(error instanceof AgentPreflightFailed ? { agentPreflight: error.agentPreflight } : {}),
15
19
  ...(error instanceof CasePreflightFailed ? { casePreflight: error.preflight } : {}),
16
20
  acceptance: { decision: 'inconclusive', eligibleForUpgrade: false, automaticUpgrade: false } };
17
21
  }
18
22
  export async function reportEvalComponent(path, options = {}) {
23
+ return options.replay ? withEvaluationInterrupts(() => readSavedEvaluation(path, options)) : readSavedEvaluation(path, options);
24
+ }
25
+ async function readSavedEvaluation(path, options) {
19
26
  if (statSync(resolve(path)).isDirectory() && existsSync(join(resolve(path), 'replay-package.json'))) {
20
27
  if (options.recordsPath || options.benchDir)
21
28
  throw new Error('Portable packages already pin their run and bench; external overrides are not allowed.');
22
29
  const metadata = verifyReplayPackage(resolve(path));
23
- return { ...await reportNativeEvaluation(join(resolve(path), 'run'), { ...options, benchDir: join(resolve(path), 'inputs/bench') }),
30
+ return { ...await reportNativeEvaluation(join(resolve(path), 'run'), { ...options,
31
+ ...(options.replay ? { benchDir: join(resolve(path), 'inputs/bench') } : {}) }),
24
32
  portablePackage: { integrityVerified: true, sourcePlanSha256: metadata.sourcePlanSha256, files: Object.keys(metadata.files).length } };
25
33
  }
26
34
  return reportNativeEvaluation(path, options);
27
35
  }
28
36
  async function reportNativeEvaluation(path, options) {
37
+ const single = await reportSingleArmEvaluation(path, options);
38
+ if (single) {
39
+ const spendingBudget = spendingBudgetReport(single.evidence.runDir);
40
+ return { ...single, ...(spendingBudget ? { spendingBudget } : {}) };
41
+ }
29
42
  const input = resolve(path), directory = statSync(input).isDirectory();
30
43
  const manifestPath = directory ? join(input, 'manifest.json') : input;
31
44
  const runDir = resolve(options.recordsPath ?? (directory ? input : dirname(input)));
@@ -36,10 +49,13 @@ async function reportNativeEvaluation(path, options) {
36
49
  const sessionPath = join(runDir, '_session.json');
37
50
  const session = existsSync(sessionPath) ? record(readComponentJson(sessionPath).value, 'session') : null;
38
51
  const nativePlan = record(readComponentJson(join(runDir, '_plan.json')).value, 'native plan');
52
+ const costs = stoppedAccounting(runDir);
39
53
  return { schemaVersion: 1, kind: 'skillfit.eval-result', status: session ? 'stopped' : 'incomplete',
54
+ agentPreflight: nativePlan.details ? record(nativePlan.details, 'native plan details').agentPreflight ?? null : null,
40
55
  casePreflight: nativePlan.details ? record(nativePlan.details, 'native plan details').casePreflight ?? null : null,
41
56
  inputSnapshot: nativePlan.inputSnapshot ?? null,
42
- manifest: null, session, costs: stoppedAccounting(runDir), evidence: { verified: false, runDir, reasons: ['No final evaluation manifest; retained spending only.'] },
57
+ manifest: null, session, costs, invocationCosts: costs.invocationCosts,
58
+ evidence: { verified: false, runDir, reasons: ['No final evaluation manifest; retained spending only.'] },
43
59
  ...(spendingBudget ? { spendingBudget } : {}),
44
60
  acceptance: { decision: 'inconclusive', eligibleForUpgrade: false, automaticUpgrade: false,
45
61
  reasons: [{ code: 'EXPERIMENT_NOT_COMPLETED', message: 'No completed paired evaluation is available.' }] } };
@@ -48,8 +64,14 @@ async function reportNativeEvaluation(path, options) {
48
64
  const audit = await auditEvaluation(data.value, runDir, options);
49
65
  const policy = options.policyPath ? parseAcceptancePolicy(readComponentJson(resolve(options.policyPath)).value) : undefined;
50
66
  const result = assessEvaluation(data.value, audit, policy);
67
+ const raw = record(data.value, 'manifest');
68
+ const populations = result.costs.populations?.attempts;
69
+ const invocationCosts = raw.invocationCosts === undefined
70
+ ? populations ? historicalInvocationCosts(combinePopulations(populations.baseline, populations.treatment), raw.judge != null) : null
71
+ : parseInvocationCosts(raw.invocationCosts);
51
72
  const nativePlan = audit.verified ? record(readComponentJson(join(runDir, '_plan.json')).value, 'native plan') : null;
52
- return { ...result, manifest: { path: manifestPath, sha256: data.sha256, schemaVersion: 4 },
73
+ return { ...result, invocationCosts, manifest: { path: manifestPath, sha256: data.sha256, schemaVersion: 4 },
74
+ agentPreflight: nativePlan ? record(nativePlan.details, 'native plan details').agentPreflight ?? null : null,
53
75
  casePreflight: nativePlan ? record(nativePlan.details, 'native plan details').casePreflight ?? null : null,
54
76
  inputSnapshot: nativePlan?.inputSnapshot ?? null,
55
77
  ...(spendingBudget ? { spendingBudget } : {}),
@@ -62,16 +84,27 @@ async function reportNativeEvaluation(path, options) {
62
84
  evidence: { ...result.evidence, runDir, planPath: join(runDir, '_plan.json'),
63
85
  ledgerPath: join(runDir, '_calls.jsonl'), artifactsPath: join(runDir, '_artifacts.json') } };
64
86
  }
87
+ function combinePopulations(a, b) {
88
+ const metrics = Object.fromEntries(Object.entries(a.metrics).map(([key, m]) => {
89
+ const other = b.metrics[key];
90
+ return [key, { knownTotal: m.knownTotal + other.knownTotal,
91
+ coverage: { final: m.coverage.final + other.coverage.final, partial: m.coverage.partial + other.coverage.partial, unknown: m.coverage.unknown + other.coverage.unknown } }];
92
+ }));
93
+ return { runs: a.runs + b.runs, passes: a.passes + b.passes, metrics };
94
+ }
95
+ async function pairedComponentReport(path) {
96
+ const result = await reportEvalComponent(path);
97
+ if ('evaluationType' in result)
98
+ throw new Error('A revision request must produce paired evaluation evidence.');
99
+ return result;
100
+ }
65
101
  /** Machine interface to the existing installed A/B engine; never installs an accepted candidate. */
66
102
  export async function runEvalComponent(requestPath, options) {
67
103
  const path = resolve(requestPath), { request, sha256: requestSha256 } = loadEvalRequest(path);
68
104
  const runDir = join(request.runsRoot, request.runGroup);
69
105
  if (existsSync(runDir))
70
106
  throw new Error('Run group already exists; declare a fresh group without overwriting evidence.');
71
- const implementationDir = fileURLToPath(new URL('../../dist', import.meta.url));
72
- const implementationFiles = listFilesRecursive(implementationDir);
73
- const implementationSha256 = hashFileSet(implementationDir, implementationFiles);
74
- const base = { skillPath: request.candidateSkill, baselineSkillPath: request.baselineSkill,
107
+ const base = { skillPath: request.candidateSkill, baselineSkillPath: request.baselineSkill ?? undefined,
75
108
  bench: request.bench, agent: request.agent, mode: 'installed', inputMode: 'workspace', trials: request.trials,
76
109
  maxCalls: request.maxCalls, pairOrder: request.pairOrder, runsRoot: request.runsRoot, runGroup: request.runGroup, yes: true, dryRun: true,
77
110
  executorTimeoutSeconds: request.executorTimeoutSeconds,
@@ -79,35 +112,26 @@ export async function runEvalComponent(requestPath, options) {
79
112
  ...(request.spendingBudget ? { spendingBudget: request.spendingBudget } : {}),
80
113
  judgeExecutor: null, executor: options.executor, sessionOptions: options.sessionOptions,
81
114
  skillInstallDir: options.skillInstallDir, log: options.log ?? (() => { }) };
82
- let prepared;
83
- await runEval({ ...base, onPlan: preview => { prepared = preview; } });
84
- if (!prepared || !prepared.baseline || prepared.judge)
85
- throw new Error('Component requires a paired installed Skill revision without a judge.');
86
- const describe = (evaluation) => ({ schemaVersion: 1, kind: 'skillfit.eval-plan',
87
- request, requestSha256, policySha256: policyHash(request.policy), implementationSha256, evaluation });
88
- const planData = describe(prepared), previewSha256 = sha256Text(JSON.stringify(planData));
89
- const plan = { ...planData, sha256: previewSha256 };
115
+ const prepared = await prepareEvalPlan(base, { request, requestSha256, policySha256: policyHash(request.policy) });
116
+ const { plan } = prepared, { sha256: previewSha256, implementationSha256 } = plan;
117
+ if (plan.evaluation.judge)
118
+ throw new Error('Component requires a paired installed Skill evaluation without a judge.');
90
119
  if (options.dryRun)
91
- return { schemaVersion: 1, kind: 'skillfit.eval-result', status: 'planned', plan,
92
- acceptance: { decision: 'inconclusive', eligibleForUpgrade: false, automaticUpgrade: false,
93
- reasons: [{ code: 'PLAN_ONLY', message: 'No agent call or outcome is available.' }] } };
94
- if (!options.expectedPlanSha256 || !/^[0-9a-f]{64}$/i.test(options.expectedPlanSha256) || options.expectedPlanSha256.toLowerCase() !== previewSha256) {
95
- throw new Error('Execution requires --plan-sha matching the current dry-run plan; inputs, policy, executor or implementation changed.');
96
- }
120
+ return plannedEvalResult(plan);
121
+ confirmEvalPlan(options.expectedPlanSha256, previewSha256);
97
122
  const component = { schemaVersion: 1, requestSha256, previewSha256, implementationSha256, policySha256: policyHash(request.policy),
98
123
  purpose: request.purpose, policy: request.policy, synthetic: options.executor !== undefined };
99
124
  try {
100
125
  await runEval({ ...base, dryRun: false, component, guardFiles: [{ label: 'component request', path, sha256: requestSha256 }],
101
- onPlan: preview => { if (sha256Text(JSON.stringify(describe(preview))) !== previewSha256)
102
- throw new Error('Plan changed before execution; no calls allowed.'); } });
126
+ onPlan: prepared.assertCurrent });
103
127
  }
104
128
  catch (error) {
105
129
  if (!existsSync(join(runDir, '_plan.json')))
106
130
  throw error;
107
- const result = await reportEvalComponent(runDir);
131
+ const result = await pairedComponentReport(runDir);
108
132
  return { ...result, status: 'stopped', plan, executionError: error instanceof Error ? error.message : String(error),
109
133
  acceptance: { ...result.acceptance, decision: result.acceptance.decision === 'reject' ? 'reject' : 'inconclusive', eligibleForUpgrade: false,
110
134
  reasons: [...result.acceptance.reasons, { code: 'EXECUTION_STOPPED', message: 'Request execution failed; inspect retained receipts before a fresh declaration.' }] } };
111
135
  }
112
- return { ...await reportEvalComponent(runDir), plan };
136
+ return { ...await pairedComponentReport(runDir), plan };
113
137
  }