28 eval-informed mental models and critical-thinking skills for Claude Code, GitHub Copilot, Codex, Cursor, and other Agent Skills-compatible tools
JavaScript agent-skillsai-toolsanthropicclaudeclaude-codecritical-thinkingdecision-makingfirst-principlesmental-modelsproblem-solvingsystems-thinking
feat(experiments): worktree orchestrator + paired/stack/capability runners
Travis Boudreaux06997ea932c6
diff --git a/experiments/lib.js b/experiments/lib.jsnew file mode 100644index 0000000..4090aea--- /dev/null+++ b/experiments/lib.js@@ -0,0 +1,85 @@+'use strict';++/**+ * Central experiment ledger (SQLite). EVERY experiment — registered, running,+ * evaluated, merged, or discarded — gets a row with a unique id, so nothing is+ * lost regardless of whether its worktree is merged into main.+ *+ * DB lives on main at evals/db/experiments.db and is written from the main repo+ * (never from a worktree), so it is the single source of truth across all runs.+ */++const fs = require('fs');+const path = require('path');+const crypto = require('crypto');+const { spawnSync } = require('child_process');++const REPO_ROOT = path.join(__dirname, '..');+const DB = path.join(REPO_ROOT, 'evals', 'db', 'experiments.db');+const EVAL_DB = path.join(REPO_ROOT, 'evals', 'db', 'evals.db');++const SCHEMA = `+CREATE TABLE IF NOT EXISTS experiment(+ id TEXT PRIMARY KEY,+ hypothesis TEXT, title TEXT, description TEXT,+ intervention TEXT, scope_skills TEXT, dataset TEXT,+ branch TEXT, worktree TEXT, commit_hash TEXT,+ status TEXT,+ baseline_win_rate REAL, result_win_rate REAL, lift_pp REAL, n_problems INT,+ merge_recommended INT,+ created_at TEXT, updated_at TEXT, notes TEXT+);+CREATE TABLE IF NOT EXISTS experiment_result(+ experiment_id TEXT, skill TEXT,+ baseline_win_rate REAL, result_win_rate REAL, lift REAL, n INT,+ PRIMARY KEY(experiment_id, skill)+);`;++function sqlExec(database, sql) {+ const r = spawnSync('sqlite3', [database], { input: sql, encoding: 'utf8' });+ if (r.status !== 0) throw new Error('sqlite3: ' + (r.stderr || r.error));+ return r.stdout;+}+function sqlQuery(database, q) {+ const r = spawnSync('sqlite3', ['-json', database, q], { encoding: 'utf8' });+ if (r.status !== 0) throw new Error('sqlite3: ' + (r.stderr || r.error));+ return r.stdout && r.stdout.trim() ? JSON.parse(r.stdout) : [];+}+const q = v => v === null || v === undefined ? 'NULL' : (typeof v === 'number' ? String(v) : `'${String(v).replace(/'/g, "''")}'`);++function init() { sqlExec(DB, SCHEMA); }++function genId(hypothesis) {+ const suffix = crypto.randomBytes(3).toString('hex');+ return `exp-${hypothesis.toLowerCase()}-${suffix}`;+}++function nowISO() { return new Date().toISOString(); }++function register(exp) {+ init();+ const t = nowISO();+ sqlExec(DB, `INSERT OR REPLACE INTO experiment+ (id,hypothesis,title,description,intervention,scope_skills,dataset,branch,worktree,commit_hash,status,baseline_win_rate,result_win_rate,lift_pp,n_problems,merge_recommended,created_at,updated_at,notes)+ VALUES (${q(exp.id)},${q(exp.hypothesis)},${q(exp.title)},${q(exp.description)},${q(exp.intervention)},${q((exp.skills||[]).join(','))},${q(exp.dataset||'behavioral')},${q(exp.branch)},${q(exp.worktree)},${q(exp.commit_hash)},${q(exp.status||'registered')},${q(exp.baseline_win_rate)},${q(exp.result_win_rate)},${q(exp.lift_pp)},${q(exp.n_problems)},${q(exp.merge_recommended?1:0)},${q(t)},${q(t)},${q(exp.notes)});`);+}++function update(id, fields) {+ const sets = Object.entries(fields).map(([k, v]) => `${k}=${q(v)}`).concat([`updated_at=${q(nowISO())}`]).join(', ');+ sqlExec(DB, `UPDATE experiment SET ${sets} WHERE id=${q(id)};`);+}++function recordSkill(id, skill, baseline, result, n) {+ sqlExec(DB, `INSERT OR REPLACE INTO experiment_result VALUES (${q(id)},${q(skill)},${q(baseline)},${q(result)},${q(result - baseline)},${q(n)});`);+}++/** Baseline per-skill win-rate from the main eval run (evals.db tier3 variant='main'). */+function baselineWinRates(skills) {+ if (!fs.existsSync(EVAL_DB)) return {};+ const rows = sqlQuery(EVAL_DB, `SELECT skill, win_rate FROM tier3 WHERE variant='main' AND skill IN (${skills.map(s => q('thinking-' + s.replace(/^thinking-/, ''))).join(',')});`);+ return Object.fromEntries(rows.map(r => [r.skill.replace(/^thinking-/, ''), r.win_rate]));+}++function all() { init(); return sqlQuery(DB, 'SELECT * FROM experiment ORDER BY created_at;'); }++module.exports = { DB, EVAL_DB, REPO_ROOT, init, genId, register, update, recordSkill, baselineWinRates, all, sqlQuery, sqlExec };diff --git a/experiments/run-capability-indomain.js b/experiments/run-capability-indomain.jsnew file mode 100644index 0000000..7ed4a6c--- /dev/null+++ b/experiments/run-capability-indomain.js@@ -0,0 +1,56 @@+#!/usr/bin/env node+'use strict';++/**+ * In-domain capability-substitution test (removes the medical out-of-domain+ * confound). Same-family ladder haiku→sonnet→opus, each skill paired with ITS OWN+ * in-domain behavioral problems (software/product/decision), skill vs length-+ * matched placebo, a FIXED single judge across all tiers (so judge bias is+ * constant → clean slope). Pairwise (these problems have no ground truth).+ *+ * Reports win-rate + CI per tier and the lift-vs-capability slope. Tracked in the+ * ledger. Usage: node experiments/run-capability-indomain.js+ */++const fs = require('fs');+const path = require('path');+const { spawnSync } = require('child_process');+const lib = require('./lib');++const ROOT = lib.REPO_ROOT;+const LADDER = (process.env.LADDER || 'claude-haiku-4-5-20251001,claude-sonnet-4-6,claude-opus-4-8').split(',');+const tag = m => m.replace('claude-', '').replace('-4-8', '').replace('-4-5-20251001', '').replace('-4-6', '');+const JUDGE = process.env.JUDGES || 'gemini-3.1-pro-preview'; // fixed across tiers+const SKILLS = (process.env.SKILLS || 'thinking-second-order,thinking-inversion,thinking-opportunity-cost,thinking-theory-of-constraints,thinking-systems,thinking-pre-mortem,thinking-via-negativa,thinking-occams-razor,thinking-first-principles,thinking-debiasing').split(',');++function runTier(model, idx) {+ const run = `indomain-${tag(model)}`;+ const env = { ...process.env, EVAL_RUN: run, SOLVER_MODEL: model, SOLVER_EFFORT: 'medium', JUDGES: JUDGE, PAIRS: 'skill:placebo', CONC: '4' };+ const r = spawnSync('node', ['evals/run-behavioral.js', ...SKILLS], { cwd: ROOT, env, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ if (r.status !== 0) { console.log(` ${tag(model)} FAILED: ${(r.stderr || '').slice(-200)}`); return null; }+ const res = JSON.parse(fs.readFileSync(path.join(ROOT, 'evals', 'results', run, 'tier3-behavioral.json'), 'utf8'));+ const a = res.aggregate_significance;+ console.log(` ${tag(model).padEnd(8)} skill beats placebo ${(a.win_rate * 100).toFixed(0)}% 95% CI [${(a.ci95[0] * 100).toFixed(0)},${(a.ci95[1] * 100).toFixed(0)}] p=${a.p_value}${a.significant ? ' SIG' : ''} (n=${a.n})`);+ return { tier: tag(model), rank: idx, win_rate: a.win_rate, ci: a.ci95, p: a.p_value, n: a.n };+}+function slope(pts) {+ const n = pts.length, sx = pts.reduce((a, p) => a + p.rank, 0), sy = pts.reduce((a, p) => a + p.win_rate, 0);+ const sxy = pts.reduce((a, p) => a + p.rank * p.win_rate, 0), sxx = pts.reduce((a, p) => a + p.rank * p.rank, 0);+ return (n * sxy - sx * sy) / (n * sxx - sx * sx) * 100; // pp per step+}++async function main() {+ lib.init();+ const id = lib.genId('CAP-MODEL-INDOMAIN');+ console.log(`▶ ${id} — in-domain capability ladder (${SKILLS.length} skills × 3 problems, judge=${JUDGE} fixed), isolation ${process.env.EVAL_NO_ISOLATE === '1' ? 'OFF' : 'ON'}`);+ lib.register({ id, hypothesis: 'CAP-MODEL-INDOMAIN', title: `In-domain capability ladder (skill vs placebo, ${SKILLS.length} software/decision skills)`, intervention: 'capability-ladder-indomain', skills: SKILLS, status: 'running', dataset: 'behavioral' });+ const pts = [];+ for (let i = 0; i < LADDER.length; i++) { const p = runTier(LADDER[i], i); if (p) { pts.push(p); lib.recordSkill(id, p.tier, 0.5, p.win_rate, p.n); } }+ const m = pts.length >= 2 ? slope(pts) : 0;+ const dir = m < -1 ? 'SUBSTITUTES (helps weak models more)' : m > 1 ? 'COMPLEMENTS (helps strong models more)' : 'flat/no interaction';+ lib.update(id, { status: 'evaluated', lift_pp: +m.toFixed(2), n_problems: pts.reduce((a, p) => a + p.n, 0),+ notes: `IN-DOMAIN (software/decision), pairwise, fixed judge ${JUDGE}, isolation ON. slope=${m.toFixed(1)}pp/step → ${dir}. tiers: ${pts.map(p => p.tier + ':' + (p.win_rate * 100).toFixed(0) + '%(p=' + p.p + ')').join(', ')}.` });+ console.log(`\n slope = ${m.toFixed(1)} pp per capability step → ${dir}`);+ console.log(` ledger id: ${id}`);+}+main();diff --git a/experiments/run-capability.js b/experiments/run-capability.jsnew file mode 100644index 0000000..1972433--- /dev/null+++ b/experiments/run-capability.js@@ -0,0 +1,72 @@+#!/usr/bin/env node+'use strict';++/**+ * Capability-substitution experiments. Tests whether a skill helps MORE at lower+ * capability (the core hypothesis). Two axes, correctness-mode (judge-free):+ * effort: one model, sweep reasoning effort (low→xhigh)+ * model : fixed effort, sweep a capability ladder (haiku→sonnet→opus)+ * Fits the lift-vs-capability slope; a NEGATIVE slope = skills substitute for+ * capability. Each sweep is registered in the experiments ledger with a unique id.+ *+ * Usage: node experiments/run-capability.js effort+ * node experiments/run-capability.js model+ */++const fs = require('fs');+const path = require('path');+const { spawnSync } = require('child_process');+const lib = require('./lib');++const ROOT = lib.REPO_ROOT;+const LIMIT = process.env.LIMIT || '24';+const FORCE_SKILL = process.env.FORCE_SKILL || 'bayesian';+const TAGS = process.env.TAGS || 'medical';++const SWEEPS = {+ effort: { hyp: 'CAP-EFFORT', model: process.env.SWEEP_MODEL || 'claude-opus-4-8', cells: (process.env.EFFORTS || 'low,medium,high,max').split(','), label: e => e, vary: 'effort' },+ model: { hyp: 'CAP-MODEL', effort: 'medium', cells: ['claude-haiku-4-5-20251001', 'claude-sonnet-4-6', 'claude-opus-4-8'], label: m => m.replace('claude-', '').replace('-4-8', '').replace('-4-5-20251001', '').replace('-4-6', ''), vary: 'model' },+};++function runCell(sweep, cell, idx) {+ const id = lib.genId(sweep.hyp + '-' + sweep.label(cell));+ const out = path.join(ROOT, 'evals', 'results', 'capability', `${sweep.hyp}-${idx}.json`);+ const env = { ...process.env, LIMIT, FORCE_SKILL, TAGS,+ SOLVER_MODEL: sweep.vary === 'model' ? cell : sweep.model,+ SOLVER_EFFORT: sweep.vary === 'effort' ? cell : sweep.effort,+ OUTFILE: out };+ const r = spawnSync('node', ['evals/run-correctness.js', ...TAGS.split(' ')], { cwd: ROOT, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ if (r.status !== 0) { console.log(` cell ${sweep.label(cell)} FAILED: ${(r.stderr || '').slice(-200)}`); return null; }+ const res = JSON.parse(fs.readFileSync(out, 'utf8'));+ console.log(` ${sweep.label(cell).padEnd(10)} acc_skill ${(res.acc_with_skill * 100).toFixed(0)}% acc_placebo ${(res.acc_placebo * 100).toFixed(0)}% Δ ${res.delta_pp >= 0 ? '+' : ''}${res.delta_pp}pp (McNemar p=${res.mcnemar_p}, n=${res.n})`);+ return { cell: sweep.label(cell), rank: idx, delta: res.delta_pp, acc_with: res.acc_with_skill, acc_placebo: res.acc_placebo, n: res.n, mcnemar_p: res.mcnemar_p };+}++// least-squares slope of delta vs capability rank+function slope(points) {+ const n = points.length, sx = points.reduce((a, p) => a + p.rank, 0), sy = points.reduce((a, p) => a + p.delta, 0);+ const sxy = points.reduce((a, p) => a + p.rank * p.delta, 0), sxx = points.reduce((a, p) => a + p.rank * p.rank, 0);+ return (n * sxy - sx * sy) / (n * sxx - sx * sx);+}++async function main() {+ const which = process.argv[2];+ const sweep = SWEEPS[which];+ if (!sweep) { console.error('usage: run-capability.js effort|model'); process.exit(1); }+ lib.init();+ const id = lib.genId(sweep.hyp);+ console.log(`▶ ${id} — ${sweep.hyp} sweep (skill=${FORCE_SKILL}, ${TAGS}, n≤${LIMIT}/cell), isolation ${process.env.EVAL_NO_ISOLATE === '1' ? 'OFF' : 'ON'}`);+ lib.register({ id, hypothesis: sweep.hyp, title: `Capability-substitution: ${sweep.vary} sweep (${FORCE_SKILL} on ${TAGS})`,+ intervention: 'capability-sweep', skills: [FORCE_SKILL], status: 'running', dataset: TAGS });++ const pts = [];+ for (let i = 0; i < sweep.cells.length; i++) { const p = runCell(sweep, sweep.cells[i], i); if (p) { pts.push(p); lib.recordSkill(id, p.cell, p.acc_placebo, p.acc_with, p.n); } }+ const m = pts.length >= 2 ? slope(pts) : 0;+ const direction = m < -0.5 ? 'SUBSTITUTES (helps more at low capability)' : m > 0.5 ? 'COMPLEMENTS (helps more at high capability)' : 'flat/no interaction';+ lib.update(id, { status: 'evaluated', result_win_rate: pts.length ? pts[0].acc_with : null, lift_pp: +m.toFixed(2),+ n_problems: pts.reduce((a, p) => a + p.n, 0),+ notes: `slope of lift vs ${sweep.vary}-rank = ${m.toFixed(2)} pp/step → ${direction}. cells: ${pts.map(p => p.cell + ':' + (p.delta >= 0 ? '+' : '') + p.delta + 'pp').join(', ')}. ISOLATION ${process.env.EVAL_NO_ISOLATE === '1' ? 'OFF' : 'ON'}.` });+ console.log(`\n slope = ${m.toFixed(2)} pp per capability step → ${direction}`);+ console.log(` ledger id: ${id}`);+}+main();diff --git a/experiments/run-experiment.js b/experiments/run-experiment.jsnew file mode 100644index 0000000..3da87bf--- /dev/null+++ b/experiments/run-experiment.js@@ -0,0 +1,137 @@+#!/usr/bin/env node+'use strict';++/**+ * Run lift experiments, each in its own git worktree, and track EVERY one in the+ * central experiments ledger with a unique id — whether merged or not.+ *+ * Flow per executed experiment:+ * register(unique id) → git worktree add (branch exp/<id>) → apply intervention+ * → commit → run behavioral eval in the worktree → record lift vs main baseline+ * → status: merged | evaluated(merge-pending) | discarded → remove worktree.+ *+ * Usage:+ * node experiments/run-experiment.js --register-all # register every spec+ * node experiments/run-experiment.js L1 L2 # register all + run L1,L2+ * MERGE=1 node experiments/run-experiment.js L1 L2 # also merge positive-lift branches to main+ */++const fs = require('fs');+const path = require('path');+const { spawnSync } = require('child_process');+const lib = require('./lib');+const { SPECS, INTERVENTIONS } = require('./specs');++const REPO = lib.REPO_ROOT;+const WT_PARENT = path.join(REPO, '..', 'cc-tsk-wt');+const SOLVER = process.env.SOLVER_MODEL || 'claude-sonnet-4-6';+const JUDGE = process.env.JUDGE_MODEL || 'gemini-3.1-pro-preview';+const DO_MERGE = process.env.MERGE === '1';++function git(args, cwd = REPO) {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr || r.stdout}`);+ return r.stdout.trim();+}++// The eval harness is uncommitted on main (untracked), so a fresh worktree at+// HEAD lacks it. Copy the needed harness pieces in (they stay untracked in the+// worktree and vanish when it's removed). The committed 39 skills are already+// present from HEAD; the intervention has already modified them + committed.+function copyHarness(worktree) {+ fs.mkdirSync(path.join(worktree, 'evals'), { recursive: true });+ for (const p of ['lib', 'rubrics', 'datasets']) {+ spawnSync('cp', ['-R', path.join(REPO, 'evals', p), path.join(worktree, 'evals', p)]);+ }+ spawnSync('cp', [path.join(REPO, 'evals', 'run-behavioral.js'), path.join(worktree, 'evals', 'run-behavioral.js')]);+}++async function execute(spec) {+ const id = lib.genId(spec.hypothesis);+ const branch = `exp/${id}`;+ const worktree = path.join(WT_PARENT, id);+ console.log(`\n▶ ${id} — ${spec.title}`);+ lib.register({ ...spec, id, branch, worktree, status: 'running' });++ try {+ fs.mkdirSync(WT_PARENT, { recursive: true });+ git(['worktree', 'add', '-b', branch, worktree, 'HEAD']);+ console.log(` worktree: ${worktree} (branch ${branch})`);++ console.log(` applying intervention: ${spec.intervention} on ${spec.skills.join(', ')}`);+ await INTERVENTIONS[spec.intervention](worktree, spec.skills);+ git(['add', '-A'], worktree);+ git(['commit', '-m', `exp ${id}: ${spec.intervention} on ${spec.skills.join(',')}`], worktree);+ const commit = git(['rev-parse', 'HEAD'], worktree);++ // Paired, length-balanced, SAME-RUN head-to-head: modified skill vs original+ // skill on the same problems. Removes the run-variance + length confounds of+ // the first pass; run-paired.js executes from main (reads both skill dirs).+ console.log(` running paired head-to-head (modified vs original, length-balanced)…`);+ const outPath = path.join(REPO, 'evals', 'results', id, 'paired.json');+ const args = ['experiments/run-paired.js', ...spec.skills.map(s => 'thinking-' + s.replace(/^thinking-/, ''))];+ const env = { ...process.env, ORIG_DIR: REPO, MOD_DIR: worktree, SOLVER_MODEL: SOLVER, JUDGES: process.env.JUDGES || JUDGE, CONC: '3', SOLVER_EFFORT: 'medium', OUT: outPath };+ const r = spawnSync('node', args, { cwd: REPO, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ if (r.status !== 0) throw new Error('paired eval failed: ' + (r.stderr || '').slice(-400));+ const res = JSON.parse(fs.readFileSync(outPath, 'utf8'));+ const agg = res.aggregate;++ for (const s of res.skills) {+ lib.recordSkill(id, s.skill, 0.5, s.win_rate, s.n);+ console.log(` ${s.skill}: modified beats original ${(s.win_rate * 100).toFixed(0)}% (n=${s.n}, CI [${(s.ci95[0] * 100).toFixed(0)},${(s.ci95[1] * 100).toFixed(0)}])`);+ }+ const winRate = agg.win_rate, liftPp = (winRate - 0.5) * 100, positive = winRate > 0.5, sig = agg.significant;++ let status = positive ? 'evaluated' : 'discarded';+ let mergedNote = '';+ if (positive && sig && DO_MERGE) {+ try { git(['merge', '--no-ff', '-m', `Merge ${id} (paired ${(winRate * 100).toFixed(0)}% vs original, p=${agg.p_value})`, branch]); status = 'merged'; mergedNote = ' [merged to main]'; }+ catch (e) { mergedNote = ' [merge failed: ' + e.message.slice(0, 80) + ']'; }+ }++ lib.update(id, {+ status, commit_hash: commit, baseline_win_rate: 0.5, result_win_rate: winRate,+ lift_pp: +liftPp.toFixed(1), n_problems: agg.n, merge_recommended: (positive && sig) ? 1 : 0,+ notes: `paired head-to-head, length-balanced, same-run. modified beats original ${(winRate * 100).toFixed(0)}% (n=${agg.n}, 95% CI [${(agg.ci95[0] * 100).toFixed(0)},${(agg.ci95[1] * 100).toFixed(0)}], p=${agg.p_value}, ${sig ? 'SIGNIFICANT' : 'directional'}). commit ${commit.slice(0, 9)}.`,+ });+ console.log(` aggregate: modified beats original ${(winRate * 100).toFixed(0)}% 95% CI [${(agg.ci95[0] * 100).toFixed(0)},${(agg.ci95[1] * 100).toFixed(0)}] p=${agg.p_value} → status=${status}${mergedNote}`);++ try { git(['worktree', 'remove', '--force', worktree]); } catch (_) {}+ return { id, status, liftPp, sig };+ } catch (e) {+ lib.update(id, { status: 'failed', notes: String(e.message).slice(0, 300) });+ console.log(` FAILED: ${e.message.slice(0, 200)}`);+ try { git(['worktree', 'remove', '--force', worktree]); } catch (_) {}+ return { id, status: 'failed' };+ }+}++async function main() {+ lib.init();+ const argv = process.argv.slice(2);+ const registerAll = argv.includes('--register-all');+ const toRun = argv.filter(a => !a.startsWith('--'));++ // 1) register EVERY spec (planned ones tracked too)+ for (const spec of SPECS) {+ if (toRun.includes(spec.hypothesis)) continue; // executed ones get registered inside execute()+ const id = `exp-${spec.hypothesis.toLowerCase()}-planned`; // stable id → idempotent across re-runs+ lib.register({ ...spec, id, status: spec.run ? 'registered' : 'planned',+ notes: spec.run ? 'runnable; not selected this invocation' : 'planned — intervention not yet implemented / needs Class-B (distractor) eval' });+ console.log(`registered ${id} [${spec.run ? 'registered' : 'planned'}] — ${spec.hypothesis}: ${spec.title}`);+ }++ // 2) execute the requested ones+ const results = [];+ for (const hyp of toRun) {+ const spec = SPECS.find(s => s.hypothesis === hyp);+ if (!spec) { console.log(`no spec for ${hyp}`); continue; }+ if (!spec.run) { console.log(`${hyp} is not runnable (planned)`); continue; }+ results.push(await execute(spec));+ }+ console.log('\n=== summary ===');+ for (const r of results) console.log(` ${r.id}: ${r.status}${r.liftPp != null ? ' (' + (r.liftPp >= 0 ? '+' : '') + r.liftPp.toFixed(1) + 'pp)' : ''}`);+ console.log(`\nLedger: ${lib.DB}`);+}++main();diff --git a/experiments/run-paired.js b/experiments/run-paired.jsnew file mode 100644index 0000000..cbb897d--- /dev/null+++ b/experiments/run-paired.js@@ -0,0 +1,73 @@+#!/usr/bin/env node+'use strict';++/**+ * Paired, length-balanced, same-run head-to-head: does the MODIFIED skill make+ * the solver reason better than the ORIGINAL skill on the same problems?+ *+ * Fixes the two confounds in the first experiment pass:+ * - run variance: both arms are solved + judged in the SAME invocation.+ * - length: the shorter skill version is padded with neutral filler to equal+ * the longer one, so only CONTENT differs (key for L1 trigger-vs-full).+ *+ * Reports the modified-vs-original win-rate with a CI + sign-test p-value, so the+ * lift is a real (if small-N) significance statement, not a stored-baseline delta.+ *+ * Env: ORIG_DIR (skills dir for originals), MOD_DIR (modified skills dir),+ * SOLVER_MODEL, JUDGES, CONC, OUT (json path). Args: skill short-names.+ */++const fs = require('fs');+const path = require('path');+const { droidExecAsync } = require('../evals/lib/droid');+const { buildBalancedSkillPrompt, wordCount } = require('../evals/lib/conditions');+const { panelJudge } = require('../evals/lib/judge');+const { summarize } = require('../evals/lib/stats');+const { mapPool } = require('../evals/lib/io');++const ORIG_DIR = process.env.ORIG_DIR;+const MOD_DIR = process.env.MOD_DIR;+const SOLVER = process.env.SOLVER_MODEL || 'claude-sonnet-4-6';+const SOLVER_EFFORT = process.env.SOLVER_EFFORT || 'medium';+const CONC = parseInt(process.env.CONC || '3', 10);+const OUT = process.env.OUT;+const DATA_DIR = path.join(__dirname, '..', 'evals', 'datasets', 'behavioral');+const RUBRIC = fs.readFileSync(path.join(__dirname, '..', 'evals', 'rubrics', 'behavioral-pairwise.md'), 'utf8');++function skillMd(dir, short) { return fs.readFileSync(path.join(dir, 'skills', 'thinking-' + short, 'SKILL.md'), 'utf8'); }+function judgePrompt(problem, a, b) { return `${RUBRIC}\n\n=== PROBLEM ===\n${problem.prompt}\n\n=== RESPONSE A ===\n${a}\n\n=== RESPONSE B ===\n${b}\n\n=== END ===\nReturn ONLY the JSON verdict.`; }++async function runSkill(short) {+ const orig = skillMd(ORIG_DIR, short), mod = skillMd(MOD_DIR, short);+ const target = Math.max(wordCount(orig), wordCount(mod));+ const ds = JSON.parse(fs.readFileSync(path.join(DATA_DIR, `thinking-${short}.json`), 'utf8'));+ let wins = 0, losses = 0, ties = 0;+ for (let i = 0; i < ds.problems.length; i++) {+ const p = ds.problems[i];+ const [rm, ro] = await Promise.all([+ droidExecAsync({ model: SOLVER, effort: SOLVER_EFFORT, prompt: buildBalancedSkillPrompt(mod, p.prompt, target) }),+ droidExecAsync({ model: SOLVER, effort: SOLVER_EFFORT, prompt: buildBalancedSkillPrompt(orig, p.prompt, target) }),+ ]);+ if (!rm.ok || !ro.ok) continue;+ const modIsA = i % 2 === 0; // deterministic order balance+ const v = await panelJudge(judgePrompt(p, modIsA ? rm.text : ro.text, modIsA ? ro.text : rm.text));+ let w = 'tie';+ if (v.winner === 'A') w = modIsA ? 'mod' : 'orig';+ else if (v.winner === 'B') w = modIsA ? 'orig' : 'mod';+ if (w === 'mod') wins++; else if (w === 'orig') losses++; else ties++;+ }+ return { skill: short, ...summarize(wins, losses, ties) };+}++async function main() {+ if (!ORIG_DIR || !MOD_DIR) { console.error('set ORIG_DIR and MOD_DIR'); process.exit(1); }+ const skills = process.argv.slice(2).map(s => s.replace(/^thinking-/, ''));+ const perSkill = await mapPool(skills, CONC, runSkill);+ const W = perSkill.reduce((a, s) => a + s.wins, 0), L = perSkill.reduce((a, s) => a + s.losses, 0), T = perSkill.reduce((a, s) => a + s.ties, 0);+ const agg = summarize(W, L, T);+ const out = { mode: 'paired-head-to-head', metric: 'modified beats original', solver: SOLVER, skills: perSkill, aggregate: agg };+ if (OUT) { fs.mkdirSync(path.dirname(OUT), { recursive: true }); fs.writeFileSync(OUT, JSON.stringify(out, null, 2)); }+ console.log(JSON.stringify({ aggregate: agg, perSkill: perSkill.map(s => ({ skill: s.skill, win_rate: s.win_rate, ci: s.ci95, p: s.p_value })) }, null, 2));+}++main();diff --git a/experiments/run-stack.js b/experiments/run-stack.jsnew file mode 100644index 0000000..3345c34--- /dev/null+++ b/experiments/run-stack.js@@ -0,0 +1,72 @@+#!/usr/bin/env node+'use strict';++/**+ * Skill-stacking experiment: does combining skills beat a single skill (synergy)+ * or just add bloat? Length-controlled, same-run, panel-judged.+ *+ * Conditions (all padded to the stack's word length to isolate content):+ * placebo — neutral filler only+ * single — the first skill alone+ * stack — all N skills combined+ * Judged pairwise: stack-vs-placebo (does stacking help at all) and+ * stack-vs-single (synergy beyond one lens). Problems = the union of the+ * stacked skills' own behavioral problems (where ≥1 lens should apply).+ *+ * Usage: node experiments/run-stack.js thinking-first-principles thinking-second-order thinking-red-team+ */++const fs = require('fs');+const path = require('path');+const { droidExecAsync } = require('../evals/lib/droid');+const { buildConditionPrompt, buildBalancedSkillPrompt, buildStackPrompt, wordCount, neutralFiller } = require('../evals/lib/conditions');+const { panelJudge } = require('../evals/lib/judge');+const { summarize } = require('../evals/lib/stats');++const SOLVER = process.env.SOLVER_MODEL || 'claude-sonnet-4-6';+const SOLVER_EFFORT = process.env.SOLVER_EFFORT || 'medium';+const ROOT = path.join(__dirname, '..');+const DATA = path.join(ROOT, 'evals', 'datasets', 'behavioral');+const RUBRIC = fs.readFileSync(path.join(ROOT, 'evals', 'rubrics', 'behavioral-pairwise.md'), 'utf8');+const skillMd = s => fs.readFileSync(path.join(ROOT, 'skills', 'thinking-' + s.replace(/^thinking-/, ''), 'SKILL.md'), 'utf8');+const judgePrompt = (p, a, b) => `${RUBRIC}\n\n=== PROBLEM ===\n${p.prompt}\n\n=== RESPONSE A ===\n${a}\n\n=== RESPONSE B ===\n${b}\n\n=== END ===\nReturn ONLY the JSON verdict.`;++async function main() {+ const skills = process.argv.slice(2).map(s => s.replace(/^thinking-/, ''));+ if (skills.length < 2) { console.error('give >=2 skills to stack'); process.exit(1); }+ const contents = skills.map(skillMd);+ const stackText = contents.map((c, i) => `SKILL ${i}\n${c}`).join('\n');+ const target = wordCount(stackText);+ // problems = union of the stacked skills' behavioral problems+ const problems = [];+ for (const s of skills) {+ const ds = JSON.parse(fs.readFileSync(path.join(DATA, `thinking-${s}.json`), 'utf8'));+ ds.problems.forEach(p => problems.push(p));+ }+ console.log(`Stacking ${skills.join(' + ')} | ${problems.length} problems | solver=${SOLVER}(${SOLVER_EFFORT})`);++ const tallies = { 'stack:placebo': { w: 0, l: 0, t: 0 }, 'stack:single': { w: 0, l: 0, t: 0 } };+ for (let i = 0; i < problems.length; i++) {+ const p = problems[i];+ const [placebo, single, stack] = await Promise.all([+ droidExecAsync({ model: SOLVER, effort: SOLVER_EFFORT, prompt: `Some general notes:\n\n${neutralFiller(target)}\n\nNow address this problem:\n\n${p.prompt}\n\nThink carefully and give your best, decision-useful answer.` }),+ droidExecAsync({ model: SOLVER, effort: SOLVER_EFFORT, prompt: buildBalancedSkillPrompt(contents[0], p.prompt, target) }),+ droidExecAsync({ model: SOLVER, effort: SOLVER_EFFORT, prompt: buildStackPrompt(contents, p.prompt, target) }),+ ]);+ if (!placebo.ok || !single.ok || !stack.ok) continue;+ for (const [key, other] of [['stack:placebo', placebo], ['stack:single', single]]) {+ const stackIsA = i % 2 === 0;+ const v = await panelJudge(judgePrompt(p, stackIsA ? stack.text : other.text, stackIsA ? other.text : stack.text));+ let w = 'tie';+ if (v.winner === 'A') w = stackIsA ? 'stack' : 'other';+ else if (v.winner === 'B') w = stackIsA ? 'other' : 'stack';+ if (w === 'stack') tallies[key].w++; else if (w === 'other') tallies[key].l++; else tallies[key].t++;+ }+ }+ const out = { stack: skills, solver: SOLVER, problems: problems.length };+ for (const k of Object.keys(tallies)) out[k] = summarize(tallies[k].w, tallies[k].l, tallies[k].t);+ if (process.env.OUTFILE) { fs.mkdirSync(path.dirname(process.env.OUTFILE), { recursive: true }); fs.writeFileSync(process.env.OUTFILE, JSON.stringify(out, null, 2)); }+ console.log(JSON.stringify(out, null, 2));+}++main();diff --git a/experiments/specs.js b/experiments/specs.jsnew file mode 100644index 0000000..28aae5d--- /dev/null+++ b/experiments/specs.js@@ -0,0 +1,87 @@+'use strict';++/**+ * Registry of lift experiments (from analysis/LIFT-HYPOTHESES.md) + the+ * interventions that mutate skills inside a worktree. `run:true` ones are+ * executed end-to-end; the rest are registered in the ledger as 'planned' so+ * every hypothesis is tracked with a unique id.+ */++const fs = require('fs');+const path = require('path');+const { droidExecAsync } = require('../evals/lib/droid');++function skillFile(root, short) { return path.join(root, 'skills', 'thinking-' + short.replace(/^thinking-/, ''), 'SKILL.md'); }+function splitFrontmatter(md) {+ const m = md.match(/^(---\n[\s\S]*?\n---\n)([\s\S]*)$/);+ return m ? { fm: m[1], body: m[2] } : { fm: '', body: md };+}++// --- interventions (mutate worktree skills in place) ---++// L1: replace a conceptual skill's long body with a compact trigger card.+async function conceptualToTrigger(root, skills) {+ for (const s of skills) {+ const f = skillFile(root, s);+ const md = fs.readFileSync(f, 'utf8');+ const { fm } = splitFrontmatter(md);+ const title = (md.match(/^#\s+(.+)$/m) || [, s])[1];+ const core = (md.match(/\*\*Core Principle:\*\*\s*(.+)/) || [, ''])[1].trim();+ const desc = (md.match(/description:\s*(.+)/) || [, ''])[1].trim();+ const whenBullets = (md.match(/## When to Use\n([\s\S]*?)(\n##|\n$)/) || [, ''])[1]+ .split('\n').filter(l => l.trim().startsWith('-')).slice(0, 4).join('\n');+ const trigger = `${fm}# ${title}\n\n${desc}\n\n**Core Principle:** ${core || desc}\n\n## When to Use\n${whenBullets || '- ' + desc}\n\n(Trigger card — apply the model directly; do not narrate the framework.)\n`;+ fs.writeFileSync(f, trigger);+ }+}++// L2: rewrite a skill for an AI-agent consumer (strip human stage-directions,+// reframe around LLM failure modes, add explicit stop conditions).+async function llmNativeRewrite(root, skills) {+ for (const s of skills) {+ const f = skillFile(root, s);+ const md = fs.readFileSync(f, 'utf8');+ const { fm, body } = splitFrontmatter(md);+ const prompt = `Rewrite the following thinking-skill guide so it is optimal for an autonomous AI CODING/REASONING AGENT (not a human in a meeting). Requirements:+- Remove human-only stage directions ("gather the team", "project to age 80", "silent brainstorming", "your gut feeling").+- Reframe around how LLMs actually fail (sycophancy to the user's framing, recency/anchoring on the prompt, fabricating specific numbers/probabilities, over-confident calibration), not human cognition.+- Add an explicit "## When NOT to Use / Stop Conditions" section: when the agent should skip this and just answer directly.+- Add a "do not fabricate facts or invent precise numbers you don't have" guard where relevant.+- Keep it concrete and tighter than the original; keep useful steps/examples.+Return ONLY the markdown BODY (no YAML frontmatter, no preamble).++ORIGINAL BODY:+${body}`;+ const r = await droidExecAsync({ model: 'gpt-5.5-pro', effort: 'high', prompt, timeoutMs: 600000 });+ const newBody = (r.ok && r.text && r.text.length > 200) ? r.text.replace(/^```\w*\n?|```$/g, '').trim() : body;+ fs.writeFileSync(f, fm + newBody + '\n');+ }+}++const INTERVENTIONS = { 'conceptual-to-trigger': conceptualToTrigger, 'llm-native-rewrite': llmNativeRewrite };++const SPECS = [+ { hypothesis: 'L1', title: 'Bifurcation: conceptual skills → trigger cards', run: true,+ intervention: 'conceptual-to-trigger', skills: ['occams-razor', 'five-whys-plus', 'inversion', 'systems'],+ description: 'Replace verbose conceptual skills the model already knows with a 2-3 sentence trigger card; test trigger >= full file.' },+ { hypothesis: 'L2', title: 'LLM-native rewrite of human-artifact skills', run: true,+ intervention: 'llm-native-rewrite', skills: ['regret-minimization', 'debiasing', 'bayesian', 'circle-of-competence'],+ description: 'Strip human stage-directions, reframe around LLM failure modes, add stop conditions + no-fabrication guards.' },+ { hypothesis: 'L3', title: 'Procedural skills as executable checklists', run: false,+ intervention: 'executable-checklist', skills: ['bayesian', 'debiasing', 'pre-mortem', 'opportunity-cost'],+ description: 'Convert procedural skills to inputs→steps→stop→answer-template; planned (needs intervention impl).' },+ { hypothesis: 'L4', title: 'Universal "When NOT to use" boundaries', run: false,+ intervention: 'add-boundaries', skills: ['ALL'],+ description: 'Class-B: measurable only with an expanded distractor eval (off-target problems).' },+ { hypothesis: 'L5', title: 'Consolidate 5 overlap clusters', run: false,+ intervention: 'consolidate-clusters', skills: ['bayesian+probabilistic', 'inversion+pre-mortem', 'model-selection→router'],+ description: 'Merge unanimous clusters; mainly improves routing discrimination (Class-B).' },+ { hypothesis: 'VGATE', title: 'Post-skill verifier / reversion gate', run: false,+ intervention: 'harness-verifier', skills: [],+ description: 'GPT unique idea: a no-framework verifier pass reverts framework-theater outputs. Harness change, not skill edit.' },+ { hypothesis: 'APULL', title: 'Active-pull consult_mental_model tool', run: false,+ intervention: 'architecture-active-pull', skills: [],+ description: 'Gemini unique idea: on-demand tool instead of auto-injection. Architecture change; needs Class-B eval.' },+];++module.exports = { SPECS, INTERVENTIONS };