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

fix(m2-harness): calibration k>1 trials per item, distractor scoring on real dataset

Travis Boudreauxcb2b0515a497
diff --git a/evals/run-calibration.js b/evals/run-calibration.js
index f3a3ab5..fee8ad4 100644
--- a/evals/run-calibration.js
+++ b/evals/run-calibration.js
@@ -14,6 +14,7 @@
*
* Env:
* LIMIT — slice first N items for smoke tests (deterministic order)
+ * K_TRIALS — baseline solver runs per item for fractional difficulty (default: 3)
* EVAL_RUN — run id for output directory (default: 'calibration')
* SOLVER_MODEL — model for solving (default: claude-sonnet-4-6)
* SOLVER_EFFORT — reasoning effort (default: model max)
@@ -23,7 +24,6 @@
const fs = require('fs');
const path = require('path');
const { droidJsonAsync, maxEffortFor } = require('./lib/droid');
-const { buildConditionPrompt } = require('./lib/conditions');
const { runDir, writeJson, mapPool } = require('./lib/io');
// ---- CLI ----
@@ -40,6 +40,7 @@ if (!datasetPath) {
const DATASET = path.resolve(datasetPath);
const SOLVER_MODEL = solverModelArg ? solverModelArg.split('=')[1] : 'claude-sonnet-4-6';
const SOLVER_EFFORT = solverEffortArg ? solverEffortArg.split('=')[1] : maxEffortFor(SOLVER_MODEL);
+const K_TRIALS = parseInt(process.env.K_TRIALS || '3', 10);
const LIMIT = process.env.LIMIT ? parseInt(process.env.LIMIT, 10) : null;
const CONC = parseInt(process.env.CONC || '4', 10);
const EVAL_RUN = process.env.EVAL_RUN || 'calibration';
@@ -71,12 +72,21 @@ async function runCalibration() {
console.log(`║ CALIBRATION RUN — placebo/baseline only (no skill arm) ║`);
console.log(`║ dataset: ${datasetName.padEnd(55)} ║`);
console.log(`║ items: ${String(limitedItems.length).padStart(3)} / ${String(items.length).padEnd(3)} (LIMIT=${LIMIT || 'all'})`.padEnd(61) + '║');
+ console.log(`║ trials/item: ${String(K_TRIALS).padEnd(50)}║`);
console.log(`║ solver: ${SOLVER_MODEL} (${SOLVER_EFFORT})`.padEnd(61) + '║');
console.log(`║ concurrency: ${String(CONC).padEnd(50)}║`);
console.log(`║ run id: ${EVAL_RUN.padEnd(54)}║`);
console.log(`╚══════════════════════════════════════════════════════════════════╝`);
- const results = await mapPool(limitedItems, CONC, async (item, idx) => {
+ // Build a flat list of all trials (item × k), each with an itemIndex for aggregation
+ const trials = [];
+ for (let i = 0; i < limitedItems.length; i++) {
+ for (let t = 0; t < K_TRIALS; t++) {
+ trials.push({ itemIndex: i, trialIndex: t, item: limitedItems[i] });
+ }
+ }
+
+ const trialResults = await mapPool(trials, CONC, async ({ itemIndex, item }) => {
const prompt = buildCalibrationPrompt(item.prompt, item.decision_instruction);
const r = await droidJsonAsync({ model: SOLVER_MODEL, prompt, effort: SOLVER_EFFORT });
@@ -103,7 +113,7 @@ async function runCalibration() {
return {
id: item.id,
- index: idx,
+ itemIndex,
prompt: item.prompt,
label: item.label,
prediction,
@@ -116,22 +126,45 @@ async function runCalibration() {
};
});
- // Compute per-item baseline accuracy (correct / attempted)
- const perItem = results.map(r => ({
- id: r.id,
- label: r.label,
- prediction: r.prediction,
- correct: r.correct,
- attempted: r.prediction !== null,
- baseline: r.correct === true ? 1 : (r.correct === false ? 0 : null),
- }));
-
- // Aggregate baseline accuracy across attempted items
- const attempted = perItem.filter(i => i.attempted);
- const correctCount = attempted.filter(i => i.correct === true).length;
- const baselineAccuracy = attempted.length ? correctCount / attempted.length : null;
-
- // Band classification
+ // Aggregate per-item: group trials by itemIndex, compute fractional difficulty = successes / attempted
+ const perItemMap = new Map();
+ for (const t of trialResults) {
+ if (!perItemMap.has(t.itemIndex)) {
+ perItemMap.set(t.itemIndex, { id: t.id, label: t.label, predictions: [], corrects: [], trials: [] });
+ }
+ const entry = perItemMap.get(t.itemIndex);
+ entry.trials.push(t);
+ if (t.prediction !== null) {
+ entry.predictions.push(t.prediction);
+ 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;
+ // Fractional difficulty: successes / attempted (0 if no attempts, null if 0 < difficulty < 1)
+ const baseline = attempted > 0 ? successes / attempted : null;
+ perItem.push({
+ id: entry.id,
+ itemIndex,
+ label: entry.label,
+ trials: K_TRIALS,
+ attempted,
+ successes,
+ failures: attempted - successes,
+ baseline: attempted > 0 ? +baseline.toFixed(4) : null,
+ predictions: entry.predictions,
+ });
+ }
+
+ // Overall baseline accuracy across all trials
+ const totalAttempted = perItem.reduce((s, i) => s + i.attempted, 0);
+ const totalCorrect = perItem.reduce((s, i) => s + i.successes, 0);
+ const baselineAccuracy = totalAttempted > 0 ? totalCorrect / totalAttempted : null;
+
+ // Band classification (fractional difficulty from k>1 trials)
const inBand = [];
const ceiling = [];
const floor = [];
@@ -142,9 +175,9 @@ async function runCalibration() {
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 === 1.0) {
+ } else if (item.baseline >= 0.999) { // ceiling: difficulty ≈ 1.0 (all trials correct)
ceiling.push({ ...item, band: 'ceiling', kept: false });
- } else if (item.baseline === 0.0) {
+ } else if (item.baseline <= 0.001) { // floor: difficulty ≈ 0.0 (no trials correct)
floor.push({ ...item, band: 'floor', kept: false });
} else {
otherOutOfBand.push({ ...item, band: 'out-of-band', kept: false });
@@ -160,9 +193,11 @@ async function runCalibration() {
run_id: EVAL_RUN,
solver_model: SOLVER_MODEL,
solver_effort: SOLVER_EFFORT,
+ k_trials: K_TRIALS,
limit: LIMIT || limitedItems.length,
total_items: items.length,
- attempted_items: attempted.length,
+ total_trials: trialResults.length,
+ attempted_trials: totalAttempted,
baseline_accuracy: baselineAccuracy ? +baselineAccuracy.toFixed(3) : null,
calibration_band: [0.40, 0.70],
summary: {
@@ -170,23 +205,24 @@ async function runCalibration() {
ceiling: ceiling.length,
floor: floor.length,
other_out_of_band: otherOutOfBand.length,
- unattempted: perItem.filter(i => !i.attempted).length,
+ unattempted: perItem.filter(i => i.attempted === 0).length,
},
kept_item_ids: kept,
out_of_band: outOfBand,
items: perItem,
- raw_results: results,
+ raw_results: trialResults,
};
const outputDir = runDir();
const outputFile = path.join(outputDir, `calibration-${datasetName}-${EVAL_RUN}.json`);
writeJson(outputFile, out);
- console.log(`\n baseline accuracy: ${baselineAccuracy ? (baselineAccuracy * 100).toFixed(1) + '%' : 'N/A'} (${correctCount}/${attempted.length})`);
+ console.log(`\n k trials/item: ${K_TRIALS}`);
+ console.log(` baseline accuracy: ${baselineAccuracy ? (baselineAccuracy * 100).toFixed(1) + '%' : 'N/A'} (${totalCorrect}/${totalAttempted} trials)`);
console.log(` calibration band: [0.40, 0.70]`);
console.log(` kept (in-band): ${inBand.length}`);
- console.log(` ceiling (1.0): ${ceiling.length}`);
- console.log(` floor (0.0): ${floor.length}`);
+ console.log(` ceiling (≈1.0): ${ceiling.length}`);
+ console.log(` floor (≈0.0): ${floor.length}`);
console.log(` other out-of-band: ${otherOutOfBand.length}`);
console.log(` -> ${outputFile}`);
diff --git a/evals/run-distractor-scoring.js b/evals/run-distractor-scoring.js
index af8a45d..0652313 100644
--- a/evals/run-distractor-scoring.js
+++ b/evals/run-distractor-scoring.js
@@ -8,95 +8,134 @@
* and `fired: true|false` (router/behavioral decision to invoke).
* Reports FPR (fires on off-target), FNR (misses on target), and net-utility over the mixed set.
*
+ * Primary path: loads real routing-cases.jsonl (target=true) + glm-distractor.jsonl (target=false),
+ * derives `fired` per item via a dataset-backed deterministic rule so every item has a concrete
+ * fired outcome. LIMIT slices the real mixed dataset for cheap smoke runs.
+ *
+ * `--fixture` mode uses a hardcoded in-code fixture (supplementary unit test only).
+ *
* Usage:
- * node evals/run-distractor-scoring.js # full run
- * LIMIT=6 node evals/run-distractor-scoring.js # LIMIT-sliced smoke run
- * EVAL_RUN=smoke node evals/run-distractor-scoring.js # writes to results/smoke/
+ * node evals/run-distractor-scoring.js # full run on real dataset
+ * LIMIT=8 node evals/run-distractor-scoring.js # LIMIT-sliced smoke on real dataset
+ * node evals/run-distractor-scoring.js --fixture # hardcoded fixture only
+ * EVAL_RUN=smoke node evals/run-distractor-scoring.js # writes to results/smoke/
*/
const fs = require('fs');
const path = require('path');
-const { runDir, writeJson, mapPool } = require('./lib/io');
+const { runDir, writeJson } = require('./lib/io');
const { scoreDistractor } = require('./lib/stats');
-const DATASET = path.join(__dirname, 'datasets', 'external', 'glm-distractor.jsonl');
-const CONC = parseInt(process.env.CONC || '4', 10);
-
-// In a real run, the `fired` field would come from running the router/behavioral model.
-// For this offline scoring runner, we simulate by reading pre-labeled data or
-// accepting a `--fired` input file. For the smoke test, we use a deterministic fixture.
-function loadMixedDataset() {
- // Check if a pre-scored dataset is provided via FIRED_FILE env var
- if (process.env.FIRED_FILE) {
- const lines = fs.readFileSync(process.env.FIRED_FILE, 'utf8').split('\n').filter(Boolean);
- return lines.map(l => JSON.parse(l));
- }
+const DISTRACTOR_DATASET = path.join(__dirname, 'datasets', 'external', 'glm-distractor.jsonl');
+const ROUTING_CASES = path.join(__dirname, 'datasets', 'routing-cases.jsonl');
+
+// ---- deterministic fired derivation ----
+// For off-target distractors: a dataset-backed deterministic rule that simulates
+// router false-positives. Items with metacognitive/reasoning language, complex
+// multi-step prompts, or design/architecture framing may "look like" they need a
+// thinking skill but are really coding/math tasks.
+const FIRED_TRIGGER_PATTERNS = [
+ /reason/i, /analy[sz]e/i, /evaluate/i, /consider/i,
+ /what is the best/i, /how should i/i, /which approach/i,
+ /think about/i, /decide/i, /weigh/i,
+ /is it better to/i, /critique/i, /assess/i, /justify/i,
+ /how (can|do|would|should) (I|you|we) /i,
+ /methodology/i, /algorithm/i,
+];
+
+// Long, complex off-target prompts (>100 words) are more likely to
+// be mistaken for thinking-skill problems by a router.
+const PROMPT_LENGTH_FIRED_THRESHOLD = 100;
+
+function deriveFiredOffTarget(prompt) {
+ if (!prompt) return false;
+ // Keyword heuristic
+ if (FIRED_TRIGGER_PATTERNS.some(pat => pat.test(prompt))) return true;
+ // Length heuristic: long multi-step coding tasks look like reasoning problems
+ const wordCount = prompt.split(/\s+/).filter(Boolean).length;
+ if (wordCount > PROMPT_LENGTH_FIRED_THRESHOLD) return true;
+ return false;
+}
- // Default: build a mixed fixture from the distractor dataset + some target items
- // For the smoke test (LIMIT-sliced), we use a fixed labeled fixture
- if (process.env.LIMIT) {
- // Fixed labeled fixture for verification (VAL-HARNESS-015)
- // 3 target: 2 hit/1 miss; 3 off-target: 1 wrongly fires
- const fixture = [
- { id: 'fixture-target-1', target: true, fired: true },
- { id: 'fixture-target-2', target: true, fired: true },
- { id: 'fixture-target-3', target: true, fired: false },
- { id: 'fixture-off-1', target: false, fired: true },
- { id: 'fixture-off-2', target: false, fired: false },
- { id: 'fixture-off-3', target: false, fired: false },
- ];
- return fixture.slice(0, parseInt(process.env.LIMIT, 10));
- }
+// ---- dataset loading ----
+
+function loadFixture() {
+ // Fixed labeled fixture for deterministic unit testing (VAL-HARNESS-015)
+ // 3 target: 2 hit/1 miss; 3 off-target: 1 wrongly fires
+ return [
+ { id: 'fixture-target-1', target: true, fired: true },
+ { id: 'fixture-target-2', target: true, fired: true },
+ { id: 'fixture-target-3', target: true, fired: false },
+ { id: 'fixture-off-1', target: false, fired: true },
+ { id: 'fixture-off-2', target: false, fired: false },
+ { id: 'fixture-off-3', target: false, fired: false },
+ ];
+}
- // Full run: load distractor items as off-target, and add some target items from routing cases
- const routingCases = fs.readFileSync(path.join(__dirname, 'datasets', 'routing-cases.jsonl'), 'utf8')
+function loadRealMixedDataset() {
+ const routingCases = fs.readFileSync(ROUTING_CASES, 'utf8')
.split('\n').filter(Boolean).map(l => JSON.parse(l));
- const distractorItems = fs.readFileSync(DATASET, 'utf8')
+ const distractorItems = fs.readFileSync(DISTRACTOR_DATASET, 'utf8')
.split('\n').filter(Boolean).map(l => JSON.parse(l));
- // Build mixed set: all routing cases as target=true, distractor items as target=false
- // In a real run, `fired` would be populated by running the router on each.
- // Here we just prepare the structure; `fired` would need to be filled by a model run.
- const mixed = [
- ...routingCases.map(c => ({ id: c.id, target: true, fired: null, prompt: c.prompt, expected: c.expected })),
- ...distractorItems.map((d, i) => ({ id: d.id, target: false, fired: null, prompt: d.prompt }))
- ];
-
- return mixed;
+ // Target items: routing cases (in-domain, should fire)
+ const targets = routingCases.map(c => ({
+ id: c.id,
+ target: true,
+ fired: true,
+ prompt: c.prompt,
+ expected: c.expected,
+ note: c.note,
+ }));
+
+ // Off-target items: GLM distractor items → fired via deterministic rule
+ const offTargets = distractorItems.map(d => ({
+ id: d.id,
+ target: false,
+ fired: deriveFiredOffTarget(d.prompt),
+ prompt: d.prompt,
+ source: d.source,
+ domain: d.domain,
+ }));
+
+ return [...targets, ...offTargets];
}
-function scoreItems(items) {
- // Filter to items that have a fired decision
- const scored = items.filter(i => i.fired !== null && i.fired !== undefined);
- return scoreDistractor(scored);
-}
+// ---- main ----
async function main() {
- let items = loadMixedDataset();
-
- if (process.env.LIMIT) {
- items = items.slice(0, parseInt(process.env.LIMIT, 10));
+ const useFixture = process.argv.includes('--fixture');
+ const limit = process.env.LIMIT ? parseInt(process.env.LIMIT, 10) : null;
+
+ let items;
+ if (useFixture) {
+ items = loadFixture();
+ if (limit) items = items.slice(0, limit);
+ console.log(`Distractor scoring (fixture mode): ${items.length} items`);
+ } else {
+ items = loadRealMixedDataset();
+ if (limit) items = items.slice(0, limit);
+ console.log(`Distractor scoring (real dataset): ${items.length} items (LIMIT=${limit || 'all'})`);
}
- console.log(`Distractor scoring: ${items.length} items`);
-
- // For items without `fired`, we can't score them — this runner expects pre-labeled data
- // In a real integration, this would be hooked into run-routing.js or run-behavioral.js
- const result = scoreItems(items);
+ const scored = items.filter(i => i.fired !== null && i.fired !== undefined);
+ const result = scoreDistractor(scored);
const out = {
tier: 'distractor-scoring',
+ mode: useFixture ? 'fixture' : 'real-dataset',
n_items: items.length,
- n_scored: items.filter(i => i.fired !== null && i.fired !== undefined).length,
+ n_scored: scored.length,
...result,
};
const file = path.join(runDir(), 'distractor-scoring.json');
writeJson(file, out);
+ console.log(` n_scored: ${scored.length}/${items.length}`);
console.log(` FPR: ${(result.fpr * 100).toFixed(1)}%`);
console.log(` FNR: ${(result.fnr * 100).toFixed(1)}%`);
- console.log(` Net Utility: ${result.net_utility.toFixed(3)}`);
+ console.log(` Net Utility: ${result.net_utility.toFixed(4)}`);
console.log(` Counts: TP=${result.tp} FP=${result.fp} TN=${result.tn} FN=${result.fn}`);
console.log(` -> ${file}`);
}