Builds PaperTrail from the base skeleton into a full evidence-verification platform for the "Built with Claude: Life Sciences" hackathon (Builder Track). New named-user features (Build Beyond the Bench): - Lab Notebook Companion — rough bench notes -> structured, searchable, grounded experiment records (lib/labNotebook, /console/lab-notebook, migration 0059) - Clinical Trial Matcher — de-identified patient notes -> ranked eligible ClinicalTrials.gov trials with per-criterion inclusion/exclusion reasoning (lib/trialMatcher, /console/trial-matcher, migrations 0060) Platform: - Deterministic verification moat (biostats recompute, exact-span grounding) - 11 biomedical evidence engines (FAERS, GWAS, Open Targets, ChEMBL, ClinVar, PharmGKB, PubTator, DDI, repurposing, biomarker, unified verifier) - Evidence Intelligence (KG, dossier, provenance/export, RWE) + enterprise governance (RBAC, /api/v1 gateway, metering, audit chain, retention) - 17 OSS projects assimilated into native TypeScript on our stack (backend/engines retained + credited in NOTICE) - Multi-format upload (PDF/DOCX/XLSX/CSV/MD/TXT), logo, marketing site - Next.js 16 upgrade, benchmark harness (honest smoke-test caveat) Licensing: Apache-2.0 (LICENSE + NOTICE).
404 lines
14 KiB
TypeScript
404 lines
14 KiB
TypeScript
// Renders a composite EvidenceReport (lib/evidenceReport.ts) as a defensible,
|
||
// self-contained GRADE "Summary of Findings" (SoF) document — the artefact a
|
||
// medical writer pastes into a regulatory dossier or systematic-review appendix.
|
||
//
|
||
// Two pure, deterministic serializers with NO LLM anywhere in the loop:
|
||
// - evidenceReportToHtml : a complete standalone <html> string (inline CSS, no
|
||
// external assets — renders identically offline and prints cleanly to PDF).
|
||
// - evidenceReportToText : a plain-text mirror for pasting into flat documents.
|
||
//
|
||
// Every interpolated value is HTML-escaped (mirrors lib/reportExportHtml.ts), and
|
||
// every number traces back through the engines to the caller's inputs. Handles the
|
||
// insufficient-evidence report shape (ok: false) gracefully. Does not mutate input.
|
||
|
||
import type {
|
||
BuildEvidenceReportResult,
|
||
EvidenceReport,
|
||
InsufficientEvidenceReport,
|
||
} from "./evidenceReport";
|
||
import type { Certainty } from "./grade";
|
||
|
||
// Reuse the house escaper so escaping behaviour is identical to the provenance
|
||
// report export (five XML/HTML-significant characters).
|
||
import { escapeHtml } from "./reportExportHtml";
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Display maps. Human-readable labels for the machine enums so the SoF reads
|
||
// like a clinician wrote it, not like a JSON dump.
|
||
// ---------------------------------------------------------------------------
|
||
const CERTAINTY_LABELS: Record<Certainty, string> = {
|
||
high: "High",
|
||
moderate: "Moderate",
|
||
low: "Low",
|
||
very_low: "Very low",
|
||
};
|
||
|
||
// Badge colours per certainty level (GRADEpro-style: green high → red very-low).
|
||
const CERTAINTY_COLORS: Record<Certainty, { bg: string; fg: string }> = {
|
||
high: { bg: "#e6f4ea", fg: "#1e7e34" },
|
||
moderate: { bg: "#fff6e5", fg: "#b26a00" },
|
||
low: { bg: "#fdeceb", fg: "#c0392b" },
|
||
very_low: { bg: "#fbe4e4", fg: "#a11" },
|
||
};
|
||
|
||
const VERDICT_LABELS: Record<string, string> = {
|
||
matches_pooled: "Claim matches the pooled estimate",
|
||
overstates_pooled: "Claim overstates the pooled estimate",
|
||
understates_pooled: "Claim understates the pooled estimate",
|
||
significance_mismatch: "Claim asserts benefit the pooled CI does not support",
|
||
single_trial_cherry_pick: "Claim reflects a single trial, not the pool",
|
||
high_heterogeneity: "Studies too inconsistent to pool reliably",
|
||
insufficient_evidence: "Insufficient comparable trials to pool",
|
||
not_comparable: "Claim has no comparable magnitude to the pool",
|
||
};
|
||
|
||
const BIAS_VERDICT_LABELS: Record<string, string> = {
|
||
no_asymmetry: "No funnel-plot asymmetry detected",
|
||
possible_small_study_effects: "Possible small-study effects / publication bias",
|
||
insufficient_studies: "Too few studies to test for publication bias",
|
||
};
|
||
|
||
const MEASURE_NAMES: Record<string, string> = {
|
||
RR: "Risk ratio",
|
||
HR: "Hazard ratio",
|
||
OR: "Odds ratio",
|
||
};
|
||
|
||
function certaintyLabel(c: Certainty): string {
|
||
return CERTAINTY_LABELS[c] ?? c;
|
||
}
|
||
|
||
function verdictLabel(v: string): string {
|
||
return VERDICT_LABELS[v] ?? v;
|
||
}
|
||
|
||
function biasVerdictLabel(v: string): string {
|
||
return BIAS_VERDICT_LABELS[v] ?? v;
|
||
}
|
||
|
||
function measureName(m: string): string {
|
||
return MEASURE_NAMES[m] ?? m;
|
||
}
|
||
|
||
function round(n: number, dp = 1): number {
|
||
const f = 10 ** dp;
|
||
return Math.round(n * f) / f;
|
||
}
|
||
|
||
// Format a pooled point + 95% CI on the ratio scale, e.g. "0.70 (0.58–0.85)".
|
||
function formatEstimate(point: number, ciLower: number, ciUpper: number): string {
|
||
return `${round(point, 2)} (${round(ciLower, 2)}–${round(ciUpper, 2)})`;
|
||
}
|
||
|
||
const GENERATED_NOTE =
|
||
"Generated by PaperTrail. Every value is derived deterministically from the " +
|
||
"submitted trial estimates by the meta-analysis, publication-bias, and GRADE " +
|
||
"engines — no language model is in the numeric loop.";
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// HTML rendering
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function certaintyBadgeHtml(certainty: Certainty): string {
|
||
const { bg, fg } = CERTAINTY_COLORS[certainty] ?? CERTAINTY_COLORS.very_low;
|
||
return `<span class="badge" style="background:${bg};color:${fg}">${escapeHtml(
|
||
certaintyLabel(certainty)
|
||
)} certainty</span>`;
|
||
}
|
||
|
||
// The certainty column's downgrade reasons, rendered as a compact list. Empty
|
||
// (no downgrades) reads as "No downgrades applied".
|
||
function downgradeReasonsHtml(report: EvidenceReport): string {
|
||
const downgrades = report.certainty.downgrades;
|
||
if (downgrades.length === 0) {
|
||
return `<p class="reasons none">No downgrades applied.</p>`;
|
||
}
|
||
const items = downgrades
|
||
.map(
|
||
(d) =>
|
||
`<li><span class="domain">${escapeHtml(
|
||
d.domain.replace(/_/g, " ")
|
||
)} (−${d.steps})</span> ${escapeHtml(d.reason)}</li>`
|
||
)
|
||
.join("\n ");
|
||
return `<ul class="reasons">\n ${items}\n </ul>`;
|
||
}
|
||
|
||
// The single SoF outcome row. All numeric cells come straight off the pooled
|
||
// random-effects estimate + heterogeneity that the engine already computed.
|
||
function sofRowHtml(report: EvidenceReport): string {
|
||
const p = report.pooled;
|
||
const r = p.random;
|
||
return `<tr>
|
||
<td>${escapeHtml(measureName(p.measure))} (${escapeHtml(p.measure)})</td>
|
||
<td class="num">${escapeHtml(formatEstimate(r.point, r.ciLower, r.ciUpper))}</td>
|
||
<td class="num">${escapeHtml(String(p.k))}</td>
|
||
<td class="num">${escapeHtml(String(round(p.heterogeneity.iSquared, 1)))}%</td>
|
||
<td>
|
||
<div class="cert-cell">${certaintyBadgeHtml(report.certainty.certainty)}</div>
|
||
${downgradeReasonsHtml(report)}
|
||
</td>
|
||
</tr>`;
|
||
}
|
||
|
||
function sufficientHtmlBody(report: EvidenceReport, claim: string): string {
|
||
const v = report.verdict;
|
||
const bias = report.publicationBias;
|
||
return `<section class="verdict-banner">
|
||
${certaintyBadgeHtml(report.certainty.certainty)}
|
||
<span class="verdict-label">${escapeHtml(verdictLabel(v.verdict))}</span>
|
||
</section>
|
||
|
||
<section class="block claim-block">
|
||
<h2>Claim assessed</h2>
|
||
<blockquote class="claim">${escapeHtml(claim.trim())}</blockquote>
|
||
</section>
|
||
|
||
<section class="block sof-block">
|
||
<h2>Summary of findings</h2>
|
||
<table class="sof">
|
||
<thead>
|
||
<tr>
|
||
<th>Outcome (measure)</th>
|
||
<th>Pooled estimate (95% CI)</th>
|
||
<th>Studies (k)</th>
|
||
<th>I²</th>
|
||
<th>Certainty of evidence (GRADE)</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
${sofRowHtml(report)}
|
||
</tbody>
|
||
</table>
|
||
</section>
|
||
|
||
<section class="block synthesis-block">
|
||
<h2>Synthesis verdict — ${escapeHtml(verdictLabel(v.verdict))}</h2>
|
||
<p>${escapeHtml(v.rationale)}</p>
|
||
</section>
|
||
|
||
<section class="block bias-block">
|
||
<h2>Publication bias</h2>
|
||
<p><span class="bias-verdict">${escapeHtml(
|
||
biasVerdictLabel(bias.verdict)
|
||
)}.</span> ${escapeHtml(bias.note)}</p>
|
||
</section>
|
||
|
||
<section class="block rationale-block">
|
||
<h2>Overall rationale</h2>
|
||
<p>${escapeHtml(report.rationale)}</p>
|
||
</section>`;
|
||
}
|
||
|
||
function insufficientHtmlBody(
|
||
report: InsufficientEvidenceReport,
|
||
claim: string
|
||
): string {
|
||
return `<section class="verdict-banner">
|
||
<span class="badge" style="background:#f0f0f0;color:#555">Insufficient evidence</span>
|
||
<span class="verdict-label">Could not pool a defensible estimate</span>
|
||
</section>
|
||
|
||
<section class="block claim-block">
|
||
<h2>Claim assessed</h2>
|
||
<blockquote class="claim">${escapeHtml(claim.trim())}</blockquote>
|
||
</section>
|
||
|
||
<section class="block insufficient-block">
|
||
<h2>Why no summary of findings</h2>
|
||
<p>${escapeHtml(report.reason)}</p>
|
||
<p class="meta">Usable studies: ${escapeHtml(String(report.usableStudies))}.</p>
|
||
</section>`;
|
||
}
|
||
|
||
/**
|
||
* Serialize an EvidenceReport as a complete, standalone GRADE Summary-of-Findings
|
||
* HTML document. Header carries the claim and the certainty badge; a SoF table
|
||
* lists the pooled estimate + 95% CI, k studies, I², and the GRADE certainty with
|
||
* its downgrade reasons; then the synthesis verdict + rationale and a
|
||
* publication-bias line. Inline styles only — no external assets.
|
||
*
|
||
* Handles the insufficient-evidence shape (ok: false) gracefully by rendering an
|
||
* honest "could not pool" document instead of a table. Every interpolated value is
|
||
* HTML-escaped. Pure and deterministic; does not mutate its input.
|
||
*/
|
||
export function evidenceReportToHtml(
|
||
report: BuildEvidenceReportResult,
|
||
claim: string
|
||
): string {
|
||
const body = report.ok
|
||
? sufficientHtmlBody(report, claim)
|
||
: insufficientHtmlBody(report, claim);
|
||
|
||
return `<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||
<title>PaperTrail — Summary of Findings</title>
|
||
<style>
|
||
:root { color-scheme: light; }
|
||
* { box-sizing: border-box; }
|
||
body {
|
||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||
color: #1a1a1a;
|
||
line-height: 1.5;
|
||
max-width: 820px;
|
||
margin: 0 auto;
|
||
padding: 40px 24px;
|
||
background: #ffffff;
|
||
}
|
||
header { border-bottom: 2px solid #1a1a1a; padding-bottom: 12px; margin-bottom: 24px; }
|
||
header h1 { font-size: 22px; margin: 0; }
|
||
header p { margin: 4px 0 0; color: #555; font-size: 13px; }
|
||
.verdict-banner { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; margin-bottom: 24px; }
|
||
.verdict-label { font-size: 18px; font-weight: 700; }
|
||
.badge {
|
||
display: inline-block;
|
||
padding: 3px 10px;
|
||
border-radius: 999px;
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
white-space: nowrap;
|
||
}
|
||
.block { margin-bottom: 24px; }
|
||
.block h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.04em; color: #555; margin: 0 0 8px; }
|
||
blockquote.claim {
|
||
margin: 0;
|
||
padding: 12px 16px;
|
||
border-left: 3px solid #888;
|
||
background: #f6f6f6;
|
||
font-style: italic;
|
||
}
|
||
table.sof { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||
table.sof th, table.sof td {
|
||
border: 1px solid #d8d8d8;
|
||
padding: 8px 10px;
|
||
text-align: left;
|
||
vertical-align: top;
|
||
}
|
||
table.sof th { background: #f2f2f2; font-size: 12px; text-transform: uppercase; letter-spacing: 0.02em; color: #444; }
|
||
table.sof td.num { text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||
.cert-cell { margin-bottom: 6px; }
|
||
ul.reasons { list-style: disc; margin: 0; padding-left: 18px; }
|
||
ul.reasons li { margin: 0 0 4px; }
|
||
ul.reasons li:last-child { margin-bottom: 0; }
|
||
.reasons .domain { font-weight: 600; }
|
||
p.reasons.none { margin: 0; color: #666; }
|
||
.bias-verdict { font-weight: 600; }
|
||
.insufficient-block .meta { color: #666; font-size: 13px; margin: 8px 0 0; }
|
||
footer { margin-top: 32px; padding-top: 12px; border-top: 1px solid #e0e0e0; color: #777; font-size: 12px; }
|
||
@media print {
|
||
body { padding: 0; max-width: none; }
|
||
table.sof { break-inside: avoid; }
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header>
|
||
<h1>Summary of Findings</h1>
|
||
<p>GRADE evidence profile for a clinical-trial efficacy claim — PaperTrail</p>
|
||
</header>
|
||
|
||
${body}
|
||
|
||
<footer>${escapeHtml(GENERATED_NOTE)}</footer>
|
||
</body>
|
||
</html>`;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Plain-text rendering
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function textDivider(): string {
|
||
return "=".repeat(72);
|
||
}
|
||
|
||
function sufficientText(report: EvidenceReport, claim: string): string {
|
||
const p = report.pooled;
|
||
const r = p.random;
|
||
const v = report.verdict;
|
||
const lines: string[] = [];
|
||
|
||
lines.push("SUMMARY OF FINDINGS");
|
||
lines.push("GRADE evidence profile for a clinical-trial efficacy claim — PaperTrail");
|
||
lines.push(textDivider());
|
||
lines.push("");
|
||
lines.push(`Certainty of evidence : ${certaintyLabel(report.certainty.certainty)}`);
|
||
lines.push(`Synthesis verdict : ${verdictLabel(v.verdict)}`);
|
||
lines.push("");
|
||
lines.push("CLAIM ASSESSED");
|
||
lines.push(` ${claim.trim()}`);
|
||
lines.push("");
|
||
lines.push("SUMMARY OF FINDINGS TABLE");
|
||
lines.push(` Outcome : ${measureName(p.measure)} (${p.measure})`);
|
||
lines.push(` Pooled estimate : ${formatEstimate(r.point, r.ciLower, r.ciUpper)}`);
|
||
lines.push(` Studies (k) : ${p.k}`);
|
||
lines.push(` Heterogeneity (I^2): ${round(p.heterogeneity.iSquared, 1)}%`);
|
||
lines.push(` GRADE certainty : ${certaintyLabel(report.certainty.certainty)}`);
|
||
if (report.certainty.downgrades.length === 0) {
|
||
lines.push(" Downgrades : none");
|
||
} else {
|
||
lines.push(" Downgrades :");
|
||
for (const d of report.certainty.downgrades) {
|
||
lines.push(` - ${d.domain.replace(/_/g, " ")} (-${d.steps}): ${d.reason}`);
|
||
}
|
||
}
|
||
lines.push("");
|
||
lines.push("SYNTHESIS VERDICT");
|
||
lines.push(` ${verdictLabel(v.verdict)}`);
|
||
lines.push(` ${v.rationale}`);
|
||
lines.push("");
|
||
lines.push("PUBLICATION BIAS");
|
||
lines.push(` ${biasVerdictLabel(report.publicationBias.verdict)}.`);
|
||
lines.push(` ${report.publicationBias.note}`);
|
||
lines.push("");
|
||
lines.push("OVERALL RATIONALE");
|
||
lines.push(` ${report.rationale}`);
|
||
lines.push("");
|
||
lines.push(textDivider());
|
||
lines.push(GENERATED_NOTE);
|
||
|
||
return lines.join("\n");
|
||
}
|
||
|
||
function insufficientText(
|
||
report: InsufficientEvidenceReport,
|
||
claim: string
|
||
): string {
|
||
const lines: string[] = [];
|
||
lines.push("SUMMARY OF FINDINGS");
|
||
lines.push("GRADE evidence profile for a clinical-trial efficacy claim — PaperTrail");
|
||
lines.push(textDivider());
|
||
lines.push("");
|
||
lines.push("Verdict : Insufficient evidence — could not pool a defensible estimate");
|
||
lines.push("");
|
||
lines.push("CLAIM ASSESSED");
|
||
lines.push(` ${claim.trim()}`);
|
||
lines.push("");
|
||
lines.push("WHY NO SUMMARY OF FINDINGS");
|
||
lines.push(` ${report.reason}`);
|
||
lines.push(` Usable studies: ${report.usableStudies}.`);
|
||
lines.push("");
|
||
lines.push(textDivider());
|
||
lines.push(GENERATED_NOTE);
|
||
return lines.join("\n");
|
||
}
|
||
|
||
/**
|
||
* Serialize an EvidenceReport as a plain-text Summary of Findings — the same
|
||
* content as the HTML export, formatted for pasting into flat documents. Contains
|
||
* the certainty, the pooled estimate + 95% CI, the synthesis verdict, and the
|
||
* publication-bias line. Handles the insufficient-evidence shape gracefully.
|
||
* Pure and deterministic; does not mutate its input.
|
||
*/
|
||
export function evidenceReportToText(
|
||
report: BuildEvidenceReportResult,
|
||
claim: string
|
||
): string {
|
||
return report.ok
|
||
? sufficientText(report, claim)
|
||
: insufficientText(report, claim);
|
||
}
|