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,436 @@
1
+ import assert from 'node:assert/strict';
2
+ import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, isAbsolute, join, resolve } from 'node:path';
5
+ import { loadBench } from './bench.js';
6
+ import { summarizeCosts } from './costs.js';
7
+ import { readComponentJson, record } from './eval-contract.js';
8
+ import { hashFileSet, sha256File, sha256Text } from './hash.js';
9
+ import { packageFiles, packageMember } from './replay-package.js';
10
+ import { verifyInputSnapshot } from './input-snapshot.js';
11
+ import { assertRecordedAgentEnvironment } from './agent-preflight.js';
12
+ import { runVerifier } from './runner.js';
13
+ import { verdictFromOutput } from './verifier-summary.js';
14
+ import { triggerMetrics } from './trigger.js';
15
+ import { collectInstalledSkillFingerprint } from './bundle.js';
16
+ import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
17
+ function integer(value, label) {
18
+ assert.ok(typeof value === 'number' && Number.isSafeInteger(value) && value >= 0, `Invalid ${label}.`);
19
+ return value;
20
+ }
21
+ function receipt(value, invoked) {
22
+ const row = record(value, 'single-arm receipt');
23
+ assert.equal(typeof row.passed, 'boolean');
24
+ assert.ok(row.error === null || typeof row.error === 'string');
25
+ assert.ok(typeof row.durationSeconds === 'number' && Number.isFinite(row.durationSeconds) && row.durationSeconds >= 0);
26
+ if (row.executorInvoked !== undefined)
27
+ assert.equal(row.executorInvoked, invoked, 'Receipt invocation differs from its ledger.');
28
+ const status = row.usageStatus ?? 'unknown';
29
+ assert.ok(['final', 'partial', 'unknown'].includes(String(status)));
30
+ assert.ok(row.error !== null || invoked, 'An uninvoked receipt cannot establish a graded task outcome.');
31
+ if (row.score !== null && row.score !== undefined)
32
+ assert.ok(typeof row.score === 'number' && Number.isFinite(row.score) && row.score >= 0 && row.score <= 1);
33
+ if (row.checks !== null && row.checks !== undefined) {
34
+ assert.ok(Array.isArray(row.checks));
35
+ const names = new Set();
36
+ for (const entry of row.checks) {
37
+ const check = record(entry, 'named check');
38
+ assert.ok(typeof check.name === 'string' && check.name.length > 0);
39
+ assert.equal(typeof check.pass, 'boolean');
40
+ assert.ok(!names.has(check.name), 'Duplicate named check.');
41
+ names.add(check.name);
42
+ }
43
+ }
44
+ if (row.tokens != null) {
45
+ const tokens = record(row.tokens, 'receipt tokens');
46
+ for (const key of ['input', 'cachedInput', 'output'])
47
+ if (tokens[key] !== undefined)
48
+ integer(tokens[key], `tokens.${key}`);
49
+ if (typeof tokens.cachedInput === 'number' && typeof tokens.input === 'number')
50
+ assert.ok(tokens.cachedInput <= tokens.input);
51
+ }
52
+ return { ...row, executorInvoked: invoked, usageStatus: status, tokens: row.tokens ?? null };
53
+ }
54
+ function unknownReceipt() {
55
+ return { executorInvoked: true, passed: false, error: 'Invocation receipt missing or invalid; raw evidence retained.', durationSeconds: NaN, tokens: null, usageStatus: 'unknown' };
56
+ }
57
+ function workdir(value, arm) {
58
+ assert.equal(typeof value, 'string');
59
+ const path = value.split(/[\\/]/).slice(-3).join('/');
60
+ assert.match(path, new RegExp(`^[a-zA-Z0-9][a-zA-Z0-9._-]*/${arm}/trial-[1-9][0-9]*$`));
61
+ return path;
62
+ }
63
+ /** Broken evidence cannot erase known spending or turn a lost receipt into zero. */
64
+ function retainedUsage(root, mode) {
65
+ const rows = [], invalidReceipts = [];
66
+ let missing = 0, ledgerComplete = true;
67
+ const path = join(root, '_calls.jsonl');
68
+ let lines = [];
69
+ try {
70
+ lines = readFileSync(path, 'utf8').trim().split('\n').filter(Boolean);
71
+ }
72
+ catch {
73
+ ledgerComplete = false;
74
+ }
75
+ for (const line of lines) {
76
+ let event;
77
+ try {
78
+ event = record(JSON.parse(line), 'ledger');
79
+ }
80
+ catch {
81
+ ledgerComplete = false;
82
+ continue;
83
+ }
84
+ if (event.event !== 'started' || event.role !== 'agent')
85
+ continue;
86
+ let trial = '(invalid invocation workspace)';
87
+ try {
88
+ const recordedArm = typeof event.workdir === 'string' ? event.workdir.split(/[\\/]/).at(-2) : null;
89
+ const expectedArm = mode === 'trigger' ? 'installed' : mode === 'calibration' ? 'baseline' : recordedArm;
90
+ assert.ok(expectedArm === 'baseline' || expectedArm === 'installed');
91
+ trial = workdir(event.workdir, expectedArm);
92
+ const file = `${trial}/_result.json`;
93
+ if (!existsSync(join(root, file))) {
94
+ missing++;
95
+ rows.push(unknownReceipt());
96
+ continue;
97
+ }
98
+ const r = receipt(readComponentJson(packageMember(root, file)).value, true), [taskId, arm, trialName] = trial.split('/');
99
+ assert.equal(r.taskId, taskId);
100
+ assert.equal(r.trial, Number(trialName.slice(6)));
101
+ if (arm === 'baseline')
102
+ assert.equal(r.condition, 'baseline');
103
+ rows.push(r);
104
+ }
105
+ catch (error) {
106
+ missing++;
107
+ rows.push(unknownReceipt());
108
+ invalidReceipts.push({ path: trial, reason: error instanceof Error ? error.message : String(error) });
109
+ }
110
+ }
111
+ return { population: summarizeCosts({ baseline: rows, treatment: [] }, { baseline: [], treatment: [] }).attempts.baseline,
112
+ startedAgentDispatches: rows.length, invocationsWithUnknownReceipts: missing, ledgerComplete,
113
+ ...(invalidReceipts.length ? { invalidReceipts } : {}) };
114
+ }
115
+ /** A native single-arm audit verifies retained observations, never paired efficacy or adoption. */
116
+ export async function auditSingleArmEvaluation(runDir, options = {}) {
117
+ const root = resolve(runDir), reasons = [], observations = [];
118
+ let indexedFiles = 0, receipts = 0, missingReceipts = 0, replayedDeliveries = 0, mode = null;
119
+ let source = null, plan = null;
120
+ try {
121
+ plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
122
+ assert.equal(plan.schemaVersion, 1);
123
+ assert.equal(typeof plan.packageVersion, 'string');
124
+ assert.ok(Array.isArray(plan.inputs), 'Native input fingerprints are missing.');
125
+ const inputs = plan.inputs;
126
+ for (const label of ['bench', 'target', 'implementation']) {
127
+ const matches = inputs.filter(input => input.label === label);
128
+ assert.equal(matches.length, 1, `Missing or repeated pinned input: ${label}`);
129
+ const input = matches[0];
130
+ assert.equal(typeof input.root, 'string');
131
+ assert.match(String(input.sha256), /^[a-f0-9]{64}$/);
132
+ assert.ok(Array.isArray(input.files) && input.files.every((path) => typeof path === 'string'));
133
+ assert.deepEqual([...new Set(input.files)].sort(), input.files, 'Pinned input files must be sorted and unique.');
134
+ }
135
+ const details = record(plan.details, 'native details');
136
+ assert.ok(details.mode === 'calibration' || details.mode === 'trigger', 'Not a single-arm native run.');
137
+ mode = details.mode;
138
+ assert.ok(integer(details.trials, 'native trials') >= 1 && Number(details.trials) <= 20, 'Native trials must be between 1 and 20.');
139
+ const arm = mode === 'calibration' ? 'baseline' : 'installed';
140
+ const session = record(readComponentJson(join(root, '_session.json')).value, 'native session');
141
+ const planSha256 = sha256File(join(root, '_plan.json'));
142
+ assert.equal(session.schemaVersion, 1);
143
+ assert.equal(session.planSha256, planSha256);
144
+ assert.ok(['completed', 'stopped', 'incomplete'].includes(String(session.status)));
145
+ assert.ok(session.stopReason === null || typeof session.stopReason === 'string');
146
+ if (session.status === 'stopped')
147
+ assert.ok(typeof session.stopReason === 'string' && session.stopReason.length > 0);
148
+ const started = integer(session.callsStarted, 'callsStarted'), finished = integer(session.callsFinished, 'callsFinished');
149
+ const planned = integer(session.plannedCalls, 'plannedCalls'), maximum = integer(session.maxCalls, 'maxCalls');
150
+ assert.ok(planned > 0 && finished <= started && started <= planned && planned <= maximum);
151
+ assert.equal(plan.plannedCalls, planned);
152
+ assert.equal(plan.maxCalls, maximum);
153
+ if (session.status === 'completed') {
154
+ assert.equal(finished, planned);
155
+ assert.equal(session.stopReason, null);
156
+ }
157
+ const index = record(readComponentJson(join(root, '_artifacts.json')).value, 'native artifact index');
158
+ assert.equal(index.schemaVersion, 1);
159
+ assert.equal(index.planSha256, planSha256);
160
+ const files = record(index.files, 'native files');
161
+ assert.deepEqual(index.links, {}, 'Single-arm replay requires portable regular files.');
162
+ assert.deepEqual(packageFiles(root).filter(path => path !== '_artifacts.json'), Object.keys(files).sort(), 'Native artifact file inventory changed.');
163
+ for (const [path, hash] of Object.entries(files)) {
164
+ assert.equal(sha256File(packageMember(root, path)), hash, `Native evidence hash mismatch: ${path}`);
165
+ indexedFiles++;
166
+ }
167
+ assert.ok(files['_plan.json'] && files['_session.json'], 'Native plan and session must be sealed.');
168
+ const snapshot = verifyInputSnapshot(root, plan);
169
+ if (details.agentPreflight !== undefined)
170
+ assertRecordedAgentEnvironment(details.agentPreflight);
171
+ const summaryName = mode === 'calibration' ? '_calibration.json' : 'manifest.json';
172
+ if (existsSync(join(root, summaryName))) {
173
+ source = record(readComponentJson(join(root, summaryName)).value, 'single-arm summary');
174
+ assert.deepEqual(source.experiment, session, 'Summary experiment differs from native session.');
175
+ assert.equal(source.trials, details.trials);
176
+ assert.ok(Array.isArray(source.tasks));
177
+ if (mode === 'calibration')
178
+ assert.equal(source.inputMode, details.inputMode);
179
+ else {
180
+ assert.deepEqual(source.executor, details.executor, 'Summary executor differs from native plan.');
181
+ const skill = record(source.skill, 'trigger Skill'), target = plan.inputs.find(input => input.label === 'target');
182
+ if (skill.installedSha256 !== undefined) {
183
+ assert.equal(skill.installedSha256, target.sha256);
184
+ assert.deepEqual(skill.installedFiles, target.files);
185
+ }
186
+ if (details.skillInstallDir !== undefined)
187
+ assert.equal(source.skillInstallDir, details.skillInstallDir);
188
+ if (details.detection !== undefined)
189
+ assert.equal(source.detection, details.detection);
190
+ if (details.competition !== undefined) {
191
+ const competition = record(details.competition, 'planned competition');
192
+ assert.deepEqual(source.competition, { mode: competition.mode, skills: competition.skills.map(skill => ({ name: skill.name, sha256: skill.sha256 })) });
193
+ }
194
+ }
195
+ }
196
+ else
197
+ assert.notEqual(session.status, 'completed', 'Completed run has no final summary.');
198
+ const benchRoot = options.benchDir ?? snapshot?.roots.get('bench');
199
+ const bench = benchRoot ? loadBench(benchRoot) : null;
200
+ if (options.replay)
201
+ assert.ok(bench, 'Replay needs the sealed bench or an explicit matching --bench.');
202
+ if (source && mode === 'trigger' && bench)
203
+ assert.equal(record(source.bench, 'trigger bench').contentSha256, bench.contentSha256, 'Replay bench differs from frozen trigger input.');
204
+ if (bench && snapshot)
205
+ assert.equal(bench.contentSha256, loadBench(snapshot.roots.get('bench')).contentSha256, 'Replay bench differs from the sealed input.');
206
+ if (bench && !snapshot) {
207
+ const input = plan.inputs.find(input => input.label === 'bench');
208
+ assert.ok(input && Array.isArray(input.files));
209
+ assert.equal(hashFileSet(bench.dir, input.files), input.sha256, 'Replay bench differs from pinned native input.');
210
+ }
211
+ const selectedIds = details.taskIds === undefined ? bench?.tasks.map(task => task.id) : details.taskIds;
212
+ if (selectedIds) {
213
+ assert.ok(Array.isArray(selectedIds) && selectedIds.length > 0 && selectedIds.every(id => typeof id === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(id)), 'Invalid native task IDs.');
214
+ assert.equal(new Set(selectedIds).size, selectedIds.length, 'Repeated native task ID.');
215
+ if (bench)
216
+ assert.ok(selectedIds.every(id => bench.tasks.some(task => task.id === id)), 'Native task selection includes a task outside the pinned bench.');
217
+ }
218
+ const taskIds = mode === 'trigger' && bench ? bench.tasks.filter(task => selectedIds?.includes(task.id) && task.shouldTrigger !== undefined).map(task => task.id) : selectedIds;
219
+ if (taskIds)
220
+ assert.equal(taskIds.length * Number(details.trials), planned, 'Native task/trial count differs from planned calls.');
221
+ if (source && taskIds)
222
+ assert.deepEqual(source.tasks.map(task => task.id), taskIds, 'Summary task identities differ from the native plan.');
223
+ if (source)
224
+ assert.equal(source.tasks.length * integer(source.trials, 'trials'), planned);
225
+ if (details.reviewedPlan !== undefined) {
226
+ const saved = record(details.reviewedPlan, 'reviewed plan');
227
+ const { sha256, planSha256: calibrationHash, ...reviewed } = saved;
228
+ assert.equal(sha256Text(JSON.stringify(reviewed)), mode === 'calibration' ? calibrationHash : sha256, 'Reviewed plan hash changed.');
229
+ assert.equal(reviewed.kind, mode === 'calibration' ? 'skillfit.calibration-plan' : 'skillfit.eval-plan');
230
+ const implementation = plan.inputs.find(input => input.label === 'implementation');
231
+ assert.equal(implementation?.sha256, reviewed.implementationSha256, 'Reviewed implementation differs from native inputs.');
232
+ const e = mode === 'calibration' ? reviewed : record(reviewed.evaluation, 'reviewed evaluation');
233
+ if (mode === 'calibration')
234
+ assert.equal(details.mode, mode);
235
+ else
236
+ assert.equal(e.mode, mode);
237
+ assert.equal(e.plannedCalls, planned);
238
+ assert.equal(e.maxCalls, maximum);
239
+ assert.equal(e.trials, details.trials);
240
+ assert.deepEqual(e.agentPreflight, details.agentPreflight);
241
+ assert.deepEqual(e.spendingBudget, details.spendingBudget);
242
+ assert.equal(e.executorTimeoutSeconds, details.executorTimeoutSeconds);
243
+ assert.deepEqual(e.executor, details.executor);
244
+ if (mode === 'calibration')
245
+ assert.equal(e.inputMode, details.inputMode);
246
+ else {
247
+ assert.equal(e.installDir, details.skillInstallDir);
248
+ assert.deepEqual(e.competition, details.competition);
249
+ assert.equal(e.detection, details.detection);
250
+ const target = plan.inputs.find(input => input.label === 'target');
251
+ assert.deepEqual(e.installedFingerprint, { sha256: target.sha256, files: target.files });
252
+ if (source)
253
+ assert.equal(record(e.target, 'reviewed target').sha256, record(source.skill, 'trigger Skill').bundleSha256);
254
+ }
255
+ if (bench) {
256
+ assert.equal(record(e.bench, 'reviewed bench').sha256, bench.contentSha256);
257
+ if (selectedIds)
258
+ assert.deepEqual(record(e.bench, 'reviewed bench').taskIds, selectedIds);
259
+ }
260
+ }
261
+ const ledger = existsSync(join(root, '_calls.jsonl')) ? readFileSync(join(root, '_calls.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => record(JSON.parse(line), 'call ledger')) : [];
262
+ const calls = new Map();
263
+ for (const event of ledger) {
264
+ const call = integer(event.call, 'ledger call');
265
+ assert.ok(call > 0);
266
+ if (event.event === 'started') {
267
+ assert.equal(event.role, 'agent', 'Single-arm runs cannot contain judge calls.');
268
+ assert.equal(call, calls.size + 1);
269
+ assert.ok(!calls.get(call - 1) || calls.get(call - 1).done);
270
+ const path = workdir(event.workdir, arm);
271
+ assert.ok(![...calls.values()].some(value => value.path === path), 'Duplicate invocation workspace.');
272
+ assert.match(String(event.promptSha256), /^[a-f0-9]{64}$/);
273
+ assert.equal(sha256File(packageMember(root, `${path}/_prompt.txt`)), event.promptSha256, 'Invocation prompt differs from ledger.');
274
+ calls.set(call, { path, done: false });
275
+ }
276
+ else {
277
+ assert.ok(event.event === 'finished' || event.event === 'failed');
278
+ const startedCall = calls.get(call);
279
+ assert.ok(startedCall && !startedCall.done);
280
+ startedCall.done = true;
281
+ }
282
+ }
283
+ assert.equal(calls.size, started);
284
+ assert.equal([...calls.values()].filter(call => call.done).length, finished);
285
+ const rows = new Map();
286
+ const cohortIds = source ? source.tasks.map(task => String(task.id)) : taskIds;
287
+ const expectedPaths = cohortIds && details.trials !== undefined ? cohortIds.flatMap(id => Array.from({ length: Number(details.trials) }, (_, i) => `${id}/${arm}/trial-${i + 1}`)) : [...calls.values()].map(call => call.path);
288
+ const invokedPaths = new Set([...calls.values()].map(call => call.path));
289
+ for (const path of new Set([...expectedPaths, ...invokedPaths])) {
290
+ assert.match(path, new RegExp(`^[a-zA-Z0-9][a-zA-Z0-9._-]*/${arm}/trial-[1-9][0-9]*$`));
291
+ const [taskId, , trialName] = path.split('/'), trial = Number(trialName.slice(6));
292
+ if (taskIds)
293
+ assert.ok(taskIds.includes(taskId), 'Invocation task is outside the native task set.');
294
+ if (details.trials !== undefined)
295
+ assert.ok(trial <= Number(details.trials), 'Invocation trial exceeds native plan.');
296
+ const file = `${path}/_result.json`, invoked = invokedPaths.has(path);
297
+ if (!files[file]) {
298
+ if (session.status === 'completed' && source)
299
+ reasons.push(`Summary receipt not sealed: ${file}`);
300
+ if (invoked) {
301
+ missingReceipts++;
302
+ rows.set(path, unknownReceipt());
303
+ }
304
+ continue;
305
+ }
306
+ let r;
307
+ try {
308
+ r = receipt(readComponentJson(packageMember(root, file)).value, invoked);
309
+ }
310
+ catch (error) {
311
+ if (session.status === 'completed')
312
+ reasons.push(`Invalid summary receipt ${file}: ${String(error)}`);
313
+ if (invoked) {
314
+ missingReceipts++;
315
+ rows.set(path, unknownReceipt());
316
+ }
317
+ continue;
318
+ }
319
+ assert.equal(r.taskId, taskId);
320
+ assert.equal(r.trial, trial);
321
+ if (mode === 'calibration')
322
+ assert.equal(r.condition, 'baseline');
323
+ if (mode === 'trigger') {
324
+ assert.ok(r.triggered === true || r.triggered === false || r.triggered === null);
325
+ if (source) {
326
+ const skill = record(source.skill, 'trigger Skill');
327
+ if (skill.installedSha256 !== undefined) {
328
+ assert.equal(r.skillInstalledSha256, skill.installedSha256);
329
+ assert.deepEqual(r.skillInstalledFiles, skill.installedFiles);
330
+ const at = r.skillInstalledAt;
331
+ assert.ok(typeof at === 'string' && !isAbsolute(at) && !/^[A-Za-z]:/.test(at) && !at.split(/[\\/]/).some(part => !part || part === '.' || part === '..'));
332
+ assert.equal(at.replaceAll('\\', '/'), `${String(source.skillInstallDir).replaceAll('\\', '/')}/${skill.name}`);
333
+ const installed = collectInstalledSkillFingerprint(join(root, path, at));
334
+ assert.equal(installed.sha256, skill.installedSha256, 'Retained installed Skill differs from its invocation fingerprint.');
335
+ assert.deepEqual(installed.files, skill.installedFiles);
336
+ }
337
+ }
338
+ }
339
+ receipts++;
340
+ rows.set(path, r);
341
+ }
342
+ for (const call of calls.values())
343
+ observations.push(rows.get(call.path) ?? unknownReceipt());
344
+ if (bench && options.replay)
345
+ for (const [path, r] of rows) {
346
+ if (r.error === null) {
347
+ const task = bench.tasks.find(task => task.id === r.taskId);
348
+ assert.ok(task);
349
+ const scratch = mkdtempSync(join(tmpdir(), 'skillfit-single-replay-'));
350
+ try {
351
+ cpSync(join(root, path), scratch, { recursive: true, filter: file => basename(file) !== '.git' });
352
+ const grade = await runVerifier(bench.dir, task.verifier, scratch, task.verifierTimeoutSeconds), verdict = verdictFromOutput(grade.output);
353
+ assert.equal(grade.error, null, `Replay verifier failed: ${grade.error}`);
354
+ assert.notEqual(grade.exitCode, null);
355
+ assert.equal(grade.exitCode === 0, r.passed, 'Replay task verdict differs from retained delivery.');
356
+ if (r.verifierExitCode !== undefined)
357
+ assert.equal(grade.exitCode, r.verifierExitCode);
358
+ assert.equal(verdict?.score ?? null, r.score);
359
+ assert.deepEqual(verdict?.checks?.map(check => ({ name: check.name, pass: check.pass })) ?? null, r.checks);
360
+ replayedDeliveries++;
361
+ }
362
+ finally {
363
+ rmSync(scratch, { recursive: true, force: true });
364
+ }
365
+ }
366
+ }
367
+ if (details.spendingBudget !== undefined) {
368
+ const limits = parseSpendingBudget(details.spendingBudget), events = existsSync(join(root, '_budget.jsonl')) ? readFileSync(join(root, '_budget.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) : [];
369
+ const observed = [], budgetInvocations = [];
370
+ // Setup refusals also have before/after events, but do not spend an Agent call.
371
+ for (let i = 0; i < events.length; i += 2) {
372
+ const event = record(events[i], 'budget before-call'), path = `${event.taskId}/${arm}/trial-${event.trial}`;
373
+ assert.equal(path, expectedPaths[i / 2], 'Budget event differs from the frozen task/trial order.');
374
+ const identity = { taskId: event.taskId, condition: arm, trial: event.trial }, before = spendingBudgetState(limits, observed);
375
+ assert.deepEqual(event, { phase: 'before-call', ...identity, state: before }, 'Budget before-call differs from receipts.');
376
+ const after = events[i + 1], row = rows.get(path);
377
+ if (after === undefined) {
378
+ assert.notEqual(session.status, 'completed', 'Completed budget has no after-call event.');
379
+ if (invokedPaths.has(path)) {
380
+ assertSpendingCanContinue(before);
381
+ budgetInvocations.push(path);
382
+ }
383
+ continue;
384
+ }
385
+ assertSpendingCanContinue(before);
386
+ assert.ok(row, 'Budget attempt has no retained receipt.');
387
+ observed.push(row);
388
+ assert.deepEqual(after, { phase: 'after-call', ...identity, state: spendingBudgetState(limits, observed) }, 'Budget after-call differs from receipts.');
389
+ if (row.executorInvoked)
390
+ budgetInvocations.push(path);
391
+ }
392
+ assert.deepEqual(budgetInvocations, [...calls.values()].map(call => call.path), 'Budget invocation coverage differs from the native ledger.');
393
+ if (session.status === 'completed')
394
+ assert.equal(events.length, expectedPaths.length * 2, 'Completed budget does not cover the cohort.');
395
+ }
396
+ if (source) {
397
+ const summaries = source.tasks.map(task => {
398
+ const records = expectedPaths.filter(path => path.startsWith(`${task.id}/`)).map(path => rows.get(path)).filter((row) => row?.taskId !== undefined);
399
+ const errors = records.filter(row => row.error !== null).length, completed = records.length - errors, passes = records.filter(row => row.error === null && row.passed).length;
400
+ if (mode === 'calibration') {
401
+ assert.deepEqual({ id: task.id, passes, completed, errors }, task, 'Calibration summary differs from receipts.');
402
+ return null;
403
+ }
404
+ const valid = records.filter(row => row.error === null), totals = records.filter(row => row.tokens).reduce((total, row) => ({ input: total.input + (row.tokens?.input ?? 0), output: total.output + (row.tokens?.output ?? 0) }), { input: 0, output: 0 });
405
+ const result = { id: String(task.id), shouldTrigger: Boolean(task.shouldTrigger), ...(task.triggerClass ? { triggerClass: task.triggerClass } : {}),
406
+ runs: valid.filter(row => row.triggered !== null).length, fired: valid.filter(row => row.triggered === true).length,
407
+ unknown: valid.filter(row => row.triggered === null).length, errors, passes, tokens: records.some(row => row.tokens) ? totals : null };
408
+ if (bench) {
409
+ const definition = bench.tasks.find(row => row.id === task.id);
410
+ assert.equal(result.shouldTrigger, definition.shouldTrigger);
411
+ assert.equal(result.triggerClass, definition.triggerClass);
412
+ }
413
+ assert.deepEqual(result, task, 'Trigger summary differs from retained observations.');
414
+ return result;
415
+ });
416
+ if (mode === 'trigger')
417
+ assert.deepEqual(JSON.parse(JSON.stringify(triggerMetrics(summaries))), source.metrics, 'Trigger metrics differ from retained observations.');
418
+ if (source.costs !== undefined)
419
+ assert.deepEqual(source.costs, summarizeCosts({ baseline: [...rows.values()], treatment: [] }, { baseline: [], treatment: [] }), 'Single-arm cost summary differs from its invocation receipts.');
420
+ }
421
+ }
422
+ catch (error) {
423
+ reasons.push(error instanceof Error ? error.message : String(error));
424
+ }
425
+ const costs = summarizeCosts({ baseline: observations, treatment: [] }, { baseline: [], treatment: [] });
426
+ const retained = reasons.length ? retainedUsage(root, mode) : null;
427
+ return { evidence: { verified: reasons.length === 0, runDir: root, scope: 'single-arm-native', reasons, indexedFiles, receipts, replayedDeliveries,
428
+ replayRequested: options.replay ?? false, observationsReused: true, modelCalls: 0,
429
+ limitation: 'Single-arm observations and local delivery grading only; no new trigger detection, paired comparison, billing claim or upgrade authorization.' },
430
+ usage: { ...(retained?.population ?? costs.attempts.baseline), startedAgentDispatches: retained?.startedAgentDispatches ?? observations.length,
431
+ invocationsWithUnknownReceipts: retained?.invocationsWithUnknownReceipts ?? missingReceipts,
432
+ ...(retained ? { ledgerComplete: retained.ledgerComplete, ...(retained.invalidReceipts ? { invalidReceipts: retained.invalidReceipts } : {}) } : {}),
433
+ scope: reasons.length ? 'Unaudited retained invocation receipts only; invalid/missing receipts remain unknown. A broken ledger may leave additional dispatches uncounted. No verified total, paired cost change or exact bill.'
434
+ : 'Retained single-arm invocation receipts only; absent usage and cache partitions remain unknown. No paired cost change or exact bill.' },
435
+ inputSnapshot: plan?.inputSnapshot ?? null, casePreflight: plan?.details ? record(plan.details, 'native details').casePreflight ?? null : null };
436
+ }
@@ -7,6 +7,7 @@ import { engagementError, gitInit, runVerifier, verifierFailure, verifierLogFor
7
7
  import { wilson95 } from './stats.js';
8
8
  import { throwIfEvaluationInterrupted } from './interruption.js';
9
9
  import { ExecutorFailure } from './types.js';
10
+ import { createSpendingBudgetRecorder } from './eval-budget.js';
10
11
  import { verdictFromOutput } from './verifier-summary.js';
11
12
  async function runTriggerTrial(plan, taskId, trial, installedSkill) {
12
13
  throwIfEvaluationInterrupted();
@@ -43,37 +44,46 @@ async function runTriggerTrial(plan, taskId, trial, installedSkill) {
43
44
  }
44
45
  }
45
46
  const started = new Date();
47
+ const monotonicStarted = performance.now();
46
48
  let output = '';
47
49
  let rawOutput = null;
48
50
  let error = null;
49
51
  let tokens = null;
50
52
  let failedUsage;
51
53
  let triggered = null;
54
+ let executorInvoked = false;
55
+ let executionTiming;
52
56
  try {
53
57
  if (!gitInitialized && task.verifierKind === 'command') {
54
58
  throw new Error('Benchmark Git initialization or reflog verification failed; trigger task was not executed.');
55
59
  }
60
+ executorInvoked = true;
56
61
  const result = await plan.executor.run(prompt, runDir);
57
62
  output = result.output;
58
63
  rawOutput = result.rawOutput ?? null;
59
64
  tokens = result.tokens ?? null;
60
65
  triggered = result.skillTriggered ?? null;
61
66
  error = result.guardError ?? null;
67
+ failedUsage = result.usageStatus ?? 'final';
68
+ executionTiming = result.executionTiming;
62
69
  }
63
70
  catch (executorError) {
64
71
  error = executorError.message;
65
72
  if (executorError instanceof ExecutorFailure) {
73
+ executorInvoked = executorError.executorInvoked;
66
74
  output = executorError.result.output;
67
75
  rawOutput = executorError.result.rawOutput ?? null;
68
76
  tokens = executorError.result.tokens ?? null;
69
77
  triggered = executorError.result.skillTriggered ?? null;
70
78
  failedUsage = executorError.result.usageStatus ?? 'unknown';
79
+ executionTiming = executorError.result.executionTiming;
71
80
  }
72
81
  }
73
82
  if (error === null) {
74
83
  error = await engagementError(output, task.verifierKind, runDir, gitInitialized);
75
84
  }
76
85
  const finished = new Date();
86
+ const durationSeconds = Math.round((performance.now() - monotonicStarted)) / 1000;
77
87
  writeFileSync(join(runDir, '_output.md'), output, 'utf8');
78
88
  if (rawOutput !== null) {
79
89
  writeFileSync(join(runDir, '_transcript.jsonl'), rawOutput, 'utf8');
@@ -82,9 +92,9 @@ async function runTriggerTrial(plan, taskId, trial, installedSkill) {
82
92
  let score = null;
83
93
  let checks = null;
84
94
  if (error === null) {
85
- const verifier = await runVerifier(plan.bench.dir, task.verifier, runDir);
95
+ const verifier = await runVerifier(plan.bench.dir, task.verifier, runDir, task.verifierTimeoutSeconds);
86
96
  writeFileSync(join(runDir, '_verifier.txt'), verifierLogFor(verifier), 'utf8');
87
- if (verifier.exitCode === null) {
97
+ if (verifier.error !== null || verifier.exitCode === null) {
88
98
  error = verifierFailure('verifier', task.verifier, verifier.error);
89
99
  }
90
100
  else {
@@ -105,7 +115,10 @@ async function runTriggerTrial(plan, taskId, trial, installedSkill) {
105
115
  runDir,
106
116
  startedAt: started.toISOString(),
107
117
  finishedAt: finished.toISOString(),
108
- durationSeconds: Math.round(((finished.getTime() - started.getTime()) / 1000) * 1000) / 1000,
118
+ durationSeconds,
119
+ wallDurationSeconds: Math.round(((finished.getTime() - started.getTime()) / 1000) * 1000) / 1000,
120
+ executorInvoked,
121
+ ...(executionTiming ? { executionTiming } : {}),
109
122
  triggered,
110
123
  passed,
111
124
  score,
@@ -258,12 +271,17 @@ export async function runTriggerExperiment(plan) {
258
271
  plan.log?.(`Skipping ${skipped} task(s) without a shouldTrigger label.`);
259
272
  }
260
273
  const taskSummaries = [];
274
+ const budget = createSpendingBudgetRecorder({ budget: plan.spendingBudget, groupDir });
261
275
  for (const task of eligible) {
262
276
  const records = [];
263
277
  for (let trial = 1; trial <= plan.trials; trial++) {
264
278
  throwIfEvaluationInterrupted();
265
279
  plan.log?.(`Running ${task.id} / installed / trial ${trial}…`);
266
- records.push(await runTriggerTrial(plan, task.id, trial, installedSkill));
280
+ const identity = { taskId: task.id, trial, condition: 'installed' };
281
+ budget.before(identity);
282
+ const outcome = await runTriggerTrial(plan, task.id, trial, installedSkill);
283
+ records.push(outcome);
284
+ budget.after(identity, { ...outcome, executorInvoked: outcome.executorInvoked ?? false, usageStatus: outcome.usageStatus ?? 'unknown' });
267
285
  throwIfEvaluationInterrupted();
268
286
  }
269
287
  taskSummaries.push(summarizeTriggerTask(task.id, task.shouldTrigger ?? false, task.triggerClass, records));
@@ -64,6 +64,18 @@ function makePlan(t, executor, overrides = {}) {
64
64
  ...overrides,
65
65
  };
66
66
  }
67
+ test('trigger verifier exceptions are errors excluded from rates while their output and tokens stay in receipts', async (t) => {
68
+ const plan = makePlan(t, stubExecutor(() => ({ output: 'done', skillTriggered: true })), { trials: 1 });
69
+ writeFileSync(join(plan.bench.dir, 'verifiers/pass.mjs'), "throw new Error('trigger grader unavailable');");
70
+ plan.bench = loadBench(plan.bench.dir);
71
+ const result = await runTriggerExperiment(plan);
72
+ assert.equal(result.metrics.positives.runs, 0);
73
+ assert.equal(result.metrics.negatives.runs, 0);
74
+ assert.ok(result.tasks.every(task => task.errors === 1 && task.runs === 0));
75
+ const receipt = JSON.parse(readFileSync(join(plan.runsRoot, plan.runGroup, 'pos-task/installed/trial-1/_result.json'), 'utf8'));
76
+ assert.match(receipt.error, /VERIFIER_RUNTIME_ERROR/);
77
+ assert.deepEqual(receipt.tokens, { input: 10, output: 5 });
78
+ });
67
79
  test('runTriggerExperiment measures recall and false-trigger rate', async (t) => {
68
80
  const executor = stubExecutor((prompt) => ({
69
81
  output: 'done',
@@ -0,0 +1,65 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { verdictFromOutput } from './verifier-summary.js';
4
+ function normalized(text) {
5
+ try {
6
+ text = decodeURI(text);
7
+ }
8
+ catch { /* Plain diagnostic text need not be URI encoded. */ }
9
+ text = text.replaceAll('\\', '/');
10
+ return process.platform === 'win32' ? text.toLowerCase() : text;
11
+ }
12
+ function roots(path) {
13
+ const paths = [resolve(path)];
14
+ try {
15
+ paths.push(realpathSync(path));
16
+ }
17
+ catch { /* Retain the declared path if it disappeared. */ }
18
+ return [...new Set(paths.map(path => normalized(path).replace(/\/$/, '') + '/'))];
19
+ }
20
+ /** Explicit errors work for every runtime. Automatic detection is limited to
21
+ * direct Node exceptions attributable to bench code, never arbitrary nonzero exits. */
22
+ export function verifierRuntimeError(output, exitCode, benchDir, runDir) {
23
+ for (const line of output.split('\n').reverse()) {
24
+ let value;
25
+ try {
26
+ value = JSON.parse(line);
27
+ }
28
+ catch {
29
+ continue;
30
+ }
31
+ if (!value || value.kind !== 'skillfit.verifier-error')
32
+ continue;
33
+ if (value.schemaVersion !== 1 || typeof value.message !== 'string' || !value.message.trim()) {
34
+ return 'VERIFIER_PROTOCOL_ERROR: malformed skillfit.verifier-error message.';
35
+ }
36
+ return `VERIFIER_REPORTED_ERROR: ${value.message.slice(0, 4096)}`;
37
+ }
38
+ if (exitCode === null || exitCode === 0 || !/^Node\.js v\d+\.\d+/m.test(output))
39
+ return null;
40
+ const errors = [...output.matchAll(/^(?:(?:Syntax|Reference|Type|Range|URI|Eval|Aggregate)?Error)(?: \[[^\]\n]+\])?:[^\n]*/gm)];
41
+ const error = errors.at(-1);
42
+ if (!error)
43
+ return null; // AssertionError/test-runner failures keep their legacy verdict.
44
+ const tail = output.slice(error.index);
45
+ if (verdictFromOutput(tail))
46
+ return null; // A wrapper deliberately graded its child's failure.
47
+ const benchRoots = roots(benchDir), trialRoots = roots(runDir);
48
+ // Syntax diagnostics put their source location before the error; other Node
49
+ // exceptions put stack frames/requireStack/import origins after it.
50
+ const before = output.slice(0, error.index).split('\n').slice(-8)
51
+ .filter(line => /^(?:file:\/\/|[A-Za-z]:[\\/]|\/).*:\d+(?::\d+)?\s*$/.test(line));
52
+ const diagnostic = tail.split('\n');
53
+ // A grader may mention the trial directory in its own exception message.
54
+ // Treat that message as a location only for a Node load/filesystem diagnostic.
55
+ if (!/Cannot find |imported from |ENOENT|EACCES|ENOTDIR|EISDIR|Invalid package config/.test(diagnostic[0]))
56
+ diagnostic.shift();
57
+ for (const line of [...before.slice(-1), ...diagnostic]) {
58
+ const text = normalized(line);
59
+ if (trialRoots.some(root => text.includes(root)))
60
+ return null;
61
+ if (benchRoots.some(root => text.includes(root)))
62
+ return `VERIFIER_RUNTIME_ERROR: ${error[0]}`;
63
+ }
64
+ return null; // An unattributed exit is not enough to invent an infrastructure error.
65
+ }
@@ -0,0 +1,8 @@
1
+ export const DEFAULT_VERIFIER_TIMEOUT_SECONDS = 120;
2
+ /** Kept separate from the model deadline: case checks and oracle commands use this limit. */
3
+ export function parseVerifierTimeoutSeconds(value = DEFAULT_VERIFIER_TIMEOUT_SECONDS) {
4
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 3600) {
5
+ throw new Error('verifierTimeoutSeconds must be an integer between 1 and 3600.');
6
+ }
7
+ return value;
8
+ }