Skip to content

28 eval-informed mental models and critical-thinking skills for Claude Code, GitHub Copilot, Codex, Cursor, and other Agent Skills-compatible tools

test(evals): harden measurement contracts

Travis Boudreaux89252c237bb0
diff --git a/evals/lib/claims.js b/evals/lib/claims.js
new file mode 100644
index 0000000..e1b129f
--- /dev/null
+++ b/evals/lib/claims.js
@@ -0,0 +1,239 @@
+'use strict';
+
+/**
+ * Claim automation: artifact eligibility classification, preregistration drift
+ * detection, and claim ledger generation.
+ *
+ * Confirmatory claims use declared study bundles via evidence.js only.
+ * Recursive results scanning remains for diagnostic/legacy ledger output but
+ * cannot alone mark a claim confirmatory.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+
+const {
+ listConfirmatoryCandidates,
+ evaluateConfirmationEligibility,
+ listDeclaredBundles,
+} = require('./evidence');
+const { loadRegistry } = require('./registry');
+
+/**
+ * Classify a legacy runner artifact's eligibility for non-confirmatory evidence.
+ * @param {object} artifact - parsed JSON artifact from a runner
+ * @returns {{eligible: boolean, status: string, blockers: string[], warnings: string[]}}
+ */
+function classifyArtifact(artifact) {
+ if (!artifact || typeof artifact !== 'object') {
+ return { eligible: false, status: 'invalid', blockers: ['artifact is not a valid object'], warnings: [] };
+ }
+
+ const blockers = [];
+ const warnings = [];
+
+ // Check run_health / health
+ const health = artifact.run_health || artifact.health;
+ if (!health) {
+ warnings.push('missing run_health; cannot verify solver reliability');
+ } else {
+ if (health.decision_eligible === false) {
+ blockers.push(`solver_failures=${health.solver_failures || health.failures || 0}; not decision-eligible`);
+ }
+ const rate = health.failure_rate || 0;
+ if (rate > 0.05) {
+ blockers.push(`failure_rate=${rate} exceeds 5% threshold; artifact is diagnostic only`);
+ }
+ }
+
+ // Check warnings array
+ if (Array.isArray(artifact.warnings)) {
+ for (const w of artifact.warnings) {
+ if (w.severity === 'major') blockers.push(w.message);
+ else warnings.push(w.message);
+ }
+ }
+
+ // Check mode — pilot/behavioral/factorial modes are NOT confirmatory
+ const mode = artifact.mode || '';
+ const isPilotMode = mode.includes('pilot') || mode.includes('behavioral') || mode.includes('factorial') || mode.includes('workflow-vs-skill') || mode.includes('workflow-factorial');
+ if (isPilotMode) {
+ blockers.push(`mode='${mode}' is exploratory/pilot; not eligible for confirmatory claims`);
+ }
+ // claim_status: 'confirmed' is confirmatory; 'inconclusive' is citable as evidence but not confirmatory
+ const claimStat = artifact.claim_status || 'missing';
+ const isConfirmed = claimStat === 'confirmed';
+ const isInconclusive = claimStat === 'inconclusive';
+ if (!isConfirmed && !isInconclusive) {
+ blockers.push(`claim_status='${claimStat}'; not eligible for any claim`);
+ }
+ if (!isConfirmed) {
+ warnings.push(`claim_status='${claimStat}'; citable as evidence only, not confirmatory`);
+ }
+
+ // Recursive scan artifacts are never confirmatory without declared-bundle gates
+ warnings.push('legacy artifact path cannot alone confirm; requires declared study bundle evaluation');
+
+ // Determine status
+ let status;
+ if (blockers.length > 0) status = 'ineligible';
+ else if (warnings.length > 0) status = 'eligible_as_evidence';
+ else status = 'eligible';
+
+ return {
+ eligible: blockers.length === 0,
+ // never confirmatory from legacy scan alone
+ confirmatory_eligible: false,
+ status,
+ blockers,
+ warnings,
+ };
+}
+
+/**
+ * Detect preregistration drift between an artifact and the current preregistration.
+ * @param {object} artifact - parsed JSON artifact
+ * @param {string} currentPreregSha256 - SHA-256 of current prereg file
+ * @returns {{drifted: boolean, artifact_sha: string|null, current_sha: string, status: string}}
+ */
+function detectPreregDrift(artifact, currentPreregSha256) {
+ const artifactPrereg = artifact?.preregistration;
+ const artifactSha = artifactPrereg?.sha256 || artifact?.preregistration_sha256 || null;
+ const currentSha = currentPreregSha256;
+
+ if (!artifactSha) {
+ return { drifted: true, artifact_sha: null, current_sha: currentSha, status: 'missing_prereg_in_artifact' };
+ }
+ if (artifactSha !== currentSha) {
+ return { drifted: true, artifact_sha: artifactSha, current_sha: currentSha, status: 'drifted' };
+ }
+ return { drifted: false, artifact_sha: artifactSha, current_sha: currentSha, status: 'current' };
+}
+
+/**
+ * Generate a claim ledger from declared study bundles (confirmatory path)
+ * plus optional legacy results scan (diagnostic only).
+ * @param {string} resultsDir - path to results directory (legacy diagnostic)
+ * @param {string} preregFile - path to current preregistration file
+ * @returns {object} claim ledger
+ */
+function generateClaimLedger(resultsDir, preregFile) {
+ const preregSha = fs.existsSync(preregFile)
+ ? crypto.createHash('sha256').update(fs.readFileSync(preregFile, 'utf8')).digest('hex')
+ : null;
+
+ let registry = null;
+ try {
+ registry = loadRegistry().registry;
+ } catch (_) {
+ registry = null;
+ }
+
+ const ledger = {
+ generated_at: new Date().toISOString(),
+ preregistration_sha256: preregSha,
+ claims: [],
+ declared_bundle_evaluations: [],
+ };
+
+ // Primary: declared study bundles only for confirmatory eligibility
+ if (registry) {
+ const evaluations = listConfirmatoryCandidates(registry).map(evaluation => {
+ // Re-evaluate with current prereg sha so drift is exact, not presence-only
+ return evaluateConfirmationEligibility({
+ studyId: evaluation.study_id,
+ registry,
+ currentPreregSha256: preregSha,
+ preregFile,
+ });
+ });
+ ledger.declared_bundle_evaluations = evaluations;
+ for (const evaluation of evaluations) {
+ const artifactSha = evaluation.hashes?.preregistration_sha256 || null;
+ const drift = detectPreregDrift(
+ { preregistration_sha256: artifactSha },
+ preregSha
+ );
+ const blockers = [...(evaluation.blockers || [])];
+ if (drift.drifted) {
+ if (!blockers.some(b => /prereg/i.test(b))) {
+ blockers.push('prereg drift: artifact sha ≠ current');
+ }
+ }
+ const confirmatory = evaluation.confirmatory === true && !drift.drifted;
+ ledger.claims.push({
+ file: evaluation.bundle?.path || evaluation.study_id,
+ mode: 'declared_study_bundle',
+ claim: evaluation.study_id,
+ study_id: evaluation.study_id,
+ eligible: confirmatory,
+ confirmatory_eligible: confirmatory,
+ status: drift.drifted ? 'stale' : evaluation.status,
+ blockers,
+ warnings: evaluation.warnings,
+ prereg_drift: drift,
+ run_health: evaluation.health,
+ source: 'declared_bundle',
+ });
+ }
+ }
+
+ // Legacy recursive scan: diagnostic only, never confirmatory
+ function scanDir(dir) {
+ if (!fs.existsSync(dir)) return;
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ scanDir(fullPath);
+ } else if (entry.name.endsWith('.json') && entry.name !== 'claim-ledger.json') {
+ try {
+ const artifact = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
+ const classification = classifyArtifact(artifact);
+ const drift = detectPreregDrift(artifact, preregSha);
+ const claimKey = artifact.mode || path.basename(fullPath, '.json');
+ const blockers = [...classification.blockers];
+ if (drift.drifted) blockers.push('prereg drift: artifact sha ≠ current');
+
+ ledger.claims.push({
+ file: path.relative(resultsDir, fullPath),
+ mode: artifact.mode || 'unknown',
+ claim: claimKey,
+ eligible: classification.eligible && !drift.drifted,
+ confirmatory_eligible: false,
+ status: drift.drifted ? 'stale' : classification.status,
+ blockers,
+ warnings: classification.warnings,
+ prereg_drift: drift,
+ run_health: (artifact.run_health || artifact.health) ? {
+ solver_calls: artifact.run_health?.solver_calls,
+ solver_failures: artifact.run_health?.solver_failures ?? artifact.health?.failures,
+ failure_rate: (artifact.run_health || artifact.health)?.failure_rate,
+ decision_eligible: (artifact.run_health || artifact.health)?.decision_eligible,
+ } : null,
+ source: 'legacy_results_scan',
+ });
+ } catch (_) { /* skip unparseable files */ }
+ }
+ }
+ }
+
+ if (resultsDir) scanDir(resultsDir);
+ return ledger;
+}
+
+/**
+ * Confirmatory claim check for a study id via declared bundles only.
+ */
+function evaluateStudyClaim(studyId, registry = null) {
+ return evaluateConfirmationEligibility({ studyId, registry });
+}
+
+module.exports = {
+ classifyArtifact,
+ detectPreregDrift,
+ generateClaimLedger,
+ evaluateStudyClaim,
+ listDeclaredBundles,
+ evaluateConfirmationEligibility,
+};
diff --git a/evals/lib/conditions.js b/evals/lib/conditions.js
index b735e12..548a4a7 100644
--- a/evals/lib/conditions.js
+++ b/evals/lib/conditions.js
@@ -1,20 +1,18 @@
'use strict';
/**
- * Solver conditions for the behavioral eval. Addresses the adversarial reviewers'
- * #1 validity threat: the treatment injects 2-4k words, so naive "skill vs empty"
- * confounds the model's reasoning with simply having more tokens to think with.
+ * Solver conditions / arm prompt builders.
*
- * placebo — problem + neutral, content-free filler matched to the skill's word count
- * skill — problem + the full SKILL.md
- * trigger — problem + skill name + a 2-3 sentence trigger summary (textbook-vs-trigger test)
- *
- * Headline comparison is skill-vs-placebo (length-controlled). The skill:trigger
- * comparison reveals whether the full guide beats a one-liner.
+ * Primary control is production no-skill (`none` / legacy `empty`).
+ * Secondary equal-budget placebo uses deterministic indexed inert tokens inside
+ * <context-padding>, sized by an injectable token counter to the treatment budget.
+ * Legacy condition names remain callable.
*/
-// Neutral, true-but-method-free sentences in a software register. Carries no
-// analytical framework — a fair length placebo.
+const DEFAULT_TAIL = '\n\nThink carefully and give your best, decision-useful answer.';
+
+// Legacy sentence bank retained for export compatibility; neutralFiller no longer
+// emits advice-bearing prose — it routes through context-padding tokens.
const FILLER_SENTENCES = [
'When approaching a task, it helps to read the request carefully and confirm what is actually being asked.',
'Software systems are made of many components, and work in one area often touches others.',
@@ -30,19 +28,69 @@ const FILLER_SENTENCES = [
'It is reasonable to ask clarifying questions when a request is open to interpretation.',
];
-function neutralFiller(wordCount) {
- const out = [];
- let count = 0, i = 0;
- while (count < wordCount) {
- const s = FILLER_SENTENCES[i % FILLER_SENTENCES.length];
- out.push(s);
- count += s.split(/\s+/).length;
- i++;
+/** Default token counter: whitespace-separated tokens (injectable override supported). */
+function defaultTokenCounter(text) {
+ if (text == null || text === '') return 0;
+ return String(text).split(/\s+/).filter(Boolean).length;
+}
+
+function wordCount(s) {
+ return defaultTokenCounter(s);
+}
+
+/**
+ * Deterministic indexed inert padding tokens. No analytical advice.
+ * Token shape: PAD_0001 PAD_0002 ... so counters treat each as one unit.
+ */
+function contextPaddingTokens(tokenCount, options = {}) {
+ const n = Math.max(0, Math.floor(Number(tokenCount) || 0));
+ if (n === 0) return '';
+ const start = Number.isInteger(options.startIndex) && options.startIndex > 0 ? options.startIndex : 1;
+ const parts = [];
+ for (let i = 0; i < n; i++) {
+ parts.push(`PAD_${String(start + i).padStart(4, '0')}`);
+ }
+ return parts.join(' ');
+}
+
+/**
+ * Wrap padding tokens in <context-padding> for the equal-budget placebo arm.
+ * Sized so total tokens of the padding body match `tokenBudget` under `tokenCounter`.
+ */
+function buildContextPadding(tokenBudget, options = {}) {
+ const counter = typeof options.tokenCounter === 'function' ? options.tokenCounter : defaultTokenCounter;
+ const budget = Math.max(0, Math.floor(Number(tokenBudget) || 0));
+ if (budget === 0) return '<context-padding></context-padding>';
+
+ // Grow token body until measured size reaches budget (handles multi-token wrappers
+ // if a custom counter is used; with default whitespace counter each PAD is 1 token).
+ let body = contextPaddingTokens(budget, options);
+ let measured = counter(body);
+ let guard = 0;
+ while (measured < budget && guard < budget + 8) {
+ body = contextPaddingTokens(budget + guard + 1, options);
+ measured = counter(body);
+ guard++;
}
- return out.join(' ');
+ if (measured > budget) {
+ // Trim to exact budget under the counter when possible.
+ const tokens = body.split(/\s+/).filter(Boolean);
+ while (tokens.length > 0 && counter(tokens.join(' ')) > budget) tokens.pop();
+ body = tokens.join(' ');
+ }
+ return `<context-padding>\n${body}\n</context-padding>`;
}
-function wordCount(s) { return s.split(/\s+/).filter(Boolean).length; }
+/**
+ * Length-matched inert filler. Replaces advice-bearing prose with context-padding
+ * tokens. `wordCount` is treated as a token budget under the optional counter.
+ * Legacy name preserved.
+ */
+function neutralFiller(tokenBudget, options = {}) {
+ const block = buildContextPadding(tokenBudget, options);
+ const m = block.match(/<context-padding>\n?([\s\S]*?)\n?<\/context-padding>/);
+ return (m ? m[1] : '').trim();
+}
/** A 2-3 sentence trigger summary built from the skill's own frontmatter + core principle. */
function triggerSummary(content, name) {
@@ -53,38 +101,102 @@ function triggerSummary(content, name) {
return s;
}
-function buildConditionPrompt(condition, problemText, skillContent, skillName) {
- const tail = `\n\nThink carefully and give your best, decision-useful answer.`;
- if (condition === 'empty') return `${problemText}${tail}`;
- if (condition === 'placebo') {
- const filler = neutralFiller(wordCount(skillContent));
- return `Some general notes before the task:\n\n${filler}\n\nNow address this problem:\n\n${problemText}${tail}`;
+function normalizeCondition(condition) {
+ if (condition == null) return 'none';
+ const c = String(condition).toLowerCase().replace(/-/g, '_');
+ if (c === 'empty' || c === 'none' || c === 'no_skill' || c === 'noskill') return 'none';
+ if (c === 'placebo' || c === 'equal_budget_placebo' || c === 'equal_budget') return 'equal_budget_placebo';
+ if (c === 'trigger') return 'trigger';
+ if (c === 'skill' || c === 'full' || c === 'full_legacy' || c === 'lean') return 'skill';
+ return c;
+}
+
+/**
+ * Build a solve prompt for a named condition/arm.
+ * Primary control: `none` (also accepts legacy `empty`).
+ * Secondary diagnostic: `equal_budget_placebo` / `placebo`.
+ * Treatment: `skill` (also accepts full/lean aliases for prompt shape).
+ */
+function buildConditionPrompt(condition, problemText, skillContent, skillName, options = {}) {
+ const arm = normalizeCondition(condition);
+ const tail = options.tail != null ? options.tail : DEFAULT_TAIL;
+ const counter = typeof options.tokenCounter === 'function' ? options.tokenCounter : defaultTokenCounter;
+ const budget = options.tokenBudget != null
+ ? options.tokenBudget
+ : (skillContent != null ? counter(skillContent) : 0);
+
+ if (arm === 'none') {
+ return `${problemText}${tail}`;
}
- if (condition === 'trigger') {
+ if (arm === 'equal_budget_placebo') {
+ const padding = buildContextPadding(budget, { tokenCounter: counter, startIndex: options.startIndex });
+ return `Some general notes before the task:\n\n${padding}\n\nNow address this problem:\n\n${problemText}${tail}`;
+ }
+ if (arm === 'trigger') {
return `Consider applying the following thinking approach if relevant. Apply it substantively; do not merely name it.\n\n${triggerSummary(skillContent, skillName)}\n\nNow address this problem:\n\n${problemText}${tail}`;
}
- // 'skill'
+ // skill / full / lean share the treatment wrapper; body is caller-supplied.
return `Use the following thinking-skill guide to structure your reasoning. Apply it substantively; do not merely name it.\n\n=== THINKING SKILL ===\n${skillContent}\n=== END SKILL ===\n\nNow address this problem:\n\n${problemText}${tail}`;
}
/**
- * Build a solve prompt for a given skill CONTENT, padded with neutral filler so
- * the total context reaches `targetWords` — lets us compare two skill versions
- * (e.g. modified vs original, or trigger vs full) head-to-head with EQUAL length,
- * isolating content from length. Used by the paired experiment runner.
+ * Build a solve prompt for given skill CONTENT, padded with inert context-padding
+ * so the total skill block reaches `targetWords` (token budget under counter).
*/
-function buildBalancedSkillPrompt(content, problemText, targetWords) {
- const have = wordCount(content);
- const pad = targetWords > have ? `\n\nAdditional general notes:\n${neutralFiller(targetWords - have)}` : '';
+function buildBalancedSkillPrompt(content, problemText, targetWords, options = {}) {
+ const counter = typeof options.tokenCounter === 'function' ? options.tokenCounter : defaultTokenCounter;
+ const have = counter(content);
+ const need = Math.max(0, (targetWords || 0) - have);
+ const pad = need > 0
+ ? `\n\nAdditional general notes:\n${buildContextPadding(need, { tokenCounter: counter, startIndex: options.startIndex })}`
+ : '';
return `Use the following thinking-skill guide to structure your reasoning. Apply it substantively; do not merely name it.\n\n=== THINKING SKILL ===\n${content}\n=== END SKILL ===${pad}\n\nNow address this problem:\n\n${problemText}\n\nThink carefully and give your best, decision-useful answer.`;
}
/** Stack N skill guides into one prompt (for the stacking experiment). */
-function buildStackPrompt(contents, problemText, targetWords) {
+function buildStackPrompt(contents, problemText, targetWords, options = {}) {
+ const counter = typeof options.tokenCounter === 'function' ? options.tokenCounter : defaultTokenCounter;
const joined = contents.map((c, i) => `=== THINKING SKILL ${i + 1} ===\n${c}`).join('\n\n');
- const have = wordCount(joined);
- const pad = targetWords && targetWords > have ? `\n\nAdditional general notes:\n${neutralFiller(targetWords - have)}` : '';
+ const have = counter(joined);
+ const need = targetWords && targetWords > have ? targetWords - have : 0;
+ const pad = need > 0
+ ? `\n\nAdditional general notes:\n${buildContextPadding(need, { tokenCounter: counter, startIndex: options.startIndex })}`
+ : '';
return `Use the following thinking-skill guides TOGETHER to structure your reasoning. Apply them substantively and in combination; do not merely name them.\n\n${joined}\n=== END SKILLS ===${pad}\n\nNow address this problem:\n\n${problemText}\n\nThink carefully and give your best, decision-useful answer.`;
}
-module.exports = { neutralFiller, triggerSummary, buildConditionPrompt, buildBalancedSkillPrompt, buildStackPrompt, wordCount, FILLER_SENTENCES };
+/** Convenience: production no-skill prompt. */
+function buildNonePrompt(problemText, options = {}) {
+ return buildConditionPrompt('none', problemText, null, null, options);
+}
+
+/** Convenience: equal-budget placebo sized to a reference text or explicit budget. */
+function buildEqualBudgetPlaceboPrompt(problemText, referenceTextOrBudget, options = {}) {
+ const counter = typeof options.tokenCounter === 'function' ? options.tokenCounter : defaultTokenCounter;
+ const budget = typeof referenceTextOrBudget === 'number'
+ ? referenceTextOrBudget
+ : counter(referenceTextOrBudget || '');
+ return buildConditionPrompt('equal_budget_placebo', problemText, null, null, {
+ ...options,
+ tokenBudget: budget,
+ tokenCounter: counter,
+ });
+}
+
+module.exports = {
+ // Primary / new
+ defaultTokenCounter,
+ contextPaddingTokens,
+ buildContextPadding,
+ buildNonePrompt,
+ buildEqualBudgetPlaceboPrompt,
+ normalizeCondition,
+ // Legacy + shared
+ neutralFiller,
+ triggerSummary,
+ buildConditionPrompt,
+ buildBalancedSkillPrompt,
+ buildStackPrompt,
+ wordCount,
+ FILLER_SENTENCES,
+};
diff --git a/evals/lib/droid.js b/evals/lib/droid.js
index 3c508cb..5fd321f 100644
--- a/evals/lib/droid.js
+++ b/evals/lib/droid.js
@@ -10,6 +10,9 @@
* model calls (solvers, judges, adversarial reviewers) through this one
* authenticated CLI.
*
+ * Canonical entry point is `executeDroid(opts)`. Legacy wrappers preserve their
+ * historical shapes and call into the same execution/classification path.
+ *
* `droid exec ... --output-format json` prints a single JSON object whose
* `.result` field holds the model's textual answer plus a `.usage` block.
*/
@@ -18,6 +21,7 @@ const { spawnSync, spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
+const { failureRecord } = require('./result');
// Highest reasoning effort actually supported per model (literal "max" is not
// valid for GPT/Gemini). See plan / `droid` model listing.
@@ -30,6 +34,12 @@ const MAX_EFFORT = {
'claude-haiku-4-5-20251001': 'high',
};
+const COST_MODEL_VERSION = '2025-07-01-estimates';
+const DEFAULT_TIMEOUT_MS = 600000;
+const DEFAULT_EXECUTABLE = 'droid';
+
+const FAILURE_TYPES = Object.freeze(['transport', 'timeout', 'tool_leakage', 'parse']);
+
function maxEffortFor(model) {
return MAX_EFFORT[model] || 'high';
}
@@ -43,137 +53,148 @@ function maxEffortFor(model) {
// cwd (no project AGENTS.md/files), and instruct it to ignore the passive context.
// The residual catalog is identical across all conditions, so it cannot bias a
// skill-vs-placebo delta or a capability slope. Set EVAL_NO_ISOLATE=1 to opt out.
-const ISOLATION_DISABLED_TOOLS = ['Read', 'LS', 'Execute', 'Grep', 'Glob', 'WebSearch', 'TodoWrite', 'FetchUrl', 'Skill', 'Edit', 'Create', 'Task', 'ToolSearch', 'GenerateDroid', 'ProposeMission', 'StartMissionRun', 'DismissHandoffItems', 'EndFeatureRun', 'ExitSpecMode'];
+const ISOLATION_DISABLED_TOOLS = [
+ 'Read', 'LS', 'Execute', 'Grep', 'Glob', 'WebSearch', 'TodoWrite', 'FetchUrl',
+ 'Skill', 'Edit', 'Create', 'Task', 'ToolSearch', 'GenerateDroid', 'ProposeMission',
+ 'StartMissionRun', 'DismissHandoffItems', 'EndFeatureRun', 'ExitSpecMode',
+];
const ISOLATION_PROMPT = 'You are answering a SELF-CONTAINED task. Ignore any "Available skills" list, AGENTS.md, "Agent Guidelines", personal/calendar/email instructions, plugins, custom droids, or external tools in your context — they are irrelevant here. Do not invoke skills or read files. Reason using ONLY the content of this message.';
-const ISOLATE = process.env.EVAL_NO_ISOLATE !== '1';
-function buildArgs(model, effort, promptFile) {
+// Env keys allowed into the isolated child. Provider auth prefixes stay so the
+// real CLI can still authenticate; arbitrary project secrets are not forwarded.
+const ISOLATION_ENV_ALLOWLIST = Object.freeze([
+ 'PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'TEMP', 'TMP',
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM', 'SHELL', 'COLORTERM',
+ 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR',
+ 'SSH_AUTH_SOCK', 'DISPLAY',
+ 'FACTORY_API_KEY', 'FACTORY_CONFIG', 'FACTORY_HOME',
+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL',
+ 'OPENAI_API_KEY', 'OPENAI_BASE_URL',
+ 'GOOGLE_API_KEY', 'GEMINI_API_KEY',
+ 'DEEPSEEK_API_KEY', 'XAI_API_KEY',
+ 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'AWS_REGION', 'AWS_DEFAULT_REGION',
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy',
+ 'NODE_OPTIONS', 'NODE_PATH', 'NODE_ENV',
+ 'EVAL_NO_ISOLATE', 'MAX_DROID_INFLIGHT',
+]);
+
+function isolationEnabled(opts = {}) {
+ if (typeof opts.isolate === 'boolean') return opts.isolate;
+ return process.env.EVAL_NO_ISOLATE !== '1';
+}
+
+function effectiveCwd(opts = {}) {
+ return opts.cwd || os.tmpdir();
+}
+
+function isolationMetadata(opts = {}) {
+ const enabled = isolationEnabled(opts);
+ return {
+ enabled,
+ effective_cwd: effectiveCwd(opts),
+ disabled_tools: enabled ? ISOLATION_DISABLED_TOOLS.slice() : [],
+ env_allowlist: enabled ? ISOLATION_ENV_ALLOWLIST.slice() : null,
+ system_prompt_appended: enabled,
+ };
+}
+
+function buildArgs(model, effort, promptFile, opts = {}) {
const args = ['exec', '-m', model, '-r', effort, '-f', promptFile, '--output-format', 'json'];
- if (ISOLATE) args.push('--disabled-tools', ISOLATION_DISABLED_TOOLS.join(' '), '--append-system-prompt', ISOLATION_PROMPT);
+ if (isolationEnabled(opts)) {
+ args.push('--disabled-tools', ISOLATION_DISABLED_TOOLS.join(' '), '--append-system-prompt', ISOLATION_PROMPT);
+ }
return args;
}
-function spawnOpts(extra) { return { encoding: 'utf8', cwd: os.tmpdir(), ...extra }; } // neutral cwd: no project AGENTS.md/files
+
+function filterEnv(baseEnv, opts = {}) {
+ if (!isolationEnabled(opts)) return { ...baseEnv, ...(opts.env || {}) };
+ const out = {};
+ for (const key of ISOLATION_ENV_ALLOWLIST) {
+ if (baseEnv[key] !== undefined) out[key] = baseEnv[key];
+ }
+ // Keep provider-prefixed keys that may not be enumerated above.
+ for (const key of Object.keys(baseEnv)) {
+ if (/^(FACTORY|ANTHROPIC|OPENAI|GOOGLE|GEMINI|DEEPSEEK|XAI|AWS)_/i.test(key)) {
+ out[key] = baseEnv[key];
+ }
+ }
+ return { ...out, ...(opts.env || {}) };
+}
+
+function spawnOpts(opts = {}, extra = {}) {
+ return {
+ encoding: 'utf8',
+ cwd: effectiveCwd(opts),
+ env: filterEnv(process.env, opts),
+ maxBuffer: 64 * 1024 * 1024,
+ ...extra,
+ };
+}
let tmpCounter = 0;
-function writeTempPrompt(prompt) {
+function writeTempPrompt(prompt, opts = {}) {
// Avoid Date.now()/Math.random() (unavailable in some sandboxes elsewhere;
// harmless here but keep deterministic): use pid + counter.
+ const dir = opts.tempDir || os.tmpdir();
const name = `droid-prompt-${process.pid}-${tmpCounter++}.txt`;
- const p = path.join(os.tmpdir(), name);
+ const p = path.join(dir, name);
fs.writeFileSync(p, prompt, 'utf8');
return p;
}
+function cleanupTempPrompt(promptFile) {
+ if (!promptFile) return;
+ try { fs.unlinkSync(promptFile); } catch (_) { /* ignore */ }
+}
+
/**
- * Run a single droid exec call.
- * @param {object} opts
- * @param {string} opts.model droid model id
- * @param {string} [opts.effort] reasoning effort; defaults to model max
- * @param {string} opts.prompt the prompt text (written to a temp file)
- * @param {number} [opts.timeoutMs] default 600000 (10 min)
- * @returns {{ok:boolean, text:string, usage:object|null, durationMs:number|null, error:string|null, raw:string}}
+ * Structured execution failure. Not thrown for per-item solver failures —
+ * returned on the result object so denominators stay explicit.
*/
-function droidExec(opts) {
- const { model, prompt } = opts;
- const effort = opts.effort || maxEffortFor(model);
- const timeoutMs = opts.timeoutMs || 600000;
- if (!model) throw new Error('droidExec: model required');
- if (!prompt) throw new Error('droidExec: prompt required');
-
- const promptFile = writeTempPrompt(prompt);
- const args = buildArgs(model, effort, promptFile);
-
- let res;
- try {
- res = spawnSync('droid', args, spawnOpts({ timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }));
- } finally {
- try { fs.unlinkSync(promptFile); } catch (_) { /* ignore */ }
+class DroidFailure {
+ constructor({ type, message, details = null, attempt = null }) {
+ if (!FAILURE_TYPES.includes(type)) {
+ throw new TypeError(`unsupported droid failure type: ${type}`);
+ }
+ this.type = type;
+ this.message = String(message || type);
+ this.details = details;
+ this.attempt = attempt;
+ this.name = 'DroidFailure';
}
- const raw = (res.stdout || '') + (res.stderr ? `\n[stderr] ${res.stderr}` : '');
-
- if (res.error) {
- return { ok: false, text: '', usage: null, durationMs: null, error: String(res.error.message || res.error), raw };
- }
- if (res.status !== 0) {
- return { ok: false, text: '', usage: null, durationMs: null, error: `exit ${res.status}`, raw };
+ toRecord(extra = {}) {
+ return failureRecord({
+ type: this.type,
+ message: this.message,
+ attempt: this.attempt,
+ details: this.details,
+ ...extra,
+ });
}
- // droid prints one JSON object on stdout. Find the last line that parses.
- const parsed = parseDroidStdout(res.stdout || '');
- if (!parsed) {
- return { ok: false, text: '', usage: null, durationMs: null, error: 'could not parse droid json', raw };
+ toJSON() {
+ return {
+ type: this.type,
+ message: this.message,
+ details: this.details,
+ attempt: this.attempt,
+ };
}
- return {
- ok: parsed.is_error ? false : true,
- text: typeof parsed.result === 'string' ? parsed.result : JSON.stringify(parsed.result),
- usage: parsed.usage || null,
- durationMs: parsed.duration_ms || null,
- error: parsed.is_error ? (parsed.result || 'is_error') : null,
- raw,
- };
}
-/** Async variant using spawn (non-blocking) for real concurrency. */
-function droidExecAsync(opts) {
- return new Promise((resolve) => {
- const { model, prompt } = opts;
- const effort = opts.effort || maxEffortFor(model);
- const timeoutMs = opts.timeoutMs || 600000;
- if (!model || !prompt) {
- return resolve({ ok: false, text: '', usage: null, durationMs: null, error: 'model and prompt required', raw: '' });
- }
- const promptFile = writeTempPrompt(prompt);
- const args = buildArgs(model, effort, promptFile);
- const child = spawn('droid', args, spawnOpts());
- let stdout = '', stderr = '', done = false;
- const timer = setTimeout(() => { if (!done) { done = true; child.kill('SIGKILL'); finish('timeout'); } }, timeoutMs);
- child.stdout.on('data', d => { stdout += d; });
- child.stderr.on('data', d => { stderr += d; });
- child.on('error', e => finish(String(e.message || e)));
- child.on('close', () => finish(null));
- function finish(errOverride) {
- if (done && errOverride !== 'timeout') return;
- done = true;
- clearTimeout(timer);
- try { fs.unlinkSync(promptFile); } catch (_) { /* ignore */ }
- const raw = stdout + (stderr ? `\n[stderr] ${stderr}` : '');
- if (errOverride) return resolve({ ok: false, text: '', usage: null, durationMs: null, error: errOverride, raw });
- const parsed = parseDroidStdout(stdout);
- if (!parsed) return resolve({ ok: false, text: '', usage: null, durationMs: null, error: 'parse error', raw });
- resolve({
- ok: parsed.is_error ? false : true,
- text: typeof parsed.result === 'string' ? parsed.result : JSON.stringify(parsed.result),
- usage: parsed.usage || null,
- durationMs: parsed.duration_ms || null,
- error: parsed.is_error ? (parsed.result || 'is_error') : null,
- raw,
- });
- }
- });
-}
-
-async function droidJsonAsync(opts) {
- let last = null;
- for (let attempt = 0; attempt < 2; attempt++) {
- const r = await droidExecAsync(opts);
- last = r;
- if (!r.ok) continue;
- const json = extractJson(r.text);
- if (json !== null) return { ok: true, json, usage: r.usage, durationMs: r.durationMs, raw: r.text, error: null };
- }
- return { ok: false, json: null, usage: last && last.usage, durationMs: last && last.durationMs, raw: last && (last.text || last.raw), error: (last && last.error) || 'no json' };
+function makeFailure(type, message, details, attempt) {
+ return new DroidFailure({ type, message, details, attempt });
}
function parseDroidStdout(stdout) {
- const lines = stdout.split('\n').map(l => l.trim()).filter(Boolean);
+ const lines = String(stdout || '').split('\n').map(l => l.trim()).filter(Boolean);
for (let i = lines.length - 1; i >= 0; i--) {
try {
const obj = JSON.parse(lines[i]);
if (obj && typeof obj === 'object' && ('result' in obj || 'type' in obj)) return obj;
} catch (_) { /* keep scanning */ }
}
- // last resort: try the whole thing
try { return JSON.parse(stdout); } catch (_) { return null; }
}
@@ -183,7 +204,6 @@ function parseDroidStdout(stdout) {
*/
function extractJson(text) {
if (!text) return null;
- // strip code fences
const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
const candidates = [];
if (fence) candidates.push(fence[1]);
@@ -191,7 +211,6 @@ function extractJson(text) {
for (const c of candidates) {
const trimmed = c.trim();
try { return JSON.parse(trimmed); } catch (_) { /* try substring */ }
- // find first balanced { } or [ ]
const start = trimmed.search(/[{[]/);
if (start === -1) continue;
const open = trimmed[start];
@@ -216,17 +235,725 @@ function extractJson(text) {
return null;
}
+function detectToolLeakage(_text, parsed, isolation) {
+ if (!isolation || !isolation.enabled || !parsed || typeof parsed !== 'object') return false;
+ // Structured CLI/tool event fields only. Do NOT regex the model answer text —
+ // ordinary answers may legitimately mention tools/functions without invoking them.
+ if (parsed.tool_use || parsed.tool_calls || parsed.function_call || parsed.tool_events) return true;
+ if (Array.isArray(parsed.content) && parsed.content.some(part => (
+ part && (part.type === 'tool_use' || part.type === 'tool_call' || part.type === 'function_call')
+ ))) return true;
+ if (Array.isArray(parsed.events) && parsed.events.some(ev => (
+ ev && (ev.type === 'tool_use' || ev.type === 'tool_call' || ev.tool_use || ev.tool_call)
+ ))) return true;
+ return false;
+}
+
+function emptyUsage() {
+ return null;
+}
+
+function classifyRunnerResult(rawResult, opts = {}, attempt = 1) {
+ const isolation = isolationMetadata(opts);
+ const stdout = rawResult && rawResult.stdout != null ? String(rawResult.stdout) : '';
+ const stderr = rawResult && rawResult.stderr != null ? String(rawResult.stderr) : '';
+ const raw = stdout + (stderr ? `\n[stderr] ${stderr}` : '');
+ const durationMs = rawResult && rawResult.durationMs != null
+ ? rawResult.durationMs
+ : (rawResult && rawResult.duration_ms != null ? rawResult.duration_ms : null);
+ const partialParsed = parseDroidStdout(stdout);
+ const partialUsage = partialParsed && partialParsed.usage ? partialParsed.usage : emptyUsage();
+ const partialDuration = durationMs != null
+ ? durationMs
+ : (partialParsed && partialParsed.duration_ms != null ? partialParsed.duration_ms : null);
+
+ if (rawResult && rawResult.timedOut) {
+ return {
+ ok: false,
+ text: '',
+ json: null,
+ usage: partialUsage,
+ durationMs: partialDuration,
+ failure: makeFailure('timeout', rawResult.error || 'timeout', { signal: rawResult.signal || 'SIGKILL' }, attempt),
+ error: 'timeout',
+ raw,
+ isolation,
+ };
+ }
+
+ if (rawResult && rawResult.error && !rawResult.status && rawResult.status !== 0) {
+ const msg = String(rawResult.error.message || rawResult.error);
+ const isTimeout = /ETIMEDOUT|timeout/i.test(msg);
+ return {
+ ok: false,
+ text: '',
+ json: null,
+ usage: partialUsage,
+ durationMs: partialDuration,
+ failure: makeFailure(isTimeout ? 'timeout' : 'transport', msg, { code: rawResult.error.code || null }, attempt),
+ error: msg,
+ raw,
+ isolation,
+ };
+ }
+
+ if (rawResult && rawResult.status != null && rawResult.status !== 0) {
+ return {
+ ok: false,
+ text: partialParsed && typeof partialParsed.result === 'string' ? partialParsed.result : '',
+ json: null,
+ usage: partialUsage,
+ durationMs: partialDuration,
+ failure: makeFailure('transport', `exit ${rawResult.status}`, { status: rawResult.status, signal: rawResult.signal || null }, attempt),
+ error: `exit ${rawResult.status}`,
+ raw,
+ isolation,
+ };
+ }
+
+ const parsed = parseDroidStdout(stdout);
+ if (!parsed) {
+ return {
+ ok: false,
+ text: '',
+ json: null,
+ usage: emptyUsage(),
+ durationMs,
+ failure: makeFailure('parse', 'could not parse droid json', { stdout_bytes: Buffer.byteLength(stdout) }, attempt),
+ error: 'could not parse droid json',
+ raw,
+ isolation,
+ };
+ }
+
+ const text = typeof parsed.result === 'string' ? parsed.result : JSON.stringify(parsed.result);
+ const json = extractJson(text);
+ if (detectToolLeakage(text, parsed, isolation)) {
+ return {
+ ok: false,
+ text,
+ json,
+ usage: parsed.usage || emptyUsage(),
+ durationMs: durationMs != null ? durationMs : (parsed.duration_ms || null),
+ failure: makeFailure('tool_leakage', 'tool invocation observed under isolation', { disabled_tools: isolation.disabled_tools }, attempt),
+ error: 'tool_leakage',
+ raw,
+ isolation,
+ };
+ }
+
+ if (parsed.is_error) {
+ return {
+ ok: false,
+ text,
+ json,
+ usage: parsed.usage || emptyUsage(),
+ durationMs: durationMs != null ? durationMs : (parsed.duration_ms || null),
+ failure: makeFailure('transport', parsed.result || 'is_error', { is_error: true }, attempt),
+ error: parsed.result || 'is_error',
+ raw,
+ isolation,
+ };
+ }
+
+ return {
+ ok: true,
+ text,
+ json,
+ usage: parsed.usage || emptyUsage(),
+ durationMs: durationMs != null ? durationMs : (parsed.duration_ms || null),
+ failure: null,
+ error: null,
+ raw,
+ isolation,
+ };
+}
+
+function defaultSyncRunner({ command, args, cwd, env, timeoutMs, maxBuffer }) {
+ const started = Date.now();
+ const res = spawnSync(command, args, {
+ encoding: 'utf8',
+ cwd,
+ env,
+ timeout: timeoutMs,
+ maxBuffer: maxBuffer || 64 * 1024 * 1024,
+ });
+ const durationMs = Date.now() - started;
+ if (res.error && res.error.code === 'ETIMEDOUT') {
+ return {
+ status: res.status,
+ stdout: res.stdout || '',
+ stderr: res.stderr || '',
+ error: res.error,
+ timedOut: true,
+ signal: res.signal,
+ durationMs,
+ };
+ }
+ return {
+ status: res.status,
+ stdout: res.stdout || '',
+ stderr: res.stderr || '',
+ error: res.error || null,
+ timedOut: false,
+ signal: res.signal,
+ durationMs,
+ };
+}
+
+function defaultAsyncRunner({ command, args, cwd, env, timeoutMs, maxBuffer }) {
+ return new Promise((resolve) => {
+ const started = Date.now();
+ const child = spawn(command, args, {
+ cwd,
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ let settled = false;
+ let timedOut = false;
+ const max = maxBuffer || 64 * 1024 * 1024;
+
+ const finish = (extra = {}) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({
+ status: extra.status != null ? extra.status : (child.exitCode != null ? child.exitCode : null),
+ stdout,
+ stderr,
+ error: extra.error || null,
+ timedOut: Boolean(extra.timedOut || timedOut),
+ signal: extra.signal != null ? extra.signal : child.signalCode,
+ durationMs: Date.now() - started,
+ });
+ };
+
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { child.kill('SIGKILL'); } catch (_) { /* ignore */ }
+ finish({ timedOut: true, status: null, signal: 'SIGKILL', error: new Error('timeout') });
+ }, timeoutMs);
+
+ child.stdout.on('data', (chunk) => {
+ stdout += chunk;
+ if (stdout.length > max) {
+ try { child.kill('SIGKILL'); } catch (_) { /* ignore */ }
+ finish({ status: null, error: new Error('maxBuffer exceeded'), signal: 'SIGKILL' });
+ }
+ });
+ child.stderr.on('data', (chunk) => {
+ stderr += chunk;
+ });
+ child.on('error', (err) => finish({ error: err, status: null }));
+ child.on('close', (code, signal) => {
+ if (timedOut) return finish({ timedOut: true, status: code, signal: signal || 'SIGKILL', error: new Error('timeout') });
+ finish({ status: code, signal });
+ });
+ });
+}
+
+function missingModelPromptResult(opts, attempt) {
+ const isolation = isolationMetadata(opts);
+ return {
+ ok: false,
+ text: '',
+ json: null,
+ usage: emptyUsage(),
+ durationMs: null,
+ failure: makeFailure('transport', 'model and prompt required', null, attempt),
+ error: 'model and prompt required',
+ raw: '',
+ isolation,
+ };
+}
+
+function thrownRunnerResult(err, opts, attempt) {
+ const isolation = isolationMetadata(opts);
+ return {
+ ok: false,
+ text: '',
+ json: null,
+ usage: emptyUsage(),
+ durationMs: null,
+ failure: makeFailure('transport', String(err && err.message || err), { thrown: true }, attempt),
+ error: String(err && err.message || err),
+ raw: '',
+ isolation,
+ };
+}
+
+/**
+ * Single execution core for both sync and async wrappers.
+ * Always writes/cleans the temp prompt and classifies failures without throwing.
+ * `invokeRunner(ctx)` may return a value or a Promise.
+ */
+function runOnceCore(opts, attempt, invokeRunner) {
+ const model = opts.model;
+ const prompt = opts.prompt;
+ if (!model || !prompt) return missingModelPromptResult(opts, attempt);
+
+ const effort = opts.effort || maxEffortFor(model);
+ const timeoutMs = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
+ const command = opts.executable || opts.command || DEFAULT_EXECUTABLE;
+ const promptFile = writeTempPrompt(prompt, opts);
+ const args = buildArgs(model, effort, promptFile, opts);
+ const isolation = isolationMetadata(opts);
+ const ctx = {
+ command,
+ args,
+ cwd: isolation.effective_cwd,
+ env: filterEnv(process.env, opts),
+ timeoutMs,
+ maxBuffer: opts.maxBuffer || 64 * 1024 * 1024,
+ promptFile,
+ model,
+ effort,
+ attempt,
+ isolation,
+ };
+
+ const finish = (rawResult) => classifyRunnerResult(rawResult, opts, attempt);
+ const fail = (err) => thrownRunnerResult(err, opts, attempt);
+
+ try {
+ const maybe = invokeRunner(ctx);
+ if (maybe && typeof maybe.then === 'function') {
+ return maybe.then(finish, fail).finally(() => cleanupTempPrompt(promptFile));
+ }
+ try {
+ return finish(maybe);
+ } catch (err) {
+ return fail(err);
+ } finally {
+ cleanupTempPrompt(promptFile);
+ }
+ } catch (err) {
+ cleanupTempPrompt(promptFile);
+ return fail(err);
+ }
+}
+
+async function runOnce(opts, attempt) {
+ const runner = opts.runner || defaultAsyncRunner;
+ return runOnceCore(opts, attempt, (ctx) => runner(ctx));
+}
+
+function runOnceSync(opts, attempt) {
+ const runner = opts.syncRunner || opts.runner || defaultSyncRunner;
+ return runOnceCore(opts, attempt, (ctx) => runner(ctx));
+}
+
+function mergeUsage(a, b) {
+ if (!a && !b) return null;
+ const left = a || {};
+ const right = b || {};
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
+ const out = {};
+ for (const key of keys) {
+ const lv = left[key];
+ const rv = right[key];
+ if (typeof lv === 'number' || typeof rv === 'number') {
+ out[key] = Number(lv || 0) + Number(rv || 0);
+ } else if (rv !== undefined) {
+ out[key] = rv;
+ } else {
+ out[key] = lv;
+ }
+ }
+ return out;
+}
+
+function finalizeResult(result, attempts, totals = {}) {
+ const durationMs = totals.durationMs != null
+ ? totals.durationMs
+ : (result.durationMs != null ? result.durationMs : null);
+ const usage = totals.usage !== undefined
+ ? totals.usage
+ : (result.usage || null);
+ return {
+ ok: Boolean(result.ok),
+ text: result.text || '',
+ json: result.json != null ? result.json : null,
+ usage,
+ durationMs,
+ attempts,
+ attempt_records: totals.attemptRecords || undefined,
+ failure: result.failure || null,
+ isolation: result.isolation || isolationMetadata(),
+ error: result.error || (result.failure ? result.failure.message : null),
+ raw: result.raw || '',
+ cost_model_version: COST_MODEL_VERSION,
+ };
+}
+
+function accumulateAttempts(runAttempt, maxAttempts) {
+ let last = null;
+ let totalUsage = null;
+ let totalDurationMs = 0;
+ const attemptRecords = [];
+
+ const record = (attempt, result) => {
+ last = result;
+ totalUsage = mergeUsage(totalUsage, result.usage);
+ if (typeof result.durationMs === 'number') totalDurationMs += result.durationMs;
+ attemptRecords.push({
+ attempt,
+ ok: Boolean(result.ok),
+ usage: result.usage || null,
+ durationMs: result.durationMs != null ? result.durationMs : null,
+ failure: result.failure ? result.failure.toJSON() : null,
+ });
+ return {
+ usage: totalUsage,
+ durationMs: totalDurationMs,
+ attemptRecords,
+ };
+ };
+
+ const shouldStop = (result) => {
+ if (result.ok) return true;
+ if (result.failure && result.failure.type !== 'transport' && result.failure.type !== 'timeout') return true;
+ return false;
+ };
+
+ return { record, shouldStop, getLast: () => last };
+}
+
+/**
+ * Canonical async droid execution path.
+ * Returns structured transport/timeout/tool_leakage/parse failures rather than
+ * throwing for per-item solver failures. Temp prompt files are always cleaned up.
+ * Usage and wall duration accumulate across retries so denominators stay honest.
+ *
+ * @param {object} opts
+ * @param {string} opts.model
+ * @param {string} opts.prompt
+ * @param {string} [opts.effort]
+ * @param {number} [opts.timeoutMs]
+ * @param {number} [opts.attempts=1] total attempts including the first
+ * @param {Function} [opts.runner] dependency-injected async runner for tests
+ * @param {string} [opts.executable] command name/path (default `droid`)
+ * @param {boolean} [opts.isolate] override EVAL_NO_ISOLATE
+ * @param {string} [opts.cwd] override neutral cwd
+ * @returns {Promise<{ok:boolean,text:string,json:*,usage:object|null,durationMs:number|null,attempts:number,failure:DroidFailure|null,isolation:object,error:string|null,raw:string,cost_model_version:string}>}
+ */
+async function executeDroid(opts = {}) {
+ const maxAttempts = Math.max(1, Number(opts.attempts || opts.maxAttempts || 1));
+ const acc = accumulateAttempts();
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const result = await runOnce(opts, attempt);
+ const totals = acc.record(attempt, result);
+ if (acc.shouldStop(result) || attempt === maxAttempts) {
+ return finalizeResult(result, attempt, totals);
+ }
+ }
+ // Unreachable, but keep a defensive return.
+ return finalizeResult(acc.getLast(), maxAttempts, {
+ usage: null,
+ durationMs: 0,
+ attemptRecords: [],
+ });
+}
+
+/**
+ * Sync variant of the same core used by legacy droidExec.
+ * Throws only for programmer-error missing model/prompt (legacy contract).
+ * Runner throws become transport failures.
+ */
+function executeDroidSync(opts = {}) {
+ const maxAttempts = Math.max(1, Number(opts.attempts || opts.maxAttempts || 1));
+ const acc = accumulateAttempts();
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ const result = runOnceSync(opts, attempt);
+ if (result && typeof result.then === 'function') {
+ throw new TypeError('executeDroidSync received an async runner; use executeDroid');
+ }
+ const totals = acc.record(attempt, result);
+ if (acc.shouldStop(result) || attempt === maxAttempts) {
+ return finalizeResult(result, attempt, totals);
+ }
+ }
+ return finalizeResult(acc.getLast(), maxAttempts, {
+ usage: null,
+ durationMs: 0,
+ attemptRecords: [],
+ });
+}
+
+/**
+ * Run a single droid exec call (sync legacy path).
+ * Routes through the same core as executeDroid.
+ */
+function droidExec(opts = {}) {
+ if (!opts.model) throw new Error('droidExec: model required');
+ if (!opts.prompt) throw new Error('droidExec: prompt required');
+ const final = executeDroidSync({ ...opts, attempts: 1 });
+ return {
+ ok: final.ok,
+ text: final.text,
+ usage: final.usage,
+ durationMs: final.durationMs,
+ error: final.error,
+ raw: final.raw,
+ failure: final.failure,
+ isolation: final.isolation,
+ attempts: final.attempts,
+ json: final.json,
+ cost_model_version: final.cost_model_version,
+ };
+}
+
+// --- In-flight call budget (prevents rate-limit/queue explosion from nested concurrency) ---
+const MAX_DROID_INFLIGHT = parseInt(process.env.MAX_DROID_INFLIGHT || '32', 10);
+let _inflight = 0;
+const _waitQueue = [];
+function _acquireSlot() {
+ if (_inflight < MAX_DROID_INFLIGHT) { _inflight++; return Promise.resolve(); }
+ return new Promise(resolve => _waitQueue.push(resolve));
+}
+function _releaseSlot() {
+ _inflight--;
+ if (_waitQueue.length > 0 && _inflight < MAX_DROID_INFLIGHT) {
+ _inflight++;
+ _waitQueue.shift()();
+ }
+}
+
+/** Async variant using spawn (non-blocking) for real concurrency. */
+async function droidExecAsync(opts = {}) {
+ await _acquireSlot();
+ try {
+ const r = await executeDroid({ ...opts, attempts: 1 });
+ return {
+ ok: r.ok,
+ text: r.text,
+ usage: r.usage,
+ durationMs: r.durationMs,
+ error: r.error,
+ raw: r.raw,
+ failure: r.failure,
+ isolation: r.isolation,
+ attempts: r.attempts,
+ json: r.json,
+ cost_model_version: r.cost_model_version,
+ };
+ } finally {
+ _releaseSlot();
+ }
+}
+
+async function droidJsonAsync(opts = {}) {
+ // Two attempts: retry once when JSON cannot be extracted (legacy behavior).
+ let last = null;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const r = await droidExecAsync(opts);
+ last = r;
+ if (!r.ok) continue;
+ const json = r.json != null ? r.json : extractJson(r.text);
+ if (json !== null) {
+ return {
+ ok: true,
+ json,
+ usage: r.usage,
+ durationMs: r.durationMs,
+ raw: r.text,
+ error: null,
+ failure: null,
+ isolation: r.isolation,
+ attempts: attempt + 1,
+ cost_model_version: r.cost_model_version,
+ };
+ }
+ }
+ const parseFailure = makeFailure('parse', (last && last.error) || 'no json', null, 2);
+ return {
+ ok: false,
+ json: null,
+ usage: last && last.usage,
+ durationMs: last && last.durationMs,
+ raw: last && (last.text || last.raw),
+ error: (last && last.error) || 'no json',
+ failure: last && last.failure ? last.failure : parseFailure,
+ isolation: last && last.isolation,
+ attempts: 2,
+ cost_model_version: last && last.cost_model_version || COST_MODEL_VERSION,
+ };
+}
+
/** Run a droid call and parse its result as JSON, with one retry. */
-function droidJson(opts) {
+function droidJson(opts = {}) {
let last = null;
for (let attempt = 0; attempt < 2; attempt++) {
const r = droidExec(opts);
last = r;
if (!r.ok) continue;
- const json = extractJson(r.text);
- if (json !== null) return { ok: true, json, usage: r.usage, durationMs: r.durationMs, raw: r.text, error: null };
+ const json = r.json != null ? r.json : extractJson(r.text);
+ if (json !== null) {
+ return {
+ ok: true,
+ json,
+ usage: r.usage,
+ durationMs: r.durationMs,
+ raw: r.text,
+ error: null,
+ failure: null,
+ isolation: r.isolation,
+ attempts: attempt + 1,
+ cost_model_version: r.cost_model_version,
+ };
+ }
}
- return { ok: false, json: null, usage: last && last.usage, durationMs: last && last.durationMs, raw: last && (last.text || last.raw), error: (last && last.error) || 'no json' };
+ const parseFailure = makeFailure('parse', (last && last.error) || 'no json', null, 2);
+ return {
+ ok: false,
+ json: null,
+ usage: last && last.usage,
+ durationMs: last && last.durationMs,
+ raw: last && (last.text || last.raw),
+ error: (last && last.error) || 'no json',
+ failure: last && last.failure ? last.failure : parseFailure,
+ isolation: last && last.isolation,
+ attempts: 2,
+ cost_model_version: last && last.cost_model_version || COST_MODEL_VERSION,
+ };
+}
+
+/** Run droidExecAsync with bounded retry on transient solver/transport failures. */
+async function droidExecWithRetry(opts = {}, attempts = 3) {
+ const r = await executeDroid({ ...opts, attempts });
+ // Acquire global slot once around the whole retry budget so retries still
+ // count as one logical in-flight call for rate limiting.
+ return {
+ ok: r.ok,
+ text: r.text,
+ usage: r.usage,
+ durationMs: r.durationMs,
+ error: r.error,
+ raw: r.raw,
+ failure: r.failure,
+ isolation: r.isolation,
+ attempts: r.attempts,
+ json: r.json,
+ cost_model_version: r.cost_model_version,
+ };
}
-module.exports = { droidExec, droidJson, droidExecAsync, droidJsonAsync, extractJson, maxEffortFor, MAX_EFFORT };
+// Wrap withRetry in the concurrency gate for live callers.
+const _droidExecWithRetryInner = droidExecWithRetry;
+async function droidExecWithRetryGated(opts = {}, attempts = 3) {
+ await _acquireSlot();
+ try {
+ return await _droidExecWithRetryInner(opts, attempts);
+ } finally {
+ _releaseSlot();
+ }
+}
+
+const COST_PER_MTOKEN = {
+ claude: { input: 3.0, output: 15.0, cache_read: 0.3, cache_creation: 3.75 },
+ gpt: { input: 2.5, output: 10.0, cache_read: 0.5, cache_creation: 2.5 },
+ gemini: { input: 1.25, output: 5.0, cache_read: 0.3, cache_creation: 1.25 },
+ deepseek: { input: 0.27, output: 1.1, cache_read: 0.07, cache_creation: 0.27 },
+ grok: { input: 5.0, output: 15.0, cache_read: 0.5, cache_creation: 5.0 },
+ glm: { input: 0.5, output: 2.0, cache_read: 0.1, cache_creation: 0.5 },
+ unknown: { input: 1.0, output: 5.0, cache_read: 0.2, cache_creation: 1.0 },
+};
+
+function modelFamilyForCost(model) {
+ const m = String(model || '').toLowerCase();
+ if (m.includes('claude') || m.includes('sonnet') || m.includes('opus') || m.includes('haiku')) return 'claude';
+ if (m.includes('gpt') || m.includes('o1') || m.includes('o3') || m.includes('o4')) return 'gpt';
+ if (m.includes('gemini') || m.includes('google')) return 'gemini';
+ if (m.includes('deepseek')) return 'deepseek';
+ if (m.includes('grok')) return 'grok';
+ if (m.includes('glm')) return 'glm';
+ return 'unknown';
+}
+
+/** Normalize droid usage data into a standard token/cost summary. */
+function usageSummary(usage, model) {
+ if (!usage) {
+ return {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_creation_tokens: 0,
+ total_tokens: 0,
+ est_cost_usd: 0,
+ cost_model_version: COST_MODEL_VERSION,
+ };
+ }
+ const fam = modelFamilyForCost(model);
+ const rates = COST_PER_MTOKEN[fam] || COST_PER_MTOKEN.unknown;
+ const input = usage.input_tokens || 0;
+ const output = usage.output_tokens || 0;
+ const cacheRead = usage.cache_read_input_tokens || 0;
+ const cacheCreation = usage.cache_creation_input_tokens || 0;
+ const total = input + output + cacheRead + cacheCreation;
+ const cost = (input * rates.input + output * rates.output + cacheRead * rates.cache_read + cacheCreation * rates.cache_creation) / 1e6;
+ return {
+ input_tokens: input,
+ output_tokens: output,
+ cache_read_tokens: cacheRead,
+ cache_creation_tokens: cacheCreation,
+ total_tokens: total,
+ est_cost_usd: +cost.toFixed(6),
+ cost_model_version: COST_MODEL_VERSION,
+ };
+}
+
+/** Merge an array of usageSummary outputs into aggregate totals. */
+function aggregateUsage(summaries) {
+ return summaries.reduce((acc, s) => ({
+ input_tokens: acc.input_tokens + (s.input_tokens || 0),
+ output_tokens: acc.output_tokens + (s.output_tokens || 0),
+ cache_read_tokens: acc.cache_read_tokens + (s.cache_read_tokens || 0),
+ cache_creation_tokens: acc.cache_creation_tokens + (s.cache_creation_tokens || 0),
+ total_tokens: acc.total_tokens + (s.total_tokens || 0),
+ est_cost_usd: +((acc.est_cost_usd || 0) + (s.est_cost_usd || 0)).toFixed(6),
+ cost_model_version: COST_MODEL_VERSION,
+ cost_rates_assumption: 'per-1M-token list prices; not actual billing',
+ }), {
+ input_tokens: 0,
+ output_tokens: 0,
+ cache_read_tokens: 0,
+ cache_creation_tokens: 0,
+ total_tokens: 0,
+ est_cost_usd: 0,
+ cost_model_version: COST_MODEL_VERSION,
+ cost_rates_assumption: 'per-1M-token list prices; not actual billing',
+ });
+}
+
+module.exports = {
+ // Canonical API
+ executeDroid,
+ DroidFailure,
+ // Legacy exports
+ droidExec,
+ droidJson,
+ droidExecAsync,
+ droidJsonAsync,
+ droidExecWithRetry: droidExecWithRetryGated,
+ extractJson,
+ parseDroidStdout,
+ maxEffortFor,
+ MAX_EFFORT,
+ usageSummary,
+ aggregateUsage,
+ modelFamilyForCost,
+ COST_PER_MTOKEN,
+ COST_MODEL_VERSION,
+ // Isolation surface for tests / runners
+ ISOLATION_DISABLED_TOOLS,
+ ISOLATION_ENV_ALLOWLIST,
+ ISOLATION_PROMPT,
+ isolationMetadata,
+ // Test hooks
+ _acquireSlot,
+ _releaseSlot,
+ _getInflight: () => _inflight,
+ MAX_DROID_INFLIGHT,
+};
diff --git a/evals/lib/evidence.js b/evals/lib/evidence.js
new file mode 100644
index 0000000..06ddab8
--- /dev/null
+++ b/evals/lib/evidence.js
@@ -0,0 +1,726 @@
+'use strict';
+
+/**
+ * Evidence reader for declared study bundles only.
+ * Confirmatory claims require prereg hash, eligible split, exact hashes,
+ * final-rule power, complete health, replication, and archive readback+SHA.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+
+const { loadRegistry, getDeclaredStudyBundle } = require('./registry');
+const { sha256, validateResultEnvelope } = require('./result');
+
+const REPO_ROOT = path.join(__dirname, '..', '..');
+const STUDIES_ROOT = path.join(REPO_ROOT, 'evals', 'studies');
+
+function readJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function fileSha256(filePath) {
+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
+}
+
+function resolveBundleDir(bundle) {
+ if (!bundle) return null;
+ if (bundle.declared_inline || bundle.path == null) return null;
+ return path.isAbsolute(bundle.path) ? bundle.path : path.join(REPO_ROOT, bundle.path);
+}
+
+/**
+ * List only registry-declared study bundles (no recursive results scan).
+ */
+function listDeclaredBundles(registry) {
+ const reg = registry || loadRegistry().registry;
+ return (reg.declared_study_bundles || []).map(b => ({
+ ...b,
+ absolute_path: resolveBundleDir(b),
+ }));
+}
+
+function loadBundleArtifacts(bundleDir) {
+ const manifestPath = path.join(bundleDir, 'manifest.json');
+ const aggregatePath = path.join(bundleDir, 'aggregate.json');
+ const itemsPath = path.join(bundleDir, 'items.jsonl');
+ const out = {
+ dir: bundleDir,
+ manifest: null,
+ aggregate: null,
+ items: [],
+ paths: { manifest: manifestPath, aggregate: aggregatePath, items: itemsPath },
+ missing: [],
+ };
+ if (!fs.existsSync(manifestPath)) out.missing.push('manifest.json');
+ else out.manifest = readJson(manifestPath);
+ if (fs.existsSync(aggregatePath)) out.aggregate = readJson(aggregatePath);
+ else out.missing.push('aggregate.json');
+ if (fs.existsSync(itemsPath)) {
+ out.items = fs.readFileSync(itemsPath, 'utf8')
+ .split('\n')
+ .map(l => l.trim())
+ .filter(Boolean)
+ .map(line => JSON.parse(line));
+ } else {
+ out.missing.push('items.jsonl');
+ }
+ return out;
+}
+
+function extractHealth(artifact) {
+ return artifact?.health || artifact?.run_health || artifact?.aggregate?.health || null;
+}
+function healthComplete(health) {
+ if (!health || typeof health !== 'object') {
+ return { ok: false, reasons: ['missing health'] };
+ }
+ const reasons = [];
+ const fields = ['attempted', 'completed', 'parsed', 'scored', 'failures'];
+ for (const f of fields) {
+ if (!Number.isInteger(health[f]) || health[f] < 0) reasons.push(`health.${f} missing or invalid`);
+ }
+ if (health.decision_eligible !== true) reasons.push('health.decision_eligible is not true');
+ if (Number.isInteger(health.failures) && health.failures > 0) reasons.push(`health.failures=${health.failures}`);
+ if (
+ Number.isInteger(health.attempted) &&
+ Number.isInteger(health.completed) &&
+ Number.isInteger(health.parsed) &&
+ Number.isInteger(health.scored)
+ ) {
+ if (!(health.attempted === health.completed &&
+ health.completed === health.parsed &&
+ health.parsed === health.scored)) {
+ reasons.push(
+ `health denominators not equal attempted=${health.attempted} completed=${health.completed} parsed=${health.parsed} scored=${health.scored}`
+ );
+ }
+ }
+ return { ok: reasons.length === 0, reasons, health };
+}
+function powerConfigPresent(stats, gates) {
+ const power = stats?.power || stats?.power_config || stats?.final_rule_power || null;
+ if (!power || typeof power !== 'object') {
+ return { ok: false, reasons: ['missing final-rule power config'] };
+ }
+ const reasons = [];
+ const target = power.power_target ?? power.target ?? power.power;
+ if (target == null || Number(target) < (gates?.power_target ?? 0.9)) {
+ reasons.push(`power_target ${target} below required ${gates?.power_target ?? 0.9}`);
+ }
+ if (power.decision_eligible === false) reasons.push('power.decision_eligible=false');
+ if (power.powered === true && power.decision_eligible == null && power.multiplicity_adjusted == null) {
+ // legacy "powered means CI excludes null" is insufficient
+ reasons.push('legacy powered flag without final-rule multiplicity/power config');
+ }
+ const hasFinalRule =
+ power.multiplicity_adjusted === true ||
+ power.final_rule === true ||
+ power.familywise === true ||
+ isNonEmptyString(power.disposition_rule) ||
+ isNonEmptyString(power.rule);
+ if (!hasFinalRule) reasons.push('power config does not declare final disposition rule / multiplicity adjustment');
+ return { ok: reasons.length === 0, reasons, power };
+}
+
+function isNonEmptyString(value) {
+ return typeof value === 'string' && value.length > 0;
+}
+
+/**
+ * Verify exact hashes against bytes/config identities when paths are available.
+ * Fails closed on missing or mismatched hashes.
+ *
+ * @param {object} manifest
+ * @param {object|null} envelope
+ * @param {object} [opts]
+ * @param {string|null} [opts.currentPreregSha256]
+ * @param {string} [opts.repoRoot]
+ */
+function verifyExactHashes(manifest, envelope, opts = {}) {
+ const reasons = [];
+ const repoRoot = opts.repoRoot || REPO_ROOT;
+ const currentPreregSha256 = opts.currentPreregSha256 || null;
+
+ const declaredPrereg =
+ envelope?.preregistration_sha256 ||
+ manifest?.preregistration?.sha256 ||
+ manifest?.preregistration_sha256 ||
+ null;
+ const hex64 = /^[a-f0-9]{64}$/i;
+ if (!isNonEmptyString(declaredPrereg)) {
+ reasons.push('missing preregistration_sha256');
+ } else if (!hex64.test(declaredPrereg)) {
+ reasons.push('preregistration_sha256 must be 64-hex');
+ } else {
+ const preregPath = manifest?.preregistration?.path
+ ? (path.isAbsolute(manifest.preregistration.path)
+ ? manifest.preregistration.path
+ : path.join(repoRoot, manifest.preregistration.path))
+ : null;
+ const hasCurrent = isNonEmptyString(currentPreregSha256);
+ const hasPath = isNonEmptyString(preregPath);
+ if (!hasCurrent && !hasPath) {
+ reasons.push('preregistration_sha256 not verifiable (need currentPreregSha256 or readable prereg path)');
+ } else {
+ if (hasCurrent && declaredPrereg !== currentPreregSha256) {
+ reasons.push('preregistration_sha256 does not match current prereg file');
+ }
+ if (hasPath) {
+ if (!fs.existsSync(preregPath)) {
+ reasons.push(`preregistration path not readable: ${manifest.preregistration.path}`);
+ } else {
+ const actual = fileSha256(preregPath);
+ if (actual !== declaredPrereg) {
+ reasons.push('preregistration_sha256 does not match prereg file bytes');
+ }
+ }
+ }
+ }
+ }
+
+ const declaredDatasetSha =
+ envelope?.dataset?.sha256 ||
+ manifest?.dataset?.sha256 ||
+ manifest?.dataset?.sha256_preregistered ||
+ null;
+ if (!isNonEmptyString(declaredDatasetSha)) {
+ reasons.push('missing dataset sha256');
+ } else {
+ const datasetPath =
+ envelope?.dataset?.source ||
+ manifest?.dataset?.path ||
+ manifest?.dataset?.source ||
+ null;
+ if (isNonEmptyString(datasetPath)) {
+ const abs = path.isAbsolute(datasetPath) ? datasetPath : path.join(repoRoot, datasetPath);
+ if (fs.existsSync(abs)) {
+ const actual = fileSha256(abs);
+ if (actual !== declaredDatasetSha) {
+ reasons.push('dataset sha256 does not match dataset file bytes');
+ }
+ } else {
+ reasons.push(`dataset path not readable for hash verify: ${datasetPath}`);
+ }
+ } else {
+ reasons.push('dataset path missing; cannot verify dataset sha256 against bytes');
+ }
+ }
+
+ // Solver: require model + exact config identity (config_sha256 of canonical payload or path+sha)
+ const solver = envelope?.solver || manifest?.solver || null;
+ const solverModel = solver?.model || null;
+ if (!isNonEmptyString(solverModel)) {
+ reasons.push('missing solver.model');
+ } else {
+ const solverConfigSha = solver.config_sha256 || solver.sha256 || null;
+ const solverConfigPath = solver.config_path || solver.path || null;
+ const solverConfig = solver.config || null;
+ if (isNonEmptyString(solverConfigPath) && isNonEmptyString(solverConfigSha)) {
+ const abs = path.isAbsolute(solverConfigPath) ? solverConfigPath : path.join(repoRoot, solverConfigPath);
+ if (!fs.existsSync(abs)) reasons.push(`solver config path not readable: ${solverConfigPath}`);
+ else if (fileSha256(abs) !== solverConfigSha) reasons.push('solver config_sha256 does not match file bytes');
+ } else if (solverConfig && typeof solverConfig === 'object' && isNonEmptyString(solverConfigSha)) {
+ const actual = sha256(solverConfig);
+ if (actual !== solverConfigSha) reasons.push('solver config_sha256 does not match config payload');
+ } else if (isNonEmptyString(solverConfigSha)) {
+ // declared sha without payload/path cannot be verified
+ reasons.push('solver config_sha256 present without config payload or path for byte verify');
+ } else {
+ reasons.push('missing solver config_sha256 (path+sha or config payload required)');
+ }
+ }
+
+ const arms = envelope?.arms || manifest?.arms || [];
+ if (!Array.isArray(arms) || arms.length === 0) {
+ reasons.push('missing arms with prompt/skill hashes');
+ } else {
+ for (const arm of arms) {
+ if (!arm || !isNonEmptyString(arm.id)) {
+ reasons.push('arm missing id');
+ continue;
+ }
+ // prompt: require prompt_sha256 and path or body for recompute
+ if (!isNonEmptyString(arm.prompt_sha256)) {
+ reasons.push(`arm ${arm.id} missing prompt_sha256`);
+ } else if (isNonEmptyString(arm.prompt_path)) {
+ const abs = path.isAbsolute(arm.prompt_path) ? arm.prompt_path : path.join(repoRoot, arm.prompt_path);
+ if (!fs.existsSync(abs)) reasons.push(`arm ${arm.id} prompt_path not readable`);
+ else if (fileSha256(abs) !== arm.prompt_sha256) reasons.push(`arm ${arm.id} prompt_sha256 does not match prompt file bytes`);
+ } else if (typeof arm.prompt === 'string') {
+ const actual = sha256(arm.prompt);
+ if (actual !== arm.prompt_sha256) reasons.push(`arm ${arm.id} prompt_sha256 does not match prompt bytes`);
+ } else {
+ reasons.push(`arm ${arm.id} prompt_sha256 not byte-verifiable (need prompt_path or prompt body)`);
+ }
+
+ // skill: none arm may have null skill; others need skill_sha256 + path/body
+ if (arm.id === 'none') {
+ if (arm.skill_sha256 != null && arm.skill_sha256 !== '' && arm.skill_sha256 !== null) {
+ // allow explicit null only
+ }
+ } else if (!isNonEmptyString(arm.skill_sha256)) {
+ reasons.push(`arm ${arm.id} missing skill_sha256`);
+ } else if (isNonEmptyString(arm.skill_path)) {
+ const abs = path.isAbsolute(arm.skill_path) ? arm.skill_path : path.join(repoRoot, arm.skill_path);
+ if (!fs.existsSync(abs)) reasons.push(`arm ${arm.id} skill_path not readable`);
+ else if (fileSha256(abs) !== arm.skill_sha256) reasons.push(`arm ${arm.id} skill_sha256 does not match skill file bytes`);
+ } else if (typeof arm.skill_body === 'string') {
+ if (sha256(arm.skill_body) !== arm.skill_sha256) reasons.push(`arm ${arm.id} skill_sha256 does not match skill_body`);
+ } else if (manifest?.skill?.path) {
+ const abs = path.isAbsolute(manifest.skill.path) ? manifest.skill.path : path.join(repoRoot, manifest.skill.path);
+ if (!fs.existsSync(abs)) reasons.push(`skill path not readable for arm ${arm.id}`);
+ else if (fileSha256(abs) !== arm.skill_sha256) reasons.push(`arm ${arm.id} skill_sha256 does not match skill path bytes`);
+ } else {
+ reasons.push(`arm ${arm.id} skill_sha256 not byte-verifiable (need skill_path, skill_body, or manifest.skill.path)`);
+ }
+ }
+ }
+
+ // Judges: require non-empty panel with per-judge model + config identity
+ const judges = envelope?.judges || manifest?.judges || null;
+ if (!Array.isArray(judges) || judges.length === 0) {
+ reasons.push('missing judges array with model/config identities');
+ } else {
+ for (let i = 0; i < judges.length; i++) {
+ const j = judges[i];
+ const model = typeof j === 'string' ? j : j?.model;
+ if (!isNonEmptyString(model)) {
+ reasons.push(`judge[${i}] missing model identity`);
+ continue;
+ }
+ if (typeof j === 'string') {
+ reasons.push(`judge[${i}] model-only string lacks config_sha256`);
+ continue;
+ }
+ const jSha = j.config_sha256 || j.sha256 || null;
+ if (!isNonEmptyString(jSha)) {
+ reasons.push(`judge[${i}] missing config_sha256`);
+ } else if (isNonEmptyString(j.config_path)) {
+ const abs = path.isAbsolute(j.config_path) ? j.config_path : path.join(repoRoot, j.config_path);
+ if (!fs.existsSync(abs)) reasons.push(`judge[${i}] config_path not readable`);
+ else if (fileSha256(abs) !== jSha) reasons.push(`judge[${i}] config_sha256 does not match file bytes`);
+ } else if (j.config && typeof j.config === 'object') {
+ if (sha256(j.config) !== jSha) reasons.push(`judge[${i}] config_sha256 does not match config payload`);
+ } else {
+ reasons.push(`judge[${i}] config_sha256 not byte-verifiable`);
+ }
+ }
+ }
+
+ // Aggregate skill/prompt hashes for reporting (first verifiable values)
+ const skillHash = Array.isArray(arms)
+ ? (arms.map(a => a && a.skill_sha256).find(Boolean) || manifest?.skill?.skill_md_sha256_preregistered || null)
+ : null;
+ const promptHash = Array.isArray(arms)
+ ? (arms.map(a => a && a.prompt_sha256).find(Boolean) || null)
+ : null;
+
+ return {
+ ok: reasons.length === 0,
+ reasons,
+ hashes: {
+ preregistration_sha256: declaredPrereg,
+ dataset_sha256: declaredDatasetSha,
+ skill_sha256: skillHash,
+ prompt_sha256: promptHash,
+ solver_model: solverModel,
+ solver_config_sha256: solver?.config_sha256 || solver?.sha256 || null,
+ judges: Array.isArray(judges)
+ ? judges.map(j => (typeof j === 'string' ? { model: j } : { model: j?.model, config_sha256: j?.config_sha256 || j?.sha256 || null }))
+ : [],
+ },
+ };
+}
+
+// Back-compat alias used by tests/callers expecting presence helper name
+function hashFieldsPresent(manifest, envelope, opts = {}) {
+ return verifyExactHashes(manifest, envelope, opts);
+}
+
+function eligibleSplitOk(manifest, envelope, requiredSplit = 'replication') {
+ const split =
+ envelope?.dataset?.split ||
+ manifest?.dataset?.split ||
+ manifest?.split ||
+ null;
+ if (!isNonEmptyString(split)) {
+ return { ok: false, reasons: ['missing dataset split'], split: null };
+ }
+ if (split !== requiredSplit && split !== 'untouched_replication' && split !== 'replication') {
+ return {
+ ok: false,
+ reasons: [`split '${split}' is not eligible for confirmation (need ${requiredSplit})`],
+ split,
+ };
+ }
+ return { ok: true, reasons: [], split };
+}
+
+function replicationOk(manifest, aggregate) {
+ const status =
+ manifest?.replication_status ||
+ aggregate?.replication_status ||
+ manifest?.statistics?.replication_status ||
+ null;
+ if (!isNonEmptyString(status)) {
+ return { ok: false, reasons: ['missing replication_status'] };
+ }
+ const okStatuses = new Set([
+ 'passed',
+ 'success',
+ 'replicated',
+ 'replication_passed',
+ 'confirmed',
+ ]);
+ if (!okStatuses.has(String(status).toLowerCase()) && status !== true) {
+ return { ok: false, reasons: [`replication_status='${status}' is not successful`] };
+ }
+ return { ok: true, reasons: [], status };
+}
+
+/**
+ * Verify per-object archive URI readback and SHA match.
+ * Supports:
+ * - absolute/relative local files
+ * - content-addressed path ending with sha256 hex
+ * - explicit {uri, sha256, bytes} objects
+ */
+function verifyArchiveObject(archiveObj, repoRoot = REPO_ROOT) {
+ if (!archiveObj || typeof archiveObj !== 'object') {
+ return { ok: false, reasons: ['archive object missing'] };
+ }
+ const status = archiveObj.status || archiveObj.raw_responses || null;
+ if (status === 'absent' || archiveObj.uri == null) {
+ return { ok: false, reasons: ['archive uri absent'], status: status || 'absent' };
+ }
+ const uri = archiveObj.uri || archiveObj.path;
+ const expectedSha = archiveObj.sha256 || archiveObj.content_sha256 || null;
+ if (!isNonEmptyString(uri)) return { ok: false, reasons: ['archive uri empty'] };
+ if (!isNonEmptyString(expectedSha)) return { ok: false, reasons: ['archive sha256 missing'] };
+
+ let filePath = uri;
+ if (uri.startsWith('file://')) filePath = uri.slice('file://'.length);
+ if (!path.isAbsolute(filePath)) filePath = path.join(repoRoot, filePath);
+ if (!fs.existsSync(filePath)) {
+ return { ok: false, reasons: [`archive file not readable: ${uri}`], uri, expectedSha };
+ }
+ const actual = fileSha256(filePath);
+ if (actual !== expectedSha) {
+ return {
+ ok: false,
+ reasons: [`archive sha mismatch for ${uri}`],
+ uri,
+ expectedSha,
+ actualSha: actual,
+ };
+ }
+ return { ok: true, reasons: [], uri, expectedSha, actualSha: actual };
+}
+
+function collectArchiveObjects(manifest, aggregate) {
+ const objects = [];
+ const archive = manifest?.archive || {};
+ if (archive.raw_response_objects && Array.isArray(archive.raw_response_objects)) {
+ for (const obj of archive.raw_response_objects) objects.push(obj);
+ }
+ if (archive.objects && Array.isArray(archive.objects)) {
+ for (const obj of archive.objects) objects.push(obj);
+ }
+ // source_artifacts may each declare raw_response_archive
+ for (const src of manifest?.source_artifacts || []) {
+ if (src.raw_response_archive) objects.push({ ...src.raw_response_archive, source_path: src.path });
+ }
+ if (aggregate?.archive_objects && Array.isArray(aggregate.archive_objects)) {
+ for (const obj of aggregate.archive_objects) objects.push(obj);
+ }
+ // single object form
+ if (archive.uri || archive.raw_response_uri) {
+ objects.push({
+ uri: archive.uri || archive.raw_response_uri,
+ sha256: archive.sha256 || archive.raw_response_sha256,
+ status: archive.status || archive.raw_responses,
+ });
+ }
+ return objects;
+}
+
+/**
+ * Evaluate whether a declared study bundle can support a confirmatory claim.
+ */
+function evaluateConfirmationEligibility({
+ studyId,
+ registry = null,
+ requiredSplit = 'replication',
+ envelope = null,
+ currentPreregSha256 = null,
+ preregFile = null,
+} = {}) {
+ const reg = registry || loadRegistry().registry;
+ const blockers = [];
+ const warnings = [];
+
+ let preregSha = currentPreregSha256;
+ if (!preregSha && preregFile && fs.existsSync(preregFile)) {
+ preregSha = fileSha256(preregFile);
+ }
+
+ const declared = getDeclaredStudyBundle(reg, studyId);
+ if (!declared) {
+ return {
+ eligible: false,
+ confirmatory: false,
+ status: 'undeclared_bundle',
+ blockers: [`study_id '${studyId}' is not in registry.declared_study_bundles`],
+ warnings: [],
+ study_id: studyId,
+ };
+ }
+
+ if (declared.confirmatory_eligible_by_default === false) {
+ warnings.push('bundle marked confirmatory_eligible_by_default=false');
+ }
+
+ // Inline declarations (e.g. blocked judge calibration) have no filesystem path.
+ if (declared.declared_inline || declared.path == null) {
+ const blockersInline = [
+ `inline bundle '${studyId}' has no filesystem artifacts`,
+ ];
+ if (declared.status === 'blocked_missing_human_labels' || declared.decision_eligible === false) {
+ blockersInline.push(`status=${declared.status || 'unknown'}; decision_eligible=false`);
+ }
+ if (declared.judged_studies_policy === 'manual_only') {
+ blockersInline.push('judged studies remain manual_only');
+ }
+ return {
+ eligible: false,
+ confirmatory: false,
+ status: declared.status || 'inline_ineligible',
+ blockers: blockersInline,
+ warnings,
+ study_id: studyId,
+ bundle: declared,
+ hashes: {},
+ split: null,
+ health: null,
+ replication_status: null,
+ archive_objects: 0,
+ };
+ }
+
+ const dir = resolveBundleDir(declared);
+ if (!dir || !fs.existsSync(dir)) {
+ blockers.push(`bundle path missing: ${declared.path}`);
+ return {
+ eligible: false,
+ confirmatory: false,
+ status: 'missing_bundle',
+ blockers,
+ warnings,
+ study_id: studyId,
+ bundle: declared,
+ };
+ }
+
+ const artifacts = loadBundleArtifacts(dir);
+ for (const m of artifacts.missing) {
+ if (m === 'manifest.json') blockers.push('missing manifest.json');
+ else warnings.push(`missing optional bundle file: ${m}`);
+ }
+
+ const manifest = artifacts.manifest || {};
+ const aggregate = artifacts.aggregate || {};
+ const env = envelope || aggregate?.result_envelope || manifest?.result_envelope || null;
+
+ if (env) {
+ const envCheck = validateResultEnvelope(env);
+ if (!envCheck.ok) blockers.push(...envCheck.errors.map(e => `envelope: ${e}`));
+ }
+
+ // Judged studies cannot confirm while panel calibration is blocked.
+ const judgesPresent = (
+ (Array.isArray(env?.judges) && env.judges.length > 0) ||
+ (Array.isArray(manifest?.judges) && manifest.judges.length > 0) ||
+ declared.kind === 'pairwise' ||
+ declared.kind === 'judged' ||
+ declared.requires_judges === true ||
+ manifest?.study_type === 'pairwise' ||
+ manifest?.requires_judges === true
+ );
+ const panel = reg.judge_panel || {};
+ if (judgesPresent) {
+ if (panel.decision_eligible === false ||
+ panel.calibration_status === 'blocked_missing_human_labels') {
+ blockers.push(
+ `judge panel calibration blocked (${panel.calibration_status || 'unknown'}); judged studies remain manual_only`
+ );
+ }
+ }
+
+ // 1. exact prereg/dataset/prompt/skill/solver/judge hashes
+ const hashes = verifyExactHashes(manifest, env, {
+ currentPreregSha256: preregSha,
+ repoRoot: REPO_ROOT,
+ });
+ blockers.push(...hashes.reasons);
+
+ // 2. eligible split
+ const split = eligibleSplitOk(manifest, env, requiredSplit);
+ blockers.push(...split.reasons);
+
+ // 3. complete health
+ const health = healthComplete(extractHealth(env) || extractHealth(aggregate) || extractHealth(manifest));
+ blockers.push(...health.reasons);
+
+ // 4. final-rule power
+ const stats = env?.statistics || aggregate?.statistics || manifest?.statistics || aggregate || {};
+ const power = powerConfigPresent(stats, reg.gates);
+ blockers.push(...power.reasons);
+
+ // 5. replication
+ const repl = replicationOk(manifest, aggregate);
+ blockers.push(...repl.reasons);
+
+ // 6. archive readback + SHA for every confirmatory observation/object
+ const archiveObjects = collectArchiveObjects(manifest, aggregate);
+ const itemRows = artifacts.items || [];
+ const envItems = env?.items || [];
+ const expectedItems = itemRows.length > 0 ? itemRows : envItems;
+
+ function observationKey(row, index) {
+ if (!row || typeof row !== 'object') return `index:${index}`;
+ if (row.item_key) return String(row.item_key);
+ if (row.observation_key) return String(row.observation_key);
+ const study = studyId || manifest.study_id || 'study';
+ const itemId = row.item_id || row.id || row.case_id || `idx${index}`;
+ const trial = row.trial != null ? row.trial : 1;
+ const armId = row.arm_id || row.arm || 'unknown';
+ return `${study}:${itemId}:${trial}:${armId}`;
+ }
+
+ const expectedKeys = expectedItems.map((row, i) => observationKey(row, i));
+ const expectedCount =
+ (Number.isInteger(health.health?.scored) && health.health.scored > 0 && health.health.scored) ||
+ (Number.isInteger(manifest?.counts?.scored) && manifest.counts.scored) ||
+ (Number.isInteger(manifest?.counts?.bundled_items) && manifest.counts.bundled_items) ||
+ expectedKeys.length;
+
+ if (archiveObjects.length === 0) {
+ blockers.push('no archive objects declared for readback');
+ } else {
+ const keyToArchives = new Map();
+ const duplicateKeys = new Set();
+ let verifiedCount = 0;
+ for (let i = 0; i < archiveObjects.length; i++) {
+ const obj = archiveObjects[i];
+ const key = obj.item_key || obj.observation_key || obj.object_key ||
+ (obj.item_id != null ? observationKey(obj, i) : null);
+ if (!isNonEmptyString(key)) {
+ blockers.push(`archive object[${i}] missing stable item/observation key`);
+ continue;
+ }
+ if (keyToArchives.has(key)) {
+ duplicateKeys.add(key);
+ blockers.push(`duplicate archive object key '${key}'`);
+ }
+ keyToArchives.set(key, obj);
+ const verified = verifyArchiveObject(obj, REPO_ROOT);
+ if (!verified.ok) blockers.push(...verified.reasons.map(r => `archive[${key}]: ${r}`));
+ else verifiedCount++;
+ }
+
+ if (expectedCount > 0 && keyToArchives.size !== expectedCount) {
+ blockers.push(
+ `archive object count ${keyToArchives.size} != expected confirmatory observations ${expectedCount}`
+ );
+ }
+ if (expectedKeys.length > 0) {
+ for (const key of expectedKeys) {
+ if (!keyToArchives.has(key)) {
+ blockers.push(`missing archive object for observation key '${key}'`);
+ }
+ }
+ }
+ if (verifiedCount === 0) {
+ blockers.push('no archive object passed readback+SHA verification');
+ } else if (expectedCount > 0 && verifiedCount !== expectedCount) {
+ blockers.push(`verified archive objects ${verifiedCount} != expected ${expectedCount}`);
+ }
+ }
+
+ // evidence_validity explicit provisional blocks confirmation
+ const validity = manifest.evidence_validity || aggregate.evidence_validity;
+ if (validity && validity !== 'confirmatory' && validity !== 'confirmed') {
+ blockers.push(`evidence_validity='${validity}' is not confirmatory`);
+ }
+
+ const confirmatory = blockers.length === 0;
+ return {
+ eligible: confirmatory,
+ confirmatory,
+ status: confirmatory ? 'confirmatory' : 'ineligible',
+ blockers,
+ warnings,
+ study_id: studyId,
+ bundle: declared,
+ hashes: hashes.hashes,
+ split: split.split,
+ health: health.health || null,
+ replication_status: repl.status || null,
+ archive_objects: archiveObjects.length,
+ };
+}
+
+/**
+ * Load a declared bundle only. Undeclared paths are rejected.
+ */
+function readDeclaredBundle(studyId, registry = null) {
+ const reg = registry || loadRegistry().registry;
+ const declared = getDeclaredStudyBundle(reg, studyId);
+ if (!declared) {
+ const err = new Error(`undeclared study bundle: ${studyId}`);
+ err.code = 'UNDECLARED_BUNDLE';
+ throw err;
+ }
+ const dir = resolveBundleDir(declared);
+ if (!dir || !fs.existsSync(dir)) {
+ const err = new Error(`bundle path missing for ${studyId}: ${declared.path}`);
+ err.code = 'BUNDLE_MISSING';
+ throw err;
+ }
+ return {
+ declaration: declared,
+ ...loadBundleArtifacts(dir),
+ confirmation: evaluateConfirmationEligibility({ studyId, registry: reg }),
+ };
+}
+
+/**
+ * Replace recursive JSON scanning: claim candidates come only from declared bundles.
+ */
+function listConfirmatoryCandidates(registry = null) {
+ const reg = registry || loadRegistry().registry;
+ return listDeclaredBundles(reg).map(b => evaluateConfirmationEligibility({
+ studyId: b.study_id,
+ registry: reg,
+ }));
+}
+module.exports = {
+ REPO_ROOT,
+ STUDIES_ROOT,
+ listDeclaredBundles,
+ loadBundleArtifacts,
+ evaluateConfirmationEligibility,
+ readDeclaredBundle,
+ listConfirmatoryCandidates,
+ verifyArchiveObject,
+ verifyExactHashes,
+ healthComplete,
+ powerConfigPresent,
+ hashFieldsPresent,
+ eligibleSplitOk,
+ replicationOk,
+ fileSha256,
+ sha256,
+};
diff --git a/evals/lib/io.js b/evals/lib/io.js
index 4aaf191..9b33bfd 100644
--- a/evals/lib/io.js
+++ b/evals/lib/io.js
@@ -2,9 +2,15 @@
const fs = require('fs');
const path = require('path');
+const {
+ checkpointKey,
+ observationCheckpointKey,
+} = require('./result');
const RESULTS_ROOT = path.join(__dirname, '..', 'results');
+let tmpCounter = 0;
+
/** Shared run directory. Set EVAL_RUN to group tiers into one folder. */
function runDir() {
const id = process.env.EVAL_RUN || 'latest';
@@ -17,10 +23,82 @@ function writeJson(file, obj) {
fs.writeFileSync(file, JSON.stringify(obj, null, 2));
}
+/**
+ * Atomic JSON write: write to a same-directory temp file, then rename.
+ * Survives process crash mid-write without leaving a truncated destination.
+ */
+function writeJsonAtomic(file, obj, opts = {}) {
+ const dir = path.dirname(file);
+ fs.mkdirSync(dir, { recursive: true });
+ const tmp = path.join(
+ dir,
+ `.${path.basename(file)}.${process.pid}.${tmpCounter++}.${Date.now()}.tmp`
+ );
+ const body = opts.pretty === false
+ ? JSON.stringify(obj)
+ : JSON.stringify(obj, null, 2);
+ try {
+ fs.writeFileSync(tmp, body);
+ fs.renameSync(tmp, file);
+ } catch (err) {
+ try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
+ throw err;
+ }
+ return file;
+}
+
function readJsonIfExists(file) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return null; }
}
+/**
+ * Persist a study-level checkpoint keyed by the common compatibility key.
+ * File name is `<checkpointKey>.json` under `dir`.
+ */
+function writeStudyCheckpoint(dir, compatibilitySpec, payload = {}) {
+ fs.mkdirSync(dir, { recursive: true });
+ const key = checkpointKey(compatibilitySpec);
+ const file = path.join(dir, `${key}.json`);
+ const body = {
+ ...payload,
+ checkpoint_key: key,
+ written_at: payload.written_at || new Date().toISOString(),
+ };
+ writeJsonAtomic(file, body);
+ return { key, file, body };
+}
+
+/**
+ * Persist a per-observation checkpoint keyed by
+ * observationCheckpointKey({compatibilityKey,itemId,trial,armId}).
+ */
+function writeObservationCheckpoint(dir, observationSpec, payload = {}) {
+ fs.mkdirSync(dir, { recursive: true });
+ const key = observationCheckpointKey(observationSpec);
+ const file = path.join(dir, `${key}.json`);
+ const body = {
+ ...payload,
+ observation_checkpoint_key: key,
+ compatibility_key: observationSpec.compatibilityKey,
+ item_id: observationSpec.itemId,
+ trial: observationSpec.trial,
+ arm_id: observationSpec.armId,
+ written_at: payload.written_at || new Date().toISOString(),
+ };
+ writeJsonAtomic(file, body);
+ return { key, file, body };
+}
+
+function readStudyCheckpoint(dir, compatibilitySpec) {
+ const key = checkpointKey(compatibilitySpec);
+ return readJsonIfExists(path.join(dir, `${key}.json`));
+}
+
+function readObservationCheckpoint(dir, observationSpec) {
+ const key = observationCheckpointKey(observationSpec);
+ return readJsonIfExists(path.join(dir, `${key}.json`));
+}
+
/** Map a thunk over items with a bounded concurrency pool. */
async function mapPool(items, limit, fn) {
const results = new Array(items.length);
@@ -44,4 +122,42 @@ function deferred(fn) {
return () => new Promise((resolve) => { setImmediate(() => resolve(fn())); });
}
-module.exports = { RESULTS_ROOT, runDir, writeJson, readJsonIfExists, mapPool, deferred };
+/** Build explicit warnings[] from run_health when failure noise is material. */
+function runHealthWarnings(runHealth, opts = {}) {
+ const warnings = [];
+ const threshold = opts.failureThreshold || 0.05;
+ if (!runHealth) return warnings;
+ const failures = runHealth.solver_failures || 0;
+ const calls = runHealth.solver_calls || 0;
+ const rate = runHealth.failure_rate || (calls ? failures / calls : 0);
+ if (failures > 0) {
+ warnings.push({
+ severity: rate >= threshold ? 'major' : 'minor',
+ code: 'solver_failure_rate_high',
+ message: `${failures} unresolved solver failure(s) out of ${calls} call(s); artifact is ${rate >= threshold ? 'diagnostic only' : 'usable with caveats'}`,
+ });
+ }
+ if (runHealth.decision_eligible === false) {
+ warnings.push({
+ severity: 'major',
+ code: 'not_decision_eligible',
+ message: 'Solver failures present; artifact should not drive confirmatory claims',
+ });
+ }
+ return warnings;
+}
+
+module.exports = {
+ RESULTS_ROOT,
+ runDir,
+ writeJson,
+ writeJsonAtomic,
+ readJsonIfExists,
+ writeStudyCheckpoint,
+ writeObservationCheckpoint,
+ readStudyCheckpoint,
+ readObservationCheckpoint,
+ mapPool,
+ deferred,
+ runHealthWarnings,
+};
diff --git a/evals/lib/judge.js b/evals/lib/judge.js
index a667da8..23b3850 100644
--- a/evals/lib/judge.js
+++ b/evals/lib/judge.js
@@ -1,35 +1,347 @@
'use strict';
/**
- * Pairwise judging across a panel of models with majority vote — reduces the
- * single-judge variance/bias the adversarial committee flagged. Set JUDGES to a
- * comma list (e.g. "gemini-3.1-pro-preview,gpt-5.5-pro,deepseek-v4-pro").
+ * Pairwise judging across a fixed three-family panel.
+ * Failed votes are missing (never silent ties). Two matching valid A/B/tie votes
+ * decide; otherwise the panel is unresolved failure.
+ *
+ * Production panel is frozen. Fixture injection uses the explicit `judges`
+ * argument to panelJudge / judgesExcludingSolver — env vars do not override.
*/
-const { droidJsonAsync } = require('./droid');
+const { droidJsonAsync, usageSummary } = require('./droid');
+/** Frozen cross-family panel — one vote each. */
+const DEFAULT_PANEL_MODELS = Object.freeze([
+ 'gpt-5.5-pro',
+ 'gemini-3.1-pro-preview',
+ 'deepseek-v4-pro',
+]);
+const FROZEN_PANEL = DEFAULT_PANEL_MODELS;
+
+/**
+ * Approved judge-calibration gates (Phase 1D).
+ * Unmet gate → judged studies ineligible / skills manual-only.
+ */
+const JUDGE_CALIBRATION_THRESHOLDS = Object.freeze({
+ panel_majority_accuracy_min: 0.85,
+ per_judge_accuracy_min: 0.75,
+ fleiss_kappa_min: 0.60,
+ order_effect_delta_max_pp: 5,
+ verbosity_effect_delta_max_pp: 5,
+ missing_vote_rate_max: 0.01,
+ min_calibration_pairs: 30,
+});
+
+/** Always the frozen three-family panel. Override only via explicit judges args. */
function panelModels() {
- return (process.env.JUDGES || process.env.JUDGE_MODEL || 'gemini-3.1-pro-preview')
- .split(',').map(s => s.trim()).filter(Boolean);
+ return [...DEFAULT_PANEL_MODELS];
+}
+
+/**
+ * Normalize a parsed judge winner. Only A/B/tie are valid labels.
+ * Null/undefined/empty → null (missing), not 'tie'.
+ * Pass { missingAsTie: true } only for legacy adapters that need the old behavior.
+ */
+function normalizeJudgeWinner(winner, { missingAsTie = false } = {}) {
+ if (winner == null || winner === '') {
+ return missingAsTie ? 'tie' : null;
+ }
+ const value = String(winner).trim().toUpperCase();
+ if (value === 'A' || value === 'B') return value;
+ if (value === 'TIE' || value === 'DRAW') return 'tie';
+ return missingAsTie ? 'tie' : null;
+}
+
+/**
+ * Tally votes. Failed/missing winners stay in `missing` — never counted as ties.
+ * Valid explicit `tie` votes still count under `tie`.
+ * @returns {{A:number,B:number,tie:number,missing:number}}
+ */
+function tallyJudgeVotes(votes) {
+ const tally = { A: 0, B: 0, tie: 0, missing: 0 };
+ for (const v of votes) {
+ if (!v || v.valid === false) {
+ tally.missing++;
+ continue;
+ }
+ if (v.winner == null || v.winner === '') {
+ tally.missing++;
+ continue;
+ }
+ const w = normalizeJudgeWinner(v.winner);
+ if (w == null) tally.missing++;
+ else tally[w]++;
+ }
+ return tally;
+}
+
+/**
+ * Panel decision from tallied valid votes.
+ * Two matching valid A, B, or explicit tie votes decide.
+ * Missing votes never create a silent tie; <2 matching valid votes → unresolved.
+ */
+function decidePanelWinner(tally) {
+ if (tally.A >= 2 && tally.A > tally.B && tally.A > tally.tie) {
+ return { winner: 'A', resolved: true, unresolved: false, failure: null };
+ }
+ if (tally.B >= 2 && tally.B > tally.A && tally.B > tally.tie) {
+ return { winner: 'B', resolved: true, unresolved: false, failure: null };
+ }
+ if (tally.tie >= 2 && tally.tie > tally.A && tally.tie > tally.B) {
+ return { winner: 'tie', resolved: true, unresolved: false, failure: null };
+ }
+ return {
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ failure: {
+ type: 'judge_unresolved',
+ message: 'Fewer than two matching valid votes (failed votes are missing, not ties)',
+ },
+ };
}
/**
- * @returns {{winner:'A'|'B'|'tie', votes:Array, vocab_only:boolean, whys:string[]}}
- * `winner` is the panel majority; ties (or no majority) → 'tie'.
+ * Run the panel. Vote transport/parse failures are recorded as missing votes.
+ * @param {string} judgePromptFor
+ * @param {string[]} [judges] explicit panel (fixtures); defaults to frozen panel
+ * @returns {Promise<{winner:'A'|'B'|'tie'|null, resolved:boolean, unresolved:boolean, failure:object|null, tally:object, votes:Array, failures:Array}>}
*/
async function panelJudge(judgePromptFor, judges = panelModels()) {
- const votes = await Promise.all(judges.map(async model => {
- const r = await droidJsonAsync({ model, prompt: judgePromptFor });
- if (!r.ok || !r.json) return { model, winner: null };
- return { model, winner: (r.json.winner || 'tie').toUpperCase(), margin: r.json.margin, why: r.json.why, vocab_only: !!r.json.skill_vocab_without_substance };
+ const panel = judges || [];
+ const votes = await Promise.all(panel.map(async model => {
+ try {
+ const r = await droidJsonAsync({ model, prompt: judgePromptFor });
+ if (!r.ok || !r.json) {
+ return {
+ model,
+ winner: null,
+ valid: false,
+ failure: {
+ type: r && r.error && /timeout/i.test(String(r.error)) ? 'timeout' : 'parse',
+ message: (r && r.error) || 'judge response missing or unparseable',
+ },
+ usage: r && r.usage || null,
+ durationMs: r && r.durationMs || null,
+ };
+ }
+ const winner = normalizeJudgeWinner(r.json.winner);
+ if (winner == null) {
+ return {
+ model,
+ winner: null,
+ valid: false,
+ failure: { type: 'parse', message: `invalid winner label: ${r.json.winner}` },
+ margin: r.json.margin,
+ why: r.json.why,
+ vocab_only: !!r.json.skill_vocab_without_substance,
+ usage: r.usage || null,
+ durationMs: r.durationMs || null,
+ };
+ }
+ return {
+ model,
+ winner,
+ valid: true,
+ failure: null,
+ margin: r.json.margin,
+ why: r.json.why,
+ vocab_only: !!r.json.skill_vocab_without_substance,
+ usage: r.usage || null,
+ durationMs: r.durationMs || null,
+ };
+ } catch (err) {
+ return {
+ model,
+ winner: null,
+ valid: false,
+ failure: { type: 'transport', message: String(err && err.message || err) },
+ usage: null,
+ durationMs: null,
+ };
+ }
}));
- const tally = { A: 0, B: 0, tie: 0 };
- for (const v of votes) if (v.winner && tally[v.winner] !== undefined) tally[v.winner]++;
- let winner = 'tie';
- if (tally.A > tally.B && tally.A > tally.tie) winner = 'A';
- else if (tally.B > tally.A && tally.B > tally.tie) winner = 'B';
- const vocabVotes = votes.filter(v => v.vocab_only).length;
- return { winner, tally, votes, vocab_only: vocabVotes > votes.length / 2, whys: votes.map(v => v.why).filter(Boolean) };
+
+ const tally = tallyJudgeVotes(votes);
+ const decision = decidePanelWinner(tally);
+ const failures = votes
+ .filter(v => v.failure)
+ .map(v => ({ model: v.model, ...v.failure }));
+ const vocabVotes = votes.filter(v => v.valid && v.vocab_only).length;
+ const validCount = votes.filter(v => v.valid).length;
+ const judge_usage = votes.map(v => (v.usage ? usageSummary(v.usage, v.model) : null)).filter(Boolean);
+ const judge_durationMs = votes.reduce((a, v) => a + (v.durationMs || 0), 0);
+
+ let failure = decision.failure;
+ if (!failure && panel.length < 2) {
+ failure = { type: 'judge_unresolved', message: 'panel has fewer than 2 judges' };
+ }
+
+ return {
+ winner: decision.winner,
+ resolved: decision.resolved && !failure,
+ unresolved: !!(decision.unresolved || failure),
+ failure,
+ tally,
+ votes,
+ failures,
+ valid_votes: validCount,
+ vocab_only: validCount > 0 && vocabVotes > validCount / 2,
+ whys: votes.map(v => v.why).filter(Boolean),
+ judge_usage,
+ judge_durationMs,
+ };
+}
+
+/**
+ * Families: claude, gpt, gemini, deepseek, grok, glm
+ */
+function modelFamily(model) {
+ const m = String(model || '').toLowerCase();
+ if (m.includes('claude') || m.includes('sonnet') || m.includes('opus') || m.includes('haiku')) return 'claude';
+ if (m.includes('gpt') || m.includes('o1') || m.includes('o3') || m.includes('o4')) return 'gpt';
+ if (m.includes('gemini') || m.includes('google')) return 'gemini';
+ if (m.includes('deepseek')) return 'deepseek';
+ if (m.includes('grok')) return 'grok';
+ if (m.includes('glm')) return 'glm';
+ return 'unknown';
+}
+
+/**
+ * Judges excluding the solver's model family.
+ * Strict: never falls back to same-family judges.
+ * Returns [] unless ≥2 distinct non-unknown independent families remain.
+ */
+function judgesExcludingSolver(solverModel, allJudges = panelModels()) {
+ const solverFamily = modelFamily(solverModel);
+ const filtered = (allJudges || []).filter(j => modelFamily(j) !== solverFamily);
+ const families = new Set(
+ filtered
+ .map(j => modelFamily(j))
+ .filter(f => f && f !== 'unknown')
+ );
+ if (families.size < 2) return [];
+ return filtered;
+}
+
+/**
+ * Evaluate calibration metrics against frozen thresholds.
+ * Requires n_pairs >= min and one valid accuracy per frozen panel model.
+ */
+function evaluateJudgeCalibration(metrics = {}) {
+ const t = JUDGE_CALIBRATION_THRESHOLDS;
+ const failures = [];
+ const requiredPanel = [...DEFAULT_PANEL_MODELS];
+
+ const nPairs = metrics.n_pairs;
+ if (!(nPairs >= t.min_calibration_pairs)) {
+ failures.push({
+ gate: 'min_calibration_pairs',
+ required: t.min_calibration_pairs,
+ observed: nPairs == null ? null : nPairs,
+ message: nPairs == null ? 'n_pairs missing' : 'n_pairs below minimum',
+ });
+ }
+
+ const panelAcc = metrics.panel_majority_accuracy;
+ if (!(panelAcc >= t.panel_majority_accuracy_min)) {
+ failures.push({
+ gate: 'panel_majority_accuracy',
+ required: t.panel_majority_accuracy_min,
+ observed: panelAcc,
+ });
+ }
+
+ let perJudgeMap = null;
+ const rawPer = metrics.per_judge_accuracy;
+ if (rawPer && !Array.isArray(rawPer) && typeof rawPer === 'object') {
+ perJudgeMap = rawPer;
+ } else if (Array.isArray(rawPer)) {
+ perJudgeMap = {};
+ requiredPanel.forEach((model, i) => {
+ if (i < rawPer.length) perJudgeMap[model] = rawPer[i];
+ });
+ }
+
+ if (!perJudgeMap) {
+ failures.push({
+ gate: 'per_judge_accuracy',
+ required: t.per_judge_accuracy_min,
+ observed: null,
+ message: 'per_judge_accuracy missing; need one score per frozen panel model',
+ });
+ } else {
+ for (const model of requiredPanel) {
+ const fam = modelFamily(model);
+ const acc = perJudgeMap[model] != null ? perJudgeMap[model]
+ : (perJudgeMap[fam] != null ? perJudgeMap[fam] : undefined);
+ if (!(acc >= t.per_judge_accuracy_min)) {
+ failures.push({
+ gate: 'per_judge_accuracy',
+ judge: model,
+ required: t.per_judge_accuracy_min,
+ observed: acc == null ? null : acc,
+ message: acc == null ? `missing accuracy for ${model}` : `accuracy below threshold for ${model}`,
+ });
+ }
+ }
+ }
+
+ if (!(metrics.fleiss_kappa >= t.fleiss_kappa_min)) {
+ failures.push({
+ gate: 'fleiss_kappa',
+ required: t.fleiss_kappa_min,
+ observed: metrics.fleiss_kappa,
+ });
+ }
+
+ const orderAbs = Math.abs(metrics.order_effect_delta_pp == null ? Infinity : metrics.order_effect_delta_pp);
+ if (!(orderAbs <= t.order_effect_delta_max_pp)) {
+ failures.push({
+ gate: 'order_effect_delta_pp',
+ required_abs_max: t.order_effect_delta_max_pp,
+ observed: metrics.order_effect_delta_pp,
+ });
+ }
+
+ const verbAbs = Math.abs(metrics.verbosity_effect_delta_pp == null ? Infinity : metrics.verbosity_effect_delta_pp);
+ if (!(verbAbs <= t.verbosity_effect_delta_max_pp)) {
+ failures.push({
+ gate: 'verbosity_effect_delta_pp',
+ required_abs_max: t.verbosity_effect_delta_max_pp,
+ observed: metrics.verbosity_effect_delta_pp,
+ });
+ }
+
+ if (!(metrics.missing_vote_rate <= t.missing_vote_rate_max)) {
+ failures.push({
+ gate: 'missing_vote_rate',
+ required_max: t.missing_vote_rate_max,
+ observed: metrics.missing_vote_rate,
+ });
+ }
+
+ return {
+ ok: failures.length === 0,
+ eligible: failures.length === 0,
+ thresholds: { ...t },
+ required_panel: requiredPanel,
+ failures,
+ metrics,
+ };
}
-module.exports = { panelModels, panelJudge };
+module.exports = {
+ DEFAULT_PANEL_MODELS,
+ FROZEN_PANEL,
+ JUDGE_CALIBRATION_THRESHOLDS,
+ panelModels,
+ panelJudge,
+ normalizeJudgeWinner,
+ tallyJudgeVotes,
+ decidePanelWinner,
+ modelFamily,
+ judgesExcludingSolver,
+ evaluateJudgeCalibration,
+};
diff --git a/evals/lib/objective.js b/evals/lib/objective.js
new file mode 100644
index 0000000..7288311
--- /dev/null
+++ b/evals/lib/objective.js
@@ -0,0 +1,841 @@
+'use strict';
+
+const {
+ sha256,
+ itemKey,
+ checkpointKey,
+ observationCheckpointKey,
+ failureRecord,
+ createResultEnvelope,
+ defaultUsage,
+} = require('./result');
+const { buildConditionPrompt, normalizeCondition, defaultTokenCounter } = require('./conditions');
+
+function okScore({ parsed, value, correct }) {
+ return {
+ parsed,
+ scored: true,
+ value: value !== undefined ? value : parsed,
+ correct: Boolean(correct),
+ failure: null,
+ };
+}
+
+function failScore({ type = 'parse', message, parsed = null, value = null, details = null }) {
+ return {
+ parsed,
+ scored: false,
+ value,
+ correct: false,
+ failure: failureRecord({ type, message, details }),
+ };
+}
+
+function lastAnswerMatch(text, pattern) {
+ if (text == null) return null;
+ const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);
+ let m;
+ let last = null;
+ while ((m = re.exec(String(text))) !== null) last = m;
+ return last;
+}
+
+/** Boolean / yes-no gold. Accepts boolean gold or yes/no/true/false strings. */
+function scoreBoolean(text, gold, options = {}) {
+ const m = lastAnswerMatch(text, /ANSWER:\s*(yes|no|true|false)\b/i)
+ || String(text || '').match(/\b(yes|no|true|false)\b\s*\.?\s*$/i);
+ if (!m) return failScore({ type: 'parse', message: 'no boolean ANSWER found' });
+ const token = m[1].toLowerCase();
+ const parsed = token === 'yes' || token === 'true';
+ let expected;
+ if (typeof gold === 'boolean') expected = gold;
+ else if (gold == null) return failScore({ type: 'scoring', message: 'missing boolean gold', parsed, value: parsed });
+ else {
+ const g = String(gold).trim().toLowerCase();
+ if (g === 'yes' || g === 'true' || g === '1') expected = true;
+ else if (g === 'no' || g === 'false' || g === '0') expected = false;
+ else return failScore({ type: 'scoring', message: `unrecognized boolean gold: ${gold}`, parsed, value: parsed });
+ }
+ return okScore({ parsed, value: parsed, correct: parsed === expected });
+}
+
+/** Multiple choice letter A-E (or custom letters). */
+function scoreMultipleChoice(text, gold, options = {}) {
+ const letters = options.letters || 'ABCDE';
+ const classRe = new RegExp(`ANSWER:\\s*([${letters}])\\b`, 'i');
+ const m = lastAnswerMatch(text, classRe)
+ || String(text || '').match(new RegExp(`\\b([${letters}])\\b\\s*\\.?\\s*$`, 'i'));
+ if (!m) return failScore({ type: 'parse', message: 'no multiple-choice ANSWER found' });
+ const parsed = m[1].toUpperCase();
+ if (gold == null || gold === '') {
+ return failScore({ type: 'scoring', message: 'missing multiple-choice gold', parsed, value: parsed });
+ }
+ const expected = String(gold).trim().toUpperCase();
+ if (!new RegExp(`^[${letters}]$`, 'i').test(expected)) {
+ return failScore({ type: 'scoring', message: `gold letter out of range: ${gold}`, parsed, value: parsed });
+ }
+ return okScore({ parsed, value: parsed, correct: parsed === expected });
+}
+
+/**
+ * Abstention scorer. Gold is { answerable: bool } or boolean answerable.
+ * Correct when abstain on unanswerable and answer on answerable.
+ */
+function scoreAbstention(text, gold, options = {}) {
+ if (text == null || String(text).trim() === '') {
+ return failScore({ type: 'parse', message: 'empty response for abstention scoring' });
+ }
+ const answerable = typeof gold === 'boolean' ? gold
+ : (gold && typeof gold === 'object' ? Boolean(gold.answerable) : null);
+ if (answerable == null) {
+ return failScore({ type: 'scoring', message: 'missing answerable gold' });
+ }
+
+ const m = String(text).match(/ANSWER:\s*([\s\S]+)$/i);
+ const tail = (m ? m[1] : text).trim();
+ let abstained = false;
+ if (/^unanswerable\b/i.test(tail)) abstained = true;
+ else if (/\bunanswerable\b/i.test(tail) && tail.length < 60) abstained = true;
+ else if (/\b(cannot|can'?t|impossible to|no one can|not knowable|unknowable|no way to know)\b/i.test(tail) && tail.length < 80) {
+ abstained = true;
+ }
+
+ const correct = answerable ? !abstained : abstained;
+ return okScore({
+ parsed: abstained ? 'UNANSWERABLE' : 'ANSWERED',
+ value: { abstained, answerable },
+ correct,
+ });
+}
+
+function parseScientificNumber(raw) {
+ if (raw == null) return null;
+ let s = String(raw).replace(/,/g, '').replace(/\s/g, '').replace(/[×x]10\^?/, 'e');
+ const n = parseFloat(s);
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Numeric order-of-magnitude: |log10(|est|/|gold|)| <= tolerance (default 1). */
+function scoreNumericOrderOfMagnitude(text, gold, options = {}) {
+ const tolerance = options.tolerance != null ? Number(options.tolerance) : 1;
+ const m = lastAnswerMatch(text, /ANSWER:\s*\$?\s*(-?[\d,]*\.?\d+(?:\s*[eE]\s*[-+]?\d+)?(?:\s*[×x]\s*10\^?-?\d+)?)/);
+ let est = m ? parseScientificNumber(m[1]) : null;
+ if (est == null) {
+ const all = String(text || '').match(/-?\d[\d,]*\.?\d*(?:[eE][-+]?\d+)?/g);
+ est = all ? parseScientificNumber(all[all.length - 1]) : null;
+ }
+ if (est == null || !Number.isFinite(est) || est === 0) {
+ return failScore({ type: 'parse', message: 'no finite non-zero numeric ANSWER found', parsed: est });
+ }
+ const expected = typeof gold === 'number' ? gold
+ : (gold && typeof gold === 'object' && gold.answer_num != null ? Number(gold.answer_num)
+ : Number(gold));
+ if (!Number.isFinite(expected) || expected === 0) {
+ return failScore({ type: 'scoring', message: 'invalid numeric gold', parsed: est, value: est });
+ }
+ const delta = Math.abs(Math.log10(Math.abs(est) / Math.abs(expected)));
+ return okScore({ parsed: est, value: { estimate: est, gold: expected, log10_delta: delta }, correct: delta <= tolerance });
+}
+
+/**
+ * Probability Brier score. Gold is 0/1 outcome (or {answer_bin}).
+ * value holds probability + brier; correct uses threshold 0.5 vs outcome.
+ */
+function scoreProbabilityBrier(text, gold, options = {}) {
+ const m = lastAnswerMatch(text, /ANSWER:\s*(-?\d+(?:\.\d+)?)\s*%?/i);
+ if (!m) return failScore({ type: 'parse', message: 'no probability ANSWER found' });
+ let p = parseFloat(m[1]);
+ if (/%/.test(m[0]) || Math.abs(p) > 1) p = p / 100;
+ // Clamp to [0,1]
+ p = Math.max(0, Math.min(1, p));
+ if (!Number.isFinite(p)) return failScore({ type: 'parse', message: 'non-finite probability', parsed: p });
+
+ let outcome;
+ if (typeof gold === 'number') outcome = gold;
+ else if (typeof gold === 'boolean') outcome = gold ? 1 : 0;
+ else if (gold && typeof gold === 'object' && gold.answer_bin != null) outcome = Number(gold.answer_bin);
+ else outcome = Number(gold);
+ if (!(outcome === 0 || outcome === 1)) {
+ return failScore({ type: 'scoring', message: 'probability gold must be 0 or 1', parsed: p, value: p });
+ }
+ const brier = Math.pow(p - outcome, 2);
+ const correct = (p > 0.5 ? 1 : 0) === outcome;
+ return okScore({
+ parsed: p,
+ value: { probability: p, outcome, brier },
+ correct,
+ });
+}
+
+function normalizeRepoPath(p) {
+ if (p == null) return null;
+ let s = String(p).trim().replace(/\\/g, '/');
+ s = s.replace(/^[`'"]+|[`'"]+$/g, '');
+ return s;
+}
+
+/** Reject absolute, drive, UNC, and parent-escape paths before inventory matching. */
+function forbiddenRepoPathReason(raw) {
+ if (raw == null) return 'empty path';
+ const original = String(raw).trim();
+ if (!original) return 'empty path';
+ // Drive / UNC checks on the original (before slash normalization alone would hide them).
+ if (/^[a-zA-Z]:/.test(original)) return 'drive path not allowed';
+ if (original.startsWith('\\\\') || original.startsWith('//')) return 'UNC path not allowed';
+ const s = original.replace(/\\/g, '/');
+ if (s.startsWith('/')) return 'absolute path not allowed';
+ // Normalize only relative form for segment checks; never strip a leading slash to salvage.
+ const rel = s.replace(/^\.\//, '').replace(/\/{2,}/g, '/');
+ const segments = rel.split('/').filter((part) => part && part !== '.');
+ if (segments.some((part) => part === '..')) return 'parent segment not allowed';
+ return null;
+}
+
+function toRepoRelativePath(raw) {
+ const reason = forbiddenRepoPathReason(raw);
+ if (reason) return { ok: false, path: null, reason };
+ let s = String(raw).trim().replace(/\\/g, '/');
+ s = s.replace(/^[`'"]+|[`'"]+$/g, '');
+ s = s.replace(/^\.\//, '').replace(/\/{2,}/g, '/');
+ if (!s || s.endsWith('/')) return { ok: false, path: s || null, reason: 'empty or directory path' };
+ return { ok: true, path: s, reason: null };
+}
+
+/**
+ * Strict file localization parse:
+ * - exactly one terminal ANSWER: <repo-relative-path> line
+ * - only whitespace may follow that line
+ * - normalize separators and ./ only for relative paths
+ * - reject absolute/drive/UNC/.. paths before inventory matching
+ * - reject directories, multi-token paths, paths outside inventory
+ */
+function parseFileLocalization(text, options = {}) {
+ const inventory = options.repositoryFiles || options.fileInventory || options.inventory || null;
+ const raw = String(text == null ? '' : text);
+
+ // Collect every ANSWER line. Exactly one is required — duplicates fail even if identical.
+ const answerLineRe = /^\s*ANSWER:\s*(.+?)\s*$/gim;
+ const answers = [];
+ let m;
+ while ((m = answerLineRe.exec(raw)) !== null) {
+ answers.push(m[1].trim());
+ }
+ if (answers.length === 0) {
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({ type: 'parse', message: 'no terminal ANSWER: path line found' }),
+ };
+ }
+ if (answers.length !== 1) {
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({
+ type: 'parse',
+ message: 'multiple ANSWER lines (exactly one terminal ANSWER required)',
+ details: { answers },
+ }),
+ };
+ }
+
+ // Terminal: after stripping trailing whitespace, the sole ANSWER line must end the text.
+ // Any non-whitespace after the ANSWER line is a parse failure.
+ const stripped = raw.replace(/\s+$/u, '');
+ const terminalRe = /(?:^|\n)\s*ANSWER:\s*(\S+)\s*$/i;
+ const terminal = stripped.match(terminalRe);
+ if (!terminal) {
+ // Distinguish trailing prose after a path vs multi-token path on the ANSWER line.
+ const looseTerminal = stripped.match(/(?:^|\n)\s*ANSWER:\s*(.+)$/i);
+ if (!looseTerminal) {
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({
+ type: 'parse',
+ message: 'ANSWER line is not terminal (non-whitespace content follows)',
+ }),
+ };
+ }
+ const loose = looseTerminal[1].trim();
+ if (/\s/.test(loose)) {
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({
+ type: 'parse',
+ message: 'ANSWER path must be a single terminal path token without trailing text',
+ details: { raw: loose },
+ }),
+ };
+ }
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({
+ type: 'parse',
+ message: 'ANSWER line is not terminal (non-whitespace content follows)',
+ }),
+ };
+ }
+
+ const rawPath = terminal[1].trim();
+ const converted = toRepoRelativePath(rawPath);
+ if (!converted.ok) {
+ return {
+ ok: false,
+ parsed: null,
+ failure: failureRecord({
+ type: 'parse',
+ message: converted.reason || 'invalid ANSWER path',
+ details: { raw: rawPath },
+ }),
+ };
+ }
+ const parsed = converted.path;
+
+ if (inventory && Array.isArray(inventory)) {
+ const inv = new Set();
+ for (const entry of inventory) {
+ const c = toRepoRelativePath(entry);
+ if (c.ok) inv.add(c.path);
+ }
+ if (!inv.has(parsed)) {
+ return {
+ ok: false,
+ parsed,
+ failure: failureRecord({
+ type: 'parse',
+ message: 'ANSWER path outside repository file inventory',
+ details: { path: parsed },
+ }),
+ };
+ }
+ } else if (!parsed.includes('/') && options.requireNestedPath) {
+ return {
+ ok: false,
+ parsed,
+ failure: failureRecord({ type: 'parse', message: 'basename-only ANSWER rejected without inventory match' }),
+ };
+ }
+
+ return { ok: true, parsed, failure: null };
+}
+
+function scoreFileLocalization(text, gold, options = {}) {
+ const parsedResult = parseFileLocalization(text, options);
+ if (!parsedResult.ok) {
+ return {
+ parsed: parsedResult.parsed,
+ scored: false,
+ value: parsedResult.parsed,
+ correct: false,
+ failure: parsedResult.failure,
+ };
+ }
+ const parsed = parsedResult.parsed;
+ let goldPaths = [];
+ if (Array.isArray(gold)) goldPaths = gold;
+ else if (gold && typeof gold === 'object') {
+ goldPaths = gold.gold_files || gold.files || gold.paths || [];
+ if (!goldPaths.length && gold.path) goldPaths = [gold.path];
+ } else if (gold != null) goldPaths = [gold];
+
+ goldPaths = goldPaths.map((g) => {
+ const c = toRepoRelativePath(g);
+ return c.ok ? c.path : null;
+ }).filter(Boolean);
+ if (!goldPaths.length) {
+ return failScore({ type: 'scoring', message: 'missing gold file path(s)', parsed, value: parsed });
+ }
+ const correct = goldPaths.includes(parsed);
+ return okScore({ parsed, value: parsed, correct });
+}
+
+const SCORERS = {
+ boolean: scoreBoolean,
+ multiple_choice: scoreMultipleChoice,
+ abstention: scoreAbstention,
+ numeric_order_of_magnitude: scoreNumericOrderOfMagnitude,
+ probability_brier: scoreProbabilityBrier,
+ file_localization: scoreFileLocalization,
+};
+
+function scoreWithAdapter(name, text, gold, options = {}) {
+ const key = String(name || '').toLowerCase().replace(/-/g, '_');
+ const fn = SCORERS[key];
+ if (!fn) {
+ return failScore({ type: 'scoring', message: `unknown scorer: ${name}` });
+ }
+ try {
+ return fn(text, gold, options);
+ } catch (err) {
+ return failScore({
+ type: 'scoring',
+ message: err && err.message ? err.message : String(err),
+ details: { scorer: key },
+ });
+ }
+}
+
+function goldForItem(item, scorerName) {
+ if (!item) return null;
+ const key = String(scorerName || item.scorer || item.mode || '').toLowerCase().replace(/-/g, '_');
+ if (item.gold !== undefined) return item.gold;
+ if (key === 'boolean' || key === 'binary_decision') {
+ if (typeof item.label === 'boolean') return item.label;
+ if (item.answer != null) return item.answer;
+ }
+ if (key === 'multiple_choice') return item.answer_idx != null ? item.answer_idx : item.answer;
+ if (key === 'abstention') return { answerable: item.answerable };
+ if (key === 'numeric_order_of_magnitude') return item.answer_num != null ? item.answer_num : item.answer;
+ if (key === 'probability_brier') return item.answer_bin != null ? item.answer_bin : item.answer;
+ if (key === 'file_localization') return item.gold_files || item.gold || item.files;
+ return item.answer != null ? item.answer : item.label;
+}
+
+function sumUsage(a, b) {
+ const x = defaultUsage(a);
+ const y = defaultUsage(b);
+ return {
+ input_tokens: x.input_tokens + y.input_tokens,
+ output_tokens: x.output_tokens + y.output_tokens,
+ cached_tokens: x.cached_tokens + y.cached_tokens,
+ calls: x.calls + y.calls,
+ latency_ms: x.latency_ms + y.latency_ms,
+ estimated_cost_usd: x.estimated_cost_usd + y.estimated_cost_usd,
+ };
+}
+
+function normalizeSolveUsage(result, countDefaultCall = false) {
+ const value = result || {};
+ const raw = value.usage || {};
+ return defaultUsage({
+ input_tokens: raw.input_tokens || 0,
+ output_tokens: raw.output_tokens || 0,
+ cached_tokens: raw.cached_tokens || raw.cache_read_tokens || raw.cache_read_input_tokens || 0,
+ calls: raw.calls != null
+ ? raw.calls
+ : (value.attempts != null ? value.attempts : (countDefaultCall ? 1 : 0)),
+ latency_ms: raw.latency_ms != null
+ ? raw.latency_ms
+ : (countDefaultCall && value.durationMs != null ? value.durationMs : 0),
+ estimated_cost_usd: raw.estimated_cost_usd != null
+ ? raw.estimated_cost_usd
+ : (raw.est_cost_usd || 0),
+ });
+}
+
+/**
+ * Run every arm × item × trial. Never drops attempted rows.
+ *
+ * @param {object} spec
+ * @param {string} spec.studyId
+ * @param {string} spec.studyVersion
+ * @param {string} spec.preregistrationSha256
+ * @param {object} spec.dataset
+ * @param {Array} spec.arms - [{id, prompt_sha256?, skill_sha256?, skillContent?, condition?}]
+ * @param {object|string} spec.solver
+ * @param {Array} spec.items
+ * @param {number} [spec.trials=1]
+ * @param {string|function} spec.scorer - adapter name or custom (text,item,arm)=>score
+ * @param {object} [spec.scorerOptions]
+ * @param {function} [spec.solve] - async ({item, arm, trial, prompt}) => {ok,text,usage,failure,...}
+ * @param {function} [spec.buildPrompt] - optional override ({item, arm}) => string
+ * @param {string} [spec.createdAt]
+ */
+async function runObjectiveItems(spec) {
+ if (!spec || typeof spec !== 'object') throw new TypeError('runObjectiveItems: spec required');
+ const itemsIn = Array.isArray(spec.items) ? spec.items : [];
+ const armsIn = Array.isArray(spec.arms) ? spec.arms : [];
+ if (!armsIn.length) throw new TypeError('runObjectiveItems: arms required');
+ const trials = Number.isInteger(spec.trials) && spec.trials > 0 ? spec.trials : 1;
+ const scorerName = typeof spec.scorer === 'string' ? spec.scorer : (spec.scorerName || null);
+ const scorerFn = typeof spec.scorer === 'function' ? spec.scorer : null;
+ const scorerOptions = spec.scorerOptions || {};
+ const solve = typeof spec.solve === 'function' ? spec.solve : null;
+ const buildPrompt = typeof spec.buildPrompt === 'function' ? spec.buildPrompt : null;
+ const solverModel = typeof spec.solver === 'string'
+ ? spec.solver
+ : (spec.solver && spec.solver.model) || 'unknown';
+ const judgeModels = (spec.judges || []).map((j) => (typeof j === 'string' ? j : j.model)).filter(Boolean);
+
+ const armMeta = armsIn.map((arm) => {
+ const id = arm.id || arm.arm_id || normalizeCondition(arm.condition) || 'arm';
+ const skillContent = arm.skillContent != null ? arm.skillContent : (arm.skill_content || null);
+ return {
+ id: String(id),
+ condition: normalizeCondition(arm.condition || arm.id),
+ skillContent,
+ skillName: arm.skillName || arm.skill_name || null,
+ // Collect every item prompt hash for this arm; aggregate after the loop.
+ promptHashes: [],
+ fixed_prompt_sha256: arm.prompt_sha256 || null,
+ skill_sha256: arm.skill_sha256 != null ? arm.skill_sha256 : (skillContent != null ? sha256(skillContent) : null),
+ tokenBudget: arm.tokenBudget,
+ raw: arm,
+ };
+ });
+
+ const outItems = [];
+ const failures = [];
+ let usage = defaultUsage(spec.usage);
+ let attempted = 0;
+ let completed = 0;
+ let scored = 0;
+
+ function pushRow(row) {
+ outItems.push(row);
+ }
+
+ function observationKeyFor({ itemId, trial, armId, promptHash, skillHash }) {
+ // Bind row-specific prompt/skill/solver/judges into the compatibility key, then
+ // observationCheckpointKey binds item/trial/arm.
+ const compatibilityKey = checkpointKey({
+ studyId: spec.studyId,
+ studyVersion: spec.studyVersion,
+ datasetSha256: (spec.dataset && spec.dataset.sha256) || 'missing-dataset-sha256',
+ promptSha256: promptHash || 'missing-prompt-sha256',
+ skillSha256: skillHash || null,
+ solver: solverModel,
+ judges: judgeModels,
+ });
+ return observationCheckpointKey({
+ compatibilityKey,
+ itemId,
+ trial,
+ armId,
+ });
+ }
+
+ for (const item of itemsIn) {
+ const itemId = String(item.id || item.item_id || item.instance_id || '');
+ if (!itemId) throw new TypeError('runObjectiveItems: every item needs id');
+ for (let trial = 1; trial <= trials; trial++) {
+ for (const arm of armMeta) {
+ attempted += 1;
+ const identityKey = itemKey({
+ studyId: spec.studyId,
+ itemId,
+ trial,
+ armId: arm.id,
+ });
+
+ let prompt;
+ try {
+ prompt = buildPrompt
+ ? buildPrompt({ item, arm: arm.raw, armId: arm.id, trial })
+ : buildConditionPrompt(
+ arm.condition,
+ item.prompt || item.problem || item.text || '',
+ arm.skillContent,
+ arm.skillName || arm.id,
+ {
+ tokenBudget: arm.tokenBudget,
+ tokenCounter: scorerOptions.tokenCounter || defaultTokenCounter,
+ tail: item.answer_instruction
+ ? `\n\n${item.answer_instruction}`
+ : (item.decision_instruction
+ ? `\n\n${item.decision_instruction}\nEnd your response with exactly: ANSWER: <Yes or No>`
+ : undefined),
+ },
+ );
+ } catch (err) {
+ const failure = failureRecord({
+ type: 'scoring',
+ message: err && err.message ? err.message : String(err),
+ itemId,
+ armId: arm.id,
+ trial,
+ });
+ failures.push(failure);
+ const obsKey = observationKeyFor({
+ itemId,
+ trial,
+ armId: arm.id,
+ promptHash: null,
+ skillHash: arm.skill_sha256,
+ });
+ pushRow({
+ item_id: itemId,
+ trial,
+ arm_id: arm.id,
+ key: identityKey,
+ observation_checkpoint_key: obsKey,
+ completed: false,
+ parsed_success: false,
+ scored: false,
+ correct: false,
+ parsed: null,
+ value: null,
+ prompt_sha256: null,
+ response_sha256: null,
+ usage: defaultUsage(),
+ failure,
+ });
+ continue;
+ }
+
+ const promptHash = sha256(prompt);
+ arm.promptHashes.push(promptHash);
+ const obsKey = observationKeyFor({
+ itemId,
+ trial,
+ armId: arm.id,
+ promptHash,
+ skillHash: arm.skill_sha256,
+ });
+
+ let solveResult;
+ if (solve) {
+ try {
+ solveResult = await solve({
+ item,
+ arm: arm.raw,
+ armId: arm.id,
+ trial,
+ prompt,
+ key: identityKey,
+ observationCheckpointKey: obsKey,
+ });
+ } catch (err) {
+ solveResult = {
+ ok: false,
+ text: null,
+ failure: failureRecord({
+ type: 'transport',
+ message: err && err.message ? err.message : String(err),
+ itemId,
+ armId: arm.id,
+ trial,
+ }),
+ };
+ }
+ } else if (item.fixture_responses && item.fixture_responses[arm.id] != null) {
+ const fr = item.fixture_responses[arm.id];
+ solveResult = typeof fr === 'string'
+ ? { ok: true, text: fr, usage: { calls: 0 } }
+ : {
+ ok: fr.ok !== false,
+ text: fr.text != null ? fr.text : null,
+ usage: fr.usage,
+ failure: fr.failure || null,
+ };
+ } else if (spec.fixtureMode) {
+ solveResult = {
+ ok: false,
+ text: null,
+ failure: failureRecord({
+ type: 'transport',
+ message: 'fixture mode: missing fixture_responses for arm',
+ itemId,
+ armId: arm.id,
+ trial,
+ }),
+ };
+ } else {
+ throw new TypeError('runObjectiveItems: solve callback or fixture_responses required');
+ }
+
+ const rowUsage = normalizeSolveUsage(solveResult, Boolean(solve));
+ usage = sumUsage(usage, rowUsage);
+
+ if (!solveResult || solveResult.ok === false) {
+ const failure = solveResult && solveResult.failure
+ ? {
+ ...solveResult.failure,
+ item_id: solveResult.failure.item_id != null ? solveResult.failure.item_id : itemId,
+ arm_id: solveResult.failure.arm_id != null ? solveResult.failure.arm_id : arm.id,
+ trial: solveResult.failure.trial != null ? solveResult.failure.trial : trial,
+ }
+ : failureRecord({
+ type: (solveResult && solveResult.failureType) || 'transport',
+ message: (solveResult && (solveResult.error || solveResult.message)) || 'solve failed',
+ itemId,
+ armId: arm.id,
+ trial,
+ attempt: solveResult && solveResult.attempts,
+ });
+ failures.push(failure);
+ pushRow({
+ item_id: itemId,
+ trial,
+ arm_id: arm.id,
+ key: identityKey,
+ observation_checkpoint_key: obsKey,
+ completed: false,
+ parsed_success: false,
+ scored: false,
+ correct: false,
+ parsed: null,
+ value: null,
+ prompt_sha256: promptHash,
+ response_sha256: solveResult && solveResult.text != null ? sha256(solveResult.text) : null,
+ usage: rowUsage,
+ failure,
+ attempts: solveResult && solveResult.attempts != null ? solveResult.attempts : null,
+ duration_ms: solveResult && solveResult.durationMs != null ? solveResult.durationMs : null,
+ });
+ continue;
+ }
+
+ completed += 1;
+ const text = solveResult.text;
+ const responseHash = text != null ? sha256(text) : null;
+
+ let score;
+ if (scorerFn) {
+ try {
+ score = scorerFn(text, item, arm.raw, scorerOptions);
+ } catch (err) {
+ score = failScore({
+ type: 'scoring',
+ message: err && err.message ? err.message : String(err),
+ });
+ }
+ } else {
+ const name = scorerName || item.scorer || item.mode || 'boolean';
+ const gold = goldForItem(item, name);
+ const opts = {
+ ...scorerOptions,
+ repositoryFiles: item.repository_files || item.file_inventory || scorerOptions.repositoryFiles,
+ };
+ score = scoreWithAdapter(name, text, gold, opts);
+ }
+
+ if (!score || typeof score !== 'object') {
+ score = failScore({ type: 'scoring', message: 'scorer returned no result' });
+ }
+
+ const parsedSuccess = score.failure
+ ? (score.failure.type !== 'parse' && score.parsed !== null && score.parsed !== undefined)
+ : (score.parsed !== null && score.parsed !== undefined);
+
+ if (score.failure) {
+ const failure = {
+ ...score.failure,
+ item_id: itemId,
+ arm_id: arm.id,
+ trial,
+ };
+ failures.push(failure);
+ pushRow({
+ item_id: itemId,
+ trial,
+ arm_id: arm.id,
+ key: identityKey,
+ observation_checkpoint_key: obsKey,
+ completed: true,
+ parsed_success: parsedSuccess,
+ scored: false,
+ correct: false,
+ parsed: score.parsed,
+ value: score.value,
+ prompt_sha256: promptHash,
+ response_sha256: responseHash,
+ usage: rowUsage,
+ failure,
+ attempts: solveResult.attempts != null ? solveResult.attempts : null,
+ duration_ms: solveResult.durationMs != null ? solveResult.durationMs : null,
+ });
+ continue;
+ }
+
+ scored += 1;
+ pushRow({
+ item_id: itemId,
+ trial,
+ arm_id: arm.id,
+ key: identityKey,
+ observation_checkpoint_key: obsKey,
+ completed: true,
+ parsed_success: true,
+ scored: true,
+ correct: Boolean(score.correct),
+ parsed: score.parsed,
+ value: score.value,
+ prompt_sha256: promptHash,
+ response_sha256: responseHash,
+ usage: rowUsage,
+ failure: null,
+ attempts: solveResult.attempts != null ? solveResult.attempts : null,
+ duration_ms: solveResult.durationMs != null ? solveResult.durationMs : null,
+ });
+ }
+ }
+ }
+
+ const envelopeArms = armMeta.map((arm) => {
+ // Always derive from every generated item prompt. A declared arm.prompt_sha256
+ // is bound as an extra input, never a substitute that can mask item changes.
+ const parts = [...arm.promptHashes];
+ if (arm.fixed_prompt_sha256) parts.push(arm.fixed_prompt_sha256);
+ const prompt_sha256 = parts.length ? sha256(parts) : sha256(arm.id);
+ return {
+ id: arm.id,
+ prompt_sha256,
+ skill_sha256: arm.skill_sha256,
+ };
+ });
+
+ const statistics = {
+ ...(spec.statistics || {}),
+ per_arm: {},
+ };
+ for (const arm of armMeta) {
+ const rows = outItems.filter((r) => r.arm_id === arm.id);
+ const scoredRows = rows.filter((r) => r.scored);
+ // ITT: failures count as incorrect; denominator is attempted, never shrinks.
+ const correct = rows.filter((r) => r.correct === true).length;
+ const conditionalCorrect = scoredRows.filter((r) => r.correct === true).length;
+ statistics.per_arm[arm.id] = {
+ attempted: rows.length,
+ completed: rows.filter((r) => r.completed).length,
+ parsed: rows.filter((r) => r.parsed_success).length,
+ scored: scoredRows.length,
+ correct,
+ accuracy: rows.length ? correct / rows.length : null,
+ conditional_accuracy: scoredRows.length ? conditionalCorrect / scoredRows.length : null,
+ };
+ }
+
+ const parsedCount = outItems.filter((r) => r.parsed_success).length;
+
+ return createResultEnvelope({
+ study_id: spec.studyId,
+ study_version: spec.studyVersion,
+ preregistration_sha256: spec.preregistrationSha256,
+ dataset: spec.dataset,
+ arms: envelopeArms,
+ solver: spec.solver,
+ judges: spec.judges || [],
+ items: outItems,
+ failures,
+ usage,
+ statistics,
+ health: {
+ attempted,
+ completed,
+ parsed: parsedCount,
+ scored,
+ failures: failures.length,
+ },
+ created_at: spec.createdAt,
+ });
+}
+
+module.exports = {
+ SCORERS,
+ scoreBoolean,
+ scoreMultipleChoice,
+ scoreAbstention,
+ scoreNumericOrderOfMagnitude,
+ scoreProbabilityBrier,
+ parseFileLocalization,
+ scoreFileLocalization,
+ scoreWithAdapter,
+ runObjectiveItems,
+ goldForItem,
+ normalizeRepoPath,
+ normalizeSolveUsage,
+};
diff --git a/evals/lib/pairwise.js b/evals/lib/pairwise.js
new file mode 100644
index 0000000..bb7454f
--- /dev/null
+++ b/evals/lib/pairwise.js
@@ -0,0 +1,793 @@
+'use strict';
+
+/**
+ * Generic blind pairwise engine.
+ *
+ * - Deterministic A/B arm order from a frozen seed (per item × trial).
+ * - Fresh independent solve calls per arm (no conversation reuse).
+ * - Panel judging via judge.js (injectable for fixtures/tests).
+ * - Every attempted item/trial remains in denominators; failures are explicit.
+ * - Item rows set completed / parsed_success / scored explicitly.
+ */
+
+const {
+ sha256,
+ itemKey,
+ checkpointKey,
+ observationCheckpointKey,
+ failureRecord,
+ createResultEnvelope,
+ defaultUsage,
+} = require('./result');
+
+let _judgeModule;
+function loadJudge() {
+ if (!_judgeModule) _judgeModule = require('./judge');
+ return _judgeModule;
+}
+
+/** Mulberry32 PRNG — deterministic, no deps. */
+function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function next() {
+ a = (a + 0x6D2B79F5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function seedToUint32(seed) {
+ if (Number.isInteger(seed) && seed >= 0) return seed >>> 0;
+ const hex = sha256(String(seed)).slice(0, 8);
+ return parseInt(hex, 16) >>> 0;
+}
+
+function unitSeed(parts) {
+ return seedToUint32(sha256(parts.map(p => String(p)).join(':')));
+}
+
+/**
+ * Deterministic presentation order for arms from a frozen seed.
+ * Stable across processes; depends only on seed + itemId + trial + arm set.
+ *
+ * @param {string[]} armIds
+ * @param {{seed:string|number, itemId:string, trial:number}} ctx
+ * @returns {string[]} arm ids in A.. presentation order
+ */
+function deterministicArmOrder(armIds, ctx = {}) {
+ if (!Array.isArray(armIds) || armIds.length === 0) {
+ throw new TypeError('armIds must be a non-empty array');
+ }
+ const ids = armIds.map(String);
+ const seed = ctx.seed == null ? 0 : ctx.seed;
+ const itemId = ctx.itemId == null ? '' : String(ctx.itemId);
+ const trial = Number.isInteger(ctx.trial) ? ctx.trial : 1;
+ const rng = mulberry32(unitSeed([seed, itemId, trial, ids.slice().sort().join(',')]));
+ // Canonicalize input order so callers' arm array order cannot change presentation.
+ const out = ids.slice().sort();
+ for (let i = out.length - 1; i > 0; i--) {
+ const j = Math.floor(rng() * (i + 1));
+ const tmp = out[i];
+ out[i] = out[j];
+ out[j] = tmp;
+ }
+ return out;
+}
+function emptyUsage() {
+ return defaultUsage();
+}
+
+function mergeUsage(a, b) {
+ const left = defaultUsage(a);
+ const right = defaultUsage(b);
+ return defaultUsage({
+ input_tokens: left.input_tokens + right.input_tokens,
+ output_tokens: left.output_tokens + right.output_tokens,
+ cached_tokens: left.cached_tokens + right.cached_tokens,
+ calls: left.calls + right.calls,
+ latency_ms: left.latency_ms + right.latency_ms,
+ estimated_cost_usd: left.estimated_cost_usd + right.estimated_cost_usd,
+ });
+}
+
+function normalizeSolveUsage(usage, durationMs) {
+ if (!usage && durationMs == null) return emptyUsage();
+ const u = usage || {};
+ return defaultUsage({
+ input_tokens: u.input_tokens || 0,
+ output_tokens: u.output_tokens || 0,
+ cached_tokens: u.cached_tokens || u.cache_read_tokens || 0,
+ calls: u.calls != null ? u.calls : 1,
+ latency_ms: u.latency_ms != null ? u.latency_ms : (durationMs || 0),
+ estimated_cost_usd: u.estimated_cost_usd != null ? u.estimated_cost_usd : (u.est_cost_usd || 0),
+ });
+}
+
+function normalizeJudgeUsage(panel) {
+ let usage = emptyUsage();
+ const voteUsages = panel && Array.isArray(panel.judge_usage) ? panel.judge_usage : [];
+ if (voteUsages.length) {
+ for (const u of voteUsages) {
+ usage = mergeUsage(usage, {
+ input_tokens: u.input_tokens || 0,
+ output_tokens: u.output_tokens || 0,
+ cached_tokens: u.cache_read_tokens || u.cached_tokens || 0,
+ calls: 1,
+ latency_ms: 0,
+ estimated_cost_usd: u.est_cost_usd || u.estimated_cost_usd || 0,
+ });
+ }
+ } else if (panel && Array.isArray(panel.votes)) {
+ for (const v of panel.votes) {
+ if (!v) continue;
+ usage = mergeUsage(usage, normalizeSolveUsage(v.usage, v.durationMs));
+ }
+ }
+ if (panel && panel.judge_durationMs) {
+ usage = defaultUsage({ ...usage, latency_ms: usage.latency_ms + Number(panel.judge_durationMs || 0) });
+ }
+ if (usage.calls === 0 && panel && Array.isArray(panel.votes) && panel.votes.length) {
+ usage = defaultUsage({ ...usage, calls: panel.votes.length });
+ }
+ return usage;
+}
+
+/** Map judge-layer failure labels onto result.FAILURE_TYPES. */
+function coerceFailureType(type, fallback = 'scoring') {
+ if (type === 'transport' || type === 'timeout' || type === 'tool_leakage' || type === 'parse' || type === 'scoring') {
+ return type;
+ }
+ if (type === 'judge_unresolved' || type === 'unresolved') return 'scoring';
+ return fallback;
+}
+
+/**
+ * Normalize both legacy and contract-era panelJudge payloads.
+ * Contract: unresolved never becomes a scored tie.
+ */
+function normalizePanelResult(raw) {
+ if (!raw || typeof raw !== 'object') {
+ return {
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ tally: { A: 0, B: 0, tie: 0, missing: 0 },
+ votes: [],
+ failures: [],
+ failure: failureRecord({ type: 'scoring', message: 'panelJudge returned no result' }),
+ vocab_only: false,
+ whys: [],
+ judge_usage: [],
+ judge_durationMs: 0,
+ };
+ }
+
+ const votes = Array.isArray(raw.votes) ? raw.votes : [];
+ const explicitUnresolved = raw.unresolved === true || raw.resolved === false;
+ let winner = raw.winner == null ? null : String(raw.winner).trim();
+ if (winner) {
+ const upper = winner.toUpperCase();
+ if (upper === 'A' || upper === 'B') winner = upper;
+ else if (upper === 'TIE') winner = 'tie';
+ else winner = null;
+ }
+
+ let unresolved = explicitUnresolved;
+ if (raw.failure) unresolved = true;
+ if (winner == null && !explicitUnresolved && raw.resolved !== true) unresolved = true;
+ // Resolved substantive ties are allowed only when caller marks resolved=true.
+ if (unresolved) winner = null;
+
+ const tally = raw.tally && typeof raw.tally === 'object'
+ ? {
+ A: Number(raw.tally.A || 0),
+ B: Number(raw.tally.B || 0),
+ tie: Number(raw.tally.tie || 0),
+ missing: Number(raw.tally.missing != null ? raw.tally.missing : 0),
+ }
+ : { A: 0, B: 0, tie: 0, missing: 0 };
+
+ let failure = null;
+ if (unresolved) {
+ const src = raw.failure || {};
+ failure = failureRecord({
+ type: coerceFailureType(src.type, 'scoring'),
+ message: src.message || 'unresolved panel judgment',
+ details: src.details || { winner: raw.winner, tally, vote_count: votes.length },
+ });
+ }
+
+ return {
+ winner,
+ resolved: !unresolved,
+ unresolved,
+ tally,
+ votes,
+ failures: Array.isArray(raw.failures) ? raw.failures : (failure ? [failure] : []),
+ failure,
+ vocab_only: !!raw.vocab_only,
+ whys: Array.isArray(raw.whys) ? raw.whys : [],
+ judge_usage: Array.isArray(raw.judge_usage) ? raw.judge_usage : [],
+ judge_durationMs: Number(raw.judge_durationMs || 0),
+ };
+}
+
+function requireFn(fn, name) {
+ if (typeof fn !== 'function') throw new TypeError(`${name} must be a function`);
+ return fn;
+}
+
+function armById(arms, id) {
+ return arms.find(a => a && a.id === id) || null;
+}
+
+function defaultBuildJudgePrompt({ item, responseA, responseB }) {
+ const problem = item.prompt || item.problem || item.text || '';
+ return [
+ 'Two assistants answered the same problem. Judge which response reasons better.',
+ 'Return ONLY JSON: {"winner":"A"|"B"|"tie","margin":"slight","why":"...","skill_vocab_without_substance":false}',
+ '',
+ '=== PROBLEM ===',
+ problem,
+ '',
+ '=== RESPONSE A ===',
+ responseA,
+ '',
+ '=== RESPONSE B ===',
+ responseB,
+ '',
+ '=== END ===',
+ ].join('\n');
+}
+
+/**
+ * Run pairwise comparisons over items × trials for a fixed arm pair.
+ *
+ * @param {object} opts
+ * @returns {Promise<object>} result envelope
+ */
+async function runPairwiseItems(opts = {}) {
+ const studyId = opts.studyId || opts.study_id;
+ const studyVersion = opts.studyVersion || opts.study_version;
+ const preregistrationSha256 = opts.preregistrationSha256 || opts.preregistration_sha256;
+ if (!studyId || !studyVersion || !preregistrationSha256) {
+ throw new TypeError('studyId, studyVersion, and preregistrationSha256 are required');
+ }
+ if (!opts.dataset || typeof opts.dataset !== 'object') throw new TypeError('dataset is required');
+ if (!Array.isArray(opts.arms) || opts.arms.length < 2) throw new TypeError('arms must include at least two entries');
+ if (!Array.isArray(opts.items)) throw new TypeError('items must be an array');
+ if (!opts.solver || typeof (opts.solver.model || opts.solver) !== 'string') {
+ throw new TypeError('solver.model is required');
+ }
+
+ const arms = opts.arms.map(a => ({
+ id: a.id,
+ prompt_sha256: a.prompt_sha256 || a.promptSha256 || null,
+ skill_sha256: a.skill_sha256 != null ? a.skill_sha256 : (a.skillSha256 != null ? a.skillSha256 : null),
+ }));
+ const armIds = arms.map(a => a.id);
+ const pair = opts.pair || { left: armIds[0], right: armIds[1] };
+ if (!armById(arms, pair.left) || !armById(arms, pair.right)) {
+ throw new TypeError(`pair arms must exist in arms: ${pair.left} vs ${pair.right}`);
+ }
+ if (pair.left === pair.right) throw new TypeError('pair.left and pair.right must differ');
+
+ const solver = typeof opts.solver === 'string'
+ ? { model: opts.solver, effort: opts.solverEffort || null }
+ : { model: opts.solver.model, effort: opts.solver.effort != null ? opts.solver.effort : null };
+
+ const judgeMod = loadJudge();
+ const judgesInput = opts.judges != null
+ ? opts.judges.map(j => (typeof j === 'string' ? j : j.model)).filter(Boolean)
+ : (typeof judgeMod.panelModels === 'function' ? judgeMod.panelModels() : []);
+
+ let judges = judgesInput;
+ if (typeof judgeMod.judgesExcludingSolver === 'function') {
+ const filtered = judgeMod.judgesExcludingSolver(solver.model, judgesInput);
+ if (Array.isArray(filtered)) judges = filtered;
+ }
+
+ const trials = Number.isInteger(opts.trials) && opts.trials > 0 ? opts.trials : 1;
+ const seed = opts.seed != null ? opts.seed : 0;
+ const solve = requireFn(opts.solve, 'solve');
+ const judgeFn = typeof opts.judge === 'function' ? opts.judge : judgeMod.panelJudge.bind(judgeMod);
+ const buildPrompt = typeof opts.buildPrompt === 'function'
+ ? opts.buildPrompt
+ : ({ item, armId }) => {
+ const text = item.prompt || item.problem || item.text || '';
+ return `[arm=${armId}]\n\n${text}`;
+ };
+ const buildJudgePrompt = typeof opts.buildJudgePrompt === 'function'
+ ? opts.buildJudgePrompt
+ : defaultBuildJudgePrompt;
+
+ const compatibilityKey = checkpointKey({
+ studyId,
+ studyVersion,
+ datasetSha256: opts.dataset.sha256,
+ promptSha256: sha256(arms.map(a => a.prompt_sha256 || null)),
+ skillSha256: sha256(arms.map(a => a.skill_sha256 || null)),
+ solver: solver.model,
+ judges,
+ });
+
+ const itemsOut = [];
+ const failures = [];
+ let usage = emptyUsage();
+ let completed = 0;
+ let parsed = 0;
+ let scored = 0;
+
+ const panelEligible = judges.length >= 2;
+ if (!panelEligible) {
+ failures.push(failureRecord({
+ type: 'scoring',
+ message: `ineligible judge panel: need ≥2 independent judges, got ${judges.length}`,
+ details: { judges, solver: solver.model },
+ }));
+ }
+
+ for (const item of opts.items) {
+ const itemId = String(item.id || item.item_id || '');
+ if (!itemId) throw new TypeError('each item requires id');
+
+ for (let trial = 1; trial <= trials; trial++) {
+ const pairArmIds = [pair.left, pair.right];
+ const order = deterministicArmOrder(pairArmIds, { seed, itemId, trial });
+ const armA = order[0];
+ const armB = order[1];
+ const leftIsA = armA === pair.left;
+
+ const responses = {};
+ let solverOk = true;
+ let rowUsage = emptyUsage();
+ const observationKeys = {};
+
+ // Fresh independent solves — never reuse a conversation between arms.
+ for (const armId of pairArmIds) {
+ const arm = armById(arms, armId);
+ const obsKey = observationCheckpointKey({
+ compatibilityKey,
+ itemId,
+ trial,
+ armId,
+ });
+ observationKeys[armId] = obsKey;
+
+ let prompt;
+ try {
+ prompt = await buildPrompt({ item, arm, trial, armId });
+ } catch (err) {
+ solverOk = false;
+ const fail = failureRecord({
+ type: 'parse',
+ message: `buildPrompt failed: ${err && err.message ? err.message : err}`,
+ itemId,
+ armId,
+ trial,
+ });
+ failures.push(fail);
+ responses[armId] = {
+ ok: false,
+ completed: false,
+ text: null,
+ response_sha256: null,
+ usage: emptyUsage(),
+ failure: fail,
+ observation_checkpoint_key: obsKey,
+ attempts: 0,
+ };
+ continue;
+ }
+
+ let result;
+ try {
+ result = await solve({ item, arm, trial, armId, prompt });
+ } catch (err) {
+ result = {
+ ok: false,
+ text: null,
+ failure: failureRecord({
+ type: 'transport',
+ message: `solve threw: ${err && err.message ? err.message : err}`,
+ itemId,
+ armId,
+ trial,
+ }),
+ };
+ }
+
+ const ok = !!(result && result.ok);
+ const text = result && result.text != null ? String(result.text) : null;
+ const armUsage = normalizeSolveUsage(result && result.usage, result && result.durationMs);
+ rowUsage = mergeUsage(rowUsage, armUsage);
+
+ let failure = null;
+ if (!ok) {
+ solverOk = false;
+ if (result && result.failure && result.failure.type) {
+ failure = failureRecord({
+ type: coerceFailureType(result.failure.type, 'transport'),
+ message: result.failure.message || 'solver failure',
+ itemId,
+ armId,
+ trial,
+ attempt: result.attempts != null ? result.attempts : null,
+ details: result.failure.details || null,
+ });
+ } else {
+ failure = failureRecord({
+ type: 'transport',
+ message: (result && result.error) || 'solver failure',
+ itemId,
+ armId,
+ trial,
+ attempt: result && result.attempts != null ? result.attempts : null,
+ });
+ }
+ failures.push(failure);
+ }
+
+ responses[armId] = {
+ ok,
+ completed: ok,
+ text: ok ? text : null,
+ response_sha256: ok && text != null ? sha256(text) : null,
+ usage: armUsage,
+ failure,
+ observation_checkpoint_key: obsKey,
+ attempts: result && result.attempts != null ? result.attempts : (ok ? 1 : 0),
+ };
+ }
+
+ let panel = null;
+ let winnerArm = null;
+ let winnerLabel = null;
+ let rowCompleted = false;
+ let rowParsed = false;
+ let rowScored = false;
+ let rowFailure = null;
+ let parsedValue = null;
+
+ if (!panelEligible) {
+ rowFailure = failureRecord({
+ type: 'scoring',
+ message: 'judge panel ineligible for solver family',
+ itemId,
+ trial,
+ details: { judges, solver: solver.model },
+ });
+ // study-level failure already recorded once
+ } else if (!solverOk) {
+ rowCompleted = false;
+ rowParsed = false;
+ rowScored = false;
+ rowFailure = failureRecord({
+ type: 'transport',
+ message: 'one or more arm solves failed; pair not judged',
+ itemId,
+ trial,
+ details: {
+ failed_arms: pairArmIds.filter(id => !responses[id].ok),
+ },
+ });
+ // per-arm failures already recorded; do not double-count this summary row
+ } else {
+ rowCompleted = true;
+ const responseA = responses[armA].text;
+ const responseB = responses[armB].text;
+
+ let rawPanel;
+ let judgePrompt;
+ try {
+ judgePrompt = await buildJudgePrompt({
+ item,
+ responseA,
+ responseB,
+ order,
+ pair,
+ leftIsA,
+ trial,
+ });
+ } catch (err) {
+ rawPanel = {
+ winner: null,
+ unresolved: true,
+ failure: {
+ type: 'parse',
+ message: `buildJudgePrompt failed: ${err && err.message ? err.message : err}`,
+ },
+ votes: [],
+ tally: { A: 0, B: 0, tie: 0, missing: judges.length },
+ };
+ }
+
+ if (!rawPanel) {
+ try {
+ rawPanel = await judgeFn(judgePrompt, judges);
+ } catch (err) {
+ rawPanel = {
+ winner: null,
+ unresolved: true,
+ failure: {
+ type: 'transport',
+ message: `panelJudge threw: ${err && err.message ? err.message : err}`,
+ },
+ votes: [],
+ tally: { A: 0, B: 0, tie: 0, missing: judges.length },
+ };
+ }
+ }
+
+ panel = normalizePanelResult(rawPanel);
+ const judgeUsage = normalizeJudgeUsage(panel);
+ rowUsage = mergeUsage(rowUsage, judgeUsage);
+
+ if (panel.unresolved || !panel.resolved) {
+ rowScored = false;
+ // Valid parsed votes (e.g. A vs B disagreement) mean parsing succeeded;
+ // only transport/parse/empty-panel failures leave parsed_success false.
+ const hasValidVotes = (panel.votes || []).some(v => (
+ v && (v.valid === true || v.winner === 'A' || v.winner === 'B' || v.winner === 'tie')
+ ));
+ const failType = coerceFailureType(panel.failure && panel.failure.type, 'scoring');
+ const parseFailed = failType === 'transport' || failType === 'timeout'
+ || failType === 'parse' || failType === 'tool_leakage';
+ rowParsed = hasValidVotes && !parseFailed;
+ rowFailure = failureRecord({
+ type: failType,
+ message: panel.failure ? panel.failure.message : 'unresolved panel judgment',
+ itemId,
+ trial,
+ details: {
+ tally: panel.tally,
+ votes: panel.votes.map(v => ({
+ model: v && v.model,
+ winner: v && v.winner,
+ valid: v && v.valid,
+ })),
+ },
+ });
+ failures.push(rowFailure);
+ if (rowParsed) {
+ parsedValue = {
+ unresolved: true,
+ tally: panel.tally,
+ left_is_a: leftIsA,
+ presentation: { A: armA, B: armB },
+ };
+ }
+ } else {
+ rowParsed = true;
+ winnerLabel = panel.winner; // 'A' | 'B' | 'tie'
+ if (winnerLabel === 'A') winnerArm = armA;
+ else if (winnerLabel === 'B') winnerArm = armB;
+ else if (winnerLabel === 'tie') winnerArm = 'tie';
+ else {
+ rowParsed = false;
+ rowScored = false;
+ rowFailure = failureRecord({
+ type: 'scoring',
+ message: `unexpected panel winner: ${winnerLabel}`,
+ itemId,
+ trial,
+ });
+ failures.push(rowFailure);
+ }
+ if (rowParsed) {
+ rowScored = true;
+ parsedValue = {
+ winner_label: winnerLabel,
+ winner_arm: winnerArm,
+ left_is_a: leftIsA,
+ presentation: { A: armA, B: armB },
+ };
+ }
+ }
+ }
+
+ if (rowCompleted) completed += 1;
+ if (rowParsed) parsed += 1;
+ if (rowScored) scored += 1;
+ usage = mergeUsage(usage, rowUsage);
+
+ itemsOut.push({
+ item_id: itemId,
+ trial,
+ pair: `${pair.left}:${pair.right}`,
+ arm_order: order,
+ left_is_a: leftIsA,
+ presentation: { A: armA, B: armB },
+ winner_arm: winnerArm,
+ winner_label: winnerLabel,
+ completed: rowCompleted,
+ parsed_success: rowParsed,
+ parsed: parsedValue,
+ scored: rowScored,
+ responses: Object.fromEntries(
+ pairArmIds.map(id => [
+ id,
+ {
+ ok: responses[id].ok,
+ completed: responses[id].completed,
+ response_sha256: responses[id].response_sha256,
+ usage: responses[id].usage,
+ failure: responses[id].failure,
+ observation_checkpoint_key: responses[id].observation_checkpoint_key,
+ attempts: responses[id].attempts,
+ ...(opts.retainResponseText ? { text: responses[id].text } : {}),
+ },
+ ])
+ ),
+ judge: panel
+ ? {
+ winner: panel.winner,
+ resolved: panel.resolved,
+ unresolved: panel.unresolved,
+ tally: panel.tally,
+ votes: panel.votes,
+ vocab_only: panel.vocab_only,
+ whys: panel.whys,
+ }
+ : null,
+ usage: rowUsage,
+ failure: rowFailure,
+ observation_checkpoint_keys: observationKeys,
+ item_keys: {
+ [pair.left]: itemKey({ studyId, itemId, trial, armId: pair.left }),
+ [pair.right]: itemKey({ studyId, itemId, trial, armId: pair.right }),
+ },
+ compatibility_key: compatibilityKey,
+ });
+ }
+ }
+
+ const statistics = summarizePairwise(itemsOut, pair);
+ const attempted = itemsOut.length;
+
+ return createResultEnvelope({
+ study_id: studyId,
+ study_version: studyVersion,
+ preregistration_sha256: preregistrationSha256,
+ dataset: opts.dataset,
+ arms,
+ solver,
+ judges,
+ items: itemsOut,
+ failures,
+ usage,
+ statistics,
+ health: {
+ attempted,
+ completed,
+ parsed,
+ scored,
+ failures: failures.length,
+ decision_eligible: panelEligible
+ && failures.length === 0
+ && attempted === completed
+ && completed === parsed
+ && parsed === scored,
+ panel_eligible: panelEligible,
+ pair: `${pair.left}:${pair.right}`,
+ seed,
+ trials,
+ },
+ created_at: opts.createdAt || opts.created_at || new Date().toISOString(),
+ checkpoint_key: compatibilityKey,
+ });
+}
+
+/**
+ * Summarize pairwise item rows into win/loss/tie counts for the left arm.
+ * Intention-to-treat: primary `win_rate` uses the attempted denominator so
+ * unresolved/failures cannot disappear. Judged-only rate is `conditional_win_rate`.
+ *
+ * @param {Array<object>} items
+ * @param {{left:string,right:string}|null} pair
+ */
+function summarizePairwise(items, pair = null) {
+ const rows = Array.isArray(items) ? items : [];
+ let left = pair && pair.left;
+ let right = pair && pair.right;
+ if (!left || !right) {
+ const first = rows.find(r => r && r.pair);
+ if (first && typeof first.pair === 'string' && first.pair.includes(':')) {
+ const [l, r] = first.pair.split(':');
+ left = left || l;
+ right = right || r;
+ }
+ }
+
+ let wins = 0;
+ let losses = 0;
+ let ties = 0;
+ let unresolved = 0;
+ let solver_failures = 0;
+ let left_is_a_count = 0;
+ let left_is_b_count = 0;
+
+ for (const row of rows) {
+ if (!row) continue;
+ if (row.left_is_a === true) left_is_a_count += 1;
+ else if (row.left_is_a === false) left_is_b_count += 1;
+
+ if (!row.scored) {
+ unresolved += 1;
+ if (row.failure && (row.failure.type === 'transport' || row.failure.type === 'timeout' || row.failure.type === 'tool_leakage')) {
+ solver_failures += 1;
+ }
+ continue;
+ }
+ if (row.winner_arm === 'tie' || row.winner_label === 'tie') {
+ ties += 1;
+ } else if (left && row.winner_arm === left) {
+ wins += 1;
+ } else if (right && row.winner_arm === right) {
+ losses += 1;
+ } else if (row.winner_label === 'A' && row.left_is_a) {
+ wins += 1;
+ } else if (row.winner_label === 'B' && row.left_is_a) {
+ losses += 1;
+ } else if (row.winner_label === 'A' && row.left_is_a === false) {
+ losses += 1;
+ } else if (row.winner_label === 'B' && row.left_is_a === false) {
+ wins += 1;
+ } else {
+ unresolved += 1;
+ }
+ }
+
+ const decisive = wins + losses;
+ const judged = decisive + ties;
+ const attempted = rows.length;
+ // ITT: unresolved/failures remain in the primary denominator (count as non-wins).
+ const winRateItt = attempted ? (wins + 0.5 * ties) / attempted : 0;
+ const conditionalWinRate = judged ? (wins + 0.5 * ties) / judged : 0;
+
+ let ci95 = [0, 1];
+ let p_value = 1;
+ try {
+ const { summarize } = require('./stats');
+ // Sign-test / Wilson stay on decisive judged outcomes; ITT rate is separate.
+ const s = summarize(wins, losses, ties);
+ ci95 = s.ci95;
+ p_value = s.p_value;
+ } catch (_) {
+ // stats optional during partial foundation boots
+ }
+
+ return {
+ pair: left && right ? `${left}:${right}` : null,
+ left: left || null,
+ right: right || null,
+ attempted,
+ judged,
+ decisive,
+ wins,
+ losses,
+ ties,
+ unresolved,
+ solver_failures,
+ win_rate: +winRateItt.toFixed(6),
+ conditional_win_rate: +conditionalWinRate.toFixed(6),
+ lift: wins - losses,
+ ci95,
+ p_value,
+ order_balance: {
+ left_is_a: left_is_a_count,
+ left_is_b: left_is_b_count,
+ },
+ };
+}
+
+module.exports = {
+ deterministicArmOrder,
+ runPairwiseItems,
+ summarizePairwise,
+ normalizePanelResult,
+ mulberry32,
+ seedToUint32,
+};
diff --git a/evals/lib/prereg.js b/evals/lib/prereg.js
new file mode 100644
index 0000000..e90bf56
--- /dev/null
+++ b/evals/lib/prereg.js
@@ -0,0 +1,65 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+
+const DEFAULT_PREREG = path.join(__dirname, '..', 'preregistrations', 'workflow-vs-skill-proof.md');
+
+function sha256(s) {
+ return crypto.createHash('sha256').update(s).digest('hex');
+}
+
+function preregistrationMeta(file = process.env.PREREGISTRATION || DEFAULT_PREREG) {
+ const resolved = path.resolve(file);
+ if (!fs.existsSync(resolved)) return { path: resolved, exists: false, sha256: null };
+ return { path: resolved, exists: true, sha256: sha256(fs.readFileSync(resolved, 'utf8')) };
+}
+
+function runMetadata(extraEnvKeys = []) {
+ const envKeys = [
+ 'EVAL_RUN',
+ 'SOLVER_MODEL',
+ 'SOLVER_EFFORT',
+ 'JUDGE_MODEL',
+ 'JUDGES',
+ 'CONC',
+ 'LIMIT',
+ 'LIMIT_PER_SKILL',
+ 'ARMS',
+ 'PAIRS',
+ 'WORKFLOW_DATASET',
+ 'PREREGISTRATION',
+ ...extraEnvKeys,
+ ];
+ const env = {};
+ for (const key of envKeys) {
+ if (Object.prototype.hasOwnProperty.call(process.env, key)) env[key] = process.env[key];
+ }
+ return {
+ command: ['node', ...process.argv.slice(1)].join(' '),
+ cwd: process.cwd(),
+ env,
+ };
+}
+
+
+/**
+ * Compute a claim_status from run_health and artifact properties.
+ * Returns one of: confirmed, invalidated, inconclusive, pilot_only, diagnostic_only, stale, noisy
+ */
+function claimStatus(runHealth, opts = {}) {
+ if (!runHealth) return 'inconclusive';
+ const failures = runHealth.solver_failures || 0;
+ const rate = runHealth.failure_rate || 0;
+ if (failures > 0 && rate > 0.05) return 'noisy';
+ if (failures > 0) return 'diagnostic_only';
+ if (opts.isPilot) return 'pilot_only';
+ if (opts.hasReplication === false) return 'inconclusive';
+ if (opts.replicationPassed) return 'confirmed';
+ if (opts.replicationFailed) return 'invalidated';
+ // hasReplication means data exists, not that replication eval passed
+ if (opts.hasReplication) return 'inconclusive';
+ return 'inconclusive';
+}
+module.exports = { preregistrationMeta, runMetadata, claimStatus };
diff --git a/evals/lib/registry.js b/evals/lib/registry.js
new file mode 100644
index 0000000..a5fca67
--- /dev/null
+++ b/evals/lib/registry.js
@@ -0,0 +1,418 @@
+'use strict';
+
+/**
+ * Study/catalog registry loader and validator.
+ * Source of truth: evals/studies/registry.json
+ */
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+
+const REPO_ROOT = path.join(__dirname, '..', '..');
+const DEFAULT_REGISTRY_PATH = path.join(REPO_ROOT, 'evals', 'studies', 'registry.json');
+
+function loadRegistry(registryPath = DEFAULT_REGISTRY_PATH) {
+ const resolved = path.resolve(registryPath);
+ if (!fs.existsSync(resolved)) {
+ const err = new Error(`registry not found: ${resolved}`);
+ err.code = 'REGISTRY_MISSING';
+ throw err;
+ }
+ const raw = fs.readFileSync(resolved, 'utf8');
+ const registry = JSON.parse(raw);
+ return { path: resolved, registry };
+}
+
+function isNonEmptyString(value) {
+ return typeof value === 'string' && value.length > 0;
+}
+
+function isPositiveNumber(value) {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
+}
+
+/**
+ * Validate registry shape and make unknown/inadequate data explicit.
+ * @returns {{ok:boolean, errors:string[], warnings:string[], summary:object}}
+ */
+function validateRegistry(registry) {
+ const errors = [];
+ const warnings = [];
+
+ if (!registry || typeof registry !== 'object') {
+ return { ok: false, errors: ['registry must be an object'], warnings, summary: {} };
+ }
+ if (registry.schema_version !== 1) errors.push('schema_version must equal 1');
+ if (!registry.catalog || typeof registry.catalog !== 'object') errors.push('catalog is required');
+ if (!registry.skills || typeof registry.skills !== 'object') errors.push('skills is required');
+ if (!registry.models || typeof registry.models !== 'object') errors.push('models is required');
+ if (!registry.judge_panel || typeof registry.judge_panel !== 'object') errors.push('judge_panel is required');
+ if (!registry.arms || typeof registry.arms !== 'object') errors.push('arms is required');
+ if (!registry.gates || typeof registry.gates !== 'object') errors.push('gates is required');
+ if (!Array.isArray(registry.required_skill_sections) || registry.required_skill_sections.length === 0) {
+ errors.push('required_skill_sections must be a non-empty array');
+ }
+ if (!Array.isArray(registry.declared_study_bundles)) errors.push('declared_study_bundles must be an array');
+
+ const skills = registry.skills || {};
+ const skillIds = Object.keys(skills);
+ const catalog = registry.catalog || {};
+ const expectedCount = catalog.expected_count ?? catalog.baseline_count;
+ if (expectedCount != null && skillIds.length !== expectedCount) {
+ errors.push(`skills count ${skillIds.length} != expected_count ${expectedCount}`);
+ }
+
+ const survivors = new Set(catalog.survivors || []);
+ const deletions = new Set(catalog.deletions || []);
+ const budgets = catalog.survivor_budgets || {};
+
+ for (const id of survivors) {
+ if (!skills[id]) errors.push(`survivor missing from skills: ${id}`);
+ else if (skills[id].disposition?.cutover !== 'survive') errors.push(`survivor ${id} cutover must be survive`);
+ if (budgets[id] == null) errors.push(`survivor budget missing for ${id}`);
+ }
+ for (const id of deletions) {
+ if (!skills[id]) errors.push(`deletion missing from skills: ${id}`);
+ else if (skills[id].disposition?.cutover !== 'delete') errors.push(`deletion ${id} cutover must be delete`);
+ }
+ if (survivors.size && deletions.size && survivors.size + deletions.size !== skillIds.length) {
+ errors.push(`survivors(${survivors.size})+deletions(${deletions.size}) != skills(${skillIds.length})`);
+ }
+
+ let adequate = 0;
+ let inadequate = 0;
+ let unknown = 0;
+ const inadequateIds = [];
+ const unknownIds = [];
+
+ for (const [id, skill] of Object.entries(skills)) {
+ if (!isNonEmptyString(skill.id) || skill.id !== id) errors.push(`skill key/id mismatch for ${id}`);
+ if (!isNonEmptyString(skill.dir)) errors.push(`skill ${id} missing dir`);
+ if (!isNonEmptyString(skill.primary_metric)) errors.push(`skill ${id} missing primary_metric`);
+ if (!skill.disposition || typeof skill.disposition !== 'object') {
+ errors.push(`skill ${id} missing disposition`);
+ }
+ if (!skill.data || typeof skill.data !== 'object') {
+ errors.push(`skill ${id} missing data block`);
+ continue;
+ }
+ const status = skill.data.status;
+ if (!['adequate', 'inadequate', 'unknown'].includes(status)) {
+ errors.push(`skill ${id} data.status must be adequate|inadequate|unknown (got ${status})`);
+ }
+ if (status === 'adequate') adequate++;
+ else if (status === 'inadequate') {
+ inadequate++;
+ inadequateIds.push(id);
+ if (!Array.isArray(skill.data.gaps) || skill.data.gaps.length === 0) {
+ errors.push(`skill ${id} inadequate without explicit gaps`);
+ }
+ } else if (status === 'unknown') {
+ unknown++;
+ unknownIds.push(id);
+ if (!Array.isArray(skill.data.gaps) || skill.data.gaps.length === 0) {
+ errors.push(`skill ${id} unknown without explicit gaps`);
+ }
+ }
+ if (survivors.has(id)) {
+ const maxWords = skill.max_words ?? skill.disposition?.max_words ?? budgets[id];
+ if (!isPositiveNumber(maxWords)) errors.push(`survivor ${id} missing positive max_words`);
+ }
+ }
+
+ // declared data_adequacy must match computed statuses (explicit, no silent filter)
+ if (registry.data_adequacy) {
+ const declaredUnknown = new Set(registry.data_adequacy.unknown_skill_ids || []);
+ const declaredInadequate = new Set(registry.data_adequacy.inadequate_skill_ids || []);
+ for (const id of unknownIds) {
+ if (!declaredUnknown.has(id)) errors.push(`data_adequacy.unknown_skill_ids missing ${id}`);
+ }
+ for (const id of inadequateIds) {
+ if (!declaredInadequate.has(id)) errors.push(`data_adequacy.inadequate_skill_ids missing ${id}`);
+ }
+ for (const id of declaredUnknown) {
+ if (!unknownIds.includes(id)) errors.push(`data_adequacy.unknown_skill_ids has stale ${id}`);
+ }
+ for (const id of declaredInadequate) {
+ if (!inadequateIds.includes(id)) errors.push(`data_adequacy.inadequate_skill_ids has stale ${id}`);
+ }
+ } else {
+ errors.push('data_adequacy block required so unknown/inadequate are explicit');
+ }
+
+ const gates = registry.gates || {};
+ for (const field of ['utility_margin_pp', 'noninferiority_margin_pp', 'harm_margin_pp', 'efficacy_hypotheses', 'power_target']) {
+ if (gates[field] == null) errors.push(`gates.${field} required`);
+ }
+ if (gates.utility_margin_pp !== 5) errors.push('gates.utility_margin_pp must equal 5');
+ if (gates.noninferiority_margin_pp !== 3) errors.push('gates.noninferiority_margin_pp must equal 3');
+ if (gates.harm_margin_pp !== 2) errors.push('gates.harm_margin_pp must equal 2');
+ if (gates.efficacy_hypotheses !== 84) errors.push('gates.efficacy_hypotheses must equal 84');
+
+ const panel = registry.judge_panel || {};
+ if (!Array.isArray(panel.models) || panel.models.length < 2) {
+ errors.push('judge_panel.models must list at least 2 judges');
+ }
+ const panelSize = panel.panel_size ?? (Array.isArray(panel.models) ? panel.models.length : 0);
+ const votesPerJudge = panel.votes_per_judge ?? panel.votes_per_item ?? 1;
+ const maxVotes = panel.max_votes_per_item ?? (panelSize * votesPerJudge);
+ const minValid = panel.min_valid_votes_to_decide;
+ if (!Number.isInteger(minValid) || minValid < 2) {
+ errors.push('judge_panel.min_valid_votes_to_decide must be an integer >= 2');
+ }
+ if (!Number.isInteger(maxVotes) || maxVotes < 1) {
+ errors.push('judge_panel.max_votes_per_item must be a positive integer');
+ } else if (Number.isInteger(minValid) && maxVotes < minValid) {
+ errors.push(
+ `judge_panel max_votes_per_item (${maxVotes}) must be >= min_valid_votes_to_decide (${minValid})`
+ );
+ }
+ if (panel.votes_per_item != null && panel.min_valid_votes_to_decide != null &&
+ panel.votes_per_item < panel.min_valid_votes_to_decide) {
+ errors.push('judge_panel.votes_per_item must be >= min_valid_votes_to_decide');
+ }
+ if (!panel.calibration || typeof panel.calibration !== 'object') {
+ errors.push('judge_panel.calibration thresholds required');
+ } else if (panel.calibration.min_pairs !== 30) {
+ errors.push('judge_panel.calibration.min_pairs must equal 30');
+ }
+ if (panel.calibration_status !== 'blocked_missing_human_labels' && panel.decision_eligible === true) {
+ // calibrated path must still declare study
+ }
+ if (panel.calibration_status === 'blocked_missing_human_labels') {
+ if (panel.decision_eligible !== false) {
+ errors.push('judge_panel.decision_eligible must be false while calibration is blocked');
+ }
+ if (panel.judged_studies_policy_while_blocked !== 'manual_only') {
+ errors.push('judge_panel.judged_studies_policy_while_blocked must be manual_only while blocked');
+ }
+ }
+ if (!isNonEmptyString(panel.calibration_status)) {
+ errors.push('judge_panel.calibration_status required');
+ }
+
+ const arms = registry.arms || {};
+ if (!Array.isArray(arms.all) || !arms.all.includes('none') || !arms.all.includes('lean')) {
+ errors.push('arms.all must include none and lean');
+ }
+
+ if (!registry.study_contracts || typeof registry.study_contracts !== 'object') {
+ errors.push('study_contracts required');
+ }
+
+ // Family counts must exist and sum to skill count
+ if (!registry.family_counts || typeof registry.family_counts !== 'object') {
+ errors.push('family_counts required');
+ } else {
+ const byFamily = registry.family_counts.by_eval_family || {};
+ const computed = {};
+ for (const skill of Object.values(skills)) {
+ const fam = skill.eval_family || 'unknown';
+ computed[fam] = (computed[fam] || 0) + 1;
+ }
+ const declaredTotal = registry.family_counts.total_skills;
+ const sumFamilies = Object.values(byFamily).reduce((a, b) => a + Number(b || 0), 0);
+ if (declaredTotal !== skillIds.length) {
+ errors.push(`family_counts.total_skills ${declaredTotal} != skills ${skillIds.length}`);
+ }
+ if (sumFamilies !== skillIds.length) {
+ errors.push(`family_counts.by_eval_family sum ${sumFamilies} != skills ${skillIds.length}`);
+ }
+ for (const [fam, n] of Object.entries(computed)) {
+ if (byFamily[fam] !== n) errors.push(`family_counts mismatch for ${fam}: declared ${byFamily[fam]} computed ${n}`);
+ }
+ for (const fam of Object.keys(byFamily)) {
+ if (computed[fam] == null) errors.push(`family_counts has unknown family ${fam}`);
+ }
+ if (registry.family_counts.survivors != null && registry.family_counts.survivors !== survivors.size) {
+ errors.push('family_counts.survivors mismatch');
+ }
+ if (registry.family_counts.deletions != null && registry.family_counts.deletions !== deletions.size) {
+ errors.push('family_counts.deletions mismatch');
+ }
+ if (registry.family_counts.efficacy_hypotheses != null && registry.family_counts.efficacy_hypotheses !== 84) {
+ errors.push('family_counts.efficacy_hypotheses must equal 84');
+ }
+ }
+
+ // Declared calibration study required (inline registry declaration is enough)
+ const bundles = registry.declared_study_bundles || [];
+ const calib = bundles.find(b => b.study_id === 'judge-panel-calibration' || b.kind === 'judge_panel_calibration');
+ const calibContract = registry.study_contracts?.judge_panel_calibration;
+ if (!calib && !calibContract) {
+ errors.push('judge-panel-calibration must be declared in study_contracts or declared_study_bundles');
+ } else {
+ const status = calib?.status || calibContract?.status;
+ const decisionEligible = calib?.decision_eligible ?? calibContract?.decision_eligible;
+ const policy = calib?.judged_studies_policy || calibContract?.rule?.judged_studies_while_blocked;
+ if (panel.calibration_status === 'blocked_missing_human_labels') {
+ if (status !== 'blocked_missing_human_labels') {
+ errors.push('judge-panel-calibration status must be blocked_missing_human_labels while panel blocked');
+ }
+ if (decisionEligible !== false) {
+ errors.push('judge-panel-calibration decision_eligible must be false until calibrated');
+ }
+ if (policy !== 'manual_only') {
+ errors.push('judge-panel-calibration judged studies policy must be manual_only while blocked');
+ }
+ }
+ }
+
+ const summary = {
+ skill_count: skillIds.length,
+ survivors: survivors.size,
+ deletions: deletions.size,
+ data_adequate: adequate,
+ data_inadequate: inadequate,
+ data_unknown: unknown,
+ inadequate_skill_ids: inadequateIds.sort(),
+ unknown_skill_ids: unknownIds.sort(),
+ declared_study_bundles: bundles.length,
+ judge_panel_calibration_status: panel.calibration_status || null,
+ judge_panel_decision_eligible: panel.decision_eligible,
+ };
+
+ return { ok: errors.length === 0, errors, warnings, summary };
+}
+
+function countJsonlSplits(filePath) {
+ const splits = { dev: 0, heldout: 0, replication: 0, other: 0 };
+ let n = 0;
+ if (!fs.existsSync(filePath)) return { n, splits, exists: false };
+ for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
+ if (!line.trim()) continue;
+ n++;
+ try {
+ const row = JSON.parse(line);
+ if (row.split && splits[row.split] !== undefined) splits[row.split]++;
+ else splits.other++;
+ } catch (_) {
+ splits.other++;
+ }
+ }
+ return { n, splits, exists: true };
+}
+
+/**
+ * File-aware source integrity: path exists, sha matches, split counts match registry.
+ */
+function validateRegistrySources(registry, repoRoot = REPO_ROOT) {
+ const errors = [];
+ const warnings = [];
+ const skills = registry.skills || {};
+ for (const [id, skill] of Object.entries(skills)) {
+ const data = skill.data || {};
+ const sources = Array.isArray(data.sources) ? data.sources : [];
+ const declared = data.row_counts || {};
+ let totalN = 0;
+ const observedSplits = { dev: 0, heldout: 0, replication: 0, other: 0 };
+
+ for (const src of sources) {
+ if (!src || !isNonEmptyString(src.path)) {
+ errors.push(`skill ${id}: source missing path`);
+ continue;
+ }
+ const abs = path.isAbsolute(src.path) ? src.path : path.join(repoRoot, src.path);
+ if (!fs.existsSync(abs)) {
+ errors.push(`skill ${id}: source path missing ${src.path}`);
+ continue;
+ }
+ const actualSha = crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex');
+ if (src.sha256 && src.sha256 !== actualSha) {
+ errors.push(`skill ${id}: source sha mismatch for ${src.path}`);
+ } else if (!src.sha256) {
+ errors.push(`skill ${id}: source missing sha256 for ${src.path}`);
+ }
+ const counts = countJsonlSplits(abs);
+ totalN += counts.n;
+ for (const k of Object.keys(observedSplits)) observedSplits[k] += counts.splits[k] || 0;
+ }
+
+ if (sources.length === 0) {
+ if (data.status !== 'unknown') {
+ errors.push(`skill ${id}: no sources but data.status=${data.status}`);
+ }
+ continue;
+ }
+
+ if (declared.n != null && declared.n !== totalN) {
+ errors.push(`skill ${id}: row_counts.n ${declared.n} != observed ${totalN}`);
+ }
+ if (declared.splits) {
+ for (const k of ['dev', 'heldout', 'replication']) {
+ if (declared.splits[k] != null && declared.splits[k] !== observedSplits[k]) {
+ errors.push(`skill ${id}: row_counts.splits.${k} ${declared.splits[k]} != observed ${observedSplits[k]}`);
+ }
+ }
+ }
+ }
+
+ // Inline calibration contract integrity (no external manifest required in this phase)
+ const calib = (registry.declared_study_bundles || []).find(b => b.study_id === 'judge-panel-calibration');
+ const contract = registry.study_contracts?.judge_panel_calibration;
+ if (calib || contract) {
+ const status = calib?.status || contract?.status;
+ const decisionEligible = calib?.decision_eligible ?? contract?.decision_eligible;
+ const policy = calib?.judged_studies_policy || contract?.rule?.judged_studies_while_blocked;
+ if (status !== 'blocked_missing_human_labels') {
+ errors.push('judge-panel-calibration status must be blocked_missing_human_labels');
+ }
+ if (decisionEligible !== false) {
+ errors.push('judge-panel-calibration decision_eligible must be false');
+ }
+ if (policy !== 'manual_only') {
+ errors.push('judge-panel-calibration judged studies policy must be manual_only');
+ }
+ if ((contract?.human_labeled_pairs?.count ?? registry.judge_panel?.human_labeled_pairs?.count ?? 0) !== 0) {
+ // non-zero without calibrated status is inconsistent for blocked state
+ if (registry.judge_panel?.calibration_status === 'blocked_missing_human_labels') {
+ errors.push('blocked calibration cannot claim non-zero human_labeled_pairs');
+ }
+ }
+ }
+
+ return { ok: errors.length === 0, errors, warnings };
+}
+
+function getSkillBudget(registry, skillId) {
+ const skill = registry.skills?.[skillId];
+ if (!skill) return null;
+ return skill.max_words ?? skill.disposition?.max_words ?? registry.catalog?.survivor_budgets?.[skillId] ?? null;
+}
+
+function listSkillEntries(registry) {
+ return Object.values(registry.skills || {}).slice().sort((a, b) => a.id.localeCompare(b.id));
+}
+
+function getDeclaredStudyBundle(registry, studyId) {
+ return (registry.declared_study_bundles || []).find(b => b.study_id === studyId) || null;
+}
+
+function loadAndValidateRegistry(registryPath = DEFAULT_REGISTRY_PATH, opts = {}) {
+ const { path: resolved, registry } = loadRegistry(registryPath);
+ const validation = validateRegistry(registry);
+ const checkSources = opts.checkSources !== false &&
+ (registry.source_integrity?.validate_on_load !== false);
+ if (checkSources) {
+ const sourceValidation = validateRegistrySources(registry, opts.repoRoot || REPO_ROOT);
+ validation.source_validation = sourceValidation;
+ if (!sourceValidation.ok) {
+ validation.ok = false;
+ validation.errors = validation.errors.concat(sourceValidation.errors.map(e => `source: ${e}`));
+ }
+ }
+ return { path: resolved, registry, validation };
+}
+
+module.exports = {
+ REPO_ROOT,
+ DEFAULT_REGISTRY_PATH,
+ loadRegistry,
+ validateRegistry,
+ validateRegistrySources,
+ loadAndValidateRegistry,
+ getSkillBudget,
+ listSkillEntries,
+ getDeclaredStudyBundle,
+};
diff --git a/evals/lib/result.js b/evals/lib/result.js
new file mode 100644
index 0000000..6a4b388
--- /dev/null
+++ b/evals/lib/result.js
@@ -0,0 +1,198 @@
+'use strict';
+
+const crypto = require('crypto');
+
+const FAILURE_TYPES = new Set(['transport', 'timeout', 'tool_leakage', 'parse', 'scoring']);
+
+function normalize(value) {
+ if (Array.isArray(value)) return value.map(normalize);
+ if (value && typeof value === 'object' && !Buffer.isBuffer(value)) {
+ const out = {};
+ for (const key of Object.keys(value).sort()) {
+ if (value[key] !== undefined) out[key] = normalize(value[key]);
+ }
+ return out;
+ }
+ return value;
+}
+
+function stableStringify(value) {
+ return JSON.stringify(normalize(value));
+}
+
+function sha256(value) {
+ const bytes = Buffer.isBuffer(value)
+ ? value
+ : Buffer.from(typeof value === 'string' ? value : stableStringify(value));
+ return crypto.createHash('sha256').update(bytes).digest('hex');
+}
+
+function requireText(value, name) {
+ if (typeof value !== 'string' || value.length === 0) throw new TypeError(`${name} must be a non-empty string`);
+ return value;
+}
+
+function itemKey({ studyId, itemId, trial, armId }) {
+ requireText(studyId, 'studyId');
+ requireText(itemId, 'itemId');
+ requireText(armId, 'armId');
+ if (!Number.isInteger(trial) || trial < 1) throw new TypeError('trial must be a positive integer');
+ return `${studyId}:${itemId}:${trial}:${armId}`;
+}
+
+function checkpointKey(spec) {
+ const payload = {
+ study_id: requireText(spec.studyId, 'studyId'),
+ study_version: requireText(spec.studyVersion, 'studyVersion'),
+ dataset_sha256: requireText(spec.datasetSha256, 'datasetSha256'),
+ prompt_sha256: requireText(spec.promptSha256, 'promptSha256'),
+ skill_sha256: spec.skillSha256 || null,
+ solver: requireText(spec.solver, 'solver'),
+ judges: [...(spec.judges || [])].sort(),
+ };
+ return sha256(payload);
+}
+
+function observationCheckpointKey({ compatibilityKey, itemId, trial, armId }) {
+ requireText(compatibilityKey, 'compatibilityKey');
+ requireText(itemId, 'itemId');
+ requireText(armId, 'armId');
+ if (!Number.isInteger(trial) || trial < 1) throw new TypeError('trial must be a positive integer');
+ return sha256({
+ compatibility_key: compatibilityKey,
+ item_id: itemId,
+ trial,
+ arm_id: armId,
+ });
+}
+
+function failureRecord({ type, message, itemId = null, armId = null, trial = null, attempt = null, details = null }) {
+ if (!FAILURE_TYPES.has(type)) throw new TypeError(`unsupported failure type: ${type}`);
+ return {
+ type,
+ message: String(message || type),
+ item_id: itemId,
+ arm_id: armId,
+ trial,
+ attempt,
+ details,
+ };
+}
+
+function defaultUsage(usage = {}) {
+ return {
+ input_tokens: Number(usage.input_tokens || 0),
+ output_tokens: Number(usage.output_tokens || 0),
+ cached_tokens: Number(usage.cached_tokens || 0),
+ calls: Number(usage.calls || 0),
+ latency_ms: Number(usage.latency_ms || 0),
+ estimated_cost_usd: Number(usage.estimated_cost_usd || 0),
+ };
+}
+
+function deriveHealth(items, failures, supplied = {}) {
+ const attempted = supplied.attempted ?? items.length;
+ const completed = supplied.completed ?? items.filter(item => item && item.completed !== false).length;
+ const parsed = supplied.parsed ?? items.filter(item => (
+ item && (item.parsed_success === true || (item.parsed !== undefined && item.parsed !== null))
+ )).length;
+ const scored = supplied.scored ?? items.filter(item => item && item.scored === true).length;
+ const failureCount = supplied.failures ?? failures.length;
+ const decisionEligible = supplied.decision_eligible ?? (
+ failureCount === 0 && attempted === completed && completed === parsed && parsed === scored
+ );
+ return {
+ attempted,
+ completed,
+ parsed,
+ scored,
+ failures: failureCount,
+ failure_rate: attempted ? failureCount / attempted : 0,
+ decision_eligible: Boolean(decisionEligible),
+ ...supplied,
+ };
+}
+
+function createResultEnvelope(spec) {
+ const items = [...(spec.items || [])];
+ const failures = [...(spec.failures || [])];
+ const judges = [...(spec.judges || [])];
+ const arms = [...(spec.arms || [])];
+ const solver = typeof spec.solver === 'string'
+ ? { model: spec.solver, effort: spec.solverEffort || null }
+ : { ...(spec.solver || {}) };
+ const dataset = { ...(spec.dataset || {}) };
+ const armPromptHash = arms.length === 1 ? arms[0].prompt_sha256 : sha256(arms.map(arm => arm.prompt_sha256 || null));
+ const armSkillHash = arms.length === 1 ? arms[0].skill_sha256 : sha256(arms.map(arm => arm.skill_sha256 || null));
+ const checkpoint = spec.checkpoint_key || checkpointKey({
+ studyId: spec.study_id,
+ studyVersion: spec.study_version,
+ datasetSha256: dataset.sha256,
+ promptSha256: armPromptHash,
+ skillSha256: armSkillHash,
+ solver: solver.model,
+ judges: judges.map(j => typeof j === 'string' ? j : j.model),
+ });
+ return {
+ schema_version: 1,
+ study_id: spec.study_id,
+ study_version: spec.study_version,
+ preregistration_sha256: spec.preregistration_sha256,
+ dataset,
+ arms,
+ solver,
+ judges,
+ items,
+ failures,
+ usage: defaultUsage(spec.usage),
+ statistics: { ...(spec.statistics || {}) },
+ health: deriveHealth(items, failures, spec.health),
+ created_at: spec.created_at || new Date().toISOString(),
+ checkpoint_key: checkpoint,
+ };
+}
+
+function validateResultEnvelope(envelope) {
+ const errors = [];
+ if (!envelope || typeof envelope !== 'object') return { ok: false, errors: ['envelope must be an object'] };
+ if (envelope.schema_version !== 1) errors.push('schema_version must equal 1');
+ for (const field of ['study_id', 'study_version', 'preregistration_sha256', 'created_at', 'checkpoint_key']) {
+ if (typeof envelope[field] !== 'string' || envelope[field].length === 0) errors.push(`${field} must be a non-empty string`);
+ }
+ if (!envelope.dataset || typeof envelope.dataset !== 'object') errors.push('dataset must be an object');
+ else for (const field of ['source', 'version', 'split', 'sha256']) {
+ if (typeof envelope.dataset[field] !== 'string' || envelope.dataset[field].length === 0) errors.push(`dataset.${field} must be a non-empty string`);
+ }
+ if (!Array.isArray(envelope.arms) || envelope.arms.length === 0) errors.push('arms must be a non-empty array');
+ if (!envelope.solver || typeof envelope.solver.model !== 'string') errors.push('solver.model must be a string');
+ for (const field of ['judges', 'items', 'failures']) if (!Array.isArray(envelope[field])) errors.push(`${field} must be an array`);
+ if (!envelope.usage || typeof envelope.usage !== 'object') errors.push('usage must be an object');
+ if (!envelope.statistics || typeof envelope.statistics !== 'object') errors.push('statistics must be an object');
+ if (!envelope.health || typeof envelope.health !== 'object') errors.push('health must be an object');
+ else {
+ for (const field of ['attempted', 'completed', 'parsed', 'scored', 'failures']) {
+ if (!Number.isInteger(envelope.health[field]) || envelope.health[field] < 0) errors.push(`health.${field} must be a non-negative integer`);
+ }
+ if (envelope.health.completed > envelope.health.attempted) errors.push('health.completed cannot exceed attempted');
+ if (envelope.health.parsed > envelope.health.completed) errors.push('health.parsed cannot exceed completed');
+ if (envelope.health.scored > envelope.health.parsed) errors.push('health.scored cannot exceed parsed');
+ }
+ for (const failure of envelope.failures || []) {
+ if (!FAILURE_TYPES.has(failure.type)) errors.push(`unsupported failure type: ${failure.type}`);
+ }
+ return { ok: errors.length === 0, errors };
+}
+
+module.exports = {
+ FAILURE_TYPES,
+ stableStringify,
+ sha256,
+ itemKey,
+ checkpointKey,
+ observationCheckpointKey,
+ failureRecord,
+ createResultEnvelope,
+ validateResultEnvelope,
+ defaultUsage,
+ deriveHealth,
+};
diff --git a/evals/lib/stats.js b/evals/lib/stats.js
index 4049c3f..122d0b2 100644
--- a/evals/lib/stats.js
+++ b/evals/lib/stats.js
@@ -124,20 +124,36 @@ function pairedDiff(treatment, control) {
return { mean_diff: meanDiff, ci95: ci, correlation };
}
-/** Summarize a win/loss/tie count into win-rate, CI, p-value, and a powered flag. */
-function summarize(wins, losses, ties = 0) {
+/**
+ * Summarize win/loss/tie counts.
+ * Legacy field `powered` is retained for callers but is ALWAYS false unless an
+ * explicit power config validates decision eligibility — simple CI exclusion of
+ * 0.5 is no longer treated as powered.
+ */
+function summarize(wins, losses, ties = 0, powerConfig = null) {
const decisive = wins + losses;
const n = decisive + ties;
const winRate = n ? (wins + 0.5 * ties) / n : 0;
const ci = wilson(wins, decisive || 1);
const p = signTest(wins, decisive);
+ const ciExcludesNull = ci[0] > 0.5 || ci[1] < 0.5;
+ let decision_eligible = false;
+ let powered = false;
+ if (powerConfig) {
+ const v = validatePowerConfig(powerConfig);
+ decision_eligible = v.ok && !!powerConfig.achieved_power_ok;
+ powered = decision_eligible;
+ }
return {
wins, losses, ties, n, decisive,
win_rate: +winRate.toFixed(3),
ci95: [+ci[0].toFixed(3), +ci[1].toFixed(3)],
p_value: +p.toFixed(3),
significant: p < 0.05,
- powered: ci[0] > 0.5 || ci[1] < 0.5, // CI excludes the null
+ // Legacy field retained; no longer means "CI excludes 0.5".
+ powered,
+ ci_excludes_null: ciExcludesNull,
+ decision_eligible,
};
}
@@ -184,4 +200,448 @@ function scoreDistractor(items) {
};
}
-module.exports = { normCdf, wilson, signTest, mcnemar, mcnemarMidp, mcnemarFull, binomExactTwoSided, lgamma, lnBinom, pairedDiff, summarize, scoreDistractor };
+/** Clamp probability to [0, 1]. Non-finite → null. */
+function clampProbability(p) {
+ if (p == null || typeof p !== 'number' || !Number.isFinite(p)) return null;
+ if (p < 0) return 0;
+ if (p > 1) return 1;
+ return p;
+}
+
+// ─── Seeded PRNG (Mulberry32) ────────────────────────────────────────────
+
+function mulberry32(seed) {
+ let t = (seed >>> 0) || 1;
+ return function next() {
+ t += 0x6D2B79F5;
+ let r = Math.imul(t ^ (t >>> 15), 1 | t);
+ r ^= r + Math.imul(r ^ (r >>> 7), 61 | r);
+ return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function hashSeed(seed) {
+ if (typeof seed === 'number' && Number.isFinite(seed)) return seed >>> 0;
+ const s = String(seed == null ? 0 : seed);
+ let h = 2166136261;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+
+// ─── Hierarchical cluster bootstrap ──────────────────────────────────────
+
+/**
+ * Build nested hierarchy: leakage_family/cluster → item → trials.
+ * Each observation: { treatment, control, item_id?, leakage_family?, cluster_id?, trial? }
+ */
+function itemKeyFor(obs, index) {
+ if (obs == null) return `idx:${index}`;
+ if (obs.item_id != null && obs.item_id !== '') return String(obs.item_id);
+ if (obs.id != null && obs.id !== '') return String(obs.id);
+ return `idx:${index}`;
+}
+
+function familyKeyFor(obs, index) {
+ if (obs == null) return `idx:${index}`;
+ if (obs.leakage_family != null && obs.leakage_family !== '') return `fam:${obs.leakage_family}`;
+ if (obs.cluster_id != null && obs.cluster_id !== '') return `cid:${obs.cluster_id}`;
+ // Fall back to item-level family when no leakage family is declared
+ return `itemfam:${itemKeyFor(obs, index)}`;
+}
+
+/** @deprecated use familyKeyFor; retained for callers of clusterKeyFor */
+function clusterKeyFor(obs, index) {
+ return familyKeyFor(obs, index);
+}
+
+/**
+ * Hierarchy node shape:
+ * { key, items: [{ key, trials: [obs,...] }] }
+ */
+function buildHierarchy(observations) {
+ const families = new Map();
+ (observations || []).forEach((obs, i) => {
+ const fKey = familyKeyFor(obs, i);
+ const iKey = itemKeyFor(obs, i);
+ if (!families.has(fKey)) families.set(fKey, new Map());
+ const items = families.get(fKey);
+ if (!items.has(iKey)) items.set(iKey, []);
+ items.get(iKey).push(obs);
+ });
+ return [...families.entries()].map(([key, itemMap]) => ({
+ key,
+ items: [...itemMap.entries()].map(([itemKey, trials]) => ({
+ key: itemKey,
+ trials,
+ })),
+ }));
+}
+
+/** Flat clusters (family-level) for randomization sign-flip unit. */
+function groupClusters(observations) {
+ return buildHierarchy(observations).map(f => ({
+ key: f.key,
+ items: f.items.flatMap(it => it.trials),
+ }));
+}
+
+function meanPairedRiskDiff(observations) {
+ if (!observations || observations.length === 0) return 0;
+ let sum = 0;
+ for (const o of observations) {
+ const t = Number(o.treatment);
+ const c = Number(o.control);
+ sum += (Number.isFinite(t) ? t : 0) - (Number.isFinite(c) ? c : 0);
+ }
+ return sum / observations.length;
+}
+
+function sampleWithReplacement(arr, rng) {
+ if (!arr || arr.length === 0) return [];
+ const out = new Array(arr.length);
+ for (let i = 0; i < arr.length; i++) {
+ out[i] = arr[Math.floor(rng() * arr.length)];
+ }
+ return out;
+}
+
+/**
+ * Nested hierarchical resample:
+ * 1) resample families with replacement
+ * 2) within each sampled family, resample items with replacement
+ * 3) within each sampled item, resample trials with replacement
+ */
+function hierarchicalResample(hierarchy, rng) {
+ const out = [];
+ if (!hierarchy.length) return out;
+ const sampledFamilies = sampleWithReplacement(hierarchy, rng);
+ for (const fam of sampledFamilies) {
+ if (!fam.items.length) continue;
+ const sampledItems = sampleWithReplacement(fam.items, rng);
+ for (const item of sampledItems) {
+ if (!item.trials.length) continue;
+ const sampledTrials = sampleWithReplacement(item.trials, rng);
+ for (const trial of sampledTrials) out.push(trial);
+ }
+ }
+ return out;
+}
+
+function flattenClusterSample(clusters, indices) {
+ const out = [];
+ for (const idx of indices) {
+ const c = clusters[idx];
+ for (const item of c.items) out.push(item);
+ }
+ return out;
+}
+
+/**
+ * Deterministic hierarchical cluster-bootstrap paired risk difference.
+ * Resamples families → items → trials with replacement (nested).
+ *
+ * @param {Array} observations
+ * @param {{seed?:number|string, resamples?:number, alpha?:number, alternative?:'two-sided'|'greater'|'less'}} [opts]
+ */
+function clusterBootstrapPairedRiskDiff(observations, opts = {}) {
+ const seed = hashSeed(opts.seed == null ? 0 : opts.seed);
+ const resamples = opts.resamples == null ? 10000 : opts.resamples;
+ const alpha = opts.alpha == null ? 0.05 : opts.alpha;
+ const alternative = opts.alternative || 'two-sided';
+ const hierarchy = buildHierarchy(observations);
+ const nClusters = hierarchy.length;
+ const nItems = hierarchy.reduce((s, f) => s + f.items.length, 0);
+ const observed = meanPairedRiskDiff(observations);
+ if (nClusters === 0 || resamples <= 0) {
+ return {
+ estimate: observed,
+ ci: [observed, observed],
+ alpha,
+ resamples,
+ seed,
+ n_clusters: nClusters,
+ n_items: nItems,
+ n_obs: (observations || []).length,
+ method: 'hierarchical-cluster-bootstrap-paired-rd',
+ };
+ }
+
+ const rng = mulberry32(seed);
+ const boots = new Array(resamples);
+ for (let b = 0; b < resamples; b++) {
+ boots[b] = meanPairedRiskDiff(hierarchicalResample(hierarchy, rng));
+ }
+ boots.sort((a, b) => a - b);
+ const loQ = alternative === 'greater' ? alpha : alpha / 2;
+ const hiQ = alternative === 'less' ? 1 - alpha : 1 - alpha / 2;
+ const loIdx = Math.max(0, Math.min(resamples - 1, Math.floor(loQ * resamples)));
+ const hiIdx = Math.max(0, Math.min(resamples - 1, Math.floor(hiQ * resamples)));
+ return {
+ estimate: observed,
+ ci: [boots[loIdx], boots[hiIdx]],
+ alpha,
+ resamples,
+ seed,
+ n_clusters: nClusters,
+ n_items: nItems,
+ n_obs: (observations || []).length,
+ method: 'hierarchical-cluster-bootstrap-paired-rd',
+ };
+}
+
+/**
+ * Cluster-aware randomization (sign-flip) test for paired risk difference.
+ * Null: within each cluster, treatment/control labels are exchangeable.
+ * p-value = proportion of |null stats| >= |observed| (two-sided) or directional.
+ */
+function clusterRandomizationTest(observations, opts = {}) {
+ const seed = hashSeed(opts.seed == null ? 0 : opts.seed);
+ const resamples = opts.resamples == null ? 10000 : opts.resamples;
+ const alternative = opts.alternative || 'two-sided';
+ const clusters = groupClusters(observations);
+ const observed = meanPairedRiskDiff(observations);
+ if (clusters.length === 0 || resamples <= 0) {
+ return { estimate: observed, p_value: 1, resamples, seed, n_clusters: clusters.length };
+ }
+ const rng = mulberry32(seed);
+ let extreme = 0;
+ for (let b = 0; b < resamples; b++) {
+ const flipped = [];
+ for (const cl of clusters) {
+ const flip = rng() < 0.5;
+ for (const o of cl.items) {
+ if (flip) flipped.push({ treatment: o.control, control: o.treatment });
+ else flipped.push(o);
+ }
+ }
+ const stat = meanPairedRiskDiff(flipped);
+ if (alternative === 'greater') {
+ if (stat >= observed - 1e-15) extreme++;
+ } else if (alternative === 'less') {
+ if (stat <= observed + 1e-15) extreme++;
+ } else if (Math.abs(stat) >= Math.abs(observed) - 1e-15) {
+ extreme++;
+ }
+ }
+ // Include observed under null (standard Monte Carlo p)
+ const p = Math.min(1, (extreme + 1) / (resamples + 1));
+ return {
+ estimate: observed,
+ p_value: p,
+ resamples,
+ seed,
+ n_clusters: clusters.length,
+ n_obs: (observations || []).length,
+ alternative,
+ method: 'cluster-randomization',
+ };
+}
+
+/**
+ * Holm–Bonferroni adjustment for a family of p-values.
+ * @param {Array<{id?:string, p:number}|number>} pValues
+ * @returns {Array<{id:string|number, p:number, p_adjusted:number, rank:number}>}
+ */
+function holmAdjustment(pValues) {
+ const items = (pValues || []).map((v, i) => {
+ if (typeof v === 'number') return { id: i, p: v, index: i };
+ return { id: v.id != null ? v.id : i, p: v.p, index: i };
+ });
+ const m = items.length;
+ if (m === 0) return [];
+ const sorted = items.slice().sort((a, b) => a.p - b.p);
+ const adjusted = new Array(m);
+ let running = 0;
+ for (let i = 0; i < m; i++) {
+ const raw = (m - i) * sorted[i].p;
+ const adj = Math.min(1, Math.max(running, raw));
+ running = adj;
+ adjusted[i] = {
+ id: sorted[i].id,
+ p: sorted[i].p,
+ p_adjusted: adj,
+ rank: i + 1,
+ index: sorted[i].index,
+ };
+ }
+ // Return in original order
+ return adjusted.sort((a, b) => a.index - b.index).map(({ index, ...rest }) => rest);
+}
+
+/**
+ * Bootstrap ratio interval for positive metrics (e.g. cost_workflow / cost_baseline).
+ * observations: [{numerator, denominator, item_id?, leakage_family?}]
+ */
+function ratioBootstrapInterval(observations, opts = {}) {
+ const seed = hashSeed(opts.seed == null ? 0 : opts.seed);
+ const resamples = opts.resamples == null ? 10000 : opts.resamples;
+ const alpha = opts.alpha == null ? 0.05 : opts.alpha;
+ const hierarchy = buildHierarchy(observations);
+ const sumRatio = (obs) => {
+ let num = 0, den = 0;
+ for (const o of obs || []) {
+ num += Number(o.numerator) || 0;
+ den += Number(o.denominator) || 0;
+ }
+ return den === 0 ? null : num / den;
+ };
+ const observed = sumRatio(observations);
+ if (hierarchy.length === 0 || resamples <= 0 || observed == null) {
+ return {
+ estimate: observed,
+ ci: [observed, observed],
+ alpha,
+ resamples,
+ seed,
+ n_clusters: hierarchy.length,
+ method: 'hierarchical-cluster-bootstrap-ratio',
+ };
+ }
+ const rng = mulberry32(seed);
+ const boots = [];
+ for (let b = 0; b < resamples; b++) {
+ const r = sumRatio(hierarchicalResample(hierarchy, rng));
+ if (r != null && Number.isFinite(r)) boots.push(r);
+ }
+ boots.sort((a, b) => a - b);
+ if (boots.length === 0) {
+ return {
+ estimate: observed,
+ ci: [observed, observed],
+ alpha,
+ resamples,
+ seed,
+ n_clusters: hierarchy.length,
+ method: 'hierarchical-cluster-bootstrap-ratio',
+ };
+ }
+ const loIdx = Math.max(0, Math.min(boots.length - 1, Math.floor((alpha / 2) * boots.length)));
+ const hiIdx = Math.max(0, Math.min(boots.length - 1, Math.floor((1 - alpha / 2) * boots.length)));
+ return {
+ estimate: observed,
+ ci: [boots[loIdx], boots[hiIdx]],
+ alpha,
+ resamples,
+ seed,
+ n_clusters: hierarchy.length,
+ n_obs: (observations || []).length,
+ method: 'hierarchical-cluster-bootstrap-ratio',
+ };
+}
+
+/**
+ * Validate explicit final-family power config.
+ * `powered` / decision_eligible requires this — not mere CI exclusion of null.
+ *
+ * Required fields:
+ * - family_size (H) > 0
+ * - alpha_family (e.g. 0.05)
+ * - target_power >= 0.90 (or power >= 0.90)
+ * - margin (utility/harm) defined
+ * - seed frozen
+ * Optional: method, one_sided, achieved_power
+ */
+function validatePowerConfig(config) {
+ const errors = [];
+ if (!config || typeof config !== 'object') {
+ return { ok: false, errors: ['power config missing'] };
+ }
+ const familySize = config.family_size ?? config.H ?? config.hypotheses;
+ if (!(Number.isInteger(familySize) && familySize > 0)) {
+ errors.push('family_size (H) must be a positive integer');
+ }
+ const alpha = config.alpha_family ?? config.alpha;
+ if (!(typeof alpha === 'number' && Number.isFinite(alpha) && alpha > 0 && alpha < 1)) {
+ errors.push('alpha_family must be a finite number in (0,1)');
+ }
+ const power = config.target_power ?? config.power;
+ if (!(typeof power === 'number' && Number.isFinite(power) && power >= 0.90 && power <= 1)) {
+ errors.push('target_power must be a finite number in [0.90, 1]');
+ }
+ const margin = config.margin;
+ if (!(typeof margin === 'number' && Number.isFinite(margin) && margin > 0)) {
+ errors.push('margin must be a finite positive number');
+ }
+ if (config.seed == null || config.seed === '') {
+ errors.push('seed must be frozen in power config');
+ }
+ if (config.method == null || String(config.method).trim() === '') {
+ errors.push('method must be declared (e.g. cluster-bootstrap-holm)');
+ }
+ return {
+ ok: errors.length === 0,
+ errors,
+ config: {
+ family_size: familySize,
+ alpha_family: alpha,
+ target_power: power,
+ margin: config.margin,
+ seed: config.seed,
+ method: config.method,
+ one_sided: config.one_sided !== false,
+ achieved_power: config.achieved_power,
+ achieved_power_ok: !!config.achieved_power_ok,
+ },
+ };
+}
+
+/**
+ * Convenience: disposition-ready paired analysis using cluster bootstrap + randomization p
+ * and optional Holm family.
+ */
+function pairedClusterAnalysis(observations, opts = {}) {
+ const boot = clusterBootstrapPairedRiskDiff(observations, opts);
+ const rand = clusterRandomizationTest(observations, opts);
+ // Secondary diagnostic: McNemar on collapsed per-observation binary pairs
+ let b = 0, c = 0;
+ for (const o of observations || []) {
+ const t = Number(o.treatment) ? 1 : 0;
+ const ctrl = Number(o.control) ? 1 : 0;
+ if (t === 1 && ctrl === 0) b++;
+ else if (t === 0 && ctrl === 1) c++;
+ }
+ const mcn = mcnemarFull(b, c);
+ return {
+ risk_difference: boot.estimate,
+ ci95: boot.ci,
+ p_value: rand.p_value,
+ mcnemar: mcn,
+ discordant: { b, c },
+ bootstrap: boot,
+ randomization: rand,
+ n_obs: (observations || []).length,
+ n_clusters: boot.n_clusters,
+ };
+}
+
+module.exports = {
+ normCdf,
+ wilson,
+ signTest,
+ mcnemar,
+ mcnemarMidp,
+ mcnemarFull,
+ binomExactTwoSided,
+ lgamma,
+ lnBinom,
+ pairedDiff,
+ summarize,
+ scoreDistractor,
+ clampProbability,
+ mulberry32,
+ hashSeed,
+ groupClusters,
+ buildHierarchy,
+ hierarchicalResample,
+ clusterKeyFor,
+ clusterBootstrapPairedRiskDiff,
+ clusterRandomizationTest,
+ holmAdjustment,
+ ratioBootstrapInterval,
+ validatePowerConfig,
+ pairedClusterAnalysis,
+ meanPairedRiskDiff,
+};
diff --git a/evals/run-calibration.js b/evals/run-calibration.js
old mode 100644
new mode 100755
index fe50df8..6c35b4b
--- a/evals/run-calibration.js
+++ b/evals/run-calibration.js
@@ -29,7 +29,7 @@
const fs = require('fs');
const path = require('path');
const { droidJsonAsync, maxEffortFor } = require('./lib/droid');
-const { runDir, writeJson, mapPool } = require('./lib/io');
+const { runDir, writeJson, mapPool, readJsonIfExists } = require('./lib/io');
// ---- CLI ----
const args = process.argv.slice(2);
@@ -40,12 +40,15 @@ const labelFieldArg = args.find(a => a.startsWith('--label-field='));
const batchSizeArg = args.find(a => a.startsWith('--batch-size='));
const BATCH_MODE = args.includes('--batch');
-if (!datasetPath) {
+// When required as a module (tests), skip CLI hard-exit
+const IS_CLI = require.main === module;
+
+if (IS_CLI && !datasetPath) {
console.error('Usage: node evals/run-calibration.js <dataset.jsonl> [--solver-model=MODEL] [--solver-effort=EFFORT] [--batch] [--batch-size=N] [--label-field=FIELD]');
process.exit(1);
}
-const DATASET = path.resolve(datasetPath);
+const DATASET = datasetPath ? path.resolve(datasetPath) : null;
const SOLVER_MODEL = solverModelArg ? solverModelArg.split('=')[1] : 'claude-sonnet-4-6';
const SOLVER_EFFORT = solverEffortArg ? solverEffortArg.split('=')[1] : maxEffortFor(SOLVER_MODEL);
const LABEL_FIELD = labelFieldArg ? labelFieldArg.split('=')[1] : null;
@@ -65,13 +68,10 @@ function loadDataset(file) {
}
// ---- Label normalization ----
-// Pools use different field names for the ground-truth label.
-// When --label-field is set, use that field exclusively.
function normalizeLabel(item) {
if (LABEL_FIELD) {
const raw = item[LABEL_FIELD];
if (raw === undefined || raw === null) return null;
- // Detect type from content
if (typeof raw === 'boolean') return { raw, type: 'boolean', field: LABEL_FIELD };
if (Array.isArray(raw)) return { raw, type: 'filepath', field: LABEL_FIELD };
const s = String(raw);
@@ -79,22 +79,17 @@ function normalizeLabel(item) {
if (/^(yes|no)$/i.test(s.trim())) return { raw: s.trim(), type: 'yesno', field: LABEL_FIELD };
return { raw: s.trim(), type: 'string', field: LABEL_FIELD };
}
- // Priority: label (boolean) > answer (Yes/No string) > answer_idx (A-E string) > gold_files (string list)
if (item.label !== undefined && item.label !== null) return { raw: item.label, type: typeof item.label === 'boolean' ? 'boolean' : 'string', field: 'label' };
if (item.answer !== undefined && item.answer !== null) return { raw: item.answer, type: 'yesno', field: 'answer' };
if (item.answer_idx !== undefined && item.answer_idx !== null) return { raw: item.answer_idx, type: 'choice', field: 'answer_idx' };
if (item.gold_files !== undefined && item.gold_files !== null) return { raw: item.gold_files, type: 'filepath', field: 'gold_files' };
- return null; // no label — judge-only or distractor without ground truth
+ return null;
}
-// ---- Prediction parsing ----
-// The model returns JSON. We also handle "ANSWER: <value>" text format
-// which some decision instructions request.
const ANSWER_LINE_RE = /\bANSWER\s*:\s*(.+)$/im;
function parsePrediction(json, rawText) {
if (!json) {
- // Try to extract ANSWER: pattern from raw text
if (rawText) {
const m = rawText.match(ANSWER_LINE_RE);
if (m) return { value: m[1].trim(), type: 'string', ok: true };
@@ -102,33 +97,26 @@ function parsePrediction(json, rawText) {
return { value: null, ok: false };
}
- // Boolean fields (answer, decision, label, result, yes, classification, answerable)
for (const key of ['answer', 'decision', 'label', 'result', 'yes', 'classification', 'answerable']) {
if (typeof json[key] === 'boolean') return { value: json[key], type: 'boolean', ok: true };
}
- // String fields — answer (Yes/No), answer_idx (A-E), file/result (file path)
for (const key of ['answer', 'answer_idx', 'result', 'file', 'files', 'path']) {
if (typeof json[key] === 'string' && json[key].trim().length > 0) {
return { value: json[key].trim(), type: 'string', ok: true };
}
}
- // Array fields — gold_files, files
for (const key of ['gold_files', 'files', 'answer']) {
if (Array.isArray(json[key]) && json[key].length > 0) {
return { value: json[key], type: 'array', ok: true };
}
}
- // Fallback: try ANSWER: pattern on the stringified JSON
const str = JSON.stringify(json);
const m = str.match(ANSWER_LINE_RE);
if (m) return { value: m[1].trim(), type: 'string', ok: true };
- // Fallback: try ANSWER: pattern in the raw text (model may have returned JSON
- // wrapper around a text answer, or the raw text may contain the answer line
- // that wasn't captured by JSON field iteration).
if (rawText) {
const rm = rawText.match(ANSWER_LINE_RE);
if (rm) return { value: rm[1].trim(), type: 'string', ok: true };
@@ -137,14 +125,10 @@ function parsePrediction(json, rawText) {
return { value: null, ok: false };
}
-// ---- Judgment ----
-// Compares prediction to expected label, handling different formats.
function judgePrediction(predParsed, normLabel) {
if (!predParsed.ok || !normLabel) return null;
if (normLabel.type === 'boolean') {
- // Compare boolean prediction to boolean label.
- // Handle both boolean values and Yes/No string values.
if (predParsed.type === 'boolean') return predParsed.value === normLabel.raw;
if (predParsed.type === 'string') {
const s = predParsed.value.toLowerCase();
@@ -156,7 +140,6 @@ function judgePrediction(predParsed, normLabel) {
}
if (normLabel.type === 'yesno') {
- // Compare prediction to "Yes"/"No" label
const predBool = predParsed.type === 'boolean' ? predParsed.value :
(typeof predParsed.value === 'string' && predParsed.value.toLowerCase() === 'yes' ? true :
typeof predParsed.value === 'string' && predParsed.value.toLowerCase() === 'no' ? false : null);
@@ -166,20 +149,16 @@ function judgePrediction(predParsed, normLabel) {
}
if (normLabel.type === 'choice') {
- // Compare prediction string (e.g. "A") to answer_idx (e.g. "A")
if (predParsed.type === 'string') {
return predParsed.value.toUpperCase() === normLabel.raw.toUpperCase();
}
- // Also support boolean-keyed answer: {"A": true, "B": false, ...}
if (predParsed.type === 'boolean' && normLabel.raw.toUpperCase() === 'A') {
- // Must check all possible choice letters
- return null; // ambiguous without knowing the full choice set
+ return null;
}
return null;
}
if (normLabel.type === 'filepath') {
- // Compare predicted file path to gold_files list
const goldFiles = Array.isArray(normLabel.raw) ? normLabel.raw : [normLabel.raw];
if (predParsed.type === 'string') {
return goldFiles.some(gf => {
@@ -201,20 +180,15 @@ function judgePrediction(predParsed, normLabel) {
return null;
}
-// ---- Prompt truncation ----
-// Long code-context prompts (e.g., SWE-bench) can cause API timeouts.
-// Truncate the middle of the prompt to keep it within a reasonable length
-// while preserving the beginning (issue description) and end (code snippets).
const MAX_PROMPT_LEN = 1600;
function truncatePrompt(prompt, maxLen = MAX_PROMPT_LEN) {
if (!prompt || prompt.length <= maxLen) return prompt;
- const keepStart = Math.floor(maxLen * 0.45); // preserve ~45% at the start
- const keepEnd = Math.floor(maxLen * 0.45); // preserve ~45% at the end
+ const keepStart = Math.floor(maxLen * 0.45);
+ const keepEnd = Math.floor(maxLen * 0.45);
const start = prompt.slice(0, keepStart);
const end = prompt.slice(prompt.length - keepEnd);
const omitted = prompt.length - keepStart - keepEnd;
- // Find a clean break point for the start section
const lastNewline = start.lastIndexOf('\n');
const cleanStart = lastNewline > keepStart * 0.7 ? start.slice(0, lastNewline) : start;
const firstNewline = end.indexOf('\n');
@@ -223,29 +197,16 @@ function truncatePrompt(prompt, maxLen = MAX_PROMPT_LEN) {
}
function buildCalibrationPrompt(problemText, decisionInstruction) {
- // Strip the ANSWER: format instruction from the problem text since we add our
- // own format instruction. Conflicting format signals (ANSWER: vs JSON) cause
- // the model to follow the embedded text instruction and return non-JSON text
- // that droidJsonAsync cannot parse.
let cleanProblem = problemText;
- // Remove trailing "End with exactly: ANSWER: ..." from the problem text
- // (SWE-bench items embed the decision instruction inside the prompt field).
cleanProblem = cleanProblem.replace(/\n*\s*End\s+with\s+exactly\s*:\s*ANSWER\s*:.+\s*$/im, '');
- // Construct a single, unambiguous instruction.
- // Use a descriptive key name, not a literal placeholder like "<path/to/file.ext>"
- // which the model may return verbatim.
let instruction = decisionInstruction;
- // If the original instruction references ANSWER:, generalize it for JSON.
const answerMatch = instruction.match(/End\s+with\s+exactly\s*:\s*ANSWER\s*:\s*(.+)/i);
if (answerMatch) {
- // Replace only the "End with exactly: ANSWER: <placeholder>" part with a clean
- // JSON instruction. Keep the substantive question text.
instruction = instruction.replace(/\s*End\s+with\s+exactly\s*:\s*ANSWER\s*:.+\s*$/i, '');
instruction += '\n\nReturn ONLY valid JSON. Use the key "answer" for your file path. Example: {"answer": "path/to/file.ext"}';
}
- // Check if the instruction already has JSON guidance (avoid duplication).
const hasJsonInstruction = /return\s+only\s+valid\s+json/i.test(instruction) ||
/\{"\w+":/i.test(instruction);
@@ -255,68 +216,148 @@ function buildCalibrationPrompt(problemText, decisionInstruction) {
return `${instruction}\n\nProblem:\n${cleanProblem}\n\nReturn ONLY valid JSON with your answer.`;
}
-// ---- Shared trial processing ----
-async function processItemTrial(item, itemIndex) {
- const normLabel = normalizeLabel(item);
- const rawPrompt = buildCalibrationPrompt(item.prompt, item.decision_instruction);
+async function processItemTrial(item, itemIndex, trialIndex = null) {
+ try {
+ const normLabel = normalizeLabel(item);
+ const rawPrompt = buildCalibrationPrompt(item.prompt, item.decision_instruction);
- // For filepath items (SWE-bench fault localization), skip truncation:
- // MAX_PROMPT_LEN=1600 strips the code context needed to localize bugs.
- const isFilepathItem = normLabel && normLabel.type === 'filepath';
- const prompt = isFilepathItem ? rawPrompt : truncatePrompt(rawPrompt);
+ const isFilepathItem = normLabel && normLabel.type === 'filepath';
+ const prompt = isFilepathItem ? rawPrompt : truncatePrompt(rawPrompt);
- const r = await droidJsonAsync({ model: SOLVER_MODEL, prompt, effort: SOLVER_EFFORT });
+ const r = await droidJsonAsync({ model: SOLVER_MODEL, prompt, effort: SOLVER_EFFORT });
- let correct = null;
- let prediction = null;
- let predType = null;
- // droidJsonAsync returns {raw: text} not {text: text} — use r.raw
- const rawText = r.raw || '';
+ let correct = null;
+ let prediction = null;
+ let predType = null;
+ let scored = false;
+ let parse_failure = false;
+ let transport_failure = false;
+ const rawText = r.raw || '';
- if (r.ok) {
- const parsed = parsePrediction(r.json, rawText);
- predType = parsed.type;
- prediction = parsed.value;
-
- if (parsed.ok && normLabel) {
- const result = judgePrediction(parsed, normLabel);
- correct = result;
- }
- } else {
- // JSON parsing failed — the model likely returned text with ANSWER: format.
- // Try to extract the answer from the raw text using the ANSWER_LINE_RE pattern.
- if (rawText) {
- const parsed = parsePrediction(null, rawText);
+ if (r.ok) {
+ const parsed = parsePrediction(r.json, rawText);
predType = parsed.type;
prediction = parsed.value;
if (parsed.ok && normLabel) {
const result = judgePrediction(parsed, normLabel);
correct = result;
+ // scored only when judgment is true/false (not null/unjudgeable)
+ scored = result === true || result === false;
+ } else if (!parsed.ok) {
+ parse_failure = true;
+ }
+ } else {
+ if (rawText) {
+ const parsed = parsePrediction(null, rawText);
+ predType = parsed.type;
+ prediction = parsed.value;
+
+ if (parsed.ok && normLabel) {
+ const result = judgePrediction(parsed, normLabel);
+ correct = result;
+ scored = result === true || result === false;
+ } else if (!parsed.ok) {
+ parse_failure = true;
+ transport_failure = true;
+ }
+ } else {
+ transport_failure = true;
+ parse_failure = true;
}
}
+
+ return {
+ id: item && item.id,
+ itemIndex,
+ trialIndex,
+ itemType: item && item.type || null,
+ target: item && item.target,
+ labelRaw: normLabel ? normLabel.raw : null,
+ labelField: normLabel ? normLabel.field : null,
+ labelType: normLabel ? normLabel.type : null,
+ prediction,
+ predType,
+ correct,
+ scored,
+ parse_failure,
+ transport_failure,
+ raw: rawText,
+ // Attempt always true once the trial was issued
+ attempted: true,
+ ok: r.ok || (prediction !== null),
+ error: r.error,
+ usage: r.usage,
+ durationMs: r.durationMs,
+ };
+ } catch (err) {
+ // Never let mapPool collapse identity into bare {__error}
+ return {
+ id: item && item.id,
+ itemIndex,
+ trialIndex,
+ itemType: item && item.type || null,
+ target: item && item.target,
+ labelRaw: null,
+ labelField: null,
+ labelType: null,
+ prediction: null,
+ predType: null,
+ correct: null,
+ scored: false,
+ parse_failure: false,
+ transport_failure: true,
+ raw: '',
+ attempted: true,
+ ok: false,
+ error: String(err && err.message || err),
+ usage: null,
+ durationMs: null,
+ };
}
+}
- return {
- id: item.id,
- itemIndex,
- itemType: item.type || null,
- target: item.target,
- labelRaw: normLabel ? normLabel.raw : null,
- labelField: normLabel ? normLabel.field : null,
- labelType: normLabel ? normLabel.type : null,
- prediction,
- predType,
- correct,
- raw: rawText,
- ok: r.ok || (prediction !== null), // mark as ok if we managed to extract a prediction
- error: r.error,
- usage: r.usage,
- durationMs: r.durationMs,
- };
+/** Normalize mapPool results that may be bare {__error} into structured failures. */
+function normalizeTrialResult(row, item, itemIndex, trialIndex) {
+ if (row && row.__error) {
+ return {
+ id: item && item.id,
+ itemIndex,
+ trialIndex,
+ itemType: item && item.type || null,
+ target: item && item.target,
+ labelRaw: null,
+ labelField: null,
+ labelType: null,
+ prediction: null,
+ predType: null,
+ correct: null,
+ scored: false,
+ parse_failure: false,
+ transport_failure: true,
+ raw: '',
+ attempted: true,
+ ok: false,
+ error: String(row.__error),
+ usage: null,
+ durationMs: null,
+ };
+ }
+ if (row && row.itemIndex == null) row.itemIndex = itemIndex;
+ if (row && row.trialIndex == null && trialIndex != null) row.trialIndex = trialIndex;
+ return row;
}
-// ---- Aggregate trial results into per-item stats ----
+/**
+ * Aggregate trial results into per-item stats.
+ * Denominators:
+ * trials_planned = kTrials
+ * attempted = number of trial rows present
+ * scored = trials with true/false judgment
+ * failures = attempted - scored (parse/transport/unjudgeable)
+ * baseline = successes / attempted (failures count against accuracy)
+ * Zero baselines serialize as 0, never null.
+ */
function aggregatePerItem(trialResults, kTrials) {
const perItemMap = new Map();
for (const t of trialResults) {
@@ -330,21 +371,34 @@ function aggregatePerItem(trialResults, kTrials) {
labelType: t.labelType,
predictions: [],
corrects: [],
- trials: []
+ trials: [],
});
}
const entry = perItemMap.get(t.itemIndex);
entry.trials.push(t);
- if (t.prediction !== null) {
+ if (t.prediction !== null && t.prediction !== undefined) {
entry.predictions.push(t.prediction);
- entry.corrects.push(t.correct);
}
+ entry.corrects.push(t.correct);
}
const perItem = [];
for (const [itemIndex, entry] of perItemMap) {
- const attempted = entry.corrects.length;
- const successes = entry.corrects.filter(c => c === true).length;
+ const attempted = entry.trials.length;
+ // Prefer explicit scored flag; fall back to boolean correct
+ const scoredCount = entry.trials.reduce((n, t) => {
+ if (t.scored === true) return n + 1;
+ if (t.scored === false) return n;
+ if (t.correct === true || t.correct === false) return n + 1;
+ return n;
+ }, 0);
+ const successes = entry.trials.filter(t => t.correct === true).length;
+ const incorrect = entry.trials.filter(t => t.correct === false).length;
+ const parseFailures = entry.trials.filter(t => t.parse_failure).length;
+ const transportFailures = entry.trials.filter(t => t.transport_failure).length;
+ // Infrastructure/parse/unjudgeable failures only — not ordinary wrong answers.
+ // Wrong answers remain in the accuracy denominator via successes/attempted.
+ const failures = attempted - scoredCount;
const baseline = attempted > 0 ? successes / attempted : null;
perItem.push({
id: entry.id,
@@ -356,18 +410,21 @@ function aggregatePerItem(trialResults, kTrials) {
labelRaw: entry.labelRaw,
trials: kTrials,
attempted,
+ scored: scoredCount,
successes,
- failures: attempted - successes,
+ incorrect,
+ failures,
+ parse_failures: parseFailures,
+ transport_failures: transportFailures,
+ // Serialize 0 as 0 (not null). Only null when nothing attempted.
baseline: attempted > 0 ? +baseline.toFixed(4) : null,
predictions: entry.predictions,
});
}
- // Sort by itemIndex to maintain deterministic order
perItem.sort((a, b) => a.itemIndex - b.itemIndex);
return perItem;
}
-// ---- Band classification ----
function classifyBands(perItem) {
const inBand = [];
const ceiling = [];
@@ -375,13 +432,14 @@ function classifyBands(perItem) {
const otherOutOfBand = [];
for (const item of perItem) {
- if (item.baseline === null) {
+ if (item.baseline === null || item.baseline === undefined) {
otherOutOfBand.push({ ...item, band: 'unattempted' });
} else if (item.baseline >= 0.40 && item.baseline <= 0.70) {
inBand.push({ ...item, band: 'in-band', kept: true });
} else if (item.baseline >= 0.999) {
ceiling.push({ ...item, band: 'ceiling', kept: false });
} else if (item.baseline <= 0.001) {
+ // Explicit floor including exact 0
floor.push({ ...item, band: 'floor', kept: false });
} else {
otherOutOfBand.push({ ...item, band: 'out-of-band', kept: false });
@@ -390,14 +448,28 @@ function classifyBands(perItem) {
return { inBand, ceiling, floor, otherOutOfBand };
}
-// ---- Build final output object ----
+/** Serialize a number that may be 0 without collapsing to null. */
+function serializeRate(value) {
+ if (value === null || value === undefined || Number.isNaN(value)) return null;
+ return +Number(value).toFixed(3);
+}
+
function buildOutput(datasetName, totalItems, limitedItems, trialResults, perItem) {
const totalAttempted = perItem.reduce((s, i) => s + i.attempted, 0);
const totalCorrect = perItem.reduce((s, i) => s + i.successes, 0);
+ // failed_trials = infra/parse/unjudgeable only (attempted - scored)
+ const totalFailures = perItem.reduce((s, i) => s + i.failures, 0);
+ const totalScored = perItem.reduce((s, i) => s + (i.scored || 0), 0);
+ const totalIncorrect = perItem.reduce((s, i) => s + (i.incorrect || 0), 0);
const baselineAccuracy = totalAttempted > 0 ? totalCorrect / totalAttempted : null;
const { inBand, ceiling, floor, otherOutOfBand } = classifyBands(perItem);
const kept = inBand.map(i => i.id);
- const outOfBand = [...ceiling, ...floor, ...otherOutOfBand].map(i => ({ id: i.id, band: i.band, baseline: i.baseline }));
+ const outOfBand = [...ceiling, ...floor, ...otherOutOfBand].map(i => ({
+ id: i.id,
+ band: i.band,
+ // Preserve 0 baselines
+ baseline: i.baseline,
+ }));
return {
tier: 'calibration',
@@ -410,7 +482,11 @@ function buildOutput(datasetName, totalItems, limitedItems, trialResults, perIte
total_items: totalItems,
total_trials: trialResults.length,
attempted_trials: totalAttempted,
- baseline_accuracy: baselineAccuracy ? +baselineAccuracy.toFixed(3) : null,
+ scored_trials: totalScored,
+ incorrect_trials: totalIncorrect,
+ failed_trials: totalFailures,
+ // 0 serializes as 0.000 not null
+ baseline_accuracy: serializeRate(baselineAccuracy),
calibration_band: [0.40, 0.70],
summary: {
in_band: inBand.length,
@@ -428,16 +504,55 @@ function buildOutput(datasetName, totalItems, limitedItems, trialResults, perIte
function logSummary(out, outputFile) {
console.log(`\n k trials/item: ${K_TRIALS}`);
- console.log(` baseline accuracy: ${out.baseline_accuracy ? (out.baseline_accuracy * 100).toFixed(1) + '%' : 'N/A'} (${out.summary.in_band + out.summary.ceiling + out.summary.floor + out.summary.other_out_of_band} items)`);
+ const accStr = out.baseline_accuracy === null || out.baseline_accuracy === undefined
+ ? 'N/A'
+ : (out.baseline_accuracy * 100).toFixed(1) + '%';
+ console.log(` baseline accuracy: ${accStr} (${out.summary.in_band + out.summary.ceiling + out.summary.floor + out.summary.other_out_of_band} items)`);
console.log(` calibration band: [0.40, 0.70]`);
console.log(` kept (in-band): ${out.summary.in_band}`);
console.log(` ceiling (≈1.0): ${out.summary.ceiling}`);
console.log(` floor (≈0.0): ${out.summary.floor}`);
console.log(` other out-of-band: ${out.summary.other_out_of_band}`);
+ console.log(` attempted/scored/failed trials: ${out.attempted_trials}/${out.scored_trials}/${out.failed_trials}`);
console.log(` -> ${outputFile}`);
}
+/**
+ * Resume support: load partial results and return per-item completed trial indexes.
+ * Partial items keep existing trials; only missing trialIndexes are re-scheduled.
+ */
+function loadPartialProgress(partialFile) {
+ const partial = readJsonIfExists(partialFile);
+ if (!partial || !Array.isArray(partial.raw_results)) {
+ return {
+ trialResults: [],
+ completedItemIndexes: new Set(),
+ completedTrialsByItem: new Map(),
+ };
+ }
+ const trialResults = partial.raw_results.slice();
+ const completedTrialsByItem = new Map(); // itemIndex -> Set(trialIndex)
+ for (const t of trialResults) {
+ if (t == null || t.itemIndex == null) continue;
+ if (!completedTrialsByItem.has(t.itemIndex)) completedTrialsByItem.set(t.itemIndex, new Set());
+ // Prefer explicit trialIndex; else assign next free slot 0..K_TRIALS-1
+ let trialIndex = t.trialIndex;
+ if (trialIndex == null || trialIndex === undefined) {
+ const used = completedTrialsByItem.get(t.itemIndex);
+ trialIndex = 0;
+ while (used.has(trialIndex) && trialIndex < K_TRIALS) trialIndex++;
+ }
+ completedTrialsByItem.get(t.itemIndex).add(trialIndex);
+ }
+ const completedItemIndexes = new Set();
+ for (const [idx, trials] of completedTrialsByItem) {
+ if (trials.size >= K_TRIALS) completedItemIndexes.add(idx);
+ }
+ return { trialResults, completedItemIndexes, completedTrialsByItem, partial };
+}
+
async function runCalibration() {
+ if (!DATASET) throw new Error('dataset path required');
const items = loadDataset(DATASET);
const limitedItems = LIMIT ? items.slice(0, LIMIT) : items;
const datasetName = path.basename(DATASET, path.extname(DATASET));
@@ -462,8 +577,17 @@ async function runCalibration() {
const allTrialResults = [];
if (BATCH_MODE) {
- // --- Batch mode: process items in small batches, saving partial results ---
const partialFile = path.join(outputDir, `calibration-${datasetName}-${EVAL_RUN}-partial.json`);
+ const {
+ trialResults: resumed,
+ completedItemIndexes,
+ completedTrialsByItem,
+ } = loadPartialProgress(partialFile);
+ if (resumed.length > 0) {
+ allTrialResults.push(...resumed);
+ console.log(` Resuming from partial: ${resumed.length} trials, ${completedItemIndexes.size} complete items`);
+ }
+
const numBatches = Math.ceil(limitedItems.length / BATCH_SIZE);
for (let batchIdx = 0; batchIdx < numBatches; batchIdx++) {
@@ -471,34 +595,48 @@ async function runCalibration() {
const end = Math.min(start + BATCH_SIZE, limitedItems.length);
const batchItems = limitedItems.slice(start, end);
- console.log(`\n [batch ${batchIdx + 1}/${numBatches}] items ${start}–${end - 1} (${batchItems.length} items)`);
-
- // Build trials for this batch
- const batchTrials = [];
+ // Schedule only missing trialIndexes per item (no duplicate partial trials)
+ const pending = [];
for (let i = 0; i < batchItems.length; i++) {
const itemIndex = start + i;
+ const done = completedTrialsByItem.get(itemIndex) || new Set();
for (let t = 0; t < K_TRIALS; t++) {
- batchTrials.push({ itemIndex, trialIndex: t, item: batchItems[i] });
+ if (done.has(t)) continue;
+ pending.push({ itemIndex, trialIndex: t, item: batchItems[i] });
}
}
- const batchResults = await mapPool(batchTrials, CONC, async ({ itemIndex, item }) => {
- return processItemTrial(item, itemIndex);
+ if (pending.length === 0) {
+ console.log(`\n [batch ${batchIdx + 1}/${numBatches}] items ${start}–${end - 1} already complete — skip`);
+ continue;
+ }
+
+ console.log(`\n [batch ${batchIdx + 1}/${numBatches}] items ${start}–${end - 1} (${pending.length} pending trials)`);
+
+ const batchResults = await mapPool(pending, CONC, async ({ itemIndex, trialIndex, item }) => {
+ const result = await processItemTrial(item, itemIndex, trialIndex);
+ return normalizeTrialResult(result, item, itemIndex, trialIndex);
});
allTrialResults.push(...batchResults);
+ for (const r of batchResults) {
+ if (r == null || r.itemIndex == null) continue;
+ if (!completedTrialsByItem.has(r.itemIndex)) completedTrialsByItem.set(r.itemIndex, new Set());
+ if (r.trialIndex != null) completedTrialsByItem.get(r.itemIndex).add(r.trialIndex);
+ if (completedTrialsByItem.get(r.itemIndex).size >= K_TRIALS) {
+ completedItemIndexes.add(r.itemIndex);
+ }
+ }
- // Save incremental partial results
const partialPerItem = aggregatePerItem(allTrialResults, K_TRIALS);
const partialOut = buildOutput(datasetName, items.length, limitedItems, allTrialResults, partialPerItem);
writeJson(partialFile, partialOut);
const batchSuccesses = batchResults.filter(r => r.correct === true).length;
- const batchAttempted = batchResults.filter(r => r.prediction !== null).length;
+ const batchAttempted = batchResults.length;
console.log(` [batch ${batchIdx + 1}/${numBatches}] complete — ${batchSuccesses}/${batchAttempted} correct. Partial saved to ${partialFile}`);
}
} else {
- // --- Standard mode: process all items at once ---
const trials = [];
for (let i = 0; i < limitedItems.length; i++) {
for (let t = 0; t < K_TRIALS; t++) {
@@ -506,12 +644,12 @@ async function runCalibration() {
}
}
- allTrialResults.push(...await mapPool(trials, CONC, async ({ itemIndex, item }) => {
- return processItemTrial(item, itemIndex);
+ allTrialResults.push(...await mapPool(trials, CONC, async ({ itemIndex, trialIndex, item }) => {
+ const result = await processItemTrial(item, itemIndex, trialIndex);
+ return normalizeTrialResult(result, item, itemIndex, trialIndex);
}));
}
- // Final aggregation and output
const perItem = aggregatePerItem(allTrialResults, K_TRIALS);
const out = buildOutput(datasetName, items.length, limitedItems, allTrialResults, perItem);
@@ -522,7 +660,25 @@ async function runCalibration() {
return out;
}
-runCalibration().catch(err => {
- console.error('Calibration run failed:', err);
- process.exit(1);
-});
+module.exports = {
+ normalizeLabel,
+ parsePrediction,
+ judgePrediction,
+ aggregatePerItem,
+ classifyBands,
+ buildOutput,
+ serializeRate,
+ loadPartialProgress,
+ truncatePrompt,
+ buildCalibrationPrompt,
+ processItemTrial,
+ normalizeTrialResult,
+ runCalibration,
+};
+
+if (IS_CLI) {
+ runCalibration().catch(err => {
+ console.error('Calibration run failed:', err);
+ process.exit(1);
+ });
+}
diff --git a/evals/run-objective.js b/evals/run-objective.js
new file mode 100755
index 0000000..3c12c66
--- /dev/null
+++ b/evals/run-objective.js
@@ -0,0 +1,182 @@
+#!/usr/bin/env node
+'use strict';
+
+/**
+ * Generic paired objective engine.
+ *
+ * Supports fixture/no-model mode and dataset/scorer registry-style inputs.
+ * Legacy specialized runners remain until Phase 6 parity cleanup.
+ *
+ * Usage:
+ * node evals/run-objective.js --fixture path/to/fixture.json
+ * FIXTURE=1 node evals/run-objective.js --dataset path.jsonl --scorer boolean --arms none,skill
+ *
+ * Fixture JSON shape:
+ * {
+ * "study_id", "study_version", "preregistration_sha256",
+ * "dataset": { source, version, split, sha256 },
+ * "solver": { model, effort },
+ * "scorer": "boolean",
+ * "arms": [{ "id": "none" }, { "id": "skill", "skillContent": "..." }],
+ * "items": [{ "id", "prompt", "label"|..., "fixture_responses": { "none": "ANSWER: Yes", ... } }],
+ * "trials": 1
+ * }
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { sha256 } = require('./lib/result');
+const { runObjectiveItems, SCORERS } = require('./lib/objective');
+const { executeDroid, usageSummary } = require('./lib/droid');
+const { normalizeCondition } = require('./lib/conditions');
+
+function usage(code = 0) {
+ const msg = `Usage:
+ node evals/run-objective.js --fixture <file.json>
+ node evals/run-objective.js --dataset <file.jsonl> --scorer <name> [--arms none,skill] [--out file]
+
+Environment:
+ FIXTURE=1 require fixture_responses; never call a model
+ SOLVER_MODEL recorded solver model id (default fixture-model)
+ SOLVER_EFFORT recorded effort
+ LIMIT max dataset items
+ OUTFILE / --out write envelope JSON
+`;
+ if (code) console.error(msg);
+ else console.log(msg);
+ process.exit(code);
+}
+
+function parseArgs(argv) {
+ const out = { arms: null, dataset: null, fixture: null, scorer: null, out: null, trials: 1 };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--help' || a === '-h') usage(0);
+ else if (a === '--fixture') out.fixture = argv[++i];
+ else if (a === '--dataset') out.dataset = argv[++i];
+ else if (a === '--scorer') out.scorer = argv[++i];
+ else if (a === '--arms') out.arms = argv[++i];
+ else if (a === '--out') out.out = argv[++i];
+ else if (a === '--trials') out.trials = parseInt(argv[++i], 10);
+ else if (a.startsWith('-')) {
+ console.error(`unknown flag: ${a}`);
+ usage(1);
+ }
+ }
+ return out;
+}
+
+function loadJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function loadJsonl(file) {
+ return fs.readFileSync(file, 'utf8')
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line));
+}
+
+function datasetShaFromItems(items, sourcePath) {
+ return sha256({ source: sourcePath, items: items.map((it) => it.id || it.item_id) });
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const fixtureMode = process.env.FIXTURE === '1' || Boolean(args.fixture);
+
+ let study;
+ if (args.fixture) {
+ study = loadJson(path.resolve(args.fixture));
+ } else if (args.dataset) {
+ const datasetPath = path.resolve(args.dataset);
+ let items = loadJsonl(datasetPath);
+ if (process.env.LIMIT) items = items.slice(0, parseInt(process.env.LIMIT, 10));
+ const scorer = args.scorer || process.env.SCORER;
+ if (!scorer || !SCORERS[String(scorer).toLowerCase().replace(/-/g, '_')]) {
+ console.error(`scorer required and must be one of: ${Object.keys(SCORERS).join(', ')}`);
+ process.exit(1);
+ }
+ const armIds = (args.arms || process.env.ARMS || 'none').split(',').map((s) => s.trim()).filter(Boolean);
+ study = {
+ study_id: process.env.STUDY_ID || 'objective-adhoc',
+ study_version: process.env.STUDY_VERSION || '0',
+ preregistration_sha256: process.env.PREREG_SHA256 || sha256('adhoc'),
+ dataset: {
+ source: datasetPath,
+ version: process.env.DATASET_VERSION || '0',
+ split: process.env.DATASET_SPLIT || 'adhoc',
+ sha256: datasetShaFromItems(items, datasetPath),
+ },
+ solver: {
+ model: process.env.SOLVER_MODEL || 'fixture-model',
+ effort: process.env.SOLVER_EFFORT || null,
+ },
+ scorer,
+ arms: armIds.map((id) => ({ id: normalizeCondition(id) === 'none' ? 'none' : id })),
+ items,
+ trials: args.trials || 1,
+ };
+ } else {
+ usage(1);
+ }
+
+ const liveSolve = fixtureMode
+ ? null
+ : async ({ prompt }) => {
+ const model = (study.solver && study.solver.model) || process.env.SOLVER_MODEL;
+ const result = await executeDroid({
+ model,
+ effort: (study.solver && study.solver.effort) || process.env.SOLVER_EFFORT,
+ prompt,
+ timeoutMs: parseInt(process.env.DROID_TIMEOUT_MS || '180000', 10),
+ attempts: parseInt(process.env.DROID_ATTEMPTS || '3', 10),
+ });
+ const normalized = usageSummary(result.usage, model);
+ return {
+ ...result,
+ usage: {
+ ...normalized,
+ calls: result.attempts,
+ latency_ms: result.durationMs || 0,
+ estimated_cost_usd: normalized.est_cost_usd,
+ },
+ };
+ };
+
+ const envelope = await runObjectiveItems({
+ studyId: study.study_id || study.studyId,
+ studyVersion: study.study_version || study.studyVersion || '1',
+ preregistrationSha256: study.preregistration_sha256 || study.preregistrationSha256,
+ dataset: study.dataset,
+ arms: study.arms,
+ solver: study.solver || { model: 'fixture-model' },
+ items: study.items,
+ trials: study.trials || 1,
+ scorer: study.scorer,
+ scorerOptions: study.scorerOptions || {},
+ judges: study.judges || [],
+ fixtureMode,
+ solve: liveSolve,
+ createdAt: study.created_at,
+ statistics: study.statistics,
+ });
+
+ const outPath = args.out || process.env.OUTFILE;
+ if (outPath) {
+ fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });
+ fs.writeFileSync(outPath, `${JSON.stringify(envelope, null, 2)}\n`, 'utf8');
+ console.log(`wrote ${outPath}`);
+ } else {
+ process.stdout.write(`${JSON.stringify(envelope, null, 2)}\n`);
+ }
+
+ const h = envelope.health;
+ console.error(`objective: attempted=${h.attempted} completed=${h.completed} scored=${h.scored} failures=${h.failures} eligible=${h.decision_eligible}`);
+}
+
+main().catch((err) => {
+ console.error(err && err.stack ? err.stack : err);
+ process.exit(1);
+});
diff --git a/evals/run-pairwise.js b/evals/run-pairwise.js
new file mode 100755
index 0000000..fe9b599
--- /dev/null
+++ b/evals/run-pairwise.js
@@ -0,0 +1,342 @@
+#!/usr/bin/env node
+'use strict';
+
+/**
+ * Generic blind pairwise engine CLI.
+ *
+ * Foundation phase: fixture / no-model mode only.
+ *
+ * Usage:
+ * node evals/run-pairwise.js --fixture path/to/fixture.json
+ * FIXTURE=1 node evals/run-pairwise.js --fixture path/to/fixture.json --out out.json
+ *
+ * Fixture JSON shape:
+ * {
+ * "study_id", "study_version", "preregistration_sha256",
+ * "dataset": { source, version, split, sha256 },
+ * "solver": { model, effort },
+ * "judges": ["gpt-5.5-pro", "gemini-3.1-pro-preview", "deepseek-v4-pro"],
+ * "arms": [{ "id": "none", "prompt_sha256"?: "..." }, { "id": "lean", ... }],
+ * "pair": { "left": "lean", "right": "none" },
+ * "seed": 0,
+ * "trials": 1,
+ * "items": [{
+ * "id", "prompt",
+ * "fixture_responses": { "none": "text...", "lean": "text..." },
+ * "fixture_judge": { "winner": "A"|"B"|"tie", "resolved": true } // optional override
+ * }]
+ * }
+ */
+
+const fs = require('fs');
+const path = require('path');
+const { sha256, validateResultEnvelope } = require('./lib/result');
+const { runPairwiseItems } = require('./lib/pairwise');
+const { panelModels } = require('./lib/judge');
+
+function usage(code = 0) {
+ const msg = `Usage:
+ node evals/run-pairwise.js --fixture <fixture.json> [--out file.json]
+ FIXTURE=1 node evals/run-pairwise.js --fixture <fixture.json>
+
+No live model calls in foundation phase. Provide fixture_responses per arm.
+`;
+ if (code) console.error(msg);
+ else console.log(msg);
+ process.exit(code);
+}
+
+function parseArgs(argv) {
+ const out = { fixture: null, out: null, trials: null, seed: null };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--help' || a === '-h') usage(0);
+ else if (a === '--fixture' && argv[i + 1]) out.fixture = argv[++i];
+ else if (a === '--out' && argv[i + 1]) out.out = argv[++i];
+ else if (a === '--trials' && argv[i + 1]) out.trials = parseInt(argv[++i], 10);
+ else if (a === '--seed' && argv[i + 1]) out.seed = argv[++i];
+ else if (a.startsWith('--')) {
+ console.error(`unknown flag: ${a}`);
+ usage(1);
+ }
+ }
+ return out;
+}
+
+function loadJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function fixtureSolve(study) {
+ return async function solve({ item, armId }) {
+ const table = item.fixture_responses || item.responses || {};
+ const entry = table[armId];
+ if (entry == null) {
+ return {
+ ok: false,
+ text: null,
+ failure: {
+ type: 'transport',
+ message: `fixture mode: missing fixture_responses for arm ${armId}`,
+ },
+ usage: { calls: 0 },
+ };
+ }
+ if (typeof entry === 'string') {
+ return { ok: true, text: entry, usage: { calls: 0, input_tokens: 0, output_tokens: 0 } };
+ }
+ return {
+ ok: entry.ok !== false,
+ text: entry.text != null ? entry.text : null,
+ usage: entry.usage || { calls: 0 },
+ failure: entry.failure || null,
+ durationMs: entry.durationMs || 0,
+ attempts: entry.attempts != null ? entry.attempts : 1,
+ };
+ };
+}
+
+/**
+ * Fixture judge: uses item.fixture_judge, study.fixture_judge, or a deterministic
+ * default that prefers arm A when responses differ in length (stable, no models).
+ */
+function fixtureJudge(study) {
+ return async function judge(prompt, judges) {
+ // Allow per-call override via a marker embedded only in tests; primary path is study items.
+ // The runner rebinds per item via closure below when items carry fixture_judge.
+ void prompt;
+ const models = Array.isArray(judges) && judges.length ? judges : panelModels();
+ const defaultWinner = study.fixture_judge && study.fixture_judge.winner
+ ? study.fixture_judge.winner
+ : 'A';
+ const resolved = study.fixture_judge && study.fixture_judge.resolved === false
+ ? false
+ : true;
+ if (!resolved) {
+ return {
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ failure: { type: 'judge_unresolved', message: 'fixture unresolved panel' },
+ tally: { A: 0, B: 0, tie: 0, missing: models.length },
+ votes: models.map(model => ({ model, winner: null, valid: false, failure: { type: 'parse', message: 'fixture missing' } })),
+ failures: [],
+ vocab_only: false,
+ whys: [],
+ judge_usage: [],
+ judge_durationMs: 0,
+ };
+ }
+ const winner = String(defaultWinner).toUpperCase() === 'B' ? 'B'
+ : String(defaultWinner).toUpperCase() === 'TIE' ? 'tie'
+ : 'A';
+ // Two matching valid votes for A/B; for tie inject resolved=true path used by pairwise normalize.
+ if (winner === 'tie') {
+ return {
+ winner: 'tie',
+ resolved: true,
+ unresolved: false,
+ failure: null,
+ tally: { A: 0, B: 0, tie: models.length, missing: 0 },
+ votes: models.map(model => ({ model, winner: 'tie', valid: true, failure: null })),
+ failures: [],
+ vocab_only: false,
+ whys: ['fixture tie'],
+ judge_usage: [],
+ judge_durationMs: 0,
+ };
+ }
+ return {
+ winner,
+ resolved: true,
+ unresolved: false,
+ failure: null,
+ tally: {
+ A: winner === 'A' ? Math.max(2, models.length) : 0,
+ B: winner === 'B' ? Math.max(2, models.length) : 0,
+ tie: 0,
+ missing: 0,
+ },
+ votes: models.map(model => ({ model, winner, valid: true, failure: null })),
+ failures: [],
+ vocab_only: false,
+ whys: [`fixture winner ${winner}`],
+ judge_usage: [],
+ judge_durationMs: 0,
+ };
+ };
+}
+
+/**
+ * Wrap fixture judge so per-item fixture_judge overrides study default.
+ * We recover the item id from the judge prompt PROBLEM section when present,
+ * else fall back to sequential consumption of items list.
+ */
+function makeItemAwareJudge(study, baseJudge) {
+ const byId = new Map();
+ for (const item of study.items || []) {
+ const id = item.id || item.item_id;
+ if (id != null && item.fixture_judge) byId.set(String(id), item.fixture_judge);
+ }
+ if (byId.size === 0) return baseJudge;
+
+ return async function judge(prompt, judges) {
+ // Prefer explicit id tag if buildJudgePrompt embeds it; else scan prompt for item prompts.
+ let override = null;
+ const idMatch = String(prompt).match(/\[item_id=([^\]]+)\]/);
+ if (idMatch && byId.has(idMatch[1])) override = byId.get(idMatch[1]);
+ if (!override) {
+ for (const item of study.items || []) {
+ const id = String(item.id || item.item_id || '');
+ const text = item.prompt || item.problem || item.text || '';
+ if (text && String(prompt).includes(text) && byId.has(id)) {
+ override = byId.get(id);
+ break;
+ }
+ }
+ }
+ if (!override) return baseJudge(prompt, judges);
+
+ const models = Array.isArray(judges) && judges.length ? judges : panelModels();
+ if (override.resolved === false || override.unresolved === true) {
+ return {
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ failure: override.failure || { type: 'judge_unresolved', message: 'fixture unresolved panel' },
+ tally: override.tally || { A: 0, B: 0, tie: 0, missing: models.length },
+ votes: override.votes || models.map(model => ({ model, winner: null, valid: false })),
+ failures: override.failures || [],
+ vocab_only: !!override.vocab_only,
+ whys: override.whys || [],
+ judge_usage: override.judge_usage || [],
+ judge_durationMs: override.judge_durationMs || 0,
+ };
+ }
+ const winnerRaw = override.winner == null ? 'A' : String(override.winner);
+ const upper = winnerRaw.toUpperCase();
+ const winner = upper === 'B' ? 'B' : upper === 'TIE' ? 'tie' : 'A';
+ return {
+ winner,
+ resolved: true,
+ unresolved: false,
+ failure: null,
+ tally: override.tally || {
+ A: winner === 'A' ? 2 : 0,
+ B: winner === 'B' ? 2 : 0,
+ tie: winner === 'tie' ? 2 : 0,
+ missing: 0,
+ },
+ votes: override.votes || models.map(model => ({ model, winner, valid: true, failure: null })),
+ failures: [],
+ vocab_only: !!override.vocab_only,
+ whys: override.whys || [`fixture winner ${winner}`],
+ judge_usage: override.judge_usage || [],
+ judge_durationMs: override.judge_durationMs || 0,
+ };
+ };
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const fixtureMode = process.env.FIXTURE === '1' || Boolean(args.fixture) || process.env.PAIRWISE_FIXTURE === '1';
+
+ if (!args.fixture) usage(1);
+ const study = loadJson(path.resolve(args.fixture));
+
+ if (!fixtureMode) {
+ console.error('run-pairwise: foundation phase requires fixture mode (--fixture / FIXTURE=1)');
+ process.exit(1);
+ }
+
+ const items = study.items || [];
+ const missing = items.some(it => !it.fixture_responses && !it.responses);
+ if (missing) {
+ console.error('run-pairwise: each item needs fixture_responses for both arms');
+ process.exit(1);
+ }
+
+ const arms = (study.arms || []).map(a => ({
+ id: a.id,
+ prompt_sha256: a.prompt_sha256 || sha256(a.id),
+ skill_sha256: a.skill_sha256 != null ? a.skill_sha256 : null,
+ }));
+ if (arms.length < 2) {
+ console.error('run-pairwise: fixture needs at least two arms');
+ process.exit(1);
+ }
+
+ const pair = study.pair || { left: arms[0].id, right: arms[1].id };
+ const judges = study.judges || panelModels();
+ const baseJudge = fixtureJudge(study);
+ const judge = makeItemAwareJudge(study, baseJudge);
+
+ const envelope = await runPairwiseItems({
+ studyId: study.study_id || study.studyId,
+ studyVersion: study.study_version || study.studyVersion || '1',
+ preregistrationSha256: study.preregistration_sha256 || study.preregistrationSha256 || sha256('adhoc'),
+ dataset: study.dataset || {
+ source: 'fixture',
+ version: '0',
+ split: 'fixture',
+ sha256: sha256((items).map(it => it.id || it.item_id)),
+ },
+ arms,
+ pair,
+ solver: study.solver || { model: 'fixture-model', effort: null },
+ judges,
+ items,
+ trials: args.trials || study.trials || 1,
+ seed: args.seed != null ? args.seed : (study.seed != null ? study.seed : 0),
+ solve: fixtureSolve(study),
+ judge,
+ buildJudgePrompt: ({ item, responseA, responseB }) => {
+ const problem = item.prompt || item.problem || item.text || '';
+ const id = item.id || item.item_id || '';
+ return [
+ `Pairwise fixture judge [item_id=${id}]`,
+ '',
+ '=== PROBLEM ===',
+ problem,
+ '',
+ '=== RESPONSE A ===',
+ responseA,
+ '',
+ '=== RESPONSE B ===',
+ responseB,
+ '',
+ '=== END ===',
+ ].join('\n');
+ },
+ createdAt: study.created_at,
+ retainResponseText: study.retain_response_text === true,
+ });
+
+ const validation = validateResultEnvelope(envelope);
+ if (!validation.ok) {
+ console.error('run-pairwise: envelope validation failed:\n' + validation.errors.join('\n'));
+ process.exit(2);
+ }
+
+ const outPath = args.out || process.env.OUTFILE;
+ if (outPath) {
+ fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });
+ fs.writeFileSync(outPath, `${JSON.stringify(envelope, null, 2)}\n`, 'utf8');
+ console.log(`wrote ${outPath}`);
+ } else {
+ process.stdout.write(`${JSON.stringify(envelope, null, 2)}\n`);
+ }
+
+ const h = envelope.health;
+ const s = envelope.statistics || {};
+ console.error(
+ `pairwise: attempted=${h.attempted} completed=${h.completed} parsed=${h.parsed} scored=${h.scored} ` +
+ `failures=${h.failures} eligible=${h.decision_eligible} ` +
+ `W/L/T=${s.wins || 0}/${s.losses || 0}/${s.ties || 0}`
+ );
+}
+
+main().catch((err) => {
+ console.error(err && err.stack ? err.stack : err);
+ process.exit(1);
+});
diff --git a/evals/run-replication.js b/evals/run-replication.js
old mode 100644
new mode 100755
index 2152432..01ab68c
--- a/evals/run-replication.js
+++ b/evals/run-replication.js
@@ -24,7 +24,7 @@
const fs = require('fs');
const path = require('path');
-const { mcnemarMidp, pairedDiff } = require('./lib/stats');
+const { mcnemarMidp, meanPairedRiskDiff, clusterBootstrapPairedRiskDiff } = require('./lib/stats');
/** Verdict taxonomy (must match architecture.md) */
const VERDICT = {
@@ -107,6 +107,86 @@ function passesThreshold(s) {
s.p_value < 0.05;
}
+/**
+ * Aggregate JSONL rows into one sample summary.
+ * Supports:
+ * - pre-aggregated rows with delta_pp + p_value
+ * - paired binary rows with treatment/control or skill_correct/placebo_correct
+ * Never silently drops unparseable lines — they count as failures.
+ */
+function aggregateJsonlRows(results) {
+ if (!results || results.length === 0) {
+ return { delta_pp: 0, p_value: 1, n: 0, failures: 0, rows: 0 };
+ }
+
+ // Path A: rows already carry delta_pp (and optionally p)
+ const withDelta = results.filter(r => r && typeof r.delta_pp === 'number');
+ if (withDelta.length === results.length) {
+ const n = withDelta.length;
+ const meanDelta = withDelta.reduce((s, r) => s + r.delta_pp, 0) / n;
+ // Prefer min p (most conservative) when multiple p-values present; else 1
+ const ps = withDelta.map(r => r.p_value ?? r.p ?? r.mcnemar_p).filter(p => typeof p === 'number');
+ const p_value = ps.length ? Math.max(...ps) : 1;
+ const nField = withDelta.reduce((s, r) => s + (typeof r.n === 'number' ? r.n : 1), 0);
+ return {
+ delta_pp: +meanDelta.toFixed(6),
+ p_value,
+ n: nField,
+ rows: n,
+ failures: 0,
+ aggregation: 'mean_delta_pp',
+ };
+ }
+
+ // Path B: paired binary observations
+ const obs = [];
+ let failures = 0;
+ for (const r of results) {
+ if (!r || typeof r !== 'object') { failures++; continue; }
+ let t = r.treatment ?? r.skill_correct ?? r.skill ?? r.lean;
+ let c = r.control ?? r.placebo_correct ?? r.placebo ?? r.none;
+ if (typeof t === 'boolean') t = t ? 1 : 0;
+ if (typeof c === 'boolean') c = c ? 1 : 0;
+ if (typeof t !== 'number' || typeof c !== 'number' || !Number.isFinite(t) || !Number.isFinite(c)) {
+ failures++;
+ continue;
+ }
+ obs.push({
+ treatment: t,
+ control: c,
+ item_id: r.item_id || r.id,
+ leakage_family: r.leakage_family || r.cluster_id,
+ });
+ }
+
+ if (obs.length === 0) {
+ return { delta_pp: 0, p_value: 1, n: 0, failures, rows: results.length, aggregation: 'empty' };
+ }
+
+ const rd = meanPairedRiskDiff(obs);
+ let b = 0, cCount = 0;
+ for (const o of obs) {
+ const t = Number(o.treatment) ? 1 : 0;
+ const ctrl = Number(o.control) ? 1 : 0;
+ if (t === 1 && ctrl === 0) b++;
+ else if (t === 0 && ctrl === 1) cCount++;
+ }
+ const p_value = mcnemarMidp(b, cCount);
+ // Optional bootstrap CI kept for diagnostics (deterministic seed)
+ const boot = clusterBootstrapPairedRiskDiff(obs, { seed: 1, resamples: 200 });
+
+ return {
+ delta_pp: +(rd * 100).toFixed(6),
+ p_value,
+ n: obs.length,
+ rows: results.length,
+ failures,
+ discordant: { b, c: cCount },
+ bootstrap_ci: boot.ci,
+ aggregation: 'paired_binary',
+ };
+}
+
/**
* Parse a result file, accepting both pretty-JSON (objective-runner schema
* with delta_pp / mcnemar_p / significant) and JSONL (one object per line).
@@ -116,48 +196,60 @@ function passesThreshold(s) {
*
* JSONL schema (paired experiment runners):
* { delta_pp, p_value, direction, n, ... } per line
+ * OR { treatment, control } / { skill_correct, placebo_correct } per line
*
* Returns normalized { delta_pp, p_value, n } or null if unparseable/empty.
*/
function parseResultsFile(filePath) {
const text = fs.readFileSync(filePath, 'utf8').trim();
+ if (!text) return null;
// Try pretty-JSON first (single object with delta_pp / mcnemar_p / significant)
try {
const obj = JSON.parse(text);
- if (typeof obj === 'object' && obj !== null && typeof obj.delta_pp === 'number') {
+ if (typeof obj === 'object' && obj !== null && !Array.isArray(obj) && typeof obj.delta_pp === 'number') {
const p_value = obj.mcnemar_p ?? obj.p_value ?? null;
if (p_value !== null) {
return {
delta_pp: obj.delta_pp,
p_value,
n: obj.n ?? null,
+ aggregation: 'pretty_json',
};
}
}
+ // Array of objects
+ if (Array.isArray(obj)) {
+ return aggregateJsonlRows(obj);
+ }
} catch (e) {
// Not valid JSON — fall through to JSONL
}
// Try JSONL (one JSON object per line)
const lines = text.split('\n').filter(l => l.trim());
- const results = lines.map((line, i) => {
- try { return JSON.parse(line); } catch (e) {
- throw new Error(`Invalid JSONL at line ${i + 1}: ${e.message}`);
+ const results = [];
+ const parseFailures = [];
+ lines.forEach((line, i) => {
+ try {
+ results.push(JSON.parse(line));
+ } catch (e) {
+ parseFailures.push({ line: i + 1, message: e.message });
}
});
+ if (results.length === 0 && parseFailures.length > 0) {
+ throw new Error(`Invalid JSONL: ${parseFailures.length} unparseable line(s); first: line ${parseFailures[0].line}: ${parseFailures[0].message}`);
+ }
+
if (results.length === 0) return null;
- // Aggregate: use mean delta_pp, combined p-value via paired stats
- // For simplicity, take the first result's paired test result
- // (in practice, this would aggregate across items)
- const first = results[0];
- return {
- delta_pp: first.delta_pp ?? 0,
- p_value: first.p_value ?? first.mcnemar_p ?? 1,
- n: first.n ?? results.length,
- };
+ const agg = aggregateJsonlRows(results);
+ if (parseFailures.length) {
+ agg.failures = (agg.failures || 0) + parseFailures.length;
+ agg.parse_failures = parseFailures.length;
+ }
+ return agg;
}
/** CLI entry point */
@@ -177,6 +269,8 @@ async function main() {
const v = verdict({ primary, replication });
console.log(`VERDICT: ${v}`);
+ if (primary) console.log(`primary: delta_pp=${primary.delta_pp} p=${primary.p_value} n=${primary.n}`);
+ if (replication) console.log(`replication: delta_pp=${replication.delta_pp} p=${replication.p_value} n=${replication.n}`);
// Exit non-zero for non-ELEVATE verdicts (guardrail enforcement)
if (v !== VERDICT.ELEVATE) {
@@ -184,7 +278,14 @@ async function main() {
}
}
-module.exports = { verdict, VERDICT, parseResultsFile, passesThreshold, normalizeSample };
+module.exports = {
+ verdict,
+ VERDICT,
+ parseResultsFile,
+ passesThreshold,
+ normalizeSample,
+ aggregateJsonlRows,
+};
if (require.main === module) {
main().catch(e => { console.error(e); process.exit(1); });
diff --git a/evals/studies/registry.json b/evals/studies/registry.json
new file mode 100644
index 0000000..7c8cb84
--- /dev/null
+++ b/evals/studies/registry.json
@@ -0,0 +1,3167 @@
+{
+ "schema_version": 1,
+ "registry_version": "phase1-baseline-v1",
+ "generated_note": "Executable study/catalog registry for Phase 1 measurement foundation. Baseline expects 39 skills; cutover target is 28 survivors with disable-model-invocation.",
+ "catalog": {
+ "baseline_count": 39,
+ "cutover_count": 28,
+ "current_phase": "baseline",
+ "expected_count": 39,
+ "expected_dirs": [
+ "thinking-archetypes",
+ "thinking-bayesian",
+ "thinking-bounded-rationality",
+ "thinking-circle-of-competence",
+ "thinking-cynefin",
+ "thinking-debiasing",
+ "thinking-dual-process",
+ "thinking-effectuation",
+ "thinking-feedback-loops",
+ "thinking-fermi-estimation",
+ "thinking-first-principles",
+ "thinking-five-whys-plus",
+ "thinking-inversion",
+ "thinking-jobs-to-be-done",
+ "thinking-kepner-tregoe",
+ "thinking-leverage-points",
+ "thinking-lindy-effect",
+ "thinking-map-territory",
+ "thinking-margin-of-safety",
+ "thinking-model-combination",
+ "thinking-model-router",
+ "thinking-model-selection",
+ "thinking-occams-razor",
+ "thinking-ooda",
+ "thinking-opportunity-cost",
+ "thinking-pre-mortem",
+ "thinking-probabilistic",
+ "thinking-red-team",
+ "thinking-regret-minimization",
+ "thinking-reversibility",
+ "thinking-scientific-method",
+ "thinking-second-order",
+ "thinking-socratic",
+ "thinking-steel-manning",
+ "thinking-systems",
+ "thinking-theory-of-constraints",
+ "thinking-thought-experiment",
+ "thinking-triz",
+ "thinking-via-negativa"
+ ],
+ "survivors": [
+ "bounded-rationality",
+ "circle-of-competence",
+ "cynefin",
+ "effectuation",
+ "first-principles",
+ "five-whys-plus",
+ "jobs-to-be-done",
+ "kepner-tregoe",
+ "lindy-effect",
+ "map-territory",
+ "margin-of-safety",
+ "model-combination",
+ "model-router",
+ "ooda",
+ "opportunity-cost",
+ "pre-mortem",
+ "probabilistic",
+ "red-team",
+ "reversibility",
+ "scientific-method",
+ "second-order",
+ "socratic",
+ "steel-manning",
+ "systems",
+ "theory-of-constraints",
+ "thought-experiment",
+ "triz",
+ "via-negativa"
+ ],
+ "deletions": [
+ "archetypes",
+ "bayesian",
+ "debiasing",
+ "dual-process",
+ "feedback-loops",
+ "fermi-estimation",
+ "inversion",
+ "leverage-points",
+ "model-selection",
+ "occams-razor",
+ "regret-minimization"
+ ],
+ "survivor_budgets": {
+ "bounded-rationality": 450,
+ "circle-of-competence": 450,
+ "cynefin": 450,
+ "effectuation": 700,
+ "first-principles": 500,
+ "five-whys-plus": 550,
+ "jobs-to-be-done": 700,
+ "kepner-tregoe": 700,
+ "lindy-effect": 400,
+ "map-territory": 550,
+ "margin-of-safety": 650,
+ "model-combination": 750,
+ "model-router": 900,
+ "ooda": 550,
+ "opportunity-cost": 600,
+ "pre-mortem": 700,
+ "probabilistic": 800,
+ "red-team": 800,
+ "reversibility": 550,
+ "scientific-method": 900,
+ "second-order": 550,
+ "socratic": 650,
+ "steel-manning": 650,
+ "systems": 950,
+ "theory-of-constraints": 750,
+ "thought-experiment": 650,
+ "triz": 700,
+ "via-negativa": 450
+ }
+ },
+ "models": {
+ "small": "claude-haiku-4-5-20251001",
+ "mid": "claude-sonnet-4-6",
+ "frontier": "claude-opus-4-8",
+ "screening": [
+ "claude-haiku-4-5-20251001",
+ "claude-opus-4-8"
+ ],
+ "deployment": [
+ "claude-haiku-4-5-20251001",
+ "claude-sonnet-4-6",
+ "claude-opus-4-8"
+ ]
+ },
+ "judge_panel": {
+ "models": [
+ "gpt-5.5-pro",
+ "gemini-3.1-pro-preview",
+ "deepseek-v4-pro"
+ ],
+ "panel_size": 3,
+ "votes_per_judge": 1,
+ "max_votes_per_item": 3,
+ "min_valid_votes_to_decide": 2,
+ "matching_valid_votes_to_decide": 2,
+ "unresolved_on_three_way_disagreement": true,
+ "never_same_family_fallback": true,
+ "exclude_solver_family": true,
+ "calibration": {
+ "min_pairs": 30,
+ "panel_majority_accuracy_min": 0.85,
+ "per_judge_accuracy_min": 0.75,
+ "fleiss_kappa_min": 0.6,
+ "order_verbosity_delta_max_pp": 5,
+ "missing_votes_max": 0.01
+ },
+ "calibration_status": "blocked_missing_human_labels",
+ "decision_eligible": false,
+ "calibration_study_id": "judge-panel-calibration",
+ "judged_studies_policy_while_blocked": "manual_only",
+ "human_labeled_pairs": {
+ "count": 0,
+ "path": null,
+ "note": "No existing fixed human-labeled 30-pair judge calibration set found. Do not fabricate pairs or run models."
+ }
+ },
+ "arms": {
+ "primary": [
+ "none",
+ "full_legacy",
+ "lean"
+ ],
+ "diagnostic": [
+ "equal_budget_placebo",
+ "wrong_neighbor"
+ ],
+ "conditional": [
+ "workflow"
+ ],
+ "all": [
+ "none",
+ "full_legacy",
+ "lean",
+ "equal_budget_placebo",
+ "wrong_neighbor",
+ "workflow"
+ ],
+ "descriptions": {
+ "none": "production request with no skill body",
+ "full_legacy": "frozen pre-cutover skill body",
+ "lean": "rewritten survivor",
+ "equal_budget_placebo": "secondary diagnostic equal-budget inert padding only",
+ "wrong_neighbor": "plausible incorrect skill for harm/overuse",
+ "workflow": "workflow engine arm; only after corrected engine exists"
+ }
+ },
+ "gates": {
+ "utility_margin_pp": 5,
+ "noninferiority_margin_pp": 3,
+ "harm_margin_pp": 2,
+ "lean_input_token_ratio_max": 0.7,
+ "lean_calls_output_latency_cost_margin": 0.1,
+ "efficacy_hypotheses": 84,
+ "alpha_one_sided": 0.05,
+ "power_target": 0.9,
+ "bootstrap_resamples": 10000,
+ "confirmatory_completeness": 1,
+ "directional_zone_pp": [
+ 3,
+ 5
+ ]
+ },
+ "required_skill_sections": [
+ "When to Use",
+ "When NOT to Use",
+ "Procedure",
+ "Output",
+ "Verification"
+ ],
+ "frontmatter": {
+ "description_max_chars": 200
+ },
+ "data_adequacy": {
+ "policy": "unknown_or_inadequate_is_explicit",
+ "inadequate_skill_ids": [
+ "first-principles",
+ "second-order",
+ "theory-of-constraints"
+ ],
+ "unknown_skill_ids": [
+ "archetypes",
+ "bayesian",
+ "bounded-rationality",
+ "circle-of-competence",
+ "debiasing",
+ "dual-process",
+ "effectuation",
+ "feedback-loops",
+ "fermi-estimation",
+ "jobs-to-be-done",
+ "leverage-points",
+ "lindy-effect",
+ "model-combination",
+ "model-router",
+ "model-selection",
+ "ooda",
+ "opportunity-cost",
+ "probabilistic",
+ "regret-minimization",
+ "steel-manning",
+ "systems",
+ "thought-experiment",
+ "triz",
+ "via-negativa"
+ ],
+ "adequate_skill_ids": [
+ "cynefin",
+ "five-whys-plus",
+ "inversion",
+ "kepner-tregoe",
+ "map-territory",
+ "margin-of-safety",
+ "occams-razor",
+ "pre-mortem",
+ "red-team",
+ "reversibility",
+ "scientific-method",
+ "socratic"
+ ]
+ },
+ "skills": {
+ "archetypes": {
+ "id": "archetypes",
+ "dir": "thinking-archetypes",
+ "contract_path": "evals/contracts/thinking-archetypes.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "archetype_match_accuracy",
+ "intervention_appropriateness"
+ ],
+ "eval_family": "Systems/product/strategy pairwise",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Novel problems with no historical precedent; one-off incidents without recurring structure; systems too simple to exhibit archetypal behavior; meta-questions about system archetypes",
+ "description": "Items where the recurring pattern library doesn't apply — genuinely novel dynamics or trivially simple systems"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "systems"
+ ],
+ "mechanism": "recurring cross-domain structure/pattern check",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "bayesian": {
+ "id": "bayesian",
+ "dir": "thinking-bayesian",
+ "contract_path": "evals/contracts/thinking-bayesian.json",
+ "primary_value_surface": "calibrated classification",
+ "primary_metric": "posterior_calibration_error",
+ "secondary_metrics": [
+ "prior_elicitation_quality",
+ "likelihood_assessment_accuracy",
+ "update_correctness",
+ "base_rate_adherence"
+ ],
+ "eval_family": "Quantitative/uncertainty",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND posterior_calibration_error < 0.10",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR base_rate_adherence < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Questions with definitive answers; situations with no meaningful prior; meta-questions about Bayesian reasoning",
+ "description": "Items where probability estimation adds no value over direct knowledge or where priors cannot be meaningfully established"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "probabilistic"
+ ],
+ "mechanism": "prior → likelihood → posterior update",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "bounded-rationality": {
+ "id": "bounded-rationality",
+ "dir": "thinking-bounded-rationality",
+ "contract_path": "evals/contracts/thinking-bounded-rationality.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "satisficing_threshold_quality",
+ "good_enough_identification"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions where optimization is feasible and warranted; situations with clear stopping criteria; time-unconstrained analysis; meta-questions about bounded rationality",
+ "description": "Items where the constraints don't bind — you have time, information, and computational capacity to find the true optimum"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 450,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 450,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "circle-of-competence": {
+ "id": "circle-of-competence",
+ "dir": "thinking-circle-of-competence",
+ "contract_path": "evals/contracts/thinking-circle-of-competence.json",
+ "primary_value_surface": "abstention/calibration",
+ "primary_metric": "abstention_accuracy",
+ "secondary_metrics": [
+ "calibration_error",
+ "overconfidence_reduction",
+ "zone_classification_accuracy",
+ "fetch_before_assert_rate"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.3,
+ 0.8
+ ],
+ "min_sample_primary": 70,
+ "min_sample_replication": 70,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND calibration_error_reduction >= 0.05",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR overconfidence_reduction < 0",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.80"
+ },
+ "distractors": {
+ "off_target_set": "Questions with verifiable grounded answers; low-stakes reversible decisions where guessing is acceptable; brainstorming/hypothetical framing; meta-questions about circle of competence",
+ "description": "Items where the answer is checkable, stakes are low, or the framing explicitly invites speculation"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 450,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 450,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "cynefin": {
+ "id": "cynefin",
+ "dir": "thinking-cynefin",
+ "contract_path": "evals/contracts/thinking-cynefin.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "domain_classification_accuracy",
+ "secondary_metrics": [
+ "approach_match_quality",
+ "confidence_calibration",
+ "boundary_case_handling"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR approach_match_quality < 0.60",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems with obvious domain classification; situations where Cynefin adds no actionable distinction; meta-questions about Cynefin framework itself",
+ "description": "Items where domain is unambiguous or where the framework provides no decision leverage"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 450,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 450,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/cynefin-classify.jsonl",
+ "sha256": "8b4fda79c0952b97ec184cfb4bcf7fc53ceb5384a8fdf4b4683d2fec2dff723b"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-cynefin.jsonl",
+ "sha256": "bdd4e4b2eea6411e9ea4d9422f630817a5fe795833c6bad6844c17bd7ef05774"
+ }
+ ],
+ "row_counts": {
+ "n": 84,
+ "splits": {
+ "dev": 21,
+ "heldout": 30,
+ "replication": 33,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "debiasing": {
+ "id": "debiasing",
+ "dir": "thinking-debiasing",
+ "contract_path": "evals/contracts/thinking-debiasing.json",
+ "primary_value_surface": "calibrated classification",
+ "primary_metric": "bias_detection_accuracy",
+ "secondary_metrics": [
+ "calibration_improvement",
+ "base_rate_adherence",
+ "anchoring_resistance",
+ "confirmation_bias_mitigation"
+ ],
+ "eval_family": "Quantitative/uncertainty",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND calibration_improvement >= 0.02",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR base_rate_adherence < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions with no identifiable bias risk; situations where the bias is already corrected by process; meta-questions about debiasing techniques",
+ "description": "Items where cognitive biases are not a meaningful threat to decision quality, or where the decision process already neutralizes them"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "probabilistic",
+ "steel-manning"
+ ],
+ "mechanism": "base-rate/alternative check; strongest-countercase check",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "dual-process": {
+ "id": "dual-process",
+ "dir": "thinking-dual-process",
+ "contract_path": "evals/contracts/thinking-dual-process.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "system1_system2_discrimination",
+ "override_appropriateness"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions where intuition is known reliable; situations where deliberation is clearly superior; time-critical decisions requiring immediate System 1 response; meta-questions about dual-process theory",
+ "description": "Items where the System 1/System 2 distinction adds no value — either intuition is clearly appropriate, or deliberation is clearly required"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [],
+ "mechanism": "human cognition taxonomy has no distinct agent procedure",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "effectuation": {
+ "id": "effectuation",
+ "dir": "thinking-effectuation",
+ "contract_path": "evals/contracts/thinking-effectuation.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "means_inventory_completeness",
+ "affordable_loss_calibration"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Goals with clear paths and predictable outcomes; mature markets with established playbooks; optimization problems with known variables; meta-questions about effectuation",
+ "description": "Items where the future is predictable enough for causal planning, and effectuation's means-driven approach adds no value"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 700,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 700,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "feedback-loops": {
+ "id": "feedback-loops",
+ "dir": "thinking-feedback-loops",
+ "contract_path": "evals/contracts/thinking-feedback-loops.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "loop_identification_accuracy",
+ "delay_recognition"
+ ],
+ "eval_family": "Systems/product/strategy pairwise",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Open-loop systems; simple cause-effect chains without feedback; situations where behavior is driven by exogenous inputs only; meta-questions about feedback loops",
+ "description": "Items where no feedback structure exists, or where the system behavior is purely feedforward"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "systems"
+ ],
+ "mechanism": "reinforcing/balancing loop and delay check",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "fermi-estimation": {
+ "id": "fermi-estimation",
+ "dir": "thinking-fermi-estimation",
+ "contract_path": "evals/contracts/thinking-fermi-estimation.json",
+ "primary_value_surface": "objective correctness",
+ "primary_metric": "estimation_accuracy_log_error",
+ "secondary_metrics": [
+ "decomposition_quality",
+ "factor_independence",
+ "range_calibration",
+ "sanity_check_pass_rate"
+ ],
+ "eval_family": "Quantitative/uncertainty",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND log_error_reduction >= 0.20",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR decomposition_quality < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Quantities that are cheaply lookup-able; decisions requiring precision over order-of-magnitude; meta-questions about Fermi estimation",
+ "description": "Items where the real answer is a query away, or where precise values are needed rather than order-of-magnitude"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "probabilistic"
+ ],
+ "mechanism": "decomposition and order-of-magnitude bounds",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "first-principles": {
+ "id": "first-principles",
+ "dir": "thinking-first-principles",
+ "contract_path": "evals/contracts/thinking-first-principles.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "assumption_identification",
+ "fundamental_decomposition_quality"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems with established best practices; situations where convention is proven optimal; time-critical decisions requiring known solutions",
+ "description": "Items where first-principles decomposition is unnecessary because convention already provides the optimal approach"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 500,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 500,
+ "data": {
+ "status": "inadequate",
+ "gaps": [
+ "heldout_rows=9<20",
+ "replication_rows=0<10"
+ ],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/first-principles-constraint.jsonl",
+ "sha256": "4fc8dcfcacccce82a59b18fe6368c4de77e1a35f9c7ab343a4009c49102150f8"
+ }
+ ],
+ "row_counts": {
+ "n": 30,
+ "splits": {
+ "dev": 21,
+ "heldout": 9,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "five-whys-plus": {
+ "id": "five-whys-plus",
+ "dir": "thinking-five-whys-plus",
+ "contract_path": "evals/contracts/thinking-five-whys-plus.json",
+ "primary_value_surface": "localization",
+ "primary_metric": "fault_localization_accuracy",
+ "secondary_metrics": [
+ "root_cause_depth",
+ "bias_guard_effectiveness",
+ "counterfactual_test_quality",
+ "stop_condition_appropriateness"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR bias_guard_effectiveness < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Incidents with single obvious cause; situations where the proximate cause IS the root cause; postmortems where bias guards are not needed; meta-questions about the 5 Whys method",
+ "description": "Items where iterative why-asking adds no value or where the skill's bias guards are irrelevant"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 550,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 550,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/five-whys-root-cause.jsonl",
+ "sha256": "eda4c7747ff3a3992f4e50566556285cc17986cc2f266bb0823874ed816cb4fb"
+ }
+ ],
+ "row_counts": {
+ "n": 69,
+ "splits": {
+ "dev": 11,
+ "heldout": 29,
+ "replication": 29,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": [
+ "legacy-july-verdict-five-whys"
+ ]
+ },
+ "inversion": {
+ "id": "inversion",
+ "dir": "thinking-inversion",
+ "contract_path": "evals/contracts/thinking-inversion.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "failure_mode_coverage",
+ "avoidance_actionability"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems where failure modes are already well-known and mitigated; simple reversible tasks; situations where positive visualization is more effective; meta-questions about inversion",
+ "description": "Items where enumerating failure paths adds no value because risks are already managed or the task is too simple to fail meaningfully"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "pre-mortem"
+ ],
+ "mechanism": "failure-first reverse analysis",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/inversion-failure-paths.jsonl",
+ "sha256": "0727f530cd678e4d9972883d24aad3534b4a26036c9448bb315f3c8c38308bb7"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-inversion.jsonl",
+ "sha256": "248982e7c511180d8aee2224a6270453cf6e9386d4a515d4ead5ebe5c6f1d553"
+ }
+ ],
+ "row_counts": {
+ "n": 72,
+ "splits": {
+ "dev": 9,
+ "heldout": 30,
+ "replication": 33,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "jobs-to-be-done": {
+ "id": "jobs-to-be-done",
+ "dir": "thinking-jobs-to-be-done",
+ "contract_path": "evals/contracts/thinking-jobs-to-be-done.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "job_identification_accuracy",
+ "competition_mapping_quality"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Execution-focused technical tasks; infrastructure/refactoring work; features with well-understood user needs; bug fixes; meta-questions about JTBD",
+ "description": "Items where the 'job' is already known and the work is about implementation, not discovery of user needs"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 700,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 700,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "kepner-tregoe": {
+ "id": "kepner-tregoe",
+ "dir": "thinking-kepner-tregoe",
+ "contract_path": "evals/contracts/thinking-kepner-tregoe.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "decision_analysis_quality",
+ "secondary_metrics": [
+ "problem_analysis_rigor",
+ "decision_analysis_completeness",
+ "potential_problem_analysis_coverage",
+ "situation_appraisal_structure"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR problem_analysis_rigor < 0.50",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions with single clear option; low-stakes reversible choices; meta-questions about Kepner-Tregoe method",
+ "description": "Items where structured decision analysis adds no value over direct choice or where the method is applied to itself"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 700,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 700,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/kepner-tregoe-selective-defect.jsonl",
+ "sha256": "e271d987d83b3369995909fa020deefec755a0f079edbe12c7141f418fac56e9"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-kepner-tregoe.jsonl",
+ "sha256": "b74b1fa30fe7a036e5d6992375fd9f5d16c96a22af38bdafa29fcaa9c9ae7246"
+ }
+ ],
+ "row_counts": {
+ "n": 72,
+ "splits": {
+ "dev": 10,
+ "heldout": 30,
+ "replication": 32,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "leverage-points": {
+ "id": "leverage-points",
+ "dir": "thinking-leverage-points",
+ "contract_path": "evals/contracts/thinking-leverage-points.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "intervention_ranking_quality",
+ "system_model_fidelity"
+ ],
+ "eval_family": "Systems/product/strategy pairwise",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Simple linear systems; problems where the bottleneck is already obvious; situations where high-leverage interventions are already in place; meta-questions about leverage points",
+ "description": "Items where the system is too simple for leverage point analysis, or where the highest-leverage interventions are already being applied"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "systems"
+ ],
+ "mechanism": "intervention ranking by leverage and side effects",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "lindy-effect": {
+ "id": "lindy-effect",
+ "dir": "thinking-lindy-effect",
+ "contract_path": "evals/contracts/thinking-lindy-effect.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "longevity_prediction_accuracy",
+ "survivorship_bias_avoidance"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions about rapidly evolving domains with no track record; situations where novelty is the selection criterion; brand-new technologies by definition; meta-questions about Lindy effect",
+ "description": "Items where age is not a meaningful predictor because the domain is too new, or where newness is the desired attribute"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 400,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 400,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "map-territory": {
+ "id": "map-territory",
+ "dir": "thinking-map-territory",
+ "contract_path": "evals/contracts/thinking-map-territory.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "divergence_detection_accuracy",
+ "secondary_metrics": [
+ "root_cause_localization_when_diverged",
+ "false_divergence_rate",
+ "model_quality_assessment"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND false_divergence_rate <= 0.15",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR false_divergence_rate > 0.20",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Situations where metrics and reality align; problems with no observability gap; questions about the framework rather than its application",
+ "description": "Items where there is no map-territory gap to detect, or where the skill is applied to the framework itself"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 550,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 550,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/map-territory-verify.jsonl",
+ "sha256": "0cde9265928a7422092226f318380e3f4a5050ff950492258887fb67ac808ccf"
+ }
+ ],
+ "row_counts": {
+ "n": 81,
+ "splits": {
+ "dev": 21,
+ "heldout": 30,
+ "replication": 30,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "margin-of-safety": {
+ "id": "margin-of-safety",
+ "dir": "thinking-margin-of-safety",
+ "contract_path": "evals/contracts/thinking-margin-of-safety.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "buffer_appropriateness_score",
+ "overengineering_avoidance"
+ ],
+ "eval_family": "Quantitative/uncertainty",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions with fully known parameters and no uncertainty; reversible low-stakes choices; situations where over-engineering is explicitly desired; meta-questions about margin of safety",
+ "description": "Items where adding safety margins is unnecessary or counterproductive — the parameters are known and the stakes are low"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 650,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 650,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/margin-of-safety-provision.jsonl",
+ "sha256": "c69bc56bd1ccec492ca31c03ca6ce37768271de8547221480a33e8eda82ca14e"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-margin-of-safety.jsonl",
+ "sha256": "005d87564cf56001a85a2c020c3fc8af6125df8117697b1ecec8a42d52ff49de"
+ }
+ ],
+ "row_counts": {
+ "n": 84,
+ "splits": {
+ "dev": 21,
+ "heldout": 30,
+ "replication": 33,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "model-combination": {
+ "id": "model-combination",
+ "dir": "thinking-model-combination",
+ "contract_path": "evals/contracts/thinking-model-combination.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "synthesis_quality",
+ "secondary_metrics": [
+ "convergence_detection",
+ "divergence_resolution",
+ "unique_contribution_attribution",
+ "combined_confidence_calibration"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND synthesis_quality_score >= 0.70",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR model_soup_detected",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems solvable by a single model; model soup (adding models without distinct roles); incompatible model combinations forced together",
+ "description": "Items where combination adds no value over single model, or where combinations are incoherent"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 750,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 750,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "model-router": {
+ "id": "model-router",
+ "dir": "thinking-model-router",
+ "contract_path": "evals/contracts/thinking-model-router.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "routing_accuracy",
+ "secondary_metrics": [
+ "top_k_routing_accuracy",
+ "abstention_rate_on_ambiguous",
+ "false_route_rate",
+ "route_explanation_quality"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 100,
+ "min_sample_replication": 100,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND false_route_rate <= 0.10",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR false_route_rate > 0.15",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Queries that clearly map to a single model; problems outside the thinking skills catalog; meta-questions about the router itself",
+ "description": "Items where routing is trivial (one obvious model) or where the router should not be invoked (out of scope)"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "model-selection"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "model-selection",
+ "mechanism": "choice criteria and NONE/one-skill default"
+ }
+ ],
+ "max_words": 900,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 900,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "model-selection": {
+ "id": "model-selection",
+ "dir": "thinking-model-selection",
+ "contract_path": "evals/contracts/thinking-model-selection.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "routing_accuracy",
+ "secondary_metrics": [
+ "top_k_routing_accuracy",
+ "model_fit_justification_quality",
+ "fallback_appropriateness"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR model_fit_justification_quality < 0.60",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems with obvious single-model solutions; problems where model selection adds no value over direct invocation; meta-questions about model selection itself",
+ "description": "Items where the model choice is obvious or where selection overhead is unwarranted"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "model-router"
+ ],
+ "mechanism": "choice criteria and NONE/one-skill default",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "occams-razor": {
+ "id": "occams-razor",
+ "dir": "thinking-occams-razor",
+ "contract_path": "evals/contracts/thinking-occams-razor.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "explanation_selection_accuracy",
+ "secondary_metrics": [
+ "assumption_count_awareness",
+ "parsimony_justification",
+ "overfitting_avoidance",
+ "debugging_efficiency"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR overfitting_avoidance < 0.50",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems requiring complex multi-factor explanations; situations where simple explanations are known to be wrong; meta-questions about Occam's Razor",
+ "description": "Items where the simplest explanation is demonstrably incorrect or where complexity is genuinely required"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "scientific-method"
+ ],
+ "mechanism": "prefer the least-assumptive hypothesis that survives evidence",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/occams-razor-competing-causes.jsonl",
+ "sha256": "08f867b12f9ff52ed55ce03bb15e3cf3a573cf97a0af7d3141b80bd555d86fe5"
+ }
+ ],
+ "row_counts": {
+ "n": 69,
+ "splits": {
+ "dev": 10,
+ "heldout": 30,
+ "replication": 29,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": [
+ "legacy-july-verdict-occams"
+ ]
+ },
+ "ooda": {
+ "id": "ooda",
+ "dir": "thinking-ooda",
+ "contract_path": "evals/contracts/thinking-ooda.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "cycle_speed",
+ "orientation_accuracy"
+ ],
+ "eval_family": "Systems/product/strategy pairwise",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Static analysis tasks; situations with no time pressure; problems where observe-orient-decide-act is already the default mode",
+ "description": "Items where the OODA loop is already the natural operating mode, or where there's no time pressure to accelerate the cycle"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 550,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 550,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "opportunity-cost": {
+ "id": "opportunity-cost",
+ "dir": "thinking-opportunity-cost",
+ "contract_path": "evals/contracts/thinking-opportunity-cost.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "foregone_alternative_identification",
+ "value_comparison_accuracy"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions with no meaningful alternatives; resource-unconstrained situations; mandatory compliance actions",
+ "description": "Items where there is no real choice to make, or where the alternative is not a genuine option"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "regret-minimization"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "regret-minimization",
+ "mechanism": "asymmetric downside/recovery and future tradeoff"
+ }
+ ],
+ "max_words": 600,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 600,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "pre-mortem": {
+ "id": "pre-mortem",
+ "dir": "thinking-pre-mortem",
+ "contract_path": "evals/contracts/thinking-pre-mortem.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "risk_surfacing_breadth",
+ "mitigation_actionability"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Small reversible tasks; ongoing incidents requiring immediate action; projects with fully mature risk registers; situations where optimism is not a bias; meta-questions about pre-mortems",
+ "description": "Items where prospective hindsight adds no value — risks are already known, the work is too small to warrant it, or you're mid-crisis"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "inversion"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "inversion",
+ "mechanism": "failure-first reverse analysis"
+ }
+ ],
+ "max_words": 700,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 700,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/pre-mortem-risk.jsonl",
+ "sha256": "3a475710d3683212fb7037c18cb305c693f603f5d111bce6714eff9084c89903"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-pre-mortem.jsonl",
+ "sha256": "2112a09dfc2ae200ffaca439da0f2887984031e39c9b602369a77f03345b16dc"
+ }
+ ],
+ "row_counts": {
+ "n": 73,
+ "splits": {
+ "dev": 9,
+ "heldout": 30,
+ "replication": 34,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "probabilistic": {
+ "id": "probabilistic",
+ "dir": "thinking-probabilistic",
+ "contract_path": "evals/contracts/thinking-probabilistic.json",
+ "primary_value_surface": "calibrated classification",
+ "primary_metric": "forecast_calibration_error",
+ "secondary_metrics": [
+ "interval_coverage_accuracy",
+ "base_rate_anchoring",
+ "update_frequency",
+ "equivalent_bet_consistency"
+ ],
+ "eval_family": "Quantitative/uncertainty",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND interval_coverage_accuracy >= 0.80",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR base_rate_anchoring < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Quantities that are directly measurable; decisions insensitive to probability range; meta-questions about probabilistic thinking",
+ "description": "Items where the number is knowable, or where the decision doesn't depend on the probability estimate"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "bayesian",
+ "fermi-estimation",
+ "debiasing"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "bayesian",
+ "mechanism": "prior → likelihood → posterior update"
+ },
+ {
+ "id": "fermi-estimation",
+ "mechanism": "decomposition and order-of-magnitude bounds"
+ },
+ {
+ "id": "debiasing",
+ "mechanism": "base-rate/alternative check; strongest-countercase check"
+ }
+ ],
+ "max_words": 800,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 800,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "red-team": {
+ "id": "red-team",
+ "dir": "thinking-red-team",
+ "contract_path": "evals/contracts/thinking-red-team.json",
+ "primary_value_surface": "false-positive reduction",
+ "primary_metric": "vulnerability_detection_f1",
+ "secondary_metrics": [
+ "false_positive_rate",
+ "false_negative_rate",
+ "attack_path_reproducibility",
+ "severity_calibration",
+ "net_utility"
+ ],
+ "eval_family": "Security/adversarial",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND false_positive_rate <= 0.20",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR false_positive_rate > 0.30 OR attack_path_reproducibility < 0.70",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Systems with no security surface; theoretical vulnerabilities without reproducible attack paths; non-security plan stress-testing; meta-questions about red teaming",
+ "description": "Items where there is no attack surface to probe, or where findings are speculative without concrete attack paths"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 800,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 800,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/red-team-vulnerability.jsonl",
+ "sha256": "b02391738182a636e9de6fb883fab66b99570a46bbf4507371868715de4c4ede"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-red-team.jsonl",
+ "sha256": "f159c3fbbb62bd012ff5663e5ce0ee9da4e5b80299e301a7fc28ce616e848aa3"
+ }
+ ],
+ "row_counts": {
+ "n": 75,
+ "splits": {
+ "dev": 9,
+ "heldout": 30,
+ "replication": 36,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "regret-minimization": {
+ "id": "regret-minimization",
+ "dir": "thinking-regret-minimization",
+ "contract_path": "evals/contracts/thinking-regret-minimization.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "future_self_alignment",
+ "reversibility_assessment"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Low-stakes reversible decisions; decisions with no long-term consequences; purely technical choices without life/career impact",
+ "description": "Items where the decision is easily reversible or the stakes are too low for regret minimization to add value over simpler frameworks"
+ },
+ "disposition": {
+ "product": "delete_at_cutover",
+ "cutover": "delete",
+ "absorb_into": [
+ "reversibility",
+ "opportunity-cost"
+ ],
+ "mechanism": "asymmetric downside/recovery and future tradeoff",
+ "auto_invocation": false
+ },
+ "max_words": null,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "reversibility": {
+ "id": "reversibility",
+ "dir": "thinking-reversibility",
+ "contract_path": "evals/contracts/thinking-reversibility.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "type1_type2_classification",
+ "commitment_appropriateness"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions that are clearly Type 1 (irreversible) with obvious analysis needs; decisions that are clearly Type 2 (reversible) where action beats analysis; meta-questions about reversibility",
+ "description": "Items where the reversibility classification is obvious and adds no decision value"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "regret-minimization"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "regret-minimization",
+ "mechanism": "asymmetric downside/recovery and future tradeoff"
+ }
+ ],
+ "max_words": 550,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 550,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/reversibility-doors.jsonl",
+ "sha256": "bd09c22d42de383d5d0a55c93b11177e1e3b0fc86f64da06b80b3f37458e80a9"
+ }
+ ],
+ "row_counts": {
+ "n": 81,
+ "splits": {
+ "dev": 21,
+ "heldout": 30,
+ "replication": 30,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "scientific-method": {
+ "id": "scientific-method",
+ "dir": "thinking-scientific-method",
+ "contract_path": "evals/contracts/thinking-scientific-method.json",
+ "primary_value_surface": "localization",
+ "primary_metric": "fault_localization_accuracy",
+ "secondary_metrics": [
+ "hypothesis_quality",
+ "discriminating_observation_quality",
+ "falsification_rigor",
+ "localization_precision"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 100,
+ "min_sample_replication": 100,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR hypothesis_quality < 0.60",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems with single obvious cause; situations where direct inspection suffices; debugging where no observation is possible; meta-questions about the scientific method",
+ "description": "Items where hypothesis-differential debugging adds no value over direct inspection or where the method cannot be applied"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "occams-razor"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "occams-razor",
+ "mechanism": "prefer the least-assumptive hypothesis that survives evidence"
+ }
+ ],
+ "max_words": 900,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 900,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/scientific-method-hypothesis.jsonl",
+ "sha256": "223a3f931aa6234f9336c36853728043ec1872851e45e4f39085edf51dda7e87"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-scientific-method.jsonl",
+ "sha256": "28f486b61a678da08fcf48f9c802f732923a4d592ab8abcfe006e19a4fb8372a"
+ }
+ ],
+ "row_counts": {
+ "n": 73,
+ "splits": {
+ "dev": 9,
+ "heldout": 30,
+ "replication": 34,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": [
+ "legacy-july-sci-method-larger-n"
+ ]
+ },
+ "second-order": {
+ "id": "second-order",
+ "dir": "thinking-second-order",
+ "contract_path": "evals/contracts/thinking-second-order.json",
+ "primary_value_surface": "objective correctness",
+ "primary_metric": "consequence_prediction_accuracy",
+ "secondary_metrics": [
+ "cascade_depth_coverage",
+ "unintended_effect_identification",
+ "time_horizon_calibration",
+ "intervention_simulation_fidelity"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR cascade_depth_coverage < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Direct cause-effect relationships with no downstream effects; immediate decisions with no ripple effects; meta-questions about second-order thinking",
+ "description": "Items where consequences are direct and immediate with no cascading effects to analyze"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 550,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 550,
+ "data": {
+ "status": "inadequate",
+ "gaps": [
+ "heldout_rows=9<20",
+ "replication_rows=4<10"
+ ],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/second-order-consequence.jsonl",
+ "sha256": "6ca918d4cff39e232c365309c86c52702a3dba7c3d4c923bfe71e5530e940363"
+ },
+ {
+ "path": "evals/datasets/authored/challenging-second-order.jsonl",
+ "sha256": "a5338b55a1b6206c1634680917e6e2e95e98ae85fee2cb178876b5c77f696da3"
+ }
+ ],
+ "row_counts": {
+ "n": 34,
+ "splits": {
+ "dev": 21,
+ "heldout": 9,
+ "replication": 4,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "socratic": {
+ "id": "socratic",
+ "dir": "thinking-socratic",
+ "contract_path": "evals/contracts/thinking-socratic.json",
+ "primary_value_surface": "routing/discoverability",
+ "primary_metric": "routing_accuracy",
+ "secondary_metrics": [
+ "top_k_routing_accuracy",
+ "clarification_quality_score",
+ "abstention_rate_on_ambiguous"
+ ],
+ "eval_family": "Routing/abstention",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 100,
+ "min_sample_replication": 100,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR clarification_quality_decrease > 0.10",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Direct factual queries with single correct answers; procedural how-to questions; requests for code generation or specific implementations",
+ "description": "Items where the Socratic method (questioning to clarify) is inappropriate because the user needs a direct answer, not guided discovery"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 650,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 650,
+ "data": {
+ "status": "adequate",
+ "gaps": [],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/socratic-clarify.jsonl",
+ "sha256": "abd143021f06976738fe0bef74b2692adbb97627d6de180c58c96fe0e25cf2e5"
+ }
+ ],
+ "row_counts": {
+ "n": 86,
+ "splits": {
+ "dev": 21,
+ "heldout": 35,
+ "replication": 30,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "steel-manning": {
+ "id": "steel-manning",
+ "dir": "thinking-steel-manning",
+ "contract_path": "evals/contracts/thinking-steel-manning.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "opposing_argument_strength",
+ "strawman_avoidance"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Decisions with no genuine opposition; situations where the opposing view is demonstrably false; time-critical decisions requiring immediate action",
+ "description": "Items where there is no credible opposing position to steel-man, or where the cost of delay exceeds the value of understanding the opposition"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "debiasing"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "debiasing",
+ "mechanism": "base-rate/alternative check; strongest-countercase check"
+ }
+ ],
+ "max_words": 650,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 650,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "systems": {
+ "id": "systems",
+ "dir": "thinking-systems",
+ "contract_path": "evals/contracts/thinking-systems.json",
+ "primary_value_surface": "localization",
+ "primary_metric": "fault_localization_accuracy",
+ "secondary_metrics": [
+ "feedback_loop_identification",
+ "emergent_behavior_explanation",
+ "leverage_point_identification",
+ "causal_loop_diagram_quality"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR feedback_loop_identification < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Single-component bugs with linear causality; problems where no feedback loops exist; meta-questions about systems thinking",
+ "description": "Items where the system behavior is linear and single-component, or where systems thinking adds no diagnostic value"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [
+ "archetypes",
+ "feedback-loops",
+ "leverage-points"
+ ],
+ "absorbed_mechanisms": [
+ {
+ "id": "archetypes",
+ "mechanism": "recurring cross-domain structure/pattern check"
+ },
+ {
+ "id": "feedback-loops",
+ "mechanism": "reinforcing/balancing loop and delay check"
+ },
+ {
+ "id": "leverage-points",
+ "mechanism": "intervention ranking by leverage and side effects"
+ }
+ ],
+ "max_words": 950,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 950,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "theory-of-constraints": {
+ "id": "theory-of-constraints",
+ "dir": "thinking-theory-of-constraints",
+ "contract_path": "evals/contracts/thinking-theory-of-constraints.json",
+ "primary_value_surface": "objective correctness",
+ "primary_metric": "bottleneck_identification_accuracy",
+ "secondary_metrics": [
+ "throughput_improvement_prediction",
+ "constraint_exploitation_plan_quality",
+ "subordination_appropriateness",
+ "elevation_timing"
+ ],
+ "eval_family": "Debugging/fault-localization",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 60,
+ "min_sample_replication": 60,
+ "planned_comparison": "placebo",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR bottleneck_identification_accuracy < 0.50",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Systems with no clear bottleneck; already optimized pipelines; meta-questions about Theory of Constraints",
+ "description": "Items where there is no constraint to find or where the constraint is already known and being addressed"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 750,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 750,
+ "data": {
+ "status": "inadequate",
+ "gaps": [
+ "heldout_rows=9<20",
+ "replication_rows=0<10"
+ ],
+ "sources": [
+ {
+ "path": "evals/datasets/authored/theory-of-constraints-bottleneck.jsonl",
+ "sha256": "b8643c8a80d9e3f39bbbd1fe58a9c01fea53f2bc67429ff3436900d9934be096"
+ }
+ ],
+ "row_counts": {
+ "n": 30,
+ "splits": {
+ "dev": 21,
+ "heldout": 9,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "thought-experiment": {
+ "id": "thought-experiment",
+ "dir": "thinking-thought-experiment",
+ "contract_path": "evals/contracts/thinking-thought-experiment.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "counterfactual_coherence",
+ "edge_case_coverage"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Questions with empirical answers available; situations requiring immediate action; problems where real testing is cheap and feasible; meta-questions about thought experiments",
+ "description": "Items where the answer can be looked up or tested directly, or where hypothetical reasoning is unnecessary because evidence is accessible"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 650,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 650,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "triz": {
+ "id": "triz",
+ "dir": "thinking-triz",
+ "contract_path": "evals/contracts/thinking-triz.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "contradiction_resolution_quality",
+ "inventive_principle_applicability"
+ ],
+ "eval_family": "Conceptual reframes",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Problems without genuine contradictions; situations where trade-offs are acceptable; well-understood design spaces with established patterns; meta-questions about TRIZ",
+ "description": "Items where there is no technical contradiction to resolve, or where compromise solutions are perfectly adequate"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 700,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 700,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ },
+ "via-negativa": {
+ "id": "via-negativa",
+ "dir": "thinking-via-negativa",
+ "contract_path": "evals/contracts/thinking-via-negativa.json",
+ "primary_value_surface": "paired reasoning quality",
+ "primary_metric": "pairwise_win_rate_vs_placebo",
+ "secondary_metrics": [
+ "judge_agreement",
+ "format_length_controlled_win_rate",
+ "subtraction_identification",
+ "harm_reduction_accuracy"
+ ],
+ "eval_family": "Systems/product/strategy pairwise",
+ "calibration_range": [
+ 0.4,
+ 0.7
+ ],
+ "min_sample_primary": 80,
+ "min_sample_replication": 80,
+ "planned_comparison": "trigger",
+ "decision_gate_legacy": {
+ "elevate": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND replication_delta_pp >= 5 AND replication_paired_test_p < 0.05 AND replication_direction_matches_primary AND format_length_control_pass",
+ "directional_not_replicated": "primary_delta_pp >= 5 AND paired_test_p < 0.05 AND (replication_delta_pp < 5 OR replication_paired_test_p >= 0.05 OR replication_direction_opposite)",
+ "no_lift": "primary_delta_pp < 5 OR paired_test_p >= 0.05",
+ "quarantine_redirect": "primary_delta_pp < 0 OR format_length_bias_detected",
+ "trigger_only": "trigger_card_delta_pp >= full_guide_delta_pp AND trigger_paired_test_p < 0.05",
+ "ceiling_needs_harder_data": "placebo_baseline > 0.70"
+ },
+ "distractors": {
+ "off_target_set": "Greenfield projects with nothing to remove; situations where addition is the only path; domains where redundancy is required for safety; meta-questions about via negativa",
+ "description": "Items where there is nothing to subtract, or where adding is the correct approach (e.g., building new capabilities, safety-critical redundancy)"
+ },
+ "disposition": {
+ "product": "manual_only_quarantine",
+ "cutover": "survive",
+ "absorb_into": null,
+ "absorbs": [],
+ "absorbed_mechanisms": [],
+ "max_words": 450,
+ "auto_invocation": false,
+ "disable_model_invocation_until_elevated": true
+ },
+ "max_words": 450,
+ "data": {
+ "status": "unknown",
+ "gaps": [
+ "no_declared_authored_dataset"
+ ],
+ "sources": [],
+ "row_counts": {
+ "n": 0,
+ "splits": {
+ "dev": 0,
+ "heldout": 0,
+ "replication": 0,
+ "other": 0
+ }
+ },
+ "required_heldout_min": 20,
+ "required_hard_negatives_min": 10,
+ "required_replication_min": 10
+ },
+ "study_ids": []
+ }
+ },
+ "study_contracts": {
+ "portfolio_skill_efficacy": {
+ "study_family": "portfolio_skill_efficacy",
+ "description": "Per-skill none/full_legacy/lean/wrong_neighbor objective or judged study across deployment models",
+ "arms": [
+ "none",
+ "full_legacy",
+ "lean",
+ "equal_budget_placebo",
+ "wrong_neighbor"
+ ],
+ "models": [
+ "claude-haiku-4-5-20251001",
+ "claude-sonnet-4-6",
+ "claude-opus-4-8"
+ ],
+ "screening_models": [
+ "claude-haiku-4-5-20251001",
+ "claude-opus-4-8"
+ ],
+ "nested_trials_screening": 3,
+ "nested_trials_replication": 5,
+ "utility_margin_pp": 5,
+ "noninferiority_margin_pp": 3,
+ "harm_margin_pp": 2,
+ "efficacy_hypothesis_count": 84,
+ "power_target": 0.9,
+ "alpha_one_sided_family": 0.05,
+ "bootstrap_resamples": 10000,
+ "disposition_algorithm": [
+ "AUTO-RETAIN LEAN",
+ "MINIMIZE FURTHER",
+ "DELETE",
+ "MANUAL-ONLY QUARANTINE"
+ ],
+ "eligible_split": "replication",
+ "screening_split": "heldout"
+ },
+ "workflow_value_gate": {
+ "study_family": "workflow_value_gate",
+ "description": "Unpadded workflow vs frozen lean comparator and no-skill on untouched replication",
+ "arms": [
+ "none",
+ "lean_comparator",
+ "workflow"
+ ],
+ "models": [
+ "claude-haiku-4-5-20251001",
+ "claude-sonnet-4-6",
+ "claude-opus-4-8"
+ ],
+ "datasets": {
+ "base": "evals/datasets/workflow-cases.jsonl",
+ "expanded": "evals/datasets/workflow-cases-expanded.jsonl",
+ "replication": "evals/datasets/workflow-cases-replication.jsonl"
+ },
+ "quality_margin_pp": 5,
+ "efficiency_token_ratio_upper": 0.8,
+ "cost_ratio_upper": 1.25,
+ "failure_rate_delta_upper_pp": 2,
+ "noninferiority_margin_pp": 3,
+ "eligible_split": "replication"
+ },
+ "judge_panel_calibration": {
+ "study_id": "judge-panel-calibration",
+ "study_family": "judge_panel_calibration",
+ "description": "Fixed human-labeled pairwise panel calibration gate before any judged confirmatory study",
+ "status": "blocked_missing_human_labels",
+ "decision_eligible": false,
+ "calibration_status": "blocked_missing_human_labels",
+ "min_pairs": 30,
+ "panel": [
+ "gpt-5.5-pro",
+ "gemini-3.1-pro-preview",
+ "deepseek-v4-pro"
+ ],
+ "thresholds": {
+ "min_pairs": 30,
+ "panel_majority_accuracy_min": 0.85,
+ "per_judge_accuracy_min": 0.75,
+ "fleiss_kappa_min": 0.6,
+ "order_verbosity_delta_max_pp": 5,
+ "missing_votes_max": 0.01
+ },
+ "required_pair_coverage": [
+ "A_wins",
+ "B_wins",
+ "true_ties",
+ "swapped_order",
+ "verbosity_traps",
+ "format_traps"
+ ],
+ "human_labeled_pairs": {
+ "count": 0,
+ "path": null,
+ "note": "No existing fixed human-labeled 30-pair judge calibration set found. Do not fabricate pairs or run models."
+ },
+ "rule": {
+ "judged_studies_while_blocked": "manual_only",
+ "auto_invocation": false,
+ "elevation_blocked": true,
+ "statement": "All judged studies remain manual-only quarantine until a fixed ≥30 human-labeled calibration set meets every panel threshold and decision_eligible becomes true."
+ },
+ "blockers": [
+ "missing_fixed_human_labeled_calibration_pairs",
+ "min_pairs_0_lt_30",
+ "panel_not_calibrated",
+ "decision_eligible_false"
+ ]
+ }
+ },
+ "declared_study_bundles": [
+ {
+ "study_id": "legacy-july-sci-method-larger-n",
+ "path": "evals/studies/legacy-july-sci-method-larger-n",
+ "kind": "legacy_july_import",
+ "skill_id": "scientific-method",
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-verdict-five-whys",
+ "path": "evals/studies/legacy-july-verdict-five-whys",
+ "kind": "legacy_july_import",
+ "skill_id": "five-whys-plus",
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-verdict-occams",
+ "path": "evals/studies/legacy-july-verdict-occams",
+ "kind": "legacy_july_import",
+ "skill_id": "occams-razor",
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-wf-confirm-haiku",
+ "path": "evals/studies/legacy-july-wf-confirm-haiku",
+ "kind": "legacy_july_import",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-wf-confirm-sonnet",
+ "path": "evals/studies/legacy-july-wf-confirm-sonnet",
+ "kind": "legacy_july_import",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-wf-confirm-opus",
+ "path": "evals/studies/legacy-july-wf-confirm-opus",
+ "kind": "legacy_july_import",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "legacy-july-wf-confirm-behavioral",
+ "path": "evals/studies/legacy-july-wf-confirm-behavioral",
+ "kind": "legacy_july_import",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "catalog-cutover",
+ "path": "evals/studies/catalog-cutover",
+ "kind": "artifact_ledger",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false
+ },
+ {
+ "study_id": "judge-panel-calibration",
+ "path": null,
+ "kind": "judge_panel_calibration",
+ "skill_id": null,
+ "confirmatory_eligible_by_default": false,
+ "decision_eligible": false,
+ "status": "blocked_missing_human_labels",
+ "calibration_status": "blocked_missing_human_labels",
+ "judged_studies_policy": "manual_only",
+ "declared_inline": true,
+ "contract_key": "judge_panel_calibration"
+ }
+ ],
+ "workflow": {
+ "datasets": {
+ "base": {
+ "path": "evals/datasets/workflow-cases.jsonl",
+ "sha256": "b39aa13901326ae1262bdb8db25fa41c38dea84a88a89b2287c1d1d00714a102",
+ "exists": true
+ },
+ "expanded": {
+ "path": "evals/datasets/workflow-cases-expanded.jsonl",
+ "sha256": "19e4e10b07583962efb6cb866be940303cd6ace0dd905450c0f4c550be345474",
+ "exists": true
+ },
+ "replication": {
+ "path": "evals/datasets/workflow-cases-replication.jsonl",
+ "sha256": "628ba407a038f957e01c747ff008cda849d29c1eedd44a13ddfaf1eea736cf72",
+ "exists": true
+ }
+ },
+ "retain_only_if_gate_passes": true,
+ "engine_path_conditional": "evals/run-agentic.js"
+ },
+ "evidence_confirmation_requirements": [
+ "matching_preregistration_sha256",
+ "eligible_split",
+ "exact_dataset_prompt_skill_solver_judge_hashes",
+ "final_rule_power",
+ "complete_health",
+ "successful_replication",
+ "archive_readback_and_sha_match"
+ ],
+ "split_validation": {
+ "authored_dir": "evals/datasets/authored",
+ "workflow_files": [
+ "evals/datasets/workflow-cases.jsonl",
+ "evals/datasets/workflow-cases-expanded.jsonl",
+ "evals/datasets/workflow-cases-replication.jsonl"
+ ],
+ "splits": [
+ "dev",
+ "heldout",
+ "replication"
+ ],
+ "global_checks": [
+ "unique_ids",
+ "prompt_hash_disjoint_splits",
+ "cluster_disjoint_splits"
+ ],
+ "write_tracked_output": false
+ },
+ "family_counts": {
+ "by_eval_family": {
+ "Systems/product/strategy pairwise": 5,
+ "Quantitative/uncertainty": 5,
+ "Conceptual reframes": 14,
+ "Routing/abstention": 6,
+ "Debugging/fault-localization": 8,
+ "Security/adversarial": 1
+ },
+ "total_skills": 39,
+ "survivors": 28,
+ "deletions": 11,
+ "efficacy_hypotheses": 84,
+ "deployment_models": 3,
+ "efficacy_hypotheses_formula": "survivors_after_cutover * deployment_models",
+ "efficacy_hypotheses_basis": {
+ "survivors_target": 28,
+ "deployment_models": 3,
+ "product": 84
+ }
+ },
+ "source_integrity": {
+ "validate_on_load": true,
+ "require_source_sha_match": true,
+ "require_split_count_match": true
+ }
+}
diff --git a/evals/tests/calibration.test.js b/evals/tests/calibration.test.js
new file mode 100644
index 0000000..5e04045
--- /dev/null
+++ b/evals/tests/calibration.test.js
@@ -0,0 +1,118 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const {
+ aggregatePerItem,
+ classifyBands,
+ buildOutput,
+ serializeRate,
+ loadPartialProgress,
+ normalizeTrialResult,
+} = require('../run-calibration.js');
+
+test('serializeRate: preserves zero instead of null', () => {
+ assert.strictEqual(serializeRate(0), 0);
+ assert.strictEqual(serializeRate(0.0), 0);
+ assert.strictEqual(serializeRate(null), null);
+ assert.strictEqual(serializeRate(undefined), null);
+ assert.strictEqual(serializeRate(0.5), 0.5);
+});
+
+test('aggregatePerItem: failures are attempted-scored; wrong answers stay in denominator', () => {
+ const trials = [
+ { itemIndex: 0, id: 'i0', correct: false, scored: true, prediction: 'no', parse_failure: false, transport_failure: false },
+ { itemIndex: 0, id: 'i0', correct: false, scored: true, prediction: 'no', parse_failure: false, transport_failure: false },
+ { itemIndex: 0, id: 'i0', correct: null, scored: false, prediction: null, parse_failure: true, transport_failure: true },
+ ];
+ const per = aggregatePerItem(trials, 3);
+ assert.strictEqual(per.length, 1);
+ assert.strictEqual(per[0].attempted, 3);
+ assert.strictEqual(per[0].scored, 2);
+ assert.strictEqual(per[0].successes, 0);
+ assert.strictEqual(per[0].incorrect, 2);
+ // failures = attempted - scored (infra only), not attempted - successes
+ assert.strictEqual(per[0].failures, 1);
+ // Zero baseline must serialize as 0, not null (wrong + failed both in denom)
+ assert.strictEqual(per[0].baseline, 0);
+});
+
+test('aggregatePerItem: successes / attempted (not successes / scored-only)', () => {
+ const trials = [
+ { itemIndex: 1, id: 'i1', correct: true, scored: true, prediction: 'yes' },
+ { itemIndex: 1, id: 'i1', correct: true, scored: true, prediction: 'yes' },
+ { itemIndex: 1, id: 'i1', correct: null, scored: false, prediction: null, parse_failure: true },
+ { itemIndex: 1, id: 'i1', correct: false, scored: true, prediction: 'no' },
+ ];
+ const per = aggregatePerItem(trials, 4);
+ assert.strictEqual(per[0].attempted, 4);
+ assert.strictEqual(per[0].scored, 3);
+ assert.strictEqual(per[0].successes, 2);
+ assert.strictEqual(per[0].incorrect, 1);
+ assert.strictEqual(per[0].failures, 1);
+ // 2/4 = 0.5 (failure trial still in accuracy denominator)
+ assert.ok(Math.abs(per[0].baseline - 0.5) < 1e-9);
+});
+
+test('classifyBands: floor includes exact zero baseline', () => {
+ const { floor, inBand } = classifyBands([
+ { id: 'z', baseline: 0, attempted: 5 },
+ { id: 'm', baseline: 0.5, attempted: 5 },
+ ]);
+ assert.strictEqual(floor.length, 1);
+ assert.strictEqual(floor[0].id, 'z');
+ assert.strictEqual(inBand.length, 1);
+});
+
+test('buildOutput: baseline_accuracy 0 serializes as 0', () => {
+ const trials = [
+ { itemIndex: 0, id: 'a', correct: false, scored: true, prediction: 'x' },
+ ];
+ const per = aggregatePerItem(trials, 1);
+ const out = buildOutput('fixture', 1, [{ id: 'a' }], trials, per);
+ assert.strictEqual(out.baseline_accuracy, 0);
+ assert.strictEqual(out.scored_trials, 1);
+ assert.strictEqual(out.incorrect_trials, 1);
+ assert.strictEqual(out.failed_trials, 0);
+ assert.strictEqual(out.attempted_trials, 1);
+});
+
+test('loadPartialProgress: tracks completed trial indexes without treating partial as complete', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cal-'));
+ const partialFile = path.join(dir, 'partial.json');
+ // K_TRIALS default is 5; write 5 trials for item 0 and 2 for item 1
+ const raw = [];
+ for (let t = 0; t < 5; t++) {
+ raw.push({ itemIndex: 0, trialIndex: t, id: 'a', correct: true, scored: true, prediction: 'yes' });
+ }
+ raw.push({ itemIndex: 1, trialIndex: 0, id: 'b', correct: false, scored: true, prediction: 'no' });
+ raw.push({ itemIndex: 1, trialIndex: 1, id: 'b', correct: false, scored: true, prediction: 'no' });
+ fs.writeFileSync(partialFile, JSON.stringify({ raw_results: raw }));
+ const { trialResults, completedItemIndexes, completedTrialsByItem } = loadPartialProgress(partialFile);
+ assert.strictEqual(trialResults.length, 7);
+ assert.ok(completedItemIndexes.has(0));
+ assert.ok(!completedItemIndexes.has(1));
+ assert.deepStrictEqual([...completedTrialsByItem.get(1)].sort(), [0, 1]);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+test('normalizeTrialResult: converts bare mapPool __error into structured failure with identity', () => {
+ const item = { id: 'x1', type: 'boolean', target: true };
+ const row = normalizeTrialResult({ __error: 'boom' }, item, 3, 2);
+ assert.strictEqual(row.itemIndex, 3);
+ assert.strictEqual(row.trialIndex, 2);
+ assert.strictEqual(row.id, 'x1');
+ assert.strictEqual(row.attempted, true);
+ assert.strictEqual(row.scored, false);
+ assert.strictEqual(row.transport_failure, true);
+ assert.strictEqual(row.correct, null);
+ // lands in failure denominator, not success
+ const per = aggregatePerItem([row], 1);
+ assert.strictEqual(per[0].attempted, 1);
+ assert.strictEqual(per[0].scored, 0);
+ assert.strictEqual(per[0].failures, 1);
+ assert.strictEqual(per[0].baseline, 0);
+});
diff --git a/evals/tests/droid.test.js b/evals/tests/droid.test.js
new file mode 100644
index 0000000..31edba2
--- /dev/null
+++ b/evals/tests/droid.test.js
@@ -0,0 +1,653 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const {
+ executeDroid,
+ DroidFailure,
+ droidExec,
+ droidJson,
+ droidExecAsync,
+ droidJsonAsync,
+ droidExecWithRetry,
+ extractJson,
+ parseDroidStdout,
+ maxEffortFor,
+ MAX_EFFORT,
+ usageSummary,
+ aggregateUsage,
+ modelFamilyForCost,
+ COST_PER_MTOKEN,
+ COST_MODEL_VERSION,
+ ISOLATION_DISABLED_TOOLS,
+ ISOLATION_ENV_ALLOWLIST,
+ isolationMetadata,
+ _acquireSlot,
+ _releaseSlot,
+ _getInflight,
+ MAX_DROID_INFLIGHT,
+} = require('../lib/droid');
+const {
+ writeJson,
+ writeJsonAtomic,
+ readJsonIfExists,
+ writeStudyCheckpoint,
+ writeObservationCheckpoint,
+ readStudyCheckpoint,
+ readObservationCheckpoint,
+ runHealthWarnings,
+} = require('../lib/io');
+const {
+ checkpointKey,
+ observationCheckpointKey,
+} = require('../lib/result');
+
+function droidStdout(result, extras = {}) {
+ return JSON.stringify({
+ result,
+ usage: extras.usage || { input_tokens: 10, output_tokens: 5 },
+ duration_ms: extras.duration_ms || 12,
+ is_error: Boolean(extras.is_error),
+ ...extras.extra,
+ });
+}
+
+function makeRunner(handler) {
+ return async (ctx) => handler(ctx);
+}
+
+test('legacy exports remain importable', () => {
+ assert.equal(typeof droidExec, 'function');
+ assert.equal(typeof droidJson, 'function');
+ assert.equal(typeof droidExecAsync, 'function');
+ assert.equal(typeof droidJsonAsync, 'function');
+ assert.equal(typeof droidExecWithRetry, 'function');
+ assert.equal(typeof extractJson, 'function');
+ assert.equal(typeof parseDroidStdout, 'function');
+ assert.equal(typeof maxEffortFor, 'function');
+ assert.equal(typeof usageSummary, 'function');
+ assert.equal(typeof aggregateUsage, 'function');
+ assert.equal(typeof modelFamilyForCost, 'function');
+ assert.ok(MAX_EFFORT);
+ assert.ok(COST_PER_MTOKEN);
+ assert.equal(typeof executeDroid, 'function');
+ assert.equal(typeof DroidFailure, 'function');
+});
+
+test('executeDroid success path returns structured envelope', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'hello',
+ runner: makeRunner(async () => ({
+ status: 0,
+ stdout: droidStdout('ANSWER: ok'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 42,
+ })),
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.text, 'ANSWER: ok');
+ assert.equal(r.failure, null);
+ assert.equal(r.attempts, 1);
+ assert.equal(r.durationMs, 42);
+ assert.equal(r.usage.input_tokens, 10);
+ assert.equal(r.cost_model_version, COST_MODEL_VERSION);
+ assert.equal(r.isolation.enabled, true);
+ assert.equal(r.isolation.effective_cwd, os.tmpdir());
+ assert.deepEqual(r.isolation.disabled_tools, ISOLATION_DISABLED_TOOLS);
+ assert.ok(Array.isArray(r.isolation.env_allowlist));
+ assert.ok(r.isolation.env_allowlist.includes('PATH'));
+});
+
+test('transport nonzero exit becomes typed failure without throw', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'x',
+ runner: makeRunner(async () => ({
+ status: 7,
+ stdout: '',
+ stderr: 'boom',
+ error: null,
+ timedOut: false,
+ durationMs: 5,
+ })),
+ });
+ assert.equal(r.ok, false);
+ assert.ok(r.failure instanceof DroidFailure);
+ assert.equal(r.failure.type, 'transport');
+ assert.match(r.failure.message, /exit 7/);
+ assert.equal(r.error, 'exit 7');
+});
+
+test('timeout is classified separately from transport', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'x',
+ runner: makeRunner(async () => ({
+ status: null,
+ stdout: '',
+ stderr: '',
+ error: new Error('timeout'),
+ timedOut: true,
+ signal: 'SIGKILL',
+ durationMs: 100,
+ })),
+ });
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'timeout');
+ assert.equal(r.error, 'timeout');
+});
+
+test('malformed stdout yields parse failure', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'x',
+ runner: makeRunner(async () => ({
+ status: 0,
+ stdout: 'not-json-at-all',
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 3,
+ })),
+ });
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'parse');
+ assert.match(r.failure.message, /parse/i);
+});
+
+test('tool leakage under isolation is typed tool_leakage', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'x',
+ isolate: true,
+ runner: makeRunner(async () => ({
+ status: 0,
+ stdout: droidStdout('invoked a tool', {
+ extra: { tool_use: { name: 'Read', input: { path: 'secret' } } },
+ }),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 8,
+ })),
+ });
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'tool_leakage');
+});
+
+test('answer text mentioning tools is not tool_leakage', async () => {
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'x',
+ isolate: true,
+ runner: makeRunner(async () => ({
+ status: 0,
+ stdout: droidStdout('Do not use tool_use or functions.Read; answer without tools.'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 4,
+ })),
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.failure, null);
+ assert.match(r.text, /tool_use/);
+});
+
+test('temp prompt file is cleaned up on success and failure', async () => {
+ const seen = [];
+ for (const mode of ['ok', 'fail']) {
+ await executeDroid({
+ model: 'fixture-model',
+ prompt: `cleanup-${mode}`,
+ runner: makeRunner(async (ctx) => {
+ seen.push(ctx.promptFile);
+ assert.equal(fs.existsSync(ctx.promptFile), true);
+ assert.equal(fs.readFileSync(ctx.promptFile, 'utf8'), `cleanup-${mode}`);
+ if (mode === 'ok') {
+ return {
+ status: 0,
+ stdout: droidStdout('done'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }
+ return {
+ status: 1,
+ stdout: '',
+ stderr: 'fail',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ });
+ }
+ assert.equal(seen.length, 2);
+ for (const file of seen) {
+ assert.equal(fs.existsSync(file), false, `temp prompt should be removed: ${file}`);
+ }
+});
+
+test('retries only on transport/timeout and report attempt count', async () => {
+ let calls = 0;
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'retry-me',
+ attempts: 3,
+ runner: makeRunner(async () => {
+ calls += 1;
+ if (calls < 3) {
+ return {
+ status: 1,
+ stdout: '',
+ stderr: 'transient',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }
+ return {
+ status: 0,
+ stdout: droidStdout('recovered'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 2,
+ };
+ }),
+ });
+ assert.equal(calls, 3);
+ assert.equal(r.ok, true);
+ assert.equal(r.attempts, 3);
+ assert.equal(r.text, 'recovered');
+});
+
+test('retries accumulate usage and duration across attempts', async () => {
+ let calls = 0;
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'retry-cost',
+ attempts: 2,
+ runner: makeRunner(async () => {
+ calls += 1;
+ if (calls === 1) {
+ return {
+ status: 1,
+ stdout: droidStdout('partial', {
+ usage: { input_tokens: 100, output_tokens: 20 },
+ duration_ms: 11,
+ }),
+ stderr: 'transient',
+ error: null,
+ timedOut: false,
+ durationMs: 11,
+ };
+ }
+ return {
+ status: 0,
+ stdout: droidStdout('final', {
+ usage: { input_tokens: 40, output_tokens: 10 },
+ duration_ms: 7,
+ }),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 7,
+ };
+ }),
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.attempts, 2);
+ assert.equal(r.usage.input_tokens, 140);
+ assert.equal(r.usage.output_tokens, 30);
+ assert.equal(r.durationMs, 18);
+ assert.equal(r.attempt_records.length, 2);
+ assert.equal(r.attempt_records[0].ok, false);
+ assert.equal(r.attempt_records[1].ok, true);
+});
+
+test('parse failures do not burn remaining retries', async () => {
+ let calls = 0;
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'no-retry-parse',
+ attempts: 4,
+ runner: makeRunner(async () => {
+ calls += 1;
+ return {
+ status: 0,
+ stdout: '<<<not json>>>',
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ });
+ assert.equal(calls, 1);
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'parse');
+ assert.equal(r.attempts, 1);
+});
+
+test('droidExecWithRetry preserves attempts on final failure', async () => {
+ let calls = 0;
+ const r = await droidExecWithRetry({
+ model: 'fixture-model',
+ prompt: 'always-fail',
+ runner: makeRunner(async () => {
+ calls += 1;
+ return {
+ status: 2,
+ stdout: '',
+ stderr: 'nope',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ }, 3);
+ assert.equal(calls, 3);
+ assert.equal(r.ok, false);
+ assert.equal(r.attempts, 3);
+ assert.equal(r.failure.type, 'transport');
+});
+
+test('throwing syncRunner becomes transport failure without escaping', () => {
+ let promptFile = null;
+ const r = droidExec({
+ model: 'fixture-model',
+ prompt: 'throwing-runner',
+ syncRunner: (ctx) => {
+ promptFile = ctx.promptFile;
+ throw new Error('sync boom');
+ },
+ });
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'transport');
+ assert.match(r.failure.message, /sync boom/);
+ assert.equal(fs.existsSync(promptFile), false);
+});
+
+test('sync droidExec uses injected syncRunner and cleans temp prompt', () => {
+ let promptFile = null;
+ const r = droidExec({
+ model: 'fixture-model',
+ prompt: 'sync-path',
+ syncRunner: (ctx) => {
+ promptFile = ctx.promptFile;
+ assert.equal(fs.existsSync(promptFile), true);
+ return {
+ status: 0,
+ stdout: droidStdout('sync-ok'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 9,
+ };
+ },
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.text, 'sync-ok');
+ assert.equal(fs.existsSync(promptFile), false);
+});
+
+test('missing model/prompt returns structured transport failure in async path', async () => {
+ const r = await executeDroid({
+ model: '',
+ prompt: 'x',
+ runner: makeRunner(async () => {
+ throw new Error('runner should not run');
+ }),
+ });
+ assert.equal(r.ok, false);
+ assert.equal(r.failure.type, 'transport');
+ assert.match(r.failure.message, /model and prompt/);
+});
+
+test('isolation metadata and args respect call-time isolate override', async () => {
+ let captured = null;
+ await executeDroid({
+ model: 'fixture-model',
+ prompt: 'iso',
+ isolate: false,
+ runner: makeRunner(async (ctx) => {
+ captured = ctx;
+ return {
+ status: 0,
+ stdout: droidStdout('ok'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ });
+ assert.ok(captured);
+ assert.equal(captured.isolation.enabled, false);
+ assert.deepEqual(captured.isolation.disabled_tools, []);
+ assert.equal(captured.args.includes('--disabled-tools'), false);
+ assert.equal(captured.env.EVAL_SECRET_SHOULD_PASS, undefined);
+});
+
+test('isolated env is allowlisted and cwd is neutral', async () => {
+ const prev = process.env.EVAL_SECRET_SHOULD_NOT_LEAK;
+ process.env.EVAL_SECRET_SHOULD_NOT_LEAK = 'sentinel-secret';
+ try {
+ let captured = null;
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'env-check',
+ isolate: true,
+ runner: makeRunner(async (ctx) => {
+ captured = ctx;
+ return {
+ status: 0,
+ stdout: droidStdout('ok'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ });
+ assert.equal(r.isolation.enabled, true);
+ assert.equal(captured.cwd, os.tmpdir());
+ assert.equal(captured.env.EVAL_SECRET_SHOULD_NOT_LEAK, undefined);
+ assert.ok(captured.env.PATH);
+ assert.ok(r.isolation.env_allowlist.includes('PATH'));
+ assert.ok(ISOLATION_ENV_ALLOWLIST.includes('HOME'));
+ } finally {
+ if (prev === undefined) delete process.env.EVAL_SECRET_SHOULD_NOT_LEAK;
+ else process.env.EVAL_SECRET_SHOULD_NOT_LEAK = prev;
+ }
+});
+
+test('isolation canary: repository sentinel is unavailable from neutral cwd/tools', async () => {
+ const repoRoot = path.resolve(__dirname, '..', '..');
+ const sentinelName = `ISOLATION_CANARY_SENTINEL_${process.pid}.txt`;
+ const sentinelPath = path.join(repoRoot, sentinelName);
+ const marker = `canary-secret-${process.pid}`;
+ fs.writeFileSync(sentinelPath, marker, 'utf8');
+ try {
+ let captured = null;
+ const r = await executeDroid({
+ model: 'fixture-model',
+ prompt: 'canary',
+ isolate: true,
+ runner: makeRunner(async (ctx) => {
+ captured = ctx;
+ // Simulate what an isolated solver could observe with only the
+ // allowlisted env + neutral cwd + disabled tools.
+ const cwdListing = fs.readdirSync(ctx.cwd);
+ const canSeeSentinelInCwd = cwdListing.includes(sentinelName);
+ let canReadByRelative = false;
+ try {
+ fs.readFileSync(path.join(ctx.cwd, sentinelName), 'utf8');
+ canReadByRelative = true;
+ } catch (_) { /* expected */ }
+ const toolsDisabled = ctx.args.includes('--disabled-tools')
+ && String(ctx.args[ctx.args.indexOf('--disabled-tools') + 1] || '').includes('Read')
+ && String(ctx.args[ctx.args.indexOf('--disabled-tools') + 1] || '').includes('Execute');
+ return {
+ status: 0,
+ stdout: droidStdout(JSON.stringify({
+ cwd: ctx.cwd,
+ canSeeSentinelInCwd,
+ canReadByRelative,
+ toolsDisabled,
+ repoRootInEnv: Object.values(ctx.env || {}).some(v => String(v).includes(repoRoot)),
+ })),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 1,
+ };
+ }),
+ });
+ assert.equal(r.ok, true);
+ assert.equal(captured.cwd, os.tmpdir());
+ assert.notEqual(path.resolve(captured.cwd), path.resolve(repoRoot));
+ const payload = JSON.parse(r.text);
+ assert.equal(payload.canSeeSentinelInCwd, false);
+ assert.equal(payload.canReadByRelative, false);
+ assert.equal(payload.toolsDisabled, true);
+ assert.equal(fs.existsSync(sentinelPath), true, 'sentinel remains in repo for the test harness only');
+ // Solver process env must not carry an easy pointer to the repo root.
+ assert.equal(payload.repoRootInEnv, false);
+ } finally {
+ try { fs.unlinkSync(sentinelPath); } catch (_) { /* ignore */ }
+ }
+});
+
+test('concurrency gate limits inflight executions', async () => {
+ const prev = _getInflight();
+ assert.equal(prev, 0);
+ let concurrent = 0;
+ let peak = 0;
+ const n = Math.min(6, MAX_DROID_INFLIGHT + 2);
+ const tasks = [];
+ for (let i = 0; i < n; i++) {
+ tasks.push(droidExecAsync({
+ model: 'fixture-model',
+ prompt: `c-${i}`,
+ runner: makeRunner(async () => {
+ concurrent += 1;
+ peak = Math.max(peak, concurrent);
+ await new Promise(resolve => setTimeout(resolve, 20));
+ concurrent -= 1;
+ return {
+ status: 0,
+ stdout: droidStdout('ok'),
+ stderr: '',
+ error: null,
+ timedOut: false,
+ durationMs: 20,
+ };
+ }),
+ }));
+ }
+ const results = await Promise.all(tasks);
+ assert.equal(results.every(r => r.ok), true);
+ assert.ok(peak <= MAX_DROID_INFLIGHT);
+ assert.equal(_getInflight(), 0);
+});
+
+test('usageSummary and aggregateUsage expose cost model version', () => {
+ const one = usageSummary({
+ input_tokens: 1000,
+ output_tokens: 500,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+ }, 'claude-sonnet-4-6');
+ assert.equal(one.cost_model_version, COST_MODEL_VERSION);
+ assert.ok(one.est_cost_usd > 0);
+ const agg = aggregateUsage([one, one]);
+ assert.equal(agg.input_tokens, 2000);
+ assert.equal(agg.cost_model_version, COST_MODEL_VERSION);
+});
+
+test('extractJson handles fences and prose', () => {
+ assert.deepEqual(extractJson('```json\n{"a":1}\n```'), { a: 1 });
+ assert.deepEqual(extractJson('answer is {"b":2} trailing'), { b: 2 });
+ assert.equal(extractJson('no json here'), null);
+});
+
+test('writeJsonAtomic is crash-safe rename and checkpoint keys bind identity', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'evals-io-'));
+ try {
+ const file = path.join(dir, 'out.json');
+ writeJsonAtomic(file, { hello: 'world' });
+ assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8')), { hello: 'world' });
+
+ const compatibilitySpec = {
+ studyId: 'study-a',
+ studyVersion: '1',
+ datasetSha256: 'd'.repeat(64),
+ promptSha256: 'p'.repeat(64),
+ skillSha256: 'k'.repeat(64),
+ solver: 'fixture-model',
+ judges: ['j2', 'j1'],
+ };
+ const compatibilityKey = checkpointKey(compatibilitySpec);
+ const study = writeStudyCheckpoint(dir, compatibilitySpec, { status: 'partial', n: 2 });
+ assert.equal(study.key, compatibilityKey);
+ assert.equal(readStudyCheckpoint(dir, compatibilitySpec).status, 'partial');
+
+ const observationSpec = {
+ compatibilityKey,
+ itemId: 'item-1',
+ trial: 1,
+ armId: 'lean',
+ };
+ const obsKey = observationCheckpointKey(observationSpec);
+ const obs = writeObservationCheckpoint(dir, observationSpec, { scored: true, value: 1 });
+ assert.equal(obs.key, obsKey);
+ const loaded = readObservationCheckpoint(dir, observationSpec);
+ assert.equal(loaded.scored, true);
+ assert.equal(loaded.item_id, 'item-1');
+ assert.equal(loaded.arm_id, 'lean');
+ assert.equal(loaded.trial, 1);
+
+ // Different arm => different observation checkpoint path.
+ assert.equal(
+ readObservationCheckpoint(dir, { ...observationSpec, armId: 'none' }),
+ null
+ );
+
+ // Legacy writeJson still works.
+ const legacy = path.join(dir, 'legacy.json');
+ writeJson(legacy, { ok: 1 });
+ assert.deepEqual(readJsonIfExists(legacy), { ok: 1 });
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('runHealthWarnings remains available', () => {
+ const warnings = runHealthWarnings({
+ solver_failures: 2,
+ solver_calls: 10,
+ failure_rate: 0.2,
+ decision_eligible: false,
+ });
+ assert.ok(warnings.some(w => w.code === 'solver_failure_rate_high'));
+ assert.ok(warnings.some(w => w.code === 'not_decision_eligible'));
+});
+
+test('isolationMetadata defaults to tmpdir and disabled tools', () => {
+ const meta = isolationMetadata({ isolate: true });
+ assert.equal(meta.enabled, true);
+ assert.equal(meta.effective_cwd, os.tmpdir());
+ assert.ok(meta.disabled_tools.includes('Read'));
+ assert.ok(meta.disabled_tools.includes('Skill'));
+});
diff --git a/evals/tests/judge.test.js b/evals/tests/judge.test.js
new file mode 100644
index 0000000..2e28141
--- /dev/null
+++ b/evals/tests/judge.test.js
@@ -0,0 +1,256 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+const {
+ normalizeJudgeWinner,
+ tallyJudgeVotes,
+ modelFamily,
+ judgesExcludingSolver,
+ decidePanelWinner,
+ evaluateJudgeCalibration,
+ DEFAULT_PANEL_MODELS,
+ FROZEN_PANEL,
+ JUDGE_CALIBRATION_THRESHOLDS,
+ panelModels,
+} = require('../lib/judge.js');
+
+test('DEFAULT_PANEL_MODELS is the frozen three-family panel', () => {
+ assert.deepStrictEqual([...DEFAULT_PANEL_MODELS], [
+ 'gpt-5.5-pro',
+ 'gemini-3.1-pro-preview',
+ 'deepseek-v4-pro',
+ ]);
+ assert.deepStrictEqual([...FROZEN_PANEL], [...DEFAULT_PANEL_MODELS]);
+});
+
+test('panelModels always returns frozen panel (env cannot override)', () => {
+ const prevJ = process.env.JUDGES;
+ const prevM = process.env.JUDGE_MODEL;
+ process.env.JUDGES = 'claude-sonnet-4-6,claude-opus-4-8';
+ process.env.JUDGE_MODEL = 'claude-haiku-4-5';
+ try {
+ assert.deepStrictEqual(panelModels(), [...DEFAULT_PANEL_MODELS]);
+ } finally {
+ if (prevJ === undefined) delete process.env.JUDGES; else process.env.JUDGES = prevJ;
+ if (prevM === undefined) delete process.env.JUDGE_MODEL; else process.env.JUDGE_MODEL = prevM;
+ }
+});
+
+test('normalizeJudgeWinner: preserves A/B and valid ties; null is missing', () => {
+ assert.strictEqual(normalizeJudgeWinner('A'), 'A');
+ assert.strictEqual(normalizeJudgeWinner('b'), 'B');
+ assert.strictEqual(normalizeJudgeWinner('TIE'), 'tie');
+ assert.strictEqual(normalizeJudgeWinner(' tie '), 'tie');
+ assert.strictEqual(normalizeJudgeWinner(null), null);
+ assert.strictEqual(normalizeJudgeWinner(undefined), null);
+ assert.strictEqual(normalizeJudgeWinner(''), null);
+ assert.strictEqual(normalizeJudgeWinner(null, { missingAsTie: true }), 'tie');
+});
+
+test('tallyJudgeVotes: valid ties counted; null/invalid are missing', () => {
+ const tally = tallyJudgeVotes([
+ { winner: 'A', valid: true },
+ { winner: 'TIE', valid: true },
+ { winner: 'tie', valid: true },
+ { winner: null, valid: false },
+ ]);
+ assert.deepStrictEqual(tally, { A: 1, B: 0, tie: 2, missing: 1 });
+});
+
+test('tallyJudgeVotes: multi-judge majority produces clear winner counts', () => {
+ const tally = tallyJudgeVotes([
+ { winner: 'A', valid: true },
+ { winner: 'A', valid: true },
+ { winner: 'B', valid: true },
+ ]);
+ assert.strictEqual(tally.A, 2);
+ assert.strictEqual(tally.B, 1);
+ assert.strictEqual(tally.tie, 0);
+ assert.strictEqual(tally.missing, 0);
+});
+
+test('decidePanelWinner: two matching valid A votes resolve', () => {
+ const d = decidePanelWinner({ A: 2, B: 1, tie: 0, missing: 0 });
+ assert.strictEqual(d.winner, 'A');
+ assert.strictEqual(d.resolved, true);
+ assert.strictEqual(d.unresolved, false);
+});
+
+test('decidePanelWinner: fewer than two matching valid votes is unresolved failure', () => {
+ const d = decidePanelWinner({ A: 1, B: 1, tie: 1, missing: 0 });
+ assert.strictEqual(d.winner, null);
+ assert.strictEqual(d.unresolved, true);
+ assert.ok(d.failure && d.failure.type === 'judge_unresolved');
+});
+
+test('decidePanelWinner: missing votes do not create a silent tie win', () => {
+ const d = decidePanelWinner({ A: 1, B: 0, tie: 0, missing: 2 });
+ assert.strictEqual(d.winner, null);
+ assert.strictEqual(d.unresolved, true);
+});
+
+test('decidePanelWinner: two explicit valid tie votes resolve as tie', () => {
+ const d = decidePanelWinner({ A: 0, B: 1, tie: 2, missing: 0 });
+ assert.strictEqual(d.winner, 'tie');
+ assert.strictEqual(d.resolved, true);
+ assert.strictEqual(d.unresolved, false);
+ assert.strictEqual(d.failure, null);
+});
+
+test('decidePanelWinner: three valid ties resolve as tie', () => {
+ const d = decidePanelWinner({ A: 0, B: 0, tie: 3, missing: 0 });
+ assert.strictEqual(d.winner, 'tie');
+ assert.strictEqual(d.resolved, true);
+});
+
+test('decidePanelWinner: one valid tie plus missing votes is unresolved failure', () => {
+ const d = decidePanelWinner({ A: 0, B: 0, tie: 1, missing: 2 });
+ assert.strictEqual(d.winner, null);
+ assert.strictEqual(d.unresolved, true);
+ assert.ok(d.failure && d.failure.type === 'judge_unresolved');
+});
+
+test('tally+decide: valid ties counted; failed votes do not manufacture a tie win', () => {
+ const tally = tallyJudgeVotes([
+ { winner: 'tie', valid: true },
+ { winner: null, valid: false },
+ { winner: null, valid: false },
+ ]);
+ assert.deepStrictEqual(tally, { A: 0, B: 0, tie: 1, missing: 2 });
+ const d = decidePanelWinner(tally);
+ assert.strictEqual(d.winner, null);
+ assert.strictEqual(d.unresolved, true);
+});
+
+test('tally+decide: two valid ties and one missing resolves as tie', () => {
+ const tally = tallyJudgeVotes([
+ { winner: 'tie', valid: true },
+ { winner: 'TIE', valid: true },
+ { winner: null, valid: false },
+ ]);
+ assert.deepStrictEqual(tally, { A: 0, B: 0, tie: 2, missing: 1 });
+ const d = decidePanelWinner(tally);
+ assert.strictEqual(d.winner, 'tie');
+ assert.strictEqual(d.resolved, true);
+});
+
+test('modelFamily: maps known model prefixes to families', () => {
+ assert.strictEqual(modelFamily('claude-sonnet-4-6'), 'claude');
+ assert.strictEqual(modelFamily('claude-opus-4-8'), 'claude');
+ assert.strictEqual(modelFamily('gpt-5.5-pro'), 'gpt');
+ assert.strictEqual(modelFamily('gemini-3.1-pro-preview'), 'gemini');
+ assert.strictEqual(modelFamily('deepseek-v4-pro'), 'deepseek');
+ assert.strictEqual(modelFamily('grok-imagine'), 'grok');
+ assert.strictEqual(modelFamily('glm-5.2'), 'glm');
+ assert.strictEqual(modelFamily('unknown-model'), 'unknown');
+});
+
+test('judgesExcludingSolver: removes same-family judges', () => {
+ const judges = ['gpt-5.5-pro', 'gemini-3.1-pro-preview', 'deepseek-v4-pro'];
+ const filtered = judgesExcludingSolver('claude-sonnet-4-6', judges);
+ assert.deepStrictEqual(filtered, judges);
+});
+
+test('judgesExcludingSolver: excludes solver family from panel', () => {
+ const judges = ['claude-opus-4-8', 'gpt-5.5-pro', 'gemini-3.1-pro-preview'];
+ const filtered = judgesExcludingSolver('claude-sonnet-4-6', judges);
+ assert.deepStrictEqual(filtered, ['gpt-5.5-pro', 'gemini-3.1-pro-preview']);
+});
+
+test('judgesExcludingSolver: no same-family fallback when <2 remain', () => {
+ const judges = ['claude-opus-4-8', 'claude-sonnet-4-6'];
+ const filtered = judgesExcludingSolver('claude-haiku-4-5', judges);
+ assert.deepStrictEqual(filtered, []);
+});
+
+test('judgesExcludingSolver: single independent judge is ineligible (empty)', () => {
+ const judges = ['claude-opus-4-8', 'gpt-5.5-pro'];
+ const filtered = judgesExcludingSolver('claude-sonnet-4-6', judges);
+ assert.deepStrictEqual(filtered, []);
+});
+
+test('judgesExcludingSolver: two same-family judges are ineligible', () => {
+ // length>=2 but only one independent family
+ const judges = ['gpt-5.5-pro', 'gpt-4o'];
+ const filtered = judgesExcludingSolver('claude-sonnet-4-6', judges);
+ assert.deepStrictEqual(filtered, []);
+});
+
+test('judgesExcludingSolver: unknown-family judges do not count toward independence', () => {
+ const judges = ['gpt-5.5-pro', 'mystery-model-x'];
+ const filtered = judgesExcludingSolver('claude-sonnet-4-6', judges);
+ assert.deepStrictEqual(filtered, []);
+});
+
+test('evaluateJudgeCalibration: passes approved thresholds', () => {
+ const ok = evaluateJudgeCalibration({
+ panel_majority_accuracy: 0.90,
+ per_judge_accuracy: { gpt: 0.80, gemini: 0.78, deepseek: 0.82 },
+ fleiss_kappa: 0.65,
+ order_effect_delta_pp: 2,
+ verbosity_effect_delta_pp: -1,
+ missing_vote_rate: 0.005,
+ n_pairs: 30,
+ });
+ assert.strictEqual(ok.ok, true);
+ assert.strictEqual(ok.eligible, true);
+ assert.strictEqual(ok.failures.length, 0);
+ assert.strictEqual(JUDGE_CALIBRATION_THRESHOLDS.panel_majority_accuracy_min, 0.85);
+});
+
+test('evaluateJudgeCalibration: fails when kappa or accuracy below gate', () => {
+ const bad = evaluateJudgeCalibration({
+ panel_majority_accuracy: 0.70,
+ per_judge_accuracy: [0.80, 0.80, 0.80],
+ fleiss_kappa: 0.40,
+ order_effect_delta_pp: 1,
+ verbosity_effect_delta_pp: 1,
+ missing_vote_rate: 0,
+ n_pairs: 30,
+ });
+ assert.strictEqual(bad.ok, false);
+ assert.ok(bad.failures.some(f => f.gate === 'panel_majority_accuracy'));
+ assert.ok(bad.failures.some(f => f.gate === 'fleiss_kappa'));
+});
+
+test('evaluateJudgeCalibration: missing n_pairs is ineligible', () => {
+ const bad = evaluateJudgeCalibration({
+ panel_majority_accuracy: 0.90,
+ per_judge_accuracy: { gpt: 0.80, gemini: 0.78, deepseek: 0.82 },
+ fleiss_kappa: 0.65,
+ order_effect_delta_pp: 1,
+ verbosity_effect_delta_pp: 1,
+ missing_vote_rate: 0,
+ });
+ assert.strictEqual(bad.ok, false);
+ assert.ok(bad.failures.some(f => f.gate === 'min_calibration_pairs'));
+});
+
+test('evaluateJudgeCalibration: empty per_judge_accuracy is ineligible', () => {
+ const bad = evaluateJudgeCalibration({
+ panel_majority_accuracy: 0.90,
+ per_judge_accuracy: [],
+ fleiss_kappa: 0.65,
+ order_effect_delta_pp: 1,
+ verbosity_effect_delta_pp: 1,
+ missing_vote_rate: 0,
+ n_pairs: 30,
+ });
+ assert.strictEqual(bad.ok, false);
+ assert.ok(bad.failures.some(f => f.gate === 'per_judge_accuracy'));
+});
+
+test('evaluateJudgeCalibration: requires all three panel models', () => {
+ const bad = evaluateJudgeCalibration({
+ panel_majority_accuracy: 0.90,
+ per_judge_accuracy: { gpt: 0.80, gemini: 0.80 },
+ fleiss_kappa: 0.65,
+ order_effect_delta_pp: 1,
+ verbosity_effect_delta_pp: 1,
+ missing_vote_rate: 0,
+ n_pairs: 30,
+ });
+ assert.strictEqual(bad.ok, false);
+ assert.ok(bad.failures.some(f => f.gate === 'per_judge_accuracy' && /deepseek/.test(String(f.judge || f.message || ''))));
+});
diff --git a/evals/tests/objective.test.js b/evals/tests/objective.test.js
new file mode 100644
index 0000000..84e288a
--- /dev/null
+++ b/evals/tests/objective.test.js
@@ -0,0 +1,441 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {
+ buildConditionPrompt,
+ buildNonePrompt,
+ buildEqualBudgetPlaceboPrompt,
+ buildContextPadding,
+ contextPaddingTokens,
+ neutralFiller,
+ normalizeCondition,
+ defaultTokenCounter,
+ wordCount,
+} = require('../lib/conditions');
+const {
+ SCORERS,
+ scoreBoolean,
+ scoreMultipleChoice,
+ scoreAbstention,
+ scoreNumericOrderOfMagnitude,
+ scoreProbabilityBrier,
+ parseFileLocalization,
+ scoreFileLocalization,
+ scoreWithAdapter,
+ runObjectiveItems,
+} = require('../lib/objective');
+const { validateResultEnvelope } = require('../lib/result');
+const { balancedAcc } = require('../run-routing-data');
+
+// --- conditions: primary none control + inert padding ---
+
+test('none is primary control and empty is a legacy alias', () => {
+ const problem = 'Should we ship?';
+ const none = buildConditionPrompt('none', problem, 'SKILL BODY', 'demo');
+ const empty = buildConditionPrompt('empty', problem, 'SKILL BODY', 'demo');
+ const helper = buildNonePrompt(problem);
+ assert.equal(normalizeCondition('empty'), 'none');
+ assert.equal(normalizeCondition('no_skill'), 'none');
+ assert.equal(none, empty);
+ assert.equal(none, helper);
+ assert.match(none, /Should we ship\?/);
+ assert.doesNotMatch(none, /THINKING SKILL|context-padding|PAD_/);
+});
+
+test('equal-budget placebo uses deterministic indexed context-padding tokens', () => {
+ const skill = 'alpha beta gamma delta epsilon';
+ const budget = defaultTokenCounter(skill);
+ const prompt = buildConditionPrompt('placebo', 'Q?', skill, 'demo');
+ const alias = buildEqualBudgetPlaceboPrompt('Q?', skill);
+ assert.match(prompt, /<context-padding>/);
+ assert.match(prompt, /PAD_0001/);
+ assert.match(prompt, new RegExp(`PAD_${String(budget).padStart(4, '0')}`));
+ assert.doesNotMatch(prompt, /read the request carefully|Software systems are made/);
+ assert.equal(normalizeCondition('equal_budget_placebo'), 'equal_budget_placebo');
+ assert.match(alias, /<context-padding>/);
+
+ const body = neutralFiller(budget);
+ assert.equal(defaultTokenCounter(body), budget);
+ assert.equal(contextPaddingTokens(3), 'PAD_0001 PAD_0002 PAD_0003');
+ assert.equal(wordCount(skill), budget);
+});
+
+test('injectable token counter sizes padding budget', () => {
+ const counter = (text) => String(text).length; // char counter
+ const pad = buildContextPadding(10, { tokenCounter: counter });
+ assert.match(pad, /<context-padding>/);
+ const inner = pad.replace(/<\/?context-padding>\n?/g, '').trim();
+ assert.ok(counter(inner) <= 10);
+ // buildConditionPrompt respects injected counter via options
+ const prompt = buildConditionPrompt('placebo', 'P', 'abcdefghij', 's', { tokenCounter: counter, tokenBudget: 5 });
+ assert.match(prompt, /context-padding/);
+});
+
+// --- scorers ---
+
+test('boolean scorer parses ANSWER and rejects missing parse', () => {
+ assert.equal(scoreBoolean('Reasoning.\nANSWER: Yes', true).correct, true);
+ assert.equal(scoreBoolean('ANSWER: no', false).correct, true);
+ assert.equal(scoreBoolean('ANSWER: Yes', false).correct, false);
+ const miss = scoreBoolean('I think maybe.', true);
+ assert.equal(miss.scored, false);
+ assert.equal(miss.failure.type, 'parse');
+});
+
+test('multiple choice requires letter and scores exact gold', () => {
+ assert.equal(scoreMultipleChoice('ANSWER: B', 'B').correct, true);
+ assert.equal(scoreMultipleChoice('ANSWER: C', 'B').correct, false);
+ const miss = scoreMultipleChoice('The answer is buried.', 'A');
+ assert.equal(miss.scored, false);
+ assert.equal(miss.failure.type, 'parse');
+});
+
+test('abstention distinguishes answerable vs unanswerable', () => {
+ assert.equal(scoreAbstention('ANSWER: 42', { answerable: true }).correct, true);
+ assert.equal(scoreAbstention('ANSWER: UNANSWERABLE', { answerable: false }).correct, true);
+ assert.equal(scoreAbstention('ANSWER: UNANSWERABLE', { answerable: true }).correct, false);
+ assert.equal(scoreAbstention('ANSWER: Paris', false).correct, false);
+});
+
+test('numeric order-of-magnitude and probability brier clamp', () => {
+ const num = scoreNumericOrderOfMagnitude('ANSWER: 1e3', 1000);
+ assert.equal(num.correct, true);
+ assert.equal(scoreNumericOrderOfMagnitude('ANSWER: 1e6', 1000, { tolerance: 1 }).correct, false);
+ const miss = scoreNumericOrderOfMagnitude('no number here', 10);
+ assert.equal(miss.scored, false);
+
+ const p = scoreProbabilityBrier('ANSWER: 150%', 1);
+ assert.equal(p.parsed, 1);
+ assert.equal(p.value.probability, 1);
+ assert.equal(p.correct, true);
+ const neg = scoreProbabilityBrier('ANSWER: -5%', 0);
+ assert.equal(neg.parsed, 0);
+ assert.ok(neg.value.brier === 0);
+});
+
+test('file localization requires single terminal ANSWER path in inventory', () => {
+ const inventory = ['src/a.js', 'src/b.js', 'lib/util.js'];
+ const ok = parseFileLocalization('notes\nANSWER: src/a.js\n', { repositoryFiles: inventory });
+ assert.equal(ok.ok, true);
+ assert.equal(ok.parsed, 'src/a.js');
+ assert.equal(scoreFileLocalization('ANSWER: ./src/a.js', ['src/a.js'], { repositoryFiles: inventory }).correct, true);
+
+ const multi = parseFileLocalization('ANSWER: src/a.js\nANSWER: src/b.js', { repositoryFiles: inventory });
+ assert.equal(multi.ok, false);
+ assert.match(multi.failure.message, /multiple ANSWER/);
+
+ const outside = parseFileLocalization('ANSWER: secret/path.py', { repositoryFiles: inventory });
+ assert.equal(outside.ok, false);
+ assert.match(outside.failure.message, /inventory/);
+
+ const dir = parseFileLocalization('ANSWER: src/\n', { repositoryFiles: inventory });
+ assert.equal(dir.ok, false);
+
+ const basenameOnly = scoreFileLocalization('The bug is in a.js somewhere', ['src/a.js'], { repositoryFiles: inventory });
+ assert.equal(basenameOnly.scored, false);
+ assert.equal(basenameOnly.failure.type, 'parse');
+
+ // backslash normalization
+ assert.equal(
+ scoreFileLocalization('ANSWER: src\\a.js', inventory, { repositoryFiles: inventory }).correct,
+ true,
+ );
+});
+
+test('file localization rejects trailing prose and duplicate identical ANSWER lines', () => {
+ const inventory = ['src/a.js', 'src/b.js'];
+
+ const trailing = parseFileLocalization('ANSWER: src/a.js\ntrailing prose', { repositoryFiles: inventory });
+ assert.equal(trailing.ok, false);
+ assert.match(trailing.failure.message, /not terminal|trailing/i);
+
+ const trailingSameLine = parseFileLocalization('notes\nANSWER: src/a.js and more text', { repositoryFiles: inventory });
+ assert.equal(trailingSameLine.ok, false);
+ assert.match(trailingSameLine.failure.message, /single terminal path|trailing|not terminal/i);
+ const trailingScore = scoreFileLocalization('notes\nANSWER: src/a.js and more text', ['src/a.js'], { repositoryFiles: inventory });
+ assert.equal(trailingScore.scored, false);
+ const dupIdentical = parseFileLocalization('ANSWER: src/a.js\nANSWER: src/a.js', { repositoryFiles: inventory });
+ assert.equal(dupIdentical.ok, false);
+ assert.match(dupIdentical.failure.message, /multiple ANSWER/);
+
+ const dupNormalized = parseFileLocalization('ANSWER: ./src/a.js\nANSWER: src/a.js', { repositoryFiles: inventory });
+ assert.equal(dupNormalized.ok, false);
+ assert.match(dupNormalized.failure.message, /multiple ANSWER/);
+
+ // whitespace after the sole ANSWER line is still terminal
+ const wsOk = parseFileLocalization('reasoning\nANSWER: src/a.js\n \n', { repositoryFiles: inventory });
+ assert.equal(wsOk.ok, true);
+ assert.equal(wsOk.parsed, 'src/a.js');
+});
+
+test('file localization rejects absolute drive UNC and parent paths', () => {
+ const inventory = ['src/a.js'];
+ for (const bad of [
+ 'ANSWER: /src/a.js',
+ 'ANSWER: /abs/path.js',
+ 'ANSWER: C:\\x',
+ 'ANSWER: C:/windows/system32/x',
+ 'ANSWER: \\\\server\\share\\file.js',
+ 'ANSWER: //server/share/file.js',
+ 'ANSWER: ../src/a.js',
+ 'ANSWER: foo/../../etc/passwd',
+ ]) {
+ const r = parseFileLocalization(bad, { repositoryFiles: inventory });
+ assert.equal(r.ok, false, `expected reject for ${bad}`);
+ assert.match(
+ r.failure.message,
+ /absolute|drive|UNC|parent/i,
+ `unexpected message for ${bad}: ${r.failure && r.failure.message}`,
+ );
+ }
+ // Leading slash must never be stripped into an inventory match.
+ const stripped = parseFileLocalization('ANSWER: /src/a.js', { repositoryFiles: inventory });
+ assert.equal(stripped.ok, false);
+ assert.notEqual(stripped.parsed, 'src/a.js');
+});
+
+test('scoreWithAdapter dispatches all registered scorers', () => {
+ assert.deepEqual(Object.keys(SCORERS).sort(), [
+ 'abstention',
+ 'boolean',
+ 'file_localization',
+ 'multiple_choice',
+ 'numeric_order_of_magnitude',
+ 'probability_brier',
+ ]);
+ assert.equal(scoreWithAdapter('boolean', 'ANSWER: Yes', true).correct, true);
+ assert.equal(scoreWithAdapter('unknown', 'x', true).failure.type, 'scoring');
+});
+
+// --- runObjectiveItems denominators ---
+
+test('runObjectiveItems retains every attempted arm/item/trial including failures', async () => {
+ const envelope = await runObjectiveItems({
+ studyId: 'obj-test',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'd'.repeat(64) },
+ arms: [
+ { id: 'none' },
+ { id: 'skill', skillContent: 'do the skill' },
+ ],
+ solver: { model: 'fixture-model', effort: 'low' },
+ scorer: 'boolean',
+ trials: 2,
+ items: [
+ {
+ id: 'i1',
+ prompt: 'Is 2 even?',
+ label: true,
+ fixture_responses: {
+ none: 'ANSWER: Yes',
+ skill: 'ANSWER: Yes',
+ },
+ },
+ {
+ id: 'i2',
+ prompt: 'Is sky green?',
+ label: false,
+ fixture_responses: {
+ none: 'not sure', // parse failure
+ skill: { ok: false, failure: { type: 'transport', message: 'timeout' } },
+ },
+ },
+ ],
+ });
+
+ // 2 items × 2 trials × 2 arms = 8 attempted rows, none dropped
+ assert.equal(envelope.items.length, 8);
+ assert.equal(envelope.health.attempted, 8);
+ assert.ok(envelope.health.failures >= 1);
+ assert.equal(envelope.health.decision_eligible, false);
+ assert.ok(envelope.items.every((row) => Object.prototype.hasOwnProperty.call(row, 'parsed_success')));
+ assert.ok(envelope.items.some((row) => row.failure && row.failure.type === 'parse'));
+ assert.ok(envelope.items.some((row) => row.failure && row.failure.type === 'transport'));
+ assert.ok(envelope.items.some((row) => row.scored && row.correct === true));
+ const v = validateResultEnvelope(envelope);
+ assert.equal(v.ok, true, v.errors && v.errors.join('; '));
+ assert.equal(envelope.usage.calls, 0);
+});
+
+test('none control prompt used for none arm; skill arm injects body', async () => {
+ const seen = [];
+ const envelope = await runObjectiveItems({
+ studyId: 'prompt-shape',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'd'.repeat(64) },
+ arms: [
+ { id: 'none' },
+ { id: 'equal_budget_placebo', skillContent: 'one two three four five' },
+ { id: 'skill', skillContent: 'UNIQUE_SKILL_BODY_XYZ' },
+ ],
+ solver: { model: 'fixture-model' },
+ scorer: 'boolean',
+ items: [{ id: 'only', prompt: 'Decide now', label: true }],
+ solve: async ({ armId, prompt }) => {
+ seen.push({ armId, prompt });
+ return { ok: true, text: 'ANSWER: Yes', usage: { calls: 1, input_tokens: 3, output_tokens: 1 } };
+ },
+ });
+ assert.equal(envelope.health.attempted, 3);
+ assert.equal(envelope.health.scored, 3);
+ const noneP = seen.find((s) => s.armId === 'none').prompt;
+ const placeP = seen.find((s) => s.armId === 'equal_budget_placebo').prompt;
+ const skillP = seen.find((s) => s.armId === 'skill').prompt;
+ assert.doesNotMatch(noneP, /UNIQUE_SKILL|context-padding/);
+ assert.match(placeP, /context-padding|PAD_/);
+ assert.match(skillP, /UNIQUE_SKILL_BODY_XYZ/);
+});
+
+// --- routing balanced accuracy nulls ---
+
+test('balanced accuracy treats null predictions as incorrect on both classes', () => {
+ const rows = [
+ { label: true, skill_yes: true },
+ { label: true, skill_yes: null }, // miss on positive
+ { label: false, skill_yes: false },
+ { label: false, skill_yes: null }, // must NOT count as TN
+ ];
+ // TPR = 1/2, TNR = 1/2 → 0.5 (if null counted as TN, TNR would be 1.0 and bal=0.75)
+ assert.equal(balancedAcc(rows, 'skill_yes'), 0.5);
+
+ const allNullNeg = [
+ { label: false, skill_yes: null },
+ { label: false, skill_yes: null },
+ { label: true, skill_yes: true },
+ ];
+ // TPR=1, TNR=0 → 0.5
+ assert.equal(balancedAcc(allNullNeg, 'skill_yes'), 0.5);
+});
+
+test('observation checkpoint invalidates when item prompt changes', async () => {
+ const base = {
+ studyId: 'obs-ckpt',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'd'.repeat(64) },
+ arms: [{ id: 'none' }],
+ solver: { model: 'fixture-model' },
+ scorer: 'boolean',
+ items: [{
+ id: 'i1',
+ prompt: 'original prompt text',
+ label: true,
+ fixture_responses: { none: 'ANSWER: Yes' },
+ }],
+ };
+ const a = await runObjectiveItems(base);
+ const b = await runObjectiveItems({
+ ...base,
+ items: [{
+ id: 'i1',
+ prompt: 'CHANGED prompt text',
+ label: true,
+ fixture_responses: { none: 'ANSWER: Yes' },
+ }],
+ });
+ assert.ok(a.items[0].observation_checkpoint_key);
+ assert.ok(b.items[0].observation_checkpoint_key);
+ assert.notEqual(
+ a.items[0].observation_checkpoint_key,
+ b.items[0].observation_checkpoint_key,
+ );
+ // identity key (study/item/trial/arm) stays the same
+ assert.equal(a.items[0].key, b.items[0].key);
+});
+
+test('arm prompt_sha256 aggregates all item prompts', async () => {
+ const mk = async (prompts, armExtra = {}) => runObjectiveItems({
+ studyId: 'arm-hash',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'd'.repeat(64) },
+ arms: [{ id: 'none', ...armExtra }],
+ solver: { model: 'fixture-model' },
+ scorer: 'boolean',
+ items: prompts.map((prompt, i) => ({
+ id: `i${i}`,
+ prompt,
+ label: true,
+ fixture_responses: { none: 'ANSWER: Yes' },
+ })),
+ });
+ const one = await mk(['only one']);
+ const two = await mk(['only one', 'second item prompt']);
+ const twoChanged = await mk(['only one', 'SECOND item prompt CHANGED']);
+ assert.notEqual(one.arms[0].prompt_sha256, two.arms[0].prompt_sha256);
+ assert.notEqual(two.arms[0].prompt_sha256, twoChanged.arms[0].prompt_sha256);
+
+ // Declared arm.prompt_sha256 must not mask second-item prompt changes.
+ const fixed = 'f'.repeat(64);
+ const withFixed = await mk(['only one', 'second item prompt'], { prompt_sha256: fixed });
+ const withFixedChanged = await mk(['only one', 'SECOND item prompt CHANGED'], { prompt_sha256: fixed });
+ assert.notEqual(withFixed.arms[0].prompt_sha256, withFixedChanged.arms[0].prompt_sha256);
+ assert.notEqual(withFixed.arms[0].prompt_sha256, fixed);
+});
+
+test('per_arm accuracy is ITT correct/attempted and failures do not shrink denominator', async () => {
+ const envelope = await runObjectiveItems({
+ studyId: 'itt-acc',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'd'.repeat(64) },
+ arms: [{ id: 'none' }],
+ solver: { model: 'fixture-model' },
+ scorer: 'boolean',
+ items: [
+ { id: 'ok', prompt: 'Q1', label: true, fixture_responses: { none: 'ANSWER: Yes' } },
+ { id: 'parse-fail', prompt: 'Q2', label: true, fixture_responses: { none: 'nope' } },
+ {
+ id: 'transport-fail',
+ prompt: 'Q3',
+ label: true,
+ fixture_responses: { none: { ok: false, failure: { type: 'transport', message: 'down' } } },
+ },
+ ],
+ });
+ const arm = envelope.statistics.per_arm.none;
+ assert.equal(arm.attempted, 3);
+ assert.equal(arm.scored, 1);
+ assert.equal(arm.correct, 1);
+ // ITT accuracy = 1/3, not 1/1
+ assert.equal(arm.accuracy, 1 / 3);
+ assert.equal(arm.conditional_accuracy, 1);
+ assert.equal(envelope.health.attempted, 3);
+ assert.equal(envelope.items.length, 3);
+});
+
+test('live solve usage counts attempts latency cache and estimated cost', async () => {
+ const envelope = await runObjectiveItems({
+ studyId: 'usage',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'smoke', sha256: 'd'.repeat(64) },
+ arms: [{ id: 'none' }],
+ solver: { model: 'fixture-model' },
+ scorer: 'boolean',
+ items: [{ id: 'one', prompt: 'Q', label: true }],
+ solve: async () => ({
+ ok: true,
+ text: 'ANSWER: Yes',
+ attempts: 1,
+ durationMs: 25,
+ usage: {
+ input_tokens: 7,
+ output_tokens: 3,
+ cache_read_tokens: 2,
+ est_cost_usd: 0.004,
+ },
+ }),
+ });
+ assert.deepEqual(envelope.usage, {
+ input_tokens: 7,
+ output_tokens: 3,
+ cached_tokens: 2,
+ calls: 1,
+ latency_ms: 25,
+ estimated_cost_usd: 0.004,
+ });
+});
diff --git a/evals/tests/pairwise.test.js b/evals/tests/pairwise.test.js
new file mode 100644
index 0000000..d058abf
--- /dev/null
+++ b/evals/tests/pairwise.test.js
@@ -0,0 +1,451 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {
+ deterministicArmOrder,
+ runPairwiseItems,
+ summarizePairwise,
+ normalizePanelResult,
+} = require('../lib/pairwise');
+const {
+ validateResultEnvelope,
+ observationCheckpointKey,
+ checkpointKey,
+ sha256,
+} = require('../lib/result');
+
+const JUDGES = ['gpt-5.5-pro', 'gemini-3.1-pro-preview', 'deepseek-v4-pro'];
+
+function baseSpec(overrides = {}) {
+ return {
+ studyId: 'pairwise-study',
+ studyVersion: '1',
+ preregistrationSha256: 'p'.repeat(64),
+ dataset: {
+ source: 'fixture',
+ version: '1',
+ split: 'heldout',
+ sha256: 'd'.repeat(64),
+ },
+ arms: [
+ { id: 'lean', prompt_sha256: 'a'.repeat(64), skill_sha256: 'b'.repeat(64) },
+ { id: 'none', prompt_sha256: 'c'.repeat(64), skill_sha256: null },
+ ],
+ pair: { left: 'lean', right: 'none' },
+ solver: { model: 'claude-sonnet-4-6', effort: 'low' },
+ judges: JUDGES,
+ items: [
+ { id: 'i1', prompt: 'Problem one' },
+ { id: 'i2', prompt: 'Problem two' },
+ ],
+ trials: 1,
+ seed: 42,
+ createdAt: '2026-07-17T00:00:00.000Z',
+ ...overrides,
+ };
+}
+
+function solveAllOk() {
+ return async ({ armId, item }) => ({
+ ok: true,
+ text: `answer for ${item.id} under ${armId}`,
+ usage: { input_tokens: 10, output_tokens: 5, calls: 1, latency_ms: 3 },
+ attempts: 1,
+ });
+}
+
+function judgeWinner(winner, opts = {}) {
+ return async (_prompt, judges = JUDGES) => {
+ if (opts.unresolved) {
+ return {
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ failure: { type: 'judge_unresolved', message: 'no majority' },
+ tally: { A: 1, B: 1, tie: 0, missing: 1 },
+ votes: (judges || JUDGES).map((model, i) => ({
+ model,
+ winner: i === 0 ? 'A' : i === 1 ? 'B' : null,
+ valid: i < 2,
+ })),
+ failures: [],
+ vocab_only: false,
+ whys: [],
+ judge_usage: [],
+ judge_durationMs: 1,
+ };
+ }
+ const w = winner;
+ return {
+ winner: w,
+ resolved: true,
+ unresolved: false,
+ failure: null,
+ tally: {
+ A: w === 'A' ? 2 : 0,
+ B: w === 'B' ? 2 : 0,
+ tie: w === 'tie' ? 2 : 0,
+ missing: 0,
+ },
+ votes: (judges || JUDGES).map(model => ({ model, winner: w, valid: true })),
+ failures: [],
+ vocab_only: false,
+ whys: [`fixture ${w}`],
+ judge_usage: [{ input_tokens: 1, output_tokens: 1, est_cost_usd: 0 }],
+ judge_durationMs: 2,
+ };
+ };
+}
+
+test('deterministicArmOrder is stable for the same seed/item/trial', () => {
+ const a = deterministicArmOrder(['lean', 'none'], { seed: 7, itemId: 'x', trial: 1 });
+ const b = deterministicArmOrder(['lean', 'none'], { seed: 7, itemId: 'x', trial: 1 });
+ assert.deepEqual(a, b);
+ assert.equal(a.length, 2);
+ assert.ok(a.includes('lean') && a.includes('none'));
+});
+
+test('deterministicArmOrder changes with seed, item, or trial', () => {
+ const base = deterministicArmOrder(['lean', 'none', 'full'], { seed: 1, itemId: 'i', trial: 1 });
+ const bySeed = deterministicArmOrder(['lean', 'none', 'full'], { seed: 2, itemId: 'i', trial: 1 });
+ const byItem = deterministicArmOrder(['lean', 'none', 'full'], { seed: 1, itemId: 'j', trial: 1 });
+ const byTrial = deterministicArmOrder(['lean', 'none', 'full'], { seed: 1, itemId: 'i', trial: 2 });
+ // At least one of the knobs must flip order for this 3-arm set (very high probability; assert not all equal).
+ const same = (x, y) => x.join('|') === y.join('|');
+ assert.equal(same(base, bySeed) && same(base, byItem) && same(base, byTrial), false);
+});
+
+test('deterministicArmOrder is independent of input arm array order', () => {
+ const a = deterministicArmOrder(['lean', 'none'], { seed: 99, itemId: 'p', trial: 3 });
+ const b = deterministicArmOrder(['none', 'lean'], { seed: 99, itemId: 'p', trial: 3 });
+ assert.deepEqual(a, b);
+});
+
+test('runPairwiseItems produces valid envelope with complete denominators', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec(),
+ solve: solveAllOk(),
+ judge: judgeWinner('A'),
+ });
+
+ const v = validateResultEnvelope(envelope);
+ assert.equal(v.ok, true, v.errors && v.errors.join('; '));
+ assert.equal(envelope.schema_version, 1);
+ assert.equal(envelope.health.attempted, 2);
+ assert.equal(envelope.health.completed, 2);
+ assert.equal(envelope.health.parsed, 2);
+ assert.equal(envelope.health.scored, 2);
+ assert.equal(envelope.health.failures, 0);
+ assert.equal(envelope.health.decision_eligible, true);
+ assert.equal(envelope.items.length, 2);
+ for (const row of envelope.items) {
+ assert.equal(row.completed, true);
+ assert.equal(row.parsed_success, true);
+ assert.equal(row.scored, true);
+ assert.ok(row.parsed && row.parsed.winner_arm);
+ assert.ok(row.observation_checkpoint_keys.lean);
+ assert.ok(row.observation_checkpoint_keys.none);
+ assert.ok(row.item_keys.lean.includes('pairwise-study:i'));
+ }
+ assert.ok(envelope.usage.calls >= 2);
+ assert.equal(envelope.statistics.attempted, 2);
+ assert.equal(envelope.statistics.wins + envelope.statistics.losses + envelope.statistics.ties, 2);
+});
+
+test('fresh independent solve calls per arm and trial', async () => {
+ const calls = [];
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ trials: 2, items: [{ id: 'only', prompt: 'p' }] }),
+ solve: async ({ armId, trial, item }) => {
+ calls.push(`${item.id}:${trial}:${armId}`);
+ return { ok: true, text: `${armId}-${trial}`, usage: { calls: 1 } };
+ },
+ judge: judgeWinner('B'),
+ });
+ assert.equal(envelope.health.attempted, 2);
+ assert.deepEqual(calls.sort(), [
+ 'only:1:lean',
+ 'only:1:none',
+ 'only:2:lean',
+ 'only:2:none',
+ ].sort());
+});
+
+test('solver failures remain in denominators and block scoring', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: async ({ armId }) => {
+ if (armId === 'none') {
+ return {
+ ok: false,
+ text: null,
+ failure: { type: 'timeout', message: 'solver timed out' },
+ usage: { calls: 1 },
+ };
+ }
+ return { ok: true, text: 'ok', usage: { calls: 1 } };
+ },
+ judge: judgeWinner('A'),
+ });
+
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.completed, 0);
+ assert.equal(envelope.health.parsed, 0);
+ assert.equal(envelope.health.scored, 0);
+ assert.ok(envelope.health.failures >= 1);
+ assert.equal(envelope.health.decision_eligible, false);
+ assert.equal(envelope.items[0].scored, false);
+ assert.equal(envelope.items[0].parsed_success, false);
+ assert.equal(envelope.items[0].completed, false);
+ assert.ok(envelope.failures.some(f => f.type === 'timeout'));
+ assert.equal(envelope.statistics.unresolved, 1);
+});
+
+test('unresolved disagreement keeps parsed_success true and scored false', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ // Two valid A/B votes that disagree → unresolved scoring failure, not parse failure.
+ judge: judgeWinner('A', { unresolved: true }),
+ });
+
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.completed, 1);
+ assert.equal(envelope.health.parsed, 1);
+ assert.equal(envelope.health.scored, 0);
+ assert.equal(envelope.health.decision_eligible, false);
+ assert.equal(envelope.items[0].winner_arm, null);
+ assert.equal(envelope.items[0].scored, false);
+ assert.equal(envelope.items[0].parsed_success, true);
+ assert.ok(envelope.items[0].parsed && envelope.items[0].parsed.unresolved === true);
+ assert.ok(envelope.failures.some(f => f.type === 'scoring'));
+ assert.equal(envelope.statistics.ties, 0);
+ assert.equal(envelope.statistics.unresolved, 1);
+});
+
+test('unresolved with no valid votes leaves parsed_success false', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ judge: async (_prompt, judges = JUDGES) => ({
+ winner: null,
+ resolved: false,
+ unresolved: true,
+ failure: { type: 'parse', message: 'all judges unparseable' },
+ tally: { A: 0, B: 0, tie: 0, missing: (judges || JUDGES).length },
+ votes: (judges || JUDGES).map(model => ({
+ model,
+ winner: null,
+ valid: false,
+ failure: { type: 'parse', message: 'bad json' },
+ })),
+ failures: [],
+ vocab_only: false,
+ whys: [],
+ judge_usage: [],
+ judge_durationMs: 0,
+ }),
+ });
+ assert.equal(envelope.health.completed, 1);
+ assert.equal(envelope.health.parsed, 0);
+ assert.equal(envelope.health.scored, 0);
+ assert.equal(envelope.items[0].parsed_success, false);
+ assert.ok(envelope.failures.some(f => f.type === 'parse'));
+});
+
+test('maps panel A/B through presentation order onto left/right arms', async () => {
+ const seed = 0;
+ const order = deterministicArmOrder(['lean', 'none'], { seed, itemId: 'i1', trial: 1 });
+ const leftIsA = order[0] === 'lean';
+
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ seed, items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ judge: judgeWinner('A'),
+ });
+
+ const row = envelope.items[0];
+ assert.deepEqual(row.arm_order, order);
+ assert.equal(row.left_is_a, leftIsA);
+ // Winner label A means presentation arm A.
+ assert.equal(row.winner_label, 'A');
+ assert.equal(row.winner_arm, order[0]);
+ if (leftIsA) {
+ assert.equal(envelope.statistics.wins, 1);
+ } else {
+ assert.equal(envelope.statistics.losses, 1);
+ }
+});
+
+test('observation checkpoint keys bind item trial arm to compatibility', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ judge: judgeWinner('B'),
+ });
+ const row = envelope.items[0];
+ const expectedLean = observationCheckpointKey({
+ compatibilityKey: row.compatibility_key,
+ itemId: 'i1',
+ trial: 1,
+ armId: 'lean',
+ });
+ assert.equal(row.observation_checkpoint_keys.lean, expectedLean);
+ assert.notEqual(row.observation_checkpoint_keys.lean, row.observation_checkpoint_keys.none);
+});
+
+test('ineligible same-family judge panel records failure and never silent-fallback', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({
+ solver: { model: 'gpt-4o', effort: 'low' },
+ judges: ['gpt-5.5-pro', 'gpt-4.1'], // all gpt → judgesExcludingSolver returns []
+ items: [{ id: 'i1', prompt: 'p' }],
+ }),
+ solve: solveAllOk(),
+ judge: judgeWinner('A'),
+ });
+ assert.equal(envelope.judges.length, 0);
+ assert.equal(envelope.health.panel_eligible, false);
+ assert.equal(envelope.health.decision_eligible, false);
+ assert.ok(envelope.failures.some(f => /ineligible judge panel/i.test(f.message)));
+ assert.equal(envelope.items[0].scored, false);
+});
+
+test('buildJudgePrompt rejection becomes explicit parse failure row', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ judge: judgeWinner('A'),
+ buildJudgePrompt: async () => {
+ throw new Error('prompt builder boom');
+ },
+ });
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.completed, 1);
+ assert.equal(envelope.health.parsed, 0);
+ assert.equal(envelope.health.scored, 0);
+ assert.equal(envelope.health.decision_eligible, false);
+ assert.equal(envelope.items[0].scored, false);
+ assert.equal(envelope.items[0].parsed_success, false);
+ assert.ok(envelope.failures.some(f => f.type === 'parse' && /prompt builder boom/.test(f.message)));
+});
+
+test('judgeFn throw remains transport failure not parse', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: solveAllOk(),
+ judge: async () => {
+ throw new Error('judge transport down');
+ },
+ });
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.completed, 1);
+ assert.equal(envelope.health.parsed, 0);
+ assert.equal(envelope.health.scored, 0);
+ assert.ok(envelope.failures.some(f => f.type === 'transport' && /judge transport down/.test(f.message)));
+ assert.equal(envelope.failures.some(f => f.type === 'parse'), false);
+});
+
+test('summarizePairwise ITT win_rate uses attempted denominator', () => {
+ const summary = summarizePairwise([
+ { scored: true, winner_arm: 'lean', left_is_a: true, pair: 'lean:none' },
+ { scored: true, winner_arm: 'none', left_is_a: true, pair: 'lean:none' },
+ { scored: true, winner_arm: 'tie', left_is_a: false, pair: 'lean:none' },
+ { scored: false, failure: { type: 'transport' }, left_is_a: true, pair: 'lean:none' },
+ ], { left: 'lean', right: 'none' });
+ assert.equal(summary.attempted, 4);
+ assert.equal(summary.wins, 1);
+ assert.equal(summary.losses, 1);
+ assert.equal(summary.ties, 1);
+ assert.equal(summary.unresolved, 1);
+ assert.equal(summary.solver_failures, 1);
+ // ITT: (1 + 0.5*1) / 4 = 0.375 — unresolved stays in denominator
+ assert.equal(summary.win_rate, 0.375);
+ // Conditional (judged-only): (1 + 0.5) / 3 = 0.5
+ assert.equal(summary.conditional_win_rate, 0.5);
+ assert.equal(summary.order_balance.left_is_a, 3);
+ assert.equal(summary.order_balance.left_is_b, 1);
+});
+
+test('fixture unresolved row keeps primary win_rate ITT denominator', async () => {
+ const items = [
+ { id: 'ok', prompt: 'resolved case' },
+ { id: 'bad', prompt: 'unresolved case' },
+ ];
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items, seed: 7 }),
+ solve: solveAllOk(),
+ // Resolved item: always award left arm (lean). Unresolved item: panel failure.
+ judge: async (prompt, judges) => {
+ if (String(prompt).includes('unresolved case')) {
+ return judgeWinner('A', { unresolved: true })(prompt, judges);
+ }
+ // Infer presentation from responses tags embedded by default solve text.
+ // Default solve text is `answer for ${id} under ${armId}` — A block has first arm.
+ const aMatch = String(prompt).match(/=== RESPONSE A ===\nanswer for ok under (\w+)/);
+ const armA = aMatch ? aMatch[1] : 'lean';
+ const label = armA === 'lean' ? 'A' : 'B';
+ return judgeWinner(label)(prompt, judges);
+ },
+ });
+ assert.equal(envelope.health.attempted, 2);
+ assert.equal(envelope.health.scored, 1);
+ assert.equal(envelope.statistics.attempted, 2);
+ assert.equal(envelope.statistics.unresolved, 1);
+ assert.equal(envelope.statistics.judged, 1);
+ assert.equal(envelope.statistics.wins, 1);
+ assert.equal(envelope.statistics.losses, 0);
+ // ITT: 1/2; conditional: 1/1 — unresolved stays in primary denominator.
+ assert.equal(envelope.statistics.win_rate, 0.5);
+ assert.equal(envelope.statistics.conditional_win_rate, 1);
+});
+
+test('normalizePanelResult never promotes unresolved to tie', () => {
+ const n = normalizePanelResult({
+ winner: 'tie',
+ unresolved: true,
+ failure: { type: 'judge_unresolved', message: 'bad' },
+ votes: [],
+ tally: { A: 0, B: 0, tie: 0, missing: 3 },
+ });
+ assert.equal(n.winner, null);
+ assert.equal(n.unresolved, true);
+ assert.equal(n.failure.type, 'scoring');
+});
+
+test('usage aggregates solver and judge calls', async () => {
+ const envelope = await runPairwiseItems({
+ ...baseSpec({ items: [{ id: 'i1', prompt: 'p' }] }),
+ solve: async () => ({
+ ok: true,
+ text: 'x',
+ usage: { input_tokens: 4, output_tokens: 2, calls: 1, latency_ms: 5, estimated_cost_usd: 0.01 },
+ }),
+ judge: judgeWinner('A'),
+ });
+ // 2 solves + judge usage calls
+ assert.ok(envelope.usage.calls >= 2);
+ assert.ok(envelope.usage.input_tokens >= 8);
+ assert.ok(envelope.usage.latency_ms >= 10);
+ assert.ok(envelope.usage.estimated_cost_usd >= 0.02);
+});
+
+test('checkpoint_key matches shared compatibility hash', async () => {
+ const spec = baseSpec({ items: [{ id: 'i1', prompt: 'p' }] });
+ const envelope = await runPairwiseItems({
+ ...spec,
+ solve: solveAllOk(),
+ judge: judgeWinner('A'),
+ });
+ const expected = checkpointKey({
+ studyId: spec.studyId,
+ studyVersion: spec.studyVersion,
+ datasetSha256: spec.dataset.sha256,
+ promptSha256: sha256(spec.arms.map(a => a.prompt_sha256 || null)),
+ skillSha256: sha256(spec.arms.map(a => a.skill_sha256 || null)),
+ solver: spec.solver.model,
+ judges: JUDGES,
+ });
+ assert.equal(envelope.checkpoint_key, expected);
+});
diff --git a/evals/tests/registry-evidence.test.js b/evals/tests/registry-evidence.test.js
new file mode 100644
index 0000000..169228d
--- /dev/null
+++ b/evals/tests/registry-evidence.test.js
@@ -0,0 +1,273 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+const crypto = require('crypto');
+
+const {
+ loadRegistry,
+ validateRegistry,
+ loadAndValidateRegistry,
+ getSkillBudget,
+ getDeclaredStudyBundle,
+} = require('../lib/registry');
+const {
+ listDeclaredBundles,
+ evaluateConfirmationEligibility,
+ readDeclaredBundle,
+ verifyArchiveObject,
+ healthComplete,
+ powerConfigPresent,
+} = require('../lib/evidence');
+const {
+ classifyArtifact,
+ generateClaimLedger,
+ evaluateStudyClaim,
+} = require('../lib/claims');
+
+test('registry loads 39 skills with 28 survivors and 11 deletions', () => {
+ const { registry, validation } = loadAndValidateRegistry();
+ assert.equal(validation.ok, true, validation.errors.join('; '));
+ assert.equal(Object.keys(registry.skills).length, 39);
+ assert.equal(registry.catalog.survivors.length, 28);
+ assert.equal(registry.catalog.deletions.length, 11);
+ assert.equal(registry.gates.utility_margin_pp, 5);
+ assert.equal(registry.gates.noninferiority_margin_pp, 3);
+ assert.equal(registry.gates.harm_margin_pp, 2);
+ assert.equal(registry.gates.efficacy_hypotheses, 84);
+ assert.equal(registry.judge_panel.models.length, 3);
+ assert.ok(registry.judge_panel.max_votes_per_item >= registry.judge_panel.min_valid_votes_to_decide);
+ assert.ok(registry.arms.all.includes('none'));
+ assert.ok(registry.arms.all.includes('lean'));
+ assert.ok(registry.arms.all.includes('workflow'));
+ assert.equal(getSkillBudget(registry, 'systems'), 950);
+ assert.equal(getSkillBudget(registry, 'scientific-method'), 900);
+ assert.equal(registry.skills['dual-process'].disposition.cutover, 'delete');
+ assert.equal(registry.skills.systems.disposition.cutover, 'survive');
+});
+
+test('judge panel calibration is blocked_missing_human_labels and manual-only', () => {
+ const { registry, validation } = loadAndValidateRegistry();
+ assert.equal(validation.ok, true, validation.errors.join('; '));
+ assert.equal(registry.judge_panel.calibration_status, 'blocked_missing_human_labels');
+ assert.equal(registry.judge_panel.decision_eligible, false);
+ assert.equal(registry.judge_panel.judged_studies_policy_while_blocked, 'manual_only');
+ assert.equal(registry.judge_panel.human_labeled_pairs.count, 0);
+ const contract = registry.study_contracts.judge_panel_calibration;
+ assert.ok(contract);
+ assert.equal(contract.status, 'blocked_missing_human_labels');
+ assert.equal(contract.decision_eligible, false);
+ assert.equal(contract.rule.judged_studies_while_blocked, 'manual_only');
+ const bundle = getDeclaredStudyBundle(registry, 'judge-panel-calibration');
+ assert.ok(bundle);
+ assert.equal(bundle.decision_eligible, false);
+ assert.equal(bundle.judged_studies_policy, 'manual_only');
+ assert.equal(bundle.declared_inline, true);
+});
+
+test('judged bundle cannot confirm while panel calibration is blocked', () => {
+ const { registry } = loadRegistry();
+ // Inject a temporary judged declaration with path for evaluation shape only
+ const judgedId = 'fixture-judged-blocked';
+ registry.declared_study_bundles = [
+ ...(registry.declared_study_bundles || []),
+ {
+ study_id: judgedId,
+ path: 'evals/studies/legacy-july-wf-confirm-behavioral',
+ kind: 'judged',
+ requires_judges: true,
+ confirmatory_eligible_by_default: true,
+ },
+ ];
+ const evaluation = evaluateConfirmationEligibility({
+ studyId: judgedId,
+ registry,
+ });
+ assert.equal(evaluation.confirmatory, false);
+ assert.ok(evaluation.blockers.some(b => /judge panel calibration blocked|manual_only/.test(b)));
+});
+
+test('registry validator errors on wrong gates and missing family_counts', () => {
+ const { registry } = loadRegistry();
+ const badGates = JSON.parse(JSON.stringify(registry));
+ badGates.gates.utility_margin_pp = 4;
+ const g = validateRegistry(badGates);
+ assert.equal(g.ok, false);
+ assert.ok(g.errors.some(e => /utility_margin_pp/.test(e)));
+
+ const badFamily = JSON.parse(JSON.stringify(registry));
+ delete badFamily.family_counts;
+ const f = validateRegistry(badFamily);
+ assert.equal(f.ok, false);
+ assert.ok(f.errors.some(e => /family_counts/.test(e)));
+});
+
+test('verifyExactHashes fails closed without path/payload verification targets', () => {
+ const { verifyExactHashes } = require('../lib/evidence');
+ const presenceOnly = verifyExactHashes({
+ preregistration: { sha256: 'a'.repeat(64) },
+ dataset: { sha256: 'b'.repeat(64) },
+ solver: { model: 'claude-sonnet-4-6' },
+ arms: [{ id: 'lean', prompt_sha256: 'c'.repeat(64), skill_sha256: 'd'.repeat(64) }],
+ judges: ['gpt-5.5-pro'],
+ }, null);
+ assert.equal(presenceOnly.ok, false);
+ assert.ok(presenceOnly.reasons.some(r => /prompt_sha256 not byte-verifiable|solver config/.test(r)));
+ assert.ok(presenceOnly.reasons.some(r => /judge/.test(r)));
+});
+
+test('verifyExactHashes requires prereg verification target not mere presence', () => {
+ const { verifyExactHashes } = require('../lib/evidence');
+ const presenceOnly = verifyExactHashes({
+ preregistration_sha256: 'a'.repeat(64),
+ dataset: { path: 'evals/datasets/workflow-cases.jsonl', sha256: 'b'.repeat(64) },
+ solver: { model: 'm', config: { x: 1 }, config_sha256: require('../lib/result').sha256({ x: 1 }) },
+ arms: [{
+ id: 'none',
+ prompt_sha256: require('../lib/result').sha256('p'),
+ prompt: 'p',
+ skill_sha256: null,
+ }],
+ judges: [{ model: 'j', config: { j: 1 }, config_sha256: require('../lib/result').sha256({ j: 1 }) }],
+ }, null);
+ assert.equal(presenceOnly.ok, false);
+ assert.ok(presenceOnly.reasons.some(r => /preregistration_sha256 not verifiable|prereg/.test(r)));
+
+ const withCurrent = verifyExactHashes({
+ preregistration_sha256: 'a'.repeat(64),
+ dataset: { path: 'evals/datasets/workflow-cases.jsonl', sha256: require('../lib/evidence').fileSha256(require('path').join(__dirname, '..', 'datasets', 'workflow-cases.jsonl')) },
+ solver: { model: 'm', config: { x: 1 }, config_sha256: require('../lib/result').sha256({ x: 1 }) },
+ arms: [{
+ id: 'none',
+ prompt_sha256: require('../lib/result').sha256('p'),
+ prompt: 'p',
+ skill_sha256: null,
+ }],
+ judges: [{ model: 'j', config: { j: 1 }, config_sha256: require('../lib/result').sha256({ j: 1 }) }],
+ }, null, { currentPreregSha256: 'a'.repeat(64) });
+ // may still fail on other fields; prereg itself should not be the missing-target reason
+ assert.ok(!withCurrent.reasons.some(r => /not verifiable \(need currentPreregSha256/.test(r)));
+});
+
+test('registry validator rejects judge panel that cannot meet min votes', () => {
+ const { registry } = loadRegistry();
+ const bad = JSON.parse(JSON.stringify(registry));
+ bad.judge_panel.votes_per_item = 1;
+ bad.judge_panel.min_valid_votes_to_decide = 2;
+ bad.judge_panel.max_votes_per_item = 1;
+ const result = validateRegistry(bad);
+ assert.equal(result.ok, false);
+ assert.ok(result.errors.some(e => /max_votes_per_item|votes_per_item/.test(e)));
+});
+
+test('registry makes unknown and inadequate data explicit', () => {
+ const { registry, validation } = loadAndValidateRegistry();
+ assert.equal(validation.ok, true, validation.errors.join('; '));
+ assert.ok(Array.isArray(registry.data_adequacy.unknown_skill_ids));
+ assert.ok(Array.isArray(registry.data_adequacy.inadequate_skill_ids));
+ assert.ok(registry.data_adequacy.unknown_skill_ids.length > 0);
+ for (const id of registry.data_adequacy.unknown_skill_ids) {
+ assert.equal(registry.skills[id].data.status, 'unknown');
+ assert.ok(registry.skills[id].data.gaps.length > 0);
+ }
+ for (const id of registry.data_adequacy.inadequate_skill_ids) {
+ assert.equal(registry.skills[id].data.status, 'inadequate');
+ assert.ok(registry.skills[id].data.gaps.length > 0);
+ }
+});
+
+test('healthComplete requires parsed and equal denominators', () => {
+ assert.equal(healthComplete({
+ attempted: 2, completed: 2, scored: 2, failures: 0, decision_eligible: true,
+ }).ok, false);
+ assert.ok(healthComplete({
+ attempted: 2, completed: 2, scored: 2, failures: 0, decision_eligible: true,
+ }).reasons.some(r => /parsed/.test(r)));
+
+ assert.equal(healthComplete({
+ attempted: 2, completed: 2, parsed: 1, scored: 1, failures: 0, decision_eligible: true,
+ }).ok, false);
+
+ assert.equal(healthComplete({
+ attempted: 2, completed: 2, parsed: 2, scored: 2, failures: 0, decision_eligible: true,
+ }).ok, true);
+});
+
+test('undeclared study bundles cannot be read for confirmation', () => {
+ const evaluation = evaluateConfirmationEligibility({ studyId: 'not-a-real-study' });
+ assert.equal(evaluation.confirmatory, false);
+ assert.equal(evaluation.status, 'undeclared_bundle');
+ assert.throws(() => readDeclaredBundle('not-a-real-study'), /undeclared/);
+});
+
+test('legacy july bundle is declared but not confirmatory without gates', () => {
+ const { registry } = loadRegistry();
+ assert.ok(getDeclaredStudyBundle(registry, 'legacy-july-sci-method-larger-n'));
+ const evaluation = evaluateStudyClaim('legacy-july-sci-method-larger-n', registry);
+ assert.equal(evaluation.confirmatory, false);
+ assert.ok(evaluation.blockers.length > 0);
+ // provisional evidence and missing archive should surface
+ assert.ok(evaluation.blockers.some(b => /archive|replication|power|split|evidence_validity|prereg|health/i.test(b)));
+});
+
+test('confirmation requires archive readback and matching sha', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'evidence-archive-'));
+ const payload = Buffer.from('raw-response-bytes');
+ const file = path.join(tmp, 'raw.bin');
+ fs.writeFileSync(file, payload);
+ const digest = crypto.createHash('sha256').update(payload).digest('hex');
+
+ const ok = verifyArchiveObject({ uri: file, sha256: digest });
+ assert.equal(ok.ok, true);
+
+ const bad = verifyArchiveObject({ uri: file, sha256: '0'.repeat(64) });
+ assert.equal(bad.ok, false);
+ assert.ok(bad.reasons.some(r => /mismatch/.test(r)));
+
+ const absent = verifyArchiveObject({ status: 'absent', uri: null });
+ assert.equal(absent.ok, false);
+});
+
+test('powerConfigPresent rejects legacy powered-only flags', () => {
+ const gates = { power_target: 0.9 };
+ assert.equal(powerConfigPresent({ power: { powered: true, power_target: 0.95 } }, gates).ok, false);
+ assert.equal(powerConfigPresent({
+ power: {
+ power_target: 0.95,
+ multiplicity_adjusted: true,
+ disposition_rule: 'AUTO-RETAIN LEAN',
+ decision_eligible: true,
+ },
+ }, gates).ok, true);
+});
+
+test('classifyArtifact never marks legacy scan as confirmatory', () => {
+ const artifact = {
+ claim_status: 'confirmed',
+ mode: 'objective',
+ run_health: { decision_eligible: true, failure_rate: 0, solver_failures: 0 },
+ };
+ const c = classifyArtifact(artifact);
+ assert.equal(c.eligible, true);
+ assert.equal(c.confirmatory_eligible, false);
+});
+
+test('generateClaimLedger includes declared bundle evaluations', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'claims-ledger-'));
+ const ledger = generateClaimLedger(tmp, path.join(__dirname, '..', 'preregistrations', 'workflow-vs-skill-proof.md'));
+ assert.ok(Array.isArray(ledger.declared_bundle_evaluations));
+ assert.ok(ledger.declared_bundle_evaluations.length >= 1);
+ assert.ok(ledger.claims.some(c => c.source === 'declared_bundle'));
+ assert.ok(ledger.claims.every(c => c.source !== 'declared_bundle' || c.confirmatory_eligible === false || c.confirmatory_eligible === true));
+ // no declared july bundle should currently be confirmatory
+ assert.ok(ledger.claims.filter(c => c.source === 'declared_bundle').every(c => c.confirmatory_eligible === false));
+});
+
+test('listDeclaredBundles only returns registry entries', () => {
+ const bundles = listDeclaredBundles();
+ assert.ok(bundles.length >= 7);
+ assert.ok(bundles.every(b => b.study_id && (b.path || b.declared_inline)));
+});
diff --git a/evals/tests/registry-validation.test.js b/evals/tests/registry-validation.test.js
new file mode 100644
index 0000000..d523aa9
--- /dev/null
+++ b/evals/tests/registry-validation.test.js
@@ -0,0 +1,289 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+
+const {
+ validateSkillContent,
+ validateAllSkills,
+ DEFAULT_REQUIRED_SECTIONS,
+} = require('../../scripts/validate-skills');
+const {
+ validateDatasetSplits,
+ validateAuthoredFile,
+ promptHash,
+ resolveExternalReportPath,
+ REPO_ROOT,
+} = require('../validate-dataset-splits');
+
+const LEAN_BODY = `---
+name: thinking-example
+description: Short situation-named description under two hundred characters.
+---
+
+## When to Use
+Use when X is observed.
+
+## When NOT to Use
+Do not use for routine Y.
+
+## Procedure
+1. Observe evidence.
+2. Decide.
+
+## Output
+Return a decision artifact.
+
+## Verification
+Stop if evidence is missing.
+`;
+
+test('required sections are When to Use / NOT / Procedure / Output / Verification', () => {
+ assert.deepEqual(DEFAULT_REQUIRED_SECTIONS, [
+ 'When to Use',
+ 'When NOT to Use',
+ 'Procedure',
+ 'Output',
+ 'Verification',
+ ]);
+ const ok = validateSkillContent(LEAN_BODY, {
+ name: 'thinking-example',
+ maxWords: 100,
+ enforceBudget: true,
+ });
+ assert.equal(ok.pass, true, JSON.stringify(ok.failed));
+});
+
+test('validator fails missing required sections and overlong description', () => {
+ const body = `---
+name: thinking-example
+description: ${'x'.repeat(201)}
+---
+
+## Overview
+Old shape only.
+`;
+ const result = validateSkillContent(body, {
+ name: 'thinking-example',
+ maxWords: 50,
+ enforceBudget: true,
+ });
+ assert.equal(result.pass, false);
+ const failedNames = result.failed.map(f => f.name);
+ assert.ok(failedNames.includes('Description Length'));
+ assert.ok(failedNames.some(n => n.includes('When to Use')));
+ assert.ok(failedNames.some(n => n.includes('When NOT to Use')));
+ assert.ok(failedNames.some(n => n.includes('Procedure')));
+ assert.ok(failedNames.some(n => n.includes('Output')));
+ assert.ok(failedNames.some(n => n.includes('Verification')));
+});
+
+test('word budget failure is observable for survivors', () => {
+ const words = Array.from({ length: 120 }, () => 'word').join(' ');
+ const body = `---
+name: thinking-example
+description: ok description
+---
+
+## When to Use
+x
+
+## When NOT to Use
+y
+
+## Procedure
+z
+
+## Output
+o
+
+## Verification
+v
+
+${words}
+`;
+ const result = validateSkillContent(body, {
+ name: 'thinking-example',
+ maxWords: 50,
+ enforceBudget: true,
+ });
+ assert.equal(result.pass, false);
+ assert.ok(result.failed.some(f => f.name === 'Word Budget'));
+});
+
+test('current pre-rewrite catalog fails new structural requirements (observable, not weakened)', () => {
+ const report = validateAllSkills();
+ assert.equal(report.found_count, 39);
+ assert.equal(report.expected_count, 39);
+ // Pre-rewrite skills lack lean sections; failures must remain visible
+ assert.equal(report.ok, false);
+ assert.ok(report.failed.length > 0, 'expected pre-rewrite skills to fail new section requirements');
+ const sample = report.failed[0];
+ assert.ok(sample.failed.length > 0);
+ // Ensure we did not silently filter failures
+ assert.equal(report.summary.failed, report.failed.length);
+ assert.equal(report.summary.total, 39);
+});
+
+test('validate-skills does not write quality-report.json', () => {
+ const reportPath = path.join(__dirname, '..', '..', 'scripts', 'quality-report.json');
+ const before = fs.existsSync(reportPath) ? fs.statSync(reportPath).mtimeMs : null;
+ // invoke pure API only
+ validateAllSkills();
+ const after = fs.existsSync(reportPath) ? fs.statSync(reportPath).mtimeMs : null;
+ assert.equal(after, before);
+});
+
+test('global split validator checks ids and clusters without requiring tracked output', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'split-val-'));
+ const authored = path.join(tmp, 'authored');
+ fs.mkdirSync(authored);
+ // two rows same cluster across splits -> fail
+ const rows = [
+ {
+ id: 'a1',
+ prompt: 'hello one',
+ cluster_id: 'c1',
+ source_family: 'f',
+ split: 'dev',
+ cluster_basis: 'x',
+ },
+ {
+ id: 'a2',
+ prompt: 'hello two',
+ cluster_id: 'c1',
+ source_family: 'f',
+ split: 'heldout',
+ cluster_basis: 'x',
+ },
+ ];
+ fs.writeFileSync(path.join(authored, 'sample.jsonl'), rows.map(r => JSON.stringify(r)).join('\n') + '\n');
+
+ const fileResult = validateAuthoredFile('sample.jsonl', authored);
+ assert.equal(fileResult.status, 'failed');
+ assert.ok(fileResult.errors.some(e => /cluster overlap/.test(e)));
+
+ // prompt hash helper is stable
+ assert.equal(promptHash({ prompt: 'abc' }), promptHash({ prompt: 'abc' }));
+ assert.notEqual(promptHash({ prompt: 'abc' }), promptHash({ prompt: 'abd' }));
+
+ // full validator on real tree should return structure and not throw
+ const real = validateDatasetSplits();
+ assert.ok(real.summary);
+ assert.ok(Array.isArray(real.authored));
+ assert.ok(Array.isArray(real.workflow));
+ assert.ok(real.global);
+ // ensure workflow-cases-replication is included when present
+ assert.ok(real.workflow.some(w => w.file.includes('replication')) || !fs.existsSync(path.join(__dirname, '..', 'datasets', 'workflow-cases-replication.jsonl')));
+});
+
+test('global validator detects cross-file authored id collisions', () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'split-global-'));
+ const authored = path.join(tmp, 'authored');
+ const workflow = path.join(tmp, 'workflow');
+ fs.mkdirSync(authored);
+ fs.mkdirSync(workflow);
+ const row = {
+ id: 'dup-id',
+ prompt: 'unique prompt text alpha',
+ cluster_id: 'cluster-a',
+ source_family: 'f',
+ split: 'dev',
+ cluster_basis: 'x',
+ };
+ const row2 = {
+ id: 'dup-id',
+ prompt: 'unique prompt text beta',
+ cluster_id: 'cluster-b',
+ source_family: 'f',
+ split: 'heldout',
+ cluster_basis: 'y',
+ };
+ fs.writeFileSync(path.join(authored, 'one.jsonl'), JSON.stringify(row) + '\n');
+ fs.writeFileSync(path.join(authored, 'two.jsonl'), JSON.stringify(row2) + '\n');
+ const report = validateDatasetSplits({
+ authoredDir: authored,
+ workflowDir: workflow,
+ workflowFiles: [],
+ });
+ assert.equal(report.ok, false);
+ assert.ok(report.global.errors.some(e => /global duplicate id/.test(e)));
+});
+
+test('EVAL_SPLIT_OUT refuses in-repo paths and leaves them absent', () => {
+ const inRepo = path.join(REPO_ROOT, 'evals', 'results', 'latest', 'dataset-split-validation.json');
+ const decision = resolveExternalReportPath(inRepo, REPO_ROOT);
+ assert.equal(decision.ok, false);
+ assert.match(decision.reason, /outside the repository/);
+
+ const external = path.join(os.tmpdir(), `split-out-${Date.now()}.json`);
+ const ok = resolveExternalReportPath(external, REPO_ROOT);
+ assert.equal(ok.ok, true);
+ assert.equal(ok.path, path.resolve(external));
+
+ // Ensure resolve helper does not create the refused path
+ // (file may already exist historically; only assert helper refusal).
+ assert.ok(!decision.ok);
+});
+
+test('workflow base and expanded share heldout; cluster overlap is not leakage', () => {
+ const {
+ validateGlobal,
+ effectiveSplit,
+ } = require('../validate-dataset-splits');
+
+ assert.equal(effectiveSplit({ kind: 'workflow', role: 'base' }), 'heldout');
+ assert.equal(effectiveSplit({ kind: 'workflow', role: 'expanded' }), 'heldout');
+ assert.equal(effectiveSplit({ kind: 'workflow', role: 'replication' }), 'replication');
+ assert.equal(effectiveSplit({ kind: 'authored', role: 'dev' }), 'dev');
+
+ const authoredResults = [{
+ file: 'a.jsonl',
+ rows: [{
+ id: 'auth-1',
+ prompt: 'authored heldout prompt',
+ cluster_id: 'auth-heldout-cluster',
+ source_family: 'f',
+ split: 'heldout',
+ cluster_basis: 'x',
+ }],
+ }];
+ const sharedCluster = 'wf-shared-cluster';
+ const workflowResults = [
+ {
+ file: 'workflow-cases.jsonl',
+ role: 'base',
+ rows: [{
+ id: 'wf-base-1',
+ case_brief: 'workflow base brief one',
+ cluster_id: sharedCluster,
+ }],
+ },
+ {
+ file: 'workflow-cases-expanded.jsonl',
+ role: 'expanded',
+ rows: [{
+ id: 'wf-exp-1',
+ case_brief: 'workflow expanded brief two',
+ cluster_id: sharedCluster,
+ }],
+ },
+ ];
+
+ const global = validateGlobal(authoredResults, workflowResults);
+ assert.ok(!global.errors.some(e => /wf-shared-cluster/.test(e)), global.errors.join('; '));
+ // still flag true cross-split leakage
+ const leak = validateGlobal(authoredResults, [{
+ file: 'workflow-cases-replication.jsonl',
+ role: 'replication',
+ rows: [{
+ id: 'wf-repl-1',
+ case_brief: 'replication brief',
+ cluster_id: 'auth-heldout-cluster',
+ }],
+ }]);
+ assert.ok(leak.errors.some(e => /auth-heldout-cluster/.test(e) && /effective heldout and replication/.test(e)));
+});
diff --git a/evals/tests/replication.test.js b/evals/tests/replication.test.js
index 6d9f1a5..6edfaae 100644
--- a/evals/tests/replication.test.js
+++ b/evals/tests/replication.test.js
@@ -2,7 +2,10 @@
const test = require('node:test');
const assert = require('node:assert');
-const { verdict, VERDICT } = require('../run-replication.js');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { verdict, VERDICT, parseResultsFile, aggregateJsonlRows } = require('../run-replication.js');
// --- McNemar alias coverage (via stats.js import) ---
test('mcnemarFull: cc and midp alias values are present and consistent', () => {
@@ -117,9 +120,6 @@ test('verdict: accepts p field as alias for p_value', () => {
// --- parseResultsFile: pretty-JSON support ---
test('parseResultsFile: handles pretty-printed JSON with delta_pp/mcnemar_p/significant', () => {
- const { parseResultsFile } = require('../run-replication.js');
- const fs = require('fs');
- const path = require('path');
// Use a real objective-runner result file to test pretty-JSON parsing
const realFile = path.join(__dirname, '..', 'results', 'run1', 'swe-five-whys-plus-improved.json');
assert.ok(fs.existsSync(realFile), 'test fixture file must exist');
@@ -130,3 +130,56 @@ test('parseResultsFile: handles pretty-printed JSON with delta_pp/mcnemar_p/sign
assert.strictEqual(result.n, 150, 'n should be 150');
});
+test('aggregateJsonlRows: averages pre-aggregated delta_pp rows', () => {
+ const agg = aggregateJsonlRows([
+ { delta_pp: 10, p_value: 0.01, n: 20 },
+ { delta_pp: 6, p_value: 0.02, n: 20 },
+ ]);
+ assert.ok(Math.abs(agg.delta_pp - 8) < 1e-9);
+ assert.strictEqual(agg.p_value, 0.02); // max p (conservative)
+ assert.strictEqual(agg.n, 40);
+ assert.strictEqual(agg.failures, 0);
+});
+
+test('aggregateJsonlRows: paired binary observations produce risk-diff pp', () => {
+ const rows = [
+ { skill_correct: true, placebo_correct: false, item_id: '1' },
+ { skill_correct: true, placebo_correct: false, item_id: '2' },
+ { skill_correct: true, placebo_correct: true, item_id: '3' },
+ { skill_correct: false, placebo_correct: false, item_id: '4' },
+ ];
+ const agg = aggregateJsonlRows(rows);
+ // mean RD = (1+1+0+0)/4 = 0.5 → 50pp
+ assert.ok(Math.abs(agg.delta_pp - 50) < 1e-6, `expected 50pp, got ${agg.delta_pp}`);
+ assert.strictEqual(agg.n, 4);
+ assert.strictEqual(agg.aggregation, 'paired_binary');
+ assert.ok(typeof agg.p_value === 'number');
+});
+
+test('parseResultsFile: JSONL paired binary aggregation', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'repl-'));
+ const file = path.join(dir, 'rows.jsonl');
+ const lines = [
+ JSON.stringify({ treatment: 1, control: 0, item_id: 'a' }),
+ JSON.stringify({ treatment: 1, control: 0, item_id: 'b' }),
+ JSON.stringify({ treatment: 1, control: 0, item_id: 'c' }),
+ JSON.stringify({ treatment: 0, control: 0, item_id: 'd' }),
+ ];
+ fs.writeFileSync(file, lines.join('\n'));
+ const result = parseResultsFile(file);
+ assert.ok(result);
+ assert.ok(result.delta_pp > 0);
+ assert.strictEqual(result.n, 4);
+ assert.strictEqual(result.failures, 0);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+test('parseResultsFile: counts unparseable paired fields as failures without dropping attempted rows from report', () => {
+ const agg = aggregateJsonlRows([
+ { treatment: 1, control: 0 },
+ { treatment: 'x', control: 0 }, // failure
+ { skill_correct: true, placebo_correct: false },
+ ]);
+ assert.strictEqual(agg.failures, 1);
+ assert.strictEqual(agg.n, 2);
+});
diff --git a/evals/tests/result.test.js b/evals/tests/result.test.js
new file mode 100644
index 0000000..cfd3709
--- /dev/null
+++ b/evals/tests/result.test.js
@@ -0,0 +1,99 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const {
+ stableStringify,
+ sha256,
+ itemKey,
+ checkpointKey,
+ observationCheckpointKey,
+ failureRecord,
+ createResultEnvelope,
+ validateResultEnvelope,
+} = require('../lib/result');
+
+function baseSpec() {
+ return {
+ study_id: 'study-1',
+ study_version: '1',
+ preregistration_sha256: 'a'.repeat(64),
+ dataset: { source: 'fixture', version: '1', split: 'heldout', sha256: 'b'.repeat(64) },
+ arms: [{ id: 'none', prompt_sha256: 'c'.repeat(64), skill_sha256: null }],
+ solver: { model: 'fixture-model', effort: 'low' },
+ judges: [],
+ items: [{ item_id: 'one', parsed_success: true, scored: true }],
+ failures: [],
+ created_at: '2026-07-17T00:00:00.000Z',
+ };
+}
+
+test('stable serialization and hashing ignore object key order', () => {
+ assert.equal(stableStringify({ b: 2, a: { d: 4, c: 3 } }), '{"a":{"c":3,"d":4},"b":2}');
+ assert.equal(sha256({ b: 2, a: 1 }), sha256({ a: 1, b: 2 }));
+});
+
+test('item identity includes study item trial and arm', () => {
+ assert.equal(itemKey({ studyId: 's', itemId: 'i', trial: 2, armId: 'lean' }), 's:i:2:lean');
+ assert.throws(() => itemKey({ studyId: 's', itemId: 'i', trial: 0, armId: 'lean' }), /positive integer/);
+});
+
+test('checkpoint changes for every compatibility input', () => {
+ const spec = { studyId: 's', studyVersion: '1', datasetSha256: 'd', promptSha256: 'p', skillSha256: 'k', solver: 'm', judges: ['j2', 'j1'] };
+ const key = checkpointKey(spec);
+ assert.equal(key, checkpointKey({ ...spec, judges: ['j1', 'j2'] }));
+ for (const [field, value] of [['studyVersion', '2'], ['datasetSha256', 'x'], ['promptSha256', 'x'], ['skillSha256', 'x'], ['solver', 'x']]) {
+ assert.notEqual(key, checkpointKey({ ...spec, [field]: value }));
+ }
+});
+
+test('observation checkpoint binds item trial and arm to compatibility', () => {
+ const compatibilityKey = checkpointKey({
+ studyId: 's',
+ studyVersion: '1',
+ datasetSha256: 'd',
+ promptSha256: 'p',
+ skillSha256: 'k',
+ solver: 'm',
+ judges: [],
+ });
+ const spec = { compatibilityKey, itemId: 'i', trial: 1, armId: 'lean' };
+ const key = observationCheckpointKey(spec);
+ assert.notEqual(key, observationCheckpointKey({ ...spec, itemId: 'j' }));
+ assert.notEqual(key, observationCheckpointKey({ ...spec, trial: 2 }));
+ assert.notEqual(key, observationCheckpointKey({ ...spec, armId: 'none' }));
+ assert.notEqual(key, observationCheckpointKey({ ...spec, compatibilityKey: 'x' }));
+});
+
+test('failure records reject unknown classes', () => {
+ assert.equal(failureRecord({ type: 'parse', message: 'bad json', itemId: 'i' }).type, 'parse');
+ assert.throws(() => failureRecord({ type: 'mystery' }), /unsupported/);
+});
+
+test('result envelope derives complete health and validates', () => {
+ const envelope = createResultEnvelope(baseSpec());
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.scored, 1);
+ assert.equal(envelope.health.parsed, 1);
+ assert.equal(envelope.health.decision_eligible, true);
+ assert.equal(validateResultEnvelope(envelope).ok, true);
+});
+
+test('unscored or failed attempts remain ineligible', () => {
+ const spec = baseSpec();
+ spec.items = [{ item_id: 'one', parsed_success: false, scored: false }];
+ spec.failures = [failureRecord({ type: 'scoring', message: 'no label', itemId: 'one' })];
+ const envelope = createResultEnvelope(spec);
+ assert.equal(envelope.health.attempted, 1);
+ assert.equal(envelope.health.scored, 0);
+ assert.equal(envelope.health.failures, 1);
+ assert.equal(envelope.health.decision_eligible, false);
+});
+
+test('validator rejects internally impossible health', () => {
+ const envelope = createResultEnvelope(baseSpec());
+ envelope.health.scored = 2;
+ const result = validateResultEnvelope(envelope);
+ assert.equal(result.ok, false);
+ assert.match(result.errors.join('\n'), /scored cannot exceed parsed/);
+});
diff --git a/evals/tests/stats.test.js b/evals/tests/stats.test.js
index a606460..adf64d2 100644
--- a/evals/tests/stats.test.js
+++ b/evals/tests/stats.test.js
@@ -2,7 +2,20 @@
const test = require('node:test');
const assert = require('node:assert');
-const { scoreDistractor, pairedDiff, mcnemarFull, mcnemarMidp, summarize } = require('../lib/stats.js');
+const {
+ scoreDistractor,
+ pairedDiff,
+ mcnemarFull,
+ mcnemarMidp,
+ summarize,
+ clampProbability,
+ clusterBootstrapPairedRiskDiff,
+ clusterRandomizationTest,
+ holmAdjustment,
+ ratioBootstrapInterval,
+ validatePowerConfig,
+ meanPairedRiskDiff,
+} = require('../lib/stats.js');
test('distractor scoring: fixed fixture computes correct FPR/FNR/net_utility', () => {
// Fixture: 3 target (2 hit, 1 miss), 3 off-target (1 wrongly fires, 2 correctly silent)
@@ -89,6 +102,29 @@ test('summarize: preserves all five legacy fields', () => {
assert.strictEqual(s.decisive, 10);
});
+test('summarize: powered is false without explicit power config even if CI excludes null', () => {
+ // 20/0 decisive → CI far above 0.5, but still not decision-powered
+ const s = summarize(20, 0, 0);
+ assert.strictEqual(s.ci_excludes_null, true);
+ assert.strictEqual(s.powered, false);
+ assert.strictEqual(s.decision_eligible, false);
+});
+
+test('summarize: decision_eligible only with validated power config + achieved flag', () => {
+ const cfg = {
+ family_size: 84,
+ alpha_family: 0.05,
+ target_power: 0.90,
+ margin: 0.05,
+ seed: 42,
+ method: 'cluster-bootstrap-holm',
+ achieved_power_ok: true,
+ };
+ const s = summarize(20, 0, 0, cfg);
+ assert.strictEqual(s.powered, true);
+ assert.strictEqual(s.decision_eligible, true);
+});
+
test('mcnemarFull: exposes validation-compatible alias fields cc and midp', () => {
const result = mcnemarFull(8, 2);
// Aliases must be present
@@ -110,3 +146,167 @@ test('mcnemarFull: legacy mcnemar scalar unchanged on (8,2) ~0.114', () => {
assert.ok(Math.abs(p - 0.114) < 0.003, `legacy mcnemar(8,2) should be ~0.114, got ${p}`);
});
+test('clampProbability: clamps to [0,1] and rejects non-finite', () => {
+ assert.strictEqual(clampProbability(-0.2), 0);
+ assert.strictEqual(clampProbability(1.5), 1);
+ assert.strictEqual(clampProbability(0.3), 0.3);
+ assert.strictEqual(clampProbability(null), null);
+ assert.strictEqual(clampProbability(NaN), null);
+});
+
+test('clusterBootstrapPairedRiskDiff: deterministic for fixed seed', () => {
+ const obs = [
+ { treatment: 1, control: 0, leakage_family: 'f1', item_id: 'a' },
+ { treatment: 1, control: 0, leakage_family: 'f1', item_id: 'a' }, // nested trial
+ { treatment: 0, control: 0, leakage_family: 'f2', item_id: 'b' },
+ { treatment: 1, control: 1, leakage_family: 'f3', item_id: 'c' },
+ { treatment: 1, control: 0, leakage_family: 'f4', item_id: 'd' },
+ ];
+ const a = clusterBootstrapPairedRiskDiff(obs, { seed: 7, resamples: 500 });
+ const b = clusterBootstrapPairedRiskDiff(obs, { seed: 7, resamples: 500 });
+ assert.strictEqual(a.estimate, b.estimate);
+ assert.deepStrictEqual(a.ci, b.ci);
+ assert.strictEqual(a.n_clusters, 4);
+ assert.ok(a.estimate > 0);
+});
+
+test('clusterBootstrapPairedRiskDiff: hierarchical nesting resamples items within family', () => {
+ // Two families; family f1 has two items with opposite effects.
+ // Flat family-only resampling would always keep both items together and
+ // never vary their relative weight. Hierarchical item-level resampling
+ // changes the estimate distribution — CI should be non-degenerate.
+ const obs = [
+ { treatment: 1, control: 0, leakage_family: 'f1', item_id: 'a1', trial: 0 },
+ { treatment: 1, control: 0, leakage_family: 'f1', item_id: 'a1', trial: 1 },
+ { treatment: 0, control: 1, leakage_family: 'f1', item_id: 'a2', trial: 0 },
+ { treatment: 0, control: 1, leakage_family: 'f1', item_id: 'a2', trial: 1 },
+ { treatment: 1, control: 0, leakage_family: 'f2', item_id: 'b1', trial: 0 },
+ { treatment: 1, control: 0, leakage_family: 'f2', item_id: 'b1', trial: 1 },
+ ];
+ const { buildHierarchy } = require('../lib/stats.js');
+ const h = buildHierarchy(obs);
+ assert.strictEqual(h.length, 2, 'two families');
+ assert.strictEqual(h.find(f => f.key === 'fam:f1').items.length, 2, 'f1 has two items');
+ const r = clusterBootstrapPairedRiskDiff(obs, { seed: 11, resamples: 1000 });
+ assert.strictEqual(r.method, 'hierarchical-cluster-bootstrap-paired-rd');
+ assert.strictEqual(r.n_clusters, 2);
+ assert.strictEqual(r.n_items, 3);
+ // Nested resampling produces a CI with positive width
+ assert.ok(r.ci[1] > r.ci[0], `expected non-degenerate CI, got ${r.ci}`);
+});
+
+test('clusterRandomizationTest: null-ish data yields high p; strong signal lower p', () => {
+ const nullish = [
+ { treatment: 1, control: 1, item_id: 'a' },
+ { treatment: 0, control: 0, item_id: 'b' },
+ { treatment: 1, control: 1, item_id: 'c' },
+ ];
+ const strong = [
+ { treatment: 1, control: 0, item_id: 'a' },
+ { treatment: 1, control: 0, item_id: 'b' },
+ { treatment: 1, control: 0, item_id: 'c' },
+ { treatment: 1, control: 0, item_id: 'd' },
+ { treatment: 1, control: 0, item_id: 'e' },
+ { treatment: 1, control: 0, item_id: 'f' },
+ ];
+ const pNull = clusterRandomizationTest(nullish, { seed: 1, resamples: 1000 });
+ const pStrong = clusterRandomizationTest(strong, { seed: 1, resamples: 1000 });
+ assert.ok(pNull.p_value > 0.2, `nullish p should be high, got ${pNull.p_value}`);
+ assert.ok(pStrong.p_value < 0.05, `strong p should be small, got ${pStrong.p_value}`);
+});
+
+test('holmAdjustment: adjusts family of p-values monotonically', () => {
+ const adj = holmAdjustment([0.001, 0.04, 0.03]);
+ assert.strictEqual(adj.length, 3);
+ assert.ok(adj[0].p_adjusted <= adj[1].p_adjusted || adj[0].p <= adj[1].p);
+ // Smallest raw p gets rank 1
+ const ranks = adj.map(a => a.rank).sort();
+ assert.deepStrictEqual(ranks, [1, 2, 3]);
+ assert.ok(adj.every(a => a.p_adjusted >= a.p - 1e-12));
+ assert.ok(adj.every(a => a.p_adjusted <= 1));
+});
+
+test('ratioBootstrapInterval: deterministic ratio CI', () => {
+ const obs = [
+ { numerator: 80, denominator: 100, item_id: 'a' },
+ { numerator: 70, denominator: 100, item_id: 'b' },
+ { numerator: 90, denominator: 100, item_id: 'c' },
+ ];
+ const r1 = ratioBootstrapInterval(obs, { seed: 3, resamples: 400 });
+ const r2 = ratioBootstrapInterval(obs, { seed: 3, resamples: 400 });
+ assert.deepStrictEqual(r1.ci, r2.ci);
+ assert.ok(Math.abs(r1.estimate - 0.8) < 1e-9);
+ assert.ok(r1.ci[0] <= r1.estimate && r1.estimate <= r1.ci[1]);
+});
+
+test('validatePowerConfig: requires family size, power, margin, seed, method', () => {
+ const bad = validatePowerConfig({});
+ assert.strictEqual(bad.ok, false);
+ assert.ok(bad.errors.length >= 3);
+
+ const good = validatePowerConfig({
+ family_size: 84,
+ alpha_family: 0.05 / 84,
+ target_power: 0.90,
+ margin: 0.05,
+ seed: 123,
+ method: 'cluster-bootstrap-holm',
+ });
+ assert.strictEqual(good.ok, true);
+});
+
+test('validatePowerConfig: rejects fractional H, infinite power, nonpositive margin', () => {
+ assert.strictEqual(validatePowerConfig({
+ family_size: 2.5,
+ alpha_family: 0.05,
+ target_power: 0.90,
+ margin: 0.05,
+ seed: 1,
+ method: 'x',
+ }).ok, false);
+
+ assert.strictEqual(validatePowerConfig({
+ family_size: 10,
+ alpha_family: 0.05,
+ target_power: Infinity,
+ margin: 0.05,
+ seed: 1,
+ method: 'x',
+ }).ok, false);
+
+ assert.strictEqual(validatePowerConfig({
+ family_size: 10,
+ alpha_family: 0.05,
+ target_power: 0.90,
+ margin: 0,
+ seed: 1,
+ method: 'x',
+ }).ok, false);
+
+ assert.strictEqual(validatePowerConfig({
+ family_size: 10,
+ alpha_family: 0.05,
+ target_power: 0.90,
+ margin: -0.01,
+ seed: 1,
+ method: 'x',
+ }).ok, false);
+
+ assert.strictEqual(validatePowerConfig({
+ family_size: 10,
+ alpha_family: 0.05,
+ target_power: 0.90,
+ margin: 0.05,
+ seed: '',
+ method: 'x',
+ }).ok, false);
+});
+
+test('meanPairedRiskDiff: simple average of treatment-control', () => {
+ const obs = [
+ { treatment: 1, control: 0 },
+ { treatment: 1, control: 1 },
+ { treatment: 0, control: 0 },
+ ];
+ assert.ok(Math.abs(meanPairedRiskDiff(obs) - (1 / 3)) < 1e-12);
+});
diff --git a/evals/tests/validate-judge-write.test.js b/evals/tests/validate-judge-write.test.js
new file mode 100644
index 0000000..f75632d
--- /dev/null
+++ b/evals/tests/validate-judge-write.test.js
@@ -0,0 +1,24 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert');
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+const { writeJson } = require('../lib/io.js');
+
+test('writeJson API is (file, obj) — path.join for filename', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vj-'));
+ const file = path.join(dir, 'judge-reliability-test.json');
+ writeJson(file, { agreement: { percent: 1 }, n: 0 });
+ const loaded = JSON.parse(fs.readFileSync(file, 'utf8'));
+ assert.strictEqual(loaded.agreement.percent, 1);
+ assert.strictEqual(loaded.n, 0);
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+test('validate-judge module still exports agreement and biasDetection', () => {
+ const vj = require('../validate-judge.js');
+ assert.strictEqual(typeof vj.agreement, 'function');
+ assert.strictEqual(typeof vj.biasDetection, 'function');
+});
diff --git a/evals/validate-dataset-splits.js b/evals/validate-dataset-splits.js
new file mode 100755
index 0000000..8b2d113
--- /dev/null
+++ b/evals/validate-dataset-splits.js
@@ -0,0 +1,462 @@
+#!/usr/bin/env node
+'use strict';
+
+/**
+ * Global split/provenance validator for eval datasets.
+ *
+ * Checks IDs, recomputed prompt hashes, and semantic clusters across all
+ * authored and workflow base/expanded/replication files.
+ * Does not write tracked files. Optional EVAL_SPLIT_OUT must resolve outside the repo.
+ *
+ * Usage: node evals/validate-dataset-splits.js
+ * Optional: EVAL_SPLIT_OUT=/tmp/x.json to write a non-repo report.
+ */
+
+const fs = require('fs');
+const path = require('path');
+const crypto = require('crypto');
+
+const REPO_ROOT = path.resolve(path.join(__dirname, '..'));
+const AUTHORED_DIR = path.join(__dirname, 'datasets', 'authored');
+const WORKFLOW_DIR = path.join(__dirname, 'datasets');
+
+const WORKFLOW_FILES = [
+ 'workflow-cases.jsonl',
+ 'workflow-cases-expanded.jsonl',
+ 'workflow-cases-replication.jsonl',
+];
+
+const SPLITS = ['dev', 'heldout', 'replication'];
+
+function loadJsonl(file) {
+ if (!fs.existsSync(file)) return [];
+ return fs.readFileSync(file, 'utf8')
+ .split('\n')
+ .map(l => l.trim())
+ .filter(Boolean)
+ .map((line, idx) => {
+ try {
+ return JSON.parse(line);
+ } catch (e) {
+ return { __parse_error: true, __line: idx + 1, __raw: line, __error: String(e.message || e) };
+ }
+ });
+}
+
+function promptText(row) {
+ return row.prompt || row.case_brief || row.question || row.input || '';
+}
+
+function computePromptHash(row) {
+ const text = promptText(row);
+ if (!text) return null;
+ return crypto.createHash('sha256').update(String(text)).digest('hex');
+}
+
+/**
+ * Always recompute from prompt text. Declared hashes are verified, never trusted.
+ */
+function promptHashInfo(row) {
+ const computed = computePromptHash(row);
+ const declared = row.prompt_sha256 || row.prompt_hash || null;
+ if (declared && computed && declared !== computed) {
+ return { hash: computed, declared, mismatch: true };
+ }
+ if (declared && !computed) {
+ return { hash: null, declared, mismatch: true };
+ }
+ return { hash: computed || null, declared, mismatch: false };
+}
+
+function promptHash(row) {
+ return promptHashInfo(row).hash;
+}
+
+function normalizePrompt(text) {
+ return String(text || '').replace(/\s+/g, ' ').trim().toLowerCase();
+}
+
+function validateAuthoredFile(filename, authoredDir = AUTHORED_DIR) {
+ const filepath = path.join(authoredDir, filename);
+ if (!fs.existsSync(filepath)) return { file: filename, status: 'missing', errors: [], rows: [] };
+
+ const rows = loadJsonl(filepath);
+ const errors = [];
+ const splitClusters = { dev: new Set(), heldout: new Set(), replication: new Set() };
+ const splitPromptHashes = { dev: new Set(), heldout: new Set(), replication: new Set() };
+ const requiredFields = ['cluster_id', 'source_family', 'split', 'cluster_basis'];
+
+ for (const row of rows) {
+ if (row.__parse_error) {
+ errors.push(`line ${row.__line}: JSON parse error: ${row.__error}`);
+ continue;
+ }
+ for (const field of requiredFields) {
+ if (!row[field]) errors.push(`${row.id || 'unknown'}: missing ${field}`);
+ }
+ if (row.split && !SPLITS.includes(row.split)) {
+ errors.push(`${row.id || 'unknown'}: invalid split '${row.split}'`);
+ }
+ if (row.split && row.cluster_id && splitClusters[row.split]) {
+ splitClusters[row.split].add(row.cluster_id);
+ }
+ const phi = promptHashInfo(row);
+ if (phi.mismatch) {
+ errors.push(`${row.id || 'unknown'}: declared prompt hash does not match recomputed prompt`);
+ }
+ if (row.split && phi.hash && splitPromptHashes[row.split]) {
+ splitPromptHashes[row.split].add(phi.hash);
+ }
+ }
+
+ const pairs = [['dev', 'heldout'], ['dev', 'replication'], ['heldout', 'replication']];
+ for (const [a, b] of pairs) {
+ const clusterOverlap = [...splitClusters[a]].filter(c => splitClusters[b].has(c));
+ if (clusterOverlap.length > 0) {
+ errors.push(`cluster overlap between ${a} and ${b}: ${clusterOverlap.join(', ')}`);
+ }
+ const promptOverlap = [...splitPromptHashes[a]].filter(h => splitPromptHashes[b].has(h));
+ if (promptOverlap.length > 0) {
+ errors.push(`prompt-hash overlap between ${a} and ${b}: ${promptOverlap.slice(0, 5).join(', ')}${promptOverlap.length > 5 ? '…' : ''}`);
+ }
+ }
+
+ const allIds = rows.map(r => r.id).filter(Boolean);
+ const seen = new Set();
+ const dupes = [];
+ for (const id of allIds) {
+ if (seen.has(id)) dupes.push(id);
+ else seen.add(id);
+ }
+ if (dupes.length > 0) errors.push(`duplicate IDs: ${[...new Set(dupes)].join(', ')}`);
+
+ return {
+ file: filename,
+ status: errors.length === 0 ? 'passed' : 'failed',
+ n: rows.filter(r => !r.__parse_error).length,
+ splits: Object.fromEntries(Object.entries(splitClusters).map(([k, v]) => [k, v.size])),
+ split_rows: {
+ dev: rows.filter(r => r.split === 'dev').length,
+ heldout: rows.filter(r => r.split === 'heldout').length,
+ replication: rows.filter(r => r.split === 'replication').length,
+ },
+ errors,
+ rows: rows.filter(r => !r.__parse_error),
+ };
+}
+
+function validateWorkflowFile(filename, authoredIndex, workflowDir = WORKFLOW_DIR) {
+ const filepath = path.join(workflowDir, filename);
+ if (!fs.existsSync(filepath)) return null;
+
+ const rows = loadJsonl(filepath);
+ const errors = [];
+ const caseClusters = new Set();
+ const casePromptHashes = new Set();
+
+ let role = 'base';
+ if (filename.includes('expanded')) role = 'expanded';
+ if (filename.includes('replication')) role = 'replication';
+
+ for (const row of rows) {
+ if (row.__parse_error) {
+ errors.push(`line ${row.__line}: JSON parse error: ${row.__error}`);
+ continue;
+ }
+ if (!row.cluster_id) errors.push(`${row.id || 'unknown'}: missing cluster_id`);
+ if (row.cluster_id) caseClusters.add(row.cluster_id);
+
+ const phi = promptHashInfo(row);
+ if (phi.mismatch) {
+ errors.push(`${row.id || 'unknown'}: declared prompt hash does not match recomputed prompt`);
+ }
+ if (phi.hash) casePromptHashes.add(phi.hash);
+
+ const sourceIds = [];
+ if (Array.isArray(row.source_ids)) {
+ for (const sid of row.source_ids) sourceIds.push(sid);
+ }
+ for (const node of row.nodes || []) {
+ if (!node.source_file) errors.push(`${row.id}: node ${node.node_id} missing source_file`);
+ if (!node.source_id) errors.push(`${row.id}: node ${node.node_id} missing source_id`);
+ if (node.source_id) sourceIds.push(node.source_id);
+ }
+
+ for (const sid of sourceIds) {
+ if (!authoredIndex.allIds.has(sid)) {
+ errors.push(`${row.id}: source_id '${sid}' not found in authored datasets`);
+ }
+ }
+ }
+
+ const allIds = rows.map(r => r.id).filter(Boolean);
+ const seen = new Set();
+ const dupes = [];
+ for (const id of allIds) {
+ if (seen.has(id)) dupes.push(id);
+ else seen.add(id);
+ }
+ if (dupes.length > 0) errors.push(`duplicate IDs: ${[...new Set(dupes)].join(', ')}`);
+
+ return {
+ file: filename,
+ role,
+ status: errors.length === 0 ? 'passed' : 'failed',
+ n: rows.filter(r => !r.__parse_error).length,
+ clusters: caseClusters.size,
+ prompt_hashes: casePromptHashes.size,
+ errors,
+ rows: rows.filter(r => !r.__parse_error),
+ cluster_set: caseClusters,
+ prompt_hash_set: casePromptHashes,
+ id_set: new Set(allIds),
+ };
+}
+
+/**
+ * Map raw entry roles to effective split for leakage checks:
+ * - authored:* keep declared split
+ * - workflow base|expanded → heldout
+ * - workflow replication → replication
+ * Cluster/prompt overlap is checked only across effective dev/heldout/replication.
+ * IDs remain globally unique across all files.
+ */
+function effectiveSplit(entry) {
+ if (!entry) return null;
+ if (entry.kind === 'authored') return entry.role;
+ if (entry.kind === 'workflow') {
+ if (entry.role === 'replication') return 'replication';
+ // base and expanded are the same heldout split surface
+ return 'heldout';
+ }
+ return entry.role || null;
+}
+
+function validateGlobal(authoredResults, workflowResults) {
+ const errors = [];
+ const warnings = [];
+ const entries = [];
+
+ for (const ar of authoredResults) {
+ for (const row of ar.rows || []) {
+ if (!row.split || !SPLITS.includes(row.split)) continue;
+ const phi = promptHashInfo(row);
+ if (phi.mismatch) {
+ errors.push(`${ar.file}:${row.id || 'unknown'}: declared prompt hash mismatch`);
+ }
+ entries.push({
+ kind: 'authored',
+ role: row.split,
+ file: ar.file,
+ id: row.id || null,
+ cluster_id: row.cluster_id || null,
+ prompt_hash: phi.hash,
+ ref: `${ar.file}:${row.id || '?'}`,
+ });
+ }
+ }
+
+ for (const wr of workflowResults) {
+ for (const row of wr.rows || []) {
+ const phi = promptHashInfo(row);
+ if (phi.mismatch) {
+ errors.push(`${wr.file}:${row.id || 'unknown'}: declared prompt hash mismatch`);
+ }
+ entries.push({
+ kind: 'workflow',
+ role: wr.role || 'base',
+ file: wr.file,
+ id: row.id || null,
+ cluster_id: row.cluster_id || null,
+ prompt_hash: phi.hash,
+ ref: `${wr.file}:${row.id || '?'}`,
+ });
+ }
+ }
+
+ // Global ID uniqueness across every authored + workflow file
+ const idIndex = new Map();
+ for (const e of entries) {
+ if (!e.id) continue;
+ if (!idIndex.has(e.id)) idIndex.set(e.id, []);
+ idIndex.get(e.id).push(e);
+ }
+ for (const [id, list] of idIndex) {
+ if (list.length > 1) {
+ const refs = [...new Set(list.map(x => x.ref))];
+ errors.push(`global duplicate id '${id}' at ${refs.join(', ')}`);
+ }
+ }
+
+ // Cluster/prompt indexes keyed by effective split only
+ const bySplitCluster = { dev: new Map(), heldout: new Map(), replication: new Map() };
+ const bySplitPrompt = { dev: new Map(), heldout: new Map(), replication: new Map() };
+ for (const e of entries) {
+ const split = effectiveSplit(e);
+ if (!split || !bySplitCluster[split]) continue;
+ if (e.cluster_id) {
+ if (!bySplitCluster[split].has(e.cluster_id)) bySplitCluster[split].set(e.cluster_id, []);
+ bySplitCluster[split].get(e.cluster_id).push(e.ref);
+ }
+ if (e.prompt_hash) {
+ if (!bySplitPrompt[split].has(e.prompt_hash)) bySplitPrompt[split].set(e.prompt_hash, []);
+ bySplitPrompt[split].get(e.prompt_hash).push(e.ref);
+ }
+ }
+
+ const pairs = [['dev', 'heldout'], ['dev', 'replication'], ['heldout', 'replication']];
+ for (const [a, b] of pairs) {
+ for (const cluster of bySplitCluster[a].keys()) {
+ if (bySplitCluster[b].has(cluster)) {
+ errors.push(`global cluster '${cluster}' overlaps effective ${a} and ${b}`);
+ }
+ }
+ for (const ph of bySplitPrompt[a].keys()) {
+ if (bySplitPrompt[b].has(ph)) {
+ errors.push(`global prompt-hash ${ph.slice(0, 12)}… overlaps effective ${a} and ${b}`);
+ }
+ }
+ }
+
+ return { errors, warnings };
+}
+
+function validateDatasetSplits(opts = {}) {
+ const authoredDir = opts.authoredDir || AUTHORED_DIR;
+ const workflowDir = opts.workflowDir || WORKFLOW_DIR;
+ const workflowFiles = opts.workflowFiles || WORKFLOW_FILES;
+
+ const authoredFiles = fs.existsSync(authoredDir)
+ ? fs.readdirSync(authoredDir).filter(f => f.endsWith('.jsonl')).sort()
+ : [];
+ const authoredResults = authoredFiles.map(f => validateAuthoredFile(f, authoredDir));
+
+ const authoredIndex = {
+ devClusters: new Set(),
+ heldoutClusters: new Set(),
+ replicationClusters: new Set(),
+ allClusters: new Set(),
+ allIds: new Set(),
+ };
+ for (const ar of authoredResults) {
+ for (const row of ar.rows || []) {
+ if (row.cluster_id) {
+ authoredIndex.allClusters.add(row.cluster_id);
+ if (row.split === 'dev') authoredIndex.devClusters.add(row.cluster_id);
+ if (row.split === 'heldout') authoredIndex.heldoutClusters.add(row.cluster_id);
+ if (row.split === 'replication') authoredIndex.replicationClusters.add(row.cluster_id);
+ }
+ if (row.id) authoredIndex.allIds.add(row.id);
+ }
+ }
+
+ const workflowResults = workflowFiles
+ .map(f => validateWorkflowFile(f, authoredIndex, workflowDir))
+ .filter(Boolean);
+
+ const global = validateGlobal(authoredResults, workflowResults);
+
+ const authoredOut = authoredResults.map(({ rows, ...rest }) => rest);
+ const workflowOut = workflowResults.map(({ rows, cluster_set, prompt_hash_set, id_set, ...rest }) => rest);
+
+ const fileFailed = [...authoredOut, ...workflowOut].filter(r => r.status === 'failed').length;
+ const ok = fileFailed === 0 && global.errors.length === 0;
+
+ return {
+ ok,
+ summary: {
+ total_files: authoredOut.length + workflowOut.length,
+ passed: authoredOut.length + workflowOut.length - fileFailed,
+ failed: fileFailed,
+ global_errors: global.errors.length,
+ global_warnings: global.warnings.length,
+ authored_dev_clusters: authoredOut.reduce((a, r) => a + (r.splits?.dev || 0), 0),
+ authored_heldout_clusters: authoredOut.reduce((a, r) => a + (r.splits?.heldout || 0), 0),
+ authored_replication_clusters: authoredOut.reduce((a, r) => a + (r.splits?.replication || 0), 0),
+ workflow_clusters: workflowOut.reduce((a, r) => a + (r.clusters || 0), 0),
+ status: ok ? 'passed' : 'failed',
+ },
+ authored: authoredOut,
+ workflow: workflowOut,
+ global,
+ };
+}
+
+function resolveExternalReportPath(outFile, repoRoot = REPO_ROOT) {
+ if (!outFile) return { ok: false, reason: 'no output path' };
+ const resolved = path.resolve(outFile);
+ const root = path.resolve(repoRoot);
+ const rel = path.relative(root, resolved);
+ const isInsideRepo = rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ if (isInsideRepo) {
+ return {
+ ok: false,
+ reason: `EVAL_SPLIT_OUT must resolve outside the repository (refused: ${resolved})`,
+ path: resolved,
+ };
+ }
+ return { ok: true, path: resolved };
+}
+
+function main() {
+ const out = validateDatasetSplits();
+
+ for (const r of out.authored) {
+ const icon = r.status === 'passed' ? '✓' : '✖';
+ console.log(` ${icon} ${r.file}: ${r.n} rows, dev=${r.split_rows?.dev || 0}/${r.splits?.dev || 0}c, heldout=${r.split_rows?.heldout || 0}/${r.splits?.heldout || 0}c, repl=${r.split_rows?.replication || 0}/${r.splits?.replication || 0}c`);
+ if (r.errors.length > 0) for (const e of r.errors.slice(0, 5)) console.log(` ${e}`);
+ }
+ for (const r of out.workflow) {
+ const icon = r.status === 'passed' ? '✓' : '✖';
+ console.log(` ${icon} ${r.file}: ${r.n} rows, ${r.clusters} clusters`);
+ if (r.errors.length > 0) for (const e of r.errors.slice(0, 5)) console.log(` ${e}`);
+ }
+ if (out.global.errors.length) {
+ console.log('\n Global errors:');
+ for (const e of out.global.errors.slice(0, 20)) console.log(` ✖ ${e}`);
+ }
+ if (out.global.warnings.length) {
+ console.log('\n Global warnings:');
+ for (const w of out.global.warnings.slice(0, 10)) console.log(` ! ${w}`);
+ }
+ console.log(`\n ${out.summary.passed}/${out.summary.total_files} files passed; global_errors=${out.summary.global_errors}`);
+
+ const outFile = process.env.EVAL_SPLIT_OUT;
+ if (outFile) {
+ const resolved = resolveExternalReportPath(outFile, REPO_ROOT);
+ if (!resolved.ok) {
+ console.error(` ${resolved.reason}`);
+ process.exit(1);
+ }
+ fs.mkdirSync(path.dirname(resolved.path), { recursive: true });
+ fs.writeFileSync(resolved.path, JSON.stringify(out, null, 2));
+ console.log(` -> ${resolved.path}`);
+ } else {
+ console.log(' (no output written; set EVAL_SPLIT_OUT to an external path to emit a report)');
+ }
+
+ if (!out.ok) process.exit(1);
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = {
+ REPO_ROOT,
+ AUTHORED_DIR,
+ WORKFLOW_DIR,
+ WORKFLOW_FILES,
+ loadJsonl,
+ promptHash,
+ promptHashInfo,
+ computePromptHash,
+ normalizePrompt,
+ validateAuthoredFile,
+ validateWorkflowFile,
+ validateGlobal,
+ validateDatasetSplits,
+ resolveExternalReportPath,
+ effectiveSplit,
+ main,
+};
diff --git a/scripts/validate-skills.js b/scripts/validate-skills.js
old mode 100644
new mode 100755
index e0bc4f8..8ff9d74
--- a/scripts/validate-skills.js
+++ b/scripts/validate-skills.js
@@ -1,225 +1,300 @@
#!/usr/bin/env node
+'use strict';
/**
- * Thinking Skills Quality Validator
+ * Thinking Skills structural validator (side-effect free).
*
- * Validates each skill against the quality framework criteria.
- * Run with: node scripts/validate-skills.js
+ * Enforces:
+ * - frontmatter description < 200 chars
+ * - required sections: When to Use, When NOT to Use, Procedure, Output, Verification
+ * - catalog count from registry
+ * - per-skill word budget from registry (survivors)
+ *
+ * Does NOT write quality-report.json or any tracked report.
+ * Run: node scripts/validate-skills.js
*/
const fs = require('fs');
const path = require('path');
-const SKILLS_DIR = path.join(__dirname, '..', 'skills');
-
-// Required sections and their markers
-const REQUIRED_SECTIONS = [
- { name: 'YAML Frontmatter', pattern: /^---\n[\s\S]*?name:[\s\S]*?description:[\s\S]*?---/m },
- { name: 'Overview', pattern: /^## Overview/m },
- { name: 'Core Principle', pattern: /\*\*Core Principle:\*\*/m },
- { name: 'When to Use', pattern: /^## When to Use/m },
- { name: 'Decision Flow', pattern: /```[\s\S]*?→[\s\S]*?```/m },
- { name: 'Process/Steps', pattern: /^### Step \d|^## The .* Process|^## .*Process$/m },
- { name: 'Examples', pattern: /^## .*Example|Example:|```markdown[\s\S]*?##/m },
- { name: 'Template', pattern: /^## .*Template|Template:/m },
- { name: 'Verification Checklist', pattern: /^## Verification Checklist/m },
- { name: 'Key Questions', pattern: /^## Key Questions/m },
- { name: 'Wisdom/Attribution', pattern: /Wisdom|".*"/m }
+const REPO_ROOT = path.join(__dirname, '..');
+const SKILLS_DIR = path.join(REPO_ROOT, 'skills');
+
+let loadRegistry;
+let validateRegistry;
+let getSkillBudget;
+try {
+ ({ loadRegistry, validateRegistry, getSkillBudget } = require(path.join(REPO_ROOT, 'evals', 'lib', 'registry')));
+} catch (_) {
+ loadRegistry = null;
+}
+
+const DEFAULT_REQUIRED_SECTIONS = [
+ 'When to Use',
+ 'When NOT to Use',
+ 'Procedure',
+ 'Output',
+ 'Verification',
];
-// Quality metrics
-const QUALITY_CHECKS = [
- {
+const DEFAULT_DESCRIPTION_MAX = 200;
+
+function listSkillDirs(skillsDir = SKILLS_DIR) {
+ if (!fs.existsSync(skillsDir)) return [];
+ return fs.readdirSync(skillsDir)
+ .filter(d => d.startsWith('thinking-'))
+ .filter(d => fs.existsSync(path.join(skillsDir, d, 'SKILL.md')))
+ .sort();
+}
+
+function parseFrontmatter(content) {
+ const m = content.match(/^---\n([\s\S]*?)\n---/);
+ const fm = {};
+ if (!m) return { frontmatter: fm, body: content, has_frontmatter: false };
+ for (const line of m[1].split('\n')) {
+ const kv = line.match(/^(\w[\w-]*):\s*(.*)$/);
+ if (kv) fm[kv[1]] = kv[2].trim();
+ }
+ const body = content.slice(m[0].length);
+ return { frontmatter: fm, body, has_frontmatter: true };
+}
+
+function countWords(text) {
+ return String(text || '').trim().split(/\s+/).filter(Boolean).length;
+}
+
+function sectionHeadingPattern(name) {
+ // Match ## When to Use / ## When NOT to Use etc.
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(`^##\\s+${escaped}\\s*$`, 'mi');
+}
+
+function hasSection(content, name) {
+ return sectionHeadingPattern(name).test(content);
+}
+
+/**
+ * Pure validation of a single skill body.
+ * @returns {object} structured result with pass/fail details
+ */
+function validateSkillContent(content, opts = {}) {
+ const skillName = opts.name || 'unknown';
+ const requiredSections = opts.requiredSections || DEFAULT_REQUIRED_SECTIONS;
+ const descriptionMax = opts.descriptionMax ?? DEFAULT_DESCRIPTION_MAX;
+ const maxWords = opts.maxWords != null ? opts.maxWords : null;
+ const enforceBudget = opts.enforceBudget !== false && maxWords != null;
+
+ const { frontmatter, has_frontmatter } = parseFrontmatter(content);
+ const words = countWords(content);
+ const description = frontmatter.description || '';
+ const descriptionLen = description.length;
+
+ const sections = requiredSections.map(name => ({
+ name,
+ found: hasSection(content, name),
+ }));
+
+ const checks = [];
+ checks.push({
+ name: 'YAML Frontmatter',
+ pass: has_frontmatter && Boolean(frontmatter.name || frontmatter.description),
+ detail: has_frontmatter ? 'present' : 'missing frontmatter',
+ });
+ checks.push({
name: 'Description Length',
- check: (content) => {
- const match = content.match(/description:\s*(.+)/);
- if (!match) return { pass: false, detail: 'No description found' };
- const len = match[1].length;
- return {
- pass: len <= 200,
- detail: `${len} chars (max 200)`
- };
- }
- },
- {
- name: 'Has Multiple Examples',
- check: (content) => {
- const examples = (content.match(/Example[s]?:/gi) || []).length +
- (content.match(/```markdown[\s\S]*?##/g) || []).length;
- return {
- pass: examples >= 2,
- detail: `Found ${examples} example(s)`
- };
- }
- },
- {
- name: 'Has Tables',
- check: (content) => {
- const tables = (content.match(/\|.*\|.*\|/g) || []).length;
- return {
- pass: tables >= 3,
- detail: `Found ${tables} table row(s)`
- };
- }
- },
- {
- name: 'Has Checklists',
- check: (content) => {
- const checks = (content.match(/- \[ \]/g) || []).length;
- return {
- pass: checks >= 3,
- detail: `Found ${checks} checklist item(s)`
- };
- }
- },
- {
- name: 'Has Code Blocks',
- check: (content) => {
- const blocks = (content.match(/```/g) || []).length / 2;
- return {
- pass: blocks >= 3,
- detail: `Found ${Math.floor(blocks)} code block(s)`
- };
- }
- },
- {
- name: 'Word Count (500-3000)',
- check: (content) => {
- const words = content.split(/\s+/).length;
- return {
- pass: words >= 500 && words <= 3000,
- detail: `${words} words`
- };
- }
- },
- {
- name: 'Has Anti-patterns/Failure Modes',
- check: (content) => {
- const hasAntiPatterns = /anti-pattern|failure mode|common mistake|when not to|don't use/i.test(content);
- return {
- pass: hasAntiPatterns,
- detail: hasAntiPatterns ? 'Found warnings' : 'No anti-patterns documented'
- };
- }
+ pass: descriptionLen > 0 && descriptionLen <= descriptionMax,
+ detail: descriptionLen
+ ? `${descriptionLen} chars (max ${descriptionMax})`
+ : 'No description found',
+ });
+
+ for (const section of sections) {
+ checks.push({
+ name: `Section: ${section.name}`,
+ pass: section.found,
+ detail: section.found ? 'found' : 'missing',
+ });
}
-];
-function validateSkill(skillPath) {
- const content = fs.readFileSync(skillPath, 'utf8');
- const skillName = path.basename(path.dirname(skillPath));
+ if (enforceBudget) {
+ checks.push({
+ name: 'Word Budget',
+ pass: words <= maxWords,
+ detail: `${words} words (max ${maxWords})`,
+ });
+ } else if (maxWords != null) {
+ checks.push({
+ name: 'Word Budget',
+ pass: true,
+ detail: `${words} words (budget ${maxWords}; not enforced for non-survivors)`,
+ });
+ }
+
+ const failed = checks.filter(c => !c.pass);
+ const score = checks.filter(c => c.pass).length;
+ const maxScore = checks.length;
- const results = {
+ return {
name: skillName,
+ description,
+ description_length: descriptionLen,
+ words,
+ max_words: maxWords,
+ sections,
+ checks,
+ failed,
+ score,
+ maxScore,
+ pass: failed.length === 0,
+ frontmatter,
+ };
+}
+
+function validateSkillFile(skillPath, opts = {}) {
+ const content = fs.readFileSync(skillPath, 'utf8');
+ const skillName = opts.name || path.basename(path.dirname(skillPath));
+ return {
+ ...validateSkillContent(content, { ...opts, name: skillName }),
path: skillPath,
- sections: [],
- quality: [],
- score: 0,
- maxScore: 0
};
+}
- // Check required sections
- for (const section of REQUIRED_SECTIONS) {
- const found = section.pattern.test(content);
- results.sections.push({
- name: section.name,
- found
- });
- results.maxScore += 1;
- if (found) results.score += 1;
+function loadCatalogExpectations(registryPath) {
+ if (!loadRegistry) {
+ return {
+ expectedCount: null,
+ requiredSections: DEFAULT_REQUIRED_SECTIONS,
+ descriptionMax: DEFAULT_DESCRIPTION_MAX,
+ budgets: {},
+ registry: null,
+ registryValidation: null,
+ };
}
+ const { registry } = loadRegistry(registryPath);
+ const registryValidation = validateRegistry(registry);
+ const budgets = {};
+ for (const [id, skill] of Object.entries(registry.skills || {})) {
+ const b = getSkillBudget(registry, id);
+ if (b != null) budgets[id] = b;
+ }
+ return {
+ expectedCount: registry.catalog?.expected_count ?? registry.catalog?.baseline_count ?? null,
+ requiredSections: registry.required_skill_sections || DEFAULT_REQUIRED_SECTIONS,
+ descriptionMax: registry.frontmatter?.description_max_chars ?? DEFAULT_DESCRIPTION_MAX,
+ budgets,
+ survivors: new Set(registry.catalog?.survivors || []),
+ deletions: new Set(registry.catalog?.deletions || []),
+ registry,
+ registryValidation,
+ };
+}
- // Check quality metrics
- for (const check of QUALITY_CHECKS) {
- const result = check.check(content);
- results.quality.push({
- name: check.name,
- ...result
- });
- results.maxScore += 1;
- if (result.pass) results.score += 1;
+/**
+ * Validate all skills under skillsDir. Pure: no file writes.
+ */
+function validateAllSkills(opts = {}) {
+ const skillsDir = opts.skillsDir || SKILLS_DIR;
+ const catalog = loadCatalogExpectations(opts.registryPath);
+ const dirs = listSkillDirs(skillsDir);
+ const results = [];
+
+ for (const dir of dirs) {
+ const id = dir.replace(/^thinking-/, '');
+ const maxWords = catalog.budgets[id] != null ? catalog.budgets[id] : null;
+ // Enforce budget only for declared survivors (Phase 3 lean contracts).
+ // Baseline pre-rewrite bodies will fail budgets/sections — that is intentional observability.
+ const enforceBudget = catalog.survivors ? catalog.survivors.has(id) : maxWords != null;
+ const skillPath = path.join(skillsDir, dir, 'SKILL.md');
+ results.push(validateSkillFile(skillPath, {
+ name: dir,
+ requiredSections: catalog.requiredSections,
+ descriptionMax: catalog.descriptionMax,
+ maxWords,
+ enforceBudget,
+ }));
}
- return results;
+ const errors = [];
+ if (catalog.expectedCount != null && results.length !== catalog.expectedCount) {
+ errors.push(`catalog count ${results.length} != expected ${catalog.expectedCount}`);
+ }
+ if (catalog.registryValidation && !catalog.registryValidation.ok) {
+ for (const e of catalog.registryValidation.errors) errors.push(`registry: ${e}`);
+ }
+
+ const failedSkills = results.filter(r => !r.pass);
+ return {
+ ok: errors.length === 0 && failedSkills.length === 0,
+ catalog_errors: errors,
+ expected_count: catalog.expectedCount,
+ found_count: results.length,
+ required_sections: catalog.requiredSections,
+ results,
+ failed: failedSkills,
+ summary: {
+ total: results.length,
+ passed: results.filter(r => r.pass).length,
+ failed: failedSkills.length,
+ },
+ registry_validation: catalog.registryValidation,
+ };
}
-function printResults(results) {
+function printResults(report) {
const GREEN = '\x1b[32m';
const RED = '\x1b[31m';
const YELLOW = '\x1b[33m';
const RESET = '\x1b[0m';
const BOLD = '\x1b[1m';
- console.log(`\n${BOLD}=== Thinking Skills Quality Report ===${RESET}\n`);
-
- let totalScore = 0;
- let totalMax = 0;
-
- for (const skill of results) {
- const percentage = Math.round((skill.score / skill.maxScore) * 100);
- const color = percentage >= 80 ? GREEN : percentage >= 60 ? YELLOW : RED;
-
- console.log(`${BOLD}${skill.name}${RESET}: ${color}${skill.score}/${skill.maxScore} (${percentage}%)${RESET}`);
-
- // Show missing sections
- const missingSections = skill.sections.filter(s => !s.found);
- if (missingSections.length > 0) {
- console.log(` ${RED}Missing sections:${RESET}`);
- for (const section of missingSections) {
- console.log(` - ${section.name}`);
- }
- }
-
- // Show failed quality checks
- const failedChecks = skill.quality.filter(q => !q.pass);
- if (failedChecks.length > 0) {
- console.log(` ${YELLOW}Quality improvements needed:${RESET}`);
- for (const check of failedChecks) {
- console.log(` - ${check.name}: ${check.detail}`);
- }
- }
-
- totalScore += skill.score;
- totalMax += skill.maxScore;
- console.log('');
+ console.log(`\n${BOLD}=== Thinking Skills Structural Validation ===${RESET}\n`);
+ if (report.expected_count != null) {
+ console.log(`Catalog: found ${report.found_count}, expected ${report.expected_count}`);
+ } else {
+ console.log(`Catalog: found ${report.found_count}`);
}
+ for (const e of report.catalog_errors || []) console.log(`${RED}CATALOG: ${e}${RESET}`);
- // Summary
- const overallPercentage = Math.round((totalScore / totalMax) * 100);
- console.log(`${BOLD}=== Summary ===${RESET}`);
- console.log(`Total Skills: ${results.length}`);
- console.log(`Overall Score: ${totalScore}/${totalMax} (${overallPercentage}%)`);
-
- // Skills needing attention
- const needsWork = results.filter(r => (r.score / r.maxScore) < 0.7);
- if (needsWork.length > 0) {
- console.log(`\n${YELLOW}Skills needing attention (< 70%):${RESET}`);
- for (const skill of needsWork) {
- const pct = Math.round((skill.score / skill.maxScore) * 100);
- console.log(` - ${skill.name} (${pct}%)`);
+ for (const skill of report.results) {
+ const color = skill.pass ? GREEN : RED;
+ console.log(`${BOLD}${skill.name}${RESET}: ${color}${skill.score}/${skill.maxScore}${RESET} words=${skill.words}${skill.max_words != null ? `/${skill.max_words}` : ''}`);
+ for (const c of skill.failed) {
+ console.log(` ${YELLOW}- ${c.name}: ${c.detail}${RESET}`);
}
}
- // Output JSON for further processing
- const jsonPath = path.join(__dirname, 'quality-report.json');
- fs.writeFileSync(jsonPath, JSON.stringify(results, null, 2));
- console.log(`\nDetailed report saved to: ${jsonPath}`);
+ console.log(`\n${BOLD}=== Summary ===${RESET}`);
+ console.log(`Passed: ${report.summary.passed}/${report.summary.total}`);
+ console.log(`Failed: ${report.summary.failed}`);
+ // Explicit: no tracked report write
+ console.log('(side-effect free: no quality-report.json written)');
}
function main() {
- // Find all skills
- const skillDirs = fs.readdirSync(SKILLS_DIR)
- .filter(d => d.startsWith('thinking-'))
- .map(d => path.join(SKILLS_DIR, d, 'SKILL.md'))
- .filter(p => fs.existsSync(p));
-
- console.log(`Found ${skillDirs.length} thinking skills to validate...`);
-
- const results = skillDirs.map(validateSkill);
-
- // Sort by score (lowest first to highlight what needs work)
- results.sort((a, b) => (a.score / a.maxScore) - (b.score / b.maxScore));
+ const report = validateAllSkills();
+ // Sort failures first for visibility
+ report.results.sort((a, b) => Number(a.pass) - Number(b.pass) || a.name.localeCompare(b.name));
+ printResults(report);
+ if (!report.ok) process.exit(1);
+}
- printResults(results);
+if (require.main === module) {
+ main();
}
-main();
+module.exports = {
+ DEFAULT_REQUIRED_SECTIONS,
+ DEFAULT_DESCRIPTION_MAX,
+ listSkillDirs,
+ parseFrontmatter,
+ countWords,
+ hasSection,
+ validateSkillContent,
+ validateSkillFile,
+ validateAllSkills,
+ loadCatalogExpectations,
+ printResults,
+ main,
+ SKILLS_DIR,
+ REPO_ROOT,
+};