openmerit 0.1.6 → 0.1.7-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +10 -4
  2. package/README.md +61 -40
  3. package/dist/eval/src/adapters.mjs +112 -0
  4. package/dist/eval/src/cli.mjs +151 -0
  5. package/dist/eval/src/config.mjs +108 -0
  6. package/dist/eval/src/process.mjs +44 -0
  7. package/dist/eval/src/report.mjs +59 -0
  8. package/dist/eval/src/runner.mjs +123 -0
  9. package/dist/eval/src/scout.mjs +37 -0
  10. package/dist/terminal/public/app.js +36 -36
  11. package/dist/terminal/public/flow.css +1 -1
  12. package/dist/terminal/public/flow.js +26 -26
  13. package/dist/terminal/public/index.html +3 -2
  14. package/dist/terminal/public/styles.css +320 -91
  15. package/dist/terminal/src/cli.mjs +2 -0
  16. package/dist/terminal/src/demo-policy.mjs +205 -0
  17. package/dist/terminal/src/enterprise-sample.mjs +151 -0
  18. package/docs/adapter-guide.md +2 -2
  19. package/docs/agent-evaluations.md +145 -0
  20. package/docs/architecture.md +3 -3
  21. package/docs/automation.md +5 -5
  22. package/docs/budgets.md +2 -2
  23. package/docs/commands.md +9 -5
  24. package/docs/demo-backfill.md +3 -1
  25. package/docs/demo-fieldkit.md +3 -1
  26. package/docs/demo-placement.md +3 -1
  27. package/docs/demo-spam.md +3 -1
  28. package/docs/demo-support.md +3 -1
  29. package/docs/demo.md +22 -5
  30. package/docs/first-trial.md +2 -2
  31. package/docs/getting-started.md +23 -12
  32. package/docs/index.md +18 -29
  33. package/docs/inference-terminal.md +90 -54
  34. package/docs/interactive-demo.md +118 -0
  35. package/docs/lifecycle.md +4 -4
  36. package/docs/metrics-and-evidence.md +3 -3
  37. package/docs/operations.md +3 -5
  38. package/docs/pi-extension.md +6 -6
  39. package/docs/roadmap.md +17 -17
  40. package/docs/scout.md +206 -0
  41. package/docs/security.md +8 -4
  42. package/docs/site-demo.md +4 -0
  43. package/docs/site-design.md +7 -1
  44. package/docs/site-documentation.md +9 -3
  45. package/docs/site-domain-migration.md +57 -0
  46. package/docs/site-dynamic-og.md +2 -2
  47. package/docs/site-faq-maintenance.md +133 -6
  48. package/docs/site-hero-resolution.md +2 -0
  49. package/docs/site-illustration-sequences.md +3 -1
  50. package/docs/site-illustration-transparency.md +80 -0
  51. package/docs/site-memo.md +6 -0
  52. package/docs/site-og-image.md +1 -1
  53. package/docs/site-publication-2026-10-14.md +29 -0
  54. package/docs/site-scout-decisions-experiment.md +87 -0
  55. package/docs/site-scout.md +254 -0
  56. package/docs/site-terminal-preview.md +96 -3
  57. package/docs/site-themes.md +30 -0
  58. package/docs/testing.md +46 -68
  59. package/docs/troubleshooting.md +3 -3
  60. package/package.json +9 -3
