skillfit 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +18 -6
  2. package/README.zh-CN.md +18 -6
  3. package/benches/README.md +2 -2
  4. package/dist/cli.js +132 -28
  5. package/dist/cli.test.js +94 -0
  6. package/dist/commands/bench-calibration.js +197 -0
  7. package/dist/commands/bench-calibration.test.js +237 -0
  8. package/dist/commands/bench-check-json.test.js +24 -3
  9. package/dist/commands/bench.js +63 -143
  10. package/dist/commands/calibration-cli.test.js +145 -0
  11. package/dist/commands/eval-agent-preflight.test.js +245 -0
  12. package/dist/commands/eval-cli.js +31 -0
  13. package/dist/commands/eval-component.js +52 -28
  14. package/dist/commands/eval-export-modes.test.js +350 -0
  15. package/dist/commands/eval-export.js +12 -4
  16. package/dist/commands/eval-plan.js +37 -0
  17. package/dist/commands/eval-preflight.test.js +144 -1
  18. package/dist/commands/eval-report.js +18 -3
  19. package/dist/commands/eval-single-arm-replay.js +21 -0
  20. package/dist/commands/eval-single-arm-report.js +223 -0
  21. package/dist/commands/eval.js +106 -56
  22. package/dist/commands/evaluation-report.js +5 -0
  23. package/dist/commands/evaluation-report.test.js +243 -0
  24. package/dist/commands/replay-cancellation.test.js +105 -0
  25. package/dist/commands/workflow-entrypoints.test.js +137 -0
  26. package/dist/harness/agent-preflight.js +180 -0
  27. package/dist/harness/bench.js +2 -1
  28. package/dist/harness/command.js +49 -0
  29. package/dist/harness/eval-audit.js +161 -16
  30. package/dist/harness/eval-budget.js +46 -2
  31. package/dist/harness/eval-budget.test.js +26 -1
  32. package/dist/harness/eval-component.test.js +163 -0
  33. package/dist/harness/eval-contract.js +11 -5
  34. package/dist/harness/executors/api.js +4 -3
  35. package/dist/harness/executors/api.test.js +18 -0
  36. package/dist/harness/experiment-session.js +18 -10
  37. package/dist/harness/experiment-session.test.js +8 -0
  38. package/dist/harness/invocation-costs.js +72 -0
  39. package/dist/harness/judge-accounting.test.js +216 -0
  40. package/dist/harness/judge-audit.js +56 -0
  41. package/dist/harness/judge.js +86 -21
  42. package/dist/harness/replay-package.js +71 -5
  43. package/dist/harness/runner.js +40 -30
  44. package/dist/harness/runner.test.js +23 -0
  45. package/dist/harness/single-arm-audit.js +436 -0
  46. package/dist/harness/trigger.js +21 -3
  47. package/dist/harness/trigger.test.js +12 -0
  48. package/dist/harness/verifier-error.js +65 -0
  49. package/dist/harness/verifier.test.js +128 -0
  50. package/docs/bench-authoring.md +34 -9
  51. package/docs/bench-check-json.md +28 -5
  52. package/docs/eval-agent-preflight.md +101 -0
  53. package/docs/eval-case-preflight.md +5 -0
  54. package/docs/eval-component.md +38 -10
  55. package/docs/eval-costs.md +44 -0
  56. package/docs/eval-planning.md +153 -0
  57. package/docs/evaluation-input-snapshots.md +2 -1
  58. package/docs/evaluation-interruption.md +22 -10
  59. package/docs/evaluation-reports.md +97 -3
  60. package/docs/experiment-workflow.md +7 -0
  61. package/docs/first-real-eval.md +50 -3
  62. package/docs/growth-roadmap-2026-10.md +41 -9
  63. package/docs/metrics.md +40 -3
  64. package/docs/plans/2026-10-17-workflow-foundations.md +64 -0
  65. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  66. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  67. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  68. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  69. package/docs/releases/0.10.1-signatures.txt +7 -0
  70. package/docs/releases/0.10.1-verification.json +90 -0
  71. package/docs/releases/0.10.1.md +37 -4
  72. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  73. package/docs/releases/0.11.0.md +47 -0
  74. package/docs/replay-packages.md +38 -6
  75. package/docs/schemas/agent-preflight.schema.json +31 -0
  76. package/docs/schemas/calibration-plan.schema.json +22 -0
  77. package/docs/schemas/calibration-result.schema.json +17 -0
  78. package/docs/schemas/eval-request.schema.json +1 -1
  79. package/docs/schemas/eval-result.schema.json +3 -1
  80. package/docs/schemas/invocation-costs.schema.json +31 -0
  81. package/docs/schemas/judge-call.schema.json +22 -0
  82. package/docs/schemas/single-arm-report.schema.json +20 -0
  83. package/docs/schemas/verifier-error.schema.json +11 -0
  84. package/docs/sharing-results.md +3 -0
  85. package/docs/verifier-contract.md +99 -0
  86. package/package.json +1 -1
  87. package/skills/skillfit/SKILL.md +41 -8
@@ -6,15 +6,19 @@ import { loadBench } from './bench.js';
6
6
  import { summarizeCosts } from './costs.js';
7
7
  import { policyHash, parseAcceptancePolicy, readComponentJson, record } from './eval-contract.js';
8
8
  import { costChanges } from './eval-acceptance.js';
9
- import { sha256File } from './hash.js';
9
+ import { sha256File, sha256Text } from './hash.js';
10
10
  import { collectInstalledSkillTarget } from './installed-skill.js';
11
- import { runVerifier } from './runner.js';
11
+ import { runVerifier, summarizeJudge } from './runner.js';
12
12
  import { verdictFromOutput } from './verifier-summary.js';
13
13
  import { parseEvalReport } from '../commands/eval-report.js';
14
14
  import { pairConditions } from './types.js';
