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).
237 lines
8.6 KiB
TypeScript
237 lines
8.6 KiB
TypeScript
// SUBMISSION-EXPORT layer — turns a computed evidence dossier into a stable,
|
||
// submission-grade artifact a regulated buyer can file and defend. Two pure,
|
||
// deterministic serializers, NO LLM in the loop:
|
||
//
|
||
// - dossierToStructured : a stable JSON object — sections, each claim carrying
|
||
// its provenance hash + source — plus the full hash-chain and a
|
||
// chain-verified flag and quality score. This is the machine-readable
|
||
// submission record.
|
||
// - dossierToText : a plain-text mirror for pasting into flat documents /
|
||
// regulatory correspondence.
|
||
//
|
||
// The input is a GENERIC dossier-like shape defined locally here, so this module
|
||
// does NOT depend on any parallel dossier vertical's exact types — an upstream
|
||
// dossier only has to expose { title?, generatedAt?, sections[] }. Every claim in
|
||
// the input becomes exactly one EvidenceItem in the provenance chain, in document
|
||
// order, so the structured export's per-claim hash matches the chain record at
|
||
// the same index. Pure and deterministic; never mutates its input.
|
||
|
||
import {
|
||
buildProvenanceChain,
|
||
verifyChain,
|
||
evidenceQualityScore,
|
||
type EvidenceItem,
|
||
type ProvenanceChain,
|
||
} from "./chain";
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Minimal input shape. Deliberately loose (optional metadata, string-ish claim
|
||
// values) so heterogeneous dossier producers can feed this without adapters.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/** One source-backed claim inside a dossier section. */
|
||
export interface DossierClaim {
|
||
readonly statement: string;
|
||
// The load-bearing verified value (already computed by a deterministic engine).
|
||
// Accepts number too for convenience; normalized to a string for hashing so the
|
||
// provenance hash is stable regardless of numeric formatting upstream.
|
||
readonly value: string | number;
|
||
readonly source: string;
|
||
readonly quote: string;
|
||
}
|
||
|
||
/** A titled group of claims (e.g. "Efficacy", "Safety signal", "Target rationale"). */
|
||
export interface DossierSection {
|
||
readonly title: string;
|
||
readonly claims: readonly DossierClaim[];
|
||
}
|
||
|
||
/** The generic dossier bundle this module accepts. */
|
||
export interface DossierInput {
|
||
readonly title?: string;
|
||
readonly generatedAt?: string;
|
||
readonly sections: readonly DossierSection[];
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Structured output shape. Stable field order + names — this is a submission
|
||
// contract, so it is typed explicitly rather than inferred.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export interface StructuredClaim {
|
||
readonly statement: string;
|
||
readonly value: string;
|
||
readonly source: string;
|
||
readonly quote: string;
|
||
// sha256 hash-chain link for THIS claim — its tamper-evident provenance anchor.
|
||
readonly provenanceHash: string;
|
||
// Ordinal in the flattened chain, so a reader can locate the chain record.
|
||
readonly chainIndex: number;
|
||
}
|
||
|
||
export interface StructuredSection {
|
||
readonly title: string;
|
||
readonly claims: readonly StructuredClaim[];
|
||
}
|
||
|
||
export interface StructuredDossier {
|
||
readonly title: string;
|
||
readonly generatedAt: string;
|
||
readonly sections: readonly StructuredSection[];
|
||
readonly provenance: {
|
||
// The full ordered hash chain (self-contained: verifiable with no other data).
|
||
readonly chain: ProvenanceChain;
|
||
// Recomputed on export — true iff every link verifies.
|
||
readonly verified: boolean;
|
||
// The chain's terminal hash: a single fingerprint of the entire dossier.
|
||
readonly rootHash: string;
|
||
// Deterministic 0..1 evidence-quality score over all claims.
|
||
readonly qualityScore: number;
|
||
readonly claimCount: number;
|
||
};
|
||
}
|
||
|
||
const DEFAULT_TITLE = "Evidence Dossier";
|
||
const GENERATED_NOTE =
|
||
"Generated by PaperTrail. Every claim is hash-chained (SHA-256) to its source " +
|
||
"quote; the chain is order-sensitive and tamper-evident. No language model is " +
|
||
"in the numeric or provenance loop.";
|
||
|
||
// Normalize a claim's value to the exact string that gets hashed and displayed,
|
||
// so the provenance hash is stable regardless of upstream number formatting.
|
||
function valueToString(value: string | number): string {
|
||
return typeof value === "number" ? String(value) : value;
|
||
}
|
||
|
||
// Flatten all sections' claims into the ordered EvidenceItem list the chain is
|
||
// built from. Document order == chain order, so section i / claim j maps to a
|
||
// single deterministic chain index.
|
||
function flattenToItems(dossier: DossierInput): EvidenceItem[] {
|
||
const items: EvidenceItem[] = [];
|
||
for (const section of dossier.sections) {
|
||
for (const claim of section.claims) {
|
||
items.push({
|
||
statement: claim.statement,
|
||
value: valueToString(claim.value),
|
||
source: claim.source,
|
||
quote: claim.quote,
|
||
});
|
||
}
|
||
}
|
||
return items;
|
||
}
|
||
|
||
/**
|
||
* Serialize a dossier into a stable, submission-grade JSON object. Builds the
|
||
* provenance hash chain over every claim (in document order), then re-emits the
|
||
* sections with each claim carrying its own `provenanceHash` + `chainIndex`, and
|
||
* attaches the full chain, a recomputed `verified` flag, the terminal `rootHash`,
|
||
* and the deterministic `qualityScore`. Pure and deterministic; does not mutate
|
||
* its input.
|
||
*/
|
||
export function dossierToStructured(dossier: DossierInput): StructuredDossier {
|
||
const items = flattenToItems(dossier);
|
||
const chain = buildProvenanceChain(items);
|
||
const verified = verifyChain(chain);
|
||
const qualityScore = evidenceQualityScore(items);
|
||
const rootHash = chain.length > 0 ? chain[chain.length - 1].hash : "";
|
||
|
||
// Re-walk the sections attaching the chain hash at the matching flat index.
|
||
// A running cursor keeps structured claim i aligned with chain record i.
|
||
let cursor = 0;
|
||
const sections: StructuredSection[] = dossier.sections.map((section) => ({
|
||
title: section.title,
|
||
claims: section.claims.map((claim) => {
|
||
const record = chain[cursor];
|
||
cursor += 1;
|
||
return {
|
||
statement: claim.statement,
|
||
value: valueToString(claim.value),
|
||
source: claim.source,
|
||
quote: claim.quote,
|
||
provenanceHash: record.hash,
|
||
chainIndex: record.index,
|
||
};
|
||
}),
|
||
}));
|
||
|
||
return {
|
||
title: dossier.title?.trim() || DEFAULT_TITLE,
|
||
generatedAt: dossier.generatedAt ?? new Date(0).toISOString(),
|
||
sections,
|
||
provenance: {
|
||
chain,
|
||
verified,
|
||
rootHash,
|
||
qualityScore,
|
||
claimCount: items.length,
|
||
},
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Plain-text rendering
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function divider(): string {
|
||
return "=".repeat(72);
|
||
}
|
||
|
||
function subDivider(): string {
|
||
return "-".repeat(72);
|
||
}
|
||
|
||
/**
|
||
* Serialize a dossier as a plain-text submission artifact — the same content as
|
||
* the structured export, formatted for pasting into flat documents. Each claim is
|
||
* printed with its statement, verified value, source, supporting quote, and its
|
||
* SHA-256 provenance hash; a footer records the root hash, chain-verified flag,
|
||
* and quality score. Pure and deterministic; does not mutate its input.
|
||
*/
|
||
export function dossierToText(dossier: DossierInput): string {
|
||
const structured = dossierToStructured(dossier);
|
||
const lines: string[] = [];
|
||
|
||
lines.push(structured.title.toUpperCase());
|
||
lines.push(`Generated at : ${structured.generatedAt}`);
|
||
lines.push(divider());
|
||
lines.push("");
|
||
lines.push(
|
||
`Provenance : ${structured.provenance.verified ? "VERIFIED" : "UNVERIFIED — chain integrity check FAILED"}`
|
||
);
|
||
lines.push(`Root hash : ${structured.provenance.rootHash || "(empty dossier)"}`);
|
||
lines.push(`Quality score: ${structured.provenance.qualityScore.toFixed(4)} (0–1)`);
|
||
lines.push(`Claims : ${structured.provenance.claimCount}`);
|
||
lines.push("");
|
||
|
||
if (structured.sections.length === 0) {
|
||
lines.push("(No sections in this dossier.)");
|
||
}
|
||
|
||
for (const section of structured.sections) {
|
||
lines.push(divider());
|
||
lines.push(`SECTION: ${section.title}`);
|
||
lines.push(divider());
|
||
if (section.claims.length === 0) {
|
||
lines.push(" (No claims in this section.)");
|
||
lines.push("");
|
||
continue;
|
||
}
|
||
for (const claim of section.claims) {
|
||
lines.push("");
|
||
lines.push(` [${claim.chainIndex}] ${claim.statement}`);
|
||
lines.push(` Value : ${claim.value}`);
|
||
lines.push(` Source : ${claim.source}`);
|
||
lines.push(` Quote : "${claim.quote}"`);
|
||
lines.push(` Hash : ${claim.provenanceHash}`);
|
||
lines.push(` ${subDivider()}`);
|
||
}
|
||
lines.push("");
|
||
}
|
||
|
||
lines.push(divider());
|
||
lines.push(GENERATED_NOTE);
|
||
|
||
return lines.join("\n");
|
||
}
|