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).
20 KiB
PaperTrail — Enterprise Architecture Blueprint
Generated by a 7-agent planning workflow (domain/product · API+data · agentic/AI · enterprise infra → synthesize → adversarial review → finalize). The build executes this wave by wave.
Targets: 133 pages · 221 API routes · 25 modules.
Vision
PaperTrail becomes an enterprise evidence-verification and research platform for life-sciences: a multi-tenant system where pharma medical-affairs, HEOR, regulatory/medical-writing, systematic-review teams, CROs, academic labs, and pharmacovigilance groups verify scientific and efficacy claims against primary sources, ingest and mine their own document corpora, and run auditable agentic research workflows. The existing deterministic core is preserved and elevated as the trust differentiator: every claim is checked against ClinicalTrials.gov structured registered results and raw event counts with code-side recomputation of ARR/NNT/RR+CI (lib/biostats.ts), multi-source cross-verification, and code-enforced exact-span grounding (lib/grounding.ts) — no AI assertion survives unless it maps to a verbatim source substring; below the similarity threshold the system returns no_support_found rather than a forced match. CRITICAL BASELINE CORRECTION (verified against the tree): the current app is NOT greenfield-auth. It already ships session auth (pt_session httpOnly JWT via jose/HS256, lib/auth/session.ts, middleware.ts guarding /console/*, /api/auth/{login,logout,register,session}), multi-tenancy (orgs, memberships[owner/admin/editor/viewer], invitations, audit_log, api_keys — every migration 0001-0009 already carries org_id), coarse RBAC (lib/authz/rbac.ts role-rank matrix + requireRole), and 39 API routes + 31 pages. Wave 1 is therefore an UPGRADE, not greenfield: session->SSO, coarse 4-role->permission matrix, add Postgres RLS (absent today), upgrade the flat audit_log to a hash-chained WORM chain, replace the in-memory single-instance rate limiter with distributed Redis, and split the sources table into a global read-only registry cache vs tenant-owned uploads. On top of that hard core sit enterprise foundations (org tenancy with RLS, RBAC permission matrix, SSO/SCIM, immutable 21 CFR Part 11-grade audit + e-signature bound to the audit chain), domain workspaces (systematic review/PRISMA, evidence library, references, publication planning, pharmacovigilance), a composable agent workflow engine bridging to Anthropic's Claude Science workbench (beta connector, no hard upstream dependency), and a commercial surface (billing/usage metering with quota-authorization BEFORE Claude spend, public API, developer portal, integrations). The result is the verification and provenance layer of record for regulated evidence work — Covidence/DistillerSR/Veeva-class capability with a deterministic adjudication engine at its center.
Personas
- Pharma medical-affairs / med-comms lead — plans publications and MLR-reviews scientific statements, each backed by a verified citation
- HEOR analyst — runs systematic literature reviews and builds evidence tables for value dossiers
- Regulatory / medical-writing specialist — needs 21 CFR Part 11 audit trail, e-signatures, and provenance for submissions
- Systematic-review methodologist — runs PRISMA-aligned dual screening, RoB 2, and GRADE synthesis
- CRO integration engineer — embeds PaperTrail verification into external pipelines via the public API and webhooks
- Academic translational researcher — verifies manuscript/grant claims against primary sources and manages references (core hackathon audience per CLAUDE.md)
- Pharmacovigilance officer — runs scheduled safety-literature monitors and triages adverse-event signals
- Organization admin — manages SSO/SCIM, members, roles, security policy, and billing for their tenant
- Platform operator (Anthropic/Gladstone staff) — cross-tenant support, audited impersonation, feature flags, and system health
Modules (by wave)
As-built note. This table is the planning blueprint (waves 1–4). The shipped platform also grew a layer of 14 Claude-heavy research features (copilot, paper-QA, synthesis, deep-research, data-chat, screening rank, full-paper extraction, hypotheses, smart-citations, drafting, knowledge graph, bring-your-own-source verify, entailment fact-check, meta cross-check) and six opt-in OSS subprocess engines (PaperQA2, STORM, ASReview, MiniCheck, PyMARE, pyalex/OpenAlex). Those are catalogued route-by-route in the README's Claude-powered capabilities and Digested OSS engines sections; the measured SciFact benchmark is in
benchmark.md.
| Wave | Module | Pages | APIs | Purpose |
|---|---|---|---|---|
| W1 | Auth & Identity | 11 | 18 | UPGRADE (not greenfield): session auth already exists (pt_session httpOnly JWT via jose/HS256 in lib/auth/sess |
| W1 | Organizations, Tenancy & RBAC | 10 | 26 | UPGRADE: orgs, memberships (owner/admin/editor/viewer), invitations already exist in 0001_foundation.sql and e |
| W1 | Projects & Workspaces | 7 | 16 | UPGRADE: projects + project_members already exist (0003_projects.sql, /api/projects, /console/projects pages). |
| W1 | Claims & Verification (Deterministic Core) | 9 | 17 | UPGRADE of the existing hard core (claims/verifications/batch already exist: 0004_claims.sql, /api/claims, /ap |
| W1 | Audit Trail, Compliance & Provenance | 6 | 11 | MOVED TO WAVE 1 (was Wave 2). A basic flat audit_log already exists (0001_foundation.sql, /api/audit, 0009). T |
| W1 | Background Jobs, Queues & Schedules | 3 | 8 | Net-new durable job/queue infrastructure for all long-running work: PDF ingestion+extraction, batch verificati |
| W1 | Account, Profile & Onboarding | 3 | 6 | Individual account surface: profile (name, role, avatar, ORCID, locale, timezone), personal access tokens, and |
| W2 | Sources, Retrieval & Evidence Search | 6 | 16 | CRITICAL DATA-MODEL FIX: split the single sources table. registry_sources (global, NO org_id, read-only cache |
| W2 | Document Ingestion & Extraction | 6 | 15 | UPGRADE: documents already exist (0005_documents.sql, /api/documents, /api/documents/upload, /console/document |
| W2 | Evidence Library & References | 10 | 18 | UPGRADE: evidence_items already exist (0006_evidence.sql, /api/evidence, /api/evidence/[id]/tags, /console/evi |
| W2 | Security, Data Isolation & Residency | 3 | 5 | Cross-cutting policy surface. NOTE: the core tenant-isolation mechanism (RLS + mandatory lib/db/tenantClient.t |
| W2 | Platform Admin & Observability | 7 | 14 | Two planes kept distinct from tenant admin: (1) cross-tenant platform-operator console for staff — tenant mana |
| W3 | Systematic Review & Screening | 10 | 15 | UPGRADE: reviews already exist (0007_reviews.sql, /api/reviews, /api/reviews/[id]/decision, /console/reviews). |
| W3 | Agentic Workflow Engine & Agent Library | 8 | 18 | Composable pipeline runtime on the Claude Agent SDK. Each workflow is a versioned DAG of typed steps (retrieve |
| W3 | Review, Collaboration & Approvals | 5 | 11 | Human review, sign-off, and dual-control across verifications, extractions, and documents: assignment queues, |
| W3 | Reporting, Exports & Analytics | 8 | 13 | UPGRADE: reports already exist (0008_reports-exports.sql, /api/reports, /dashboard). Generate/export deliverab |
| W3 | API Platform & Developer Portal | 6 | 14 | UPGRADE: api_keys already exist (0001, /api/api-keys, /api-docs, lib/apiSpec.ts). Public, versioned API (/api/ |
| W3 | Billing & Usage Metering | 5 | 9 | SPLIT from the draft's fused Billing+Notifications module (different data owners, SLAs, failure modes). Subscr |
| W3 | Notifications | 3 | 7 | SPLIT from the draft's fused Billing+Notifications module. In-app + email notifications (invites, review assig |
| W4 | Claude Science Integration | 6 | 9 | EXPLICITLY DEFERRABLE, HIGHEST-RISK Wave-4 item — the connector is Anthropic-hosted and beta (launched 2026-06 |
| W4 | MCP & Tool Registry | 3 | 5 | Governs the tools agents can call. Registers internal in-process MCP tools (verifyClaim, statAudit/biostats, g |
| W4 | Agent Evaluation & Quality | 4 | 6 | SOLE OWNER of the eval entity cluster (EvalSuite/GoldCase/EvalRun) — the Workflow Engine references but does n |
| W4 | Pharmacovigilance & Literature Monitoring | 5 | 8 | Continuous safety-literature scanning (GVP Module IX style): scheduled searches over new publications per prod |
| W4 | Publication Planning & Medical Writing | 6 | 10 | EXPLICITLY DEFERRABLE Wave-4 (sales-driven; weakest fit for the stated translational-lab hackathon audience pe |
| W4 | Integrations | 3 | 9 | Connectors to external systems life-sciences teams already use: reference managers (Zotero/EndNote), content p |
| W4 | Marketing, Docs & Trust Center | 8 | 4 | Public unauthenticated surface. NOTE (per review): the API side is a 4-endpoint CMS, NOT a full enterprise mod |
Build waves
- Wave 1 — Foundation UPGRADE (not greenfield — auth/orgs/RBAC/audit_log/api_keys/39 routes/31 pages already exist). Ship the four load-bearing corrections: (1) Postgres RLS + mandatory tenant DB client — currently absent, must precede route sprawl; (2) split registry_sources from tenant sources; (3) upgrade flat audit_log to hash-chained WORM — e-sig and every mutation depend on it; (4) distributed Redis rate limiting + durable job queue (batch verify off the request path) + quota-authorization-before-Claude in the verify path. Also: session->SSO, coarse 4-role -> permission matrix. After this wave the existing PaperTrail flow works org-scoped, RLS-isolated, authenticated, audited, quota-guarded, with batch verification off the request path.: Auth & Identity, Organizations, Tenancy & RBAC, Projects & Workspaces, Claims & Verification (Deterministic Core), Audit Trail, Compliance & Provenance, Background Jobs, Queues & Schedules, Account, Profile & Onboarding
- Wave 2 — Evidence platform + enterprise trust layer: cache/retrieval/search (registry vs org split, consolidated search endpoints), document ingestion (R2 + Docling + Claude PDF), the reusable evidence/reference library, org-facing security/isolation controls (RLS itself already shipped Wave 1), and platform admin/observability.: Sources, Retrieval & Evidence Search, Document Ingestion & Extraction, Evidence Library & References, Security, Data Isolation & Residency, Platform Admin & Observability
- Wave 3 — Research workflows + collaboration + commercialization: PRISMA systematic review, the agentic workflow engine, human review/approval with e-sign (binds to the Wave-1 audit chain), reporting/analytics, the public API/developer portal (rate limiting already shipped Wave 1), and — SPLIT — Billing & Usage Metering separate from Notifications.: Systematic Review & Screening, Agentic Workflow Engine & Agent Library, Review, Collaboration & Approvals, Reporting, Exports & Analytics, API Platform & Developer Portal, Billing & Usage Metering, Notifications
- Wave 4 — Advanced agentic + domain depth + growth surface, with explicit deferability. Claude Science bridge (highest-risk, Anthropic-hosted beta, NO hard upstream dependency) and Publication Planning (sales-driven, weakest fit for translational-lab audience) are both explicitly deferrable if the timeline slips. Plus MCP/tool governance, agent evals (sole owner of the eval entity cluster), pharmacovigilance, integrations marketplace, and the marketing/docs/trust center (a 4-endpoint CMS, not a full module).: Claude Science Integration, MCP & Tool Registry, Agent Evaluation & Quality, Pharmacovigilance & Literature Monitoring, Publication Planning & Medical Writing, Integrations, Marketing, Docs & Trust Center
Tech additions (OSS/libraries)
- Auth: WorkOS AuthKit for enterprise SSO (SAML/OIDC), SCIM directory sync, and MFA, layered ON TOP of the existing pt_session cookie + middleware.ts guard (session auth already exists — this is an upgrade, not a replacement)
- Tenant isolation (WAVE 1, CRITICAL): Postgres RLS — currently absent — via ENABLE+FORCE ROW LEVEL SECURITY on every tenant table + a mandatory lib/db/tenantClient.ts that sets SET LOCAL app.current_org per transaction and is the ONLY DB-handle path. registry_sources (global cache) split from tenant-owned sources so no permissive NULL-org carve-out is ever needed
- Job queue / durable workflows: Trigger.dev v4 (Apache-2.0, self-hostable, dedicated long-running compute, human-in-the-loop waitpoint tokens with callback URLs for review/e-sign gates). CAVEAT: warm-starts/checkpoints/auto-scaling are Cloud-only — self-hosting forgoes checkpoint/resume unless paying for Cloud
- Redis (Upstash) — WAVE 1 — for distributed rate limiting (replacing the in-memory single-instance lib/rateLimit.ts which is non-functional multi-region), token buckets per org/API key, and Trigger.dev backing store
- Object storage: Cloudflare R2 (S3-compatible) for uploaded PDF blobs, per-org KMS envelope encryption + signed expiring URLs
- PDF parsing: Docling (IBM, open-source scientific-paper layout/table/formula extraction) for deterministic parse, paired with native Claude PDF (Files API, page-level citations, 32MB/100pp limits) for cited semantic extraction
- XML/registry parsing: fast-xml-parser for PubMed E-utilities XML and ClinicalTrials.gov v2 responses
- Billing: Stripe Billing for subscriptions/seats/invoices/payments + an internal usage_events table as metering source of truth (quota authorization BEFORE expensive Claude chains — the authorize-before-Claude control ships in Wave 1). Orb/Metronome deferred until event volume warrants SQL-defined rating
- Agent orchestration: Claude Agent SDK for the workflow engine (coordinator + specialist sub-agents, tool allow-lists, MCP) and PaperTrail-as-MCP-server exposing verify/statAudit/search to Claude Science (beta connector, no hard dependency)
- Transactional email: Resend (or Postmark) for invites, assignments, job-completion, quota/PV alerts, digests — driven off the Wave-1 job queue (Notifications module, split from Billing)
- Observability: OpenTelemetry (vendor-neutral traces/metrics/logs) to OpenObserve (self-hosted, OTel-native) + Sentry for errors; privacy-preserving structured logging preserved (never log claim text or keys, extending lib/logger.ts)
- Secrets management: Doppler (or AWS Secrets Manager) with required-secret validation at startup, extending the existing .env.example discipline
- Validation: Zod remains the mandatory LLM trust boundary (lib/schemas.ts) — no raw JSON.parse of any LLM output; extended to every new agent. Advisory LLM checks (citation-qa, reviewer-agent, llm-judge) NEVER gate — deterministic lib/grounding.ts is the pass/fail gate
- Database: Postgres + pgvector on Neon retained (vector(1024) matches existing lib/embeddings.ts Voyage contract); add pg RLS policies + BM25/keyword index (pg_trgm or ParadeDB pg_search) for hybrid retrieval with reciprocal-rank fusion
- Citations: citation-js / CSL for AMA/Vancouver/APA/custom-style bibliography formatting in the References module
Core data model
- organizations (id, name, slug, region, plan_id, settings jsonb, retention_defaults, status, created_at) — EXISTING (0001_foundation.sql orgs table); tenant root. CRITICAL Wave-1 upgrade: every business table carries org_id (already true across migrations 0001-0009) AND is enforced by Postgres RLS (currently ABSENT — grep confirms no RLS): ENABLE + FORCE ROW LEVEL SECURITY, non-superuser app role, app.current_org session GUC, set only via mandatory lib/db/tenantClient.ts (the sole DB-handle path for routes)
- users (id, email unique, full_name, avatar_url, orcid, is_platform_admin, last_login_at) — EXISTING (0001 users). memberships(org_id, user_id, role) EXISTING with owner/admin/editor/viewer; Wave-1 upgrade adds role_id -> fine-grained roles/permissions
- roles (id, org_id nullable, name, is_system, template_key) + permissions (id, key catalog e.g. claims:verify) + role_permissions (role_id, permission_id) — UPGRADE of coarse lib/authz/rbac.ts rank matrix into grant-only RBAC; acl_version bumped on mutation. authz check is an in-process function, not an HTTP route
- projects (id, org_id, name, type, review_config jsonb[PICO/dual-screen], stage, status, created_by, archived_at) + project_members — EXISTING (0003_projects.sql); scopes claims/documents/reviews/reports
- registry_sources (id, source_type, external_id, title, raw_text, url, embedding vector(1024), phase, enrollment_count, registered_results jsonb, fetched_at, unique(source_type,external_id)) — GLOBAL read-only PubMed/CTgov cache, NO org_id, never RLS'd. CRITICAL FIX: split OUT from the draft's nullable-org_id sources table which was a cross-tenant leak
- sources / documents (id, org_id NOT NULL, ...) — tenant-OWNED uploaded content, RLS-forced, never co-mingled with registry_sources. Retrieval unions registry_sources + org sources at query time
- findings (id, org_id, source_id, effect_size, population, condition, endpoint, caveats jsonb, extracted_by[agent|human], unique(source_id)) — EXISTING (evidence_items in 0006_evidence.sql), extended with provenance
- claims (id, org_id, project_id, text, normalized_text, status, origin[manual|document|import|api], document_id nullable, created_by) — EXISTING (0004_claims.sql)
- verifications (id, org_id, project_id, claim_id, matched_source_id, discrepancy_type, trust_score, explanation, flagged_spans jsonb, cross_source_agreement, corroborating_source_ids jsonb, recomputed_stats jsonb[ARR/NNT/RR/CI], model, agent_run_id, status, created_by) — EXISTING core; flagged_spans map to exact source raw_text offsets
- batches (id, org_id, project_id, claim_count, status, created_by, completed_at) — EXISTING (0004); tenant-scoped, now driven by Wave-1 job queue off the request path
- documents (id, org_id, project_id, filename, mime_type, storage_key[R2], file_id[Claude Files API], page_count, sha256, status) — EXISTING (0005_documents.sql) + document_chunks(embedding vector(1024)) + extractions(kind, data jsonb, span jsonb, confidence, reviewed)
- evidence layer: collections, taggings(polymorphic), references (RIS/BibTeX/DOI/PMID), citation_styles(CSL) — extends existing evidence_items/tags
- reviews/SLR: reviews (EXISTING 0007), protocols(PICO versioned), search_strategies, screening_records + screening_decisions + screening_conflicts, extraction_forms, risk_of_bias_assessments, evidence_table_rows, prisma_counts
- agentic: workflow_templates(versioned DAG) + workflow_steps, agent_definitions + agent_versions(immutable prompt+schema+tool allow-list+eval score), agent_runs + agent_run_steps + agent_traces, mcp_tools + mcp_connectors + tool_call_audit. Eval cluster (eval_suites + gold_cases + eval_runs + drift_metric) is SOLE-OWNED by Agent Evaluation module, referenced by the engine
- science: science_connections(per-tenant MCP link + sharing scope), science_jobs, science_artifacts(code+env+query_history), hypotheses — Wave 4, no hard upstream dependency (Anthropic-hosted beta)
- collaboration/compliance: review_queue_items, review_assignments, approval_chains + approval_steps, comments(polymorphic), annotations(span-bound). audit_events — UPGRADE of EXISTING flat audit_log (0001) to append-only hash-chained WORM (prev_hash/hash, actor/action noun.verb/before_hash/after_hash/request_id, no UPDATE/DELETE) in WAVE 1; e_signatures(record_ref, signer, meaning, reason_code, manifest_hash) bind to the chain; retention_policies, legal_holds
- platform: api_keys — EXISTING (0001), hashed/prefix-indexed/scopes/rate_tier; webhook_endpoints + webhook_deliveries(HMAC-signed, retries, rotatable secret); jobs(type, payload, status, idempotency_key, attempts) + schedules(cron), idempotency_keys(org_id, key, response, 24h replay); integrations + integration_connections + integration_events
- commercial + ops: plans, subscriptions(stripe_customer_id/subscription_id), invoices, usage_events(metric, quantity, occurred_at) + quotas — metering source of truth, quota authorized BEFORE Claude chains (Wave-1 verify-path control); notifications + notification_prefs + notification_channels (split from billing); feature_flags; sso_connections; scim_tokens; security_settings; sessions(EXISTING); impersonation_sessions; leads