/** * FULL RUN (2026-09-30) - shared library. Imports the pilot's lib-common / lib-prompt read-only and * does NOT change any pilot file. What it adds: * - the fourth test (Multiple Intelligences, 40 items, same 5-option scale) registered into the imported * TESTS object at runtime (the pilot's own scripts never see it: they run in their own processes); * - the 16-row model table (13 API rows: Bedrock + Vertex; 3 subscription rows: claude -p / codex exec); * - its own ledger + responses (runs-full/), its own caps, both STOP files, heartbeat status.json; * - the gate on the IQ rerun's live 47-probe-run processes (read-only process listing, nothing else). * Spend = logged tokens x list price x 1.15. Not an invoice (no billing access). */ import fs from 'fs' import path from 'path' import { execFileSync } from 'child_process' import os from 'os' import { pathToFileURL } from 'url' import { TESTS, VAULT, BUNDLE, HF_DIR, SCRATCH as PILOT_SCRATCH, RUNS as PILOT_RUNS, sha256File } from './lib-common.mjs' // ---------------------------------------------------------------- the fourth test TESTS.multiple_intelligences = { slug: 'multiple-intelligences', pack: 'en.test.multiple-intelligences.json', key: 'multiple_intelligences', csv: 'multiple_intelligences.csv', scales: ['bodily', 'interpersonal', 'intrapersonal', 'linguistic', 'logical', 'musical', 'naturalist', 'spatial'], nItems: 40, } export const TEST_IDS_FULL = ['big_five', 'riasec', 'dark_triad', 'multiple_intelligences'] export const PILOT_TESTS = ['big_five', 'riasec', 'dark_triad'] // ---------------------------------------------------------------- paths export const FULL_SCRATCH = path.join(process.env.PROTOCOL_SCRATCH || os.tmpdir(), 'full-2026-09-30') fs.mkdirSync(FULL_SCRATCH, { recursive: true }) export const RUNS_FULL = path.join(VAULT, 'runs-full') fs.mkdirSync(RUNS_FULL, { recursive: true }) export const LEDGER = path.join(RUNS_FULL, 'ledger.jsonl') export const RESPONSES = path.join(RUNS_FULL, 'responses.jsonl') export const PILOT_RESPONSES = path.join(PILOT_RUNS, 'responses.jsonl') // read only export const PILOT_LEDGER = path.join(PILOT_RUNS, 'ledger.jsonl') // read only export const STOP_FILES = [path.join(PILOT_SCRATCH, 'STOP'), path.join(FULL_SCRATCH, 'STOP')] // read, never created here export const STATUS_FILE = path.join(FULL_SCRATCH, 'status.json') export const DRYRUN_FILE = path.join(VAULT, 'full-dryrun.json') // ---------------------------------------------------------------- money guards export const PRICE_MARGIN = 1.15 export const HARD_CAP_USD = 30.0 // hard cap of 30 USD for the whole full run export const STOP_AT_USD = 28.0 // stop at 28 USD export const MAX_CALL_USD = 0.25 // single-call guard: one call above this stops that model (largest possible by design: gemini battery retry at 16,000 output tokens = 0.19) export const FAIL_STREAK = 25 // as lib-run.mjs // ---------------------------------------------------------------- models // arm: bedrock | vertex | claude-cli | codex-cli. pin/pout = USD per 1M tokens (list; same table as the IQ rerun transport). // pilot: its three pilot tests are reused from the pilot's responses.jsonl. iqGate: wait while a 47-probe-run for it is alive. export const MODELS = { 'claude-haiku-4.5': { arm: 'bedrock', id: 'global.anthropic.claude-haiku-4-5-20251001-v1:0', pin: 1.0, pout: 5.0, reasoning: false, vendor: 'Anthropic', iqGate: true }, 'gpt-oss-120b': { arm: 'bedrock', id: 'openai.gpt-oss-120b-1:0', pin: 0.15, pout: 0.6, reasoning: true, vendor: 'OpenAI', pilot: true }, 'gemma-3-27b': { arm: 'bedrock', id: 'google.gemma-3-27b-it', pin: 0.23, pout: 0.38, reasoning: false, vendor: 'Google' }, 'llama-4-maverick': { arm: 'bedrock', id: 'us.meta.llama4-maverick-17b-instruct-v1:0', pin: 0.24, pout: 0.97, reasoning: false, vendor: 'Meta', pilot: true, iqGate: true }, 'deepseek-v3.2': { arm: 'bedrock', id: 'deepseek.v3.2', pin: 0.62, pout: 1.85, reasoning: false, vendor: 'DeepSeek' }, 'mistral-large-3': { arm: 'bedrock', id: 'mistral.mistral-large-3-675b-instruct', pin: 0.5, pout: 1.5, reasoning: false, vendor: 'Mistral', pilot: true }, 'qwen3-32b': { arm: 'bedrock', id: 'qwen.qwen3-32b-v1:0', pin: 0.15, pout: 0.6, reasoning: false, vendor: 'Alibaba' }, 'nova-pro': { arm: 'bedrock', id: 'us.amazon.nova-pro-v1:0', pin: 0.8, pout: 3.2, reasoning: false, vendor: 'Amazon', iqGate: true }, 'glm-5': { arm: 'bedrock', id: 'zai.glm-5', pin: 1.0, pout: 3.2, reasoning: false, vendor: 'Zhipu' }, 'kimi-k2.5': { arm: 'bedrock', id: 'moonshotai.kimi-k2.5', pin: 0.6, pout: 3.0, reasoning: false, vendor: 'Moonshot' }, 'qwen3-235b': { arm: 'bedrock', id: 'qwen.qwen3-vl-235b-a22b', pin: 0.53, pout: 2.66, reasoning: false, vendor: 'Alibaba' }, 'deepseek-r1': { arm: 'bedrock', id: 'us.deepseek.r1-v1:0', pin: 1.35, pout: 5.4, reasoning: true, vendor: 'DeepSeek', iqGate: true, gapMs: 31000 }, 'gemini-2.5-pro': { arm: 'vertex', id: 'gemini-2.5-pro', pin: 1.25, pout: 10.0, reasoning: true, vendor: 'Google' }, 'claude-opus-5.5': { arm: 'claude-cli', id: 'claude-opus-5-5', pin: 0, pout: 0, reasoning: true, vendor: 'Anthropic', cli: true }, 'claude-fable-5.1': { arm: 'claude-cli', id: 'claude-fable-5-1', pin: 0, pout: 0, reasoning: true, vendor: 'Anthropic', cli: true }, 'gpt-6-astra': { arm: 'codex-cli', id: 'gpt-6-astra', pin: 0, pout: 0, reasoning: true, vendor: 'OpenAI', cli: true }, } export const API_ROWS = Object.keys(MODELS).filter((m) => !MODELS[m].cli) export const CLI_ROWS = Object.keys(MODELS).filter((m) => MODELS[m].cli) // ---------------------------------------------------------------- conditions (identical to the pilot) export const ALL_CONDS = ['S0', 'B0', 'BS1', 'BS2', 'BS3', 'BS4', 'SR', 'S0r', 'B0r', 'ST1', 'SP'] export const keyOf = (t) => `${t.model}|${t.cond}|${t.test}|${t.unit}|${t.rep}` // ---------------------------------------------------------------- spend state (rebuilt from the ledger, so every process sees the others) export const spend = { global: 0, byModel: {}, calls: 0, byModelCalls: {}, at: 0 } export function refreshSpend() { const s = { global: 0, byModel: {}, calls: 0, byModelCalls: {}, at: Date.now() } if (fs.existsSync(LEDGER)) { for (const line of fs.readFileSync(LEDGER, 'utf8').split('\n')) { if (!line.trim()) continue try { const r = JSON.parse(line) s.global += r.costUsd || 0 s.byModel[r.model] = (s.byModel[r.model] || 0) + (r.costUsd || 0) s.calls++ s.byModelCalls[r.model] = (s.byModelCalls[r.model] || 0) + 1 } catch {} } } Object.assign(spend, s) } refreshSpend() let caps = null export function modelCap(model) { if (!caps) { caps = {} if (fs.existsSync(DRYRUN_FILE)) { const d = JSON.parse(fs.readFileSync(DRYRUN_FILE, 'utf8')); for (const r of d.rows) caps[r.model] = r.capUsd } } return caps[model] ?? 0.5 } export class CapHit extends Error {} export class ModelStop extends Error {} // stops one model only (per-model cap, single-call cost, failure streak) export const stopFileHit = () => STOP_FILES.find((f) => fs.existsSync(f)) || null let guardChecks = 0 export function checkGuards(model) { if (++guardChecks % 25 === 0 || Date.now() - spend.at > 30000) refreshSpend() const sf = stopFileHit() if (sf) throw new CapHit(`STOP file present (${sf})`) if (spend.global >= STOP_AT_USD) throw new CapHit(`global stop ${STOP_AT_USD} USD reached (${spend.global.toFixed(4)})`) if (!MODELS[model].cli && (spend.byModel[model] || 0) >= modelCap(model)) throw new ModelStop(`per-model cap ${modelCap(model)} USD reached for ${model} (${(spend.byModel[model] || 0).toFixed(4)})`) } export function costOf(model, inTok, outTok) { const m = MODELS[model] return ((inTok * m.pin + outTok * m.pout) / 1e6) * PRICE_MARGIN } export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) // ---------------------------------------------------------------- transports // The Bedrock request signer is not part of this bundle (it lives in the product repo). Point PROTOCOL_BEDROCK_HELPER at a module // that exports resolveAwsCredentials({ profile, home }) and signRequest({ method, host, path, region, body, creds, now }); AWS SigV4. // Loaded on first use only, so the analysis scripts (11, 12) do not need it. const bedrockHelper = async () => { if (!process.env.PROTOCOL_BEDROCK_HELPER) throw new Error('set PROTOCOL_BEDROCK_HELPER to a SigV4 helper module (see README); not needed for the analysis scripts') return import(pathToFileURL(path.resolve(process.env.PROTOCOL_BEDROCK_HELPER)).href) } let creds = null const encodeOnce = (p) => p.split('/').map((s) => encodeURIComponent(s)).join('/') export const REGION = process.env.PROTOCOL_REGION || 'us-east-1' async function bedrockOnce(model, system, user, { maxTokens, temperature, timeoutMs = 240000 }) { const { resolveAwsCredentials, signRequest } = await bedrockHelper() creds ??= resolveAwsCredentials({ profile: process.env.PROTOCOL_AWS_PROFILE || 'default', home: process.env.USERPROFILE || process.env.HOME }) const host = `bedrock-runtime.${REGION}.amazonaws.com` const p = `/model/${MODELS[model].id}/converse` const body = JSON.stringify({ messages: [{ role: 'user', content: [{ text: user }] }], ...(system ? { system: [{ text: system }] } : {}), inferenceConfig: { maxTokens, temperature }, }) const headers = signRequest({ method: 'POST', host, path: p, region: REGION, body, creds, now: new Date() }) const ctrl = new AbortController() const timer = setTimeout(() => ctrl.abort(), timeoutMs) const t0 = Date.now() try { const res = await fetch(`https://${host}${encodeOnce(p)}`, { method: 'POST', headers, body, signal: ctrl.signal }) const raw = await res.text() let j = null try { j = JSON.parse(raw) } catch {} if (!res.ok) { const retryable = res.status === 429 || res.status >= 500 || /Throttl/i.test(String(j?.__type || j?.message || '')) return { ok: false, status: res.status, reason: String(j?.message || raw).slice(0, 200), retryable, ms: Date.now() - t0, inTok: 0, outTok: 0 } } const blocks = j?.output?.message?.content || [] const text = blocks.map((b) => b.text || '').join('').trim() const reasoning = blocks.map((b) => b.reasoningContent?.reasoningText?.text || '').join('').trim() return { ok: true, text, reasoningChars: reasoning.length, stopReason: j?.stopReason || null, inTok: j?.usage?.inputTokens ?? 0, outTok: j?.usage?.outputTokens ?? 0, ms: Date.now() - t0, } } catch (e) { return { ok: false, status: 0, reason: e?.name === 'AbortError' ? 'timeout' : e.message, retryable: true, ms: Date.now() - t0, inTok: 0, outTok: 0 } } finally { clearTimeout(timer) } } // Vertex only: the shared endpoint must never fall back to AI Studio (brief). Env is set before the import. let gem = null async function gemini() { if (gem) return gem delete process.env.GEMINI_API_KEY // GCP_SERVICE_ACCOUNT_KEY_FILE and GCP_PROJECT_ID must be set by the caller (Vertex AI service account). process.env.GCP_VERTEX_LOCATION ||= 'us-central1' if (!process.env.PROTOCOL_GEMINI_HELPER) throw new Error('set PROTOCOL_GEMINI_HELPER to a Vertex Gemini endpoint module (see README)') gem = await import(pathToFileURL(path.resolve(process.env.PROTOCOL_GEMINI_HELPER)).href) if (gem.geminiTransport() !== 'vertex') throw new Error(`gemini transport is ${gem.geminiTransport()}, refusing (Vertex only)`) return gem } async function vertexOnce(model, system, user, { maxTokens, temperature, timeoutMs = 240000 }) { const g = await gemini() const body = { contents: [{ role: 'user', parts: [{ text: user }] }], generationConfig: { temperature, maxOutputTokens: maxTokens }, // thinking tokens count INSIDE this ceiling on 2.5 Pro ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}), } const t0 = Date.now() let res try { res = await g.geminiFetch(MODELS[model].id, body, { timeoutMs }) } catch (e) { if (/Vertex (401|403|404)|token exchange|GCP_SERVICE_ACCOUNT_KEY/.test(e.message)) return { ok: false, status: 0, reason: e.message.slice(0, 200), retryable: false, fatal: true, ms: Date.now() - t0, inTok: 0, outTok: 0 } return { ok: false, status: 0, reason: `network: ${e.message}`.slice(0, 200), retryable: true, ms: Date.now() - t0, inTok: 0, outTok: 0 } } const raw = await res.text() if (!res.ok) return { ok: false, status: res.status, reason: raw.slice(0, 200), retryable: [408, 429, 500, 502, 503, 504].includes(res.status), ms: Date.now() - t0, inTok: 0, outTok: 0 } let d try { d = JSON.parse(raw) } catch { return { ok: false, status: res.status, reason: `unparseable: ${raw.slice(0, 120)}`, retryable: true, ms: Date.now() - t0, inTok: 0, outTok: 0 } } const um = d.usageMetadata || {} const inTok = um.promptTokenCount ?? 0 const outTok = (um.candidatesTokenCount ?? 0) + (um.thoughtsTokenCount ?? 0) if (d.promptFeedback?.blockReason) return { ok: false, status: res.status, reason: `prompt blocked: ${d.promptFeedback.blockReason}`, retryable: false, ms: Date.now() - t0, inTok, outTok } const cand = d.candidates?.[0] const text = (cand?.content?.parts || []).filter((p) => !p.thought).map((p) => p.text || '').join('').trim() const fr = cand?.finishReason ?? null // normalised so the pilot's "empty + max_tokens -> one retry at 2x" rule applies unchanged return { ok: true, text, stopReason: fr === 'MAX_TOKENS' ? 'max_tokens' : fr, rawStop: fr, thoughts: um.thoughtsTokenCount ?? 0, inTok, outTok, ms: Date.now() - t0 } } // pacing (deepseek-r1: 2 requests per minute account quota, shared with the IQ run - hence the gate) const nextStart = new Map() async function pace(model) { const gap = MODELS[model].gapMs if (!gap) return const now = Date.now() const t = Math.max(now, nextStart.get(model) || 0) nextStart.set(model, t + gap) if (t > now) await sleep(t - now) } const failStreak = {} /** Guarded API call, jittered retry, one ledger line per attempt written BEFORE the caller sees the result. */ export async function callApi(model, system, user, meta, { maxTokens, temperature, attempts = 12 }) { const m = MODELS[model] let last for (let a = 1; a <= attempts; a++) { checkGuards(model) await pace(model) const r = m.arm === 'vertex' ? await vertexOnce(model, system, user, { maxTokens, temperature }) : await bedrockOnce(model, system, user, { maxTokens, temperature }) const costUsd = costOf(model, r.inTok || 0, r.outTok || 0) spend.global += costUsd spend.byModel[model] = (spend.byModel[model] || 0) + costUsd spend.calls++ spend.byModelCalls[model] = (spend.byModelCalls[model] || 0) + 1 fs.appendFileSync(LEDGER, JSON.stringify({ t: new Date().toISOString(), model, arm: m.arm, region: m.arm === 'bedrock' ? REGION : undefined, ...meta, attempt: a, temperature, maxTokens, ok: r.ok, status: r.status ?? 200, stopReason: r.rawStop ?? r.stopReason ?? null, inTok: r.inTok || 0, outTok: r.outTok || 0, thoughts: r.thoughts, ms: r.ms, costUsd: +costUsd.toFixed(8), reason: r.ok ? undefined : r.reason, }) + '\n') last = r if (costUsd > MAX_CALL_USD) throw new ModelStop(`single call cost ${costUsd.toFixed(4)} USD > ${MAX_CALL_USD} for ${model}`) if (r.fatal) throw new ModelStop(`fatal transport error for ${model}: ${r.reason}`) if (r.ok) { failStreak[model] = 0; return r } failStreak[model] = (failStreak[model] || 0) + 1 if (failStreak[model] >= FAIL_STREAK) throw new ModelStop(`failure streak >= ${FAIL_STREAK} for ${model}: ${r.reason}`) if (!r.retryable) return r await sleep(Math.min(45000, 500 * 2 ** a) * (0.5 + Math.random())) } return last } // ---------------------------------------------------------------- responses (new file + pilot file read-only) export function appendResponse(rec) { fs.appendFileSync(RESPONSES, JSON.stringify(rec) + '\n') } function readJsonl(f) { const out = [] if (!fs.existsSync(f)) return out for (const line of fs.readFileSync(f, 'utf8').split('\n')) { if (!line.trim()) continue; try { out.push(JSON.parse(line)) } catch {} } return out } /** key -> record. Pilot records first (source 'pilot'), then this run's (source 'full') - a full-run record for the same key wins. */ export function loadDone({ includePilot = true } = {}) { const done = new Map() if (includePilot) for (const r of readJsonl(PILOT_RESPONSES)) if (r.ok !== false) done.set(r.key, { ...r, source: 'pilot' }) for (const r of readJsonl(RESPONSES)) if (r.ok !== false) done.set(r.key, { ...r, source: 'full' }) return done } export { readJsonl } // ---------------------------------------------------------------- task list (identical construction to 02-run-models.mjs) export function taskList(model, tests, conds = ALL_CONDS, items) { const tasks = [] const single = (cond, sys, opts) => { for (const test of tests) items[test].forEach((it, i) => { for (let rep = 0; rep < (opts.reps || 1); rep++) tasks.push({ kind: 'single', model, cond, test, unit: i, rep, sys, ...opts }) }) } const battery = (cond, seed, rep = 0) => { for (const test of tests) tasks.push({ kind: 'battery', model, cond, test, unit: 'B', rep, seed }) } for (const c of conds) { if (c === 'S0') single('S0', 'P1', { temp: 0, reversed: false }) else if (c === 'S0r') single('S0r', 'P1', { temp: 0, reversed: false }) else if (c === 'SR') single('SR', 'P1', { temp: 0, reversed: true }) else if (c === 'SP') single('SP', 'P2', { temp: 0, reversed: false }) else if (c === 'ST1') single('ST1', 'P1', { temp: 1.0, reversed: false, reps: 3 }) else if (c === 'B0') battery('B0', 0) else if (c === 'B0r') battery('B0r', 0, 1) else if (/^BS\d$/.test(c)) battery(c, Number(c.slice(2))) else throw new Error(`unknown cond ${c}`) } return tasks } // Pilot models: every task is built for all four tests, then filtered by loadDone(), which includes the pilot's // responses - so only MI (plus any pilot cell that is genuinely missing) is asked again. // ---------------------------------------------------------------- IQ-rerun gate (read-only process listing) /** Set of model names that have a live 47-probe-run process right now. Throws if the listing itself fails. */ export function iqRunnersAlive() { const ps = "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object { $_.CommandLine -match '47-probe-run' } | ForEach-Object { $_.CommandLine }" const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', ps], { encoding: 'utf8', windowsHide: true, timeout: 60000 }) const alive = new Set() for (const line of out.split(/\r?\n/)) { const m = line.match(/--models\s+([^\s]+)/) if (m) for (const name of m[1].split(',')) alive.add(name.trim()) } return alive } // ---------------------------------------------------------------- runner state + heartbeat const RUNNER_DIR = path.join(FULL_SCRATCH, 'runners') fs.mkdirSync(RUNNER_DIR, { recursive: true }) export function setRunnerState(tag, state) { const f = path.join(RUNNER_DIR, `${tag}.json`) const prev = fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : {} fs.writeFileSync(f + '.tmp', JSON.stringify({ ...prev, ...state, pid: process.pid, at: new Date().toISOString() }, null, 1)) fs.renameSync(f + '.tmp', f) } /** Planned totals per model x condition (what "done/total" in status.json counts against). */ export function plannedTotals(itemsByTest) { const out = {} for (const model of Object.keys(MODELS)) { const tasks = taskList(model, TEST_IDS_FULL, ALL_CONDS, itemsByTest) const c = {} for (const t of tasks) c[t.cond] = (c[t.cond] || 0) + 1 out[model] = c } return out } export function writeStatus(itemsByTest, extra = {}) { refreshSpend() const done = loadDone() const planned = plannedTotals(itemsByTest) const models = {} for (const [model, byCond] of Object.entries(planned)) { const conds = {} for (const [cond, total] of Object.entries(byCond)) conds[cond] = { done: 0, total } models[model] = { done: 0, total: Object.values(byCond).reduce((a, b) => a + b, 0), fromPilot: 0, spendUsd: +(spend.byModel[model] || 0).toFixed(4), capUsd: MODELS[model].cli ? null : modelCap(model), calls: spend.byModelCalls[model] || 0, lastError: null, conds } } for (const r of done.values()) { const m = models[r.model] if (!m || !m.conds[r.cond]) continue if (!TEST_IDS_FULL.includes(r.test)) continue m.conds[r.cond].done++ m.done++ if (r.source === 'pilot') m.fromPilot++ } // last error per model = last non-ok ledger line if (fs.existsSync(LEDGER)) { for (const line of fs.readFileSync(LEDGER, 'utf8').split('\n')) { if (!line.includes('"ok":false')) continue try { const r = JSON.parse(line); if (models[r.model]) models[r.model].lastError = { t: r.t, status: r.status, reason: String(r.reason || '').slice(0, 160) } } catch {} } } const runners = {} for (const f of fs.readdirSync(RUNNER_DIR)) if (f.endsWith('.json')) { try { runners[f.slice(0, -5)] = JSON.parse(fs.readFileSync(path.join(RUNNER_DIR, f), 'utf8')) } catch {} } const st = { updatedAt: new Date().toISOString(), by: process.pid, spend: { loggedUsd: +spend.global.toFixed(4), note: 'tokens x list price x 1.15', stopAtUsd: STOP_AT_USD, hardCapUsd: HARD_CAP_USD, ledgerLines: spend.calls }, stopFile: stopFileHit(), runners, models, ...extra, } fs.writeFileSync(STATUS_FILE + '.' + process.pid + '.tmp', JSON.stringify(st, null, 1)) try { fs.renameSync(STATUS_FILE + '.' + process.pid + '.tmp', STATUS_FILE) } catch { try { fs.unlinkSync(STATUS_FILE + '.' + process.pid + '.tmp') } catch {} } return st } export function startHeartbeat(itemsByTest) { const tick = () => { try { writeStatus(itemsByTest) } catch (e) { console.error('heartbeat failed:', e.message) } } tick() const h = setInterval(tick, 60000) h.unref() return h } // ---------------------------------------------------------------- provenance (full run: adds the MI files) export function provenanceFull() { const files = ['scoring-key.csv', 'scripts/score-from-key.mjs'] return { sha256: Object.fromEntries(files.map((f) => [f, sha256File(path.join(BUNDLE, f)).slice(0, 16)])), humanCsv: Object.fromEntries(TEST_IDS_FULL.map((t) => [TESTS[t].csv, sha256File(path.join(HF_DIR, TESTS[t].csv)).slice(0, 16)])), hfCommit: 'a39a58649a58202a02bb7eaf826609c2fe8bca84', } }