skillfit 0.11.0 → 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 (61) hide show
  1. package/README.md +28 -5
  2. package/README.zh-CN.md +28 -5
  3. package/benches/README.md +6 -2
  4. package/dist/cli.js +28 -16
  5. package/dist/commands/bench-calibration.js +5 -1
  6. package/dist/commands/bench-draft.js +167 -0
  7. package/dist/commands/bench-draft.test.js +168 -0
  8. package/dist/commands/bench-manage.js +5 -4
  9. package/dist/commands/bench-source.js +101 -0
  10. package/dist/commands/bench-source.test.js +84 -0
  11. package/dist/commands/bench.js +165 -103
  12. package/dist/commands/bench.test.js +7 -3
  13. package/dist/commands/eval-agent-preflight.test.js +24 -0
  14. package/dist/commands/eval-api-failure.test.js +46 -0
  15. package/dist/commands/eval-cli-usage.test.js +75 -0
  16. package/dist/commands/eval-interruption.test.js +26 -1
  17. package/dist/commands/eval-layout.test.js +126 -0
  18. package/dist/commands/eval.js +7 -32
  19. package/dist/commands/npm-first-run.test.js +74 -0
  20. package/dist/harness/agent-preflight.js +18 -2
  21. package/dist/harness/bench-location.js +29 -0
  22. package/dist/harness/bench-location.test.js +33 -0
  23. package/dist/harness/bench.js +8 -3
  24. package/dist/harness/eval-audit.js +1 -1
  25. package/dist/harness/evaluation-layout.js +30 -0
  26. package/dist/harness/executors/api.js +20 -7
  27. package/dist/harness/executors/api.test.js +39 -0
  28. package/dist/harness/executors/cli.js +15 -25
  29. package/dist/harness/executors/cli.test.js +33 -2
  30. package/dist/harness/experiment-session.js +5 -15
  31. package/dist/harness/hash.js +3 -1
  32. package/dist/harness/runner.js +5 -4
  33. package/dist/harness/single-arm-audit.js +1 -1
  34. package/dist/harness/trigger.js +1 -1
  35. package/dist/harness/verifier-timeout.js +8 -0
  36. package/dist/harness/verifier-timeout.test.js +76 -0
  37. package/docs/bench-authoring.md +23 -3
  38. package/docs/bench-drafting.md +75 -0
  39. package/docs/case-management.md +12 -1
  40. package/docs/eval-agent-preflight.md +15 -2
  41. package/docs/eval-costs.md +28 -2
  42. package/docs/eval-planning.md +14 -0
  43. package/docs/evaluation-input-snapshots.md +20 -4
  44. package/docs/first-real-eval.md +28 -3
  45. package/docs/growth-roadmap-2026-10.md +23 -14
  46. package/docs/plans/2026-10-17-workflow-foundations.md +37 -2
  47. package/docs/releases/0.11.0-ci-registry-install.json +130 -0
  48. package/docs/releases/0.11.0-feature-smoke.json +1576 -0
  49. package/docs/releases/0.11.0-local-attempt-1.json +24 -0
  50. package/docs/releases/0.11.0-local-attempt-1.log +19 -0
  51. package/docs/releases/0.11.0-local-registry-install.json +25 -0
  52. package/docs/releases/0.11.0-registry-metadata.json +33 -0
  53. package/docs/releases/0.11.0-signatures.txt +12 -0
  54. package/docs/releases/0.11.0-verification.json +95 -0
  55. package/docs/releases/0.11.0.md +54 -11
  56. package/docs/releases/0.12.0-feature-smoke.mjs +73 -0
  57. package/docs/releases/0.12.0.md +68 -0
  58. package/docs/schemas/agent-preflight.schema.json +1 -1
  59. package/docs/verifier-contract.md +9 -0
  60. package/package.json +1 -1
  61. package/skills/skillfit/SKILL.md +25 -5
@@ -2,9 +2,9 @@ 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 { loadBench, selectBenchTasks } from '../harness/bench.js';
6
- import { CliExecutor } from '../harness/executors/cli.js';
7
- import { listFilesRecursive } from '../harness/hash.js';
5
+ import { BENCH_SCHEMA_VERSION, loadBench, selectBenchTasks, validateBenchTask } from '../harness/bench.js';
6
+ import { resolveBenchDir } from '../harness/bench-location.js';
7
+ import { listFilesRecursive, sha256File, sha256Text } from '../harness/hash.js';
8
8
  import { runVerifier, verifierFailure } from '../harness/runner.js';
9
9
  import { MOCK_MARKER_FILE } from '../harness/constants.js';
10
10
  import { verdictFromOutput } from '../harness/verifier-summary.js';
@@ -15,6 +15,10 @@ import { BACKUP_SUFFIX } from './install.js';
15
15
  import { withEvaluationInterrupts, throwIfEvaluationInterrupted } from '../harness/interruption.js';
16
16
  import { assertAgentEnvironment, renderAgentEnvironment } from '../harness/agent-preflight.js';
17
17
  import { calibrationCasePreflight, executeCalibration, prepareCalibration } from './bench-calibration.js';
18
+ import { freezeSourceFiles } from './bench-source.js';
19
+ import { BenchDraftSession } from './bench-draft.js';
20
+ import { parseVerifierTimeoutSeconds } from '../harness/verifier-timeout.js';
21
+ export { captureSourceFiles } from './bench-source.js';
18
22
  export { prepareBenchCalibration } from './bench-calibration.js';
