skillfit 0.10.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +43 -8
  2. package/README.zh-CN.md +43 -8
  3. package/benches/README.md +6 -2
  4. package/dist/cli.js +153 -37
  5. package/dist/cli.test.js +94 -0
  6. package/dist/commands/bench-calibration.js +201 -0
  7. package/dist/commands/bench-calibration.test.js +237 -0
  8. package/dist/commands/bench-check-json.test.js +24 -3
  9. package/dist/commands/bench-draft.js +167 -0
  10. package/dist/commands/bench-draft.test.js +168 -0
  11. package/dist/commands/bench-manage.js +5 -4
  12. package/dist/commands/bench-source.js +101 -0
  13. package/dist/commands/bench-source.test.js +84 -0
  14. package/dist/commands/bench.js +227 -245
  15. package/dist/commands/bench.test.js +7 -3
  16. package/dist/commands/calibration-cli.test.js +145 -0
  17. package/dist/commands/eval-agent-preflight.test.js +269 -0
  18. package/dist/commands/eval-api-failure.test.js +46 -0
  19. package/dist/commands/eval-cli-usage.test.js +75 -0
  20. package/dist/commands/eval-cli.js +31 -0
  21. package/dist/commands/eval-component.js +52 -28
  22. package/dist/commands/eval-export-modes.test.js +350 -0
  23. package/dist/commands/eval-export.js +12 -4
  24. package/dist/commands/eval-interruption.test.js +26 -1
  25. package/dist/commands/eval-layout.test.js +126 -0
  26. package/dist/commands/eval-plan.js +37 -0
  27. package/dist/commands/eval-preflight.test.js +144 -1
  28. package/dist/commands/eval-report.js +18 -3
  29. package/dist/commands/eval-single-arm-replay.js +21 -0
  30. package/dist/commands/eval-single-arm-report.js +223 -0
  31. package/dist/commands/eval.js +113 -88
  32. package/dist/commands/evaluation-report.js +5 -0
  33. package/dist/commands/evaluation-report.test.js +243 -0
  34. package/dist/commands/npm-first-run.test.js +74 -0
  35. package/dist/commands/replay-cancellation.test.js +105 -0
  36. package/dist/commands/workflow-entrypoints.test.js +137 -0
  37. package/dist/harness/agent-preflight.js +196 -0
  38. package/dist/harness/bench-location.js +29 -0
  39. package/dist/harness/bench-location.test.js +33 -0
  40. package/dist/harness/bench.js +10 -4
  41. package/dist/harness/command.js +49 -0
  42. package/dist/harness/eval-audit.js +162 -17
  43. package/dist/harness/eval-budget.js +46 -2
  44. package/dist/harness/eval-budget.test.js +26 -1
  45. package/dist/harness/eval-component.test.js +163 -0
  46. package/dist/harness/eval-contract.js +11 -5
  47. package/dist/harness/evaluation-layout.js +30 -0
  48. package/dist/harness/executors/api.js +24 -10
  49. package/dist/harness/executors/api.test.js +57 -0
  50. package/dist/harness/executors/cli.js +15 -25
  51. package/dist/harness/executors/cli.test.js +33 -2
  52. package/dist/harness/experiment-session.js +23 -25
  53. package/dist/harness/experiment-session.test.js +8 -0
  54. package/dist/harness/hash.js +3 -1
  55. package/dist/harness/invocation-costs.js +72 -0
  56. package/dist/harness/judge-accounting.test.js +216 -0
  57. package/dist/harness/judge-audit.js +56 -0
  58. package/dist/harness/judge.js +86 -21
  59. package/dist/harness/replay-package.js +71 -5
  60. package/dist/harness/runner.js +44 -33
  61. package/dist/harness/runner.test.js +23 -0
  62. package/dist/harness/single-arm-audit.js +436 -0
  63. package/dist/harness/trigger.js +22 -4
  64. package/dist/harness/trigger.test.js +12 -0
  65. package/dist/harness/verifier-error.js +65 -0
  66. package/dist/harness/verifier-timeout.js +8 -0
  67. package/dist/harness/verifier-timeout.test.js +76 -0
  68. package/dist/harness/verifier.test.js +128 -0
  69. package/docs/bench-authoring.md +57 -12
  70. package/docs/bench-check-json.md +28 -5
  71. package/docs/bench-drafting.md +75 -0
  72. package/docs/case-management.md +12 -1
  73. package/docs/eval-agent-preflight.md +114 -0
  74. package/docs/eval-case-preflight.md +5 -0
  75. package/docs/eval-component.md +38 -10
  76. package/docs/eval-costs.md +70 -0
  77. package/docs/eval-planning.md +167 -0
  78. package/docs/evaluation-input-snapshots.md +22 -5
  79. package/docs/evaluation-interruption.md +22 -10
  80. package/docs/evaluation-reports.md +97 -3
  81. package/docs/experiment-workflow.md +7 -0
  82. package/docs/first-real-eval.md +75 -3
  83. package/docs/growth-roadmap-2026-10.md +51 -10
  84. package/docs/metrics.md +40 -3
  85. package/docs/plans/2026-10-17-workflow-foundations.md +99 -0
  86. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  87. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  88. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  89. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  90. package/docs/releases/0.10.1-signatures.txt +7 -0
  91. package/docs/releases/0.10.1-verification.json +90 -0
  92. package/docs/releases/0.10.1.md +37 -4
  93. package/docs/releases/0.11.0-ci-registry-install.json +130 -0
  94. package/docs/releases/0.11.0-feature-smoke.json +1576 -0
  95. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  96. package/docs/releases/0.11.0-local-attempt-1.json +24 -0
  97. package/docs/releases/0.11.0-local-attempt-1.log +19 -0
  98. package/docs/releases/0.11.0-local-registry-install.json +25 -0
  99. package/docs/releases/0.11.0-registry-metadata.json +33 -0
  100. package/docs/releases/0.11.0-signatures.txt +12 -0
  101. package/docs/releases/0.11.0-verification.json +95 -0
  102. package/docs/releases/0.11.0.md +90 -0
  103. package/docs/releases/0.12.0-feature-smoke.mjs +73 -0
  104. package/docs/releases/0.12.0.md +68 -0
  105. package/docs/replay-packages.md +38 -6
  106. package/docs/schemas/agent-preflight.schema.json +31 -0
  107. package/docs/schemas/calibration-plan.schema.json +22 -0
  108. package/docs/schemas/calibration-result.schema.json +17 -0
  109. package/docs/schemas/eval-request.schema.json +1 -1
  110. package/docs/schemas/eval-result.schema.json +3 -1
  111. package/docs/schemas/invocation-costs.schema.json +31 -0
  112. package/docs/schemas/judge-call.schema.json +22 -0
  113. package/docs/schemas/single-arm-report.schema.json +20 -0
  114. package/docs/schemas/verifier-error.schema.json +11 -0
  115. package/docs/sharing-results.md +3 -0
  116. package/docs/verifier-contract.md +108 -0
  117. package/package.json +1 -1
  118. package/skills/skillfit/SKILL.md +61 -8
