skillfit 0.10.0 → 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 (104) hide show
  1. package/README.md +27 -7
  2. package/README.zh-CN.md +27 -7
  3. package/benches/README.md +2 -2
  4. package/dist/cli.js +146 -36
  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 +69 -141
  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 +59 -28
  14. package/dist/commands/eval-export-modes.test.js +350 -0
  15. package/dist/commands/eval-export.js +44 -10
  16. package/dist/commands/eval-export.test.js +165 -8
  17. package/dist/commands/eval-interruption.test.js +238 -0
  18. package/dist/commands/eval-plan.js +37 -0
  19. package/dist/commands/eval-preflight.js +61 -0
  20. package/dist/commands/eval-preflight.test.js +382 -0
  21. package/dist/commands/eval-report.js +60 -14
  22. package/dist/commands/eval-report.test.js +2 -2
  23. package/dist/commands/eval-single-arm-replay.js +21 -0
  24. package/dist/commands/eval-single-arm-report.js +223 -0
  25. package/dist/commands/eval.js +184 -112
  26. package/dist/commands/evaluation-report.js +5 -0
  27. package/dist/commands/evaluation-report.test.js +243 -0
  28. package/dist/commands/replay-cancellation.test.js +105 -0
  29. package/dist/commands/workflow-entrypoints.test.js +137 -0
  30. package/dist/harness/agent-preflight.js +180 -0
  31. package/dist/harness/bench.js +2 -1
  32. package/dist/harness/command.js +49 -0
  33. package/dist/harness/eval-audit.js +164 -17
  34. package/dist/harness/eval-budget.js +46 -2
  35. package/dist/harness/eval-budget.test.js +30 -3
  36. package/dist/harness/eval-component.test.js +169 -6
  37. package/dist/harness/eval-contract.js +11 -5
  38. package/dist/harness/executors/api.js +14 -4
  39. package/dist/harness/executors/api.test.js +61 -0
  40. package/dist/harness/executors/cli.js +24 -3
  41. package/dist/harness/experiment-session.js +77 -18
  42. package/dist/harness/experiment-session.test.js +51 -1
  43. package/dist/harness/input-snapshot.js +150 -0
  44. package/dist/harness/interruption.js +48 -0
  45. package/dist/harness/interruption.test.js +31 -0
  46. package/dist/harness/invocation-costs.js +72 -0
  47. package/dist/harness/judge-accounting.test.js +216 -0
  48. package/dist/harness/judge-audit.js +56 -0
  49. package/dist/harness/judge.js +86 -21
  50. package/dist/harness/replay-package.js +71 -5
  51. package/dist/harness/runner.js +92 -44
  52. package/dist/harness/runner.test.js +23 -0
  53. package/dist/harness/single-arm-audit.js +436 -0
  54. package/dist/harness/trigger.js +41 -7
  55. package/dist/harness/trigger.test.js +12 -0
  56. package/dist/harness/verifier-error.js +65 -0
  57. package/dist/harness/verifier.test.js +128 -0
  58. package/docs/bench-authoring.md +34 -9
  59. package/docs/bench-check-json.md +36 -6
  60. package/docs/eval-agent-preflight.md +101 -0
  61. package/docs/eval-case-preflight.md +115 -0
  62. package/docs/eval-component.md +65 -9
  63. package/docs/eval-costs.md +53 -0
  64. package/docs/eval-planning.md +153 -0
  65. package/docs/evaluation-input-snapshots.md +125 -0
  66. package/docs/evaluation-interruption.md +101 -0
  67. package/docs/evaluation-reports.md +143 -0
  68. package/docs/experiment-workflow.md +16 -2
  69. package/docs/first-real-eval.md +55 -5
  70. package/docs/growth-roadmap-2026-10.md +48 -11
  71. package/docs/metrics.md +71 -3
  72. package/docs/plans/2026-10-16-case-workflow-and-release.md +19 -0
  73. package/docs/plans/2026-10-17-workflow-foundations.md +64 -0
  74. package/docs/releases/0.10.0-ci-registry-install.json +140 -0
  75. package/docs/releases/0.10.0-feature-smoke.json +22 -0
  76. package/docs/releases/0.10.0-feature-smoke.mjs +62 -0
  77. package/docs/releases/0.10.0-signatures.txt +7 -0
  78. package/docs/releases/0.10.0-verification.json +76 -0
  79. package/docs/releases/0.10.0.md +44 -8
  80. package/docs/releases/0.10.1-ci-registry-install.json +70 -0
  81. package/docs/releases/0.10.1-feature-smoke.json +28 -0
  82. package/docs/releases/0.10.1-feature-smoke.mjs +95 -0
  83. package/docs/releases/0.10.1-local-registry-install.json +60 -0
  84. package/docs/releases/0.10.1-registry-metadata.json +33 -0
  85. package/docs/releases/0.10.1-signatures.txt +7 -0
  86. package/docs/releases/0.10.1-verification.json +90 -0
  87. package/docs/releases/0.10.1.md +71 -0
  88. package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
  89. package/docs/releases/0.11.0.md +47 -0
  90. package/docs/replay-packages.md +52 -11
  91. package/docs/schemas/agent-preflight.schema.json +31 -0
  92. package/docs/schemas/calibration-plan.schema.json +22 -0
  93. package/docs/schemas/calibration-result.schema.json +17 -0
  94. package/docs/schemas/eval-preflight.schema.json +57 -0
  95. package/docs/schemas/eval-request.schema.json +1 -1
  96. package/docs/schemas/eval-result.schema.json +14 -1
  97. package/docs/schemas/invocation-costs.schema.json +31 -0
  98. package/docs/schemas/judge-call.schema.json +22 -0
  99. package/docs/schemas/single-arm-report.schema.json +20 -0
  100. package/docs/schemas/verifier-error.schema.json +11 -0
  101. package/docs/sharing-results.md +8 -2
  102. package/docs/verifier-contract.md +99 -0
  103. package/package.json +1 -1
  104. package/skills/skillfit/SKILL.md +41 -8
