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

210 lines
8.0 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.

// SciEval -- native TS port of MultiVerS + SciFact scientific claim verification.
//
// Faithful mapping to backend/engines/multivers:
// - data.py segments the abstract into sentences; the model scores each abstract
// sentence as a rationale candidate. We segment natively (splitAbstract) so the
// rationale space is exactly "sentences of THIS abstract".
// - model.py::decode maps the label head to {CONTRADICT, NEI, SUPPORT} and emits the
// selected rationale sentence indices. We ask Claude for the label + the rationale
// sentences (the one learned step MultiVerS trained a Longformer for), validated by Zod.
// - predict.py drops the rationale when the label is NEI. We enforce the inverse trust
// invariant too: a non-NEI label whose rationales are all ungroundable is downgraded
// to NEI -- a label we can't ground to a real abstract sentence is not asserted.
//
// Deterministic parts (segmentation, grounding, NEI logic) are native and pure; only the
// label/rationale assignment uses Claude.
import { CLAUDE_MODEL, callClaudeForJson } from "../claude";
import { locateSpan } from "../grounding";
import { retrieveSources } from "../agents/retrievalAgent";
import {
ScievalModelOutputSchema,
type GroundedRationale,
type ScievalLabel,
type ScievalOutcome,
type ScievalSourceRef,
type ScievalVerification,
} from "./schemas";
const SYSTEM = `You are a scientific claim verification model in the style of MultiVerS / SciFact.
You are given:
- CLAIM: a single scientific claim.
- ABSTRACT: the abstract of a paper, presented as a numbered list of its sentences.
Assign exactly ONE label describing how the ABSTRACT relates to the CLAIM:
- "SUPPORTS": the abstract provides evidence that the claim is true.
- "REFUTES": the abstract provides evidence that the claim is false or contradicts it.
- "NEI": not enough information; the abstract neither supports nor refutes the claim.
Then select the RATIONALE sentences: the minimal set of abstract sentences that justify your label.
Rules:
- Base the label ONLY on the ABSTRACT's content, not outside knowledge.
- For SUPPORTS or REFUTES, "rationale_sentences" MUST contain one or more sentences, each copied EXACTLY and verbatim (character-for-character) from the ABSTRACT. Do not paraphrase, merge, renumber, or add ellipses.
- For NEI, "rationale_sentences" MUST be an empty array.
- If no abstract sentence actually justifies SUPPORTS or REFUTES, label NEI instead of forcing a weak rationale.
Respond with ONLY a JSON object:
{"label": "...", "rationale_sentences": ["...", "..."], "reasoning": "..."}`;
// A sentinel that cannot occur in normal source text. splitAbstract masks the periods of
// abbreviations/decimals with it before splitting on sentence boundaries, then restores
// them -- this keeps the segmentation deterministic without a heavyweight tokenizer.
const PERIOD_SENTINEL = "";
/**
* Split an abstract into candidate rationale sentences. Deterministic, native port of
* the sentence-boundary step MultiVerS relies on (data.py uses pre-segmented abstract
* sentences). We split on sentence-final punctuation followed by whitespace + a capital
* or digit, while masking common scientific abbreviations and decimals (e.g. "0.75",
* "e.g.", "vs.", "Fig.") so they don't trigger a false split. Returns trimmed, non-empty
* sentences in order.
*/
export function splitAbstract(abstract: string): string[] {
const normalized = abstract.replace(/\s+/g, " ").trim();
if (normalized.length === 0) return [];
const ABBREV = /\b(e\.g|i\.e|vs|cf|Fig|no|approx|al|Dr|Prof|Inc|Ltd|St|resp|ca|etc)\.(?=\s)/gi;
const decimalGuarded = normalized.replace(/(\d)\.(\d)/g, `$1${PERIOD_SENTINEL}$2`);
const abbrevGuarded = decimalGuarded.replace(ABBREV, (m) => m.replace(".", PERIOD_SENTINEL));
const parts = abbrevGuarded.split(/(?<=[.!?])\s+(?=[A-Z0-9(])/);
return parts
.map((s) => s.split(PERIOD_SENTINEL).join(".").trim())
.filter((s) => s.length > 0);
}
function buildUser(claim: string, sentences: readonly string[]): string {
const numbered = sentences.map((s, i) => `${i + 1}. ${s}`).join("\n");
return [
"CLAIM:",
claim,
"",
"ABSTRACT:",
numbered,
"",
"Assign the label and select the exact rationale sentences from the ABSTRACT.",
].join("\n");
}
/**
* Ground a model's raw label + rationale sentences against the abstract, applying the
* MultiVerS-faithful trust rules. Pure and immutable (no network/LLM) so it can be
* unit-tested directly. Steps:
* 1. NEI => never carries rationales (predict.py drops them).
* 2. For SUPPORTS/REFUTES, locate each rationale sentence verbatim in the abstract via
* lib/grounding; keep the located verbatim text + offsets, DROP any that can't be found.
* 3. If a non-NEI label ends up with zero grounded rationales, DOWNGRADE to NEI.
*/
export function groundVerification(
abstract: string,
model: { label: ScievalLabel; rationale_sentences: readonly string[]; reasoning: string }
): ScievalVerification {
if (model.label === "NEI") {
return {
label: "NEI",
rationales: [],
reasoning: model.reasoning,
dropped_rationale_count: 0,
downgraded_to_nei: false,
};
}
const rationales: GroundedRationale[] = [];
let dropped = 0;
const seen = new Set<string>();
for (const candidate of model.rationale_sentences) {
const located = locateSpan(abstract, candidate);
if (!located) {
dropped += 1;
continue;
}
// Dedupe on the verbatim located text so a repeated selection isn't double-counted.
if (seen.has(located.text)) continue;
seen.add(located.text);
rationales.push({
sentence: located.text,
grounding: { status: located.status, start: located.start, end: located.end },
});
}
// A non-NEI label with no groundable supporting sentence is not asserted: downgrade to NEI.
if (rationales.length === 0) {
return {
label: "NEI",
rationales: [],
reasoning: model.reasoning,
dropped_rationale_count: dropped,
downgraded_to_nei: true,
};
}
return {
label: model.label,
rationales,
reasoning: model.reasoning,
dropped_rationale_count: dropped,
downgraded_to_nei: false,
};
}
export interface VerifyClaimInput {
claim: string;
/** Supply the abstract directly, or omit it to retrieve a cached source. */
abstract?: string;
}
/**
* Verify a claim against an abstract (MultiVerS + SciFact port).
*
* If `abstract` is omitted, retrieve the best-matching cached source's raw_text via
* retrieveSources; if none is confident, return `status: "no_source_found"` rather than
* verifying against nothing (honest "couldn't verify" over a fabricated match).
*
* Otherwise: segment the abstract, ask Claude for the label + rationale sentences
* (callClaudeForJson + Zod), then ground the rationales and apply the NEI trust rules.
*
* Throws only on infrastructure/validation failure (no Claude JSON, schema mismatch);
* the caller maps that to a user-safe error.
*/
export async function verifyClaim(input: VerifyClaimInput): Promise<ScievalOutcome> {
let abstract = input.abstract;
let source: ScievalSourceRef | undefined;
if (!abstract) {
const [best] = await retrieveSources(input.claim);
if (!best) {
return {
status: "no_source_found",
message:
"No confident source abstract was found for this claim, so it could not be verified. Provide the abstract text directly and try again.",
};
}
abstract = best.raw_text;
source = {
source_type: best.source_type,
external_id: best.external_id,
title: best.title,
url: best.url,
similarity: best.similarity,
};
}
const sentences = splitAbstract(abstract);
const raw = await callClaudeForJson({
system: SYSTEM,
user: buildUser(input.claim, sentences),
schema: ScievalModelOutputSchema,
maxTokens: 700,
});
const verification = groundVerification(abstract, raw);
return source
? { status: "verified", verification, source }
: { status: "verified", verification };
}
export { CLAUDE_MODEL };