@@ -0,0 +1,223 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { record, readComponentJson } from '../harness/eval-contract.js';
5
+ import { stoppedAccounting } from '../harness/eval-audit.js';
6
+ import { COST_METRICS } from '../harness/costs.js';
7
+ import { triggerMetrics } from '../harness/trigger.js';
8
+ import { agentEnvironmentReportLines } from '../harness/agent-preflight.js';
9
+ function text(value, label) {
10
+ if (typeof value !== 'string' || !value.trim())
11
+ throw new Error(`${label} must be a nonempty string.`);
12
+ return value;
13
+ }
14
+ function count(value, label, max = Number.MAX_SAFE_INTEGER) {
15
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > max)
16
+ throw new Error(`${label} must be a nonnegative safe integer no greater than ${max}.`);
17
+ return value;
18
+ }
19
+ function tasks(value) {
20
+ if (!Array.isArray(value) || !value.length)
21
+ throw new Error('Summary tasks must be a nonempty array.');
22
+ const result = value.map((task, i) => record(task, `tasks[${i}]`));
23
+ const ids = result.map(task => text(task.id, 'task.id'));
24
+ if (new Set(ids).size !== ids.length)
25
+ throw new Error('Summary task IDs must be unique.');
26
+ return result;
27
+ }
28
+ function experiment(value) {
29
+ const s = record(value, 'experiment');
30
+ if (s.schemaVersion !== 1 || !['completed', 'stopped', 'incomplete'].includes(String(s.status)))
31
+ throw new Error('Invalid experiment schema or status.');
32
+ const max = count(s.maxCalls, 'experiment.maxCalls'), planned = count(s.plannedCalls, 'experiment.plannedCalls', max);
33
+ const started = count(s.callsStarted, 'experiment.callsStarted', planned), finished = count(s.callsFinished, 'experiment.callsFinished', started);
34
+ if (!planned || (s.stopReason !== null && typeof s.stopReason !== 'string') || typeof s.planSha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(s.planSha256))
35
+ throw new Error('Invalid experiment metadata.');
36
+ if (s.status === 'completed' && (finished !== planned || s.stopReason !== null))
37
+ throw new Error('Completed experiment has unfinished calls or a stop reason.');
38
+ if (s.stopCode !== undefined && !['EXECUTION_FAILED', 'FINAL_USAGE_MISSING', 'SPENDING_BUDGET_REACHED'].includes(String(s.stopCode)))
39
+ throw new Error('Invalid experiment stopCode.');
40
+ return { schemaVersion: 1, status: s.status, plannedCalls: planned, maxCalls: max,
41
+ callsStarted: started, callsFinished: finished, stopReason: s.stopReason, planSha256: s.planSha256,
42
+ ...(s.stopCode === undefined ? {} : { stopCode: s.stopCode }) };
43
+ }
44
+ function trials(value) {
45
+ const n = count(value, 'trials', 20);
46
+ if (!n)
47
+ throw new Error('trials must be at least 1.');
48
+ return n;
49
+ }
50
+ function calibration(value, complete) {
51
+ if (value.inputMode !== 'snapshot' && value.inputMode !== 'workspace')
52
+ throw new Error('Calibration inputMode must be snapshot or workspace.');
53
+ const repetitions = trials(value.trials);
54
+ const rows = tasks(value.tasks).map(task => {
55
+ const completed = count(task.completed, 'task.completed', repetitions), errors = count(task.errors, 'task.errors', repetitions);
56
+ if (completed + errors > repetitions || (complete && completed + errors !== repetitions))
57
+ throw new Error('Calibration trial counts disagree with trials.');
58
+ const passes = count(task.passes, 'task.passes', completed), passRate = completed ? passes / completed : null;
59
+ const difficulty = passRate === null ? 'unmeasured' : passRate >= 0.9 ? 'saturated' : passRate <= 0.1 ? 'floor' : 'discriminative';
60
+ return { id: text(task.id, 'task.id'), passes, completed, errors, passRate, difficulty };
61
+ });
62
+ const completed = rows.reduce((n, row) => n + row.completed, 0), passes = rows.reduce((n, row) => n + row.passes, 0);
63
+ return { trials: repetitions, inputMode: value.inputMode, tasks: rows,
64
+ metrics: { taskCount: rows.length, measuredTasks: rows.filter(row => row.completed > 0).length,
65
+ discriminativeTasks: rows.filter(row => row.difficulty === 'discriminative').length,
66
+ passes, completed, errors: rows.reduce((n, row) => n + row.errors, 0), baselinePassRate: completed ? passes / completed : null } };
67
+ }
68
+ function tokens(value) {
69
+ if (value === null)
70
+ return null;
71
+ const pair = record(value, 'task.tokens');
72
+ return { input: count(pair.input, 'tokens.input'), output: count(pair.output, 'tokens.output') };
73
+ }
74
+ function trigger(value, complete) {
75
+ const repetitions = trials(value.trials);
76
+ const rows = tasks(value.tasks).map(task => {
77
+ if (typeof task.shouldTrigger !== 'boolean')
78
+ throw new Error('task.shouldTrigger must be boolean.');
79
+ const runs = count(task.runs, 'task.runs', repetitions), unknown = count(task.unknown, 'task.unknown', repetitions), errors = count(task.errors, 'task.errors', repetitions);
80
+ if (runs + unknown + errors > repetitions || (complete && runs + unknown + errors !== repetitions))
81
+ throw new Error('Trigger trial counts disagree with trials.');
82
+ if (task.triggerClass !== undefined && !['explicit', 'implicit', 'contextual'].includes(String(task.triggerClass)))
83
+ throw new Error('Invalid triggerClass.');
84
+ return { id: text(task.id, 'task.id'), shouldTrigger: task.shouldTrigger,
85
+ ...(task.triggerClass ? { triggerClass: task.triggerClass } : {}),
86
+ runs, fired: count(task.fired, 'task.fired', runs), unknown, errors, passes: count(task.passes, 'task.passes', runs + unknown), tokens: tokens(task.tokens) };
87
+ });
88
+ const metrics = JSON.parse(JSON.stringify(triggerMetrics(rows))), saved = record(value.metrics, 'trigger metrics');
89
+ // Reuse the frozen formulas and validate recorded fields. Older v1 additions
90
+ // may be absent; intervals can be derived from the retained counts, not new runs.
91
+ for (const key of Object.keys(metrics)) {
92
+ if (saved[key] !== undefined && !isDeepStrictEqual(saved[key], metrics[key]))
93
+ throw new Error(`Trigger metrics.${key} disagrees with saved task counts.`);
94
+ }
95
+ for (const key of ['recall', 'falseTriggerRate', 'precision', 'f1', 'positives', 'negatives'])
96
+ if (saved[key] === undefined)
97
+ throw new Error(`Missing trigger metrics.${key}.`);
98
+ const skill = record(value.skill, 'trigger skill'), bench = record(value.bench, 'trigger bench');
99
+ if (count(bench.taskCount, 'bench.taskCount') !== rows.length)
100
+ throw new Error('Trigger bench.taskCount disagrees with tasks.');
101
+ if (value.detection !== undefined && !['skill-tool', 'skill-read', 'unrecorded'].includes(String(value.detection)))
102
+ throw new Error('Invalid trigger detection.');
103
+ const competition = value.competition === undefined ? null : record(value.competition, 'competition');
104
+ if (competition && competition.mode !== 'alone' && competition.mode !== 'installed')
105
+ throw new Error('Invalid competition mode.');
106
+ return { trials: repetitions, skillName: text(skill.name, 'skill.name'), benchName: text(bench.name, 'bench.name'),
107
+ detection: value.detection ?? 'unrecorded', competition: competition?.mode ?? 'unrecorded', tasks: rows, metrics };
108
+ }
109
+ /** Descriptive single-arm reports never enter the paired acceptance protocol. */
110
+ export function readSingleArmReport(inputPath, options = {}) {
111
+ const input = resolve(inputPath), directory = statSync(input).isDirectory(), root = directory ? input : dirname(input);
112
+ const regular = join(root, 'manifest.json'), calibrated = join(root, '_calibration.json');
113
+ if (directory && existsSync(regular) && existsSync(calibrated))
114
+ throw new Error('Ambiguous run: both paired/trigger and calibration summaries exist.');
115
+ const source = directory ? existsSync(regular) ? regular : existsSync(calibrated) ? calibrated : null : input;
116
+ const data = source ? readComponentJson(source) : null, value = data ? record(data.value, 'summary') : null;
117
+ let mode = value?.mode === 'trigger' ? 'trigger'
118
+ : value?.schemaVersion === 1 && (basename(source) === '_calibration.json' || value.inputMode !== undefined) ? 'calibration' : null;
119
+ let plan = null;
120
+ if (!source || mode) {
121
+ if (existsSync(join(root, '_plan.json')))
122
+ plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
123
+ const planned = plan?.details ? record(plan.details, 'native plan details').mode : undefined;
124
+ if (!mode && (planned === 'trigger' || planned === 'calibration'))
125
+ mode = planned;
126
+ else if (mode && planned !== undefined && planned !== mode)
127
+ throw new Error('Summary type differs from the native plan.');
128
+ }
129
+ if (!mode)
130
+ return null;
131
+ if (options.replay || options.policyPath || options.recordsPath || options.benchDir)
132
+ throw new Error(`${mode} reports support saved summaries only; --replay, --policy, --records and --bench require a paired report.`);
133
+ if (value && value.schemaVersion !== 1)
134
+ throw new Error(`Unsupported ${mode} summary schemaVersion: ${String(value.schemaVersion)}.`);
135
+ let session = value?.experiment === undefined ? null : experiment(value.experiment);
136
+ if (existsSync(join(root, '_session.json'))) {
137
+ const native = experiment(readComponentJson(join(root, '_session.json')).value);
138
+ if (session && !isDeepStrictEqual(session, native))
139
+ throw new Error('Summary experiment differs from the saved session.');
140
+ session = native;
141
+ }
142
+ const status = value ? session?.status ?? 'reported' : session?.status === 'stopped' ? 'stopped' : 'incomplete';
143
+ const warnings = value?.warnings === undefined ? [] : value.warnings;
144
+ if (!Array.isArray(warnings) || warnings.some(w => typeof w !== 'string'))
145
+ throw new Error('Summary warnings must be strings.');
146
+ if (value && session && session.plannedCalls !== tasks(value.tasks).length * trials(value.trials))
147
+ throw new Error('Summary task/trial count differs from the declared call plan.');
148
+ const accounting = mode === 'calibration' && existsSync(join(root, '_calls.jsonl')) ? stoppedAccounting(root) : null;
149
+ if (accounting && accounting.populations.attempts.treatment.runs)
150
+ throw new Error('Calibration receipts contain an unexpected treatment invocation.');
151
+ const usage = accounting ? { ...accounting.populations.attempts.baseline,
152
+ startedAgentDispatches: accounting.startedAgentDispatches, invocationsWithUnknownReceipts: accounting.invocationsWithUnknownReceipts,
153
+ scope: 'Available baseline invocation receipts only; missing or invalid usage remains unknown. No paired comparison or billing estimate.' } : null;
154
+ const base = { schemaVersion: 1, status, runGroup: value ? text(value.runGroup, 'runGroup') : basename(root), session,
155
+ agentPreflight: plan?.details ? record(plan.details, 'native plan details').agentPreflight ?? null : null,
156
+ usage,
157
+ source: data && source ? { path: source, sha256: data.sha256, schemaVersion: 1 } : null,
158
+ warnings: [...warnings, ...(!value ? ['Final summary is missing; no aggregate metrics inferred from an unfinished run.'] : [])],
159
+ evidence: { verified: false, runDir: root, scope: 'saved-summary-only', reasons: ['Saved single-arm summary only; paired native audit and delivery replay do not apply.'] },
160
+ acceptance: { decision: 'inconclusive', eligibleForUpgrade: false, automaticUpgrade: false,
161
+ reasons: [{ code: 'NOT_A_PAIRED_COMPARISON', message: 'Calibration measures baseline difficulty; trigger mode measures discovery. Neither establishes a paired Skill improvement or authorizes an upgrade.' }] } };
162
+ if (mode === 'calibration')
163
+ return { ...base, kind: 'skillfit.calibration-report', evaluationType: 'calibration',
164
+ summary: value ? calibration(value, status === 'completed') : null };
165
+ return { ...base, kind: 'skillfit.trigger-report', evaluationType: 'trigger',
166
+ summary: value ? trigger(value, status === 'completed') : null };
167
+ }
168
+ const escape = (value) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
169
+ .replaceAll('\\', '\\\\').replaceAll('`', '\\`').replaceAll('*', '\\*').replaceAll('_', '\\_')
170
+ .replaceAll('[', '\\[').replaceAll(']', '\\]').replaceAll('|', '\\|').replaceAll('\n', ' ').replaceAll('\r', ' ');
171
+ const percent = (value) => value === null ? 'n/a' : `${(value * 100).toFixed(1)}%`;
172
+ export function renderSingleArmReport(report) {
173
+ const lines = [`# skillfit ${report.evaluationType} report: ${escape(report.runGroup)}`, '', `- State: ${report.status}`,
174
+ `- Evidence: ${report.evidence.verified ? 'verified native single-arm receipts' : 'unverified saved single-arm evidence'}; no paired efficacy or adoption decision.`, '- Eligible for upgrade: no', '- Automatic upgrade: no'];
175
+ for (const reason of report.evidence.reasons)
176
+ lines.push(`- Audit: ${escape(reason.replaceAll(report.evidence.runDir, '[run]'))}`);
177
+ if (report.session?.stopReason)
178
+ lines.push(`- Stop reason: ${escape(report.session.stopReason.replaceAll(report.evidence.runDir, '[run]'))}`);
179
+ lines.push(...agentEnvironmentReportLines(report.agentPreflight).map(line => `- ${escape(line)}`));
180
+ if (report.evaluationType === 'calibration' && report.summary) {
181
+ const { tasks, metrics } = report.summary;
182
+ lines.push('', '## Baseline difficulty', '', `- Baseline pass rate: ${metrics.passes}/${metrics.completed} (${percent(metrics.baselinePassRate)})`, `- Measured tasks: ${metrics.measuredTasks}/${metrics.taskCount}; discriminative tasks: ${metrics.discriminativeTasks}/${metrics.measuredTasks}`, `- Ungraded errors: ${metrics.errors}`, '', '| Task | Passes / completed | Pass rate | Errors | Difficulty |', '|---|---:|---:|---:|---|', ...tasks.map(t => `| ${escape(t.id)} | ${t.passes}/${t.completed} | ${percent(t.passRate)} | ${t.errors} | ${t.difficulty} |`), '', 'Completed runs exclude execution errors. Saturated >=90%; floor <=10%; otherwise discriminative; zero completed runs are unmeasured.', 'Baseline difficulty does not measure Skill benefit.');
183
+ }
184
+ else if (report.evaluationType === 'trigger' && report.summary) {
185
+ const { metrics: m, tasks, detection, competition } = report.summary;
186
+ const ci = (value, interval) => `${percent(value)}${interval ? ` [${percent(interval.lo)}, ${percent(interval.hi)}]` : ''}`;
187
+ lines.push('', '## Trigger metrics', '', `- Skill: ${escape(report.summary.skillName)}; bench: ${escape(report.summary.benchName)}`, `- Detection: ${detection}; competition: ${competition}`, `- Recall: ${ci(m.recall, m.recallCi95)} (${m.positives.fired}/${m.positives.runs})`, `- False-trigger rate: ${ci(m.falseTriggerRate, m.falseTriggerRateCi95)} (${m.negatives.fired}/${m.negatives.runs})`, `- Precision: ${ci(m.precision, m.precisionCi95)}`, `- F1: ${m.f1 === null ? 'n/a' : m.f1.toFixed(3)} (no confidence interval)`, '', '| Task | Expected trigger | Fired / observed | Unknown | Errors | Task passes |', '|---|---|---:|---:|---:|---:|', ...tasks.map(t => `| ${escape(t.id)} | ${t.shouldTrigger ? 'yes' : 'no'} | ${t.fired}/${t.runs} | ${t.unknown} | ${t.errors} | ${t.passes} |`));
188
+ for (const label of ['explicit', 'implicit', 'contextual']) {
189
+ const group = m.classRecall?.[label];
190
+ if (group)
191
+ lines.push(`- ${label} recall: ${ci(group.recall, group.recallCi95)} (${group.fired}/${group.runs})`);
192
+ else if (tasks.some(t => t.shouldTrigger && t.triggerClass === label))
193
+ lines.push(`- ${label} recall: n/a (no observed detections)`);
194
+ }
195
+ if (detection === 'skill-read')
196
+ lines.push('- A SKILL.md read is an observation, not a Skill-invocation event.');
197
+ if (competition === 'alone')
198
+ lines.push('- Recall is an upper bound with the tested Skill installed alone.');
199
+ lines.push('- Rates exclude unknown detections and execution errors; zero denominators are n/a. Intervals use Wilson 95%.', '- Recorded token totals are historical aggregates, not complete final/partial/unknown costs or a bill; missing cache partitions remain unknown.');
200
+ if (m.tokens)
201
+ lines.push(`- Recorded input/output tokens: ${m.tokens.input}/${m.tokens.output}`);
202
+ }
203
+ else
204
+ lines.push('', 'Final summary is missing. Metrics are unavailable; the run is not a completed comparison.');
205
+ if (report.evaluationType === 'calibration' || report.usage) {
206
+ lines.push('', `## Retained ${report.evaluationType === 'calibration' ? 'baseline' : 'Agent'} usage`, '');
207
+ if (report.usage) {
208
+ const u = report.usage;
209
+ lines.push(`- Started agent dispatches: ${u.startedAgentDispatches}; missing or invalid receipts: ${u.invocationsWithUnknownReceipts}`, '| Measure | Known total | Final/partial/unknown |', '|---|---:|---:|');
210
+ for (const metric of COST_METRICS) {
211
+ const m = u.metrics[metric], c = m.coverage;
212
+ const total = c.unknown === u.runs ? 'unrecorded' : c.final === u.runs ? String(m.knownTotal) : `>= ${m.knownTotal}`;
213
+ lines.push(`| ${metric} | ${total} | ${c.final}/${c.partial}/${c.unknown} |`);
214
+ }
215
+ lines.push('Available receipt totals only; >= is a lower bound. Unknown usage is not zero; no bill or paired cost change is inferred.');
216
+ }
217
+ else
218
+ lines.push('Invocation usage is unrecorded; no spending totals inferred from task success counts.');
219
+ }
220
+ for (const warning of report.warnings)
221
+ lines.push(`- Warning: ${escape(warning)}`);
222
+ return lines.join('\n') + '\n';
223
+ }
@@ -1,58 +1,31 @@
1
- import { existsSync, readdirSync, statSync } from 'node:fs';
1
+ import { existsSync, statSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
4
  import { getAgent } from '../agents.js';
6
5
  import { loadBench, selectBenchTasks } from '../harness/bench.js';
6
+ import { resolveBenchDir } from '../harness/bench-location.js';
7
7
  import { RUN_GROUP_PATTERN } from '../harness/constants.js';
8
8
  import { ExperimentSession, validateCallBudget } from '../harness/experiment-session.js';
9
- import { ApiExecutor } from '../harness/executors/api.js';
10
- import { CliExecutor, DEFAULT_CLI_TIMEOUT_MS } from '../harness/executors/cli.js';
9
+ import { ApiExecutor, DEFAULT_API_TIMEOUT_MS } from '../harness/executors/api.js';
10
+ import { CliExecutor } from '../harness/executors/cli.js';
11
11
  import { listFilesRecursive } from '../harness/hash.js';
12
12
  import { assertNativeDiffFixtures, nativeDiffDescriptor } from '../harness/native-diff.js';
13
13
  import { assertInstalledSkillFixtures, assertSkillRevisionTargets, collectInstalledSkillTarget } from '../harness/installed-skill.js';
14
14
  import { assertInputModeSupported } from '../harness/prompt.js';
15
15
  import { CONCLUSIVE_TASKS, CONCLUSIVE_TRIALS, renderSummary } from '../harness/report.js';
16
- import { runExperiment } from '../harness/runner.js';
16
+ import { runExperiment, withSampling } from '../harness/runner.js';
17
17
  import { collectInstalledSkillFingerprint } from '../harness/bundle.js';
18
18
  import { installedUserSkills } from '../harness/receipts.js';
19
19
  import { collectEvaluationTarget } from '../harness/target.js';
20
20
  import { renderTriggerSummary, runTriggerExperiment, } from '../harness/trigger.js';
21
+ import { parseExecutorTimeoutSeconds, parsePairOrder } from '../harness/eval-contract.js';
21
22
  import { parseSpendingBudget } from '../harness/eval-budget.js';
22
23
  import { withEvaluationInterrupts, throwIfEvaluationInterrupted } from '../harness/interruption.js';
23
24
  import { CASE_PREFLIGHT_POLICY, checkEvalCases } from './eval-preflight.js';
24
25
  import { INPUT_SNAPSHOT_POLICY } from '../harness/input-snapshot.js';
26
+ import { assertEvaluationOutputLayout } from '../harness/evaluation-layout.js';
27
+ import { inspectAgentEnvironment, assertAgentEnvironment, assertAgentEnvironmentUnchanged, renderAgentEnvironment } from '../harness/agent-preflight.js';
25
28
  export const DEFAULT_EVAL_TRIALS = 5;
26
- function bundledBenchesRoot() {
27
- return fileURLToPath(new URL('../../benches', import.meta.url));
28
- }
29
- function resolveBenchDir(bench) {
30
- const root = bundledBenchesRoot();
31
- const candidates = existsSync(root)
32
- ? readdirSync(root)
33
- .map((entry) => join(root, entry))
34
- .filter((dir) => statSync(dir).isDirectory() && existsSync(join(dir, 'bench.json')))
35
- : [];
36
- if (bench) {
37
- const dir = resolve(bench);
38
- if (existsSync(join(dir, 'bench.json'))) {
39
- return dir;
40
- }
41
- const byName = candidates.find((candidate) => candidate.split(/[\\/]/).pop() === bench);
42
- if (byName) {
43
- return byName;
44
- }
45
- throw new Error(`Not a bench directory (missing bench.json): ${dir}`);
46
- }
47
- if (candidates.length === 1 && candidates[0]) {
48
- return candidates[0];
49
- }
50
- if (candidates.length === 0) {
51
- throw new Error(`No bundled benches found under ${root}; pass --bench <path>`);
52
- }
53
- const names = candidates.map((dir) => ` --bench ${dir.split(/[\\/]/).pop() ?? dir}`).join('\n');
54
- throw new Error(`More than one bundled bench is available; pick one explicitly:\n${names}`);
55
- }
56
29
  function resolveExecutor(agent, target, installed = false, executorTimeoutSeconds) {
57
30
  if (agent) {
58
31
  const definition = getAgent(agent);
@@ -62,7 +35,7 @@ function resolveExecutor(agent, target, installed = false, executorTimeoutSecond
62
35
  ...(installed && definition.headless.streamJson ? { triggerSkillName: target.name } : {}),
63
36
  });
64
37
  }
65
- return ApiExecutor.fromEnv();
38
+ return ApiExecutor.fromEnv(process.env, executorTimeoutSeconds === undefined ? {} : { timeoutMs: executorTimeoutSeconds * 1000 });
66
39
  }
