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
package/dist/cli.test.js CHANGED
@@ -97,3 +97,97 @@ test('CLI wires the previous Skill into an installed dry-run and rejects single-
97
97
  assert.equal(unrelated.stdout, '');
98
98
  assert.equal(existsSync(join(cwd, 'runs')), false);
99
99
  });
100
+ test('ordinary JSON/human and Agent request previews expose the same effective installed no-Skill plan', t => {
101
+ const cwd = mkdtempSync(join(tmpdir(), 'skillfit-cli-shared-plan-'));
102
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
103
+ const skill = join(cwd, 'candidate');
104
+ cpSync(join(PACKAGE_ROOT, 'skills/skillfit'), skill, { recursive: true });
105
+ const bench = join(PACKAGE_ROOT, 'benches/code-review'), task = JSON.parse(readFileSync(join(bench, 'bench.json'), 'utf8')).tasks[0].id;
106
+ const limits = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
107
+ const budget = join(cwd, 'budget.json'), request = join(cwd, 'request.json');
108
+ writeFileSync(budget, JSON.stringify(limits));
109
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, baselineSkill: null, candidateSkill: skill, bench, taskIds: [task], agent: 'codex',
110
+ purpose: 'development', trials: 1, maxCalls: 2, pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget: limits,
111
+ runsRoot: join(cwd, 'runs'), runGroup: 'shared' }));
112
+ const args = ['eval', skill, '--mode', 'installed', '--bench', bench, '--task', task, '--agent', 'codex', '--trials', '1', '--max-calls', '2',
113
+ '--pair-order', 'balanced', '--executor-timeout-seconds', '17', '--spending-budget', budget, '--runs-root', join(cwd, 'runs'), '--run-group', 'shared', '--dry-run'];
114
+ const env = { ...process.env, SKILLFIT_JUDGE: '0' };
115
+ const ordinary = spawnSync(process.execPath, [CLI, ...args, '--json'], { cwd, env, encoding: 'utf8', timeout: 30_000 });
116
+ const agent = spawnSync(process.execPath, [CLI, 'eval', '--request', request, '--dry-run'], { cwd, env, encoding: 'utf8', timeout: 30_000 });
117
+ const human = spawnSync(process.execPath, [CLI, ...args], { cwd, env, encoding: 'utf8', timeout: 30_000 });
118
+ for (const result of [ordinary, agent, human])
119
+ assert.equal(result.status, 0, result.stderr);
120
+ const plan = JSON.parse(ordinary.stdout).plan, agentPlan = JSON.parse(agent.stdout).plan;
121
+ assert.deepEqual(plan.evaluation, agentPlan.evaluation);
122
+ assert.equal(plan.evaluation.baseline, null);
123
+ assert.deepEqual(plan.evaluation.spendingBudget, limits);
124
+ assert.equal(plan.evaluation.executorTimeoutSeconds, 17);
125
+ assert.equal(agentPlan.request.baselineSkill, null);
126
+ assert.match(human.stdout, /no Skill installed by the harness/);
127
+ assert.ok(human.stdout.includes(plan.sha256));
128
+ assert.match(human.stdout, /Agent deadline: 17s/);
129
+ assert.equal(existsSync(join(cwd, 'runs')), false);
130
+ for (const override of [['--executor-timeout-seconds', '18'], ['--spending-budget', budget], ['--run-group', 'other']]) {
131
+ const bad = spawnSync(process.execPath, [CLI, 'eval', '--request', request, '--dry-run', ...override], { cwd, env, encoding: 'utf8' });
132
+ assert.equal(bad.status, 2);
133
+ assert.match(JSON.parse(bad.stdout).error.message, /cannot be combined/);
134
+ }
135
+ });
136
+ test('positional JSON eval rejects unconfirmed execution and invalid new controls without writes or calls', t => {
137
+ const cwd = mkdtempSync(join(tmpdir(), 'skillfit-cli-new-controls-'));
138
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
139
+ // No target or executor is supplied: even a broken guard cannot dispatch a real model.
140
+ for (const args of [['eval', '--json'], ['eval', '--json', '--plan-sha', 'a'.repeat(64)]]) {
141
+ const result = spawnSync(process.execPath, [CLI, ...args], { cwd, encoding: 'utf8' });
142
+ assert.equal(result.status, 2);
143
+ const error = JSON.parse(result.stdout);
144
+ assert.equal(error.kind, 'skillfit.eval-error');
145
+ assert.match(error.error.message, /plan-sha|run-group/);
146
+ assert.equal(error.acceptance.eligibleForUpgrade, false);
147
+ }
148
+ for (const value of ['0', '3601', '1.5', 'NaN', '2junk']) {
149
+ const result = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--agent', 'codex', '--dry-run', '--json', '--executor-timeout-seconds', value], { cwd, encoding: 'utf8' });
150
+ assert.equal(result.status, 2);
151
+ assert.match(JSON.parse(result.stdout).error.message, /executorTimeoutSeconds/);
152
+ }
153
+ const file = join(cwd, 'budget.json');
154
+ writeFileSync(file, JSON.stringify({ input: 10 }));
155
+ const invalid = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--dry-run', '--json', '--spending-budget', file], { cwd, encoding: 'utf8' });
156
+ assert.equal(invalid.status, 2);
157
+ assert.match(JSON.parse(invalid.stdout).error.message, /spendingBudget/);
158
+ const unrelated = spawnSync(process.execPath, [CLI, 'doctor', '--executor-timeout-seconds', '17'], { cwd, encoding: 'utf8' });
159
+ assert.equal(unrelated.status, 1);
160
+ assert.match(unrelated.stderr, /apply only to eval/);
161
+ for (const args of [['eval'], [...COMMANDS[0], '--mode', 'invalid'], [...COMMANDS[0], '--runs-root', '']]) {
162
+ const invalid = spawnSync(process.execPath, [CLI, ...args, '--json', '--dry-run'], { cwd, encoding: 'utf8' });
163
+ assert.equal(invalid.status, 2);
164
+ assert.equal(JSON.parse(invalid.stdout).kind, 'skillfit.eval-error');
165
+ }
166
+ assert.equal(existsSync(join(cwd, 'runs')), false);
167
+ });
168
+ test('API, trigger and judged paired previews bind deadlines and budgets without starting executors', t => {
169
+ const cwd = mkdtempSync(join(tmpdir(), 'skillfit-cli-api-plan-'));
170
+ t.after(() => rmSync(cwd, { recursive: true, force: true }));
171
+ const env = { ...process.env, SKILLFIT_API_KEY: 'synthetic-dry-run-only', SKILLFIT_API_BASE_URL: 'https://offline.invalid/v1', SKILLFIT_JUDGE: '0' };
172
+ const api = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--dry-run', '--json', '--executor-timeout-seconds', '9'], { cwd, env, encoding: 'utf8' });
173
+ assert.equal(api.status, 0, api.stderr);
174
+ const plan = JSON.parse(api.stdout).plan.evaluation;
175
+ assert.equal(plan.executor.kind, 'api');
176
+ assert.equal(plan.executorTimeoutSeconds, 9);
177
+ const defaults = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--dry-run', '--json'], { cwd, env, encoding: 'utf8' });
178
+ assert.equal(defaults.status, 0, defaults.stderr);
179
+ assert.equal(JSON.parse(defaults.stdout).plan.evaluation.executorTimeoutSeconds, 120);
180
+ const trigger = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--agent', 'codex', '--mode', 'trigger', '--dry-run', '--json'], { cwd, env, encoding: 'utf8' });
181
+ assert.equal(trigger.status, 0, trigger.stderr);
182
+ assert.equal(JSON.parse(trigger.stdout).plan.evaluation.mode, 'trigger');
183
+ const file = join(cwd, 'budget.json');
184
+ writeFileSync(file, JSON.stringify({ input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 }));
185
+ for (const flags of [['--mode', 'trigger', '--agent', 'codex'], ['--judge-agent', 'codex', '--agent', 'codex']]) {
186
+ const result = spawnSync(process.execPath, [CLI, ...COMMANDS[0], '--dry-run', '--json', '--spending-budget', file, ...flags], { cwd, env, encoding: 'utf8' });
187
+ assert.equal(result.status, 0, result.stderr);
188
+ const preview = JSON.parse(result.stdout).plan.evaluation;
189
+ assert.deepEqual(preview.spendingBudget, JSON.parse(readFileSync(file, 'utf8')));
190
+ assert.equal(preview.plannedCalls, flags[0] === '--mode' ? 25 : 100);
191
+ }
192
+ assert.equal(existsSync(join(cwd, 'runs')), false);
193
+ });
@@ -0,0 +1,197 @@
1
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { getAgent } from '../agents.js';
6
+ import { assertAgentEnvironment, assertAgentEnvironmentUnchanged, inspectAgentEnvironment, renderAgentEnvironment } from '../harness/agent-preflight.js';
7
+ import { loadBench, selectBenchTasks } from '../harness/bench.js';
8
+ import { RUN_GROUP_PATTERN } from '../harness/constants.js';
9
+ import { summarizeCosts } from '../harness/costs.js';
10
+ import { createSpendingBudgetRecorder, parseSpendingBudget } from '../harness/eval-budget.js';
11
+ import { parseExecutorTimeoutSeconds } from '../harness/eval-contract.js';
12
+ import { ExperimentSession, validateCallBudget } from '../harness/experiment-session.js';
13
+ import { CliExecutor } from '../harness/executors/cli.js';
14
+ import { hashFileSet, listFilesRecursive, sha256File, sha256Text } from '../harness/hash.js';
15
+ import { throwIfEvaluationInterrupted } from '../harness/interruption.js';
16
+ import { assertInputModeSupported } from '../harness/prompt.js';
17
+ import { runTrial } from '../harness/runner.js';
18
+ function emptySkill(sourceDir) {
19
+ return { kind: 'skill', name: 'calibration-none', sourceDir, files: [], sha256: '0'.repeat(64), payload: '', overlays: {} };
20
+ }
21
+ function resolveCalibration(input) {
22
+ const options = input.calibrate;
23
+ const bench = selectBenchTasks(loadBench(resolve(input.dir ?? '.')), input.taskIds ?? options.taskIds);
24
+ const trials = options.trials ?? 2;
25
+ if (!Number.isInteger(trials) || trials < 1 || trials > 20)
26
+ throw new Error(`calibration trials must be an integer between 1 and 20, got ${trials}`);
27
+ const plannedCalls = bench.tasks.length * trials, maxCalls = validateCallBudget(plannedCalls, options.maxCalls);
28
+ const inputMode = options.inputMode ?? 'snapshot', executorTimeoutSeconds = parseExecutorTimeoutSeconds(options.executorTimeoutSeconds);
29
+ const spendingBudget = options.spendingBudget === undefined ? undefined : parseSpendingBudget(options.spendingBudget);
30
+ if (options.executor && options.executorTimeoutSeconds !== undefined) {
31
+ throw new Error('executorTimeoutSeconds cannot configure an injected executor; configure its timeout directly.');
32
+ }
33
+ const definition = options.agent ? getAgent(options.agent) : undefined;
34
+ let executor = null, resolutionError, capabilityError;
35
+ try {
36
+ executor = options.executor ?? (definition ? CliExecutor.forAgent(definition.id, {
37
+ timeoutMs: executorTimeoutSeconds * 1000,
38
+ ...(definition.headless.streamJson ? { triggerSkillName: 'calibration-none' } : {}),
39
+ }) : null);
40
+ }
41
+ catch (error) {
42
+ resolutionError = error.message;
43
+ }
44
+ try {
45
+ if (executor) {
46
+ assertInputModeSupported(inputMode, executor);
47
+ if (executor.describe().kind === 'api' && bench.tasks.some(task => (task.verifierKind ?? 'output') === 'command')) {
48
+ throw new Error('Command-verifier calibration needs a filesystem-capable CLI executor; an API executor cannot edit the workspace.');
49
+ }
50
+ }
51
+ }
52
+ catch (error) {
53
+ capabilityError = error.message;
54
+ }
55
+ const inspect = () => inspectAgentEnvironment({ roles: [{ role: 'agent', definition, executor: executor?.describe() ?? null,
56
+ injected: options.executor !== undefined, resolutionError: resolutionError ?? (!executor ? '--calibrate needs --agent (a CLI executor for real runs)' : undefined) }],
57
+ mode: 'inject', target: emptySkill(bench.dir), capabilityError,
58
+ homeDir: options.sessionOptions?.homeDir, env: options.sessionOptions?.env });
59
+ const agentPreflight = inspect();
60
+ const runsRoot = resolve(options.runsRoot ?? 'runs');
61
+ const runGroup = options.runGroup ?? `calibrate-${new Date().toISOString().replace(/\D/g, '').slice(0, 17)}`;
62
+ if (!RUN_GROUP_PATTERN.test(runGroup))
63
+ throw new Error(`Invalid run group: ${runGroup}`);
64
+ const outputDir = join(runsRoot, runGroup);
65
+ if (existsSync(outputDir))
66
+ throw new Error(`Run group directory already exists: ${outputDir}`);
67
+ const guardFiles = (options.guardFiles ?? []).map(file => ({ ...file, path: resolve(file.path) }));
68
+ for (const file of guardFiles)
69
+ if (sha256File(file.path) !== file.sha256)
70
+ throw new Error(`Frozen ${file.label} file changed before planning.`);
71
+ const implementationDir = fileURLToPath(new URL('../../dist', import.meta.url));
72
+ const data = { schemaVersion: 1, kind: 'skillfit.calibration-plan',
73
+ implementationSha256: hashFileSet(implementationDir, listFilesRecursive(implementationDir)),
74
+ bench: { dir: bench.dir, name: bench.name, sha256: bench.contentSha256, taskIds: bench.tasks.map(task => task.id) },
75
+ agent: options.agent ?? null, executor: executor?.describe() ?? null, inputMode, trials, plannedCalls, maxCalls,
76
+ executorTimeoutSeconds, ...(spendingBudget ? { spendingBudget } : {}), runsRoot, runGroup, outputDir, guardFiles, agentPreflight,
77
+ casePreflight: { schemaVersion: 1, scope: 'offline-case-integrity', required: true, status: 'pending' } };
78
+ const plan = { ...data, planSha256: sha256Text(JSON.stringify(data)) };
79
+ if (options.reviewedPlanSha256 !== undefined && options.reviewedPlanSha256.toLowerCase() !== plan.planSha256) {
80
+ throw new Error('Calibration plan changed before execution; inputs, budget, executor or implementation changed. No calls allowed.');
81
+ }
82
+ return { bench, executor, options, plan, inspect };
83
+ }
84
+ /** A preview reads fingerprints and PATH only; it runs no verifier, oracle or agent. */
85
+ export function prepareBenchCalibration(input) {
86
+ return resolveCalibration(input).plan;
87
+ }
88
+ export function prepareCalibration(input) {
89
+ return resolveCalibration(input);
90
+ }
91
+ export function calibrationCasePreflight(bench, report, durationMs) {
92
+ const checks = report.checks.map(check => ({ ...check,
93
+ status: (check.code === 'ORACLE' && check.status === 'WARN') ||
94
+ ((check.code === 'MOCK_BASELINE' || check.code === 'MOCK_TREATMENT') && check.status === 'INFO' && check.evidence === null) ||
95
+ (check.code === 'MOCK_COVERAGE' && check.status === 'INFO' && bench.tasks.some(task => task.id === check.taskId && (task.verifierKind ?? 'output') === 'output'))
96
+ ? 'UNKNOWN' : check.status }));
97
+ if (loadBench(bench.dir).contentSha256 !== bench.contentSha256)
98
+ checks.push({ code: 'INPUT_CHANGED', status: 'FAIL',
99
+ message: 'Bench content changed during offline calibration preflight.', taskId: null, location: { path: 'bench.json', field: null },
100
+ remediation: 'Fix the inputs and create a fresh calibration plan.', evidence: null });
101
+ const count = (status) => checks.filter(check => check.status === status).length;
102
+ return { schemaVersion: 1, kind: 'skillfit.eval-preflight', scope: 'offline-case-integrity', status: count('FAIL') ? 'blocked' : 'ready',
103
+ bench: { dir: bench.dir, sha256: bench.contentSha256, taskIds: bench.tasks.map(task => task.id) }, checks,
104
+ summary: { failures: count('FAIL'), warnings: count('WARN'), unknown: count('UNKNOWN'), passed: count('PASS'), info: count('INFO') },
105
+ cost: { modelCalls: 0, durationMs } };
106
+ }
107
+ export async function executeCalibration(prepared, casePreflight, push, log) {
108
+ const { bench, executor, options, plan, inspect } = prepared;
109
+ if (casePreflight.status !== 'ready' || casePreflight.checks.some(check => check.status === 'FAIL') ||
110
+ casePreflight.bench.sha256 !== bench.contentSha256 ||
111
+ JSON.stringify(casePreflight.bench.taskIds) !== JSON.stringify(plan.bench.taskIds)) {
112
+ throw new Error('Offline case preflight blocked calibration; matching ready evidence is required before any agent call.');
113
+ }
114
+ assertAgentEnvironment(plan.agentPreflight);
115
+ if (!executor)
116
+ throw new Error('--calibrate needs --agent (a CLI executor for real runs)');
117
+ assertAgentEnvironmentUnchanged(plan.agentPreflight, inspect());
118
+ throwIfEvaluationInterrupted();
119
+ const emptySkillDir = mkdtempSync(join(tmpdir(), 'skillfit-calibrate-'));
120
+ const outcomes = [];
121
+ // Retain the declared cohort even when a stop line prevents its later tasks.
122
+ const taskResults = bench.tasks.map(task => ({ id: task.id, passes: 0, completed: 0, errors: 0 }));
123
+ let session, failure;
124
+ try {
125
+ log(renderAgentEnvironment(plan.agentPreflight));
126
+ session = new ExperimentSession({ bench, target: emptySkill(emptySkillDir), groupDir: plan.outputDir,
127
+ plannedCalls: plan.plannedCalls, maxCalls: plan.maxCalls, agent: options.agent, injected: options.executor !== undefined,
128
+ ...options.sessionOptions, guardFiles: options.guardFiles,
129
+ workspaces: bench.tasks.flatMap(task => Array.from({ length: plan.trials }, (_, index) => join(plan.outputDir, task.id, 'baseline', `trial-${index + 1}`))),
130
+ details: { mode: 'calibration', inputMode: plan.inputMode, trials: plan.trials, executor: executor.describe(),
131
+ executorTimeoutSeconds: plan.executorTimeoutSeconds, ...(plan.spendingBudget ? { spendingBudget: plan.spendingBudget } : {}),
132
+ taskIds: plan.bench.taskIds, agentPreflight: plan.agentPreflight, casePreflight, reviewedPlan: plan } });
133
+ const runPlan = { bench, target: emptySkill(emptySkillDir), inputMode: plan.inputMode,
134
+ executor: session.wrap(executor, 'agent'), trials: plan.trials, runsRoot: plan.runsRoot, runGroup: plan.runGroup, log };
135
+ const budget = createSpendingBudgetRecorder({ budget: plan.spendingBudget, groupDir: session.groupDir });
136
+ push('INFO', `calibration: ${plan.trials} run(s) per task with no skill installed (baseline difficulty; input ${plan.inputMode}); ${plan.plannedCalls} calls, ceiling ${plan.maxCalls}; deadline ${plan.executorTimeoutSeconds}s`);
137
+ let discriminative = 0, tasksRun = 0;
138
+ for (const [taskIndex, task] of bench.tasks.entries()) {
139
+ const taskResult = taskResults[taskIndex];
140
+ for (let trial = 1; trial <= plan.trials; trial++) {
141
+ throwIfEvaluationInterrupted();
142
+ const identity = { taskId: task.id, condition: 'baseline', trial };
143
+ budget.before(identity);
144
+ const outcome = await runTrial(runPlan, task.id, 'baseline', trial);
145
+ outcomes.push(outcome);
146
+ if (outcome.error !== null)
147
+ taskResult.errors++;
148
+ else {
149
+ taskResult.completed++;
150
+ if (outcome.passed)
151
+ taskResult.passes++;
152
+ }
153
+ budget.after(identity, outcome);
154
+ throwIfEvaluationInterrupted();
155
+ }
156
+ const { passes, completed, errors } = taskResult;
157
+ if (!completed) {
158
+ push('WARN', `${task.id}: no completed runs${errors ? ` (${errors} ungraded run(s))` : ''} — cannot assess difficulty`);
159
+ continue;
160
+ }
161
+ tasksRun++;
162
+ const rate = passes / completed;
163
+ if (rate >= .9)
164
+ push('WARN', `${task.id}: baseline ${passes}/${completed} — too easy (saturated; cannot discriminate skill effects)`);
165
+ else if (rate <= .1)
166
+ push('WARN', `${task.id}: baseline ${passes}/${completed} — too hard or broken (floor)`);
167
+ else {
168
+ discriminative++;
169
+ push('PASS', `${task.id}: baseline ${passes}/${completed} — discriminative band`);
170
+ }
171
+ }
172
+ session.settle();
173
+ if (session.summary().status !== 'completed')
174
+ push('FAIL', 'Calibration stopped or incomplete; inspect _session.json and _calls.jsonl before a fresh plan.');
175
+ if (!tasksRun)
176
+ push('FAIL', `calibration ran 0 task(s): difficulty unmeasured (runs under ${plan.runGroup})`);
177
+ else
178
+ push(discriminative === tasksRun ? 'PASS' : 'INFO', `calibration: ${discriminative}/${tasksRun} task(s) in the discriminative band (runs under ${plan.runGroup}; use --trials 3+ for steadier reads)`);
179
+ }
180
+ catch (error) {
181
+ failure = error;
182
+ throw error;
183
+ }
184
+ finally {
185
+ try {
186
+ if (session) {
187
+ const result = { schemaVersion: 1, runGroup: plan.runGroup, inputMode: plan.inputMode, trials: plan.trials, tasks: taskResults,
188
+ costs: summarizeCosts({ baseline: outcomes, treatment: [] }, { baseline: [], treatment: [] }), experiment: session.summary() };
189
+ writeFileSync(join(session.groupDir, '_calibration.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
190
+ session.finish(failure, result, '_calibration.json');
191
+ }
192
+ }
193
+ finally {
194
+ rmSync(emptySkillDir, { recursive: true, force: true });
195
+ }
196
+ }
197
+ }
@@ -0,0 +1,237 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { test } from 'node:test';
8
+ import { prepareBenchCalibration, runBenchCalibration, runBenchCheck, runBenchInit } from './bench.js';
9
+ import { CasePreflightFailed } from './eval-preflight.js';
10
+ import { AgentPreflightFailed } from '../harness/agent-preflight.js';
11
+ import { killTree } from '../harness/kill-tree.js';
12
+ import { evaluationSignal, withEvaluationInterrupts } from '../harness/interruption.js';
13
+ import { sha256File } from '../harness/hash.js';
14
+ import { readSingleArmReport } from './eval-single-arm-report.js';
15
+ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
16
+ const json = (path) => JSON.parse(readFileSync(path, 'utf8'));
17
+ const budget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
18
+ const final = { output: 'skillfit-ok', tokens: { input: 10, cachedInput: 2, output: 3 } };
19
+ async function fixture(t, kind = 'output') {
20
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-calibration-guard-')), dir = join(root, 'bench');
21
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
22
+ await runBenchInit({ dir, kind, yes: true, log: () => { } });
23
+ return { root, dir, runsRoot: join(root, 'runs'), runGroup: 'calibration' };
24
+ }
25
+ test('calibration refuses a solved fixture or broken oracle before any executor, version probe or native output', async (t) => {
26
+ for (const gate of ['untouched', 'oracle'])
27
+ await t.test(gate, async (t) => {
28
+ const f = await fixture(t, 'command');
29
+ if (gate === 'untouched')
30
+ writeFileSync(join(f.dir, 'verifiers/example-task.mjs'), 'process.exit(0);');
31
+ else
32
+ writeFileSync(join(f.dir, 'ground-truth/oracle-example-task.mjs'), 'process.exit(4);');
33
+ let calls = 0, versions = 0;
34
+ const executor = { describe: () => ({ kind: 'cli', model: 'offline' }), run: async () => { calls++; return final; } };
35
+ const report = await runBenchCheck({ dir: f.dir, calibrate: { executor, agent: 'codex', trials: 1,
36
+ runsRoot: f.runsRoot, runGroup: f.runGroup, sessionOptions: { homeDir: join(f.root, 'home'),
37
+ env: { CODEX_HOME: join(f.root, 'home/codex') }, versionProbe: () => { versions++; return 'offline'; } } }, log: () => { } });
38
+ assert.ok(report.failures > 0);
39
+ assert.ok(report.checks.some(check => check.code === 'CALIBRATION' && check.status === 'FAIL' && /preflight blocked/.test(check.message)));
40
+ assert.equal(calls, 0);
41
+ assert.equal(versions, 0);
42
+ assert.ok(!existsSync(f.runsRoot));
43
+ });
44
+ });
45
+ test('calibration preview fingerprints settings without executing verifier/oracle and rejects a stale plan', async (t) => {
46
+ const f = await fixture(t), sentinel = join(f.root, 'probe');
47
+ writeFileSync(join(f.dir, 'verifiers/example-task.mjs'), `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'bad');process.exit(1);`);
48
+ const options = { dir: f.dir, calibrate: { agent: 'codex', trials: 2, runsRoot: f.runsRoot, runGroup: f.runGroup,
49
+ executorTimeoutSeconds: 17, spendingBudget: budget, sessionOptions: { homeDir: join(f.root, 'home'), env: { PATH: '' } } } };
50
+ const plan = prepareBenchCalibration(options);
51
+ assert.equal(plan.kind, 'skillfit.calibration-plan');
52
+ assert.equal(plan.executorTimeoutSeconds, 17);
53
+ assert.equal(plan.plannedCalls, 2);
54
+ assert.equal(plan.maxCalls, 2);
55
+ assert.equal(plan.agentPreflight.status, 'blocked');
56
+ assert.ok(plan.agentPreflight.checks.some(check => check.code === 'AUTHENTICATION' && check.status === 'UNKNOWN'));
57
+ assert.ok(!existsSync(sentinel));
58
+ assert.ok(!existsSync(f.runsRoot));
59
+ assert.deepEqual(prepareBenchCalibration(options), plan);
60
+ await assert.rejects(runBenchCheck({ ...options, calibrate: { ...options.calibrate,
61
+ executorTimeoutSeconds: 18, reviewedPlanSha256: plan.planSha256 }, log: () => { } }), /plan changed before execution/);
62
+ assert.ok(!existsSync(sentinel));
63
+ const lines = [];
64
+ await runBenchCheck({ ...options, calibrate: { ...options.calibrate, dryRun: true }, log: line => lines.push(line) });
65
+ assert.ok(!existsSync(sentinel));
66
+ assert.match(lines.join('\n'), /no verifier, oracle or agent started/);
67
+ });
68
+ test('strict calibration exposes typed Agent and case preflight failures without changing legacy bench check', async (t) => {
69
+ const f = await fixture(t, 'command');
70
+ await assert.rejects(runBenchCalibration({ dir: f.dir, calibrate: { agent: 'codex', runsRoot: f.runsRoot, runGroup: f.runGroup,
71
+ sessionOptions: { homeDir: join(f.root, 'home'), env: { PATH: '', CODEX_HOME: join(f.root, 'home/codex') } } }, log: () => { } }), (error) => error instanceof AgentPreflightFailed && error.agentPreflight.status === 'blocked');
72
+ writeFileSync(join(f.dir, 'verifiers/example-task.mjs'), 'process.exit(0);');
73
+ let calls = 0;
74
+ const executor = { describe: () => ({ kind: 'cli', model: 'offline' }), run: async () => { calls++; return final; } };
75
+ await assert.rejects(runBenchCalibration({ dir: f.dir, calibrate: { executor, runsRoot: f.runsRoot, runGroup: f.runGroup }, log: () => { } }), (error) => error instanceof CasePreflightFailed && error.preflight.checks.some(check => check.code === 'UNTOUCHED_FIXTURE' && check.status === 'FAIL'));
76
+ assert.equal(calls, 0);
77
+ assert.ok(!existsSync(f.runsRoot));
78
+ });
79
+ test('offline warnings and unknown winnability do not block calibration and are retained separately', async (t) => {
80
+ const f = await fixture(t);
81
+ const manifest = json(join(f.dir, 'bench.json'));
82
+ delete manifest.tasks[0].oracle;
83
+ writeFileSync(join(f.dir, 'bench.json'), JSON.stringify(manifest));
84
+ writeFileSync(join(f.dir, 'fixtures/example-task/large.txt'), 'x'.repeat(66 * 1024));
85
+ let calls = 0;
86
+ const executor = { describe: () => ({ kind: 'cli', model: 'offline' }), run: async () => { calls++; return final; } };
87
+ const options = { dir: f.dir, calibrate: { executor, trials: 1, runsRoot: f.runsRoot, runGroup: f.runGroup, spendingBudget: budget } };
88
+ const preview = prepareBenchCalibration(options);
89
+ const report = await runBenchCheck({ ...options, calibrate: { ...options.calibrate, reviewedPlanSha256: preview.planSha256 }, log: () => { } });
90
+ assert.equal(report.failures, 0);
91
+ assert.equal(calls, 1);
92
+ const details = json(join(f.runsRoot, f.runGroup, '_plan.json')).details;
93
+ assert.equal(details.reviewedPlan.planSha256, preview.planSha256);
94
+ assert.equal(details.casePreflight.status, 'ready');
95
+ assert.ok(details.casePreflight.checks.some((check) => check.code === 'ORACLE' && check.status === 'UNKNOWN'));
96
+ assert.ok(details.casePreflight.checks.some((check) => check.code === 'FIXTURE_SIZE' && check.status === 'WARN'));
97
+ assert.ok(details.agentPreflight.checks.some((check) => check.code === 'AUTHENTICATION' && check.status === 'UNKNOWN'));
98
+ const result = json(join(f.runsRoot, f.runGroup, '_calibration.json'));
99
+ assert.equal(result.experiment.status, 'completed');
100
+ assert.equal(result.costs.attempts.baseline.metrics.input.knownTotal, 10);
101
+ });
102
+ test('calibration rechecks environment and bench changes introduced by offline probes before first dispatch', async (t) => {
103
+ for (const change of ['environment', 'bench'])
104
+ await t.test(change, async (t) => {
105
+ const f = await fixture(t), home = join(f.root, 'home'), codex = join(home, 'codex');
106
+ const path = join(f.dir, 'verifiers/example-task.mjs'), source = readFileSync(path, 'utf8');
107
+ const mutation = change === 'environment'
108
+ ? `mkdirSync(${JSON.stringify(join(codex, 'skills/calibration-none'))},{recursive:true});writeFileSync(${JSON.stringify(join(codex, 'skills/calibration-none/SKILL.md'))},'---\\nname: calibration-none\\n---\\nbody');`
109
+ : `writeFileSync(${JSON.stringify(join(f.dir, 'prompts/example-task.md'))},'changed');`;
110
+ writeFileSync(path, `import{mkdirSync,writeFileSync}from'node:fs';${mutation}\n${source}`);
111
+ let calls = 0;
112
+ const executor = { describe: () => ({ kind: 'cli', model: 'offline' }), run: async () => { calls++; return final; } };
113
+ const options = { dir: f.dir, calibrate: { agent: 'codex', executor, trials: 1, runsRoot: f.runsRoot,
114
+ runGroup: f.runGroup, sessionOptions: { homeDir: home, env: { CODEX_HOME: codex } } }, log: () => { } };
115
+ if (change === 'environment')
116
+ await assert.rejects(runBenchCheck(options), /Baseline contamination|environment preflight blocked/);
117
+ else
118
+ assert.ok((await runBenchCheck(options)).failures > 0);
119
+ assert.equal(calls, 0);
120
+ assert.ok(!existsSync(f.runsRoot));
121
+ });
122
+ });
123
+ test('calibration budgets stop at the next boundary and retain stopped receipts without retries', async (t) => {
124
+ for (const usage of ['reached', 'missing', 'error'])
125
+ await t.test(usage, async (t) => {
126
+ const f = await fixture(t);
127
+ const manifest = json(join(f.dir, 'bench.json'));
128
+ manifest.tasks.push({ ...manifest.tasks[0], id: 'later-task' });
129
+ writeFileSync(join(f.dir, 'bench.json'), JSON.stringify(manifest));
130
+ let calls = 0;
131
+ const executor = { describe: () => ({ kind: 'cli', model: 'offline' }), run: async () => {
132
+ calls++;
133
+ if (usage === 'error')
134
+ throw new Error('offline executor failure');
135
+ return usage === 'missing' ? { output: final.output } : final;
136
+ } };
137
+ await assert.rejects(runBenchCheck({ dir: f.dir, calibrate: { executor, trials: 3,
138
+ spendingBudget: { ...budget, input: usage === 'reached' ? 10 : 1000 }, runsRoot: f.runsRoot, runGroup: f.runGroup }, log: () => { } }), usage === 'reached' ? /SPENDING_BUDGET_REACHED/ : usage === 'missing' ? /FINAL_USAGE_MISSING/ : /EXECUTION_FAILED/);
139
+ assert.equal(calls, 1);
140
+ const group = join(f.runsRoot, f.runGroup), session = json(join(group, '_session.json'));
141
+ assert.equal(session.status, 'stopped');
142
+ assert.equal(session.callsStarted, 1);
143
+ const result = json(join(group, '_calibration.json'));
144
+ assert.equal(result.experiment.status, 'stopped');
145
+ assert.deepEqual(result.tasks[1], { id: 'later-task', passes: 0, completed: 0, errors: 0 });
146
+ const report = readSingleArmReport(group);
147
+ assert.ok(report);
148
+ assert.equal(report.status, 'stopped');
149
+ const events = readFileSync(join(group, '_budget.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line));
150
+ assert.equal(events.filter(event => event.phase === 'after-call').length, 1);
151
+ assert.equal(events.at(-1).state.reason, usage === 'reached' ? 'SPENDING_BUDGET_REACHED' : usage === 'missing' ? 'FINAL_USAGE_MISSING' : 'EXECUTION_FAILED');
152
+ const index = json(join(group, '_artifacts.json'));
153
+ for (const [path, sha] of Object.entries(index.files))
154
+ assert.equal(sha256File(join(group, path)), sha, path);
155
+ });
156
+ });
157
+ test('standalone bench check reuses an enclosing evaluation cancellation context and removes only its own handlers', async (t) => {
158
+ const f = await fixture(t);
159
+ const counts = () => [process.listenerCount('SIGINT'), process.listenerCount('SIGTERM')], initial = counts();
160
+ await withEvaluationInterrupts(async () => {
161
+ const signal = evaluationSignal(), before = counts();
162
+ const result = await runBenchCheck({ dir: f.dir, log: () => assert.equal(evaluationSignal(), signal) });
163
+ assert.equal(result.failures, 0);
164
+ assert.deepEqual(counts(), before);
165
+ assert.equal(evaluationSignal(), signal);
166
+ });
167
+ assert.deepEqual(counts(), initial);
168
+ assert.equal(evaluationSignal(), undefined);
169
+ });
170
+ function running(pid) {
171
+ try {
172
+ process.kill(pid, 0);
173
+ if (process.platform === 'linux' && readFileSync(`/proc/${pid}/stat`, 'utf8').split(')').at(-1).trim().startsWith('Z'))
174
+ return false;
175
+ return true;
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ for (const signal of ['SIGINT', 'SIGTERM'])
182
+ for (const stage of ['verifier', 'oracle']) {
183
+ test(`${signal} cancels independent bench check ${stage} and its descendants and removes disposable probes`, { timeout: 30_000 }, async (t) => {
184
+ const f = await fixture(t), ready = join(f.root, 'ready.json'), heartbeat = join(f.root, 'heartbeat'), leaf = join(f.root, 'leaf.mjs');
185
+ let child;
186
+ t.after(async () => {
187
+ if (child?.exitCode === null && child.signalCode === null)
188
+ killTree(child);
189
+ if (existsSync(ready))
190
+ for (const pid of json(ready).pids)
191
+ if (running(pid))
192
+ try {
193
+ process.kill(pid, 'SIGKILL');
194
+ }
195
+ catch { /* already dead */ }
196
+ await delay(100);
197
+ });
198
+ writeFileSync(leaf, `import{appendFileSync}from'node:fs';setInterval(()=>appendFileSync(${JSON.stringify(heartbeat)},'x'),30);setTimeout(()=>process.exit(),20000);`);
199
+ const source = `import{spawn}from'node:child_process';import{existsSync,writeFileSync}from'node:fs';
200
+ const leaf=spawn(process.execPath,[${JSON.stringify(leaf)}],{stdio:'ignore'});
201
+ const timer=setInterval(()=>{if(existsSync(${JSON.stringify(heartbeat)})){clearInterval(timer);writeFileSync(${JSON.stringify(ready)},JSON.stringify({dir:process.argv[2],pids:[process.pid,leaf.pid]}));}},20);
202
+ setTimeout(()=>process.exit(),20000);`;
203
+ writeFileSync(join(f.dir, stage === 'oracle' ? 'ground-truth/oracle-example-task.mjs' : 'verifiers/example-task.mjs'), source);
204
+ const module = pathToFileURL(fileURLToPath(new URL('./bench.js', import.meta.url))).href;
205
+ const harness = join(f.root, 'harness.mjs');
206
+ writeFileSync(harness, `import{writeFileSync}from'node:fs';import{runBenchCheck}from ${JSON.stringify(module)};
207
+ const counts=()=>[process.listenerCount('SIGINT'),process.listenerCount('SIGTERM')],before=counts();
208
+ process.on('message',message=>process.emit(message.signal));
209
+ try{await runBenchCheck({dir:${JSON.stringify(f.dir)},log:()=>{}});}catch(error){writeFileSync(${JSON.stringify(join(f.root, 'error'))},error.message);}
210
+ finally{writeFileSync(${JSON.stringify(join(f.root, 'done.json'))},JSON.stringify({before,after:counts()}));process.disconnect();}`);
211
+ child = spawn(process.execPath, [harness], { stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
212
+ let stderr = '';
213
+ child.stdout.resume();
214
+ child.stderr.on('data', chunk => { stderr += chunk; });
215
+ const exited = new Promise(resolve => child.on('exit', (code, signal) => resolve({ code, signal })));
216
+ for (let index = 0; index < 200 && !existsSync(ready) && child.exitCode === null; index++)
217
+ await delay(50);
218
+ assert.ok(existsSync(ready), `Offline ${stage} did not start: ${stderr}`);
219
+ if (process.platform === 'win32')
220
+ child.send({ signal });
221
+ else
222
+ child.kill(signal);
223
+ let timeout;
224
+ const exit = await Promise.race([exited, new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error(`bench check did not stop: ${stderr}`)), 8000); })]).finally(() => clearTimeout(timeout));
225
+ assert.deepEqual(exit, { code: signal === 'SIGINT' ? 130 : 143, signal: null }, stderr);
226
+ assert.deepEqual(json(join(f.root, 'done.json')).after, json(join(f.root, 'done.json')).before);
227
+ assert.match(readFileSync(join(f.root, 'error'), 'utf8'), new RegExp(signal));
228
+ assert.ok(!existsSync(json(ready).dir), 'the interrupted disposable fixture must be removed');
229
+ for (let index = 0; index < 100 && json(ready).pids.some(running); index++)
230
+ await delay(50);
231
+ assert.ok(json(ready).pids.every((pid) => !running(pid)), 'both verifier/oracle and grandchild must stop');
232
+ const before = readFileSync(heartbeat, 'utf8');
233
+ await delay(100);
234
+ assert.equal(readFileSync(heartbeat, 'utf8'), before);
235
+ assert.ok(!existsSync(f.runsRoot), 'offline interruption must not create a calibration run');
236
+ });
237
+ }
@@ -185,13 +185,11 @@ test('noisy verifier output stays inside bounded JSON evidence while named facet
185
185
  assert.equal(evidence.checks.length, 4);
186
186
  assert.ok(evidence.checks.every((c) => c.pass));
187
187
  });
188
- test('argument errors and calibration combinations return JSON before any verifier or agent starts', async (t) => {
188
+ test('argument errors return offline bench JSON before any verifier or agent starts', async (t) => {
189
189
  const { cwd, dir } = await scaffold(t);
190
190
  const sentinel = join(cwd, 'verifier-started');
191
191
  writeFileSync(join(dir, 'verifiers/example-task.mjs'), `import {writeFileSync} from 'node:fs'; writeFileSync(${JSON.stringify(sentinel)},'unexpected'); process.exit(1);`);
192
192
  const cases = [
193
- ['bench', 'check', dir, '--json', '--calibrate', '--agent', 'skillfit-no-live-agent'],
194
- ['bench', 'check', dir, '--json', '--calibrate', '--dry-run', '--agent', 'skillfit-no-live-agent'],
195
193
  ['--json', 'bench', 'check', dir, '--trials', 'nope'],
196
194
  ['bench', '--json', 'check', dir, '--unknown-option'],
197
195
  ['bench', 'check', dir, '--json', '--trials'],
@@ -207,6 +205,29 @@ test('argument errors and calibration combinations return JSON before any verifi
207
205
  assert.ok(!existsSync(sentinel));
208
206
  }
209
207
  });
208
+ test('JSON calibration has a distinct planned/error contract and never runs probes without confirmation', async (t) => {
209
+ const { cwd, dir } = await scaffold(t);
210
+ const sentinel = join(cwd, 'verifier-started');
211
+ writeFileSync(join(dir, 'verifiers/example-task.mjs'), `import {writeFileSync} from 'node:fs';writeFileSync(${JSON.stringify(sentinel)},'unexpected');process.exit(1);`);
212
+ const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'PATH')),
213
+ PATH: '', HOME: join(cwd, 'home'), USERPROFILE: join(cwd, 'home'), CODEX_HOME: join(cwd, 'home/codex') };
214
+ for (const dryRun of [false, true]) {
215
+ const result = spawnSync(process.execPath, [CLI, 'bench', 'check', dir, '--json', '--calibrate', '--agent', 'codex',
216
+ ...(dryRun ? ['--dry-run'] : [])], { cwd, env, encoding: 'utf8', timeout: 30_000 });
217
+ assert.equal(result.status, dryRun ? 0 : 2, result.stderr || result.stdout);
218
+ assert.equal(result.stderr, '');
219
+ const data = JSON.parse(result.stdout);
220
+ assert.equal(data.kind, dryRun ? 'skillfit.calibration-result' : 'skillfit.eval-error');
221
+ assert.equal(data.status, dryRun ? 'planned' : 'error');
222
+ assert.equal(data.acceptance.eligibleForUpgrade, false);
223
+ if (dryRun)
224
+ assert.equal(data.plan.agentPreflight.status, 'blocked');
225
+ else
226
+ assert.match(data.error.message, /requires --plan-sha/);
227
+ assert.ok(!existsSync(sentinel));
228
+ assert.ok(!existsSync(join(cwd, 'runs')));
229
+ }
230
+ });
210
231
  test('unexpected local execution errors cannot be mistaken for a completed JSON validation', async (t) => {
211
232
  const { cwd, dir } = await scaffold(t);
212
233
  const absent = join(cwd, 'missing-temp-root');