19
23
  const FIXTURE_SIZE_WARN_BYTES = 64 * 1024;
20
24
  // benches/README.md: a verifier decomposes its acceptance criteria into 2–8 named checks.
@@ -142,13 +146,13 @@ export async function runBenchInit(options) {
142
146
  log('This is a teaching case. Replace it with your own task before measuring Skill benefit.');
143
147
  return { dir, created };
144
148
  }
145
- async function probeVerifier(benchDir, verifier, output) {
149
+ async function probeVerifier(benchDir, verifier, output, timeoutSeconds) {
146
150
  const dir = mkdtempSync(join(tmpdir(), 'skillfit-check-'));
147
151
  try {
148
152
  if (output !== null) {
149
153
  writeFileSync(join(dir, '_output.md'), output, 'utf8');
150
154
  }
151
- const result = await runVerifier(benchDir, verifier, dir);
155
+ const result = await runVerifier(benchDir, verifier, dir, timeoutSeconds);
152
156
  return {
153
157
  exitCode: result.exitCode,
154
158
  error: result.error,
@@ -185,11 +189,12 @@ function copyFixture(fixtureDir, dest) {
185
189
  writeFileSync(target, readFileSync(join(fixtureDir, rel)));
186
190
  }
187
191
  }
188
- async function runOracleGate(benchDir, fixtureDir, oracle, verifier) {
192
+ async function runOracleGate(benchDir, fixtureDir, oracle, verifier, timeoutSeconds, record) {
189
193
  const dir = mkdtempSync(join(tmpdir(), 'skillfit-check-'));
190
194
  try {
191
195
  copyFixture(fixtureDir, dir);
192
- const oracleRun = await runVerifier(benchDir, oracle, dir);
196
+ const oracleRun = await runVerifier(benchDir, oracle, dir, timeoutSeconds);
197
+ record?.('oracle', oracleRun);
193
198
  if (oracleRun.error !== null || oracleRun.exitCode !== 0) {
194
199
  return {
195
200
  kind: 'oracle-failed',
@@ -199,7 +204,8 @@ async function runOracleGate(benchDir, fixtureDir, oracle, verifier) {
199
204
  reason: oracleRun.error !== null || oracleRun.exitCode === null ? verifierFailure('oracle', oracle, oracleRun.error) : null,
200
205
  };
201
206
  }
202
- const graded = await runVerifier(benchDir, verifier, dir);
207
+ const graded = await runVerifier(benchDir, verifier, dir, timeoutSeconds);
208
+ record?.('oracle-verifier', graded);
203
209
  if (graded.error !== null || graded.exitCode !== 0) {
204
210
  return {
205
211
  kind: 'verifier-failed',
@@ -218,8 +224,8 @@ async function runOracleGate(benchDir, fixtureDir, oracle, verifier) {
218
224
  rmSync(dir, { recursive: true, force: true });
219
225
  }
220
226
  }
221
- async function probeOracle(benchDir, fixture, oracle, verifier) {
222
- const gate = await runOracleGate(benchDir, join(benchDir, fixture), oracle, verifier);
227
+ async function probeOracle(benchDir, fixture, oracle, verifier, timeoutSeconds) {
228
+ const gate = await runOracleGate(benchDir, join(benchDir, fixture), oracle, verifier, timeoutSeconds);
223
229
  switch (gate.kind) {
224
230
  case 'oracle-failed':
225
231
  return {
@@ -259,7 +265,7 @@ export async function runBenchCalibration(options) {
259
265
  }
260
266
  async function runBenchCheckWithinInterrupts(options, strictCalibration = false) {
261
267
  const log = options.log ?? ((msg) => console.log(msg));
262
- const dir = resolve(options.dir ?? '.');
268
+ let dir = resolve(options.dir ?? '.');
263
269
  const checks = [];
264
270
  let identity = null;
265
271
  const push = (code, status, message, task, evidence) => {
@@ -269,6 +275,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
269
275
  };
270
276
  let bench;
271
277
  try {
278
+ dir = resolveBenchDir(options.dir ?? '.');
272
279
  bench = selectBenchTasks(loadBench(dir), options.taskIds ?? (options.calibrate ? options.calibrate.taskIds : undefined));
273
280
  }
274
281
  catch (error) {
@@ -306,7 +313,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
306
313
  const fixtureCopy = mkdtempSync(join(tmpdir(), 'skillfit-check-'));
307
314
  try {
308
315
  copyFixture(join(bench.dir, task.fixture), fixtureCopy);
309
- const pristine = await runVerifier(bench.dir, task.verifier, fixtureCopy);
316
+ const pristine = await runVerifier(bench.dir, task.verifier, fixtureCopy, task.verifierTimeoutSeconds);
310
317
  facetChecks = verdictFromOutput(pristine.output)?.checks ?? null;
311
318
  if (pristine.error !== null || pristine.exitCode === null) {
312
319
  // Without this branch a verifier that cannot even be spawned reads as a clean NOP gate:
@@ -325,7 +332,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
325
332
  }
326
333
  }
327
334
  else {
328
- const missing = await probeVerifier(bench.dir, task.verifier, null);
335
+ const missing = await probeVerifier(bench.dir, task.verifier, null, task.verifierTimeoutSeconds);
329
336
  if (missing.error !== null || missing.exitCode === null) {
330
337
  taskPush('MISSING_OUTPUT', 'FAIL', `${task.id}: ${verifierFailure('verifier', task.verifier, missing.error)}`, benchCheckEvidence(missing, task.verifier));
331
338
  }
@@ -335,7 +342,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
335
342
  else {
336
343
  taskPush('MISSING_OUTPUT', 'PASS', `${task.id}: verifier rejects missing output`, benchCheckEvidence(missing, task.verifier));
337
344
  }
338
- const empty = await probeVerifier(bench.dir, task.verifier, '');
345
+ const empty = await probeVerifier(bench.dir, task.verifier, '', task.verifierTimeoutSeconds);
339
346
  facetChecks = empty.checks;
340
347
  if (empty.error !== null || empty.exitCode === null) {
341
348
  taskPush('EMPTY_OUTPUT', 'FAIL', `${task.id}: ${verifierFailure('verifier', task.verifier, empty.error)}`, benchCheckEvidence(empty, task.verifier));
@@ -351,7 +358,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
351
358
  if (facetGate)
352
359
  taskPush('FACET_COUNT', facetGate.status, facetGate.message);
353
360
  if (task.oracle) {
354
- const oracleResult = await probeOracle(bench.dir, task.fixture, task.oracle, task.verifier);
361
+ const oracleResult = await probeOracle(bench.dir, task.fixture, task.oracle, task.verifier, task.verifierTimeoutSeconds);
355
362
  taskPush('ORACLE', oracleResult.status, `${task.id}: ${oracleResult.message}`, oracleResult.evidence);
356
363
  }
357
364
  else {
@@ -372,7 +379,7 @@ async function runBenchCheckWithinInterrupts(options, strictCalibration = false)
372
379
  taskPush(arm === 'baseline' ? 'MOCK_BASELINE' : 'MOCK_TREATMENT', 'INFO', `${task.id}: no mock ${arm} output — this arm was not probed`);
373
380
  continue;
374
381
  }
375
- const probe = await probeVerifier(bench.dir, task.verifier, behavior.output);
382
+ const probe = await probeVerifier(bench.dir, task.verifier, behavior.output, task.verifierTimeoutSeconds);
376
383
  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));
377
384
  }
378
385
  }
@@ -452,13 +459,6 @@ function finish(dir, checks, log, calibrated = false, bench = null) {
452
459
  return { dir, bench, checks, failures, warnings };
453
460
  }
454
461
  const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
455
- export function captureSourceFiles(sourceDir) {
456
- const git = spawnSync('git', ['ls-files', '-z'], { cwd: sourceDir, encoding: 'utf8' });
457
- if (git.status === 0 && git.stdout.trim() !== '') {
458
- return git.stdout.split('\0').filter(Boolean);
459
- }
460
- return listFilesRecursive(sourceDir).filter((rel) => !rel.split(/[\\/]/).some((part) => part === '.git' || part === 'node_modules'));
461
- }
462
462
  function verifierForCmd(cmd) {
463
463
  return `import { spawnSync } from 'node:child_process';
464
464
 
@@ -549,58 +549,45 @@ Node built-ins. Your draft is validated automatically: the verifier must fail th
549
549
  fixture and pass the oracle-solved one, so test both directions before you finish.
550
550
  `;
551
551
  }
552
- async function draftVerifierWithOracle(options, prepared, log) {
553
- const executor = options.executor ?? (options.agent ? CliExecutor.forAgent(options.agent) : undefined);
554
- if (!executor) {
555
- throw new Error('bench add --decompose needs an agent to draft with: --agent <id>.');
552
+ async function draftVerifierWithOracle(session, log) {
553
+ const staging = session.workspace;
554
+ const fixtureDir = join(staging, 'fixture');
555
+ log(`Drafting verifier + oracle; at most 1 call. Records: ${session.dir}`);
556
+ await session.run();
557
+ const verifierPath = join(staging, 'verifier.mjs');
558
+ const oraclePath = join(staging, 'oracle.mjs');
559
+ if (!existsSync(verifierPath) || !existsSync(oraclePath)) {
560
+ throw new Error('the drafting agent did not write verifier.mjs and oracle.mjs into its working directory — nothing was added');
556
561
  }
557
- const staging = mkdtempSync(join(tmpdir(), 'skillfit-decompose-'));
562
+ const nopDir = mkdtempSync(join(tmpdir(), 'skillfit-decompose-nop-'));
558
563
  try {
559
- const fixtureDir = join(staging, 'fixture');
560
- for (const file of prepared.fixtureFiles) {
561
- const target = join(fixtureDir, file.rel);
562
- mkdirSync(dirname(target), { recursive: true });
563
- writeFileSync(target, file.content);
564
- }
565
- log(`Drafting verifier + oracle with ${executor.describe().kind} (${executor.describe().model})…`);
566
- await executor.run(buildDecomposePrompt(prepared.promptText, prepared.fixtureFiles.map((f) => f.rel), prepared.verifierKind), staging);
567
- const verifierPath = join(staging, 'verifier.mjs');
568
- const oraclePath = join(staging, 'oracle.mjs');
569
- if (!existsSync(verifierPath) || !existsSync(oraclePath)) {
570
- throw new Error('the drafting agent did not write verifier.mjs and oracle.mjs into its working directory — nothing was added');
571
- }
572
- const nopDir = mkdtempSync(join(tmpdir(), 'skillfit-decompose-nop-'));
573
- try {
574
- copyFixture(fixtureDir, nopDir);
575
- const nop = await runVerifier(staging, 'node verifier.mjs', nopDir);
576
- if (nop.error !== null || nop.exitCode === null) {
577
- throw new Error(`draft rejected: ${verifierFailure('verifier', 'node verifier.mjs', nop.error)}`);
578
- }
579
- if (nop.exitCode === 0) {
580
- throw new Error('draft rejected: the verifier passes the untouched fixture — the task would start solved (NOP gate)');
581
- }
582
- }
583
- finally {
584
- rmSync(nopDir, { recursive: true, force: true });
564
+ copyFixture(fixtureDir, nopDir);
565
+ const nop = await runVerifier(staging, 'node verifier.mjs', nopDir, session.plan.verifierTimeoutSeconds);
566
+ session.gate('untouched-fixture', nop);
567
+ if (nop.error !== null || nop.exitCode === null) {
568
+ throw new Error(`draft rejected: ${verifierFailure('verifier', 'node verifier.mjs', nop.error)}`);
585
569
  }
586
- const solvedGate = await runOracleGate(staging, fixtureDir, 'node oracle.mjs', 'node verifier.mjs');
587
- if (solvedGate.kind === 'oracle-failed') {
588
- throw new Error(`draft rejected: ${solvedGate.reason ?? 'the oracle command failed on a fresh fixture copy'}`);
570
+ if (nop.exitCode === 0) {
571
+ throw new Error('draft rejected: the verifier passes the untouched fixture — the task would start solved (NOP gate)');
589
572
  }
590
- if (solvedGate.kind === 'verifier-failed') {
591
- throw new Error(`draft rejected: ${solvedGate.reason ?? 'the verifier fails even after the oracle solved the task (oracle gate)'}`);
592
- }
593
- if (solvedGate.kind === 'low-score') {
594
- throw new Error(`draft rejected: the oracle scores ${solvedGate.score.toFixed(2)} on the drafted checks — checks are stricter than the oracle`);
595
- }
596
- return {
597
- verifierSource: readFileSync(verifierPath, 'utf8'),
598
- oracleSource: readFileSync(oraclePath, 'utf8'),
599
- };
600
573
  }
601
574
  finally {
602
- rmSync(staging, { recursive: true, force: true });
575
+ rmSync(nopDir, { recursive: true, force: true });
576
+ }
577
+ const solvedGate = await runOracleGate(staging, fixtureDir, 'node oracle.mjs', 'node verifier.mjs', session.plan.verifierTimeoutSeconds, (name, result) => session.gate(name, result));
578
+ if (solvedGate.kind === 'oracle-failed') {
579
+ throw new Error(`draft rejected: ${solvedGate.reason ?? 'the oracle command failed on a fresh fixture copy'}`);
580
+ }
581
+ if (solvedGate.kind === 'verifier-failed') {
582
+ throw new Error(`draft rejected: ${solvedGate.reason ?? 'the verifier fails even after the oracle solved the task (oracle gate)'}`);
603
583
  }
584
+ if (solvedGate.kind === 'low-score') {
585
+ throw new Error(`draft rejected: the oracle scores ${solvedGate.score.toFixed(2)} on the drafted checks — checks are stricter than the oracle`);
586
+ }
587
+ return {
588
+ verifierSource: readFileSync(verifierPath, 'utf8'),
589
+ oracleSource: readFileSync(oraclePath, 'utf8'),
590
+ };
604
591
  }
605
592
  function assertInsideBench(benchDir, target) {
606
593
  const rel = relative(benchDir, target);
@@ -608,7 +595,38 @@ function assertInsideBench(benchDir, target) {
608
595
  throw new Error(`Refusing to write outside the bench directory: ${target}`);
609
596
  }
610
597
  }
598
+ function assertBenchWrites(benchDir, targets) {
599
+ for (const target of targets) {
600
+ assertInsideBench(benchDir, target);
601
+ const parts = relative(benchDir, target).split(/[\\/]/);
602
+ let path = benchDir;
603
+ for (let index = 0; index < parts.length; index++) {
604
+ path = join(path, parts[index]);
605
+ try {
606
+ const stat = lstatSync(path);
607
+ if (stat.isSymbolicLink())
608
+ throw new Error(`Refusing a symlink in bench output: ${path}`);
609
+ if (index < parts.length - 1 ? !stat.isDirectory() : !stat.isFile())
610
+ throw new Error(`Refusing to overwrite a non-file or traverse a non-directory: ${path}`);
611
+ }
612
+ catch (error) {
613
+ if (error.code !== 'ENOENT')
614
+ throw error;
615
+ }
616
+ }
617
+ try {
618
+ const stat = lstatSync(target + BACKUP_SUFFIX);
619
+ if (stat.isSymbolicLink() || !stat.isFile())
620
+ throw new Error(`Refusing an unsafe backup target: ${target + BACKUP_SUFFIX}`);
621
+ }
622
+ catch (error) {
623
+ if (error.code !== 'ENOENT')
624
+ throw error;
625
+ }
626
+ }
627
+ }
611
628
  export function applyBenchWrites(benchDir, writes) {
629
+ assertBenchWrites(benchDir, writes.map(write => write.target));
612
630
  const applied = [];
613
631
  try {
614
632
  for (const write of writes) {
@@ -657,7 +675,11 @@ export function applyBenchWrites(benchDir, writes) {
657
675
  }
658
676
  }
659
677
  export async function runBenchAdd(options) {
678
+ return options.dryRun ? runBenchAddWithinInterrupts(options) : withEvaluationInterrupts(() => runBenchAddWithinInterrupts(options));
679
+ }
680
+ async function runBenchAddWithinInterrupts(options) {
660
681
  const log = options.log ?? ((msg) => console.log(msg));
682
+ const timeout = options.verifierTimeoutSeconds === undefined ? {} : { verifierTimeoutSeconds: parseVerifierTimeoutSeconds(options.verifierTimeoutSeconds) };
661
683
  if (!options.freeze && !options.fromCommit) {
662
684
  throw new Error('bench add needs an importer: --freeze (current directory) or --from-commit <sha> (git history).');
663
685
  }
@@ -679,8 +701,15 @@ export async function runBenchAdd(options) {
679
701
  if (!existsSync(benchJsonPath)) {
680
702
  throw new Error(`Not a bench directory (missing bench.json): ${benchDir} — run \`skillfit bench init\` first.`);
681
703
  }
682
- const benchJson = JSON.parse(readFileSync(benchJsonPath, 'utf8'));
704
+ const originalManifest = readFileSync(benchJsonPath, 'utf8');
705
+ const benchJson = JSON.parse(originalManifest);
683
706
  const tasks = Array.isArray(benchJson.tasks) ? benchJson.tasks : [];
707
+ if (benchJson.schemaVersion !== BENCH_SCHEMA_VERSION || !Array.isArray(benchJson.tasks))
708
+ throw new Error('Invalid bench.json schema or task list; fix the bench before adding a task.');
709
+ for (const [index, task] of tasks.entries())
710
+ validateBenchTask(benchDir, task, index);
711
+ if (new Set(tasks.map(task => task.id)).size !== tasks.length)
712
+ throw new Error('Duplicate task IDs in bench.json; fix the bench before adding a task.');
684
713
  const prepared = options.fromCommit
685
714
  ? prepareFromCommit(options, cwd)
686
715
  : prepareFreeze(options, cwd);
@@ -691,19 +720,15 @@ export async function runBenchAdd(options) {
691
720
  if (tasks.some((task) => task?.id === taskId)) {
692
721
  throw new Error(`Task "${taskId}" already exists in ${benchJsonPath}.`);
693
722
  }
694
- if (options.decompose && !options.dryRun) {
695
- const drafted = await draftVerifierWithOracle(options, prepared, log);
696
- prepared.verifierSource = drafted.verifierSource;
697
- prepared.oracleSource = drafted.oracleSource;
698
- }
723
+ const draft = options.decompose ? new BenchDraftSession(options, taskId, benchDir, cwd, prepared.fixtureFiles, buildDecomposePrompt(prepared.promptText, prepared.fixtureFiles.map(file => file.rel), prepared.verifierKind)) : undefined;
699
724
  const generated = {
700
725
  [`prompts/${taskId}.md`]: `${prepared.promptText.trimEnd()}\n`,
701
726
  [`prompts/${taskId}.trigger.md`]: `${prepared.promptText.trimEnd()}\n\nThe repository is in your current working directory.\n`,
702
727
  [`verifiers/${taskId}.mjs`]: prepared.verifierSource,
703
728
  [`ground-truth/${taskId}.md`]: prepared.groundTruth,
704
729
  };
705
- if (prepared.oracleSource) {
706
- generated[`ground-truth/oracle-${taskId}.mjs`] = prepared.oracleSource;
730
+ if (prepared.oracleSource || options.decompose) {
731
+ generated[`ground-truth/oracle-${taskId}.mjs`] = prepared.oracleSource ?? '';
707
732
  }
708
733
  const taskEntry = {
709
734
  id: taskId,
@@ -712,11 +737,29 @@ export async function runBenchAdd(options) {
712
737
  promptTrigger: `prompts/${taskId}.trigger.md`,
713
738
  verifier: `node verifiers/${taskId}.mjs`,
714
739
  verifierKind: prepared.verifierKind,
740
+ ...timeout,
715
741
  rubric: `ground-truth/${taskId}.md`,
716
- ...(prepared.oracleSource ? { oracle: `node ground-truth/oracle-${taskId}.mjs` } : {}),
742
+ ...(prepared.oracleSource || options.decompose ? { oracle: `node ground-truth/oracle-${taskId}.mjs` } : {}),
717
743
  ...(options.oracle ? { oracle: options.oracle } : {}),
718
744
  ...(options.shouldTrigger !== undefined ? { shouldTrigger: options.shouldTrigger } : {}),
719
745
  };
746
+ const targets = [...prepared.fixtureFiles.map(file => join(benchDir, 'fixtures', taskId, file.rel)),
747
+ ...Object.keys(generated).map(rel => join(benchDir, rel)), benchJsonPath];
748
+ assertBenchWrites(benchDir, targets);
749
+ if (sha256File(benchJsonPath) !== sha256Text(originalManifest))
750
+ throw new Error('Bench manifest changed while preparing the task; nothing was written.');
751
+ const writeState = () => targets.flatMap(target => [target, target + BACKUP_SUFFIX]).map(path => existsSync(path) ? sha256File(path) : null);
752
+ const expectedWrites = JSON.stringify(writeState());
753
+ const assertOutputsUnchanged = () => {
754
+ assertBenchWrites(benchDir, targets);
755
+ if (JSON.stringify(writeState()) !== expectedWrites)
756
+ throw new Error('Bench outputs changed while preparing the task; nothing was written. Review a fresh plan.');
757
+ };
758
+ if (draft) {
759
+ log(`Draft plan: 1 call; ceiling ${draft.plan.maxCalls}; executor deadline ${draft.plan.executorTimeoutSeconds}s; no automatic retry.`);
760
+ log(`Draft records: ${draft.dir}`);
761
+ log(`Spending limits: ${draft.plan.spendingBudget ? JSON.stringify(draft.plan.spendingBudget) : 'not set; token/cache usage may remain unknown'}. Authentication: unknown offline.`);
762
+ }
720
763
  if (options.verifierCmd) {
721
764
  // The string is not used once and discarded: it is written into a generated .mjs and re-executed
722
765
  // with a shell on every later `bench check` and `eval`. Disclose it before writing, in both the
@@ -738,38 +781,57 @@ export async function runBenchAdd(options) {
738
781
  }
739
782
  if (!options.yes) {
740
783
  const confirm = options.confirm ?? confirmPrompt;
741
- const ok = await confirm(`Add ${prepared.fixtureFiles.length} fixture file(s) + ${Object.keys(generated).length} generated file(s) into ${benchDir}? [y/N] `);
784
+ const ok = await confirm(`${draft ? 'Authorize 1 drafting call, retain its costs, then ' : ''}Add ${prepared.fixtureFiles.length} fixture file(s) + ${Object.keys(generated).length} generated file(s) into ${benchDir}? [y/N] `);
742
785
  if (!ok) {
743
786
  log('Aborted — nothing was written.');
744
787
  return null;
745
788
  }
746
789
  }
747
- const writes = [];
748
- for (const file of prepared.fixtureFiles) {
749
- if (file.rel.split(/[\\/]/).includes('..') || isAbsolute(file.rel)) {
750
- throw new Error(`Fixture path escapes the task directory: ${file.rel}`);
790
+ let failure;
791
+ try {
792
+ throwIfEvaluationInterrupted();
793
+ assertOutputsUnchanged();
794
+ if (draft) {
795
+ const drafted = await draftVerifierWithOracle(draft, log);
796
+ generated[`verifiers/${taskId}.mjs`] = drafted.verifierSource;
797
+ generated[`ground-truth/oracle-${taskId}.mjs`] = drafted.oracleSource;
798
+ }
799
+ const writes = [];
800
+ for (const file of prepared.fixtureFiles) {
801
+ if (file.rel.split(/[\\/]/).includes('..') || isAbsolute(file.rel)) {
802
+ throw new Error(`Fixture path escapes the task directory: ${file.rel}`);
803
+ }
804
+ writes.push({ target: join(benchDir, 'fixtures', taskId, file.rel), content: file.content });
805
+ }
806
+ for (const [rel, content] of Object.entries(generated)) {
807
+ writes.push({ target: join(benchDir, rel), content });
751
808
  }
752
- writes.push({ target: join(benchDir, 'fixtures', taskId, file.rel), content: file.content });
809
+ benchJson.tasks = [...tasks, taskEntry];
810
+ writes.push({ target: benchJsonPath, content: `${JSON.stringify(benchJson, null, 2)}\n` });
811
+ throwIfEvaluationInterrupted();
812
+ assertOutputsUnchanged();
813
+ applyBenchWrites(benchDir, writes);
814
+ log(`Task "${taskId}" added to ${benchDir} (${prepared.fixtureFiles.length} fixture file(s), verifier: ${prepared.verifierKind}).`);
815
+ log('Next:');
816
+ log(` skillfit bench check ${benchDir}`);
817
+ log(` skillfit eval <skill-path> --bench ${benchDir} --agent <id> --trials 5`);
818
+ return {
819
+ dir: benchDir,
820
+ taskId,
821
+ files: [
822
+ ...prepared.fixtureFiles.map((file) => `fixtures/${taskId}/${file.rel}`),
823
+ ...Object.keys(generated),
824
+ 'bench.json',
825
+ ],
826
+ };
753
827
  }
754
- for (const [rel, content] of Object.entries(generated)) {
755
- writes.push({ target: join(benchDir, rel), content });
828
+ catch (error) {
829
+ failure = error;
830
+ throw error;
831
+ }
832
+ finally {
833
+ draft?.finish(failure);
756
834
  }
757
- benchJson.tasks = [...tasks, taskEntry];
758
- writes.push({ target: benchJsonPath, content: `${JSON.stringify(benchJson, null, 2)}\n` });
759
- applyBenchWrites(benchDir, writes);
760
- log(`Task "${taskId}" added to ${benchDir} (${prepared.fixtureFiles.length} fixture file(s), verifier: ${prepared.verifierKind}).`);
761
- log('Next:');
762
- log(` skillfit bench check ${benchDir}`);
763
- log(` skillfit eval <skill-path> --bench ${benchDir} --agent <id> --trials 5`);
764
- return {
765
- dir: benchDir,
766
- taskId,
767
- files: [
768
- ...prepared.fixtureFiles.map((file) => `fixtures/${taskId}/${file.rel}`),
769
- ...Object.keys(generated),
770
- 'bench.json',
771
- ],
772
- };
773
835
  }
774
836
  function prepareFreeze(options, cwd) {
775
837
  const promptText = options.prompt ??
@@ -794,7 +856,7 @@ function prepareFreeze(options, cwd) {
794
856
  if (!existsSync(sourceDir)) {
795
857
  throw new Error(`--source-dir does not exist: ${sourceDir}`);
796
858
  }
797
- const captured = captureSourceFiles(sourceDir);
859
+ const captured = freezeSourceFiles(sourceDir, resolve(cwd, options.benchDir ?? '.'), options.include);
798
860
  if (captured.length === 0) {
799
861
  throw new Error(`No capturable files in ${sourceDir} (empty git index or directory).`);
800
862
  }
@@ -811,7 +873,7 @@ function prepareFreeze(options, cwd) {
811
873
  : options.verifierCmd
812
874
  ? 'command'
813
875
  : 'output',
814
- fixtureFiles: captured.map((rel) => ({ rel, content: readFileSync(join(sourceDir, rel)) })),
876
+ fixtureFiles: captured,
815
877
  groundTruth: `# Ground truth — frozen task
816
878
 
817
879
  Frozen from a real failure on ${new Date().toISOString().slice(0, 10)}.
@@ -664,6 +664,7 @@ test('runBenchAdd --freeze --decompose installs a gated draft with its oracle',
664
664
  freeze: true,
665
665
  sourceDir: source,
666
666
  decompose: true,
667
+ runsRoot: tmp(t, 'skillfit-draft-records-'),
667
668
  verifierKind: 'command',
668
669
  executor: stubDrafter(DRAFTED_COMMAND_VERIFIER, DRAFTED_ORACLE),
669
670
  yes: true,
@@ -689,6 +690,7 @@ test('runBenchAdd --decompose needs an agent or injected executor', async (t) =>
689
690
  freeze: true,
690
691
  sourceDir: source,
691
692
  decompose: true,
693
+ runsRoot: tmp(t, 'skillfit-draft-records-'),
692
694
  yes: true,
693
695
  log: () => { },
694
696
  }), /needs an agent/);
@@ -704,6 +706,7 @@ test('runBenchAdd --decompose rejects a draft that passes the untouched fixture'
704
706
  freeze: true,
705
707
  sourceDir: source,
706
708
  decompose: true,
709
+ runsRoot: tmp(t, 'skillfit-draft-records-'),
707
710
  executor: stubDrafter(laxVerifier, DRAFTED_ORACLE),
708
711
  yes: true,
709
712
  log: () => { },
@@ -722,6 +725,7 @@ test('runBenchAdd --decompose rejects a draft whose oracle does not solve the ta
722
725
  freeze: true,
723
726
  sourceDir: source,
724
727
  decompose: true,
728
+ runsRoot: tmp(t, 'skillfit-draft-records-'),
725
729
  verifierKind: 'command',
726
730
  executor: stubDrafter(DRAFTED_COMMAND_VERIFIER, idleOracle),
727
731
  yes: true,
@@ -762,6 +766,7 @@ test('runBenchAdd --decompose dry-run skips the agent and writes nothing', async
762
766
  freeze: true,
763
767
  sourceDir: source,
764
768
  decompose: true,
769
+ runsRoot: tmp(t, 'skillfit-draft-records-'),
765
770
  executor: spy,
766
771
  dryRun: true,
767
772
  log: () => { },
@@ -832,13 +837,11 @@ test('runBenchAdd backs up an existing file and rolls back a failed write', asyn
832
837
  assert.equal(readFileSync(leftover + '.skillfit-bak', 'utf8'), 'original verifier\n');
833
838
  assert.notEqual(readFileSync(leftover, 'utf8'), 'original verifier\n');
834
839
  });
835
- test('runBenchAdd works in a non-git source directory (filtered copy)', async (t) => {
840
+ test('runBenchAdd works in a non-git source directory with explicit file selection', async (t) => {
836
841
  const source = tmp(t, 'skillfit-freeze-plain-');
837
842
  writeFileSync(join(source, 'main.js'), 'console.log(1);\n');
838
843
  mkdirSync(join(source, 'node_modules', 'junk'), { recursive: true });
839
844
  writeFileSync(join(source, 'node_modules', 'junk', 'x.js'), 'x');
840
- mkdirSync(join(source, '.git'));
841
- writeFileSync(join(source, '.git', 'config'), 'x');
842
845
  const benchDir = await freezeBench(t);
843
846
  await runBenchAdd({
844
847
  benchDir,
@@ -846,6 +849,7 @@ test('runBenchAdd works in a non-git source directory (filtered copy)', async (t
846
849
  prompt: 'p',
847
850
  freeze: true,
848
851
  sourceDir: source,
852
+ include: ['main.js'],
849
853
  verifierCmd: 'node main.js',
850
854
  yes: true,
851
855
  log: () => { },
@@ -96,11 +96,35 @@ test('capability checks use matrix declarations and cover trigger support, insta
96
96
  assert.match(installed.checks.find(c => c.code === 'MATRIX_CAPABILITY').message, /project Skill directory/);
97
97
  const judge = structuredClone(f.role.definition);
98
98
  judge.headless.argv = ['missing-offline-judge'];
99
+ if (judge.headless.streamJson)
100
+ judge.headless.streamJson.argv = ['missing-offline-judge'];
99
101
  const judged = f.inspect([f.role, { ...f.role, role: 'judge', definition: judge }]);
100
102
  assert.equal(judged.status, 'blocked');
101
103
  assert.equal(judged.checks.find(c => c.role === 'judge' && c.code === 'CLI_AVAILABLE').status, 'FAIL');
102
104
  assert.equal(judged.checks.filter(c => c.code === 'AUTHENTICATION').length, 2);
103
105
  });
106
+ test('budget preflight distinguishes supported, unavailable and unknown token counters for every role', t => {
107
+ const f = setup(t);
108
+ for (const [id, status] of [['codex', 'PASS'], ['kimi-code', 'FAIL'], ['claude-code', 'FAIL']]) {
109
+ const checked = inspectAgentEnvironment({ roles: [{ ...f.role, definition: getAgent(id) }], target: f.target,
110
+ mode: 'inject', spendingBudget: true, homeDir: f.home, env: f.env });
111
+ const check = checked.checks.find(c => c.code === 'USAGE_CAPABILITY');
112
+ assert.equal(check.status, status, id);
113
+ if (status === 'FAIL') {
114
+ assert.match(check.message, /unavailable counters/);
115
+ assert.ok(check.remediation);
116
+ }
117
+ }
118
+ const checked = inspectAgentEnvironment({ roles: [f.role, { ...f.role, role: 'judge', definition: getAgent('claude-code') }],
119
+ target: f.target, mode: 'inject', spendingBudget: true, homeDir: f.home, env: f.env });
120
+ assert.equal(checked.checks.find(c => c.code === 'USAGE_CAPABILITY' && c.role === 'judge').status, 'FAIL');
121
+ for (const role of [{ ...f.role, injected: true }, { role: 'agent', injected: false, executor: { kind: 'api', model: 'not-called' } }]) {
122
+ const unknown = inspectAgentEnvironment({ roles: [role], target: f.target, mode: 'inject', spendingBudget: true, homeDir: f.home, env: f.env });
123
+ assert.equal(unknown.checks.find(c => c.code === 'USAGE_CAPABILITY').status, 'UNKNOWN');
124
+ assert.equal(unknown.status, 'ready');
125
+ assert.deepEqual(unknown.cost, { modelCalls: 0, cliInvocations: 0 });
126
+ }
127
+ });
104
128
  test('global conflicts include frontmatter aliases and configured home overrides without exposing Skill bodies', t => {
105
129
  const f = setup(t), dir = f.conflict();
106
130
  const report = f.inspect(), conflict = report.checks.find(c => c.code === 'GLOBAL_SKILL_CONFLICT');
@@ -0,0 +1,46 @@
1
+ import assert from 'node:assert/strict';
2
+ import { 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 { ApiExecutor } from '../harness/executors/api.js';
7
+ import { runBenchInit } from './bench.js';
8
+ import { runEval } from './eval.js';
9
+ import { readEvaluationReport } from './evaluation-report.js';
10
+ for (const role of ['agent', 'judge'])
11
+ test(`failed ${role} API content retains known final costs in stopped reports`, async (t) => {
12
+ const root = mkdtempSync(join(tmpdir(), 'skillfit-api-failure-'));
13
+ t.after(() => rmSync(root, { recursive: true, force: true }));
14
+ const skill = join(root, 'skill'), bench = join(root, 'bench'), run = join(root, 'runs', 'failed');
15
+ mkdirSync(skill);
16
+ writeFileSync(join(skill, 'SKILL.md'), '# Offline response failure regression\n');
17
+ await runBenchInit({ dir: bench, yes: true, log: () => { } });
18
+ let apiCalls = 0, primaryCalls = 0;
19
+ const payload = { choices: [{ message: { content: null, refusal: 'synthetic response' } }],
20
+ usage: { prompt_tokens: 123, completion_tokens: 17, prompt_tokens_details: { cached_tokens: 23 } } };
21
+ const api = new ApiExecutor({ apiKey: 'synthetic-api-key', fetchImpl: async () => { apiCalls++; return new Response(JSON.stringify(payload)); } });
22
+ const primary = { describe: () => ({ kind: 'mock', model: 'offline-primary' }), run: async () => {
23
+ primaryCalls++;
24
+ return { output: 'skillfit-ok', tokens: { input: 10, cachedInput: 4, output: 2 } };
25
+ } };
26
+ await assert.rejects(runEval({ skillPath: skill, bench, trials: 1, dryRun: false, yes: true, runsRoot: join(root, 'runs'), runGroup: 'failed',
27
+ executor: role === 'agent' ? api : primary, judgeExecutor: role === 'judge' ? api : null,
28
+ spendingBudget: { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 }, log: () => { } }), /EXECUTION_FAILED|choices\[0\]/);
29
+ assert.equal(apiCalls, 1);
30
+ assert.equal(primaryCalls, role === 'agent' ? 0 : 2);
31
+ const report = await readEvaluationReport(run);
32
+ assert.equal(report.status, 'stopped');
33
+ assert.ok('invocationCosts' in report);
34
+ const costs = report.invocationCosts?.total;
35
+ assert.ok(costs);
36
+ assert.equal(costs.metrics.input.knownTotal, role === 'agent' ? 123 : 143);
37
+ assert.equal(costs.metrics.cachedInput.knownTotal, role === 'agent' ? 23 : 31);
38
+ assert.equal(costs.metrics.output.knownTotal, role === 'agent' ? 17 : 21);
39
+ assert.equal(costs.metrics.input.coverage.final, role === 'agent' ? 1 : 3);
40
+ assert.equal(report.acceptance.eligibleForUpgrade, false);
41
+ assert.equal(report.acceptance.automaticUpgrade, false);
42
+ const evidence = role === 'agent' ? readFileSync(join(run, 'example-task/baseline/trial-1/_transcript.jsonl'), 'utf8')
43
+ : JSON.parse(readFileSync(join(run, 'example-task/judge-trial-1/call-1.json'), 'utf8')).rawOutput;
44
+ assert.deepEqual(JSON.parse(evidence), payload);
45
+ assert.equal(readFileSync(join(run, '_session.json'), 'utf8').includes('synthetic-api-key'), false);
46
+ });