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
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import { test } from 'node:test';
6
6
  import { runEvalComponent, reportEvalComponent } from '../commands/eval-component.js';
7
7
  import { parseEvalRequest } from './eval-contract.js';
8
- import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
8
+ import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState, spendingStopFrom, SpendingBudgetStop } from './eval-budget.js';
9
9
  import { COST_METRICS } from './costs.js';
10
10
  import { sha256File } from './hash.js';
11
11
  import { ExecutorFailure } from './types.js';
@@ -36,6 +36,25 @@ test('all-invocation budgets count functional failures, partial costs and unknow
36
36
  assert.equal(state.metrics.input.coverage.partial, 1);
37
37
  assert.equal(state.reason, 'FINAL_USAGE_MISSING');
38
38
  });
39
+ test('budget stop codes survive trusted cause chains without treating arbitrary error text as safe diagnostics', () => {
40
+ const state = spendingBudgetState({ ...limits, input: 10 }, [observation()]);
41
+ let stopped;
42
+ try {
43
+ assertSpendingCanContinue(state);
44
+ }
45
+ catch (error) {
46
+ stopped = error;
47
+ }
48
+ assert.ok(stopped instanceof SpendingBudgetStop);
49
+ assert.equal(stopped.code, 'SPENDING_BUDGET_REACHED');
50
+ assert.equal(spendingStopFrom(new Error('wrapper', { cause: stopped })), stopped);
51
+ const ordinary = new Error('SPENDING_BUDGET_REACHED: private credential text');
52
+ ordinary.name = 'SpendingBudgetStop';
53
+ assert.equal(spendingStopFrom(ordinary), null);
54
+ const cycle = new Error('cyclic cause');
55
+ cycle.cause = cycle;
56
+ assert.equal(spendingStopFrom(cycle), null);
57
+ });
39
58
  function setup(t, change = {}, result, functionalFailure = false) {
40
59
  const root = mkdtempSync(join(tmpdir(), 'skillfit-budget-'));
41
60
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -47,7 +66,7 @@ function setup(t, change = {}, result, functionalFailure = false) {
47
66
  mkdirSync(join(bench, 'fixture'), { recursive: true });
48
67
  writeFileSync(join(bench, 'fixture/answer.txt'), 'pending');
49
68
  writeFileSync(join(bench, 'prompt.md'), 'Repair the answer.');
50
- writeFileSync(join(bench, 'check.mjs'), `const passed=${!functionalFailure};console.log(JSON.stringify({passed,checks:[{name:'answer',pass:passed}]}));process.exit(passed?0:1);\n`);
69
+ writeFileSync(join(bench, 'check.mjs'), `import{readFileSync}from'node:fs';import{join}from'node:path';const passed=readFileSync(join(process.argv[2],'answer.txt'),'utf8')==='fixed';console.log(JSON.stringify({passed,checks:[{name:'answer',pass:passed}]}));process.exit(passed?0:1);\n`);
51
70
  writeFileSync(join(bench, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'budget', tasks: [
52
71
  { id: 'first', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs', verifierKind: 'command' },
53
72
  { id: 'second', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs', verifierKind: 'command' },
@@ -57,7 +76,9 @@ function setup(t, change = {}, result, functionalFailure = false) {
57
76
  const request = join(root, 'request.json');
58
77
  writeFileSync(request, JSON.stringify(body));
59
78
  let count = 0;
60
- const executor = { describe: () => ({ kind: 'mock', model: 'offline-budget' }), run: async () => {
79
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-budget' }), run: async (_prompt, workdir) => {
80
+ if (!functionalFailure)
81
+ writeFileSync(join(workdir, 'answer.txt'), 'fixed');
61
82
  count++;
62
83
  return result ? result() : { output: 'done', tokens: { input: 10, cachedInput: 6, output: 3 } };
63
84
  } };
@@ -81,6 +102,9 @@ for (const metric of COST_METRICS)
81
102
  const receipt = JSON.parse(readFileSync(join(f.directory, 'first/baseline/trial-1/_result.json'), 'utf8'));
82
103
  assert.deepEqual(receipt.tokens, { input: 10, cachedInput: 6, output: 3 });
83
104
  assert.equal(existsSync(join(f.directory, 'first/treatment/trial-1')), false);
105
+ const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
106
+ assert.equal(session.stopCode, 'SPENDING_BUDGET_REACHED');
107
+ assert.match(session.stopReason, /SPENDING_BUDGET_REACHED/);
84
108
  assert.ok('spendingBudget' in result);
85
109
  assert.ok(result.spendingBudget);
86
110
  assert.ok(result.spendingBudget.latestState.reached.includes(metric));
@@ -104,6 +128,9 @@ for (const [label, tokens] of [['no counters', undefined], ['missing cache', { i
104
128
  assert.equal(f.calls(), 1);
105
129
  assert.equal(result.status, 'stopped');
106
130
  assert.equal(result.acceptance.eligibleForUpgrade, false);
131
+ const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
132
+ assert.equal(session.stopCode, 'FINAL_USAGE_MISSING');
133
+ assert.match(session.stopReason, /FINAL_USAGE_MISSING/);
107
134
  assert.ok('spendingBudget' in result);
108
135
  assert.ok(result.spendingBudget);
109
136
  assert.equal(result.spendingBudget.latestState.reason, 'FINAL_USAGE_MISSING');
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url';
8
8
  import { reportEvalComponent, runEvalComponent } from '../commands/eval-component.js';
9
9
  import { exportEvaluation } from '../commands/eval-export.js';
10
10
  import { runEval } from '../commands/eval.js';
11
+ import { runEvalCli } from '../commands/eval-cli.js';
11
12
  import { assessEvaluation } from './eval-acceptance.js';
12
13
  import { parseAcceptancePolicy, parseEvalRequest, policyHash } from './eval-contract.js';
13
14
  import { hashFileSet, listFilesRecursive, sha256File } from './hash.js';
@@ -68,15 +69,15 @@ test('component exports include the frozen request and both complete Skills and
68
69
  const f = await run(t), output = join(f.root, 'portable');
69
70
  const originalRequest = readFileSync(f.requestPath, 'utf8');
70
71
  writeFileSync(f.requestPath, '{}');
71
- await assert.rejects(() => exportEvaluation(f.runDir, output, { yes: true, log: () => { } }), /request changed/);
72
- const recovered = join(f.root, 'recovered-request.json');
73
- writeFileSync(recovered, originalRequest);
74
- await exportEvaluation(f.runDir, output, { yes: true, inputRoots: [`request=${recovered}`], log: () => { } });
72
+ for (const path of ['bench', 'old', 'new'])
73
+ rmSync(join(f.root, path), { recursive: true });
74
+ const nativeReplay = await reportEvalComponent(f.runDir, { replay: true });
75
+ assert.ok('evidence' in nativeReplay && nativeReplay.evidence.verified);
76
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
75
77
  assert.equal(readFileSync(join(output, 'inputs/request.json'), 'utf8'), originalRequest);
76
78
  assert.equal(readFileSync(join(output, 'inputs/baseline-skill/answer.txt'), 'utf8'), '1');
77
79
  assert.equal(readFileSync(join(output, 'inputs/target/answer.txt'), 'utf8'), '2');
78
- for (const path of ['bench', 'old', 'new', 'runs'])
79
- rmSync(join(f.root, path), { recursive: true });
80
+ rmSync(join(f.root, 'runs'), { recursive: true });
80
81
  const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
81
82
  assert.equal(child.status, 0, child.stderr);
82
83
  const replay = JSON.parse(child.stdout);
@@ -316,6 +317,7 @@ test('changing the request policy during a call stops further calls and retains
316
317
  assert.ok('costs' in result);
317
318
  assert.equal(result.costs.populations?.attempts.baseline.metrics.input.knownTotal, 10);
318
319
  const replay = await reportEvalComponent(f.runDir);
320
+ assert.ok('costs' in replay);
319
321
  assert.deepEqual(replay.costs, result.costs);
320
322
  });
321
323
  test('executor failures preserve partial usage and missing cache counts remain unknown', async (t) => {
@@ -605,3 +607,164 @@ test('CLI request plans and errors emit one parseable JSON document without agen
605
607
  assert.match(JSON.parse(mixed.stdout).error.message, /cannot be combined/);
606
608
  assert.equal(existsSync(join(f.root, 'runs')), false);
607
609
  });
610
+ test('an explicit null baseline installs no Skill in baseline, preserves identical prompts and replays without originals', async (t) => {
611
+ const f = setup(t), seen = [], prompts = [];
612
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, baselineSkill: null, taskIds: ['fix'], maxCalls: 2, executorTimeoutSeconds: 17 }));
613
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-no-skill' }), run: async (prompt, workdir) => {
614
+ prompts.push(prompt);
615
+ const installed = existsSync(join(workdir, 'project-skills/answer-skill/SKILL.md'));
616
+ seen.push(installed);
617
+ writeFileSync(join(workdir, 'answer.txt'), installed ? '2' : '1');
618
+ return { output: 'done', tokens: { input: 10, cachedInput: 6, output: 2 } };
619
+ } };
620
+ const options = { ...f.options, executor }, preview = await runEvalComponent(f.requestPath, { ...options, dryRun: true });
621
+ assert.equal(preview.plan.request.baselineSkill, null);
622
+ assert.equal(preview.plan.evaluation.baseline, null);
623
+ assert.equal(preview.plan.evaluation.executorTimeoutSeconds, 17);
624
+ assert.equal(preview.plan.evaluation.plannedCalls, 2);
625
+ assert.equal(existsSync(f.runDir), false);
626
+ assert.equal(seen.length, 0);
627
+ const result = await runEvalComponent(f.requestPath, { ...options, dryRun: false, expectedPlanSha256: preview.plan.sha256 });
628
+ assert.deepEqual(seen, [false, true]);
629
+ assert.equal(prompts[0], prompts[1]);
630
+ assert.ok('identity' in result);
631
+ assert.equal(result.identity.baseline, null);
632
+ assert.equal(result.evidence.verified, true);
633
+ assert.ok(result.acceptance.reasons.some(r => r.code === 'REVISION_COMPARISON_REQUIRED'));
634
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
635
+ for (const path of [f.requestPath, join(f.root, 'bench'), join(f.root, 'old'), join(f.root, 'new')])
636
+ rmSync(path, { recursive: true });
637
+ const replay = await reportEvalComponent(f.runDir, { replay: true });
638
+ assert.equal(replay.evidence.verified, true);
639
+ const output = join(f.root, 'portable');
640
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
641
+ assert.equal(existsSync(join(output, 'inputs/baseline-skill')), false);
642
+ assert.equal(JSON.parse(readFileSync(join(output, 'inputs/request.json'), 'utf8')).baselineSkill, null);
643
+ rmSync(f.runDir, { recursive: true });
644
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
645
+ assert.equal(child.status, 0, child.stderr);
646
+ const portable = JSON.parse(child.stdout);
647
+ assert.equal(portable.identity.baseline, null);
648
+ assert.equal(portable.acceptance.eligibleForUpgrade, false);
649
+ assert.equal(seen.length, 2);
650
+ });
651
+ test('null is an explicit baseline choice; missing, empty or malformed paths never silently select it', t => {
652
+ const f = setup(t), { baselineSkill: _previous, ...missing } = f.body;
653
+ assert.equal(parseEvalRequest({ ...f.body, baselineSkill: null }, f.root).baselineSkill, null);
654
+ assert.equal(parseEvalRequest(f.body, f.root).baselineSkill, join(f.root, 'old'));
655
+ for (const baselineSkill of [undefined, '', false, 0, {}])
656
+ assert.throws(() => parseEvalRequest({ ...f.body, baselineSkill }, f.root), /baselineSkill/);
657
+ assert.throws(() => parseEvalRequest(missing, f.root), /baselineSkill/);
658
+ assert.equal(f.calls(), 0);
659
+ });
660
+ function ordinaryOptions(f, overrides = {}) {
661
+ return { skillPath: join(f.root, 'new'), baselineSkillPath: join(f.root, 'old'), bench: join(f.root, 'bench'), agent: 'codex',
662
+ mode: 'installed', inputMode: 'workspace', trials: 1, maxCalls: 4, runsRoot: join(f.root, 'runs'), runGroup: 'component',
663
+ dryRun: true, yes: true, ...f.options, log: () => { }, ...overrides };
664
+ }
665
+ test('ordinary eval and request preview share the effective plan, timeout and all spending lines', async (t) => {
666
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
667
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget }));
668
+ const request = await runEvalComponent(f.requestPath, { ...f.options, dryRun: true });
669
+ const ordinary = await runEvalCli(ordinaryOptions(f, { pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget }));
670
+ assert.ok('plan' in ordinary);
671
+ assert.deepEqual(ordinary.plan.evaluation, request.plan.evaluation);
672
+ assert.equal(ordinary.plan.implementationSha256, request.plan.implementationSha256);
673
+ assert.equal(ordinary.status, 'planned');
674
+ assert.equal(ordinary.acceptance.eligibleForUpgrade, false);
675
+ assert.equal(existsSync(join(f.root, 'runs')), false);
676
+ assert.equal(f.calls(), 0);
677
+ });
678
+ test('ordinary confirmed plans reject changed budget, timeout, ordering, selection and baseline before calls', async (t) => {
679
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
680
+ const base = ordinaryOptions(f, { pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget });
681
+ const preview = await runEvalCli(base);
682
+ assert.ok('plan' in preview);
683
+ for (const change of [{ executorTimeoutSeconds: 18 }, { pairOrder: 'baseline-first' }, { spendingBudget: { ...spendingBudget, input: 999 } },
684
+ { maxCalls: 5 }, { taskIds: ['fix'] }, { baselineSkillPath: undefined }]) {
685
+ await assert.rejects(() => runEvalCli({ ...base, ...change, dryRun: false }, preview.plan.sha256), /--plan-sha matching/);
686
+ }
687
+ assert.equal(f.calls(), 0);
688
+ assert.equal(existsSync(f.runDir), false);
689
+ });
690
+ test('ordinary execution seals the shared reviewed plan and retains replayable costs without component adoption', async (t) => {
691
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
692
+ const base = ordinaryOptions(f, { executorTimeoutSeconds: 17, pairOrder: 'balanced', spendingBudget });
693
+ const preview = await runEvalCli(base);
694
+ assert.ok('plan' in preview);
695
+ const result = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
696
+ assert.equal(result.status, 'completed');
697
+ assert.ok('evidence' in result);
698
+ assert.equal(result.evidence.verified, true, result.evidence.reasons.join('; '));
699
+ assert.ok('costs' in result);
700
+ const native = JSON.parse(readFileSync(join(f.runDir, '_plan.json'), 'utf8'));
701
+ assert.deepEqual(native.details.reviewedPlan, preview.plan);
702
+ assert.equal(native.details.executorTimeoutSeconds, 17);
703
+ assert.equal(native.details.component, undefined);
704
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
705
+ for (const path of ['bench', 'old', 'new'])
706
+ rmSync(join(f.root, path), { recursive: true });
707
+ const replay = await reportEvalComponent(f.runDir, { replay: true });
708
+ assert.equal(replay.evidence.verified, true);
709
+ assert.ok('costs' in replay);
710
+ assert.deepEqual(replay.costs, result.costs);
711
+ assert.deepEqual(replay.spendingBudget?.limits, spendingBudget);
712
+ const output = join(f.root, 'portable');
713
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
714
+ rmSync(f.runDir, { recursive: true });
715
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
716
+ assert.equal(child.status, 0, child.stderr);
717
+ const portable = JSON.parse(child.stdout);
718
+ assert.equal(portable.evidence.verified, true);
719
+ assert.deepEqual(portable.costs, result.costs);
720
+ assert.deepEqual(portable.spendingBudget.limits, spendingBudget);
721
+ assert.equal(portable.acceptance.eligibleForUpgrade, false);
722
+ assert.equal(f.calls(), 4);
723
+ });
724
+ test('ordinary and Agent no-Skill comparisons stop at the same budget line and keep the one invoked receipt', async (t) => {
725
+ const f = setup(t), spendingBudget = { input: 10, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 };
726
+ let calls = 0;
727
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-common-budget' }), run: async (_prompt, workdir) => {
728
+ calls++;
729
+ assert.equal(existsSync(join(workdir, 'project-skills/answer-skill')), false);
730
+ writeFileSync(join(workdir, 'answer.txt'), '1');
731
+ return { output: 'done', tokens: { input: 10, cachedInput: 6, output: 2 } };
732
+ } };
733
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, baselineSkill: null, taskIds: ['fix'], maxCalls: 2, spendingBudget }));
734
+ const requestPreview = await runEvalComponent(f.requestPath, { ...f.options, executor, dryRun: true });
735
+ const request = await runEvalComponent(f.requestPath, { ...f.options, executor, dryRun: false, expectedPlanSha256: requestPreview.plan.sha256 });
736
+ const base = ordinaryOptions(f, { baselineSkillPath: undefined, taskIds: ['fix'], maxCalls: 2, spendingBudget, executor, runGroup: 'ordinary' });
737
+ const preview = await runEvalCli(base);
738
+ assert.ok('plan' in preview);
739
+ const ordinary = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
740
+ for (const result of [request, ordinary]) {
741
+ assert.equal(result.status, 'stopped');
742
+ assert.ok('spendingBudget' in result && result.spendingBudget);
743
+ assert.equal(result.spendingBudget.latestState.metrics.input.knownTotal, 10);
744
+ assert.ok(result.spendingBudget.latestState.reached.includes('input'));
745
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
746
+ }
747
+ assert.equal(calls, 2);
748
+ assert.equal(existsSync(join(f.runDir, 'fix/treatment/trial-1')), false);
749
+ assert.equal(existsSync(join(f.root, 'runs/ordinary/fix/treatment/trial-1')), false);
750
+ });
751
+ for (const [label, tokens] of [['missing cache', { input: 10, output: 2 }], ['partial', { input: 10, cachedInput: 6, output: 2 }]]) {
752
+ test(`ordinary ${label} usage cannot authorize a second budgeted invocation`, async (t) => {
753
+ const f = setup(t);
754
+ let calls = 0;
755
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-incomplete-budget' }), run: async (_prompt, workdir) => {
756
+ calls++;
757
+ writeFileSync(join(workdir, 'answer.txt'), '1');
758
+ return { output: 'done', tokens, ...(label === 'partial' ? { usageStatus: 'partial' } : {}) };
759
+ } };
760
+ const base = ordinaryOptions(f, { executor, spendingBudget: { input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 } });
761
+ const preview = await runEvalCli(base);
762
+ assert.ok('plan' in preview);
763
+ const result = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
764
+ assert.equal(result.status, 'stopped');
765
+ assert.equal(calls, 1);
766
+ assert.ok('spendingBudget' in result && result.spendingBudget);
767
+ assert.equal(result.spendingBudget.latestState.reason, 'FINAL_USAGE_MISSING');
768
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
769
+ });
770
+ }
@@ -28,6 +28,14 @@ function numeric(value, label, min, max = Number.MAX_SAFE_INTEGER, integer = fal
28
28
  }
