papertrail/.claude/workflows/builder-track.js
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

261 lines
18 KiB
JavaScript

export const meta = {
name: 'builder-track-features',
description: 'Build lab-notebook companion + clinical-trial matcher natively into PaperTrail',
phases: [
{ title: 'Build', detail: 'two Builder-Track features in parallel, disjoint files' },
{ title: 'Verify', detail: 'adversarial read-only review of each feature' },
],
}
// Shared conventions every builder must follow. Reference code in single quotes only
// (no backticks) so this script parses.
const CONV = [
'PAPERTRAIL CONVENTIONS — follow exactly; read the named reference files before writing.',
'',
'STACK: Next.js 16 App Router, TypeScript strict, React 19, Tailwind. Theme tokens: bg-paper,',
'text-ink (use text-ink/70, text-ink/40 etc for muted), text-accent, border-ink/15, bg-white cards,',
'rounded. Match the visual language of app/console/layout.tsx and app/console/hypotheses/page.tsx.',
'',
'DB: import { getPool } from "@/lib/db". Raw parameterized SQL with $1 placeholders. EVERY query on',
'a tenant table MUST filter by org_id = $1. Use gen_random_uuid() pk defaults and timestamptz',
'created_at default now(). See lib/api/handler.ts for the Ctx shape (ctx.org.id, ctx.user.id).',
'',
'MIGRATIONS: create ONLY your assigned numbered file under db/migrations/. Fully idempotent:',
'create table if not exists, create index if not exists. FK org_id references orgs(id) on delete cascade.',
'',
'API ROUTES (org-scoped): import { withOrg } from "@/lib/api/handler" and',
'import { ok, created, fail } from "@/lib/api/response". Pattern:',
' export const runtime = "nodejs";',
' export const POST = withOrg(async (req, ctx, params) => { ... });',
'Validate the JSON body with a zod schema via safeParse; on failure return fail(message, 400).',
'For writes (create/delete) call requireRole(ctx, "editor") from "@/lib/authz/rbac" (it throws an',
'RbacError that withOrg already turns into a 403 — no manual catch needed). Wrap real work in',
'try/catch and return fail("user-facing message", 500) plus console.error on failure. NEVER log the',
'raw notes / patient text — only counts, ids, and verdicts. Dynamic routes receive resolved params',
'as the 3rd arg (already awaited by withOrg): const id = params?.id.',
'',
'CLAUDE: import { callClaudeForJson } from "@/lib/claude". Call it with { system, user, schema, maxTokens }',
'where schema is a zod schema — it validates the model JSON for you and throws on mismatch. The model id',
'is configured centrally; do NOT hardcode one. Make the LLM caller injectable (opts?.llm) so logic is',
'testable offline, exactly like lib/hypotheses/generate.ts does.',
'',
'GROUNDING INVARIANT (non-negotiable): import { locateSpan } from "@/lib/grounding". Any structured',
'field that quotes the source (a note span, an eligibility criterion) MUST carry a source_span that is a',
'VERBATIM substring of the raw text. After the Claude call, run locateSpan(rawText, span) on every such',
'field; if it returns null the span is ungroundable — drop that item (or null its source_span) and COUNT',
'the drops in a droppedUngrounded number you return. PaperTrail never makes an unsourced claim about a source.',
'',
'CLIENT PAGES: "use client". Create your own _components/api.ts that reads window.localStorage',
'"pt_active_org" and sends it as the x-org-id header on every fetch — copy',
'app/console/connectors/_components/api.ts verbatim in shape. Handle loading, empty, and error states',
'explicitly. No console.log in committed code.',
'',
'QUALITY: no TODOs, no stubs — ship complete working increments. Files < 400 lines; split components.',
'Immutable updates (spread, never mutate). Explicit types on exported functions.',
].join('\n')
const FEATURES = [
{
key: 'lab-notebook',
label: 'Lab Notebook Companion',
prompt: [
'Build the LAB NOTEBOOK COMPANION feature into PaperTrail (Builder-Track: a wet-lab scientist).',
'A bench scientist pastes rough notes or a voice-memo transcript; Claude turns them into a',
'structured, reproducible, searchable experiment record with auto-tagged protocol steps, reagents,',
'samples, equipment, observations and outcomes — every quoted field grounded to a verbatim span of',
'the raw note. Records are stored org-scoped and full-text searchable.',
'',
CONV,
'',
'FIRST read these for exact patterns: lib/hypotheses/generate.ts, lib/hypotheses/schemas.ts,',
'app/api/hypotheses/route.ts, app/console/hypotheses/page.tsx, app/console/connectors/_components/api.ts,',
'lib/api/handler.ts, lib/api/response.ts, lib/grounding.ts, lib/claude.ts, and the newest migration',
'db/migrations/0058_evidence-events.sql for SQL style.',
'',
'CREATE EXACTLY THESE FILES (create no others; do NOT touch layout.tsx or any shared lib):',
'1. db/migrations/0059_lab-notebook.sql — table lab_experiments: id uuid pk default gen_random_uuid(),',
' org_id uuid not null references orgs(id) on delete cascade, created_by uuid, title text not null,',
' experiment_date date, raw_notes text not null, structured jsonb not null, tags text[] not null',
' default \'{}\', created_at timestamptz not null default now(), and a generated tsvector column',
' search (to_tsvector english over title + raw_notes) stored. GIN index on search; btree index on',
' (org_id, created_at desc). All if-not-exists / idempotent.',
'2. lib/labNotebook/schemas.ts — zod: ReagentSchema {name, vendor(nullable), catalog(nullable),',
' amount(nullable), source_span}; ProtocolStepSchema {order:number, text, source_span}; a Sample,',
' Observation and Outcome shape each with text + source_span; EntitySchema {type: enum',
' gene|protein|cell_line|reagent|organism|method|other, name}; StructuredExperimentSchema bundling',
' objective(string), protocol_steps[], reagents[], samples[], equipment string[], observations[],',
' outcomes[], next_steps string[], entities[], suggested_title, suggested_date(nullable). Also input',
' schemas for the API and a LabExperimentRecord row type + list-item type. Infer TS types from zod.',
'3. lib/labNotebook/structure.ts — export async structureExperiment(rawNotes, opts?:{llm?}):',
' Promise<{ structured, droppedUngrounded:number }>. System prompt: you structure a wet-lab',
' scientist rough bench notes into a reproducible record; every field that quotes the notes MUST',
' include source_span = a verbatim substring; never invent reagents/steps not in the notes; also',
' normalize/auto-tag entities. Use callClaudeForJson with StructuredExperimentSchema, maxTokens ~2500.',
' Then ENFORCE GROUNDING: for every item carrying source_span run locateSpan(rawNotes, span); drop',
' ungroundable items (count them). LLM caller injectable.',
'4. lib/labNotebook/repository.ts — org-scoped pg functions: createExperiment(orgId,userId,input),',
' listExperiments(orgId,{q?,limit,offset}) using websearch_to_tsquery(\'english\', $q) against the',
' search column when q is present else recent-first, getExperiment(orgId,id), deleteExperiment(orgId,id).',
' Return typed rows. Always filter org_id.',
'5. app/api/lab-notebook/structure/route.ts — POST { notes } -> withOrg, requireRole editor, validate',
' notes (1..20000 chars) -> structureExperiment -> ok({ structured, droppedUngrounded }). Never log notes.',
'6. app/api/lab-notebook/route.ts — GET list/search (?q,&page,&limit via parsePagination) returning',
' ok(items, meta) ; POST create a saved record {title, experiment_date?, raw_notes, structured, tags?}',
' -> requireRole editor -> created(record).',
'7. app/api/lab-notebook/[id]/route.ts — GET one (org-scoped) ; DELETE (editor).',
'8. app/console/lab-notebook/_components/api.ts — org-header fetch helpers (copy connectors pattern).',
'9. app/console/lab-notebook/_components/*.tsx + types.ts — Capture (textarea + Structure-with-Claude',
' button), StructuredPreview (renders the structured record; highlight grounded spans; show dropped',
' count; Save button), ExperimentList (search box + cards), ExperimentDetail. Split cleanly.',
'10. app/console/lab-notebook/page.tsx — client page composing capture -> preview -> save on the left and',
' the searchable saved-experiment list/detail on the right. Polished, theme tokens, loading/empty/error states.',
'',
'Return the list of files you created and any follow-ups. Do NOT run npm/tsc. Do NOT edit shared files.',
].join('\n'),
},
{
key: 'trial-matcher',
label: 'Clinical Trial Matcher',
prompt: [
'Build the CLINICAL TRIAL MATCHER feature into PaperTrail (Builder-Track: a research coordinator).',
'A coordinator pastes free-text, de-identified patient notes; Claude extracts a structured patient',
'profile (grounded to note spans), we query ClinicalTrials.gov for candidate trials, parse each',
'trial eligibility into inclusion/exclusion criteria, and assess EACH criterion against the profile',
'(met / not_met / unknown) with reasoning grounded to the exact criterion text — then rank trials by',
'eligibility fit. The inclusion/exclusion reasoning is shown for every match. Runs stored org-scoped.',
'',
CONV,
'',
'FIRST read these for exact patterns: lib/sources/clinicaltrials.ts (searchTrials + fetchTrialResults),',
'lib/hypotheses/generate.ts, app/api/hypotheses/route.ts, app/console/hypotheses/page.tsx,',
'app/console/connectors/_components/api.ts, lib/api/handler.ts, lib/api/response.ts, lib/grounding.ts,',
'lib/claude.ts, and db/migrations/0058_evidence-events.sql for SQL style.',
'',
'CREATE EXACTLY THESE FILES; you MAY also add ONE new exported function to',
'lib/sources/clinicaltrials.ts (do not modify its existing exports). Do NOT touch layout.tsx or any',
'other shared file. Files:',
'1. db/migrations/0060_trial-matcher.sql — table trial_match_runs: id uuid pk default gen_random_uuid(),',
' org_id uuid not null references orgs(id) on delete cascade, created_by uuid, patient_summary text',
' (short non-identifying label, e.g. primary condition), profile jsonb not null, note_char_count int,',
' created_at timestamptz default now(). Table trial_matches: id uuid pk, run_id uuid not null',
' references trial_match_runs(id) on delete cascade, nct_id text, title text, url text, phase text,',
' overall_status text, eligibility_score numeric, verdict text, criteria jsonb not null, created_at',
' timestamptz default now(). Indexes (org_id, created_at desc) and (run_id). Idempotent.',
'2. lib/sources/clinicaltrials.ts — ADD export async searchTrialsForMatching(query, pageSize=6):',
' Promise<TrialCandidate[]> where TrialCandidate = { nctId, title, url, phase, enrollmentCount,',
' overallStatus, conditions:string[], briefSummary, eligibilityCriteria (raw text), sex, minAge,',
' maxAge, healthyVolunteers }. Request the eligibility + status + conditions fields from the v2 API',
' (reuse the existing CTGOV_BASE + parsing style). Export the TrialCandidate interface.',
'3. lib/trialMatcher/schemas.ts — zod: PatientProfileSchema {age(nullable number), sex(nullable),',
' conditions:{name,source_span}[], biomarkers:{name,status(nullable),source_span}[],',
' prior_treatments:{name,source_span}[], performance_status(nullable), labs:{name,value,source_span}[],',
' other_factors:{text,source_span}[], search_terms:string[]}. CriterionAssessmentSchema {type: enum',
' inclusion|exclusion, text, source_span(nullable), assessment: enum met|not_met|unknown, reasoning}.',
' TrialMatchSchema and run/row types. Emphasize: NO identifiers (name/MRN/DOB) are ever extracted.',
'4. lib/trialMatcher/patientProfile.ts — extractPatientProfile(notes, opts?:{llm?}):',
' Promise<{profile, droppedUngrounded}>. System prompt: extract only clinically relevant, de-identified',
' facts; NEVER extract patient names, MRNs, dates of birth; every field source_span must be verbatim',
' from the notes; produce search_terms (main condition + key biomarkers) for a trial search. Enforce',
' grounding via locateSpan(notes, span); drop ungroundable (count). Injectable llm.',
'5. lib/trialMatcher/eligibility.ts — deterministic parseEligibility(raw):{inclusion:string[],',
' exclusion:string[]} splitting on Inclusion/Exclusion headings + bullets/newlines. And',
' assessTrial(profile, candidate, opts?:{llm?}): Promise<TrialMatch> — ONE Claude call per trial',
' returning a CriterionAssessment for each parsed criterion; ground each source_span against the raw',
' criteria via locateSpan (null it if ungroundable). Then DETERMINISTIC scoring (no LLM in the number):',
' inclusion met = +, exclusion that applies = disqualifying, unknown = neutral-but-flagged; compute',
' eligibility_score in 0..1 and a verdict likely_eligible | possibly_eligible | likely_ineligible |',
' unknown per clear rules you document in comments. Semantics: for exclusion criteria assessment=met',
' means the patient MEETS the exclusion => ineligible.',
'6. lib/trialMatcher/match.ts — runTrialMatch(notes, opts?:{llm?, search?}): Promise<{profile, matches,',
' droppedUngrounded}>. extractPatientProfile -> build query from search_terms ->',
' searchTrialsForMatching (cap 5 candidates) -> assess all candidates IN PARALLEL with Promise.all ->',
' sort by eligibility_score desc. search + llm injectable for offline tests.',
'7. lib/trialMatcher/repository.ts — createRun(orgId,userId,{patient_summary,profile,note_char_count,',
' matches}) inserting the run + its matches in a transaction; listRuns(orgId,{limit,offset});',
' getRun(orgId,id) returning run + matches. Always filter org_id.',
'8. app/api/trial-matcher/route.ts — export const maxDuration = 60; GET list runs; POST { notes } ->',
' withOrg, requireRole editor, validate notes (10..20000) -> runTrialMatch -> persist -> created(run).',
' Never log notes; log only counts/verdicts.',
'9. app/api/trial-matcher/[id]/route.ts — GET one run with its matches (org-scoped).',
'10. app/console/trial-matcher/_components/api.ts + *.tsx + types.ts — PatientInput (textarea + Match',
' button + de-identification reminder), ProfileCard (the extracted profile with grounded chips),',
' MatchResults (ranked trial cards; each expandable to show per-criterion inclusion/exclusion',
' reasoning with green/red/gray met|not_met|unknown chips and the quoted criterion), RunHistory.',
'11. app/console/trial-matcher/page.tsx — client page composing input -> profile -> ranked matches, plus',
' run history. Polished, theme tokens, explicit loading/empty/error states.',
'',
'Return the list of files you created and any follow-ups. Do NOT run npm/tsc. Do NOT edit layout.tsx.',
].join('\n'),
},
]
const BUILD_SCHEMA = {
type: 'object',
additionalProperties: false,
required: ['feature', 'filesCreated', 'summary'],
properties: {
feature: { type: 'string' },
filesCreated: { type: 'array', items: { type: 'string' } },
summary: { type: 'string' },
followups: { type: 'array', items: { type: 'string' } },
},
}
const VERIFY_SCHEMA = {
type: 'object',
additionalProperties: false,
required: ['feature', 'issues', 'orgScoped', 'groundingEnforced'],
properties: {
feature: { type: 'string' },
orgScoped: { type: 'boolean' },
groundingEnforced: { type: 'boolean' },
issues: {
type: 'array',
items: {
type: 'object',
additionalProperties: false,
required: ['severity', 'file', 'problem', 'suggestedFix'],
properties: {
severity: { type: 'string', enum: ['high', 'medium', 'low'] },
file: { type: 'string' },
problem: { type: 'string' },
suggestedFix: { type: 'string' },
},
},
},
},
}
phase('Build')
const results = await pipeline(
FEATURES,
(f) => agent(f.prompt, { label: 'build:' + f.key, phase: 'Build', schema: BUILD_SCHEMA }),
(built, f) =>
agent(
[
'Adversarially review the just-built PaperTrail feature "' + f.label + '".',
'Files created: ' + (built && built.filesCreated ? built.filesCreated.join(', ') : 'unknown') + '.',
'Read each file. Check specifically:',
'- Every tenant DB query filters by org_id (no cross-org leak).',
'- Writes call requireRole(ctx, "editor"); reads are session-gated via withOrg.',
'- The grounding invariant is actually enforced: locateSpan is run on every source_span and',
' ungroundable spans are dropped/counted (not trusted blindly).',
'- callClaudeForJson is used with a zod schema; no raw JSON.parse of model output is trusted.',
'- No patient/note raw text is logged.',
'- Obvious TypeScript build risks (bad imports, wrong withOrg signature, missing awaits, params usage).',
'- The migration is idempotent and numbered correctly.',
'Report concrete issues with file + suggested fix. Do not rewrite code; just review.',
].join('\n'),
{ label: 'verify:' + f.key, phase: 'Verify', agentType: 'Explore', schema: VERIFY_SCHEMA }
).then((v) => ({ feature: f.label, build: built, review: v }))
)
const highIssues = results
.filter(Boolean)
.flatMap((r) => (r.review && r.review.issues ? r.review.issues : []).map((i) => ({ ...i, feature: r.feature })))
.filter((i) => i.severity === 'high')
log('Build complete. ' + results.filter(Boolean).length + ' features; ' + highIssues.length + ' high-severity issues to fix.')
return { results: results.filter(Boolean), highIssues }