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.
- package/README.md +43 -8
- package/README.zh-CN.md +43 -8
- package/benches/README.md +6 -2
- package/dist/cli.js +153 -37
- package/dist/cli.test.js +94 -0
- package/dist/commands/bench-calibration.js +201 -0
- package/dist/commands/bench-calibration.test.js +237 -0
- package/dist/commands/bench-check-json.test.js +24 -3
- package/dist/commands/bench-draft.js +167 -0
- package/dist/commands/bench-draft.test.js +168 -0
- package/dist/commands/bench-manage.js +5 -4
- package/dist/commands/bench-source.js +101 -0
- package/dist/commands/bench-source.test.js +84 -0
- package/dist/commands/bench.js +227 -245
- package/dist/commands/bench.test.js +7 -3
- package/dist/commands/calibration-cli.test.js +145 -0
- package/dist/commands/eval-agent-preflight.test.js +269 -0
- package/dist/commands/eval-api-failure.test.js +46 -0
- package/dist/commands/eval-cli-usage.test.js +75 -0
- package/dist/commands/eval-cli.js +31 -0
- package/dist/commands/eval-component.js +52 -28
- package/dist/commands/eval-export-modes.test.js +350 -0
- package/dist/commands/eval-export.js +12 -4
- package/dist/commands/eval-interruption.test.js +26 -1
- package/dist/commands/eval-layout.test.js +126 -0
- package/dist/commands/eval-plan.js +37 -0
- package/dist/commands/eval-preflight.test.js +144 -1
- package/dist/commands/eval-report.js +18 -3
- package/dist/commands/eval-single-arm-replay.js +21 -0
- package/dist/commands/eval-single-arm-report.js +223 -0
- package/dist/commands/eval.js +113 -88
- package/dist/commands/evaluation-report.js +5 -0
- package/dist/commands/evaluation-report.test.js +243 -0
- package/dist/commands/npm-first-run.test.js +74 -0
- package/dist/commands/replay-cancellation.test.js +105 -0
- package/dist/commands/workflow-entrypoints.test.js +137 -0
- package/dist/harness/agent-preflight.js +196 -0
- package/dist/harness/bench-location.js +29 -0
- package/dist/harness/bench-location.test.js +33 -0
- package/dist/harness/bench.js +10 -4
- package/dist/harness/command.js +49 -0
- package/dist/harness/eval-audit.js +162 -17
- package/dist/harness/eval-budget.js +46 -2
- package/dist/harness/eval-budget.test.js +26 -1
- package/dist/harness/eval-component.test.js +163 -0
- package/dist/harness/eval-contract.js +11 -5
- package/dist/harness/evaluation-layout.js +30 -0
- package/dist/harness/executors/api.js +24 -10
- package/dist/harness/executors/api.test.js +57 -0
- package/dist/harness/executors/cli.js +15 -25
- package/dist/harness/executors/cli.test.js +33 -2
- package/dist/harness/experiment-session.js +23 -25
- package/dist/harness/experiment-session.test.js +8 -0
- package/dist/harness/hash.js +3 -1
- package/dist/harness/invocation-costs.js +72 -0
- package/dist/harness/judge-accounting.test.js +216 -0
- package/dist/harness/judge-audit.js +56 -0
- package/dist/harness/judge.js +86 -21
- package/dist/harness/replay-package.js +71 -5
- package/dist/harness/runner.js +44 -33
- package/dist/harness/runner.test.js +23 -0
- package/dist/harness/single-arm-audit.js +436 -0
- package/dist/harness/trigger.js +22 -4
- package/dist/harness/trigger.test.js +12 -0
- package/dist/harness/verifier-error.js +65 -0
- package/dist/harness/verifier-timeout.js +8 -0
- package/dist/harness/verifier-timeout.test.js +76 -0
- package/dist/harness/verifier.test.js +128 -0
- package/docs/bench-authoring.md +57 -12
- package/docs/bench-check-json.md +28 -5
- package/docs/bench-drafting.md +75 -0
- package/docs/case-management.md +12 -1
- package/docs/eval-agent-preflight.md +114 -0
- package/docs/eval-case-preflight.md +5 -0
- package/docs/eval-component.md +38 -10
- package/docs/eval-costs.md +70 -0
- package/docs/eval-planning.md +167 -0
- package/docs/evaluation-input-snapshots.md +22 -5
- package/docs/evaluation-interruption.md +22 -10
- package/docs/evaluation-reports.md +97 -3
- package/docs/experiment-workflow.md +7 -0
- package/docs/first-real-eval.md +75 -3
- package/docs/growth-roadmap-2026-10.md +51 -10
- package/docs/metrics.md +40 -3
- package/docs/plans/2026-10-17-workflow-foundations.md +99 -0
- package/docs/releases/0.10.1-ci-registry-install.json +70 -0
- package/docs/releases/0.10.1-feature-smoke.json +28 -0
- package/docs/releases/0.10.1-local-registry-install.json +60 -0
- package/docs/releases/0.10.1-registry-metadata.json +33 -0
- package/docs/releases/0.10.1-signatures.txt +7 -0
- package/docs/releases/0.10.1-verification.json +90 -0
- package/docs/releases/0.10.1.md +37 -4
- package/docs/releases/0.11.0-ci-registry-install.json +130 -0
- package/docs/releases/0.11.0-feature-smoke.json +1576 -0
- package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
- package/docs/releases/0.11.0-local-attempt-1.json +24 -0
- package/docs/releases/0.11.0-local-attempt-1.log +19 -0
- package/docs/releases/0.11.0-local-registry-install.json +25 -0
- package/docs/releases/0.11.0-registry-metadata.json +33 -0
- package/docs/releases/0.11.0-signatures.txt +12 -0
- package/docs/releases/0.11.0-verification.json +95 -0
- package/docs/releases/0.11.0.md +90 -0
- package/docs/releases/0.12.0-feature-smoke.mjs +73 -0
- package/docs/releases/0.12.0.md +68 -0
- package/docs/replay-packages.md +38 -6
- package/docs/schemas/agent-preflight.schema.json +31 -0
- package/docs/schemas/calibration-plan.schema.json +22 -0
- package/docs/schemas/calibration-result.schema.json +17 -0
- package/docs/schemas/eval-request.schema.json +1 -1
- package/docs/schemas/eval-result.schema.json +3 -1
- package/docs/schemas/invocation-costs.schema.json +31 -0
- package/docs/schemas/judge-call.schema.json +22 -0
- package/docs/schemas/single-arm-report.schema.json +20 -0
- package/docs/schemas/verifier-error.schema.json +11 -0
- package/docs/sharing-results.md +3 -0
- package/docs/verifier-contract.md +108 -0
- package/package.json +1 -1
- package/skills/skillfit/SKILL.md +61 -8
|
@@ -0,0 +1,196 @@
|
|
|
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 agentTokenCounters(agent) {
|
|
44
|
+
return agent.headless.streamJson?.wireShape === 'codex-items'
|
|
45
|
+
? ['input', 'cachedInput', 'output'] : agent.headless.usageFromSessionLog ? ['input', 'output'] : [];
|
|
46
|
+
}
|
|
47
|
+
export function inspectAgentEnvironment(options) {
|
|
48
|
+
const checks = [], env = options.env ?? process.env;
|
|
49
|
+
const home = options.homeDir ?? homedir();
|
|
50
|
+
const names = new Set([options.target.name]);
|
|
51
|
+
if (options.target.kind === 'skill') {
|
|
52
|
+
try {
|
|
53
|
+
const name = parseFrontmatter(readFileSync(join(options.target.sourceDir, 'SKILL.md'), 'utf8'))?.name?.trim();
|
|
54
|
+
if (name)
|
|
55
|
+
names.add(name);
|
|
56
|
+
}
|
|
57
|
+
catch { /* Some legacy injectable bundles have no root SKILL.md. */ }
|
|
58
|
+
}
|
|
59
|
+
for (const role of options.roles) {
|
|
60
|
+
const agent = role.definition;
|
|
61
|
+
const add = (code, status, message, remediation = null, paths = []) => checks.push({ code, status, message, remediation, paths, role: role.role, agent: agent?.id ?? null });
|
|
62
|
+
const trigger = role.role === 'agent' && options.mode === 'trigger';
|
|
63
|
+
const argv = trigger ? agent?.headless.streamJson?.argv : agent?.headless.streamJson?.argv ?? agent?.headless.argv;
|
|
64
|
+
const binary = argv?.[0] ?? agent?.headless.argv[0] ?? agent?.detect.binaries[0];
|
|
65
|
+
if (role.injected)
|
|
66
|
+
add('EXECUTOR_INJECTED', 'UNKNOWN', 'Injected executor: installed CLI availability and runtime capabilities are not attested.');
|
|
67
|
+
else if (agent && binary) {
|
|
68
|
+
const path = findExecutable(binary, env);
|
|
69
|
+
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] : []);
|
|
70
|
+
}
|
|
71
|
+
else if (!agent && role.executor?.kind === 'api')
|
|
72
|
+
add('CLI_AVAILABLE', 'INFO', 'API executor: no local agent CLI is required.');
|
|
73
|
+
let error = (role.role === 'agent' ? options.capabilityError : undefined) ?? role.resolutionError;
|
|
74
|
+
if (agent && !argv?.[0])
|
|
75
|
+
error ??= options.mode === 'trigger' && role.role === 'agent'
|
|
76
|
+
? `Agent "${agent.id}" has no headless streamJson command template; trigger detection is unavailable for it.`
|
|
77
|
+
: `Agent "${agent.id}" has no usable headless command template.`;
|
|
78
|
+
if (agent && role.role === 'agent' && ['installed', 'trigger'].includes(options.mode) && !agent.skills.projectDirs.length) {
|
|
79
|
+
error ??= `Agent "${agent.id}" has no matrix-defined project Skill directory for ${options.mode} mode.`;
|
|
80
|
+
}
|
|
81
|
+
if (!role.injected && !role.executor && !error)
|
|
82
|
+
error = 'No executor available; pass --agent or set SKILLFIT_API_KEY.';
|
|
83
|
+
add('MATRIX_CAPABILITY', error ? 'FAIL' : role.injected && !agent ? 'UNKNOWN' : 'PASS', error ??
|
|
84
|
+
(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);
|
|
85
|
+
if (agent && !role.injected) {
|
|
86
|
+
// These are adapter capabilities declared by matrix wire shape, not a probe
|
|
87
|
+
// or a guarantee that this installed CLI/provider will return final counters.
|
|
88
|
+
const metrics = agentTokenCounters(agent);
|
|
89
|
+
const missing = ['input', 'cachedInput', 'output'].filter(metric => !metrics.includes(metric));
|
|
90
|
+
const blocked = options.spendingBudget && missing.length > 0;
|
|
91
|
+
add('USAGE_CAPABILITY', blocked ? 'FAIL' : options.spendingBudget ? 'PASS' : 'INFO', `CLI adapter token counters: ${metrics.join(', ') || 'none'}. ${blocked
|
|
92
|
+
? `Whole-batch spending limits require unavailable counters: ${missing.join(', ')}; no calls may start.`
|
|
93
|
+
: 'Actual missing/partial final counters remain unknown and stop a budgeted batch.'}`, blocked ? 'Choose an adapter/provider with all required counters or explicitly review a new plan without token spending limits; unknown usage cannot be treated as zero.' : null);
|
|
94
|
+
}
|
|
95
|
+
else
|
|
96
|
+
add('USAGE_CAPABILITY', 'UNKNOWN', 'Final token/cache coverage cannot be confirmed offline for this API or injected executor; runtime spending guards still require complete final counters.');
|
|
97
|
+
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.');
|
|
98
|
+
if (role.role !== 'agent' || options.target.kind !== 'skill')
|
|
99
|
+
continue;
|
|
100
|
+
if (!agent || (role.injected && options.homeDir === undefined)) {
|
|
101
|
+
add('GLOBAL_SKILL_SCAN', 'UNKNOWN', 'Global Skill availability was not inspected for this injected/unconfigured executor.');
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const roots = globalSkillRoots(agent, home, env), conflicts = [], unreadable = [];
|
|
105
|
+
for (const root of roots) {
|
|
106
|
+
try {
|
|
107
|
+
for (const entry of readdirSync(root).sort()) {
|
|
108
|
+
const dir = join(root, entry), manifest = join(dir, 'SKILL.md');
|
|
109
|
+
try {
|
|
110
|
+
if (!statSync(manifest).isFile())
|
|
111
|
+
continue;
|
|
112
|
+
if (names.has(entry) || names.has(parseFrontmatter(readFileSync(manifest, 'utf8'))?.name?.trim() ?? ''))
|
|
113
|
+
conflicts.push(dir);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (!['ENOENT', 'ENOTDIR'].includes(String(error.code)))
|
|
117
|
+
unreadable.push(dir);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error.code !== 'ENOENT')
|
|
123
|
+
unreadable.push(root);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
add('GLOBAL_SKILL_CONFLICT', conflicts.length ? 'FAIL' : 'PASS', conflicts.length
|
|
127
|
+
? 'Baseline contamination risk: a globally available Skill has the evaluated directory/frontmatter name; it may be loaded in baseline too.'
|
|
128
|
+
: '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);
|
|
129
|
+
add('GLOBAL_SKILL_SCAN', unreadable.length ? 'UNKNOWN' : 'INFO', unreadable.length
|
|
130
|
+
? 'Some global Skill entries could not be inspected; absence of contamination is not established.'
|
|
131
|
+
: 'Only matrix-listed user/global roots were inspected. Inherited project, plugin and unlisted Skill scopes remain uncontrolled.', null, unreadable.length ? unreadable : roots);
|
|
132
|
+
}
|
|
133
|
+
return report(checks);
|
|
134
|
+
}
|
|
135
|
+
export class AgentPreflightFailed extends Error {
|
|
136
|
+
agentPreflight;
|
|
137
|
+
constructor(agentPreflight) {
|
|
138
|
+
super('Agent environment preflight blocked evaluation; no agent or judge calls were made.\n' +
|
|
139
|
+
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'));
|
|
140
|
+
this.agentPreflight = agentPreflight;
|
|
141
|
+
this.name = 'AgentPreflightFailed';
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function assertAgentEnvironment(preflight) {
|
|
145
|
+
if (preflight.status === 'blocked')
|
|
146
|
+
throw new AgentPreflightFailed(preflight);
|
|
147
|
+
}
|
|
148
|
+
export function assertAgentEnvironmentUnchanged(before, after) {
|
|
149
|
+
assertAgentEnvironment(after);
|
|
150
|
+
if (JSON.stringify(before) !== JSON.stringify(after))
|
|
151
|
+
throw new AgentPreflightFailed(report([...after.checks, {
|
|
152
|
+
code: 'ENVIRONMENT_CHANGED', status: 'FAIL', role: 'agent', agent: null,
|
|
153
|
+
message: 'Agent environment changed during offline case preflight.', remediation: 'Create a fresh preview before execution.', paths: [],
|
|
154
|
+
}]));
|
|
155
|
+
}
|
|
156
|
+
export function renderAgentEnvironment(preflight) {
|
|
157
|
+
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');
|
|
158
|
+
}
|
|
159
|
+
/** Validate saved metadata without consulting today's machine or implying login. */
|
|
160
|
+
export function assertRecordedAgentEnvironment(value) {
|
|
161
|
+
const p = value;
|
|
162
|
+
if (!p || p.schemaVersion !== 1 || p.kind !== 'skillfit.agent-preflight' || p.scope !== 'offline-agent-environment' ||
|
|
163
|
+
p.status !== 'ready' || p.cost?.modelCalls !== 0 || p.cost?.cliInvocations !== 0 || !Array.isArray(p.checks) || !p.checks.length ||
|
|
164
|
+
!p.matrix || !Number.isSafeInteger(p.matrix.schemaVersion) || typeof p.matrix.verifiedAt !== 'string')
|
|
165
|
+
throw new Error('Invalid recorded Agent environment preflight.');
|
|
166
|
+
for (const check of p.checks) {
|
|
167
|
+
if (!check || !['PASS', 'UNKNOWN', 'INFO'].includes(check.status) || !['agent', 'judge'].includes(check.role) ||
|
|
168
|
+
typeof check.code !== 'string' || typeof check.message !== 'string' || !Array.isArray(check.paths) || check.paths.some(path => typeof path !== 'string') ||
|
|
169
|
+
(check.agent !== null && typeof check.agent !== 'string') || (check.remediation !== null && typeof check.remediation !== 'string') ||
|
|
170
|
+
(check.code === 'AUTHENTICATION' && (check.status !== 'UNKNOWN' || check.paths.length)))
|
|
171
|
+
throw new Error('Invalid recorded Agent environment check.');
|
|
172
|
+
}
|
|
173
|
+
if (!p.checks.some(check => check.role === 'agent' && check.code === 'AUTHENTICATION'))
|
|
174
|
+
throw new Error('Recorded Agent preflight has no primary agent.');
|
|
175
|
+
for (const role of new Set(p.checks.map(check => check.role)))
|
|
176
|
+
if (!p.checks.some(check => check.role === role && check.code === 'AUTHENTICATION' && check.status === 'UNKNOWN')) {
|
|
177
|
+
throw new Error('Recorded Agent preflight must retain unknown offline authentication.');
|
|
178
|
+
}
|
|
179
|
+
if (!p.summary || p.summary.failures !== 0 || p.summary.passed !== p.checks.filter(check => check.status === 'PASS').length ||
|
|
180
|
+
p.summary.unknown !== p.checks.filter(check => check.status === 'UNKNOWN').length || p.summary.info !== p.checks.filter(check => check.status === 'INFO').length) {
|
|
181
|
+
throw new Error('Recorded Agent preflight summary is inconsistent.');
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** Human reports omit local paths; JSON retains the original saved checks. */
|
|
185
|
+
export function agentEnvironmentReportLines(value) {
|
|
186
|
+
if (value == null)
|
|
187
|
+
return [];
|
|
188
|
+
try {
|
|
189
|
+
assertRecordedAgentEnvironment(value);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return ['Agent preflight: invalid/unverified saved metadata; inspect the JSON record.'];
|
|
193
|
+
}
|
|
194
|
+
return [`Agent preflight: ${value.status}; ${value.summary.unknown} unknown check(s); authentication remains unknown offline.`,
|
|
195
|
+
...value.checks.map(check => `[${check.status}] ${check.role}/${check.code}: ${check.message}`)];
|
|
196
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
/** Paths win over bundled names. Explicit/existing local paths never fall back. */
|
|
5
|
+
export function resolveBenchDir(bench, options = {}) {
|
|
6
|
+
const root = options.bundledRoot ?? fileURLToPath(new URL('../../benches', import.meta.url));
|
|
7
|
+
const cwd = options.cwd ?? process.cwd();
|
|
8
|
+
if (bench !== undefined) {
|
|
9
|
+
const dir = resolve(cwd, bench);
|
|
10
|
+
if (existsSync(join(dir, 'bench.json')))
|
|
11
|
+
return dir;
|
|
12
|
+
if (existsSync(dir) || isAbsolute(bench) || /[\\/]/.test(bench) || bench === '.' || bench === '..') {
|
|
13
|
+
throw new Error(`Not a bench directory (missing bench.json): ${dir}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const candidates = existsSync(root) ? readdirSync(root).sort().map(name => ({ name, dir: join(root, name) }))
|
|
17
|
+
.filter(entry => statSync(entry.dir).isDirectory() && existsSync(join(entry.dir, 'bench.json'))) : [];
|
|
18
|
+
if (bench !== undefined) {
|
|
19
|
+
const match = candidates.find(entry => entry.name === bench);
|
|
20
|
+
if (match)
|
|
21
|
+
return match.dir;
|
|
22
|
+
throw new Error(`Not a bench directory (missing bench.json): ${resolve(cwd, bench)}`);
|
|
23
|
+
}
|
|
24
|
+
if (candidates.length === 1)
|
|
25
|
+
return candidates[0].dir;
|
|
26
|
+
if (!candidates.length)
|
|
27
|
+
throw new Error(`No bundled benches found under ${root}; pass --bench <path>`);
|
|
28
|
+
throw new Error(`More than one bundled bench is available; pick one explicitly:\n${candidates.map(entry => ` --bench ${entry.name}`).join('\n')}`);
|
|
29
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { test } from 'node:test';
|
|
6
|
+
import { resolveBenchDir } from './bench-location.js';
|
|
7
|
+
test('bench references prefer local inputs, preserve explicit-path errors and choose bundled names consistently', t => {
|
|
8
|
+
const root = mkdtempSync(join(tmpdir(), 'skillfit-bench-reference-'));
|
|
9
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
10
|
+
const cwd = join(root, 'user'), bundledRoot = join(root, 'package', 'benches');
|
|
11
|
+
mkdirSync(cwd);
|
|
12
|
+
mkdirSync(bundledRoot, { recursive: true });
|
|
13
|
+
const options = { cwd, bundledRoot };
|
|
14
|
+
assert.throws(() => resolveBenchDir(undefined, options), /No bundled benches/);
|
|
15
|
+
const bundled = join(bundledRoot, 'example');
|
|
16
|
+
mkdirSync(bundled);
|
|
17
|
+
writeFileSync(join(bundled, 'bench.json'), '{}');
|
|
18
|
+
assert.equal(resolveBenchDir('example', options), bundled);
|
|
19
|
+
assert.equal(resolveBenchDir(undefined, options), bundled);
|
|
20
|
+
assert.throws(() => resolveBenchDir('./example', options), /Not a bench directory/);
|
|
21
|
+
assert.throws(() => resolveBenchDir('absent', options), /missing bench.json/);
|
|
22
|
+
const local = join(cwd, 'example');
|
|
23
|
+
mkdirSync(local);
|
|
24
|
+
assert.throws(() => resolveBenchDir('example', options), /Not a bench directory/, 'An existing local directory must not silently use a bundled case.');
|
|
25
|
+
writeFileSync(join(local, 'bench.json'), '{malformed-but-local');
|
|
26
|
+
assert.equal(resolveBenchDir('example', options), local);
|
|
27
|
+
assert.equal(resolveBenchDir('./example', options), local);
|
|
28
|
+
assert.equal(resolveBenchDir('.', { ...options, cwd: local }), local);
|
|
29
|
+
const other = join(bundledRoot, 'other');
|
|
30
|
+
mkdirSync(other);
|
|
31
|
+
writeFileSync(join(other, 'bench.json'), '{}');
|
|
32
|
+
assert.throws(() => resolveBenchDir(undefined, options), /pick one explicitly/);
|
|
33
|
+
});
|
package/dist/harness/bench.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
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';
|
|
5
|
+
import { parseVerifierTimeoutSeconds } from './verifier-timeout.js';
|
|
4
6
|
export const BENCH_SCHEMA_VERSION = 1;
|
|
5
7
|
const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
6
8
|
function assertRelativeInside(benchDir, rel, label) {
|
|
9
|
+
if (rel.split(/[\\/]/).includes('.git'))
|
|
10
|
+
throw new Error(`${label} cannot reference Git metadata: ${rel}`);
|
|
7
11
|
if (isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) {
|
|
8
12
|
throw new Error(`${label} must be a relative path inside the bench directory: ${rel}`);
|
|
9
13
|
}
|
|
@@ -14,7 +18,7 @@ function assertRelativeInside(benchDir, rel, label) {
|
|
|
14
18
|
return abs;
|
|
15
19
|
}
|
|
16
20
|
function assertCommandTokensExist(benchDir, command, label) {
|
|
17
|
-
for (const token of command
|
|
21
|
+
for (const token of parseCommand(command)) {
|
|
18
22
|
if (!token.includes('/') && !token.includes('\\'))
|
|
19
23
|
continue;
|
|
20
24
|
const tokenAbs = assertRelativeInside(benchDir, token, label);
|
|
@@ -48,6 +52,8 @@ export function validateBenchTask(benchDir, raw, index) {
|
|
|
48
52
|
throw new Error(`bench.json task "${id}" has an invalid "verifierKind" field (expected "output" or "command")`);
|
|
49
53
|
}
|
|
50
54
|
const verifierKindField = verifierKind === undefined ? {} : { verifierKind: verifierKind };
|
|
55
|
+
const timeoutField = task['verifierTimeoutSeconds'] === undefined ? {} :
|
|
56
|
+
{ verifierTimeoutSeconds: parseVerifierTimeoutSeconds(task['verifierTimeoutSeconds']) };
|
|
51
57
|
if (shouldTrigger !== undefined && typeof shouldTrigger !== 'boolean') {
|
|
52
58
|
throw new Error(`bench.json task "${id}" has an invalid "shouldTrigger" field`);
|
|
53
59
|
}
|
|
@@ -97,9 +103,9 @@ export function validateBenchTask(benchDir, raw, index) {
|
|
|
97
103
|
if (!existsSync(rubricAbs) || !statSync(rubricAbs).isFile()) {
|
|
98
104
|
throw new Error(`task "${id}" rubric file not found: ${rubric}`);
|
|
99
105
|
}
|
|
100
|
-
return { id, fixture, prompt, verifier, rubric, ...triggerField, ...promptTriggerField, ...verifierKindField, ...oracleField };
|
|
106
|
+
return { id, fixture, prompt, verifier, rubric, ...triggerField, ...promptTriggerField, ...verifierKindField, ...timeoutField, ...oracleField };
|
|
101
107
|
}
|
|
102
|
-
return { id, fixture, prompt, verifier, ...triggerField, ...promptTriggerField, ...verifierKindField, ...oracleField };
|
|
108
|
+
return { id, fixture, prompt, verifier, ...triggerField, ...promptTriggerField, ...verifierKindField, ...timeoutField, ...oracleField };
|
|
103
109
|
}
|
|
104
110
|
export function loadBench(benchDir) {
|
|
105
111
|
const dir = resolve(benchDir);
|
|
@@ -129,7 +135,7 @@ export function loadBench(benchDir) {
|
|
|
129
135
|
seen.add(task.id);
|
|
130
136
|
}
|
|
131
137
|
const name = typeof raw.name === 'string' && raw.name.trim() !== '' ? raw.name : basename(dir);
|
|
132
|
-
const contentSha256 = hashFileSet(dir, listFilesRecursive(dir));
|
|
138
|
+
const contentSha256 = hashFileSet(dir, listFilesRecursive(dir, { excludeGitMetadata: true }));
|
|
133
139
|
return { dir, name, schemaVersion: BENCH_SCHEMA_VERSION, tasks, contentSha256 };
|
|
134
140
|
}
|
|
135
141
|
/** Keep manifest order so selecting IDs cannot silently change balanced pair order. */
|
|
@@ -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,15 +6,19 @@ import { loadBench } from './bench.js';
|
|
|
6
6
|
import { summarizeCosts } from './costs.js';
|
|
7
7
|
import { policyHash, parseAcceptancePolicy, readComponentJson, record } from './eval-contract.js';
|
|
8
8
|
import { costChanges } from './eval-acceptance.js';
|
|
9
|
-
import { sha256File } from './hash.js';
|
|
9
|
+
import { sha256File, sha256Text } from './hash.js';
|
|
10
10
|
import { collectInstalledSkillTarget } from './installed-skill.js';
|
|
11
|
-
import { runVerifier } from './runner.js';
|
|
11
|
+
import { runVerifier, summarizeJudge } from './runner.js';
|
|
12
12
|
import { verdictFromOutput } from './verifier-summary.js';
|
|
13
13
|
import { parseEvalReport } from '../commands/eval-report.js';
|
|
14
14
|
import { pairConditions } from './types.js';
|
|
15
15
|
import { NATIVE_DIFF_PATH, NATIVE_DIFF_SNAPSHOT } from './native-diff.js';
|
|
16
16
|
import { assertSpendingCanContinue, parseSpendingBudget, spendingBudgetState } from './eval-budget.js';
|
|
17
17
|
import { verifyInputSnapshot } from './input-snapshot.js';
|
|
18
|
+
import { assertRecordedAgentEnvironment } from './agent-preflight.js';
|
|
19
|
+
import { judgeCallReceipt } from './judge-audit.js';
|
|
20
|
+
import { buildJudgePrompt, judgeOrder } from './judge.js';
|
|
21
|
+
import { summarizeInvocationCosts } from './invocation-costs.js';
|
|
18
22
|
function inside(root, path) {
|
|
19
23
|
const rel = relative(root, path);
|
|
20
24
|
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
|
|
@@ -102,6 +106,34 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
102
106
|
const plan = record(readComponentJson(join(root, '_plan.json')).value, 'native plan');
|
|
103
107
|
const inputSnapshot = verifyInputSnapshot(root, plan);
|
|
104
108
|
const details = record(plan.details, 'native plan details');
|
|
109
|
+
if (details.agentPreflight !== undefined)
|
|
110
|
+
assertRecordedAgentEnvironment(details.agentPreflight);
|
|
111
|
+
if (details.reviewedPlan !== undefined) {
|
|
112
|
+
const reviewed = record(details.reviewedPlan, 'reviewed plan'), { sha256, ...data } = reviewed;
|
|
113
|
+
assert.equal(data.schemaVersion, 1);
|
|
114
|
+
assert.equal(data.kind, 'skillfit.eval-plan');
|
|
115
|
+
assert.equal(sha256Text(JSON.stringify(data)), sha256, 'Reviewed plan hash changed.');
|
|
116
|
+
const e = record(data.evaluation, 'reviewed evaluation');
|
|
117
|
+
assert.equal(e.mode, details.mode);
|
|
118
|
+
assert.equal(record(e.target, 'reviewed target').kind, report.target.kind);
|
|
119
|
+
const implementation = plan.inputs.find(input => input.label === 'implementation');
|
|
120
|
+
assert.equal(implementation?.sha256, data.implementationSha256, 'Reviewed implementation differs from native inputs.');
|
|
121
|
+
assert.equal(record(e.target, 'reviewed target').sha256, report.target.sha256);
|
|
122
|
+
assert.equal(record(e.bench, 'reviewed bench').sha256, report.bench.sha256);
|
|
123
|
+
assert.deepEqual(record(e.bench, 'reviewed bench').taskIds, report.tasks.map(task => task.id));
|
|
124
|
+
assert.equal(e.baseline === null ? null : record(e.baseline, 'reviewed baseline').sha256, report.baselineTarget?.sha256 ?? null);
|
|
125
|
+
assert.deepEqual(e.executor, raw.executor);
|
|
126
|
+
assert.deepEqual(e.judge, raw.judge);
|
|
127
|
+
assert.equal(e.trials, report.trials);
|
|
128
|
+
assert.equal(e.plannedCalls, report.experiment.plannedCalls);
|
|
129
|
+
assert.equal(e.maxCalls, report.experiment.maxCalls);
|
|
130
|
+
assert.equal(e.inputMode, raw.inputMode);
|
|
131
|
+
assert.equal(e.installDir, report.skillDelivery?.installDir ?? null);
|
|
132
|
+
assert.equal(e.pairOrder, details.pairOrder);
|
|
133
|
+
assert.equal(e.executorTimeoutSeconds, details.executorTimeoutSeconds);
|
|
134
|
+
assert.deepEqual(e.spendingBudget, details.spendingBudget, 'Reviewed spending limits differ from the native plan.');
|
|
135
|
+
assert.deepEqual(e.agentPreflight, details.agentPreflight, 'Reviewed Agent preflight differs from the native plan.');
|
|
136
|
+
}
|
|
105
137
|
let pairOrder = null;
|
|
106
138
|
if (raw.pairOrder !== undefined || details.pairOrder !== undefined) {
|
|
107
139
|
assert.ok(raw.pairOrder === 'baseline-first' || raw.pairOrder === 'balanced', 'Invalid recorded pair order.');
|
|
@@ -147,6 +179,8 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
147
179
|
let invoked = 0;
|
|
148
180
|
const expectedAgentOrder = [];
|
|
149
181
|
const budgetReceipts = new Map();
|
|
182
|
+
const expectedDispatches = [];
|
|
183
|
+
const judgeCalls = [];
|
|
150
184
|
const rawTasks = raw.tasks;
|
|
151
185
|
for (const [taskIndex, task] of report.tasks.entries()) {
|
|
152
186
|
assert.ok(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(task.id), 'Unsafe task id.');
|
|
@@ -167,7 +201,7 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
167
201
|
if (details.nativeDiffTool !== undefined && r.executorInvoked) {
|
|
168
202
|
assert.equal(sha256File(member(root, `${task.id}/${arm}/trial-${trial}/${NATIVE_DIFF_PATH}`)), record(details.nativeDiffTool, 'native diff tool').sha256, 'Delivered native diff tool changed.');
|
|
169
203
|
}
|
|
170
|
-
if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false) {
|
|
204
|
+
if (details.executorTimeoutSeconds !== undefined && r.executorInvoked && plan.injectedExecutor === false && report.executor.kind === 'cli') {
|
|
171
205
|
assert.ok(typeof details.executorTimeoutSeconds === 'number' && Number.isSafeInteger(details.executorTimeoutSeconds) && details.executorTimeoutSeconds >= 1 && details.executorTimeoutSeconds <= 3600);
|
|
172
206
|
const actualTiming = record(record(r.timing, 'CLI timing').execution, 'CLI execution timing');
|
|
173
207
|
assert.equal(actualTiming.timeoutMs, details.executorTimeoutSeconds * 1000, 'CLI deadline differs from the native plan.');
|
|
@@ -194,7 +228,8 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
194
228
|
const scratch = mkdtempSync(join(tmpdir(), 'skillfit-eval-replay-'));
|
|
195
229
|
try {
|
|
196
230
|
cpSync(join(root, task.id, arm, `trial-${trial}`), scratch, { recursive: true, filter: path => basename(path) !== '.git' });
|
|
197
|
-
const grade = await runVerifier(bench.dir, definition.verifier, scratch), summary = verdictFromOutput(grade.output);
|
|
231
|
+
const grade = await runVerifier(bench.dir, definition.verifier, scratch, definition.verifierTimeoutSeconds), summary = verdictFromOutput(grade.output);
|
|
232
|
+
assert.equal(grade.error, null, `Replay verifier failed: ${grade.error}`);
|
|
198
233
|
assert.notEqual(grade.exitCode, null);
|
|
199
234
|
assert.equal(grade.exitCode, r.verifierExitCode);
|
|
200
235
|
assert.equal(grade.exitCode === 0, r.passed);
|
|
@@ -215,8 +250,10 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
215
250
|
const b = pair.baseline, t = pair.treatment;
|
|
216
251
|
if (pairOrder)
|
|
217
252
|
for (const arm of pairConditions(pairOrder, taskIndex, trial)) {
|
|
218
|
-
if (pair[arm].executorInvoked)
|
|
253
|
+
if (pair[arm].executorInvoked) {
|
|
219
254
|
expectedAgentOrder.push(`${task.id}/${arm}/trial-${trial}`);
|
|
255
|
+
expectedDispatches.push({ role: 'agent', identity: { taskId: task.id, condition: arm, trial }, receipt: pair[arm] });
|
|
256
|
+
}
|
|
220
257
|
}
|
|
221
258
|
const graded = b.error === null && t.error === null;
|
|
222
259
|
const changes = [];
|
|
@@ -239,38 +276,101 @@ export async function auditEvaluation(value, runDir, options = {}) {
|
|
|
239
276
|
const outcomes = record(source.outcomes, 'paired outcomes');
|
|
240
277
|
for (const arm of ['baseline', 'treatment'])
|
|
241
278
|
assert.deepEqual(taskPaired[arm].map(r => r.passed), outcomes[arm]);
|
|
279
|
+
if (raw.judge != null) {
|
|
280
|
+
assert.ok(raw.invocationCosts != null, 'Judge usage unrecorded; cannot verify full invocation accounting.');
|
|
281
|
+
const judged = [];
|
|
282
|
+
for (let trial = 1; trial <= report.trials; trial++) {
|
|
283
|
+
const baseline = budgetReceipts.get(`${task.id}/baseline/trial-${trial}`);
|
|
284
|
+
const treatment = budgetReceipts.get(`${task.id}/treatment/trial-${trial}`);
|
|
285
|
+
if (baseline.error !== null || treatment.error !== null)
|
|
286
|
+
continue;
|
|
287
|
+
const seed = `${raw.runGroup}:${task.id}:${trial}`, order = judgeOrder(seed), calls = [];
|
|
288
|
+
for (const callIndex of [1, 2]) {
|
|
289
|
+
const path = `${task.id}/judge-trial-${trial}/call-${callIndex}.json`;
|
|
290
|
+
assert.equal(typeof files[path], 'string', 'Judge invocation receipt was not sealed.');
|
|
291
|
+
const call = judgeCallReceipt(readComponentJson(member(root, path)).value);
|
|
292
|
+
assert.equal(call.taskId, task.id);
|
|
293
|
+
assert.equal(call.trial, trial);
|
|
294
|
+
assert.equal(call.callIndex, callIndex);
|
|
295
|
+
assert.equal(call.seed, seed);
|
|
296
|
+
assert.equal(call.firstCondition, order[callIndex - 1]);
|
|
297
|
+
assert.equal(call.error, null);
|
|
298
|
+
assert.deepEqual(call.executor, raw.judge, 'Judge receipt executor differs from frozen metadata.');
|
|
299
|
+
if (details.executorTimeoutSeconds !== undefined && plan.injectedExecutor === false && record(raw.judge, 'judge').kind === 'cli') {
|
|
300
|
+
assert.equal(record(call.timing.execution, 'judge execution timing').timeoutMs, Number(details.executorTimeoutSeconds) * 1000, 'Judge deadline differs from the native plan.');
|
|
301
|
+
}
|
|
302
|
+
const nonce = call.prompt.match(/<<<BEGIN ANSWER A ([0-9a-f]{16})>>>/)?.[1];
|
|
303
|
+
assert.ok(nonce, 'Judge prompt anonymity nonce is missing.');
|
|
304
|
+
const benchSource = inputSnapshot?.roots.get('bench');
|
|
305
|
+
assert.ok(benchSource, 'Judge prompt auditing requires the sealed bench input.');
|
|
306
|
+
const frozenBench = loadBench(benchSource), definition = frozenBench.tasks.find(t => t.id === task.id);
|
|
307
|
+
assert.ok(definition);
|
|
308
|
+
const baseOutput = readFileSync(member(root, `${task.id}/baseline/trial-${trial}/_output.md`), 'utf8');
|
|
309
|
+
const treatmentOutput = readFileSync(member(root, `${task.id}/treatment/trial-${trial}/_output.md`), 'utf8');
|
|
310
|
+
assert.deepEqual(call.prompt, buildJudgePrompt(readFileSync(join(benchSource, definition.prompt), 'utf8'), definition.rubric ? readFileSync(join(benchSource, definition.rubric), 'utf8') : null, call.firstCondition === 'baseline' ? baseOutput : treatmentOutput, call.firstCondition === 'baseline' ? treatmentOutput : baseOutput, nonce), 'Judge prompt differs from the sealed task and anonymized answers.');
|
|
311
|
+
calls.push(call);
|
|
312
|
+
judgeCalls.push(call);
|
|
313
|
+
audit.receipts++;
|
|
314
|
+
expectedDispatches.push({ role: 'judge', identity: { role: 'judge', taskId: task.id, trial, callIndex }, receipt: call, promptSha256: call.promptSha256 });
|
|
315
|
+
}
|
|
316
|
+
const forward = calls[0].scores, reverse = calls[1].scores;
|
|
317
|
+
const result = { baselineScore: (forward.baseline + reverse.baseline) / 2, treatmentScore: (forward.treatment + reverse.treatment) / 2,
|
|
318
|
+
consistent: Math.sign(forward.baseline - forward.treatment) === Math.sign(reverse.baseline - reverse.treatment),
|
|
319
|
+
firstCondition: order[0], raw: `${calls[0].output}\n--- reverse order ---\n${calls[1].output}`, calls };
|
|
320
|
+
const path = `${task.id}/judge-trial-${trial}.json`;
|
|
321
|
+
assert.equal(typeof files[path], 'string');
|
|
322
|
+
assert.deepEqual(readComponentJson(member(root, path)).value, { trial, seed, ...result }, 'Judge pair summary differs from independent invocation receipts.');
|
|
323
|
+
judged.push(result);
|
|
324
|
+
}
|
|
325
|
+
assert.deepEqual(source.judge, summarizeJudge(judged), 'Judge task summary differs from invocation receipts.');
|
|
326
|
+
}
|
|
242
327
|
}
|
|
243
328
|
assert.deepEqual(summarizeCosts(all, paired), report.overall.costs, 'Overall cost accounting differs from receipts.');
|
|
244
329
|
const ledger = readFileSync(join(root, '_calls.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => record(JSON.parse(line), 'ledger'));
|
|
330
|
+
const startedEvents = ledger.filter(e => e.event === 'started'), terminalEvents = ledger.filter(e => e.event === 'finished' || e.event === 'failed');
|
|
331
|
+
assert.equal(terminalEvents.length, report.experiment.callsFinished, 'Terminal call ledger differs from session accounting.');
|
|
332
|
+
for (const [ordinal, event] of startedEvents.entries()) {
|
|
333
|
+
assert.equal(event.call, ordinal + 1, 'Call ledger dispatch numbers must be consecutive.');
|
|
334
|
+
assert.ok(event.role === 'agent' || event.role === 'judge');
|
|
335
|
+
assert.ok(typeof event.promptSha256 === 'string' && /^[a-f0-9]{64}$/.test(event.promptSha256));
|
|
336
|
+
assert.equal(terminalEvents.filter(terminal => terminal.call === event.call).length, 1, 'Each dispatched call needs one terminal ledger receipt.');
|
|
337
|
+
}
|
|
245
338
|
assert.equal(ledger.filter(e => e.event === 'started' && e.role === 'agent').length, invoked);
|
|
246
339
|
assert.equal(ledger.filter(e => e.event === 'started').length, report.experiment.callsStarted);
|
|
247
340
|
if (pairOrder)
|
|
248
341
|
assert.deepEqual(ledger.filter(e => e.event === 'started' && e.role === 'agent')
|
|
249
342
|
.map(e => String(e.workdir).split(/[\\/]/).slice(-3).join('/')), expectedAgentOrder, 'Recorded execution order differs from the frozen pair order.');
|
|
343
|
+
if (raw.invocationCosts !== undefined) {
|
|
344
|
+
assert.deepEqual(raw.invocationCosts, summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeCalls, raw.judge != null), 'Full invocation accounting differs from agent/judge receipts.');
|
|
345
|
+
const started = ledger.filter(e => e.event === 'started');
|
|
346
|
+
assert.equal(started.length, expectedDispatches.length, 'Agent/judge receipt coverage differs from the dispatch ledger.');
|
|
347
|
+
for (const [index, event] of started.entries()) {
|
|
348
|
+
const expected = expectedDispatches[index];
|
|
349
|
+
assert.equal(event.role, expected.role, 'Agent/judge dispatch order differs from frozen execution.');
|
|
350
|
+
if (expected.promptSha256)
|
|
351
|
+
assert.equal(event.promptSha256, expected.promptSha256, 'Judge invocation prompt hash differs from the call ledger.');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
250
354
|
if (details.spendingBudget !== undefined) {
|
|
251
355
|
const limits = parseSpendingBudget(details.spendingBudget);
|
|
252
356
|
assert.ok(pairOrder, 'Budget replay requires the recorded pair order.');
|
|
253
357
|
assert.ok(typeof files['_budget.jsonl'] === 'string', 'Budget events are not sealed.');
|
|
254
358
|
const events = readFileSync(join(root, '_budget.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
255
|
-
assert.equal(events.length,
|
|
359
|
+
assert.equal(events.length, expectedDispatches.length * 2, 'Budget event coverage differs from calls.');
|
|
256
360
|
const observations = [];
|
|
257
|
-
for (const [ordinal,
|
|
258
|
-
const [taskId, condition, trialPath] = path.split('/');
|
|
259
|
-
const trial = Number(trialPath.slice('trial-'.length));
|
|
361
|
+
for (const [ordinal, dispatch] of expectedDispatches.entries()) {
|
|
260
362
|
const before = spendingBudgetState(limits, observations);
|
|
261
363
|
assertSpendingCanContinue(before);
|
|
262
|
-
assert.deepEqual(events[ordinal * 2], { phase: 'before-call',
|
|
263
|
-
observations.push(
|
|
364
|
+
assert.deepEqual(events[ordinal * 2], { phase: 'before-call', ...dispatch.identity, state: before }, 'Budget before-call state differs from receipts.');
|
|
365
|
+
observations.push(dispatch.receipt);
|
|
264
366
|
const after = spendingBudgetState(limits, observations);
|
|
265
367
|
assert.equal(after.incomplete.length, 0, 'Budget run has missing final usage.');
|
|
266
368
|
assert.notEqual(after.reason, 'EXECUTION_FAILED');
|
|
267
|
-
assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call',
|
|
369
|
+
assert.deepEqual(events[ordinal * 2 + 1], { phase: 'after-call', ...dispatch.identity, state: after }, 'Budget after-call state differs from receipts.');
|
|
268
370
|
}
|
|
269
371
|
}
|
|
270
372
|
else
|
|
271
373
|
assert.equal(files['_budget.jsonl'], undefined, 'Budget events were not declared in the native plan.');
|
|
272
|
-
// This component does not run a judge whose separate usage would be absent from agent costs.
|
|
273
|
-
assert.ok(raw.judge == null, 'Judge usage is not covered by component accounting.');
|
|
274
374
|
audit.verified = true;
|
|
275
375
|
}
|
|
276
376
|
catch (error) {
|
|
@@ -307,9 +407,54 @@ export function stoppedAccounting(runDir) {
|
|
|
307
407
|
}
|
|
308
408
|
}
|
|
309
409
|
const populations = summarizeCosts(all, paired);
|
|
410
|
+
const judgeEvents = ledger.filter(e => e.event === 'started' && e.role === 'judge');
|
|
411
|
+
const retainedJudgeCalls = new Map();
|
|
412
|
+
const walkJudge = (dir, prefix = '') => {
|
|
413
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
414
|
+
if (!entry.isDirectory() || entry.name === '.git' || entry.name === '_inputs')
|
|
415
|
+
continue;
|
|
416
|
+
const path = join(dir, entry.name), rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
417
|
+
if (/^[a-zA-Z0-9][a-zA-Z0-9._-]*\/judge-trial-[0-9]+$/.test(rel)) {
|
|
418
|
+
for (const name of ['call-1.json', 'call-2.json'])
|
|
419
|
+
if (existsSync(join(path, name))) {
|
|
420
|
+
try {
|
|
421
|
+
const value = readComponentJson(join(path, name)).value, r = record(value, 'judge receipt');
|
|
422
|
+
if (typeof r.promptSha256 === 'string')
|
|
423
|
+
retainedJudgeCalls.set(r.promptSha256, { path: `${rel}/${name}`, value });
|
|
424
|
+
}
|
|
425
|
+
catch { /* Unparseable files remain on disk; unmatched dispatch is unknown below. */ }
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
else if (!prefix)
|
|
429
|
+
walkJudge(path, rel);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
walkJudge(root);
|
|
433
|
+
let missingJudgeReceipts = 0;
|
|
434
|
+
const judgeObservations = judgeEvents.map(event => {
|
|
435
|
+
const retained = retainedJudgeCalls.get(String(event.promptSha256));
|
|
436
|
+
if (retained) {
|
|
437
|
+
try {
|
|
438
|
+
const receipt = judgeCallReceipt(retained.value);
|
|
439
|
+
assert.equal(receipt.executorInvoked, true);
|
|
440
|
+
return receipt;
|
|
441
|
+
}
|
|
442
|
+
catch (error) {
|
|
443
|
+
invalidReceipts.push({ path: retained.path, reason: String(error) });
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
missingJudgeReceipts++;
|
|
447
|
+
return { executorInvoked: true, passed: false, error: 'Judge invocation receipt missing or invalid', durationSeconds: NaN, tokens: null, usageStatus: 'unknown' };
|
|
448
|
+
});
|
|
449
|
+
const nativePlan = existsSync(join(root, '_plan.json')) ? record(readComponentJson(join(root, '_plan.json')).value, 'native plan') : null;
|
|
450
|
+
const judgeRequested = judgeEvents.length > 0 || Boolean(nativePlan?.details && record(nativePlan.details, 'native plan details').judge != null);
|
|
451
|
+
const invocationCosts = summarizeInvocationCosts([...all.baseline, ...all.treatment], judgeObservations, judgeRequested);
|
|
452
|
+
if (missingJudgeReceipts)
|
|
453
|
+
invocationCosts.judgeUsage = 'unknown';
|
|
310
454
|
return { populations, startedAgentDispatches: all.baseline.length + all.treatment.length,
|
|
311
|
-
|
|
312
|
-
|
|
455
|
+
invocationCosts, startedJudgeDispatches: judgeEvents.length, judgeInvocationsWithUnknownReceipts: missingJudgeReceipts,
|
|
456
|
+
recordedExecutorInvocations: populations.attempts.baseline.runs + populations.attempts.treatment.runs - missingReceipts - invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
|
|
457
|
+
invocationsWithUnknownReceipts: missingReceipts + invalidReceipts.filter(r => !r.path.includes('/judge-trial-')).length,
|
|
313
458
|
...(invalidReceipts.length ? { invalidReceipts } : {}),
|
|
314
|
-
scope: 'Known
|
|
459
|
+
scope: 'Known primary Agent spending and separate all-role invocation totals from stopped-run receipts; missing fields remain unknown. No paired efficacy comparison or exact bill.' };
|
|
315
460
|
}
|