|
| 1 | +import { mkdirSync } from 'node:fs'; |
| 2 | +import { dirname } from 'node:path'; |
| 3 | +import { Database } from '../../schema/database.js'; |
| 4 | +import { scoreRecord } from '../../scoring/confidence.js'; |
| 5 | +import type { RawRecord } from '../../adapters/adapter.js'; |
| 6 | + |
| 7 | +interface CalibrateOpts { |
| 8 | + db: string; |
| 9 | + since?: string; |
| 10 | + autoAccept?: string; |
| 11 | + review?: string; |
| 12 | + sweep?: boolean; |
| 13 | +} |
| 14 | + |
| 15 | +interface BucketStats { |
| 16 | + total: number; |
| 17 | + byAction: Record<string, number>; |
| 18 | + avgConfidence: number; |
| 19 | + examples: Array<{ content: string; score: number; action: string }>; |
| 20 | +} |
| 21 | + |
| 22 | +export function calibrate(opts: CalibrateOpts): void { |
| 23 | + mkdirSync(dirname(opts.db), { recursive: true }); |
| 24 | + const db = new Database(opts.db); |
| 25 | + |
| 26 | + try { |
| 27 | + const status = db.getStatus(); |
| 28 | + if (status.nodeCount === 0) { |
| 29 | + console.error('No nodes in graph. Ingest data first before calibrating.'); |
| 30 | + process.exit(1); |
| 31 | + } |
| 32 | + |
| 33 | + // Load all nodes as records for re-scoring |
| 34 | + const sinceMs = opts.since ? new Date(opts.since).getTime() : 0; |
| 35 | + const nodes = db.searchNodesByKeywords( |
| 36 | + [], |
| 37 | + 10000, |
| 38 | + undefined, |
| 39 | + sinceMs || undefined |
| 40 | + ); |
| 41 | + |
| 42 | + console.log(`Calibrating against ${nodes.length} nodes`); |
| 43 | + console.log('═'.repeat(50)); |
| 44 | + |
| 45 | + if (opts.sweep) { |
| 46 | + runThresholdSweep(nodes); |
| 47 | + } else { |
| 48 | + const autoAccept = opts.autoAccept ? parseFloat(opts.autoAccept) : 0.7; |
| 49 | + const reviewThreshold = opts.review ? parseFloat(opts.review) : 0.4; |
| 50 | + runCalibration(nodes, autoAccept, reviewThreshold); |
| 51 | + } |
| 52 | + } finally { |
| 53 | + db.close(); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +function nodeToRecord(node: { |
| 58 | + content: string; |
| 59 | + actor: string | null; |
| 60 | +}): RawRecord { |
| 61 | + return { |
| 62 | + external_id: 'calibration', |
| 63 | + content: node.content, |
| 64 | + raw_payload: JSON.stringify({ content: node.content }), |
| 65 | + actor: node.actor ?? undefined, |
| 66 | + }; |
| 67 | +} |
| 68 | + |
| 69 | +function runCalibration( |
| 70 | + nodes: Array<{ content: string; actor: string | null; confidence: number }>, |
| 71 | + autoAccept: number, |
| 72 | + reviewThreshold: number |
| 73 | +): void { |
| 74 | + const buckets: Record<string, BucketStats> = { |
| 75 | + auto_accept: { total: 0, byAction: {}, avgConfidence: 0, examples: [] }, |
| 76 | + review: { total: 0, byAction: {}, avgConfidence: 0, examples: [] }, |
| 77 | + discard: { total: 0, byAction: {}, avgConfidence: 0, examples: [] }, |
| 78 | + }; |
| 79 | + |
| 80 | + let confidenceSum = 0; |
| 81 | + let mismatchCount = 0; |
| 82 | + |
| 83 | + for (const node of nodes) { |
| 84 | + const record = nodeToRecord(node); |
| 85 | + const result = scoreRecord(record, undefined, { |
| 86 | + autoAccept, |
| 87 | + review: reviewThreshold, |
| 88 | + }); |
| 89 | + |
| 90 | + const bucket = buckets[result.action]!; |
| 91 | + bucket.total++; |
| 92 | + confidenceSum += result.score; |
| 93 | + |
| 94 | + // Track original confidence vs re-scored action |
| 95 | + // Nodes in the graph were auto-accepted, so any that now score as |
| 96 | + // 'review' or 'discard' are potential false positives |
| 97 | + if (result.action !== 'auto_accept') { |
| 98 | + mismatchCount++; |
| 99 | + } |
| 100 | + |
| 101 | + if (bucket.examples.length < 3) { |
| 102 | + bucket.examples.push({ |
| 103 | + content: node.content.slice(0, 80), |
| 104 | + score: result.score, |
| 105 | + action: result.action, |
| 106 | + }); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + const fpRate = nodes.length > 0 ? (mismatchCount / nodes.length) * 100 : 0; |
| 111 | + |
| 112 | + console.log( |
| 113 | + `\nThresholds: autoAccept=${autoAccept}, review=${reviewThreshold}` |
| 114 | + ); |
| 115 | + console.log('─'.repeat(50)); |
| 116 | + |
| 117 | + for (const [action, stats] of Object.entries(buckets)) { |
| 118 | + if (stats.total === 0) continue; |
| 119 | + const pct = ((stats.total / nodes.length) * 100).toFixed(1); |
| 120 | + console.log(`\n${action.toUpperCase()} — ${stats.total} nodes (${pct}%)`); |
| 121 | + for (const ex of stats.examples) { |
| 122 | + console.log(` ${ex.score.toFixed(2)} │ ${ex.content}`); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + console.log('\n' + '═'.repeat(50)); |
| 127 | + console.log( |
| 128 | + `FP rate (accepted nodes that would now be filtered): ${fpRate.toFixed(1)}%` |
| 129 | + ); |
| 130 | + if (fpRate > 10) { |
| 131 | + console.log( |
| 132 | + `⚠ FP rate exceeds 10% target — consider lowering autoAccept threshold` |
| 133 | + ); |
| 134 | + } else { |
| 135 | + console.log(`✓ FP rate within 10% target`); |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +function runThresholdSweep( |
| 140 | + nodes: Array<{ content: string; actor: string | null; confidence: number }> |
| 141 | +): void { |
| 142 | + console.log('\nThreshold sweep (autoAccept / review → FP%)'); |
| 143 | + console.log('─'.repeat(50)); |
| 144 | + console.log('autoAccept │ review │ accept% │ review% │ discard% │ FP%'); |
| 145 | + console.log('───────────┼────────┼─────────┼─────────┼──────────┼─────'); |
| 146 | + |
| 147 | + const thresholds = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8]; |
| 148 | + const reviewThresholds = [0.2, 0.3, 0.4]; |
| 149 | + |
| 150 | + for (const autoAccept of thresholds) { |
| 151 | + for (const review of reviewThresholds) { |
| 152 | + if (review >= autoAccept) continue; |
| 153 | + |
| 154 | + let accepted = 0; |
| 155 | + let reviewed = 0; |
| 156 | + let discarded = 0; |
| 157 | + |
| 158 | + for (const node of nodes) { |
| 159 | + const record = nodeToRecord(node); |
| 160 | + const result = scoreRecord(record, undefined, { autoAccept, review }); |
| 161 | + if (result.action === 'auto_accept') accepted++; |
| 162 | + else if (result.action === 'review') reviewed++; |
| 163 | + else discarded++; |
| 164 | + } |
| 165 | + |
| 166 | + const total = nodes.length; |
| 167 | + const fpRate = |
| 168 | + total > 0 ? (((reviewed + discarded) / total) * 100).toFixed(1) : '0.0'; |
| 169 | + const acceptPct = |
| 170 | + total > 0 ? ((accepted / total) * 100).toFixed(1) : '0.0'; |
| 171 | + const reviewPct = |
| 172 | + total > 0 ? ((reviewed / total) * 100).toFixed(1) : '0.0'; |
| 173 | + const discardPct = |
| 174 | + total > 0 ? ((discarded / total) * 100).toFixed(1) : '0.0'; |
| 175 | + |
| 176 | + const marker = parseFloat(fpRate) <= 10 ? ' ✓' : ''; |
| 177 | + console.log( |
| 178 | + ` ${autoAccept.toFixed(1)} │ ${review.toFixed(1)} │ ${acceptPct.padStart(5)} │ ${reviewPct.padStart(5)} │ ${discardPct.padStart(5)} │ ${fpRate.padStart(5)}${marker}` |
| 179 | + ); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + console.log('\n✓ = FP rate ≤ 10% target'); |
| 184 | +} |
0 commit comments