skillfit 0.10.1 → 0.12.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 (118) hide show
  1. package/README.md +43 -8
  2. package/README.zh-CN.md +43 -8
  3. package/benches/README.md +6 -2
  4. package/dist/cli.js +153 -37
  5. package/dist/cli.test.js +94 -0
  6. package/dist/commands/bench-calibration.js +201 -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-draft.js +167 -0
  10. package/dist/commands/bench-draft.test.js +168 -0
  11. package/dist/commands/bench-manage.js +5 -4
  12. package/dist/commands/bench-source.js +101 -0
  13. package/dist/commands/bench-source.test.js +84 -0
  14. package/dist/commands/bench.js +227 -245
  15. package/dist/commands/bench.test.js +7 -3
  16. package/dist/commands/calibration-cli.test.js +145 -0
  17. package/dist/commands/eval-agent-preflight.test.js +269 -0
  18. package/dist/commands/eval-api-failure.test.js +46 -0
  19. package/dist/commands/eval-cli-usage.test.js +75 -0
  20. package/dist/commands/eval-cli.js +31 -0
  21. package/dist/commands/eval-component.js +52 -28
  22. package/dist/commands/eval-export-modes.test.js +350 -0
  23. package/dist/commands/eval-export.js +12 -4
  24. package/dist/commands/eval-interruption.test.js +26 -1
  25. package/dist/commands/eval-layout.test.js +126 -0
  26. package/dist/commands/eval-plan.js +37 -0
  27. package/dist/commands/eval-preflight.test.js +144 -1
  28. package/dist/commands/eval-report.js +18 -3
  29. package/dist/commands/eval-single-arm-replay.js +21 -0
  30. package/dist/commands/eval-single-arm-report.js +223 -0
  31. package/dist/commands/eval.js +113 -88
  32. package/dist/commands/evaluation-report.js +5 -0
  33. package/dist/commands/evaluation-report.test.js +243 -0
  34. package/dist/commands/npm-first-run.test.js +74 -0
  35. package/dist/commands/replay-cancellation.test.js +105 -0
  36. package/dist/commands/workflow-entrypoints.test.js +137 -0
  37. package/dist/harness/agent-preflight.js +196 -0
  38. package/dist/harness/bench-location.js +29 -0
  39. package/dist/harness/bench-location.test.js +33 -0
  40. package/dist/harness/bench.js +10 -4
  41. package/dist/harness/command.js +49 -0
  42. package/dist/harness/eval-audit.js +162 -17
  43. package/dist/harness/eval-budget.js +46 -2
  44. package/dist/harness/eval-budget.test.js +26 -1
  45. package/dist/harness/eval-component.test.js +163 -0
  46. package/dist/harness/eval-contract.js +11 -5
  47. package/dist/harness/evaluation-layout.js +30 -0
  48. package/dist/harness/executors/api.js +24 -10
  49. package/dist/harness/executors/api.test.js +57 -0
  50. package/dist/harness/executors/cli.js +15 -25
  51. package/dist/harness/executors/cli.test.js +33 -2
  52. package/dist/harness/experiment-session.js +23 -25
  53. package/dist/harness/experiment-session.test.js +8 -0
  54. package/dist/harness/hash.js +3 -1
  55. package/dist/harness/invocation-costs.js +72 -0
  56. package/dist/harness/judge-accounting.test.js +216 -0
  57. package/dist/harness/judge-audit.js +56 -0
  58. package/dist/harness/judge.js +86 -21
  59. package/dist/harness/replay-package.js +71 -5
  60. package/dist/harness/runner.js +44 -33
  61. package/dist/harness/runner.test.js +23 -0
  62. package/dist/harness/single-arm-audit.js +436 -0
  63. package/dist/harness/trigger.js +22 -4
  64. package/dist/harness/trigger.test.js +12 -0
  65. package/dist/harness/verifier-error.js +65 -0
  66. package/dist/harness/verifier-timeout.js +8 -0
  67. package/dist/harness/verifier-timeout.test.js +76 -0
  68. package/dist/harness/verifier.test.js +128 -0
  69. package/docs/bench-authoring.md +57 -12
  70. package/docs/bench-check-json.md +28 -5
  71. package/docs/bench-drafting.md +75 -0
  72. package/docs/case-management.md +12 -1
  73. package/docs/eval-agent-preflight.md +114 -0
  74. package/docs/eval-case-preflight.md +5 -0
  75. package/docs/eval-component.md +38 -10
  76. package/docs/eval-costs.md +70 -0
  77. package/docs/eval-planning.md +167 -0
  78. package/docs/evaluation-input-snapshots.md +22 -5
  79. package/docs/evaluation-interruption.md +22 -10
  80. package/docs/evaluation-reports.md +97 -3
  81. package/docs/experiment-workflow.md +7 -0
  82. package/docs/first-real-eval.md +75 -3
  83. package/docs/growth-roadmap-2026-10.md +51 -10
  84. package/docs/metrics.md +40 -3
  85. package/docs/plans/2026-10-17-workflow-foundations.md +99 -0
  86. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  87. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  88. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  89. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  90. package/docs/releases/0.10.1-signatures.txt +7 -0
  91. package/docs/releases/0.10.1-verification.json +90 -0
  92. package/docs/releases/0.10.1.md +37 -4
  93. package/docs/releases/0.11.0-ci-registry-install.json +130 -0
  94. package/docs/releases/0.11.0-feature-smoke.json +1576 -0
  95. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  96. package/docs/releases/0.11.0-local-attempt-1.json +24 -0
  97. package/docs/releases/0.11.0-local-attempt-1.log +19 -0
  98. package/docs/releases/0.11.0-local-registry-install.json +25 -0
  99. package/docs/releases/0.11.0-registry-metadata.json +33 -0
  100. package/docs/releases/0.11.0-signatures.txt +12 -0
  101. package/docs/releases/0.11.0-verification.json +95 -0
  102. package/docs/releases/0.11.0.md +90 -0
  103. package/docs/releases/0.12.0-feature-smoke.mjs +73 -0
  104. package/docs/releases/0.12.0.md +68 -0
  105. package/docs/replay-packages.md +38 -6
  106. package/docs/schemas/agent-preflight.schema.json +31 -0
  107. package/docs/schemas/calibration-plan.schema.json +22 -0
  108. package/docs/schemas/calibration-result.schema.json +17 -0
  109. package/docs/schemas/eval-request.schema.json +1 -1
  110. package/docs/schemas/eval-result.schema.json +3 -1
  111. package/docs/schemas/invocation-costs.schema.json +31 -0
  112. package/docs/schemas/judge-call.schema.json +22 -0
  113. package/docs/schemas/single-arm-report.schema.json +20 -0
  114. package/docs/schemas/verifier-error.schema.json +11 -0
  115. package/docs/sharing-results.md +3 -0
  116. package/docs/verifier-contract.md +108 -0
  117. package/package.json +1 -1
  118. package/skills/skillfit/SKILL.md +61 -8
