import { renderCitations } from "./citations.mjs"; import { chunkText } from "./rag.mjs"; import { CORPUS, INVESTIGATION } from "./corpus.mjs"; import { auditMarkdown } from "./search.mjs"; const $ = (id) => document.getElementById(id); let chunks = [], worker = null, busy = false, requestId = 0, lastTrace = null, lastEvaluation = null, brief = [], pending = null; function setBusy(value) { busy = value; for (const id of [ "ask", "evidenceOnly", "index", "sample", "evaluate", "investigate", "export", "exportBrief", "exportEval", "answerAudit", "exportAudit", ]) $(id).disabled = value; } function sources(hits) { $("sources").replaceChildren(); hits.forEach((c, i) => { const a = document.createElement("article"), h = document.createElement("strong"), p = document.createElement("p"), m = document.createElement("small"); a.id = `source-${i + 1}`; a.tabIndex = -1; h.textContent = `[${i + 1}] ${c.source} · ${c.location}`; p.textContent = c.text; m.textContent = c.semantic === undefined ? "Keyword retrieval" : `Semantic similarity ${c.semantic.toFixed(3)} · retrieval score, not confidence`; a.append(h, m, p); $("sources").append(a); }); } let exportUrl; function download(name, text, type = "text/markdown") { if (exportUrl) URL.revokeObjectURL(exportUrl); exportUrl = URL.createObjectURL(new Blob([text], { type })); $("exportPanel").hidden = false; $("exportText").value = text; $("exportName").textContent = name; $("saveExport").href = exportUrl; $("saveExport").download = name; $("status").textContent = "Export ready. Save the file or copy its contents below."; $("exportPanel").scrollIntoView({ behavior: "smooth", block: "start" }); } function getWorker() { if (worker) return worker; worker = new Worker("./worker.mjs?v=3", { type: "module" }); worker.onmessage = ({ data }) => { if (data.requestId !== requestId) return; if (data.type === "status") { $("status").textContent = data.text; return; } if (data.type === "evidence") { sources(data.hits); return; } if (data.type === "audit-progress") { $("answerAuditResult").textContent = `Completed ${data.complete}/${data.total} actual model checks…`; return; } if (data.type === "answer-audit") { renderAnswerAudit(data.result); setBusy(false); $("status").textContent = "Answer audit complete. Inspect failures and fallback routes below."; return; } if (data.type === "evaluation") { lastEvaluation = data.result; renderEvaluation(data.result); $("status").textContent = "Benchmark complete. Retrieval scores are measured; answer accuracy is not."; setBusy(false); return; } if (data.type === "answer") { lastTrace = { question: pending.question, mode: pending.mode, created: new Date().toISOString(), answer: data.text, hits: data.hits, metadata: data.metadata, }; renderCitations($("answer"), data.text, data.hits.length); $("status").textContent = `Retrieval ${(data.metadata.retrievalMs / 1000).toFixed(1)}s · total ${(data.metadata.totalMs / 1000).toFixed(1)}s · verify relevance and source authority`; if (pending.brief) { brief.push(lastTrace); renderBrief(); if (brief.length < INVESTIGATION.length) { sendQuestion(INVESTIGATION[brief.length], true, true); return; } } setBusy(false); return; } if (data.type === "error") { $("answer").textContent = data.text; $("status").textContent = "Processing stopped. Evidence already shown is retained."; setBusy(false); } }; worker.onerror = () => { $("answer").textContent = "The browser worker failed. Cancel, then retry or select keyword search with Evidence only."; setBusy(false); worker.terminate(); worker = null; }; return worker; } function sendQuestion(question, generate, forBrief = false) { setBusy(true); pending = { question, generate, mode: $("mode").value, brief: forBrief }; $("question").value = question; $("answer").textContent = "Finding evidence…"; getWorker().postMessage({ ...pending, action: "ask", requestId: ++requestId, chunks, }); } function ask(generate) { if (busy) return; const q = $("question").value.trim(); if (!chunks.length) { $("answer").textContent = "Load documents or the demo case first."; return; } if (!q || q.length > 1500) { $("answer").textContent = "Enter a question between 1 and 1,500 characters."; return; } sendQuestion(q, generate); } function resetResults() { if (exportUrl) { URL.revokeObjectURL(exportUrl); exportUrl = null; } $("exportPanel").hidden = true; $("exportText").value = ""; lastTrace = null; brief = []; $("brief").replaceChildren(); $("sources").textContent = "Ask a question to inspect its passages."; $("answer").textContent = "The closest source sentence will appear here."; } $("sample").onclick = () => { chunks = CORPUS.map((c) => ({ ...c })); resetResults(); $("indexStatus").textContent = `Demo loaded · ${chunks.length} passages across 9 fictional documents`; $("question").value = "Why did HBR-1042 happen?"; }; $("index").onclick = async () => { setBusy(true); chunks = []; resetResults(); const epoch = ++requestId; try { const files = [...$("files").files]; if (!files.length || files.length > 5) throw Error("Choose 1–5 files."); if (files.reduce((n, f) => n + f.size, 0) > 5e6) throw Error("Combined limit: 5 MB."); const next = []; for (const file of files) { const ext = file.name.split(".").pop().toLowerCase(); if (ext === "pdf") { const pdfjs = await import( "https://cdn.jsdelivr.net/npm/pdfjs-dist@4.10.38/build/pdf.min.mjs" ); pdfjs.GlobalWorkerOptions.workerSrc = "https://cdn.jsdelivr.net/npm/pdfjs-dist@4.10.38/build/pdf.worker.min.mjs"; const pdf = await pdfjs.getDocument({ data: new Uint8Array(await file.arrayBuffer()), isEvalSupported: false, }).promise; try { if (pdf.numPages > 50) throw Error("Limit: 50 pages per PDF."); for (let n = 1; n <= pdf.numPages; n++) { if (epoch !== requestId) return; const page = await pdf.getPage(n), content = await page.getTextContent(); next.push( ...chunkText( content.items.map((i) => i.str || "").join(" "), file.name, `page ${n}`, ), ); if (next.length > 600) throw Error("Limit: 600 passages."); } } finally { await pdf.destroy(); } } else if (["txt", "md"].includes(ext)) next.push(...chunkText(await file.text(), file.name)); else throw Error("Use PDF, TXT, or MD."); if (next.length > 600) throw Error("Limit: 600 passages."); } if (epoch !== requestId) return; if (!next.length) throw Error("No readable text. Scanned PDFs need OCR."); chunks = next; $("indexStatus").textContent = `Ready · ${files.length} files · ${chunks.length} passages`; } catch (e) { if (epoch === requestId) $("indexStatus").textContent = e.message; } finally { if (epoch === requestId) setBusy(false); } }; $("ask").onclick = () => ask(true); $("evidenceOnly").onclick = () => ask(false); $("clear").onclick = () => { requestId++; if (worker) { worker.terminate(); worker = null; } setBusy(false); chunks = []; pending = null; resetResults(); $("files").value = ""; $("question").value = ""; $("indexStatus").textContent = "Session cleared."; lastAnswerAudit = null; $("answerAuditResult").textContent = "No answer checks run in this session."; lastEvaluation = null; $("evaluation").textContent = "No benchmark run in this session."; $("exportPanel").hidden = true; $("exportText").value = ""; if (exportUrl) { URL.revokeObjectURL(exportUrl); exportUrl = null; } $("status").textContent = "No paid API. Everything runs on this device."; }; $("evaluate").onclick = () => { if (busy) return; setBusy(true); $("evaluation").textContent = "Running 30 fixed queries against both retrieval methods…"; getWorker().postMessage({ action: "evaluate", requestId: ++requestId }); }; function renderEvaluation(result) { const pct = (x) => (x === null ? "—" : `${(100 * x).toFixed(1)}%`); $("evaluation").replaceChildren(); const table = document.createElement("table"); for (const row of [ ["Retrieval metric", "Original BM25", "Hybrid"], [ "Hit @ 1 · 24 answerable", pct(result.baseline.hitAt1), pct(result.hybrid.hitAt1), ], [ "Recall @ 3 · 24 answerable", pct(result.baseline.recallAt3), pct(result.hybrid.recallAt3), ], [ "MRR · answerable", result.baseline.mrr.toFixed(3), result.hybrid.mrr.toFixed(3), ], [ "Reject unknown · 6 questions", pct(result.baseline.unknownRejection), pct(result.hybrid.unknownRejection), ], ]) { const tr = document.createElement("tr"); row.forEach((text) => { const td = document.createElement("td"); td.textContent = text; tr.append(td); }); table.append(tr); } $("evaluation").append(table); const note = document.createElement("p"); note.textContent = result.scope + " Fixed semantic threshold: 0.30. Export JSON to inspect every query, miss, and label."; $("evaluation").append(note); const details = document.createElement("details"), summary = document.createElement("summary"); summary.textContent = "Inspect every benchmark result"; details.append(summary); for (const row of result.rows) { const p = document.createElement("p"); p.textContent = `${row.id} · ${row.question} | expected ${row.expected ?? "abstain"} | BM25 ${row.baseline.join(", ") || "abstain"} | hybrid ${row.hybrid.join(", ") || "abstain"}`; details.append(p); } $("evaluation").append(details); } $("exportEval").onclick = () => { if (!lastEvaluation) { $("status").textContent = "Run the benchmark first."; return; } download( "fieldnotes-retrieval-evaluation.json", JSON.stringify(lastEvaluation, null, 2), "application/json", ); }; $("export").onclick = () => { if (!lastTrace) { $("status").textContent = "Ask a question before exporting."; return; } download("fieldnotes-evidence-record.md", auditMarkdown(lastTrace)); }; $("investigate").onclick = () => { if (busy) return; if (!chunks.some((c) => c.id === "root-cause")) { $("status").textContent = "Load the HBR-1042 demo case to build this case-specific brief."; return; } brief = []; $("brief").replaceChildren(); sendQuestion(INVESTIGATION[0], true, true); }; function renderBrief() { $("brief").replaceChildren(); brief.forEach((t, i) => { const article = document.createElement("article"), h = document.createElement("strong"), p = document.createElement("p"), details = document.createElement("details"), summary = document.createElement("summary"); const prefix = `brief-${i + 1}-source`; h.textContent = `${i + 1}. ${t.question}`; renderCitations(p, t.answer, t.hits.length, prefix); summary.textContent = `Supporting passages (${t.hits.length})`; details.append(summary); t.hits.forEach((source, j) => { const box = document.createElement("div"), label = document.createElement("strong"), excerpt = document.createElement("p"); box.id = `${prefix}-${j + 1}`; box.tabIndex = -1; label.textContent = `[${j + 1}] ${source.source} · ${source.location}`; excerpt.textContent = source.text; box.append(label, excerpt); details.append(box); }); article.append(h, p, details); $("brief").append(article); }); } $("exportBrief").onclick = () => { if (!brief.length) { $("status").textContent = "Build the incident brief first."; return; } download( "fieldnotes-incident-brief.md", "# HBR-1042 evidence brief\n\nFictional demonstration. Verify every claim.\n\n" + brief.map(auditMarkdown).join("\n---\n"), ); }; let lastAnswerAudit = null; $("answerAudit").onclick = () => { if (busy) return; setBusy(true); $("answerAuditResult").textContent = "Running real retrieval and LLM inference. This may take 1–2 minutes."; getWorker().postMessage({ action: "answer-audit", requestId: ++requestId }); }; function renderAnswerAudit(result) { lastAnswerAudit = result; const box = $("answerAuditResult"); box.replaceChildren(); const summary = document.createElement("strong"); summary.textContent = `${result.passed}/${result.total} checks passed · ${result.fallbacks} labeled fallbacks · ${(result.elapsedMs / 1000).toFixed(1)} seconds`; box.append(summary); const note = document.createElement("p"); note.textContent = result.scope; box.append(note); for (const row of result.rows) { const article = document.createElement("article"), h = document.createElement("strong"), p = document.createElement("p"), small = document.createElement("small"); h.textContent = `${row.check.pass ? "PASS" : "FAIL"} · ${row.question}`; p.textContent = row.answer; small.textContent = `Route: ${row.method} · ${(row.elapsedMs / 1000).toFixed(1)}s · ${row.sources.map((s) => s.id).join(", ")}`; article.append(h, p, small); box.append(article); } } $("exportAudit").onclick = () => { if (!lastAnswerAudit) { $("status").textContent = "Run answer checks first."; return; } download( "fieldnotes-answer-audit.json", JSON.stringify(lastAnswerAudit, null, 2), "application/json", ); };