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
@@ -2,19 +2,20 @@ import { spawnSync } from 'node:child_process';
2
2
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { tmpdir } from 'node:os';
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
- import { getAgent } from '../agents.js';
6
- import { loadBench } from '../harness/bench.js';
7
- import { ExperimentSession, validateCallBudget } from '../harness/experiment-session.js';
5
+ import { loadBench, selectBenchTasks } from '../harness/bench.js';
8
6
  import { CliExecutor } from '../harness/executors/cli.js';
9
7
  import { listFilesRecursive } from '../harness/hash.js';
10
- import { assertInputModeSupported } from '../harness/prompt.js';
11
- import { runTrial, runVerifier, verifierFailure } from '../harness/runner.js';
12
- import { MOCK_MARKER_FILE, RUN_GROUP_PATTERN } from '../harness/constants.js';
8
+ import { runVerifier, verifierFailure } from '../harness/runner.js';
9
+ import { MOCK_MARKER_FILE } from '../harness/constants.js';
13
10
  import { verdictFromOutput } from '../harness/verifier-summary.js';
14
11
  import { confirm as confirmPrompt } from './confirm.js';
15
12
  import { commandTemplateFiles } from './bench-command-template.js';
16
13
  import { benchDiagnostic, benchCheckEvidence } from './bench-check-report.js';
17
14
  import { BACKUP_SUFFIX } from './install.js';
15
+ import { withEvaluationInterrupts, throwIfEvaluationInterrupted } from '../harness/interruption.js';
16
+ import { assertAgentEnvironment, renderAgentEnvironment } from '../harness/agent-preflight.js';
17
+ import { calibrationCasePreflight, executeCalibration, prepareCalibration } from './bench-calibration.js';
18
+ export { prepareBenchCalibration } from './bench-calibration.js';
18
19
  const FIXTURE_SIZE_WARN_BYTES = 64 * 1024;
19
20
  // benches/README.md: a verifier decomposes its acceptance criteria into 2–8 named checks.
20
21
  const MIN_FACET_CHECKS = 2;