15
15
  import { NATIVE_DIFF_PATH, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
16
16
  import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
17
17
  import { verifyInputSnapshot } from './input-snapshot.js';
18
+ import { assertRecordedAgentEnvironment } from './agent-preflight.js';
19
+ import { judgeCallReceipt } from './judge-audit.js';
20
+ import { buildJudgePrompt, judgeOrder } from './judge.js';
21
+ import { summarizeInvocationCosts } from './invocation-costs.js';
18
22
  function inside(root, path) {
19
23
  const rel = relative(root, path);
20
24
  return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
@@ -102,6 +106,34 @@ export async function auditEvaluation(value, runDir, options = {}) {
102
106
  const plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
103
107
  const inputSnapshot = verifyInputSnapshot(root, plan);
104
108
  const details = record(plan.details, 'native plan details');
109
+ if (details.agentPreflight !== undefined)
110
+ assertRecordedAgentEnvironment(details.agentPreflight);
111
+ if (details.reviewedPlan !== undefined) {
112
+ const reviewed = record(details.reviewedPlan, 'reviewed plan'), { sha256, ...data } = reviewed;
113
+ assert.equal(data.schemaVersion, 1);
114
+ assert.equal(data.kind, 'skillfit.eval-plan');
115
+ assert.equal(sha256Text(JSON.stringify(data)), sha256, 'Reviewed plan hash changed.');
116
+ const e = record(data.evaluation, 'reviewed evaluation');
117
+ assert.equal(e.mode, details.mode);
118
+ assert.equal(record(e.target, 'reviewed target').kind, report.target.kind);
119
+ const implementation = plan.inputs.find(input => input.label === 'implementation');
120
+ assert.equal(implementation?.sha256, data.implementationSha256, 'Reviewed implementation differs from native inputs.');
121
+ assert.equal(record(e.target, 'reviewed target').sha256, report.target.sha256);
122
+ assert.equal(record(e.bench, 'reviewed bench').sha256, report.bench.sha256);
123
+ assert.deepEqual(record(e.bench, 'reviewed bench').taskIds, report.tasks.map(task => task.id));
124
+ assert.equal(e.baseline === null ? null : record(e.baseline, 'reviewed baseline').sha256, report.baselineTarget?.sha256 ?? null);
125
+ assert.deepEqual(e.executor, raw.executor);
126
+ assert.deepEqual(e.judge, raw.judge);
127
+ assert.equal(e.trials, report.trials);
128
+ assert.equal(e.plannedCalls, report.experiment.plannedCalls);
129
+ assert.equal(e.maxCalls, report.experiment.maxCalls);
130
+ assert.equal(e.inputMode, raw.inputMode);
131
+ assert.equal(e.installDir, report.skillDelivery?.installDir ?? null);
132
+ assert.equal(e.pairOrder, details.pairOrder);
133
+ assert.equal(e.executorTimeoutSeconds, details.executorTimeoutSeconds);
134
+ assert.deepEqual(e.spendingBudget, details.spendingBudget, 'Reviewed spending limits differ from the native plan.');
135
+ assert.deepEqual(e.agentPreflight, details.agentPreflight, 'Reviewed Agent preflight differs from the native plan.');
136
+ }
105
137
  let pairOrder = null;
106
138
  if (raw.pairOrder !== undefined || details.pairOrder !== undefined) {
107
139
  assert.ok(raw.pairOrder === 'baseline-first' || raw.pairOrder === 'balanced', 'Invalid recorded pair order.');
@@ -147,6 +179,8 @@ export async function auditEvaluation(value, runDir, options = {}) {
147
179
  let invoked = 0;
148
180
  const expectedAgentOrder = [];
149
181
  const budgetReceipts = new Map();
182
+ const expectedDispatches = [];
183
+ const judgeCalls = [];
150
184
  const rawTasks = raw.tasks;
151
185
  for (const [taskIndex, task] of report.tasks.entries()) {
152
186
  assert.ok(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(task.id), 'Unsafe task id.');
@@ -167,7 +201,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
167
201
  if (details.nativeDiffTool !== undefined && r.executorInvoked) {
168
202
  assert.equal(sha256File(member(root, `${task.id}/${arm}/trial-${trial}/${NATIVE_DIFF_PATH}`)), record(details.nativeDiffTool, 'native diff tool').sha256, 'Delivered native diff tool changed.');
169
203
  }
170
- if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false) {
204
+ if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false && report.executor.kind === 'cli') {
171
205
  assert.ok(typeof details.executorTimeoutSeconds === 'number' && Number.isSafeInteger(details.executorTimeoutSeconds) && details.executorTimeoutSeconds >= 1 && details.executorTimeoutSeconds <= 3600);
172
206
  const actualTiming = record(record(r.timing, 'CLI timing').execution, 'CLI execution timing');
173
207
  assert.equal(actualTiming.timeoutMs, details.executorTimeoutSeconds * 1000, 'CLI deadline differs from the native plan.');
@@ -195,6 +229,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
195
229
  try {
196
230
  cpSync(join(root, task.id, arm, `trial-${trial}`), scratch, { recursive: true, filter: path => basename(path) !== '.git' });
197
231
  const grade = await runVerifier(bench.dir, definition.verifier, scratch), summary = verdictFromOutput(grade.output);
232
+ assert.equal(grade.error, null, `Replay verifier failed: ${grade.error}`);
198
233
  assert.notEqual(grade.exitCode, null);
199
234
  assert.equal(grade.exitCode, r.verifierExitCode);
200
235
  assert.equal(grade.exitCode === 0, r.passed);
@@ -215,8 +250,10 @@ export async function auditEvaluation(value, runDir, options = {}) {
215
250
  const b = pair.baseline, t = pair.treatment;
216
251
  if (pairOrder)
217
252
  for (const arm of pairConditions(pairOrder, taskIndex, trial)) {
218
- if (pair[arm].executorInvoked)
253
+ if (pair[arm].executorInvoked) {
219
254
  expectedAgentOrder.push(`${task.id}/${arm}/trial-${trial}`);
255
+ expectedDispatches.push({ role: 'agent', identity: { taskId: task.id, condition: arm, trial }, receipt: pair[arm] });
256
+ }
220
257
  }
221
258
  const graded = b.error === null && t.error === null;
222
259
  const changes = [];
@@ -239,38 +276,101 @@ export async function auditEvaluation(value, runDir, options = {}) {
239
276
  const outcomes = record(source.outcomes, 'paired outcomes');
240
277
  for (const arm of ['baseline', 'treatment'])
241
278
  assert.deepEqual(taskPaired[arm].map(r => r.passed), outcomes[arm]);
279
+ if (raw.judge != null) {
280
+ assert.ok(raw.invocationCosts != null, 'Judge usage unrecorded; cannot verify full invocation accounting.');
281
+ const judged = [];
282
+ for (let trial = 1; trial <= report.trials; trial++) {
283
+ const baseline = budgetReceipts.get(`${task.id}/baseline/trial-${trial}`);
284
+ const treatment = budgetReceipts.get(`${task.id}/treatment/trial-${trial}`);
285
+ if (baseline.error !== null || treatment.error !== null)
286
+ continue;
287
+ const seed = `${raw.runGroup}:${task.id}:${trial}`, order = judgeOrder(seed), calls = [];
288
+ for (const callIndex of [1, 2]) {
289
+ const path = `${task.id}/judge-trial-${trial}/call-${callIndex}.json`;
290
+ assert.equal(typeof files[path], 'string', 'Judge invocation receipt was not sealed.');
291
+ const call = judgeCallReceipt(readComponentJson(member(root, path)).value);
292
+ assert.equal(call.taskId, task.id);
293
+ assert.equal(call.trial, trial);
294
+ assert.equal(call.callIndex, callIndex);
295
+ assert.equal(call.seed, seed);
296
+ assert.equal(call.firstCondition, order[callIndex - 1]);
297
+ assert.equal(call.error, null);
298
+ assert.deepEqual(call.executor, raw.judge, 'Judge receipt executor differs from frozen metadata.');
299
+ if (details.executorTimeoutSeconds !== undefined && plan.injectedExecutor === false && record(raw.judge, 'judge').kind === 'cli') {
300
+ assert.equal(record(call.timing.execution, 'judge execution timing').timeoutMs, Number(details.executorTimeoutSeconds) * 1000, 'Judge deadline differs from the native plan.');
301
+ }
302
+ const nonce = call.prompt.match(/<<<BEGIN ANSWER A ([0-9a-f]{16})>>>/)?.[1];
303
+ assert.ok(nonce, 'Judge prompt anonymity nonce is missing.');
304
+ const benchSource = inputSnapshot?.roots.get('bench');
305
+ assert.ok(benchSource, 'Judge prompt auditing requires the sealed bench input.');
306
+ const frozenBench = loadBench(benchSource), definition = frozenBench.tasks.find(t => t.id === task.id);
307
+ assert.ok(definition);
308
+ const baseOutput = readFileSync(member(root, `${task.id}/baseline/trial-${trial}/_output.md`), 'utf8');
309
+ const treatmentOutput = readFileSync(member(root, `${task.id}/treatment/trial-${trial}/_output.md`), 'utf8');
310
+ assert.deepEqual(call.prompt, buildJudgePrompt(readFileSync(join(benchSource, definition.prompt), 'utf8'), definition.rubric ? readFileSync(join(benchSource, definition.rubric), 'utf8') : null, call.firstCondition === 'baseline' ? baseOutput : treatmentOutput, call.firstCondition === 'baseline' ? treatmentOutput : baseOutput, nonce), 'Judge prompt differs from the sealed task and anonymized answers.');
311
+ calls.push(call);
312
+ judgeCalls.push(call);
313
+ audit.receipts++;
314
+ expectedDispatches.push({ role: 'judge', identity: { role: 'judge', taskId: task.id, trial, callIndex }, receipt: call, promptSha256: call.promptSha256 });
315
+ }
316
+ const forward = calls[0].scores, reverse = calls[1].scores;
317
+ const result = { baselineScore: (forward.baseline + reverse.baseline) / 2, treatmentScore: (forward.treatment + reverse.treatment) / 2,
318
+ consistent: Math.sign(forward.baseline - forward.treatment) === Math.sign(reverse.baseline - reverse.treatment),
319
+ firstCondition: order[0], raw: `${calls[0].output}\n--- reverse order ---\n${calls[1].output}`, calls };
320
+ const path = `${task.id}/judge-trial-${trial}.json`;
321
+ assert.equal(typeof files[path], 'string');
322
+ assert.deepEqual(readComponentJson(member(root, path)).value, { trial, seed, ...result }, 'Judge pair summary differs from independent invocation receipts.');
323
+ judged.push(result);
324
+ }
325
+ assert.deepEqual(source.judge, summarizeJudge(judged), 'Judge task summary differs from invocation receipts.');
326
+ }
242
327
  }
243
328
  assert.deepEqual(summarizeCosts(all, paired), report.overall.costs, 'Overall cost accounting differs from receipts.');
244
329
  const ledger = readFileSync(join(root, '_calls.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => record(JSON.parse(line), 'ledger'));
330
+ const startedEvents = ledger.filter(e => e.event === 'started'), terminalEvents = ledger.filter(e => e.event === 'finished' || e.event === 'failed');
331
+ assert.equal(terminalEvents.length, report.experiment.callsFinished, 'Terminal call ledger differs from session accounting.');
332
+ for (const [ordinal, event] of startedEvents.entries()) {
333
+ assert.equal(event.call, ordinal + 1, 'Call ledger dispatch numbers must be consecutive.');
334
+ assert.ok(event.role === 'agent' || event.role === 'judge');
335
+ assert.ok(typeof event.promptSha256 === 'string' && /^[a-f0-9]{64}$/.test(event.promptSha256));
336
+ assert.equal(terminalEvents.filter(terminal => terminal.call === event.call).length, 1, 'Each dispatched call needs one terminal ledger receipt.');
337
+ }
245
338
  assert.equal(ledger.filter(e => e.event === 'started' && e.role === 'agent').length, invoked);
246
339
  assert.equal(ledger.filter(e => e.event === 'started').length, report.experiment.callsStarted);
247
340
  if (pairOrder)
248
341
  assert.deepEqual(ledger.filter(e => e.event === 'started' && e.role === 'agent')
249
342
  .map(e => String(e.workdir).split(/[\\/]/).slice(-3).join('/')), expectedAgentOrder, 'Recorded execution order differs from the frozen pair order.');
343
+ if (raw.invocationCosts !== undefined) {
344
+ assert.deepEqual(raw.invocationCosts, summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeCalls, raw.judge != null), 'Full invocation accounting differs from agent/judge receipts.');
345
+ const started = ledger.filter(e => e.event === 'started');
346
+ assert.equal(started.length, expectedDispatches.length, 'Agent/judge receipt coverage differs from the dispatch ledger.');
347
+ for (const [index, event] of started.entries()) {
348
+ const expected = expectedDispatches[index];
349
+ assert.equal(event.role, expected.role, 'Agent/judge dispatch order differs from frozen execution.');
350
+ if (expected.promptSha256)
351
+ assert.equal(event.promptSha256, expected.promptSha256, 'Judge invocation prompt hash differs from the call ledger.');
352
+ }
353
+ }
250
354
  if (details.spendingBudget !== undefined) {
251
355
  const limits = parseSpendingBudget(details.spendingBudget);
252
356
  assert.ok(pairOrder, 'Budget replay requires the recorded pair order.');
253
357
  assert.ok(typeof files['_budget.jsonl'] === 'string', 'Budget events are not sealed.');
254
358
  const events = readFileSync(join(root, '_budget.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
255
- assert.equal(events.length, expectedAgentOrder.length * 2, 'Budget event coverage differs from calls.');
359
+ assert.equal(events.length, expectedDispatches.length * 2, 'Budget event coverage differs from calls.');
256
360
  const observations = [];
257
- for (const [ordinal, path] of expectedAgentOrder.entries()) {
258
- const [taskId, condition, trialPath] = path.split('/');
259
- const trial = Number(trialPath.slice('trial-'.length));
361
+ for (const [ordinal, dispatch] of expectedDispatches.entries()) {
260
362
  const before = spendingBudgetState(limits, observations);
261
363
  assertSpendingCanContinue(before);
262
- assert.deepEqual(events[ordinal * 2], { phase: 'before-call', taskId, condition, trial, state: before }, 'Budget before-call state differs from receipts.');
263
- observations.push(budgetReceipts.get(path));
364
+ assert.deepEqual(events[ordinal * 2], { phase: 'before-call', ...dispatch.identity, state: before }, 'Budget before-call state differs from receipts.');
365
+ observations.push(dispatch.receipt);
264
366
  const after = spendingBudgetState(limits, observations);
265
367
  assert.equal(after.incomplete.length, 0, 'Budget run has missing final usage.');
266
368
  assert.notEqual(after.reason, 'EXECUTION_FAILED');
267
- assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call', taskId, condition, trial, state: after }, 'Budget after-call state differs from receipts.');
369
+ assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call', ...dispatch.identity, state: after }, 'Budget after-call state differs from receipts.');
268
370
  }
269
371
  }
270
372
  else
271
373
  assert.equal(files['_budget.jsonl'], undefined, 'Budget events were not declared in the native plan.');
272
- // This component does not run a judge whose separate usage would be absent from agent costs.
273
- assert.ok(raw.judge == null, 'Judge usage is not covered by component accounting.');
274
374
  audit.verified = true;
275
375
  }
276
376
  catch (error) {
@@ -307,9 +407,54 @@ export function stoppedAccounting(runDir) {
307
407
  }
308
408
  }
309
409
  const populations = summarizeCosts(all, paired);
410
+ const judgeEvents = ledger.filter(e => e.event === 'started' && e.role === 'judge');
411
+ const retainedJudgeCalls = new Map();
412
+ const walkJudge = (dir, prefix = '') => {
413
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
414
+ if (!entry.isDirectory() || entry.name === '.git' || entry.name === '_inputs')
415
+ continue;
416
+ const path = join(dir, entry.name), rel = prefix ? `${prefix}/${entry.name}` : entry.name;
417
+ if (/^[a-zA-Z0-9][a-zA-Z0-9._-]*\/judge-trial-[0-9]+$/.test(rel)) {
418
+ for (const name of ['call-1.json', 'call-2.json'])
419
+ if (existsSync(join(path, name))) {
420
+ try {
421
+ const value = readComponentJson(join(path, name)).value, r = record(value, 'judge receipt');
422
+ if (typeof r.promptSha256 === 'string')
423
+ retainedJudgeCalls.set(r.promptSha256, { path: `${rel}/${name}`, value });
424
+ }
425
+ catch { /* Unparseable files remain on disk; unmatched dispatch is unknown below. */ }
426
+ }
427
+ }
428
+ else if (!prefix)
429
+ walkJudge(path, rel);
430
+ }
431
+ };
432
+ walkJudge(root);
433
+ let missingJudgeReceipts = 0;
434
+ const judgeObservations = judgeEvents.map(event => {
435
+ const retained = retainedJudgeCalls.get(String(event.promptSha256));
436
+ if (retained) {
437
+ try {
438
+ const receipt = judgeCallReceipt(retained.value);
439
+ assert.equal(receipt.executorInvoked, true);
440
+ return receipt;
441
+ }
442
+ catch (error) {
443
+ invalidReceipts.push({ path: retained.path, reason: String(error) });
444
+ }
445
+ }
446
+ missingJudgeReceipts++;
447
+ return { executorInvoked: true, passed: false, error: 'Judge invocation receipt missing or invalid', durationSeconds: NaN, tokens: null, usageStatus: 'unknown' };
448
+ });
449
+ const nativePlan = existsSync(join(root, '_plan.json')) ? record(readComponentJson(join(root, '_plan.json')).value, 'native plan') : null;
450
+ const judgeRequested = judgeEvents.length > 0 || Boolean(nativePlan?.details && record(nativePlan.details, 'native plan details').judge != null);
451
+ const invocationCosts = summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeObservations, judgeRequested);
452
+ if (missingJudgeReceipts)
453
+ invocationCosts.judgeUsage = 'unknown';
310
454
  return { populations, startedAgentDispatches: all.baseline.length + all.treatment.length,
311
- recordedExecutorInvocations: populations.attempts.baseline.runs + populations.attempts.treatment.runs - missingReceipts - invalidReceipts.length,
312
- invocationsWithUnknownReceipts: missingReceipts + invalidReceipts.length,
455
+ invocationCosts, startedJudgeDispatches: judgeEvents.length, judgeInvocationsWithUnknownReceipts: missingJudgeReceipts,
456
+ recordedExecutorInvocations: populations.attempts.baseline.runs + populations.attempts.treatment.runs - missingReceipts - invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
457
+ invocationsWithUnknownReceipts: missingReceipts + invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
313
458
  ...(invalidReceipts.length ? { invalidReceipts } : {}),
314
- scope: 'Known agent invocation spending from stopped-run receipts; missing fields remain unknown. No paired efficacy comparison or exact bill.' };
459
+ scope: 'Known primary Agent spending and separate all-role invocation totals from stopped-run receipts; missing fields remain unknown. No paired efficacy comparison or exact bill.' };
315
460
  }
@@ -1,6 +1,26 @@
1
1
  import { COST_METRICS, summarizeCosts } from './costs.js';
2
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ /** Only controlled budget diagnostics may be copied into a durable session stop reason. */
5
+ export class SpendingBudgetStop extends Error {
6
+ code;
7
+ constructor(code, state) {
8
+ super(`${code}: no further agent calls; reached=${state.reached.join(',') || 'none'}, incomplete=${state.incomplete.join(',') || 'none'}. Retained spending is not discarded; no retry or replacement.`);
9
+ this.code = code;
10
+ this.name = 'SpendingBudgetStop';
11
+ }
12
+ }
13
+ export function spendingStopFrom(error) {
14
+ const seen = new Set();
15
+ let current = error;
16
+ while (current instanceof Error && !seen.has(current) && seen.size < 8) {
17
+ if (current instanceof SpendingBudgetStop)
18
+ return current;
19
+ seen.add(current);
20
+ current = current.cause;
21
+ }
22
+ return null;
23
+ }
4
24
  export function parseSpendingBudget(value) {
5
25
  if (!value || typeof value !== 'object' || Array.isArray(value))
6
26
  throw new Error('spendingBudget must be an object.');
@@ -30,7 +50,31 @@ export function spendingBudgetState(limits, observations) {
30
50
  }
31
51
  export function assertSpendingCanContinue(state) {
32
52
  if (state.reason)
33
- throw new Error(`${state.reason}: no further agent calls; reached=${state.reached.join(',') || 'none'}, incomplete=${state.incomplete.join(',') || 'none'}. Retained spending is not discarded; no retry or replacement.`);
53
+ throw new SpendingBudgetStop(state.reason, state);
54
+ }
55
+ /** One serial stop-line recorder for every executor role and evaluation mode. */
56
+ export function createSpendingBudgetRecorder(options) {
57
+ const observations = [];
58
+ const event = (phase, identity) => {
59
+ if (!options.budget)
60
+ return null;
61
+ const state = spendingBudgetState(options.budget, observations);
62
+ appendFileSync(join(options.groupDir, '_budget.jsonl'), JSON.stringify({ phase, ...identity, state }) + '\n', 'utf8');
63
+ return state;
64
+ };
65
+ return {
66
+ before(identity) {
67
+ const state = event('before-call', identity);
68
+ if (state)
69
+ assertSpendingCanContinue(state);
70
+ },
71
+ after(identity, observation) {
72
+ observations.push(observation);
73
+ const state = event('after-call', identity);
74
+ if (state && (state.incomplete.length || state.reason === 'EXECUTION_FAILED'))
75
+ assertSpendingCanContinue(state);
76
+ },
77
+ };
34
78
  }
35
79
  /** Informational on stopped evidence; a completed native audit verifies every event. */
36
80
  export function spendingBudgetReport(runDir) {
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import { test } from 'node:test';
6
6
  import { runEvalComponent, reportEvalComponent } from '../commands/eval-component.js';
7
7
  import { parseEvalRequest } from './eval-contract.js';
8
- import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
8
+ import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState, spendingStopFrom, SpendingBudgetStop } from './eval-budget.js';
9
9
  import { COST_METRICS } from './costs.js';
10
10
  import { sha256File } from './hash.js';
11
11
  import { ExecutorFailure } from './types.js';
@@ -36,6 +36,25 @@ test('all-invocation budgets count functional failures, partial costs and unknow
36
36
  assert.equal(state.metrics.input.coverage.partial, 1);
37
37
  assert.equal(state.reason, 'FINAL_USAGE_MISSING');
38
38
  });
39
+ test('budget stop codes survive trusted cause chains without treating arbitrary error text as safe diagnostics', () => {
40
+ const state = spendingBudgetState({ ...limits, input: 10 }, [observation()]);
41
+ let stopped;
42
+ try {
43
+ assertSpendingCanContinue(state);
44
+ }
45
+ catch (error) {
46
+ stopped = error;
47
+ }
48
+ assert.ok(stopped instanceof SpendingBudgetStop);
49
+ assert.equal(stopped.code, 'SPENDING_BUDGET_REACHED');
50
+ assert.equal(spendingStopFrom(new Error('wrapper', { cause: stopped })), stopped);
51
+ const ordinary = new Error('SPENDING_BUDGET_REACHED: private credential text');
52
+ ordinary.name = 'SpendingBudgetStop';
53
+ assert.equal(spendingStopFrom(ordinary), null);
54
+ const cycle = new Error('cyclic cause');
55
+ cycle.cause = cycle;
56
+ assert.equal(spendingStopFrom(cycle), null);
57
+ });
39
58
  function setup(t, change = {}, result, functionalFailure = false) {
40
59
  const root = mkdtempSync(join(tmpdir(), 'skillfit-budget-'));
41
60
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -83,6 +102,9 @@ for (const metric of COST_METRICS)
83
102
  const receipt = JSON.parse(readFileSync(join(f.directory, 'first/baseline/trial-1/_result.json'), 'utf8'));
84
103
  assert.deepEqual(receipt.tokens, { input: 10, cachedInput: 6, output: 3 });
85
104
  assert.equal(existsSync(join(f.directory, 'first/treatment/trial-1')), false);
105
+ const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
106
+ assert.equal(session.stopCode, 'SPENDING_BUDGET_REACHED');
107
+ assert.match(session.stopReason, /SPENDING_BUDGET_REACHED/);
86
108
  assert.ok('spendingBudget' in result);
87
109
  assert.ok(result.spendingBudget);
88
110
  assert.ok(result.spendingBudget.latestState.reached.includes(metric));
@@ -106,6 +128,9 @@ for (const [label, tokens] of [['no counters', undefined], ['missing cache', { i
106
128
  assert.equal(f.calls(), 1);
107
129
  assert.equal(result.status, 'stopped');
108
130
  assert.equal(result.acceptance.eligibleForUpgrade, false);
131
+ const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
132
+ assert.equal(session.stopCode, 'FINAL_USAGE_MISSING');
133
+ assert.match(session.stopReason, /FINAL_USAGE_MISSING/);
109
134
  assert.ok('spendingBudget' in result);
110
135
  assert.ok(result.spendingBudget);
111
136
  assert.equal(result.spendingBudget.latestState.reason, 'FINAL_USAGE_MISSING');
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url';
8
8
  import { reportEvalComponent, runEvalComponent } from '../commands/eval-component.js';
9
9
  import { exportEvaluation } from '../commands/eval-export.js';
10
10
  import { runEval } from '../commands/eval.js';
11
+ import { runEvalCli } from '../commands/eval-cli.js';
11
12
  import { assessEvaluation } from './eval-acceptance.js';
12
13
  import { parseAcceptancePolicy, parseEvalRequest, policyHash } from './eval-contract.js';
13
14
  import { hashFileSet, listFilesRecursive, sha256File } from './hash.js';
@@ -316,6 +317,7 @@ test('changing the request policy during a call stops further calls and retains
316
317
  assert.ok('costs' in result);
317
318
  assert.equal(result.costs.populations?.attempts.baseline.metrics.input.knownTotal, 10);
318
319
  const replay = await reportEvalComponent(f.runDir);
320
+ assert.ok('costs' in replay);
319
321
  assert.deepEqual(replay.costs, result.costs);
320
322
  });
321
323
  test('executor failures preserve partial usage and missing cache counts remain unknown', async (t) => {
@@ -605,3 +607,164 @@ test('CLI request plans and errors emit one parseable JSON document without agen
605
607
  assert.match(JSON.parse(mixed.stdout).error.message, /cannot be combined/);
606
608
  assert.equal(existsSync(join(f.root, 'runs')), false);
607
609
  });
610
+ test('an explicit null baseline installs no Skill in baseline, preserves identical prompts and replays without originals', async (t) => {
611
+ const f = setup(t), seen = [], prompts = [];
612
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, baselineSkill: null, taskIds: ['fix'], maxCalls: 2, executorTimeoutSeconds: 17 }));
613
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-no-skill' }), run: async (prompt, workdir) => {
614
+ prompts.push(prompt);
615
+ const installed = existsSync(join(workdir, 'project-skills/answer-skill/SKILL.md'));
616
+ seen.push(installed);
617
+ writeFileSync(join(workdir, 'answer.txt'), installed ? '2' : '1');
618
+ return { output: 'done', tokens: { input: 10, cachedInput: 6, output: 2 } };
619
+ } };
620
+ const options = { ...f.options, executor }, preview = await runEvalComponent(f.requestPath, { ...options, dryRun: true });
621
+ assert.equal(preview.plan.request.baselineSkill, null);
622
+ assert.equal(preview.plan.evaluation.baseline, null);
623
+ assert.equal(preview.plan.evaluation.executorTimeoutSeconds, 17);
624
+ assert.equal(preview.plan.evaluation.plannedCalls, 2);
625
+ assert.equal(existsSync(f.runDir), false);
626
+ assert.equal(seen.length, 0);
627
+ const result = await runEvalComponent(f.requestPath, { ...options, dryRun: false, expectedPlanSha256: preview.plan.sha256 });
628
+ assert.deepEqual(seen, [false, true]);
629
+ assert.equal(prompts[0], prompts[1]);
630
+ assert.ok('identity' in result);
631
+ assert.equal(result.identity.baseline, null);
632
+ assert.equal(result.evidence.verified, true);
633
+ assert.ok(result.acceptance.reasons.some(r => r.code === 'REVISION_COMPARISON_REQUIRED'));
634
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
635
+ for (const path of [f.requestPath, join(f.root, 'bench'), join(f.root, 'old'), join(f.root, 'new')])
636
+ rmSync(path, { recursive: true });
637
+ const replay = await reportEvalComponent(f.runDir, { replay: true });
638
+ assert.equal(replay.evidence.verified, true);
639
+ const output = join(f.root, 'portable');
640
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
641
+ assert.equal(existsSync(join(output, 'inputs/baseline-skill')), false);
642
+ assert.equal(JSON.parse(readFileSync(join(output, 'inputs/request.json'), 'utf8')).baselineSkill, null);
643
+ rmSync(f.runDir, { recursive: true });
644
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
645
+ assert.equal(child.status, 0, child.stderr);
646
+ const portable = JSON.parse(child.stdout);
647
+ assert.equal(portable.identity.baseline, null);
648
+ assert.equal(portable.acceptance.eligibleForUpgrade, false);
649
+ assert.equal(seen.length, 2);
650
+ });
651
+ test('null is an explicit baseline choice; missing, empty or malformed paths never silently select it', t => {
652
+ const f = setup(t), { baselineSkill: _previous, ...missing } = f.body;
653
+ assert.equal(parseEvalRequest({ ...f.body, baselineSkill: null }, f.root).baselineSkill, null);
654
+ assert.equal(parseEvalRequest(f.body, f.root).baselineSkill, join(f.root, 'old'));
655
+ for (const baselineSkill of [undefined, '', false, 0, {}])
656
+ assert.throws(() => parseEvalRequest({ ...f.body, baselineSkill }, f.root), /baselineSkill/);
657
+ assert.throws(() => parseEvalRequest(missing, f.root), /baselineSkill/);
658
+ assert.equal(f.calls(), 0);
659
+ });
660
+ function ordinaryOptions(f, overrides = {}) {
661
+ return { skillPath: join(f.root, 'new'), baselineSkillPath: join(f.root, 'old'), bench: join(f.root, 'bench'), agent: 'codex',
662
+ mode: 'installed', inputMode: 'workspace', trials: 1, maxCalls: 4, runsRoot: join(f.root, 'runs'), runGroup: 'component',
663
+ dryRun: true, yes: true, ...f.options, log: () => { }, ...overrides };
664
+ }
665
+ test('ordinary eval and request preview share the effective plan, timeout and all spending lines', async (t) => {
666
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
667
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget }));
668
+ const request = await runEvalComponent(f.requestPath, { ...f.options, dryRun: true });
669
+ const ordinary = await runEvalCli(ordinaryOptions(f, { pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget }));
670
+ assert.ok('plan' in ordinary);
671
+ assert.deepEqual(ordinary.plan.evaluation, request.plan.evaluation);
672
+ assert.equal(ordinary.plan.implementationSha256, request.plan.implementationSha256);
673
+ assert.equal(ordinary.status, 'planned');
674
+ assert.equal(ordinary.acceptance.eligibleForUpgrade, false);
675
+ assert.equal(existsSync(join(f.root, 'runs')), false);
676
+ assert.equal(f.calls(), 0);
677
+ });
678
+ test('ordinary confirmed plans reject changed budget, timeout, ordering, selection and baseline before calls', async (t) => {
679
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
680
+ const base = ordinaryOptions(f, { pairOrder: 'balanced', executorTimeoutSeconds: 17, spendingBudget });
681
+ const preview = await runEvalCli(base);
682
+ assert.ok('plan' in preview);
683
+ for (const change of [{ executorTimeoutSeconds: 18 }, { pairOrder: 'baseline-first' }, { spendingBudget: { ...spendingBudget, input: 999 } },
684
+ { maxCalls: 5 }, { taskIds: ['fix'] }, { baselineSkillPath: undefined }]) {
685
+ await assert.rejects(() => runEvalCli({ ...base, ...change, dryRun: false }, preview.plan.sha256), /--plan-sha matching/);
686
+ }
687
+ assert.equal(f.calls(), 0);
688
+ assert.equal(existsSync(f.runDir), false);
689
+ });
690
+ test('ordinary execution seals the shared reviewed plan and retains replayable costs without component adoption', async (t) => {
691
+ const f = setup(t), spendingBudget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
692
+ const base = ordinaryOptions(f, { executorTimeoutSeconds: 17, pairOrder: 'balanced', spendingBudget });
693
+ const preview = await runEvalCli(base);
694
+ assert.ok('plan' in preview);
695
+ const result = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
696
+ assert.equal(result.status, 'completed');
697
+ assert.ok('evidence' in result);
698
+ assert.equal(result.evidence.verified, true, result.evidence.reasons.join('; '));
699
+ assert.ok('costs' in result);
700
+ const native = JSON.parse(readFileSync(join(f.runDir, '_plan.json'), 'utf8'));
701
+ assert.deepEqual(native.details.reviewedPlan, preview.plan);
702
+ assert.equal(native.details.executorTimeoutSeconds, 17);
703
+ assert.equal(native.details.component, undefined);
704
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
705
+ for (const path of ['bench', 'old', 'new'])
706
+ rmSync(join(f.root, path), { recursive: true });
707
+ const replay = await reportEvalComponent(f.runDir, { replay: true });
708
+ assert.equal(replay.evidence.verified, true);
709
+ assert.ok('costs' in replay);
710
+ assert.deepEqual(replay.costs, result.costs);
711
+ assert.deepEqual(replay.spendingBudget?.limits, spendingBudget);
712
+ const output = join(f.root, 'portable');
713
+ await exportEvaluation(f.runDir, output, { yes: true, log: () => { } });
714
+ rmSync(f.runDir, { recursive: true });
715
+ const child = spawnSync(process.execPath, [join(output, 'reproduce.mjs')], { encoding: 'utf8', timeout: 30_000 });
716
+ assert.equal(child.status, 0, child.stderr);
717
+ const portable = JSON.parse(child.stdout);
718
+ assert.equal(portable.evidence.verified, true);
719
+ assert.deepEqual(portable.costs, result.costs);
720
+ assert.deepEqual(portable.spendingBudget.limits, spendingBudget);
721
+ assert.equal(portable.acceptance.eligibleForUpgrade, false);
722
+ assert.equal(f.calls(), 4);
723
+ });
724
+ test('ordinary and Agent no-Skill comparisons stop at the same budget line and keep the one invoked receipt', async (t) => {
725
+ const f = setup(t), spendingBudget = { input: 10, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 };
726
+ let calls = 0;
727
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-common-budget' }), run: async (_prompt, workdir) => {
728
+ calls++;
729
+ assert.equal(existsSync(join(workdir, 'project-skills/answer-skill')), false);
730
+ writeFileSync(join(workdir, 'answer.txt'), '1');
731
+ return { output: 'done', tokens: { input: 10, cachedInput: 6, output: 2 } };
732
+ } };
733
+ writeFileSync(f.requestPath, JSON.stringify({ ...f.body, baselineSkill: null, taskIds: ['fix'], maxCalls: 2, spendingBudget }));
734
+ const requestPreview = await runEvalComponent(f.requestPath, { ...f.options, executor, dryRun: true });
735
+ const request = await runEvalComponent(f.requestPath, { ...f.options, executor, dryRun: false, expectedPlanSha256: requestPreview.plan.sha256 });
736
+ const base = ordinaryOptions(f, { baselineSkillPath: undefined, taskIds: ['fix'], maxCalls: 2, spendingBudget, executor, runGroup: 'ordinary' });
737
+ const preview = await runEvalCli(base);
738
+ assert.ok('plan' in preview);
739
+ const ordinary = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
740
+ for (const result of [request, ordinary]) {
741
+ assert.equal(result.status, 'stopped');
742
+ assert.ok('spendingBudget' in result && result.spendingBudget);
743
+ assert.equal(result.spendingBudget.latestState.metrics.input.knownTotal, 10);
744
+ assert.ok(result.spendingBudget.latestState.reached.includes('input'));
745
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
746
+ }
747
+ assert.equal(calls, 2);
748
+ assert.equal(existsSync(join(f.runDir, 'fix/treatment/trial-1')), false);
749
+ assert.equal(existsSync(join(f.root, 'runs/ordinary/fix/treatment/trial-1')), false);
750
+ });
751
+ for (const [label, tokens] of [['missing cache', { input: 10, output: 2 }], ['partial', { input: 10, cachedInput: 6, output: 2 }]]) {
752
+ test(`ordinary ${label} usage cannot authorize a second budgeted invocation`, async (t) => {
753
+ const f = setup(t);
754
+ let calls = 0;
755
+ const executor = { describe: () => ({ kind: 'mock', model: 'offline-incomplete-budget' }), run: async (_prompt, workdir) => {
756
+ calls++;
757
+ writeFileSync(join(workdir, 'answer.txt'), '1');
758
+ return { output: 'done', tokens, ...(label === 'partial' ? { usageStatus: 'partial' } : {}) };
759
+ } };
760
+ const base = ordinaryOptions(f, { executor, spendingBudget: { input: 100, cachedInput: 100, uncachedInput: 100, output: 100, durationSeconds: 100 } });
761
+ const preview = await runEvalCli(base);
762
+ assert.ok('plan' in preview);
763
+ const result = await runEvalCli({ ...base, dryRun: false }, preview.plan.sha256);
764
+ assert.equal(result.status, 'stopped');
765
+ assert.equal(calls, 1);
766
+ assert.ok('spendingBudget' in result && result.spendingBudget);
767
+ assert.equal(result.spendingBudget.latestState.reason, 'FINAL_USAGE_MISSING');
768
+ assert.equal(result.acceptance.eligibleForUpgrade, false);
769
+ });
770
+ }
@@ -28,6 +28,14 @@ function numeric(value, label, min, max = Number.MAX_SAFE_INTEGER, integer = fal
28
28
  }
29
29
  return value;
30
30
  }
31
+ export function parseExecutorTimeoutSeconds(value = DEFAULT_CLI_TIMEOUT_MS / 1000, label = 'executorTimeoutSeconds') {
32
+ return numeric(value, label, 1, 3600, true);
33
+ }
34
+ export function parsePairOrder(value = 'baseline-first', label = 'pairOrder') {
35
+ if (value !== 'baseline-first' && value !== 'balanced')
36
+ throw new Error(`${label} must be baseline-first or balanced.`);
37
+ return value;
38
+ }
31
39
  export function parseAcceptancePolicy(value = {}) {
32
40
  const p = record(value, 'policy');
33
41
  if (p.schemaVersion === 2) {
@@ -79,18 +87,16 @@ export function parseEvalRequest(value, baseDir) {
79
87
  getAgent(agent);
80
88
  if (r.purpose !== 'development' && r.purpose !== 'validation')
81
89
  throw new Error('request.purpose must be development or validation.');
82
- if (r.pairOrder !== undefined && r.pairOrder !== 'baseline-first' && r.pairOrder !== 'balanced')
83
- throw new Error('request.pairOrder must be baseline-first or balanced.');
84
90
  const runGroup = text(r.runGroup, 'request.runGroup');
85
91
  if (!RUN_GROUP_PATTERN.test(runGroup))
86
92
  throw new Error('request.runGroup is invalid.');
87
93
  return { schemaVersion: 1,
88
- baselineSkill: resolve(baseDir, text(r.baselineSkill, 'request.baselineSkill')),
94
+ baselineSkill: r.baselineSkill === null ? null : resolve(baseDir, text(r.baselineSkill, 'request.baselineSkill (use null for no installed Skill)')),
89
95
  candidateSkill: resolve(baseDir, text(r.candidateSkill, 'request.candidateSkill')),
90
96
  bench: resolve(baseDir, text(r.bench, 'request.bench')),
91
97
  ...(r.taskIds !== undefined ? { taskIds: parseTaskIds(r.taskIds) } : {}),
92
- agent, purpose: r.purpose, pairOrder: r.pairOrder ?? 'baseline-first',
93
- executorTimeoutSeconds: numeric(r.executorTimeoutSeconds ?? DEFAULT_CLI_TIMEOUT_MS / 1000, 'request.executorTimeoutSeconds', 1, 3600, true),
98
+ agent, purpose: r.purpose, pairOrder: parsePairOrder(r.pairOrder, 'request.pairOrder'),
99
+ executorTimeoutSeconds: parseExecutorTimeoutSeconds(r.executorTimeoutSeconds, 'request.executorTimeoutSeconds'),
94
100
  trials: numeric(r.trials, 'request.trials', 1, 20, true),
95
101
  maxCalls: numeric(r.maxCalls, 'request.maxCalls', 1, Number.MAX_SAFE_INTEGER, true),
96
102
  ...(r.spendingBudget !== undefined ? { spendingBudget: parseSpendingBudget(r.spendingBudget) } : {}),
@@ -20,7 +20,7 @@ function tokenUsage(usage) {
20
20
  ...(cachedInput !== undefined ? { cachedInput } : {}),
21
21
  };
22
22
  }
23
- const DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
23
+ export const DEFAULT_API_TIMEOUT_MS = 2 * 60 * 1000;
24
24
  export class ApiExecutor {
25
25
  apiKey;
26
26
  model;
@@ -34,11 +34,12 @@ export class ApiExecutor {
34
34
  this.apiKey = options.apiKey;
35
35
  this.model = options.model ?? 'gpt-4o';
36
36
  this.baseUrl = (options.baseUrl ?? 'https://api.openai.com/v1').replace(/\/+$/, '');
37
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
37
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_API_TIMEOUT_MS;
38
38
  this.fetchImpl = options.fetchImpl ?? fetch;
39
39
  }
40
- static fromEnv(env = process.env) {
40
+ static fromEnv(env = process.env, options = {}) {
41
41
  return new ApiExecutor({
42
+ ...options,
42
43
  apiKey: env['SKILLFIT_API_KEY'] ?? env['OPENAI_API_KEY'],
43
44
  model: env['SKILLFIT_API_MODEL'],
44
45
  baseUrl: env['SKILLFIT_API_BASE_URL'],