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
@@ -116,3 +116,21 @@ test('ApiExecutor.fromEnv reads SKILLFIT_API_KEY first', () => {
116
116
  test('ApiExecutor.fromEnv throws without any key', () => {
117
117
  assert.throws(() => ApiExecutor.fromEnv({}), /API key/);
118
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
+ });
@@ -3,7 +3,7 @@ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlin
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
- import { getAgent, skillUserDirSpecs } from '../agents.js';
6
+ import { getAgent } from '../agents.js';
7
7
  import { parseFrontmatter } from '../frontmatter.js';
8
8
  import { hashFileSet, sha256File, sha256Text } from './hash.js';
9
9
  import { assertNativeDiffFile, assertNativeDiffWorkspace, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
@@ -11,6 +11,8 @@ import { ExecutorFailure } from './types.js';
11
11
  import { EvaluationInterrupted, evaluationSignal, throwIfEvaluationInterrupted } from './interruption.js';
12
12
  import { freezeInputSnapshot, verifyInputSnapshot } from './input-snapshot.js';
13
13
  import { loadBench } from './bench.js';
14
+ import { globalSkillRoots } from './agent-preflight.js';
15
+ import { spendingStopFrom } from './eval-budget.js';
14
16
  function skillInventory(root) {
15
17
  if (!existsSync(root))
16
18
  return { root, entries: ['missing'] };
@@ -163,6 +165,7 @@ export class ExperimentSession {
163
165
  callsStarted = 0;
164
166
  callsFinished = 0;
165
167
  stopReason = null;
168
+ stopCode;
166
169
  finished = false;
167
170
  guardFiles;
168
171
  nativeDiffTool;
@@ -190,12 +193,13 @@ export class ExperimentSession {
190
193
  }
191
194
  const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
192
195
  this.inputs = [pin('bench', options.bench.dir, this.groupDir), pin('target', options.target.sourceDir), pin('implementation', join(packageRoot, 'dist'))];
193
- if (options.details['component'] !== undefined) {
194
- const expected = options.details['component'].implementationSha256;
195
- if (typeof expected !== 'string' || expected !== this.inputs.find(input => input.label === 'implementation').sha256) {
196
- throw new Error('Component implementation differs from the approved preview; no calls allowed.');
196
+ for (const metadata of [options.details['component'], options.details['reviewedPlan']])
197
+ if (metadata !== undefined) {
198
+ const expected = metadata.implementationSha256;
199
+ if (typeof expected !== 'string' || expected !== this.inputs.find(input => input.label === 'implementation').sha256) {
200
+ throw new Error('Evaluation implementation differs from the approved preview; no calls allowed.');
201
+ }
197
202
  }
198
- }
199
203
  if (options.baselineTarget)
200
204
  this.inputs.push(pin('baseline Skill', options.baselineTarget.sourceDir));
201
205
  this.configs = [];
@@ -226,8 +230,7 @@ export class ExperimentSession {
226
230
  const trust = match ? { table: match[1], field: match[2], value: match[3] } : undefined;
227
231
  for (const path of paths)
228
232
  this.configs.push(configState(path, path === settings.path ? trust : undefined, this.trustWorkspaces));
229
- for (const spec of new Set([...skillUserDirSpecs(agent, env), ...agent.skills.sharedDirs.filter(path => path.startsWith('~/'))])) {
230
- const root = expand(spec, home);
233
+ for (const root of globalSkillRoots(agent, home, env)) {
231
234
  this.inventories.push(skillInventory(root));
232
235
  if (!existsSync(root))
233
236
  continue;
@@ -370,7 +373,7 @@ export class ExperimentSession {
370
373
  const result = error instanceof ExecutorFailure ? error.result : null;
371
374
  writeFileSync(join(this.groupDir, `_interrupted-judge-${call}.json`), JSON.stringify({
372
375
  schemaVersion: 1, call, role, error: error.message, result,
373
- scope: 'Interrupted judge output and available usage only; separate judge spending is not a complete primary-agent cost total.',
376
+ scope: 'Supplementary interrupted judge output and available usage. Independent judge-call receipts retain invocation accounting; primary Agent comparison stays separate.',
374
377
  }, null, 2) + '\n', { flag: 'wx' });
375
378
  }
376
379
  if (this.callsFinished < call) {
@@ -384,7 +387,7 @@ export class ExperimentSession {
384
387
  summary() {
385
388
  return { schemaVersion: 1, status: this.stopReason ? 'stopped' : this.callsFinished === this.plannedCalls ? 'completed' : 'incomplete',
386
389
  plannedCalls: this.plannedCalls, maxCalls: this.maxCalls, callsStarted: this.callsStarted, callsFinished: this.callsFinished,
387
- stopReason: this.stopReason, planSha256: this.planSha256 };
390
+ stopReason: this.stopReason, ...(this.stopCode ? { stopCode: this.stopCode } : {}), planSha256: this.planSha256 };
388
391
  }
389
392
  settle() {
390
393
  try {
@@ -405,6 +408,11 @@ export class ExperimentSession {
405
408
  exitCode: interruption.exitCode, automaticRetry: false,
406
409
  }, null, 2) + '\n', { flag: 'wx' });
407
410
  }
411
+ const spendingStop = spendingStopFrom(error);
412
+ if (spendingStop && !(interruption instanceof EvaluationInterrupted)) {
413
+ this.stopCode = spendingStop.code;
414
+ this.stopReason ??= spendingStop.message;
415
+ }
408
416
  if (error && !this.stopReason)
409
417
  this.stopReason = 'Experiment setup or execution stopped; inspect the command error and retained receipts.';
410
418
  this.settle();
@@ -140,6 +140,14 @@ test('executor failure stops further actual calls and keeps a failure receipt wi
140
140
  assert.equal(readFileSync(join(s.groupDir, '_session.json'), 'utf8').includes('PRIVATE_SECRET'), false);
141
141
  assert.match(readFileSync(join(s.groupDir, '_calls.jsonl'), 'utf8'), /"event":"failed"/);
142
142
  });
143
+ test('finalizing arbitrary errors keeps generic session diagnostics instead of copying secret-bearing messages', t => {
144
+ const s = setup(t), session = new ExperimentSession(s.options);
145
+ session.finish(new Error('secret-bearing untrusted executor error'));
146
+ const saved = readFileSync(join(s.groupDir, '_session.json'), 'utf8');
147
+ assert.doesNotMatch(saved, /secret-bearing/);
148
+ assert.equal(session.summary().stopCode, undefined);
149
+ assert.match(session.summary().stopReason, /Experiment setup or execution stopped/);
150
+ });
143
151
  test('trust normalization covers declared pure blocks only and preserves other configuration bytes', () => {
144
152
  const trust = { table: 'projects', field: 'trust_level', value: 'trusted' };
145
153
  const base = 'model = "m"\n';
@@ -0,0 +1,72 @@
1
+ import { COST_METRICS, summarizeCosts } from './costs.js';
2
+ import assert from 'node:assert/strict';
3
+ import { record } from './eval-contract.js';
4
+ export function invocationPopulation(rows) {
5
+ return summarizeCosts({ baseline: rows, treatment: [] }, { baseline: [], treatment: [] }).attempts.baseline;
6
+ }
7
+ export function summarizeInvocationCosts(agent, judge, requested) {
8
+ return { schemaVersion: 1, agent: invocationPopulation(agent), judge: invocationPopulation(judge),
9
+ total: invocationPopulation([...agent, ...judge]), judgeUsage: requested ? 'recorded' : 'not-requested' };
10
+ }
11
+ /** Historical absence never establishes a free judge or a complete invocation total. */
12
+ export function historicalInvocationCosts(agent, requested) {
13
+ return { schemaVersion: 1, agent, judge: requested ? null : invocationPopulation([]),
14
+ total: requested ? null : agent, judgeUsage: requested ? 'unknown' : 'not-requested' };
15
+ }
16
+ export function parseInvocationCosts(value) {
17
+ const r = record(value, 'invocationCosts');
18
+ assert.equal(r.schemaVersion, 1, 'Unsupported invocationCosts schema.');
19
+ assert.ok(['recorded', 'unknown', 'not-requested'].includes(String(r.judgeUsage)), 'Invalid judge usage state.');
20
+ const population = (value, label) => {
21
+ const p = record(value, label);
22
+ for (const field of ['runs', 'passes'])
23
+ assert.ok(Number.isSafeInteger(p[field]) && Number(p[field]) >= 0, `${label}.${field} must be a non-negative safe integer.`);
24
+ assert.ok(Number(p.passes) <= Number(p.runs), `${label} successes exceed invocations.`);
25
+ const metrics = record(p.metrics, `${label}.metrics`);
26
+ for (const metric of COST_METRICS) {
27
+ const m = record(metrics[metric], `${label}.${metric}`), c = record(m.coverage, `${label}.${metric}.coverage`);
28
+ assert.ok(typeof m.knownTotal === 'number' && Number.isFinite(m.knownTotal) && m.knownTotal >= 0 &&
29
+ (metric === 'durationSeconds' || Number.isSafeInteger(m.knownTotal)), `${label}.${metric} has invalid known spending.`);
30
+ for (const status of ['final', 'partial', 'unknown'])
31
+ assert.ok(Number.isSafeInteger(c[status]) && Number(c[status]) >= 0, `${label}.${metric} has invalid coverage.`);
32
+ assert.equal(Number(c.final) + Number(c.partial) + Number(c.unknown), p.runs, `${label}.${metric} coverage differs from invocations.`);
33
+ if (Number(c.final) + Number(c.partial) === 0)
34
+ assert.equal(m.knownTotal, 0, `${label}.${metric} unknown spending must not invent a known total.`);
35
+ }
36
+ return p;
37
+ };
38
+ const agent = population(r.agent, 'invocationCosts.agent'), judge = r.judge === null ? null : population(r.judge, 'invocationCosts.judge');
39
+ const total = r.total === null ? null : population(r.total, 'invocationCosts.total');
40
+ assert.equal(judge === null, total === null, 'Unknown judge usage must keep its invocation total unknown too.');
41
+ if (r.judgeUsage !== 'unknown')
42
+ assert.ok(judge && total, 'Recorded judge usage requires cost populations.');
43
+ if (judge && total) {
44
+ for (const field of ['runs', 'passes'])
45
+ assert.equal(total[field], agent[field] + judge[field], `Invocation ${field} total differs from roles.`);
46
+ for (const metric of COST_METRICS) {
47
+ assert.ok(Math.abs(total.metrics[metric].knownTotal - agent.metrics[metric].knownTotal - judge.metrics[metric].knownTotal) < 1e-6, `Invocation ${metric} total differs from roles.`);
48
+ for (const status of ['final', 'partial', 'unknown'])
49
+ assert.equal(total.metrics[metric].coverage[status], agent.metrics[metric].coverage[status] + judge.metrics[metric].coverage[status], `Invocation ${metric} coverage total differs from roles.`);
50
+ }
51
+ }
52
+ if (r.judgeUsage === 'not-requested')
53
+ assert.equal(judge.runs, 0, 'Disabled judge cannot have invocations.');
54
+ return { schemaVersion: 1, agent, judge, total, judgeUsage: r.judgeUsage };
55
+ }
56
+ export function renderInvocationCostLines(costs) {
57
+ const lines = ['All executor invocation costs (primary Agent and optional judge):'];
58
+ for (const role of ['agent', 'judge', 'total']) {
59
+ const population = costs[role];
60
+ if (!population) {
61
+ lines.push(`- ${role}: unknown; historical judge receipts were not recorded.`);
62
+ continue;
63
+ }
64
+ lines.push(`- ${role}: ${population.runs} invocations.`);
65
+ for (const metric of COST_METRICS) {
66
+ const m = population.metrics[metric], c = m.coverage;
67
+ lines.push(` ${metric}: known total ${m.knownTotal}; final/partial/unknown ${c.final}/${c.partial}/${c.unknown}.`);
68
+ }
69
+ }
70
+ lines.push('- Usage and monotonic elapsed intervals only; no exact bill. Judge spending does not alter the primary Agent comparison or adoption policy.');
71
+ return lines;
72
+ }
@@ -0,0 +1,216 @@
1
+ import assert from 'node:assert/strict';
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { test } from 'node:test';
6
+ import { runEval } from '../commands/eval.js';
7
+ import { auditEvaluation, stoppedAccounting } from './eval-audit.js';
8
+ import { sha256File } from './hash.js';
9
+ import { JudgePairFailure, judgePair } from './judge.js';
10
+ import { judgeCallReceipt } from './judge-audit.js';
11
+ import { historicalInvocationCosts, invocationPopulation, parseInvocationCosts, summarizeInvocationCosts } from './invocation-costs.js';
12
+ import { ExecutorFailure } from './types.js';
13
+ const checklist = '{"A":{"correct":true,"complete":true,"grounded":true},"B":{"correct":true,"complete":true,"grounded":true}}';
14
+ const budget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
15
+ const primaryTokens = { input: 10, cachedInput: 6, output: 3 };
16
+ const judgeTokens = { input: 5, cachedInput: 2, output: 1 };
17
+ function setup(t, judgeResult = () => ({ output: checklist, rawOutput: 'judge raw transcript', tokens: judgeTokens })) {
18
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-judge-accounting-'));
19
+ t.after(() => rmSync(root, { recursive: true, force: true }));
20
+ const skill = join(root, 'skill'), bench = join(root, 'bench');
21
+ mkdirSync(skill);
22
+ mkdirSync(join(bench, 'fixture'), { recursive: true });
23
+ writeFileSync(join(skill, 'SKILL.md'), '---\nname: audit-skill\ndescription: Offline test.\n---\nReturn the answer.\n');
24
+ writeFileSync(join(bench, 'fixture/answer.txt'), 'pending');
25
+ writeFileSync(join(bench, 'prompt.md'), 'Return an answer.');
26
+ writeFileSync(join(bench, 'check.mjs'), `import{existsSync,readFileSync}from'node:fs';import{join}from'node:path';const file=join(process.argv[2],'_output.md');process.exit(existsSync(file)&&readFileSync(file,'utf8').trim()?0:1);\n`);
27
+ writeFileSync(join(bench, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'judge-costs', tasks: [{ id: 'answer', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs' }] }));
28
+ let primaryCalls = 0, judgeCalls = 0;
29
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-primary' }), run: async () => {
30
+ primaryCalls++;
31
+ return { output: 'answer', tokens: primaryTokens };
32
+ } };
33
+ const judge = { describe: () => ({ kind: 'mock', model: 'offline-judge' }), run: async () => judgeResult(++judgeCalls) };
34
+ return { root, executor, judge, counts: () => ({ primary: primaryCalls, judge: judgeCalls }), directory: join(root, 'runs/judge'),
35
+ options: { skillPath: skill, bench, executor, judgeExecutor: judge, trials: 1, maxCalls: 4, runsRoot: join(root, 'runs'), runGroup: 'judge',
36
+ dryRun: false, yes: true, log: () => { }, sessionOptions: { homeDir: root, env: {}, versionProbe: () => null } } };
37
+ }
38
+ function reseal(directory, relative, value) {
39
+ writeFileSync(join(directory, relative), JSON.stringify(value, null, 2) + '\n');
40
+ const indexPath = join(directory, '_artifacts.json'), index = JSON.parse(readFileSync(indexPath, 'utf8'));
41
+ index.files[relative] = sha256File(join(directory, relative));
42
+ writeFileSync(indexPath, JSON.stringify(index, null, 2) + '\n');
43
+ }
44
+ test('each judge order retains independent complete usage and transcript; total budget/audit includes all four calls', async (t) => {
45
+ const f = setup(t), manifest = await runEval({ ...f.options, spendingBudget: budget });
46
+ assert.ok(manifest && 'overall' in manifest);
47
+ assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
48
+ const calls = [1, 2].map(i => judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, `answer/judge-trial-1/call-${i}.json`), 'utf8'))));
49
+ for (const call of calls) {
50
+ assert.deepEqual(call.tokens, judgeTokens);
51
+ assert.equal(call.usageStatus, 'final');
52
+ assert.equal(call.rawOutput, 'judge raw transcript');
53
+ assert.equal(call.timing.clock, 'performance.now');
54
+ }
55
+ assert.notEqual(calls[0].promptSha256, calls[1].promptSha256);
56
+ assert.equal(manifest.overall.costs.attempts.baseline.metrics.input.knownTotal, 10);
57
+ assert.equal(manifest.overall.costs.attempts.treatment.metrics.input.knownTotal, 10);
58
+ assert.equal(manifest.invocationCosts.judge.metrics.input.knownTotal, 10);
59
+ assert.equal(manifest.invocationCosts.total.metrics.input.knownTotal, 30);
60
+ assert.equal(manifest.invocationCosts.total.metrics.cachedInput.knownTotal, 16);
61
+ const events = readFileSync(join(f.directory, '_budget.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line));
62
+ assert.equal(events.length, 8);
63
+ assert.equal(events.at(-1).state.invocations, 4);
64
+ assert.equal(events.at(-1).state.metrics.input.knownTotal, 30);
65
+ const audited = await auditEvaluation(manifest, f.directory, { replay: true });
66
+ assert.equal(audited.verified, true, audited.reasons.join('\n'));
67
+ assert.equal(audited.receipts, 4);
68
+ assert.equal(audited.replayedDeliveries, 2);
69
+ assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
70
+ });
71
+ test('malformed judge JSON is retained with final spending and stops instead of launching its reverse order', async (t) => {
72
+ const f = setup(t, () => ({ output: 'malformed but charged', tokens: judgeTokens, rawOutput: 'retained raw' }));
73
+ await assert.rejects(runEval({ ...f.options, spendingBudget: budget }), /EXECUTION_FAILED|checklist JSON/);
74
+ assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
75
+ const call = judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-1.json'), 'utf8')));
76
+ assert.match(call.error, /checklist JSON/);
77
+ assert.equal(call.output, 'malformed but charged');
78
+ assert.equal(call.usageStatus, 'final');
79
+ const costs = stoppedAccounting(f.directory);
80
+ assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 25);
81
+ assert.equal(costs.startedJudgeDispatches, 1);
82
+ assert.equal(costs.judgeInvocationsWithUnknownReceipts, 0);
83
+ assert.ok(existsSync(join(f.directory, '_artifacts.json')));
84
+ assert.ok(existsSync(join(f.directory, 'answer/judge-trial-1-error.json')));
85
+ });
86
+ test('reverse judge execution failure retains its partial public output and lower-bound counters', async (t) => {
87
+ const f = setup(t, index => {
88
+ if (index === 1)
89
+ return { output: checklist, tokens: judgeTokens };
90
+ throw new ExecutorFailure('offline routing failure', { output: 'partial answer', rawOutput: 'partial raw', tokens: { input: 7, output: 2 }, usageStatus: 'partial' });
91
+ });
92
+ await assert.rejects(runEval(f.options), /routing failure/);
93
+ assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
94
+ const costs = stoppedAccounting(f.directory), judge = costs.invocationCosts.judge;
95
+ assert.equal(judge.runs, 2);
96
+ assert.equal(judge.metrics.input.knownTotal, 12);
97
+ assert.equal(judge.metrics.input.coverage.partial, 1);
98
+ assert.equal(judge.metrics.cachedInput.coverage.unknown, 1);
99
+ assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 32);
100
+ const retained = JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-2.json'), 'utf8'));
101
+ assert.equal(retained.output, 'partial answer');
102
+ assert.equal(retained.rawOutput, 'partial raw');
103
+ assert.equal(retained.scores, null);
104
+ });
105
+ test('interrupting an offline judge seals its partial receipt and stops before reverse order', async (t) => {
106
+ const previousExit = process.exitCode, listeners = process.listenerCount('SIGINT');
107
+ t.after(() => { process.exitCode = previousExit; });
108
+ const f = setup(t, () => {
109
+ process.emit('SIGINT');
110
+ throw new ExecutorFailure('simulated interrupted judge', { output: 'retained interrupted text',
111
+ rawOutput: 'retained interrupted transcript', tokens: { input: 8, cachedInput: 3, output: 1 }, usageStatus: 'partial' });
112
+ });
113
+ try {
114
+ await assert.rejects(runEval(f.options), /interrupted by SIGINT/);
115
+ assert.equal(process.exitCode, 130);
116
+ assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
117
+ assert.equal(process.listenerCount('SIGINT'), listeners);
118
+ const call = judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-1.json'), 'utf8')));
119
+ assert.equal(call.output, 'retained interrupted text');
120
+ assert.equal(call.usageStatus, 'partial');
121
+ const costs = stoppedAccounting(f.directory);
122
+ assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 28);
123
+ assert.equal(costs.invocationCosts.judge.metrics.input.coverage.partial, 1);
124
+ assert.ok(existsSync(join(f.directory, '_interruption.json')));
125
+ assert.ok(existsSync(join(f.directory, '_artifacts.json')));
126
+ assert.equal(existsSync(join(f.directory, 'answer/judge-trial-1/call-2.json')), false);
127
+ }
128
+ finally {
129
+ process.exitCode = previousExit;
130
+ }
131
+ });
132
+ test('missing judge usage or reached total spending stops before reverse order, with no retries or replacements', async (t) => {
133
+ for (const [label, result, limits] of [
134
+ ['unknown', { output: checklist }, budget],
135
+ ['line', { output: checklist, tokens: judgeTokens }, { ...budget, input: 25 }],
136
+ ]) {
137
+ const f = setup(t, () => result);
138
+ await assert.rejects(runEval({ ...f.options, spendingBudget: limits }), label === 'unknown' ? /FINAL_USAGE_MISSING/ : /SPENDING_BUDGET_REACHED/);
139
+ assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
140
+ assert.equal(existsSync(join(f.directory, 'answer/judge-trial-1/call-2.json')), false);
141
+ const costs = stoppedAccounting(f.directory);
142
+ assert.equal(costs.invocationCosts.total.runs, 3);
143
+ assert.equal(costs.invocationCosts.judge.metrics.input.coverage.unknown, label === 'unknown' ? 1 : 0);
144
+ const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
145
+ assert.equal(session.stopCode, label === 'unknown' ? 'FINAL_USAGE_MISSING' : 'SPENDING_BUDGET_REACHED');
146
+ assert.match(session.stopReason, label === 'unknown' ? /FINAL_USAGE_MISSING/ : /SPENDING_BUDGET_REACHED/);
147
+ }
148
+ });
149
+ test('resealing altered aggregate usage, prompt evidence or missing historical judge usage cannot pass semantic audit', async (t) => {
150
+ for (const mutation of ['total', 'ledger', 'history']) {
151
+ const f = setup(t), manifest = await runEval(f.options);
152
+ assert.ok(manifest && 'overall' in manifest);
153
+ if (mutation === 'total') {
154
+ manifest.invocationCosts.total.metrics.input.knownTotal = 20;
155
+ reseal(f.directory, 'manifest.json', manifest);
156
+ }
157
+ if (mutation === 'history') {
158
+ delete manifest.invocationCosts;
159
+ reseal(f.directory, 'manifest.json', manifest);
160
+ }
161
+ if (mutation === 'ledger') {
162
+ const path = join(f.directory, '_calls.jsonl'), ledger = readFileSync(path, 'utf8').trim().split('\n').map(line => JSON.parse(line));
163
+ ledger.find(row => row.event === 'started' && row.role === 'judge').promptSha256 = '0'.repeat(64);
164
+ writeFileSync(path, ledger.map(row => JSON.stringify(row)).join('\n') + '\n');
165
+ const index = JSON.parse(readFileSync(join(f.directory, '_artifacts.json'), 'utf8'));
166
+ index.files['_calls.jsonl'] = sha256File(path);
167
+ writeFileSync(join(f.directory, '_artifacts.json'), JSON.stringify(index, null, 2) + '\n');
168
+ }
169
+ const audit = await auditEvaluation(manifest, f.directory);
170
+ assert.equal(audit.verified, false);
171
+ assert.match(audit.reasons.join(' '), /Full invocation accounting|Invocation.*total differs|prompt hash|Judge usage unrecorded/);
172
+ }
173
+ });
174
+ test('invocation summary parser refuses invalid counters, coverage and role totals, preserving historical unknown', () => {
175
+ const valid = summarizeInvocationCosts([], [], false);
176
+ assert.deepEqual(parseInvocationCosts(valid), valid);
177
+ const historical = historicalInvocationCosts(invocationPopulation([]), true);
178
+ assert.deepEqual(parseInvocationCosts(historical), historical);
179
+ for (const mutate of [
180
+ (r) => { r.agent.metrics.input.knownTotal = -1; },
181
+ (r) => { r.agent.metrics.output.coverage.final = 1; },
182
+ (r) => { r.total.runs = 1; },
183
+ (r) => { r.judge = null; r.total = null; },
184
+ ]) {
185
+ const value = JSON.parse(JSON.stringify(valid));
186
+ mutate(value);
187
+ assert.throws(() => parseInvocationCosts(value));
188
+ }
189
+ });
190
+ test('judge duration is monotonic even when wall clock moves backwards; non-invoked refusal spends nothing', async () => {
191
+ let wall = 100_000, mono = 0;
192
+ const capture = [];
193
+ const judge = { describe: () => ({ kind: 'mock', model: 'clock' }), run: async () => { wall -= 5000; mono += 250; return { output: checklist, tokens: judgeTokens }; } };
194
+ const result = await judgePair(judge, { taskPromptText: 'task', baselineOutput: 'b', treatmentOutput: 't', seed: 'clock',
195
+ clock: { wallNow: () => wall, monotonicNow: () => mono }, onCall: call => capture.push(call) });
196
+ assert.equal(result.calls.length, 2);
197
+ assert.equal(capture[0].durationSeconds, 0.25);
198
+ assert.equal(capture[0].timing.wallDurationSeconds, -5);
199
+ judgeCallReceipt(capture[0]);
200
+ const refused = { ...judge, run: async () => { throw new ExecutorFailure('not dispatched', { output: '' }, false); } };
201
+ let failure;
202
+ try {
203
+ await judgePair(refused, { taskPromptText: 'task', baselineOutput: 'b', treatmentOutput: 't', seed: 'refusal' });
204
+ }
205
+ catch (error) {
206
+ failure = error;
207
+ }
208
+ assert.ok(failure instanceof JudgePairFailure);
209
+ assert.equal(failure.calls.length, 1);
210
+ assert.equal(failure.calls[0].executorInvoked, false);
211
+ assert.equal(summarizeInvocationCosts([], failure.calls, true).total.runs, 0);
212
+ const history = historicalInvocationCosts(invocationPopulation([]), true);
213
+ assert.equal(history.judgeUsage, 'unknown');
214
+ assert.equal(history.judge, null);
215
+ assert.equal(history.total, null);
216
+ });
@@ -0,0 +1,56 @@
1
+ import assert from 'node:assert/strict';
2
+ import { record } from './eval-contract.js';
3
+ import { parseJudgeScores } from './judge.js';
4
+ import { sha256Text } from './hash.js';
5
+ /** Validate a retained judge receipt without executing a judge or reading current config. */
6
+ export function judgeCallReceipt(value) {
7
+ const r = record(value, 'judge invocation receipt');
8
+ assert.equal(r.schemaVersion, 1);
9
+ assert.equal(r.kind, 'skillfit.judge-call');
10
+ assert.ok(typeof r.taskId === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r.taskId));
11
+ assert.ok(Number.isSafeInteger(r.trial) && Number(r.trial) >= 1);
12
+ assert.ok(r.callIndex === 1 || r.callIndex === 2);
13
+ assert.equal(typeof r.seed, 'string');
14
+ assert.ok(r.firstCondition === 'baseline' || r.firstCondition === 'treatment');
15
+ assert.equal(typeof r.prompt, 'string');
16
+ assert.equal(sha256Text(r.prompt), r.promptSha256);
17
+ assert.equal(typeof r.output, 'string');
18
+ assert.ok(r.rawOutput === null || typeof r.rawOutput === 'string');
19
+ assert.equal(typeof r.executorInvoked, 'boolean');
20
+ assert.equal(typeof r.passed, 'boolean');
21
+ assert.ok(r.error === null || typeof r.error === 'string');
22
+ assert.equal(r.passed, r.error === null);
23
+ assert.ok(['final', 'partial', 'unknown'].includes(String(r.usageStatus)));
24
+ assert.ok(typeof r.durationSeconds === 'number' && Number.isFinite(r.durationSeconds) && r.durationSeconds >= 0);
25
+ for (const key of ['startedAt', 'finishedAt'])
26
+ assert.ok(typeof r[key] === 'string' && Number.isFinite(Date.parse(r[key])));
27
+ const timing = record(r.timing, 'judge invocation timing');
28
+ assert.equal(timing.clock, 'performance.now');
29
+ assert.equal(timing.wallDurationSeconds, (Date.parse(r.finishedAt) - Date.parse(r.startedAt)) / 1000);
30
+ if (timing.execution !== null) {
31
+ const execution = record(timing.execution, 'judge execution timing');
32
+ assert.equal(execution.clock, 'performance.now');
33
+ assert.ok(typeof execution.elapsedMs === 'number' && Number.isFinite(execution.elapsedMs) && execution.elapsedMs >= 0);
34
+ assert.ok(r.durationSeconds >= execution.elapsedMs / 1000 - 0.002, 'Judge execution interval exceeds invocation duration.');
35
+ }
36
+ if (r.tokens !== null) {
37
+ const tokens = record(r.tokens, 'judge tokens');
38
+ for (const key of ['input', 'cachedInput', 'output'])
39
+ if (tokens[key] !== undefined) {
40
+ assert.ok(Number.isSafeInteger(tokens[key]) && Number(tokens[key]) >= 0);
41
+ }
42
+ if (typeof tokens.cachedInput === 'number' && typeof tokens.input === 'number')
43
+ assert.ok(tokens.cachedInput <= tokens.input);
44
+ }
45
+ const executor = record(r.executor, 'judge executor');
46
+ assert.equal(typeof executor.kind, 'string');
47
+ assert.equal(typeof executor.model, 'string');
48
+ if (r.error === null) {
49
+ assert.equal(r.executorInvoked, true);
50
+ const scores = parseJudgeScores(r.output);
51
+ assert.deepEqual(r.scores, r.firstCondition === 'baseline' ? { baseline: scores.a, treatment: scores.b } : { baseline: scores.b, treatment: scores.a });
52
+ }
53
+ else
54
+ assert.equal(r.scores, null);
55
+ return r;
56
+ }
@@ -2,6 +2,17 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { ExecutorFailure } from './types.js';
6
+ import { executionClock } from './execution-timing.js';
7
+ import { throwIfEvaluationInterrupted } from './interruption.js';
8
+ export class JudgePairFailure extends Error {
9
+ calls;
10
+ constructor(message, calls, cause) {
11
+ super(message, { cause });
12
+ this.calls = calls;
13
+ this.name = 'JudgePairFailure';
14
+ }
15
+ }
5
16
  export function judgeOrder(seed) {
6
17
  const digest = createHash('sha256').update(seed, 'utf8').digest();
7
18
  const first = (digest[0] ?? 0) % 2 === 0 ? 'baseline' : 'treatment';
@@ -63,7 +74,7 @@ function parseChecklist(raw, label) {
63
74
  }
64
75
  return score;
65
76
  }
66
- function parseScores(raw) {
77
+ export function parseJudgeScores(raw) {
67
78
  return { a: parseChecklist(raw, 'A'), b: parseChecklist(raw, 'B') };
68
79
  }
69
80
  export async function judgePair(judge, args) {
@@ -72,26 +83,79 @@ export async function judgePair(judge, args) {
72
83
  // the task directory would expose both arms' _output.md and their _result.json — which names the
73
84
  // condition and the evaluation-target hash — and the AB/BA swap would be blindfolding a judge that can
74
85
  // just look. It gets a fresh directory holding only the two positionally-anonymized answers.
75
- const judgeDir = mkdtempSync(join(tmpdir(), 'skillfit-judge-'));
86
+ const calls = [];
87
+ const clock = args.clock ?? executionClock;
76
88
  try {
77
- const call = async (firstCondition) => {
78
- const answerA = firstCondition === 'baseline' ? args.baselineOutput : args.treatmentOutput;
79
- const answerB = firstCondition === 'baseline' ? args.treatmentOutput : args.baselineOutput;
80
- writeFileSync(join(judgeDir, 'answerA.md'), answerA, 'utf8');
81
- writeFileSync(join(judgeDir, 'answerB.md'), answerB, 'utf8');
82
- const prompt = buildJudgePrompt(args.taskPromptText, args.rubricText ?? null, answerA, answerB);
83
- const result = await judge.run(prompt, judgeDir);
84
- if (result.guardError)
85
- throw new Error(result.guardError);
86
- const scores = parseScores(result.output);
87
- return {
88
- baseline: firstCondition === 'baseline' ? scores.a : scores.b,
89
- treatment: firstCondition === 'baseline' ? scores.b : scores.a,
90
- raw: result.output,
91
- };
89
+ const call = async (firstCondition, callIndex) => {
90
+ throwIfEvaluationInterrupted();
91
+ args.beforeCall?.(callIndex);
92
+ const judgeDir = mkdtempSync(join(tmpdir(), 'skillfit-judge-'));
93
+ try {
94
+ const answerA = firstCondition === 'baseline' ? args.baselineOutput : args.treatmentOutput;
95
+ const answerB = firstCondition === 'baseline' ? args.treatmentOutput : args.baselineOutput;
96
+ writeFileSync(join(judgeDir, 'answerA.md'), answerA, 'utf8');
97
+ writeFileSync(join(judgeDir, 'answerB.md'), answerB, 'utf8');
98
+ const prompt = buildJudgePrompt(args.taskPromptText, args.rubricText ?? null, answerA, answerB);
99
+ const startedWall = clock.wallNow(), startedMono = clock.monotonicNow();
100
+ let output = '', rawOutput = null, tokens = null;
101
+ let usageStatus = 'unknown', execution = null;
102
+ let executorInvoked = true, error = null, scores = null;
103
+ let usageEvidence;
104
+ try {
105
+ const result = await judge.run(prompt, judgeDir);
106
+ output = result.output;
107
+ rawOutput = result.rawOutput ?? null;
108
+ tokens = result.tokens ?? null;
109
+ usageStatus = result.usageStatus ?? (tokens ? 'final' : 'unknown');
110
+ execution = result.executionTiming ?? null;
111
+ usageEvidence = result.usageEvidence;
112
+ if (result.guardError)
113
+ throw new Error(result.guardError);
114
+ }
115
+ catch (failure) {
116
+ error = failure.message;
117
+ if (failure instanceof ExecutorFailure) {
118
+ executorInvoked = failure.executorInvoked;
119
+ output = failure.result.output;
120
+ rawOutput = failure.result.rawOutput ?? null;
121
+ tokens = failure.result.tokens ?? null;
122
+ usageStatus = failure.result.usageStatus ?? (tokens ? 'partial' : 'unknown');
123
+ execution = failure.result.executionTiming ?? null;
124
+ usageEvidence = failure.result.usageEvidence;
125
+ }
126
+ }
127
+ const finishedWall = clock.wallNow(), durationSeconds = Math.round(clock.monotonicNow() - startedMono) / 1000;
128
+ if (!error) {
129
+ try {
130
+ const parsed = parseJudgeScores(output);
131
+ scores = { baseline: firstCondition === 'baseline' ? parsed.a : parsed.b,
132
+ treatment: firstCondition === 'baseline' ? parsed.b : parsed.a };
133
+ }
134
+ catch (failure) {
135
+ error = failure.message;
136
+ }
137
+ }
138
+ const receipt = { schemaVersion: 1, kind: 'skillfit.judge-call',
139
+ taskId: args.taskId ?? 'standalone', trial: args.trial ?? 1, callIndex, seed: args.seed, firstCondition,
140
+ prompt, promptSha256: createHash('sha256').update(prompt).digest('hex'), output, rawOutput,
141
+ executor: { ...judge.describe(), sampling: judge.describe().sampling ?? null },
142
+ startedAt: new Date(startedWall).toISOString(), finishedAt: new Date(finishedWall).toISOString(), durationSeconds,
143
+ timing: { clock: 'performance.now', wallDurationSeconds: (finishedWall - startedWall) / 1000, execution },
144
+ executorInvoked, error, passed: error === null, tokens, usageStatus, ...(usageEvidence ? { usageEvidence } : {}), scores };
145
+ calls.push(receipt);
146
+ // Persist before propagating a parse/execution error, cancellation or budget stop.
147
+ args.onCall?.(receipt);
148
+ throwIfEvaluationInterrupted();
149
+ if (error)
150
+ throw new Error(error);
151
+ return { ...scores, raw: output };
152
+ }
153
+ finally {
154
+ rmSync(judgeDir, { recursive: true, force: true });
155
+ }
92
156
  };
93
- const forward = await call(first);
94
- const reverse = await call(second);
157
+ const forward = await call(first, 1);
158
+ const reverse = await call(second, 2);
95
159
  const winner = (scores) => Math.sign(scores.baseline - scores.treatment);
96
160
  const consistent = winner(forward) === winner(reverse);
97
161
  return {
@@ -100,9 +164,10 @@ export async function judgePair(judge, args) {
100
164
  consistent,
101
165
  firstCondition: first,
102
166
  raw: `${forward.raw}\n--- reverse order ---\n${reverse.raw}`,
167
+ calls,
103
168
  };
104
169
  }
105
- finally {
106
- rmSync(judgeDir, { recursive: true, force: true });
170
+ catch (error) {
171
+ throw new JudgePairFailure(error.message, calls, error);
107
172
  }
108
173
  }