Automating ADSL Generation with AI Agents and the Pharmaverse
Jaime Yan · jaimeyan.com
R/Pharma 2026 · October 21
The Problem Everyone Knows
ADSL Programming
49 variables from 8+ SDTM domains(CDISCPilot01 ADSL — the FDA public pilot submission; same spec used throughout this talk)
Cross-domain joins, date imputation, flag derivations
Days to weeks per study, plus QC cycles
Every study repeats this work
Source Domains for ADSL (core 5 shown)
Domain
Variables
DM
SUBJID, ARM, RFSTDTC…
EX
EXSTDTC, EXENDTC…
DS
DSDECOD, DSSTDTC…
MH
MHTERM, MHSTDTC…
VS
VSTESTCD, VSSTRESN…
And all of it under GxP (good-practice regulations) — every derivation reviewable, every decision auditable. So “just let the AI write the code” was never an option — but “never use AI” wasn’t either.
What GxP asks of this work
Not accuracy alone — the process must stand up to inspection:
Pillar
What it means for ADSL programming
Reproducible
same spec + same data → same dataset, every run
Traceable
every variable back to its spec sentence and source data
Auditable
time-stamped, tamper-evident record of every action
Human-accountable
a named person reviews and owns the output
These are standing expectations, not new ones — scan for the primary sources:
21 CFR Part 11 §11.10(e) · ICH E6(R3) 2025 · FDA AI draft 2025 · EMA AI reflection 2024
It’s Not the Model
A working agent = model + harness + context. Same task, same frontier models — only the harness + context changes:
harness = pipeline, prompts, validation gates · context = the closed vocabulary and evidence the model is given
Harness + context around the model
Best result
Single-shot prompt (5 models, 16 attempts)
0%
Flat multi-step
0%
Keyword retrieval (RAG)
59.2%
Structured pipeline + validation gates
84–100%
coverage vs CDISCPilot01 ADSL, best per configuration
The models did not get smarter between rows. The leverage is in the harness and the context — so that is what we engineer. But an 84–100% draft is still just a draft — what GxP inspects is the process around it. So the real question: what should the harness be?
Two published routes — and what each leaves open
Route
What it proved
What it leaves open
Scan
Augment the agent — ClinAgent, Biology Methods & Protocols 2026
9 clinical-programming skills for general coding agents · validated over 11 ADaM domains · deterministic checks at 100% precision
prompt-written derivations: 72.1% · a chat transcript is not an inspectable process
Encode the process — GxP-Agent prototype, arXiv preprint 2026
regulatory ordering encoded as a DAG — 15 nodes, validation gates · 84–100% coverage where single-shot scores 0%
bespoke research pipeline — per-study setup, and the LLM still writes the code
One route lacks a governed process; the other lacks a product. So where should the compliance live?
Clinical trial programming is a compliance task, not a creativity task.
GxP regulates the work process, not the model — reviewable steps, auditable decisions. So compliance must live in the harness: a GxP agent = model + harness (the GxP layer) + context — and the AI should not write code at all:
Let the model translate the spec into a closed, reviewable vocabulary. Let deterministic code do the generating.
GxP-Agent is admiralagent
The GxP layer, as one package — routing + GxP workflow, one agent, two stages:
v0 · research prototype
15-step pipeline, agents write R per step
Validation gates catch errors after each step
84–100% variable coverage (CDISCPilot01)
Proved: structure beats model size — every failure traced back to free-form code generation
v1 · installable R package
The constraint: the LLM never writes code
LLM only translates spec → Layer IR (intermediate representation: one typed record per variable, closed vocabulary)
Deterministic compiler emits admiral code
Every output: # CHECK: comments, provenance sidecar, hash-chained audit
Rules backend: full pipeline offline, zero LLM
Codegen verified once at package level — 42 files · 398 blocks
admiralagent is GxP-Agent, productized — GitHub + r-universe today, CRAN submission in preparation.
How admiralagent works
Five tasks, one package — what it does:
Spec matching — spec text → closed Layer IR (intermediate representation; rules backend; optional LLM translate, gated)
%%{init: {'theme': 'neutral', 'themeVariables': {'fontSize': '14px'}}}%%
flowchart LR
A["Spec source text<br/>(verbatim)"] --> B["Layer IR<br/>15 registered layer types"]
C["LLM (optional)"] -.->|translate only| B
R["rules backend<br/>(deterministic)"] --> B
B --> D{{"validate_ir()<br/>shape + semantics + cycles"}}
D -->|invalid| H["needs_human<br/>no code generated"]
D -->|valid| E["Compiler<br/>admiral R + CHECK"]
E --> F["Artifact + sidecar<br/>hash-chained audit"]
style B fill:#fff3e0
style D fill:#fce4ec
style H fill:#f5f5f5
style F fill:#e8f5e9
How routing works — computed, not declared
admiralagent computes the routing plan deterministically from the spec’s own lineage — not by an LLM, not wired by hand (real pilot1 spec, 49 variables):
%%{init: {'theme': 'neutral', 'themeVariables': {'fontSize': '14px'}}}%%
flowchart LR
S["pilot1 spec<br/>49 variables"] --> R["routing_plan()<br/>deterministic · lineage → waves"]
R --> W0["WAVE 0 · 13 vars<br/>STUDYID · ARM · RFSTDTC …"]
W0 --> W1["WAVE 1 · 3 vars<br/>TRT01P ← ARM …"]
W1 --> W2["WAVE 2 · 1 var<br/>TRT01A ← TRT01P"]
R --> H["HUMAN LANE · 32<br/>what rules cannot express"]
style R fill:#fff3e0
style H fill:#f5f5f5
style W2 fill:#e8f5e9
LLM sits upstream only (optional spec → IR); routing never touches a model
Execution order is a reviewable artifact before anything runs — the auditability GxP demands: compliant by design
Cyclic specs are refused by validate_ir() — never silently reordered
The 32 variables rules can’t express go explicitly to humans — every decision auditable
One variable’s journey — TRT01A
Same system, zoomed to a single variable. Every step leaves an artifact someone can inspect:
Step
Who
Artifact left behind
GxP purpose
Spec sentence read verbatim
package (metacore)
spec_origin link
traceability to source text
Translated to Layer IR
rules (or LLM, gated)
one typed IR record
reviewable intermediate
validate_ir() gate
package
pass / refuse event
refusal enforced
routing_plan() assignment
package
wave 2 of the plan
execution order reviewed pre-run
Deterministic compile
package
admiral R draft + # CHECK:
reproducible generation
Provenance + audit
package
sidecar + hash-chained log
tamper-evident audit trail
Review & approve
human
approval event
accountability — a named owner
Why this stands up in an inspection: FDA 21 CFR Part 11 §11.10(e) · ICH E6(R3) 2025 · FDA AI draft guidance 2025 · EMA AI reflection paper 2024 — they set the bar; these artifacts answer it.
What it actually looks like — one spec row, end to end
Real pilot1 spec row, quoted verbatim:
TRT01A · “Actual Treatment for Period 01” · origin = derived · derivation: “TRT01A=TRT01P, i.e., no difference between actual and randomized treatment in this study.”
→ Layer IR record (7 fields, hash-pinned)
{"steps":[{"layer":"assign","args":{"from":"TRT01P","target":"TRT01A"}}],"spec_origin":"TRT01A=TRT01P, i.e., no difference …","confidence":1,"needs_human":false}
Rules vs LLM — disagreement escalates, weak models refused
Case 04: rules and deepseek-chat translate the same spec independently → 70% full-semantics agreement; on TRTSDTM/TRTEDTM/BMIBL the LLM abstained — all three went to the human lane
Case 06: the candidate model scored 0.500 on the prespecified test suite (floor: 0.600) → REJECTED; layer-sequence-only comparison gave a flattering 0.700 — shallow metrics mislead. The refusal is the feature.
agreement corroborates, never proves
Results
Same agent, evidence at two stages:
Stage 1 · prototype (CDISCPilot01)
Five design iterations, 0% → 100% — re-runs: 84–100% · 4/6 Claude runs: 100% match · 254/254 records
Stage 2 · admiralagent (today, public evidence)
Real pilot1 spec, rules backend, scored against the oracle — the actually submitted pilot1 adsl.xpt, i.e. the ground-truth answer key:
17 routed to waves · 16 executed end-to-end — 1 runtime error, visible in the evidence
14 of the 16 match the oracle 100%
32 visibly routed to human review · every number recomputed from machine-generated evidence
Who Does What
The actors
Actor
Does
Never does
Human
reviews IR + CHECK, edits IR, owns the human lane
—
LLM (optional)
translates spec → Layer IR; gated and cross-checked
derivation functions the draft calls — runs when you execute the reviewed draft
metacore / metatools
spec reading, metadata
xportr
XPT export
pharmaversesdtm / pharmaverseadam
pilot data + oracle
Not replacing programmers — routing work to them: drafts with evidence, governed model choice, fail-closed everywhere. admiralagent is a consumer of pharmaverse, not a competitor — pure R, LLM optional (ellmer).
Claude models: 100% on every node; failures concentrate in derive_disposition / derive_completion (GPT-4.1) and downstream cascade nodes (GPT-4o, Gemini)
Dominant failure classes: variable hallucination, function-signature drift, wrong file references — all eliminated by closed-vocabulary IR
Cost per full ADSL run: a few US dollars (frontier model); rules backend: $0
Backup: dual-backend and acceptance details
Fingerprints (hashes of each IR record) compare canonical semantics: registry defaults filled, temporary names standardized, expressions normalized through the R parser
classify_variables_dual(): agree → adopt rules IR; any divergence → needs_human, LLM candidate preserved for review, hash-only audit event
accept_model(): thresholds are required arguments — acceptance criteria must be prespecified by the deploying organization
Agreement is corroboration, not correctness; oracle comparison is the correctness check
Backup: rules-only vs LLM-assisted — same gates, wider coverage
Rules backend (zero LLM, offline)
Full pipeline, no model: spec text → metacore → rules → closed IR → validate_ir() → routing_plan() → compile
Demo cases 01–03 run entirely on rules
Real pilot1 spec: 17 routed · 16 executed · 14 match the oracle (submitted adsl.xpt) 100%
+ LLM: coverage changes, constraints don’t
Same closed IR output space, same validate_ir() gate
build_context() sends schema + spec text only — never data rows
Backup: where GxP lives in the workflow
Workflow step
GxP property
Spec input
spec_origin — verbatim traceability to source text
validate_ir() gate
Invalid IR refused, never repaired silently — fail-closed
Approval gate
On by default (AA_GATE_REQUIRED_DEFAULT); bypassed output self-labels UNGATED DRAFT
Sidecar + hash-chained audit log
Tamper-evident provenance; verify_log() walks the chain
accept_model()
Thresholds are required arguments — acceptance criteria prespecified
Human lane
needs_human is explicit (32/49) — abstain, never fabricate
The archived artifact of record is the IR itself; every generated draft carries a mandatory DISCLAIMER header — human review required before submission.
Backup: what the spec looks like — one row, end to end
Input: any flat spec with 6 required columns (dataset, variable, label, type, origin, derivation) — or read define.xml (read_define()) and P21-style workbooks (read_spec()) directly. Real pilot1 row:
TRT01A · “Actual Treatment for Period 01” · origin = derived · derivation: “TRT01A=TRT01P, i.e., no difference between actual and randomized treatment in this study.”
→ Layer IR record (7 fields, hash-pinned)
{"steps":[{"layer":"assign","args":{"from":"TRT01P","target":"TRT01A"}}],"spec_origin":"TRT01A=TRT01P, i.e., no difference …","confidence":1,"needs_human":false}
# CHECK: target variable must not be# all-missing after the derivationADSL <- ADSL |> dplyr::mutate(TRT01A = TRT01P)
LLM path, when used, receives only these schema fields — never data rows (build_context()).
Backup: the rules engine — mechanics and robustness
How it works
Fixed-precedence keyword/regex chain over the lowercased spec text, first match wins — patterns are ADaM derivation idioms as written in real CDISC specs (TRT01A=TRT01P → assign)
Emits only the 15 registered layer types, each mapped 1:1 to an admiral/metatools function — hand-written, not learned
No match → abstain: needs_human, empty steps, no code generated (“no matching pattern, routed to human review”)
Pure function, zero deps, offline: same spec → same IR → same code
Strengths & honest limits
Fail-closed by design: 32/49 abstained — safety property, not weakness
42 test files · 398 test blocks · 26-case public evals (rules must score 1.0)
Oracle-verified: 14 of 16 executed match pilot1 adsl.xpt 100%
CI: R CMD check --as-cran (warnings fail) · ubuntu + windows
Honest limits: keyword-fragile; vocabulary holes → humans by design
Backup: how the IR is computed — two paths, one gate
Rules path (default, offline)
Lowercase the origin + derivation text
Fixed-precedence keyword/regex chain — first match wins
Emit steps in the 15-layer registry
No match → abstain (needs_human, no code)
LLM path (optional, gated)
build_context() — schema fields only, never data rows
System prompt pins the layer vocabulary + strict JSON contract + abstention rules
Candidate IR → align_batch() — dataset/variable tokens must match exactly
Dual mode: cross-checked vs rules — divergence → human
Both paths emit the same 7-field record — dataset · variable · steps[] · spec_origin · confidence · needs_human · rationale — hash-pinned (ir_hash), human-editable, and refused by the same validate_ir() if invalid.
library(ellmer) # key stays in env var (DEEPSEEK_API_KEY, ...)chat <-chat_deepseek(model ="deepseek-chat")# or chat_openai() / chat_anthropic()# pre-deployment gate; thresholds are required argumentsaccept_model(chat, min_eval_accuracy =0.6,min_full_agreement =0.5) # case 06: REJECTED# either LLM path — same closed IR, same validate_ir() gateir <-classify_variables(spec, "ADSL", backend ="llm", chat = chat)ir <-classify_variables_dual(spec, "ADSL", chat = chat) # cross-check
The model receives schema + spec text only — never data rows (build_context()). Every output still carries # CHECK: comments, a provenance sidecar, and the hash-chained audit log.
Backup: the augmented general-agent route — ClinAgent, in print