29
29
  return value;
30
30
  }
31
+ export function parseExecutorTimeoutSeconds(value = DEFAULT_CLI_TIMEOUT_MS / 1000, label = 'executorTimeoutSeconds') {
32
+ return numeric(value, label, 1, 3600, true);
33
+ }
34
+ export function parsePairOrder(value = 'baseline-first', label = 'pairOrder') {
35
+ if (value !== 'baseline-first' && value !== 'balanced')
36
+ throw new Error(`${label} must be baseline-first or balanced.`);
37
+ return value;
38
+ }
31
39
  export function parseAcceptancePolicy(value = {}) {
32
40
  const p = record(value, 'policy');
33
41
  if (p.schemaVersion === 2) {
@@ -79,18 +87,16 @@ export function parseEvalRequest(value, baseDir) {
79
87
  getAgent(agent);
80
88
  if (r.purpose !== 'development' && r.purpose !== 'validation')
81
89
  throw new Error('request.purpose must be development or validation.');
82
- if (r.pairOrder !== undefined && r.pairOrder !== 'baseline-first' && r.pairOrder !== 'balanced')
83
- throw new Error('request.pairOrder must be baseline-first or balanced.');
84
90
  const runGroup = text(r.runGroup, 'request.runGroup');
85
91
  if (!RUN_GROUP_PATTERN.test(runGroup))
86
92
  throw new Error('request.runGroup is invalid.');
87
93
  return { schemaVersion: 1,
88
- baselineSkill: resolve(baseDir, text(r.baselineSkill, 'request.baselineSkill')),
94
+ baselineSkill: r.baselineSkill === null ? null : resolve(baseDir, text(r.baselineSkill, 'request.baselineSkill (use null for no installed Skill)')),
89
95
  candidateSkill: resolve(baseDir, text(r.candidateSkill, 'request.candidateSkill')),
90
96
  bench: resolve(baseDir, text(r.bench, 'request.bench')),
91
97
  ...(r.taskIds !== undefined ? { taskIds: parseTaskIds(r.taskIds) } : {}),
92
- agent, purpose: r.purpose, pairOrder: r.pairOrder ?? 'baseline-first',
93
- executorTimeoutSeconds: numeric(r.executorTimeoutSeconds ?? DEFAULT_CLI_TIMEOUT_MS / 1000, 'request.executorTimeoutSeconds', 1, 3600, true),
98
+ agent, purpose: r.purpose, pairOrder: parsePairOrder(r.pairOrder, 'request.pairOrder'),
99
+ executorTimeoutSeconds: parseExecutorTimeoutSeconds(r.executorTimeoutSeconds, 'request.executorTimeoutSeconds'),
94
100
  trials: numeric(r.trials, 'request.trials', 1, 20, true),
95
101
  maxCalls: numeric(r.maxCalls, 'request.maxCalls', 1, Number.MAX_SAFE_INTEGER, true),
96
102
  ...(r.spendingBudget !== undefined ? { spendingBudget: parseSpendingBudget(r.spendingBudget) } : {}),
@@ -1,3 +1,4 @@
1
+ import { evaluationSignal } from '../interruption.js';
1
2
  function tokenCount(value) {
2
3
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
3
4
  }
@@ -6,14 +7,20 @@ function tokenUsage(usage) {
6
7
  return undefined;
7
8
  const input = tokenCount(usage.prompt_tokens);
8
9
  const output = tokenCount(usage.completion_tokens);
10
+ const details = usage.prompt_tokens_details;
11
+ const cached = details && typeof details === 'object' && !Array.isArray(details)
12
+ ? tokenCount(details.cached_tokens) : undefined;
13
+ const cachedInput = input !== undefined && Number.isSafeInteger(input) && cached !== undefined && Number.isSafeInteger(cached) && cached <= input
14
+ ? cached : undefined;
9
15
  if (input === undefined && output === undefined)
10
16
  return undefined;
11
17
  return {
12
18
  ...(input !== undefined ? { input } : {}),
13
19
  ...(output !== undefined ? { output } : {}),
20
+ ...(cachedInput !== undefined ? { cachedInput } : {}),
14
21
  };
15
22
  }
16
- const DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
23
+ export const DEFAULT_API_TIMEOUT_MS = 2 * 60 * 1000;
17
24
  export class ApiExecutor {
18
25
  apiKey;
19
26
  model;
@@ -27,11 +34,12 @@ export class ApiExecutor {
27
34
  this.apiKey = options.apiKey;
28
35
  this.model = options.model ?? 'gpt-4o';
29
36
  this.baseUrl = (options.baseUrl ?? 'https://api.openai.com/v1').replace(/\/+$/, '');
30
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_API_TIMEOUT_MS;
31
38
  this.fetchImpl = options.fetchImpl ?? fetch;
32
39
  }
33
- static fromEnv(env = process.env) {
40
+ static fromEnv(env = process.env, options = {}) {
34
41
  return new ApiExecutor({
42
+ ...options,
35
43
  apiKey: env['SKILLFIT_API_KEY'] ?? env['OPENAI_API_KEY'],
36
44
  model: env['SKILLFIT_API_MODEL'],
37
45
  baseUrl: env['SKILLFIT_API_BASE_URL'],
@@ -41,6 +49,8 @@ export class ApiExecutor {
41
49
  return { kind: 'api', model: this.model, detail: this.baseUrl, sampling: null };
42
50
  }
43
51
  async run(prompt, _workdir) {
52
+ const interrupted = evaluationSignal();
53
+ interrupted?.throwIfAborted();
44
54
  const response = await this.fetchImpl(`${this.baseUrl}/chat/completions`, {
45
55
  method: 'POST',
46
56
  headers: {
@@ -51,7 +61,7 @@ export class ApiExecutor {
51
61
  model: this.model,
52
62
  messages: [{ role: 'user', content: prompt }],
53
63
  }),
54
- signal: AbortSignal.timeout(this.timeoutMs),
64
+ signal: interrupted ? AbortSignal.any([interrupted, AbortSignal.timeout(this.timeoutMs)]) : AbortSignal.timeout(this.timeoutMs),
55
65
  });
56
66
  if (!response.ok) {
57
67
  const body = (await response.text()).slice(0, 300);
@@ -1,6 +1,8 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { test } from 'node:test';
3
3
  import { ApiExecutor } from './api.js';
4
+ import { summarizeCosts } from '../costs.js';
5
+ import { spendingBudgetState } from '../eval-budget.js';
4
6
  function jsonResponse(body, status = 200) {
5
7
  return new Response(JSON.stringify(body), {
6
8
  status,
@@ -34,6 +36,47 @@ test('ApiExecutor throws on non-2xx responses', async () => {
34
36
  const executor = new ApiExecutor({ apiKey: 'k', fetchImpl });
35
37
  await assert.rejects(() => executor.run('hi', '/tmp'), /status 500/);
36
38
  });
39
+ test('API cache counts reach cost partitions and budget stop lines without double counting', async () => {
40
+ for (const cached of [0, 80, 100]) {
41
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
42
+ usage: { prompt_tokens: 100, completion_tokens: 10, prompt_tokens_details: { cached_tokens: cached } } });
43
+ const result = await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline');
44
+ assert.deepEqual(result.tokens, { input: 100, output: 10, cachedInput: cached });
45
+ const record = { executorInvoked: true, passed: true, error: null, durationSeconds: 1, tokens: result.tokens, usageStatus: 'final' };
46
+ const costs = summarizeCosts({ baseline: [record], treatment: [] }, { baseline: [record], treatment: [] });
47
+ const metrics = costs.attempts.baseline.metrics;
48
+ assert.equal(metrics.input.knownTotal, 100);
49
+ assert.equal(metrics.cachedInput.knownTotal, cached);
50
+ assert.equal(metrics.uncachedInput.knownTotal, 100 - cached);
51
+ assert.equal(metrics.cachedInput.coverage.final, 1);
52
+ const state = spendingBudgetState({ input: 100, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 }, [record]);
53
+ assert.equal(state.incomplete.length, 0);
54
+ assert.ok(state.reached.includes('input'));
55
+ }
56
+ });
57
+ test('missing, malformed and incompatible API cache counts stay unknown rather than becoming zero', async () => {
58
+ const cases = [undefined, null, false, 'cache', [], {}, { cached_tokens: null }, { cached_tokens: '0' },
59
+ { cached_tokens: -1 }, { cached_tokens: 101 }, { cached_tokens: 0.5 }, { cached_tokens: Number.MAX_SAFE_INTEGER + 1 }];
60
+ for (const details of cases) {
61
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
62
+ usage: { prompt_tokens: 100, completion_tokens: 10, prompt_tokens_details: details } });
63
+ const tokens = (await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline')).tokens;
64
+ assert.deepEqual(tokens, { input: 100, output: 10 });
65
+ const state = spendingBudgetState({ input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 }, [{ executorInvoked: true, passed: true, error: null, durationSeconds: 1, tokens, usageStatus: 'final' }]);
66
+ assert.equal(state.reason, 'FINAL_USAGE_MISSING');
67
+ assert.ok(state.incomplete.includes('cachedInput'));
68
+ assert.equal(state.metrics.uncachedInput.coverage.unknown, 1);
69
+ }
70
+ });
71
+ test('cache counts without a valid input total cannot establish an API input partition', async () => {
72
+ for (const input of [undefined, null, '100', -1, 0.5]) {
73
+ const fetchImpl = async () => jsonResponse({ choices: [{ message: { content: 'offline' } }],
74
+ usage: { prompt_tokens: input, completion_tokens: 10, prompt_tokens_details: { cached_tokens: 0 } } });
75
+ const tokens = (await new ApiExecutor({ apiKey: 'offline-only', fetchImpl }).run('offline')).tokens;
76
+ assert.equal(tokens.cachedInput, undefined);
77
+ assert.equal(tokens.output, 10);
78
+ }
79
+ });
37
80
  test('ApiExecutor ignores usage objects that do not contain finite token counts', async () => {
38
81
  const fetchImpl = (async () => jsonResponse({
39
82
  choices: [{ message: { content: 'answer' } }],
@@ -73,3 +116,21 @@ test('ApiExecutor.fromEnv reads SKILLFIT_API_KEY first', () => {
73
116
  test('ApiExecutor.fromEnv throws without any key', () => {
74
117
  assert.throws(() => ApiExecutor.fromEnv({}), /API key/);
75
118
  });
119
+ test('API environment construction applies an explicit deadline to fake fetch without any network call', async () => {
120
+ let observed = false;
121
+ const executor = ApiExecutor.fromEnv({ SKILLFIT_API_KEY: 'offline-only' }, { timeoutMs: 10,
122
+ fetchImpl: async (_url, init) => new Promise((_resolve, reject) => {
123
+ observed = true;
124
+ const signal = init.signal;
125
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
126
+ }) });
127
+ // AbortSignal.timeout uses an unreferenced timer; keep only this offline test alive.
128
+ const timer = setTimeout(() => { }, 1000);
129
+ try {
130
+ await assert.rejects(() => executor.run('offline'), error => error instanceof Error && error.name === 'TimeoutError');
131
+ }
132
+ finally {
133
+ clearTimeout(timer);
134
+ }
135
+ assert.equal(observed, true);
136
+ });
@@ -7,6 +7,7 @@ import { probeKimiSessionUsage } from '../kimi-usage.js';
7
7
  import { probeCodexPartialUsage } from '../codex-usage.js';
8
8
  import { ExecutorFailure } from '../types.js';
9
9
  import { ExecutionDeadline } from '../execution-timing.js';
10
+ import { evaluationSignal } from '../interruption.js';
10
11
  export const DEFAULT_CLI_TIMEOUT_MS = 10 * 60 * 1000;
11
12
  const MAX_AGENT_OUTPUT_BYTES = 32 * 1024 * 1024;
12
13
  const DEFAULT_PROMPT_FILE = '_prompt.txt';
@@ -137,6 +138,9 @@ export class CliExecutor {
137
138
  };
138
139
  }
139
140
  run(prompt, workdir) {
141
+ const signal = evaluationSignal();
142
+ if (signal?.aborted)
143
+ return Promise.reject(new ExecutorFailure(String(signal.reason), { output: '' }, false));
140
144
  const startedAtMs = Date.now();
141
145
  let argv = this.argv;
142
146
  if (this.projectTrustConfigArg) {
@@ -195,7 +199,7 @@ export class CliExecutor {
195
199
  }
196
200
  return new ExecutorFailure(message, { ...result, usageStatus: 'partial' });
197
201
  };
198
- const stopMessage = () => overflow
202
+ const stopMessage = () => signal?.aborted ? signal.reason.message : overflow
199
203
  ? `"${command}" produced more than ${MAX_AGENT_OUTPUT_BYTES} bytes of output`
200
204
  : deadline.timingError ? `"${command}" execution timing anomaly: ${deadline.timingError}`
201
205
  : `"${command}" timed out after ${this.timeoutMs}ms`;
@@ -229,7 +233,13 @@ export class CliExecutor {
229
233
  checkDeadline();
230
234
  }, this.timeoutMs);
231
235
  const heartbeat = setInterval(() => checkDeadline(), deadline.heartbeatMs);
232
- const clearTimers = () => { clearTimeout(timer); clearInterval(heartbeat); clearTimeout(drainTimer); };
236
+ const onAbort = () => stopChild();
237
+ const clearTimers = () => {
238
+ clearTimeout(timer);
239
+ clearInterval(heartbeat);
240
+ clearTimeout(drainTimer);
241
+ signal?.removeEventListener('abort', onAbort);
242
+ };
233
243
  const take = (chunk, sink) => {
234
244
  checkDeadline();
235
245
  bytes += chunk.length;
@@ -253,6 +263,10 @@ export class CliExecutor {
253
263
  child.on('close', (code) => {
254
264
  checkDeadline(false);
255
265
  clearTimers();
266
+ if (signal?.aborted) {
267
+ rejectPromise(failure(stopMessage()));
268
+ return;
269
+ }
256
270
  if (overflow) {
257
271
  rejectPromise(failure(`"${command}" produced more than ${MAX_AGENT_OUTPUT_BYTES} bytes of output`));
258
272
  return;
@@ -287,12 +301,19 @@ export class CliExecutor {
287
301
  }
288
302
  resolvePromise(result);
289
303
  });
290
- if (this.promptVia === 'stdin') {
304
+ signal?.addEventListener('abort', onAbort, { once: true });
305
+ if (signal?.aborted)
306
+ onAbort();
307
+ if (this.promptVia === 'stdin' && !signal?.aborted) {
291
308
  // A child that exits before draining stdin makes the write fail (EPIPE on POSIX, EOF on
292
309
  // Windows). With no listener that surfaces as an uncaught exception rather than a rejection,
293
310
  // so the caller's catch never runs and the process dies mid-trial leaving a half-populated
294
311
  // run group behind. Reject instead, and kill the child so it cannot outlive the failure.
295
312
  child.stdin.on('error', (error) => {
313
+ // Killing the tree can close stdin too. Let close/the bounded drain
314
+ // retain parsed usage instead of replacing cancellation with EPIPE.
315
+ if (stopping)
316
+ return;
296
317
  clearTimers();
297
318
  deadline.observe();
298
319
  killTree(child);