@@ -0,0 +1,180 @@
1
+ import { accessSync, constants, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join, resolve, win32 } from 'node:path';
4
+ import { loadMatrix, skillUserDirSpecs } from '../agents.js';
5
+ import { parseFrontmatter } from '../frontmatter.js';
6
+ /** Read PATH only; never run which/where, an agent, a login command or an API. */
7
+ export function findExecutable(binary, env = process.env, platform = process.platform) {
8
+ const windows = platform === 'win32';
9
+ // Match Node's first lexicographically sorted key when Windows env keys repeat by case.
10
+ const entries = Object.entries(env).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
11
+ const value = (key) => entries.find(([name]) => windows ? name.toLowerCase() === key.toLowerCase() : name === key)?.[1];
12
+ const path = value('PATH') ?? '';
13
+ const hasPath = /[\\/]/.test(binary) || isAbsolute(binary) || (windows && win32.isAbsolute(binary));
14
+ const directories = hasPath ? [''] : path.split(windows ? ';' : ':').map(dir => dir.replace(/^"(.*)"$/, '$1'))
15
+ .filter(dir => isAbsolute(dir) || (windows && win32.isAbsolute(dir)));
16
+ const extensions = windows ? (value('PATHEXT') ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean) : [];
17
+ const names = windows && !extensions.some(ext => binary.toLowerCase().endsWith(ext.toLowerCase()))
18
+ ? extensions.map(ext => binary + ext) : [binary];
19
+ for (const dir of directories)
20
+ for (const name of names) {
21
+ const file = resolve(dir.replace(/^"(.*)"$/, '$1'), name);
22
+ try {
23
+ if (!statSync(file).isFile())
24
+ continue;
25
+ accessSync(file, windows ? constants.F_OK : constants.X_OK);
26
+ return realpathSync(file);
27
+ }
28
+ catch { /* Continue searching; config directories are not executable evidence. */ }
29
+ }
30
+ return null;
31
+ }
32
+ export function globalSkillRoots(agent, home, env) {
33
+ return [...new Set([...skillUserDirSpecs(agent, env), ...agent.skills.sharedDirs.filter(path => path.startsWith('~/'))]
34
+ .map(path => path.startsWith('~/') ? join(home, path.slice(2)) : resolve(path)))];
35
+ }
36
+ function report(checks) {
37
+ const matrix = loadMatrix(), count = (status) => checks.filter(check => check.status === status).length;
38
+ return { schemaVersion: 1, kind: 'skillfit.agent-preflight', scope: 'offline-agent-environment',
39
+ status: count('FAIL') ? 'blocked' : 'ready', matrix: { schemaVersion: matrix.schemaVersion, verifiedAt: matrix.verifiedAt }, checks,
40
+ summary: { failures: count('FAIL'), passed: count('PASS'), unknown: count('UNKNOWN'), info: count('INFO') },
41
+ cost: { modelCalls: 0, cliInvocations: 0 } };
42
+ }
43
+ export function inspectAgentEnvironment(options) {
44
+ const checks = [], env = options.env ?? process.env;
45
+ const home = options.homeDir ?? homedir();
46
+ const names = new Set([options.target.name]);
47
+ if (options.target.kind === 'skill') {
48
+ try {
49
+ const name = parseFrontmatter(readFileSync(join(options.target.sourceDir, 'SKILL.md'), 'utf8'))?.name?.trim();
50
+ if (name)
51
+ names.add(name);
52
+ }
53
+ catch { /* Some legacy injectable bundles have no root SKILL.md. */ }
54
+ }
55
+ for (const role of options.roles) {
56
+ const agent = role.definition;
57
+ const add = (code, status, message, remediation = null, paths = []) => checks.push({ code, status, message, remediation, paths, role: role.role, agent: agent?.id ?? null });
58
+ const streamed = role.role === 'agent' && (options.mode === 'trigger' || (options.mode === 'installed' && agent?.headless.streamJson));
59
+ const argv = streamed ? agent?.headless.streamJson?.argv : agent?.headless.argv;
60
+ const binary = argv?.[0] ?? agent?.headless.argv[0] ?? agent?.detect.binaries[0];
61
+ if (role.injected)
62
+ add('EXECUTOR_INJECTED', 'UNKNOWN', 'Injected executor: installed CLI availability and runtime capabilities are not attested.');
63
+ else if (agent && binary) {
64
+ const path = findExecutable(binary, env);
65
+ add('CLI_AVAILABLE', path ? 'PASS' : 'FAIL', path ? `CLI executable is available: ${binary}.` : `CLI executable is missing or not executable on PATH: ${binary}.`, path ? null : 'Install the selected agent CLI or fix PATH, then create a fresh preview.', path ? [path] : []);
66
+ }
67
+ else if (!agent && role.executor?.kind === 'api')
68
+ add('CLI_AVAILABLE', 'INFO', 'API executor: no local agent CLI is required.');
69
+ let error = (role.role === 'agent' ? options.capabilityError : undefined) ?? role.resolutionError;
70
+ if (agent && !argv?.[0])
71
+ error ??= options.mode === 'trigger' && role.role === 'agent'
72
+ ? `Agent "${agent.id}" has no headless streamJson command template; trigger detection is unavailable for it.`
73
+ : `Agent "${agent.id}" has no usable headless command template.`;
74
+ if (agent && role.role === 'agent' && ['installed', 'trigger'].includes(options.mode) && !agent.skills.projectDirs.length) {
75
+ error ??= `Agent "${agent.id}" has no matrix-defined project Skill directory for ${options.mode} mode.`;
76
+ }
77
+ if (!role.injected && !role.executor && !error)
78
+ error = 'No executor available; pass --agent or set SKILLFIT_API_KEY.';
79
+ add('MATRIX_CAPABILITY', error ? 'FAIL' : role.injected && !agent ? 'UNKNOWN' : 'PASS', error ??
80
+ (agent ? 'Declared matrix capabilities match this evaluation; installed CLI flag compatibility was not probed.' : 'Executor supports the declared evaluation surface.'), error ? 'Select a compatible agent/input/mode or correct its configuration, then create a fresh preview.' : null);
81
+ add('AUTHENTICATION', 'UNKNOWN', 'Login and credential validity cannot be confirmed offline; no authentication command, credential file or network probe was used.', 'Confirm authentication separately before authorizing a live run.');
82
+ if (role.role !== 'agent' || options.target.kind !== 'skill')
83
+ continue;
84
+ if (!agent || (role.injected && options.homeDir === undefined)) {
85
+ add('GLOBAL_SKILL_SCAN', 'UNKNOWN', 'Global Skill availability was not inspected for this injected/unconfigured executor.');
86
+ continue;
87
+ }
88
+ const roots = globalSkillRoots(agent, home, env), conflicts = [], unreadable = [];
89
+ for (const root of roots) {
90
+ try {
91
+ for (const entry of readdirSync(root).sort()) {
92
+ const dir = join(root, entry), manifest = join(dir, 'SKILL.md');
93
+ try {
94
+ if (!statSync(manifest).isFile())
95
+ continue;
96
+ if (names.has(entry) || names.has(parseFrontmatter(readFileSync(manifest, 'utf8'))?.name?.trim() ?? ''))
97
+ conflicts.push(dir);
98
+ }
99
+ catch (error) {
100
+ if (!['ENOENT', 'ENOTDIR'].includes(String(error.code)))
101
+ unreadable.push(dir);
102
+ }
103
+ }
104
+ }
105
+ catch (error) {
106
+ if (error.code !== 'ENOENT')
107
+ unreadable.push(root);
108
+ }
109
+ }
110
+ add('GLOBAL_SKILL_CONFLICT', conflicts.length ? 'FAIL' : 'PASS', conflicts.length
111
+ ? 'Baseline contamination risk: a globally available Skill has the evaluated directory/frontmatter name; it may be loaded in baseline too.'
112
+ : 'No matching Skill was found among readable direct entries of matrix-listed user/global Skill roots.', conflicts.length ? 'Use a controlled agent profile without the conflicting Skill, then create a fresh preview. No global Skill was changed.' : null, conflicts);
113
+ add('GLOBAL_SKILL_SCAN', unreadable.length ? 'UNKNOWN' : 'INFO', unreadable.length
114
+ ? 'Some global Skill entries could not be inspected; absence of contamination is not established.'
115
+ : 'Only matrix-listed user/global roots were inspected. Inherited project, plugin and unlisted Skill scopes remain uncontrolled.', null, unreadable.length ? unreadable : roots);
116
+ }
117
+ return report(checks);
118
+ }
119
+ export class AgentPreflightFailed extends Error {
120
+ agentPreflight;
121
+ constructor(agentPreflight) {
122
+ super('Agent environment preflight blocked evaluation; no agent or judge calls were made.\n' +
123
+ agentPreflight.checks.filter(check => check.status === 'FAIL').map(check => `[FAIL] ${check.role}/${check.code}: ${check.message}${check.paths.length ? ` Paths: ${check.paths.join(', ')}` : ''} ${check.remediation ?? ''}`).join('\n'));
124
+ this.agentPreflight = agentPreflight;
125
+ this.name = 'AgentPreflightFailed';
126
+ }
127
+ }
128
+ export function assertAgentEnvironment(preflight) {
129
+ if (preflight.status === 'blocked')
130
+ throw new AgentPreflightFailed(preflight);
131
+ }
132
+ export function assertAgentEnvironmentUnchanged(before, after) {
133
+ assertAgentEnvironment(after);
134
+ if (JSON.stringify(before) !== JSON.stringify(after))
135
+ throw new AgentPreflightFailed(report([...after.checks, {
136
+ code: 'ENVIRONMENT_CHANGED', status: 'FAIL', role: 'agent', agent: null,
137
+ message: 'Agent environment changed during offline case preflight.', remediation: 'Create a fresh preview before execution.', paths: [],
138
+ }]));
139
+ }
140
+ export function renderAgentEnvironment(preflight) {
141
+ return [`Agent preflight: ${preflight.status} (offline; login remains unknown)`, ...preflight.checks.map(check => `[${check.status}] ${check.role}/${check.code}: ${check.message}${check.paths.length ? ` Paths: ${check.paths.join(', ')}` : ''}${check.remediation ? ` Remedy: ${check.remediation}` : ''}`)].join('\n');
142
+ }
143
+ /** Validate saved metadata without consulting today's machine or implying login. */
144
+ export function assertRecordedAgentEnvironment(value) {
145
+ const p = value;
146
+ if (!p || p.schemaVersion !== 1 || p.kind !== 'skillfit.agent-preflight' || p.scope !== 'offline-agent-environment' ||
147
+ p.status !== 'ready' || p.cost?.modelCalls !== 0 || p.cost?.cliInvocations !== 0 || !Array.isArray(p.checks) || !p.checks.length ||
148
+ !p.matrix || !Number.isSafeInteger(p.matrix.schemaVersion) || typeof p.matrix.verifiedAt !== 'string')
149
+ throw new Error('Invalid recorded Agent environment preflight.');
150
+ for (const check of p.checks) {
151
+ if (!check || !['PASS', 'UNKNOWN', 'INFO'].includes(check.status) || !['agent', 'judge'].includes(check.role) ||
152
+ typeof check.code !== 'string' || typeof check.message !== 'string' || !Array.isArray(check.paths) || check.paths.some(path => typeof path !== 'string') ||
153
+ (check.agent !== null && typeof check.agent !== 'string') || (check.remediation !== null && typeof check.remediation !== 'string') ||
154
+ (check.code === 'AUTHENTICATION' && (check.status !== 'UNKNOWN' || check.paths.length)))
155
+ throw new Error('Invalid recorded Agent environment check.');
156
+ }
157
+ if (!p.checks.some(check => check.role === 'agent' && check.code === 'AUTHENTICATION'))
158
+ throw new Error('Recorded Agent preflight has no primary agent.');
159
+ for (const role of new Set(p.checks.map(check => check.role)))
160
+ if (!p.checks.some(check => check.role === role && check.code === 'AUTHENTICATION' && check.status === 'UNKNOWN')) {
161
+ throw new Error('Recorded Agent preflight must retain unknown offline authentication.');
162
+ }
163
+ if (!p.summary || p.summary.failures !== 0 || p.summary.passed !== p.checks.filter(check => check.status === 'PASS').length ||
164
+ p.summary.unknown !== p.checks.filter(check => check.status === 'UNKNOWN').length || p.summary.info !== p.checks.filter(check => check.status === 'INFO').length) {
165
+ throw new Error('Recorded Agent preflight summary is inconsistent.');
166
+ }
167
+ }
168
+ /** Human reports omit local paths; JSON retains the original saved checks. */
169
+ export function agentEnvironmentReportLines(value) {
170
+ if (value == null)
171
+ return [];
172
+ try {
173
+ assertRecordedAgentEnvironment(value);
174
+ }
175
+ catch {
176
+ return ['Agent preflight: invalid/unverified saved metadata; inspect the JSON record.'];
177
+ }
178
+ return [`Agent preflight: ${value.status}; ${value.summary.unknown} unknown check(s); authentication remains unknown offline.`,
179
+ ...value.checks.map(check => `[${check.status}] ${check.role}/${check.code}: ${check.message}`)];
180
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { basename, isAbsolute, join, resolve, sep } from 'node:path';
3
3
  import { hashFileSet, listFilesRecursive } from './hash.js';
4
+ import { parseCommand } from './command.js';
4
5
  export const BENCH_SCHEMA_VERSION = 1;
5
6
  const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
6
7
  function assertRelativeInside(benchDir, rel, label) {
@@ -14,7 +15,7 @@ function assertRelativeInside(benchDir, rel, label) {
14
15
  return abs;
15
16
  }
16
17
  function assertCommandTokensExist(benchDir, command, label) {
17
- for (const token of command.split(/\s+/).filter(Boolean)) {
18
+ for (const token of parseCommand(command)) {
18
19
  if (!token.includes('/') && !token.includes('\\'))
19
20
  continue;
20
21
  const tokenAbs = assertRelativeInside(benchDir, token, label);
@@ -0,0 +1,49 @@
1
+ /** Tokenize a shell-free command. Quotes group arguments; no expansions run. */
2
+ export function parseCommand(command) {
3
+ const args = [];
4
+ let word = '', started = false, quote = null;
5
+ for (let i = 0; i < command.length; i++) {
6
+ const char = command[i];
7
+ if (char === '\0')
8
+ throw new Error('Command contains a NUL character.');
9
+ if (quote === "'") {
10
+ if (char === quote)
11
+ quote = null;
12
+ else
13
+ word += char;
14
+ }
15
+ else if (char === '\\' && i + 1 < command.length &&
16
+ (command[i + 1] === quote || (!quote && /[\s'"]/.test(command[i + 1])))) {
17
+ word += command[++i];
18
+ started = true;
19
+ }
20
+ else if (quote === '"') {
21
+ if (char === quote)
22
+ quote = null;
23
+ else
24
+ word += char;
25
+ }
26
+ else if (char === "'" || char === '"') {
27
+ quote = char;
28
+ started = true;
29
+ }
30
+ else if (/\s/.test(char)) {
31
+ if (started) {
32
+ args.push(word);
33
+ word = '';
34
+ started = false;
35
+ }
36
+ }
37
+ else {
38
+ word += char;
39
+ started = true;
40
+ }
41
+ }
42
+ if (quote)
43
+ throw new Error('Command has an unterminated quote.');
44
+ if (started)
45
+ args.push(word);
46
+ if (!args[0])
47
+ throw new Error('Command requires a non-empty executable.');
48
+ return args;
49
+ }
@@ -6,14 +6,19 @@ import { loadBench } from './bench.js';
6
6
  import { summarizeCosts } from './costs.js';
7
7
  import { policyHash, parseAcceptancePolicy, readComponentJson, record } from './eval-contract.js';
8
8
  import { costChanges } from './eval-acceptance.js';
9
- import { sha256File } from './hash.js';
9
+ import { sha256File, sha256Text } from './hash.js';
10
10
  import { collectInstalledSkillTarget } from './installed-skill.js';
11
- import { runVerifier } from './runner.js';
11
+ import { runVerifier, summarizeJudge } from './runner.js';
12
12
  import { verdictFromOutput } from './verifier-summary.js';
13
13
  import { parseEvalReport } from '../commands/eval-report.js';
14
14
  import { pairConditions } from './types.js';
15
15
  import { NATIVE_DIFF_PATH, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
16
16
  import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
17
+ import { verifyInputSnapshot } from './input-snapshot.js';
18
+ import { assertRecordedAgentEnvironment } from './agent-preflight.js';
19
+ import { judgeCallReceipt } from './judge-audit.js';
20
+ import { buildJudgePrompt, judgeOrder } from './judge.js';
21
+ import { summarizeInvocationCosts } from './invocation-costs.js';
17
22
  function inside(root, path) {
18
23
  const rel = relative(root, path);
19
24
  return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
@@ -99,7 +104,36 @@ export async function auditEvaluation(value, runDir, options = {}) {
99
104
  assert.equal(index.planSha256, report.experiment.planSha256);
100
105
  assert.deepEqual(readComponentJson(join(root, '_session.json')).value, report.experiment);
101
106
  const plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
107
+ const inputSnapshot = verifyInputSnapshot(root, plan);
102
108
  const details = record(plan.details, 'native plan details');
109
+ if (details.agentPreflight !== undefined)
110
+ assertRecordedAgentEnvironment(details.agentPreflight);
111
+ if (details.reviewedPlan !== undefined) {
112
+ const reviewed = record(details.reviewedPlan, 'reviewed plan'), { sha256, ...data } = reviewed;
113
+ assert.equal(data.schemaVersion, 1);
114
+ assert.equal(data.kind, 'skillfit.eval-plan');
115
+ assert.equal(sha256Text(JSON.stringify(data)), sha256, 'Reviewed plan hash changed.');
116
+ const e = record(data.evaluation, 'reviewed evaluation');
117
+ assert.equal(e.mode, details.mode);
118
+ assert.equal(record(e.target, 'reviewed target').kind, report.target.kind);
119
+ const implementation = plan.inputs.find(input => input.label === 'implementation');
120
+ assert.equal(implementation?.sha256, data.implementationSha256, 'Reviewed implementation differs from native inputs.');
121
+ assert.equal(record(e.target, 'reviewed target').sha256, report.target.sha256);
122
+ assert.equal(record(e.bench, 'reviewed bench').sha256, report.bench.sha256);
123
+ assert.deepEqual(record(e.bench, 'reviewed bench').taskIds, report.tasks.map(task => task.id));
124
+ assert.equal(e.baseline === null ? null : record(e.baseline, 'reviewed baseline').sha256, report.baselineTarget?.sha256 ?? null);
125
+ assert.deepEqual(e.executor, raw.executor);
126
+ assert.deepEqual(e.judge, raw.judge);
127
+ assert.equal(e.trials, report.trials);
128
+ assert.equal(e.plannedCalls, report.experiment.plannedCalls);
129
+ assert.equal(e.maxCalls, report.experiment.maxCalls);
130
+ assert.equal(e.inputMode, raw.inputMode);
131
+ assert.equal(e.installDir, report.skillDelivery?.installDir ?? null);
132
+ assert.equal(e.pairOrder, details.pairOrder);
133
+ assert.equal(e.executorTimeoutSeconds, details.executorTimeoutSeconds);
134
+ assert.deepEqual(e.spendingBudget, details.spendingBudget, 'Reviewed spending limits differ from the native plan.');
135
+ assert.deepEqual(e.agentPreflight, details.agentPreflight, 'Reviewed Agent preflight differs from the native plan.');
136
+ }
103
137
  let pairOrder = null;
104
138
  if (raw.pairOrder !== undefined || details.pairOrder !== undefined) {
105
139
  assert.ok(raw.pairOrder === 'baseline-first' || raw.pairOrder === 'balanced', 'Invalid recorded pair order.');
@@ -139,12 +173,14 @@ export async function auditEvaluation(value, runDir, options = {}) {
139
173
  const all = { baseline: [], treatment: [] }, paired = { baseline: [], treatment: [] };
140
174
  if (details.taskIds !== undefined)
141
175
  assert.deepEqual(details.taskIds, report.tasks.map(task => task.id), 'Selected task IDs differ from the frozen plan.');
142
- const bench = options.replay ? loadBench(options.benchDir ?? String(record(raw.bench, 'bench').dir)) : null;
176
+ const bench = options.replay ? loadBench(options.benchDir ?? inputSnapshot?.roots.get('bench') ?? String(record(raw.bench, 'bench').dir)) : null;
143
177
  if (bench)
144
178
  assert.equal(bench.contentSha256, report.bench.sha256, 'Replay bench differs from the frozen task set.');
145
179
  let invoked = 0;
146
180
  const expectedAgentOrder = [];
147
181
  const budgetReceipts = new Map();
182
+ const expectedDispatches = [];
183
+ const judgeCalls = [];
148
184
  const rawTasks = raw.tasks;
149
185
  for (const [taskIndex, task] of report.tasks.entries()) {
150
186
  assert.ok(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(task.id), 'Unsafe task id.');
@@ -165,7 +201,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
165
201
  if (details.nativeDiffTool !== undefined && r.executorInvoked) {
166
202
  assert.equal(sha256File(member(root, `${task.id}/${arm}/trial-${trial}/${NATIVE_DIFF_PATH}`)), record(details.nativeDiffTool, 'native diff tool').sha256, 'Delivered native diff tool changed.');
167
203
  }
168
- if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false) {
204
+ if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false && report.executor.kind === 'cli') {
169
205
  assert.ok(typeof details.executorTimeoutSeconds === 'number' && Number.isSafeInteger(details.executorTimeoutSeconds) && details.executorTimeoutSeconds >= 1 && details.executorTimeoutSeconds <= 3600);
170
206
  const actualTiming = record(record(r.timing, 'CLI timing').execution, 'CLI execution timing');
171
207
  assert.equal(actualTiming.timeoutMs, details.executorTimeoutSeconds * 1000, 'CLI deadline differs from the native plan.');
@@ -193,6 +229,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
193
229
  try {
194
230
  cpSync(join(root, task.id, arm, `trial-${trial}`), scratch, { recursive: true, filter: path => basename(path) !== '.git' });
195
231
  const grade = await runVerifier(bench.dir, definition.verifier, scratch), summary = verdictFromOutput(grade.output);
232
+ assert.equal(grade.error, null, `Replay verifier failed: ${grade.error}`);
196
233
  assert.notEqual(grade.exitCode, null);
197
234
  assert.equal(grade.exitCode, r.verifierExitCode);
198
235
  assert.equal(grade.exitCode === 0, r.passed);
@@ -213,8 +250,10 @@ export async function auditEvaluation(value, runDir, options = {}) {
213
250
  const b = pair.baseline, t = pair.treatment;
214
251
  if (pairOrder)
215
252
  for (const arm of pairConditions(pairOrder, taskIndex, trial)) {
216
- if (pair[arm].executorInvoked)
253
+ if (pair[arm].executorInvoked) {
217
254
  expectedAgentOrder.push(`${task.id}/${arm}/trial-${trial}`);
255
+ expectedDispatches.push({ role: 'agent', identity: { taskId: task.id, condition: arm, trial }, receipt: pair[arm] });
256
+ }
218
257
  }
219
258
  const graded = b.error === null && t.error === null;
220
259
  const changes = [];
@@ -237,38 +276,101 @@ export async function auditEvaluation(value, runDir, options = {}) {
237
276
  const outcomes = record(source.outcomes, 'paired outcomes');
238
277
  for (const arm of ['baseline', 'treatment'])
239
278
  assert.deepEqual(taskPaired[arm].map(r => r.passed), outcomes[arm]);
279
+ if (raw.judge != null) {
280
+ assert.ok(raw.invocationCosts != null, 'Judge usage unrecorded; cannot verify full invocation accounting.');
281
+ const judged = [];
282
+ for (let trial = 1; trial <= report.trials; trial++) {
283
+ const baseline = budgetReceipts.get(`${task.id}/baseline/trial-${trial}`);
284
+ const treatment = budgetReceipts.get(`${task.id}/treatment/trial-${trial}`);
285
+ if (baseline.error !== null || treatment.error !== null)
286
+ continue;
287
+ const seed = `${raw.runGroup}:${task.id}:${trial}`, order = judgeOrder(seed), calls = [];
288
+ for (const callIndex of [1, 2]) {
289
+ const path = `${task.id}/judge-trial-${trial}/call-${callIndex}.json`;
290
+ assert.equal(typeof files[path], 'string', 'Judge invocation receipt was not sealed.');
291
+ const call = judgeCallReceipt(readComponentJson(member(root, path)).value);
292
+ assert.equal(call.taskId, task.id);
293
+ assert.equal(call.trial, trial);
294
+ assert.equal(call.callIndex, callIndex);
295
+ assert.equal(call.seed, seed);
296
+ assert.equal(call.firstCondition, order[callIndex - 1]);
297
+ assert.equal(call.error, null);
298
+ assert.deepEqual(call.executor, raw.judge, 'Judge receipt executor differs from frozen metadata.');
299
+ if (details.executorTimeoutSeconds !== undefined && plan.injectedExecutor === false && record(raw.judge, 'judge').kind === 'cli') {
300
+ assert.equal(record(call.timing.execution, 'judge execution timing').timeoutMs, Number(details.executorTimeoutSeconds) * 1000, 'Judge deadline differs from the native plan.');
301
+ }
302
+ const nonce = call.prompt.match(/<<<BEGIN ANSWER A ([0-9a-f]{16})>>>/)?.[1];
303
+ assert.ok(nonce, 'Judge prompt anonymity nonce is missing.');
304
+ const benchSource = inputSnapshot?.roots.get('bench');
305
+ assert.ok(benchSource, 'Judge prompt auditing requires the sealed bench input.');
306
+ const frozenBench = loadBench(benchSource), definition = frozenBench.tasks.find(t => t.id === task.id);
307
+ assert.ok(definition);
308
+ const baseOutput = readFileSync(member(root, `${task.id}/baseline/trial-${trial}/_output.md`), 'utf8');
309
+ const treatmentOutput = readFileSync(member(root, `${task.id}/treatment/trial-${trial}/_output.md`), 'utf8');
310
+ assert.deepEqual(call.prompt, buildJudgePrompt(readFileSync(join(benchSource, definition.prompt), 'utf8'), definition.rubric ? readFileSync(join(benchSource, definition.rubric), 'utf8') : null, call.firstCondition === 'baseline' ? baseOutput : treatmentOutput, call.firstCondition === 'baseline' ? treatmentOutput : baseOutput, nonce), 'Judge prompt differs from the sealed task and anonymized answers.');
311
+ calls.push(call);
312
+ judgeCalls.push(call);
313
+ audit.receipts++;
314
+ expectedDispatches.push({ role: 'judge', identity: { role: 'judge', taskId: task.id, trial, callIndex }, receipt: call, promptSha256: call.promptSha256 });
315
+ }
316
+ const forward = calls[0].scores, reverse = calls[1].scores;
317
+ const result = { baselineScore: (forward.baseline + reverse.baseline) / 2, treatmentScore: (forward.treatment + reverse.treatment) / 2,
318
+ consistent: Math.sign(forward.baseline - forward.treatment) === Math.sign(reverse.baseline - reverse.treatment),
319
+ firstCondition: order[0], raw: `${calls[0].output}\n--- reverse order ---\n${calls[1].output}`, calls };
320
+ const path = `${task.id}/judge-trial-${trial}.json`;
321
+ assert.equal(typeof files[path], 'string');
322
+ assert.deepEqual(readComponentJson(member(root, path)).value, { trial, seed, ...result }, 'Judge pair summary differs from independent invocation receipts.');
323
+ judged.push(result);
324
+ }
325
+ assert.deepEqual(source.judge, summarizeJudge(judged), 'Judge task summary differs from invocation receipts.');
326
+ }
240
327
  }
241
328
  assert.deepEqual(summarizeCosts(all, paired), report.overall.costs, 'Overall cost accounting differs from receipts.');
242
329
  const ledger = readFileSync(join(root, '_calls.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => record(JSON.parse(line), 'ledger'));
330
+ const startedEvents = ledger.filter(e => e.event === 'started'), terminalEvents = ledger.filter(e => e.event === 'finished' || e.event === 'failed');
331
+ assert.equal(terminalEvents.length, report.experiment.callsFinished, 'Terminal call ledger differs from session accounting.');
332
+ for (const [ordinal, event] of startedEvents.entries()) {
333
+ assert.equal(event.call, ordinal + 1, 'Call ledger dispatch numbers must be consecutive.');
334
+ assert.ok(event.role === 'agent' || event.role === 'judge');
335
+ assert.ok(typeof event.promptSha256 === 'string' && /^[a-f0-9]{64}$/.test(event.promptSha256));
336
+ assert.equal(terminalEvents.filter(terminal => terminal.call === event.call).length, 1, 'Each dispatched call needs one terminal ledger receipt.');
337
+ }
243
338
  assert.equal(ledger.filter(e => e.event === 'started' && e.role === 'agent').length, invoked);
244
339
  assert.equal(ledger.filter(e => e.event === 'started').length, report.experiment.callsStarted);
245
340
  if (pairOrder)
246
341
  assert.deepEqual(ledger.filter(e => e.event === 'started' && e.role === 'agent')
247
342
  .map(e => String(e.workdir).split(/[\\/]/).slice(-3).join('/')), expectedAgentOrder, 'Recorded execution order differs from the frozen pair order.');
343
+ if (raw.invocationCosts !== undefined) {
344
+ assert.deepEqual(raw.invocationCosts, summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeCalls, raw.judge != null), 'Full invocation accounting differs from agent/judge receipts.');
345
+ const started = ledger.filter(e => e.event === 'started');
346
+ assert.equal(started.length, expectedDispatches.length, 'Agent/judge receipt coverage differs from the dispatch ledger.');
347
+ for (const [index, event] of started.entries()) {
348
+ const expected = expectedDispatches[index];
349
+ assert.equal(event.role, expected.role, 'Agent/judge dispatch order differs from frozen execution.');
350
+ if (expected.promptSha256)
351
+ assert.equal(event.promptSha256, expected.promptSha256, 'Judge invocation prompt hash differs from the call ledger.');
352
+ }
353
+ }
248
354
  if (details.spendingBudget !== undefined) {
249
355
  const limits = parseSpendingBudget(details.spendingBudget);
250
356
  assert.ok(pairOrder, 'Budget replay requires the recorded pair order.');
251
357
  assert.ok(typeof files['_budget.jsonl'] === 'string', 'Budget events are not sealed.');
252
358
  const events = readFileSync(join(root, '_budget.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
253
- assert.equal(events.length, expectedAgentOrder.length * 2, 'Budget event coverage differs from calls.');
359
+ assert.equal(events.length, expectedDispatches.length * 2, 'Budget event coverage differs from calls.');
254
360
  const observations = [];
255
- for (const [ordinal, path] of expectedAgentOrder.entries()) {
256
- const [taskId, condition, trialPath] = path.split('/');
257
- const trial = Number(trialPath.slice('trial-'.length));
361
+ for (const [ordinal, dispatch] of expectedDispatches.entries()) {
258
362
  const before = spendingBudgetState(limits, observations);
259
363
  assertSpendingCanContinue(before);
260
- assert.deepEqual(events[ordinal * 2], { phase: 'before-call', taskId, condition, trial, state: before }, 'Budget before-call state differs from receipts.');
261
- observations.push(budgetReceipts.get(path));
364
+ assert.deepEqual(events[ordinal * 2], { phase: 'before-call', ...dispatch.identity, state: before }, 'Budget before-call state differs from receipts.');
365
+ observations.push(dispatch.receipt);
262
366
  const after = spendingBudgetState(limits, observations);
263
367
  assert.equal(after.incomplete.length, 0, 'Budget run has missing final usage.');
264
368
  assert.notEqual(after.reason, 'EXECUTION_FAILED');
265
- assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call', taskId, condition, trial, state: after }, 'Budget after-call state differs from receipts.');
369
+ assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call', ...dispatch.identity, state: after }, 'Budget after-call state differs from receipts.');
266
370
  }
267
371
  }
268
372
  else
269
373
  assert.equal(files['_budget.jsonl'], undefined, 'Budget events were not declared in the native plan.');
270
- // This component does not run a judge whose separate usage would be absent from agent costs.
271
- assert.ok(raw.judge == null, 'Judge usage is not covered by component accounting.');
272
374
  audit.verified = true;
273
375
  }
274
376
  catch (error) {
@@ -305,9 +407,54 @@ export function stoppedAccounting(runDir) {
305
407
  }
306
408
  }
307
409
  const populations = summarizeCosts(all, paired);
410
+ const judgeEvents = ledger.filter(e => e.event === 'started' && e.role === 'judge');
411
+ const retainedJudgeCalls = new Map();
412
+ const walkJudge = (dir, prefix = '') => {
413
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
414
+ if (!entry.isDirectory() || entry.name === '.git' || entry.name === '_inputs')
415
+ continue;
416
+ const path = join(dir, entry.name), rel = prefix ? `${prefix}/${entry.name}` : entry.name;
417
+ if (/^[a-zA-Z0-9][a-zA-Z0-9._-]*\/judge-trial-[0-9]+$/.test(rel)) {
418
+ for (const name of ['call-1.json', 'call-2.json'])
419
+ if (existsSync(join(path, name))) {
420
+ try {
421
+ const value = readComponentJson(join(path, name)).value, r = record(value, 'judge receipt');
422
+ if (typeof r.promptSha256 === 'string')
423
+ retainedJudgeCalls.set(r.promptSha256, { path: `${rel}/${name}`, value });
424
+ }
425
+ catch { /* Unparseable files remain on disk; unmatched dispatch is unknown below. */ }
426
+ }
427
+ }
428
+ else if (!prefix)
429
+ walkJudge(path, rel);
430
+ }
431
+ };
432
+ walkJudge(root);
433
+ let missingJudgeReceipts = 0;
434
+ const judgeObservations = judgeEvents.map(event => {
435
+ const retained = retainedJudgeCalls.get(String(event.promptSha256));
436
+ if (retained) {
437
+ try {
438
+ const receipt = judgeCallReceipt(retained.value);
439
+ assert.equal(receipt.executorInvoked, true);
440
+ return receipt;
441
+ }
442
+ catch (error) {
443
+ invalidReceipts.push({ path: retained.path, reason: String(error) });
444
+ }
445
+ }
446
+ missingJudgeReceipts++;
447
+ return { executorInvoked: true, passed: false, error: 'Judge invocation receipt missing or invalid', durationSeconds: NaN, tokens: null, usageStatus: 'unknown' };
448
+ });
449
+ const nativePlan = existsSync(join(root, '_plan.json')) ? record(readComponentJson(join(root, '_plan.json')).value, 'native plan') : null;
450
+ const judgeRequested = judgeEvents.length > 0 || Boolean(nativePlan?.details && record(nativePlan.details, 'native plan details').judge != null);
451
+ const invocationCosts = summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeObservations, judgeRequested);
452
+ if (missingJudgeReceipts)
453
+ invocationCosts.judgeUsage = 'unknown';
308
454
  return { populations, startedAgentDispatches: all.baseline.length + all.treatment.length,
309
- recordedExecutorInvocations: populations.attempts.baseline.runs + populations.attempts.treatment.runs - missingReceipts - invalidReceipts.length,
310
- invocationsWithUnknownReceipts: missingReceipts + invalidReceipts.length,
455
+ invocationCosts, startedJudgeDispatches: judgeEvents.length, judgeInvocationsWithUnknownReceipts: missingJudgeReceipts,
456
+ recordedExecutorInvocations: populations.attempts.baseline.runs + populations.attempts.treatment.runs - missingReceipts - invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
457
+ invocationsWithUnknownReceipts: missingReceipts + invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
311
458
  ...(invalidReceipts.length ? { invalidReceipts } : {}),
312
- scope: 'Known agent invocation spending from stopped-run receipts; missing fields remain unknown. No paired efficacy comparison or exact bill.' };
459
+ scope: 'Known primary Agent spending and separate all-role invocation totals from stopped-run receipts; missing fields remain unknown. No paired efficacy comparison or exact bill.' };
313
460
  }
@@ -1,6 +1,26 @@
1
1
  import { COST_METRICS, summarizeCosts } from './costs.js';
2
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ /** Only controlled budget diagnostics may be copied into a durable session stop reason. */
5
+ export class SpendingBudgetStop extends Error {
6
+ code;
7
+ constructor(code, state) {
8
+ super(`${code}: no further agent calls; reached=${state.reached.join(',') || 'none'}, incomplete=${state.incomplete.join(',') || 'none'}. Retained spending is not discarded; no retry or replacement.`);
9
+ this.code = code;
10
+ this.name = 'SpendingBudgetStop';
11
+ }
12
+ }
13
+ export function spendingStopFrom(error) {
14
+ const seen = new Set();
15
+ let current = error;
16
+ while (current instanceof Error && !seen.has(current) && seen.size < 8) {
17
+ if (current instanceof SpendingBudgetStop)
18
+ return current;
19
+ seen.add(current);
20
+ current = current.cause;
21
+ }
22
+ return null;
23
+ }
4
24
  export function parseSpendingBudget(value) {
5
25
  if (!value || typeof value !== 'object' || Array.isArray(value))
6
26
  throw new Error('spendingBudget must be an object.');
@@ -30,7 +50,31 @@ export function spendingBudgetState(limits, observations) {
30
50
  }
31
51
  export function assertSpendingCanContinue(state) {
32
52
  if (state.reason)
33
- throw new Error(`${state.reason}: no further agent calls; reached=${state.reached.join(',') || 'none'}, incomplete=${state.incomplete.join(',') || 'none'}. Retained spending is not discarded; no retry or replacement.`);
53
+ throw new SpendingBudgetStop(state.reason, state);
54
+ }
55
+ /** One serial stop-line recorder for every executor role and evaluation mode. */
56
+ export function createSpendingBudgetRecorder(options) {
57
+ const observations = [];
58
+ const event = (phase, identity) => {
59
+ if (!options.budget)
60
+ return null;
61
+ const state = spendingBudgetState(options.budget, observations);
62
+ appendFileSync(join(options.groupDir, '_budget.jsonl'), JSON.stringify({ phase, ...identity, state }) + '\n', 'utf8');
63
+ return state;
64
+ };
65
+ return {
66
+ before(identity) {
67
+ const state = event('before-call', identity);
68
+ if (state)
69
+ assertSpendingCanContinue(state);
70
+ },
71
+ after(identity, observation) {
72
+ observations.push(observation);
73
+ const state = event('after-call', identity);
74
+ if (state && (state.incomplete.length || state.reason === 'EXECUTION_FAILED'))
75
+ assertSpendingCanContinue(state);
76
+ },
77
+ };
34
78
  }
35
79
  /** Informational on stopped evidence; a completed native audit verifies every event. */
36
80
  export function spendingBudgetReport(runDir) {