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).
289 lines
12 KiB
TypeScript
289 lines
12 KiB
TypeScript
// MECHANISM-STATEMENT ASSEMBLY — a native TypeScript port of INDRA's causal-statement
|
||
// assembly + belief model (backend/engines/indra).
|
||
//
|
||
// Pipeline (assembleMechanisms):
|
||
// 1. EXTRACT — Claude proposes causal mechanistic statements from the source text:
|
||
// { subj, relation (activates|inhibits|phosphorylates|binds|regulates), obj,
|
||
// evidenceQuote }. This is the only LLM step; its output is validated against a
|
||
// Zod schema (MechanismExtractionSchema) at the trust boundary.
|
||
// 2. GROUND — each candidate's evidenceQuote is located verbatim in the source text
|
||
// via lib/grounding locateSpan. A candidate whose quote can't be located is
|
||
// DROPPED (INDRA never keeps an unsupported statement; PaperTrail never makes an
|
||
// unsourced claim about the source).
|
||
// 3. ASSEMBLE — de-duplicate grounded candidates into (subj, relation, obj) triples,
|
||
// merging their evidence (INDRA "preassembly": one Statement, many Evidence).
|
||
// 4. SCORE — compute a DETERMINISTIC belief per statement from its evidence:
|
||
// belief = 1 - prod_i (1 - reliability_i)
|
||
// the exact belief-combination idea from INDRA's SimpleScorer (probability of
|
||
// correctness = 1 - product of per-source incorrectness), with reliability_i the
|
||
// documented per-tier reliability. NO LLM number is load-bearing in the belief.
|
||
// 5. PERSIST — write each statement as an edge in OUR knowledge graph via
|
||
// lib/kg/repository upsertEdge, carrying full provenance.
|
||
//
|
||
// Every external dependency (Claude, grounding, the DB pool) is injected via a deps
|
||
// object so the whole thing runs OFFLINE against mocks in tests. On any failure the
|
||
// pipeline degrades to an HONEST empty result rather than fabricating statements.
|
||
|
||
import { locateSpan, type SpanGroundingStatus } from "../grounding";
|
||
import { callClaudeForJson } from "../claude";
|
||
import { upsertNode, upsertEdge, type KgPool } from "../kg/repository";
|
||
import type { KgPredicate } from "../kg/schemas";
|
||
import {
|
||
MechanismExtractionSchema,
|
||
SOURCE_TIER_RELIABILITY,
|
||
type GroundedEvidence,
|
||
type MechanismAssemblyResult,
|
||
type MechanismRelation,
|
||
type MechanismStatement,
|
||
type RawMechanismStatement,
|
||
type SourceTier,
|
||
} from "./schemas";
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Injectable dependencies. Defaults hit the real Claude client / KG repository; tests
|
||
// pass deterministic stubs so no network or DB is touched.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export interface MechanismDeps {
|
||
// Extract candidate mechanistic statements from source text. Returns validated,
|
||
// schema-shaped candidates (belief/grounding are added downstream by this module).
|
||
extract: (text: string) => Promise<RawMechanismStatement[]>;
|
||
}
|
||
|
||
const EXTRACTION_SYSTEM = [
|
||
"You extract CAUSAL MECHANISTIC statements from biomedical source text.",
|
||
"Return ONLY a single JSON object of the form:",
|
||
'{ "statements": [ { "subj": string, "relation": string, "obj": string, "evidenceQuote": string } ] }',
|
||
"relation MUST be one of: activates, inhibits, phosphorylates, binds, regulates.",
|
||
"subj and obj are the two biological entities in the mechanism (gene, protein, drug, pathway).",
|
||
"evidenceQuote MUST be an EXACT, VERBATIM substring copied from the provided text that states the mechanism — do not paraphrase, do not add words.",
|
||
"Only include statements the text actually asserts. If the text asserts no mechanism, return an empty statements array.",
|
||
].join("\n");
|
||
|
||
// Default extractor: Claude proposes candidates, validated against the Zod schema.
|
||
async function defaultExtract(text: string): Promise<RawMechanismStatement[]> {
|
||
const extraction = await callClaudeForJson({
|
||
system: EXTRACTION_SYSTEM,
|
||
user: text,
|
||
schema: MechanismExtractionSchema,
|
||
maxTokens: 2048,
|
||
});
|
||
return extraction.statements;
|
||
}
|
||
|
||
const defaultDeps: MechanismDeps = {
|
||
extract: (text) => defaultExtract(text),
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Belief combination — the deterministic heart, ported from INDRA's SimpleScorer.
|
||
//
|
||
// INDRA: probability the statement is INCORRECT = product over sources of the
|
||
// source-specific incorrectness; probability CORRECT = 1 - that product. With one
|
||
// reliability r_i per piece of evidence (r_i = 1 - incorrectness_i), this is exactly:
|
||
//
|
||
// belief = 1 - prod_i (1 - r_i)
|
||
//
|
||
// More corroborating evidence (or higher-tier sources) drives the product toward 0 and
|
||
// the belief toward 1; a single low-tier quote yields a modest belief. Pure + total.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export function combineBelief(evidence: readonly GroundedEvidence[]): number {
|
||
if (evidence.length === 0) return 0;
|
||
let productIncorrect = 1;
|
||
for (const ev of evidence) {
|
||
const reliability = SOURCE_TIER_RELIABILITY[ev.tier];
|
||
productIncorrect *= 1 - reliability;
|
||
}
|
||
return 1 - productIncorrect;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Grounding — locate each candidate's evidenceQuote verbatim in the source text. A
|
||
// candidate whose quote can't be located is dropped (returned null).
|
||
// ---------------------------------------------------------------------------
|
||
|
||
interface GroundedCandidate {
|
||
subj: string;
|
||
relation: MechanismRelation;
|
||
obj: string;
|
||
evidence: GroundedEvidence;
|
||
}
|
||
|
||
function groundCandidate(
|
||
candidate: RawMechanismStatement,
|
||
rawText: string,
|
||
tier: SourceTier
|
||
): GroundedCandidate | null {
|
||
const located = locateSpan(rawText, candidate.evidenceQuote);
|
||
if (!located) return null;
|
||
const status: SpanGroundingStatus = located.status;
|
||
return {
|
||
subj: candidate.subj,
|
||
relation: candidate.relation,
|
||
obj: candidate.obj,
|
||
evidence: {
|
||
quote: located.text, // verbatim source substring, never the model paraphrase
|
||
tier,
|
||
grounding: { status, start: located.start, end: located.end },
|
||
},
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Assembly (INDRA "preassembly") — collapse grounded candidates into de-duplicated
|
||
// (subj, relation, obj) triples, merging their evidence and computing the belief.
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function tripleKey(subj: string, relation: MechanismRelation, obj: string): string {
|
||
// Case-insensitive entity identity so "MEK" and "mek" collapse to one statement,
|
||
// matching INDRA's matches-key intent (same mechanism, more evidence -> one Statement).
|
||
return `${subj.toLowerCase()} |