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
@@ -1,8 +1,11 @@
1
1
  import { readFileSync, statSync } from 'node:fs';
2
+ import { agentEnvironmentReportLines } from '../harness/agent-preflight.js';
3
+ import { renderSingleArmReport } from './eval-single-arm-report.js';
2
4
  import { CONCLUSIVE_TASKS, CONCLUSIVE_TRIALS, formatP, formatPp1, verdictFor } from '../harness/report.js';
3
5
  import { mcnemarExactP } from '../harness/stats.js';
4
6
  import { validateSkillInstallDir } from '../harness/installed-skill.js';
5
7
  import { assertCostTotals, COST_METRICS, renderCostLines } from '../harness/costs.js';
8
+ import { parseInvocationCosts, renderInvocationCostLines } from '../harness/invocation-costs.js';
6
9
  const MAX_MANIFEST_BYTES = 16 * 1024 * 1024;
7
10
  function object(value, label) {
8
11
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
@@ -53,6 +56,8 @@ function experiment(value) {
53
56
  const callsStarted = integer(item['callsStarted'], 'experiment.callsStarted');
54
57
  const callsFinished = integer(item['callsFinished'], 'experiment.callsFinished');
55
58
  const stopReason = item['stopReason'] === null ? null : string(item['stopReason'], 'experiment.stopReason');
59
+ if (item['stopCode'] !== undefined && !['EXECUTION_FAILED', 'FINAL_USAGE_MISSING', 'SPENDING_BUDGET_REACHED'].includes(String(item['stopCode'])))
60
+ throw new Error('Invalid experiment.stopCode');
56
61
  if (![plannedCalls, maxCalls, callsStarted, callsFinished].every(Number.isSafeInteger) ||
57
62
  maxCalls < plannedCalls || callsStarted > plannedCalls || callsFinished > callsStarted ||
58
63
  (status === 'completed' && (stopReason !== null || callsFinished !== plannedCalls)) ||
@@ -61,7 +66,8 @@ function experiment(value) {
61
66
  throw new Error('experiment status, call counts, ceiling, and stop reason contradict each other');
62
67
  }
63
68
  return { schemaVersion: 1, status, plannedCalls, maxCalls, callsStarted, callsFinished, stopReason,
64
- planSha256: hash(item['planSha256'], 'experiment.planSha256') };
69
+ planSha256: hash(item['planSha256'], 'experiment.planSha256'),
70
+ ...(item['stopCode'] === undefined ? {} : { stopCode: item['stopCode'] }) };
65
71
  }
66
72
  function counts(value, label) {
67
73
  const item = object(value, label);
@@ -425,6 +431,7 @@ export function parseEvalReport(value) {
425
431
  }
426
432
  return {
427
433
  runGroup: string(manifest['runGroup'], 'runGroup'),
434
+ ...(manifest['invocationCosts'] === undefined ? {} : { invocationCosts: parseInvocationCosts(manifest['invocationCosts']) }),
428
435
  createdAt,
429
436
  target: { kind, name: string(target['name'], 'target.name'), sha256: hash(target['bundleSha256'], 'target.bundleSha256') },
430
437
  baselineTarget,
@@ -584,6 +591,8 @@ export function renderEvalMarkdown(report) {
584
591
  lines.push(...renderCostLines(report.overall.costs));
585
592
  else
586
593
  lines.push('Cache partitions and all-invocation costs were not recorded in this legacy manifest. Missing usage is unknown; the report does not infer it from prompt size or treat it as zero.');
594
+ if (report.invocationCosts)
595
+ lines.push('', ...renderInvocationCostLines(report.invocationCosts));
587
596
  lines.push('', '## Warnings', '');
588
597
  if (report.warnings.length === 0)
589
598
  lines.push('- None');
@@ -595,8 +604,12 @@ export function renderEvalMarkdown(report) {
595
604
  export async function runEvalReport(inputPath, log = console.log, options = {}) {
596
605
  // Import after module initialization: component assessment itself uses this
597
606
  // module's manifest parser. Both CLI formats must share the same assessment.
598
- const { reportEvalComponent } = await import('./eval-component.js');
599
- const result = await reportEvalComponent(inputPath, options);
607
+ const { readEvaluationReport } = await import('./evaluation-report.js');
608
+ const result = await readEvaluationReport(inputPath, options);
609
+ if ('evaluationType' in result) {
610
+ log(renderSingleArmReport(result));
611
+ return;
612
+ }
600
613
  const root = result.evidence.runDir;
601
614
  const safe = (message) => escapeMarkdown(message.replaceAll(root, '[run]'));
602
615
  const lines = [];
@@ -613,12 +626,14 @@ export async function runEvalReport(inputPath, log = console.log, options = {})
613
626
  if ('startedAgentDispatches' in result.costs)
614
627
  lines.push(`- Started agent dispatches: ${result.costs.startedAgentDispatches}`, `- Missing or invalid invocation receipts: ${result.costs.invocationsWithUnknownReceipts}`);
615
628
  lines.push('', '## Retained costs', '', ...renderCostLines(result.costs.populations));
629
+ lines.push('', ...renderInvocationCostLines(result.invocationCosts));
616
630
  }
617
631
  lines.push('', '## Evidence and acceptance', '', `- State: ${result.status}`, `- Native evidence: ${result.evidence.verified ? 'verified' : 'unverified'}`, `- Acceptance: ${result.acceptance.decision}`, `- Eligible for upgrade: ${result.acceptance.eligibleForUpgrade ? 'yes' : 'no'}`, '- Automatic upgrade: no');
618
632
  for (const reason of result.acceptance.reasons)
619
633
  lines.push(`- ${reason.code}: ${safe(reason.message)}`);
620
634
  for (const reason of result.evidence.reasons)
621
635
  lines.push(`- Audit: ${safe(reason)}`);
636
+ lines.push(...agentEnvironmentReportLines(result.agentPreflight).map(line => `- ${safe(line)}`));
622
637
  if (result.casePreflight) {
623
638
  const gate = result.casePreflight;
624
639
  if (typeof gate.status === 'string' && gate.summary && [gate.summary.failures, gate.summary.warnings, gate.summary.unknown].every(n => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0)) {
@@ -0,0 +1,21 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { readSingleArmReport } from './eval-single-arm-report.js';
4
+ import { auditSingleArmEvaluation } from '../harness/single-arm-audit.js';
5
+ /** Shared async single-arm report reader; only native evidence can be replayed. */
6
+ export async function reportSingleArmEvaluation(path, options = {}) {
7
+ const report = readSingleArmReport(path);
8
+ if (!report)
9
+ return null;
10
+ if (options.policyPath || options.recordsPath)
11
+ throw new Error('Single-arm reports do not support paired --policy or external --records overrides.');
12
+ if (options.benchDir && !options.replay)
13
+ throw new Error('--bench is only used with --replay for a single-arm report.');
14
+ const input = resolve(path), root = statSync(input).isDirectory() ? input : dirname(input);
15
+ if (!existsSync(join(root, '_plan.json')) || !existsSync(join(root, '_session.json')) || !existsSync(join(root, '_artifacts.json'))) {
16
+ if (options.replay)
17
+ throw new Error('Offline single-arm replay requires a sealed native run, not a standalone historical summary.');
18
+ return report;
19
+ }
20
+ return { ...report, ...await auditSingleArmEvaluation(root, options) };
21
+ }
@@ -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
+ }