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

feat(evals): isolated harness core

Travis Boudreauxa3ce58d1c102
diff --git a/evals/lib/conditions.js b/evals/lib/conditions.js
new file mode 100644
index 0000000..b735e12
--- /dev/null
+++ b/evals/lib/conditions.js
@@ -0,0 +1,90 @@
+'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.
+ *
+ * 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.
+ */
+
+// Neutral, true-but-method-free sentences in a software register. Carries no
+// analytical framework — a fair length placebo.
+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.',
+ 'It is generally good practice to communicate clearly and to write down the reasoning behind a choice.',
+ 'Consider the broader context of the work, including the people and teams involved.',
+ 'Tools, libraries, and platforms change over time, so it is worth staying reasonably current.',
+ 'Testing and verification are part of delivering work that holds up in practice.',
+ 'Keep an eye on timelines and available resources as the work proceeds.',
+ 'Where possible, prefer clarity over cleverness so others can follow the work later.',
+ 'Document assumptions and constraints so they can be revisited if circumstances change.',
+ 'Small, steady progress is often easier to manage than large, infrequent changes.',
+ 'Be mindful of edge cases and conditions that may not appear in the most common path.',
+ '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++;
+ }
+ return out.join(' ');
+}
+
+function wordCount(s) { return s.split(/\s+/).filter(Boolean).length; }
+
+/** A 2-3 sentence trigger summary built from the skill's own frontmatter + core principle. */
+function triggerSummary(content, name) {
+ const desc = (content.match(/description:\s*(.+)/) || [, ''])[1].trim();
+ const core = (content.match(/\*\*Core Principle:\*\*\s*(.+)/) || [, ''])[1].trim();
+ let s = `Thinking skill "${name}". ${desc}`;
+ if (core) s += ` Core principle: ${core}`;
+ 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}`;
+ }
+ if (condition === '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'
+ 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.
+ */
+function buildBalancedSkillPrompt(content, problemText, targetWords) {
+ const have = wordCount(content);
+ const pad = targetWords > have ? `\n\nAdditional general notes:\n${neutralFiller(targetWords - have)}` : '';
+ 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) {
+ 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)}` : '';
+ 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 };
diff --git a/evals/lib/droid.js b/evals/lib/droid.js
new file mode 100644
index 0000000..3c508cb
--- /dev/null
+++ b/evals/lib/droid.js
@@ -0,0 +1,232 @@
+'use strict';
+
+/**
+ * Thin wrapper around the `droid exec` CLI (Factory.ai Droid, v0.137.x).
+ *
+ * Why droid and not `claude -p`: the headless `claude -p` subprocess does not
+ * inherit this machine's interactive OAuth and fails with a 401. `droid` has
+ * provider API keys configured in ~/.factory/config.json, so it can drive
+ * Claude, GPT, Gemini and DeepSeek models uniformly. We therefore route ALL
+ * model calls (solvers, judges, adversarial reviewers) through this one
+ * authenticated CLI.
+ *
+ * `droid exec ... --output-format json` prints a single JSON object whose
+ * `.result` field holds the model's textual answer plus a `.usage` block.
+ */
+
+const { spawnSync, spawn } = require('child_process');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+// Highest reasoning effort actually supported per model (literal "max" is not
+// valid for GPT/Gemini). See plan / `droid` model listing.
+const MAX_EFFORT = {
+ 'gpt-5.5-pro': 'xhigh',
+ 'gemini-3.1-pro-preview': 'high',
+ 'deepseek-v4-pro': 'max',
+ 'claude-opus-4-8': 'max',
+ 'claude-sonnet-4-6': 'high',
+ 'claude-haiku-4-5-20251001': 'high',
+};
+
+function maxEffortFor(model) {
+ return MAX_EFFORT[model] || 'high';
+}
+
+// --- Harness isolation -------------------------------------------------------
+// The Factory session injects ~/.factory/AGENTS.md and a ~150-skill catalog (incl.
+// the thinking skills) into every solver. We CANNOT remove that passive context
+// without a Factory API key (the WorkOS session is keyring-bound and home-override
+// breaks auth). What we CAN and MUST do: disable every tool so the solver cannot
+// INVOKE another skill or READ the repo (the active confound), run from a neutral
+// 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_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) {
+ 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);
+ return args;
+}
+function spawnOpts(extra) { return { encoding: 'utf8', cwd: os.tmpdir(), ...extra }; } // neutral cwd: no project AGENTS.md/files
+
+let tmpCounter = 0;
+function writeTempPrompt(prompt) {
+ // Avoid Date.now()/Math.random() (unavailable in some sandboxes elsewhere;
+ // harmless here but keep deterministic): use pid + counter.
+ const name = `droid-prompt-${process.pid}-${tmpCounter++}.txt`;
+ const p = path.join(os.tmpdir(), name);
+ fs.writeFileSync(p, prompt, 'utf8');
+ return p;
+}
+
+/**
+ * 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}}
+ */
+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 */ }
+ }
+
+ 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 };
+ }
+
+ // 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 };
+ }
+ 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 parseDroidStdout(stdout) {
+ const lines = 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; }
+}
+
+/**
+ * Extract a JSON value from arbitrary model text (handles ```json fences and
+ * leading/trailing prose). Returns null if nothing parses.
+ */
+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]);
+ candidates.push(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];
+ const close = open === '{' ? '}' : ']';
+ let depth = 0, end = -1, inStr = false, esc = false;
+ for (let i = start; i < trimmed.length; i++) {
+ const ch = trimmed[i];
+ if (inStr) {
+ if (esc) esc = false;
+ else if (ch === '\\') esc = true;
+ else if (ch === '"') inStr = false;
+ } else {
+ if (ch === '"') inStr = true;
+ else if (ch === open) depth++;
+ else if (ch === close) { depth--; if (depth === 0) { end = i; break; } }
+ }
+ }
+ if (end !== -1) {
+ try { return JSON.parse(trimmed.slice(start, end + 1)); } catch (_) { /* fallthrough */ }
+ }
+ }
+ return null;
+}
+
+/** Run a droid call and parse its result as JSON, with one retry. */
+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 };
+ }
+ 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' };
+}
+
+module.exports = { droidExec, droidJson, droidExecAsync, droidJsonAsync, extractJson, maxEffortFor, MAX_EFFORT };
diff --git a/evals/lib/io.js b/evals/lib/io.js
new file mode 100644
index 0000000..4aaf191
--- /dev/null
+++ b/evals/lib/io.js
@@ -0,0 +1,47 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+
+const RESULTS_ROOT = path.join(__dirname, '..', 'results');
+
+/** Shared run directory. Set EVAL_RUN to group tiers into one folder. */
+function runDir() {
+ const id = process.env.EVAL_RUN || 'latest';
+ const dir = path.join(RESULTS_ROOT, id);
+ fs.mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function writeJson(file, obj) {
+ fs.writeFileSync(file, JSON.stringify(obj, null, 2));
+}
+
+function readJsonIfExists(file) {
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return null; }
+}
+
+/** Map a thunk over items with a bounded concurrency pool. */
+async function mapPool(items, limit, fn) {
+ const results = new Array(items.length);
+ let next = 0;
+ async function worker() {
+ while (true) {
+ const i = next++;
+ if (i >= items.length) return;
+ try { results[i] = await fn(items[i], i); }
+ catch (e) { results[i] = { __error: String(e && e.message || e) }; }
+ }
+ }
+ const workers = [];
+ for (let w = 0; w < Math.min(limit, items.length); w++) workers.push(worker());
+ await Promise.all(workers);
+ return results;
+}
+
+/** spawnSync-based droid is blocking; wrap so the pool can interleave timers. */
+function deferred(fn) {
+ return () => new Promise((resolve) => { setImmediate(() => resolve(fn())); });
+}
+
+module.exports = { RESULTS_ROOT, runDir, writeJson, readJsonIfExists, mapPool, deferred };
diff --git a/evals/lib/judge.js b/evals/lib/judge.js
new file mode 100644
index 0000000..a667da8
--- /dev/null
+++ b/evals/lib/judge.js
@@ -0,0 +1,35 @@
+'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").
+ */
+
+const { droidJsonAsync } = require('./droid');
+
+function panelModels() {
+ return (process.env.JUDGES || process.env.JUDGE_MODEL || 'gemini-3.1-pro-preview')
+ .split(',').map(s => s.trim()).filter(Boolean);
+}
+
+/**
+ * @returns {{winner:'A'|'B'|'tie', votes:Array, vocab_only:boolean, whys:string[]}}
+ * `winner` is the panel majority; ties (or no majority) → 'tie'.
+ */
+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 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) };
+}
+
+module.exports = { panelModels, panelJudge };
diff --git a/evals/lib/skills.js b/evals/lib/skills.js
new file mode 100644
index 0000000..88604d2
--- /dev/null
+++ b/evals/lib/skills.js
@@ -0,0 +1,49 @@
+'use strict';
+
+/** Helpers for loading the thinking skills and their frontmatter. */
+
+const fs = require('fs');
+const path = require('path');
+
+const REPO_ROOT = path.join(__dirname, '..', '..');
+const SKILLS_DIR = path.join(REPO_ROOT, 'skills');
+
+function listSkillDirs() {
+ return fs.readdirSync(SKILLS_DIR)
+ .filter(d => d.startsWith('thinking-'))
+ .filter(d => fs.existsSync(path.join(SKILLS_DIR, d, 'SKILL.md')))
+ .sort();
+}
+
+function skillPath(name) {
+ return path.join(SKILLS_DIR, name, 'SKILL.md');
+}
+
+function readSkill(name) {
+ const content = fs.readFileSync(skillPath(name), 'utf8');
+ return { name, content, ...parseFrontmatter(content) };
+}
+
+function parseFrontmatter(content) {
+ const m = content.match(/^---\n([\s\S]*?)\n---/);
+ const fm = {};
+ if (m) {
+ for (const line of m[1].split('\n')) {
+ const kv = line.match(/^(\w[\w-]*):\s*(.*)$/);
+ if (kv) fm[kv[1]] = kv[2].trim();
+ }
+ }
+ return { description: fm.description || '', frontmatter: fm };
+}
+
+function loadAllSkills() {
+ return listSkillDirs().map(readSkill);
+}
+
+/** All skills minus the meta routers/selectors (leaf models only). */
+function leafSkills() {
+ const meta = new Set(['thinking-model-router', 'thinking-model-selection', 'thinking-model-combination']);
+ return loadAllSkills().filter(s => !meta.has(s.name));
+}
+
+module.exports = { REPO_ROOT, SKILLS_DIR, listSkillDirs, skillPath, readSkill, loadAllSkills, leafSkills, parseFrontmatter };
diff --git a/evals/lib/stats.js b/evals/lib/stats.js
new file mode 100644
index 0000000..332053c
--- /dev/null
+++ b/evals/lib/stats.js
@@ -0,0 +1,54 @@
+'use strict';
+
+/** Significance helpers shared by all eval runners. No deps. */
+
+function erf(x) {
+ const s = x < 0 ? -1 : 1; x = Math.abs(x);
+ const t = 1 / (1 + 0.3275911 * x);
+ const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x);
+ return s * y;
+}
+const normCdf = z => 0.5 * (1 + erf(z / Math.SQRT2));
+
+/** Wilson score interval for a binomial proportion. */
+function wilson(k, n, z = 1.959964) {
+ if (n === 0) return [0, 1];
+ const p = k / n, d = 1 + z * z / n;
+ const c = p + z * z / (2 * n), h = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n));
+ return [(c - h) / d, (c + h) / d];
+}
+
+/** Two-sided sign test (normal approx + continuity correction) for k successes of n vs p=0.5. */
+function signTest(k, n) {
+ if (n === 0) return 1;
+ const z = (Math.abs(k - n / 2) - 0.5) / (0.5 * Math.sqrt(n));
+ return Math.min(1, 2 * (1 - normCdf(z)));
+}
+
+/** McNemar test for paired binary outcomes: b = treatment-only successes, c = control-only successes. */
+function mcnemar(b, c) {
+ const n = b + c;
+ if (n === 0) return 1;
+ const chi = Math.pow(Math.abs(b - c) - 1, 2) / n; // continuity-corrected
+ // p from chi-square(1) = 2*(1-Phi(sqrt(chi)))
+ return Math.min(1, 2 * (1 - normCdf(Math.sqrt(chi))));
+}
+
+/** Summarize a win/loss/tie count into win-rate, CI, p-value, and a powered flag. */
+function summarize(wins, losses, ties = 0) {
+ 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);
+ 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
+ };
+}
+
+module.exports = { normCdf, wilson, signTest, mcnemar, summarize };