caelum0x 174222bcaa feat: Builder-Track named-user tools, bio + evidence-intelligence platform, Apache-2.0
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).
2026-07-10 16:23:13 +03:00

289 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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()}${relation}${obj.toLowerCase()}`;
}
function assembleStatements(candidates: readonly GroundedCandidate[]): MechanismStatement[] {
const byTriple = new Map<
string,
{ subj: string; relation: MechanismRelation; obj: string; evidence: GroundedEvidence[] }
>();
for (const c of candidates) {
const key = tripleKey(c.subj, c.relation, c.obj);
const existing = byTriple.get(key);
if (existing) {
// Merge evidence, de-duping identical quotes (same sentence extracted twice).
const seen = existing.evidence.some((e) => e.quote === c.evidence.quote);
if (!seen) existing.evidence = [...existing.evidence, c.evidence];
} else {
byTriple.set(key, {
subj: c.subj,
relation: c.relation,
obj: c.obj,
evidence: [c.evidence],
});
}
}
const statements: MechanismStatement[] = [];
for (const s of byTriple.values()) {
statements.push({
subj: s.subj,
relation: s.relation,
obj: s.obj,
evidence: s.evidence,
belief: combineBelief(s.evidence),
});
}
// Highest-belief statements first — the most-corroborated mechanisms lead.
return statements.sort((a, b) => b.belief - a.belief);
}
// ---------------------------------------------------------------------------
// KG persistence. Mechanism relations are richer than the KG's closed predicate
// vocabulary (associates_with | targets | treats), so we persist the edge under the
// closest structural predicate — `targets` (subject mechanistically acts on object) —
// while preserving the EXACT mechanistic relation and the deterministic belief inside
// the edge provenance. This keeps the KG queryable and the provenance faithful.
// ---------------------------------------------------------------------------
const KG_PREDICATE_FOR_MECHANISM: KgPredicate = "targets";
// A mechanism entity has no PubTator-normalized id here, so we key its KG node on a
// stable, mechanism-scoped normalized id derived from the lower-cased surface form.
// Deterministic, so re-ingesting the same entity collapses to one node.
function mechanismNormalizedId(name: string): string {
return `mechanism:${name.trim().toLowerCase()}`;
}
async function persistStatements(
pool: KgPool,
statements: readonly MechanismStatement[]
): Promise<number> {
const nodeIds = new Map<string, string>();
const resolveNode = async (name: string): Promise<string> => {
const normalizedId = mechanismNormalizedId(name);
const cached = nodeIds.get(normalizedId);
if (cached) return cached;
// entityType 'gene' is the safest fit for a mechanism participant in the KG's
// entity vocabulary (proteins/genes are the typical subjects/objects of these
// relations); the true surface form is preserved in `name`.
const node = await upsertNode(pool, {
entityType: "gene",
name: name.trim(),
normalizedId,
});
nodeIds.set(normalizedId, node.id);
return node.id;
};
let edgesUpserted = 0;
for (const stmt of statements) {
const subjectId = await resolveNode(stmt.subj);
const objectId = await resolveNode(stmt.obj);
// The first (highest-status) grounded quote backs the edge provenance.
const primary = stmt.evidence[0];
await upsertEdge(pool, {
subjectId,
predicate: KG_PREDICATE_FOR_MECHANISM,
objectId,
provenance: {
source: "mechanism_assembly",
// Preserve the exact mechanistic relation + evidence count so the edge is
// self-describing and an auditor can re-derive the belief.
evidenceRef: `relation:${stmt.relation};evidence:${stmt.evidence.length}`,
groundedQuote: primary.quote,
score: stmt.belief,
},
});
edgesUpserted += 1;
}
return edgesUpserted;
}
// ---------------------------------------------------------------------------
// assembleMechanisms — the public entry point.
// ---------------------------------------------------------------------------
export async function assembleMechanisms(
input: { text: string; tier?: SourceTier },
pool: KgPool | null,
deps: MechanismDeps = defaultDeps
): Promise<MechanismAssemblyResult> {
const text = typeof input.text === "string" ? input.text : "";
const tier: SourceTier = input.tier ?? "abstract";
const empty: MechanismAssemblyResult = {
statements: [],
groundingDroppedCount: 0,
edgesUpserted: 0,
};
if (text.trim().length === 0) return empty;
// 1. Extract candidate mechanistic statements (honest-empty on LLM failure).
const candidates = await deps.extract(text).catch(() => [] as RawMechanismStatement[]);
if (candidates.length === 0) return empty;
// 2. Ground each candidate's quote; drop the ungroundable.
const grounded: GroundedCandidate[] = [];
let groundingDroppedCount = 0;
for (const candidate of candidates) {
const g = groundCandidate(candidate, text, tier);
if (g) grounded.push(g);
else groundingDroppedCount += 1;
}
// 3 + 4. Assemble into de-duplicated statements with deterministic belief.
const statements = assembleStatements(grounded);
// 5. Persist as KG edges when a pool is available. Persistence failure must not
// discard the assembled result — the statements are still valid and returnable.
let edgesUpserted = 0;
if (pool && statements.length > 0) {
edgesUpserted = await persistStatements(pool, statements).catch(() => 0);
}
return { statements, groundingDroppedCount, edgesUpserted };
}