23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
252 lines
12 KiB
JavaScript
252 lines
12 KiB
JavaScript
// Quality-gated auto-retrain for the cost-optimal router (ADR-149 iter 20).
|
|
//
|
|
// THE PROBLEM: iter 17-19 closed the production-data loop, but blindly
|
|
// retraining the bundled KRR off every JSONL row would degrade quality.
|
|
// Production data is noisy — judge variance, transient model regressions,
|
|
// outlier tasks. A naive nightly retrain ratchets quality DOWN over time
|
|
// when the corpus is contaminated.
|
|
//
|
|
// THE GATE: train a CANDIDATE KRR off the union (seed + production) and a
|
|
// BASELINE KRR off seed-only. Compare leave-one-out CV quality (looQuality).
|
|
// Only swap the bundled artifact if:
|
|
//
|
|
// 1. paired_count >= MIN_NEW_ROWS (don't retrain off 1 row of data), AND
|
|
// 2. candidate.looQuality >= baseline.looQuality + MARGIN
|
|
//
|
|
// Failure mode coverage:
|
|
// - 0 paired rows → "no production data" exit (success, no swap)
|
|
// - <MIN_NEW_ROWS paired → "below threshold" exit (success, no swap)
|
|
// - candidate < baseline → "regression detected" exit (success, no swap)
|
|
// - candidate ≈ baseline → "no improvement" exit (success, no swap)
|
|
// - candidate > baseline + margin → SWAP (with atomic rename + .bak)
|
|
//
|
|
// USAGE
|
|
// node scripts/auto-retrain-router.mjs --dry-run # always-no-swap, prints decision
|
|
// node scripts/auto-retrain-router.mjs # swap if gate passes
|
|
// node scripts/auto-retrain-router.mjs --margin 0.01 # tighter improvement bar
|
|
// node scripts/auto-retrain-router.mjs --min-new-rows 50 # require ≥50 production rows
|
|
// CLAUDE_FLOW_ROUTER_TRAJECTORY_PATH=... node scripts/auto-retrain-router.mjs
|
|
//
|
|
// Exits 0 on every gated outcome (no-swap is success). Exits 1 only on
|
|
// I/O errors. JSON report goes to stdout; the decision and reason are in
|
|
// the top-level `decision` and `reason` fields.
|
|
|
|
import { readFileSync, writeFileSync, copyFileSync, existsSync, mkdtempSync, renameSync, statSync, unlinkSync } from 'node:fs';
|
|
import { resolve, join, dirname } from 'node:path';
|
|
import { tmpdir } from 'node:os';
|
|
import * as mh from '@metaharness/router';
|
|
import { pairTrajectoryRows } from '../v3/@claude-flow/cli/dist/src/ruvector/router-trajectory.js';
|
|
import { IsotonicCalibrator } from '../v3/@claude-flow/cli/dist/src/ruvector/router-calibrator.js';
|
|
// iter 35 — single source of truth for prices.
|
|
import { blendedPrice } from '../v3/@claude-flow/cli/dist/src/ruvector/model-prices.js';
|
|
|
|
const ARGS = (() => {
|
|
const a = {
|
|
in: process.env.CLAUDE_FLOW_ROUTER_TRAJECTORY_PATH
|
|
?? resolve('.swarm', 'model-router-trajectories.jsonl'),
|
|
seedRows: resolve('v3/@claude-flow/cli/assets/model-router/seed-rows.json'),
|
|
artifact: resolve('v3/@claude-flow/cli/assets/model-router/seed-router.krr.json'),
|
|
calibratorPath: resolve('v3/@claude-flow/cli/assets/model-router/seed-router.calibrator.json'),
|
|
margin: 0.005, // 0.5 percentage points by default
|
|
minNewRows: 10,
|
|
dryRun: false,
|
|
filterSource: null, // optionally restrict to llm-judge etc.
|
|
skipCalibrator: false, // iter 27 — by default, refit calibrators on KRR swap
|
|
};
|
|
for (let i = 2; i < process.argv.length; i++) {
|
|
const v = process.argv[i];
|
|
if (v === '--in') a.in = process.argv[++i];
|
|
else if (v === '--seed-rows') a.seedRows = process.argv[++i];
|
|
else if (v === '--artifact') a.artifact = process.argv[++i];
|
|
else if (v === '--calibrator') a.calibratorPath = process.argv[++i];
|
|
else if (v === '--margin') a.margin = parseFloat(process.argv[++i]);
|
|
else if (v === '--min-new-rows') a.minNewRows = parseInt(process.argv[++i], 10);
|
|
else if (v === '--dry-run') a.dryRun = true;
|
|
else if (v === '--filter-source') a.filterSource = process.argv[++i];
|
|
else if (v === '--no-calibrator-update') a.skipCalibrator = true;
|
|
}
|
|
return a;
|
|
})();
|
|
|
|
const QUALITY_BAR = 0.25;
|
|
|
|
function emit(report) {
|
|
console.log(JSON.stringify(report, null, 2));
|
|
process.exit(report.decision === 'error' ? 1 : 0);
|
|
}
|
|
|
|
function trainKrr(rows, label) {
|
|
if (rows.length < 3) return { ok: false, reason: `${label}: only ${rows.length} rows (KRR needs ≥3 for LOO-CV)` };
|
|
const corpusModels = Object.keys(rows[0].scores);
|
|
const prices = Object.fromEntries(corpusModels.map(m => [m, blendedPrice(m)]));
|
|
const t0 = performance.now();
|
|
const { router, lambda, looQuality } = mh.trainRouter(rows, prices, {
|
|
qualityBar: QUALITY_BAR,
|
|
lambdas: [1e-4, 1e-3, 1e-2, 1e-1, 1e0],
|
|
});
|
|
return { ok: true, router, lambda, looQuality, trainMs: performance.now() - t0, rowCount: rows.length };
|
|
}
|
|
|
|
// --- 1. Read trajectory JSONL (gracefully handle missing file). ---
|
|
if (!existsSync(ARGS.in)) {
|
|
emit({
|
|
decision: 'no-data',
|
|
reason: `trajectory file not found at ${ARGS.in}; nothing to retrain on`,
|
|
swapped: false,
|
|
args: ARGS,
|
|
});
|
|
}
|
|
|
|
const trajLines = readFileSync(ARGS.in, 'utf8').split('\n').filter(l => l.trim().length > 0);
|
|
const trajRows = [];
|
|
let malformed = 0;
|
|
for (const l of trajLines) {
|
|
try { trajRows.push(JSON.parse(l)); } catch { malformed++; }
|
|
}
|
|
|
|
// --- 2. Pair + filter. ---
|
|
const { pairs: rawPairs, stats } = pairTrajectoryRows(trajRows);
|
|
let pairs = rawPairs;
|
|
if (ARGS.filterSource) pairs = pairs.filter(p => p.source === ARGS.filterSource);
|
|
const corpusRows = pairs.map(p => ({ task: p.task, embedding: p.embedding, scores: p.scores, tier: p.tier }));
|
|
|
|
if (corpusRows.length < ARGS.minNewRows) {
|
|
emit({
|
|
decision: 'below-threshold',
|
|
reason: `only ${corpusRows.length} paired production rows < min-new-rows=${ARGS.minNewRows}`,
|
|
swapped: false,
|
|
paired: corpusRows.length,
|
|
minNewRows: ARGS.minNewRows,
|
|
stats,
|
|
malformed,
|
|
args: ARGS,
|
|
});
|
|
}
|
|
|
|
// --- 3. Load seed corpus + union (production wins on task-text collision). ---
|
|
if (!existsSync(ARGS.seedRows)) {
|
|
emit({ decision: 'error', reason: `seed corpus not found at ${ARGS.seedRows}`, swapped: false, args: ARGS });
|
|
}
|
|
const seedRows = JSON.parse(readFileSync(ARGS.seedRows, 'utf8'));
|
|
const prodTasks = new Set(corpusRows.map(r => r.task));
|
|
const seedKept = seedRows.filter(r => !prodTasks.has(r.task));
|
|
const unionRows = [...seedKept, ...corpusRows];
|
|
|
|
// --- 4. Train baseline (seed-only) AND candidate (unioned). ---
|
|
const baseline = trainKrr(seedRows, 'baseline');
|
|
if (!baseline.ok) emit({ decision: 'error', reason: baseline.reason, swapped: false, args: ARGS });
|
|
|
|
const candidate = trainKrr(unionRows, 'candidate');
|
|
if (!candidate.ok) emit({ decision: 'error', reason: candidate.reason, swapped: false, args: ARGS });
|
|
|
|
// --- 5. Gate: candidate must beat baseline by MARGIN. ---
|
|
const improvement = candidate.looQuality - baseline.looQuality;
|
|
const passesGate = improvement >= ARGS.margin;
|
|
|
|
const report = {
|
|
decision: passesGate ? (ARGS.dryRun ? 'would-swap' : 'swap') : 'no-improvement',
|
|
reason: passesGate
|
|
? `candidate looQuality ${candidate.looQuality.toFixed(4)} beats baseline ${baseline.looQuality.toFixed(4)} by ${improvement.toFixed(4)} ≥ margin ${ARGS.margin}`
|
|
: `candidate looQuality ${candidate.looQuality.toFixed(4)} did not beat baseline ${baseline.looQuality.toFixed(4)} by margin ${ARGS.margin} (delta=${improvement.toFixed(4)})`,
|
|
swapped: false,
|
|
paired: corpusRows.length,
|
|
seedRows: seedRows.length,
|
|
unionRows: unionRows.length,
|
|
baseline: { lambda: baseline.lambda, looQuality: baseline.looQuality, trainMs: baseline.trainMs },
|
|
candidate: { lambda: candidate.lambda, looQuality: candidate.looQuality, trainMs: candidate.trainMs },
|
|
improvement,
|
|
margin: ARGS.margin,
|
|
stats,
|
|
malformed,
|
|
args: ARGS,
|
|
};
|
|
|
|
if (passesGate && !ARGS.dryRun) {
|
|
// --- 6. Atomic swap: write to tmp + backup old → rename. ---
|
|
if (!existsSync(ARGS.artifact)) {
|
|
emit({ ...report, decision: 'error', reason: `artifact path ${ARGS.artifact} does not exist; cannot back up before swap`, swapped: false });
|
|
}
|
|
const tmpDir = mkdtempSync(join(tmpdir(), 'router-retrain-'));
|
|
const tmpArtifact = join(tmpDir, 'seed-router.krr.json');
|
|
writeFileSync(tmpArtifact, JSON.stringify(candidate.router.toJSON()));
|
|
const backupPath = `${ARGS.artifact}.bak`;
|
|
try {
|
|
copyFileSync(ARGS.artifact, backupPath); // backup current
|
|
renameSync(tmpArtifact, ARGS.artifact); // atomic-ish replace
|
|
report.swapped = true;
|
|
report.backup = backupPath;
|
|
report.artifactBytes = statSync(ARGS.artifact).size;
|
|
} catch (err) {
|
|
// Restore on failure.
|
|
if (existsSync(backupPath)) {
|
|
try { copyFileSync(backupPath, ARGS.artifact); } catch { /* */ }
|
|
}
|
|
try { unlinkSync(tmpArtifact); } catch { /* */ }
|
|
emit({ ...report, decision: 'error', reason: `swap failed: ${err instanceof Error ? err.message : String(err)}`, swapped: false });
|
|
}
|
|
|
|
// --- 7. iter 27 — co-update the calibrator(s) on the NEW KRR. ---
|
|
// Without this, the bundled calibrators are fit against the OLD KRR's
|
|
// LOO predictions, so the moment KRR shifts, the calibrators become
|
|
// stale and over- or under-correct. Refit unified + per-tier in one pass.
|
|
if (!ARGS.skipCalibrator) {
|
|
try {
|
|
const corpusModels = Object.keys(unionRows[0].scores);
|
|
const prices = Object.fromEntries(corpusModels.map(m => [m, blendedPrice(m)]));
|
|
// LOO-CV against the union → collect (pred, obs, tier) pairs.
|
|
const t1 = performance.now();
|
|
const allPairs = [];
|
|
const pairsByTier = { cheap: [], mid: [], strong: [] };
|
|
for (let i = 0; i < unionRows.length; i++) {
|
|
const heldOut = unionRows[i];
|
|
const trainSet = unionRows.filter((_, j) => j !== i);
|
|
if (trainSet.length < 3) continue;
|
|
const { router } = mh.trainRouter(trainSet, prices, {
|
|
qualityBar: 0.25,
|
|
lambdas: [1e-4, 1e-3, 1e-2, 1e-1, 1e0],
|
|
});
|
|
for (const model of corpusModels) {
|
|
const pred = router.predict(model, heldOut.embedding);
|
|
const obs = heldOut.scores[model];
|
|
if (obs != null && Number.isFinite(pred)) {
|
|
allPairs.push([pred, obs]);
|
|
if (heldOut.tier && pairsByTier[heldOut.tier]) pairsByTier[heldOut.tier].push([pred, obs]);
|
|
}
|
|
}
|
|
}
|
|
const cvMs = performance.now() - t1;
|
|
// Fit unified + per-tier.
|
|
const calibratorsWritten = [];
|
|
const tierToBucket = { cheap: 'low', mid: 'med', strong: 'high' };
|
|
const fitOne = (pairs, outPath, label) => {
|
|
if (pairs.length < 3) return { ok: false, label, reason: `only ${pairs.length} pairs` };
|
|
const cal = IsotonicCalibrator.fit(pairs);
|
|
// Atomic write via tmp + rename.
|
|
const tmpCal = join(tmpDir, `cal-${label}.json`);
|
|
writeFileSync(tmpCal, JSON.stringify(cal.toJSON()));
|
|
if (existsSync(outPath)) copyFileSync(outPath, `${outPath}.bak`);
|
|
renameSync(tmpCal, outPath);
|
|
calibratorsWritten.push({ label, path: outPath, buckets: cal.bucketCount, pairs: pairs.length });
|
|
return { ok: true };
|
|
};
|
|
fitOne(allPairs, ARGS.calibratorPath, 'unified');
|
|
// Per-tier path: replace the final `.json` with `.{bucket}.json`. Works
|
|
// for both the bundled `seed-router.calibrator.json` → `…calibrator.low.json`
|
|
// AND for sandbox paths like `/tmp/x.json` → `/tmp/x.low.json`.
|
|
const perTierPath = (bucket) => ARGS.calibratorPath.replace(/\.json$/, `.${bucket}.json`);
|
|
for (const [tier, bucket] of Object.entries(tierToBucket)) {
|
|
fitOne(pairsByTier[tier], perTierPath(bucket), bucket);
|
|
}
|
|
report.calibrators = { swapped: true, cvMs: Math.round(cvMs), written: calibratorsWritten };
|
|
} catch (err) {
|
|
// Calibrator co-update is corrective, not load-bearing. If it fails,
|
|
// the KRR swap already succeeded — record but don't roll back.
|
|
report.calibrators = { swapped: false, error: err instanceof Error ? err.message : String(err) };
|
|
}
|
|
} else {
|
|
report.calibrators = { swapped: false, reason: 'skipped via --no-calibrator-update' };
|
|
}
|
|
}
|
|
|
|
emit(report);
|