@@ -189,22 +190,22 @@ async function runOracleGate(benchDir, fixtureDir, oracle, verifier) {
189
190
  try {
190
191
  copyFixture(fixtureDir, dir);
191
192
  const oracleRun = await runVerifier(benchDir, oracle, dir);
192
- if (oracleRun.exitCode !== 0) {
193
+ if (oracleRun.error !== null || oracleRun.exitCode !== 0) {
193
194
  return {
194
195
  kind: 'oracle-failed',
195
196
  result: oracleRun,
196
197
  command: oracle,
197
198
  exitCode: oracleRun.exitCode,
198
- reason: oracleRun.exitCode === null ? verifierFailure('oracle', oracle, oracleRun.error) : null,
199
+ reason: oracleRun.error !== null || oracleRun.exitCode === null ? verifierFailure('oracle', oracle, oracleRun.error) : null,
199
200
  };
200
201
  }
201
202
  const graded = await runVerifier(benchDir, verifier, dir);
202
- if (graded.exitCode !== 0) {
203
+ if (graded.error !== null || graded.exitCode !== 0) {
203
204
  return {
204
205
  kind: 'verifier-failed',
205
206
  result: graded,
206
207
  command: verifier,
207
- reason: graded.exitCode === null ? verifierFailure('verifier', verifier, graded.error) : null,
208
+ reason: graded.error !== null || graded.exitCode === null ? verifierFailure('verifier', verifier, graded.error) : null,
208
209
  };
209
210
  }
210
211
  const score = verdictFromOutput(graded.output)?.score ?? null;
@@ -251,17 +252,24 @@ function renderCheck({ status, message }) {
251
252
  return `[${status}] ${message}`;
252
253
  }
253
254
  export async function runBenchCheck(options) {
255
+ return withEvaluationInterrupts(() => runBenchCheckWithinInterrupts(options));
256
+ }
257
+ export async function runBenchCalibration(options) {
258
+ return withEvaluationInterrupts(() => runBenchCheckWithinInterrupts(options, true));
259
+ }
260
+ async function runBenchCheckWithinInterrupts(options, strictCalibration = false) {
254
261
  const log = options.log ?? ((msg) => console.log(msg));
255
262
  const dir = resolve(options.dir ?? '.');
256
263
  const checks = [];
257
264
  let identity = null;
258
265
  const push = (code, status, message, task, evidence) => {
266
+ throwIfEvaluationInterrupted();
259
267
  checks.push(benchDiagnostic(code, status, message, task, evidence));
260
268
  log(renderCheck({ status, message }));
261
269
  };
262
270
  let bench;
263
271
  try {
264
- bench = loadBench(dir);
272
+ bench = selectBenchTasks(loadBench(dir), options.taskIds ?? (options.calibrate ? options.calibrate.taskIds : undefined));
265
273
  }
266
274
  catch (error) {
267
275
  push('BENCH_LOAD', 'FAIL', `bench does not load: ${error.message}`);
@@ -269,12 +277,26 @@ export async function runBenchCheck(options) {
269
277
  }
270
278
  identity = { name: bench.name, sha256: bench.contentSha256, taskCount: bench.tasks.length };
271
279
  push('BENCH_LOAD', 'PASS', `bench.json valid (${bench.tasks.length} task(s), content sha256 ${bench.contentSha256.slice(0, 12)}…)`);
272
- if (options.calibrate) {
273
- const trials = options.calibrate.trials ?? CALIBRATE_DEFAULT_TRIALS;
274
- if (!Number.isInteger(trials) || trials < 1 || trials > 20)
275
- throw new Error(`calibration trials must be an integer between 1 and 20, got ${trials}`);
276
- validateCallBudget(bench.tasks.length * trials, options.calibrate.maxCalls);
280
+ const calibration = options.calibrate ? prepareCalibration({ dir, taskIds: options.taskIds, calibrate: options.calibrate }) : null;
281
+ if (calibration) {
282
+ log(renderAgentEnvironment(calibration.plan.agentPreflight));
283
+ if (options.calibrate && options.calibrate.dryRun) {
284
+ push('CALIBRATION', 'INFO', `calibration executor: ${calibration.plan.executor?.detail ?? calibration.plan.executor?.model ?? 'unavailable'}`);
285
+ push('CALIBRATION', 'INFO', `calibration plan: ${bench.tasks.length} task(s) × ${calibration.plan.trials} baseline run(s), input ${calibration.plan.inputMode}; ${calibration.plan.plannedCalls} calls, ceiling ${calibration.plan.maxCalls}; deadline ${calibration.plan.executorTimeoutSeconds}s; no verifier, oracle or agent started and no run directory created`);
286
+ push('CALIBRATION', 'INFO', `Plan SHA-256: ${calibration.plan.planSha256}; fresh output ${calibration.plan.outputDir}`);
287
+ return finish(dir, checks, log, true, identity);
288
+ }
289
+ try {
290
+ assertAgentEnvironment(calibration.plan.agentPreflight);
291
+ }
292
+ catch (error) {
293
+ if (strictCalibration)
294
+ throw error;
295
+ push('CALIBRATION', 'FAIL', error.message);
296
+ return finish(dir, checks, log, true, identity);
297
+ }
277
298
  }
299
+ const offlineStarted = performance.now();
278
300
  let labeledTasks = 0;
279
301
  let negativeTasks = 0;
280
302
  for (const task of bench.tasks) {
@@ -286,7 +308,7 @@ export async function runBenchCheck(options) {
286
308
  copyFixture(join(bench.dir, task.fixture), fixtureCopy);
287
309
  const pristine = await runVerifier(bench.dir, task.verifier, fixtureCopy);
288
310
  facetChecks = verdictFromOutput(pristine.output)?.checks ?? null;
289
- if (pristine.exitCode === null) {
311
+ if (pristine.error !== null || pristine.exitCode === null) {
290
312
  // Without this branch a verifier that cannot even be spawned reads as a clean NOP gate:
291
313
  // "fails on the untouched fixture" is exactly what `exitCode !== 0` looks like.
292
314
  taskPush('UNTOUCHED_FIXTURE', 'FAIL', `${task.id}: ${verifierFailure('verifier', task.verifier, pristine.error)}`, benchCheckEvidence(pristine, task.verifier));
@@ -304,7 +326,7 @@ export async function runBenchCheck(options) {
304
326
  }
305
327
  else {
306
328
  const missing = await probeVerifier(bench.dir, task.verifier, null);
307
- if (missing.exitCode === null) {
329
+ if (missing.error !== null || missing.exitCode === null) {
308
330
  taskPush('MISSING_OUTPUT', 'FAIL', `${task.id}: ${verifierFailure('verifier', task.verifier, missing.error)}`, benchCheckEvidence(missing, task.verifier));
309
331
  }
310
332
  else if (missing.exitCode === 0) {
@@ -315,7 +337,7 @@ export async function runBenchCheck(options) {
315
337
  }
316
338
  const empty = await probeVerifier(bench.dir, task.verifier, '');
317
339
  facetChecks = empty.checks;
318
- if (empty.exitCode === null) {
340
+ if (empty.error !== null || empty.exitCode === null) {
319
341
  taskPush('EMPTY_OUTPUT', 'FAIL', `${task.id}: ${verifierFailure('verifier', task.verifier, empty.error)}`, benchCheckEvidence(empty, task.verifier));
320
342
  }
321
343
  else if (empty.exitCode === 0) {
@@ -346,13 +368,16 @@ export async function runBenchCheck(options) {
346
368
  const marker = JSON.parse(readFileSync(markerPath, 'utf8'));
347
369
  for (const arm of ['baseline', 'treatment']) {
348
370
  const behavior = marker[arm];
349
- if (behavior?.output === undefined)
371
+ if (behavior?.output === undefined) {
372
+ taskPush(arm === 'baseline' ? 'MOCK_BASELINE' : 'MOCK_TREATMENT', 'INFO', `${task.id}: no mock ${arm} output — this arm was not probed`);
350
373
  continue;
374
+ }
351
375
  const probe = await probeVerifier(bench.dir, task.verifier, behavior.output);
352
- taskPush(arm === 'baseline' ? 'MOCK_BASELINE' : 'MOCK_TREATMENT', 'INFO', `${task.id}: mock ${arm} output → verifier ${probe.exitCode === 0 ? 'pass' : 'fail'}`, benchCheckEvidence(probe, task.verifier));
376
+ taskPush(arm === 'baseline' ? 'MOCK_BASELINE' : 'MOCK_TREATMENT', probe.error !== null || probe.exitCode === null ? 'FAIL' : 'INFO', `${task.id}: mock ${arm} output → ${probe.error !== null || probe.exitCode === null ? verifierFailure('verifier', task.verifier, probe.error) : `verifier ${probe.exitCode === 0 ? 'pass' : 'fail'}`}`, benchCheckEvidence(probe, task.verifier));
353
377
  }
354
378
  }
355
379
  catch (error) {
380
+ throwIfEvaluationInterrupted();
356
381
  taskPush('MOCK_MARKER', 'FAIL', `${task.id}: ${MOCK_MARKER_FILE} is unreadable (${error.message})`);
357
382
  }
358
383
  }
@@ -391,125 +416,27 @@ export async function runBenchCheck(options) {
391
416
  push('NEGATIVE_CONTROLS', 'PASS', `${negativeTasks}/${labeledTasks} labeled task(s) are negative controls (${percent}%) — at or above the ${NEGATIVE_CONTROL_PERCENT}% target`);
392
417
  }
393
418
  }
394
- if (options.calibrate) {
395
- await calibrateBench(bench, options.calibrate, (status, message) => push('CALIBRATION', status, message), log);
396
- }
397
- return finish(dir, checks, log, options.calibrate !== false && options.calibrate !== undefined, identity);
398
- }
399
- const CALIBRATE_DEFAULT_TRIALS = 2;
400
- async function calibrateBench(bench, options, push, log) {
401
- if (!options.agent && !options.executor) {
402
- push('FAIL', '--calibrate needs --agent (a CLI executor for real runs)');
403
- return;
404
- }
405
- const trials = options.trials ?? CALIBRATE_DEFAULT_TRIALS;
406
- const inputMode = options.inputMode ?? 'snapshot';
407
- const capture = options.agent && getAgent(options.agent).headless.streamJson;
408
- const executor = options.executor ?? CliExecutor.forAgent(options.agent ?? '', capture ? { triggerSkillName: 'calibration-none' } : undefined);
409
- assertInputModeSupported(inputMode, executor);
410
- if (!Number.isInteger(trials) || trials < 1 || trials > 20) {
411
- throw new Error(`calibration trials must be an integer between 1 and 20, got ${trials}`);
412
- }
413
- const plannedCalls = bench.tasks.length * trials;
414
- const maxCalls = validateCallBudget(plannedCalls, options.maxCalls);
415
- if (options.dryRun) {
416
- push('INFO', `calibration executor: ${executor.describe().detail ?? executor.describe().model}`);
417
- push('INFO', `calibration plan: ${bench.tasks.length} task(s) × ${trials} baseline run(s), input ${inputMode}; ${plannedCalls} calls, ceiling ${maxCalls}; no agent started and no run directory created`);
418
- return;
419
- }
420
- const emptySkillDir = mkdtempSync(join(tmpdir(), 'skillfit-calibrate-'));
421
- let session;
422
- let failure;
423
- try {
424
- const skill = {
425
- kind: 'skill',
426
- name: 'calibration-none',
427
- sourceDir: emptySkillDir,
428
- files: [],
429
- sha256: '0'.repeat(64),
430
- payload: '',
431
- overlays: {},
432
- };
433
- const runGroup = options.runGroup ??
434
- `calibrate-${new Date().toISOString().slice(0, 10).replaceAll('-', '')}-${String(Date.now() % 100000).padStart(5, '0')}`;
435
- if (!RUN_GROUP_PATTERN.test(runGroup))
436
- throw new Error(`Invalid run group: ${runGroup}`);
437
- const runsRoot = options.runsRoot ?? resolve('runs');
438
- push('INFO', `calibration plan: ${plannedCalls} baseline calls, ceiling ${maxCalls}; fresh output ${join(runsRoot, runGroup)}`);
439
- session = new ExperimentSession({ bench, target: skill, groupDir: join(runsRoot, runGroup), plannedCalls,
440
- maxCalls, agent: options.agent, injected: options.executor !== undefined, ...options.sessionOptions,
441
- workspaces: bench.tasks.flatMap(task => Array.from({ length: trials }, (_, i) => join(runsRoot, runGroup, task.id, 'baseline', `trial-${i + 1}`))),
442
- details: { mode: 'calibration', inputMode, trials, executor: executor.describe() } });
443
- // Calibration measures inject-mode baseline difficulty, so it drives the inject path with an
444
- // empty skill payload (prompt.ts drops a falsy payload, so no skill block is injected) and runs
445
- // one arm per task. This used to route through trigger mode, whose `shouldTrigger` filter
446
- // silently calibrated zero tasks on an unlabelled bench and then reported PASS 0/0.
447
- const plan = {
448
- bench,
449
- target: skill,
450
- inputMode,
451
- executor: session.wrap(executor, 'agent'),
452
- trials,
453
- runsRoot,
454
- runGroup,
455
- log,
456
- };
457
- push('INFO', `calibration: ${trials} run(s) per task with no skill installed (baseline difficulty; input ${inputMode})`);
458
- let discriminative = 0;
459
- let tasksRun = 0;
460
- const taskResults = [];
461
- for (const task of bench.tasks) {
462
- let passes = 0;
463
- let completed = 0;
464
- let errors = 0;
465
- for (let trial = 1; trial <= trials; trial++) {
466
- const outcome = await runTrial(plan, task.id, 'baseline', trial);
467
- if (outcome.error !== null) {
468
- errors++;
469
- continue;
470
- }
471
- completed++;
472
- if (outcome.passed)
473
- passes++;
474
- }
475
- taskResults.push({ id: task.id, passes, completed, errors });
476
- if (completed === 0) {
477
- push('WARN', `${task.id}: no completed runs${errors > 0 ? ` (${errors} ungraded run(s))` : ''} — cannot assess difficulty`);
478
- continue;
479
- }
480
- tasksRun++;
481
- const rate = passes / completed;
482
- if (rate >= 0.9) {
483
- push('WARN', `${task.id}: baseline ${passes}/${completed} — too easy (saturated; cannot discriminate skill effects)`);
484
- }
485
- else if (rate <= 0.1) {
486
- push('WARN', `${task.id}: baseline ${passes}/${completed} — too hard or broken (floor)`);
487
- }
488
- else {
489
- discriminative++;
490
- push('PASS', `${task.id}: baseline ${passes}/${completed} — discriminative band`);
419
+ if (calibration) {
420
+ const offlineReport = { dir, bench: identity, checks, failures: checks.filter(check => check.status === 'FAIL').length,
421
+ warnings: checks.filter(check => check.status === 'WARN').length };
422
+ const casePreflight = calibrationCasePreflight(bench, offlineReport, Math.round(performance.now() - offlineStarted));
423
+ log(`Case preflight: ${casePreflight.status}; ${casePreflight.summary.failures} failure(s), ${casePreflight.summary.warnings} warning(s), ${casePreflight.summary.unknown} unknown(s); 0 model calls`);
424
+ for (const check of casePreflight.checks.filter(check => check.status === 'UNKNOWN'))
425
+ log(`[UNKNOWN] ${check.code}: ${check.message}`);
426
+ if (casePreflight.status === 'blocked') {
427
+ if (strictCalibration) {
428
+ const { CasePreflightFailed } = await import('./eval-preflight.js');
429
+ throw new CasePreflightFailed(casePreflight);
491
430
  }
431
+ push('CALIBRATION', 'FAIL', 'Offline case preflight blocked calibration; no agent calls or run directory were created. Fix every hard failure before a fresh plan.');
432
+ for (const check of casePreflight.checks.filter(check => check.code === 'INPUT_CHANGED'))
433
+ push('CALIBRATION', 'FAIL', check.message);
492
434
  }
493
- session.settle();
494
- const result = { schemaVersion: 1, runGroup, inputMode, trials, tasks: taskResults, experiment: session.summary() };
495
- writeFileSync(join(session.groupDir, '_calibration.json'), JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });
496
- session.finish(undefined, result, '_calibration.json');
497
- if (session.summary().status !== 'completed')
498
- push('FAIL', 'Calibration stopped or incomplete; inspect _session.json and _calls.jsonl before a fresh plan.');
499
- if (tasksRun === 0) {
500
- push('FAIL', `calibration ran 0 task(s): difficulty unmeasured (runs under ${runGroup})`);
501
- return;
435
+ else {
436
+ await executeCalibration(calibration, casePreflight, (status, message) => push('CALIBRATION', status, message), log);
502
437
  }
503
- push(discriminative === tasksRun ? 'PASS' : 'INFO', `calibration: ${discriminative}/${tasksRun} task(s) in the discriminative band (runs under ${runGroup}; use --trials 3+ for steadier reads)`);
504
- }
505
- catch (error) {
506
- failure = error;
507
- throw error;
508
- }
509
- finally {
510
- session?.finish(failure);
511
- rmSync(emptySkillDir, { recursive: true, force: true });
512
438
  }
439
+ return finish(dir, checks, log, options.calibrate !== false && options.calibrate !== undefined, identity);
513
440
  }
514
441
  function finish(dir, checks, log, calibrated = false, bench = null) {
515
442
  const failures = checks.filter((c) => c.status === 'FAIL').length;
@@ -549,11 +476,12 @@ function scrubbedEnv() {
549
476
  const result = spawnSync(${JSON.stringify(cmd)}, { cwd: runDir, shell: true, encoding: 'utf8', env: scrubbedEnv() });
550
477
  if (result.stdout) process.stdout.write(result.stdout);
551
478
  if (result.stderr) process.stderr.write(result.stderr);
552
- if (result.error) {
553
- console.error(String(result.error));
554
- process.exit(1);
479
+ if (result.error || result.signal || result.status === null) {
480
+ console.log(JSON.stringify({ schemaVersion: 1, kind: 'skillfit.verifier-error',
481
+ message: result.error ? String(result.error) : 'Verifier command ended without a verdict: ' + (result.signal ?? 'no exit code') }));
482
+ process.exit(2);
555
483
  }
556
- process.exit(result.status ?? 1);
484
+ process.exit(result.status);
557
485
  `;
558
486
  }
559
487
  function verifierForExpect(needle) {
@@ -645,7 +573,7 @@ async function draftVerifierWithOracle(options, prepared, log) {
645
573
  try {
646
574
  copyFixture(fixtureDir, nopDir);
647
575
  const nop = await runVerifier(staging, 'node verifier.mjs', nopDir);
648
- if (nop.exitCode === null) {
576
+ if (nop.error !== null || nop.exitCode === null) {
649
577
  throw new Error(`draft rejected: ${verifierFailure('verifier', 'node verifier.mjs', nop.error)}`);
650
578
  }
651
579
  if (nop.exitCode === 0) {
@@ -0,0 +1,145 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { test } from 'node:test';
8
+ import { runBenchInit } from './bench.js';
9
+ const CLI = fileURLToPath(new URL('../cli.js', import.meta.url));
10
+ const budget = { input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 60 };
11
+ async function fixture(t) {
12
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-calibration-cli-')), dir = join(root, 'bench with spaces');
13
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
14
+ await runBenchInit({ dir, kind: 'command', yes: true, log: () => { } });
15
+ const home = join(root, 'home'), sentinel = join(root, 'unexpected-probe'), budgetPath = join(root, 'budget.json');
16
+ mkdirSync(home);
17
+ writeFileSync(budgetPath, JSON.stringify(budget));
18
+ const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'PATH')),
19
+ PATH: '', HOME: home, USERPROFILE: home, CODEX_HOME: join(home, 'codex') };
20
+ const manifest = JSON.parse(readFileSync(join(dir, 'bench.json'), 'utf8'));
21
+ manifest.tasks.push({ ...manifest.tasks[0], id: 'second-task' });
22
+ writeFileSync(join(dir, 'bench.json'), JSON.stringify(manifest));
23
+ writeFileSync(join(dir, 'verifiers/example-task.mjs'), `import{writeFileSync}from'node:fs';writeFileSync(${JSON.stringify(sentinel)},'must never run');process.exit(1);`);
24
+ const args = ['bench', 'check', dir, '--calibrate', '--json', '--agent', 'codex', '--run-group', 'reviewed', '--runs-root', join(root, 'results')];
25
+ const cli = (extra, status, base = args) => {
26
+ const result = spawnSync(process.execPath, [CLI, ...base, ...extra], { cwd: root, env, encoding: 'utf8', timeout: 20_000 });
27
+ assert.equal(result.status, status, result.stderr || result.stdout);
28
+ const data = JSON.parse(result.stdout);
29
+ assert.equal(data.schemaVersion, 1);
30
+ assert.ok(!existsSync(sentinel), 'plans and rejected executions must not run even the verifier');
31
+ assert.ok(!existsSync(join(root, 'runs')));
32
+ assert.ok(!existsSync(join(root, 'results')));
33
+ return { data, stderr: result.stderr };
34
+ };
35
+ return { root, dir, sentinel, budgetPath, args, cli, env };
36
+ }
37
+ test('public calibration JSON preview is read-only and retains blocked CLI, capabilities, unknown login and effective settings', async (t) => {
38
+ const f = await fixture(t);
39
+ const settings = ['--dry-run', '--trials', '3', '--max-calls', '3', '--task', 'second-task', '--input', 'workspace',
40
+ '--executor-timeout-seconds', '13', '--spending-budget', f.budgetPath];
41
+ const first = f.cli(settings, 0), plan = first.data.plan;
42
+ assert.equal(first.stderr, '');
43
+ assert.equal(first.data.kind, 'skillfit.calibration-result');
44
+ assert.equal(first.data.status, 'planned');
45
+ assert.equal(plan.kind, 'skillfit.calibration-plan');
46
+ assert.match(plan.planSha256, /^[0-9a-f]{64}$/);
47
+ assert.match(plan.implementationSha256, /^[0-9a-f]{64}$/);
48
+ assert.match(plan.bench.sha256, /^[0-9a-f]{64}$/);
49
+ assert.deepEqual(plan.bench.taskIds, ['second-task']);
50
+ assert.equal(plan.trials, 3);
51
+ assert.equal(plan.plannedCalls, 3);
52
+ assert.equal(plan.maxCalls, 3);
53
+ assert.equal(plan.executorTimeoutSeconds, 13);
54
+ assert.equal(plan.inputMode, 'workspace');
55
+ assert.deepEqual(plan.spendingBudget, budget);
56
+ assert.equal(plan.outputDir, join(f.root, 'results/reviewed'));
57
+ assert.equal(plan.casePreflight.status, 'pending');
58
+ assert.equal(plan.agentPreflight.status, 'blocked');
59
+ assert.ok(plan.agentPreflight.checks.some((check) => check.code === 'CLI_AVAILABLE' && check.status === 'FAIL'));
60
+ assert.ok(plan.agentPreflight.checks.some((check) => check.code === 'MATRIX_CAPABILITY' && check.status === 'PASS'));
61
+ assert.ok(plan.agentPreflight.checks.some((check) => check.code === 'AUTHENTICATION' && check.status === 'UNKNOWN'));
62
+ assert.equal(plan.agentPreflight.cost.modelCalls, 0);
63
+ assert.equal(plan.agentPreflight.cost.cliInvocations, 0);
64
+ assert.equal(first.data.acceptance.automaticUpgrade, false);
65
+ assert.equal(first.data.acceptance.eligibleForUpgrade, false);
66
+ assert.deepEqual(f.cli(settings, 0).data, first.data, 'identical effective settings yield a reproducible plan');
67
+ });
68
+ test('JSON calibration execution requires a current plan and its explicit output group before any call', async (t) => {
69
+ const f = await fixture(t);
70
+ assert.match(f.cli([], 2).data.error.message, /requires --plan-sha/);
71
+ const withoutGroup = f.args.filter((_, index, values) => values[index - 1] !== '--run-group' && values[index] !== '--run-group');
72
+ assert.match(f.cli(['--plan-sha', '0'.repeat(64)], 2, withoutGroup).data.error.message, /requires --run-group/);
73
+ assert.match(f.cli(['--plan-sha', '0'.repeat(64)], 2).data.error.message, /plan changed/);
74
+ assert.match(f.cli(['--dry-run', '--plan-sha', '0'.repeat(64)], 2).data.error.message, /non-dry-run/);
75
+ const preview = f.cli(['--dry-run'], 0).data;
76
+ const live = f.cli(['--plan-sha', preview.plan.planSha256], 2);
77
+ assert.equal(live.data.kind, 'skillfit.eval-error');
78
+ assert.equal(live.data.error.code, 'AGENT_PREFLIGHT_FAILED');
79
+ assert.equal(live.data.agentPreflight.status, 'blocked');
80
+ assert.match(live.data.error.message, /CLI executable is missing/);
81
+ assert.doesNotMatch(live.data.error.message, /ENOENT|no such file or directory/i);
82
+ });
83
+ test('changing a calibration bench, spending lines, task set or executor deadline invalidates its reviewed plan', async (t) => {
84
+ for (const change of ['bench', 'budget', 'tasks', 'timeout'])
85
+ await t.test(change, async (t) => {
86
+ const f = await fixture(t), settings = ['--spending-budget', f.budgetPath];
87
+ const preview = f.cli(['--dry-run', ...settings], 0).data;
88
+ let altered = [];
89
+ if (change === 'bench')
90
+ writeFileSync(join(f.dir, 'prompts/example-task.md'), 'A new task.');
91
+ if (change === 'budget')
92
+ writeFileSync(f.budgetPath, JSON.stringify({ ...budget, input: 101 }));
93
+ if (change === 'tasks')
94
+ altered = ['--task', 'second-task'];
95
+ if (change === 'timeout')
96
+ altered = ['--executor-timeout-seconds', '12'];
97
+ const live = f.cli([...settings, ...altered, '--plan-sha', preview.plan.planSha256], 2).data;
98
+ assert.equal(live.kind, 'skillfit.eval-error');
99
+ assert.equal(live.status, 'error');
100
+ assert.equal(live.acceptance.eligibleForUpgrade, false);
101
+ assert.match(live.error.message, /plan changed/);
102
+ });
103
+ });
104
+ test('invalid calibration task selection, budgets, timeout, output and paired-only settings fail before probes', async (t) => {
105
+ const f = await fixture(t), invalidBudget = join(f.root, 'bad-budget.json');
106
+ writeFileSync(invalidBudget, JSON.stringify({ ...budget, input: 0 }));
107
+ const malformedBudget = join(f.root, 'malformed-budget.json');
108
+ writeFileSync(malformedBudget, '{');
109
+ const cases = [
110
+ [['--task', 'missing'], /Unknown task/],
111
+ [['--task', 'second-task', '--task', 'second-task'], /Duplicate task/],
112
+ [['--max-calls', '1'], /exceeding --max-calls/],
113
+ [['--executor-timeout-seconds', '0'], /executorTimeoutSeconds/],
114
+ [['--executor-timeout-seconds', '3601'], /executorTimeoutSeconds/],
115
+ [['--executor-timeout-seconds', '1.5'], /executorTimeoutSeconds/],
116
+ [['--spending-budget', invalidBudget], /spendingBudget.input/],
117
+ [['--spending-budget', malformedBudget], /JSON/],
118
+ [['--pair-order', 'balanced'], /requires a paired eval/],
119
+ [['--run-group', '../outside'], /Invalid run group/],
120
+ ];
121
+ for (const [extra, message] of cases) {
122
+ const data = f.cli(['--dry-run', ...extra], 2).data;
123
+ assert.equal(data.kind, 'skillfit.eval-error');
124
+ assert.match(data.error.message, message);
125
+ }
126
+ });
127
+ test('ordinary offline bench JSON retains its own integrity contract while calibration JSON returns a plan', async (t) => {
128
+ const f = await fixture(t);
129
+ const ordinary = spawnSync(process.execPath, [CLI, 'bench', 'check', f.dir, '--json'], { cwd: f.root, env: f.env, encoding: 'utf8', timeout: 20_000 });
130
+ // PATH is deliberately empty, so Node verifier commands cannot start; that is an offline
131
+ // integrity failure, distinct from a paid calibration or a model outcome.
132
+ assert.equal(ordinary.status, 1, ordinary.stderr || ordinary.stdout);
133
+ assert.equal(ordinary.stderr, '');
134
+ const data = JSON.parse(ordinary.stdout);
135
+ assert.equal(data.kind, 'skillfit.bench-check');
136
+ assert.equal(data.scope, 'offline-integrity');
137
+ assert.equal(data.status, 'failed');
138
+ assert.ok(data.summary.failures > 0);
139
+ assert.equal(data.plan, undefined);
140
+ assert.ok(!existsSync(f.sentinel));
141
+ const preview = f.cli(['--dry-run'], 0).data;
142
+ assert.equal(preview.kind, 'skillfit.calibration-result');
143
+ assert.equal(preview.status, 'planned');
144
+ assert.ok(preview.plan);
145
+ });