@skathio/somi 4.0.1 → 4.1.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/.claude/settings.json +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +5 -4
- package/VERSION +1 -1
- package/agents/somi-coder.md +4 -228
- package/agents/somi-designer.md +4 -160
- package/agents/somi-discovery-analyst.md +4 -276
- package/agents/somi-flow.md +47 -0
- package/agents/somi-general.md +36 -0
- package/agents/somi-planner.md +4 -341
- package/agents/somi-reviewer.md +4 -199
- package/agents/somi.md +81 -253
- package/commands/adopt.md +6 -84
- package/commands/architecture-review.md +11 -86
- package/commands/atlas.md +10 -25
- package/commands/code-loop.md +10 -221
- package/commands/code-parallel.md +10 -151
- package/commands/code.md +9 -157
- package/commands/debug.md +9 -131
- package/commands/design.md +9 -160
- package/commands/discover.md +9 -194
- package/commands/impact.md +9 -25
- package/commands/incident.md +9 -39
- package/commands/plan-loop.md +9 -181
- package/commands/plan.md +9 -244
- package/commands/pr.md +10 -25
- package/commands/refactor-design.md +11 -89
- package/commands/refactor.md +11 -50
- package/commands/release-readiness.md +11 -70
- package/commands/review-panel.md +10 -141
- package/commands/review.md +11 -181
- package/commands/security-review.md +11 -75
- package/commands/ship-loop.md +9 -260
- package/commands/ship.md +9 -115
- package/commands/somi-config.md +11 -130
- package/commands/test-strategy.md +11 -75
- package/commands/upgrade.md +9 -72
- package/hooks/hooks.json +1 -1
- package/hooks/lib/common.mjs +8 -5
- package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
- package/hooks/pre-tool/block-secret-writes.mjs +5 -7
- package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
- package/package.json +1 -1
- package/scripts/lib/cost-defaults.mjs +2 -0
- package/scripts/lib/escalation-facts.mjs +146 -0
- package/scripts/lib/escalation.mjs +129 -0
- package/scripts/lib/findings-ledger.mjs +241 -0
- package/scripts/lib/install-text.mjs +97 -0
- package/scripts/lib/loop-caps.mjs +140 -0
- package/scripts/lib/loop-diff.mjs +12 -70
- package/scripts/lib/loop-engine.mjs +226 -0
- package/scripts/lib/loop-escalate.mjs +49 -0
- package/scripts/lib/loop-exit.mjs +47 -0
- package/scripts/lib/loop-notes-compact.mjs +72 -0
- package/scripts/lib/loop-notes.mjs +278 -0
- package/scripts/lib/loop-review.mjs +355 -12
- package/scripts/lib/loop-state.mjs +44 -0
- package/scripts/lib/loop-step-close.mjs +75 -0
- package/scripts/lib/loop-step-kit.mjs +179 -0
- package/scripts/lib/loop-step-review.mjs +140 -0
- package/scripts/lib/loop-step-tool.mjs +89 -0
- package/scripts/lib/loop-step.mjs +301 -0
- package/scripts/lib/mcp-project-root.mjs +18 -7
- package/scripts/lib/path-facts.mjs +187 -0
- package/scripts/lib/path-safety.mjs +171 -0
- package/scripts/lib/run-card.mjs +73 -0
- package/scripts/size-budget-overrides.json +5 -13
- package/scripts/somi-card.mjs +39 -0
- package/scripts/somi-findings.mjs +56 -271
- package/scripts/somi-loop.mjs +77 -447
- package/scripts/somi-mcp.mjs +26 -95
- package/scripts/validate.sh +75 -57
- package/skills/flow-adopt/SKILL.md +92 -0
- package/skills/flow-architecture-review/SKILL.md +94 -0
- package/skills/flow-atlas/SKILL.md +34 -0
- package/skills/flow-code/SKILL.md +167 -0
- package/skills/flow-code-loop/SKILL.md +263 -0
- package/skills/flow-code-parallel/SKILL.md +160 -0
- package/skills/flow-debug/SKILL.md +141 -0
- package/skills/flow-design/SKILL.md +170 -0
- package/skills/flow-discover/SKILL.md +204 -0
- package/skills/flow-impact/SKILL.md +35 -0
- package/skills/flow-incident/SKILL.md +49 -0
- package/skills/flow-plan/SKILL.md +254 -0
- package/skills/flow-plan-loop/SKILL.md +254 -0
- package/skills/flow-pr/SKILL.md +34 -0
- package/skills/flow-refactor/SKILL.md +58 -0
- package/skills/flow-refactor-design/SKILL.md +97 -0
- package/skills/flow-release-readiness/SKILL.md +82 -0
- package/skills/flow-review/SKILL.md +193 -0
- package/skills/flow-review-panel/SKILL.md +154 -0
- package/skills/flow-security-review/SKILL.md +83 -0
- package/skills/flow-ship/SKILL.md +125 -0
- package/skills/flow-ship-loop/SKILL.md +274 -0
- package/skills/flow-somi-config/SKILL.md +142 -0
- package/skills/flow-status/SKILL.md +43 -0
- package/skills/flow-test-strategy/SKILL.md +83 -0
- package/skills/flow-upgrade/SKILL.md +82 -0
- package/skills/role-coder/SKILL.md +247 -0
- package/skills/role-designer/SKILL.md +172 -0
- package/skills/role-discovery-analyst/SKILL.md +288 -0
- package/skills/role-planner/SKILL.md +353 -0
- package/skills/role-reviewer/SKILL.md +218 -0
- package/skills/somi-checkpoint/SKILL.md +95 -0
- package/skills/somi-dispatch/SKILL.md +14 -14
- package/skills/somi-routing/SKILL.md +6 -2
- package/tests/hooks/cases/block-secret-writes.json +6 -1
- package/tests/hooks/cases/guard-protected-paths.json +44 -2
- package/tests/hooks/run.sh +21 -0
- package/tests/scripts/checkpoint-gate.sh +2 -2
- package/tests/scripts/cost-defaults.sh +2 -0
- package/tests/scripts/dispatch-line-gate.sh +4 -4
- package/tests/scripts/dispatch-reference-gate.sh +14 -14
- package/tests/scripts/escalation.sh +409 -0
- package/tests/scripts/eval-runner.sh +8 -7
- package/tests/scripts/fact-sheet.sh +296 -0
- package/tests/scripts/goldens/somi-loop.json +2 -2
- package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
- package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
- package/tests/scripts/lib/escalation-tests.mjs +154 -0
- package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
- package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
- package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
- package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
- package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
- package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
- package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
- package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
- package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
- package/tests/scripts/lib/loop-step-tests.mjs +499 -0
- package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
- package/tests/scripts/lib/path-facts-tests.mjs +198 -0
- package/tests/scripts/lib/path-safety-tests.mjs +201 -0
- package/tests/scripts/lib/run-suites.mjs +139 -0
- package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
- package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
- package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
- package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
- package/tests/scripts/loop-engine.sh +22 -0
- package/tests/scripts/loop-flow-gate.sh +11 -0
- package/tests/scripts/review-panel-seats.sh +4 -4
- package/tests/scripts/run-card.sh +57 -0
- package/tests/scripts/run-suites.sh +74 -0
- package/tests/scripts/run.sh +11 -0
- package/tests/scripts/size-tier.sh +3 -3
- package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
- package/tests/scripts/somi-mcp.sh +1 -0
- package/tests/scripts/suite-plan.json +20 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// run-suites.mjs -- runs independent test scripts concurrently and prints each one's output whole, in the
|
|
3
|
+
// order given, so a parallel run reads exactly like a serial one.
|
|
4
|
+
//
|
|
5
|
+
// Usage: node tests/scripts/lib/run-suites.mjs [--jobs N] [--alone <script.sh>]... [--plan FILE [--shard NAME]]
|
|
6
|
+
// [--] <script.sh> ...
|
|
7
|
+
//
|
|
8
|
+
// Each script runs as `bash <script>` from the current directory with the inherited environment. --jobs
|
|
9
|
+
// defaults to SOMI_TEST_JOBS, else half the machine's cores (at least 2); 1 is a serial run. Exit 0 when
|
|
10
|
+
// every script exits 0, else 1, after every script has finished and printed, followed by a summary that
|
|
11
|
+
// names each failure and the slowest scripts. Exit 64 on a usage error. Ctrl-C stops every running script.
|
|
12
|
+
//
|
|
13
|
+
// --alone runs a script by itself, before the pool, with nothing else running: for a script whose checks carry
|
|
14
|
+
// wall-clock limits that CPU contention can break (a hidden-suite family killed at its timeout reads as failed cases).
|
|
15
|
+
//
|
|
16
|
+
// --plan reads tests/scripts/suite-plan.json: its `alone` list, and its `shards`, named groups of slow scripts that
|
|
17
|
+
// CI runs on separate runners. --shard (default SOMI_SUITE_SHARD, else `all`) picks what runs: `all`, one named
|
|
18
|
+
// shard, or `light`, every given script no shard names. So the shards and `light` together run each script once.
|
|
19
|
+
// A script the plan names but the caller did not give is an error, so a rename cannot drop a script silently.
|
|
20
|
+
|
|
21
|
+
import { spawn } from 'node:child_process';
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import os from 'node:os';
|
|
24
|
+
|
|
25
|
+
const USAGE = 'usage: run-suites.mjs [--jobs N] [--alone <script.sh>]... [--plan FILE [--shard NAME]] [--] <script.sh> ...';
|
|
26
|
+
|
|
27
|
+
// Half the cores, at least two: most scripts start node processes of their own, and a fully loaded machine makes the
|
|
28
|
+
// eval gates' hidden-suite runs hit their 60 s kill, which reads as failed cases.
|
|
29
|
+
export function defaultJobs(cores = os.availableParallelism()) {
|
|
30
|
+
return Math.max(2, Math.floor(cores / 2));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function parseArgs(argv, env = process.env) {
|
|
34
|
+
const scripts = [];
|
|
35
|
+
const alone = [];
|
|
36
|
+
let jobs = env.SOMI_TEST_JOBS ?? String(defaultJobs());
|
|
37
|
+
let plan = null;
|
|
38
|
+
let shard = null; // --shard; SOMI_SUITE_SHARD applies only when a plan is given
|
|
39
|
+
for (let i = 0; i < argv.length; i++) {
|
|
40
|
+
if (argv[i] === '--') { scripts.push(...argv.slice(i + 1)); break; }
|
|
41
|
+
if (argv[i] === '--jobs') { jobs = argv[++i]; continue; }
|
|
42
|
+
if (argv[i] === '--plan') { if (!argv[i + 1]) return { error: '--plan needs a file' }; plan = argv[++i]; continue; }
|
|
43
|
+
if (argv[i] === '--shard') { if (!argv[i + 1]) return { error: '--shard needs a name' }; shard = argv[++i]; continue; }
|
|
44
|
+
if (argv[i] === '--alone') { if (!argv[i + 1]) return { error: '--alone needs a script' }; alone.push(argv[++i]); continue; }
|
|
45
|
+
if (argv[i].startsWith('-')) return { error: `unknown option ${argv[i]}` };
|
|
46
|
+
scripts.push(argv[i]);
|
|
47
|
+
}
|
|
48
|
+
if (!/^[1-9][0-9]{0,2}$/.test(String(jobs))) return { error: `--jobs (or SOMI_TEST_JOBS) must be a whole number from 1 to 999, got ${JSON.stringify(jobs)}` };
|
|
49
|
+
if (scripts.length + alone.length === 0) return { error: 'no scripts given' };
|
|
50
|
+
if (plan === null) return shard === null ? { jobs: Number(jobs), scripts, alone } : { error: '--shard needs --plan' };
|
|
51
|
+
shard ??= env.SOMI_SUITE_SHARD || 'all';
|
|
52
|
+
let parsed;
|
|
53
|
+
try { parsed = JSON.parse(fs.readFileSync(plan, 'utf8')); } catch (e) { return { error: `cannot read the plan ${plan}: ${e.message}` }; }
|
|
54
|
+
const chosen = selectShard([...alone, ...scripts], parsed, shard);
|
|
55
|
+
return chosen.error ? chosen : { jobs: Number(jobs), ...chosen };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Applies a suite plan to the given scripts. Returns { alone, scripts } for the shard, or { error }.
|
|
59
|
+
export function selectShard(given, plan, shard) {
|
|
60
|
+
const shards = plan?.shards ?? {};
|
|
61
|
+
const planAlone = plan?.alone ?? [];
|
|
62
|
+
if (!Array.isArray(planAlone) || typeof shards !== 'object' || Array.isArray(shards)) return { error: 'the plan needs an `alone` list and a `shards` object' };
|
|
63
|
+
if (Object.hasOwn(shards, 'all') || Object.hasOwn(shards, 'light')) return { error: '`all` and `light` are reserved shard names' };
|
|
64
|
+
const owner = new Map();
|
|
65
|
+
for (const [name, list] of Object.entries(shards)) {
|
|
66
|
+
if (!Array.isArray(list) || list.length === 0) return { error: `shard ${name} must list at least one script` };
|
|
67
|
+
for (const s of list) { if (owner.has(s)) return { error: `${s} is in two shards, ${owner.get(s)} and ${name}` }; owner.set(s, name); }
|
|
68
|
+
}
|
|
69
|
+
const named = [...new Set([...planAlone, ...owner.keys()])];
|
|
70
|
+
const missing = named.filter((s) => !given.includes(s));
|
|
71
|
+
if (missing.length) return { error: `the plan names scripts that were not given: ${missing.join(', ')}` };
|
|
72
|
+
if (shard !== 'all' && shard !== 'light' && !Object.hasOwn(shards, shard)) return { error: `unknown shard ${shard} (expected all, light or ${Object.keys(shards).join(', ')})` };
|
|
73
|
+
const pick = shard === 'all' ? given : shard === 'light' ? given.filter((s) => !owner.has(s)) : given.filter((s) => owner.get(s) === shard);
|
|
74
|
+
return { alone: pick.filter((s) => planAlone.includes(s)), scripts: pick.filter((s) => !planAlone.includes(s)) };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Every child still running, so Ctrl-C can stop them all.
|
|
78
|
+
const running = new Set();
|
|
79
|
+
|
|
80
|
+
function runOne(script) {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
const started = Date.now();
|
|
83
|
+
const chunks = [];
|
|
84
|
+
const child = spawn('bash', [script], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
85
|
+
running.add(child);
|
|
86
|
+
child.stdout.on('data', (d) => chunks.push(d));
|
|
87
|
+
child.stderr.on('data', (d) => chunks.push(d));
|
|
88
|
+
const done = (code) => { running.delete(child); resolve({ script, code, output: Buffer.concat(chunks).toString('utf8'), seconds: (Date.now() - started) / 1000 }); };
|
|
89
|
+
child.on('error', (e) => { chunks.push(Buffer.from(`run-suites: could not start bash ${script}: ${e.message}\n`)); done(127); });
|
|
90
|
+
child.on('close', (code, signal) => done(code ?? (signal ? 128 : 1)));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
export async function runSuites({ jobs, scripts: pooled, alone = [] }, write = (s) => process.stdout.write(s)) {
|
|
96
|
+
// The alone scripts come first in the list and run with a pool of one, so nothing overlaps them.
|
|
97
|
+
const scripts = [...alone, ...pooled];
|
|
98
|
+
const results = new Array(scripts.length);
|
|
99
|
+
const waiters = new Array(scripts.length);
|
|
100
|
+
let next = 0;
|
|
101
|
+
const worker = async () => {
|
|
102
|
+
while (next < scripts.length) {
|
|
103
|
+
const i = next++;
|
|
104
|
+
results[i] = await runOne(scripts[i]);
|
|
105
|
+
waiters[i]?.();
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const worker1 = async () => { const i = next++; results[i] = await runOne(scripts[i]); waiters[i]?.(); };
|
|
109
|
+
const finished = (i) => (results[i] ? Promise.resolve() : new Promise((r) => { waiters[i] = r; }));
|
|
110
|
+
const started = Date.now();
|
|
111
|
+
const pool = (async () => {
|
|
112
|
+
while (next < alone.length) await worker1();
|
|
113
|
+
await Promise.all(Array.from({ length: Math.min(jobs, scripts.length - next) }, worker));
|
|
114
|
+
})();
|
|
115
|
+
// Print in input order: each block waits for its own script, never for a later one.
|
|
116
|
+
for (let i = 0; i < scripts.length; i++) {
|
|
117
|
+
await finished(i);
|
|
118
|
+
const r = results[i];
|
|
119
|
+
write(`==> ${r.script}\n${r.output}${r.output.endsWith('\n') || r.output === '' ? '' : '\n'}`);
|
|
120
|
+
write(` (${r.seconds.toFixed(1)}s, ${r.code === 0 ? 'ok' : `FAILED, exit ${r.code}`})\n`);
|
|
121
|
+
}
|
|
122
|
+
await pool;
|
|
123
|
+
const failed = results.filter((r) => r.code !== 0);
|
|
124
|
+
const slowest = [...results].sort((a, b) => b.seconds - a.seconds).slice(0, 5);
|
|
125
|
+
const total = results.reduce((s, r) => s + r.seconds, 0);
|
|
126
|
+
write(`\n==> ${results.length} suites, ${failed.length} failed, ${jobs} at a time: ${((Date.now() - started) / 1000).toFixed(1)}s wall, ${total.toFixed(1)}s of suite time\n`);
|
|
127
|
+
write(` slowest: ${slowest.map((r) => `${r.script} ${r.seconds.toFixed(1)}s`).join(', ')}\n`);
|
|
128
|
+
for (const r of failed) write(` FAILED: ${r.script} (exit ${r.code})\n`);
|
|
129
|
+
return failed.length === 0;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
133
|
+
const args = parseArgs(process.argv.slice(2));
|
|
134
|
+
if (args.error) { console.error(`run-suites: ${args.error}\n${USAGE}`); process.exit(64); }
|
|
135
|
+
const stop = () => { for (const c of running) c.kill('SIGTERM'); process.exit(130); };
|
|
136
|
+
process.on('SIGINT', stop);
|
|
137
|
+
process.on('SIGTERM', stop);
|
|
138
|
+
process.exit((await runSuites(args)) ? 0 : 1);
|
|
139
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of the sizing scorer (tests/evals/lib/sizing-score.mjs). Risk: a bar that passes a run it should fail (a weak
|
|
3
|
+
// share, an unguarded floor case, a tie read as a winner), or two runs on different labels compared as one. Tables run
|
|
4
|
+
// over records built from the committed set; the entry point runs as a child process for its exit codes. Each guard is
|
|
5
|
+
// then broken on a scratch copy of the module and the same suite must turn red. Run by
|
|
6
|
+
// tests/scripts/eval-gate-bench-driver.sh. Hermetic: no model, no network, no randomness.
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
13
|
+
import { pathToFileURL } from 'node:url';
|
|
14
|
+
import { REPO_ROOT, TIERS, isFloorCase, labelHash, loadSet, scenarioId } from '../../evals/lib/sizing-set.mjs';
|
|
15
|
+
|
|
16
|
+
const LIB = path.join(REPO_ROOT, 'tests', 'evals', 'lib');
|
|
17
|
+
const set = loadSet();
|
|
18
|
+
const SHA = 'a'.repeat(40);
|
|
19
|
+
const clone = (v) => JSON.parse(JSON.stringify(v));
|
|
20
|
+
// A record in which every entry matches its label on all five draws, with `over` replacing some entries' draws.
|
|
21
|
+
const rec = (over = {}, extra = {}) => ({ label_sha256: labelHash(set), plugin_sha: SHA, arm: 'somi', entries: Object.fromEntries(set.entries.map((e) => [e.id, over[e.id] ?? Array(5).fill(e.label)])), ...extra });
|
|
22
|
+
const draws = (n, tier, rest = null) => [...Array(n).fill(tier), ...Array(5 - n).fill(rest)];
|
|
23
|
+
// The cases the tests lean on come from the set itself, so a relabelled or extended set does not silently void them.
|
|
24
|
+
const floors = set.entries.filter(isFloorCase);
|
|
25
|
+
const [O1, O2] = set.entries.filter((e) => !isFloorCase(e));
|
|
26
|
+
const F1 = floors[0]; const F2 = floors[1]; const F3 = floors.at(-1);
|
|
27
|
+
const otherThan = (...tiers) => TIERS.filter((t) => !tiers.includes(t));
|
|
28
|
+
const [X1] = otherThan(O1.label); const [Y1] = otherThan(O1.label, X1);
|
|
29
|
+
const offDraws = (e, n) => [...Array(n).fill(otherThan(e.label)[0]), ...Array(5 - n).fill(e.label)];
|
|
30
|
+
const rowsFor = (n) => set.entries.flatMap((e) => Array.from({ length: n }, () => ({ scenario: scenarioId(e), arm: 'somi', phase: 'sizing', tier: e.label })));
|
|
31
|
+
const META = { plugin_sha: SHA, arm: 'somi' };
|
|
32
|
+
|
|
33
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sizing-score-'));
|
|
34
|
+
process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
|
|
35
|
+
|
|
36
|
+
// A scratch copy of the scorer (and the modules it imports, with the data directories linked) with `from` replaced by `to`.
|
|
37
|
+
let scratchN = 0;
|
|
38
|
+
function scratch(from, to) {
|
|
39
|
+
const dir = path.join(tmp, `scratch${scratchN++}`, 'tests', 'evals');
|
|
40
|
+
fs.mkdirSync(path.join(dir, 'lib'), { recursive: true });
|
|
41
|
+
for (const f of ['sizing-set.mjs', 'bench-schema.mjs', 'manifest.mjs']) fs.copyFileSync(path.join(LIB, f), path.join(dir, 'lib', f));
|
|
42
|
+
for (const d of ['ab', 'ab-micro', 'fixtures', 'sizing-set']) fs.symlinkSync(path.join(REPO_ROOT, 'tests', 'evals', d), path.join(dir, d));
|
|
43
|
+
const original = fs.readFileSync(path.join(LIB, 'sizing-score.mjs'), 'utf8');
|
|
44
|
+
fs.writeFileSync(path.join(dir, 'lib', 'sizing-score.mjs'), original.replace(from, to));
|
|
45
|
+
return { file: path.join(dir, 'lib', 'sizing-score.mjs'), applies: original.includes(from) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function suite(modPath, say) {
|
|
49
|
+
let pass = 0; let fail = 0;
|
|
50
|
+
const check = (name, got, want) => {
|
|
51
|
+
if (isDeepStrictEqual(got, want)) { pass++; say(` ok ${name}`); } else { fail++; say(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
|
|
52
|
+
};
|
|
53
|
+
const M = await import(pathToFileURL(modPath).href);
|
|
54
|
+
const refused = (fn) => { try { fn(); return 'no throw'; } catch (e) { return e instanceof M.Refusal ? e.message : `wrong error: ${e.message}`; } };
|
|
55
|
+
const refusedWith = (fn, re) => re.test(refused(fn));
|
|
56
|
+
const score = (r, o) => M.scoreResult(set, r, o);
|
|
57
|
+
const entry = (r, id, o) => score(r, o).entries.find((x) => x.id === id);
|
|
58
|
+
|
|
59
|
+
say('== sizing score: building a record ==');
|
|
60
|
+
const built = M.buildResult(set, rowsFor(5), META);
|
|
61
|
+
check('turns sizing rows into a record bound to the set', [built.label_sha256, built.plugin_sha, built.arm, Object.keys(built.entries).length, built.entries[O1.id]], [labelHash(set), SHA, 'somi', set.entries.length, Array(5).fill(O1.label)]);
|
|
62
|
+
check('keeps the draw order and reads a tier outside the three as null', M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, tier: 'unknown' } : r)), META).entries[O1.id], [null]);
|
|
63
|
+
check('reads a missing tier as null', M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, tier: undefined } : r)), META).entries[O1.id], [null]);
|
|
64
|
+
check('refuses a row outside the sizing phase', refusedWith(() => M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, phase: 'experiment' } : r)), META), /not sizing/), true);
|
|
65
|
+
check('refuses a scenario that is not in the set', refusedWith(() => M.buildResult(set, [...rowsFor(1), { scenario: 'S4-Z9', arm: 'somi', phase: 'sizing', tier: 'small' }], META), /not in the set/), true);
|
|
66
|
+
check('refuses a row of the other arm', refusedWith(() => M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, arm: 'bare' } : r)), META), /arm "bare"/), true);
|
|
67
|
+
check('refuses entries with different draw counts', refusedWith(() => M.buildResult(set, [...rowsFor(2), rowsFor(1)[0]], META), /same number of draws/), true);
|
|
68
|
+
check('refuses an entry with no draw', refusedWith(() => M.buildResult(set, rowsFor(2).slice(2), META), /same number of draws/), true);
|
|
69
|
+
check('refuses an empty list of rows', refusedWith(() => M.buildResult(set, [], META), /at least one/), true);
|
|
70
|
+
const withOutcome = (outcome) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome } : r));
|
|
71
|
+
check('refuses a draw that ended paused or over budget, so it has to be drawn again', ['paused', 'over-budget'].map((o) => refusedWith(() => M.buildResult(set, withOutcome(o), META), new RegExp(`ended ${o}`))), [true, true]);
|
|
72
|
+
const withEnd = (outcome, reason) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome, reason } : r));
|
|
73
|
+
check("takes a scored draw and the probe's own invalid draw as answers", [['scored'], ['invalid', 'probe']].map((a) => M.buildResult(set, withEnd(...a), META).entries[O1.id]), [[O1.label], [O1.label]]);
|
|
74
|
+
check('refuses a draw that ended invalid for any reason but probe: a harness event, not an answer', ['timeout', 'output-cap', 'leak: token', 'unpinned-model', undefined].map((why) => refusedWith(() => M.buildResult(set, withEnd('invalid', why), META), /ended invalid/)), Array(5).fill(true));
|
|
75
|
+
const timedOut = (tier, tierSource) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome: 'invalid', reason: 'timeout', tier, tierSource } : r));
|
|
76
|
+
check('takes a timed-out draw whose tier is full from the record file as an answer', M.buildResult(set, timedOut('full', 'file'), META).entries[O1.id], ['full']);
|
|
77
|
+
check('counts only the timed-out full draws it took, and never a scored draw that carries a timeout reason', [M.buildRecord(set, timedOut('full', 'file'), META).taken, M.buildRecord(set, rowsFor(1), META).taken, M.buildRecord(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome: 'scored', reason: 'timeout', tier: 'full', tierSource: 'file' } : r)), META).taken], [1, 0, 0]);
|
|
78
|
+
check('refuses a timeout on any other tier or tier source', [['small', 'file'], ['trivial', 'file'], ['unknown', 'file'], ['full', 'stream'], ['full', 'none'], ['full', undefined]].map((a) => refusedWith(() => M.buildResult(set, timedOut(...a), META), /ended invalid \("timeout"\)/)), Array(6).fill(true));
|
|
79
|
+
check('refuses a full/file draw that ended invalid for a reason but timeout', ['output-cap', 'leak: token', 'unpinned-model', undefined].map((why) => refusedWith(() => M.buildResult(set, timedOut('full', 'file').map((r, i) => (i === 0 ? { ...r, reason: why } : r)), META), /ended invalid/)), Array(4).fill(true));
|
|
80
|
+
check('refuses a bad plugin sha', refusedWith(() => M.buildResult(set, rowsFor(1), { plugin_sha: 'main', arm: 'somi' }), /plugin_sha/), true);
|
|
81
|
+
|
|
82
|
+
say('== sizing score: the bar per entry ==');
|
|
83
|
+
check('passes when every entry matches 5 of 5', score(rec()).bar_met, true);
|
|
84
|
+
check('modal tier, share and need are reported', (({ modal, share, need, pass }) => ({ modal, share, need, pass }))(entry(rec({ [O1.id]: draws(4, O1.label, X1) }), O1.id)), { modal: O1.label, share: 0.8, need: 4, pass: true });
|
|
85
|
+
check('fails an ordinary entry at 3 of 5', entry(rec({ [O1.id]: draws(3, O1.label, X1) }), O1.id).pass, false);
|
|
86
|
+
check('passes an ordinary entry at 4 of 5', entry(rec({ [O1.id]: draws(4, O1.label, X1) }), O1.id).pass, true);
|
|
87
|
+
check('fails a floor case at 4 of 5', entry(rec({ [F1.id]: draws(4, F1.label, otherThan(F1.label)[0]) }), F1.id).pass, false);
|
|
88
|
+
check('passes a floor case at 5 of 5', entry(rec(), F1.id).pass, true);
|
|
89
|
+
check('a floor case at 4 of 5 fails the whole bar', score(rec({ [F3.id]: draws(4, F3.label, otherThan(F3.label)[0]) })).bar_met, false);
|
|
90
|
+
check('fails a 2/2/1 tie, which has no modal tier', (({ modal, pass }) => ({ modal, pass }))(entry(rec({ [O1.id]: [O1.label, O1.label, X1, X1, Y1] }), O1.id)), { modal: null, pass: false });
|
|
91
|
+
check('fails a modal tier that is not the label even at 5 of 5', entry(rec({ [O1.id]: Array(5).fill(X1) }), O1.id).pass, false);
|
|
92
|
+
check('counts a null tier as a miss', [entry(rec({ [O1.id]: draws(4, O1.label) }), O1.id).pass, entry(rec({ [O1.id]: draws(3, O1.label) }), O1.id).pass], [true, false]);
|
|
93
|
+
check('counts a null tier as an off-label draw', score(rec({ [O1.id]: draws(4, O1.label) })).pooled.off, 1);
|
|
94
|
+
check('fails a floor case with one null draw', entry(rec({ [F2.id]: draws(4, F2.label) }), F2.id).pass, false);
|
|
95
|
+
check('scales the share to the draw count (10 draws need 8)', [8, 7].map((n) => entry(rec({ [O1.id]: [...Array(n).fill(O1.label), ...Array(10 - n).fill(X1)], ...Object.fromEntries(set.entries.filter((e) => e.id !== O1.id).map((e) => [e.id, Array(10).fill(e.label)])) }), O1.id).pass), [true, false]);
|
|
96
|
+
|
|
97
|
+
say('== sizing score: the pooled reading ==');
|
|
98
|
+
// Off-label draws spread over the ordinary entries, five to an entry (the set size sets the allowance: one draw in ten).
|
|
99
|
+
const ordinary = set.entries.filter((e) => !isFloorCase(e));
|
|
100
|
+
const spread = (n, per = 5) => Object.fromEntries(ordinary.map((e, i) => [e.id, offDraws(e, Math.max(0, Math.min(per, n - i * per)))]));
|
|
101
|
+
const allowed = Math.floor((set.entries.length * 5) / 10);
|
|
102
|
+
const atLimit = rec(spread(allowed)); const overLimit = rec(spread(allowed + 1));
|
|
103
|
+
const failing = Math.ceil((allowed - 1) / 5);
|
|
104
|
+
check(`accepts ${allowed} of ${set.entries.length * 5} off-label draws`, [score(atLimit, { mode: 'pooled' }).pooled.off, score(atLimit, { mode: 'pooled' }).bar_met], [allowed, true]);
|
|
105
|
+
check('the same draws miss the per-task bar and both numbers are reported', [score(atLimit).bar_met, score(atLimit).per_task.passing, score(atLimit).pooled.allowed], [false, set.entries.length - failing, allowed]);
|
|
106
|
+
check(`rejects ${allowed + 1} of ${set.entries.length * 5} off-label draws`, [score(overLimit, { mode: 'pooled' }).pooled.off, score(overLimit, { mode: 'pooled' }).bar_met], [allowed + 1, false]);
|
|
107
|
+
// 3 draws an entry is a total that is not a multiple of ten: the allowance rounds down, so one draw over is rejected.
|
|
108
|
+
const few = (n) => Object.fromEntries(ordinary.map((e, i) => { const k = Math.max(0, Math.min(3, n - i * 3)); return [e.id, [...Array(k).fill(otherThan(e.label)[0]), ...Array(3 - k).fill(e.label)]]; }));
|
|
109
|
+
const rec3 = (over) => rec(Object.fromEntries(set.entries.map((e) => [e.id, over[e.id] ?? Array(3).fill(e.label)])));
|
|
110
|
+
const allowed3 = Math.floor((set.entries.length * 3) / 10);
|
|
111
|
+
check(`rounds the allowance down: ${allowed3} of ${set.entries.length * 3} accepted, ${allowed3 + 1} rejected`, [allowed3, allowed3 + 1].map((n) => score(rec3(few(n)), { mode: 'pooled' }).bar_met), [true, false]);
|
|
112
|
+
check('still fails a floor case at 4 of 5', score(rec({ [F1.id]: draws(4, F1.label, otherThan(F1.label)[0]) }), { mode: 'pooled' }).bar_met, false);
|
|
113
|
+
check('refuses an unknown mode', refusedWith(() => score(rec(), { mode: 'loose' }), /unknown mode/), true);
|
|
114
|
+
|
|
115
|
+
say('== sizing score: the label-hash binding and malformed records ==');
|
|
116
|
+
check('refuses a record whose hash is not the committed set', refusedWith(() => score(rec({}, { label_sha256: 'b'.repeat(64) })), /different label set/), true);
|
|
117
|
+
const altered = clone(set); altered.entries[0].label = otherThan(altered.entries[0].label)[0];
|
|
118
|
+
check('refuses a record scored against a re-labelled set', refusedWith(() => M.scoreResult(altered, rec()), /different label set/), true);
|
|
119
|
+
check('refuses a record without a hash', refusedWith(() => score(rec({}, { label_sha256: undefined })), /label_sha256/), true);
|
|
120
|
+
check('refuses a record with an unknown arm', refusedWith(() => score(rec({}, { arm: 'x' })), /plugin_sha or arm/), true);
|
|
121
|
+
check('refuses a record that is not an object', refusedWith(() => score([]), /not a result record/), true);
|
|
122
|
+
check('refuses a record missing an entry', refusedWith(() => { const r = rec(); delete r.entries[O1.id]; score(r); }, /exactly the set's entries/), true);
|
|
123
|
+
check('refuses a record with an extra entry', refusedWith(() => { const r = rec(); r.entries.Z9 = ['small']; score(r); }, /exactly the set's entries/), true);
|
|
124
|
+
check('refuses a draw outside the three tiers', refusedWith(() => score(rec({ [O1.id]: ['medium', ...Array(4).fill(O1.label)] })), /list of tiers or null/), true);
|
|
125
|
+
check('refuses an entry with no draws', refusedWith(() => score(rec({ [O1.id]: [] })), /list of tiers or null/), true);
|
|
126
|
+
check('refuses entries with different draw counts', refusedWith(() => score(rec({ [O1.id]: Array(4).fill(O1.label) })), /different draw counts/), true);
|
|
127
|
+
const base = rec(); const cand = rec({ [O1.id]: draws(3, O1.label, X1) });
|
|
128
|
+
const side = M.compareResults(set, base, cand);
|
|
129
|
+
check('compares two records of the same set side by side', [side.baseline.bar_met, side.candidate.bar_met, side.candidate.entries.find((x) => x.id === O1.id).pass], [true, false, false]);
|
|
130
|
+
check('refuses a candidate with a different label hash than the baseline', refusedWith(() => M.compareResults(set, base, rec({}, { label_sha256: 'b'.repeat(64) })), /different label sets/), true);
|
|
131
|
+
check('refuses two records that agree with each other but not with the set', refusedWith(() => M.compareResults(set, rec({}, { label_sha256: 'b'.repeat(64) }), rec({}, { label_sha256: 'b'.repeat(64) })), /different label set/), true);
|
|
132
|
+
|
|
133
|
+
say('== sizing score: the entry point ==');
|
|
134
|
+
const cli = (...argv) => spawnSync('node', [path.join(path.dirname(modPath), 'sizing-score.mjs'), ...argv], { encoding: 'utf8' });
|
|
135
|
+
const work = fs.mkdtempSync(path.join(tmp, 'c-'));
|
|
136
|
+
const put = (name, v) => { const f = path.join(work, name); fs.writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v)); return f; };
|
|
137
|
+
const met = put('met.json', rec()); const missed = put('missed.json', cand); const wrong = put('wrong.json', rec({}, { label_sha256: 'b'.repeat(64) }));
|
|
138
|
+
const ran = (...a) => { const r = cli(...a); return [r.status, r.stdout.split('\n')[0].slice(0, 22)]; };
|
|
139
|
+
check('exits 0 and says met when the bar is met', ran('--score', met), [0, 'sizing bar met (per-ta']);
|
|
140
|
+
check('exits 3 and names the entry when the bar is missed', [cli('--score', missed).status, cli('--score', missed).stdout.includes(`missed (per-task): disagrees on ${O1.id};`)], [3, true]);
|
|
141
|
+
check('exits 2 on a refusal, not 3 and not 64 or 65', [cli('--score', wrong).status, /different label set/.test(cli('--score', wrong).stderr)], [2, true]);
|
|
142
|
+
check('exits 2 on a record that is not JSON', cli('--score', put('junk.json', 'nope')).status, 2);
|
|
143
|
+
check('exits 2 on a usage error', [cli().status, cli('--score').status, cli('--bogus').status], [2, 2, 2]);
|
|
144
|
+
check('--pooled reads the same record by the pooled bar', [cli('--score', put('at-limit.json', atLimit), '--pooled').status, cli('--score', put('at-limit2.json', atLimit)).status], [0, 3]);
|
|
145
|
+
check('--compare exits 0 on comparable records even when the candidate missed', [cli('--compare', met, missed).status, /^baseline: sizing bar met[^\n]*\ncandidate: sizing bar missed/.test(cli('--compare', met, missed).stdout)], [0, true]);
|
|
146
|
+
check('--compare exits 2 when the label hashes differ', cli('--compare', met, wrong).status, 2);
|
|
147
|
+
const rowsFile = put('rows.jsonl', rowsFor(1).map((r) => JSON.stringify({ status: 'halted', row: null, ...r })).concat(rowsFor(5).map((r) => JSON.stringify({ status: 'done', row: r }))).join('\n'));
|
|
148
|
+
const out = cli('--build', rowsFile, '--plugin-sha', SHA);
|
|
149
|
+
check('--build prints a record that scores as met, ignoring halted draws', [out.status, out.status === 0 && M.scoreResult(set, JSON.parse(out.stdout)).bar_met], [0, true]);
|
|
150
|
+
const err = (r) => [r.status, /^sizing-score: refused: /.test(r.stderr), /^sizing-score: error: /.test(r.stderr)];
|
|
151
|
+
check('a refusal is reported as refused, exit 2', err(cli('--score', wrong)), [2, true, false]);
|
|
152
|
+
const bug = scratch('const needOf = (draws) => Math.ceil((draws * 4) / 5);', "const needOf = () => { throw new TypeError('boom'); };");
|
|
153
|
+
const bugRun = spawnSync('node', [bug.file, '--score', met], { encoding: 'utf8' });
|
|
154
|
+
check('any other exception is an error, exit 1, never a refusal', [bug.applies, ...err(bugRun), /boom/.test(bugRun.stderr)], [true, 1, false, true, true]);
|
|
155
|
+
const badSet = put('bad-set.json', '{"entries": []}');
|
|
156
|
+
check('a set that fails validation is a refusal, exit 2', [...err(cli('--score', met, '--set', badSet)), /sizing set invalid/.test(cli('--score', met, '--set', badSet).stderr)], [2, true, false, true]);
|
|
157
|
+
check('a set file that is missing is a refusal, exit 2', err(cli('--score', met, '--set', path.join(work, 'nope.json'))).slice(0, 2), [2, true]);
|
|
158
|
+
const badRows = put('bad-rows.jsonl', `${JSON.stringify({ status: 'done', row: rowsFor(1)[0] })}\n\n{"status": "done", row\n`);
|
|
159
|
+
const badRun = cli('--build', badRows, '--plugin-sha', SHA);
|
|
160
|
+
check('--build names the line whose JSON does not parse', [badRun.status, /line 3 is not JSON/.test(badRun.stderr)], [2, true]);
|
|
161
|
+
check('--build refuses an empty rows file', [cli('--build', put('empty.jsonl', ''), '--plugin-sha', SHA).status, /at least one/.test(cli('--build', put('empty.jsonl', ''), '--plugin-sha', SHA).stderr)], [2, true]);
|
|
162
|
+
check('--build refuses a finished draw whose entry reason is not probe, and takes one that is', [['timeout', 2], ['probe', 0]].map(([why, code]) => cli('--build', put(`why-${why}.jsonl`, rowsFor(1).map((r) => JSON.stringify({ status: 'done', reason: why, row: { ...r, outcome: 'invalid' } })).join('\n')), '--plugin-sha', SHA).status === code), [true, true]);
|
|
163
|
+
const timeoutFile = (tier) => put(`timeout-${tier}.jsonl`, rowsFor(5).map((r, i) => JSON.stringify({ status: 'done', reason: i === 0 ? 'timeout' : 'probe', row: i === 0 ? { ...r, outcome: 'invalid', tier, tierSource: 'file' } : r })).join('\n'));
|
|
164
|
+
const tFull = cli('--build', timeoutFile('full'), '--plugin-sha', SHA); const tSmall = cli('--build', timeoutFile('small'), '--plugin-sha', SHA);
|
|
165
|
+
const tRows = rowsFor(5).map((r, i) => (i === 0 ? { ...r, outcome: 'invalid', reason: 'timeout', tier: 'full', tierSource: 'file' } : { ...r, outcome: 'invalid', reason: 'probe' }));
|
|
166
|
+
check('--build takes a timed-out full draw, says so on stderr and prints exactly the record (stdout is one JSON document)', [tFull.status, tFull.stderr, tFull.status === 0 && isDeepStrictEqual(JSON.parse(tFull.stdout), M.buildResult(set, tRows, META))],
|
|
167
|
+
[0, 'sizing-score: timed-out full draws taken as answers (tier from the record file): 1\n', true]);
|
|
168
|
+
check('--build refuses a timed-out small draw, exit 2', [tSmall.status, /ended invalid/.test(tSmall.stderr)], [2, true]);
|
|
169
|
+
check('--build says nothing on stderr when it took no timeout', [out.status, out.stderr], [0, '']);
|
|
170
|
+
check('--build refuses a file that is missing', cli('--build', path.join(work, 'nope.jsonl'), '--plugin-sha', SHA).status, 2);
|
|
171
|
+
check('a flag that needs a value and has none is a usage refusal, even last or before another flag', [
|
|
172
|
+
cli('--score', met, '--set'), cli('--build', rowsFile, '--plugin-sha'), cli('--build', rowsFile, '--plugin-sha', SHA, '--arm'), cli('--score', met, '--set', '--pooled'),
|
|
173
|
+
].map((r) => [...err(r).slice(0, 2), /needs a value/.test(r.stderr)]), Array(4).fill([2, true, true]));
|
|
174
|
+
const pausedFile = put('paused.jsonl', rowsFor(5).map((r, i) => JSON.stringify({ status: 'done', row: i === 0 ? { ...r, outcome: 'paused' } : r })).join('\n'));
|
|
175
|
+
const pausedRun = cli('--build', pausedFile, '--plugin-sha', SHA);
|
|
176
|
+
check('--build refuses a draw that ended paused rather than scoring it', [pausedRun.status, /ended paused/.test(pausedRun.stderr)], [2, true]);
|
|
177
|
+
return { pass, fail };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const say = (s) => console.log(s);
|
|
181
|
+
const real = await suite(path.join(LIB, 'sizing-score.mjs'), say);
|
|
182
|
+
|
|
183
|
+
// ---- mutations: each guard broken on a scratch copy of the module; the suite must fail on it ------------------------
|
|
184
|
+
say('== sizing score: mutations ==');
|
|
185
|
+
const MUTATIONS = [
|
|
186
|
+
['the share threshold weakened to 3 of 5', 'Math.ceil((draws * 4) / 5)', 'Math.ceil((draws * 3) / 5)'],
|
|
187
|
+
['the floor rule dropped', 'const need = floor ? draws.length : needOf(draws.length);', 'const need = needOf(draws.length);'],
|
|
188
|
+
['the label-hash check dropped', 'if (rec.label_sha256 !== labelHash(set))', 'if (false)'],
|
|
189
|
+
// A tie can only change the reported modal tier, never `pass` (a tied top count is below the need); the suite pins the modal.
|
|
190
|
+
['the empty-rows guard dropped', 'counts.length !== 1 || counts[0] === 0', 'counts.length !== 1'],
|
|
191
|
+
['the pooled allowance rounded up', 'Math.floor(total / 10)', 'Math.ceil(total / 10)'],
|
|
192
|
+
['an invalid draw taken as an answer', "(r.outcome === 'invalid' && r.reason !== 'probe' && !isTakenTimeout(r))", 'false'],
|
|
193
|
+
['a timeout taken whatever its tier', "r.tier === 'full' && r.tierSource === 'file'", "r.tierSource === 'file'"],
|
|
194
|
+
['a timeout taken whatever its reason', "r.reason === 'timeout' && r.tier === 'full'", "r.tier === 'full'"],
|
|
195
|
+
['a timeout counted whatever its outcome', "r.outcome === 'invalid' && r.reason === 'timeout'", "r.reason === 'timeout'"],
|
|
196
|
+
['a timeout taken whatever its tier source', "r.tier === 'full' && r.tierSource === 'file'", "r.tier === 'full'"],
|
|
197
|
+
['ties resolved to the first tier', 'if (top.length !== 1) return { tier: null, count };', 'if (top.length === 0) return { tier: null, count };'],
|
|
198
|
+
];
|
|
199
|
+
let mutFail = 0;
|
|
200
|
+
for (const [name, from, to] of MUTATIONS) {
|
|
201
|
+
const m = scratch(from, to);
|
|
202
|
+
const r = m.applies ? await suite(m.file, () => {}) : { fail: 0 };
|
|
203
|
+
const red = m.applies && r.fail > 0;
|
|
204
|
+
if (!red) mutFail++;
|
|
205
|
+
say(red ? ` ok mutation turns the suite red: ${name} (${r.fail} failing)` : ` FAIL mutation ${m.applies ? 'left the suite green' : 'did not apply'}: ${name}`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const failed = real.fail + mutFail;
|
|
209
|
+
say(` ${real.pass} passed, ${failed} failed`);
|
|
210
|
+
process.exit(failed === 0 ? 0 : 1);
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tests of the labelled sizing set (tests/evals/lib/sizing-set.mjs). Risk: a set that validates when it should not, or a
|
|
3
|
+
// hash that does not move when a label, a request or a fixture does, would let two runs on different labels be compared.
|
|
4
|
+
// Red cases run against a scratch repository tree; the committed set is checked against the real one. Run by
|
|
5
|
+
// tests/scripts/eval-gate-bench-driver.sh. Hermetic: no model, no network.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
11
|
+
import { REPO_ROOT, SET_FILE, TIERS, labelHash, loadSet, scenarioId, setMaterial, sizingScenarios, stageFixture, validateSet } from '../../evals/lib/sizing-set.mjs';
|
|
12
|
+
|
|
13
|
+
let pass = 0; let fail = 0;
|
|
14
|
+
const check = (name, got, want) => {
|
|
15
|
+
if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
|
|
16
|
+
};
|
|
17
|
+
const clone = (v) => JSON.parse(JSON.stringify(v));
|
|
18
|
+
|
|
19
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sizing-set-'));
|
|
20
|
+
process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
|
|
21
|
+
// A scratch tree: one corpus task, two fixtures, and the things a fixture name must not resolve to.
|
|
22
|
+
for (const d of ['tests/evals/ab-micro/M1-x', 'tests/evals/fixtures/fx', 'tests/evals/fixtures/fy', 'tests/evals/fixtures/_candidates', 'tests/evals/fixtures/_target', 'tests/evals/ab/D-empty']) fs.mkdirSync(path.join(tmp, d), { recursive: true });
|
|
23
|
+
fs.writeFileSync(path.join(tmp, 'tests/evals/ab-micro/M1-x/task.json'), '{}');
|
|
24
|
+
fs.writeFileSync(path.join(tmp, 'tests/evals/fixtures/afile'), 'x');
|
|
25
|
+
fs.symlinkSync('fx', path.join(tmp, 'tests/evals/fixtures/lnk'));
|
|
26
|
+
|
|
27
|
+
const corpus = { id: 'M1', label: 'small', task: 'ab-micro/M1-x', reason: 'one file' };
|
|
28
|
+
const authored = { id: 'A1', label: 'trivial', fixture: 'fx', request: 'Fix the typo in src/a.mjs.', reason: 'one file' };
|
|
29
|
+
const floor = { id: 'A2', label: 'full', sensitive: true, fixture: 'fy', request: 'Rotate the key.', reason: 'floor' };
|
|
30
|
+
const base = { schema_version: 1, entries: [corpus, authored, floor] };
|
|
31
|
+
const problems = (mut) => { const s = clone(base); mut(s); return validateSet(s, { root: tmp }); };
|
|
32
|
+
|
|
33
|
+
console.log('== sizing set: validator ==');
|
|
34
|
+
check('accepts a valid set of both kinds and a floor case', validateSet(base, { root: tmp }), []);
|
|
35
|
+
const REDS = [
|
|
36
|
+
['a missing label', (s) => { delete s.entries[0].label; }, /no label/],
|
|
37
|
+
['an unknown tier', (s) => { s.entries[0].label = 'medium'; }, /unknown tier/],
|
|
38
|
+
['a sensitive entry labelled below full', (s) => { s.entries[2].label = 'small'; }, /security floor/],
|
|
39
|
+
['a duplicate id', (s) => { s.entries[1].id = 'M1'; }, /duplicate id M1/],
|
|
40
|
+
['a corpus task that does not exist', (s) => { s.entries[0].task = 'ab-micro/M9-none'; }, /does not exist/],
|
|
41
|
+
['a corpus task directory with no task.json', (s) => { s.entries[0].task = 'ab/D-empty'; }, /does not exist/],
|
|
42
|
+
['a corpus task outside the two corpora', (s) => { s.entries[0].task = 'fixtures/fx'; }, /needs a task/],
|
|
43
|
+
['a corpus entry that carries a fixture', (s) => { s.entries[0].fixture = 'fx'; }, /carries a fixture/],
|
|
44
|
+
['a corpus entry that carries a request', (s) => { s.entries[0].request = 'x'; }, /carries a fixture or a request/],
|
|
45
|
+
['an authored entry with no request', (s) => { delete s.entries[1].request; }, /needs request text/],
|
|
46
|
+
['an authored entry with a blank request', (s) => { s.entries[1].request = ' '; }, /needs request text/],
|
|
47
|
+
['an authored entry with no fixture', (s) => { delete s.entries[1].fixture; }, /needs a fixture/],
|
|
48
|
+
['a fixture that does not exist', (s) => { s.entries[1].fixture = 'nope'; }, /fixture does not exist/],
|
|
49
|
+
['a fixture that is a file', (s) => { s.entries[1].fixture = 'afile'; }, /not a directory/],
|
|
50
|
+
['a fixture that is a symlink', (s) => { s.entries[1].fixture = 'lnk'; }, /symlink/],
|
|
51
|
+
['a fixture holding ..', (s) => { s.entries[1].fixture = '..'; }, /plain directory name/],
|
|
52
|
+
['a fixture path that climbs', (s) => { s.entries[1].fixture = '../fixtures/fx'; }, /plain directory name/],
|
|
53
|
+
['a fixture that is not directly under fixtures', (s) => { s.entries[1].fixture = 'fx/sub'; }, /plain directory name/],
|
|
54
|
+
['a fixture that is absolute', (s) => { s.entries[1].fixture = path.join(tmp, 'tests/evals/fixtures/fx'); }, /plain directory name/],
|
|
55
|
+
['the candidates directory', (s) => { s.entries[1].fixture = '_candidates'; }, /underscore directories/],
|
|
56
|
+
['the target directory', (s) => { s.entries[1].fixture = '_target'; }, /underscore directories/],
|
|
57
|
+
['an unknown key', (s) => { s.entries[1].notes = 'x'; }, /unknown key/],
|
|
58
|
+
['a control character in a request', (s) => { s.entries[1].request = 'a\u202eb'; }, /needs request text/],
|
|
59
|
+
['a wrong schema version', (s) => { s.schema_version = 2; }, /schema_version/],
|
|
60
|
+
['no entries', (s) => { s.entries = []; }, /non-empty/],
|
|
61
|
+
];
|
|
62
|
+
for (const [name, mut, want] of REDS) { const p = problems(mut); check(`rejects ${name}`, p.length > 0 && p.some((x) => want.test(x)), true); }
|
|
63
|
+
check('rejects a set that is not an object', validateSet([], { root: tmp }).length, 1);
|
|
64
|
+
|
|
65
|
+
console.log('== sizing set: label hash ==');
|
|
66
|
+
const h0 = labelHash(base);
|
|
67
|
+
check('is 64 hex characters', /^[0-9a-f]{64}$/.test(h0), true);
|
|
68
|
+
const reordered = { entries: [floor, corpus, authored].map((e) => Object.fromEntries(Object.entries(e).reverse())), schema_version: 1 };
|
|
69
|
+
check('is stable across key order and entry order', labelHash(reordered), h0);
|
|
70
|
+
const changed = (mut) => { const s = clone(base); mut(s); return labelHash(s) !== h0; };
|
|
71
|
+
check('is stable when only a reason changes', changed((s) => { s.entries[1].reason = 'other words'; }), false);
|
|
72
|
+
const MOVES = [
|
|
73
|
+
['an id', (s) => { s.entries[1].id = 'A9'; }],
|
|
74
|
+
['a label', (s) => { s.entries[0].label = 'full'; }],
|
|
75
|
+
['a request text', (s) => { s.entries[1].request += ' '; }],
|
|
76
|
+
['a fixture name', (s) => { s.entries[1].fixture = 'fy'; }],
|
|
77
|
+
['a corpus task', (s) => { s.entries[0].task = 'ab/D-empty'; }],
|
|
78
|
+
['the sensitive flag', (s) => { s.entries[2].sensitive = false; }],
|
|
79
|
+
['an added entry', (s) => { s.entries.push({ ...authored, id: 'A3' }); }],
|
|
80
|
+
];
|
|
81
|
+
for (const [name, mut] of MOVES) check(`moves when ${name} changes`, changed(mut), true);
|
|
82
|
+
check('does not confuse a request with a fixture name', labelHash({ entries: [{ id: 'X', label: 'full', fixture: 'ab', request: 'cd' }] }) !== labelHash({ entries: [{ id: 'X', label: 'full', fixture: 'a', request: 'bcd' }] }), true);
|
|
83
|
+
|
|
84
|
+
console.log('== sizing set: the committed set ==');
|
|
85
|
+
const set = loadSet();
|
|
86
|
+
check('loads and validates against the repository', validateSet(set), []);
|
|
87
|
+
check('is the file the library points at', path.relative(REPO_ROOT, SET_FILE), path.join('tests', 'evals', 'sizing-set', 'set.json'));
|
|
88
|
+
check('holds the planned entries', set.entries.map((e) => e.id), ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'T1', 'H1', 'H2', 'H4', 'A1', 'A2', 'A3', 'A4']);
|
|
89
|
+
check('uses all three tiers', TIERS.filter((t) => set.entries.some((e) => e.label === t)), [...TIERS]);
|
|
90
|
+
check('has floor cases, all labelled full', set.entries.filter((e) => e.sensitive).map((e) => `${e.id}:${e.label}`), ['H4:full', 'A3:full', 'A4:full']);
|
|
91
|
+
check('derives the scenario ids already in use', ['M01', 'T1'].map((id) => scenarioId(set.entries.find((e) => e.id === id))), ['S4-M01', 'S4-T1']);
|
|
92
|
+
// A reason or request that cites a path its fixture does not hold is a wrong label, so every cited path must exist: in the
|
|
93
|
+
// authored entry's fixture, or for a corpus entry in the repository (tests/...) or in its task's fixture (src/...).
|
|
94
|
+
const EV = path.join(REPO_ROOT, 'tests', 'evals');
|
|
95
|
+
const missing = [];
|
|
96
|
+
for (const e of set.entries) {
|
|
97
|
+
const bases = e.fixture ? [path.join(EV, 'fixtures', e.fixture)] : [REPO_ROOT, path.join(EV, e.task, 'fixture')];
|
|
98
|
+
for (const cited of `${e.request ?? ''} ${e.reason}`.match(/(?<![\w/.-])(?:src|tests|docs)\/[\w./-]*\w/g) ?? []) {
|
|
99
|
+
if (!bases.some((b) => fs.existsSync(path.join(b, cited)))) missing.push(`${e.id}: ${cited}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
check('every entry cites only paths its tree holds', missing, []);
|
|
103
|
+
check('loadSet refuses a set that fails validation', (() => { const f = path.join(tmp, 'bad.json'); fs.writeFileSync(f, '{"schema_version":1,"entries":[{"id":"Z"}]}'); try { loadSet(f); return 'no throw'; } catch (e) { return /no label/.test(e.message); } })(), true);
|
|
104
|
+
check('loadSet refuses a file that is not JSON', (() => { const f = path.join(tmp, 'junk.json'); fs.writeFileSync(f, 'nope'); try { loadSet(f); return 'no throw'; } catch (e) { return /unreadable/.test(e.message); } })(), true);
|
|
105
|
+
|
|
106
|
+
console.log('== sizing set: probe scenarios and fixture staging ==');
|
|
107
|
+
const scen = sizingScenarios(set);
|
|
108
|
+
check('has one probe scenario per entry, in set order', Object.keys(scen), set.entries.map(scenarioId));
|
|
109
|
+
check('runs a corpus entry in its task', scen['S4-M03'], { kind: 'task', corpus: 'tests/evals/ab-micro', task: 'M03-rank-aggregation', probe: true });
|
|
110
|
+
const a3 = set.entries.find((e) => e.id === 'A3');
|
|
111
|
+
check('runs an authored entry as its request in a copy of its fixture', scen['S4-A3'], { kind: 'set', dir: 'tests/evals/fixtures/task02-code', request: a3.request, probe: true });
|
|
112
|
+
const fixtureDir = path.join(REPO_ROOT, scen['S4-A3'].dir);
|
|
113
|
+
const staged = path.join(tmp, 'staged');
|
|
114
|
+
stageFixture(fixtureDir, staged);
|
|
115
|
+
check('stages the fixture files and leaves the plan tree out', [fs.existsSync(path.join(staged, 'src/auth/token.mjs')), fs.existsSync(path.join(staged, '_somi')), fs.existsSync(path.join(staged, '.somi'))], [true, false, false]);
|
|
116
|
+
check('keeps the plan tree as .somi when asked', (() => { stageFixture(fixtureDir, `${staged}-plans`, { keepPlans: true }); return [fs.existsSync(`${staged}-plans/.somi/plans`), fs.existsSync(`${staged}-plans/_somi`)]; })(), [true, false]);
|
|
117
|
+
// A scratch fixture: a file, a plan tree, and a link to a file outside it that staging must never read through.
|
|
118
|
+
const fx = path.join(tmp, 'tests/evals/fixtures/fx');
|
|
119
|
+
fs.mkdirSync(path.join(fx, '_somi/plans'), { recursive: true });
|
|
120
|
+
fs.writeFileSync(path.join(fx, 'a.txt'), 'a'); fs.writeFileSync(path.join(fx, '_somi/plans/p.md'), 'p');
|
|
121
|
+
const h1 = setMaterial(fx, 'req');
|
|
122
|
+
check('binds a fixture and a request in a stable hash that moves with either', [/^[0-9a-f]{64}$/.test(h1), setMaterial(fx, 'req') === h1, setMaterial(fx, 'req2') !== h1, (fs.writeFileSync(path.join(fx, 'a.txt'), 'b'), setMaterial(fx, 'req') !== h1)], [true, true, true, true]);
|
|
123
|
+
fs.writeFileSync(path.join(tmp, 'outside.txt'), 'SECRET');
|
|
124
|
+
fs.symlinkSync(path.join(tmp, 'outside.txt'), path.join(fx, 'inner'));
|
|
125
|
+
const out = path.join(tmp, 'out-link');
|
|
126
|
+
const thrown = (() => { try { stageFixture(fx, out); return 'no throw'; } catch (e) { return e.message; } })();
|
|
127
|
+
check('refuses a fixture with an inner link: nothing is staged, so nothing is read through it', [/could not be read/.test(thrown), fs.existsSync(out)], [true, false]);
|
|
128
|
+
check('has no material for a fixture with an inner link or one that is missing', [setMaterial(fx, 'req'), setMaterial(path.join(tmp, 'nope'), 'req')], [null, null]);
|
|
129
|
+
|
|
130
|
+
console.log(` ${pass} passed, ${fail} failed`);
|
|
131
|
+
process.exit(fail === 0 ? 0 : 1);
|