@@ -0,0 +1,59 @@
1
+ const mean = values => values.length ? values.reduce((a, b) => a + b, 0) / values.length : null;
2
+ const median = values => { const sorted = [...values].sort((a, b) => a - b); return sorted.length ? (sorted[Math.floor((sorted.length - 1) / 2)] + sorted[Math.floor(sorted.length / 2)]) / 2 : null; };
3
+ const completeMean = values => values.every(v => v !== null) ? mean(values) : null;
4
+ export function summarize(rows) {
5
+ const groups = new Map();
6
+ for (const row of rows) {
7
+ const key = [row.task, row.connection, row.variant].join('/');
8
+ if (!groups.has(key)) groups.set(key, []); groups.get(key).push(row);
9
+ }
10
+ return [...groups].map(([key, runs]) => ({
11
+ key, task: runs[0].task, connection: runs[0].connection, variant: runs[0].variant, runs: runs.length,
12
+ quality: completeMean(runs.map(r => r.quality)), failures: runs.filter(r => r.status !== 'ok' && r.quality !== null).length,
13
+ blockedAttempts: runs.filter(r => r.failureReason).length, scoredRuns: runs.filter(r => r.quality !== null).length,
14
+ failedTaskChecks: runs.filter(r => r.status === 'ok' && r.quality === 0).length,
15
+ qualityRange: runs.every(r => r.quality !== null) ? [Math.min(...runs.map(r => r.quality)), Math.max(...runs.map(r => r.quality))] : null,
16
+ inputTokens: completeMean(runs.map(r => r.usage?.input ?? null)), outputTokens: completeMean(runs.map(r => r.usage?.output ?? null)),
17
+ reportedCostUsd: runs.some(r => r.costUsd !== null) ? runs.filter(r => r.costUsd !== null).reduce((s, r) => s + r.costUsd, 0) : null, unknownCosts: runs.filter(r => r.costUsd === null).length,
18
+ partialReportedCostUsd: runs.reduce((s, r) => s + (r.partialCostUsd ?? 0), 0),
19
+ meanCostUsd: completeMean(runs.map(r => r.costUsd)), medianSeconds: median(runs.map(r => r.seconds)),
20
+ }));
21
+ }
22
+ export function isVolatile(rows) {
23
+ const spread = values => {
24
+ if (values.length < 3 || values.some(v => v === null)) return false;
25
+ const avg = mean(values);
26
+ return avg > 0 && Math.sqrt(mean(values.map(v => (v - avg) ** 2))) / avg > .25;
27
+ };
28
+ for (const group of summarize(rows)) {
29
+ const runs = rows.filter(r => `${r.task}/${r.connection}/${r.variant}` === group.key);
30
+ if (group.qualityRange && group.qualityRange[1] - group.qualityRange[0] > .05 || runs.some(r => r.status !== 'ok') || spread(runs.map(r => r.seconds)) || spread(runs.map(r => r.costUsd)) || spread(runs.map(r => r.usage?.input ?? null))) return true;
31
+ }
32
+ return false;
33
+ }
34
+ export function compareReports(current, previous) {
35
+ if (!previous || previous.compatibility !== current.compatibility || previous.planHash !== current.planHash || previous.status !== 'complete' || current.status !== 'complete') return null;
36
+ return current.summary.map(now => {
37
+ const before = previous.summary.find(row => row.key === now.key);
38
+ if (!before) return null;
39
+ const delta = key => now[key] === null || before[key] === null ? null : now[key] - before[key];
40
+ return { key: now.key, previousRuns: before.runs, runs: now.runs, qualityDelta: delta('quality'), inputTokensDelta: delta('inputTokens'), outputTokensDelta: delta('outputTokens'), meanCostUsdDelta: delta('meanCostUsd'), medianSecondsDelta: delta('medianSeconds') };
41
+ }).filter(Boolean);
42
+ }
43
+ const fmt = (v, digits = 2) => v === null || v === undefined ? '?' : v.toFixed(digits);
44
+ export function formatReport(report) {
45
+ const lines = [`OpenMerit eval · ${report.status} · ${report.revision.slice(0, 12)}`, '', 'Task / connection / variant | scored / attempts | blocked | quality | input / output tokens | estimated $/run | seconds (median)'];
46
+ for (const row of report.summary) {
47
+ lines.push(`${row.key} | ${row.scoredRuns ?? row.runs} / ${row.runs} | ${row.blockedAttempts ?? 0} | ${row.quality === null ? '?' : fmt(row.quality * 100, 1) + '%'} | ${fmt(row.inputTokens, 0)} / ${fmt(row.outputTokens, 0)} | ${fmt(row.meanCostUsd, 5)} | ${fmt(row.medianSeconds)}`);
48
+ if (row.partialReportedCostUsd > 0) lines.push(` Partial cost estimate: $${fmt(row.partialReportedCostUsd, 5)}; full attempt cost unknown.`);
49
+ }
50
+ if (report.comparison) {
51
+ lines.push('', 'Change from the previous compatible revision (negative tokens/cost/time is lower):');
52
+ for (const row of report.comparison) lines.push(`${row.key}: quality ${fmt(row.qualityDelta === null ? null : row.qualityDelta * 100, 1)} pp; tokens ${fmt(row.inputTokensDelta, 0)} / ${fmt(row.outputTokensDelta, 0)}; $ ${fmt(row.meanCostUsdDelta, 5)}; seconds ${fmt(row.medianSecondsDelta)}`);
53
+ } else lines.push('', 'No complete, compatible previous revision for comparison.');
54
+ lines.push('', '3–10 repetitions measure variability, not statistical certainty. ? means unavailable.', 'Costs are agent-reported estimates, not reconciled bills. Compare agents as different harnesses.');
55
+ if (report.budgetLimitUsd !== undefined) lines.push(report.budgetLimitUsd === 'unlimited' ? 'Budget: no fixed cap. Task/repetition limits and timeouts still apply; watched changes can incur further charges until stopped.' : `Budget: $${fmt(report.budgetLimitUsd)} cumulative across reruns.`);
56
+ lines.push(`Reserved allowance used: $${fmt(report.budgetUsedUsd, 5)} (not billed spend). Blocked attempts are unscored.`);
57
+ if (report.reason) lines.push(`Stopped: ${report.reason}`);
58
+ return lines.join('\n');
59
+ }
@@ -0,0 +1,123 @@
1
+ import { mkdir, mkdtemp, rm, readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { loadConfig, snapshot, materialize, readJSON, saveJSON, statePath, digest, reservationFor } from './config.mjs';
6
+ import { validatePlan } from './scout.mjs';
7
+ import { preflight, runAgent, invocation } from './adapters.mjs';
8
+ import { execute, agentEnvironment } from './process.mjs';
9
+ import { summarize, isVolatile, compareReports } from './report.mjs';
10
+
11
+ async function optionalJSON(path) { try { return await readJSON(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
12
+ export async function acquireLock(root) {
13
+ const lock = join(root, statePath, 'lock'); await mkdir(join(root, statePath), { recursive: true });
14
+ try { await mkdir(lock); } catch (error) { if (error.code === 'EEXIST') throw new Error('An eval run/watch owns this project. Stop it first. After a crash, verify the PID in .openmerit/eval/lock/pid before removing that lock directory.'); throw error; }
15
+ await writeFile(join(lock, 'pid'), String(process.pid));
16
+ return () => rm(lock, { recursive: true, force: true });
17
+ }
18
+ export function budgetUsed(ledger) {
19
+ if (ledger?.version !== 1 || !Array.isArray(ledger.entries) || ledger.entries.some(e => !Number.isFinite(e.reservationUsd) || e.reservationUsd <= 0 || e.costUsd !== null && (!Number.isFinite(e.costUsd) || e.costUsd < 0))) throw new Error('Invalid budget ledger. Restore it before running; never discard unknown charges.');
20
+ // Agent prices are estimates, not provider settlement. Never release a
21
+ // reservation on that evidence, including entries written by older previews.
22
+ return ledger.entries.reduce((sum, e) => sum + Math.max(e.costUsd ?? 0, e.reservationUsd), 0);
23
+ }
24
+
25
+ export async function evaluate(root, { signal, onProgress = () => {}, agentRunner = runAgent, checkAgent = preflight } = {}) {
26
+ const config = await loadConfig(root), plan = await readJSON(join(root, statePath, 'plan.json'));
27
+ validatePlan(config, plan);
28
+ const snap = await snapshot(root, config);
29
+ const selected = new Set(plan.tasks.flatMap(t => t.candidates.flatMap(c => c.connections)));
30
+ const versions = {};
31
+ const ledgerPath = join(root, statePath, 'budget.json');
32
+ const ledger = await optionalJSON(ledgerPath) ?? { version: 1, entries: [] };
33
+ const reservationUsd = reservationFor(config, plan), unlimitedBudget = config.budget.maxUsd === 'unlimited';
34
+ const exhausted = () => { const used = budgetUsed(ledger); return !unlimitedBudget && used + reservationUsd > config.budget.maxUsd + 1e-10; };
35
+ if (exhausted()) throw new Error('Evaluation budget is exhausted or disabled. Choose a budget with eval plan --budget <USD|unlimited>; prior reservations still count.');
36
+ const runnerVersion = (await readJSON(new URL('../../../package.json', import.meta.url))).version;
37
+ const commands = config.connections.filter(c => selected.has(c.id)).map(c => ({ id: c.id, args: invocation(c, reservationUsd, unlimitedBudget) }));
38
+ const report = { version: 2, runnerVersion, budgetLimitUsd: config.budget.maxUsd, reservationUsd, id: randomUUID(), startedAt: new Date().toISOString(), revision: snap.revision, compatibility: null, planHash: digest(plan.tasks), agentVersions: versions, status: 'running', rows: [], summary: [] };
39
+ const reportPath = join(root, statePath, 'runs', `${report.startedAt.replace(/[:.]/g, '-')}-${report.id}.json`);
40
+ const previous = await optionalJSON(join(root, statePath, 'latest.json'));
41
+ const temp = await mkdtemp(join(tmpdir(), 'openmerit-eval-'));
42
+ const checkpoint = async () => { report.summary = summarize(report.rows); await saveJSON(reportPath, report); };
43
+ try {
44
+ await checkpoint();
45
+ for (const connection of config.connections.filter(c => selected.has(c.id))) {
46
+ try { versions[connection.id] = await checkAgent(connection, { cwd: temp }); }
47
+ catch (error) { error.connection = connection.id; throw error; }
48
+ }
49
+ // Graders are copied outside all agent workspaces, before any trial runs.
50
+ for (const task of snap.tasks) await materialize(task.graderFiles, join(temp, 'graders', task.id));
51
+ outer: for (const task of snap.tasks) {
52
+ const taskPlan = plan.tasks.find(t => t.id === task.id);
53
+ const cells = taskPlan.candidates.flatMap(candidate => candidate.connections.flatMap(connection => snap.variants.map(variant => ({ connection: config.connections.find(c => c.id === connection), variant, candidate }))));
54
+ for (let round = 0; round < config.repeats.max; round++) {
55
+ // Rotate and reverse the balanced order so one candidate is not always warm/last.
56
+ const ordered = [...cells.slice(round % cells.length), ...cells.slice(0, round % cells.length)];
57
+ if (round % 2) ordered.reverse();
58
+ for (const { connection, variant, candidate } of ordered) {
59
+ if (signal?.aborted) { report.status = 'cancelled'; report.reason = 'Interrupted'; break outer; }
60
+ if (exhausted()) { report.status = 'budget_stopped'; report.reason = 'Cumulative budget cannot admit another reserved attempt.'; break outer; }
61
+ const entry = { id: randomUUID(), run: report.id, reservationUsd, costUsd: null, settled: false };
62
+ ledger.entries.push(entry); await saveJSON(ledgerPath, ledger);
63
+ const workspace = join(temp, entry.id); await mkdir(workspace);
64
+ await materialize(task.fixtureFiles, workspace, task.fixture);
65
+ await materialize(variant.sourceFiles, workspace);
66
+ const prompt = `${task.prompt}\n\n${variant.instructions}\n\nThis is an isolated evaluation attempt. Do not run OpenMerit evaluation commands or inspect paths outside this workspace.`;
67
+ const result = await agentRunner(connection, prompt, { cwd: workspace, timeoutMs: config.timeoutSeconds * 1000, signal, reservationUsd, unlimitedBudget });
68
+ entry.costUsd = result.costUsd; entry.costBasis = result.costBasis ?? (result.costUsd === null ? 'unknown' : 'agent_estimate');
69
+ entry.partialCostUsd = result.partialCostUsd ?? null; entry.reservationUsd = Math.max(entry.reservationUsd, result.partialCostUsd ?? 0); entry.settled = true; await saveJSON(ledgerPath, ledger);
70
+ let quality = result.status === 'ok' || result.failureReason ? null : 0, status = result.status;
71
+ if (result.status === 'ok') {
72
+ const grader = await execute(process.execPath, [join(temp, 'graders', task.id, task.grader)], { cwd: temp, env: agentEnvironment(), input: JSON.stringify({ workspace, output: result.output }), timeoutMs: 30_000, signal });
73
+ try {
74
+ const value = JSON.parse(grader.stdout);
75
+ if (grader.code !== 0 || grader.reason || typeof value.quality !== 'number' || !Number.isFinite(value.quality) || value.quality < 0 || value.quality > 1) throw new Error('Invalid grade');
76
+ quality = value.quality;
77
+ } catch { status = 'grader_error'; }
78
+ }
79
+ const row = { task: task.id, connection: connection.id, agent: connection.agent, requestedModel: connection.model, observedModels: result.observedModels, scoutId: candidate.scoutId, scoutRank: candidate.rank, variant: variant.id, round: round + 1, quality, status, failureReason: result.failureReason ?? null, usage: result.usage, costUsd: result.costUsd, partialCostUsd: result.partialCostUsd ?? null, costBasis: entry.costBasis, seconds: result.seconds };
80
+ report.rows.push(row); await checkpoint(); await rm(workspace, { recursive: true, force: true });
81
+ onProgress(row);
82
+ if (result.failureReason) {
83
+ report.status = result.failureReason === 'budget_exhausted' ? 'budget_stopped' : result.failureReason === 'cancelled' ? 'cancelled' : ['sandbox_unavailable', 'permission_denied', 'spawn_failed'].includes(result.failureReason) ? 'environment_blocked' : 'connection_blocked';
84
+ report.reason = `${connection.id}: ${result.failureReason}. This attempt is unscored; resolve the execution block before retrying.`;
85
+ break outer;
86
+ }
87
+ if (status === 'grader_error') { report.status = 'invalid'; report.reason = `Grader failed for ${task.id}. Fix it before collecting more trials.`; break outer; }
88
+ }
89
+ if (round + 1 >= config.repeats.min && !isVolatile(report.rows.filter(r => r.task === task.id))) break;
90
+ }
91
+ }
92
+ if (report.status === 'running') report.status = 'complete';
93
+ } catch (error) {
94
+ if (error.failureReason) {
95
+ report.status = 'environment_blocked'; report.reason = `${error.connection}: ${error.failureReason}. ${error.message}`;
96
+ report.blockers = [{ connection: error.connection, failureReason: error.failureReason }];
97
+ } else {
98
+ report.status = 'error'; report.reason = 'Execution failed; unsettled reservations remain charged. Check configuration and agent authentication.';
99
+ throw error;
100
+ }
101
+ } finally {
102
+ report.finishedAt = new Date().toISOString(); report.budgetUsedUsd = budgetUsed(ledger);
103
+ report.compatibility = digest({ accountingVersion: report.version, snapshot: snap.compatibility, versions, runnerVersion, commands, observedModels: Object.fromEntries([...selected].sort().map(id => [id, [...new Set(report.rows.filter(r => r.connection === id).flatMap(r => r.observedModels ?? []))].sort()])) });
104
+ report.summary = summarize(report.rows); report.comparison = compareReports(report, previous);
105
+ await saveJSON(reportPath, report); await saveJSON(join(root, statePath, 'latest.json'), report);
106
+ await rm(temp, { recursive: true, force: true });
107
+ }
108
+ return report;
109
+ }
110
+
111
+ export async function watch(root, { signal, onReport, onProgress, intervalMs = 1500, ...options } = {}) {
112
+ let last = null, pending = null;
113
+ while (!signal?.aborted) {
114
+ const config = await loadConfig(root), current = (await snapshot(root, config)).revision;
115
+ if (current !== last && current === pending) {
116
+ const result = await evaluate(root, { signal, onProgress, ...options });
117
+ onReport?.(result); last = result.revision;
118
+ if (result.status !== 'complete') return result;
119
+ }
120
+ pending = current;
121
+ await new Promise(resolve => { const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); }; const timer = setTimeout(done, intervalMs); signal?.addEventListener('abort', done, { once: true }); });
122
+ }
123
+ }
@@ -0,0 +1,37 @@
1
+ import { digest, saveJSON, statePath } from './config.mjs';
2
+ import { join } from 'node:path';
3
+
4
+ export const selectionHash = config => digest({ scope: config.scope, connections: config.connections, tasks: config.tasks.map(t => ({ id: t.id, description: t.description })), scoutURL: config.scoutURL });
5
+ export async function makePlan(config, fetcher = fetch) {
6
+ if (!['existing', 'all'].includes(config.scope)) throw new Error('Choose a scope with eval plan --scope existing or --scope all. Existing means the connections declared for this project.');
7
+ const modelIds = [...new Set(config.connections.map(c => c.scoutId))];
8
+ if (config.scope === 'existing' && !modelIds.length) throw new Error('Declare project connections in .openmerit/eval.json first. No credentials are sent to Scout.');
9
+ const tasks = [];
10
+ for (const task of config.tasks) {
11
+ const response = await fetcher(config.scoutURL ?? 'https://openmerit.ai/scout/api/recommend', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: task.description, ...(config.scope === 'existing' ? { modelIds } : {}) }), signal: AbortSignal.timeout(15_000), redirect: 'error' });
12
+ if (!response.ok) throw new Error(`Scout returned HTTP ${response.status}; no evaluation was started.`);
13
+ const body = await response.json();
14
+ if (!Array.isArray(body.recommendations) || body.recommendations.length > 5) throw new Error('Invalid Scout response.');
15
+ if (config.scope === 'existing' && (!Array.isArray(body.selection?.modelIds) || digest([...body.selection.modelIds].sort()) !== digest([...modelIds].sort()))) throw new Error('Scout did not acknowledge filtering before ranking. Update the Scout endpoint; no unscoped fallback is allowed.');
16
+ const seen = new Set();
17
+ const candidates = body.recommendations.map(m => {
18
+ if (typeof m.id !== 'string' || seen.has(m.id) || config.scope === 'existing' && !modelIds.includes(m.id)) throw new Error('Invalid Scout model selection.');
19
+ seen.add(m.id);
20
+ return { scoutId: m.id, name: m.name, rank: m.rank, connections: config.connections.filter(c => c.scoutId === m.id).map(c => c.id) };
21
+ });
22
+ tasks.push({ id: task.id, candidates, ranking: body.ranking, warnings: body.warnings ?? [] });
23
+ }
24
+ return { version: 1, createdAt: new Date().toISOString(), scope: config.scope, selectionHash: selectionHash(config), tasks };
25
+ }
26
+ export async function savePlan(root, plan) { await saveJSON(join(root, statePath, 'plan.json'), plan); }
27
+ export function validatePlan(config, plan) {
28
+ if (plan.selectionHash !== selectionHash(config)) throw new Error('Task descriptions, scope or connections changed. Run eval plan again.');
29
+ if (!Array.isArray(plan.tasks) || plan.tasks.length !== config.tasks.length) throw new Error('Incomplete evaluation plan. Run eval plan again.');
30
+ for (const task of config.tasks) {
31
+ const entry = plan.tasks.find(t => t.id === task.id);
32
+ if (!entry?.candidates?.length) throw new Error(`Scout has no supported candidates for ${task.id}. Broaden scope or revise the task description.`);
33
+ for (const model of entry.candidates) {
34
+ if (!model.connections.length || model.connections.some(id => !config.connections.some(c => c.id === id && c.scoutId === model.scoutId))) throw new Error(`Configure an authenticated agent connection for ${model.scoutId}, then plan again. All-model discovery does not grant endpoint access.`);
35
+ }
36
+ }
37
+ }