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.
- package/README.md +27 -7
- package/README.zh-CN.md +27 -7
- package/benches/README.md +2 -2
- package/dist/cli.js +146 -36
- package/dist/cli.test.js +94 -0
- package/dist/commands/bench-calibration.js +197 -0
- package/dist/commands/bench-calibration.test.js +237 -0
- package/dist/commands/bench-check-json.test.js +24 -3
- package/dist/commands/bench.js +69 -141
- package/dist/commands/calibration-cli.test.js +145 -0
- package/dist/commands/eval-agent-preflight.test.js +245 -0
- package/dist/commands/eval-cli.js +31 -0
- package/dist/commands/eval-component.js +59 -28
- package/dist/commands/eval-export-modes.test.js +350 -0
- package/dist/commands/eval-export.js +44 -10
- package/dist/commands/eval-export.test.js +165 -8
- package/dist/commands/eval-interruption.test.js +238 -0
- package/dist/commands/eval-plan.js +37 -0
- package/dist/commands/eval-preflight.js +61 -0
- package/dist/commands/eval-preflight.test.js +382 -0
- package/dist/commands/eval-report.js +60 -14
- package/dist/commands/eval-report.test.js +2 -2
- 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 +184 -112
- package/dist/commands/evaluation-report.js +5 -0
- package/dist/commands/evaluation-report.test.js +243 -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 +180 -0
- package/dist/harness/bench.js +2 -1
- package/dist/harness/command.js +49 -0
- package/dist/harness/eval-audit.js +164 -17
- package/dist/harness/eval-budget.js +46 -2
- package/dist/harness/eval-budget.test.js +30 -3
- package/dist/harness/eval-component.test.js +169 -6
- package/dist/harness/eval-contract.js +11 -5
- package/dist/harness/executors/api.js +14 -4
- package/dist/harness/executors/api.test.js +61 -0
- package/dist/harness/executors/cli.js +24 -3
- package/dist/harness/experiment-session.js +77 -18
- package/dist/harness/experiment-session.test.js +51 -1
- package/dist/harness/input-snapshot.js +150 -0
- package/dist/harness/interruption.js +48 -0
- package/dist/harness/interruption.test.js +31 -0
- 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 +92 -44
- package/dist/harness/runner.test.js +23 -0
- package/dist/harness/single-arm-audit.js +436 -0
- package/dist/harness/trigger.js +41 -7
- package/dist/harness/trigger.test.js +12 -0
- package/dist/harness/verifier-error.js +65 -0
- package/dist/harness/verifier.test.js +128 -0
- package/docs/bench-authoring.md +34 -9
- package/docs/bench-check-json.md +36 -6
- package/docs/eval-agent-preflight.md +101 -0
- package/docs/eval-case-preflight.md +115 -0
- package/docs/eval-component.md +65 -9
- package/docs/eval-costs.md +53 -0
- package/docs/eval-planning.md +153 -0
- package/docs/evaluation-input-snapshots.md +125 -0
- package/docs/evaluation-interruption.md +101 -0
- package/docs/evaluation-reports.md +143 -0
- package/docs/experiment-workflow.md +16 -2
- package/docs/first-real-eval.md +55 -5
- package/docs/growth-roadmap-2026-10.md +48 -11
- package/docs/metrics.md +71 -3
- package/docs/plans/2026-10-16-case-workflow-and-release.md +19 -0
- package/docs/plans/2026-10-17-workflow-foundations.md +64 -0
- package/docs/releases/0.10.0-ci-registry-install.json +140 -0
- package/docs/releases/0.10.0-feature-smoke.json +22 -0
- package/docs/releases/0.10.0-feature-smoke.mjs +62 -0
- package/docs/releases/0.10.0-signatures.txt +7 -0
- package/docs/releases/0.10.0-verification.json +76 -0
- package/docs/releases/0.10.0.md +44 -8
- 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-feature-smoke.mjs +95 -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 +71 -0
- package/docs/releases/0.11.0-feature-smoke.mjs +224 -0
- package/docs/releases/0.11.0.md +47 -0
- package/docs/replay-packages.md +52 -11
- 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-preflight.schema.json +57 -0
- package/docs/schemas/eval-request.schema.json +1 -1
- package/docs/schemas/eval-result.schema.json +14 -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 +8 -2
- package/docs/verifier-contract.md +99 -0
- package/package.json +1 -1
- package/skills/skillfit/SKILL.md +41 -8
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, 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 { runEval } from '../commands/eval.js';
|
|
7
|
+
import { auditEvaluation, stoppedAccounting } from './eval-audit.js';
|
|
8
|
+
import { sha256File } from './hash.js';
|
|
9
|
+
import { JudgePairFailure, judgePair } from './judge.js';
|
|
10
|
+
import { judgeCallReceipt } from './judge-audit.js';
|
|
11
|
+
import { historicalInvocationCosts, invocationPopulation, parseInvocationCosts, summarizeInvocationCosts } from './invocation-costs.js';
|
|
12
|
+
import { ExecutorFailure } from './types.js';
|
|
13
|
+
const checklist = '{"A":{"correct":true,"complete":true,"grounded":true},"B":{"correct":true,"complete":true,"grounded":true}}';
|
|
14
|
+
const budget = { input: 1000, cachedInput: 1000, uncachedInput: 1000, output: 1000, durationSeconds: 1000 };
|
|
15
|
+
const primaryTokens = { input: 10, cachedInput: 6, output: 3 };
|
|
16
|
+
const judgeTokens = { input: 5, cachedInput: 2, output: 1 };
|
|
17
|
+
function setup(t, judgeResult = () => ({ output: checklist, rawOutput: 'judge raw transcript', tokens: judgeTokens })) {
|
|
18
|
+
const root = mkdtempSync(join(tmpdir(), 'skillfit-judge-accounting-'));
|
|
19
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
20
|
+
const skill = join(root, 'skill'), bench = join(root, 'bench');
|
|
21
|
+
mkdirSync(skill);
|
|
22
|
+
mkdirSync(join(bench, 'fixture'), { recursive: true });
|
|
23
|
+
writeFileSync(join(skill, 'SKILL.md'), '---\nname: audit-skill\ndescription: Offline test.\n---\nReturn the answer.\n');
|
|
24
|
+
writeFileSync(join(bench, 'fixture/answer.txt'), 'pending');
|
|
25
|
+
writeFileSync(join(bench, 'prompt.md'), 'Return an answer.');
|
|
26
|
+
writeFileSync(join(bench, 'check.mjs'), `import{existsSync,readFileSync}from'node:fs';import{join}from'node:path';const file=join(process.argv[2],'_output.md');process.exit(existsSync(file)&&readFileSync(file,'utf8').trim()?0:1);\n`);
|
|
27
|
+
writeFileSync(join(bench, 'bench.json'), JSON.stringify({ schemaVersion: 1, name: 'judge-costs', tasks: [{ id: 'answer', fixture: 'fixture', prompt: 'prompt.md', verifier: 'node check.mjs' }] }));
|
|
28
|
+
let primaryCalls = 0, judgeCalls = 0;
|
|
29
|
+
const executor = { describe: () => ({ kind: 'mock', model: 'offline-primary' }), run: async () => {
|
|
30
|
+
primaryCalls++;
|
|
31
|
+
return { output: 'answer', tokens: primaryTokens };
|
|
32
|
+
} };
|
|
33
|
+
const judge = { describe: () => ({ kind: 'mock', model: 'offline-judge' }), run: async () => judgeResult(++judgeCalls) };
|
|
34
|
+
return { root, executor, judge, counts: () => ({ primary: primaryCalls, judge: judgeCalls }), directory: join(root, 'runs/judge'),
|
|
35
|
+
options: { skillPath: skill, bench, executor, judgeExecutor: judge, trials: 1, maxCalls: 4, runsRoot: join(root, 'runs'), runGroup: 'judge',
|
|
36
|
+
dryRun: false, yes: true, log: () => { }, sessionOptions: { homeDir: root, env: {}, versionProbe: () => null } } };
|
|
37
|
+
}
|
|
38
|
+
function reseal(directory, relative, value) {
|
|
39
|
+
writeFileSync(join(directory, relative), JSON.stringify(value, null, 2) + '\n');
|
|
40
|
+
const indexPath = join(directory, '_artifacts.json'), index = JSON.parse(readFileSync(indexPath, 'utf8'));
|
|
41
|
+
index.files[relative] = sha256File(join(directory, relative));
|
|
42
|
+
writeFileSync(indexPath, JSON.stringify(index, null, 2) + '\n');
|
|
43
|
+
}
|
|
44
|
+
test('each judge order retains independent complete usage and transcript; total budget/audit includes all four calls', async (t) => {
|
|
45
|
+
const f = setup(t), manifest = await runEval({ ...f.options, spendingBudget: budget });
|
|
46
|
+
assert.ok(manifest && 'overall' in manifest);
|
|
47
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
|
|
48
|
+
const calls = [1, 2].map(i => judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, `answer/judge-trial-1/call-${i}.json`), 'utf8'))));
|
|
49
|
+
for (const call of calls) {
|
|
50
|
+
assert.deepEqual(call.tokens, judgeTokens);
|
|
51
|
+
assert.equal(call.usageStatus, 'final');
|
|
52
|
+
assert.equal(call.rawOutput, 'judge raw transcript');
|
|
53
|
+
assert.equal(call.timing.clock, 'performance.now');
|
|
54
|
+
}
|
|
55
|
+
assert.notEqual(calls[0].promptSha256, calls[1].promptSha256);
|
|
56
|
+
assert.equal(manifest.overall.costs.attempts.baseline.metrics.input.knownTotal, 10);
|
|
57
|
+
assert.equal(manifest.overall.costs.attempts.treatment.metrics.input.knownTotal, 10);
|
|
58
|
+
assert.equal(manifest.invocationCosts.judge.metrics.input.knownTotal, 10);
|
|
59
|
+
assert.equal(manifest.invocationCosts.total.metrics.input.knownTotal, 30);
|
|
60
|
+
assert.equal(manifest.invocationCosts.total.metrics.cachedInput.knownTotal, 16);
|
|
61
|
+
const events = readFileSync(join(f.directory, '_budget.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line));
|
|
62
|
+
assert.equal(events.length, 8);
|
|
63
|
+
assert.equal(events.at(-1).state.invocations, 4);
|
|
64
|
+
assert.equal(events.at(-1).state.metrics.input.knownTotal, 30);
|
|
65
|
+
const audited = await auditEvaluation(manifest, f.directory, { replay: true });
|
|
66
|
+
assert.equal(audited.verified, true, audited.reasons.join('\n'));
|
|
67
|
+
assert.equal(audited.receipts, 4);
|
|
68
|
+
assert.equal(audited.replayedDeliveries, 2);
|
|
69
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
|
|
70
|
+
});
|
|
71
|
+
test('malformed judge JSON is retained with final spending and stops instead of launching its reverse order', async (t) => {
|
|
72
|
+
const f = setup(t, () => ({ output: 'malformed but charged', tokens: judgeTokens, rawOutput: 'retained raw' }));
|
|
73
|
+
await assert.rejects(runEval({ ...f.options, spendingBudget: budget }), /EXECUTION_FAILED|checklist JSON/);
|
|
74
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
|
|
75
|
+
const call = judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-1.json'), 'utf8')));
|
|
76
|
+
assert.match(call.error, /checklist JSON/);
|
|
77
|
+
assert.equal(call.output, 'malformed but charged');
|
|
78
|
+
assert.equal(call.usageStatus, 'final');
|
|
79
|
+
const costs = stoppedAccounting(f.directory);
|
|
80
|
+
assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 25);
|
|
81
|
+
assert.equal(costs.startedJudgeDispatches, 1);
|
|
82
|
+
assert.equal(costs.judgeInvocationsWithUnknownReceipts, 0);
|
|
83
|
+
assert.ok(existsSync(join(f.directory, '_artifacts.json')));
|
|
84
|
+
assert.ok(existsSync(join(f.directory, 'answer/judge-trial-1-error.json')));
|
|
85
|
+
});
|
|
86
|
+
test('reverse judge execution failure retains its partial public output and lower-bound counters', async (t) => {
|
|
87
|
+
const f = setup(t, index => {
|
|
88
|
+
if (index === 1)
|
|
89
|
+
return { output: checklist, tokens: judgeTokens };
|
|
90
|
+
throw new ExecutorFailure('offline routing failure', { output: 'partial answer', rawOutput: 'partial raw', tokens: { input: 7, output: 2 }, usageStatus: 'partial' });
|
|
91
|
+
});
|
|
92
|
+
await assert.rejects(runEval(f.options), /routing failure/);
|
|
93
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 2 });
|
|
94
|
+
const costs = stoppedAccounting(f.directory), judge = costs.invocationCosts.judge;
|
|
95
|
+
assert.equal(judge.runs, 2);
|
|
96
|
+
assert.equal(judge.metrics.input.knownTotal, 12);
|
|
97
|
+
assert.equal(judge.metrics.input.coverage.partial, 1);
|
|
98
|
+
assert.equal(judge.metrics.cachedInput.coverage.unknown, 1);
|
|
99
|
+
assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 32);
|
|
100
|
+
const retained = JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-2.json'), 'utf8'));
|
|
101
|
+
assert.equal(retained.output, 'partial answer');
|
|
102
|
+
assert.equal(retained.rawOutput, 'partial raw');
|
|
103
|
+
assert.equal(retained.scores, null);
|
|
104
|
+
});
|
|
105
|
+
test('interrupting an offline judge seals its partial receipt and stops before reverse order', async (t) => {
|
|
106
|
+
const previousExit = process.exitCode, listeners = process.listenerCount('SIGINT');
|
|
107
|
+
t.after(() => { process.exitCode = previousExit; });
|
|
108
|
+
const f = setup(t, () => {
|
|
109
|
+
process.emit('SIGINT');
|
|
110
|
+
throw new ExecutorFailure('simulated interrupted judge', { output: 'retained interrupted text',
|
|
111
|
+
rawOutput: 'retained interrupted transcript', tokens: { input: 8, cachedInput: 3, output: 1 }, usageStatus: 'partial' });
|
|
112
|
+
});
|
|
113
|
+
try {
|
|
114
|
+
await assert.rejects(runEval(f.options), /interrupted by SIGINT/);
|
|
115
|
+
assert.equal(process.exitCode, 130);
|
|
116
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
|
|
117
|
+
assert.equal(process.listenerCount('SIGINT'), listeners);
|
|
118
|
+
const call = judgeCallReceipt(JSON.parse(readFileSync(join(f.directory, 'answer/judge-trial-1/call-1.json'), 'utf8')));
|
|
119
|
+
assert.equal(call.output, 'retained interrupted text');
|
|
120
|
+
assert.equal(call.usageStatus, 'partial');
|
|
121
|
+
const costs = stoppedAccounting(f.directory);
|
|
122
|
+
assert.equal(costs.invocationCosts.total.metrics.input.knownTotal, 28);
|
|
123
|
+
assert.equal(costs.invocationCosts.judge.metrics.input.coverage.partial, 1);
|
|
124
|
+
assert.ok(existsSync(join(f.directory, '_interruption.json')));
|
|
125
|
+
assert.ok(existsSync(join(f.directory, '_artifacts.json')));
|
|
126
|
+
assert.equal(existsSync(join(f.directory, 'answer/judge-trial-1/call-2.json')), false);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
process.exitCode = previousExit;
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
test('missing judge usage or reached total spending stops before reverse order, with no retries or replacements', async (t) => {
|
|
133
|
+
for (const [label, result, limits] of [
|
|
134
|
+
['unknown', { output: checklist }, budget],
|
|
135
|
+
['line', { output: checklist, tokens: judgeTokens }, { ...budget, input: 25 }],
|
|
136
|
+
]) {
|
|
137
|
+
const f = setup(t, () => result);
|
|
138
|
+
await assert.rejects(runEval({ ...f.options, spendingBudget: limits }), label === 'unknown' ? /FINAL_USAGE_MISSING/ : /SPENDING_BUDGET_REACHED/);
|
|
139
|
+
assert.deepEqual(f.counts(), { primary: 2, judge: 1 });
|
|
140
|
+
assert.equal(existsSync(join(f.directory, 'answer/judge-trial-1/call-2.json')), false);
|
|
141
|
+
const costs = stoppedAccounting(f.directory);
|
|
142
|
+
assert.equal(costs.invocationCosts.total.runs, 3);
|
|
143
|
+
assert.equal(costs.invocationCosts.judge.metrics.input.coverage.unknown, label === 'unknown' ? 1 : 0);
|
|
144
|
+
const session = JSON.parse(readFileSync(join(f.directory, '_session.json'), 'utf8'));
|
|
145
|
+
assert.equal(session.stopCode, label === 'unknown' ? 'FINAL_USAGE_MISSING' : 'SPENDING_BUDGET_REACHED');
|
|
146
|
+
assert.match(session.stopReason, label === 'unknown' ? /FINAL_USAGE_MISSING/ : /SPENDING_BUDGET_REACHED/);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
test('resealing altered aggregate usage, prompt evidence or missing historical judge usage cannot pass semantic audit', async (t) => {
|
|
150
|
+
for (const mutation of ['total', 'ledger', 'history']) {
|
|
151
|
+
const f = setup(t), manifest = await runEval(f.options);
|
|
152
|
+
assert.ok(manifest && 'overall' in manifest);
|
|
153
|
+
if (mutation === 'total') {
|
|
154
|
+
manifest.invocationCosts.total.metrics.input.knownTotal = 20;
|
|
155
|
+
reseal(f.directory, 'manifest.json', manifest);
|
|
156
|
+
}
|
|
157
|
+
if (mutation === 'history') {
|
|
158
|
+
delete manifest.invocationCosts;
|
|
159
|
+
reseal(f.directory, 'manifest.json', manifest);
|
|
160
|
+
}
|
|
161
|
+
if (mutation === 'ledger') {
|
|
162
|
+
const path = join(f.directory, '_calls.jsonl'), ledger = readFileSync(path, 'utf8').trim().split('\n').map(line => JSON.parse(line));
|
|
163
|
+
ledger.find(row => row.event === 'started' && row.role === 'judge').promptSha256 = '0'.repeat(64);
|
|
164
|
+
writeFileSync(path, ledger.map(row => JSON.stringify(row)).join('\n') + '\n');
|
|
165
|
+
const index = JSON.parse(readFileSync(join(f.directory, '_artifacts.json'), 'utf8'));
|
|
166
|
+
index.files['_calls.jsonl'] = sha256File(path);
|
|
167
|
+
writeFileSync(join(f.directory, '_artifacts.json'), JSON.stringify(index, null, 2) + '\n');
|
|
168
|
+
}
|
|
169
|
+
const audit = await auditEvaluation(manifest, f.directory);
|
|
170
|
+
assert.equal(audit.verified, false);
|
|
171
|
+
assert.match(audit.reasons.join(' '), /Full invocation accounting|Invocation.*total differs|prompt hash|Judge usage unrecorded/);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
test('invocation summary parser refuses invalid counters, coverage and role totals, preserving historical unknown', () => {
|
|
175
|
+
const valid = summarizeInvocationCosts([], [], false);
|
|
176
|
+
assert.deepEqual(parseInvocationCosts(valid), valid);
|
|
177
|
+
const historical = historicalInvocationCosts(invocationPopulation([]), true);
|
|
178
|
+
assert.deepEqual(parseInvocationCosts(historical), historical);
|
|
179
|
+
for (const mutate of [
|
|
180
|
+
(r) => { r.agent.metrics.input.knownTotal = -1; },
|
|
181
|
+
(r) => { r.agent.metrics.output.coverage.final = 1; },
|
|
182
|
+
(r) => { r.total.runs = 1; },
|
|
183
|
+
(r) => { r.judge = null; r.total = null; },
|
|
184
|
+
]) {
|
|
185
|
+
const value = JSON.parse(JSON.stringify(valid));
|
|
186
|
+
mutate(value);
|
|
187
|
+
assert.throws(() => parseInvocationCosts(value));
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
test('judge duration is monotonic even when wall clock moves backwards; non-invoked refusal spends nothing', async () => {
|
|
191
|
+
let wall = 100_000, mono = 0;
|
|
192
|
+
const capture = [];
|
|
193
|
+
const judge = { describe: () => ({ kind: 'mock', model: 'clock' }), run: async () => { wall -= 5000; mono += 250; return { output: checklist, tokens: judgeTokens }; } };
|
|
194
|
+
const result = await judgePair(judge, { taskPromptText: 'task', baselineOutput: 'b', treatmentOutput: 't', seed: 'clock',
|
|
195
|
+
clock: { wallNow: () => wall, monotonicNow: () => mono }, onCall: call => capture.push(call) });
|
|
196
|
+
assert.equal(result.calls.length, 2);
|
|
197
|
+
assert.equal(capture[0].durationSeconds, 0.25);
|
|
198
|
+
assert.equal(capture[0].timing.wallDurationSeconds, -5);
|
|
199
|
+
judgeCallReceipt(capture[0]);
|
|
200
|
+
const refused = { ...judge, run: async () => { throw new ExecutorFailure('not dispatched', { output: '' }, false); } };
|
|
201
|
+
let failure;
|
|
202
|
+
try {
|
|
203
|
+
await judgePair(refused, { taskPromptText: 'task', baselineOutput: 'b', treatmentOutput: 't', seed: 'refusal' });
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
failure = error;
|
|
207
|
+
}
|
|
208
|
+
assert.ok(failure instanceof JudgePairFailure);
|
|
209
|
+
assert.equal(failure.calls.length, 1);
|
|
210
|
+
assert.equal(failure.calls[0].executorInvoked, false);
|
|
211
|
+
assert.equal(summarizeInvocationCosts([], failure.calls, true).total.runs, 0);
|
|
212
|
+
const history = historicalInvocationCosts(invocationPopulation([]), true);
|
|
213
|
+
assert.equal(history.judgeUsage, 'unknown');
|
|
214
|
+
assert.equal(history.judge, null);
|
|
215
|
+
assert.equal(history.total, null);
|
|
216
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { record } from './eval-contract.js';
|
|
3
|
+
import { parseJudgeScores } from './judge.js';
|
|
4
|
+
import { sha256Text } from './hash.js';
|
|
5
|
+
/** Validate a retained judge receipt without executing a judge or reading current config. */
|
|
6
|
+
export function judgeCallReceipt(value) {
|
|
7
|
+
const r = record(value, 'judge invocation receipt');
|
|
8
|
+
assert.equal(r.schemaVersion, 1);
|
|
9
|
+
assert.equal(r.kind, 'skillfit.judge-call');
|
|
10
|
+
assert.ok(typeof r.taskId === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r.taskId));
|
|
11
|
+
assert.ok(Number.isSafeInteger(r.trial) && Number(r.trial) >= 1);
|
|
12
|
+
assert.ok(r.callIndex === 1 || r.callIndex === 2);
|
|
13
|
+
assert.equal(typeof r.seed, 'string');
|
|
14
|
+
assert.ok(r.firstCondition === 'baseline' || r.firstCondition === 'treatment');
|
|
15
|
+
assert.equal(typeof r.prompt, 'string');
|
|
16
|
+
assert.equal(sha256Text(r.prompt), r.promptSha256);
|
|
17
|
+
assert.equal(typeof r.output, 'string');
|
|
18
|
+
assert.ok(r.rawOutput === null || typeof r.rawOutput === 'string');
|
|
19
|
+
assert.equal(typeof r.executorInvoked, 'boolean');
|
|
20
|
+
assert.equal(typeof r.passed, 'boolean');
|
|
21
|
+
assert.ok(r.error === null || typeof r.error === 'string');
|
|
22
|
+
assert.equal(r.passed, r.error === null);
|
|
23
|
+
assert.ok(['final', 'partial', 'unknown'].includes(String(r.usageStatus)));
|
|
24
|
+
assert.ok(typeof r.durationSeconds === 'number' && Number.isFinite(r.durationSeconds) && r.durationSeconds >= 0);
|
|
25
|
+
for (const key of ['startedAt', 'finishedAt'])
|
|
26
|
+
assert.ok(typeof r[key] === 'string' && Number.isFinite(Date.parse(r[key])));
|
|
27
|
+
const timing = record(r.timing, 'judge invocation timing');
|
|
28
|
+
assert.equal(timing.clock, 'performance.now');
|
|
29
|
+
assert.equal(timing.wallDurationSeconds, (Date.parse(r.finishedAt) - Date.parse(r.startedAt)) / 1000);
|
|
30
|
+
if (timing.execution !== null) {
|
|
31
|
+
const execution = record(timing.execution, 'judge execution timing');
|
|
32
|
+
assert.equal(execution.clock, 'performance.now');
|
|
33
|
+
assert.ok(typeof execution.elapsedMs === 'number' && Number.isFinite(execution.elapsedMs) && execution.elapsedMs >= 0);
|
|
34
|
+
assert.ok(r.durationSeconds >= execution.elapsedMs / 1000 - 0.002, 'Judge execution interval exceeds invocation duration.');
|
|
35
|
+
}
|
|
36
|
+
if (r.tokens !== null) {
|
|
37
|
+
const tokens = record(r.tokens, 'judge tokens');
|
|
38
|
+
for (const key of ['input', 'cachedInput', 'output'])
|
|
39
|
+
if (tokens[key] !== undefined) {
|
|
40
|
+
assert.ok(Number.isSafeInteger(tokens[key]) && Number(tokens[key]) >= 0);
|
|
41
|
+
}
|
|
42
|
+
if (typeof tokens.cachedInput === 'number' && typeof tokens.input === 'number')
|
|
43
|
+
assert.ok(tokens.cachedInput <= tokens.input);
|
|
44
|
+
}
|
|
45
|
+
const executor = record(r.executor, 'judge executor');
|
|
46
|
+
assert.equal(typeof executor.kind, 'string');
|
|
47
|
+
assert.equal(typeof executor.model, 'string');
|
|
48
|
+
if (r.error === null) {
|
|
49
|
+
assert.equal(r.executorInvoked, true);
|
|
50
|
+
const scores = parseJudgeScores(r.output);
|
|
51
|
+
assert.deepEqual(r.scores, r.firstCondition === 'baseline' ? { baseline: scores.a, treatment: scores.b } : { baseline: scores.b, treatment: scores.a });
|
|
52
|
+
}
|
|
53
|
+
else
|
|
54
|
+
assert.equal(r.scores, null);
|
|
55
|
+
return r;
|
|
56
|
+
}
|
package/dist/harness/judge.js
CHANGED
|
@@ -2,6 +2,17 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
2
2
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
+
import { ExecutorFailure } from './types.js';
|
|
6
|
+
import { executionClock } from './execution-timing.js';
|
|
7
|
+
import { throwIfEvaluationInterrupted } from './interruption.js';
|
|
8
|
+
export class JudgePairFailure extends Error {
|
|
9
|
+
calls;
|
|
10
|
+
constructor(message, calls, cause) {
|
|
11
|
+
super(message, { cause });
|
|
12
|
+
this.calls = calls;
|
|
13
|
+
this.name = 'JudgePairFailure';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
5
16
|
export function judgeOrder(seed) {
|
|
6
17
|
const digest = createHash('sha256').update(seed, 'utf8').digest();
|
|
7
18
|
const first = (digest[0] ?? 0) % 2 === 0 ? 'baseline' : 'treatment';
|
|
@@ -63,7 +74,7 @@ function parseChecklist(raw, label) {
|
|
|
63
74
|
}
|
|
64
75
|
return score;
|
|
65
76
|
}
|
|
66
|
-
function
|
|
77
|
+
export function parseJudgeScores(raw) {
|
|
67
78
|
return { a: parseChecklist(raw, 'A'), b: parseChecklist(raw, 'B') };
|
|
68
79
|
}
|
|
69
80
|
export async function judgePair(judge, args) {
|
|
@@ -72,26 +83,79 @@ export async function judgePair(judge, args) {
|
|
|
72
83
|
// the task directory would expose both arms' _output.md and their _result.json — which names the
|
|
73
84
|
// condition and the evaluation-target hash — and the AB/BA swap would be blindfolding a judge that can
|
|
74
85
|
// just look. It gets a fresh directory holding only the two positionally-anonymized answers.
|
|
75
|
-
const
|
|
86
|
+
const calls = [];
|
|
87
|
+
const clock = args.clock ?? executionClock;
|
|
76
88
|
try {
|
|
77
|
-
const call = async (firstCondition) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
const call = async (firstCondition, callIndex) => {
|
|
90
|
+
throwIfEvaluationInterrupted();
|
|
91
|
+
args.beforeCall?.(callIndex);
|
|
92
|
+
const judgeDir = mkdtempSync(join(tmpdir(), 'skillfit-judge-'));
|
|
93
|
+
try {
|
|
94
|
+
const answerA = firstCondition === 'baseline' ? args.baselineOutput : args.treatmentOutput;
|
|
95
|
+
const answerB = firstCondition === 'baseline' ? args.treatmentOutput : args.baselineOutput;
|
|
96
|
+
writeFileSync(join(judgeDir, 'answerA.md'), answerA, 'utf8');
|
|
97
|
+
writeFileSync(join(judgeDir, 'answerB.md'), answerB, 'utf8');
|
|
98
|
+
const prompt = buildJudgePrompt(args.taskPromptText, args.rubricText ?? null, answerA, answerB);
|
|
99
|
+
const startedWall = clock.wallNow(), startedMono = clock.monotonicNow();
|
|
100
|
+
let output = '', rawOutput = null, tokens = null;
|
|
101
|
+
let usageStatus = 'unknown', execution = null;
|
|
102
|
+
let executorInvoked = true, error = null, scores = null;
|
|
103
|
+
let usageEvidence;
|
|
104
|
+
try {
|
|
105
|
+
const result = await judge.run(prompt, judgeDir);
|
|
106
|
+
output = result.output;
|
|
107
|
+
rawOutput = result.rawOutput ?? null;
|
|
108
|
+
tokens = result.tokens ?? null;
|
|
109
|
+
usageStatus = result.usageStatus ?? (tokens ? 'final' : 'unknown');
|
|
110
|
+
execution = result.executionTiming ?? null;
|
|
111
|
+
usageEvidence = result.usageEvidence;
|
|
112
|
+
if (result.guardError)
|
|
113
|
+
throw new Error(result.guardError);
|
|
114
|
+
}
|
|
115
|
+
catch (failure) {
|
|
116
|
+
error = failure.message;
|
|
117
|
+
if (failure instanceof ExecutorFailure) {
|
|
118
|
+
executorInvoked = failure.executorInvoked;
|
|
119
|
+
output = failure.result.output;
|
|
120
|
+
rawOutput = failure.result.rawOutput ?? null;
|
|
121
|
+
tokens = failure.result.tokens ?? null;
|
|
122
|
+
usageStatus = failure.result.usageStatus ?? (tokens ? 'partial' : 'unknown');
|
|
123
|
+
execution = failure.result.executionTiming ?? null;
|
|
124
|
+
usageEvidence = failure.result.usageEvidence;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const finishedWall = clock.wallNow(), durationSeconds = Math.round(clock.monotonicNow() - startedMono) / 1000;
|
|
128
|
+
if (!error) {
|
|
129
|
+
try {
|
|
130
|
+
const parsed = parseJudgeScores(output);
|
|
131
|
+
scores = { baseline: firstCondition === 'baseline' ? parsed.a : parsed.b,
|
|
132
|
+
treatment: firstCondition === 'baseline' ? parsed.b : parsed.a };
|
|
133
|
+
}
|
|
134
|
+
catch (failure) {
|
|
135
|
+
error = failure.message;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const receipt = { schemaVersion: 1, kind: 'skillfit.judge-call',
|
|
139
|
+
taskId: args.taskId ?? 'standalone', trial: args.trial ?? 1, callIndex, seed: args.seed, firstCondition,
|
|
140
|
+
prompt, promptSha256: createHash('sha256').update(prompt).digest('hex'), output, rawOutput,
|
|
141
|
+
executor: { ...judge.describe(), sampling: judge.describe().sampling ?? null },
|
|
142
|
+
startedAt: new Date(startedWall).toISOString(), finishedAt: new Date(finishedWall).toISOString(), durationSeconds,
|
|
143
|
+
timing: { clock: 'performance.now', wallDurationSeconds: (finishedWall - startedWall) / 1000, execution },
|
|
144
|
+
executorInvoked, error, passed: error === null, tokens, usageStatus, ...(usageEvidence ? { usageEvidence } : {}), scores };
|
|
145
|
+
calls.push(receipt);
|
|
146
|
+
// Persist before propagating a parse/execution error, cancellation or budget stop.
|
|
147
|
+
args.onCall?.(receipt);
|
|
148
|
+
throwIfEvaluationInterrupted();
|
|
149
|
+
if (error)
|
|
150
|
+
throw new Error(error);
|
|
151
|
+
return { ...scores, raw: output };
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
rmSync(judgeDir, { recursive: true, force: true });
|
|
155
|
+
}
|
|
92
156
|
};
|
|
93
|
-
const forward = await call(first);
|
|
94
|
-
const reverse = await call(second);
|
|
157
|
+
const forward = await call(first, 1);
|
|
158
|
+
const reverse = await call(second, 2);
|
|
95
159
|
const winner = (scores) => Math.sign(scores.baseline - scores.treatment);
|
|
96
160
|
const consistent = winner(forward) === winner(reverse);
|
|
97
161
|
return {
|
|
@@ -100,9 +164,10 @@ export async function judgePair(judge, args) {
|
|
|
100
164
|
consistent,
|
|
101
165
|
firstCondition: first,
|
|
102
166
|
raw: `${forward.raw}\n--- reverse order ---\n${reverse.raw}`,
|
|
167
|
+
calls,
|
|
103
168
|
};
|
|
104
169
|
}
|
|
105
|
-
|
|
106
|
-
|
|
170
|
+
catch (error) {
|
|
171
|
+
throw new JudgePairFailure(error.message, calls, error);
|
|
107
172
|
}
|
|
108
173
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
2
3
|
import { lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
|
|
3
4
|
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
5
|
export function packageFiles(root, prefix = '') {
|
|
@@ -56,30 +57,95 @@ export function verifyReplayPackage(root) {
|
|
|
56
57
|
}
|
|
57
58
|
if (metadata.hasManifest !== ('run/manifest.json' in metadata.files))
|
|
58
59
|
throw new Error('Portable manifest coverage changed.');
|
|
60
|
+
if (metadata.evaluationType !== undefined) {
|
|
61
|
+
if (!['paired', 'calibration', 'trigger'].includes(metadata.evaluationType))
|
|
62
|
+
throw new Error('Invalid portable evaluation type.');
|
|
63
|
+
const plan = JSON.parse(readFileSync(packageMember(root, 'run/_plan.json'), 'utf8'));
|
|
64
|
+
const plannedType = ['calibration', 'trigger'].includes(plan.details?.mode) ? plan.details.mode : 'paired';
|
|
65
|
+
if (metadata.evaluationType !== plannedType)
|
|
66
|
+
throw new Error('Portable evaluation type differs from its native plan.');
|
|
67
|
+
}
|
|
59
68
|
return metadata;
|
|
60
69
|
}
|
|
70
|
+
/** Wait for the pinned CLI to clean its verifier tree before returning a signal exit. */
|
|
71
|
+
function runPinnedReplay(root, interrupted) {
|
|
72
|
+
return new Promise((resolveRun, reject) => {
|
|
73
|
+
// The original cancellation context also covers older pinned CLIs whose
|
|
74
|
+
// report dispatcher predates the public replay wrapper. The CLI stays byte-identical.
|
|
75
|
+
const loader = "import{dirname,join}from'node:path';import{pathToFileURL}from'node:url';process.on('message',message=>{if(message?.kind==='skillfit.replay-signal'&&['SIGINT','SIGTERM'].includes(message.signal))process.emit(message.signal);});process.channel?.unref();const cli=process.argv[1];const{withEvaluationInterrupts}=await import(pathToFileURL(join(dirname(cli),'harness/interruption.js')).href);await withEvaluationInterrupts(async()=>{const idle=new Promise(resolve=>process.once('beforeExit',resolve));await import(pathToFileURL(cli).href);await idle;});";
|
|
76
|
+
const child = spawn(process.execPath, ['--input-type=module', '--eval', loader, join(root, 'runtime/dist/cli.js'), 'report', 'eval', join(root, 'run'), '--json', '--replay', '--bench', join(root, 'inputs/bench')], { cwd: root, stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true });
|
|
77
|
+
let stdout = '', stderr = '', bytes = 0, failure = null, signal = null;
|
|
78
|
+
const stopChild = (value) => {
|
|
79
|
+
if (process.platform === 'win32' && child.connected)
|
|
80
|
+
child.send({ kind: 'skillfit.replay-signal', signal: value });
|
|
81
|
+
else
|
|
82
|
+
child.kill(value);
|
|
83
|
+
};
|
|
84
|
+
const forward = (value) => {
|
|
85
|
+
if (signal)
|
|
86
|
+
return;
|
|
87
|
+
signal = value;
|
|
88
|
+
interrupted(value);
|
|
89
|
+
stopChild(value);
|
|
90
|
+
};
|
|
91
|
+
const onInt = () => forward('SIGINT'), onTerm = () => forward('SIGTERM');
|
|
92
|
+
process.on('SIGINT', onInt);
|
|
93
|
+
process.on('SIGTERM', onTerm);
|
|
94
|
+
const cleanup = () => { process.removeListener('SIGINT', onInt); process.removeListener('SIGTERM', onTerm); };
|
|
95
|
+
const append = (value, error) => {
|
|
96
|
+
bytes += Buffer.byteLength(value);
|
|
97
|
+
if (bytes > 32 * 1024 * 1024) {
|
|
98
|
+
if (!failure) {
|
|
99
|
+
failure = new Error('Pinned replay output exceeded 32 MiB.');
|
|
100
|
+
stopChild('SIGTERM');
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (error)
|
|
105
|
+
stderr += value;
|
|
106
|
+
else
|
|
107
|
+
stdout += value;
|
|
108
|
+
};
|
|
109
|
+
child.stdout.setEncoding('utf8');
|
|
110
|
+
child.stderr.setEncoding('utf8');
|
|
111
|
+
child.stdout.on('data', value => append(String(value), false));
|
|
112
|
+
child.stderr.on('data', value => append(String(value), true));
|
|
113
|
+
child.once('error', error => { failure = error; });
|
|
114
|
+
child.once('close', status => {
|
|
115
|
+
cleanup();
|
|
116
|
+
if (signal)
|
|
117
|
+
reject(new Error(`Offline replay interrupted by ${signal}; waited for the pinned CLI to stop its verifier processes.`));
|
|
118
|
+
else if (failure)
|
|
119
|
+
reject(failure);
|
|
120
|
+
else
|
|
121
|
+
resolveRun({ stdout, stderr, status });
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
}
|
|
61
125
|
/** Serialize these dependency-free functions so old pinned runtimes need no new export API. */
|
|
62
126
|
export function portableReproducer() {
|
|
63
127
|
return `import {createHash} from 'node:crypto';
|
|
64
128
|
import {lstatSync,readFileSync,readdirSync,realpathSync} from 'node:fs';
|
|
65
129
|
import {isAbsolute,join,relative,resolve,sep} from 'node:path';
|
|
66
130
|
import {fileURLToPath} from 'node:url';
|
|
67
|
-
import {
|
|
131
|
+
import {spawn} from 'node:child_process';
|
|
68
132
|
${packageFiles.toString()}
|
|
69
133
|
${packageMember.toString()}
|
|
70
134
|
${packageHash.toString()}
|
|
71
135
|
${verifyReplayPackage.toString()}
|
|
136
|
+
${runPinnedReplay.toString()}
|
|
137
|
+
let interruptedSignal=null;
|
|
72
138
|
try {
|
|
73
139
|
const root=fileURLToPath(new URL('.',import.meta.url)), metadata=verifyReplayPackage(root);
|
|
74
140
|
if(process.argv.includes('--verify-only')) {
|
|
75
141
|
console.log(JSON.stringify({schemaVersion:1,kind:'skillfit.replay-package-verification',verified:true,files:Object.keys(metadata.files).length,nativeStatus:metadata.nativeStatus,modelCalls:0}));
|
|
76
142
|
} else {
|
|
77
|
-
const child=
|
|
78
|
-
if(child.
|
|
143
|
+
const child=await runPinnedReplay(root,signal=>{interruptedSignal=signal;});
|
|
144
|
+
if(child.status!==0) throw new Error(child.stderr||'Pinned offline replay failed.');
|
|
79
145
|
const result=JSON.parse(child.stdout);
|
|
80
|
-
if(metadata.hasManifest&&!result.evidence?.verified) throw new Error('Offline evidence audit failed: '+JSON.stringify(result.evidence));
|
|
146
|
+
if((metadata.hasManifest||metadata.evaluationType==='calibration'||metadata.evaluationType==='trigger')&&!result.evidence?.verified) throw new Error('Offline evidence audit failed: '+JSON.stringify(result.evidence));
|
|
81
147
|
console.log(JSON.stringify({...result,portableReplay:{verified:true,sourcePlanSha256:metadata.sourcePlanSha256,modelCalls:0,scope:'Offline evidence reproduction; no new observations or upgrade authorization.'}},null,2));
|
|
82
148
|
}
|
|
83
|
-
} catch(error) { console.error(error.message); process.exitCode=2; }
|
|
149
|
+
} catch(error) { console.error(error.message); process.exitCode=interruptedSignal==='SIGINT'?130:interruptedSignal==='SIGTERM'?143:2; }
|
|
84
150
|
`;
|
|
85
151
|
}
|