67
40
  /**
68
41
  * An API executor has no filesystem access, so it cannot satisfy a `verifierKind: "command"` task.
@@ -84,23 +57,19 @@ function assertExecutorSupportsBench(executor, bench) {
84
57
  'would be written and both arms would score 0. Use --agent <id> for a CLI executor that works in the run ' +
85
58
  'directory, or re-grade those tasks as verifierKind "output".');
86
59
  }
87
- function resolveJudge(judgeAgent) {
60
+ function resolveJudge(judgeAgent, timeoutSeconds) {
88
61
  const flag = process.env['SKILLFIT_JUDGE'];
89
62
  if (!judgeAgent && (!flag || flag === '0' || flag === 'false'))
90
63
  return null;
91
64
  if (judgeAgent) {
92
- return CliExecutor.forAgent(judgeAgent);
93
- }
94
- try {
95
- return new ApiExecutor({
96
- apiKey: process.env['SKILLFIT_JUDGE_API_KEY'] ?? process.env['SKILLFIT_API_KEY'] ?? process.env['OPENAI_API_KEY'],
97
- model: process.env['SKILLFIT_JUDGE_MODEL'] ?? process.env['SKILLFIT_API_MODEL'],
98
- baseUrl: process.env['SKILLFIT_JUDGE_BASE_URL'] ?? process.env['SKILLFIT_API_BASE_URL'],
99
- });
100
- }
101
- catch {
102
- return null;
65
+ return CliExecutor.forAgent(judgeAgent, timeoutSeconds === undefined ? {} : { timeoutMs: timeoutSeconds * 1000 });
103
66
  }
67
+ return new ApiExecutor({
68
+ apiKey: process.env['SKILLFIT_JUDGE_API_KEY'] ?? process.env['SKILLFIT_API_KEY'] ?? process.env['OPENAI_API_KEY'],
69
+ model: process.env['SKILLFIT_JUDGE_MODEL'] ?? process.env['SKILLFIT_API_MODEL'],
70
+ baseUrl: process.env['SKILLFIT_JUDGE_BASE_URL'] ?? process.env['SKILLFIT_API_BASE_URL'],
71
+ ...(timeoutSeconds === undefined ? {} : { timeoutMs: timeoutSeconds * 1000 }),
72
+ });
104
73
  }
105
74
  function defaultRunGroup(now = new Date()) {
106
75
  const pad2 = (value) => String(value).padStart(2, '0');
@@ -108,6 +77,16 @@ function defaultRunGroup(now = new Date()) {
108
77
  const time = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
109
78
  return `eval-${date}-${time}`;
110
79
  }
80
+ function inspectEvalAgent(options, target, executor, judge, capabilityError, resolutionError, judgeError) {
81
+ const roles = [{ role: 'agent', definition: options.agent ? getAgent(options.agent) : undefined,
82
+ executor: executor?.describe() ?? null, injected: options.executor !== undefined, resolutionError }];
83
+ if (judge || judgeError)
84
+ roles.push({ role: 'judge', definition: options.judgeAgent ? getAgent(options.judgeAgent) : undefined,
85
+ executor: judge?.describe() ?? null, injected: options.judgeExecutor != null, resolutionError: judgeError });
86
+ return inspectAgentEnvironment({ roles, mode: options.mode ?? 'inject', target, capabilityError,
87
+ spendingBudget: options.spendingBudget !== undefined,
88
+ homeDir: options.sessionOptions?.homeDir, env: options.sessionOptions?.env });
89
+ }
111
90
  function sessionFor(options, bench, target, trials, runsRoot, runGroup, armNames, plannedCalls, details, baselineTarget) {
112
91
  if (!RUN_GROUP_PATTERN.test(runGroup))
113
92
  throw new Error(`Invalid run group: ${runGroup}`);
@@ -144,6 +123,8 @@ function renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup,
144
123
  lines.push(`Baseline : ${baselineTarget.name} (${baselineTarget.files.length} files, bundle sha256 ${baselineTarget.sha256.slice(0, 12)}…)`);
145
124
  lines.push('Compare : previous Skill in baseline vs target Skill in treatment; measures revision effects, not benefit over no Skill');
146
125
  }
126
+ else if (inputMode === 'workspace' && target.kind === 'skill')
127
+ lines.push('Baseline : no Skill installed by the harness (inherited configuration still applies)');
147
128
  if (target.kind !== 'skill') {
148
129
  lines.push(' applied as project files; treatment material is never injected into the prompt');
149
130
  }
@@ -205,17 +186,21 @@ function renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, i
205
186
  return lines.join('\n');
206
187
  }
207
188
  async function runEvalTrigger(options, bench, skill, trials, log) {
189
+ if (options.judgeAgent || options.judgeExecutor)
190
+ throw new Error('Trigger evaluation does not use a judge.');
191
+ const executorTimeoutSeconds = parseExecutorTimeoutSeconds(options.executorTimeoutSeconds);
192
+ const spendingBudget = options.spendingBudget === undefined ? undefined : parseSpendingBudget(options.spendingBudget);
208
193
  let executor = options.executor ?? null;
194
+ let resolutionError;
209
195
  if (!executor) {
210
196
  if (!options.agent) {
211
197
  throw new Error('trigger mode requires --agent (a CLI executor with trigger detection); API executors cannot measure skill triggering.');
212
198
  }
213
199
  try {
214
- executor = CliExecutor.forAgent(options.agent, { triggerSkillName: skill.name });
200
+ executor = CliExecutor.forAgent(options.agent, { triggerSkillName: skill.name, timeoutMs: executorTimeoutSeconds * 1000 });
215
201
  }
216
202
  catch (error) {
217
- if (!options.dryRun)
218
- throw error;
203
+ resolutionError = error.message;
219
204
  log(`Note: ${error.message}`);
220
205
  }
221
206
  }
@@ -225,8 +210,11 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
225
210
  const runGroup = options.runGroup ?? defaultRunGroup();
226
211
  const plannedCalls = bench.tasks.filter(task => task.shouldTrigger !== undefined).length * trials;
227
212
  const maxCalls = validateCallBudget(plannedCalls, options.maxCalls);
213
+ const inspect = () => inspectEvalAgent(options, skill, executor, null, undefined, resolutionError);
214
+ const agentPreflight = inspect();
228
215
  if (!RUN_GROUP_PATTERN.test(runGroup))
229
216
  throw new Error(`Invalid run group: ${runGroup}`);
217
+ assertEvaluationOutputLayout(join(runsRoot, runGroup), { benchDir: bench.dir, targetDirs: [skill.sourceDir] });
230
218
  const competitors = options.competeInstalled && options.agent
231
219
  ? installedUserSkills(getAgent(options.agent), options.sessionOptions?.homeDir ?? homedir(), options.sessionOptions?.env ?? process.env)
232
220
  .filter((entry) => entry.name !== skill.name)
@@ -236,13 +224,28 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
236
224
  const competeLine = competitors.length === 0
237
225
  ? 'Compete : alone (recall is an upper bound)'
238
226
  : `Compete : ${competitors.map((entry) => entry.name).join(', ')}`;
227
+ const installedFingerprint = collectInstalledSkillFingerprint(skill.sourceDir);
228
+ const competition = { mode: competitors.length ? 'installed' : 'alone', skills: competitors };
229
+ options.onPlan?.({ mode: 'trigger', target: { kind: 'skill', name: skill.name, sourceDir: skill.sourceDir,
230
+ sha256: skill.sha256, files: skill.files }, baseline: null,
231
+ bench: { name: bench.name, dir: bench.dir, sha256: bench.contentSha256, taskIds: bench.tasks.map(task => task.id) },
232
+ executor: executor?.describe() ?? null, judge: null, inputMode: 'workspace', installDir: installDir ?? null,
233
+ trials, plannedCalls, maxCalls, outputDir: join(runsRoot, runGroup),
234
+ agentPreflight, casePreflight: { ...CASE_PREFLIGHT_POLICY, status: 'pending' }, inputSnapshot: { ...INPUT_SNAPSHOT_POLICY },
235
+ executorTimeoutSeconds, ...(spendingBudget ? { spendingBudget } : {}),
236
+ installedFingerprint: { sha256: installedFingerprint.sha256, files: installedFingerprint.files }, competition, detection });
239
237
  if (options.dryRun) {
240
238
  log(renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, installDir));
239
+ log(renderAgentEnvironment(agentPreflight));
241
240
  log('Case preflight: pending; required before execution. Dry run does not execute verifiers or oracles.');
242
241
  log(competeLine);
243
242
  log(`Calls : ${plannedCalls} planned; ceiling ${maxCalls} (agent calls only)`);
243
+ log(`Agent deadline: ${executorTimeoutSeconds}s per invocation`);
244
+ if (spendingBudget)
245
+ log(`Spending stop lines: ${JSON.stringify(spendingBudget)}; checked between calls, in-flight overshoot remains possible`);
244
246
  return null;
245
247
  }
248
+ assertAgentEnvironment(agentPreflight);
246
249
  if (!executor) {
247
250
  throw new Error('No executor available for trigger mode; pass --agent.');
248
251
  }
@@ -254,10 +257,19 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
254
257
  throw new Error(`Run group directory already exists: ${join(runsRoot, runGroup)}`);
255
258
  const eligible = { ...bench, tasks: bench.tasks.filter(t => t.shouldTrigger !== undefined) };
256
259
  const casePreflight = await checkEvalCases(eligible, [skill], false, log);
260
+ assertAgentEnvironmentUnchanged(agentPreflight, inspect());
261
+ if (collectInstalledSkillFingerprint(skill.sourceDir).sha256 !== installedFingerprint.sha256 ||
262
+ competitors.some(entry => collectInstalledSkillFingerprint(entry.sourceDir).sha256 !== entry.sha256)) {
263
+ throw new Error('Installed Skill resources changed during case preflight; create a fresh plan. No calls started.');
264
+ }
257
265
  throwIfEvaluationInterrupted();
258
266
  log(renderTriggerPlan(bench, skill, executor, trials, runsRoot, runGroup, installDir).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
259
267
  log(competeLine);
260
- const session = sessionFor(options, bench, skill, trials, runsRoot, runGroup, ['installed'], plannedCalls, { mode: 'trigger', trials, executor: executor.describe(), casePreflight });
268
+ log(renderAgentEnvironment(agentPreflight));
269
+ const session = sessionFor(options, bench, skill, trials, runsRoot, runGroup, ['installed'], plannedCalls, { mode: 'trigger', trials, executor: executor.describe(), casePreflight, agentPreflight,
270
+ skillInstallDir: installDir, executorTimeoutSeconds, competition, detection,
271
+ ...(options.reviewedPlan ? { reviewedPlan: options.reviewedPlan } : {}),
272
+ ...(spendingBudget ? { spendingBudget } : {}) });
261
273
  let manifest;
262
274
  try {
263
275
  manifest = await runTriggerExperiment({
@@ -271,6 +283,7 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
271
283
  skillInstallDir: installDir,
272
284
  competitors,
273
285
  detection,
286
+ ...(spendingBudget ? { spendingBudget } : {}),
274
287
  log,
275
288
  });
276
289
  throwIfEvaluationInterrupted();
@@ -285,14 +298,8 @@ async function runEvalTrigger(options, bench, skill, trials, log) {
285
298
  });
286
299
  }
287
300
  export async function runEval(options) {
288
- if (options.spendingBudget !== undefined && options.mode === 'trigger')
289
- throw new Error('spendingBudget applies only to paired evaluations.');
290
- const executorTimeoutSeconds = options.executorTimeoutSeconds ?? DEFAULT_CLI_TIMEOUT_MS / 1000;
291
- if (!Number.isSafeInteger(executorTimeoutSeconds) || executorTimeoutSeconds < 1 || executorTimeoutSeconds > 3600) {
292
- throw new Error('executorTimeoutSeconds must be an integer between 1 and 3600.');
293
- }
294
- if (options.executorTimeoutSeconds !== undefined && !options.agent && !options.executor)
295
- throw new Error('executorTimeoutSeconds requires a CLI agent.');
301
+ const executorTimeoutSeconds = parseExecutorTimeoutSeconds(options.executorTimeoutSeconds ??
302
+ (!options.agent && !options.executor ? DEFAULT_API_TIMEOUT_MS / 1000 : undefined));
296
303
  const log = options.log ?? ((msg) => console.log(msg));
297
304
  const installed = options.mode === 'installed';
298
305
  if (options.baselineSkillPath !== undefined && !installed) {
@@ -303,9 +310,6 @@ export async function runEval(options) {
303
310
  }
304
311
  const inputMode = options.inputMode ?? (installed ? 'workspace' : 'snapshot');
305
312
  assertInputModeSupported(inputMode, null);
306
- if (inputMode === 'workspace' && !options.agent && !options.executor) {
307
- throw new Error('workspace input requires --agent <id> for a CLI executor; API keys do not provide filesystem access.');
308
- }
309
313
  if (options.mode === 'trigger' && options.inputMode !== undefined) {
310
314
  throw new Error('--input applies only to paired modes; trigger mode already presents files on disk.');
311
315
  }
@@ -341,8 +345,6 @@ export async function runEval(options) {
341
345
  assertNativeDiffFixtures(bench);
342
346
  }
343
347
  if ((options.mode ?? 'inject') === 'trigger') {
344
- if (options.executorTimeoutSeconds !== undefined)
345
- throw new Error('executorTimeoutSeconds is only available for paired experiments.');
346
348
  if (options.pairOrder !== undefined)
347
349
  throw new Error('pairOrder is only available for paired experiments.');
348
350
  if (target.kind !== 'skill') {
@@ -350,9 +352,6 @@ export async function runEval(options) {
350
352
  }
351
353
  return runEvalTrigger(options, bench, target, trials, log);
352
354
  }
353
- if (target.kind !== 'skill' && !options.agent && !options.executor) {
354
- throw new Error(`${target.kind} experiments require --agent because API executors do not load project configuration files.`);
355
- }
356
355
  if (target.kind !== 'skill' && options.agent) {
357
356
  const agent = getAgent(options.agent);
358
357
  const expected = (target.kind === 'mcp' ? agent.mcp.projectFiles : agent.rules.projectFiles)
@@ -372,23 +371,43 @@ export async function runEval(options) {
372
371
  }
373
372
  }
374
373
  let executor = null;
374
+ let resolutionError;
375
375
  try {
376
- executor = options.executor ?? resolveExecutor(options.agent, target, installed, options.executorTimeoutSeconds);
376
+ executor = options.executor ?? resolveExecutor(options.agent, target, installed, executorTimeoutSeconds);
377
377
  }
378
378
  catch (error) {
379
- if (!options.dryRun)
380
- throw error;
379
+ resolutionError = error.message;
381
380
  log(`Note: ${error.message}`);
382
381
  }
383
- assertExecutorSupportsBench(executor, bench);
384
- assertInputModeSupported(inputMode, executor);
385
- if (target.kind !== 'skill' && executor?.describe().kind === 'api') {
386
- throw new Error(`${target.kind} experiments require a CLI executor; API executors cannot load project configuration files.`);
382
+ let capabilityError;
383
+ try {
384
+ if (inputMode === 'workspace' && !options.agent && !options.executor) {
385
+ throw new Error('workspace input requires --agent <id> for a CLI executor; API keys do not provide filesystem access.');
386
+ }
387
+ if (target.kind !== 'skill' && !options.agent && !options.executor) {
388
+ throw new Error(`${target.kind} experiments require --agent because API executors do not load project configuration files.`);
389
+ }
390
+ assertExecutorSupportsBench(executor, bench);
391
+ assertInputModeSupported(inputMode, executor);
392
+ if (target.kind !== 'skill' && executor?.describe().kind === 'api') {
393
+ throw new Error(`${target.kind} experiments require a CLI executor; API executors cannot load project configuration files.`);
394
+ }
395
+ }
396
+ catch (error) {
397
+ capabilityError = error.message;
398
+ }
399
+ let judge = null, judgeError;
400
+ try {
401
+ judge = options.judgeExecutor !== undefined ? options.judgeExecutor : resolveJudge(options.judgeAgent, executorTimeoutSeconds);
402
+ }
403
+ catch (error) {
404
+ judgeError = error.message;
387
405
  }
388
- const judge = options.judgeExecutor !== undefined ? options.judgeExecutor : resolveJudge(options.judgeAgent);
406
+ const inspect = () => inspectEvalAgent(options, target, executor, judge, capabilityError, resolutionError, judgeError);
407
+ const agentPreflight = inspect();
408
+ if (capabilityError)
409
+ assertAgentEnvironment(agentPreflight);
389
410
  const spendingBudget = options.spendingBudget === undefined ? undefined : parseSpendingBudget(options.spendingBudget);
390
- if (spendingBudget && judge)
391
- throw new Error('spendingBudget requires a paired evaluation without a judge; judge usage is not covered.');
392
411
  if (options.judgeAgent && options.judgeAgent === options.agent) {
393
412
  log('Warning: judge and executor are the same agent — self-preference bias risk (docs/metrics.md L4).');
394
413
  }
@@ -396,32 +415,34 @@ export async function runEval(options) {
396
415
  const runGroup = options.runGroup ?? defaultRunGroup();
397
416
  const plannedCalls = bench.tasks.length * trials * (judge ? 4 : 2);
398
417
  const maxCalls = validateCallBudget(plannedCalls, options.maxCalls);
399
- const pairOrder = options.pairOrder ?? 'baseline-first';
400
- if (pairOrder !== 'baseline-first' && pairOrder !== 'balanced')
401
- throw new Error('pairOrder must be baseline-first or balanced.');
418
+ const pairOrder = parsePairOrder(options.pairOrder);
402
419
  if (!RUN_GROUP_PATTERN.test(runGroup))
403
420
  throw new Error(`Invalid run group: ${runGroup}`);
421
+ assertEvaluationOutputLayout(join(runsRoot, runGroup), { benchDir: bench.dir,
422
+ targetDirs: [target.sourceDir, ...(baselineTarget ? [baselineTarget.sourceDir] : [])] });
404
423
  options.onPlan?.({
424
+ mode: installed ? 'installed' : 'inject',
425
+ agentPreflight,
405
426
  casePreflight: { ...CASE_PREFLIGHT_POLICY, status: 'pending' },
406
427
  inputSnapshot: { ...INPUT_SNAPSHOT_POLICY },
407
- target: { name: target.name, sourceDir: target.sourceDir, sha256: target.sha256, files: target.files },
428
+ target: { kind: target.kind, name: target.name, sourceDir: target.sourceDir, sha256: target.sha256, files: target.files },
408
429
  baseline: baselineTarget ? { name: baselineTarget.name, sourceDir: baselineTarget.sourceDir, sha256: baselineTarget.sha256, files: baselineTarget.files } : null,
409
430
  bench: { name: bench.name, dir: bench.dir, sha256: bench.contentSha256, taskIds: bench.tasks.map(t => t.id) },
410
- executor: executor?.describe() ?? null, judge: judge?.describe() ?? null, inputMode,
431
+ executor: executor ? withSampling(executor.describe()) : null, judge: judge ? withSampling(judge.describe()) : null, inputMode,
411
432
  installDir: skillInstallDir ?? null, trials, plannedCalls, maxCalls, pairOrder,
412
433
  ...(spendingBudget ? { spendingBudget } : {}),
413
434
  ...(installed ? { nativeDiffTool: nativeDiffDescriptor() } : {}),
414
- ...(options.agent || options.executorTimeoutSeconds !== undefined ? { executorTimeoutSeconds } : {}), outputDir: join(runsRoot, runGroup),
435
+ executorTimeoutSeconds, outputDir: join(runsRoot, runGroup),
415
436
  });
416
437
  if (options.dryRun) {
417
438
  log(renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup, inputMode, baselineTarget));
439
+ log(renderAgentEnvironment(agentPreflight));
418
440
  log('Case preflight: pending; required before execution. Dry run does not execute verifiers or oracles.');
419
441
  log(`Calls : ${plannedCalls} planned; ceiling ${maxCalls} (includes both judge orders when enabled)`);
420
442
  log(`Pair order: ${pairOrder}; arms remain adjacent`);
421
443
  if (spendingBudget)
422
444
  log(`Spending stop lines: ${JSON.stringify(spendingBudget)}; checked between calls, in-flight overshoot remains possible`);
423
- if (options.agent || options.executorTimeoutSeconds !== undefined)
424
- log(`Agent deadline: ${executorTimeoutSeconds}s per invocation in both arms`);
445
+ log(`Agent deadline: ${executorTimeoutSeconds}s per invocation in both arms`);
425
446
  if (skillInstallDir) {
426
447
  log('Tool : native untracked-file diff helper in both arms (version 1; environment correction)');
427
448
  log('Delivery : complete Skill resources installed ' + (baselineTarget ? 'in both conditions' : 'only in treatment') + ' at ' + skillInstallDir + '/' + target.name);
@@ -429,6 +450,7 @@ export async function runEval(options) {
429
450
  }
430
451
  return null;
431
452
  }
453
+ assertAgentEnvironment(agentPreflight);
432
454
  if (!executor) {
433
455
  throw new Error('No executor available; pass --agent or set SKILLFIT_API_KEY.');
434
456
  }
@@ -436,12 +458,15 @@ export async function runEval(options) {
436
458
  if (existsSync(join(runsRoot, runGroup)))
437
459
  throw new Error(`Run group directory already exists: ${join(runsRoot, runGroup)}`);
438
460
  const casePreflight = await checkEvalCases(bench, [target, ...(baselineTarget ? [baselineTarget] : [])], installed, log);
461
+ assertAgentEnvironmentUnchanged(agentPreflight, inspect());
439
462
  throwIfEvaluationInterrupted();
440
463
  log(renderPlan(bench, target, executor, judge, trials, runsRoot, runGroup, inputMode, baselineTarget).replace(' (dry run)', '').replace(' (not created)', '').replace('Dry run — nothing was written.', `Calls : ${plannedCalls} planned; ceiling ${maxCalls}`));
441
- const session = sessionFor(options, bench, target, trials, runsRoot, runGroup, ['baseline', 'treatment'], plannedCalls, { mode: installed ? 'installed' : 'inject', inputMode, trials, pairOrder, casePreflight,
464
+ log(renderAgentEnvironment(agentPreflight));
465
+ const session = sessionFor(options, bench, target, trials, runsRoot, runGroup, ['baseline', 'treatment'], plannedCalls, { mode: installed ? 'installed' : 'inject', inputMode, trials, pairOrder, casePreflight, agentPreflight,
466
+ ...(options.reviewedPlan ? { reviewedPlan: options.reviewedPlan } : {}),
442
467
  ...(spendingBudget ? { spendingBudget } : {}),
443
468
  ...(installed ? { nativeDiffTool: nativeDiffDescriptor() } : {}),
444
- ...(options.agent || options.executorTimeoutSeconds !== undefined ? { executorTimeoutSeconds } : {}), executor: executor.describe(), judge: judge?.describe() ?? null,
469
+ executorTimeoutSeconds, executor: executor.describe(), judge: judge?.describe() ?? null,
445
470
  ...(options.component ? { component: options.component } : {}),
446
471
  ...(baselineTarget ? { baselineTarget: { name: baselineTarget.name, sourceDir: baselineTarget.sourceDir, bundleSha256: baselineTarget.sha256, files: baselineTarget.files } } : {}) }, baselineTarget);
447
472
  let manifest;
@@ -0,0 +1,5 @@
1
+ import { reportEvalComponent } from './eval-component.js';
2
+ /** One read-only dispatcher for the public Markdown and JSON report entry points. */
3
+ export async function readEvaluationReport(path, options = {}) {
4
+ return reportEvalComponent(path, options);
5
+ }