#!/usr/bin/env node /** Offline scorer. No network, providers, or model generation. */ import fs from 'node:fs'; import {fileURLToPath} from 'node:url'; import {resolve,dirname} from 'node:path'; import {execFileSync} from 'node:child_process'; import assert from 'node:assert/strict'; import {isValidModelAnswer,matchesAcceptedAnswer,stripResponseWrapperResidue} from './answer-normalization.mjs'; import {taskMatch} from './typed-normalization.mjs'; const root=resolve(dirname(fileURLToPath(import.meta.url)),'..'); const args=process.argv.slice(2); const opt=(name,fallback)=>{const i=args.indexOf(name);return i<0?fallback:args[i+1];}; const input=opt('--predictions',resolve(root,'results/predictions.jsonl')); const questionFile=opt('--questions',resolve(root,'data/questions.jsonl')); const output=opt('--output',null),report=opt('--report',null),db=opt('--live-database',null); const scorer=opt('--scorer','reference'); assert(['reference','typed'].includes(scorer),'Choose --scorer reference or typed'); const readLines=p=>fs.readFileSync(p,'utf8').split('\n').filter(l=>l.trim()).map(l=>JSON.parse(l)); const release=readLines(questionFile); let authoritative=release; if(db){ assert(fs.statSync(db).size>0); assert.equal(fs.readFileSync(db).subarray(0,16).toString(),'SQLite format 3\0'); const sql=s=>JSON.parse(execFileSync('sqlite3',['-readonly','-json',db,s],{encoding:'utf8',maxBuffer:30e6})); assert.equal(sql("SELECT name FROM sqlite_master WHERE type='table' AND name='questions'").length,1); const rows=sql("SELECT * FROM questions WHERE status IN ('Final','Approved')"); const byId=new Map(rows.map(q=>[q.id,q]));assert.equal(rows.length,release.length); authoritative=release.map(r=>{ const q=byId.get(r.question_id);assert(q,'Release question absent from live database'); assert.equal(r.question,q.full_question,'Release text differs from live editor'); assert.deepEqual(r.answers,JSON.parse(q.answers),'Release references differ from live editor'); return {...r,question:q.full_question,modality:q.modality,answers:JSON.parse(q.answers), answer_format:q.answer_format,answer_quantity:q.answer_quantity}; }); } const byId=new Map(authoritative.flatMap(q=>[[q.id,q],[q.question_id,q]])); const seen=new Set(),rows=[];let disagreements=0; for(const p of readLines(input)){ const q=byId.get(p.question_id??p.id);assert(q,'Prediction does not identify a question in this release'); if(p.question!==undefined)assert.equal(p.question,q.question,`Question text differs: ${q.question_id} — ${q.question}`); const key=[p.collection??'evaluation',p.model??'unspecified',p.representation??'unspecified',q.question_id].join('\t'); assert(!seen.has(key),`Duplicate prediction: ${q.question_id} — ${q.question}`);seen.add(key); const answer=p.answer===null||p.answer===undefined?null:stripResponseWrapperResidue(p.answer); const valid=answer!==null&&isValidModelAnswer(answer); const references=q.answers.filter(a=>typeof a==='string'&&a.trim()); const context={...q,full_question:q.question}; const referenceCorrect=valid&&references.some(a=>matchesAcceptedAnswer(answer,a,{fullQuestion:q.question})); const typedCorrect=valid&&references.some(a=>taskMatch(answer,a,context)); disagreements+=+(referenceCorrect!==typedCorrect); rows.push({...p,id:q.id,question_id:q.question_id,question:q.question,modality:q.modality, accepted_answers:q.answers,answer,correct:scorer==='typed'?typedCorrect:referenceCorrect,missing:answer===null}); } if(output)fs.writeFileSync(output,rows.map(r=>JSON.stringify(r)).join('\n')+'\n'); if(report){ const esc=s=>String(s??'(missing response)').replaceAll('|','\\|').replaceAll('\n','
'); const groups=new Map();for(const r of rows){const k=[r.collection,r.model,r.representation].join(' · ');if(!groups.has(k))groups.set(k,[]);groups.get(k).push(r);} const parts=[`# Scored answers (${scorer})`,'','Denominators count supplied prediction rows, including explicit null answers. Include a null row for every missing expected prediction; omitted rows are not silently imputed. New model cost: $0.','']; for(const [label,rs] of groups){parts.push(`## ${label}`,'','| Question ID | Question | Modality | Correct answer | Model answer | Correct |','|---|---|---|---|---|---|',...rs.map(r=>'| '+[r.question_id,r.question,r.modality,r.accepted_answers.filter(Boolean).join(' OR '),r.answer,r.correct?'✅':'❌'].map(esc).join(' | ')+' |'),'');} fs.writeFileSync(report,parts.join('\n')+'\n'); } console.log(JSON.stringify({scorer,provided_prediction_slots:rows.length,available:rows.filter(r=>!r.missing).length, missing:rows.filter(r=>r.missing).length,correct:rows.filter(r=>r.correct).length, ...(args.includes('--compare-typed')?{reference_vs_typed_disagreements:disagreements}:{}),new_model_calls:0,new_cost_usd:0},null,2)); if(args.includes('--compare-typed'))assert.equal(disagreements,0,'The two scorers differ; inspect changed judgments before using shared tables');