@@ -78,12 +78,12 @@ test('CliExecutor rejects when the command cannot be started', async () => {
78
78
  });
79
79
  await assert.rejects(() => executor.run('x', process.cwd()), /Failed to start/);
80
80
  });
81
- test('CliExecutor.forAgent uses the headless template from the agent matrix', () => {
81
+ test('CliExecutor.forAgent prefers the structured matrix template even without Skill detection', () => {
82
82
  for (const agentId of agentIds()) {
83
83
  const headless = getAgent(agentId).headless;
84
84
  assert.ok(headless.argv.length > 0, `${agentId} has no headless argv`);
85
85
  const executor = CliExecutor.forAgent(agentId);
86
- assert.equal(executor.describe().detail, `${agentId}: ${headless.argv.join(' ')}`);
86
+ assert.equal(executor.describe().detail, `${agentId}: ${(headless.streamJson?.argv ?? headless.argv).join(' ')}`);
87
87
  }
88
88
  });
89
89
  test('Codex paired and trigger runs both use a writable disposable workspace', () => {
@@ -97,8 +97,39 @@ test('Codex paired and trigger runs both use a writable disposable workspace', (
97
97
  assert.equal(argv[sandboxIndex + 1], 'workspace-write');
98
98
  }
99
99
  assert.match(paired ?? '', /--sandbox workspace-write/);
100
+ assert.match(paired ?? '', /--json/);
100
101
  assert.match(trigger ?? '', /--sandbox workspace-write/);
101
102
  });
103
+ test('ordinary structured output retains counters without inventing a Skill detection', async () => {
104
+ const executor = new CliExecutor({ argv: [process.execPath, '-e', PASSTHROUGH_SCRIPT], shell: false, streamJson: true });
105
+ const transcript = toNdjson([
106
+ { type: 'item.completed', item: { type: 'agent_message', text: 'A normal answer.' } },
107
+ { type: 'turn.completed', usage: { input_tokens: 123, cached_input_tokens: 23, output_tokens: 17 } },
108
+ { type: 'turn.completed', usage: { input_tokens: 10, cached_input_tokens: 0, output_tokens: 2 } },
109
+ ]);
110
+ const result = await executor.run(transcript, process.cwd());
111
+ assert.equal(result.output, 'A normal answer.');
112
+ assert.equal(result.rawOutput, transcript);
113
+ assert.deepEqual(result.tokens, { input: 133, cachedInput: 23, output: 19 });
114
+ assert.equal(result.usageStatus, 'final');
115
+ assert.equal(result.skillTriggered, undefined);
116
+ });
117
+ test('ordinary structured failure retains public counters and diagnostics without a trigger target', async () => {
118
+ const transcript = toNdjson([
119
+ { type: 'turn.completed', usage: { input_tokens: 123, cached_input_tokens: 23, output_tokens: 17 } },
120
+ { type: 'turn.failed', error: { message: 'synthetic stream failure' } },
121
+ ]);
122
+ const executor = new CliExecutor({ argv: [process.execPath, '-e', PASSTHROUGH_SCRIPT + ';process.on("beforeExit",()=>process.exitCode=1)'], shell: false, streamJson: true });
123
+ await assert.rejects(executor.run(transcript, process.cwd()), error => {
124
+ assert.ok(error instanceof ExecutorFailure);
125
+ assert.match(error.message, /synthetic stream failure/);
126
+ assert.deepEqual(error.result.tokens, { input: 123, cachedInput: 23, output: 17 });
127
+ assert.equal(error.result.usageStatus, 'partial');
128
+ assert.equal(error.result.rawOutput, transcript);
129
+ assert.equal(error.result.skillTriggered, undefined);
130
+ return true;
131
+ });
132
+ });
102
133
  test('CliExecutor.forAgent kimi-code passes the prompt as a -p file reference', () => {
103
134
  const headless = getAgent('kimi-code').headless;
104
135
  assert.equal(headless.promptVia, 'file');
@@ -1,9 +1,9 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { 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,9 @@ 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';
16
+ import { assertEvaluationOutputLayout, physicalPath } from './evaluation-layout.js';
14
17
  function skillInventory(root) {
15
18
  if (!existsSync(root))
16
19
  return { root, entries: ['missing'] };
@@ -38,15 +41,6 @@ function inside(root, path) {
38
41
  return false;
39
42
  return !rel.startsWith(`..${sep}`) && rel !== '..' && !rel.startsWith(sep);
40
43
  }
41
- function physicalPath(path) {
42
- let parent = resolve(path);
43
- const parts = [];
44
- while (!existsSync(parent)) {
45
- parts.unshift(basename(parent));
46
- parent = dirname(parent);
47
- }
48
- return join(realpathSync(parent), ...parts);
49
- }
50
44
  function filesUnder(root, exclude) {
51
45
  const out = [];
52
46
  const walk = (rel) => {
@@ -163,6 +157,7 @@ export class ExperimentSession {
163
157
  callsStarted = 0;
164
158
  callsFinished = 0;
165
159
  stopReason = null;
160
+ stopCode;
166
161
  finished = false;
167
162
  guardFiles;
168
163
  nativeDiffTool;
@@ -184,18 +179,17 @@ export class ExperimentSession {
184
179
  this.trustWorkspaces = [...new Set([...this.workspaces, ...this.workspaceAliases.map(alias => alias.physical)])];
185
180
  if (existsSync(this.groupDir))
186
181
  throw new Error(`Run group directory already exists: ${this.groupDir}`);
187
- for (const input of [options.target.sourceDir, ...(options.baselineTarget ? [options.baselineTarget.sourceDir] : []), ...options.bench.tasks.map(task => join(options.bench.dir, task.fixture))]) {
188
- if (inside(physicalPath(input), physicalPath(this.groupDir)))
189
- throw new Error('Experiment output must be outside the Skill/overlay and fixture inputs; run the CLI from their parent directory.');
190
- }
182
+ assertEvaluationOutputLayout(this.groupDir, { benchDir: options.bench.dir,
183
+ targetDirs: [options.target.sourceDir, ...(options.baselineTarget ? [options.baselineTarget.sourceDir] : [])] });
191
184
  const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
192
185
  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.');
186
+ for (const metadata of [options.details['component'], options.details['reviewedPlan']])
187
+ if (metadata !== undefined) {
188
+ const expected = metadata.implementationSha256;
189
+ if (typeof expected !== 'string' || expected !== this.inputs.find(input => input.label === 'implementation').sha256) {
190
+ throw new Error('Evaluation implementation differs from the approved preview; no calls allowed.');
191
+ }
197
192
  }
198
- }
199
193
  if (options.baselineTarget)
200
194
  this.inputs.push(pin('baseline Skill', options.baselineTarget.sourceDir));
201
195
  this.configs = [];
@@ -226,8 +220,7 @@ export class ExperimentSession {
226
220
  const trust = match ? { table: match[1], field: match[2], value: match[3] } : undefined;
227
221
  for (const path of paths)
228
222
  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);
223
+ for (const root of globalSkillRoots(agent, home, env)) {
231
224
  this.inventories.push(skillInventory(root));
232
225
  if (!existsSync(root))
233
226
  continue;
@@ -266,7 +259,7 @@ export class ExperimentSession {
266
259
  try {
267
260
  this.inputSnapshot = freezeInputSnapshot(this.groupDir, this.inputs, this.guardFiles);
268
261
  if (loadBench(join(this.groupDir, '_inputs/bench')).contentSha256 !== options.bench.contentSha256)
269
- throw new Error('Sealed bench does not match the planned content hash; keep Git metadata and run outputs outside bench inputs.');
262
+ throw new Error('Sealed bench does not match the planned content hash; input bytes changed before sealing.');
270
263
  for (const input of this.inputs)
271
264
  if (pin(input.label, input.root, input.exclude).sha256 !== input.sha256)
272
265
  throw new Error(`Frozen ${input.label} input changed while sealing snapshots.`);
@@ -370,7 +363,7 @@ export class ExperimentSession {
370
363
  const result = error instanceof ExecutorFailure ? error.result : null;
371
364
  writeFileSync(join(this.groupDir, `_interrupted-judge-${call}.json`), JSON.stringify({
372
365
  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.',
366
+ scope: 'Supplementary interrupted judge output and available usage. Independent judge-call receipts retain invocation accounting; primary Agent comparison stays separate.',
374
367
  }, null, 2) + '\n', { flag: 'wx' });
375
368
  }
376
369
  if (this.callsFinished < call) {
@@ -384,7 +377,7 @@ export class ExperimentSession {
384
377
  summary() {
385
378
  return { schemaVersion: 1, status: this.stopReason ? 'stopped' : this.callsFinished === this.plannedCalls ? 'completed' : 'incomplete',
386
379
  plannedCalls: this.plannedCalls, maxCalls: this.maxCalls, callsStarted: this.callsStarted, callsFinished: this.callsFinished,
387
- stopReason: this.stopReason, planSha256: this.planSha256 };
380
+ stopReason: this.stopReason, ...(this.stopCode ? { stopCode: this.stopCode } : {}), planSha256: this.planSha256 };
388
381
  }
389
382
  settle() {
390
383
  try {
@@ -405,6 +398,11 @@ export class ExperimentSession {
405
398
  exitCode: interruption.exitCode, automaticRetry: false,
406
399
  }, null, 2) + '\n', { flag: 'wx' });
407
400
  }
401
+ const spendingStop = spendingStopFrom(error);
402
+ if (spendingStop && !(interruption instanceof EvaluationInterrupted)) {
403
+ this.stopCode = spendingStop.code;
404
+ this.stopReason ??= spendingStop.message;
405
+ }
408
406
  if (error && !this.stopReason)
409
407
  this.stopReason = 'Experiment setup or execution stopped; inspect the command error and retained receipts.';
410
408
  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';
@@ -7,10 +7,12 @@ export function sha256Text(text) {
7
7
  export function sha256File(path) {
8
8
  return createHash('sha256').update(readFileSync(path)).digest('hex');
9
9
  }
10
- export function listFilesRecursive(rootDir) {
10
+ export function listFilesRecursive(rootDir, options = {}) {
11
11
  const out = [];
12
12
  const walk = (rel) => {
13
13
  for (const entry of readdirSync(join(rootDir, rel), { withFileTypes: true })) {
14
+ if (options.excludeGitMetadata && entry.name === '.git')
15
+ continue;
14
16
  const childRel = rel ? `${rel}/${entry.name}` : entry.name;
15
17
  if (entry.isDirectory()) {
16
18
  walk(childRel);
@@ -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
+ }