// Inspection knowledge agent: one persistent memory per PCBA type, built from operator feedback. // The inspector station records spoken (or typed) feedback about an inspection result; this // agent folds it into that board type's notes -- approved alternates, DNP parts, revision // differences, what to ignore, what to look harder at -- and every later inspection of that // board type gets the notes in its prompt. Runs inside the loader server (always up, supervised); // work is queued per board so updates never race. // // On disk, per board: inspect-knowledge// // notes.md the current notes the inspection agent follows // feedback.jsonl every piece of feedback, with the inspection it was about and the // operator's verdict when one was given (ground truth for later evals) // history/ every previous version of notes.md import Anthropic from '@anthropic-ai/sdk'; import { readFileSync, writeFileSync, appendFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; const HERE = fileURLToPath(new URL('.', import.meta.url)); const KDIR = join(HERE, 'inspect-knowledge'); const INSPECTIONS = join(HERE, 'inspections'); const MODEL = process.env.KNOWLEDGE_MODEL || 'claude-opus-5-5'; const MAX_NOTES = 6000; // characters; the agent is asked to stay well under this const boardDir = (board) => join(KDIR, board.replace(/[^a-z0-9._-]/gi, '_')); export function getNotes(board) { try { return readFileSync(join(boardDir(board), 'notes.md'), 'utf8'); } catch { return ''; } } export function knowledgeInfo(board) { const d = boardDir(board); let feedback = 0, updated = ''; try { feedback = readFileSync(join(d, 'feedback.jsonl'), 'utf8').split('\n').filter(Boolean).length; } catch {} const notes = getNotes(board); try { updated = readdirSync(join(d, 'history')).sort().pop()?.slice(0, 19) || ''; } catch {} const lessons = notes.split('\n').filter((l) => /^\s*[-*]\s/.test(l)).length; return { board, notes, lessons, feedback, updated }; } function findInspection(id) { if (!id || !/^[0-9TZ:.-]+-[a-z0-9._-]+$/i.test(id)) return null; const dir = join(INSPECTIONS, id.slice(0, 10)); try { const rec = JSON.parse(readFileSync(join(dir, id + '.json'), 'utf8')); let jpeg = null; try { jpeg = readFileSync(join(dir, id + '.jpg')); } catch {} return { rec, jpeg }; } catch { return null; } } const SCHEMA = { type: 'object', additionalProperties: false, required: ['understood', 'ack', 'operator_verdict', 'notes'], properties: { understood: { type: 'boolean' }, ack: { type: 'string' }, operator_verdict: { type: 'string', enum: ['pass', 'fail', 'none'] }, notes: { type: 'string' }, }, }; const SYSTEM = `You keep the inspection notes for one PCBA type on an assembly line. An automated optical inspection agent (Claude vision) reads these notes before it inspects every board of this type, so they are how the line teaches the inspector. An operator has just given feedback, usually spoken and transcribed by a phone, so expect speech-recognition errors (part numbers and reference designators may be misheard; use the inspection result and photo to work out what was meant). Your job: 1. Decide what the feedback teaches about this board type: an approved alternate part, a part that is not populated (DNP) on this build, a revision difference, something the inspector should ignore, something it should look at more carefully, how to judge an item it cannot see, or a correction to its verdict. 2. Rewrite the notes so they include it. The operator is the authority on the board; when new feedback contradicts an older note, the newer feedback wins. Keep the notes a short, deduplicated markdown bullet list grouped under a few headings (for example: Parts and alternates, Not populated, Revisions, How to judge, Common false alarms). Each bullet is one specific, checkable instruction that names the item, part or reference designator. No history, no dates, no names. Stay under 40 bullets. 3. If the feedback is only about this one board (for example "this one has a bad joint on U5"), do not turn it into a general rule; keep the notes unchanged unless it reveals a pattern. 4. operator_verdict: "pass" or "fail" if the operator said what this board really is, otherwise "none". 5. ack: one short sentence for the operator saying what you learned or changed (or what was unclear). understood=false if the feedback was empty, noise, or too unclear to act on; in that case return the notes unchanged and ask in the ack for what you need.`; let client = null, clientKey = null; function getClient(apiKey) { const k = apiKey(); if (!k) return null; if (k !== clientKey) { client = new Anthropic({ apiKey: k }); clientKey = k; } return client; } async function learn(apiKey, boardInfo, item) { const c = getClient(apiKey); if (!c) return { ok: false, error: 'server has no Anthropic API key' }; const d = boardDir(item.board); mkdirSync(join(d, 'history'), { recursive: true }); const notes = getNotes(item.board); const insp = findInspection(item.inspection); let recent = []; try { recent = readFileSync(join(d, 'feedback.jsonl'), 'utf8').split('\n').filter(Boolean).slice(-15).map((l) => JSON.parse(l).text); } catch {} const content = []; content.push({ type: 'text', text: `Board type: ${boardInfo ? boardInfo.name : item.board}\nInspection checklist:\n${(boardInfo?.checks || []).map((t, i) => `${i + 1}. ${t}`).join('\n')}` }); content.push({ type: 'text', text: `Current notes:\n${notes.trim() || '(none yet)'}` }); if (recent.length) content.push({ type: 'text', text: `Earlier feedback for this board type (oldest first, already folded into the notes):\n${recent.map((t) => '- ' + t).join('\n')}` }); if (insp) { const r = insp.rec.result || {}; content.push({ type: 'text', text: `The feedback is about this inspection (${item.inspection}). The inspector said:\n${JSON.stringify({ verdict: r.verdict, summary: r.summary, image_quality: r.image_quality, checks: r.checks, defects: r.defects, error: insp.rec.ok ? undefined : insp.rec.error }, null, 1)}` }); if (insp.jpeg) { content.push({ type: 'text', text: 'The photo it inspected:' }); content.push({ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: insp.jpeg.toString('base64') } }); } } else { content.push({ type: 'text', text: 'This feedback is general (not about one particular inspection).' }); } content.push({ type: 'text', text: `Operator feedback (${item.station || 'station'}): "${item.text}"` }); let resp; try { resp = await c.beta.messages.create({ model: MODEL, max_tokens: 16000, betas: ['server-side-fallback-2026-07-01'], fallbacks: 'default', system: SYSTEM, output_config: { effort: 'medium', format: { type: 'json_schema', schema: SCHEMA } }, messages: [{ role: 'user', content }], }); } catch (e) { if (e instanceof Anthropic.APIError) return { ok: false, error: `API error ${e.status ?? ''}: ${e.message}` }; throw e; } if (resp.stop_reason !== 'end_turn') return { ok: false, error: `agent stopped: ${resp.stop_reason}` }; let out; try { out = JSON.parse(resp.content.filter((b) => b.type === 'text').map((b) => b.text).join('')); } catch { return { ok: false, error: 'agent reply was not valid JSON' }; } const stamp = new Date().toISOString(); let changed = false; const newNotes = String(out.notes || '').trim().slice(0, MAX_NOTES); if (out.understood && newNotes && newNotes !== notes.trim()) { if (notes) writeFileSync(join(d, 'history', `${stamp.replace(/[:.]/g, '-')}.md`), notes); writeFileSync(join(d, 'notes.md'), newNotes + '\n'); changed = true; } appendFileSync(join(d, 'feedback.jsonl'), JSON.stringify({ t: stamp, station: item.station, inspection: item.inspection || null, text: item.text, inspector_verdict: insp?.rec?.result?.verdict ?? null, operator_verdict: out.operator_verdict, understood: out.understood, ack: out.ack, notes_changed: changed, }) + '\n'); console.log(`[knowledge] ${item.board} ${changed ? 'notes updated' : 'no change'}: ${out.ack}`); return { ok: true, ack: out.ack, understood: out.understood, changed, operator_verdict: out.operator_verdict, ...knowledgeInfo(item.board) }; } // one queue per board: feedback is applied strictly in order const queues = new Map(); export function submitFeedback(apiKey, boardInfo, item) { const prev = queues.get(item.board) || Promise.resolve(); const run = prev.catch(() => {}).then(() => learn(apiKey, boardInfo, item)) .catch((e) => ({ ok: false, error: 'agent failed: ' + (e && e.message || e) })); queues.set(item.board, run); return run; } // A plain "good" / "bad" from the operator: record the ground truth right away, no AI call. export function recordLabel(item, verdict) { const d = boardDir(item.board); mkdirSync(d, { recursive: true }); const insp = findInspection(item.inspection); const said = insp?.rec?.result?.verdict ?? null; const ack = verdict === 'pass' ? (said === 'pass' ? 'Recorded: good board, inspector agreed.' : `Recorded: good board (inspector said ${said || 'nothing'}).`) : (said === 'fail' ? 'Recorded: bad board, inspector agreed.' : `Recorded: bad board (inspector said ${said || 'nothing'}). Tell me what is wrong with it if you can.`); appendFileSync(join(d, 'feedback.jsonl'), JSON.stringify({ t: new Date().toISOString(), station: item.station, inspection: item.inspection || null, text: item.text, inspector_verdict: said, operator_verdict: verdict, understood: true, ack, notes_changed: false, quick: true, }) + '\n'); return { ok: true, ack, understood: true, changed: false, operator_verdict: verdict, ...knowledgeInfo(item.board) }; } // Ground truth: the operator's last verdict for each inspection. export function labels(board) { const out = new Map(); try { for (const l of readFileSync(join(boardDir(board), 'feedback.jsonl'), 'utf8').split('\n').filter(Boolean)) { const j = JSON.parse(l); if (j.inspection && (j.operator_verdict === 'pass' || j.operator_verdict === 'fail')) out.set(j.inspection, j.operator_verdict); } } catch {} return out; }