Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Redesign clinical decision support safety

Timothy Kassis820bcb8ee3da
diff --git a/skills/clinical-decision-support/SKILL.md b/skills/clinical-decision-support/SKILL.md
index a323c584..f2b49c8c 100644
--- a/skills/clinical-decision-support/SKILL.md
+++ b/skills/clinical-decision-support/SKILL.md
@@ -1,509 +1,238 @@
---
name: clinical-decision-support
-description: Generate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
-allowed-tools: Read Write Edit Bash
-license: MIT License
-required_environment_variables: [{"name": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key for the skill's LLM-powered steps.", "required_for": "optional features"}]
-metadata: {"version": "1.2", "skill-author": "K-Dense Inc.", "openclaw": {"primaryEnv": "OPENROUTER_API_KEY", "envVars": [{"name": "OPENROUTER_API_KEY", "required": false, "description": "OpenRouter API key for the skill's LLM-powered steps."}]}}
+description: Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.
+license: MIT
+compatibility: Python 3.11+; local files only; bundled scripts use the standard library and require no network, credentials, API keys, LLMs, or image services.
+metadata:
+ version: "2.0"
+ skill-author: K-Dense Inc.
---
-# Clinical Decision Support Documents
+# Clinical Decision-Support Research and Evaluation
-## Description
+## Hard Safety Boundary
-Generate professional clinical decision support (CDS) documents for pharmaceutical companies, clinical researchers, and medical decision-makers. This skill specializes in analytical, evidence-based documents that inform treatment strategies and drug development:
+This skill produces **research, evaluation, documentation, and governance artifacts only**.
-1. **Patient Cohort Analysis** - Biomarker-stratified group analyses with statistical outcome comparisons
-2. **Treatment Recommendation Reports** - Evidence-based clinical guidelines with GRADE grading and decision algorithms
+Never use it to:
-All documents are generated as publication-ready LaTeX/PDF files optimized for pharmaceutical research, regulatory submissions, and clinical guideline development.
+- diagnose or classify a person;
+- recommend, select, sequence, start, stop, or modify treatment;
+- calculate or communicate a patient-specific dose;
+- triage, prioritize, alarm, alert, or determine urgency;
+- make or automate a patient-specific clinical decision;
+- support bedside, point-of-care, or live clinical operation;
+- replace professional judgment or a validated, authorized clinical system;
+- claim FDA authorization, regulatory conformity, HIPAA compliance, or legal compliance.
-**Note:** For individual patient treatment plans at the bedside, use the `treatment-plans` skill instead. This skill focuses on group-level analyses and evidence synthesis for pharmaceutical/research settings.
+If a request could affect care for a person, stop the workflow and route the matter to a licensed healthcare professional using locally validated and appropriately authorized systems. Do not redirect to another skill for patient-specific care.
-**Writing Style:** For publication-ready documents targeting medical journals, consult the **venue-templates** skill's `medical_journal_styles.md` for guidance on structured abstracts, evidence language, and CONSORT/STROBE compliance.
+## In Scope
-## Capabilities
+- Intended-use and limitation statements for research artifacts
+- Aggregate cohort table shells with disclosure controls
+- Statistical analysis plans and survival-analysis plan review
+- Aggregate model or biomarker performance evaluation
+- Transparent GRADE evidence-profile checklists
+- Evidence-source and decision-logic traceability
+- De-identification process checklists
+- Fairness, subgroup, calibration, uncertainty, external-validation, monitoring, change-control, audit, and human-factors documentation
-### Document Types
+Outputs remain drafts until qualified humans approve them. Reporting guidance improves transparency; it does not establish study quality, clinical utility, safety, effectiveness, authorization, or compliance.
-**Patient Cohort Analysis**
-- Biomarker-based patient stratification (molecular subtypes, gene expression, IHC)
-- Molecular subtype classification (e.g., GBM mesenchymal-immune-active vs proneural, breast cancer subtypes)
-- Outcome metrics with statistical analysis (OS, PFS, ORR, DOR, DCR)
-- Statistical comparisons between subgroups (hazard ratios, p-values, 95% CI)
-- Survival analysis with Kaplan-Meier curves and log-rank tests
-- Efficacy tables and waterfall plots
-- Comparative effectiveness analyses
-- Pharmaceutical cohort reporting (trial subgroups, real-world evidence)
+## Data Gate
-**Treatment Recommendation Reports**
-- Evidence-based treatment guidelines for specific disease states
-- Strength of recommendation grading (GRADE system: 1A, 1B, 2A, 2B, 2C)
-- Quality of evidence assessment (high, moderate, low, very low)
-- Treatment algorithm flowcharts with TikZ diagrams
-- Line-of-therapy sequencing based on biomarkers
-- Decision pathways with clinical and molecular criteria
-- Pharmaceutical strategy documents
-- Clinical guideline development for medical societies
+Before any script:
-### Clinical Features
+1. Confirm input is synthetic or aggregate.
+2. Reject patient rows, records, narratives, identifiers, free text, dates tied to people, images, waveforms, or genomic sequences.
+3. Keep source files local. Do not fetch URLs, call APIs, read environment variables, or send data to a model.
+4. Set disclosure thresholds before producing tables.
+5. Record provenance, data cut date, population, exclusions, missingness, and transformations.
-- **Biomarker Integration**: Genomic alterations (mutations, CNV, fusions), gene expression signatures, IHC markers, PD-L1 scoring
-- **Statistical Analysis**: Hazard ratios, p-values, confidence intervals, survival curves, Cox regression, log-rank tests
-- **Evidence Grading**: GRADE system (1A/1B/2A/2B/2C), Oxford CEBM levels, quality of evidence assessment
-- **Clinical Terminology**: SNOMED-CT, LOINC, proper medical nomenclature, trial nomenclature
-- **Regulatory Compliance**: HIPAA de-identification, confidentiality headers, ICH-GCP alignment
-- **Professional Formatting**: Compact 0.5in margins, color-coded recommendations, publication-ready, suitable for regulatory submissions
+The scripts cap file size, groups, rows, and text length. They reject URL-like paths and common row-level keys. These controls reduce accidental misuse; they are not a privacy determination.
-## Pharmaceutical and Research Use Cases
+## Required Artifact Header
-This skill is specifically designed for pharmaceutical and clinical research applications:
+Every artifact must visibly include:
-**Drug Development**
-- **Phase 2/3 Trial Analyses**: Biomarker-stratified efficacy and safety analyses
-- **Subgroup Analyses**: Forest plots showing treatment effects across patient subgroups
-- **Companion Diagnostic Development**: Linking biomarkers to drug response
-- **Regulatory Submissions**: IND/NDA documentation with evidence summaries
+- `artifact_type`, title, version, status, owner, date, and change summary;
+- intended purpose, intended users, aggregate population scope, and decision role;
+- all prohibited uses from the hard boundary;
+- data level and confirmation that no PHI or raw rows were supplied;
+- limitations, uncertainty, and foreseeable failure modes;
+- external-validation and subgroup applicability status;
+- human-review roles, completion status, and approval boundary;
+- source citations with versions or dates;
+- monitoring, change-control, retirement, and audit expectations;
+- the statement: **Not for patient care or live clinical use.**
-**Medical Affairs**
-- **KOL Education Materials**: Evidence-based treatment algorithms for thought leaders
-- **Medical Strategy Documents**: Competitive landscape and positioning strategies
-- **Advisory Board Materials**: Cohort analyses and treatment recommendation frameworks
-- **Publication Planning**: Manuscript-ready analyses for peer-reviewed journals
+Start from `assets/artifact_intended_use_template.json`.
-**Clinical Guidelines**
-- **Guideline Development**: Evidence synthesis with GRADE methodology for specialty societies
-- **Consensus Recommendations**: Multi-stakeholder treatment algorithm development
-- **Practice Standards**: Biomarker-based treatment selection criteria
-- **Quality Measures**: Evidence-based performance metrics
+## Workflow
-**Real-World Evidence**
-- **RWE Cohort Studies**: Retrospective analyses of patient cohorts from EMR data
-- **Comparative Effectiveness**: Head-to-head treatment comparisons in real-world settings
-- **Outcomes Research**: Long-term survival and safety in clinical practice
-- **Health Economics**: Cost-effectiveness analyses by biomarker subgroup
+### 1. Frame the Research Question
-## When to Use
+- Define the estimand or evaluation target before viewing results.
+- Distinguish descriptive, prognostic, predictive, diagnostic-accuracy, and causal questions.
+- Pre-specify outcomes, time origin, horizon, subgroups, cut points, missing-data handling, multiplicity, and sensitivity analyses.
+- Separate exploratory findings from confirmatory analyses.
-Use this skill when you need to:
+### 2. Select the Artifact
-- **Analyze patient cohorts** stratified by biomarkers, molecular subtypes, or clinical characteristics
-- **Generate treatment recommendation reports** with evidence grading for clinical guidelines or pharmaceutical strategies
-- **Compare outcomes** between patient subgroups with statistical analysis (survival, response rates, hazard ratios)
-- **Produce pharmaceutical research documents** for drug development, clinical trials, or regulatory submissions
-- **Develop clinical practice guidelines** with GRADE evidence grading and decision algorithms
-- **Document biomarker-guided therapy selection** at the population level (not individual patients)
-- **Synthesize evidence** from multiple trials or real-world data sources
-- **Create clinical decision algorithms** with flowcharts for treatment sequencing
+| Need | Asset | Script |
+|---|---|---|
+| Intended-use/governance review | `assets/artifact_intended_use_template.json` | `scripts/validate_cds_artifact.py` |
+| GRADE evidence profile | `assets/evidence_profile_template.json` | `scripts/evidence_profile_check.py` |
+| Aggregate model/biomarker evaluation | `assets/aggregate_model_evaluation_template.json` | `scripts/model_biomarker_evaluation.py` |
+| Aggregate cohort table | `assets/aggregate_cohort_table_template.json` | `scripts/cohort_table_generator.py` |
+| Survival analysis plan | `assets/survival_analysis_plan_template.json` | `scripts/survival_plan_validator.py` |
+| Logic traceability matrix | `assets/decision_logic_traceability_template.json` | `scripts/decision_logic_traceability.py` |
+| De-identification process review | `assets/deidentification_checklist_template.json` | `scripts/deidentification_checklist.py` |
-**Do NOT use this skill for:**
-- Individual patient treatment plans (use `treatment-plans` skill)
-- Bedside clinical care documentation (use `treatment-plans` skill)
-- Simple patient-specific treatment protocols (use `treatment-plans` skill)
+### 3. Run Locally
-## Visual Enhancement with Scientific Schematics
+All helpers are dependency-free:
-**⚠️ MANDATORY: Every clinical decision support document MUST include at least 1-2 AI-generated figures using the scientific-schematics skill.**
-
-This is not optional. Clinical decision documents require clear visual algorithms. Before finalizing any document:
-1. Generate at minimum ONE schematic or diagram (e.g., clinical decision algorithm, treatment pathway, or biomarker stratification tree)
-2. For cohort analyses: include patient flow diagram
-3. For treatment recommendations: include decision flowchart
-
-**How to generate figures:**
-- Use the **scientific-schematics** skill to generate AI-powered publication-quality diagrams
-- Simply describe your desired diagram in natural language
-- Nano Banana Pro will automatically generate, review, and refine the schematic
-
-**How to generate schematics:**
```bash
-python scripts/generate_schematic.py "your diagram description" -o figures/output.png
+python3 scripts/validate_cds_artifact.py --help
+python3 scripts/evidence_profile_check.py --help
+python3 scripts/model_biomarker_evaluation.py --help
+python3 scripts/cohort_table_generator.py --help
+python3 scripts/survival_plan_validator.py --help
+python3 scripts/decision_logic_traceability.py --help
+python3 scripts/deidentification_checklist.py --help
```
-The AI will automatically:
-- Create publication-quality images with proper formatting
-- Review and refine through multiple iterations
-- Ensure accessibility (colorblind-friendly, high contrast)
-- Save outputs in the figures/ directory
+Write outputs only to a reviewed local directory. Never place generated reports in an EHR, alerting system, clinical portal, or device workflow.
-**When to add schematics:**
-- Clinical decision algorithm flowcharts
-- Treatment pathway diagrams
-- Biomarker stratification trees
-- Patient cohort flow diagrams (CONSORT-style)
-- Survival curve visualizations
-- Molecular mechanism diagrams
-- Any complex concept that benefits from visualization
+### 4. Human Review
-For detailed guidance on creating schematics, refer to the scientific-schematics skill documentation.
+Require review proportionate to the artifact:
----
+- methodologist/statistician for design and analysis;
+- domain expert for clinical-scientific context;
+- privacy officer or qualified expert for disclosure decisions;
+- regulatory or legal counsel for jurisdiction-specific interpretations;
+- human-factors specialist for user studies;
+- authorized governance owner for release and change control.
-## Document Structure
-
-**CRITICAL REQUIREMENT: All clinical decision support documents MUST begin with a complete executive summary on page 1 that spans the entire first page before any table of contents or detailed sections.**
-
-### Page 1 Executive Summary Structure
-
-The first page of every CDS document should contain ONLY the executive summary with the following components:
-
-**Required Elements (all on page 1):**
-1. **Document Title and Type**
- - Main title (e.g., "Biomarker-Stratified Cohort Analysis" or "Evidence-Based Treatment Recommendations")
- - Subtitle with disease state and focus
-
-2. **Report Information Box** (using colored tcolorbox)
- - Document type and purpose
- - Date of analysis/report
- - Disease state and patient population
- - Author/institution (if applicable)
- - Analysis framework or methodology
-
-3. **Key Findings Boxes** (3-5 colored boxes using tcolorbox)
- - **Primary Results** (blue box): Main efficacy/outcome findings
- - **Biomarker Insights** (green box): Key molecular subtype findings
- - **Clinical Implications** (yellow/orange box): Actionable treatment implications
- - **Statistical Summary** (gray box): Hazard ratios, p-values, key statistics
- - **Safety Highlights** (red box, if applicable): Critical adverse events or warnings
-
-**Visual Requirements:**
-- Use `\thispagestyle{empty}` to remove page numbers from page 1
-- All content must fit on page 1 (before `\newpage`)
-- Use colored tcolorbox environments with different colors for visual hierarchy
-- Boxes should be scannable and highlight most critical information
-- Use bullet points, not narrative paragraphs
-- End page 1 with `\newpage` before table of contents or detailed sections
-
-**Example First Page LaTeX Structure:**
-```latex
-\maketitle
-\thispagestyle{empty}
-
-% Report Information Box
-\begin{tcolorbox}[colback=blue!5!white, colframe=blue!75!black, title=Report Information]
-\textbf{Document Type:} Patient Cohort Analysis\\
-\textbf{Disease State:} HER2-Positive Metastatic Breast Cancer\\
-\textbf{Analysis Date:} \today\\
-\textbf{Population:} 60 patients, biomarker-stratified by HR status
-\end{tcolorbox}
-
-\vspace{0.3cm}
-
-% Key Finding #1: Primary Results
-\begin{tcolorbox}[colback=blue!5!white, colframe=blue!75!black, title=Primary Efficacy Results]
-\begin{itemize}
- \item Overall ORR: 72\% (95\% CI: 59-83\%)
- \item Median PFS: 18.5 months (95\% CI: 14.2-22.8)
- \item Median OS: 35.2 months (95\% CI: 28.1-NR)
-\end{itemize}
-\end{tcolorbox}
-
-\vspace{0.3cm}
-
-% Key Finding #2: Biomarker Insights
-\begin{tcolorbox}[colback=green!5!white, colframe=green!75!black, title=Biomarker Stratification Findings]
-\begin{itemize}
- \item HR+/HER2+: ORR 68\%, median PFS 16.2 months
- \item HR-/HER2+: ORR 78\%, median PFS 22.1 months
- \item HR status significantly associated with outcomes (p=0.041)
-\end{itemize}
-\end{tcolorbox}
-
-\vspace{0.3cm}
-
-% Key Finding #3: Clinical Implications
-\begin{tcolorbox}[colback=orange!5!white, colframe=orange!75!black, title=Clinical Recommendations]
-\begin{itemize}
- \item Strong efficacy observed regardless of HR status (Grade 1A)
- \item HR-/HER2+ patients showed numerically superior outcomes
- \item Treatment recommended for all HER2+ MBC patients
-\end{itemize}
-\end{tcolorbox}
-
-\newpage
-\tableofcontents % TOC on page 2
-\newpage % Detailed content starts page 3
-```
+Script success means only that declared fields and internal consistency checks passed.
-### Patient Cohort Analysis (Detailed Sections - Page 3+)
-- **Cohort Characteristics**: Demographics, baseline features, patient selection criteria
-- **Biomarker Stratification**: Molecular subtypes, genomic alterations, IHC profiles
-- **Treatment Exposure**: Therapies received, dosing, treatment duration by subgroup
-- **Outcome Analysis**: Response rates (ORR, DCR), survival data (OS, PFS), DOR
-- **Statistical Methods**: Kaplan-Meier survival curves, hazard ratios, log-rank tests, Cox regression
-- **Subgroup Comparisons**: Biomarker-stratified efficacy, forest plots, statistical significance
-- **Safety Profile**: Adverse events by subgroup, dose modifications, discontinuations
-- **Clinical Recommendations**: Treatment implications based on biomarker profiles
-- **Figures**: Waterfall plots, swimmer plots, survival curves, forest plots
-- **Tables**: Demographics table, biomarker frequency, outcomes by subgroup
-
-### Treatment Recommendation Reports (Detailed Sections - Page 3+)
-
-**Page 1 Executive Summary for Treatment Recommendations should include:**
-1. **Report Information Box**: Disease state, guideline version/date, target population
-2. **Key Recommendations Box** (green): Top 3-5 GRADE-graded recommendations by line of therapy
-3. **Biomarker Decision Criteria Box** (blue): Key molecular markers influencing treatment selection
-4. **Evidence Summary Box** (gray): Major trials supporting recommendations (e.g., KEYNOTE-189, FLAURA)
-5. **Critical Monitoring Box** (orange/red): Essential safety monitoring requirements
-
-**Detailed Sections (Page 3+):**
-- **Clinical Context**: Disease state, epidemiology, current treatment landscape
-- **Target Population**: Patient characteristics, biomarker criteria, staging
-- **Evidence Review**: Systematic literature synthesis, guideline summary, trial data
-- **Treatment Options**: Available therapies with mechanism of action
-- **Evidence Grading**: GRADE assessment for each recommendation (1A, 1B, 2A, 2B, 2C)
-- **Recommendations by Line**: First-line, second-line, subsequent therapies
-- **Biomarker-Guided Selection**: Decision criteria based on molecular profiles
-- **Treatment Algorithms**: TikZ flowcharts showing decision pathways
-- **Monitoring Protocol**: Safety assessments, efficacy monitoring, dose modifications
-- **Special Populations**: Elderly, renal/hepatic impairment, comorbidities
-- **References**: Full bibliography with trial names and citations
-
-## Output Format
-
-**MANDATORY FIRST PAGE REQUIREMENT:**
-- **Page 1**: Full-page executive summary with 3-5 colored tcolorbox elements
-- **Page 2**: Table of contents (optional)
-- **Page 3+**: Detailed sections with methods, results, figures, tables
-
-**Document Specifications:**
-- **Primary**: LaTeX/PDF with 0.5in margins for compact, data-dense presentation
-- **Length**: Typically 5-15 pages (1 page executive summary + 4-14 pages detailed content)
-- **Style**: Publication-ready, pharmaceutical-grade, suitable for regulatory submissions
-- **First Page**: Always a complete executive summary spanning entire page 1 (see Document Structure section)
-
-**Visual Elements:**
-- **Colors**:
- - Page 1 boxes: blue=data/information, green=biomarkers/recommendations, yellow/orange=clinical implications, red=warnings
- - Recommendation boxes (green=strong recommendation, yellow=conditional, blue=research needed)
- - Biomarker stratification (color-coded molecular subtypes)
- - Statistical significance (color-coded p-values, hazard ratios)
-- **Tables**:
- - Demographics with baseline characteristics
- - Biomarker frequency by subgroup
- - Outcomes table (ORR, PFS, OS, DOR by molecular subtype)
- - Adverse events by cohort
- - Evidence summary tables with GRADE ratings
-- **Figures**:
- - Kaplan-Meier survival curves with log-rank p-values and number at risk tables
- - Waterfall plots showing best response by patient
- - Forest plots for subgroup analyses with confidence intervals
- - TikZ decision algorithm flowcharts
- - Swimmer plots for individual patient timelines
-- **Statistics**: Hazard ratios with 95% CI, p-values, median survival times, landmark survival rates
-- **Compliance**: De-identification per HIPAA Safe Harbor, confidentiality notices for proprietary data
-
-## Integration
-
-This skill integrates with:
-- **scientific-writing**: Citation management, statistical reporting, evidence synthesis
-- **clinical-reports**: Medical terminology, HIPAA compliance, regulatory documentation
-- **scientific-schematics**: TikZ flowcharts for decision algorithms and treatment pathways
-- **treatment-plans**: Individual patient applications of cohort-derived insights (bidirectional)
-
-## Key Differentiators from Treatment-Plans Skill
-
-**Clinical Decision Support (this skill):**
-- **Audience**: Pharmaceutical companies, clinical researchers, guideline committees, medical affairs
-- **Scope**: Population-level analyses, evidence synthesis, guideline development
-- **Focus**: Biomarker stratification, statistical comparisons, evidence grading
-- **Output**: Multi-page analytical documents (5-15 pages typical) with extensive figures and tables
-- **Use Cases**: Drug development, regulatory submissions, clinical practice guidelines, medical strategy
-- **Example**: "Analyze 60 HER2+ breast cancer patients by hormone receptor status with survival outcomes"
-
-**Treatment-Plans Skill:**
-- **Audience**: Clinicians, patients, care teams
-- **Scope**: Individual patient care planning
-- **Focus**: SMART goals, patient-specific interventions, monitoring plans
-- **Output**: Concise 1-4 page actionable care plans
-- **Use Cases**: Bedside clinical care, EMR documentation, patient-centered planning
-- **Example**: "Create treatment plan for a 55-year-old patient with newly diagnosed type 2 diabetes"
-
-**When to use each:**
-- Use **clinical-decision-support** for: cohort analyses, biomarker stratification studies, treatment guideline development, pharmaceutical strategy documents
-- Use **treatment-plans** for: individual patient care plans, treatment protocols for specific patients, bedside clinical documentation
-
-## Example Usage
-
-### Patient Cohort Analysis
-
-**Example 1: NSCLC Biomarker Stratification**
-```
-> Analyze a cohort of 45 NSCLC patients stratified by PD-L1 expression (<1%, 1-49%, ≥50%)
-> receiving pembrolizumab. Include outcomes: ORR, median PFS, median OS with hazard ratios
-> comparing PD-L1 ≥50% vs <50%. Generate Kaplan-Meier curves and waterfall plot.
-```
+## GRADE Evidence Profiles
-**Example 2: GBM Molecular Subtype Analysis**
-```
-> Generate cohort analysis for 30 GBM patients classified into Cluster 1 (Mesenchymal-Immune-Active)
-> and Cluster 2 (Proneural) molecular subtypes. Compare outcomes including median OS, 6-month PFS rate,
-> and response to TMZ+bevacizumab. Include biomarker profile table and statistical comparison.
-```
+Do not infer a certainty rating from article text, study design alone, p-values, or keywords. Do not use the legacy `1A/2B` shorthand as if it were universal GRADE output.
-**Example 3: Breast Cancer HER2 Cohort**
-```
-> Analyze 60 HER2-positive metastatic breast cancer patients treated with trastuzumab-deruxtecan,
-> stratified by prior trastuzumab exposure (yes/no). Include ORR, DOR, median PFS with forest plot
-> showing subgroup analyses by hormone receptor status, brain metastases, and number of prior lines.
-```
+For each important outcome, a human panel must document:
-### Treatment Recommendation Report
+- risk of bias;
+- inconsistency;
+- indirectness;
+- imprecision;
+- publication bias;
+- any applicable upgrading considerations;
+- effect estimate and uncertainty;
+- rationale and source IDs for every judgment;
+- final certainty judgment and named review role.
-**Example 1: HER2+ Metastatic Breast Cancer Guidelines**
-```
-> Create evidence-based treatment recommendations for HER2-positive metastatic breast cancer including
-> biomarker-guided therapy selection. Use GRADE system to grade recommendations for first-line
-> (trastuzumab+pertuzumab+taxane), second-line (trastuzumab-deruxtecan), and third-line options.
-> Include decision algorithm flowchart based on brain metastases, hormone receptor status, and prior therapies.
-```
+The checker validates completeness and citation links only. It never calculates certainty or recommendation strength. See `references/evidence_profiles.md`.
-**Example 2: Advanced NSCLC Treatment Algorithm**
-```
-> Generate treatment recommendation report for advanced NSCLC based on PD-L1 expression, EGFR mutation,
-> ALK rearrangement, and performance status. Include GRADE-graded recommendations for each molecular subtype,
-> TikZ flowchart for biomarker-directed therapy selection, and evidence tables from KEYNOTE-189, FLAURA,
-> and CheckMate-227 trials.
-```
+## Aggregate Model and Biomarker Evaluation
-**Example 3: Multiple Myeloma Line-of-Therapy Sequencing**
-```
-> Create treatment algorithm for newly diagnosed multiple myeloma through relapsed/refractory setting.
-> Include GRADE recommendations for transplant-eligible vs ineligible, high-risk cytogenetics considerations,
-> and sequencing of daratumumab, carfilzomib, and CAR-T therapy. Provide flowchart showing decision points
-> at each line of therapy.
+Do not derive thresholds, assign molecular or disease classes, match therapies, or emit person-level predictions.
+
+The evaluator accepts only aggregate confusion counts and calibration bins. It reports bounded descriptive metrics with Wilson intervals, calibration gaps, subgroup differences, and explicit suppression. It does not determine fairness, clinical utility, or fitness for use. Require:
+
+- locked model/assay/version and pre-specified threshold provenance;
+- representative internal validation and independent external validation;
+- calibration and discrimination appropriate to the target;
+- subgroup performance with uncertainty and sample sizes;
+- missingness, spectrum/selection bias, dataset shift, and assay variability;
+- human-factors and prospective evaluation where relevant;
+- monitoring, change control, rollback, and retirement criteria.
+
+See `references/model_biomarker_evaluation.md`.
+
+## Cohort Tables
+
+Use aggregate cells only. Do not provide row-level data to the generator.
+
+- Choose the minimum cell threshold under an approved disclosure policy.
+- Apply primary and complementary suppression.
+- Report denominators and missingness.
+- Avoid baseline significance testing as a balance diagnostic.
+- Label adjusted, unadjusted, pre-specified, and exploratory results.
+- Do not interpret association as causation or clinical actionability.
+
+The default threshold is an operational safeguard, not a HIPAA rule or guarantee. See `references/cohort_evaluation.md` and `references/privacy_and_disclosure.md`.
+
+## Survival Plans
+
+Define time zero, event, competing events, censoring, intercurrent events, estimand, horizon, effect measure, and analysis population together.
+
+- Assess proportional hazards before treating a hazard ratio as constant.
+- Pre-specify alternatives such as time-varying effects or restricted mean survival time.
+- Use cumulative-incidence methods when competing events matter.
+- Address immortal-time, informative-censoring, delayed-entry, missing-data, and multiplicity risks.
+- Include sensitivity analyses and uncertainty, not only p-values.
+
+The bundled helper validates a plan; it does not analyze survival data. See `references/survival_analysis.md`.
+
+## Decision Logic
+
+Only document research or governance logic, such as evidence inclusion, validation gates, release holds, and human-review checkpoints. Each node must link to source IDs, tests, owner, version, and status.
+
+Do not encode care pathways, urgency, medication actions, diagnostic rules, alarms, or patient-facing outputs. See `references/decision_logic_traceability.md`.
+
+## Privacy and De-identification
+
+The HHS methods are Expert Determination and Safe Harbor. A checklist cannot perform either method by itself. Do not claim that removing a list of fields, hashing identifiers, using a minimum cell size, or passing this script proves de-identification or HIPAA compliance.
+
+The helper inventories documented human work. It never reads a dataset. Escalate unresolved items, free text, dates, geography, rare combinations, linkage risk, genomics, and longitudinal patterns to qualified privacy review.
+
+## Reporting-Guideline Selection
+
+- Cohort/case-control/cross-sectional: STROBE; add RECORD for routinely collected data.
+- Prediction model development/evaluation: TRIPOD+AI and PROBAST+AI.
+- Tumor prognostic marker study: REMARK.
+- AI diagnostic accuracy: STARD-AI with STARD.
+- AI trial protocol: SPIRIT-AI with the current SPIRIT base statement.
+- AI randomized trial report: CONSORT-AI with the current CONSORT base statement.
+- Early live AI evaluation: DECIDE-AI—but live evaluation is outside this skill's execution scope.
+
+These are reporting or appraisal tools, not automatic quality scores. See `references/study_reporting.md`.
+
+## Regulatory and Governance Context
+
+FDA device status turns on intended use and function, not a document label. FDA's January 2026 CDS guidance distinguishes certain non-device CDS functions from device software functions; its examples are not a self-certification checklist. ONC HTI-1 requirements apply within the defined certification scope. ICH E6(R3) and E9/E9(R1) inform trial governance and statistical planning but do not make an artifact compliant.
+
+Use `references/regulatory_and_governance.md` for dated context. Obtain qualified advice for an actual product, study, submission, deployment, or jurisdiction.
+
+## Verification
+
+From this skill directory:
+
+```bash
+python3 -m unittest discover -s tests -p 'test_*.py'
```
-## Key Features
-
-### Biomarker Classification
-- Genomic: Mutations, CNV, gene fusions
-- Expression: RNA-seq, IHC scores
-- Molecular subtypes: Disease-specific classifications
-- Clinical actionability: Therapy selection guidance
-
-### Outcome Metrics
-- Survival: OS (overall survival), PFS (progression-free survival)
-- Response: ORR (objective response rate), DOR (duration of response), DCR (disease control rate)
-- Quality: ECOG performance status, symptom burden
-- Safety: Adverse events, dose modifications
-
-### Statistical Methods
-- Survival analysis: Kaplan-Meier curves, log-rank tests
-- Group comparisons: t-tests, chi-square, Fisher's exact
-- Effect sizes: Hazard ratios, odds ratios with 95% CI
-- Significance: p-values, multiple testing corrections
-
-### Evidence Grading
-
-**GRADE System**
-- **1A**: Strong recommendation, high-quality evidence
-- **1B**: Strong recommendation, moderate-quality evidence
-- **2A**: Weak recommendation, high-quality evidence
-- **2B**: Weak recommendation, moderate-quality evidence
-- **2C**: Weak recommendation, low-quality evidence
-
-**Recommendation Strength**
-- **Strong**: Benefits clearly outweigh risks
-- **Conditional**: Trade-offs exist, patient values important
-- **Research**: Insufficient evidence, clinical trials needed
-
-## Best Practices
-
-### For Cohort Analyses
-
-1. **Patient Selection Transparency**: Clearly document inclusion/exclusion criteria, patient flow, and reasons for exclusions
-2. **Biomarker Clarity**: Specify assay methods, platforms (e.g., FoundationOne, Caris), cut-points, and validation status
-3. **Statistical Rigor**:
- - Report hazard ratios with 95% confidence intervals, not just p-values
- - Include median follow-up time for survival analyses
- - Specify statistical tests used (log-rank, Cox regression, Fisher's exact)
- - Account for multiple comparisons when appropriate
-4. **Outcome Definitions**: Use standard criteria:
- - Response: RECIST 1.1, iRECIST for immunotherapy
- - Adverse events: CTCAE version 5.0
- - Performance status: ECOG or Karnofsky
-5. **Survival Data Presentation**:
- - Median OS/PFS with 95% CI
- - Landmark survival rates (6-month, 12-month, 24-month)
- - Number at risk tables below Kaplan-Meier curves
- - Censoring clearly indicated
-6. **Subgroup Analyses**: Pre-specify subgroups; clearly label exploratory vs pre-planned analyses
-7. **Data Completeness**: Report missing data and how it was handled
-
-### For Treatment Recommendation Reports
-
-1. **Evidence Grading Transparency**:
- - Use GRADE system consistently (1A, 1B, 2A, 2B, 2C)
- - Document rationale for each grade
- - Clearly state quality of evidence (high, moderate, low, very low)
-2. **Comprehensive Evidence Review**:
- - Include phase 3 randomized trials as primary evidence
- - Supplement with phase 2 data for emerging therapies
- - Note real-world evidence and meta-analyses
- - Cite trial names (e.g., KEYNOTE-189, CheckMate-227)
-3. **Biomarker-Guided Recommendations**:
- - Link specific biomarkers to therapy recommendations
- - Specify testing methods and validated assays
- - Include FDA/EMA approval status for companion diagnostics
-4. **Clinical Actionability**: Every recommendation should have clear implementation guidance
-5. **Decision Algorithm Clarity**: TikZ flowcharts should be unambiguous with clear yes/no decision points
-6. **Special Populations**: Address elderly, renal/hepatic impairment, pregnancy, drug interactions
-7. **Monitoring Guidance**: Specify safety labs, imaging, and frequency
-8. **Update Frequency**: Date recommendations and plan for periodic updates
-
-### General Best Practices
-
-1. **First Page Executive Summary (MANDATORY)**:
- - ALWAYS create a complete executive summary on page 1 that spans the entire first page
- - Use 3-5 colored tcolorbox elements to highlight key findings
- - No table of contents or detailed sections on page 1
- - Use `\thispagestyle{empty}` and end with `\newpage`
- - This is the single most important page - it should be scannable in 60 seconds
-2. **De-identification**: Remove all 18 HIPAA identifiers before document generation (Safe Harbor method)
-3. **Regulatory Compliance**: Include confidentiality notices for proprietary pharmaceutical data
-4. **Publication-Ready Formatting**: Use 0.5in margins, professional fonts, color-coded sections
-5. **Reproducibility**: Document all statistical methods to enable replication
-6. **Conflict of Interest**: Disclose pharmaceutical funding or relationships when applicable
-7. **Visual Hierarchy**: Use colored boxes consistently (blue=data, green=biomarkers, yellow/orange=recommendations, red=warnings)
-
-## References
-
-See the `references/` directory for detailed guidance on:
-- Patient cohort analysis and stratification methods
-- Treatment recommendation development
-- Clinical decision algorithms
-- Biomarker classification and interpretation
-- Outcome analysis and statistical methods
-- Evidence synthesis and grading systems
-
-## Templates
-
-See the `assets/` directory for LaTeX templates:
-- `cohort_analysis_template.tex` - Biomarker-stratified patient cohort analysis with statistical comparisons
-- `treatment_recommendation_template.tex` - Evidence-based clinical practice guidelines with GRADE grading
-- `clinical_pathway_template.tex` - TikZ decision algorithm flowcharts for treatment sequencing
-- `biomarker_report_template.tex` - Molecular subtype classification and genomic profile reports
-
-**Template Features:**
-- 0.5in margins for compact presentation
-- Color-coded recommendation boxes
-- Professional tables for demographics, biomarkers, outcomes
-- Built-in support for Kaplan-Meier curves, waterfall plots, forest plots
-- GRADE evidence grading tables
-- Confidentiality headers for pharmaceutical documents
-
-## Scripts
-
-See the `scripts/` directory for analysis and visualization tools:
-- `generate_survival_analysis.py` - Kaplan-Meier curve generation with log-rank tests, hazard ratios, 95% CI
-- `create_waterfall_plot.py` - Best response visualization for cohort analyses
-- `create_forest_plot.py` - Subgroup analysis visualization with confidence intervals
-- `create_cohort_tables.py` - Demographics, biomarker frequency, and outcomes tables
-- `build_decision_tree.py` - TikZ flowchart generation for treatment algorithms
-- `biomarker_classifier.py` - Patient stratification algorithms by molecular subtype
-- `calculate_statistics.py` - Hazard ratios, Cox regression, log-rank tests, Fisher's exact
-- `validate_cds_document.py` - Quality and compliance checks (HIPAA, statistical reporting standards)
-- `grade_evidence.py` - Automated GRADE assessment helper for treatment recommendations
+Run AST compilation without bytecode:
+```bash
+python3 -c "import ast,pathlib; [ast.parse(p.read_text()) for p in pathlib.Path('scripts').glob('*.py')]"
+```
+## Reference Map
+
+- `references/README.md` — scope and navigation
+- `references/safety_and_scope.md` — refusal and escalation rules
+- `references/regulatory_and_governance.md` — FDA, ONC, ICH context
+- `references/evidence_profiles.md` — human GRADE workflow
+- `references/study_reporting.md` — EQUATOR and PROBAST+AI selection
+- `references/cohort_evaluation.md` — aggregate cohort methods
+- `references/survival_analysis.md` — time-to-event planning
+- `references/model_biomarker_evaluation.md` — model/biomarker evaluation
+- `references/privacy_and_disclosure.md` — de-identification and suppression
+- `references/decision_logic_traceability.md` — governance logic
+- `references/sources.md` — dated authoritative source ledger
+- `references/security_validation.md` — scan results and accepted LOW findings
diff --git a/skills/clinical-decision-support/assets/aggregate_cohort_table_template.json b/skills/clinical-decision-support/assets/aggregate_cohort_table_template.json
new file mode 100644
index 00000000..cba589bb
--- /dev/null
+++ b/skills/clinical-decision-support/assets/aggregate_cohort_table_template.json
@@ -0,0 +1,114 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "table_id": "SYNTHETIC-COHORT-TABLE-001",
+ "title": "Synthetic Aggregate Cohort Summary",
+ "purpose": "Demonstrate descriptive aggregate table generation with disclosure controls.",
+ "population": "Synthetic cohort only; no real persons or records.",
+ "data_cut_date": "2026-07-23",
+ "data_level": "synthetic",
+ "raw_rows_supplied": false,
+ "patient_care_use": false,
+ "disclosure_policy": "Synthetic demonstration using an operational minimum cell size and complementary suppression.",
+ "human_review": "A data steward and statistician must review any non-synthetic release."
+ },
+ "intended_use": "Research description only; not for patient care or live clinical use.",
+ "prohibited_uses": [
+ "No diagnosis, treatment recommendation, dosing, triage, alarm, or autonomous decision.",
+ "No row-level or person-level output.",
+ "No claim that suppression establishes de-identification or HIPAA compliance."
+ ],
+ "limitations": [
+ "All values are synthetic.",
+ "Cell thresholds do not address every linkage or differencing risk.",
+ "Descriptive differences do not establish causality or clinical importance."
+ ],
+ "human_review": {
+ "required": true,
+ "roles": [
+ "statistician",
+ "data steward",
+ "privacy reviewer"
+ ],
+ "completed": false
+ },
+ "governance": {
+ "version": "synthetic-v1",
+ "owner": "research data governance owner",
+ "change_summary": "Initial synthetic aggregate template.",
+ "auditability": "Retain aggregate provenance, disclosure settings, code version, and reviewer decisions.",
+ "monitoring": "Review new releases for differencing, rare combinations, and changed denominators."
+ },
+ "groups": [
+ {
+ "id": "A",
+ "label": "Synthetic Group A",
+ "n": 120
+ },
+ {
+ "id": "B",
+ "label": "Synthetic Group B",
+ "n": 120
+ }
+ ],
+ "rows": [
+ {
+ "label": "Aggregate characteristics",
+ "type": "header"
+ },
+ {
+ "label": "Synthetic measure, units",
+ "type": "continuous",
+ "values": {
+ "A": {
+ "n": 120,
+ "missing": 0,
+ "summary": "median 52; quartiles 44 to 61"
+ },
+ "B": {
+ "n": 120,
+ "missing": 0,
+ "summary": "median 50; quartiles 42 to 60"
+ }
+ }
+ },
+ {
+ "label": "Synthetic category",
+ "type": "header"
+ },
+ {
+ "label": "Synthetic category",
+ "level": "Category 1",
+ "type": "categorical",
+ "values": {
+ "A": {
+ "count": 54,
+ "denominator": 120,
+ "missing": 0
+ },
+ "B": {
+ "count": 63,
+ "denominator": 120,
+ "missing": 0
+ }
+ }
+ },
+ {
+ "label": "Synthetic category",
+ "level": "Rare synthetic category",
+ "type": "categorical",
+ "values": {
+ "A": {
+ "count": 7,
+ "denominator": 120,
+ "missing": 0
+ },
+ "B": {
+ "count": 15,
+ "denominator": 120,
+ "missing": 0
+ }
+ }
+ }
+ ]
+}
diff --git a/skills/clinical-decision-support/assets/aggregate_model_evaluation_template.json b/skills/clinical-decision-support/assets/aggregate_model_evaluation_template.json
new file mode 100644
index 00000000..85f11b4d
--- /dev/null
+++ b/skills/clinical-decision-support/assets/aggregate_model_evaluation_template.json
@@ -0,0 +1,115 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "evaluation_id": "SYNTHETIC-MODEL-EVAL-001",
+ "title": "Synthetic Aggregate Model Evaluation",
+ "evaluation_target": "Locked binary research model",
+ "target_version": "synthetic-v1",
+ "purpose": "Demonstrate aggregate performance and calibration reporting.",
+ "population": "Synthetic validation cohort; no real persons or records.",
+ "setting": "Synthetic offline evaluation",
+ "outcome": "Synthetic binary outcome",
+ "outcome_horizon": "Synthetic fixed horizon",
+ "threshold": "0.50, prespecified for this synthetic example",
+ "threshold_pre_specified": true,
+ "threshold_source_id": "SRC-PROTOCOL",
+ "validation_dataset": "Independent synthetic aggregate dataset",
+ "external_validation": true,
+ "data_cut_date": "2026-07-23",
+ "data_level": "synthetic",
+ "person_level_output": false,
+ "human_review_required": true
+ },
+ "intended_use": "Research evaluation only; not for patient care or live clinical use.",
+ "prohibited_uses": [
+ "No person-level prediction or classification.",
+ "No diagnosis, treatment recommendation, dosing, triage, alarm, or autonomous decision.",
+ "No claim of clinical validity, utility, safety, fairness, authorization, or compliance."
+ ],
+ "limitations": [
+ "All counts are synthetic.",
+ "Aggregate bins cannot estimate calibration slope.",
+ "Subgroup differences are descriptive and do not determine fairness."
+ ],
+ "human_review": {
+ "required": true,
+ "roles": [
+ "prediction-model methodologist",
+ "domain expert",
+ "fairness and governance reviewer"
+ ],
+ "completed": false
+ },
+ "governance": {
+ "owner": "research model governance owner",
+ "version_and_change_control": "Lock model, threshold, data, code, and report versions; independently validate every change.",
+ "monitoring": "Define aggregate calibration, discrimination, subgroup, drift, failure, and incident review.",
+ "auditability": "Retain provenance, commands, versions, reviewer decisions, and unresolved findings without sensitive data.",
+ "human_factors": "Document intended users and offline usability evidence; live evaluation is outside this skill.",
+ "rollback_and_retirement": "Define rollback, suspension, and retirement triggers before release."
+ },
+ "sources": [
+ {
+ "id": "SRC-PROTOCOL",
+ "citation": "Synthetic locked evaluation protocol, version 1.",
+ "url": "not_applicable_for_local_synthetic_source",
+ "accessed": "2026-07-23"
+ }
+ ],
+ "groups": [
+ {
+ "name": "Synthetic Group A",
+ "n": 120,
+ "confusion": {
+ "tp": 36,
+ "fp": 18,
+ "tn": 50,
+ "fn": 16
+ },
+ "calibration_bins": [
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.2,
+ "observed_events": 12
+ },
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.5,
+ "observed_events": 17
+ },
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.75,
+ "observed_events": 23
+ }
+ ]
+ },
+ {
+ "name": "Synthetic Group B",
+ "n": 120,
+ "confusion": {
+ "tp": 28,
+ "fp": 22,
+ "tn": 56,
+ "fn": 14
+ },
+ "calibration_bins": [
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.2,
+ "observed_events": 11
+ },
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.45,
+ "observed_events": 14
+ },
+ {
+ "n": 40,
+ "mean_predicted_probability": 0.7,
+ "observed_events": 17
+ }
+ ]
+ }
+ ]
+}
diff --git a/skills/clinical-decision-support/assets/artifact_intended_use_template.json b/skills/clinical-decision-support/assets/artifact_intended_use_template.json
new file mode 100644
index 00000000..3ab136c5
--- /dev/null
+++ b/skills/clinical-decision-support/assets/artifact_intended_use_template.json
@@ -0,0 +1,81 @@
+{
+ "schema_version": "1.0",
+ "artifact": {
+ "id": "REPLACE_WITH_ARTIFACT_ID",
+ "title": "Research Evaluation Artifact",
+ "type": "model_biomarker_evaluation",
+ "version": "0.1-draft",
+ "status": "draft",
+ "owner": "REPLACE_WITH_GOVERNANCE_OWNER_ROLE",
+ "date": "YYYY-MM-DD",
+ "change_summary": "Initial research-only draft."
+ },
+ "intended_use": {
+ "purpose": "Document an aggregate research evaluation and its limitations.",
+ "intended_users": [
+ "research methodologist",
+ "governance reviewer"
+ ],
+ "population_scope": "aggregate_or_synthetic_only",
+ "decision_role": "research_evaluation_governance_only",
+ "boundary_statement": "Not for patient care or live clinical use."
+ },
+ "prohibited_uses": [
+ "No patient-specific output.",
+ "No diagnosis or prognosis for a person.",
+ "No treatment recommendation, treatment selection, or care plan.",
+ "No dosing or medication instruction.",
+ "No triage or urgency assignment.",
+ "No autonomous decision.",
+ "No alarm or alert.",
+ "No bedside or point-of-care use.",
+ "No live clinical use or deployment.",
+ "No claim of regulatory compliance, authorization, or approval.",
+ "No claim of HIPAA compliance or de-identification."
+ ],
+ "data_governance": {
+ "data_level": "synthetic",
+ "phi_supplied": false,
+ "raw_rows_supplied": false,
+ "provenance": "Synthetic aggregate template; replace with approved aggregate provenance.",
+ "data_cut_date": "YYYY-MM-DD",
+ "disclosure_policy": "Organization-approved policy; minimum cell size and complementary suppression selected before release."
+ },
+ "limitations": [
+ "Aggregate summaries cannot support person-level inference.",
+ "External validity depends on the evaluated population and setting.",
+ "Passing structural checks does not establish clinical validity, utility, safety, fairness, authorization, or compliance."
+ ],
+ "human_review": {
+ "required": true,
+ "roles": [
+ "methodologist",
+ "domain expert",
+ "privacy or governance reviewer"
+ ],
+ "completed": false,
+ "approval_boundary": "Release requires documented approval by the accountable organization; no approval permits patient-care use."
+ },
+ "validation": {
+ "external_validation": "REPLACE_WITH_STATUS_AND_EVIDENCE",
+ "calibration": "REPLACE_WITH_STATUS_AND_EVIDENCE",
+ "subgroup_fairness": "REPLACE_WITH_STATUS_AND_EVIDENCE",
+ "uncertainty": "REPLACE_WITH_INTERVAL_METHOD_AND_LIMITATIONS",
+ "human_factors": "REPLACE_WITH_STATUS; live clinical evaluation is outside this skill."
+ },
+ "lifecycle": {
+ "monitoring_plan": "Define aggregate performance, calibration, subgroup, drift, incident, and review cadence.",
+ "change_control": "Record version, rationale, validation, approval, and rollback for every change.",
+ "audit_plan": "Retain sources, data/code versions, commands, reviewers, decisions, and unresolved issues without sensitive data.",
+ "retirement_criteria": "Define evidence, performance, safety, governance, or obsolescence triggers."
+ },
+ "compliance_claims": false,
+ "sources": [
+ {
+ "id": "SRC-001",
+ "citation": "REPLACE_WITH_FULL_AUTHORITATIVE_CITATION",
+ "url": "REPLACE_WITH_CANONICAL_URL",
+ "accessed": "YYYY-MM-DD"
+ }
+ ]
+}
diff --git a/skills/clinical-decision-support/assets/biomarker_report_template.tex b/skills/clinical-decision-support/assets/biomarker_report_template.tex
deleted file mode 100644
index f66b4922..00000000
--- a/skills/clinical-decision-support/assets/biomarker_report_template.tex
+++ /dev/null
@@ -1,380 +0,0 @@
-\documentclass[10pt,letterpaper]{article}
-
-% Packages
-\usepackage[margin=0.5in]{geometry}
-\usepackage[utf8]{inputenc}
-\usepackage[T1]{fontenc}
-\usepackage{helvet}
-\renewcommand{\familydefault}{\sfdefault}
-\usepackage{xcolor}
-\usepackage{tcolorbox}
-\usepackage{array}
-\usepackage{tabularx}
-\usepackage{booktabs}
-\usepackage{enumitem}
-\usepackage{titlesec}
-\usepackage{fancyhdr}
-\usepackage{graphicx}
-
-% Color definitions
-\definecolor{headerblue}{RGB}{0,102,204}
-\definecolor{tier1green}{RGB}{0,153,76}
-\definecolor{tier2orange}{RGB}{255,152,0}
-\definecolor{tier3gray}{RGB}{158,158,158}
-\definecolor{mutationred}{RGB}{244,67,54}
-\definecolor{amplificationblue}{RGB}{33,150,243}
-\definecolor{fusionpurple}{RGB}{156,39,176}
-\definecolor{highlightgray}{RGB}{240,240,240}
-
-% Section formatting
-\titleformat{\section}{\normalfont\fontsize{11}{12}\bfseries\color{headerblue}}{\thesection}{0.5em}{}
-\titlespacing*{\section}{0pt}{4pt}{2pt}
-
-\titleformat{\subsection}{\normalfont\fontsize{10}{11}\bfseries}{\thesubsection}{0.5em}{}
-\titlespacing*{\subsection}{0pt}{3pt}{1pt}
-
-% List formatting
-\setlist[itemize]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-\setlist[enumerate]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{2pt}
-
-% Header/footer
-\pagestyle{fancy}
-\fancyhf{}
-\fancyhead[L]{\footnotesize \textbf{Genomic Profile Report: [PATIENT ID]}}
-\fancyhead[R]{\footnotesize Page \thepage}
-\renewcommand{\headrulewidth}{0.5pt}
-\fancyfoot[C]{\footnotesize Confidential Laboratory Report - CLIA/CAP Certified}
-
-\begin{document}
-
-% Title block
-\begin{center}
-{\fontsize{14}{16}\selectfont\bfseries\color{headerblue} COMPREHENSIVE GENOMIC PROFILING REPORT}\\[2pt]
-{\fontsize{10}{12}\selectfont [Laboratory Name] | CLIA \#: [Number] | CAP \#: [Number]}
-\end{center}
-
-\vspace{2pt}
-
-% Patient/Specimen Information
-\begin{tcolorbox}[colback=highlightgray,colframe=black]
-\begin{minipage}{0.48\textwidth}
-{\small
-\textbf{Patient Information}\\
-Patient ID: [De-identified ID]\\
-Date of Birth: [De-identified/Age only]\\
-Sex: [M/F]\\
-Ordering Physician: [Name, MD]
-}
-\end{minipage}
-\hfill
-\begin{minipage}{0.48\textwidth}
-{\small
-\textbf{Specimen Information}\\
-Specimen Type: [Tissue/Blood/Other]\\
-Collection Date: [Date]\\
-Received Date: [Date]\\
-Report Date: [Date]
-}
-\end{minipage}
-\end{tcolorbox}
-
-\vspace{2pt}
-
-% Diagnosis
-\textbf{Diagnosis}: [Cancer type, stage, histology]
-
-\textbf{Testing Performed}: [Assay name - e.g., FoundationOne CDx, NGS Panel]
-
-\vspace{2pt}
-
-% Results Summary Box
-\begin{tcolorbox}[enhanced,colback=tier1green!10,colframe=tier1green,
-title=\textbf{RESULTS SUMMARY},fonttitle=\bfseries,coltitle=black]
-{\small
-\textbf{Actionable Findings}: [X] alteration(s) detected
-\begin{itemize}
-\item \textbf{Tier 1}: [Number] FDA-approved therapy target(s)
-\item \textbf{Tier 2}: [Number] clinical trial or off-label option(s)
-\item \textbf{Tier 3}: [Number] variant(s) of uncertain significance
-\end{itemize}
-
-\textbf{Additional Biomarkers}:
-\begin{itemize}
-\item Tumor Mutational Burden (TMB): [X.X] mutations/Mb - [High/Intermediate/Low]
-\item Microsatellite Status: [MSI-H / MSS / Not assessed]
-\item PD-L1 Expression: [X\% TPS / Not assessed]
-\end{itemize}
-}
-\end{tcolorbox}
-
-\section{Tier 1: FDA-Approved Targeted Therapies}
-
-\begin{tcolorbox}[enhanced,colback=tier1green!5,colframe=tier1green,
-title={\colorbox{mutationred!60}{\textcolor{white}{\textbf{MUTATION}}} \textbf{[Gene Name] [Alteration]} \hfill \textbf{TIER 1 - ACTIONABLE}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Alteration}: [Gene] [Specific variant - e.g., EGFR p.L858R (c.2573T>G)]\\
-\textbf{Variant Allele Frequency (VAF)}: XX\% (suggests [clonal/subclonal] mutation)\\
-\textbf{Classification}: [Pathogenic / Likely Pathogenic] (ClinVar, OncoKB)
-
-\textbf{Clinical Significance}: \textcolor{tier1green}{\textbf{ACTIONABLE - FDA-APPROVED THERAPY AVAILABLE}}
-
-\textbf{FDA-Approved Therapy}:
-\begin{itemize}
-\item \textbf{Drug}: [Drug name (brand name)] XX mg [PO/IV] [schedule]
-\item \textbf{Indication}: [Specific disease, line of therapy]
-\item \textbf{Evidence}: [Pivotal trial] - [Key results with HR, ORR, median survival]
-\item \textbf{Guideline}: NCCN Category [1/2A], [ESMO/ASCO recommendation]
-\item \textbf{Expected Outcomes}: ORR XX\%, median PFS XX months
-\end{itemize}
-
-\textbf{Alternative Therapies}:
-\begin{itemize}
-\item [Alternative drug] - [Indication, evidence level]
-\end{itemize}
-
-\textbf{Recommendation}: \textbf{STRONG} - Consider [drug name] as [first-line/second-line] therapy (GRADE 1A)
-}
-\end{tcolorbox}
-
-\vspace{3pt}
-
-\begin{tcolorbox}[enhanced,colback=tier1green!5,colframe=tier1green,
-title={\colorbox{amplificationblue!60}{\textcolor{white}{\textbf{AMPLIFICATION}}} \textbf{[Gene] Amplification} \hfill \textbf{TIER 1}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Alteration}: [Gene name] amplification\\
-\textbf{Copy Number}: [X.X] copies per cell (threshold for positivity: ≥[Y])\\
-\textbf{Method}: [NGS copy number analysis / FISH]
-
-\textbf{Clinical Significance}: \textcolor{tier1green}{\textbf{ACTIONABLE - COMPANION DIAGNOSTIC}}
-
-\textbf{Therapy Options}: [Similar structure as mutation section]
-}
-\end{tcolorbox}
-
-\section{Tier 2: Clinical Trial or Guideline-Recommended Off-Label}
-
-\begin{tcolorbox}[enhanced,colback=tier2orange!5,colframe=tier2orange,
-title={\colorbox{fusionpurple!60}{\textcolor{white}{\textbf{FUSION}}} \textbf{[Gene] Rearrangement} \hfill \textbf{TIER 2 - INVESTIGATIONAL}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Alteration}: [Gene A]-[Gene B] fusion detected\\
-\textbf{Method}: [RNA-seq / DNA NGS / FISH]
-
-\textbf{Clinical Significance}: \textcolor{tier2orange}{\textbf{INVESTIGATIONAL - CLINICAL TRIAL PREFERRED}}
-
-\textbf{Treatment Options}:
-\begin{itemize}
-\item \textbf{Clinical Trial}: [Specific trial or trial search guidance]
-\item \textbf{Off-Label Option}: [Drug] - NCCN Category 2A recommendation
-\item \textbf{Evidence}: [Phase 2 data, basket trial results, case series]
-\end{itemize}
-
-\textbf{Recommendation}: \textbf{CONDITIONAL} - Consider clinical trial enrollment or off-label use after standard therapy (GRADE 2B)
-}
-\end{tcolorbox}
-
-\section{Tier 3: Variants of Uncertain Significance (VUS)}
-
-\begin{tcolorbox}[colback=tier3gray!10,colframe=tier3gray]
-{\small
-\textbf{[Gene] [Variant]}: [Description]\\
-\textbf{Classification}: Variant of Uncertain Significance (VUS)\\
-\textbf{Clinical Actionability}: None currently - insufficient evidence\\
-\textbf{Recommendation}: No treatment change based on this finding; may be reclassified as evidence emerges
-}
-\end{tcolorbox}
-
-\section{Biomarkers Assessed - Negative}
-
-\textbf{No Alterations Detected in}:
-\begin{multicols}{3}
-\begin{itemize}
-\item [Gene 1]
-\item [Gene 2]
-\item [Gene 3]
-\item [Gene 4]
-\item [Gene 5]
-\item [Gene 6]
-\end{itemize}
-\end{multicols}
-
-\section{Additional Biomarkers}
-
-\subsection{Tumor Mutational Burden (TMB)}
-
-\textbf{TMB}: [X.X] mutations per megabase
-
-\textbf{Classification}:
-\begin{itemize}
-\item $\geq$10 mut/Mb: TMB-high (potential immunotherapy benefit)
-\item 6-9 mut/Mb: TMB-intermediate
-\item <6 mut/Mb: TMB-low
-\end{itemize}
-
-\textbf{Result}: [TMB-high / TMB-intermediate / TMB-low]
-
-\textbf{Clinical Implication}:
-\begin{itemize}
-\item TMB-high: Consider immunotherapy; pembrolizumab FDA-approved for TMB-H ($\geq$10) solid tumors
-\item TMB-intermediate/low: Standard chemotherapy or biomarker-directed therapy
-\end{itemize}
-
-\subsection{Microsatellite Instability (MSI)}
-
-\textbf{MSI Status}: [MSI-H / MSI-L / MSS]
-
-\textbf{Method}: [NGS-based MSI calling / PCR-based assay]
-
-\textbf{Clinical Implication}:
-\begin{itemize}
-\item MSI-H: Immunotherapy highly effective (ORR 30-60\%); pembrolizumab, nivolumab approved
-\item MSS: Standard therapy; MSI-H-specific therapies not indicated
-\item If MSI-H + [relevant cancer] + young age: Consider germline Lynch syndrome testing
-\end{itemize}
-
-\section{Integrated Treatment Recommendations}
-
-\begin{tcolorbox}[enhanced,colback=stronggreen!10,colframe=tier1green,
-title=\textbf{PERSONALIZED TREATMENT PLAN},fonttitle=\bfseries,coltitle=black]
-{\small
-Based on the genomic profile, the following treatment approach is recommended:
-
-\textbf{Primary Recommendation (GRADE 1A)}:
-\begin{itemize}
-\item \textbf{[Drug targeting identified alteration]}
-\item Dosing: [Specific dose and schedule]
-\item Evidence: [Supporting data]
-\item Expected outcomes: ORR XX\%, median PFS XX months
-\end{itemize}
-
-\textbf{If Primary Recommendation Contraindicated}:
-\begin{itemize}
-\item Alternative 1: [Second-line biomarker-directed option]
-\item Alternative 2: [Standard therapy if targeted therapy ineligible]
-\end{itemize}
-
-\textbf{At Progression}:
-\begin{itemize}
-\item Repeat molecular profiling (liquid biopsy or tissue) for resistance mechanisms
-\item Expected resistance alterations: [e.g., EGFR T790M, MET amplification]
-\item Sequential targeted therapy if secondary actionable alteration identified
-\end{itemize}
-
-\textbf{Clinical Trial Matching}:
-\begin{itemize}
-\item [List relevant trials based on identified alterations]
-\item ClinicalTrials.gov search terms: [Suggested keywords]
-\end{itemize}
-}
-\end{tcolorbox}
-
-\section{Clinical Trial Matching}
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{llll}
-\toprule
-\textbf{Trial} & \textbf{Intervention} & \textbf{Biomarker} & \textbf{Phase} \\
-\midrule
-[NCT Number] & [Drug/regimen] & [Matching biomarker] & Phase [1/2/3] \\
-[NCT Number] & [Drug/regimen] & [Matching biomarker] & Phase [1/2/3] \\
-\bottomrule
-\end{tabular}
-\caption{Potential clinical trials based on molecular profile (as of [date])}
-\end{table}
-
-\textit{Note: Trial availability changes frequently. Search ClinicalTrials.gov for current options.}
-
-\section{Methodology}
-
-\subsection{Assay Information}
-
-\textbf{Test Name}: [FoundationOne CDx / Custom NGS Panel / Other]\\
-\textbf{Methodology}: Next-generation sequencing (NGS)\\
-\textbf{Genes Analyzed}: [Number] genes for SNVs, indels, CNVs, and rearrangements\\
-\textbf{Coverage Depth}: [XXX]x median coverage\\
-\textbf{Limit of Detection}: [X\%] variant allele frequency
-
-\textbf{Specimen Details}:
-\begin{itemize}
-\item Specimen type: [FFPE tissue block / Blood (ctDNA)]
-\item Tumor content: [XX\%] (minimum 20\% required for optimal sensitivity)
-\item DNA quality: [Adequate / Suboptimal]
-\item DNA quantity: [XX ng] (minimum [Y ng] required)
-\end{itemize}
-
-\subsection{Interpretation}
-
-\textbf{Variant Classification}:
-\begin{itemize}
-\item Pathogenic: Disease-causing, clinically significant
-\item Likely Pathogenic: Probably disease-causing based on available evidence
-\item VUS: Uncertain significance, insufficient evidence for classification
-\item Likely Benign: Probably not disease-causing
-\item Benign: Not disease-causing
-\end{itemize}
-
-\textbf{Databases Referenced}:
-\begin{itemize}
-\item OncoKB (Memorial Sloan Kettering)
-\item CIViC (Clinical Interpretations of Variants in Cancer)
-\item ClinVar (NCBI)
-\item COSMIC (Catalogue of Somatic Mutations in Cancer)
-\item [Others - PMKB, CGI, etc.]
-\end{itemize}
-
-\section{Limitations}
-
-\begin{itemize}
-\item This test analyzes [somatic/germline] alterations in tumor tissue. [If somatic: Results not informative for inherited cancer risk]
-\item Negative result does not exclude presence of alterations in genes not covered by this panel
-\item Low VAF alterations (<5\%) may not be detected due to assay sensitivity limits
-\item Copy number analysis limited for small amplifications or deletions
-\item Structural variants detection depends on breakpoint location within sequenced regions
-\item TMB and MSI calculations are estimate-based; consider orthogonal testing if borderline
-\end{itemize}
-
-\section{Recommendations for Referring Clinician}
-
-\begin{enumerate}
-\item \textbf{[Action 1]}: [e.g., Initiate targeted therapy with drug X based on detected alteration]
-\item \textbf{[Action 2]}: [e.g., Consider clinical trial enrollment for Tier 2 alteration]
-\item \textbf{[Action 3]}: [e.g., Repeat molecular profiling at progression to identify resistance mechanisms]
-\item \textbf{[Action 4]}: [e.g., If MSI-H detected and patient <50 years, refer for genetic counseling for Lynch syndrome]
-\item \textbf{[Action 5]}: [e.g., Share report with molecular tumor board for complex decision-making]
-\end{enumerate}
-
-\section{References}
-
-\begin{enumerate}
-\item [FDA Label for companion diagnostic]
-\item [Key clinical trial supporting biomarker-therapy association]
-\item [NCCN Guideline reference]
-\item [OncoKB database version]
-\item [Assay validation publication]
-\end{enumerate}
-
-\vspace{10pt}
-
-\hrule
-\vspace{4pt}
-{\footnotesize
-\textbf{Laboratory Director}: [Name, MD, PhD] | [Board certifications]\\
-\textbf{Report Authorized By}: [Name, credentials] | Date: [Date]\\
-\textbf{Laboratory}: [Name, address]\\
-\textbf{CLIA \#}: [Number] | \textbf{CAP \#}: [Number]\\
-\textbf{Questions}: Contact [Name] at [Phone] or [Email]
-
-\vspace{2pt}
-
-\textit{This report is intended for use by qualified healthcare professionals. The information provided is based on current scientific literature and databases. Interpretation and treatment decisions should be made by qualified physicians in consultation with the patient. This test was performed in a CLIA-certified, CAP-accredited laboratory.}
-}
-
-\end{document}
-
diff --git a/skills/clinical-decision-support/assets/clinical_pathway_template.tex b/skills/clinical-decision-support/assets/clinical_pathway_template.tex
deleted file mode 100644
index 2726a63c..00000000
--- a/skills/clinical-decision-support/assets/clinical_pathway_template.tex
+++ /dev/null
@@ -1,222 +0,0 @@
-\documentclass[10pt,letterpaper,landscape]{article}
-
-% Landscape for wider flowcharts
-\usepackage[margin=0.4in]{geometry}
-\usepackage[utf8]{inputenc}
-\usepackage[T1]{fontenc}
-\usepackage{helvet}
-\renewcommand{\familydefault}{\sfdefault}
-\usepackage{xcolor}
-\usepackage{tcolorbox}
-\usepackage{tikz}
-\usetikzlibrary{shapes,arrows,positioning,fit,calc}
-\usepackage{fancyhdr}
-
-% Color definitions
-\definecolor{headerblue}{RGB}{0,102,204}
-\definecolor{actiongreen}{RGB}{0,153,76}
-\definecolor{decisionyellow}{RGB}{255,193,7}
-\definecolor{urgentred}{RGB}{220,20,60}
-\definecolor{infobox}{RGB}{33,150,243}
-\definecolor{routineblue}{RGB}{100,181,246}
-
-% Header/footer
-\pagestyle{fancy}
-\fancyhf{}
-\fancyhead[L]{\footnotesize \textbf{Clinical Pathway: [CONDITION/DISEASE]}}
-\fancyhead[R]{\footnotesize Version X.X | [Date]}
-\renewcommand{\headrulewidth}{0.5pt}
-\fancyfoot[C]{\footnotesize Evidence-Based Clinical Decision Pathway | For Professional Use Only | Page \thepage}
-
-% TikZ styles
-\tikzstyle{startstop} = [rectangle, rounded corners=8pt, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=headerblue!20, font=\small\bfseries]
-\tikzstyle{decision} = [diamond, minimum width=3cm, minimum height=1.2cm, text centered, draw=black, fill=decisionyellow!40, font=\small, aspect=2, inner sep=0pt]
-\tikzstyle{process} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=black, fill=actiongreen!20, font=\small]
-\tikzstyle{urgent} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=urgentred, line width=1.5pt, fill=urgentred!15, font=\small\bfseries]
-\tikzstyle{routine} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm, text centered, draw=black, fill=routineblue!20, font=\small]
-\tikzstyle{info} = [rectangle, rounded corners=2pt, minimum width=2.5cm, minimum height=0.7cm, text centered, draw=infobox, fill=infobox!10, font=\footnotesize]
-\tikzstyle{arrow} = [thick,->,>=stealth]
-\tikzstyle{urgentarrow} = [ultra thick,->,>=stealth,color=urgentred]
-
-\setlength{\parindent}{0pt}
-
-\begin{document}
-
-\begin{center}
-{\fontsize{16}{18}\selectfont\bfseries\color{headerblue} CLINICAL DECISION PATHWAY}\\[2pt]
-{\fontsize{13}{15}\selectfont\bfseries [Disease/Condition - e.g., Acute Chest Pain Management]}\\[2pt]
-{\fontsize{10}{12}\selectfont [Institution Name] | Version X.X | Effective Date: [Date]}
-\end{center}
-
-\vspace{6pt}
-
-% Legend box
-\begin{tcolorbox}[colback=white,colframe=black,width=\textwidth]
-\begin{minipage}{0.48\textwidth}
-\textbf{Pathway Symbols:}\\[2pt]
-\begin{tikzpicture}[node distance=0.5cm]
-\node[startstop, scale=0.7] (start) {Start/End};
-\node[decision, right=1cm of start, scale=0.7] (dec) {Decision\\Point};
-\node[process, right=1cm of dec, scale=0.7] (proc) {Action/Process};
-\end{tikzpicture}
-\end{minipage}
-\begin{minipage}{0.48\textwidth}
-\textbf{Urgency Color Coding:}\\[2pt]
-\begin{tikzpicture}[node distance=0.5cm]
-\node[urgent, scale=0.7] (urg) {URGENT\\<1 hour};
-\node[process, right=1cm of urg, scale=0.7] (sem) {Semi-Urgent\\<24 hours};
-\node[routine, right=1cm of sem, scale=0.7] (rout) {Routine\\>24 hours};
-\end{tikzpicture}
-\end{minipage}
-\end{tcolorbox}
-
-\vspace{4pt}
-
-% Main flowchart
-\begin{center}
-\begin{tikzpicture}[node distance=2.2cm and 3cm, auto]
-
-% Start
-\node [startstop] (start) {Patient Presentation:\\[2pt] [Chief Complaint]};
-
-% First decision
-\node [decision, below=of start] (decision1) {[Critical\\Criteria\\Present?]};
-
-% Urgent pathway (left branch)
-\node [urgent, left=of decision1, below=1.8cm] (urgent1) {IMMEDIATE ACTION:\\[2pt] [Specific intervention]\\[2pt] Call Code/Transfer};
-
-% Continue evaluation (right branch)
-\node [process, right=of decision1, below=1.8cm] (eval1) {Continue\\Evaluation:\\[2pt][Tests/Assessment]};
-
-% Second decision
-\node [decision, below=of eval1] (decision2) {[Risk\\Score\\$\geq$X?]};
-
-% High risk pathway
-\node [urgent, left=of decision2, below=1.8cm] (high) {HIGH RISK:\\[2pt] Admit ICU/Telemetry\\[2pt] [Specific management]};
-
-% Moderate risk
-\node [process, below=of decision2] (moderate) {MODERATE RISK:\\[2pt] Admit for observation\\[2pt] Serial testing};
-
-% Low risk pathway
-\node [routine, right=of decision2, below=1.8cm] (low) {LOW RISK:\\[2pt] Outpatient management\\[2pt] Follow-up in X days};
-
-% Final outcome node
-\node [startstop, below=of moderate, node distance=2.5cm] (outcome) {Definitive Management\\Based on Results};
-
-% Arrows
-\draw [urgentarrow] (start) -- (decision1);
-\draw [urgentarrow] (decision1) -| node[near start,left] {YES} (urgent1);
-\draw [arrow] (decision1) -| node[near start,right] {NO} (eval1);
-\draw [arrow] (eval1) -- (decision2);
-\draw [arrow] (decision2) -| node[near start,left] {HIGH} (high);
-\draw [arrow] (decision2) -- node[right] {MODERATE} (moderate);
-\draw [arrow] (decision2) -| node[near start,right] {LOW} (low);
-\draw [arrow] (urgent1) |- (outcome);
-\draw [arrow] (high) |- (outcome);
-\draw [arrow] (moderate) -- (outcome);
-\draw [arrow] (low) |- (outcome);
-
-% Information boxes
-\node [info, right=1.5cm of eval1] (info1) {[Criteria]:\\[1pt] \footnotesize • Item 1\\• Item 2\\• Item 3};
-\node [info, right=1.5cm of decision2] (info2) {[Score]:\\[1pt] \footnotesize Calculate:\\risk score};
-
-\end{tikzpicture}
-\end{center}
-
-\vspace{8pt}
-
-% Detailed pathway steps
-\begin{tcolorbox}[colback=highlightgray!30,colframe=headerblue,title=\textbf{Detailed Pathway Steps},fonttitle=\bfseries]
-
-\textbf{STEP 1: Initial Assessment}
-\begin{itemize}
-\item Vital signs: BP, HR, RR, temp, O₂ saturation
-\item Focused history: [Key elements]
-\item Physical examination: [Key findings]
-\item Initial labs: [Specify tests]
-\item ECG (if applicable)
-\end{itemize}
-
-\textbf{STEP 2: Risk Stratification}
-\begin{itemize}
-\item Calculate [Risk Score Name] (see scoring table below)
-\item Identify high-risk features requiring immediate intervention
-\item Document risk category in medical record
-\end{itemize}
-
-\textbf{STEP 3: Treatment Initiation}
-\begin{itemize}
-\item Urgent: [Specific interventions within 1 hour]
-\item Semi-urgent: [Interventions within 24 hours]
-\item Routine: [Standard management approach]
-\end{itemize}
-
-\textbf{STEP 4: Monitoring and Reassessment}
-\begin{itemize}
-\item Frequency: [Based on risk category]
-\item Parameters: [What to monitor]
-\item Escalation criteria: [When to intensify treatment]
-\item De-escalation criteria: [When to transition to lower intensity]
-\end{itemize}
-
-\end{tcolorbox}
-
-\vspace{4pt}
-
-% Risk scoring table
-\begin{tcolorbox}[colback=white,colframe=headerblue,title=\textbf{[Risk Score Name] Calculation},fonttitle=\bfseries]
-{\small
-\begin{tabular}{lc}
-\toprule
-\textbf{Clinical Feature} & \textbf{Points} \\
-\midrule
-[Feature 1 - e.g., Age $\geq$65 years] & +1 \\
-[Feature 2 - e.g., Prior history] & +1 \\
-[Feature 3 - e.g., Abnormal lab value] & +2 \\
-[Feature 4 - e.g., Specific symptom] & +1 \\
-[Feature 5 - e.g., Imaging finding] & +2 \\
-\midrule
-\textbf{Total Score} & \textbf{0-X points} \\
-\bottomrule
-\end{tabular}
-
-\vspace{4pt}
-
-\textbf{Risk Categories}:
-\begin{itemize}
-\item \textbf{Low Risk}: 0-1 points → [Management approach, predicted outcome]
-\item \textbf{Moderate Risk}: 2-3 points → [Management approach, predicted outcome]
-\item \textbf{High Risk}: $\geq$4 points → [Management approach, predicted outcome]
-\end{itemize}
-}
-\end{tcolorbox}
-
-\vspace{4pt}
-
-% Evidence basis
-\begin{tcolorbox}[colback=actiongreen!5,colframe=actiongreen,title=\textbf{Evidence Basis for Pathway},fonttitle=\bfseries]
-{\small
-\textbf{Key Supporting Evidence}:
-\begin{enumerate}
-\item \textbf{[Clinical Trial/Study]}: [Key finding supporting pathway decision]
-\item \textbf{Guidelines}: NCCN/ASCO/AHA/ACC/[Relevant society] [Year] - [Recommendation level]
-\item \textbf{Meta-Analysis}: [If applicable - pooled results supporting approach]
-\end{enumerate}
-
-\textbf{Validation}: Pathway validated at [institution] with [X\%] adherence rate and [outcome metrics].
-
-\textbf{Last Updated}: [Date] based on [new trial, guideline update, or scheduled review]
-}
-\end{tcolorbox}
-
-\vspace{8pt}
-
-\hrule
-\vspace{4pt}
-{\footnotesize
-\textbf{Pathway Committee}: [Names, titles] | \textbf{Approved}: [Date] | \textbf{Next Review}: [Date]\\
-\textbf{Contact for Questions}: [Name, email, phone]
-}
-
-\end{document}
-
diff --git a/skills/clinical-decision-support/assets/cohort_analysis_template.tex b/skills/clinical-decision-support/assets/cohort_analysis_template.tex
deleted file mode 100644
index 1dc98104..00000000
--- a/skills/clinical-decision-support/assets/cohort_analysis_template.tex
+++ /dev/null
@@ -1,359 +0,0 @@
-\documentclass[10pt,letterpaper]{article}
-
-% Packages
-\usepackage[margin=0.5in]{geometry}
-\usepackage[utf8]{inputenc}
-\usepackage[T1]{fontenc}
-\usepackage{helvet}
-\renewcommand{\familydefault}{\sfdefault}
-\usepackage{xcolor}
-\usepackage{tcolorbox}
-\usepackage{array}
-\usepackage{tabularx}
-\usepackage{booktabs}
-\usepackage{enumitem}
-\usepackage{titlesec}
-\usepackage{fancyhdr}
-\usepackage{multicol}
-\usepackage{graphicx}
-\usepackage{float}
-
-% Color definitions
-\definecolor{headerblue}{RGB}{0,102,204}
-\definecolor{highlightgreen}{RGB}{0,153,76}
-\definecolor{warningred}{RGB}{204,0,0}
-\definecolor{highlightgray}{RGB}{240,240,240}
-\definecolor{biomarkerblue}{RGB}{51,102,204}
-
-% Section formatting - compact
-\titleformat{\section}{\normalfont\fontsize{11}{12}\bfseries\color{headerblue}}{\thesection}{0.5em}{}
-\titlespacing*{\section}{0pt}{4pt}{2pt}
-
-\titleformat{\subsection}{\normalfont\fontsize{10}{11}\bfseries}{\thesubsection}{0.5em}{}
-\titlespacing*{\subsection}{0pt}{3pt}{1pt}
-
-% List formatting - ultra compact
-\setlist[itemize]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-\setlist[enumerate]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-
-% Remove paragraph indentation
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{2pt}
-
-% Header/footer
-\pagestyle{fancy}
-\fancyhf{}
-\fancyhead[L]{\footnotesize \textbf{Clinical Decision Support: [COHORT NAME]}}
-\fancyhead[R]{\footnotesize Page \thepage}
-\renewcommand{\headrulewidth}{0.5pt}
-\fancyfoot[C]{\footnotesize Confidential Medical Document - For Professional Use Only}
-
-\begin{document}
-
-% Title block - compact
-\begin{center}
-{\fontsize{14}{16}\selectfont\bfseries\color{headerblue} PATIENT COHORT ANALYSIS REPORT}\\[2pt]
-{\fontsize{12}{14}\selectfont\bfseries [Cohort Description - e.g., NSCLC Patients Stratified by PD-L1 Expression]}\\[2pt]
-{\fontsize{10}{12}\selectfont [Institution/Study Name]}\\[1pt]
-{\fontsize{9}{11}\selectfont Report Date: [Date]}
-\end{center}
-
-\vspace{4pt}
-
-% Executive Summary Box
-\begin{tcolorbox}[colback=highlightgray,colframe=headerblue,title=\textbf{Executive Summary},fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Cohort}: [n=XX] patients with [disease] stratified by [biomarker/characteristic]
-
-\textbf{Key Findings}:
-\begin{itemize}
-\item [Primary finding - e.g., Biomarker+ patients had significantly longer PFS]
-\item [Secondary finding - e.g., ORR 45\% vs 30\%, p=0.023]
-\item [Safety finding - e.g., Similar toxicity profiles between groups]
-\end{itemize}
-
-\textbf{Clinical Implications}: [Treatment recommendations based on findings]
-}
-\end{tcolorbox}
-
-\vspace{2pt}
-
-\section{Cohort Characteristics}
-
-\subsection{Patient Demographics}
-
-[Narrative description of cohort composition, inclusion/exclusion criteria, time period]
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lccc}
-\toprule
-\textbf{Characteristic} & \textbf{Group A (n=XX)} & \textbf{Group B (n=XX)} & \textbf{p-value} \\
-\midrule
-Age, years (median [IQR]) & XX [XX-XX] & XX [XX-XX] & X.XX \\
-Sex, n (\%) & & & \\
-\quad Male & XX (XX\%) & XX (XX\%) & X.XX \\
-\quad Female & XX (XX\%) & XX (XX\%) & \\
-ECOG PS, n (\%) & & & \\
-\quad 0-1 & XX (XX\%) & XX (XX\%) & X.XX \\
-\quad 2 & XX (XX\%) & XX (XX\%) & \\
-Disease Stage, n (\%) & & & \\
-\quad III & XX (XX\%) & XX (XX\%) & X.XX \\
-\quad IV & XX (XX\%) & XX (XX\%) & \\
-Prior Lines of Therapy & & & \\
-\quad 0 (treatment-naïve) & XX (XX\%) & XX (XX\%) & X.XX \\
-\quad 1-2 & XX (XX\%) & XX (XX\%) & \\
-\quad $\geq$3 & XX (XX\%) & XX (XX\%) & \\
-\bottomrule
-\end{tabular}
-\caption{Baseline patient demographics and clinical characteristics}
-\end{table}
-
-\subsection{Biomarker Profile}
-
-\begin{tcolorbox}[colback=biomarkerblue!10,colframe=biomarkerblue,title=\textbf{Biomarker Stratification},fonttitle=\bfseries\small]
-{\small
-\textbf{Classification Method}: [e.g., IHC for PD-L1 expression, NGS for mutations, gene expression clustering]
-
-\textbf{Group Definitions}:
-\begin{itemize}
-\item \textbf{Group A (Biomarker+)}: [n=XX] - [Definition, e.g., PD-L1 TPS $\geq$50\%, or Mesenchymal-Immune-Active subtype]
-\item \textbf{Group B (Biomarker-)}: [n=XX] - [Definition, e.g., PD-L1 TPS <50\%]
-\end{itemize}
-
-\textbf{Molecular Features of Group A}:
-\begin{itemize}
-\item [Feature 1]: XX\% (n=XX) - [Clinical significance]
-\item [Feature 2]: XX\% (n=XX) - [Clinical significance]
-\item [Feature 3]: Elevated/decreased [marker] (median [value])
-\end{itemize}
-}
-\end{tcolorbox}
-
-\section{Treatment Exposures}
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lcc}
-\toprule
-\textbf{Treatment Received} & \textbf{Group A, n (\%)} & \textbf{Group B, n (\%)} \\
-\midrule
-[Treatment regimen 1] & XX (XX\%) & XX (XX\%) \\
-[Treatment regimen 2] & XX (XX\%) & XX (XX\%) \\
-[Treatment regimen 3] & XX (XX\%) & XX (XX\%) \\
-Median cycles received (range) & X (X-X) & X (X-X) \\
-\bottomrule
-\end{tabular}
-\caption{Treatment exposures by biomarker group}
-\end{table}
-
-\section{Treatment Outcomes}
-
-\subsection{Response Rates}
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lccc}
-\toprule
-\textbf{Response Category} & \textbf{Group A (n=XX)} & \textbf{Group B (n=XX)} & \textbf{p-value} \\
-\midrule
-Objective Response Rate (ORR) & XX\% [95\% CI] & XX\% [95\% CI] & X.XXX \\
-\quad Complete Response (CR) & XX (XX\%) & XX (XX\%) & \\
-\quad Partial Response (PR) & XX (XX\%) & XX (XX\%) & \\
-Disease Control Rate (DCR) & XX\% [95\% CI] & XX\% [95\% CI] & X.XXX \\
-\quad Stable Disease (SD) & XX (XX\%) & XX (XX\%) & \\
-Progressive Disease (PD) & XX (XX\%) & XX (XX\%) & \\
-\midrule
-Median Duration of Response (months) & X.X (95\% CI X.X-X.X) & X.X (95\% CI X.X-X.X) & X.XXX \\
-\bottomrule
-\end{tabular}
-\caption{Best overall response by biomarker group (RECIST v1.1 criteria)}
-\end{table}
-
-\subsection{Survival Outcomes}
-
-\textbf{Progression-Free Survival (PFS)}:
-\begin{itemize}
-\item Group A: Median X.X months (95\% CI X.X-X.X), 12-month PFS rate: XX\%
-\item Group B: Median X.X months (95\% CI X.X-X.X), 12-month PFS rate: XX\%
-\item Hazard Ratio: X.XX (95\% CI X.XX-X.XX), log-rank p = X.XXX
-\item \textit{[Interpretation: Group A had XX\% reduction in risk of progression compared to Group B]}
-\end{itemize}
-
-\textbf{Overall Survival (OS)}:
-\begin{itemize}
-\item Group A: Median XX.X months (95\% CI XX.X-XX.X), 12-month OS rate: XX\%
-\item Group B: Median XX.X months (95\% CI XX.X-XX.X), 12-month OS rate: XX\%
-\item Hazard Ratio: X.XX (95\% CI X.XX-X.XX), log-rank p = X.XXX
-\item \textit{[Interpretation: XX\% reduction in risk of death for Group A]}
-\end{itemize}
-
-% Note: Include Kaplan-Meier curves as figures if available
-% \begin{figure}[H]
-% \centering
-% \includegraphics[width=0.9\textwidth]{figures/pfs_by_biomarker.pdf}
-% \caption{Progression-free survival by biomarker status}
-% \end{figure}
-
-\section{Safety and Tolerability}
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lcccc}
-\toprule
-\multirow{2}{*}{\textbf{Adverse Event}} & \multicolumn{2}{c}{\textbf{Any Grade, n (\%)}} & \multicolumn{2}{c}{\textbf{Grade 3-4, n (\%)}} \\
-\cmidrule(lr){2-3} \cmidrule(lr){4-5}
-& Group A & Group B & Group A & Group B \\
-\midrule
-[AE 1 - e.g., Fatigue] & XX (XX\%) & XX (XX\%) & X (X\%) & X (X\%) \\
-[AE 2 - e.g., Nausea] & XX (XX\%) & XX (XX\%) & X (X\%) & X (X\%) \\
-[AE 3 - e.g., Neutropenia] & XX (XX\%) & XX (XX\%) & X (X\%) & X (X\%) \\
-[AE 4 - e.g., Diarrhea] & XX (XX\%) & XX (XX\%) & X (X\%) & X (X\%) \\
-[AE 5 - immune-related] & XX (XX\%) & XX (XX\%) & X (X\%) & X (X\%) \\
-\midrule
-Treatment discontinuation & XX (XX\%) & XX (XX\%) & \multicolumn{2}{c}{-} \\
-Dose reductions & XX (XX\%) & XX (XX\%) & \multicolumn{2}{c}{-} \\
-\bottomrule
-\end{tabular}
-\caption{Treatment-emergent adverse events by biomarker group (CTCAE v5.0)}
-\end{table}
-
-\section{Statistical Analysis}
-
-\subsection{Methods}
-
-\textbf{Study Design}: [Retrospective cohort analysis / Prospective cohort / Post-hoc analysis of clinical trial]
-
-\textbf{Statistical Tests}:
-\begin{itemize}
-\item Continuous variables: [t-test / Mann-Whitney U test], reported as [mean $\pm$ SD / median [IQR]]
-\item Categorical variables: Chi-square test or Fisher's exact test (if expected count <5)
-\item Survival analysis: Kaplan-Meier method, log-rank test, Cox proportional hazards regression
-\item Significance level: Two-sided p<0.05 considered statistically significant
-\item Software: [R version X.X.X, survival package / SAS / Stata / Python lifelines]
-\end{itemize}
-
-\subsection{Multivariable Analysis}
-
-Cox regression model adjusting for baseline prognostic factors:
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lccc}
-\toprule
-\textbf{Variable} & \textbf{Hazard Ratio} & \textbf{95\% CI} & \textbf{p-value} \\
-\midrule
-Biomarker+ (vs Biomarker-) & X.XX & X.XX-X.XX & X.XXX \\
-Age (per 10 years) & X.XX & X.XX-X.XX & X.XXX \\
-ECOG PS 2 (vs 0-1) & X.XX & X.XX-X.XX & X.XXX \\
-Stage IV (vs III) & X.XX & X.XX-X.XX & X.XXX \\
-[Additional variable] & X.XX & X.XX-X.XX & X.XXX \\
-\bottomrule
-\end{tabular}
-\caption{Multivariable Cox regression for progression-free survival}
-\end{table}
-
-\textbf{Interpretation}: After adjusting for age, performance status, and disease stage, [biomarker status] remained an independent predictor of [PFS/OS] (HR X.XX, 95\% CI X.XX-X.XX, p=X.XXX).
-
-\section{Clinical Implications}
-
-\begin{tcolorbox}[colback=highlightgreen!10,colframe=highlightgreen,title=\textbf{Treatment Recommendations},fonttitle=\bfseries\small]
-{\small
-\textbf{For Biomarker-Positive Patients (Group A)}:
-
-\textbf{Preferred Regimen} (GRADE 1A):
-\begin{itemize}
-\item [Specific treatment based on biomarker]
-\item Evidence: [Trial name/data showing benefit in biomarker+ population]
-\item Expected outcomes: ORR XX\%, median PFS XX months
-\end{itemize}
-
-\textbf{Monitoring}:
-\begin{itemize}
-\item Imaging every [X weeks] for response assessment
-\item [Specific lab monitoring for biomarker+ patients]
-\item Watch for [specific toxicities more common in this group]
-\end{itemize}
-
-\textbf{For Biomarker-Negative Patients (Group B)}:
-
-\textbf{Standard Regimen} (GRADE 1B):
-\begin{itemize}
-\item [Standard therapy for biomarker- population]
-\item Expected outcomes: ORR XX\%, median PFS XX months
-\item Consider [alternative approaches or clinical trial enrollment]
-\end{itemize}
-}
-\end{tcolorbox}
-
-\section{Subgroup Analyses}
-
-\textbf{Interaction Testing}: Treatment effect by biomarker subgroup (p-interaction = X.XXX)
-
-[Describe whether treatment benefit differs by biomarker status - i.e., predictive biomarker]
-
-Additional exploratory subgroups:
-\begin{itemize}
-\item Age <65 vs $\geq$65 years
-\item Sex (male vs female)
-\item Prior lines of therapy (0 vs 1+ prior treatments)
-\item Disease burden (high vs low tumor burden)
-\end{itemize}
-
-\section{Strengths and Limitations}
-
-\subsection{Strengths}
-\begin{itemize}
-\item [e.g., Biomarker-stratified analysis with prospectively defined groups]
-\item [e.g., Adequate sample size for statistical power]
-\item [e.g., Standardized response assessment using RECIST v1.1]
-\item [e.g., Multivariable analysis adjusting for confounders]
-\end{itemize}
-
-\subsection{Limitations}
-\begin{itemize}
-\item [e.g., Retrospective design with potential selection bias]
-\item [e.g., Single-institution cohort may limit generalizability]
-\item [e.g., Biomarker testing not available for all patients (XX\% tested)]
-\item [e.g., Limited follow-up for OS (median X months)]
-\item [e.g., Heterogeneous treatment regimens across cohort]
-\end{itemize}
-
-\section{Conclusions}
-
-[Paragraph summarizing key findings]
-
-[Biomarker-positive patients demonstrated [significantly better/worse] outcomes compared to biomarker-negative patients, with [outcome metric] of [values] (HR X.XX, p=X.XXX). These findings support [biomarker-guided therapy selection / routine biomarker testing / specific treatment approach].]
-
-[Future directions: Prospective validation in independent cohort, investigation of mechanisms, clinical trial design implications]
-
-\section{References}
-
-\begin{enumerate}
-\item [Reference 1 - Key clinical trial]
-\item [Reference 2 - Biomarker validation study]
-\item [Reference 3 - Guideline reference (NCCN, ASCO, ESMO)]
-\item [Reference 4 - Statistical methods reference]
-\item [Reference 5 - Additional supporting evidence]
-\end{enumerate}
-
-\vspace{10pt}
-
-\hrule
-\vspace{4pt}
-{\footnotesize
-\textbf{Report Prepared By}: [Name, Title]\\
-\textbf{Date}: [Date]\\
-\textbf{Contact}: [Email/Phone]\\
-\textbf{Institutional Review}: [IRB approval number if applicable]\\
-\textbf{Data Cut-Off Date}: [Date]\\
-\textbf{Confidentiality}: This document contains proprietary clinical data. Distribution restricted to authorized personnel only.
-}
-
-\end{document}
-
diff --git a/skills/clinical-decision-support/assets/color_schemes.tex b/skills/clinical-decision-support/assets/color_schemes.tex
deleted file mode 100644
index 6da4611b..00000000
--- a/skills/clinical-decision-support/assets/color_schemes.tex
+++ /dev/null
@@ -1,149 +0,0 @@
-% Clinical Decision Support Color Schemes
-% For use in LaTeX documents
-
-% ============================================================================
-% PRIMARY THEME COLORS
-% ============================================================================
-
-% Header and structural elements
-\definecolor{headerblue}{RGB}{0,102,204} % Section headers, titles
-\definecolor{highlightgray}{RGB}{240,240,240} % Background boxes
-
-% ============================================================================
-% RECOMMENDATION STRENGTH COLORS
-% ============================================================================
-
-% Strong recommendations (benefits clearly outweigh risks)
-\definecolor{stronggreen}{RGB}{0,153,76} % Grade 1A, 1B
-\definecolor{strongdark}{RGB}{0,120,60} % Darker variant for emphasis
-
-% Conditional recommendations (trade-offs exist)
-\definecolor{conditionalyellow}{RGB}{255,193,7} % Grade 2A, 2B, 2C
-\definecolor{conditionalamber}{RGB}{255,160,0} % Darker variant
-
-% Research/Investigational (insufficient evidence)
-\definecolor{researchblue}{RGB}{33,150,243} % Clinical trials
-\definecolor{researchdark}{RGB}{25,118,210} % Darker variant
-
-% Not recommended / Contraindicated
-\definecolor{warningred}{RGB}{204,0,0} % Strong recommendation against
-\definecolor{dangerred}{RGB}{220,20,60} % Critical warnings, urgent actions
-
-% ============================================================================
-% URGENCY LEVELS (Clinical Pathways)
-% ============================================================================
-
-\definecolor{urgentred}{RGB}{220,20,60} % Immediate action (<1 hour)
-\definecolor{semiurgent}{RGB}{255,152,0} % Action within 24 hours
-\definecolor{routineblue}{RGB}{100,181,246} % Routine care (>24 hours)
-\definecolor{actiongreen}{RGB}{0,153,76} % Standard interventions
-
-% ============================================================================
-% BIOMARKER CATEGORIES
-% ============================================================================
-
-% Alteration types
-\definecolor{mutationred}{RGB}{244,67,54} % Point mutations, SNVs
-\definecolor{amplificationblue}{RGB}{33,150,243} % Copy number gains
-\definecolor{deletionpurple}{RGB}{156,39,176} % Copy number losses
-\definecolor{fusionpurple}{RGB}{156,39,176} % Gene fusions/rearrangements
-\definecolor{expressionorange}{RGB}{255,152,0} % Expression alterations
-
-% Actionability tiers
-\definecolor{tier1green}{RGB}{0,153,76} % FDA-approved therapy
-\definecolor{tier2orange}{RGB}{255,152,0} % Clinical trial/off-label
-\definecolor{tier3gray}{RGB}{158,158,158} % VUS, no action
-
-% ============================================================================
-% STATISTICAL SIGNIFICANCE
-% ============================================================================
-
-\definecolor{significant}{RGB}{0,153,76} % p < 0.05, statistically significant
-\definecolor{trending}{RGB}{255,193,7} % p = 0.05-0.10, trending
-\definecolor{nonsignificant}{RGB}{158,158,158} % p > 0.10, not significant
-
-% ============================================================================
-% OUTCOME CATEGORIES
-% ============================================================================
-
-% Response assessment (RECIST)
-\definecolor{completeresponse}{RGB}{0,153,76} % CR (complete response)
-\definecolor{partialresponse}{RGB}{76,175,80} % PR (partial response)
-\definecolor{stabledisease}{RGB}{255,193,7} % SD (stable disease)
-\definecolor{progressivedisease}{RGB}{244,67,54} % PD (progressive disease)
-
-% Survival outcomes
-\definecolor{survivedgreen}{RGB}{0,153,76} % Patient alive
-\definecolor{eventred}{RGB}{244,67,54} % Event occurred (death, progression)
-\definecolor{censoredgray}{RGB}{158,158,158} % Censored observation
-
-% ============================================================================
-% ADVERSE EVENT SEVERITY (CTCAE)
-% ============================================================================
-
-\definecolor{grade1}{RGB}{255,235,59} % Mild
-\definecolor{grade2}{RGB}{255,193,7} % Moderate
-\definecolor{grade3}{RGB}{255,152,0} % Severe
-\definecolor{grade4}{RGB}{244,67,54} % Life-threatening
-\definecolor{grade5}{RGB}{198,40,40} % Fatal
-
-% ============================================================================
-% COLORBLIND-SAFE PALETTE (Okabe-Ito)
-% ============================================================================
-% Use these for graphs/figures to ensure accessibility
-
-\definecolor{okabe1}{RGB}{230,159,0} % Orange
-\definecolor{okabe2}{RGB}{86,180,233} % Sky blue
-\definecolor{okabe3}{RGB}{0,158,115} % Bluish green
-\definecolor{okabe4}{RGB}{240,228,66} % Yellow
-\definecolor{okabe5}{RGB}{0,114,178} % Blue
-\definecolor{okabe6}{RGB}{213,94,0} % Vermillion
-\definecolor{okabe7}{RGB}{204,121,167} % Reddish purple
-
-% ============================================================================
-% USAGE EXAMPLES
-% ============================================================================
-
-% Example 1: Strong recommendation box
-% \begin{tcolorbox}[enhanced,colback=stronggreen!10,colframe=stronggreen,
-% title={\textbf{STRONG RECOMMENDATION} \hfill \textbf{GRADE: 1A}}]
-% We recommend osimertinib for EGFR-mutated NSCLC...
-% \end{tcolorbox}
-
-% Example 2: Conditional recommendation box
-% \begin{tcolorbox}[enhanced,colback=conditionalyellow!10,colframe=conditionalyellow,
-% title={\textbf{CONDITIONAL RECOMMENDATION} \hfill \textbf{GRADE: 2B}}]
-% We suggest considering maintenance therapy...
-% \end{tcolorbox}
-
-% Example 3: Biomarker alteration
-% \colorbox{mutationred!60}{\textcolor{white}{\textbf{MUTATION}}}
-
-% Example 4: Statistical significance in table
-% \cellcolor{significant!20} p < 0.001
-
-% Example 5: Adverse event severity
-% \textcolor{grade3}{Grade 3} or \colorbox{grade3!30}{Grade 3}
-
-% ============================================================================
-% ACCESSIBILITY NOTES
-% ============================================================================
-
-% 1. Always use sufficient color contrast (4.5:1 ratio for normal text)
-% 2. Do not rely on color alone - use symbols/text as well
-% 3. Test in grayscale to ensure readability
-% 4. Use Okabe-Ito palette for colorblind accessibility in figures
-% 5. Add text labels to colored boxes ("STRONG", "CONDITIONAL", etc.)
-
-% ============================================================================
-% STYLE CONSISTENCY
-% ============================================================================
-
-% Font: Helvetica (sans-serif) for clinical documents
-% Margins: 0.5 inches for compact professional appearance
-% Font sizes: 10pt body, 11pt subsections, 12-14pt headers
-% Line spacing: Compact (minimal whitespace for dense information)
-% Boxes: tcolorbox with rounded corners, colored backgrounds at 10-20% opacity
-
-% End of color scheme definitions
-
diff --git a/skills/clinical-decision-support/assets/decision_logic_traceability_template.json b/skills/clinical-decision-support/assets/decision_logic_traceability_template.json
new file mode 100644
index 00000000..fb415f8a
--- /dev/null
+++ b/skills/clinical-decision-support/assets/decision_logic_traceability_template.json
@@ -0,0 +1,108 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "logic_id": "SYNTHETIC-RESEARCH-GOVERNANCE-001",
+ "title": "Synthetic Research Release Traceability",
+ "version": "0.1-draft",
+ "status": "draft",
+ "owner": "research governance owner",
+ "purpose": "Document evidence, validation, and human-review gates for an offline research artifact.",
+ "decision_role": "research_governance_only",
+ "data_level": "metadata_only",
+ "patient_care_use": false,
+ "executable_logic": false,
+ "change_summary": "Initial synthetic documentation example.",
+ "monitoring_plan": "Review source currency, validation status, subgroup evidence, and unresolved issues at each version.",
+ "retirement_criteria": "Retire when sources, validation evidence, ownership, or intended use are obsolete."
+ },
+ "intended_use": "Research/governance traceability only; not for patient care or live clinical use.",
+ "prohibited_uses": [
+ "No diagnosis, treatment recommendation, dosing, triage, urgency, alarm, or autonomous decision.",
+ "No care pathway, EHR rule, or executable clinical logic.",
+ "No claim of authorization or compliance."
+ ],
+ "limitations": [
+ "The matrix documents plain-language logic and does not execute it.",
+ "Source presence does not establish evidence quality.",
+ "Human review and independent validation remain required."
+ ],
+ "sources": [
+ {
+ "id": "SRC-GOV-001",
+ "citation": "Synthetic research governance procedure, version 1.",
+ "url": "not_applicable_for_local_synthetic_source",
+ "accessed": "2026-07-23"
+ }
+ ],
+ "nodes": [
+ {
+ "id": "source_gate",
+ "type": "evidence_rule",
+ "dependency_ids": [],
+ "precondition": "An evidence record is proposed for the research artifact.",
+ "logic_statement": "Check for a stable citation, source version, and retrieval date.",
+ "output_kind": "flag_for_review",
+ "output_value": "missing_source_provenance when any required source field is absent",
+ "source_ids": [
+ "SRC-GOV-001"
+ ],
+ "rationale": "Reviewers need reproducible source provenance.",
+ "validation_tests": [
+ "Complete source fields produce no provenance flag.",
+ "Missing retrieval date produces missing_source_provenance."
+ ],
+ "owner": "evidence review owner",
+ "reviewer_role": "independent methodologist",
+ "status": "draft"
+ },
+ {
+ "id": "validation_gate",
+ "type": "validation_gate",
+ "dependency_ids": [
+ "source_gate"
+ ],
+ "precondition": "Source provenance is complete.",
+ "logic_statement": "Check whether independent external validation and subgroup uncertainty are documented.",
+ "output_kind": "release_hold",
+ "output_value": "true when required validation documentation is absent",
+ "source_ids": [
+ "SRC-GOV-001"
+ ],
+ "rationale": "Transportability claims require independent evidence and uncertainty.",
+ "validation_tests": [
+ "Missing external-validation evidence produces a release hold.",
+ "Complete validation evidence passes to human review."
+ ],
+ "owner": "validation owner",
+ "reviewer_role": "independent statistician",
+ "status": "draft"
+ },
+ {
+ "id": "human_review_gate",
+ "type": "human_review",
+ "dependency_ids": [
+ "validation_gate"
+ ],
+ "precondition": "Required documentation gates are complete.",
+ "logic_statement": "Require recorded review by the accountable method, domain, privacy, and governance roles.",
+ "output_kind": "documentation_status",
+ "output_value": "pending until all accountable review roles record a decision",
+ "source_ids": [
+ "SRC-GOV-001"
+ ],
+ "rationale": "Automated structural checks cannot approve a research artifact.",
+ "validation_tests": [
+ "Absent reviewer decision produces pending status.",
+ "Recorded reviewer decisions produce complete documentation status."
+ ],
+ "owner": "governance owner",
+ "reviewer_role": "authorized governance approver",
+ "status": "draft"
+ }
+ ],
+ "human_review": {
+ "required": true,
+ "completed": false,
+ "approval_boundary": "Only the accountable organization can approve a research artifact; this matrix never authorizes clinical use."
+ }
+}
diff --git a/skills/clinical-decision-support/assets/deidentification_checklist_template.json b/skills/clinical-decision-support/assets/deidentification_checklist_template.json
new file mode 100644
index 00000000..60e893f9
--- /dev/null
+++ b/skills/clinical-decision-support/assets/deidentification_checklist_template.json
@@ -0,0 +1,176 @@
+{
+ "schema_version": "1.0",
+ "checklist_id": "REPLACE_WITH_CHECKLIST_ID",
+ "title": "De-identification Process Documentation Checklist",
+ "method": "undecided",
+ "intended_use": "Document qualified human review without supplying a dataset.",
+ "prohibited_uses": [
+ "Do not paste PHI, raw rows, notes, images, sequences, or example identifiers.",
+ "Do not claim de-identification, HIPAA compliance, or publication safety from this checklist."
+ ],
+ "limitations": [
+ "The script does not inspect or transform data.",
+ "The checklist cannot determine covered-entity status or legal obligations.",
+ "Residual linkage and differencing risks require contextual expert review."
+ ],
+ "data_boundary": {
+ "raw_data_supplied": false,
+ "metadata_only": true,
+ "data_context": "REPLACE_WITH_HIGH_LEVEL_DATA_CONTEXT_WITHOUT_SENSITIVE_VALUES",
+ "recipient_context": "REPLACE_WITH_RECIPIENT_AND_ACCESS_CONTEXT",
+ "release_context": "REPLACE_WITH_RELEASE, ACCESS, AND PRIOR-RELEASE_CONTEXT"
+ },
+ "source_ids": [
+ "HHS-DEID",
+ "CFR-164514"
+ ],
+ "sources": [
+ {
+ "id": "HHS-DEID",
+ "citation": "HHS OCR. Guidance Regarding Methods for De-identification of Protected Health Information.",
+ "url": "https://www.hhs.gov/hipaa/for-professionals/special-topics/de-identification/index.html",
+ "accessed": "2026-07-23"
+ },
+ {
+ "id": "CFR-164514",
+ "citation": "45 CFR 164.514, Other requirements relating to uses and disclosures of protected health information.",
+ "url": "https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-E/section-164.514",
+ "accessed": "2026-07-23"
+ }
+ ],
+ "identifier_categories": [
+ {
+ "id": "names",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "geography",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "dates_and_ages",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "telephone_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "fax_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "email_addresses",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "social_security_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "medical_record_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "health_plan_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "account_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "certificate_license_numbers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "vehicle_identifiers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "device_identifiers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "web_urls",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "ip_addresses",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "biometric_identifiers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "full_face_images",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ },
+ {
+ "id": "other_unique_identifiers",
+ "status": "unresolved",
+ "evidence": "REQUIRES_HUMAN_DOCUMENTATION_WITHOUT_VALUES"
+ }
+ ],
+ "safe_harbor_review": {
+ "actual_knowledge": "REQUIRES_HUMAN_REVIEW",
+ "free_text": "REQUIRES_HUMAN_REVIEW",
+ "derived_fields": "REQUIRES_HUMAN_REVIEW",
+ "date_age_zip_rules": "REQUIRES_HUMAN_REVIEW",
+ "reviewer_role": "REPLACE_WITH_QUALIFIED_ROLE",
+ "review_date": "YYYY-MM-DD",
+ "completed": false
+ },
+ "expert_determination_review": {
+ "expert_qualification_reference": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "method_document_reference": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "risk_threshold_rationale": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "residual_risk": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "validity_period": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "change_triggers": "REQUIRES_QUALIFIED_EXPERT_IF_SELECTED",
+ "review_date": "YYYY-MM-DD",
+ "completed": false
+ },
+ "residual_risk_review": {
+ "linkage": "REQUIRES_HUMAN_REVIEW",
+ "differencing": "REQUIRES_HUMAN_REVIEW",
+ "rare_combinations": "REQUIRES_HUMAN_REVIEW",
+ "longitudinal_patterns": "REQUIRES_HUMAN_REVIEW",
+ "geography": "REQUIRES_HUMAN_REVIEW",
+ "genomics": "REQUIRES_HUMAN_REVIEW",
+ "prior_releases": "REQUIRES_HUMAN_REVIEW",
+ "completed": false
+ },
+ "human_review": {
+ "required": true,
+ "role": "qualified privacy reviewer or de-identification expert",
+ "completed": false,
+ "approval_boundary": "Completion documents a process only and does not establish de-identification or HIPAA compliance."
+ },
+ "governance": {
+ "version": "0.1-draft",
+ "owner": "REPLACE_WITH_PRIVACY_GOVERNANCE_OWNER_ROLE",
+ "change_summary": "Initial unresolved template.",
+ "auditability": "Retain method documentation, assumptions, approvals, release context, and change triggers without sensitive values.",
+ "monitoring": "Reassess when data, recipients, linkage sources, prior releases, or release conditions change."
+ },
+ "compliance_claims": false
+}
diff --git a/skills/clinical-decision-support/assets/evidence_profile_template.json b/skills/clinical-decision-support/assets/evidence_profile_template.json
new file mode 100644
index 00000000..7389fdcd
--- /dev/null
+++ b/skills/clinical-decision-support/assets/evidence_profile_template.json
@@ -0,0 +1,139 @@
+{
+ "schema_version": "1.0",
+ "profile_id": "REPLACE_WITH_PROFILE_ID",
+ "title": "Human-Judged GRADE Evidence Profile",
+ "data_level": "published_aggregate_evidence",
+ "human_judgments_required": true,
+ "auto_grade": false,
+ "intended_use": "Research evidence synthesis and panel documentation only.",
+ "prohibited_uses": [
+ "No automatic evidence grade or recommendation strength.",
+ "No patient-specific diagnosis, treatment recommendation, dosing, triage, alarm, or autonomous decision.",
+ "No claim of clinical, regulatory, legal, or HIPAA compliance."
+ ],
+ "limitations": [
+ "No certainty judgment is inferred from text or study design.",
+ "Certainty is outcome-specific.",
+ "Recommendation development requires a separate human Evidence-to-Decision process."
+ ],
+ "human_review": {
+ "required": true,
+ "roles": [
+ "systematic-review methodologist",
+ "domain expert",
+ "GRADE panel chair"
+ ],
+ "completed": false
+ },
+ "governance": {
+ "version": "0.1-draft",
+ "owner": "REPLACE_WITH_EVIDENCE_PROFILE_OWNER_ROLE",
+ "change_summary": "Initial unresolved template.",
+ "auditability": "Retain searches, selection decisions, source versions, domain judgments, disagreements, and approvals.",
+ "update_plan": "Define surveillance, update triggers, supersession, and retirement."
+ },
+ "question": {
+ "population": "REPLACE_WITH_DEFINED_POPULATION",
+ "intervention_or_exposure": "REPLACE_WITH_INTERVENTION_OR_EXPOSURE",
+ "comparator": "REPLACE_WITH_COMPARATOR",
+ "setting": "REPLACE_WITH_SETTING",
+ "outcomes": [
+ "REPLACE_WITH_IMPORTANT_OUTCOME_AND_TIME_HORIZON"
+ ]
+ },
+ "sources": [
+ {
+ "id": "SRC-001",
+ "citation": "REPLACE_WITH_FULL_CITATION",
+ "url": "REPLACE_WITH_CANONICAL_URL",
+ "accessed": "YYYY-MM-DD"
+ }
+ ],
+ "outcomes": [
+ {
+ "name": "REPLACE_WITH_OUTCOME",
+ "importance": "critical",
+ "effect_measure": "REPLACE_WITH_EFFECT_MEASURE",
+ "effect_estimate": "REPLACE_WITH_ABSOLUTE_AND_RELATIVE_EFFECTS",
+ "uncertainty_interval": "REPLACE_WITH_INTERVAL",
+ "participants": "REPLACE_WITH_NUMBER_AND_ANALYSIS_POPULATION",
+ "studies": "REPLACE_WITH_NUMBER_AND_DESIGNS",
+ "time_horizon": "REPLACE_WITH_TIME_HORIZON",
+ "domains": {
+ "risk_of_bias": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_REVIEWER_ROLE",
+ "source_ids": [
+ "SRC-001"
+ ]
+ },
+ "inconsistency": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_REVIEWER_ROLE",
+ "source_ids": [
+ "SRC-001"
+ ]
+ },
+ "indirectness": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_REVIEWER_ROLE",
+ "source_ids": [
+ "SRC-001"
+ ]
+ },
+ "imprecision": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_REVIEWER_ROLE",
+ "source_ids": [
+ "SRC-001"
+ ]
+ },
+ "publication_bias": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_REVIEWER_ROLE",
+ "source_ids": [
+ "SRC-001"
+ ]
+ }
+ },
+ "upgrading": {
+ "large_effect": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "source_ids": []
+ },
+ "dose_response": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "source_ids": []
+ },
+ "residual_confounding": {
+ "judgment": "unassessed",
+ "rationale": "REQUIRES_HUMAN_JUDGMENT",
+ "source_ids": []
+ }
+ },
+ "certainty": {
+ "human_judgment": false,
+ "level": "unassessed",
+ "rationale": "REQUIRES_HUMAN_PANEL_JUDGMENT",
+ "reviewer_role": "REPLACE_WITH_PANEL_ROLE",
+ "judgment_date": "YYYY-MM-DD",
+ "source_ids": [
+ "SRC-001"
+ ]
+ }
+ }
+ ],
+ "profile_review": {
+ "prepared_by_role": "REPLACE_WITH_ROLE",
+ "reviewed_by_role": "REPLACE_WITH_ROLE",
+ "review_date": "YYYY-MM-DD",
+ "completed": false
+ }
+}
diff --git a/skills/clinical-decision-support/assets/example_gbm_cohort.md b/skills/clinical-decision-support/assets/example_gbm_cohort.md
deleted file mode 100644
index aeec9957..00000000
--- a/skills/clinical-decision-support/assets/example_gbm_cohort.md
+++ /dev/null
@@ -1,208 +0,0 @@
-# Example: GBM Molecular Subtype Cohort Analysis
-
-## Clinical Context
-
-This example demonstrates a patient cohort analysis stratified by molecular biomarkers, similar to the GBM Mesenchymal-Immune-Active cluster analysis provided as reference.
-
-## Cohort Overview
-
-**Disease**: Glioblastoma (GBM), IDH-wild-type
-
-**Study Population**: n=60 patients with newly diagnosed GBM treated with standard Stupp protocol (temozolomide + radiation → adjuvant temozolomide)
-
-**Molecular Classification**: Verhaak 2010 subtypes with immune signature refinement
-- **Group A**: Mesenchymal-Immune-Active subtype (n=18, 30%)
-- **Group B**: Other molecular subtypes (Proneural, Classical, Neural) (n=42, 70%)
-
-**Study Period**: January 2019 - December 2022
-
-**Data Source**: Single academic medical center, retrospective cohort analysis
-
-## Biomarker Classification
-
-### Mesenchymal-Immune-Active Subtype Characteristics
-
-**Molecular Features**:
-- NF1 alterations (mutations or deletions): 72% (13/18)
-- High YKL-40 (CHI3L1) expression: 100% (18/18, median z-score +2.8)
-- Immune gene signature: Elevated (median ESTIMATE immune score +1250)
-- CD163+ macrophage infiltration: High density (median 195 cells/mm², range 120-340)
-- MES (mesenchymal) signature score: >0.5 (all patients)
-
-**Clinical Characteristics**:
-- Median age: 64 years (range 42-76)
-- Male: 61% (11/18)
-- Tumor location: Temporal lobe predominant (55%)
-- Multifocal disease: 33% (6/18) - higher than overall cohort
-
-### Comparison Groups (Other Subtypes)
-
-**Molecular Features**:
-- Proneural: n=15 (25%) - PDGFRA amplification, younger age
-- Classical: n=18 (30%) - EGFR amplification, chromosome 7+/10-
-- Neural: n=9 (15%) - neuronal markers, may include normal tissue
-
-## Treatment Outcomes
-
-### Response Assessment (RANO Criteria)
-
-**Objective Response Rate** (after chemoradiation, ~3 months):
-- Mesenchymal-Immune-Active: 6/18 (33%) - CR 0, PR 6
-- Other subtypes: 18/42 (43%) - CR 1, PR 17
-- p = 0.48 (Fisher's exact)
-
-**Interpretation**: No significant difference in initial response rates
-
-### Survival Outcomes
-
-**Progression-Free Survival (PFS)**:
-- Mesenchymal-Immune-Active: Median 7.2 months (95% CI 5.8-9.1)
-- Other subtypes: Median 9.5 months (95% CI 8.1-11.3)
-- Hazard Ratio: 1.58 (95% CI 0.89-2.81), p = 0.12
-- 6-month PFS rate: 61% vs 74%
-
-**Overall Survival (OS)**:
-- Mesenchymal-Immune-Active: Median 12.8 months (95% CI 10.2-15.4)
-- Other subtypes: Median 16.3 months (95% CI 14.7-18.9)
-- Hazard Ratio: 1.72 (95% CI 0.95-3.11), p = 0.073
-- 12-month OS rate: 55% vs 68%
-- 24-month OS rate: 17% vs 31%
-
-**Interpretation**: Trend toward worse survival in mesenchymal-immune-active subtype, not reaching statistical significance in this cohort size
-
-### Response to Bevacizumab at Recurrence
-
-**Subset Analysis** (patients receiving bevacizumab at first recurrence, n=35):
-- Mesenchymal-Immune-Active: n=12
- - ORR: 58% (7/12)
- - Median PFS2 (from bevacizumab start): 6.8 months
-- Other subtypes: n=23
- - ORR: 35% (8/23)
- - Median PFS2: 4.2 months
-- p = 0.19 (Fisher's exact for ORR)
-- HR for PFS2: 0.62 (95% CI 0.29-1.32), p = 0.21
-
-**Interpretation**: Exploratory finding suggesting enhanced benefit from bevacizumab in mesenchymal-immune-active subtype (not statistically significant with small sample)
-
-## Safety Profile
-
-**Treatment-Related Adverse Events** (Temozolomide):
-
-No significant differences in toxicity between molecular subtypes:
-- Lymphopenia (any grade): 89% vs 86%, p = 0.77
-- Thrombocytopenia (grade 3-4): 22% vs 19%, p = 0.79
-- Fatigue (any grade): 94% vs 90%, p = 0.60
-- Treatment discontinuation: 17% vs 14%, p = 0.77
-
-## Clinical Implications
-
-### Treatment Recommendations
-
-**For Mesenchymal-Immune-Active GBM**:
-
-1. **First-Line**: Standard Stupp protocol (no change based on subtype)
- - Evidence: No proven benefit for alternative first-line strategies
- - GRADE: 1A (strong recommendation, high-quality evidence)
-
-2. **At Recurrence - Consider Bevacizumab Earlier**:
- - Rationale: Exploratory data suggesting enhanced anti-angiogenic response
- - Evidence: Mesenchymal GBM has high VEGF expression, angiogenic phenotype
- - GRADE: 2C (conditional recommendation, low-quality evidence from subset)
-
-3. **Clinical Trial Enrollment - Immunotherapy Combinations**:
- - Rationale: High immune cell infiltration may predict immunotherapy benefit
- - Targets: PD-1/PD-L1 blockade ± anti-CTLA-4 or anti-angiogenic agents
- - Evidence: Ongoing trials (CheckMate-498, CheckMate-548 showed negative results, but did not select for immune-active)
- - GRADE: R (research recommendation)
-
-**For Other GBM Subtypes**:
-- Standard treatment per NCCN guidelines
-- Consider tumor treating fields (Optune) after radiation completion
-- Clinical trials based on specific molecular features (EGFR amplification → EGFR inhibitor trials)
-
-### Prognostic Information
-
-**Counseling Patients**:
-- Mesenchymal-immune-active subtype associated with trend toward shorter survival (12.8 vs 16.3 months)
-- Not definitive due to small sample size and confidence intervals overlapping
-- Prospective validation needed
-- Should not alter standard first-line treatment
-
-## Study Limitations
-
-1. **Small Sample Size**: n=18 in mesenchymal-immune-active group limits statistical power
-2. **Retrospective Design**: Potential selection bias, unmeasured confounders
-3. **Single Institution**: May not generalize to other populations
-4. **Heterogeneous Recurrence Treatment**: Not all patients received bevacizumab; treatment selection bias
-5. **Molecular Classification**: Based on bulk tumor RNA-seq; intratumoral heterogeneity not captured
-6. **No Central Pathology Review**: Molecular classification performed locally
-
-## Future Directions
-
-1. **Prospective Validation**: Confirm survival differences in independent cohort (n>100 per group for adequate power)
-2. **Biomarker Testing**: Develop clinically feasible assay for mesenchymal-immune subtype identification
-3. **Clinical Trial Design**: Immunotherapy combinations targeting mesenchymal-immune-active GBM specifically
-4. **Mechanistic Studies**: Investigate why mesenchymal-immune GBM may respond better to bevacizumab
-5. **Longitudinal Analysis**: Track molecular subtype evolution over treatment course
-
-## Data Presentation Example
-
-### Baseline Characteristics Table
-
-```
-Characteristic Mesenchymal-IA (n=18) Other (n=42) p-value
-Age, years (median [IQR]) 64 [56-71] 61 [53-68] 0.42
-Sex, n (%)
- Male 11 (61%) 24 (57%) 0.78
- Female 7 (39%) 18 (43%)
-ECOG PS, n (%)
- 0-1 15 (83%) 37 (88%) 0.63
- 2 3 (17%) 5 (12%)
-Tumor location
- Frontal 4 (22%) 15 (36%) 0.35
- Temporal 10 (56%) 16 (38%)
- Parietal/Occipital 4 (22%) 11 (26%)
-Extent of resection
- Gross total 8 (44%) 22 (52%) 0.58
- Subtotal 10 (56%) 20 (48%)
-MGMT promoter methylated 5 (28%) 18 (43%) 0.27
-```
-
-### Survival Outcomes Summary
-
-```
-Endpoint Mesenchymal-IA Other HR (95% CI) p-value
-Median PFS, months (95% CI) 7.2 (5.8-9.1) 9.5 (8.1-11.3) 1.58 (0.89-2.81) 0.12
-6-month PFS rate 61% 74%
-Median OS, months (95% CI) 12.8 (10.2-15.4) 16.3 (14.7-18.9) 1.72 (0.95-3.11) 0.073
-12-month OS rate 55% 68%
-24-month OS rate 17% 31%
-```
-
-## Key Takeaways
-
-1. **Molecular heterogeneity exists** in GBM with distinct subtypes
-2. **Mesenchymal-immune-active subtype** characterized by NF1 alterations, immune infiltration
-3. **Trend toward worse prognosis** but not statistically significant (power limitations)
-4. **Potential bevacizumab benefit** hypothesis-generating, requires prospective validation
-5. **Immunotherapy target**: High immune infiltration rational for checkpoint inhibitor trials
-6. **Clinical implementation pending**: Need prospective validation before routine subtyping
-
-## References
-
-1. Verhaak RG, et al. Integrated genomic analysis identifies clinically relevant subtypes of glioblastoma characterized by abnormalities in PDGFRA, IDH1, EGFR, and NF1. Cancer Cell. 2010;17(1):98-110.
-2. Wang Q, et al. Tumor Evolution of Glioma-Intrinsic Gene Expression Subtypes Associates with Immunological Changes in the Microenvironment. Cancer Cell. 2017;32(1):42-56.
-3. Stupp R, et al. Radiotherapy plus Concomitant and Adjuvant Temozolomide for Glioblastoma. NEJM. 2005;352(10):987-996.
-4. Gilbert MR, et al. Bevacizumab for Newly Diagnosed Glioblastoma. NEJM. 2014;370(8):699-708.
-5. NCCN Clinical Practice Guidelines in Oncology: Central Nervous System Cancers. Version 1.2024.
-
----
-
-**This example demonstrates**:
-- Biomarker-based stratification methodology
-- Outcome reporting with appropriate statistics
-- Clinical contextualization of findings
-- Evidence-based recommendations with grading
-- Transparent limitation discussion
-- Structure suitable for pharmaceutical/clinical research documentation
-
diff --git a/skills/clinical-decision-support/assets/recommendation_strength_guide.md b/skills/clinical-decision-support/assets/recommendation_strength_guide.md
deleted file mode 100644
index 8f0637fa..00000000
--- a/skills/clinical-decision-support/assets/recommendation_strength_guide.md
+++ /dev/null
@@ -1,328 +0,0 @@
-# Recommendation Strength Guide
-
-## GRADE Framework for Clinical Recommendations
-
-### Components of a Recommendation
-
-Every clinical recommendation should address:
-
-1. **Population**: Who should receive the intervention?
-2. **Intervention**: What specific treatment/action?
-3. **Comparator**: Compared to what alternative?
-4. **Outcome**: What are the expected results?
-5. **Strength**: How strong is the recommendation?
-6. **Quality of Evidence**: How confident are we in the evidence?
-
-### Recommendation Strength (Grade 1 vs Grade 2)
-
-#### Strong Recommendation (Grade 1)
-
-**When to Use**:
-- Desirable effects clearly outweigh undesirable effects (or vice versa)
-- High or moderate quality evidence
-- Values and preferences: Little variability expected
-- Resource implications: Cost-effective or cost considerations minor
-
-**Wording**: "We recommend..." or "Clinicians should..."
-
-**Implications**:
-- Most patients should receive the recommended intervention
-- Adherence to recommendation could be a quality indicator
-- Policy-makers can adapt as performance measure
-
-**Examples**:
-
-```
-STRONG RECOMMENDATION FOR (Grade 1):
-
-"We recommend osimertinib 80 mg daily as first-line therapy for adults with
-advanced NSCLC harboring EGFR exon 19 deletion or L858R mutation (Strong
-recommendation, High-quality evidence - GRADE 1A)."
-
-Rationale:
-- Large PFS benefit: 18.9 vs 10.2 months (HR 0.46, p<0.001)
-- OS benefit: 38.6 vs 31.8 months (HR 0.80, p=0.046)
-- Better tolerability: Lower grade 3-4 AEs
-- Evidence: High-quality (large RCT, low risk of bias)
-- Benefits clearly outweigh harms
-```
-
-```
-STRONG RECOMMENDATION AGAINST (Grade 1):
-
-"We recommend against using bevacizumab in the first-line treatment of newly
-diagnosed glioblastoma to improve overall survival (Strong recommendation against,
-High-quality evidence - GRADE 1A)."
-
-Rationale:
-- No OS benefit: HR 0.88 (0.76-1.02), p=0.10 (AVAglio trial)
-- Toxicity: Increased grade ≥3 AEs (66% vs 52%)
-- Evidence: High-quality (two large phase 3 RCTs)
-- Harms outweigh lack of survival benefit
-```
-
-#### Conditional/Weak Recommendation (Grade 2)
-
-**When to Use**:
-- Desirable and undesirable effects closely balanced
-- Low or very low quality evidence
-- Values and preferences: Substantial variability
-- Resource implications: High cost or limited access
-
-**Wording**: "We suggest..." or "Clinicians might..."
-
-**Implications**:
-- Different choices will be appropriate for different patients
-- Shared decision-making essential
-- Policy-making requires substantial debate and stakeholder involvement
-
-**Examples**:
-
-```
-CONDITIONAL RECOMMENDATION FOR (Grade 2):
-
-"We suggest considering maintenance pemetrexed after first-line platinum-pemetrexed
-chemotherapy for advanced non-squamous NSCLC in patients without disease progression
-(Conditional recommendation, Moderate-quality evidence - GRADE 2B)."
-
-Rationale:
-- Modest PFS benefit: 4.0 vs 2.0 months (HR 0.62)
-- No OS benefit: 13.9 vs 11.0 months (HR 0.79, p=0.23)
-- Toxicity: Continued chemotherapy burden
-- Quality of life: Trade-off between symptom control and treatment side effects
-- Patient values: Some prioritize time off treatment, others prioritize disease control
-- Shared decision-making essential
-```
-
-```
-CONDITIONAL RECOMMENDATION - EITHER OPTION ACCEPTABLE (Grade 2):
-
-"We suggest either pembrolizumab monotherapy OR pembrolizumab plus platinum-doublet
-chemotherapy as first-line treatment for PD-L1 ≥50% NSCLC, based on patient
-preferences and clinical factors (Conditional recommendation, High-quality evidence -
-GRADE 2A)."
-
-Rationale:
-- Both regimens NCCN Category 1 preferred
-- Monotherapy: Less toxicity, oral vs IV, better quality of life
-- Combination: Higher ORR (48% vs 39%), numerically longer PFS
-- OS: Similar between strategies
-- Patient values: Varies widely (tolerability vs response rate priority)
-```
-
-### Evidence Quality (⊕⊕⊕⊕ to ⊕○○○)
-
-#### High Quality (⊕⊕⊕⊕)
-
-- Further research very unlikely to change confidence in effect estimate
-- Consistent results from well-designed RCTs
-- No serious limitations
-- Direct evidence (target population, intervention, outcomes)
-- Precise estimate (narrow CI)
-
-**Example**: FLAURA trial for osimertinib in EGFR+ NSCLC - Large RCT, consistent results, low risk of bias, direct outcomes
-
-#### Moderate Quality (⊕⊕⊕○)
-
-- Further research likely to impact confidence and may change estimate
-- RCTs with some limitations OR very strong evidence from observational studies
-- Some inconsistency, indirectness, imprecision, or publication bias
-
-**Example**: Single RCT with some limitations, or multiple RCTs with moderate heterogeneity
-
-#### Low Quality (⊕⊕○○)
-
-- Further research very likely to have important impact on confidence in estimate
-- Observational studies OR RCTs with serious limitations
-- Serious issues with consistency, directness, precision, or bias
-
-**Example**: Well-conducted cohort study, or RCT with high attrition and unclear allocation concealment
-
-#### Very Low Quality (⊕○○○)
-
-- Estimate of effect very uncertain
-- Case series, expert opinion, mechanistic reasoning
-- Very serious limitations
-
-**Example**: Retrospective case series, expert consensus without systematic review
-
-## Combining Strength and Quality
-
-### All Nine Possible Combinations
-
-| Evidence Quality | Strong For (↑↑) | Weak For (↑) | Strong Against (↓↓) | Weak Against (↓) |
-|-----------------|----------------|--------------|---------------------|------------------|
-| **High (⊕⊕⊕⊕)** | Grade 1A | Grade 2A | Grade 1A (against) | Grade 2A (against) |
-| **Moderate (⊕⊕⊕○)** | Grade 1B | Grade 2B | Grade 1B (against) | Grade 2B (against) |
-| **Low (⊕⊕○○)** | Grade 1C* | Grade 2C | Grade 1C (against)* | Grade 2C (against) |
-| **Very Low (⊕○○○)** | Grade 1D* | Grade 2D | Grade 1D (against)* | Grade 2D (against) |
-
-*Rare: Strong recommendations usually require at least moderate-quality evidence
-
-### Unusual Combinations (When They Occur)
-
-**Strong Recommendation with Low Quality Evidence (Grade 1C)**
-
-Rare, but can occur when:
-- Large magnitude of effect from observational data (RR >5 or <0.2)
-- Low quality evidence, but clear benefit-harm balance
-- Example: Anticoagulation for atrial fibrillation (before RCTs, strong observational data)
-
-**Weak Recommendation with High Quality Evidence (Grade 2A)**
-
-Occurs when:
-- Benefits and harms closely balanced
-- Patient values highly variable
-- Example: Aspirin for primary prevention in low-risk individuals (benefits small, bleeding risk present, patient values vary)
-
-## Wording Templates
-
-### Strong Recommendations
-
-**FOR (↑↑)**:
-- "We recommend [intervention] for [population]."
-- "Clinicians should [action]."
-- "[Intervention] is recommended."
-
-**AGAINST (↓↓)**:
-- "We recommend against [intervention] for [population]."
-- "Clinicians should not [action]."
-- "[Intervention] is not recommended."
-
-### Conditional/Weak Recommendations
-
-**FOR (↑)**:
-- "We suggest [intervention] for [population]."
-- "Clinicians might consider [action]."
-- "[Intervention] may be considered for selected patients."
-
-**AGAINST (↓)**:
-- "We suggest not using [intervention] for [population]."
-- "Clinicians might avoid [action]."
-- "[Intervention] is generally not recommended."
-
-**EITHER ACCEPTABLE**:
-- "We suggest either [option A] or [option B] based on patient preferences."
-- "Either approach is reasonable."
-
-## Color Coding for Visual Documents
-
-**Strong Recommendations (Green Background)**:
-- RGB(0, 153, 76) or #009954
-- Clear visual priority
-- Use for Grade 1A, 1B
-
-**Conditional Recommendations (Yellow Background)**:
-- RGB(255, 193, 7) or #FFC107
-- Indicates discussion needed
-- Use for Grade 2A, 2B, 2C
-
-**Research/Investigational (Blue Background)**:
-- RGB(33, 150, 243) or #2196F3
-- Clinical trial consideration
-- Insufficient evidence for standard care
-
-**Not Recommended (Red Border/Background)**:
-- RGB(220, 20, 60) or #DC143C
-- Strong recommendation against
-- Evidence of harm or no benefit
-
-## Common Scenarios
-
-### Scenario 1: Strong Evidence, Clear Benefit-Harm Balance
-
-**Example**: Pembrolizumab for PD-L1 ≥50% NSCLC
-
-- Evidence: Large phase 3 RCT (KEYNOTE-024), n=305, well-designed
-- Results: PFS HR 0.50 (0.37-0.68), OS HR 0.60 (0.41-0.89)
-- Toxicity: Lower grade 3-5 AEs than chemotherapy (27% vs 53%)
-- Patient values: Most prioritize efficacy and tolerability
-
-**Recommendation**: STRONG FOR (Grade 1A)
-
-### Scenario 2: Moderate Evidence, Balanced Trade-Offs
-
-**Example**: Adjuvant immunotherapy for resected melanoma
-
-- Evidence: RCT showing relapse-free survival benefit, OS data immature
-- Results: Recurrence risk reduced but ongoing toxicity
-- Toxicity: Immune-related AEs requiring steroids (some severe)
-- Cost: High annual cost for 12 months treatment
-- Patient values: Variable (some prioritize recurrence prevention, others avoid toxicity)
-
-**Recommendation**: CONDITIONAL FOR (Grade 2B)
-
-### Scenario 3: Low Evidence, but Severe Consequence
-
-**Example**: Anticoagulation for prosthetic heart valve
-
-- Evidence: No RCTs (would be unethical), observational data and mechanistic reasoning
-- Consequence: Very high thromboembolic risk without anticoagulation
-- Benefit-harm: Clear despite low quality evidence
-
-**Recommendation**: STRONG FOR (Grade 1C)
-
-### Scenario 4: High Evidence, but Patient Preferences Vary
-
-**Example**: Breast reconstruction after mastectomy
-
-- Evidence: High-quality data on outcomes and satisfaction
-- Trade-offs: Cosmetic benefit vs additional surgery, recovery time
-- Values: Highly personal decision, wide preference variability
-
-**Recommendation**: CONDITIONAL (Grade 2A) - discuss options, patient decides
-
-## Documentation Template
-
-```
-RECOMMENDATION: [State recommendation clearly]
-
-Strength: [STRONG / CONDITIONAL]
-Quality of Evidence: [HIGH / MODERATE / LOW / VERY LOW]
-GRADE: [1A / 1B / 2A / 2B / 2C]
-
-Evidence Summary:
-- Primary study: [Citation]
-- Design: [RCT / Observational / Meta-analysis]
-- Sample size: n = [X]
-- Results: [Primary outcome with effect size, CI, p-value]
-- Quality assessment: [Strengths and limitations]
-
-Benefits:
-- [Quantified benefit 1]
-- [Quantified benefit 2]
-
-Harms:
-- [Quantified harm 1]
-- [Quantified harm 2]
-
-Balance: [Benefits clearly outweigh harms / Close balance requiring discussion / etc.]
-
-Values and Preferences: [Little variability / Substantial variability]
-
-Cost Considerations: [If relevant]
-
-Guideline Concordance:
-- NCCN: [Category and recommendation]
-- ASCO: [Recommendation]
-- ESMO: [Grade and recommendation]
-```
-
-## Quality Checklist
-
-Before finalizing recommendations, verify:
-
-- [ ] Recommendation statement is clear and actionable
-- [ ] Strength is explicitly stated (strong vs conditional)
-- [ ] Quality of evidence is graded (high/moderate/low/very low)
-- [ ] GRADE notation provided (1A, 1B, 2A, 2B, 2C)
-- [ ] Evidence is cited with specific study results
-- [ ] Benefits are quantified (effect sizes with CIs)
-- [ ] Harms are quantified (AE rates)
-- [ ] Balance of benefits/harms is explained
-- [ ] Patient values consideration is addressed (if conditional)
-- [ ] Alternative options are mentioned
-- [ ] Guideline concordance is documented
-- [ ] Special populations are addressed (elderly, renal/hepatic impairment)
-- [ ] Monitoring requirements are specified
-
diff --git a/skills/clinical-decision-support/assets/survival_analysis_plan_template.json b/skills/clinical-decision-support/assets/survival_analysis_plan_template.json
new file mode 100644
index 00000000..49ba7b13
--- /dev/null
+++ b/skills/clinical-decision-support/assets/survival_analysis_plan_template.json
@@ -0,0 +1,134 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "plan_id": "SYNTHETIC-SURVIVAL-PLAN-001",
+ "title": "Synthetic Aggregate Time-to-Event Analysis Plan",
+ "version": "0.1-draft",
+ "status": "draft",
+ "purpose": "Demonstrate estimand-led planning without time-to-event records.",
+ "data_cut_date": "2026-07-23",
+ "data_level": "plan_only",
+ "raw_rows_supplied": false,
+ "patient_care_use": false,
+ "human_review_required": true
+ },
+ "intended_use": "Research analysis planning only; not for patient care or live clinical use.",
+ "prohibited_uses": [
+ "No individual prognosis or classification.",
+ "No diagnosis, treatment recommendation, dosing, triage, alarm, or autonomous decision.",
+ "No claim of statistical approval, clinical validity, authorization, or compliance."
+ ],
+ "limitations": [
+ "The validator does not inspect data or fit a model.",
+ "Methods require review against the actual design and estimand.",
+ "Synthetic placeholders must be replaced before an approved research analysis."
+ ],
+ "estimand": {
+ "population": "Synthetic eligible research cohort",
+ "condition_or_comparison": "Synthetic exposure A versus synthetic exposure B",
+ "endpoint_variable": "Time from defined synthetic index to defined synthetic event",
+ "population_summary": "Hazard contrast plus restricted mean survival time difference at the prespecified horizon",
+ "time_horizon": "24 synthetic time units",
+ "rationale": "The hazard contrast addresses relative event rate; restricted mean survival time supports interpretation if proportional hazards is doubtful.",
+ "intercurrent_events": [
+ {
+ "event": "Synthetic exposure discontinuation",
+ "strategy": "Treatment-policy strategy in the primary estimand",
+ "rationale": "Preserves the prespecified research question."
+ },
+ {
+ "event": "Synthetic competing event",
+ "strategy": "Competing-event strategy with cumulative incidence",
+ "rationale": "The competing event precludes the primary event."
+ }
+ ]
+ },
+ "endpoint": {
+ "time_zero": "Synthetic index date defined before analysis",
+ "event_definition": "Prespecified synthetic event with blinded aggregate adjudication",
+ "time_scale": "Synthetic months",
+ "ascertainment": "Prespecified uniform synthetic schedule",
+ "follow_up_end": "Earliest of event, loss to follow-up, or administrative data cut",
+ "delayed_entry": "Assess and use left-truncation methods if eligibility begins after time zero",
+ "same_time_rules": "Apply prespecified deterministic ordering and document ties",
+ "censoring_rules": [
+ "Administrative censoring at the fixed data cut",
+ "Censor loss to follow-up at last verified observation with informative-censoring sensitivity analysis"
+ ],
+ "competing_events": [
+ "Synthetic competing event"
+ ]
+ },
+ "analysis": {
+ "primary_method": "cox_proportional_hazards",
+ "effect_measure": "Hazard ratio with 95% confidence interval; restricted mean survival time difference at 24 units if proportional hazards is not supported",
+ "analysis_population": "Prespecified synthetic analysis population",
+ "covariate_strategy": "Prespecified covariates based on subject-matter rationale; no univariable p-value selection",
+ "missing_data": "Describe patterns; use justified multiple-imputation or model-based approach with sensitivity analysis",
+ "multiplicity": "Prespecify primary endpoint and control or transparently label secondary and exploratory analyses",
+ "uncertainty": "Two-sided 95% confidence intervals and assumption-focused sensitivity analyses",
+ "software_and_version": "Record locked statistical software, packages, code, and versions before execution",
+ "model_diagnostics": "Functional forms, influential observations, residual checks, convergence, and calibration where predictive",
+ "proportional_hazards_assessment": "Prespecified graphical assessment and time-interaction/residual-based assessment",
+ "non_proportional_hazards_strategy": "Report time-varying effects and restricted mean survival time at the prespecified horizon",
+ "competing_risk_method": "cumulative_incidence"
+ },
+ "bias_controls": {
+ "informative_censoring": "Compare follow-up patterns and run a justified sensitivity analysis.",
+ "immortal_time": "Align eligibility, assignment, and time zero; model time-varying exposure if required.",
+ "time_dependent_confounding": "Specify whether g-methods are required for the causal estimand.",
+ "outcome_misclassification": "Document ascertainment validity and conduct plausible sensitivity analyses.",
+ "informative_visits": "Assess observation schedules and potential outcome-dependent measurement."
+ },
+ "sensitivity_analyses": [
+ "Alternative censoring assumptions tied to plausible loss-to-follow-up mechanisms",
+ "Alternative effect summary when proportional hazards is not supported",
+ "Competing-risk analysis aligned with the absolute-incidence question"
+ ],
+ "subgroups": {
+ "prespecification": "List scientifically justified subgroups before results.",
+ "interaction_testing": "Use formal interaction estimates with uncertainty.",
+ "multiplicity": "Control or label exploratory subgroup analyses.",
+ "precision_and_disclosure": "Report aggregate sizes/events and suppress unstable or disclosive outputs."
+ },
+ "validation": {
+ "internal_validation": "Use design-appropriate resampling if a prediction model is involved.",
+ "external_validation": "Plan independent temporal or geographic validation before transportability claims.",
+ "calibration": "Evaluate calibration at prespecified horizons for prediction models.",
+ "subgroup_performance": "Report performance and uncertainty across prespecified groups."
+ },
+ "human_review": {
+ "roles": [
+ "survival-analysis statistician",
+ "epidemiologist",
+ "domain expert"
+ ],
+ "completed": false,
+ "approval_boundary": "An accountable research organization must approve the final plan; approval never permits patient-care use."
+ },
+ "governance": {
+ "owner": "research analysis governance owner",
+ "change_control": "Version the estimand, endpoint, data cut, code, software, deviations, and sensitivity analyses.",
+ "auditability": "Retain the approved plan, amendments, execution logs, aggregate outputs, and reviewer decisions.",
+ "monitoring": "Review assumption violations, missingness, censoring, subgroup precision, and external validation.",
+ "retirement": "Supersede or retire the plan when the question, data source, endpoint, or method changes materially."
+ },
+ "source_ids": [
+ "ICH-E9R1",
+ "RMST"
+ ],
+ "sources": [
+ {
+ "id": "ICH-E9R1",
+ "citation": "ICH E9(R1), Addendum on Estimands and Sensitivity Analysis in Clinical Trials, 2019.",
+ "url": "https://database.ich.org/sites/default/files/E9-R1_Step4_Guideline_2019_1203.pdf",
+ "accessed": "2026-07-23"
+ },
+ {
+ "id": "RMST",
+ "citation": "Royston P, Parmar MKB. Restricted mean survival time. BMC Medical Research Methodology. 2013;13:152.",
+ "url": "https://pubmed.ncbi.nlm.nih.gov/24314264/",
+ "accessed": "2026-07-23"
+ }
+ ]
+}
diff --git a/skills/clinical-decision-support/assets/treatment_recommendation_template.tex b/skills/clinical-decision-support/assets/treatment_recommendation_template.tex
deleted file mode 100644
index bd8b71aa..00000000
--- a/skills/clinical-decision-support/assets/treatment_recommendation_template.tex
+++ /dev/null
@@ -1,529 +0,0 @@
-\documentclass[10pt,letterpaper]{article}
-
-% Packages
-\usepackage[margin=0.5in]{geometry}
-\usepackage[utf8]{inputenc}
-\usepackage[T1]{fontenc}
-\usepackage{helvet}
-\renewcommand{\familydefault}{\sfdefault}
-\usepackage{xcolor}
-\usepackage{tcolorbox}
-\usepackage{array}
-\usepackage{tabularx}
-\usepackage{booktabs}
-\usepackage{enumitem}
-\usepackage{titlesec}
-\usepackage{fancyhdr}
-\usepackage{multicol}
-\usepackage{graphicx}
-\usepackage{tikz}
-\usetikzlibrary{shapes,arrows,positioning}
-
-% Color definitions
-\definecolor{headerblue}{RGB}{0,102,204}
-\definecolor{stronggreen}{RGB}{0,153,76}
-\definecolor{conditionalyellow}{RGB}{255,193,7}
-\definecolor{researchblue}{RGB}{33,150,243}
-\definecolor{warningred}{RGB}{204,0,0}
-\definecolor{highlightgray}{RGB}{240,240,240}
-
-% Section formatting - compact
-\titleformat{\section}{\normalfont\fontsize{11}{12}\bfseries\color{headerblue}}{\thesection}{0.5em}{}
-\titlespacing*{\section}{0pt}{4pt}{2pt}
-
-\titleformat{\subsection}{\normalfont\fontsize{10}{11}\bfseries}{\thesubsection}{0.5em}{}
-\titlespacing*{\subsection}{0pt}{3pt}{1pt}
-
-% List formatting - ultra compact
-\setlist[itemize]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-\setlist[enumerate]{leftmargin=*,itemsep=0pt,parsep=0pt,topsep=1pt}
-
-% Remove paragraph indentation
-\setlength{\parindent}{0pt}
-\setlength{\parskip}{2pt}
-
-% Header/footer
-\pagestyle{fancy}
-\fancyhf{}
-\fancyhead[L]{\footnotesize \textbf{Treatment Recommendations: [CONDITION]}}
-\fancyhead[R]{\footnotesize Page \thepage}
-\renewcommand{\headrulewidth}{0.5pt}
-\fancyfoot[C]{\footnotesize Evidence-Based Clinical Guideline - For Professional Use Only}
-
-\begin{document}
-
-% Title block
-\begin{center}
-{\fontsize{14}{16}\selectfont\bfseries\color{headerblue} EVIDENCE-BASED TREATMENT RECOMMENDATIONS}\\[2pt]
-{\fontsize{12}{14}\selectfont\bfseries [Disease/Condition - e.g., HER2+ Metastatic Breast Cancer]}\\[2pt]
-{\fontsize{10}{12}\selectfont [Institution/Organization]}\\[1pt]
-{\fontsize{9}{11}\selectfont Version X.X | Effective Date: [Date] | Next Review: [Date]}
-\end{center}
-
-\vspace{4pt}
-
-% Recommendation Strength Legend
-\begin{tcolorbox}[colback=highlightgray,colframe=black,title=\textbf{Recommendation Strength Key},fonttitle=\bfseries\small,coltitle=black]
-{\small
-\begin{itemize}
-\item \colorbox{stronggreen!30}{\textbf{STRONG (Grade 1)}} - Benefits clearly outweigh risks; most patients should receive intervention
-\item \colorbox{conditionalyellow!30}{\textbf{CONDITIONAL (Grade 2)}} - Trade-offs exist; shared decision-making essential
-\item \colorbox{researchblue!30}{\textbf{RESEARCH (Grade R)}} - Insufficient evidence; clinical trial enrollment preferred
-\end{itemize}
-
-\textbf{Evidence Quality}: \textbf{A} = High (RCTs), \textbf{B} = Moderate (RCTs with limitations), \textbf{C} = Low (observational), \textbf{D} = Very low (expert opinion)
-}
-\end{tcolorbox}
-
-\vspace{2pt}
-
-\section{Clinical Context}
-
-\subsection{Disease Overview}
-
-[Brief description of disease state, epidemiology, natural history]
-
-\subsection{Patient Population}
-
-\textbf{Target Population}:
-\begin{itemize}
-\item [Demographic characteristics - e.g., Adults $\geq$18 years]
-\item [Disease stage/severity - e.g., Metastatic disease, Stage IV]
-\item [Biomarker status - e.g., HER2-positive (IHC 3+ or FISH+)]
-\item [Performance status - e.g., ECOG 0-2]
-\item [Line of therapy - e.g., First-line, previously untreated]
-\end{itemize}
-
-\textbf{Exclusions}:
-\begin{itemize}
-\item [Contraindications to recommended therapies]
-\item [Comorbidities affecting eligibility]
-\end{itemize}
-
-\section{Evidence Review}
-
-\subsection{Key Clinical Trials}
-
-\textbf{[Trial Name 1]} (Author, Journal Year):
-\begin{itemize}
-\item \textbf{Design}: Phase 3 RCT, n=XXX, [Treatment A] vs [Treatment B]
-\item \textbf{Population}: [Key eligibility criteria]
-\item \textbf{Primary Endpoint}: [Outcome] - XX vs XX months (HR X.XX, 95\% CI X.XX-X.XX, p<X.XXX)
-\item \textbf{Secondary Endpoints}: [Additional outcomes]
-\item \textbf{Safety}: Grade 3-4 AEs XX\% vs XX\%
-\item \textbf{Quality}: \textbf{High} (low risk of bias, adequate power, intention-to-treat analysis)
-\end{itemize}
-
-\textbf{[Trial Name 2]} (Author, Journal Year):
-\begin{itemize}
-\item \textbf{Design}: Phase 3 RCT, n=XXX, [Treatment C] vs [Standard of care]
-\item \textbf{Primary Endpoint}: [Outcome and results]
-\item \textbf{Quality}: \textbf{Moderate} (some limitations)
-\end{itemize}
-
-\subsection{Guideline Concordance}
-
-\begin{table}[H]
-\centering
-\small
-\begin{tabular}{lll}
-\toprule
-\textbf{Guideline} & \textbf{Recommendation} & \textbf{Evidence Level} \\
-\midrule
-NCCN vX.XXXX & [Specific recommendation] & Category 1 (preferred) \\
-ASCO Year & [Recommendation] & Strong, Evidence A \\
-ESMO Year & [Recommendation] & Grade I, A \\
-\bottomrule
-\end{tabular}
-\caption{Major guideline recommendations}
-\end{table}
-
-\section{Treatment Options}
-
-\subsection{First-Line Therapy}
-
-\begin{tcolorbox}[enhanced,colback=stronggreen!10,colframe=stronggreen,
-title={\textbf{Option 1: [Regimen Name]} \hfill \colorbox{white}{\textbf{STRONG (1A)}}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Regimen}:
-\begin{itemize}
-\item [Drug A]: XX mg [IV/PO] [schedule]
-\item [Drug B]: XX mg [IV/PO] [schedule]
-\item Cycle length: XX days
-\item Duration: Until progression or unacceptable toxicity
-\end{itemize}
-
-\textbf{Evidence Basis}:
-\begin{itemize}
-\item Primary study: [Trial name], n=XXX
-\item Primary outcome: [Endpoint] XX vs XX months (HR X.XX, p<X.XXX)
-\item ORR: XX\% vs XX\% (control)
-\end{itemize}
-
-\textbf{Indications}:
-\begin{itemize}
-\item [Biomarker-defined population or all patients]
-\item [Performance status requirement]
-\item [Organ function requirements]
-\end{itemize}
-
-\textbf{Key Toxicities}:
-\begin{itemize}
-\item Grade 3-4 AEs: XX\%
-\item Common: [List 3-5 most common AEs with incidence]
-\item Serious: [SAEs, discontinuation rate]
-\item Management: [Key mitigation strategies]
-\end{itemize}
-
-\textbf{Monitoring}:
-\begin{itemize}
-\item Labs: [Specific tests, frequency]
-\item Imaging: Every [X weeks] (RECIST v1.1)
-\item Clinical assessment: Every cycle
-\end{itemize}
-
-\textbf{Recommendation Strength}: \textbf{STRONG} - Benefits clearly outweigh risks\\
-\textbf{Evidence Quality}: \textbf{HIGH} - Well-designed RCT with consistent results
-}
-\end{tcolorbox}
-
-\vspace{3pt}
-
-\begin{tcolorbox}[enhanced,colback=conditionalyellow!10,colframe=conditionalyellow,
-title={\textbf{Option 2: [Alternative Regimen]} \hfill \colorbox{white}{\textbf{CONDITIONAL (2B)}}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Regimen}: [Dosing details]
-
-\textbf{Evidence Basis}: [Moderate-quality evidence or specific population subset]
-
-\textbf{Indications}: [When to consider this option - e.g., patient preference for oral therapy, specific contraindication to Option 1]
-
-\textbf{Trade-offs}:
-\begin{itemize}
-\item Advantages: [e.g., Oral administration, better tolerability]
-\item Disadvantages: [e.g., Lower response rate, less survival benefit]
-\end{itemize}
-
-\textbf{Recommendation Strength}: \textbf{CONDITIONAL} - Patient values important in decision\\
-\textbf{Evidence Quality}: \textbf{MODERATE} - Some limitations in evidence base
-}
-\end{tcolorbox}
-
-\vspace{3pt}
-
-\begin{tcolorbox}[enhanced,colback=researchblue!10,colframe=researchblue,
-title={\textbf{Option 3: Clinical Trial} \hfill \colorbox{white}{\textbf{RESEARCH (R)}}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{Recommendation}: Consider clinical trial enrollment for [specific scenario - e.g., biomarker-selected patients, refractory disease]
-
-\textbf{Available Trials}: [List relevant trials if known, or state "ClinicalTrials.gov search"]
-
-\textbf{Rationale}: [Why clinical trial appropriate - e.g., novel mechanism, unmet medical need, investigational biomarker]
-}
-\end{tcolorbox}
-
-\subsection{Second-Line and Beyond}
-
-\textbf{At Progression on First-Line Therapy}:
-
-\begin{itemize}
-\item \textbf{Biomarker Re-Testing}: [If applicable - e.g., liquid biopsy for resistance mutations]
-\item \textbf{Second-Line Options}:
- \begin{itemize}
- \item Preferred: [Regimen] (Evidence level)
- \item Alternative: [Regimen] (Evidence level)
- \end{itemize}
-\item \textbf{Third-Line Options}: [Subsequent therapy options]
-\end{itemize}
-
-\section{Special Populations}
-
-\subsection{Elderly Patients ($\geq$70 years)}
-
-\textbf{Considerations}:
-\begin{itemize}
-\item Geriatric assessment recommended (G8 screening tool)
-\item Dose reductions: [Specific adjustments for frail patients]
-\item Monitoring: More frequent assessments for toxicity
-\end{itemize}
-
-\textbf{Regimen Modifications}:
-\begin{itemize}
-\item [Reduced-intensity regimens if appropriate]
-\item [Single-agent vs combination considerations]
-\end{itemize}
-
-\subsection{Renal Impairment}
-
-\begin{table}[H]
-\centering
-\footnotesize
-\begin{tabular}{lll}
-\toprule
-\textbf{eGFR (mL/min/1.73m²)} & \textbf{Category} & \textbf{Dose Adjustment} \\
-\midrule
-$\geq$60 & Normal/Mild & Standard dosing \\
-30-59 & Moderate & [Specific adjustment - e.g., Reduce 25\%] \\
-15-29 & Severe & [Specific adjustment - e.g., Reduce 50\% or avoid] \\
-<15 or dialysis & ESRD & [Use with caution or contraindicated] \\
-\bottomrule
-\end{tabular}
-\caption{Dose adjustments for renal impairment}
-\end{table}
-
-\subsection{Hepatic Impairment}
-
-[Similar table for hepatic dose adjustments using Child-Pugh class or bilirubin/transaminases]
-
-\section{Clinical Decision Algorithm}
-
-% Simple flowchart example - can be expanded with more complex TikZ
-\begin{center}
-\begin{tikzpicture}[node distance=1.8cm, auto,
- decision/.style={diamond, draw, fill=conditionalyellow!30, text width=4.5em, text centered, inner sep=1pt, font=\tiny},
- process/.style={rectangle, draw, fill=stronggreen!20, text width=5.5em, text centered, rounded corners, minimum height=2em, font=\tiny},
- terminal/.style={rectangle, draw, fill=highlightgray, text width=5.5em, text centered, rounded corners=6pt, minimum height=2em, font=\tiny},
- alert/.style={rectangle, draw=warningred, line width=1pt, fill=warningred!10, text width=5.5em, text centered, rounded corners, minimum height=2em, font=\tiny\bfseries},
- arrow/.style={thick,->,>=stealth}]
-
- \node [terminal] (start) {[Disease] Diagnosis Confirmed};
- \node [decision, below of=start, node distance=1.8cm] (biomarker) {Biomarker\\ Positive?};
- \node [process, left of=biomarker, node distance=3.5cm] (optionA) {Targeted\\ Therapy};
- \node [process, right of=biomarker, node distance=3.5cm] (optionB) {Standard\\ Therapy};
- \node [terminal, below of=biomarker, node distance=2.5cm] (monitor) {Monitor Response\\ Every X weeks};
-
- \draw [arrow] (start) -- (biomarker);
- \draw [arrow] (biomarker) -- node[above] {Yes} (optionA);
- \draw [arrow] (biomarker) -- node[above] {No} (optionB);
- \draw [arrow] (optionA) |- (monitor);
- \draw [arrow] (optionB) |- (monitor);
-\end{tikzpicture}
-\end{center}
-
-{\footnotesize \textit{Figure 1: Simplified treatment selection algorithm. See detailed algorithm in references for complete decision pathway.}}
-
-\section{Monitoring Protocol}
-
-\subsection{On-Treatment Monitoring}
-
-\begin{table}[H]
-\centering
-\footnotesize
-\begin{tabular}{lccl}
-\toprule
-\textbf{Assessment} & \textbf{Baseline} & \textbf{Frequency} & \textbf{Rationale} \\
-\midrule
-CBC with differential & $\checkmark$ & Before each cycle & Myelosuppression \\
-Comprehensive metabolic panel & $\checkmark$ & Before each cycle & Organ function \\
-[Specific biomarker] & $\checkmark$ & Every X cycles & [Reason] \\
-Imaging (CT chest/abd/pelvis) & $\checkmark$ & Every X weeks & Response assessment \\
-ECOG performance status & $\checkmark$ & Every visit & Functional status \\
-Toxicity assessment (CTCAE) & - & Every visit & Safety monitoring \\
-\bottomrule
-\end{tabular}
-\caption{Recommended monitoring schedule}
-\end{table}
-
-\subsection{Dose Modification Guidelines}
-
-\textbf{Hematologic Toxicity}:
-\begin{itemize}
-\item \textbf{ANC <1.0 or Platelets <75k}: Delay treatment, recheck weekly, dose reduce 20\% when recovered
-\item \textbf{ANC <0.5 or Platelets <50k}: Hold treatment, G-CSF support, dose reduce 25-40\%
-\item \textbf{Febrile neutropenia}: Hold, hospitalize, antibiotics, dose reduce 25\% when recovered
-\end{itemize}
-
-\textbf{Non-Hematologic Toxicity}:
-\begin{itemize}
-\item \textbf{Grade 2}: Continue with supportive care, consider dose modification if persistent
-\item \textbf{Grade 3}: Hold until $\leq$Grade 1, resume at reduced dose (20-25\% reduction)
-\item \textbf{Grade 4}: Discontinue treatment or hold pending recovery (case-by-case)
-\end{itemize}
-
-\textbf{Specific Toxicity Management}:
-\begin{itemize}
-\item \textbf{[Specific AE]}: [Management approach - e.g., Diarrhea Grade 3: Hold treatment, loperamide, hydration, resume at reduced dose when $\leq$Grade 1]
-\item \textbf{[Immune-related AE]}: [Management - e.g., Pneumonitis Grade 2+: Hold immunotherapy, corticosteroids, pulmonology consultation]
-\end{itemize}
-
-\section{Treatment Recommendations by Clinical Scenario}
-
-\subsection{Scenario 1: [Specific Clinical Situation]}
-
-\begin{tcolorbox}[enhanced,colback=stronggreen!10,colframe=stronggreen,
-title={\textbf{RECOMMENDATION} \hfill \textbf{GRADE: 1A}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{We recommend} [specific intervention] for [patient population].
-
-\textbf{Evidence}:
-\begin{itemize}
-\item [Primary supporting evidence with results]
-\item [Guideline concordance - NCCN, ASCO, ESMO]
-\end{itemize}
-
-\textbf{Benefits}: [Quantified improvements - e.g., 8.7-month PFS benefit, HR 0.46]
-
-\textbf{Harms}: [Quantified risks - e.g., 15\% grade 3-4 immune-related AEs]
-
-\textbf{Balance}: Benefits clearly outweigh harms for most patients
-}
-\end{tcolorbox}
-
-\subsection{Scenario 2: [Alternative Clinical Situation]}
-
-\begin{tcolorbox}[enhanced,colback=conditionalyellow!10,colframe=conditionalyellow,
-title={\textbf{RECOMMENDATION} \hfill \textbf{GRADE: 2B}},
-fonttitle=\bfseries\small,coltitle=black]
-{\small
-\textbf{We suggest} [intervention] for [patient population] who value [specific outcome].
-
-\textbf{Evidence}: [Moderate-quality evidence summary]
-
-\textbf{Trade-offs}:
-\begin{itemize}
-\item \textbf{Advantages}: [e.g., Oral administration, less frequent monitoring]
-\item \textbf{Disadvantages}: [e.g., Lower response rate, more out-of-pocket cost]
-\end{itemize}
-
-\textbf{Patient Values}: Substantial variability in how patients value outcomes; shared decision-making essential
-}
-\end{tcolorbox}
-
-\section{Alternative Approaches}
-
-\subsection{Non-Recommended Options}
-
-\begin{tcolorbox}[enhanced,colback=warningred!10,colframe=warningred,
-title={\textbf{NOT RECOMMENDED}},
-fonttitle=\bfseries\small,coltitle=white,colbacktitle=warningred]
-{\small
-\textbf{[Intervention X]} is \textbf{not recommended} for [population].
-
-\textbf{Reason}: [Evidence of harm, lack of benefit, or superior alternatives available]
-
-\textbf{Evidence}: [Supporting data showing no benefit or harm]
-}
-\end{tcolorbox}
-
-\section{Supportive Care}
-
-\subsection{Symptom Management}
-
-\begin{itemize}
-\item \textbf{Pain Control}: [Analgesic recommendations, WHO ladder]
-\item \textbf{Nausea Prevention}: [Antiemetics - e.g., 5-HT3 antagonists, NK1 antagonists for highly emetogenic]
-\item \textbf{Bone Health}: [e.g., Bisphosphonates or denosumab if bone metastases]
-\item \textbf{Nutritional Support}: [Consult if weight loss >5\%, cachexia management]
-\item \textbf{Psychosocial Support}: [Depression screening, support groups, palliative care early integration]
-\end{itemize}
-
-\subsection{Growth Factor Support}
-
-\textbf{G-CSF Prophylaxis}:
-\begin{itemize}
-\item \textbf{Primary prophylaxis}: If febrile neutropenia risk $\geq$20\%
-\item \textbf{Secondary prophylaxis}: After prior febrile neutropenia episode
-\item Agent: [Pegfilgrastim 6 mg SC day 2 or filgrastim 5 mcg/kg SC daily days 3-10]
-\end{itemize}
-
-\section{Follow-Up and Surveillance}
-
-\subsection{During Active Treatment}
-
-[Schedule outlined in Monitoring Protocol section above]
-
-\subsection{Post-Treatment Surveillance}
-
-\begin{table}[H]
-\centering
-\footnotesize
-\begin{tabular}{lccc}
-\toprule
-\textbf{Time Period} & \textbf{Imaging} & \textbf{Labs} & \textbf{Clinical Visits} \\
-\midrule
-Year 1 & Every 3 months & Every 3 months & Every 3 months \\
-Year 2 & Every 3-4 months & Every 3-4 months & Every 3-4 months \\
-Years 3-5 & Every 6 months & Every 6 months & Every 6 months \\
-Year 5+ & Annually & Annually & Annually \\
-\bottomrule
-\end{tabular}
-\caption{Post-treatment surveillance schedule (adjust based on risk of recurrence)}
-\end{table}
-
-\section{Clinical Trial Opportunities}
-
-\textbf{When to Consider Clinical Trials}:
-\begin{itemize}
-\item After progression on standard therapies
-\item High-risk disease with poor prognosis on standard therapy
-\item Novel biomarker potentially predictive of response
-\item Patient preference for investigational approach
-\end{itemize}
-
-\textbf{Resources}:
-\begin{itemize}
-\item ClinicalTrials.gov search: [Specific keywords]
-\item [Institution] clinical trials office: [Contact information]
-\end{itemize}
-
-\section{Shared Decision-Making}
-
-\subsection{Key Discussion Points}
-
-\textbf{Goals of Care}:
-\begin{itemize}
-\item Curative intent vs prolonged disease control vs palliation
-\item Quality of life vs quantity of life trade-offs
-\item Functional independence goals
-\end{itemize}
-
-\textbf{Treatment Options Counseling}:
-\begin{itemize}
-\item Expected benefits (median survival, response rates)
-\item Potential harms (toxicity profile, quality of life impact)
-\item Treatment schedule and logistics (frequency of visits, IV vs oral)
-\item Financial considerations (out-of-pocket costs, time off work)
-\end{itemize}
-
-\textbf{Decision Aids}:
-\begin{itemize}
-\item Number Needed to Treat: [e.g., Treat X patients to prevent 1 progression event]
-\item Survival benefit visualization: [X-month improvement in median survival]
-\end{itemize}
-
-\section{References}
-
-\begin{enumerate}
-\item [Primary clinical trial reference]
-\item [Secondary supporting trial]
-\item [NCCN Guidelines, version]
-\item [ASCO/ESMO Guideline reference]
-\item [Meta-analysis or systematic review if applicable]
-\item [Biomarker validation reference]
-\end{enumerate}
-
-\vspace{10pt}
-
-\hrule
-\vspace{4pt}
-{\footnotesize
-\textbf{Guideline Development Committee}:\\
-[Names and titles of committee members, affiliations]
-
-\textbf{Evidence Review Date}: [Date]\\
-\textbf{Guideline Effective Date}: [Date]\\
-\textbf{Next Scheduled Review}: [Date] (or earlier if practice-changing evidence published)
-
-\textbf{Conflicts of Interest}: [None / See disclosure statements]
-
-\textbf{Methodology}: GRADE framework for evidence evaluation and recommendation development. Systematic literature review conducted [date range]. Guidelines concordance checked with NCCN, ASCO, ESMO current versions.
-
-\textbf{For Questions}: Contact [Name], [Title] at [Email/Phone]
-}
-
-\end{document}
-
diff --git a/skills/clinical-decision-support/references/README.md b/skills/clinical-decision-support/references/README.md
index c96faf77..b6fc0d74 100644
--- a/skills/clinical-decision-support/references/README.md
+++ b/skills/clinical-decision-support/references/README.md
@@ -1,129 +1,62 @@
-# Clinical Decision Support Skill
-
-Professional clinical decision support documents for medical professionals in pharmaceutical and clinical research settings.
-
-## Quick Start
-
-This skill enables generation of three types of clinical documents:
-
-1. **Individual Patient Treatment Plans** - Personalized protocols for specific patients
-2. **Patient Cohort Analysis** - Biomarker-stratified group analyses with outcomes
-3. **Treatment Recommendation Reports** - Evidence-based clinical guidelines
-
-All documents are generated as compact, professional LaTeX/PDF files.
-
-## Directory Structure
-
-```
-clinical-decision-support/
-├── SKILL.md # Main skill definition
-├── README.md # This file
-│
-├── references/ # Clinical guidance documents
-│ ├── patient_cohort_analysis.md
-│ ├── treatment_recommendations.md
-│ ├── clinical_decision_algorithms.md
-│ ├── biomarker_classification.md
-│ ├── outcome_analysis.md
-│ └── evidence_synthesis.md
-│
-├── assets/ # Templates and examples
-│ ├── cohort_analysis_template.tex
-│ ├── treatment_recommendation_template.tex
-│ ├── clinical_pathway_template.tex
-│ ├── biomarker_report_template.tex
-│ ├── example_gbm_cohort.md
-│ ├── recommendation_strength_guide.md
-│ └── color_schemes.tex
-│
-└── scripts/ # Analysis and generation tools
- ├── generate_survival_analysis.py
- ├── create_cohort_tables.py
- ├── build_decision_tree.py
- ├── biomarker_classifier.py
- └── validate_cds_document.py
-```
-
-## Example Use Cases
-
-### Create a Patient Cohort Analysis
-```
-> Analyze a cohort of 45 NSCLC patients stratified by PD-L1 expression
- (<1%, 1-49%, ≥50%) including ORR, PFS, and OS outcomes
-```
-
-### Generate Treatment Recommendations
-```
-> Create evidence-based treatment recommendations for HER2-positive
- metastatic breast cancer with GRADE methodology
-```
-
-### Build Clinical Pathway
-```
-> Generate a clinical decision algorithm for acute chest pain
- management with TIMI risk score
-```
-
-## Key Features
-
-- **GRADE Methodology**: Evidence quality grading (High/Moderate/Low/Very Low)
-- **Recommendation Strength**: Strong (Grade 1) vs Conditional (Grade 2)
-- **Biomarker Integration**: Genomic, expression, and molecular subtype classification
-- **Statistical Analysis**: Kaplan-Meier, Cox regression, log-rank tests
-- **Guideline Concordance**: NCCN, ASCO, ESMO, AHA/ACC integration
-- **Professional Output**: 0.5in margins, color-coded boxes, publication-ready
-
-## Dependencies
-
-Python scripts require:
-- `pandas`, `numpy`, `scipy`: Data analysis and statistics
-- `lifelines`: Survival analysis (Kaplan-Meier, Cox regression)
-- `matplotlib`: Visualization
-- `pyyaml` (optional): YAML input for decision trees
-
-Install with:
-```bash
-pip install pandas numpy scipy lifelines matplotlib pyyaml
-```
-
-## References Included
-
-1. **Patient Cohort Analysis**: Stratification methods, biomarker correlations, statistical comparisons
-2. **Treatment Recommendations**: Evidence grading, treatment sequencing, special populations
-3. **Clinical Decision Algorithms**: Risk scores, decision trees, TikZ flowcharts
-4. **Biomarker Classification**: Genomic alterations, molecular subtypes, companion diagnostics
-5. **Outcome Analysis**: Survival methods, response criteria (RECIST), effect sizes
-6. **Evidence Synthesis**: Guideline integration, systematic reviews, meta-analysis
-
-## Templates Provided
-
-1. **Cohort Analysis**: Demographics table, biomarker profile, outcomes, statistics, recommendations
-2. **Treatment Recommendations**: Evidence review, GRADE-graded options, monitoring, decision algorithm
-3. **Clinical Pathway**: TikZ flowchart with risk stratification and urgency-coded actions
-4. **Biomarker Report**: Genomic profiling with tier-based actionability and therapy matching
-
-## Scripts Included
-
-1. **`generate_survival_analysis.py`**: Create Kaplan-Meier curves with hazard ratios
-2. **`create_cohort_tables.py`**: Generate baseline, efficacy, and safety tables
-3. **`build_decision_tree.py`**: Convert text/JSON to TikZ flowcharts
-4. **`biomarker_classifier.py`**: Stratify patients by PD-L1, HER2, molecular subtypes
-5. **`validate_cds_document.py`**: Quality checks for completeness and compliance
-
-## Integration
-
-Integrates with existing skills:
-- **scientific-writing**: Citation management, statistical reporting
-- **clinical-reports**: Medical terminology, HIPAA compliance
-- **scientific-schematics**: TikZ flowcharts
-
-## Version
-
-Version 1.0 - Initial release
-Created: November 2024
-Last Updated: November 5, 2024
-
-## Questions or Feedback
-
-This skill was designed for pharmaceutical and clinical research professionals creating clinical decision support documents. For questions about usage or suggestions for improvements, contact the Scientific Writer development team.
+# Clinical Decision-Support References
+
+Version 2.0 is the breaking safety redesign dated 2026-07-23. It replaces
+the former recommendation-oriented templates, references, and scripts with
+offline research-evaluation and governance artifacts.
+
+## Boundary
+
+These references support aggregate or synthetic research evaluation, methods documentation, evidence profiles, privacy review, and governance traceability. They do not support diagnosis, treatment recommendations, dosing, triage, alarms, bedside use, autonomous decisions, or patient-specific output.
+
+No reference or script establishes regulatory authorization, HIPAA compliance, clinical validity, or fitness for live use. Route care decisions to licensed professionals using validated and appropriately authorized systems.
+
+## Navigation
+
+| File | Purpose |
+|---|---|
+| `safety_and_scope.md` | Refusal rules, escalation, and intended-use language |
+| `regulatory_and_governance.md` | FDA CDS/AI, ONC HTI-1, and ICH context |
+| `evidence_profiles.md` | Human GRADE evidence-profile workflow |
+| `study_reporting.md` | STROBE/RECORD, TRIPOD+AI, CONSORT-AI, SPIRIT-AI, DECIDE-AI, STARD-AI, REMARK, and PROBAST+AI |
+| `cohort_evaluation.md` | Aggregate cohort reporting and disclosure-aware tables |
+| `survival_analysis.md` | Estimand-led time-to-event planning |
+| `model_biomarker_evaluation.md` | Aggregate validation, calibration, uncertainty, and subgroup review |
+| `privacy_and_disclosure.md` | HHS de-identification methods and output controls |
+| `decision_logic_traceability.md` | Research/governance logic matrices |
+| `sources.md` | Authoritative source ledger checked 2026-07-23 |
+| `security_validation.md` | Baseline remediation, scan results, and accepted LOW findings |
+
+## Assets
+
+All assets are JSON skeletons. They contain no patient rows or real identifiers:
+
+- `artifact_intended_use_template.json`
+- `evidence_profile_template.json`
+- `aggregate_model_evaluation_template.json`
+- `aggregate_cohort_table_template.json`
+- `survival_analysis_plan_template.json`
+- `decision_logic_traceability_template.json`
+- `deidentification_checklist_template.json`
+
+Every template includes intended use, prohibited uses, limitations, data level, and human-review fields.
+
+## Scripts
+
+The standard-library scripts read bounded local JSON and produce bounded local JSON, Markdown, or CSV:
+
+- `validate_cds_artifact.py`
+- `evidence_profile_check.py`
+- `model_biomarker_evaluation.py`
+- `cohort_table_generator.py`
+- `survival_plan_validator.py`
+- `decision_logic_traceability.py`
+- `deidentification_checklist.py`
+
+They do not use networks, API keys, environment variables, dynamic evaluation, serialization formats that execute code, LLMs, or image services.
+
+## Method Selection
+
+Use the study design and evaluation stage—not the presence of “AI” in a title—to select a framework. Reporting checklists are minimum disclosure guidance. Risk-of-bias tools require informed human judgments. GRADE certainty is outcome-specific and cannot be inferred from text.
+
+For an actual protocol, product, regulated submission, certified health IT module, or data release, obtain review from the relevant methodologist, privacy official, legal/regulatory counsel, governance owner, and domain experts.
diff --git a/skills/clinical-decision-support/references/biomarker_classification.md b/skills/clinical-decision-support/references/biomarker_classification.md
deleted file mode 100644
index 64ec0e6b..00000000
--- a/skills/clinical-decision-support/references/biomarker_classification.md
+++ /dev/null
@@ -1,719 +0,0 @@
-# Biomarker Classification and Interpretation Guide
-
-## Overview
-
-Biomarkers are measurable indicators of biological state or condition. In clinical decision support, biomarkers guide diagnosis, prognosis, treatment selection, and monitoring. This guide covers genomic, proteomic, and molecular biomarkers with emphasis on clinical actionability.
-
-## Biomarker Categories
-
-### Prognostic Biomarkers
-
-**Definition**: Predict clinical outcome (survival, recurrence) regardless of treatment received
-
-**Examples by Disease**
-
-**Cancer**
-- **Ki-67 index**: High proliferation (>20%) predicts worse outcome in breast cancer
-- **TP53 mutation**: Poor prognosis across many cancer types
-- **Tumor stage/grade**: TNM staging, histologic grade
-- **LDH elevation**: Poor prognosis in melanoma, lymphoma
-- **AFP elevation**: Poor prognosis in hepatocellular carcinoma
-
-**Cardiovascular**
-- **NT-proBNP/BNP**: Elevated levels predict mortality in heart failure
-- **Troponin**: Predicts adverse events in ACS
-- **CRP**: Inflammation marker, predicts cardiovascular events
-
-**Infectious Disease**
-- **HIV viral load**: Predicts disease progression if untreated
-- **HCV genotype**: Predicts treatment duration needed
-
-**Application**: Risk stratification, treatment intensity selection, clinical trial enrollment
-
-### Predictive Biomarkers
-
-**Definition**: Identify patients likely to benefit (or not benefit) from specific therapy
-
-**Positive Predictive Biomarkers (Treatment Benefit)**
-
-**Oncology - Targeted Therapy**
-- **EGFR exon 19 del/L858R → EGFR TKIs**: Response rate 60-70%, PFS 10-14 months
-- **ALK rearrangement → ALK inhibitors**: ORR 70-90%, PFS 25-34 months
-- **HER2 amplification → Trastuzumab**: Benefit only in HER2+ (IHC 3+ or FISH+)
-- **BRAF V600E → BRAF inhibitors**: ORR 50%, PFS 6-7 months (melanoma)
-- **PD-L1 ≥50% → Pembrolizumab**: ORR 45%, PFS 10 months vs 6 months (chemo)
-
-**Oncology - Immunotherapy**
-- **MSI-H/dMMR → Anti-PD-1**: ORR 40-60% across tumor types
-- **TMB-high → Immunotherapy**: Investigational, some benefit signals
-- **PD-L1 expression → Anti-PD-1/PD-L1**: Higher expression correlates with better response
-
-**Hematology**
-- **BCR-ABL → Imatinib (CML)**: Complete cytogenetic response 80%
-- **CD20+ → Rituximab (lymphoma)**: Benefit only if CD20-expressing cells
-- **CD33+ → Gemtuzumab ozogamicin (AML)**: Benefit in CD33+ subset
-
-**Negative Predictive Biomarkers (Resistance/No Benefit)**
-- **KRAS mutation → Anti-EGFR mAbs (CRC)**: No benefit, contraindicated
-- **EGFR T790M → 1st/2nd-gen TKIs**: Resistance mechanism, use osimertinib
-- **RAS/RAF wild-type required → BRAF inhibitors (melanoma)**: Paradoxical MAPK activation
-
-### Diagnostic Biomarkers
-
-**Definition**: Detect or confirm presence of disease
-
-**Infectious Disease**
-- **PCR for pathogen DNA/RNA**: SARS-CoV-2, HIV, HCV viral load
-- **Antibody titers**: IgM (acute), IgG (prior exposure/immunity)
-- **Antigen tests**: Rapid detection (strep, flu, COVID)
-
-**Autoimmune**
-- **ANA**: Screen for lupus, connective tissue disease
-- **Anti-CCP**: Specific for rheumatoid arthritis
-- **Anti-dsDNA**: Lupus, correlates with disease activity
-- **ANCA**: Vasculitis (c-ANCA for GPA, p-ANCA for MPA)
-
-**Cancer**
-- **PSA**: Prostate cancer screening/monitoring
-- **CA 19-9**: Pancreatic cancer, biliary obstruction
-- **CEA**: Colorectal cancer monitoring
-- **AFP**: Hepatocellular carcinoma, germ cell tumors
-
-### Pharmacodynamic Biomarkers
-
-**Definition**: Assess treatment response or mechanism of action
-
-**Examples**
-- **HbA1c**: Glycemic control in diabetes (target <7% typically)
-- **LDL cholesterol**: Statin efficacy (target <70 mg/dL in high-risk)
-- **Blood pressure**: Antihypertensive efficacy (target <130/80 mmHg)
-- **Viral load suppression**: Antiretroviral efficacy (target <20 copies/mL)
-- **INR**: Warfarin anticoagulation monitoring (target 2-3 for most indications)
-
-## Genomic Biomarkers
-
-### Mutation Analysis
-
-**Driver Mutations (Oncogenic)**
-- **Activating mutations**: Constitutive pathway activation (BRAF V600E, EGFR L858R)
-- **Inactivating mutations**: Tumor suppressor loss (TP53, PTEN)
-- **Hotspot mutations**: Recurrent positions (KRAS G12/G13, PIK3CA H1047R)
-- **Variant allele frequency (VAF)**: Clonality (VAF ≈50% clonal, <10% subclonal)
-
-**Resistance Mutations**
-- **EGFR T790M**: Resistance to 1st/2nd-gen TKIs (40-60% of cases)
-- **ALK G1202R, I1171N**: Resistance to early ALK inhibitors
-- **ESR1 mutations**: Resistance to aromatase inhibitors (breast cancer)
-- **RAS mutations**: Acquired resistance to anti-EGFR therapy (CRC)
-
-**Mutation Detection Methods**
-- **Tissue NGS**: Comprehensive genomic profiling, 300-500 genes
-- **Liquid biopsy**: ctDNA analysis, non-invasive, serial monitoring
-- **PCR-based assays**: Targeted hotspot detection, FDA-approved companion diagnostics
-- **Allele-specific PCR**: High sensitivity for known mutations (cobas EGFR test)
-
-### Copy Number Variations (CNV)
-
-**Amplifications**
-- **HER2 (ERBB2)**: Breast, gastric cancer → trastuzumab, pertuzumab
- - Testing: IHC (0, 1+, 2+, 3+) → FISH if 2+ (HER2/CEP17 ratio ≥2.0)
-- **MET amplification**: NSCLC resistance mechanism → crizotinib, capmatinib
- - Cut-point: Gene copy number ≥5, GCN/CEP7 ratio ≥2.0
-- **EGFR amplification**: Glioblastoma, some NSCLC
-- **FGFR2 amplification**: Gastric cancer → investigational FGFR inhibitors
-
-**Deletions**
-- **PTEN loss**: Common in many cancers, predicts PI3K pathway activation
-- **RB1 loss**: Small cell transformation, poor prognosis
-- **CDKN2A/B deletion**: Cell cycle dysregulation
-- **Homozygous deletion**: Complete loss of both alleles (more significant)
-
-**Detection Methods**
-- **FISH (Fluorescence In Situ Hybridization)**: HER2, ALK rearrangements
-- **NGS copy number calling**: Depth of coverage analysis
-- **SNP array**: Genome-wide CNV detection
-- **ddPCR**: Quantitative copy number measurement
-
-### Gene Fusions and Rearrangements
-
-**Oncogenic Fusions**
-- **ALK fusions** (NSCLC): EML4-ALK most common (60%), 20+ partners
- - Detection: IHC (D5F3 antibody), FISH (break-apart probe), NGS/RNA-seq
-- **ROS1 fusions** (NSCLC, glioblastoma): CD74-ROS1, SLC34A2-ROS1, others
-- **RET fusions** (NSCLC, thyroid): KIF5B-RET, CCDC6-RET
-- **NTRK fusions** (many tumor types, rare): ETV6-NTRK3, others
- - Pan-cancer: Larotrectinib, entrectinib approved across tumor types
-- **BCR-ABL** (CML, ALL): t(9;22), Philadelphia chromosome
-
-**Fusion Partner Considerations**
-- Partner influences drug sensitivity (EML4-ALK variant 3 more sensitive)
-- 5' vs 3' fusion affects detection methods
-- Intron breakpoints vary (RNA-seq more comprehensive than DNA panels)
-
-**Detection Methods**
-- **FISH break-apart probes**: ALK, ROS1, RET
-- **IHC**: ALK protein overexpression (screening), ROS1
-- **RT-PCR**: Targeted fusion detection
-- **RNA-seq**: Comprehensive fusion detection, identifies novel partners
-
-### Tumor Mutational Burden (TMB)
-
-**Definition**: Number of somatic mutations per megabase of DNA
-
-**Classification**
-- **TMB-high**: ≥10 mutations/Mb (some definitions ≥20 mut/Mb)
-- **TMB-intermediate**: 6-9 mutations/Mb
-- **TMB-low**: <6 mutations/Mb
-
-**Clinical Application**
-- **Predictive for immunotherapy**: Higher TMB → more neoantigens → better immune response
-- **FDA approval**: Pembrolizumab for TMB-H (≥10 mut/Mb) solid tumors (2020)
-- **Limitations**: Not validated in all tumor types, assay variability
-
-**Tumor Types with Typically High TMB**
-- Melanoma (median 10-15 mut/Mb)
-- NSCLC (especially smoking-associated, 8-12 mut/Mb)
-- Urothelial carcinoma (8-10 mut/Mb)
-- Microsatellite instable tumors (30-50 mut/Mb)
-
-### Microsatellite Instability (MSI) and Mismatch Repair (MMR)
-
-**Classification**
-- **MSI-high (MSI-H)**: Instability at ≥2 of 5 loci or ≥30% of markers
-- **MSI-low (MSI-L)**: Instability at <2 of 5 loci
-- **Microsatellite stable (MSS)**: No instability
-
-**Mismatch Repair Status**
-- **dMMR (deficient)**: Loss of MLH1, MSH2, MSH6, or PMS2 by IHC
-- **pMMR (proficient)**: Intact expression of all four MMR proteins
-
-**Clinical Significance**
-- **MSI-H/dMMR Tumors**: 3-5% of most solid tumors, 15% of colorectal cancer
-- **Immunotherapy Sensitivity**: ORR 30-60% to anti-PD-1 therapy
- - Pembrolizumab FDA-approved for MSI-H/dMMR solid tumors (2017)
- - Nivolumab ± ipilimumab approved
-- **Chemotherapy Resistance**: MSI-H CRC does not benefit from 5-FU adjuvant therapy
-- **Lynch Syndrome**: Germline MMR mutation if MSI-H + young age + family history
-
-**Testing Algorithm**
-```
-Colorectal Cancer (all newly diagnosed):
-1. IHC for MMR proteins (MLH1, MSH2, MSH6, PMS2)
- ├─ All intact → pMMR (MSS) → Standard chemotherapy if indicated
- │
- └─ Loss of one or more → dMMR (likely MSI-H)
- └─ Reflex MLH1 promoter hypermethylation test
- ├─ Methylated → Sporadic MSI-H, immunotherapy option
- └─ Unmethylated → Germline testing for Lynch syndrome
-```
-
-## Expression Biomarkers
-
-### Immunohistochemistry (IHC)
-
-**PD-L1 Expression (Immune Checkpoint)**
-- **Assays**: 22C3 (FDA), 28-8, SP263, SP142 (some differences in scoring)
-- **Scoring**: Tumor Proportion Score (TPS) = % tumor cells with membrane staining
- - TPS <1%: Low/negative
- - TPS 1-49%: Intermediate
- - TPS ≥50%: High
-- **Combined Positive Score (CPS)**: (PD-L1+ tumor + immune cells) / total tumor cells × 100
- - Used for some indications (e.g., CPS ≥10 for pembrolizumab in HNSCC)
-
-**Hormone Receptors (Breast Cancer)**
-- **ER/PR Positivity**: ≥1% nuclear staining by IHC (ASCO/CAP guidelines)
- - Allred Score 0-8 (proportion + intensity) - historical
- - H-score 0-300 (percentage at each intensity) - quantitative
-- **Clinical Cut-Points**:
- - ER ≥1%: Endocrine therapy indicated
- - ER 1-10%: "Low positive," may have lower benefit
- - PR loss with ER+: Possible endocrine resistance
-
-**HER2 Testing (Breast/Gastric Cancer)**
-```
-IHC Initial Test:
-├─ 0 or 1+: HER2-negative (no further testing)
-│
-├─ 2+: Equivocal → Reflex FISH testing
-│ ├─ FISH+ (HER2/CEP17 ratio ≥2.0 OR HER2 copies ≥6/cell) → HER2-positive
-│ └─ FISH- → HER2-negative
-│
-└─ 3+: HER2-positive (no FISH needed)
- └─ Uniform intense complete membrane staining in >10% of tumor cells
-
-HER2-positive: Trastuzumab-based therapy indicated
-HER2-low (IHC 1+ or 2+/FISH-): Trastuzumab deruxtecan eligibility (2022)
-```
-
-### RNA Expression Analysis
-
-**Gene Expression Signatures (Breast Cancer)**
-
-**Oncotype DX (21-gene assay)**
-- **Recurrence Score (RS)**: 0-100
- - RS <26: Low risk → Endocrine therapy alone (most patients)
- - RS 26-100: High risk → Chemotherapy + endocrine therapy
-- **Population**: ER+/HER2-, node-negative or 1-3 positive nodes
-- **Evidence**: TAILORx trial (N=10,273) validated RS <26 can omit chemo
-
-**MammaPrint (70-gene assay)**
-- **Result**: High risk vs Low risk (binary)
-- **Population**: Early-stage breast cancer, ER+/HER2-
-- **Evidence**: MINDACT trial validated low-risk can omit chemo
-
-**Prosigna (PAM50)**
-- **Result**: Risk of Recurrence (ROR) score + intrinsic subtype
-- **Subtypes**: Luminal A, Luminal B, HER2-enriched, Basal-like
-- **Application**: Post-menopausal, ER+, node-negative or 1-3 nodes
-
-**RNA-Seq for Fusion Detection**
-- **Advantage**: Detects novel fusion partners, quantifies expression
-- **Application**: NTRK fusions (rare, many partners), RET fusions
-- **Limitation**: Requires fresh/frozen tissue or good-quality FFPE RNA
-
-## Molecular Subtypes
-
-### Glioblastoma (GBM) Molecular Classification
-
-**Verhaak 2010 Classification (4 subtypes)**
-
-**Proneural Subtype**
-- **Characteristics**: PDGFRA amplification, IDH1 mutations (secondary GBM), TP53 mutations
-- **Age**: Younger patients typically
-- **Prognosis**: Better prognosis (median OS 15-18 months)
-- **Treatment**: May benefit from bevacizumab less than other subtypes
-
-**Neural Subtype**
-- **Characteristics**: Neuron markers (NEFL, GABRA1, SYT1, SLC12A5)
-- **Controversy**: May represent normal brain contamination
-- **Prognosis**: Intermediate
-- **Treatment**: Standard temozolomide-based therapy
-
-**Classical Subtype**
-- **Characteristics**: EGFR amplification (97%), chromosome 7 gain, chromosome 10 loss
-- **Association**: Lacks TP53, PDGFRA, NF1 mutations
-- **Prognosis**: Intermediate
-- **Treatment**: May benefit from EGFR inhibitors (investigational)
-
-**Mesenchymal Subtype**
-- **Characteristics**: NF1 mutations/deletions, high expression of mesenchymal markers (CHI3L1/YKL-40)
-- **Immune Features**: Higher macrophage/microglia infiltration
-- **Subgroup**: Mesenchymal-immune-active (high immune signature)
-- **Prognosis**: Poor prognosis (median OS 12-13 months)
-- **Treatment**: May respond better to anti-angiogenic therapy, immunotherapy investigational
-
-**Clinical Application**
-```
-GBM Molecular Subtyping Report:
-
-Patient Cohort: Mesenchymal-Immune-Active Subtype (n=15)
-
-Molecular Features:
-- NF1 alterations: 73% (11/15)
-- High YKL-40 expression: 100% (15/15)
-- Immune gene signature: Elevated (median z-score +2.3)
-- CD163+ macrophages: High density (median 180/mm²)
-
-Treatment Implications:
-- Standard therapy: Temozolomide-based (Stupp protocol)
-- Consider: Bevacizumab for recurrent disease (may have enhanced benefit)
-- Clinical trial: Immune checkpoint inhibitors ± anti-angiogenic therapy
-- Prognosis: Median OS 12-14 months (worse than proneural)
-
-Recommendation:
-Enroll in combination immunotherapy trial if eligible, otherwise standard therapy
-with early consideration of bevacizumab at progression.
-```
-
-### Breast Cancer Intrinsic Subtypes
-
-**PAM50-Based Classification**
-
-**Luminal A**
-- **Characteristics**: ER+, HER2-, low proliferation (Ki-67 <20%)
-- **Gene signature**: High ER-related genes, low proliferation genes
-- **Prognosis**: Best prognosis, low recurrence risk
-- **Treatment**: Endocrine therapy alone usually sufficient
-- **Chemotherapy**: Rarely needed unless high-risk features
-
-**Luminal B**
-- **Characteristics**: ER+, HER2- or HER2+, high proliferation (Ki-67 ≥20%)
-- **Subtypes**: Luminal B (HER2-) and Luminal B (HER2+)
-- **Prognosis**: Intermediate prognosis
-- **Treatment**: Chemotherapy + endocrine therapy; add trastuzumab if HER2+
-
-**HER2-Enriched**
-- **Characteristics**: HER2+, ER-, PR-
-- **Gene signature**: High HER2 and proliferation genes, low ER genes
-- **Prognosis**: Poor if untreated, good with HER2-targeted therapy
-- **Treatment**: Chemotherapy + trastuzumab + pertuzumab
-
-**Basal-Like**
-- **Characteristics**: ER-, PR-, HER2- (triple-negative), high proliferation
-- **Gene signature**: Basal cytokeratins (CK5/6, CK17), EGFR
-- **Overlap**: 80% concordance with TNBC, but not identical
-- **Prognosis**: Aggressive, high early recurrence risk
-- **Treatment**: Chemotherapy (platinum, anthracycline), PARP inhibitors if BRCA-mutated
-- **Immunotherapy**: PD-L1+ may benefit from pembrolizumab + chemotherapy
-
-### Colorectal Cancer Consensus Molecular Subtypes (CMS)
-
-**CMS1 (14%): MSI Immune**
-- **Features**: MSI-high, BRAF mutations, strong immune activation
-- **Prognosis**: Poor survival after relapse despite immune infiltration
-- **Treatment**: Immunotherapy highly effective, 5-FU chemotherapy ineffective
-
-**CMS2 (37%): Canonical**
-- **Features**: Epithelial, marked WNT and MYC activation
-- **Prognosis**: Better survival
-- **Treatment**: Benefits from adjuvant chemotherapy
-
-**CMS3 (13%): Metabolic**
-- **Features**: Metabolic dysregulation, KRAS mutations
-- **Prognosis**: Intermediate survival
-- **Treatment**: May benefit from targeted metabolic therapies (investigational)
-
-**CMS4 (23%): Mesenchymal**
-- **Features**: Stromal infiltration, TGF-β activation, angiogenesis
-- **Prognosis**: Worst survival, often diagnosed at advanced stage
-- **Treatment**: May benefit from anti-angiogenic therapy (bevacizumab)
-
-## Companion Diagnostics
-
-### FDA-Approved Biomarker-Drug Pairs
-
-**Required Testing (Label Indication)**
-```
-Biomarker Drug(s) Indication Assay
-EGFR exon 19 del/L858R Osimertinib NSCLC cobas EGFR v2, NGS
-ALK rearrangement Alectinib, brigatinib NSCLC Vysis ALK FISH, IHC (D5F3)
-BRAF V600E Vemurafenib, dabrafenib Melanoma, NSCLC THxID BRAF, cobas BRAF
-HER2 amplification Trastuzumab, pertuzumab Breast, gastric HercepTest IHC, FISH
-ROS1 rearrangement Crizotinib, entrectinib NSCLC FISH, NGS
-PD-L1 ≥50% TPS Pembrolizumab (mono) NSCLC first-line 22C3 pharmDx
-MSI-H/dMMR Pembrolizumab Any solid tumor IHC (MMR), PCR (MSI)
-NTRK fusion Larotrectinib, entrectinib Pan-cancer FoundationOne CDx
-BRCA1/2 mutations Olaparib, talazoparib Breast, ovarian, prostate BRACAnalysis CDx
-```
-
-### Complementary Diagnostics (Informative, Not Required)
-
-- **PD-L1 1-49%**: Informs combination vs monotherapy choice
-- **TMB-high**: May predict immunotherapy benefit (not FDA-approved indication)
-- **STK11/KEAP1 mutations**: Associated with immunotherapy resistance
-- **Homologous recombination deficiency (HRD)**: Predicts PARP inhibitor benefit
-
-## Clinical Actionability Frameworks
-
-### OncoKB Levels of Evidence (Memorial Sloan Kettering)
-
-**Level 1: FDA-Approved**
-- Biomarker-drug pair with FDA approval in specific tumor type
-- Example: EGFR L858R → osimertinib in NSCLC
-
-**Level 2: Standard Care Off-Label**
-- Biomarker-drug in professional guidelines for specific tumor type (not FDA-approved for biomarker)
-- Example: BRAF V600E → dabrafenib + trametinib in CRC (NCCN-recommended)
-
-**Level 3: Clinical Evidence**
-- Clinical trial evidence supporting biomarker-drug association
-- 3A: Compelling clinical evidence
-- 3B: Standard care for different tumor type or investigational
-
-**Level 4: Biological Evidence**
-- Preclinical evidence only (cell lines, mouse models)
-- 4: Biological evidence supporting association
-
-**Level R1-R2: Resistance**
-- R1: Standard care associated with resistance
-- R2: Investigational or preclinical resistance evidence
-
-### CIViC (Clinical Interpretation of Variants in Cancer)
-
-**Evidence Levels**
-- **A**: Validated in clinical practice or validated by regulatory association
-- **B**: Clinical trial or other primary patient data supporting association
-- **C**: Case study with molecular analysis
-- **D**: Preclinical evidence (cell culture, animal models)
-- **E**: Inferential association (literature review, expert opinion)
-
-**Clinical Significance Tiers**
-- **Tier I**: Variants with strong clinical significance (predictive, diagnostic, prognostic in professional guidelines)
-- **Tier II**: Variants with potential clinical significance (clinical trial or case study evidence)
-- **Tier III**: Variants with uncertain significance
-- **Tier IV**: Benign or likely benign variants
-
-## Multi-Biomarker Panels
-
-### Comprehensive Genomic Profiling (CGP)
-
-**FoundationOne CDx**
-- **Genes**: 324 genes (SNVs, indels, CNVs, rearrangements)
-- **Additional**: TMB, MSI status
-- **FDA-Approved**: Companion diagnostic for 18+ targeted therapies
-- **Turnaround**: 10-14 days
-- **Tissue**: FFPE, 40 unstained slides or tissue block
-
-**Guardant360 CDx (Liquid Biopsy)**
-- **Genes**: 74 genes in cell-free DNA (cfDNA)
-- **Sample**: 2 tubes of blood (20 mL total)
-- **FDA-Approved**: Companion diagnostic for osimertinib (EGFR), NSCLC
-- **Application**: Non-invasive, serial monitoring, when tissue unavailable
-- **Limitation**: Lower sensitivity than tissue (especially for low tumor burden)
-
-**Tempus xT**
-- **Genes**: 648 genes (DNA) + whole transcriptome (RNA)
-- **Advantage**: RNA detects fusions, expression signatures
-- **Application**: Research and clinical use
-- **Not FDA-Approved**: Not a companion diagnostic currently
-
-### Testing Recommendations by Tumor Type
-
-**NSCLC (NCCN Guidelines)**
-```
-Broad molecular profiling for all advanced NSCLC at diagnosis:
-
-Required (FDA-approved therapies available):
-✓ EGFR mutations (exons 18, 19, 20, 21)
-✓ ALK rearrangement
-✓ ROS1 rearrangement
-✓ BRAF V600E
-✓ MET exon 14 skipping
-✓ RET rearrangements
-✓ NTRK fusions
-✓ KRAS G12C
-✓ PD-L1 IHC
-
-Recommended (to inform treatment strategy):
-✓ Comprehensive NGS panel (captures all above + emerging targets)
-✓ Consider liquid biopsy if tissue insufficient
-
-At progression on targeted therapy:
-✓ Repeat tissue biopsy or liquid biopsy for resistance mechanisms
-✓ Examples: EGFR T790M, ALK resistance mutations, MET amplification
-```
-
-**Metastatic Colorectal Cancer**
-```
-Required before anti-EGFR therapy (cetuximab, panitumumab):
-✓ RAS testing (KRAS exons 2, 3, 4; NRAS exons 2, 3, 4)
- └─ RAS mutation → Do NOT use anti-EGFR therapy (resistance)
-✓ BRAF V600E
- └─ If BRAF V600E+ → Consider encorafenib + cetuximab + binimetinib
-
-Recommended for all metastatic CRC:
-✓ MSI/MMR testing (immunotherapy indication)
-✓ HER2 amplification (investigational trastuzumab-based therapy if RAS/BRAF WT)
-✓ NTRK fusions (rare, <1%, but actionable)
-
-Left-sided vs Right-sided:
-- Left-sided (descending, sigmoid, rectum): Better prognosis, anti-EGFR more effective
-- Right-sided (cecum, ascending): Worse prognosis, anti-EGFR less effective, consider bevacizumab
-```
-
-**Melanoma**
-```
-All advanced melanoma:
-✓ BRAF V600 mutation (30-50% of cutaneous melanoma)
- └─ If BRAF V600E/K → Dabrafenib + trametinib or vemurafenib + cobimetinib
-✓ NRAS mutation (20-30%)
- └─ No targeted therapy approved, consider MEK inhibitor trials
-✓ KIT mutations (mucosal, acral, chronic sun-damaged melanoma)
- └─ If KIT exon 11 or 13 mutation → Imatinib (off-label)
-✓ PD-L1 (optional, not required for immunotherapy eligibility)
-
-Note: Uveal melanoma has different biology (GNAQ, GNA11 mutations)
-```
-
-## Biomarker Cut-Points and Thresholds
-
-### Establishing Clinical Cut-Points
-
-**Methods for Cut-Point Determination**
-
-**Data-Driven Approaches**
-- **Median split**: Simple but arbitrary, may not be optimal
-- **Tertiles/quartiles**: Categorizes into 3-4 groups
-- **ROC curve analysis**: Maximizes sensitivity and specificity
-- **Maximally selected rank statistics**: Finds optimal prognostic cut-point
-- **Validation required**: Independent cohort confirmation essential
-
-**Biologically Informed**
-- **Detection limit**: Assay lower limit of quantification
-- **Mechanism-based**: Threshold for pathway activation
-- **Pharmacodynamic**: Threshold for target engagement
-- **Normal range**: Comparison to healthy individuals
-
-**Clinically Defined**
-- **Guideline-recommended**: Established by professional societies
-- **Regulatory-approved**: FDA-specified threshold for companion diagnostic
-- **Trial-defined**: Cut-point used in pivotal clinical trial
-
-**PD-L1 Example**
-- **Cut-points**: 1%, 5%, 10%, 50% TPS used in different trials
-- **Context-dependent**: Varies by drug, disease, line of therapy
-- **≥50%**: Pembrolizumab monotherapy (KEYNOTE-024)
-- **≥1%**: Atezolizumab combinations, broader population
-
-### Continuous vs Categorical
-
-**Continuous Analysis Advantages**
-- Preserves information (no dichotomization loss)
-- Statistical power maintained
-- Can assess dose-response relationship
-- HR per unit increase or per standard deviation
-
-**Categorical Analysis Advantages**
-- Clinically interpretable (high vs low)
-- Facilitates treatment decisions (binary: use targeted therapy yes/no)
-- Aligns with regulatory approvals (biomarker-positive = eligible)
-
-**Best Practice**: Report both continuous and categorical analyses
-- Cox model with continuous biomarker
-- Stratified analysis by clinically relevant cut-point
-- Subgroup analysis to confirm consistency
-
-## Germline vs Somatic Testing
-
-### Germline (Inherited) Mutations
-
-**Indications for Germline Testing**
-- **Cancer predisposition syndromes**: BRCA1/2, Lynch syndrome (MLH1, MSH2), Li-Fraumeni (TP53)
-- **Family history**: Multiple affected relatives, young age at diagnosis
-- **Tumor features**: MSI-H in young patient, triple-negative breast cancer <60 years
-- **Treatment implications**: PARP inhibitors for BRCA-mutated (germline or somatic)
-
-**Common Hereditary Cancer Syndromes**
-- **BRCA1/2**: Breast, ovarian, pancreatic, prostate cancer
- - Testing: All ovarian cancer, TNBC <60 years, male breast cancer
- - Treatment: PARP inhibitors (olaparib, talazoparib)
- - Prevention: Prophylactic mastectomy, oophorectomy (risk-reducing)
-- **Lynch syndrome (MLH1, MSH2, MSH6, PMS2)**: Colorectal, endometrial, ovarian, gastric
- - Testing: MSI-H/dMMR tumors, Amsterdam II criteria families
- - Surveillance: Colonoscopy every 1-2 years starting age 20-25
-- **Li-Fraumeni (TP53)**: Diverse cancers at young age
-- **PTEN (Cowden syndrome)**: Breast, thyroid, endometrial cancer
-
-**Genetic Counseling**
-- Pre-test counseling: Implications for patient and family
-- Post-test counseling: Management, surveillance, family testing
-- Informed consent: Genetic discrimination concerns (GINA protections)
-
-### Somatic (Tumor-Only) Testing
-
-**Tumor Tissue Testing**
-- Detects mutations present in cancer cells only (not inherited)
-- Most cancer driver mutations are somatic (KRAS, EGFR in lung cancer)
-- No implications for family members
-- Guides therapy selection
-
-**Distinguishing Germline from Somatic**
-- **Variant allele frequency**: Germline ~50% (heterozygous) or ~100% (homozygous); somatic variable
-- **Matched normal**: Paired tumor-normal sequencing definitive
-- **Databases**: Germline variant databases (gnomAD, ClinVar)
-- **Reflex germline testing**: Trigger testing if pathogenic germline variant suspected
-
-## Reporting Biomarker Results
-
-### Structured Report Template
-
-```
-MOLECULAR PROFILING REPORT
-
-Patient: [De-identified ID]
-Tumor Type: Non-Small Cell Lung Adenocarcinoma
-Specimen: Lung biopsy (left upper lobe)
-Testing Date: [Date]
-Report Date: [Date]
-
-METHODOLOGY
-- Assay: FoundationOne CDx (comprehensive genomic profiling)
-- Specimen Type: Formalin-fixed paraffin-embedded (FFPE)
-- Tumor Content: 40% (adequate for testing)
-
-RESULTS SUMMARY
-Biomarkers Detected: 4
-- 1 FDA-approved therapy target
-- 1 prognostic biomarker
-- 2 variants of uncertain significance
-
-ACTIONABLE FINDINGS
-
-Tier 1: FDA-Approved Targeted Therapy Available
-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-EGFR Exon 19 Deletion (p.E746_A750del)
- Variant Allele Frequency: 42%
- Clinical Significance: Sensitizing mutation
- FDA-Approved Therapy: Osimertinib (Tagrisso) 80 mg daily
- Evidence: FLAURA trial - median PFS 18.9 vs 10.2 months (HR 0.46, p<0.001)
- Guideline: NCCN Category 1 preferred first-line
- Recommendation: Strong recommendation for EGFR TKI therapy (GRADE 1A)
-
-Tier 2: Prognostic Biomarker
-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-TP53 Mutation (p.R273H)
- Variant Allele Frequency: 85%
- Clinical Significance: Poor prognostic marker, no targeted therapy
- Implication: Associated with worse survival, does not impact first-line treatment selection
-
-BIOMARKERS ASSESSED - NEGATIVE
-- ALK rearrangement: Not detected
-- ROS1 rearrangement: Not detected
-- BRAF V600E: Not detected
-- MET exon 14 skipping: Not detected
-- RET rearrangement: Not detected
-- KRAS mutation: Not detected
-- PD-L1 IHC: Separate report (TPS 30%)
-
-TUMOR MUTATIONAL BURDEN: 8 mutations/Mb (Intermediate)
-- Interpretation: Below threshold for TMB-high designation (≥10 mut/Mb)
-- Clinical relevance: May still benefit from immunotherapy combinations
-
-MICROSATELLITE STATUS: Stable (MSS)
-
-CLINICAL RECOMMENDATIONS
-
-Primary Recommendation:
-First-line therapy with osimertinib 80 mg PO daily until progression or unacceptable toxicity.
-
-Monitoring:
-- CT imaging every 6 weeks for first 12 weeks, then every 9 weeks
-- At progression, repeat tissue or liquid biopsy for resistance mechanisms (T790M, C797S, MET amplification)
-
-Alternative Options:
-- Clinical trial enrollment for novel EGFR TKI combinations
-- Erlotinib or afatinib (second-line for osimertinib if used first-line)
-
-References:
-1. Soria JC, et al. Osimertinib in Untreated EGFR-Mutated Advanced NSCLC. NEJM 2018.
-2. NCCN Guidelines for Non-Small Cell Lung Cancer v4.2024.
-
-Report Prepared By: [Lab Name]
-Medical Director: [Name, MD, PhD]
-CLIA #: [Number] | CAP #: [Number]
-```
-
-## Quality Assurance
-
-### Analytical Validation
-
-- **Sensitivity**: Minimum 5-10% variant allele frequency detection
-- **Specificity**: <1% false positive rate
-- **Reproducibility**: >95% concordance between replicates
-- **Accuracy**: >99% concordance with validated orthogonal method
-- **Turnaround time**: Median time from sample receipt to report
-
-### Clinical Validation
-
-- **Positive Predictive Value**: % biomarker+ patients who respond to therapy
-- **Negative Predictive Value**: % biomarker- patients who do not respond
-- **Clinical Utility**: Does testing improve patient outcomes?
-- **Cost-Effectiveness**: QALY gained vs cost of testing and treatment
-
-### Proficiency Testing
-
-- CAP/CLIA proficiency testing for clinical labs
-- Participate in external quality assurance schemes
-- Blinded sample exchange with reference laboratories
-- Document corrective actions for failures
-
diff --git a/skills/clinical-decision-support/references/clinical_decision_algorithms.md b/skills/clinical-decision-support/references/clinical_decision_algorithms.md
deleted file mode 100644
index 643b6a40..00000000
--- a/skills/clinical-decision-support/references/clinical_decision_algorithms.md
+++ /dev/null
@@ -1,604 +0,0 @@
-# Clinical Decision Algorithms Guide
-
-## Overview
-
-Clinical decision algorithms provide systematic, step-by-step guidance for diagnosis, treatment selection, and patient management. This guide covers algorithm development, validation, and visual presentation using decision trees and flowcharts.
-
-## Algorithm Design Principles
-
-### Key Components
-
-**Decision Nodes**
-- **Question/Criteria**: Clear, measurable clinical parameter
-- **Binary vs Multi-Way**: Yes/no (simple) vs multiple options (complex)
-- **Objective**: Lab value, imaging finding vs Subjective: Clinical judgment
-
-**Action Nodes**
-- **Treatment**: Specific intervention with dosing
-- **Test**: Additional diagnostic procedure
-- **Referral**: Specialist consultation, higher level of care
-- **Observation**: Watchful waiting with defined follow-up
-
-**Terminal Nodes**
-- **Outcome**: Final decision point
-- **Follow-up**: Schedule for reassessment
-- **Exit criteria**: When to exit algorithm
-
-### Design Criteria
-
-**Clarity**
-- Unambiguous decision points
-- Mutually exclusive pathways
-- No circular loops (unless intentional reassessment cycles)
-- Clear entry and exit points
-
-**Clinical Validity**
-- Evidence-based decision criteria
-- Validated cut-points for biomarkers
-- Guideline-concordant recommendations
-- Expert consensus where evidence limited
-
-**Usability**
-- Maximum 7 decision points per pathway (cognitive load)
-- Visual hierarchy (most common path highlighted)
-- Printable single-page format preferred
-- Color coding for urgency/safety
-
-**Completeness**
-- All possible scenarios covered
-- Default pathway for edge cases
-- Safety-net provisions for unusual presentations
-- Escalation criteria clearly stated
-
-## Clinical Decision Trees
-
-### Diagnostic Algorithms
-
-**Chest Pain Evaluation Algorithm**
-
-```
-Entry: Patient with chest pain
-
-├─ STEMI Criteria? (ST elevation ≥1mm in ≥2 contiguous leads)
-│ ├─ YES → Activate cath lab, aspirin 325mg, heparin, clopidogrel 600mg
-│ │ Transfer for primary PCI (goal door-to-balloon <90 minutes)
-│ └─ NO → Continue evaluation
-
-├─ High-Risk Features? (Hemodynamic instability, arrhythmia, troponin elevation)
-│ ├─ YES → Admit CCU, serial troponins, cardiology consultation
-│ │ Consider early angiography if NSTEMI
-│ └─ NO → Calculate TIMI or HEART score
-
-├─ TIMI Score 0-1 or HEART Score 0-3? (Low risk)
-│ ├─ YES → Observe 6-12 hours, serial troponins, stress test if negative
-│ │ Discharge if all negative with cardiology follow-up in 72 hours
-│ └─ NO → TIMI 2-4 or HEART 4-6 (Intermediate risk)
-
-├─ TIMI Score 2-4 or HEART Score 4-6? (Intermediate risk)
-│ ├─ YES → Admit telemetry, serial troponins, stress imaging vs CT angiography
-│ │ Medical management: Aspirin, statin, beta-blocker
-│ └─ NO → TIMI ≥5 or HEART ≥7 (High risk) → Treat as NSTEMI
-
-Decision Endpoint: Risk-stratified pathway with 30-day event rate documented
-```
-
-**Pulmonary Embolism Diagnostic Algorithm (Wells Criteria)**
-
-```
-Entry: Suspected PE
-
-Step 1: Calculate Wells Score
- Clinical features points:
- - Clinical signs of DVT: 3 points
- - PE more likely than alternative diagnosis: 3 points
- - Heart rate >100: 1.5 points
- - Immobilization/surgery in past 4 weeks: 1.5 points
- - Previous PE/DVT: 1.5 points
- - Hemoptysis: 1 point
- - Malignancy: 1 point
-
-Step 2: Risk Stratify
- ├─ Wells Score ≤4 (PE unlikely)
- │ └─ D-dimer test
- │ ├─ D-dimer negative (<500 ng/mL) → PE excluded, consider alternative diagnosis
- │ └─ D-dimer positive (≥500 ng/mL) → CTPA
- │
- └─ Wells Score >4 (PE likely)
- └─ CTPA (skip D-dimer)
-
-Step 3: CTPA Results
- ├─ Positive for PE → Risk stratify severity
- │ ├─ Massive PE (hypotension, shock) → Thrombolytics vs embolectomy
- │ ├─ Submassive PE (RV strain, troponin+) → Admit ICU, consider thrombolytics
- │ └─ Low-risk PE → Anticoagulation, consider outpatient management
- │
- └─ Negative for PE → PE excluded, investigate alternative diagnosis
-
-Step 4: Treatment Decision (if PE confirmed)
- ├─ Absolute contraindication to anticoagulation?
- │ ├─ YES → IVC filter placement, treat underlying condition
- │ └─ NO → Anticoagulation therapy
- │
- ├─ Cancer-associated thrombosis?
- │ ├─ YES → LMWH preferred (edoxaban alternative)
- │ └─ NO → DOAC preferred (apixaban, rivaroxaban, edoxaban)
- │
- └─ Duration: Minimum 3 months, extended if unprovoked or recurrent
-```
-
-### Treatment Selection Algorithms
-
-**NSCLC First-Line Treatment Algorithm**
-
-```
-Entry: Advanced/Metastatic NSCLC, adequate PS (ECOG 0-2)
-
-Step 1: Biomarker Testing Complete?
- ├─ NO → Reflex testing: EGFR, ALK, ROS1, BRAF, PD-L1, consider NGS
- │ Hold systemic therapy pending results (unless rapidly progressive)
- └─ YES → Proceed to Step 2
-
-Step 2: Actionable Genomic Alteration?
- ├─ EGFR exon 19 deletion or L858R → Osimertinib 80mg daily
- │ └─ Alternative: Erlotinib, gefitinib, afatinib (less preferred)
- │
- ├─ ALK rearrangement → Alectinib 600mg BID
- │ └─ Alternatives: Brigatinib, lorlatinib, crizotinib (less preferred)
- │
- ├─ ROS1 rearrangement → Crizotinib 250mg BID or entrectinib
- │
- ├─ BRAF V600E → Dabrafenib + trametinib
- │
- ├─ MET exon 14 skipping → Capmatinib or tepotinib
- │
- ├─ RET rearrangement → Selpercatinib or pralsetinib
- │
- ├─ NTRK fusion → Larotrectinib or entrectinib
- │
- ├─ KRAS G12C → Sotorasib or adagrasib (if no other options)
- │
- └─ NO actionable alteration → Proceed to Step 3
-
-Step 3: PD-L1 Testing Result?
- ├─ PD-L1 ≥50% (TPS)
- │ ├─ Option 1: Pembrolizumab 200mg Q3W (monotherapy, NCCN Category 1)
- │ ├─ Option 2: Pembrolizumab + platinum doublet chemotherapy
- │ └─ Option 3: Atezolizumab + bevacizumab + carboplatin + paclitaxel
- │
- ├─ PD-L1 1-49% (TPS)
- │ ├─ Preferred: Pembrolizumab + platinum doublet chemotherapy
- │ └─ Alternative: Platinum doublet chemotherapy alone
- │
- └─ PD-L1 <1% (TPS)
- ├─ Preferred: Pembrolizumab + platinum doublet chemotherapy
- └─ Alternative: Platinum doublet chemotherapy ± bevacizumab
-
-Step 4: Platinum Doublet Selection (if applicable)
- ├─ Squamous histology
- │ └─ Carboplatin AUC 6 + paclitaxel 200 mg/m² Q3W (4 cycles)
- │ or Carboplatin AUC 5 + nab-paclitaxel 100 mg/m² D1,8,15 Q4W
- │
- └─ Non-squamous histology
- └─ Carboplatin AUC 6 + pemetrexed 500 mg/m² Q3W (4 cycles)
- Continue pemetrexed maintenance if responding
- Add bevacizumab 15 mg/kg if eligible (no hemoptysis, brain mets)
-
-Step 5: Monitoring and Response Assessment
- - Imaging every 6 weeks for first 12 weeks, then every 9 weeks
- - Continue until progression or unacceptable toxicity
- - At progression, proceed to second-line algorithm
-```
-
-**Heart Failure Management Algorithm (AHA/ACC Guidelines)**
-
-```
-Entry: Heart Failure Diagnosis Confirmed
-
-Step 1: Determine HF Type
- ├─ HFrEF (EF ≤40%)
- │ └─ Proceed to Guideline-Directed Medical Therapy (GDMT)
- │
- ├─ HFpEF (EF ≥50%)
- │ └─ Treat comorbidities, diuretics for congestion, consider SGLT2i
- │
- └─ HFmrEF (EF 41-49%)
- └─ Consider HFrEF GDMT, evidence less robust
-
-Step 2: GDMT for HFrEF (All patients unless contraindicated)
-
-Quadruple Therapy (Class 1 recommendations):
-
-1. ACE Inhibitor/ARB/ARNI
- ├─ Preferred: Sacubitril-valsartan 49/51mg BID → titrate to 97/103mg BID
- │ └─ If ACE-I naïve or taking <10mg enalapril equivalent
- ├─ Alternative: ACE-I (enalapril, lisinopril, ramipril) to target dose
- └─ Alternative: ARB (losartan, valsartan) if ACE-I intolerant
-
-2. Beta-Blocker (start low, titrate slowly)
- ├─ Bisoprolol 1.25mg daily → 10mg daily target
- ├─ Metoprolol succinate 12.5mg daily → 200mg daily target
- └─ Carvedilol 3.125mg BID → 25mg BID target (50mg BID if >85kg)
-
-3. Mineralocorticoid Receptor Antagonist (MRA)
- ├─ Spironolactone 12.5-25mg daily → 50mg daily target
- └─ Eplerenone 25mg daily → 50mg daily target
- └─ Contraindications: K >5.0, CrCl <30 mL/min
-
-4. SGLT2 Inhibitor (regardless of diabetes status)
- ├─ Dapagliflozin 10mg daily
- └─ Empagliflozin 10mg daily
-
-Step 3: Additional Therapies Based on Phenotype
-
-├─ Sinus rhythm + HR ≥70 despite beta-blocker?
-│ └─ YES: Add ivabradine 5mg BID → 7.5mg BID target
-│
-├─ African American + NYHA III-IV?
-│ └─ YES: Add hydralazine 37.5mg TID + isosorbide dinitrate 20mg TID
-│ (Target: hydralazine 75mg TID + ISDN 40mg TID)
-│
-├─ Atrial fibrillation?
-│ ├─ Rate control (target <80 bpm at rest, <110 bpm with activity)
-│ └─ Anticoagulation (DOAC preferred, warfarin if valvular)
-│
-└─ Iron deficiency (ferritin <100 or <300 with TSAT <20%)?
- └─ YES: IV iron supplementation (ferric carboxymaltose)
-
-Step 4: Device Therapy Evaluation
-
-├─ EF ≤35%, NYHA II-III, LBBB with QRS ≥150 ms, sinus rhythm?
-│ └─ YES: Cardiac resynchronization therapy (CRT-D)
-│
-├─ EF ≤35%, NYHA II-III, on GDMT ≥3 months?
-│ └─ YES: ICD for primary prevention
-│ (if life expectancy >1 year with good functional status)
-│
-└─ EF ≤35%, NYHA IV despite GDMT, or advanced HF?
- └─ Refer to advanced HF specialist
- ├─ LVAD evaluation
- ├─ Heart transplant evaluation
- └─ Palliative care consultation
-
-Step 5: Monitoring and Titration
-
-Weekly to biweekly visits during titration:
-- Blood pressure (target SBP ≥90 mmHg)
-- Heart rate (target 50-60 bpm)
-- Potassium (target 4.0-5.0 mEq/L, hold MRA if >5.5)
-- Creatinine (expect 10-20% increase, acceptable if <30% and stable)
-- Symptoms and congestion status (daily weights, NYHA class)
-
-Stable on GDMT:
-- Visits every 3-6 months
-- Echocardiogram at 3-6 months after GDMT optimization, then annually
-- NT-proBNP or BNP trending (biomarker-guided therapy investigational)
-```
-
-## Risk Stratification Tools
-
-### Cardiovascular Risk Scores
-
-**TIMI Risk Score (NSTEMI/Unstable Angina)**
-
-```
-Score Calculation (0-7 points):
-☐ Age ≥65 years (1 point)
-☐ ≥3 cardiac risk factors (HTN, hyperlipidemia, diabetes, smoking, family history) (1)
-☐ Known CAD (stenosis ≥50%) (1)
-☐ ASA use in past 7 days (1)
-☐ Severe angina (≥2 episodes in 24 hours) (1)
-☐ ST deviation ≥0.5 mm (1)
-☐ Elevated cardiac biomarkers (1)
-
-Risk Stratification:
-├─ Score 0-1: 5% risk of death/MI/urgent revasc at 14 days (Low)
-│ └─ Management: Observation, stress test, outpatient follow-up
-│
-├─ Score 2: 8% risk (Low-intermediate)
-│ └─ Management: Admission, medical therapy, stress imaging
-│
-├─ Score 3-4: 13-20% risk (Intermediate-high)
-│ └─ Management: Admission, aggressive medical therapy, early invasive strategy
-│
-└─ Score 5-7: 26-41% risk (High)
- └─ Management: Aggressive treatment, urgent angiography (<24 hours)
-```
-
-**CHA2DS2-VASc Score (Stroke Risk in Atrial Fibrillation)**
-
-```
-Score Calculation:
-☐ Congestive heart failure (1 point)
-☐ Hypertension (1)
-☐ Age ≥75 years (2)
-☐ Diabetes mellitus (1)
-☐ Prior stroke/TIA/thromboembolism (2)
-☐ Vascular disease (MI, PAD, aortic plaque) (1)
-☐ Age 65-74 years (1)
-☐ Sex category (female) (1)
-
-Maximum score: 9 points
-
-Treatment Algorithm:
-├─ Score 0 (male) or 1 (female): 0-1.3% annual stroke risk
-│ └─ No anticoagulation or aspirin (Class IIb)
-│
-├─ Score 1 (male): 1.3% annual stroke risk
-│ └─ Consider anticoagulation (Class IIa)
-│ Factors: Patient preference, bleeding risk, comorbidities
-│
-└─ Score ≥2 (male) or ≥3 (female): ≥2.2% annual stroke risk
- └─ Anticoagulation recommended (Class I)
- ├─ Preferred: DOAC (apixaban, rivaroxaban, edoxaban, dabigatran)
- └─ Alternative: Warfarin (INR 2-3) if DOAC contraindicated
-
-Bleeding Risk Assessment (HAS-BLED):
-H - Hypertension (SBP >160)
-A - Abnormal renal/liver function (1 point each)
-S - Stroke history
-B - Bleeding history or predisposition
-L - Labile INR (if on warfarin)
-E - Elderly (age >65)
-D - Drugs (antiplatelet, NSAIDs) or alcohol (1 point each)
-
-HAS-BLED ≥3: High bleeding risk → Modifiable factors, consider DOAC over warfarin
-```
-
-### Oncology Risk Calculators
-
-**MELD Score (Hepatocellular Carcinoma Eligibility)**
-
-```
-MELD = 3.78×ln(bilirubin mg/dL) + 11.2×ln(INR) + 9.57×ln(creatinine mg/dL) + 6.43
-
-Interpretation:
-├─ MELD <10: 1.9% 3-month mortality (Low)
-│ └─ Consider resection or ablation for HCC
-│
-├─ MELD 10-19: 6-20% 3-month mortality (Moderate)
-│ └─ Transplant evaluation if within Milan criteria
-│ Milan: Single ≤5cm or ≤3 lesions each ≤3cm, no vascular invasion
-│
-├─ MELD 20-29: 20-45% 3-month mortality (High)
-│ └─ Urgent transplant evaluation, bridge therapy (TACE, ablation)
-│
-└─ MELD ≥30: 50-70% 3-month mortality (Very high)
- └─ Transplant vs palliative care discussion
- Too ill for transplant if MELD >35-40 typically
-```
-
-**Adjuvant! Online (Breast Cancer Recurrence Risk)**
-
-```
-Input Variables:
-- Age at diagnosis
-- Tumor size
-- Tumor grade (1-3)
-- ER status
-- Node status (0, 1-3, 4-9, ≥10)
-- HER2 status
-- Comorbidity index
-
-Output: 10-year risk of:
-- Recurrence
-- Breast cancer mortality
-- Overall mortality
-
-Treatment Benefit Estimates:
-- Chemotherapy: Absolute reduction in recurrence
-- Endocrine therapy: Absolute reduction in recurrence
-- Trastuzumab: Absolute reduction (if HER2+)
-
-Clinical Application:
-├─ Low risk (<10% recurrence): Consider endocrine therapy alone if ER+
-├─ Intermediate risk (10-20%): Chemotherapy discussion, genomic assay
-│ └─ Oncotype DX score <26: Endocrine therapy alone
-│ └─ Oncotype DX score ≥26: Chemotherapy + endocrine therapy
-└─ High risk (>20%): Chemotherapy + endocrine therapy if ER+
-```
-
-## TikZ Flowchart Best Practices
-
-### Visual Design Principles
-
-**Node Styling**
-```latex
-% Decision nodes (diamond)
-\tikzstyle{decision} = [diamond, draw, fill=yellow!20, text width=4.5em, text centered, inner sep=0pt]
-
-% Process nodes (rectangle)
-\tikzstyle{process} = [rectangle, draw, fill=blue!20, text width=5em, text centered, rounded corners, minimum height=3em]
-
-% Terminal nodes (rounded rectangle)
-\tikzstyle{terminal} = [rectangle, draw, fill=green!20, text width=5em, text centered, rounded corners=1em, minimum height=3em]
-
-% Input/Output (parallelogram)
-\tikzstyle{io} = [trapezium, draw, fill=purple!20, text width=5em, text centered, minimum height=3em]
-```
-
-**Color Coding by Urgency**
-- **Red**: Life-threatening, immediate action required
-- **Orange**: Urgent, action within hours
-- **Yellow**: Semi-urgent, action within 24-48 hours
-- **Green**: Routine, stable clinical situation
-- **Blue**: Informational, monitoring only
-
-**Pathway Emphasis**
-- Bold arrows for most common pathway
-- Dashed arrows for rare scenarios
-- Arrow thickness proportional to pathway frequency
-- Highlight boxes around critical decision points
-
-### LaTeX TikZ Template
-
-```latex
-\documentclass{article}
-\usepackage{tikz}
-\usetikzlibrary{shapes, arrows, positioning}
-
-\begin{document}
-
-\tikzstyle{decision} = [diamond, draw, fill=yellow!20, text width=4em, text centered, inner sep=2pt, font=\small]
-\tikzstyle{process} = [rectangle, draw, fill=blue!20, text width=6em, text centered, rounded corners, minimum height=2.5em, font=\small]
-\tikzstyle{terminal} = [rectangle, draw, fill=green!20, text width=6em, text centered, rounded corners=8pt, minimum height=2.5em, font=\small]
-\tikzstyle{alert} = [rectangle, draw=red, line width=1.5pt, fill=red!10, text width=6em, text centered, rounded corners, minimum height=2.5em, font=\small\bfseries]
-\tikzstyle{arrow} = [thick,->,>=stealth]
-
-\begin{tikzpicture}[node distance=2cm, auto]
- % Nodes
- \node [terminal] (start) {Patient presents with symptom X};
- \node [decision, below of=start] (decision1) {Criterion A met?};
- \node [alert, below of=decision1, node distance=2.5cm] (alert1) {Immediate action};
- \node [process, right of=decision1, node distance=4cm] (process1) {Standard evaluation};
- \node [terminal, below of=process1, node distance=2.5cm] (end) {Outcome};
-
- % Arrows
- \draw [arrow] (start) -- (decision1);
- \draw [arrow] (decision1) -- node {Yes} (alert1);
- \draw [arrow] (decision1) -- node {No} (process1);
- \draw [arrow] (process1) -- (end);
- \draw [arrow] (alert1) -| (end);
-\end{tikzpicture}
-
-\end{document}
-```
-
-## Algorithm Validation
-
-### Development Process
-
-**Step 1: Literature Review and Evidence Synthesis**
-- Systematic review of guidelines (NCCN, ASCO, ESMO, AHA/ACC)
-- Meta-analyses of clinical trials
-- Expert consensus statements
-- Local practice patterns and resource availability
-
-**Step 2: Draft Algorithm Development**
-- Multidisciplinary team input (physicians, nurses, pharmacists)
-- Define decision nodes and criteria
-- Specify actions and outcomes
-- Identify areas of uncertainty
-
-**Step 3: Pilot Testing**
-- Retrospective application to historical cases (n=20-50)
-- Identify scenarios not covered by algorithm
-- Refine decision criteria
-- Usability testing with end-users
-
-**Step 4: Prospective Validation**
-- Implement in clinical practice with data collection
-- Track adherence rate (target >80%)
-- Monitor outcomes vs historical controls
-- User satisfaction surveys
-
-**Step 5: Continuous Quality Improvement**
-- Quarterly review of algorithm performance
-- Update based on new evidence
-- Address deviations and reasons for non-adherence
-- Version control and change documentation
-
-### Performance Metrics
-
-**Process Metrics**
-- Algorithm adherence rate (% cases following algorithm)
-- Time to decision (median time from presentation to treatment start)
-- Completion rate (% cases reaching terminal node)
-
-**Outcome Metrics**
-- Appropriateness of care (concordance with guidelines)
-- Clinical outcomes (mortality, morbidity, readmissions)
-- Resource utilization (length of stay, unnecessary tests)
-- Safety (adverse events, errors)
-
-**User Experience Metrics**
-- Ease of use (Likert scale survey)
-- Time to use (median time to navigate algorithm)
-- Perceived utility (% users reporting algorithm helpful)
-- Barriers to use (qualitative feedback)
-
-## Implementation Strategies
-
-### Integration into Clinical Workflow
-
-**Electronic Health Record Integration**
-- Clinical decision support (CDS) alerts at key decision points
-- Order sets linked to algorithm pathways
-- Auto-population of risk scores from EHR data
-- Documentation templates following algorithm structure
-
-**Point-of-Care Tools**
-- Pocket cards for quick reference
-- Mobile apps with interactive algorithms
-- Wall posters in clinical areas
-- QR codes linking to full algorithm
-
-**Education and Training**
-- Didactic presentation of algorithm rationale
-- Case-based exercises
-- Simulation scenarios
-- Audit and feedback on adherence
-
-### Overcoming Barriers
-
-**Common Barriers**
-- Algorithm complexity (too many decision points)
-- Lack of awareness (not disseminated effectively)
-- Disagreement with recommendations (perceived as cookbook medicine)
-- Competing priorities (time pressure, multiple patients)
-- Resource limitations (recommended tests/treatments not available)
-
-**Mitigation Strategies**
-- Simplify algorithms (≤7 decision points per pathway preferred)
-- Champion network (local opinion leaders promoting algorithm)
-- Customize to local context (allow flexibility for clinical judgment)
-- Measure and report outcomes (demonstrate value)
-- Provide resources (ensure algorithm-recommended options available)
-
-## Algorithm Maintenance and Updates
-
-### Version Control
-
-**Change Log Documentation**
-```
-Algorithm: NSCLC First-Line Treatment
-Version: 3.2
-Effective Date: January 1, 2024
-Previous Version: 3.1 (effective July 1, 2023)
-
-Changes in Version 3.2:
-1. Added KRAS G12C-mutated pathway (sotorasib, adagrasib)
- - Evidence: FDA approval May 2021/2022
- - Guideline: NCCN v4.2023
-
-2. Updated PD-L1 ≥50% recommendation to include pembrolizumab monotherapy as Option 1
- - Evidence: KEYNOTE-024 5-year follow-up
- - Guideline: NCCN Category 1 preferred
-
-3. Removed crizotinib as preferred ALK inhibitor, moved to alternative
- - Evidence: ALEX, CROWN trials showing superiority of alectinib, lorlatinib
- - Guideline: NCCN/ESMO Category 1 for alectinib as first-line
-
-Reviewed by: Thoracic Oncology Committee
-Approved by: Dr. [Name], Medical Director
-Next Review Date: July 1, 2024
-```
-
-### Trigger for Updates
-
-**Mandatory Updates (Within 3 Months)**
-- FDA approval of new drug for algorithm indication
-- Guideline change (NCCN, ASCO, ESMO Category 1 recommendation)
-- Safety alert or black box warning added to recommended agent
-- Major clinical trial results changing standard of care
-
-**Routine Updates (Annually)**
-- Minor evidence updates
-- Optimization based on local performance data
-- Formatting or usability improvements
-- Addition of new clinical scenarios encountered
-
-**Emergency Updates (Within 1 Week)**
-- Drug shortage requiring alternative pathways
-- Drug recall or safety withdrawal
-- Outbreak or pandemic requiring modified protocols
-
diff --git a/skills/clinical-decision-support/references/cohort_evaluation.md b/skills/clinical-decision-support/references/cohort_evaluation.md
new file mode 100644
index 00000000..5ab3840d
--- /dev/null
+++ b/skills/clinical-decision-support/references/cohort_evaluation.md
@@ -0,0 +1,142 @@
+# Aggregate Cohort Evaluation
+
+## Scope
+
+This workflow documents cohorts using pre-aggregated counts and summaries. It does not ingest records, classify people, estimate a patient-specific risk, or recommend care.
+
+## Protocol Before Results
+
+Pre-specify:
+
+- objective and target population;
+- study design and setting;
+- index date/time zero;
+- eligibility and sampling;
+- exposure, comparator, outcomes, covariates, and time windows;
+- causal estimand if making a causal claim;
+- confounding strategy;
+- missing-data strategy;
+- subgroup and interaction analyses;
+- multiplicity control;
+- sensitivity and negative-control analyses;
+- disclosure policy.
+
+For routinely collected data, document code sets, phenotypes, database versions, linkage quality, data provenance, and validation.
+
+## Participant Flow
+
+Report aggregate counts for:
+
+1. source population;
+2. eligibility assessed;
+3. excluded by reason;
+4. included;
+5. analysis populations;
+6. missing outcome or follow-up;
+7. subgroup availability.
+
+Apply suppression before releasing the flow. Do not reconstruct suppressed values through totals.
+
+## Table 1
+
+Use summaries appropriate to distributions and measurement:
+
+- categorical: count, denominator, percentage, missing;
+- continuous: mean and standard deviation or median and quartiles;
+- time-dependent or repeated measures: define the summary window;
+- assay measurements: units, platform, detection limits, batch, and transformation.
+
+Baseline significance tests do not measure meaningful imbalance and are not generated by the bundled table helper. If comparison is needed, pre-specify descriptive standardized differences or another justified measure and interpret it in context.
+
+## Effect Estimation
+
+Match measure to question:
+
+- prevalence/risk: risk difference and risk ratio;
+- rates: rate difference and rate ratio;
+- odds: odds ratio, with care when outcomes are common;
+- time to event: estimand-aligned survival measures;
+- repeated outcomes: model and covariance assumptions;
+- diagnostic accuracy: sensitivity/specificity and predictive values at prespecified thresholds.
+
+Report absolute and relative effects with uncertainty when both are relevant. A p-value is not an effect size and “not significant” is not evidence of no difference.
+
+## Confounding and Bias
+
+Address:
+
+- confounding by indication;
+- selection and collider bias;
+- immortal-time and time-varying treatment bias;
+- informative observation/censoring;
+- measurement error and misclassification;
+- missing data;
+- outcome ascertainment;
+- site and calendar-time effects;
+- data-driven subgroup or cut-point selection;
+- unmeasured confounding.
+
+State which variables were selected before analysis and why. Do not select confounders solely by univariable p-values. Distinguish prediction from causal inference.
+
+## Subgroups and Fairness
+
+Subgroup work must document:
+
+- rationale and prespecification;
+- representation and missingness;
+- sample sizes and event counts;
+- effect estimates with intervals;
+- interaction tests when effect heterogeneity is the question;
+- multiplicity;
+- measurement validity across groups;
+- intersectional and site effects where feasible;
+- whether categories are self-reported, assigned, or derived;
+- risk of reinforcing structural inequities.
+
+Do not rank groups or declare fairness from one metric. Small groups may require pooling, secure analysis, or non-release rather than unstable public estimates.
+
+## Biomarker Cohorts
+
+Record:
+
+- biomarker category using FDA-NIH BEST terminology;
+- biological and analytical rationale;
+- specimen collection and handling;
+- assay platform, version, units, and quality controls;
+- prespecified threshold and source;
+- analytical validation;
+- blinding to outcomes;
+- missing/failed assays;
+- internal and external validation;
+- distinction among prognostic, predictive, and treatment-effect interaction claims.
+
+Never derive a threshold on the evaluation cohort and present it as validated without independent confirmation.
+
+## Disclosure Controls
+
+The table generator implements:
+
+- a configurable minimum cell size;
+- primary suppression for small nonzero cells;
+- complementary suppression when one cell could be recovered from a row;
+- group-level suppression when denominators are too small;
+- bounded groups and rows;
+- omission of raw values and identifiers.
+
+The default threshold is a conservative operational setting, not a universal rule. It does not address all differencing, linkage, longitudinal, geographic, genomic, or rare-combination risks. Follow an approved disclosure policy and privacy review.
+
+## Interpretation Template
+
+Use:
+
+> In this aggregate [design] evaluation, [effect/summary] was estimated as [value and interval] for [defined outcome and horizon]. The analysis is [prespecified/exploratory] and is limited by [bias, missingness, precision, transportability]. It does not establish causality, clinical utility, or an action for any person.
+
+## Reporting
+
+- STROBE for observational design.
+- RECORD for routinely collected data.
+- REMARK for tumor prognostic-marker studies.
+- TRIPOD+AI for prediction-model development/evaluation.
+- Appropriate causal-inference and target-trial reporting when making causal claims.
+
+See `study_reporting.md` and `privacy_and_disclosure.md`.
diff --git a/skills/clinical-decision-support/references/decision_logic_traceability.md b/skills/clinical-decision-support/references/decision_logic_traceability.md
new file mode 100644
index 00000000..6761b973
--- /dev/null
+++ b/skills/clinical-decision-support/references/decision_logic_traceability.md
@@ -0,0 +1,146 @@
+# Decision-Logic Traceability
+
+## Scope
+
+“Decision logic” here means research and governance logic only:
+
+- evidence inclusion/exclusion;
+- data-quality gates;
+- validation acceptance criteria;
+- release holds;
+- documentation completeness;
+- change-control approval;
+- human-review checkpoints.
+
+Do not encode diagnostic, treatment, dosing, triage, alarm, urgency, bedside, or patient-facing logic.
+
+## Matrix Purpose
+
+A traceability matrix links each rule to:
+
+- its source and rationale;
+- input/precondition;
+- deterministic statement;
+- bounded output kind;
+- verification tests;
+- owner and reviewer;
+- version and status;
+- known limitations and change history.
+
+The matrix documents logic. It does not execute arbitrary expressions.
+
+## Allowed Node Types
+
+- `input_check`
+- `data_quality_gate`
+- `evidence_rule`
+- `validation_gate`
+- `documentation_gate`
+- `human_review`
+- `release_gate`
+- `monitoring_gate`
+
+Allowed output kinds:
+
+- `include_evidence`
+- `exclude_evidence`
+- `flag_for_review`
+- `validation_status`
+- `documentation_status`
+- `release_hold`
+- `monitoring_status`
+
+There is deliberately no generic “action” node.
+
+## Required Fields
+
+### Matrix Metadata
+
+- logic ID and title;
+- version/status/owner;
+- research-only intended use;
+- prohibited uses;
+- data level;
+- source ledger;
+- human-review requirement;
+- change summary;
+- monitoring and retirement criteria.
+
+### Per Node
+
+- unique node ID;
+- type;
+- precondition/input;
+- logic statement in plain language;
+- output kind;
+- output value;
+- source IDs;
+- rationale;
+- validation tests;
+- owner;
+- reviewer role;
+- status.
+
+## Rule-Writing Guidance
+
+Write rules so an independent reviewer can reproduce the result without hidden knowledge.
+
+Good:
+
+> If an evidence record lacks a stable citation and retrieval date, set output kind `flag_for_review` with value `missing_source_provenance`.
+
+> If external validation is absent, set `release_hold` to `true` for claims of transportability.
+
+Unsafe and prohibited:
+
+> If a person's score is high, trigger an urgent alert.
+
+> If a biomarker is positive, recommend a therapy.
+
+## Validation Tests
+
+For each node include:
+
+- positive case;
+- negative case;
+- boundary case;
+- missing/invalid input;
+- source/version regression;
+- expected output;
+- reviewer and date.
+
+For the matrix as a whole include:
+
+- unreachable or orphan nodes;
+- conflicting outputs;
+- cycles;
+- missing sources;
+- stale versions;
+- bypass paths around human review;
+- rollback and retirement behavior.
+
+The bundled helper validates identifiers, allowed node/output types, citations, and required review fields, then emits CSV. It does not parse or execute the logic statement.
+
+## Change Control
+
+For any change:
+
+1. state the reason;
+2. link new evidence or requirement;
+3. identify affected nodes and downstream artifacts;
+4. update tests;
+5. independently validate;
+6. record approval;
+7. define rollout/rollback when applicable;
+8. retain the previous version;
+9. update monitoring;
+10. retire superseded logic explicitly.
+
+## Script
+
+```bash
+python3 scripts/decision_logic_traceability.py \
+ assets/decision_logic_traceability_template.json
+```
+
+The output is a documentation matrix, not executable clinical logic.
diff --git a/skills/clinical-decision-support/references/evidence_profiles.md b/skills/clinical-decision-support/references/evidence_profiles.md
new file mode 100644
index 00000000..e4e437e7
--- /dev/null
+++ b/skills/clinical-decision-support/references/evidence_profiles.md
@@ -0,0 +1,153 @@
+# GRADE Evidence Profiles
+
+## Purpose
+
+An evidence profile transparently records a human panel's judgments about a body of evidence for each important outcome. It is not an article-scoring shortcut and does not produce a patient-care recommendation.
+
+Use the current [GRADE Book](https://book.gradepro.org/) and the [GRADE Working Group](https://www.gradeworkinggroup.org/) as the controlling methodology. The GRADE Book is replacing the older handbook with progressively updated content.
+
+## Non-Automation Rule
+
+Never:
+
+- infer certainty from keywords, abstracts, p-values, journal name, or study design alone;
+- count checklist items to calculate certainty;
+- treat one study's risk-of-bias judgment as certainty in a body of evidence;
+- equate certainty with recommendation strength;
+- assign recommendation strength without an Evidence-to-Decision process and a responsible panel;
+- invent source citations or downgrade/upgrade rationales.
+
+The bundled checker verifies structure, allowed labels, human attribution, rationale, and source linkage. It does not alter or endorse a judgment.
+
+## Unit of Assessment
+
+Rate certainty separately for every critical or important outcome. Include desirable and undesirable effects. Different outcomes may have different:
+
+- bodies of evidence;
+- risk-of-bias concerns;
+- directness;
+- precision;
+- reporting bias;
+- certainty.
+
+Do not collapse all outcomes into a single study-level grade.
+
+## Required Profile Fields
+
+### Question
+
+- Population
+- Intervention/exposure/index approach
+- Comparator/reference
+- Outcomes and time horizons
+- Setting and decision context
+
+### Sources
+
+For every source include:
+
+- stable source ID;
+- full citation;
+- URL or DOI;
+- publication type;
+- version/date;
+- access date when content is living.
+
+### Effect
+
+For each outcome record:
+
+- measure and direction;
+- absolute and relative effects when appropriate;
+- confidence or credible interval;
+- participants and studies;
+- follow-up/horizon;
+- missingness;
+- whether the estimate is adjusted;
+- applicability limits.
+
+Do not convert an effect into a clinical instruction.
+
+## Certainty Domains
+
+Every domain entry requires a judgment, rationale, source IDs, and human reviewer role.
+
+### Risk of Bias
+
+Use a design-appropriate tool. Describe how limitations could change the estimated effect. Do not use a numeric quality score as a substitute.
+
+### Inconsistency
+
+Examine the direction and magnitude of effects, interval overlap, heterogeneity, and plausible explanations. A statistical heterogeneity value alone is not the judgment.
+
+### Indirectness
+
+Compare population, intervention/exposure, comparator, outcome, time horizon, setting, and evidence pathway with the framed question.
+
+### Imprecision
+
+Use decision-relevant thresholds and the range of effects compatible with the interval. Do not apply unsupported universal event-count rules.
+
+### Publication Bias
+
+Consider missing studies/results, selective reporting, small-study effects, sponsorship patterns, registrations, protocols, and reporting availability.
+
+### Upgrading Considerations
+
+When the selected GRADE approach permits, a panel may consider large effects, dose-response gradients, or plausible residual confounding. Each requires explicit methodology, rationale, and citations. “Statistically significant” is not an upgrading reason.
+
+## Final Certainty
+
+Allowed labels:
+
+- high;
+- moderate;
+- low;
+- very low.
+
+Record:
+
+- the final human judgment;
+- who made it and in what role;
+- date;
+- domain-to-final-rating rationale;
+- dissent or unresolved issues;
+- source IDs.
+
+The label describes confidence in an estimate for an outcome in a defined context. It is not a recommendation and does not imply safety, effectiveness, or authorization.
+
+## Evidence to Decision
+
+Recommendation development is outside the automated helper. A qualified panel using an applicable GRADE Evidence-to-Decision framework must explicitly consider, as relevant:
+
+- priority of the problem;
+- desirable and undesirable effects;
+- certainty of evidence;
+- values and variability;
+- resources and cost effectiveness;
+- equity;
+- acceptability;
+- feasibility.
+
+Keep the evidence profile and any later recommendation record separate and traceable.
+
+## Quality-Control Checklist
+
+- [ ] Search and selection methods are documented.
+- [ ] Outcome definitions and horizons match the question.
+- [ ] All important benefits and harms are represented.
+- [ ] Effect estimates include uncertainty.
+- [ ] Each domain has a human judgment and rationale.
+- [ ] Every rationale links to source IDs.
+- [ ] The final certainty is outcome-specific.
+- [ ] Conflicts of interest and panel roles are recorded.
+- [ ] Disagreements and updates are versioned.
+- [ ] No patient-specific or treatment directive appears.
+
+## Helper
+
+```bash
+python3 scripts/evidence_profile_check.py assets/evidence_profile_template.json
+```
+
+The distributed template intentionally contains unresolved judgments. A non-zero result is expected until qualified humans complete it.
diff --git a/skills/clinical-decision-support/references/evidence_synthesis.md b/skills/clinical-decision-support/references/evidence_synthesis.md
deleted file mode 100644
index 6d42d0d8..00000000
--- a/skills/clinical-decision-support/references/evidence_synthesis.md
+++ /dev/null
@@ -1,840 +0,0 @@
-# Evidence Synthesis and Guideline Integration Guide
-
-## Overview
-
-Evidence synthesis involves systematically reviewing, analyzing, and integrating research findings to inform clinical recommendations. This guide covers guideline sources, evidence hierarchies, systematic reviews, meta-analyses, and integration of multiple evidence streams for clinical decision support.
-
-## Major Clinical Practice Guidelines
-
-### Oncology Guidelines
-
-**NCCN (National Comprehensive Cancer Network)**
-- **Scope**: 60+ cancer types, supportive care guidelines
-- **Update Frequency**: Continuous (online), 1-3 updates per year per guideline
-- **Evidence Categories**:
- - **Category 1**: High-level evidence, uniform NCCN consensus
- - **Category 2A**: Lower-level evidence, uniform consensus (appropriate)
- - **Category 2B**: Lower-level evidence, non-uniform consensus (appropriate)
- - **Category 3**: Major disagreement or insufficient evidence
-- **Access**: Free for patients, subscription for providers (institutional access common)
-- **Application**: US-focused, most widely used in clinical practice
-
-**ASCO (American Society of Clinical Oncology)**
-- **Scope**: Evidence-based clinical practice guidelines
-- **Methodology**: Systematic review, GRADE-style evidence tables
-- **Endorsements**: Often endorses NCCN, ESMO, or other guidelines
-- **Focused Topics**: Specific clinical questions (e.g., biomarker testing, supportive care)
-- **Guideline Products**: Full guidelines, rapid recommendations, endorsements
-- **Quality**: Rigorous methodology, peer-reviewed publication
-
-**ESMO (European Society for Medical Oncology)**
-- **Scope**: European guidelines for cancer management
-- **Evidence Levels**:
- - **I**: Evidence from at least one large RCT or meta-analysis
- - **II**: Evidence from at least one well-designed non-randomized trial, cohort study
- - **III**: Evidence from well-designed non-experimental study
- - **IV**: Evidence from expert committee reports or opinions
- - **V**: Evidence from case series, case reports
-- **Recommendation Grades**:
- - **A**: Strong evidence for efficacy, substantial clinical benefit (strongly recommended)
- - **B**: Strong or moderate evidence, limited clinical benefit (generally recommended)
- - **C**: Insufficient evidence, benefit not sufficiently well established
- - **D**: Moderate evidence against efficacy or for adverse effects (not recommended)
- - **E**: Strong evidence against efficacy (never recommended)
-- **ESMO-MCBS**: Magnitude of Clinical Benefit Scale (grades 1-5 for meaningful benefit)
-
-### Cardiovascular Guidelines
-
-**AHA/ACC (American Heart Association / American College of Cardiology)**
-- **Scope**: Cardiovascular disease prevention, diagnosis, management
-- **Class of Recommendation (COR)**:
- - **Class I**: Strong recommendation - should be performed/administered
- - **Class IIa**: Moderate recommendation - is reasonable
- - **Class IIb**: Weak recommendation - may be considered
- - **Class III - No Benefit**: Not recommended
- - **Class III - Harm**: Potentially harmful
-- **Level of Evidence (LOE)**:
- - **A**: High-quality evidence from >1 RCT, meta-analyses
- - **B-R**: Moderate-quality evidence from ≥1 RCT
- - **B-NR**: Moderate-quality evidence from non-randomized studies
- - **C-LD**: Limited data from observational studies, registries
- - **C-EO**: Expert opinion based on clinical experience
-- **Example**: "Statin therapy is recommended for adults with LDL-C ≥190 mg/dL (Class I, LOE A)"
-
-**ESC (European Society of Cardiology)**
-- **Scope**: European cardiovascular guidelines
-- **Class of Recommendation**:
- - **I**: Recommended or indicated
- - **II**: Should be considered
- - **III**: Not recommended
-- **Level of Evidence**: A (RCTs), B (single RCT or observational), C (expert opinion)
-
-### Other Specialties
-
-**IDSA (Infectious Diseases Society of America)**
-- Antimicrobial guidelines, infection management
-- GRADE methodology
-- Strong vs weak recommendations
-
-**ATS/ERS (American Thoracic Society / European Respiratory Society)**
-- Respiratory disease management
-- GRADE methodology
-
-**ACR (American College of Rheumatology)**
-- Rheumatic disease guidelines
-- Conditionally recommended vs strongly recommended
-
-**KDIGO (Kidney Disease: Improving Global Outcomes)**
-- Chronic kidney disease, dialysis, transplant
-- GRADE-based recommendations
-
-## GRADE Methodology
-
-### Assessing Quality of Evidence
-
-**Initial Quality Assignment**
-
-**Randomized Controlled Trials**: Start at HIGH quality (⊕⊕⊕⊕)
-
-**Observational Studies**: Start at LOW quality (⊕⊕○○)
-
-### Factors Decreasing Quality (Downgrade)
-
-**Risk of Bias** (-1 or -2 levels)
-- Lack of allocation concealment
-- Lack of blinding
-- Incomplete outcome data
-- Selective outcome reporting
-- Other sources of bias
-
-**Inconsistency** (-1 or -2 levels)
-- Unexplained heterogeneity in results across studies
-- Wide variation in effect estimates
-- Non-overlapping confidence intervals
-- High I² statistic in meta-analysis (>50-75%)
-
-**Indirectness** (-1 or -2 levels)
-- Different population than target (younger patients in trials, applying to elderly)
-- Different intervention (higher dose in trial than used in practice)
-- Different comparator (placebo in trial, comparing to active treatment)
-- Surrogate outcomes (PFS) when interested in survival (OS)
-
-**Imprecision** (-1 or -2 levels)
-- Wide confidence intervals crossing threshold of benefit/harm
-- Small sample size, few events
-- Optimal information size (OIS) not met
-- Rule of thumb: <300 events for continuous outcomes, <200 events for dichotomous
-
-**Publication Bias** (-1 level)
-- Funnel plot asymmetry (if ≥10 studies)
-- Known unpublished studies with negative results
-- Selective outcome reporting
-- Industry-sponsored studies only
-
-### Factors Increasing Quality (Upgrade - Observational Only)
-
-**Large Magnitude of Effect** (+1 or +2 levels)
-- +1: RR >2 or <0.5 (moderate effect)
-- +2: RR >5 or <0.2 (large effect)
-- No plausible confounders would reduce effect
-
-**Dose-Response Gradient** (+1 level)
-- Clear dose-response or duration-response relationship
-- Strengthens causal inference
-
-**All Plausible Confounders Would Reduce Effect** (+1 level)
-- Observed effect despite confounders biasing toward null
-- Rare, requires careful justification
-
-### Final Quality Rating
-
-After adjustments, assign final quality:
-- **High (⊕⊕⊕⊕)**: Very confident in effect estimate
-- **Moderate (⊕⊕⊕○)**: Moderately confident; true effect likely close to estimate
-- **Low (⊕⊕○○)**: Limited confidence; true effect may be substantially different
-- **Very Low (⊕○○○)**: Very little confidence; true effect likely substantially different
-
-## Systematic Reviews and Meta-Analyses
-
-### PRISMA (Preferred Reporting Items for Systematic Reviews and Meta-Analyses)
-
-**Search Strategy**
-- **Databases**: PubMed/MEDLINE, Embase, Cochrane Library, Web of Science
-- **Search Terms**: PICO (Population, Intervention, Comparator, Outcome)
-- **Date Range**: Typically last 10-20 years or comprehensive
-- **Language**: English only or all languages with translation
-- **Grey Literature**: Conference abstracts, trial registries, unpublished data
-
-**Study Selection**
-```
-PRISMA Flow Diagram:
-
-Records identified through database searching (n=2,450)
-Additional records through other sources (n=15)
- ↓
-Records after duplicates removed (n=1,823)
- ↓
-Records screened (title/abstract) (n=1,823) → Excluded (n=1,652)
- ↓ - Not relevant topic (n=1,120)
-Full-text articles assessed (n=171) - Animal studies (n=332)
- ↓ - Reviews (n=200)
-Studies included in qualitative synthesis (n=38) → Excluded (n=133)
- ↓ - Wrong population (n=42)
-Studies included in meta-analysis (n=24) - Wrong intervention (n=35)
- - No outcomes reported (n=28)
- - Duplicate data (n=18)
- - Poor quality (n=10)
-```
-
-**Data Extraction**
-- Study characteristics: Design, sample size, population, intervention
-- Results: Outcomes, effect sizes, confidence intervals, p-values
-- Quality assessment: Risk of bias tool (Cochrane RoB 2.0 for RCTs)
-- Dual extraction: Two reviewers independently, resolve disagreements
-
-### Meta-Analysis Methods
-
-**Fixed-Effect Model**
-- **Assumption**: Single true effect size shared by all studies
-- **Weighting**: By inverse variance (larger studies have more weight)
-- **Application**: When heterogeneity is low (I² <25%)
-- **Interpretation**: Estimate of common effect across studies
-
-**Random-Effects Model**
-- **Assumption**: True effect varies across studies (distribution of effects)
-- **Weighting**: By inverse variance + between-study variance
-- **Application**: When heterogeneity moderate to high (I² ≥25%)
-- **Interpretation**: Estimate of average effect (center of distribution)
-- **Wider CI**: Accounts for heterogeneity, more conservative
-
-**Heterogeneity Assessment**
-
-**I² Statistic**
-- Percentage of variability due to heterogeneity rather than chance
-- I² = 0-25%: Low heterogeneity
-- I² = 25-50%: Moderate heterogeneity
-- I² = 50-75%: Substantial heterogeneity
-- I² = 75-100%: Considerable heterogeneity
-
-**Q Test (Cochran's Q)**
-- Test for heterogeneity
-- p<0.10 suggests significant heterogeneity (liberal threshold)
-- Low power when few studies, use I² as primary measure
-
-**Tau² (τ²)**
-- Estimate of between-study variance
-- Used in random-effects weighting
-
-**Subgroup Analysis**
-- Explore sources of heterogeneity
-- Pre-specified subgroups: Disease stage, biomarker status, treatment regimen
-- Test for interaction between subgroups
-
-**Forest Plot Interpretation**
-```
-Study n HR (95% CI) Weight
-─────────────────────────────────────────────────────────────
-Trial A 2018 450 0.62 (0.45-0.85) ●───┤ 28%
-Trial B 2019 320 0.71 (0.49-1.02) ●────┤ 22%
-Trial C 2020 580 0.55 (0.41-0.74) ●──┤ 32%
-Trial D 2021 210 0.88 (0.56-1.38) ●──────┤ 18%
-
-Overall (RE model) 1560 0.65 (0.53-0.80) ◆──┤
-Heterogeneity: I²=42%, p=0.16
-
- 0.25 0.5 1.0 2.0 4.0
- Favors Treatment Favors Control
-```
-
-## Guideline Integration
-
-### Concordance Checking
-
-**Multi-Guideline Comparison**
-```
-Recommendation: First-line treatment for advanced NSCLC, PD-L1 ≥50%
-
-Guideline Version Recommendation Strength
-─────────────────────────────────────────────────────────────────────────────
-NCCN v4.2024 Pembrolizumab monotherapy (preferred) Category 1
-ESMO 2023 Pembrolizumab monotherapy (preferred) I, A
-ASCO 2022 Endorses NCCN guidelines Strong
-NICE (UK) 2023 Pembrolizumab approved Recommended
-
-Synthesis: Strong consensus across guidelines for pembrolizumab monotherapy.
-Alternative: Pembrolizumab + chemotherapy also Category 1/I-A recommended.
-```
-
-**Discordance Resolution**
-- Identify differences and reasons (geography, cost, access, evidence interpretation)
-- Note date of each guideline (newer may incorporate recent trials)
-- Consider regional applicability
-- Favor guidelines with most rigorous methodology (GRADE-based)
-
-### Regulatory Approval Landscape
-
-**FDA Approvals**
-- Track indication-specific approvals
-- Accelerated approval vs full approval
-- Post-marketing requirements
-- Contraindications and warnings
-
-**EMA (European Medicines Agency)**
-- May differ from FDA in approved indications
-- Conditional marketing authorization
-- Additional monitoring (black triangle)
-
-**Regional Variations**
-- Health Technology Assessment (HTA) agencies
-- NICE (UK): Cost-effectiveness analysis, QALY thresholds
-- CADTH (Canada): Therapeutic review and recommendations
-- PBAC (Australia): Reimbursement decisions
-
-## Real-World Evidence (RWE)
-
-### Sources of RWE
-
-**Electronic Health Records (EHR)**
-- Clinical data from routine practice
-- Large patient numbers
-- Heterogeneous populations (more generalizable than RCTs)
-- Limitations: Missing data, inconsistent documentation, selection bias
-
-**Claims Databases**
-- Administrative claims for billing/reimbursement
-- Large scale (millions of patients)
-- Outcomes: Mortality, hospitalizations, procedures
-- Limitations: Lack clinical detail (labs, imaging, biomarkers)
-
-**Cancer Registries**
-- **SEER (Surveillance, Epidemiology, and End Results)**: US cancer registry
-- **NCDB (National Cancer Database)**: Hospital registry data
-- Population-level survival, treatment patterns
-- Limited treatment detail, no toxicity data
-
-**Prospective Cohorts**
-- Framingham Heart Study, Nurses' Health Study
-- Long-term follow-up, rich covariate data
-- Expensive, time-consuming
-
-### RWE Applications
-
-**Comparative Effectiveness**
-- Compare treatments in real-world settings (less strict eligibility than RCTs)
-- Complement RCT data with broader populations
-- Example: Effectiveness of immunotherapy in elderly, poor PS patients excluded from trials
-
-**Safety Signal Detection**
-- Rare adverse events not detected in trials
-- Long-term toxicities
-- Drug-drug interactions in polypharmacy
-- Postmarketing surveillance
-
-**Treatment Patterns and Access**
-- Guideline adherence in community practice
-- Time to treatment initiation
-- Disparities in care delivery
-- Off-label use prevalence
-
-**Limitations of RWE**
-- **Confounding by indication**: Sicker patients receive more aggressive treatment
-- **Immortal time bias**: Time between events affecting survival estimates
-- **Missing data**: Incomplete or inconsistent data collection
-- **Causality**: Association does not prove causation without randomization
-
-**Strengthening RWE**
-- **Propensity score matching**: Balance baseline characteristics between groups
-- **Multivariable adjustment**: Adjust for measured confounders in Cox model
-- **Sensitivity analyses**: Test robustness to unmeasured confounding
-- **Instrumental variables**: Use natural experiments to approximate randomization
-
-## Meta-Analysis Techniques
-
-### Binary Outcomes (Response Rate, Event Rate)
-
-**Effect Measures**
-- **Risk Ratio (RR)**: Ratio of event probabilities
-- **Odds Ratio (OR)**: Ratio of odds (less intuitive)
-- **Risk Difference (RD)**: Absolute difference in event rates
-
-**Example Calculation**
-```
-Study 1:
-- Treatment A: 30/100 responded (30%)
-- Treatment B: 15/100 responded (15%)
-- RR = 0.30/0.15 = 2.0 (95% CI 1.15-3.48)
-- RD = 0.30 - 0.15 = 0.15 or 15% (95% CI 4.2%-25.8%)
-- NNT = 1/RD = 1/0.15 = 6.7 (treat 7 patients to get 1 additional response)
-```
-
-**Pooling Methods**
-- **Mantel-Haenszel**: Common fixed-effect method
-- **DerSimonian-Laird**: Random-effects method
-- **Peto**: For rare events (event rate <1%)
-
-### Time-to-Event Outcomes (Survival, PFS)
-
-**Hazard Ratio Pooling**
-- Extract HR and 95% CI (or log(HR) and SE) from each study
-- Weight by inverse variance
-- Pool using generic inverse variance method
-- Report pooled HR with 95% CI, heterogeneity statistics
-
-**When HR Not Reported**
-- Extract from Kaplan-Meier curves (Parmar method, digitizing software)
-- Calculate from log-rank p-value and event counts
-- Request from study authors
-
-### Continuous Outcomes (Quality of Life, Lab Values)
-
-**Standardized Mean Difference (SMD)**
-- Application: Different scales used across studies
-- SMD = (Mean₁ - Mean₂) / Pooled SD
-- Interpretation: Cohen's d effect size (0.2 small, 0.5 medium, 0.8 large)
-
-**Mean Difference (MD)**
-- Application: Same scale/unit used across studies
-- MD = Mean₁ - Mean₂
-- More directly interpretable than SMD
-
-## Network Meta-Analysis
-
-### Purpose
-
-Compare multiple treatments simultaneously when no head-to-head trials exist
-
-**Example Scenario**
-- Drug A vs placebo (Trial 1)
-- Drug B vs placebo (Trial 2)
-- Drug C vs Drug A (Trial 3)
-- **Question**: How does Drug B compare to Drug C? (no direct comparison)
-
-### Methods
-
-**Fixed-Effect Network Meta-Analysis**
-- Assumes consistency (transitivity): A vs B effect = (A vs C effect) - (B vs C effect)
-- Provides indirect comparison estimates
-- Ranks treatments by P-score or SUCRA
-
-**Random-Effects Network Meta-Analysis**
-- Allows heterogeneity between studies
-- More conservative estimates
-
-**Consistency Checking**
-- Compare direct vs indirect evidence for same comparison
-- Node-splitting analysis
-- Loop consistency (if closed loops in network)
-
-### Interpretation Cautions
-
-- **Transitivity assumption**: May not hold if studies differ in important ways
-- **Indirect evidence**: Less reliable than direct head-to-head trials
-- **Rankings**: Probabilistic, not definitive ordering
-- **Clinical judgment**: Consider beyond statistical rankings
-
-## Evidence Tables
-
-### Constructing Evidence Summary Tables
-
-**PICO Framework**
-- **P (Population)**: Patient characteristics, disease stage, biomarker status
-- **I (Intervention)**: Treatment regimen, dose, schedule
-- **C (Comparator)**: Control arm (placebo, standard of care)
-- **O (Outcomes)**: Primary and secondary endpoints
-
-**Evidence Table Template**
-```
-Study Design n Population Intervention vs Comparator Outcome Result Quality
-────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
-Smith 2020 RCT 450 Advanced NSCLC Drug A 10mg vs Median PFS 12 vs 6 months High
- EGFR+ standard chemo (95% CI) (10-14 vs 5-7) ⊕⊕⊕⊕
- HR (95% CI) 0.48 (0.36-0.64)
- p-value p<0.001
-
- ORR 65% vs 35%
- Grade 3-4 AEs 42% vs 38%
-
-Jones 2021 RCT 380 Advanced NSCLC Drug A 10mg vs Median PFS 10 vs 5.5 months High
- EGFR+ placebo HR (95% CI) 0.42 (0.30-0.58) ⊕⊕⊕⊕
- p-value p<0.001
-
-Pooled Effect Pooled HR 0.45 (0.36-0.57) High
-(Meta-analysis) I² 12% (low heterogeneity) ⊕⊕⊕⊕
-```
-
-### Evidence to Decision Framework
-
-**Benefits and Harms**
-- Magnitude of desirable effects (ORR, PFS, OS improvement)
-- Magnitude of undesirable effects (toxicity, quality of life impact)
-- Balance of benefits and harms
-- Net benefit calculation
-
-**Values and Preferences**
-- How do patients value outcomes? (survival vs quality of life)
-- Variability in patient values
-- Shared decision-making importance
-
-**Resource Considerations**
-- Cost of intervention
-- Cost-effectiveness ($/QALY)
-- Budget impact
-- Equity and access
-
-**Feasibility and Acceptability**
-- Is treatment available in practice settings?
-- Route of administration feasible? (oral vs IV vs subcutaneous)
-- Monitoring requirements realistic?
-- Patient and provider acceptability
-
-## Guideline Concordance Documentation
-
-### Synthesizing Multiple Guidelines
-
-**Concordant Recommendations**
-```
-Clinical Question: Treatment for HER2+ metastatic breast cancer, first-line
-
-Guideline Summary:
-━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-NCCN v3.2024 (Category 1):
- Preferred: Pertuzumab + trastuzumab + taxane
- Alternative: T-DM1, other HER2-targeted combinations
-
-ESMO 2022 (Grade I, A):
- Preferred: Pertuzumab + trastuzumab + docetaxel
- Alternative: Trastuzumab + chemotherapy (if pertuzumab unavailable)
-
-ASCO 2020 Endorsement:
- Endorses NCCN guidelines, recommends pertuzumab-based first-line
-
-Synthesis:
- Strong consensus for pertuzumab + trastuzumab + taxane as first-line standard.
- Evidence: CLEOPATRA trial (Swain 2015): median OS 56.5 vs 40.8 months (HR 0.68, p<0.001)
-
-Recommendation:
- Pertuzumab 840 mg IV loading then 420 mg + trastuzumab 8 mg/kg loading then 6 mg/kg
- + docetaxel 75 mg/m² every 3 weeks until progression.
-
- Strength: Strong (GRADE 1A)
- Evidence: High-quality, multiple RCTs, guideline concordance
-```
-
-**Discordant Recommendations**
-```
-Clinical Question: Adjuvant osimertinib for resected EGFR+ NSCLC
-
-NCCN v4.2024 (Category 1):
- Osimertinib 80 mg daily × 3 years after adjuvant chemotherapy
- Evidence: ADAURA trial (median DFS not reached vs 28 months, HR 0.17)
-
-ESMO 2023 (II, B):
- Osimertinib may be considered
- Note: Cost-effectiveness concerns, OS data immature
-
-NICE (UK) 2022:
- Not recommended for routine use
- Reason: QALY analysis unfavorable at current pricing
-
-Synthesis:
- Efficacy demonstrated in phase 3 trial (ADAURA), FDA/EMA approved.
- Guideline discordance based on cost-effectiveness, not clinical efficacy.
-
- US practice: NCCN Category 1, widely adopted
- European/UK: Variable adoption based on national HTA decisions
-
-Recommendation Context-Dependent:
- US: Strong recommendation if accessible (GRADE 1B)
- Countries with cost constraints: Conditional recommendation (GRADE 2B)
-```
-
-## Quality Assessment Tools
-
-### RCT Quality Assessment (Cochrane Risk of Bias 2.0)
-
-**Domains**
-1. **Bias from randomization process**: Sequence generation, allocation concealment
-2. **Bias from deviations from intended interventions**: Blinding, protocol adherence
-3. **Bias from missing outcome data**: Attrition, intention-to-treat analysis
-4. **Bias in outcome measurement**: Blinded assessment, objective outcomes
-5. **Bias in selection of reported result**: Selective reporting, outcome switching
-
-**Judgment**: Low risk, some concerns, high risk (for each domain)
-
-**Overall Risk of Bias**: Based on highest-risk domain
-
-### Observational Study Quality (Newcastle-Ottawa Scale)
-
-**Selection (max 4 stars)**
-- Representativeness of exposed cohort
-- Selection of non-exposed cohort
-- Ascertainment of exposure
-- Outcome not present at start
-
-**Comparability (max 2 stars)**
-- Comparability of cohorts (design/analysis adjustment for confounders)
-
-**Outcome (max 3 stars)**
-- Assessment of outcome
-- Follow-up duration adequate
-- Adequacy of follow-up (low attrition)
-
-**Total Score**: 0-9 stars
-- **High quality**: 7-9 stars
-- **Moderate quality**: 4-6 stars
-- **Low quality**: 0-3 stars
-
-## Translating Evidence to Recommendations
-
-### Recommendation Development Process
-
-**Step 1: PICO Question Formulation**
-```
-Example PICO:
-P - Population: Adults with type 2 diabetes and cardiovascular disease
-I - Intervention: SGLT2 inhibitor (empagliflozin)
-C - Comparator: Placebo (added to standard care)
-O - Outcomes: Major adverse cardiovascular events (3P-MACE), hospitalization for heart failure
-```
-
-**Step 2: Systematic Evidence Review**
-- Identify all relevant studies
-- Assess quality using standardized tools
-- Extract outcome data
-- Synthesize findings (narrative or meta-analysis)
-
-**Step 3: GRADE Evidence Rating**
-- Start at high (RCTs) or low (observational)
-- Downgrade for risk of bias, inconsistency, indirectness, imprecision, publication bias
-- Upgrade for large effect, dose-response, confounders reducing effect (observational only)
-- Assign final quality rating
-
-**Step 4: Recommendation Strength Determination**
-
-**Strong Recommendation (Grade 1)**
-- Desirable effects clearly outweigh undesirable effects
-- High or moderate quality evidence
-- Little variability in patient values
-- Intervention cost-effective
-
-**Conditional Recommendation (Grade 2)**
-- Trade-offs: Desirable and undesirable effects closely balanced
-- Low or very low quality evidence
-- Substantial variability in patient values/preferences
-- Uncertain cost-effectiveness
-
-**Step 5: Wording the Recommendation**
-```
-Strong: "We recommend..."
- Example: "We recommend SGLT2 inhibitor therapy for adults with type 2 diabetes and
- established cardiovascular disease to reduce risk of hospitalization for heart failure
- and cardiovascular death (Strong recommendation, high-quality evidence - GRADE 1A)."
-
-Conditional: "We suggest..."
- Example: "We suggest considering GLP-1 receptor agonist therapy for adults with type 2
- diabetes and CKD to reduce risk of kidney disease progression (Conditional recommendation,
- moderate-quality evidence - GRADE 2B)."
-```
-
-## Incorporating Emerging Evidence
-
-### Early-Phase Trial Data
-
-**Phase 1 Trials**
-- Purpose: Dose-finding, safety
-- Outcomes: Maximum tolerated dose (MTD), dose-limiting toxicities (DLTs), pharmacokinetics
-- Evidence level: Very low (expert opinion, case series)
-- Clinical application: Investigational only, clinical trial enrollment
-
-**Phase 2 Trials**
-- Purpose: Preliminary efficacy signal
-- Design: Single-arm (ORR primary endpoint) or randomized (PFS comparison)
-- Evidence level: Low to moderate
-- Clinical application: May support off-label use in refractory settings, clinical trial enrollment preferred
-
-**Phase 3 Trials**
-- Purpose: Confirmatory efficacy and safety
-- Design: Randomized controlled trial, OS or PFS primary endpoint
-- Evidence level: High (if well-designed and executed)
-- Clinical application: Regulatory approval basis, guideline recommendations
-
-**Phase 4 Trials**
-- Purpose: Post-marketing surveillance, additional indications
-- Evidence level: Variable (depends on design)
-- Clinical application: Safety monitoring, expanded usage
-
-### Breakthrough Therapy Designation
-
-**FDA Fast-Track Programs**
-- **Breakthrough Therapy**: Preliminary evidence of substantial improvement over existing therapy
-- **Accelerated Approval**: Approval based on surrogate endpoint (PFS, ORR)
- - Post-marketing requirement: Confirmatory OS trial
-- **Priority Review**: Shortened FDA review time (6 vs 10 months)
-
-**Implications for Guidelines**
-- May receive NCCN Category 2A before phase 3 data mature
-- Upgrade to Category 1 when confirmatory data published
-- Monitor for post-market confirmatory trial results
-
-### Updating Recommendations
-
-**Triggers for Update**
-- New phase 3 trial results (major journal publication)
-- FDA/EMA approval for new indication or agent
-- Guideline update from NCCN, ASCO, ESMO
-- Safety alert or drug withdrawal
-- Meta-analysis changing effect estimates
-
-**Rapid Update Process**
-- Critical appraisal of new evidence
-- Assess impact on current recommendations
-- Revise evidence grade and recommendation strength if needed
-- Disseminate update to users
-- Version control and change log
-
-## Conflicts of Interest and Bias
-
-### Identifying Potential Bias
-
-**Study Sponsorship**
-- **Industry-sponsored**: May favor sponsor's product (publication bias, outcome selection)
-- **Academic**: May favor investigator's hypothesis
-- **Independent**: Government funding (NIH, PCORI)
-
-**Author Conflicts of Interest**
-- Consulting fees, research funding, stock ownership
-- Disclosure statements required by journals
-- ICMJE Form for Disclosure of Potential COI
-
-**Mitigating Bias**
-- Register trials prospectively (ClinicalTrials.gov)
-- Pre-specify primary endpoint and analysis plan
-- Independent data monitoring committee (IDMC)
-- Blinding of outcome assessors
-- Intention-to-treat analysis
-
-### Transparency in Evidence Synthesis
-
-**Pre-Registration**
-- PROSPERO for systematic reviews
-- Pre-specify PICO, search strategy, outcomes, analysis plan
-- Prevents post-hoc changes to avoid negative findings
-
-**Reporting Checklists**
-- PRISMA for systematic reviews/meta-analyses
-- CONSORT for RCTs
-- STROBE for observational studies
-
-**Data Availability**
-- Individual patient data (IPD) sharing increases transparency
-- Repositories: ClinicalTrials.gov results database, journal supplements
-
-## Practical Application
-
-### Evidence Summary for Clinical Document
-
-```
-EVIDENCE SYNTHESIS: Osimertinib for EGFR-Mutated NSCLC
-
-Clinical Question:
-Should adults with treatment-naïve advanced NSCLC harboring EGFR exon 19 deletion
-or L858R mutation receive osimertinib versus first-generation EGFR TKIs?
-
-Evidence Review:
-┌──────────────────────────────────────────────────────────────────────┐
-│ FLAURA Trial (Soria et al., NEJM 2018) │
-├──────────────────────────────────────────────────────────────────────┤
-│ Design: Phase 3 RCT, double-blind, 1:1 randomization │
-│ Population: EGFR exon 19 del or L858R, stage IIIB/IV, ECOG 0-1 │
-│ Sample Size: n=556 (279 osimertinib, 277 comparator) │
-│ Intervention: Osimertinib 80 mg PO daily │
-│ Comparator: Gefitinib 250 mg or erlotinib 150 mg PO daily │
-│ Primary Endpoint: PFS by investigator assessment │
-│ Secondary: OS, ORR, DOR, CNS progression, safety │
-│ │
-│ Results: │
-│ - Median PFS: 18.9 vs 10.2 months (HR 0.46, 95% CI 0.37-0.57, p<0.001)│
-│ - Median OS: 38.6 vs 31.8 months (HR 0.80, 95% CI 0.64-1.00, p=0.046)│
-│ - ORR: 80% vs 76% (p=0.24) │
-│ - Grade ≥3 AEs: 34% vs 45% │
-│ - Quality: High (well-designed RCT, low risk of bias) │
-└──────────────────────────────────────────────────────────────────────┘
-
-Guideline Recommendations:
- NCCN v4.2024: Category 1 preferred
- ESMO 2022: Grade I, A
- ASCO 2022: Endorsed
-
-GRADE Assessment:
- Quality of Evidence: ⊕⊕⊕⊕ HIGH
- - Randomized controlled trial
- - Low risk of bias (allocation concealment, blinding, ITT analysis)
- - Consistent results (single large trial, consistent with phase 2 data)
- - Direct evidence (target population and outcomes)
- - Precise estimate (narrow CI, sufficient events)
- - No publication bias concerns
-
- Balance of Benefits and Harms:
- - Large PFS benefit (8.7 month improvement, HR 0.46)
- - OS benefit (6.8 month improvement, HR 0.80)
- - Similar ORR, improved tolerability (lower grade 3-4 AEs)
- - Desirable effects clearly outweigh undesirable effects
-
- Patient Values: Little variability (most patients value survival extension)
-
- Cost: Higher cost than first-gen TKIs, but widely accessible in developed countries
-
-FINAL RECOMMENDATION:
- Osimertinib 80 mg PO daily is recommended as first-line therapy for adults with
- advanced NSCLC harboring EGFR exon 19 deletion or L858R mutation.
-
- Strength: STRONG (Grade 1)
- Quality of Evidence: HIGH (⊕⊕⊕⊕)
- GRADE: 1A
-```
-
-## Keeping Current
-
-### Literature Surveillance
-
-**Automated Alerts**
-- PubMed My NCBI (save searches, email alerts)
-- Google Scholar alerts for specific topics
-- Journal table of contents alerts (NEJM, Lancet, JCO)
-- Guideline update notifications (NCCN, ASCO, ESMO email lists)
-
-**Conference Monitoring**
-- ASCO Annual Meeting (June)
-- ESMO Congress (September)
-- ASH Annual Meeting (December, hematology)
-- AHA Scientific Sessions (November, cardiology)
-- Plenary and press releases for practice-changing trials
-
-**Trial Results Databases**
-- ClinicalTrials.gov results database
-- FDA approval letters and reviews
-- EMA European public assessment reports (EPARs)
-
-### Critical Appraisal Workflow
-
-**Weekly Review**
-1. Screen new publications (title/abstract)
-2. Full-text review of relevant studies
-3. Quality assessment using checklists
-4. Extract key findings
-5. Assess impact on current recommendations
-
-**Monthly Synthesis**
-1. Review accumulated evidence
-2. Identify practice-changing findings
-3. Update evidence tables
-4. Revise recommendations if warranted
-5. Disseminate updates to clinical teams
-
-**Annual Comprehensive Review**
-1. Systematic review of guideline updates
-2. Re-assess all recommendations
-3. Incorporate year's evidence
-4. Major version release
-5. Continuing education activities
-
diff --git a/skills/clinical-decision-support/references/model_biomarker_evaluation.md b/skills/clinical-decision-support/references/model_biomarker_evaluation.md
new file mode 100644
index 00000000..a7cb276f
--- /dev/null
+++ b/skills/clinical-decision-support/references/model_biomarker_evaluation.md
@@ -0,0 +1,152 @@
+# Aggregate Model and Biomarker Evaluation
+
+## Boundary
+
+Evaluate a locked model, assay, or prespecified biomarker rule using synthetic or aggregate validation summaries. Do not:
+
+- ingest individual records;
+- discover or optimize a threshold;
+- assign a class or risk to a person;
+- match a person to a test or intervention;
+- state clinical validity, utility, safety, or fitness for deployment.
+
+## Define the Target
+
+Record:
+
+- evaluation target and version;
+- biomarker category using FDA-NIH BEST terminology;
+- intended research purpose;
+- target population, setting, prevalence, and outcome horizon;
+- intended user and non-clinical decision role;
+- inputs, output, threshold, and threshold provenance;
+- development, tuning, internal-test, and external-validation datasets;
+- whether evaluation is temporal, geographic, site-based, or population-based.
+
+Do not call a random split from one source “external validation.”
+
+## Analytical and Clinical Questions
+
+Keep separate:
+
+1. **Analytical validation** — measurement accuracy, precision, detection limits, reproducibility, interference, specimen stability.
+2. **Clinical validation** — association or predictive performance for the defined context.
+3. **Clinical utility** — whether use improves meaningful outcomes compared with alternatives.
+
+The bundled evaluator addresses only selected aggregate clinical-validation performance summaries. It cannot establish any of the three.
+
+## Performance Dimensions
+
+### Discrimination
+
+Depending on the target:
+
+- sensitivity and specificity;
+- predictive values, with prevalence/context;
+- likelihood ratios;
+- C statistic/AUC with uncertainty;
+- time-dependent discrimination for censored outcomes.
+
+Do not report accuracy alone when classes are imbalanced.
+
+### Calibration
+
+Calibration asks whether predicted probabilities agree with observed frequencies. Evaluate:
+
+- calibration-in-the-large;
+- calibration slope;
+- calibration plots with uncertainty;
+- observed versus predicted risk across meaningful ranges;
+- integrated or absolute calibration error when justified.
+
+The standard-library helper accepts calibration bins and reports a weighted absolute gap. Binning loses information and does not replace individual-level calibration analysis in an approved environment.
+
+Primary overview: [Van Calster et al., calibration](https://pubmed.ncbi.nlm.nih.gov/31842878).
+
+### Overall Accuracy and Utility
+
+Use proper scoring rules and decision-curve/net-benefit methods only with a prespecified, defensible decision context. Do not imply utility from AUC or accuracy. Utility evaluation that changes care is outside this skill.
+
+### Uncertainty
+
+Report intervals for performance estimates and explain resampling or analytic methods. The helper uses Wilson intervals for aggregate proportions. It does not model correlated observations, clustering, repeated measurements, censoring, or verification bias.
+
+## External Validation
+
+Apply the original locked model without refitting. Document:
+
+- differences in case mix, prevalence, setting, workflow, and measurement;
+- eligibility and missingness;
+- sample-size rationale based on precision targets, not a blanket event rule;
+- calibration, discrimination, and any prespecified utility measure;
+- subgroup performance;
+- model failures and unusable inputs;
+- whether recalibration was separate from validation.
+
+See [BMJ 2024 external-validation guidance](https://www.bmj.com/content/384/bmj-2023-074820) and [sample-size methodology](https://pmc.ncbi.nlm.nih.gov/articles/PMC8352630).
+
+## Subgroup and Fairness Evaluation
+
+Before analysis:
+
+- identify groups based on intended use, evidence, and stakeholder input;
+- document category provenance and limitations;
+- set minimum precision and disclosure rules;
+- plan intersectional analyses where feasible;
+- define metrics and acceptable uncertainty;
+- evaluate measurement and label validity;
+- plan investigation and mitigation, not only detection.
+
+Report:
+
+- representation and missingness;
+- performance and calibration with intervals;
+- data quality and failure rates;
+- distribution shift;
+- human-AI interaction where relevant;
+- observed differences without declaring a group deficient.
+
+No single parity metric establishes fairness. Equal metrics can coexist with inequitable outcomes, and unequal metrics may reflect case mix, measurement, structural conditions, or model behavior that requires investigation.
+
+## Biomarker-Specific Controls
+
+- Pre-specify specimen, assay, platform, software, quality controls, units, and threshold.
+- Preserve continuous information where appropriate.
+- Separate prognostic association from treatment-effect interaction.
+- Blind assay assessment to outcome when feasible.
+- Account for batch/site effects and failed measurements.
+- Validate thresholds independently.
+- Report analytical validity before clinical interpretation.
+- Use REMARK for tumor prognostic markers.
+
+## Change Control and Monitoring
+
+For each release record:
+
+- immutable model/assay version;
+- data and code versions;
+- planned changes and rationale;
+- validation protocol and acceptance criteria;
+- subgroup/calibration regression tests;
+- human-factors impact;
+- approval and rollback;
+- monitoring cadence and drift triggers;
+- incident handling and retirement.
+
+Never update a threshold or model silently after viewing performance.
+
+## Aggregate Evaluator
+
+Input contains only:
+
+- group labels and aggregate denominators;
+- confusion counts;
+- aggregate calibration bins;
+- provenance and validation metadata.
+
+Output contains bounded descriptive metrics, uncertainty, suppression, and documented gaps. It never outputs a person-level class or recommendation.
+
+```bash
+python3 scripts/model_biomarker_evaluation.py \
+ assets/aggregate_model_evaluation_template.json
+```
diff --git a/skills/clinical-decision-support/references/outcome_analysis.md b/skills/clinical-decision-support/references/outcome_analysis.md
deleted file mode 100644
index 21a746b5..00000000
--- a/skills/clinical-decision-support/references/outcome_analysis.md
+++ /dev/null
@@ -1,640 +0,0 @@
-# Outcome Analysis and Statistical Methods Guide
-
-## Overview
-
-Rigorous outcome analysis is essential for clinical decision support documents. This guide covers survival analysis, response assessment, statistical testing, and data visualization for patient cohort analyses and treatment evaluation.
-
-## Survival Analysis
-
-### Kaplan-Meier Method
-
-**Overview**
-- Non-parametric estimator of survival function from time-to-event data
-- Handles censored observations (patients alive at last follow-up)
-- Provides survival probability at each time point
-- Generates characteristic step-function survival curves
-
-**Key Concepts**
-
-**Censoring**
-- **Right censoring**: Most common - patient alive at last follow-up or study end
-- **Left censoring**: Rare in clinical studies
-- **Interval censoring**: Event occurred between two assessment times
-- **Informative vs non-informative**: Censoring should be independent of outcome
-
-**Survival Function S(t)**
-- S(t) = Probability of surviving beyond time t
-- S(0) = 1.0 (100% alive at time zero)
-- S(t) decreases as time increases
-- Step decreases at each event time
-
-**Median Survival**
-- Time point where S(t) = 0.50
-- 50% of patients alive, 50% have had event
-- Reported with 95% confidence interval
-- "Not reached (NR)" if fewer than 50% events
-
-**Survival Rates at Fixed Time Points**
-- 1-year survival rate, 2-year survival rate, 5-year survival rate
-- Read from K-M curve at specific time point
-- Report with 95% CI: S(t) ± 1.96 × SE
-
-**Calculation Example**
-```
-Time Events At Risk Survival Probability
-0 0 100 1.000
-3 2 100 0.980 (98/100)
-5 1 95 0.970 (97/100 × 95/98)
-8 3 87 0.936 (94/100 × 92/95 × 84/87)
-...
-```
-
-### Log-Rank Test
-
-**Purpose**: Compare survival curves between two or more groups
-
-**Null Hypothesis**: No difference in survival distributions between groups
-
-**Test Statistic**
-- Compares observed vs expected events in each group at each time point
-- Weights all time points equally
-- Follows chi-square distribution with df = k-1 (k groups)
-
-**Reporting**
-- Chi-square statistic, degrees of freedom, p-value
-- Example: χ² = 6.82, df = 1, p = 0.009
-- Interpretation: Significant difference in survival curves
-
-**Assumptions**
-- Censoring is non-informative and independent
-- Proportional hazards (constant HR over time)
-- If non-proportional, consider time-varying effects
-
-**Alternatives for Non-Proportional Hazards**
-- **Gehan-Breslow test**: Weights early events more heavily
-- **Peto-Peto test**: Modifies Gehan-Breslow weighting
-- **Restricted mean survival time (RMST)**: Difference in area under K-M curve
-
-### Cox Proportional Hazards Regression
-
-**Purpose**: Multivariable survival analysis, estimate hazard ratios adjusting for covariates
-
-**Model**: h(t|X) = h₀(t) × exp(β₁X₁ + β₂X₂ + ... + βₚXₚ)
-- h(t|X): Hazard rate for individual with covariates X
-- h₀(t): Baseline hazard function (unspecified)
-- exp(β): Hazard ratio for one-unit change in covariate
-
-**Hazard Ratio Interpretation**
-- HR = 1.0: No effect
-- HR > 1.0: Increased risk (harmful)
-- HR < 1.0: Decreased risk (beneficial)
-- HR = 0.50: 50% reduction in hazard (risk of event)
-
-**Example Output**
-```
-Variable HR 95% CI p-value
-Treatment (B vs A) 0.62 0.43-0.89 0.010
-Age (per 10 years) 1.15 1.02-1.30 0.021
-ECOG PS (2 vs 0-1) 1.85 1.21-2.83 0.004
-Biomarker+ (vs -) 0.71 0.48-1.05 0.089
-```
-
-**Proportional Hazards Assumption**
-- Hazard ratio constant over time
-- Test: Schoenfeld residuals, log-minus-log plots
-- Violation: Time-varying effects, consider stratification or time-dependent covariates
-
-**Multivariable vs Univariable**
-- **Univariable**: One covariate at a time, unadjusted HRs
-- **Multivariable**: Multiple covariates simultaneously, adjusted HRs
-- Report both: Univariable for all variables, multivariable for final model
-
-**Model Selection**
-- **Forward selection**: Start with empty model, add significant variables
-- **Backward elimination**: Start with all variables, remove non-significant
-- **Clinical judgment**: Include known prognostic factors regardless of p-value
-- **Parsimony**: Avoid overfitting, rule of thumb 1 variable per 10-15 events
-
-## Response Assessment
-
-### RECIST v1.1 (Response Evaluation Criteria in Solid Tumors)
-
-**Target Lesions**
-- Select up to 5 lesions total (maximum 2 per organ)
-- Measurable: ≥10 mm longest diameter (≥15 mm for lymph nodes short axis)
-- Sum of longest diameters (SLD) at baseline
-
-**Response Categories**
-
-**Complete Response (CR)**
-- Disappearance of all target and non-target lesions
-- Lymph nodes must regress to <10 mm short axis
-- Confirmation required at ≥4 weeks
-
-**Partial Response (PR)**
-- ≥30% decrease in SLD from baseline
-- No new lesions or unequivocal progression of non-target lesions
-- Confirmation required at ≥4 weeks
-
-**Stable Disease (SD)**
-- Neither PR nor PD criteria met
-- Minimum duration typically 6-8 weeks from baseline
-
-**Progressive Disease (PD)**
-- ≥20% increase in SLD AND ≥5 mm absolute increase from smallest SLD (nadir)
-- OR appearance of new lesions
-- OR unequivocal progression of non-target lesions
-
-**Example Calculation**
-```
-Baseline SLD: 80 mm (4 target lesions)
-Week 6 SLD: 52 mm
-
-Percent change: (52 - 80)/80 × 100% = -35%
-Classification: Partial Response (≥30% decrease)
-
-Week 12 SLD: 48 mm (nadir)
-Week 18 SLD: 62 mm
-
-Percent change from nadir: (62 - 48)/48 × 100% = +29%
-Absolute change: 62 - 48 = 14 mm
-Classification: Progressive Disease (>20% AND ≥5 mm increase)
-```
-
-### iRECIST (Immune RECIST)
-
-**Purpose**: Account for atypical response patterns with immunotherapy
-
-**Modifications from RECIST v1.1**
-
-**iUPD (Immune Unconfirmed Progressive Disease)**
-- Initial increase in tumor burden or new lesions
-- Requires confirmation at next assessment (≥4 weeks later)
-- Continue treatment if clinically stable
-
-**iCPD (Immune Confirmed Progressive Disease)**
-- Confirmed progression at repeat imaging
-- Discontinue immunotherapy
-
-**Pseudoprogression**
-- Initial apparent progression followed by response
-- Mechanism: Immune cell infiltration increases tumor size
-- Incidence: 5-10% of patients on immunotherapy
-- Management: Continue treatment if patient clinically stable
-
-**New Lesions**
-- Record size and location but continue treatment
-- Do not automatically classify as PD
-- Confirm progression if new lesions grow or additional new lesions appear
-
-### Other Response Criteria
-
-**Lugano Classification (Lymphoma)**
-- **PET-based**: Deauville 5-point scale
- - Score 1-3: Negative (metabolic CR)
- - Score 4-5: Positive (residual disease)
-- **CT-based**: If PET not available
-- **Bone marrow**: Required for staging in some lymphomas
-
-**RANO (Response Assessment in Neuro-Oncology)**
-- **Glioblastoma-specific**: Accounts for pseudoprogression with radiation/temozolomide
-- **Enhancing disease**: Bidimensional measurements (product of perpendicular diameters)
-- **Non-enhancing disease**: FLAIR changes assessed separately
-- **Corticosteroid dose**: Must document, increase may indicate progression
-
-**mRECIST (Modified RECIST for HCC)**
-- **Viable tumor**: Enhancing portion only (arterial phase enhancement)
-- **Necrosis**: Non-enhancing areas excluded from measurements
-- **Application**: Hepatocellular carcinoma with arterial enhancement
-
-## Outcome Metrics
-
-### Efficacy Endpoints
-
-**Overall Survival (OS)**
-- **Definition**: Time from randomization/treatment start to death from any cause
-- **Advantages**: Objective, not subject to assessment bias, regulatory gold standard
-- **Disadvantages**: Requires long follow-up, affected by subsequent therapies
-- **Censoring**: Last known alive date
-- **Analysis**: Kaplan-Meier, log-rank test, Cox regression
-
-**Progression-Free Survival (PFS)**
-- **Definition**: Time from randomization to progression (RECIST) or death
-- **Advantages**: Earlier readout than OS, direct treatment effect
-- **Disadvantages**: Requires regular imaging, subject to assessment timing
-- **Censoring**: Last tumor assessment without progression
-- **Sensitivity Analysis**: Assess impact of censoring assumptions
-
-**Objective Response Rate (ORR)**
-- **Definition**: Proportion of patients achieving CR or PR (best response)
-- **Denominator**: Evaluable patients (baseline measurable disease)
-- **Reporting**: Percentage with 95% CI (exact binomial method)
-- **Duration**: Time from first response to progression (DOR)
-- **Advantage**: Binary endpoint, no censoring complications
-
-**Disease Control Rate (DCR)**
-- **Definition**: CR + PR + SD (stable disease ≥6-8 weeks)
-- **Less Stringent**: Captures clinical benefit beyond objective response
-- **Reporting**: Percentage with 95% CI
-
-**Duration of Response (DOR)**
-- **Definition**: Time from first CR or PR to progression (among responders only)
-- **Population**: Subset analysis of responders
-- **Analysis**: Kaplan-Meier among responders
-- **Reporting**: Median DOR with 95% CI
-
-**Time to Treatment Failure (TTF)**
-- **Definition**: Time from start to discontinuation for any reason (progression, toxicity, death, patient choice)
-- **Advantage**: Reflects real-world treatment duration
-- **Components**: PFS + toxicity-related discontinuations
-
-### Safety Endpoints
-
-**Adverse Events (CTCAE v5.0)**
-
-**Grading**
-- **Grade 1**: Mild, asymptomatic or mild symptoms, clinical intervention not indicated
-- **Grade 2**: Moderate, minimal/local intervention indicated, age-appropriate ADL limitation
-- **Grade 3**: Severe or medically significant, not immediately life-threatening, hospitalization/prolongation indicated, disabling, self-care ADL limitation
-- **Grade 4**: Life-threatening consequences, urgent intervention indicated
-- **Grade 5**: Death related to adverse event
-
-**Reporting Standards**
-```
-Adverse Event Summary Table:
-
-AE Term (MedDRA) Any Grade, n (%) Grade 3-4, n (%) Grade 5, n (%)
- Trt A Trt B Trt A Trt B Trt A Trt B
-─────────────────────────────────────────────────────────────────────────
-Hematologic
- Anemia 45 (90%) 42 (84%) 8 (16%) 6 (12%) 0 0
- Neutropenia 35 (70%) 38 (76%) 15 (30%) 18 (36%) 0 0
- Thrombocytopenia 28 (56%) 25 (50%) 6 (12%) 4 (8%) 0 0
- Febrile neutropenia 4 (8%) 6 (12%) 4 (8%) 6 (12%) 0 0
-
-Gastrointestinal
- Nausea 42 (84%) 40 (80%) 2 (4%) 1 (2%) 0 0
- Diarrhea 31 (62%) 28 (56%) 5 (10%) 3 (6%) 0 0
- Mucositis 18 (36%) 15 (30%) 3 (6%) 2 (4%) 0 0
-
-Any AE 50 (100%) 50 (100%) 38 (76%) 35 (70%) 1 (2%) 0
-```
-
-**Serious Adverse Events (SAEs)**
-- SAE incidence and type
-- Relationship to treatment (related vs unrelated)
-- Outcome (resolved, ongoing, fatal)
-- Causality assessment (definite, probable, possible, unlikely, unrelated)
-
-**Treatment Modifications**
-- Dose reductions: n (%), reason
-- Dose delays: n (%), duration
-- Discontinuations: n (%), reason (toxicity vs progression vs other)
-- Relative dose intensity: (actual dose delivered / planned dose) × 100%
-
-## Statistical Analysis Methods
-
-### Comparing Continuous Outcomes
-
-**Independent Samples t-test**
-- **Application**: Compare means between two independent groups (normally distributed)
-- **Assumptions**: Normal distribution, equal variances (or use Welch's t-test)
-- **Reporting**: Mean ± SD for each group, mean difference (95% CI), t-statistic, df, p-value
-- **Example**: Mean age 62.3 ± 8.4 vs 58.7 ± 9.1 years, difference 3.6 years (95% CI 0.2-7.0, p=0.038)
-
-**Mann-Whitney U Test (Wilcoxon Rank-Sum)**
-- **Application**: Compare medians between two groups (non-normal distribution)
-- **Non-parametric**: No distributional assumptions
-- **Reporting**: Median [IQR] for each group, median difference, U-statistic, p-value
-- **Example**: Median time to response 6.2 [4.1-8.3] vs 8.5 [5.9-11.2] weeks, p=0.042
-
-**ANOVA (Analysis of Variance)**
-- **Application**: Compare means across three or more groups
-- **Output**: F-statistic, p-value (overall test)
-- **Post-hoc**: If significant, pairwise comparisons with Tukey or Bonferroni correction
-- **Example**: Treatment effect varied by biomarker subgroup (F=4.32, df=2, p=0.016)
-
-### Comparing Categorical Outcomes
-
-**Chi-Square Test for Independence**
-- **Application**: Compare proportions between two or more groups
-- **Assumptions**: Expected count ≥5 in at least 80% of cells
-- **Reporting**: n (%) for each cell, χ², df, p-value
-- **Example**: ORR 45% vs 30%, χ²=6.21, df=1, p=0.013
-
-**Fisher's Exact Test**
-- **Application**: 2×2 tables when expected count <5
-- **Exact p-value**: No large-sample approximation
-- **Two-sided vs one-sided**: Typically report two-sided
-- **Example**: SAE rate 3/20 (15%) vs 8/22 (36%), Fisher's exact p=0.083
-
-**McNemar's Test**
-- **Application**: Paired categorical data (before/after, matched pairs)
-- **Example**: Response before vs after treatment switch in same patients
-
-### Sample Size and Power
-
-**Power Analysis Components**
-- **Alpha (α)**: Type I error rate, typically 0.05 (two-sided)
-- **Beta (β)**: Type II error rate, typically 0.10 or 0.20
-- **Power**: 1 - β, typically 0.80 or 0.90 (80-90% power)
-- **Effect size**: Expected difference (HR, mean difference, proportion difference)
-- **Sample size**: Number of patients or events needed
-
-**Survival Study Sample Size**
-- Events-driven: Need sufficient events (deaths, progressions)
-- Rule of thumb: 80% power requires approximately 165 events for HR=0.70 (α=0.05, two-sided)
-- Accrual time + follow-up time determines calendar time
-
-**Response Rate Study**
-```
-Example: Detect ORR difference 45% vs 30% (15 percentage points)
-- α = 0.05 (two-sided)
-- Power = 0.80
-- Sample size: n = 94 per group (188 total)
-- With 10% dropout: n = 105 per group (210 total)
-```
-
-## Data Visualization
-
-### Survival Curves
-
-**Kaplan-Meier Plot Best Practices**
-
-```python
-# Key elements for publication-quality survival curve
-1. X-axis: Time (months or years), starts at 0
-2. Y-axis: Survival probability (0 to 1.0 or 0% to 100%)
-3. Step function: Survival curve with steps at event times
-4. 95% CI bands: Shaded region around survival curve (optional but recommended)
-5. Number at risk table: Below x-axis showing n at risk at time intervals
-6. Censoring marks: Vertical tick marks (|) at censored observations
-7. Legend: Clearly identify each curve
-8. Log-rank p-value: Prominently displayed
-9. Median survival: Horizontal line at 0.50, labeled
-10. Follow-up: Median follow-up time reported
-```
-
-**Number at Risk Table Format**
-```
-Number at risk
-Group A 50 42 35 28 18 10 5
-Group B 48 38 29 19 12 6 2
-Time 0 6 12 18 24 30 36 (months)
-```
-
-**Hazard Ratio Annotation**
-```
-On plot: HR 0.62 (95% CI 0.43-0.89), p=0.010
-Or in caption: Log-rank test p=0.010; Cox model HR=0.62 (95% CI 0.43-0.89)
-```
-
-### Waterfall Plots
-
-**Purpose**: Visualize individual patient responses to treatment
-
-**Construction**
-- **X-axis**: Individual patients (anonymized patient IDs)
-- **Y-axis**: Best % change from baseline tumor burden
-- **Bars**: Vertical bars, one per patient
- - Positive values: Tumor growth
- - Negative values: Tumor shrinkage
-- **Ordering**: Sorted from best response (left) to worst (right)
-- **Color coding**:
- - Green/blue: CR or PR (≥30% decrease)
- - Yellow: SD (-30% to +20%)
- - Red: PD (≥20% increase)
-- **Reference lines**: Horizontal lines at +20% (PD), -30% (PR)
-- **Annotations**: Biomarker status, response duration (symbols)
-
-**Example Annotations**
-```
-■ = Biomarker-positive
-○ = Biomarker-negative
-* = Ongoing response
-† = Progressed
-```
-
-### Forest Plots
-
-**Purpose**: Display subgroup analyses with hazard ratios and confidence intervals
-
-**Construction**
-- **Y-axis**: Subgroup categories
-- **X-axis**: Hazard ratio (log scale), vertical line at HR=1.0
-- **Points**: HR estimate for each subgroup
-- **Horizontal lines**: 95% confidence interval
-- **Square size**: Proportional to sample size or precision
-- **Overall effect**: Diamond at bottom, width represents 95% CI
-
-**Subgroups to Display**
-```
-Subgroup n HR (95% CI) Favors A Favors B
-──────────────────────────────────────────────────────────────────────────
-Overall 300 0.65 (0.48-0.88) ●────┤
-Age
- <65 years 180 0.58 (0.39-0.86) ●────┤
- ≥65 years 120 0.78 (0.49-1.24) ●──────┤
-Sex
- Male 175 0.62 (0.43-0.90) ●────┤
- Female 125 0.70 (0.44-1.12) ●─────┤
-Biomarker Status
- Positive 140 0.45 (0.28-0.72) ●───┤
- Negative 160 0.89 (0.59-1.34) ●──────┤
- p-interaction=0.041
-
- 0.25 0.5 1.0 2.0
- Hazard Ratio
-```
-
-**Interaction Testing**
-- Test whether treatment effect differs across subgroups
-- p-interaction <0.05 suggests heterogeneity
-- Pre-specify subgroups to avoid data mining
-
-### Spider Plots
-
-**Purpose**: Display longitudinal tumor burden changes over time for individual patients
-
-**Construction**
-- **X-axis**: Time from treatment start (weeks or months)
-- **Y-axis**: % change from baseline tumor burden
-- **Lines**: One line per patient connecting assessments
-- **Color coding**: By response category or biomarker status
-- **Reference lines**: 0% (no change), +20% (PD threshold), -30% (PR threshold)
-
-**Clinical Insights**
-- Identify delayed responders (initial SD then PR)
-- Detect early progression (rapid upward trajectory)
-- Assess depth of response (maximum tumor shrinkage)
-- Duration visualization (when lines cross PD threshold)
-
-### Swimmer Plots
-
-**Purpose**: Display treatment duration and response for individual patients
-
-**Construction**
-- **X-axis**: Time from treatment start (weeks or months)
-- **Y-axis**: Individual patients (one row per patient)
-- **Bars**: Horizontal bars representing treatment duration
-- **Symbols**:
- - ● Start of treatment
- - ▼ Ongoing treatment (arrow)
- - ■ Progressive disease (end of bar)
- - ◆ Death
- - | Dose modification
-- **Color**: Response status (CR=green, PR=blue, SD=yellow, PD=red)
-
-**Example**
-```
-Patient ID |0 3 6 9 12 15 18 21 24 months
-──────────────|──────────────────────────────────────────
-Pt-001 ●═══PR═══════════|════════PR══════════▼
-Pt-002 ●═══PR═══════════════PD■
-Pt-003 ●══════SD══════════PD■
-Pt-004 ●PR══════════════════════════════════PR▼
-...
-```
-
-## Confidence Intervals
-
-### Interpretation
-
-**95% Confidence Interval**
-- Range of plausible values for true population parameter
-- If study repeated 100 times, 95 of the 95% CIs would contain true value
-- **Not**: 95% probability true value within this interval (frequentist, not Bayesian)
-
-**Relationship to p-value**
-- If 95% CI excludes null value (HR=1.0, difference=0), p<0.05
-- If 95% CI includes null value, p≥0.05
-- CI provides more information: magnitude and precision of effect
-
-**Precision**
-- **Narrow CI**: High precision, large sample size
-- **Wide CI**: Low precision, small sample size or high variability
-- **Example**: HR 0.65 (95% CI 0.62-0.68) very precise; HR 0.65 (0.30-1.40) imprecise
-
-### Calculation Methods
-
-**Hazard Ratio CI**
-- From Cox regression output
-- Standard error of log(HR) → exp(log(HR) ± 1.96×SE)
-- Example: HR=0.62, SE(logHR)=0.185 → 95% CI (0.43, 0.89)
-
-**Survival Rate CI (Greenwood Formula)**
-- SE(S(t)) = S(t) × sqrt(Σ[d_i / (n_i × (n_i - d_i))])
-- 95% CI: S(t) ± 1.96 × SE(S(t))
-- Can use complementary log-log transformation for better properties
-
-**Proportion CI (Exact Binomial)**
-- For ORR, DCR: Use exact method (Clopper-Pearson) for small samples
-- Wilson score interval: Better properties than normal approximation
-- Example: 12/30 responses → ORR 40% (95% CI 22.7-59.4%)
-
-## Censoring and Missing Data
-
-### Types of Censoring
-
-**Right Censoring**
-- **End of study**: Patient alive at study termination (administrative censoring)
-- **Loss to follow-up**: Patient stops attending visits
-- **Withdrawal**: Patient withdraws consent
-- **Competing risk**: Death from unrelated cause (in disease-specific survival)
-
-**Handling Censoring**
-- **Assumption**: Non-informative - censoring independent of event probability
-- **Sensitivity Analysis**: Assess impact if assumption violated
- - Best case: All censored patients never progress
- - Worst case: All censored patients progress immediately after censoring
- - Actual result should fall between best/worst case
-
-### Missing Data
-
-**Mechanisms**
-- **MCAR (Missing Completely at Random)**: Missingness unrelated to any variable
-- **MAR (Missing at Random)**: Missingness related to observed but not unobserved variables
-- **NMAR (Not Missing at Random)**: Missingness related to the missing value itself
-
-**Handling Strategies**
-- **Complete case analysis**: Exclude patients with missing data (biased if not MCAR)
-- **Multiple imputation**: Generate multiple plausible datasets, analyze each, pool results
-- **Maximum likelihood**: Estimate parameters using all available data
-- **Sensitivity analysis**: Assess robustness to missing data assumptions
-
-**Response Assessment Missing Data**
-- **Unevaluable for response**: Baseline measurable disease but post-baseline assessment missing
- - Exclude from ORR denominator or count as non-responder (sensitivity analysis)
-- **PFS censoring**: Last adequate tumor assessment date if later assessments missing
-
-## Reporting Standards
-
-### CONSORT Statement (RCTs)
-
-**Flow Diagram**
-- Assessed for eligibility (n=)
-- Randomized (n=)
-- Allocated to intervention (n=)
-- Lost to follow-up (n=, reasons)
-- Discontinued intervention (n=, reasons)
-- Analyzed (n=)
-
-**Baseline Table**
-- Demographics and clinical characteristics
-- Baseline prognostic factors
-- Show balance between arms
-
-**Outcomes Table**
-- Primary endpoint results with CI and p-value
-- Secondary endpoints
-- Safety summary
-
-### STROBE Statement (Observational Studies)
-
-**Study Design**: Cohort, case-control, or cross-sectional
-
-**Participants**: Eligibility, sources, selection methods, sample size
-
-**Variables**: Clearly define outcomes, exposures, predictors, confounders
-
-**Statistical Methods**: Describe all methods, handling of missing data, sensitivity analyses
-
-**Results**: Participant flow, descriptive data, outcome data, main results, other analyses
-
-### Reproducible Research Practices
-
-**Statistical Analysis Plan (SAP)**
-- Pre-specify all analyses before data lock
-- Primary and secondary endpoints
-- Analysis populations (ITT, per-protocol, safety)
-- Statistical tests and models
-- Subgroup analyses (pre-specified)
-- Interim analyses (if planned)
-- Multiple testing procedures
-
-**Transparency**
-- Report all pre-specified analyses
-- Distinguish pre-specified from post-hoc exploratory
-- Report both positive and negative results
-- Provide access to anonymized individual patient data (when possible)
-
-## Software and Tools
-
-### R Packages for Survival Analysis
-- **survival**: Core package (Surv, survfit, coxph, survdiff)
-- **survminer**: Publication-ready Kaplan-Meier plots (ggsurvplot)
-- **rms**: Regression modeling strategies
-- **flexsurv**: Flexible parametric survival models
-
-### Python Libraries
-- **lifelines**: Kaplan-Meier, Cox regression, survival curves
-- **scikit-survival**: Machine learning for survival analysis
-- **matplotlib**: Custom survival curve plotting
-
-### Statistical Software
-- **R**: Most comprehensive for survival analysis
-- **Stata**: Medical statistics, good for epidemiology
-- **SAS**: Industry standard for clinical trials
-- **GraphPad Prism**: User-friendly for basic analyses
-- **SPSS**: Point-and-click interface, limited survival features
-
diff --git a/skills/clinical-decision-support/references/patient_cohort_analysis.md b/skills/clinical-decision-support/references/patient_cohort_analysis.md
deleted file mode 100644
index 67ad8939..00000000
--- a/skills/clinical-decision-support/references/patient_cohort_analysis.md
+++ /dev/null
@@ -1,427 +0,0 @@
-# Patient Cohort Analysis Guide
-
-## Overview
-
-Patient cohort analysis involves systematically studying groups of patients to identify patterns, compare outcomes, and derive clinical insights. In pharmaceutical and clinical research settings, cohort analysis is essential for understanding treatment effectiveness, biomarker correlations, and patient stratification.
-
-## Patient Stratification Methods
-
-### Biomarker-Based Stratification
-
-**Genomic Biomarkers**
-- **Mutations**: Driver mutations (EGFR, KRAS, BRAF), resistance mutations (T790M)
-- **Copy Number Variations**: Amplifications (HER2, MET), deletions (PTEN, RB1)
-- **Gene Fusions**: ALK, ROS1, NTRK, RET rearrangements
-- **Tumor Mutational Burden (TMB)**: High (≥10 mut/Mb) vs low TMB
-- **Microsatellite Instability**: MSI-high vs MSS/MSI-low
-
-**Expression Biomarkers**
-- **IHC Scores**: PD-L1 TPS (<1%, 1-49%, ≥50%), HER2 (0, 1+, 2+, 3+)
-- **RNA Expression**: Gene signatures, pathway activity scores
-- **Protein Levels**: Ki-67 proliferation index, hormone receptors (ER/PR)
-
-**Molecular Subtypes**
-- **Breast Cancer**: Luminal A, Luminal B, HER2-enriched, Triple-negative
-- **Glioblastoma**: Proneural, neural, classical, mesenchymal
-- **Lung Adenocarcinoma**: Terminal respiratory unit, proximal inflammatory, proximal proliferative
-- **Colorectal Cancer**: CMS1-4 (consensus molecular subtypes)
-
-### Demographic Stratification
-
-- **Age Groups**: Pediatric (<18), young adult (18-39), middle-age (40-64), elderly (65-79), very elderly (≥80)
-- **Sex/Gender**: Male, female, sex-specific biomarkers
-- **Race/Ethnicity**: FDA-recognized categories, ancestry-informative markers
-- **Geographic Location**: Regional variation in disease prevalence
-
-### Clinical Stratification
-
-**Disease Characteristics**
-- **Stage**: TNM staging (I, II, III, IV), Ann Arbor (lymphoma)
-- **Grade**: Well-differentiated (G1), moderately differentiated (G2), poorly differentiated (G3), undifferentiated (G4)
-- **Histology**: Adenocarcinoma vs squamous vs other subtypes
-- **Disease Burden**: Tumor volume, number of lesions, organ involvement
-
-**Patient Status**
-- **Performance Status**: ECOG (0-4), Karnofsky (0-100)
-- **Comorbidities**: Charlson Comorbidity Index, organ dysfunction
-- **Prior Treatment**: Treatment-naïve, previously treated, lines of therapy
-- **Response to Prior Therapy**: Responders vs non-responders, progressive disease
-
-### Risk Stratification
-
-**Prognostic Scores**
-- **Cancer**: AJCC staging, Gleason score, Nottingham grade
-- **Cardiovascular**: Framingham risk, TIMI, GRACE, CHADS2-VASc
-- **Liver Disease**: Child-Pugh class, MELD score
-- **Renal Disease**: eGFR categories, albuminuria stages
-
-**Composite Risk Models**
-- Low risk: Good prognosis, less aggressive treatment
-- Intermediate risk: Moderate prognosis, standard treatment
-- High risk: Poor prognosis, intensive treatment or clinical trials
-
-## Cluster Analysis and Subgroup Identification
-
-### Unsupervised Clustering
-
-**Methods**
-- **K-means**: Partition-based clustering with pre-defined number of clusters
-- **Hierarchical Clustering**: Agglomerative or divisive, creates dendrogram
-- **DBSCAN**: Density-based clustering, identifies outliers
-- **Consensus Clustering**: Robust cluster identification across multiple runs
-
-**Applications**
-- Molecular subtype discovery (e.g., GBM mesenchymal-immune-active cluster)
-- Patient phenotype identification
-- Treatment response patterns
-- Multi-omic data integration
-
-### Supervised Classification
-
-**Approaches**
-- **Pre-defined Criteria**: Clinical guidelines, established biomarker cut-points
-- **Machine Learning**: Random forests, support vector machines for prediction
-- **Neural Networks**: Deep learning for complex pattern recognition
-- **Validated Signatures**: Published gene expression panels (Oncotype DX, MammaPrint)
-
-### Validation Requirements
-
-- **Internal Validation**: Cross-validation, bootstrap resampling
-- **External Validation**: Independent cohort confirmation
-- **Clinical Validation**: Prospective trial confirmation of utility
-- **Analytical Validation**: Assay reproducibility, inter-lab concordance
-
-## Outcome Metrics
-
-### Survival Endpoints
-
-**Overall Survival (OS)**
-- Definition: Time from treatment start (or randomization) to death from any cause
-- Censoring: Last known alive date for patients lost to follow-up
-- Reporting: Median OS, 1-year/2-year/5-year OS rates, hazard ratio
-- Gold Standard: Primary endpoint for regulatory approval
-
-**Progression-Free Survival (PFS)**
-- Definition: Time from treatment start to disease progression or death
-- Assessment: RECIST v1.1, iRECIST (for immunotherapy)
-- Advantages: Earlier readout than OS, direct measure of treatment benefit
-- Limitations: Requires imaging, subject to assessment timing
-
-**Disease-Free Survival (DFS)**
-- Definition: Time from complete response to recurrence or death (adjuvant setting)
-- Application: Post-surgery, post-curative treatment
-- Synonyms: Recurrence-free survival (RFS), event-free survival (EFS)
-
-### Response Endpoints
-
-**Objective Response Rate (ORR)**
-- Definition: Proportion achieving complete response (CR) or partial response (PR)
-- Measurement: RECIST v1.1 criteria (≥30% tumor shrinkage for PR)
-- Reporting: ORR with 95% confidence interval
-- Advantage: Earlier endpoint than survival
-
-**Duration of Response (DOR)**
-- Definition: Time from first response (CR/PR) to progression
-- Population: Responders only
-- Clinical Relevance: Durability of treatment benefit
-- Reporting: Median DOR among responders
-
-**Disease Control Rate (DCR)**
-- Definition: CR + PR + stable disease (SD)
-- Threshold: SD must persist ≥6-8 weeks typically
-- Application: Less stringent than ORR, captures clinical benefit
-
-### Quality of Life and Functional Status
-
-**Performance Status**
-- **ECOG Scale**: 0 (fully active) to 4 (bedridden)
-- **Karnofsky Scale**: 100% (normal) to 0% (dead)
-- **Assessment Frequency**: Baseline and each cycle
-
-**Patient-Reported Outcomes (PROs)**
-- **Symptom Scales**: EORTC QLQ-C30, FACT-G
-- **Disease-Specific**: FACT-L (lung), FACT-B (breast)
-- **Toxicity**: PRO-CTCAE for adverse events
-- **Reporting**: Change from baseline, clinically meaningful differences
-
-### Safety and Tolerability
-
-**Adverse Events (AEs)**
-- **Grading**: CTCAE v5.0 (Grade 1-5)
-- **Attribution**: Related vs unrelated to treatment
-- **Serious AEs (SAEs)**: Death, life-threatening, hospitalization, disability
-- **Reporting**: Incidence, severity, time to onset, resolution
-
-**Treatment Modifications**
-- **Dose Reductions**: Proportion requiring dose decrease
-- **Dose Delays**: Treatment interruptions, cycle delays
-- **Discontinuations**: Treatment termination due to toxicity
-- **Relative Dose Intensity**: Actual dose / planned dose ratio
-
-## Statistical Methods for Group Comparisons
-
-### Continuous Variables
-
-**Parametric Tests (Normal Distribution)**
-- **Two Groups**: Independent t-test, paired t-test
-- **Multiple Groups**: ANOVA (analysis of variance), repeated measures ANOVA
-- **Reporting**: Mean ± SD, mean difference with 95% CI, p-value
-
-**Non-Parametric Tests (Non-Normal Distribution)**
-- **Two Groups**: Mann-Whitney U test (Wilcoxon rank-sum)
-- **Paired Data**: Wilcoxon signed-rank test
-- **Multiple Groups**: Kruskal-Wallis test
-- **Reporting**: Median [IQR], median difference, p-value
-
-### Categorical Variables
-
-**Chi-Square Test**
-- **Application**: Compare proportions between ≥2 groups
-- **Assumptions**: Expected count ≥5 in each cell
-- **Reporting**: Proportions, chi-square statistic, df, p-value
-
-**Fisher's Exact Test**
-- **Application**: 2x2 tables with small sample sizes (expected count <5)
-- **Advantage**: Exact p-value, no large-sample approximation
-- **Limitation**: Computationally intensive for large tables
-
-### Survival Analysis
-
-**Kaplan-Meier Method**
-- **Application**: Estimate survival curves with censored data
-- **Output**: Survival probability at each time point, median survival
-- **Visualization**: Step function curves with 95% CI bands
-
-**Log-Rank Test**
-- **Application**: Compare survival curves between groups
-- **Null Hypothesis**: No difference in survival distributions
-- **Reporting**: Chi-square statistic, df, p-value
-- **Limitation**: Assumes proportional hazards
-
-**Cox Proportional Hazards Model**
-- **Application**: Multivariable survival analysis
-- **Output**: Hazard ratio (HR) with 95% CI for each covariate
-- **Interpretation**: HR > 1 (increased risk), HR < 1 (decreased risk)
-- **Assumptions**: Proportional hazards (test with Schoenfeld residuals)
-
-### Effect Sizes
-
-**Hazard Ratio (HR)**
-- Definition: Ratio of hazard rates between groups
-- Interpretation: HR = 0.5 means 50% reduction in risk
-- Reporting: HR (95% CI), p-value
-- Example: HR = 0.65 (0.52-0.81), p<0.001
-
-**Odds Ratio (OR)**
-- Application: Case-control studies, logistic regression
-- Interpretation: OR > 1 (increased odds), OR < 1 (decreased odds)
-- Reporting: OR (95% CI), p-value
-
-**Risk Ratio (RR) / Relative Risk**
-- Application: Cohort studies, clinical trials
-- Interpretation: RR = 2.0 means 2-fold increased risk
-- More intuitive than OR for interpreting probabilities
-
-### Multiple Testing Corrections
-
-**Bonferroni Correction**
-- Method: Divide α by number of tests (α/n)
-- Example: 5 tests → significance threshold = 0.05/5 = 0.01
-- Conservative: Reduces Type I error but increases Type II error
-
-**False Discovery Rate (FDR)**
-- Method: Benjamini-Hochberg procedure
-- Interpretation: Expected proportion of false positives among significant results
-- Less Conservative: More power than Bonferroni
-
-**Family-Wise Error Rate (FWER)**
-- Method: Control probability of any false positive
-- Application: When even one false positive is problematic
-- Examples: Bonferroni, Holm-Bonferroni
-
-## Biomarker Correlation with Outcomes
-
-### Predictive Biomarkers
-
-**Definition**: Biomarkers that identify patients likely to respond to a specific treatment
-
-**Examples**
-- **PD-L1 ≥50%**: Predicts response to pembrolizumab monotherapy (NSCLC)
-- **HER2 3+**: Predicts response to trastuzumab (breast cancer)
-- **EGFR mutations**: Predicts response to EGFR TKIs (lung cancer)
-- **BRAF V600E**: Predicts response to vemurafenib (melanoma)
-- **MSI-H/dMMR**: Predicts response to immune checkpoint inhibitors
-
-**Analysis**
-- Stratified analysis: Compare treatment effect within biomarker-positive vs negative
-- Interaction test: Test if treatment effect differs by biomarker status
-- Reporting: HR in biomarker+ vs biomarker-, interaction p-value
-
-### Prognostic Biomarkers
-
-**Definition**: Biomarkers that predict outcome regardless of treatment
-
-**Examples**
-- **High Ki-67**: Poor prognosis independent of treatment (breast cancer)
-- **TP53 mutation**: Poor prognosis in many cancers
-- **Low albumin**: Poor prognosis marker (many diseases)
-- **Elevated LDH**: Poor prognosis (melanoma, lymphoma)
-
-**Analysis**
-- Compare outcomes across biomarker levels in untreated or uniformly treated cohort
-- Multivariable Cox model adjusting for other prognostic factors
-- Validate in independent cohorts
-
-### Continuous Biomarker Analysis
-
-**Cut-Point Selection**
-- **Data-Driven**: Maximally selected rank statistics, ROC curve analysis
-- **Literature-Based**: Established clinical cut-points
-- **Median/Tertiles**: Simple divisions for exploration
-- **Validation**: Cut-points must be validated in independent cohort
-
-**Continuous Analysis**
-- Treat biomarker as continuous variable in Cox model
-- Report HR per unit increase or per standard deviation
-- Spline curves to assess non-linear relationships
-- Advantage: No information loss from dichotomization
-
-## Data Presentation
-
-### Baseline Characteristics Table (Table 1)
-
-**Standard Format**
-```
-Characteristic Group A (n=50) Group B (n=45) p-value
-Age, years (median [IQR]) 62 [54-68] 59 [52-66] 0.34
-Sex, n (%)
- Male 30 (60%) 28 (62%) 0.82
- Female 20 (40%) 17 (38%)
-ECOG PS, n (%)
- 0-1 42 (84%) 39 (87%) 0.71
- 2 8 (16%) 6 (13%)
-Biomarker+, n (%) 23 (46%) 21 (47%) 0.94
-```
-
-**Key Principles**
-- Report all clinically relevant baseline variables
-- Use appropriate summary statistics (mean±SD for normal, median[IQR] for skewed)
-- Include sample size for each group
-- Report p-values for group comparisons (but baseline imbalances expected by chance)
-- Do NOT adjust baseline p-values for multiple testing
-
-### Efficacy Outcomes Table
-
-**Response Outcomes**
-```
-Outcome Group A (n=50) Group B (n=45) p-value
-ORR, n (%) [95% CI] 25 (50%) [36-64] 15 (33%) [20-48] 0.08
- Complete Response 3 (6%) 1 (2%)
- Partial Response 22 (44%) 14 (31%)
-DCR, n (%) [95% CI] 40 (80%) [66-90] 35 (78%) [63-89] 0.79
-Median DOR, months (95% CI) 8.2 (6.1-11.3) 6.8 (4.9-9.7) 0.12
-```
-
-**Survival Outcomes**
-```
-Endpoint Group A Group B HR (95% CI) p-value
-Median PFS, months (95% CI) 10.2 (8.3-12.1) 6.5 (5.1-7.9) 0.62 (0.41-0.94) 0.02
-12-month PFS rate 42% 28%
-Median OS, months (95% CI) 21.3 (17.8-NR) 15.7 (12.4-19.1) 0.71 (0.45-1.12) 0.14
-12-month OS rate 68% 58%
-```
-
-### Safety and Tolerability Table
-
-**Adverse Events**
-```
-Adverse Event Any Grade, n (%) Grade 3-4, n (%)
- Group A Group B Group A Group B
-Fatigue 35 (70%) 32 (71%) 3 (6%) 2 (4%)
-Nausea 28 (56%) 25 (56%) 1 (2%) 1 (2%)
-Neutropenia 15 (30%) 18 (40%) 8 (16%) 10 (22%)
-Thrombocytopenia 12 (24%) 14 (31%) 4 (8%) 6 (13%)
-Hepatotoxicity 8 (16%) 6 (13%) 2 (4%) 1 (2%)
-Treatment discontinuation 6 (12%) 8 (18%) - -
-```
-
-### Visualization Formats
-
-**Survival Curves**
-- Kaplan-Meier plots with 95% CI bands
-- Number at risk table below x-axis
-- Log-rank p-value and HR prominently displayed
-- Clear legend identifying groups
-
-**Forest Plots**
-- Subgroup analysis showing HR with 95% CI for each subgroup
-- Test for interaction assessing heterogeneity
-- Overall effect at bottom
-
-**Waterfall Plots**
-- Individual patient best response (% change from baseline)
-- Ordered from best to worst response
-- Color-coded by response category (CR, PR, SD, PD)
-- Biomarker status annotation
-
-**Swimmer Plots**
-- Time on treatment for each patient
-- Response duration for responders
-- Treatment modifications marked
-- Ongoing treatments indicated with arrow
-
-## Quality Control and Validation
-
-### Data Quality Checks
-
-- **Completeness**: Missing data patterns, loss to follow-up
-- **Consistency**: Cross-field validation, logical checks
-- **Outliers**: Identify and investigate extreme values
-- **Duplicates**: Patient ID verification, enrollment checks
-
-### Statistical Assumptions
-
-- **Normality**: Shapiro-Wilk test, Q-Q plots for continuous variables
-- **Proportional Hazards**: Schoenfeld residuals for Cox models
-- **Independence**: Check for clustering, matched data
-- **Missing Data**: Assess mechanism (MCAR, MAR, NMAR), handle appropriately
-
-### Reporting Standards
-
-- **CONSORT**: Randomized controlled trials
-- **STROBE**: Observational studies
-- **REMARK**: Tumor marker prognostic studies
-- **STARD**: Diagnostic accuracy studies
-- **TRIPOD**: Prediction model development/validation
-
-## Clinical Interpretation
-
-### Translating Statistics to Clinical Meaning
-
-**Statistical Significance vs Clinical Significance**
-- p<0.05 does not guarantee clinical importance
-- Small effects can be statistically significant with large samples
-- Large effects can be non-significant with small samples
-- Consider effect size magnitude and confidence interval width
-
-**Number Needed to Treat (NNT)**
-- NNT = 1 / absolute risk reduction
-- Example: 10% vs 5% event rate → ARR = 5% → NNT = 20
-- Interpretation: Treat 20 patients to prevent 1 event
-- Useful for communicating treatment benefit
-
-**Minimal Clinically Important Difference (MCID)**
-- Pre-defined threshold for meaningful clinical benefit
-- OS: Often 2-3 months in oncology
-- PFS: Context-dependent, often 1.5-3 months
-- QoL: 10-point change on 100-point scale
-- Response rate: Often 10-15 percentage point difference
-
-### Contextualization
-
-- Compare to historical controls or standard of care
-- Consider patient population characteristics
-- Account for prior treatment exposure
-- Evaluate toxicity trade-offs
-- Assess quality of life impact
-
diff --git a/skills/clinical-decision-support/references/privacy_and_disclosure.md b/skills/clinical-decision-support/references/privacy_and_disclosure.md
new file mode 100644
index 00000000..23cba77a
--- /dev/null
+++ b/skills/clinical-decision-support/references/privacy_and_disclosure.md
@@ -0,0 +1,144 @@
+# Privacy, De-identification, and Disclosure
+
+## Boundary
+
+The skill never reads PHI, raw records, free-text notes, images, sequences, or row-level data. The checklist records a human process; it does not de-identify data.
+
+Do not paste sensitive information into a template to see whether it passes.
+
+## HHS Methods
+
+The HIPAA Privacy Rule at 45 CFR 164.514 provides two methods for de-identification:
+
+1. **Expert Determination** — a qualified expert applies generally accepted statistical and scientific principles, determines that re-identification risk is very small, and documents methods and results.
+2. **Safe Harbor** — specified identifiers of the individual and relatives, employers, or household members are removed, and the covered entity has no actual knowledge that the remaining information could identify an individual alone or in combination.
+
+Primary sources:
+
+- [HHS de-identification guidance](https://www.hhs.gov/hipaa/for-professionals/special-topics/de-identification/index.html)
+- [45 CFR 164.514](https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-E/section-164.514)
+
+The checklist cannot determine whether an organization is a covered entity/business associate, whether information is PHI, or whether a method was correctly applied.
+
+## Safe Harbor Categories
+
+The human review must address all categories:
+
+1. names;
+2. geographic subdivisions smaller than a state, subject to ZIP-code rules;
+3. date elements more specific than year, with the age-90 rule;
+4. telephone numbers;
+5. fax numbers;
+6. email addresses;
+7. Social Security numbers;
+8. medical record numbers;
+9. health-plan beneficiary numbers;
+10. account numbers;
+11. certificate/license numbers;
+12. vehicle identifiers and serial numbers;
+13. device identifiers and serial numbers;
+14. web URLs;
+15. IP addresses;
+16. biometric identifiers;
+17. full-face photographs and comparable images;
+18. other unique identifying numbers, characteristics, or codes.
+
+Parts and derivatives can still be identifiers. HHS specifically notes that free text is not exempt and can contain listed identifiers or identifying context.
+
+## Expert Determination Record
+
+Record without embedding the sensitive data:
+
+- expert qualifications and independence;
+- data context and recipients;
+- anticipated data linkages and attacker knowledge;
+- methods and assumptions;
+- risk threshold and rationale;
+- mitigation and residual risk;
+- validity period and change triggers;
+- documentation location and approval.
+
+Do not claim that hashing, pseudonymization, encryption, a data-use agreement, or a low cell count alone constitutes Expert Determination.
+
+## Aggregate Disclosure
+
+Aggregate tables can still disclose information through:
+
+- small cells;
+- row/column totals;
+- differencing across releases;
+- rare combinations;
+- nested geographies;
+- longitudinal patterns;
+- extreme values;
+- genomics;
+- external linkage.
+
+Controls may include:
+
+- minimum cell thresholds;
+- primary suppression;
+- complementary suppression;
+- category aggregation;
+- top/bottom coding;
+- rounding or perturbation under an approved method;
+- release coordination;
+- query budgets;
+- access controls and data-use agreements;
+- secure enclaves;
+- expert review.
+
+There is no universal small-cell threshold that proves HIPAA de-identification. The table generator defaults to 11 only as a conservative operational safeguard and applies complementary suppression within a row. The data steward must select policy.
+
+## Template Status Values
+
+For each category use:
+
+- `not_present` — documented inventory confirms absence;
+- `removed` — documented transformation confirms removal;
+- `generalized` — allowed generalization documented and approved;
+- `expert_reviewed` — addressed under the referenced Expert Determination;
+- `unresolved` — not complete.
+
+Every non-unresolved status needs evidence text. Never include an example identifier in evidence.
+
+## Actual-Knowledge and Residual-Risk Review
+
+Document:
+
+- free-text review;
+- derived fields;
+- linkage and differencing;
+- unusual occupations or events;
+- rare diseases/combinations;
+- dates and ages;
+- geography;
+- longitudinal uniqueness;
+- recipient context;
+- prior releases;
+- residual identifiers.
+
+Escalate uncertainty. Do not mark the checklist complete merely because all obvious columns were removed.
+
+## Output Language
+
+Allowed:
+
+> Documentation checklist complete for the selected method. This output is not a HIPAA compliance or de-identification determination.
+
+Not allowed:
+
+> HIPAA compliant.
+
+> Safe to publish.
+
+> Anonymous.
+
+## Script
+
+```bash
+python3 scripts/deidentification_checklist.py \
+ assets/deidentification_checklist_template.json
+```
+
+The distributed template is unresolved by design.
diff --git a/skills/clinical-decision-support/references/regulatory_and_governance.md b/skills/clinical-decision-support/references/regulatory_and_governance.md
new file mode 100644
index 00000000..d4499523
--- /dev/null
+++ b/skills/clinical-decision-support/references/regulatory_and_governance.md
@@ -0,0 +1,104 @@
+# Regulatory and Governance Context
+
+Checked 2026-07-23. This is orientation for research documentation, not legal advice or a regulatory determination.
+
+## FDA Clinical Decision Support
+
+FDA issued the current **Clinical Decision Support Software** final guidance in January 2026 and reissued it on January 29, 2026. It explains how FDA interprets the statutory criteria for certain CDS software functions excluded from the device definition under section 520(o)(1)(E) of the FD&C Act and distinguishes those functions from device software functions.
+
+Do not turn the guidance into a self-certification score. Regulatory status depends on the complete function and intended use, including:
+
+- who uses the function;
+- what information it acquires, processes, or analyzes;
+- the output and its role in prevention, diagnosis, or treatment;
+- whether the healthcare professional can independently review the basis;
+- time criticality, automation, and reliance;
+- patient/caregiver use and other applicable digital-health policies.
+
+This skill intentionally stays outside patient-specific and live clinical functions. An artifact title, disclaimer, or “human in the loop” statement does not by itself make software non-device.
+
+Source: [FDA Clinical Decision Support Software, final guidance (January 2026)](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/clinical-decision-support-software).
+
+## FDA AI-Enabled Device Lifecycle
+
+Use these sources only to identify documentation themes for research governance:
+
+- [Predetermined Change Control Plan for AI-Enabled Device Software Functions](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/marketing-submission-recommendations-predetermined-change-control-plan-artificial-intelligence) — final guidance, August 2025. A PCCP describes planned modifications, methods to develop/validate/implement them, and impact assessment; FDA reviews it within a marketing submission.
+- [AI-Enabled Device Software Functions: Lifecycle Management and Marketing Submission Recommendations](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/artificial-intelligence-enabled-device-software-functions-lifecycle-management-and-marketing) — draft guidance, January 2025; **not for implementation** as of the check date.
+- [Good Machine Learning Practice for Medical Device Development](https://www.fda.gov/medical-devices/software-medical-device-samd/good-machine-learning-practice-medical-device-development-guiding-principles) — FDA page points to the January 2025 IMDRF final principles.
+- [Transparency for Machine Learning-Enabled Medical Devices](https://www.fda.gov/medical-devices/software-medical-device-samd/transparency-machine-learning-enabled-medical-devices-guiding-principles) — joint guiding principles, June 2024.
+
+Recurring lifecycle themes:
+
+- representative data and independent test sets;
+- performance of the human-AI team;
+- clinically relevant testing across intended conditions;
+- known limitations, confidence intervals, gaps, and failure modes;
+- monitoring, issue investigation, change notification, and version traceability;
+- training/test data characterization and subgroup performance.
+
+These sources do not authorize this skill to create a medical device or a submission.
+
+## ONC HTI-1 Transparency
+
+The HTI-1 final rule added the Decision Support Interventions certification criterion at 45 CFR 170.315(b)(11). Its scope is certified health IT and the configurations defined in the rule; it is not a universal certification checklist for every research model.
+
+For predictive DSIs in scope, the rule and ONC materials emphasize source attributes covering:
+
+- developer and funding;
+- output type, purpose, intended population, users, and decision role;
+- cautioned out-of-scope uses and known limitations;
+- development data and input features;
+- fairness process;
+- external validation;
+- quantitative performance;
+- ongoing maintenance;
+- update, continued-validation, and fairness-assessment schedules.
+
+They also describe intervention risk management for predictive DSIs supplied by certified health IT developers. Use these categories as a useful transparency crosswalk only when relevant; do not claim ONC certification.
+
+Sources:
+
+- [HTI-1 final rule](https://www.federalregister.gov/citation/89-FR-1391)
+- [ONC HTI-1 DSI fact sheet](https://www.healthit.gov/wp-content/uploads/2023/12/HTI-1_DSI_fact-sheet_508.pdf)
+- [ONC DSI final-rule presentation](https://healthit.gov/wp-content/uploads/2024/01/DSI_HTI1-Final-Rule-Presentation_508.pdf)
+
+## ICH E6(R3), E9, and E9(R1)
+
+Use ICH only when the artifact concerns clinical-trial planning, conduct, analysis, or evidence interpretation.
+
+The current consolidated E6(R3) Step 4 guideline combines the principles, Annex 1, and Annex 2. It was adopted June 16, 2026 after Annex 2 reached Step 4 on June 3, 2026. Relevant governance themes include:
+
+- quality by design and proportionate risk management;
+- clear roles, oversight, and documented decisions;
+- fit-for-purpose data and computerized systems;
+- data integrity, metadata, auditability, and traceability;
+- privacy and confidentiality;
+- protocol and statistical-analysis-plan alignment;
+- management of deviations, incidents, and important changes;
+- fitness-for-purpose considerations for real-world data.
+
+ICH E9 provides statistical principles for clinical trials. E9(R1), adopted November 20, 2019, requires alignment of the clinical question, estimand, design, conduct, analysis, and interpretation. Its estimand attributes and intercurrent-event strategies should be pre-specified; sensitivity analyses assess robustness to assumptions.
+
+Sources:
+
+- [ICH E6(R3) consolidated Step 4 guideline (June 2026)](https://database.ich.org/sites/default/files/ICH%20E6(R3)_Step4_FinalConsolidatedGuideline_2026_0616_.pdf)
+- [ICH E9(R1) estimands and sensitivity analysis](https://database.ich.org/sites/default/files/E9-R1_Step4_Guideline_2019_1203.pdf)
+- [ICH efficacy guideline index](https://www.ich.org/page/efficacy-guidelines)
+
+ICH alignment must be assessed by the sponsor and relevant authorities. A script cannot establish GCP conformity.
+
+## Governance Crosswalk
+
+| Documentation field | FDA/AI theme | ONC HTI-1 theme | ICH theme |
+|---|---|---|---|
+| Intended use/users/population | Function and intended use | Purpose/source attributes | Trial objective/population |
+| Limitations/out-of-scope use | Labeling/transparency | Cautioned use | Protocol constraints |
+| Data provenance | Dataset characterization | Development details | Data origin/fitness |
+| External validation | Clinically relevant testing | External-validation process | Evidence reliability |
+| Subgroup/fairness | Representative performance | Fairness process | Population relevance |
+| Human factors | Human-AI team | Intended decision role | Feasibility/quality |
+| Monitoring/change control | TPLC/PCCP | Maintenance schedule | Quality management |
+| Audit trail | Submission/version evidence | Source attributes | Essential records/metadata |
+
+Treat the crosswalk as a documentation aid, never a conformity assessment.
diff --git a/skills/clinical-decision-support/references/safety_and_scope.md b/skills/clinical-decision-support/references/safety_and_scope.md
new file mode 100644
index 00000000..92cbc270
--- /dev/null
+++ b/skills/clinical-decision-support/references/safety_and_scope.md
@@ -0,0 +1,103 @@
+# Safety and Scope
+
+## Intended Use
+
+Use this skill only to create or check research, evaluation, documentation, and governance artifacts from synthetic or aggregate data.
+
+Acceptable examples:
+
+- an intended-use statement for a retrospective model evaluation;
+- an aggregate subgroup performance report;
+- a statistical analysis plan;
+- a GRADE evidence-profile shell for a human panel;
+- a release-gate traceability matrix;
+- a de-identification process checklist.
+
+## Prohibited Use
+
+Do not:
+
+- accept or produce a record about a person;
+- infer a diagnosis, prognosis, phenotype, biomarker class, or eligibility for a person;
+- recommend or compare care options for a person;
+- provide medication, dose, schedule, monitoring, or contraindication instructions;
+- triage, assign urgency, create an alarm, or suggest escalation;
+- deploy logic in an EHR, bedside tool, portal, order set, or alerting workflow;
+- represent output as clinical advice, a validated medical device, or an authorized clinical system;
+- claim legal, regulatory, quality-system, or HIPAA compliance.
+
+No disclaimer makes an otherwise prohibited workflow acceptable.
+
+## Stop Conditions
+
+Stop and do not process the input when any of the following is present:
+
+- names, record numbers, contact details, precise locations, or person-linked dates;
+- row-level records, timelines, notes, images, signals, or sequences;
+- a request about “this patient,” “this result,” or an individual case;
+- instructions to choose a therapy, test, dose, disposition, or urgency;
+- instructions to push output to a live clinical system;
+- an assertion that passing a checklist proves authorization or compliance.
+
+Explain the boundary briefly. For care, direct the requester to a licensed healthcare professional and locally validated, appropriately authorized systems. For privacy, regulatory, or legal determinations, direct them to qualified organizational reviewers.
+
+## Required Intended-Use Elements
+
+An artifact is incomplete unless it states:
+
+1. **Purpose** — the specific research or governance question.
+2. **Users** — named roles, not “clinicians” broadly.
+3. **Population scope** — aggregate cohort or synthetic data only.
+4. **Decision role** — descriptive, evaluative, or governance support.
+5. **Excluded uses** — every prohibited use above.
+6. **Data level** — aggregate or synthetic, with no PHI/raw rows supplied.
+7. **Limitations** — known gaps, assumptions, transportability, and failure modes.
+8. **Human review** — required roles and approval status.
+9. **Versioning** — owner, version, release date, changes, and retirement criteria.
+10. **Monitoring** — drift, calibration, subgroup performance, incidents, and review cadence when applicable.
+
+## Human Review Matrix
+
+| Artifact | Minimum review roles |
+|---|---|
+| Evidence profile | systematic-review methodologist; domain experts; panel chair |
+| Cohort report | statistician/epidemiologist; data steward; domain expert |
+| Survival plan | statistician with time-to-event expertise; domain expert |
+| Model/biomarker evaluation | prediction-model methodologist; assay/domain expert; fairness reviewer |
+| Privacy checklist | privacy official or qualified de-identification expert |
+| Logic traceability | system owner; independent validator; governance approver |
+| Regulatory context | qualified legal/regulatory counsel |
+
+Review completion must be recorded by the responsible organization. The scripts do not authenticate reviewers or approvals.
+
+## Safe Language
+
+Prefer:
+
+- “The aggregate evaluation estimated…”
+- “Performance differed across evaluated subgroups; causes and practical importance require review.”
+- “The evidence panel judged certainty as…; rationale and sources are recorded.”
+- “This checklist is complete; it is not a compliance determination.”
+- “External validation has not been performed.”
+
+Avoid:
+
+- “The model is safe/fair/clinically valid.”
+- “This biomarker means the patient should…”
+- “The tool is FDA compliant/approved.”
+- “The dataset is HIPAA compliant.”
+- “The recommendation is Grade 1A” without the framework, panel process, outcome-specific judgments, and source trail.
+
+## Audit Trail
+
+Record:
+
+- immutable artifact ID and version;
+- source versions and access dates;
+- data provenance and cut date;
+- code version and command;
+- declared thresholds before analysis;
+- reviewer roles, dates, decisions, and unresolved objections;
+- change reason, validation evidence, rollback plan, and retirement decision.
+
+Do not put secrets, credentials, or patient information in audit logs.
diff --git a/skills/clinical-decision-support/references/security_validation.md b/skills/clinical-decision-support/references/security_validation.md
new file mode 100644
index 00000000..3df2181e
--- /dev/null
+++ b/skills/clinical-decision-support/references/security_validation.md
@@ -0,0 +1,60 @@
+# Security Validation Record
+
+Validation date: **2026-07-23** (local project date).
+
+## Baseline
+
+The repository `SECURITY.md` section recorded 11 findings:
+
+- 3 CRITICAL findings for cross-file environment-variable/network exfiltration behavior;
+- 1 HIGH finding for transmitting a credential to an external service;
+- 5 MEDIUM findings for command chaining, credential flow, undeclared network use, and environment harvesting;
+- 2 LOW findings for mandatory cross-skill invocation and dependency concerns.
+
+The affected external schematic wrappers were the now-deleted files
+`generate_schematic.py` and `generate_schematic_ai.py`.
+
+## Remediation
+
+- Deleted both schematic-generation scripts.
+- Removed all external service, LLM, image, credential, and environment-variable behavior.
+- Removed mandatory figures and cross-skill calls.
+- Replaced unsafe person-level classification and care-pathway helpers with aggregate or planning-only tools.
+- Added bounded local JSON handling, person-level-key rejection, output limits, and deterministic schemas.
+- Added static AST tests that reject network libraries, dynamic code execution, credential access, and executable serialization.
+
+## Post-Refresh Results
+
+- Direct behavioral scan: **SAFE, 0 findings**.
+- Pull-request gate with `--fail-on HIGH`: **passed** with 0 CRITICAL and
+ 0 HIGH. Repeated LLM-assisted runs returned 2–3 LOW findings because the
+ analyzer is nondeterministic.
+
+## Accepted LOW Findings
+
+Across repeated runs, the nondeterministic analyzer reported different subsets of
+these LOW observations:
+
+1. **Optional `allowed-tools` field absent** — accepted as informational. The
+ Agent Skills specification does not require it; compatibility and runtime
+ instructions explicitly prohibit network and credential access.
+2. **Broad description** — accepted. The scope intentionally covers the related research-evaluation artifacts requested for this safety refresh, while the frontmatter and first body section explicitly exclude care and live operation.
+3. **Person-level key filtering uses a denylist** — accepted as a documented limitation, not a privacy guarantee. Input is contractually restricted to synthetic or aggregate schemas, common person-level fields are rejected as defense in depth, and the documentation repeatedly requires qualified privacy review. The filter cannot detect every identifier name or sensitive value and is never presented as de-identification.
+4. **Occasional missing-file report** — accepted as an analyzer false
+ positive. Some runs invented a `templates/` directory and nonexistent
+ `assets/*.md` references. The deterministic
+ `test_documented_local_paths_exist` check resolves every documented local
+ path and passes.
+
+None of the accepted findings permits network access, sensitive-data handling, or clinical action.
+
+## Reproduction
+
+```bash
+uv run skill-scanner scan skills/clinical-decision-support --use-behavioral
+
+uv run python scan_pr_skills.py \
+ --fail-on HIGH \
+ --output /tmp/clinical-decision-support-pr-scan.md \
+ skills/clinical-decision-support
+```
diff --git a/skills/clinical-decision-support/references/sources.md b/skills/clinical-decision-support/references/sources.md
new file mode 100644
index 00000000..d130bc0f
--- /dev/null
+++ b/skills/clinical-decision-support/references/sources.md
@@ -0,0 +1,119 @@
+# Authoritative Source Ledger
+
+Research cutoff and link check: **2026-07-23**.
+
+Research used `parallel-cli search` and `parallel-cli extract`, constrained to official agencies, standards groups, guideline hosts, and primary publications. Status labels below reflect the source on the cutoff date. A link in this ledger is not an endorsement of an artifact or a substitute for checking the current source before use.
+
+## FDA: CDS and AI-Enabled Devices
+
+- **Clinical Decision Support Software** — FDA final guidance, January 2026; page reissued/content current January 29, 2026. Defines FDA's current interpretation of non-device CDS criteria and device-software boundaries.
+ https://www.fda.gov/regulatory-information/search-fda-guidance-documents/clinical-decision-support-software
+- **Marketing Submission Recommendations for a Predetermined Change Control Plan for AI-Enabled Device Software Functions** — FDA final guidance, August 2025. Used for planned modifications, validation methodology, impact assessment, and change-control concepts.
+ https://www.fda.gov/regulatory-information/search-fda-guidance-documents/marketing-submission-recommendations-predetermined-change-control-plan-artificial-intelligence
+- **AI-Enabled Device Software Functions: Lifecycle Management and Marketing Submission Recommendations** — FDA draft guidance, January 2025; explicitly draft/not for implementation on the cutoff date. Used only as clearly labeled draft lifecycle context.
+ https://www.fda.gov/regulatory-information/search-fda-guidance-documents/artificial-intelligence-enabled-device-software-functions-lifecycle-management-and-marketing
+- **Good Machine Learning Practice for Medical Device Development: Guiding Principles** — FDA page current December 19, 2025, linking the January 2025 IMDRF final principles. Used for lifecycle, representative data, human-AI team, and independent testing themes.
+ https://www.fda.gov/medical-devices/software-medical-device-samd/good-machine-learning-practice-medical-device-development-guiding-principles
+- **Transparency for Machine Learning-Enabled Medical Devices: Guiding Principles** — FDA/Health Canada/MHRA, June 13, 2024. Used for intended users, limitations, data characterization, uncertainty, human factors, monitoring, and update communication.
+ https://www.fda.gov/medical-devices/software-medical-device-samd/transparency-machine-learning-enabled-medical-devices-guiding-principles
+- **Artificial Intelligence in Software as a Medical Device** — FDA topic page, content current March 25, 2025 in search results. Used to cross-check the guidance sequence.
+ https://www.fda.gov/medical-devices/software-medical-device-samd/artificial-intelligence-software-medical-device
+
+## ONC / HTI-1
+
+- **HTI-1 Final Rule** — official Federal Register text, January 2024. Used for the legal scope of predictive DSI/source-attribute and intervention-risk-management requirements.
+ https://www.federalregister.gov/citation/89-FR-1391
+- **HTI-1 Decision Support Interventions Fact Sheet** — ONC, December 2023. Used for the section 170.315(b)(11) overview and predictive-DSI transparency categories.
+ https://www.healthit.gov/wp-content/uploads/2023/12/HTI-1_DSI_fact-sheet_508.pdf
+- **Requirements for Decision Support Interventions and Predictive Models** — ONC final-rule presentation, January 18, 2024. Used for intended use, population, user, decision role, out-of-scope use, fairness, validation, performance, and maintenance source attributes.
+ https://healthit.gov/wp-content/uploads/2024/01/DSI_HTI1-Final-Rule-Presentation_508.pdf
+- **HTI-1 Final Rule landing page** — ONC. Used to verify official supporting materials and current resource location.
+ https://healthit.gov/regulations/hti-rules/hti-1-final-rule
+
+## GRADE
+
+- **GRADE Working Group** — official overview and minimum requirements. Used for outcome-specific certainty, explicit domain judgments, evidence profiles, and Evidence-to-Decision separation.
+ https://www.gradeworkinggroup.org/
+- **GRADE Book** — official current resource, progressively replacing the prior handbook by 2026. Used as the preferred methodology entry point.
+ https://book.gradepro.org/
+- **GRADE Handbook** — legacy/current transition resource. Retained for comparison where a GRADE Book chapter is not yet available; verify against the GRADE Book.
+ https://gradepro.org/handbook
+
+## AI and Clinical-Study Reporting
+
+- **TRIPOD+AI** — Collins et al., BMJ 2024;385:e078378, published April 16, 2024. Reporting of prediction-model development/evaluation using regression or machine learning.
+ https://www.bmj.com/content/385/bmj-2023-078378
+- **TRIPOD+AI EQUATOR record** — scope, checklist, and related materials.
+ https://www.equator-network.org/reporting-guidelines/tripod-statement
+- **CONSORT-AI** — Liu et al., Nature Medicine 2020;26:1364-1374, published September 9, 2020. AI-intervention randomized-trial reports.
+ https://www.nature.com/articles/s41591-020-1034-x
+- **CONSORT 2025** — Hopewell et al., BMJ 2025;389:e081123, published April 14, 2025. Current generic base statement used with CONSORT-AI.
+ https://www.bmj.com/content/389/bmj-2024-081123
+- **SPIRIT-AI** — Rivera et al., Nature Medicine 2020;26:1351-1363, published September 9, 2020. AI-intervention trial protocols.
+ https://www.nature.com/articles/s41591-020-1037-7
+- **SPIRIT 2025** — current generic base statement used with SPIRIT-AI.
+ https://pubmed.ncbi.nlm.nih.gov/40295741
+- **DECIDE-AI** — Vasey et al., Nature Medicine 2022;28:924-933, published May 18, 2022. Early-stage live clinical evaluation of AI-based decision-support systems. Included for reporting context; live evaluation is outside this skill.
+ https://www.nature.com/articles/s41591-022-01772-9
+- **DECIDE-AI EQUATOR record** — scope and publication links.
+ https://www.equator-network.org/reporting-guidelines/reporting-guideline-for-the-early-stage-clinical-evaluation-of-decision-support-systems-driven-by-artificial-intelligence-decide-ai/
+- **STARD-AI** — Sounderajah et al., Nature Medicine, published September 15, 2025, DOI 10.1038/s41591-025-03953-8. Final reporting guideline for AI diagnostic-accuracy studies.
+ https://www.nature.com/articles/s41591-025-03953-8
+- **STARD-AI EQUATOR record** — final status, scope, citation, and checklist location.
+ https://www.equator-network.org/reporting-guidelines/the-stard-ai-reporting-guideline-for-diagnostic-accuracy-studies-using-artificial-intelligence/
+
+## Prediction-Model Risk of Bias
+
+- **PROBAST+AI** — Moons et al., BMJ 2025;388:e082505, published March 24, 2025. Current quality/risk-of-bias/applicability tool for regression and AI prediction models; separates development from evaluation and uses participants/data sources, predictors, outcome, and analysis domains.
+ https://pubmed.ncbi.nlm.nih.gov/40127903
+- **PROBAST+AI project site** — tool resources and updates.
+ https://www.probast.org/probast_ai
+
+## Privacy and De-identification
+
+- **HHS Guidance Regarding Methods for De-identification of PHI** — official OCR guidance; page current March 20, 2026 in extraction. Used for Expert Determination, Safe Harbor, actual knowledge, derivatives, and free-text cautions.
+ https://www.hhs.gov/hipaa/for-professionals/special-topics/de-identification/index.html
+- **45 CFR 164.514** — current eCFR text for de-identification and related requirements.
+ https://www.ecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-E/section-164.514
+
+## ICH
+
+- **ICH E6(R3) consolidated Step 4 guideline** — final version adopted June 16, 2026, consolidating principles, Annex 1, and Annex 2. Used for quality by design, fit-for-purpose data, oversight, privacy, auditability, and modern trial settings.
+ https://database.ich.org/sites/default/files/ICH%20E6(R3)_Step4_FinalConsolidatedGuideline_2026_0616_.pdf
+- **ICH E9(R1) Addendum on Estimands and Sensitivity Analysis** — final, adopted November 20, 2019. Used for estimand-led planning and sensitivity analysis.
+ https://database.ich.org/sites/default/files/E9-R1_Step4_Guideline_2019_1203.pdf
+- **ICH efficacy-guideline index** — official status/version cross-check.
+ https://www.ich.org/page/efficacy-guidelines
+
+## Cohort, Survival, and Biomarker Methods
+
+- **STROBE** — official reporting guidance for observational studies.
+ https://www.strobe-statement.org/
+- **RECORD** — reporting extension for routinely collected health data.
+ https://www.record-statement.org/
+- **REMARK** — reporting recommendations for tumor-marker prognostic studies.
+ https://www.equator-network.org/reporting-guidelines/reporting-recommendations-for-tumour-marker-prognostic-studies-remark
+- **FDA-NIH BEST Resource** — living biomarker and endpoint terminology resource, 2016 onward.
+ https://www.ncbi.nlm.nih.gov/books/NBK326791/
+- **External validation of clinical prediction models** — Riley et al., BMJ 2024;384:e074820, published January 15, 2024. Used for locked-model evaluation, calibration, discrimination, utility, and transparent reporting.
+ https://www.bmj.com/content/384/bmj-2023-074820
+- **External-validation sample size** — Riley et al., Statistics in Medicine 2021. Used to reject blanket event-count rules and emphasize precision targets.
+ https://pmc.ncbi.nlm.nih.gov/articles/PMC8352630
+- **Calibration: the Achilles heel of predictive analytics** — Van Calster et al., BMC Medicine 2019. Used for calibration assessment and interpretation.
+ https://pubmed.ncbi.nlm.nih.gov/31842878
+- **Restricted mean survival time** — Royston and Parmar, BMC Medical Research Methodology 2013;13:152. Used as an alternative population-level summary when proportional hazards is doubtful.
+ https://pubmed.ncbi.nlm.nih.gov/24314264/
+- **Competing risks introduction** — Austin, Lee, and Fine, Circulation 2016;133:601-609. Used to distinguish cause-specific hazards, subdistribution hazards, and cumulative incidence.
+ https://pubmed.ncbi.nlm.nih.gov/26858290/
+- **Fine-Gray reporting recommendations** — Austin and Fine, Statistics in Medicine 2017;36:4391-4400. Used for careful interpretation of subdistribution hazard models.
+ https://pmc.ncbi.nlm.nih.gov/articles/PMC5698744
+
+## Deliberately Out of Scope
+
+HL7 CDS Hooks, SMART on FHIR, and FHIR implementation guidance were not
+added because the version 2.0 safety redesign deliberately removes
+recommendation-oriented and live CDS behavior. It produces offline
+research/governance artifacts only; implementation guidance would conflict
+with the hard boundary.
+
+No source requiring an API key, external model, image generator, or network call is used at runtime.
diff --git a/skills/clinical-decision-support/references/study_reporting.md b/skills/clinical-decision-support/references/study_reporting.md
new file mode 100644
index 00000000..86f9da24
--- /dev/null
+++ b/skills/clinical-decision-support/references/study_reporting.md
@@ -0,0 +1,134 @@
+# Study Reporting and Appraisal
+
+Checked 2026-07-23.
+
+## First Principle
+
+Choose by study purpose, design, and evaluation stage. A reporting guideline states what to report; it does not prove that the study was well designed, unbiased, clinically useful, safe, or effective.
+
+Use risk-of-bias/applicability tools separately and preserve human judgments.
+
+## Selection Map
+
+| Study or artifact | Primary framework | Important companion |
+|---|---|---|
+| Observational cohort/case-control/cross-sectional | STROBE | RECORD for routinely collected data |
+| Prediction model development or evaluation | TRIPOD+AI | PROBAST+AI |
+| Tumor prognostic marker | REMARK | Appropriate risk-of-bias and assay guidance |
+| Diagnostic accuracy | STARD | STARD-AI when the index test uses AI |
+| Randomized AI intervention protocol | Current SPIRIT base | SPIRIT-AI extension |
+| Randomized AI intervention report | Current CONSORT base | CONSORT-AI extension |
+| Early-stage live AI support evaluation | DECIDE-AI | Design-specific guideline |
+| Evidence profile | GRADE | Design-specific risk-of-bias tools |
+
+## Observational Data
+
+### STROBE
+
+STROBE addresses reporting of cohort, case-control, and cross-sectional studies. Use the design-specific checklist and explanation material from the [STROBE site](https://www.strobe-statement.org/).
+
+### RECORD
+
+RECORD extends STROBE for routinely collected health data such as administrative, EHR, primary-care surveillance, and registry data. It emphasizes code lists/algorithms, database linkage, selection, cleaning, and data-access transparency. See the [RECORD site](https://www.record-statement.org/).
+
+Neither framework authorizes this skill to read EHR rows.
+
+## Prediction Models
+
+### TRIPOD+AI
+
+[TRIPOD+AI](https://www.bmj.com/content/385/bmj-2023-078378), published April 16, 2024, updates reporting guidance for development and evaluation of clinical prediction models using regression or machine-learning methods. It primarily targets non-generative models.
+
+Report, at minimum:
+
+- intended use, target population, outcome, horizon, and setting;
+- data sources, eligibility, sampling, and preprocessing;
+- predictor/outcome definitions and timing;
+- missing data;
+- sample-size rationale;
+- full model specification or access;
+- internal-validation method;
+- discrimination and calibration with uncertainty;
+- external validation and transportability;
+- subgroup performance and fairness considerations;
+- intended user, presentation, and limitations.
+
+### PROBAST+AI
+
+[PROBAST+AI](https://pubmed.ncbi.nlm.nih.gov/40127903), published March 24, 2025, replaces the original PROBAST for broad prediction-model assessment. It has two distinct parts:
+
+- **model development** — quality and applicability;
+- **model evaluation** — risk of bias and applicability.
+
+Both parts use four domains:
+
+1. participants and data sources;
+2. predictors;
+3. outcome;
+4. analysis.
+
+Applicability is assessed for participants/data sources, predictors, and outcome. Do not average signaling questions into a score. Domain and overall judgments require knowledgeable assessors and rationale.
+
+## Biomarker Studies
+
+Use the FDA-NIH [BEST Resource](https://www.ncbi.nlm.nih.gov/books/NBK326791/) for terminology. Distinguish:
+
+- diagnostic;
+- monitoring;
+- pharmacodynamic/response;
+- predictive;
+- prognostic;
+- safety;
+- susceptibility/risk;
+- surrogate endpoint biomarkers.
+
+A biomarker is not itself a measure of how a person feels, functions, or survives. Analytical validation, clinical validation, and clinical utility are distinct.
+
+For tumor prognostic markers, use [REMARK](https://www.equator-network.org/reporting-guidelines/reporting-recommendations-for-tumour-marker-prognostic-studies-remark). Report specimen handling, assay methods, prespecified hypotheses/cut points, participant flow, missing data, analysis, effect estimates, and validation.
+
+## AI Diagnostic Accuracy
+
+[STARD-AI](https://www.nature.com/articles/s41591-025-03953-8) was published September 15, 2025. It adds AI-specific or modified items to STARD 2015 for diagnostic-accuracy studies, including:
+
+- dataset practices;
+- AI index-test description and evaluation;
+- algorithmic bias and fairness;
+- applicability and generalizability;
+- transparent participant flow and reference-standard handling.
+
+Use STARD-AI with STARD. Do not use it for a prognostic prediction model merely because the model returns a class.
+
+## AI Trial Protocols and Reports
+
+[SPIRIT-AI](https://www.nature.com/articles/s41591-020-1037-7) and [CONSORT-AI](https://www.nature.com/articles/s41591-020-1034-x) were published September 9, 2020.
+
+- Use SPIRIT-AI for protocols evaluating an AI intervention.
+- Use CONSORT-AI for reports of randomized trials evaluating an AI intervention.
+- Apply them with the current generic [SPIRIT 2025](https://pubmed.ncbi.nlm.nih.gov/40295741) or [CONSORT 2025](https://www.bmj.com/content/389/bmj-2024-081123) statement, respectively.
+
+AI extensions emphasize the intervention version, input acquisition/quality handling, human-AI interaction, integration requirements, errors/failures, and analysis of performance.
+
+## Early Live Evaluation
+
+[DECIDE-AI](https://www.nature.com/articles/s41591-022-01772-9), published May 18, 2022, covers early-stage live clinical evaluation of AI-based decision-support systems and includes human factors, workflow, safety, and iterative change reporting.
+
+Live evaluation affects real care and is outside this skill's execution boundary. Use the guideline only to understand documentation requirements. Such work requires an approved protocol, qualified investigators, safety oversight, validated systems, applicable authorization, and institutional governance.
+
+## Cross-Cutting Reporting
+
+Always disclose:
+
+- prespecified versus exploratory work;
+- all evaluated outcomes and analyses, including negative results;
+- effect sizes and uncertainty;
+- missingness and exclusions;
+- conflicts, funding, and developer involvement;
+- version and data cut dates;
+- external validation;
+- subgroup representation and performance;
+- calibration and decision thresholds;
+- human-factors methods;
+- incidents, failures, drift, updates, and monitoring;
+- access to protocol, analysis plan, code, model, and data when lawful and feasible.
+
+Never state “reported according to” as proof of adherence without a completed checklist and human verification.
diff --git a/skills/clinical-decision-support/references/survival_analysis.md b/skills/clinical-decision-support/references/survival_analysis.md
new file mode 100644
index 00000000..e8bfaf8e
--- /dev/null
+++ b/skills/clinical-decision-support/references/survival_analysis.md
@@ -0,0 +1,156 @@
+# Survival-Analysis Planning
+
+## Scope
+
+The bundled script validates a plan. It does not read time-to-event rows, fit models, draw curves, or provide an individual prognosis.
+
+## Start With the Estimand
+
+Align:
+
+1. **Population** — eligibility and analysis set.
+2. **Condition/comparison** — intervention, exposure, or groups being contrasted.
+3. **Variable/endpoint** — event definition and ascertainment.
+4. **Intercurrent-event strategy** — how events such as discontinuation, rescue therapy, switching, or competing events relate to the question.
+5. **Population-level summary** — risk, survival probability, restricted mean survival time, hazard contrast, quantile, or another justified measure.
+6. **Time horizon** — clinically and statistically justified.
+
+Record time zero, delayed entry, time scale, follow-up end, and calendar/data-cut date.
+
+## Endpoint Definition
+
+Specify:
+
+- exact event;
+- competing events;
+- recurrent events if relevant;
+- ascertainment schedule and adjudication;
+- censoring rules;
+- handling of same-day and tied events;
+- loss to follow-up;
+- administrative censoring;
+- endpoint changes and versioning.
+
+Do not treat a competing event as ordinary independent censoring when the target is absolute event probability.
+
+## Descriptive Estimation
+
+Kaplan-Meier estimates are suitable for survival from the event of interest under appropriate censoring assumptions. Report:
+
+- numbers at risk;
+- events and censoring;
+- estimates at prespecified times with intervals;
+- median only if estimable;
+- follow-up distribution using an appropriate method;
+- truncation where risk sets become uninformative.
+
+When competing events exist, use cumulative-incidence methods for event probabilities. Naively censoring competing events in Kaplan-Meier can overestimate absolute incidence.
+
+## Group Comparisons
+
+The log-rank test compares event-time distributions and is most powerful under proportional alternatives. It does not quantify an effect. Pre-specify alternatives if curves may cross or effects may be delayed.
+
+A Cox model estimates a hazard contrast conditional on model specification. Before presenting a single hazard ratio:
+
+- assess proportional hazards graphically and analytically;
+- examine functional forms;
+- evaluate influential observations and interactions;
+- define adjustment variables a priori;
+- account for clustering or stratification;
+- avoid interpreting `1 − HR` as a reduction in cumulative risk.
+
+If proportional hazards is doubtful, consider:
+
+- time-varying coefficients;
+- piecewise effects;
+- landmark effects;
+- restricted mean survival time at a justified horizon;
+- survival or cumulative-incidence differences at prespecified times;
+- accelerated failure-time or flexible parametric models.
+
+Report why the selected summary answers the research question.
+
+## Competing Risks
+
+Distinguish:
+
+- cause-specific hazard questions;
+- cumulative-incidence/absolute-risk questions;
+- subdistribution-hazard modeling.
+
+State which question the method answers. A subdistribution hazard ratio is not directly a risk ratio. When modeling several event types, check that resulting probability estimates are coherent.
+
+Primary reference: [Austin, Lee, and Fine, competing risks](https://pubmed.ncbi.nlm.nih.gov/26858290/).
+
+## Bias and Missingness
+
+Plan for:
+
+- informative censoring;
+- delayed entry/left truncation;
+- immortal time;
+- time-dependent confounding;
+- interval censoring;
+- outcome misclassification;
+- missing covariates;
+- competing events;
+- informative visit schedules;
+- treatment switching and rescue treatment;
+- site and calendar effects.
+
+Specify sensitivity analyses tied to plausible departures from assumptions. A “best/worst case” alone is rarely sufficient.
+
+## Prediction Models
+
+For time-to-event prediction:
+
+- preserve the locked model and prediction horizon;
+- evaluate calibration at prespecified times;
+- report time-dependent discrimination with uncertainty;
+- use appropriate handling of censoring;
+- evaluate overall and subgroup performance;
+- perform external validation in relevant settings;
+- avoid selecting a horizon after viewing results.
+
+Use TRIPOD+AI and PROBAST+AI.
+
+## Biomarker Evaluation
+
+For a prognostic biomarker:
+
+- analyze continuous form where scientifically justified;
+- pre-specify transformations and threshold;
+- avoid minimum-p-value cut-point searches;
+- report assay and specimen handling;
+- adjust for established prognostic factors;
+- validate externally.
+
+For a predictive biomarker, estimate and report a treatment-by-biomarker interaction in an appropriate design. Separate prognostic association from treatment-effect modification.
+
+## Uncertainty and Multiplicity
+
+Include:
+
+- confidence intervals for every primary effect;
+- uncertainty in calibration/discrimination;
+- prespecified alpha or interval interpretation;
+- multiplicity strategy for outcomes, times, subgroups, and models;
+- bootstrap or cross-validation details if used;
+- sensitivity analyses;
+- model optimism and overfitting assessment.
+
+Do not turn a threshold-crossing p-value into clinical importance.
+
+## Primary Method Sources
+
+- [ICH E9(R1) estimands and sensitivity analysis](https://database.ich.org/sites/default/files/E9-R1_Step4_Guideline_2019_1203.pdf)
+- [Royston and Parmar, restricted mean survival time](https://pubmed.ncbi.nlm.nih.gov/24314264/)
+- [Austin and Fine, reporting competing-risk analyses](https://pmc.ncbi.nlm.nih.gov/articles/PMC5698744/)
+
+## Plan Validator
+
+```bash
+python3 scripts/survival_plan_validator.py assets/survival_analysis_plan_template.json
+```
+
+An exit code of zero means required planning fields and selected consistency rules passed. It is not statistical approval.
diff --git a/skills/clinical-decision-support/references/treatment_recommendations.md b/skills/clinical-decision-support/references/treatment_recommendations.md
deleted file mode 100644
index 7404cda3..00000000
--- a/skills/clinical-decision-support/references/treatment_recommendations.md
+++ /dev/null
@@ -1,521 +0,0 @@
-# Treatment Recommendations Guide
-
-## Overview
-
-Evidence-based treatment recommendations provide clinicians with systematic guidance for therapeutic decision-making. This guide covers the development, grading, and presentation of clinical recommendations in pharmaceutical and healthcare settings.
-
-## Evidence Grading Systems
-
-### GRADE (Grading of Recommendations Assessment, Development and Evaluation)
-
-**Quality of Evidence Levels**
-
-**High Quality (⊕⊕⊕⊕)**
-- Further research very unlikely to change confidence in estimate
-- Criteria: Well-designed RCTs with consistent results, no serious limitations
-- Example: Multiple large RCTs showing similar treatment effects
-
-**Moderate Quality (⊕⊕⊕○)**
-- Further research likely to have important impact on confidence
-- Criteria: RCTs with limitations OR very strong evidence from observational studies
-- Example: Single RCT or multiple RCTs with some inconsistency
-
-**Low Quality (⊕⊕○○)**
-- Further research very likely to have important impact on confidence
-- Criteria: Observational studies OR RCTs with serious limitations
-- Example: Case-control studies, cohort studies with confounding
-
-**Very Low Quality (⊕○○○)**
-- Estimate of effect very uncertain
-- Criteria: Case series, expert opinion, or very serious limitations
-- Example: Mechanistic reasoning, unsystematic clinical observations
-
-**Strength of Recommendation**
-
-**Strong Recommendation (Grade 1)**
-- Benefits clearly outweigh risks and burdens (or vice versa)
-- Wording: "We recommend..."
-- Implications: Most patients should receive recommended course
-- Symbol: ↑↑ (strong for) or ↓↓ (strong against)
-
-**Conditional/Weak Recommendation (Grade 2)**
-- Trade-offs exist; benefits and risks closely balanced
-- Wording: "We suggest..."
-- Implications: Different choices for different patients; shared decision-making
-- Symbol: ↑ (weak for) or ↓ (weak against)
-
-**GRADE Notation Examples**
-- **1A**: Strong recommendation, high-quality evidence
-- **1B**: Strong recommendation, moderate-quality evidence
-- **2A**: Weak recommendation, high-quality evidence
-- **2B**: Weak recommendation, moderate-quality evidence
-- **2C**: Weak recommendation, low- or very low-quality evidence
-
-### Oxford Centre for Evidence-Based Medicine (CEBM) Levels
-
-**Level 1: Systematic Review/Meta-Analysis**
-- 1a: SR of RCTs
-- 1b: Individual RCT with narrow confidence interval
-- 1c: All-or-none studies (all patients died before treatment, some survive after)
-
-**Level 2: Cohort Studies**
-- 2a: SR of cohort studies
-- 2b: Individual cohort study (including low-quality RCT)
-- 2c: Outcomes research, ecological studies
-
-**Level 3: Case-Control Studies**
-- 3a: SR of case-control studies
-- 3b: Individual case-control study
-
-**Level 4: Case Series**
-- Case series, poor-quality cohort, or case-control studies
-
-**Level 5: Expert Opinion**
-- Mechanism-based reasoning, expert opinion without critical appraisal
-
-**Grades of Recommendation**
-- **Grade A**: Consistent level 1 studies
-- **Grade B**: Consistent level 2 or 3 studies, or extrapolations from level 1
-- **Grade C**: Level 4 studies or extrapolations from level 2 or 3
-- **Grade D**: Level 5 evidence or inconsistent/inconclusive studies
-
-## Treatment Sequencing and Line-of-Therapy
-
-### First-Line Therapy
-
-**Selection Criteria**
-- **Standard of Care**: Guideline-recommended based on phase 3 trials
-- **Patient Factors**: Performance status, comorbidities, organ function
-- **Disease Factors**: Stage, molecular profile, aggressiveness
-- **Goals**: Cure (adjuvant/neoadjuvant), prolonged remission, symptom control
-
-**First-Line Options Documentation**
-```
-First-Line Treatment Options:
-
-Option 1: Regimen A (NCCN Category 1, ESMO I-A)
-- Evidence: Phase 3 RCT (n=1000), median PFS 12 months vs 8 months (HR 0.6, p<0.001)
-- Population: PD-L1 ≥50%, EGFR/ALK negative
-- Toxicity Profile: Immune-related AEs (15% grade 3-4)
-- Recommendation Strength: 1A (strong, high-quality evidence)
-
-Option 2: Regimen B (NCCN Category 1, ESMO I-A)
-- Evidence: Phase 3 RCT (n=800), median PFS 10 months vs 8 months (HR 0.7, p=0.003)
-- Population: All patients, no biomarker selection
-- Toxicity Profile: Hematologic toxicity (25% grade 3-4)
-- Recommendation Strength: 1A (strong, high-quality evidence)
-```
-
-### Second-Line and Beyond
-
-**Second-Line Selection**
-- **Prior Response**: Duration of response to first-line
-- **Progression Pattern**: Oligoprogression vs widespread progression
-- **Residual Toxicity**: Recovery from first-line toxicities
-- **Biomarker Evolution**: Acquired resistance mechanisms
-- **Clinical Trial Availability**: Novel agents in development
-
-**Treatment History Documentation**
-```
-Prior Therapies:
-1. First-Line: Pembrolizumab (12 cycles)
- - Best Response: Partial response (-45% tumor burden)
- - PFS: 14 months
- - Discontinuation Reason: Progressive disease
- - Residual Toxicity: Grade 1 hypothyroidism (on levothyroxine)
-
-2. Second-Line: Docetaxel + ramucirumab (6 cycles)
- - Best Response: Stable disease
- - PFS: 5 months
- - Discontinuation Reason: Progressive disease
- - Residual Toxicity: Grade 2 peripheral neuropathy
-
-Current Consideration: Third-Line Options
-- Clinical trial vs platinum-based chemotherapy
-```
-
-### Maintenance Therapy
-
-**Indications**
-- Consolidation after response to induction therapy
-- Prevention of progression without continuous cytotoxic treatment
-- Bridging to definitive therapy (e.g., transplant)
-
-**Evidence Requirements**
-- PFS benefit demonstrated in randomized trials
-- Tolerable long-term toxicity profile
-- Quality of life preserved or improved
-
-## Biomarker-Guided Therapy Selection
-
-### Companion Diagnostics
-
-**FDA-Approved Biomarker-Drug Pairs**
-
-**Required Testing (Treatment-Specific)**
-- **ALK rearrangement → Alectinib, Brigatinib, Lorlatinib** (NSCLC)
-- **EGFR exon 19 del/L858R → Osimertinib** (NSCLC)
-- **BRAF V600E → Dabrafenib + Trametinib** (Melanoma, NSCLC, CRC)
-- **HER2 amplification/3+ → Trastuzumab, Pertuzumab** (Breast, Gastric)
-- **PD-L1 ≥50% → Pembrolizumab monotherapy** (NSCLC first-line)
-
-**Complementary Diagnostics (Informative but not Required)**
-- **PD-L1 1-49%**: Combination immunotherapy preferred
-- **TMB-high**: May predict immunotherapy benefit (investigational)
-- **MSI-H/dMMR**: Pembrolizumab approved across tumor types
-
-### Biomarker Testing Algorithms
-
-**NSCLC Biomarker Panel**
-```
-Reflex Testing at Diagnosis:
-✓ EGFR mutations (exons 18, 19, 20, 21)
-✓ ALK rearrangement (IHC or FISH)
-✓ ROS1 rearrangement (FISH or NGS)
-✓ BRAF V600E mutation
-✓ PD-L1 IHC (22C3 or SP263)
-✓ Consider: Comprehensive NGS panel
-
-If EGFR+ on Osimertinib progression:
-✓ Liquid biopsy for T790M (if first/second-gen TKI)
-✓ Tissue biopsy for resistance mechanisms
-✓ MET amplification, HER2 amplification, SCLC transformation
-```
-
-**Breast Cancer Biomarker Algorithm**
-```
-Initial Diagnosis:
-✓ ER/PR IHC
-✓ HER2 IHC and FISH (if 2+)
-✓ Ki-67 proliferation index
-
-If Metastatic ER+/HER2-:
-✓ ESR1 mutations (liquid biopsy after progression on AI)
-✓ PIK3CA mutations (for alpelisib eligibility)
-✓ BRCA1/2 germline testing (for PARP inhibitor eligibility)
-✓ PD-L1 testing (if considering immunotherapy combinations)
-```
-
-### Actionable Alterations
-
-**Tier I: FDA-Approved Targeted Therapy**
-- Strong evidence from prospective trials
-- Guideline-recommended
-- Examples: EGFR exon 19 deletion, HER2 amplification, ALK fusion
-
-**Tier II: Clinical Trial or Off-Label Use**
-- Emerging evidence, clinical trial preferred
-- Examples: NTRK fusion (larotrectinib), RET fusion (selpercatinib)
-
-**Tier III: Biological Plausibility**
-- Preclinical evidence only
-- Clinical trial enrollment strongly recommended
-- Examples: Novel kinase fusions, rare resistance mutations
-
-## Combination Therapy Protocols
-
-### Rationale for Combinations
-
-**Mechanisms**
-- **Non-Overlapping Toxicity**: Maximize dose intensity of each agent
-- **Synergistic Activity**: Enhanced efficacy beyond additive effects
-- **Complementary Mechanisms**: Target multiple pathways simultaneously
-- **Prevent Resistance**: Decrease selection pressure for resistant clones
-
-**Combination Design Principles**
-- **Sequential**: Induction then consolidation (different regimens)
-- **Concurrent**: Administered together for synergy
-- **Alternating**: Rotate regimens to minimize resistance
-- **Intermittent**: Pulse dosing vs continuous exposure
-
-### Drug Interaction Assessment
-
-**Pharmacokinetic Interactions**
-- **CYP450 Induction/Inhibition**: Check for drug-drug interactions
-- **Transporter Interactions**: P-gp, BCRP, OATP substrates/inhibitors
-- **Protein Binding**: Highly protein-bound drugs (warfarin caution)
-- **Renal/Hepatic Clearance**: Avoid multiple renally cleared agents
-
-**Pharmacodynamic Interactions**
-- **Additive Toxicity**: Avoid overlapping adverse events (e.g., QTc prolongation)
-- **Antagonism**: Ensure mechanisms are complementary, not opposing
-- **Dose Modifications**: Pre-defined dose reduction schedules for combinations
-
-### Combination Documentation
-
-```
-Combination Regimen: Drug A + Drug B
-
-Rationale:
-- Phase 3 RCT demonstrated PFS benefit (16 vs 11 months, HR 0.62, p<0.001)
-- Complementary mechanisms: Drug A (VEGF inhibitor) + Drug B (immune checkpoint inhibitor)
-- Non-overlapping toxicity profiles
-
-Dosing:
-- Drug A: 10 mg/kg IV every 3 weeks
-- Drug B: 1200 mg IV every 3 weeks
-- Continue until progression or unacceptable toxicity
-
-Key Toxicities:
-- Hypertension (Drug A): 30% grade 3-4, manage with antihypertensives
-- Immune-related AEs (Drug B): 15% grade 3-4, corticosteroid management
-- No significant pharmacokinetic interactions observed
-
-Monitoring:
-- Blood pressure: Daily for first month, then weekly
-- Thyroid function: Every 6 weeks
-- Liver enzymes: Before each cycle
-- Imaging: Every 6 weeks (RECIST v1.1)
-```
-
-## Monitoring and Follow-up Schedules
-
-### On-Treatment Monitoring
-
-**Laboratory Monitoring**
-```
-Test Baseline Cycle 1 Cycle 2+ Rationale
-CBC with differential ✓ Weekly Day 1 Myelosuppression risk
-Comprehensive panel ✓ Day 1 Day 1 Electrolytes, renal, hepatic
-Thyroid function ✓ - Q6 weeks Immunotherapy
-Lipase/amylase ✓ - As needed Pancreatitis risk
-Troponin/BNP ✓* - As needed Cardiotoxicity risk
-(*if cardiotoxic agent)
-```
-
-**Imaging Assessment**
-```
-Modality Baseline Follow-up Criteria
-CT chest/abd/pelvis ✓ Every 6-9 weeks RECIST v1.1
-Brain MRI ✓* Every 12 weeks If CNS metastases
-Bone scan ✓** Every 12-24 weeks If bone metastases
-PET/CT ✓*** Response assessment Lymphoma (Lugano criteria)
-(*if CNS mets, **if bone mets, ***if PET-avid tumor)
-```
-
-**Clinical Assessment**
-```
-Assessment Frequency Notes
-ECOG performance status Every visit Decline may warrant dose modification
-Vital signs Every visit Blood pressure for anti-VEGF agents
-Weight Every visit Cachexia, fluid retention
-Symptom assessment Every visit PRO-CTCAE questionnaire
-Physical exam Every visit Target lesions, new symptoms
-```
-
-### Dose Modification Guidelines
-
-**Hematologic Toxicity**
-```
-ANC and Platelet Counts Action
-ANC ≥1.5 AND platelets ≥100k Treat at full dose
-ANC 1.0-1.5 OR platelets 75-100k Delay 1 week, recheck
-ANC 0.5-1.0 OR platelets 50-75k Delay treatment, G-CSF support, reduce dose 20%
-ANC <0.5 OR platelets <50k Hold treatment, G-CSF, transfusion PRN, reduce 40%
-
-Febrile Neutropenia Hold treatment, hospitalize, antibiotics, G-CSF
- Reduce dose 20-40% on recovery, consider prophylactic G-CSF
-```
-
-**Non-Hematologic Toxicity**
-```
-Adverse Event Grade 1 Grade 2 Grade 3 Grade 4
-Diarrhea Continue Continue with Hold until ≤G1, Hold, hospitalize
- loperamide reduce 20% Consider discontinuation
-Rash Continue Continue with Hold until ≤G1, Discontinue
- topical Rx reduce 20%
-Hepatotoxicity Continue Repeat in 1 wk, Hold until ≤G1, Discontinue permanently
- hold if worsening reduce 20-40%
-Pneumonitis Continue Hold, consider Hold, corticosteroids, Discontinue, high-dose
- corticosteroids discontinue if no improvement steroids
-```
-
-### Post-Treatment Surveillance
-
-**Disease Monitoring**
-```
-Time After Treatment Imaging Frequency Labs Clinical
-Year 1 Every 3 months Every 3 months Every 3 months
-Year 2 Every 3-4 months Every 3-4 months Every 3-4 months
-Years 3-5 Every 6 months Every 6 months Every 6 months
-Year 5+ Annually Annually Annually
-
-Earlier imaging if symptoms suggest recurrence
-```
-
-**Survivorship Care**
-```
-Surveillance Frequency Duration
-Disease monitoring Per schedule above Lifelong or until recurrence
-Late toxicity screening Annually Lifelong
- - Cardiac function Every 1-2 years If anthracycline/trastuzumab
- - Pulmonary function As clinically indicated If bleomycin/radiation
- - Neuropathy Symptom-based Peripheral neuropathy history
- - Secondary malignancy Age-appropriate screening Lifelong (increased risk)
-Genetic counseling One time If hereditary cancer syndrome
-Psychosocial support As needed Depression, anxiety, PTSD screening
-```
-
-## Special Populations
-
-### Elderly Patients (≥65-70 years)
-
-**Considerations**
-- **Reduced organ function**: Adjust for renal/hepatic impairment
-- **Polypharmacy**: Drug-drug interaction risk
-- **Frailty**: Geriatric assessment (G8, VES-13, CARG score)
-- **Goals of care**: Quality of life vs survival, functional independence
-
-**Modifications**
-- Dose reductions: 20-25% reduction for frail patients
-- Longer intervals: Every 4 weeks instead of every 3 weeks
-- Less aggressive regimens: Single-agent vs combination therapy
-- Supportive care: Increased monitoring, G-CSF prophylaxis
-
-### Renal Impairment
-
-**Dose Adjustments by eGFR**
-```
-eGFR (mL/min/1.73m²) Category Action
-≥90 Normal Standard dosing
-60-89 Mild Standard dosing (most agents)
-30-59 Moderate Dose reduce renally cleared drugs 25-50%
-15-29 Severe Dose reduce 50-75%, avoid nephrotoxic agents
-<15 (dialysis) ESRD Avoid most agents, case-by-case decisions
-```
-
-**Renally Cleared Agents Requiring Adjustment**
-- Carboplatin (Calvert formula: AUC × [GFR + 25])
-- Methotrexate (reduce dose 50-75% if CrCl <60)
-- Capecitabine (reduce dose 25-50% if CrCl 30-50)
-
-### Hepatic Impairment
-
-**Dose Adjustments by Bili and AST/ALT**
-```
-Category Bilirubin AST/ALT Action
-Normal ≤ULN ≤ULN Standard dosing
-Mild (Child A) 1-1.5× ULN Any Reduce dose 25% for hepatically metabolized
-Moderate (Child B) 1.5-3× ULN Any Reduce dose 50%, consider alternative
-Severe (Child C) >3× ULN Any Avoid most agents, case-by-case
-```
-
-**Hepatically Metabolized Agents Requiring Adjustment**
-- Docetaxel (reduce 25-50% if bilirubin elevated)
-- Irinotecan (reduce 50% if bilirubin 1.5-3× ULN)
-- Tyrosine kinase inhibitors (most metabolized by CYP3A4, reduce by 50%)
-
-### Pregnancy and Fertility
-
-**Contraception Requirements**
-- Effective contraception required during treatment and 6-12 months after
-- Two methods recommended for highly teratogenic agents
-- Male patients: Contraception if partner of childbearing potential
-
-**Fertility Preservation**
-- Oocyte/embryo cryopreservation (females, before gonadotoxic therapy)
-- Sperm banking (males, before alkylating agents, platinum)
-- GnRH agonists (ovarian suppression, controversial efficacy)
-- Referral to reproductive endocrinology before treatment
-
-**Pregnancy Management**
-- Avoid chemotherapy in first trimester (organogenesis)
-- Selective agents safe in second/third trimester (case-by-case)
-- Multidisciplinary team: oncology, maternal-fetal medicine, neonatology
-
-## Clinical Trial Considerations
-
-### When to Recommend Clinical Trials
-
-**Ideal Scenarios**
-- No standard therapy available (rare diseases, refractory settings)
-- Multiple equivalent standard options (patient preference for novel agent)
-- Standard therapy failed (second-line and beyond)
-- High-risk disease (adjuvant trials for improved outcomes)
-
-**Trial Selection Criteria**
-- **Phase**: Phase 1 (dose-finding, safety), Phase 2 (efficacy signal), Phase 3 (comparative effectiveness)
-- **Eligibility**: Match patient to inclusion/exclusion criteria
-- **Mechanism**: Novel vs established mechanism, biological rationale
-- **Sponsor**: Academic vs industry, trial design quality
-- **Logistics**: Distance to trial site, visit frequency, out-of-pocket costs
-
-### Shared Decision-Making
-
-**Informing Patients**
-- Natural history without treatment
-- Standard treatment options with evidence, benefits, risks
-- Clinical trial options (if available)
-- Goals of care alignment
-- Patient values and preferences
-
-**Decision Aids**
-- Visual representations of benefit (icon arrays)
-- Number needed to treat calculations
-- Quality of life trade-offs
-- Decisional conflict scales
-
-## Documentation Standards
-
-### Treatment Plan Documentation
-
-```
-TREATMENT PLAN
-
-Diagnosis: [Disease, stage, molecular profile]
-
-Goals of Therapy:
-☐ Curative intent
-☐ Prolonged disease control
-☑ Palliation and quality of life
-
-Recommended Regimen: [Name] (NCCN Category 1, GRADE 1A)
-
-Evidence Basis:
-- Primary study: [Citation], Phase 3 RCT, n=XXX
-- Primary endpoint: PFS 12 months vs 8 months (HR 0.6, 95% CI 0.45-0.80, p<0.001)
-- Secondary endpoints: OS 24 vs 20 months (HR 0.75, p=0.02), ORR 60% vs 40%
-- Safety: Grade 3-4 AEs 35%, discontinuation rate 12%
-
-Dosing Schedule:
-- Drug A: XX mg IV day 1
-- Drug B: XX mg PO days 1-21
-- Cycle length: 21 days
-- Planned cycles: Until progression or unacceptable toxicity
-
-Premedications:
-- Dexamethasone 8 mg IV (anti-emetic)
-- Ondansetron 16 mg IV (anti-emetic)
-- Diphenhydramine 25 mg IV (hypersensitivity prophylaxis)
-
-Monitoring Plan: [See schedule above]
-
-Dose Modification Plan: [See guidelines above]
-
-Alternative Options Discussed:
-- Option 2: [Alternative regimen], GRADE 1B
-- Clinical trial: [Trial name/number], Phase 2, novel agent
-- Best supportive care
-
-Patient Decision: Proceed with recommended regimen
-
-Informed Consent: Obtained for chemotherapy, risks/benefits discussed
-
-Date: [Date]
-Provider: [Name, credentials]
-```
-
-## Quality Metrics
-
-### Treatment Recommendation Quality Indicators
-
-- Evidence grading provided for all recommendations
-- Multiple options presented when equivalent evidence exists
-- Toxicity profiles clearly described
-- Monitoring plans specified
-- Dose modification guidelines included
-- Special populations addressed (elderly, renal/hepatic impairment)
-- Clinical trial options mentioned when appropriate
-- Shared decision-making documented
-- Goals of care aligned with treatment intensity
-
diff --git a/skills/clinical-decision-support/scripts/_common.py b/skills/clinical-decision-support/scripts/_common.py
new file mode 100644
index 00000000..af2d8d49
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/_common.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python3
+"""Shared bounded local-file utilities for research-only CDS helpers."""
+
+from __future__ import annotations
+
+import json
+import math
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Iterable
+
+MAX_INPUT_BYTES = 1_000_000
+MAX_TEXT_LENGTH = 4_000
+MAX_SOURCES = 200
+
+PERSON_LEVEL_KEYS = {
+ "address",
+ "date_of_birth",
+ "dob",
+ "email",
+ "full_name",
+ "individual_record",
+ "individual_records",
+ "medical_record_number",
+ "mrn",
+ "note_text",
+ "person_name",
+ "patient",
+ "patient_data",
+ "patient_id",
+ "patient_record",
+ "patient_records",
+ "phone",
+ "raw_data",
+ "raw_rows",
+ "record_id",
+ "social_security_number",
+ "ssn",
+}
+
+
+class InputError(ValueError):
+ """Raised for unsafe, malformed, or out-of-bounds input."""
+
+
+@dataclass
+class IssueLog:
+ """Deterministic validation findings."""
+
+ errors: list[str] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+ info: list[str] = field(default_factory=list)
+
+ @property
+ def ok(self) -> bool:
+ return not self.errors
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "status": "pass" if self.ok else "fail",
+ "errors": self.errors,
+ "warnings": self.warnings,
+ "info": self.info,
+ "disclaimer": (
+ "Structural checks only; not a clinical, privacy, regulatory, "
+ "legal, or compliance determination."
+ ),
+ }
+
+
+def _reject_nonlocal_path(raw: str) -> None:
+ lowered = raw.strip().lower()
+ if not lowered:
+ raise InputError("Path must not be empty")
+ if "\x00" in raw or "://" in lowered or lowered.startswith("\\\\"):
+ raise InputError("Only local filesystem paths are allowed")
+
+
+def local_input_path(raw: str, suffixes: Iterable[str] | None = None) -> Path:
+ """Resolve a bounded, regular, non-symlink local input file."""
+
+ _reject_nonlocal_path(raw)
+ path = Path(raw).expanduser()
+ if path.is_symlink():
+ raise InputError("Symlink inputs are not allowed")
+ resolved = path.resolve()
+ if not resolved.is_file():
+ raise InputError(f"Input is not a regular file: {path}")
+ if suffixes and resolved.suffix.lower() not in {s.lower() for s in suffixes}:
+ raise InputError(f"Unsupported input suffix: {resolved.suffix}")
+ size = resolved.stat().st_size
+ if size > MAX_INPUT_BYTES:
+ raise InputError(f"Input exceeds {MAX_INPUT_BYTES} bytes")
+ return resolved
+
+
+def local_output_path(raw: str, suffixes: Iterable[str] | None = None) -> Path:
+ """Resolve a local output whose parent already exists."""
+
+ _reject_nonlocal_path(raw)
+ path = Path(raw).expanduser()
+ if path.exists() and path.is_symlink():
+ raise InputError("Symlink outputs are not allowed")
+ resolved = path.resolve()
+ if not resolved.parent.is_dir():
+ raise InputError("Output parent directory must already exist")
+ if suffixes and resolved.suffix.lower() not in {s.lower() for s in suffixes}:
+ raise InputError(f"Unsupported output suffix: {resolved.suffix}")
+ return resolved
+
+
+def load_json_object(raw_path: str) -> dict[str, Any]:
+ """Load one bounded UTF-8 JSON object."""
+
+ path = local_input_path(raw_path, {".json"})
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise InputError(f"Invalid UTF-8 JSON: {exc}") from exc
+ if not isinstance(value, dict):
+ raise InputError("Top-level JSON value must be an object")
+ ensure_no_person_level_keys(value)
+ return value
+
+
+def ensure_no_person_level_keys(value: Any, location: str = "$") -> None:
+ """Reject common person-level fields anywhere in a JSON document."""
+
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ normalized = str(key).strip().lower()
+ if normalized in PERSON_LEVEL_KEYS:
+ raise InputError(
+ f"Person-level or raw-data key is prohibited at {location}.{key}"
+ )
+ ensure_no_person_level_keys(nested, f"{location}.{key}")
+ elif isinstance(value, list):
+ for index, nested in enumerate(value):
+ ensure_no_person_level_keys(nested, f"{location}[{index}]")
+
+
+def write_json(raw_path: str, payload: dict[str, Any]) -> None:
+ path = local_output_path(raw_path, {".json"})
+ text = json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
+ path.write_text(text, encoding="utf-8")
+
+
+def write_text(raw_path: str, text: str, suffixes: Iterable[str]) -> None:
+ path = local_output_path(raw_path, suffixes)
+ path.write_text(text, encoding="utf-8")
+
+
+def require_nonempty_text(
+ value: Any, field_name: str, *, max_length: int = MAX_TEXT_LENGTH
+) -> str:
+ if not isinstance(value, str) or not value.strip():
+ raise InputError(f"{field_name} must be non-empty text")
+ text = value.strip()
+ if len(text) > max_length:
+ raise InputError(f"{field_name} exceeds {max_length} characters")
+ return text
+
+
+def require_list(value: Any, field_name: str, *, maximum: int) -> list[Any]:
+ if not isinstance(value, list):
+ raise InputError(f"{field_name} must be a list")
+ if len(value) > maximum:
+ raise InputError(f"{field_name} exceeds {maximum} entries")
+ return value
+
+
+def finite_number(value: Any, field_name: str) -> float:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise InputError(f"{field_name} must be numeric")
+ result = float(value)
+ if not math.isfinite(result):
+ raise InputError(f"{field_name} must be finite")
+ return result
+
+
+def nonnegative_int(value: Any, field_name: str) -> int:
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+ raise InputError(f"{field_name} must be a non-negative integer")
+ return value
+
+
+def source_ids(document: dict[str, Any]) -> set[str]:
+ sources = require_list(document.get("sources"), "sources", maximum=MAX_SOURCES)
+ identifiers: set[str] = set()
+ for index, source in enumerate(sources):
+ if not isinstance(source, dict):
+ raise InputError(f"sources[{index}] must be an object")
+ identifier = require_nonempty_text(
+ source.get("id"), f"sources[{index}].id", max_length=100
+ )
+ require_nonempty_text(
+ source.get("citation"), f"sources[{index}].citation", max_length=1_000
+ )
+ if identifier in identifiers:
+ raise InputError(f"Duplicate source id: {identifier}")
+ identifiers.add(identifier)
+ return identifiers
+
+
+def validate_references(
+ references: Any, known_sources: set[str], field_name: str
+) -> list[str]:
+ values = require_list(references, field_name, maximum=50)
+ normalized: list[str] = []
+ for index, value in enumerate(values):
+ identifier = require_nonempty_text(
+ value, f"{field_name}[{index}]", max_length=100
+ )
+ if identifier not in known_sources:
+ raise InputError(f"{field_name} references unknown source id: {identifier}")
+ normalized.append(identifier)
+ if not normalized:
+ raise InputError(f"{field_name} must cite at least one source")
+ return normalized
+
+
+def print_report(report: dict[str, Any]) -> None:
+ print(json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False))
diff --git a/skills/clinical-decision-support/scripts/biomarker_classifier.py b/skills/clinical-decision-support/scripts/biomarker_classifier.py
deleted file mode 100755
index 8ef0a878..00000000
--- a/skills/clinical-decision-support/scripts/biomarker_classifier.py
+++ /dev/null
@@ -1,384 +0,0 @@
-#!/usr/bin/env python3
-"""
-Biomarker-Based Patient Stratification and Classification
-
-Performs patient stratification based on biomarker profiles with:
-- Binary classification (biomarker+/-)
-- Multi-class molecular subtypes
-- Continuous biomarker scoring
-- Correlation with clinical outcomes
-
-Dependencies: pandas, numpy, scipy, scikit-learn (optional for clustering)
-"""
-
-import pandas as pd
-import numpy as np
-from scipy import stats
-import argparse
-from pathlib import Path
-
-
-def classify_binary_biomarker(data, biomarker_col, threshold,
- above_label='Biomarker+', below_label='Biomarker-'):
- """
- Binary classification based on biomarker threshold.
-
- Parameters:
- data: DataFrame
- biomarker_col: Column name for biomarker values
- threshold: Cut-point value
- above_label: Label for values >= threshold
- below_label: Label for values < threshold
-
- Returns:
- DataFrame with added 'biomarker_class' column
- """
-
- data = data.copy()
- data['biomarker_class'] = data[biomarker_col].apply(
- lambda x: above_label if x >= threshold else below_label
- )
-
- return data
-
-
-def classify_pd_l1_tps(data, pd_l1_col='pd_l1_tps'):
- """
- Classify PD-L1 Tumor Proportion Score into clinical categories.
-
- Categories:
- - Negative: <1%
- - Low: 1-49%
- - High: >=50%
-
- Returns:
- DataFrame with 'pd_l1_category' column
- """
-
- data = data.copy()
-
- def categorize(tps):
- if tps < 1:
- return 'PD-L1 Negative (<1%)'
- elif tps < 50:
- return 'PD-L1 Low (1-49%)'
- else:
- return 'PD-L1 High (≥50%)'
-
- data['pd_l1_category'] = data[pd_l1_col].apply(categorize)
-
- # Distribution
- print("\nPD-L1 TPS Distribution:")
- print(data['pd_l1_category'].value_counts())
-
- return data
-
-
-def classify_her2_status(data, ihc_col='her2_ihc', fish_col='her2_fish'):
- """
- Classify HER2 status based on IHC and FISH results (ASCO/CAP guidelines).
-
- IHC Scores: 0, 1+, 2+, 3+
- FISH: Positive, Negative (if IHC 2+)
-
- Classification:
- - HER2-positive: IHC 3+ OR IHC 2+/FISH+
- - HER2-negative: IHC 0/1+ OR IHC 2+/FISH-
- - HER2-low: IHC 1+ or IHC 2+/FISH- (subset of HER2-negative)
-
- Returns:
- DataFrame with 'her2_status' and 'her2_low' columns
- """
-
- data = data.copy()
-
- def classify_her2(row):
- ihc = row[ihc_col]
- fish = row.get(fish_col, None)
-
- if ihc == '3+':
- status = 'HER2-positive'
- her2_low = False
- elif ihc == '2+':
- if fish == 'Positive':
- status = 'HER2-positive'
- her2_low = False
- elif fish == 'Negative':
- status = 'HER2-negative'
- her2_low = True # HER2-low
- else:
- status = 'HER2-equivocal (FISH needed)'
- her2_low = False
- elif ihc == '1+':
- status = 'HER2-negative'
- her2_low = True # HER2-low
- else: # IHC 0
- status = 'HER2-negative'
- her2_low = False
-
- return pd.Series({'her2_status': status, 'her2_low': her2_low})
-
- data[['her2_status', 'her2_low']] = data.apply(classify_her2, axis=1)
-
- print("\nHER2 Status Distribution:")
- print(data['her2_status'].value_counts())
- print(f"\nHER2-low (IHC 1+ or 2+/FISH-): {data['her2_low'].sum()} patients")
-
- return data
-
-
-def classify_breast_cancer_subtype(data, er_col='er_positive', pr_col='pr_positive',
- her2_col='her2_positive'):
- """
- Classify breast cancer into molecular subtypes.
-
- Subtypes:
- - HR+/HER2-: Luminal (ER+ and/or PR+, HER2-)
- - HER2+: Any HER2-positive (regardless of HR status)
- - Triple-negative: ER-, PR-, HER2-
-
- Returns:
- DataFrame with 'bc_subtype' column
- """
-
- data = data.copy()
-
- def get_subtype(row):
- er = row[er_col]
- pr = row[pr_col]
- her2 = row[her2_col]
-
- if her2:
- if er or pr:
- return 'HR+/HER2+ (Luminal B HER2+)'
- else:
- return 'HR-/HER2+ (HER2-enriched)'
- elif er or pr:
- return 'HR+/HER2- (Luminal)'
- else:
- return 'Triple-Negative'
-
- data['bc_subtype'] = data.apply(get_subtype, axis=1)
-
- print("\nBreast Cancer Subtype Distribution:")
- print(data['bc_subtype'].value_counts())
-
- return data
-
-
-def correlate_biomarker_outcome(data, biomarker_col, outcome_col, biomarker_type='binary'):
- """
- Assess correlation between biomarker and clinical outcome.
-
- Parameters:
- biomarker_col: Biomarker variable
- outcome_col: Outcome variable
- biomarker_type: 'binary', 'categorical', 'continuous'
-
- Returns:
- Statistical test results
- """
-
- print(f"\nCorrelation Analysis: {biomarker_col} vs {outcome_col}")
- print("="*60)
-
- # Remove missing data
- analysis_data = data[[biomarker_col, outcome_col]].dropna()
-
- if biomarker_type == 'binary' or biomarker_type == 'categorical':
- # Cross-tabulation
- contingency = pd.crosstab(analysis_data[biomarker_col], analysis_data[outcome_col])
- print("\nContingency Table:")
- print(contingency)
-
- # Chi-square test
- chi2, p_value, dof, expected = stats.chi2_contingency(contingency)
-
- print(f"\nChi-square test:")
- print(f" χ² = {chi2:.2f}, df = {dof}, p = {p_value:.4f}")
-
- # Odds ratio if 2x2 table
- if contingency.shape == (2, 2):
- a, b = contingency.iloc[0, :]
- c, d = contingency.iloc[1, :]
- or_value = (a * d) / (b * c) if b * c > 0 else np.inf
-
- # Confidence interval for OR (log method)
- log_or = np.log(or_value)
- se_log_or = np.sqrt(1/a + 1/b + 1/c + 1/d)
- ci_lower = np.exp(log_or - 1.96 * se_log_or)
- ci_upper = np.exp(log_or + 1.96 * se_log_or)
-
- print(f"\nOdds Ratio: {or_value:.2f} (95% CI {ci_lower:.2f}-{ci_upper:.2f})")
-
- elif biomarker_type == 'continuous':
- # Correlation coefficient
- r, p_value = stats.pearsonr(analysis_data[biomarker_col], analysis_data[outcome_col])
-
- print(f"\nPearson correlation:")
- print(f" r = {r:.3f}, p = {p_value:.4f}")
-
- # Also report Spearman for robustness
- rho, p_spearman = stats.spearmanr(analysis_data[biomarker_col], analysis_data[outcome_col])
- print(f"Spearman correlation:")
- print(f" ρ = {rho:.3f}, p = {p_spearman:.4f}")
-
- return p_value
-
-
-def stratify_cohort_report(data, stratification_var, output_dir='stratification_report'):
- """
- Generate comprehensive stratification report.
-
- Parameters:
- data: DataFrame with patient data
- stratification_var: Column name for stratification
- output_dir: Output directory for reports
- """
-
- output_dir = Path(output_dir)
- output_dir.mkdir(parents=True, exist_ok=True)
-
- print(f"\nCOHORT STRATIFICATION REPORT")
- print("="*60)
- print(f"Stratification Variable: {stratification_var}")
- print(f"Total Patients: {len(data)}")
-
- # Group distribution
- distribution = data[stratification_var].value_counts()
- print(f"\nGroup Distribution:")
- for group, count in distribution.items():
- pct = count / len(data) * 100
- print(f" {group}: {count} ({pct:.1f}%)")
-
- # Save distribution
- distribution.to_csv(output_dir / 'group_distribution.csv')
-
- # Compare baseline characteristics across groups
- print(f"\nBaseline Characteristics by {stratification_var}:")
-
- results = []
-
- # Continuous variables
- continuous_vars = data.select_dtypes(include=[np.number]).columns.tolist()
- continuous_vars = [v for v in continuous_vars if v != stratification_var]
-
- for var in continuous_vars[:5]: # Limit to first 5 for demo
- print(f"\n{var}:")
- for group in distribution.index:
- group_data = data[data[stratification_var] == group][var].dropna()
- print(f" {group}: median {group_data.median():.1f} [IQR {group_data.quantile(0.25):.1f}-{group_data.quantile(0.75):.1f}]")
-
- # Statistical test
- if len(distribution) == 2:
- groups_list = distribution.index.tolist()
- g1 = data[data[stratification_var] == groups_list[0]][var].dropna()
- g2 = data[data[stratification_var] == groups_list[1]][var].dropna()
- _, p_value = stats.mannwhitneyu(g1, g2, alternative='two-sided')
- print(f" p-value: {p_value:.4f}")
-
- results.append({
- 'Variable': var,
- 'Test': 'Mann-Whitney U',
- 'p_value': p_value,
- 'Significant': 'Yes' if p_value < 0.05 else 'No'
- })
-
- # Save results
- if results:
- df_results = pd.DataFrame(results)
- df_results.to_csv(output_dir / 'statistical_comparisons.csv', index=False)
- print(f"\nStatistical comparison results saved to: {output_dir}/statistical_comparisons.csv")
-
- print(f"\nStratification report complete! Files saved to {output_dir}/")
-
-
-def main():
- parser = argparse.ArgumentParser(description='Biomarker-based patient classification')
- parser.add_argument('input_file', type=str, nargs='?', default=None,
- help='CSV file with patient and biomarker data')
- parser.add_argument('-b', '--biomarker', type=str, default=None,
- help='Biomarker column name for stratification')
- parser.add_argument('-t', '--threshold', type=float, default=None,
- help='Threshold for binary classification')
- parser.add_argument('-o', '--output-dir', type=str, default='stratification',
- help='Output directory')
- parser.add_argument('--example', action='store_true',
- help='Run with example data')
-
- args = parser.parse_args()
-
- # Example data if requested
- if args.example or args.input_file is None:
- print("Generating example dataset...")
- np.random.seed(42)
- n = 80
-
- data = pd.DataFrame({
- 'patient_id': [f'PT{i:03d}' for i in range(1, n+1)],
- 'age': np.random.normal(62, 10, n),
- 'sex': np.random.choice(['Male', 'Female'], n),
- 'pd_l1_tps': np.random.exponential(20, n), # Exponential distribution for PD-L1
- 'tmb': np.random.exponential(8, n), # Mutations per Mb
- 'her2_ihc': np.random.choice(['0', '1+', '2+', '3+'], n, p=[0.6, 0.2, 0.15, 0.05]),
- 'response': np.random.choice(['Yes', 'No'], n, p=[0.4, 0.6]),
- })
-
- # Simulate correlation: higher PD-L1 -> better response
- data.loc[data['pd_l1_tps'] >= 50, 'response'] = np.random.choice(['Yes', 'No'],
- (data['pd_l1_tps'] >= 50).sum(),
- p=[0.65, 0.35])
- else:
- print(f"Loading data from {args.input_file}...")
- data = pd.read_csv(args.input_file)
-
- print(f"Dataset: {len(data)} patients")
- print(f"Columns: {list(data.columns)}")
-
- # PD-L1 classification example
- if 'pd_l1_tps' in data.columns or args.biomarker == 'pd_l1_tps':
- data = classify_pd_l1_tps(data, 'pd_l1_tps')
-
- # Correlate with response if available
- if 'response' in data.columns:
- correlate_biomarker_outcome(data, 'pd_l1_category', 'response', biomarker_type='categorical')
-
- # HER2 classification if columns present
- if 'her2_ihc' in data.columns:
- if 'her2_fish' not in data.columns:
- # Add placeholder FISH for IHC 2+
- data['her2_fish'] = np.nan
- data = classify_her2_status(data, 'her2_ihc', 'her2_fish')
-
- # Generic binary classification if threshold provided
- if args.biomarker and args.threshold is not None:
- print(f"\nBinary classification: {args.biomarker} with threshold {args.threshold}")
- data = classify_binary_biomarker(data, args.biomarker, args.threshold)
- print(data['biomarker_class'].value_counts())
-
- # Generate stratification report
- if args.biomarker:
- stratify_cohort_report(data, args.biomarker, output_dir=args.output_dir)
- elif 'pd_l1_category' in data.columns:
- stratify_cohort_report(data, 'pd_l1_category', output_dir=args.output_dir)
-
- # Save classified data
- output_path = Path(args.output_dir) / 'classified_data.csv'
- data.to_csv(output_path, index=False)
- print(f"\nClassified data saved to: {output_path}")
-
-
-if __name__ == '__main__':
- main()
-
-
-# Example usage:
-# python biomarker_classifier.py data.csv -b pd_l1_tps -t 50 -o classification/
-# python biomarker_classifier.py --example
-#
-# Input CSV format:
-# patient_id,pd_l1_tps,tmb,her2_ihc,response,pfs_months,event
-# PT001,55.5,12.3,1+,Yes,14.2,1
-# PT002,8.2,5.1,0,No,6.5,1
-# ...
-
diff --git a/skills/clinical-decision-support/scripts/build_decision_tree.py b/skills/clinical-decision-support/scripts/build_decision_tree.py
deleted file mode 100755
index 2d3c3b98..00000000
--- a/skills/clinical-decision-support/scripts/build_decision_tree.py
+++ /dev/null
@@ -1,447 +0,0 @@
-#!/usr/bin/env python3
-"""
-Build Clinical Decision Tree Flowcharts in TikZ Format
-
-Generates LaTeX/TikZ code for clinical decision algorithms from
-simple text or YAML descriptions.
-
-Dependencies: pyyaml (optional, for YAML input)
-"""
-
-import argparse
-from pathlib import Path
-import json
-
-
-class DecisionNode:
- """Represents a decision point in the clinical algorithm."""
-
- def __init__(self, question, yes_path=None, no_path=None, node_id=None):
- self.question = question
- self.yes_path = yes_path
- self.no_path = no_path
- self.node_id = node_id or self._generate_id(question)
-
- def _generate_id(self, text):
- """Generate clean node ID from text."""
- return ''.join(c for c in text if c.isalnum())[:15].lower()
-
-
-class ActionNode:
- """Represents an action/outcome in the clinical algorithm."""
-
- def __init__(self, action, urgency='routine', node_id=None):
- self.action = action
- self.urgency = urgency # 'urgent', 'semiurgent', 'routine'
- self.node_id = node_id or self._generate_id(action)
-
- def _generate_id(self, text):
- return ''.join(c for c in text if c.isalnum())[:15].lower()
-
-
-def generate_tikz_header():
- """Generate TikZ preamble with style definitions."""
-
- tikz = """\\documentclass[10pt]{article}
-\\usepackage[margin=0.5in, landscape]{geometry}
-\\usepackage{tikz}
-\\usetikzlibrary{shapes,arrows,positioning}
-\\usepackage{xcolor}
-
-% Color definitions
-\\definecolor{urgentred}{RGB}{220,20,60}
-\\definecolor{actiongreen}{RGB}{0,153,76}
-\\definecolor{decisionyellow}{RGB}{255,193,7}
-\\definecolor{routineblue}{RGB}{100,181,246}
-\\definecolor{headerblue}{RGB}{0,102,204}
-
-% TikZ styles
-\\tikzstyle{startstop} = [rectangle, rounded corners=8pt, minimum width=3cm, minimum height=1cm,
- text centered, draw=black, fill=headerblue!20, font=\\small\\bfseries]
-\\tikzstyle{decision} = [diamond, minimum width=3cm, minimum height=1.2cm, text centered,
- draw=black, fill=decisionyellow!40, font=\\small, aspect=2, inner sep=0pt,
- text width=3.5cm]
-\\tikzstyle{process} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm,
- text centered, draw=black, fill=actiongreen!20, font=\\small]
-\\tikzstyle{urgent} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm,
- text centered, draw=urgentred, line width=1.5pt, fill=urgentred!15,
- font=\\small\\bfseries]
-\\tikzstyle{routine} = [rectangle, rounded corners=4pt, minimum width=3.5cm, minimum height=0.9cm,
- text centered, draw=black, fill=routineblue!20, font=\\small]
-\\tikzstyle{arrow} = [thick,->,>=stealth]
-\\tikzstyle{urgentarrow} = [ultra thick,->,>=stealth,color=urgentred]
-
-\\begin{document}
-
-\\begin{center}
-{\\Large\\bfseries Clinical Decision Algorithm}\\\\[10pt]
-{\\large [TITLE TO BE SPECIFIED]}
-\\end{center}
-
-\\vspace{10pt}
-
-\\begin{tikzpicture}[node distance=2.2cm and 3.5cm, auto]
-
-"""
-
- return tikz
-
-
-def generate_tikz_footer():
- """Generate TikZ closing code."""
-
- tikz = """
-\\end{tikzpicture}
-
-\\end{document}
-"""
-
- return tikz
-
-
-def simple_algorithm_to_tikz(algorithm_text, output_file='algorithm.tex'):
- """
- Convert simple text-based algorithm to TikZ flowchart.
-
- Input format (simple question-action pairs):
- START: Chief complaint
- Q1: High-risk criteria present? -> YES: Immediate action (URGENT) | NO: Continue
- Q2: Risk score >= 3? -> YES: Admit ICU | NO: Outpatient management (ROUTINE)
- END: Final outcome
-
- Parameters:
- algorithm_text: Multi-line string with algorithm
- output_file: Path to save .tex file
- """
-
- tikz_code = generate_tikz_header()
-
- # Parse algorithm text
- lines = [line.strip() for line in algorithm_text.strip().split('\n') if line.strip()]
-
- node_defs = []
- arrow_defs = []
-
- previous_node = None
- node_counter = 0
-
- for line in lines:
- if line.startswith('START:'):
- # Start node
- text = line.replace('START:', '').strip()
- node_id = 'start'
- node_defs.append(f"\\node [startstop] ({node_id}) {{{text}}};")
- previous_node = node_id
- node_counter += 1
-
- elif line.startswith('END:'):
- # End node
- text = line.replace('END:', '').strip()
- node_id = 'end'
-
- # Position relative to previous
- if previous_node:
- node_defs.append(f"\\node [startstop, below=of {previous_node}] ({node_id}) {{{text}}};")
- arrow_defs.append(f"\\draw [arrow] ({previous_node}) -- ({node_id});")
-
- elif line.startswith('Q'):
- # Decision node
- parts = line.split(':', 1)
- if len(parts) < 2:
- continue
-
- question_part = parts[1].split('->')[0].strip()
- node_id = f'q{node_counter}'
-
- # Add decision node
- if previous_node:
- node_defs.append(f"\\node [decision, below=of {previous_node}] ({node_id}) {{{question_part}}};")
- arrow_defs.append(f"\\draw [arrow] ({previous_node}) -- ({node_id});")
- else:
- node_defs.append(f"\\node [decision] ({node_id}) {{{question_part}}};")
-
- # Parse YES and NO branches
- if '->' in line:
- branches = line.split('->')[1].split('|')
-
- for branch in branches:
- branch = branch.strip()
-
- if branch.startswith('YES:'):
- yes_action = branch.replace('YES:', '').strip()
- yes_id = f'yes{node_counter}'
-
- # Check urgency
- if '(URGENT)' in yes_action:
- style = 'urgent'
- yes_action = yes_action.replace('(URGENT)', '').strip()
- arrow_style = 'urgentarrow'
- elif '(ROUTINE)' in yes_action:
- style = 'routine'
- yes_action = yes_action.replace('(ROUTINE)', '').strip()
- arrow_style = 'arrow'
- else:
- style = 'process'
- arrow_style = 'arrow'
-
- node_defs.append(f"\\node [{style}, left=of {node_id}] ({yes_id}) {{{yes_action}}};")
- arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -- node[above] {{Yes}} ({yes_id});")
-
- elif branch.startswith('NO:'):
- no_action = branch.replace('NO:', '').strip()
- no_id = f'no{node_counter}'
-
- # Check urgency
- if '(URGENT)' in no_action:
- style = 'urgent'
- no_action = no_action.replace('(URGENT)', '').strip()
- arrow_style = 'urgentarrow'
- elif '(ROUTINE)' in no_action:
- style = 'routine'
- no_action = no_action.replace('(ROUTINE)', '').strip()
- arrow_style = 'arrow'
- else:
- style = 'process'
- arrow_style = 'arrow'
-
- node_defs.append(f"\\node [{style}, right=of {node_id}] ({no_id}) {{{no_action}}};")
- arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -- node[above] {{No}} ({no_id});")
-
- previous_node = node_id
- node_counter += 1
-
- # Add all nodes and arrows to TikZ
- tikz_code += '\n'.join(node_defs) + '\n\n'
- tikz_code += '% Arrows\n'
- tikz_code += '\n'.join(arrow_defs) + '\n'
-
- tikz_code += generate_tikz_footer()
-
- # Save to file
- with open(output_file, 'w') as f:
- f.write(tikz_code)
-
- print(f"TikZ flowchart saved to: {output_file}")
- print(f"Compile with: pdflatex {output_file}")
-
- return tikz_code
-
-
-def json_to_tikz(json_file, output_file='algorithm.tex'):
- """
- Convert JSON decision tree specification to TikZ flowchart.
-
- JSON format:
- {
- "title": "Algorithm Title",
- "nodes": {
- "start": {"type": "start", "text": "Patient presentation"},
- "q1": {"type": "decision", "text": "Criteria met?", "yes": "action1", "no": "q2"},
- "action1": {"type": "action", "text": "Immediate intervention", "urgency": "urgent"},
- "q2": {"type": "decision", "text": "Score >= 3?", "yes": "action2", "no": "action3"},
- "action2": {"type": "action", "text": "Admit ICU"},
- "action3": {"type": "action", "text": "Outpatient", "urgency": "routine"}
- },
- "start_node": "start"
- }
- """
-
- with open(json_file, 'r') as f:
- spec = json.load(f)
-
- tikz_code = generate_tikz_header()
-
- # Replace title
- title = spec.get('title', 'Clinical Decision Algorithm')
- tikz_code = tikz_code.replace('[TITLE TO BE SPECIFIED]', title)
-
- nodes = spec['nodes']
- start_node = spec.get('start_node', 'start')
-
- # Generate nodes (simplified layout - vertical)
- node_defs = []
- arrow_defs = []
-
- # Track positioning
- previous_node = None
- level = 0
-
- def add_node(node_id, position_rel=None):
- """Recursively add nodes."""
-
- if node_id not in nodes:
- return
-
- node = nodes[node_id]
- node_type = node['type']
- text = node['text']
-
- # Determine TikZ style
- if node_type == 'start' or node_type == 'end':
- style = 'startstop'
- elif node_type == 'decision':
- style = 'decision'
- elif node_type == 'action':
- urgency = node.get('urgency', 'normal')
- if urgency == 'urgent':
- style = 'urgent'
- elif urgency == 'routine':
- style = 'routine'
- else:
- style = 'process'
- else:
- style = 'process'
-
- # Position node
- if position_rel:
- node_def = f"\\node [{style}, {position_rel}] ({node_id}) {{{text}}};"
- else:
- node_def = f"\\node [{style}] ({node_id}) {{{text}}};"
-
- node_defs.append(node_def)
-
- # Add arrows for decision nodes
- if node_type == 'decision':
- yes_target = node.get('yes')
- no_target = node.get('no')
-
- if yes_target:
- # Determine arrow style based on target urgency
- target_node = nodes.get(yes_target, {})
- arrow_style = 'urgentarrow' if target_node.get('urgency') == 'urgent' else 'arrow'
- arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -| node[near start, above] {{Yes}} ({yes_target});")
-
- if no_target:
- target_node = nodes.get(no_target, {})
- arrow_style = 'urgentarrow' if target_node.get('urgency') == 'urgent' else 'arrow'
- arrow_defs.append(f"\\draw [{arrow_style}] ({node_id}) -| node[near start, above] {{No}} ({no_target});")
-
- # Simple layout - just list nodes (manual positioning in JSON works better for complex trees)
- for node_id in nodes.keys():
- add_node(node_id)
-
- tikz_code += '\n'.join(node_defs) + '\n\n'
- tikz_code += '% Arrows\n'
- tikz_code += '\n'.join(arrow_defs) + '\n'
-
- tikz_code += generate_tikz_footer()
-
- # Save
- with open(output_file, 'w') as f:
- f.write(tikz_code)
-
- print(f"TikZ flowchart saved to: {output_file}")
- return tikz_code
-
-
-def create_example_json():
- """Create example JSON specification for testing."""
-
- example = {
- "title": "Acute Chest Pain Management Algorithm",
- "nodes": {
- "start": {
- "type": "start",
- "text": "Patient with\\nchest pain"
- },
- "q1": {
- "type": "decision",
- "text": "STEMI\\ncriteria?",
- "yes": "stemi_action",
- "no": "q2"
- },
- "stemi_action": {
- "type": "action",
- "text": "Activate cath lab\\nAspirin, heparin\\nPrimary PCI",
- "urgency": "urgent"
- },
- "q2": {
- "type": "decision",
- "text": "High-risk\\nfeatures?",
- "yes": "admit",
- "no": "q3"
- },
- "admit": {
- "type": "action",
- "text": "Admit CCU\\nSerial troponins\\nEarly angiography"
- },
- "q3": {
- "type": "decision",
- "text": "TIMI\\nscore 0-1?",
- "yes": "lowrisk",
- "no": "moderate"
- },
- "lowrisk": {
- "type": "action",
- "text": "Observe 6-12h\\nStress test\\nOutpatient f/u",
- "urgency": "routine"
- },
- "moderate": {
- "type": "action",
- "text": "Admit telemetry\\nMedical management\\nRisk stratification"
- }
- },
- "start_node": "start"
- }
-
- return example
-
-
-def main():
- parser = argparse.ArgumentParser(description='Build clinical decision tree flowcharts')
- parser.add_argument('-i', '--input', type=str, default=None,
- help='Input file (JSON format)')
- parser.add_argument('-o', '--output', type=str, default='clinical_algorithm.tex',
- help='Output .tex file')
- parser.add_argument('--example', action='store_true',
- help='Generate example algorithm')
- parser.add_argument('--text', type=str, default=None,
- help='Simple text algorithm (see format in docstring)')
-
- args = parser.parse_args()
-
- if args.example:
- print("Generating example algorithm...")
- example_spec = create_example_json()
-
- # Save example JSON
- with open('example_algorithm.json', 'w') as f:
- json.dump(example_spec, f, indent=2)
- print("Example JSON saved to: example_algorithm.json")
-
- # Generate TikZ from example
- json_to_tikz('example_algorithm.json', args.output)
-
- elif args.text:
- print("Generating algorithm from text...")
- simple_algorithm_to_tikz(args.text, args.output)
-
- elif args.input:
- print(f"Generating algorithm from {args.input}...")
- if args.input.endswith('.json'):
- json_to_tikz(args.input, args.output)
- else:
- with open(args.input, 'r') as f:
- text = f.read()
- simple_algorithm_to_tikz(text, args.output)
-
- else:
- print("No input provided. Use --example to generate example, --text for simple text, or -i for JSON input.")
- print("\nSimple text format:")
- print("START: Patient presentation")
- print("Q1: Criteria met? -> YES: Action (URGENT) | NO: Continue")
- print("Q2: Score >= 3? -> YES: Admit | NO: Outpatient (ROUTINE)")
- print("END: Follow-up")
-
-
-if __name__ == '__main__':
- main()
-
-
-# Example usage:
-# python build_decision_tree.py --example
-# python build_decision_tree.py -i algorithm_spec.json -o my_algorithm.tex
-#
-# Then compile:
-# pdflatex clinical_algorithm.tex
-
diff --git a/skills/clinical-decision-support/scripts/cohort_table_generator.py b/skills/clinical-decision-support/scripts/cohort_table_generator.py
new file mode 100644
index 00000000..87934b31
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/cohort_table_generator.py
@@ -0,0 +1,288 @@
+#!/usr/bin/env python3
+"""Generate disclosure-controlled tables from bounded aggregate cohort summaries."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import io
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ nonnegative_int,
+ require_list,
+ require_nonempty_text,
+ write_text,
+)
+
+MAX_GROUPS = 12
+MAX_ROWS = 200
+
+
+def _format_count(count: int, denominator: int) -> str:
+ percentage = 100.0 * count / denominator if denominator else 0.0
+ return f"{count}/{denominator} ({percentage:.1f}%)"
+
+
+def _build_table(
+ document: dict[str, Any], minimum: int
+) -> tuple[IssueLog, list[str], list[list[str]], list[str]]:
+ log = IssueLog()
+ notes: list[str] = []
+ headers: list[str] = ["Characteristic"]
+ output_rows: list[list[str]] = []
+
+ metadata = document.get("metadata")
+ if not isinstance(metadata, dict):
+ raise InputError("metadata must be an object")
+ for field in ("table_id", "title", "purpose", "population", "data_cut_date"):
+ require_nonempty_text(metadata.get(field), f"metadata.{field}")
+ if metadata.get("data_level") not in {"aggregate", "synthetic"}:
+ log.errors.append("metadata.data_level must be aggregate or synthetic")
+ if metadata.get("raw_rows_supplied") is not False:
+ log.errors.append("metadata.raw_rows_supplied must be false")
+ if metadata.get("patient_care_use") is not False:
+ log.errors.append("metadata.patient_care_use must be false")
+ require_nonempty_text(
+ metadata.get("disclosure_policy"), "metadata.disclosure_policy"
+ )
+ require_nonempty_text(
+ metadata.get("human_review"), "metadata.human_review"
+ )
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ if review.get("required") is not True:
+ log.errors.append("human_review.required must be true")
+ roles = require_list(review.get("roles"), "human_review.roles", maximum=20)
+ if not roles:
+ log.errors.append("At least one human-review role is required")
+ for index, role in enumerate(roles):
+ require_nonempty_text(role, f"human_review.roles[{index}]")
+ if review.get("completed") is not True:
+ log.warnings.append("Human review is not recorded as complete")
+
+ governance = document.get("governance")
+ if not isinstance(governance, dict):
+ raise InputError("governance must be an object")
+ for field in (
+ "version",
+ "owner",
+ "change_summary",
+ "auditability",
+ "monitoring",
+ ):
+ require_nonempty_text(governance.get(field), f"governance.{field}")
+
+ groups = require_list(document.get("groups"), "groups", maximum=MAX_GROUPS)
+ if not groups:
+ raise InputError("At least one group is required")
+ group_map: dict[str, dict[str, Any]] = {}
+ for index, group in enumerate(groups):
+ field = f"groups[{index}]"
+ if not isinstance(group, dict):
+ raise InputError(f"{field} must be an object")
+ identifier = require_nonempty_text(
+ group.get("id"), f"{field}.id", max_length=50
+ )
+ label = require_nonempty_text(
+ group.get("label"), f"{field}.label", max_length=120
+ )
+ n = nonnegative_int(group.get("n"), f"{field}.n")
+ if n == 0:
+ raise InputError(f"{field}.n must be positive")
+ if identifier in group_map:
+ raise InputError(f"Duplicate group id: {identifier}")
+ group_map[identifier] = {"label": label, "n": n}
+ headers.append(f"{label} (n={n if n >= minimum else 'SUPP'})")
+
+ rows = require_list(document.get("rows"), "rows", maximum=MAX_ROWS)
+ if not rows:
+ raise InputError("At least one aggregate table row is required")
+ for row_index, row in enumerate(rows):
+ field = f"rows[{row_index}]"
+ if not isinstance(row, dict):
+ raise InputError(f"{field} must be an object")
+ if "p_value" in row or "statistical_test" in row:
+ raise InputError(
+ f"{field} contains inferential fields; this helper creates descriptive tables only"
+ )
+ label = require_nonempty_text(row.get("label"), f"{field}.label", max_length=200)
+ level = row.get("level")
+ if level is not None:
+ label = f" {require_nonempty_text(level, f'{field}.level', max_length=120)}"
+ row_type = require_nonempty_text(
+ row.get("type"), f"{field}.type", max_length=30
+ )
+ if row_type not in {"categorical", "continuous", "header"}:
+ raise InputError(f"{field}.type is unsupported")
+ values = row.get("values")
+ if row_type == "header":
+ output_rows.append([label] + [""] * len(group_map))
+ continue
+ if not isinstance(values, dict):
+ raise InputError(f"{field}.values must be an object")
+ if set(values) != set(group_map):
+ raise InputError(f"{field}.values must contain exactly all group ids")
+
+ cells: dict[str, str] = {}
+ primary_suppressed: set[str] = set()
+ eligible_counts: dict[str, int] = {}
+ for group_id, group in group_map.items():
+ value = values[group_id]
+ cell_field = f"{field}.values.{group_id}"
+ if not isinstance(value, dict):
+ raise InputError(f"{cell_field} must be an object")
+ group_n = group["n"]
+ if group_n < minimum:
+ cells[group_id] = "SUPP"
+ primary_suppressed.add(group_id)
+ continue
+ if row_type == "categorical":
+ count = nonnegative_int(value.get("count"), f"{cell_field}.count")
+ denominator = nonnegative_int(
+ value.get("denominator"), f"{cell_field}.denominator"
+ )
+ missing = nonnegative_int(
+ value.get("missing", group_n - denominator),
+ f"{cell_field}.missing",
+ )
+ if denominator == 0 or count > denominator:
+ raise InputError(f"{cell_field} has inconsistent counts")
+ if denominator + missing != group_n:
+ raise InputError(
+ f"{cell_field} denominator plus missing must equal group n"
+ )
+ if (
+ 0 < count < minimum
+ or 0 < denominator - count < minimum
+ or 0 < missing < minimum
+ ):
+ cells[group_id] = "SUPP"
+ primary_suppressed.add(group_id)
+ else:
+ cells[group_id] = _format_count(count, denominator)
+ eligible_counts[group_id] = count
+ else:
+ summarized_n = nonnegative_int(value.get("n"), f"{cell_field}.n")
+ missing = nonnegative_int(
+ value.get("missing", group_n - summarized_n),
+ f"{cell_field}.missing",
+ )
+ if summarized_n + missing != group_n:
+ raise InputError(
+ f"{cell_field} n plus missing must equal group n"
+ )
+ summary = require_nonempty_text(
+ value.get("summary"), f"{cell_field}.summary", max_length=120
+ )
+ if summarized_n < minimum or 0 < missing < minimum:
+ cells[group_id] = "SUPP"
+ primary_suppressed.add(group_id)
+ else:
+ cells[group_id] = f"{summary}; n={summarized_n}"
+
+ if (
+ row_type == "categorical"
+ and len(primary_suppressed) == 1
+ and eligible_counts
+ ):
+ complementary = min(eligible_counts, key=eligible_counts.get)
+ cells[complementary] = "SUPP-C"
+ notes.append(
+ f"Complementary suppression applied to row {row_index + 1}."
+ )
+ output_rows.append([label] + [cells[group_id] for group_id in group_map])
+
+ notes.extend(
+ [
+ f"Cells use a minimum threshold of {minimum}. SUPP is primary suppression; SUPP-C is complementary suppression.",
+ "Thresholding is an operational disclosure control, not a HIPAA or privacy determination.",
+ "Descriptive aggregate table only; no patient-specific or clinical recommendation output.",
+ ]
+ )
+ if log.ok:
+ log.info.append("Disclosure-controlled aggregate table generated")
+ return log, headers, output_rows, notes
+
+
+def _to_markdown(
+ title: str, headers: list[str], rows: list[list[str]], notes: list[str]
+) -> str:
+ lines = [
+ f"# {title}",
+ "",
+ "**Research aggregate only — not for patient care or live clinical use.**",
+ "",
+ "| " + " | ".join(headers) + " |",
+ "|" + "|".join("---" for _ in headers) + "|",
+ ]
+ lines.extend("| " + " | ".join(row) + " |" for row in rows)
+ lines.extend(["", "## Disclosure notes"])
+ lines.extend(f"- {note}" for note in notes)
+ return "\n".join(lines) + "\n"
+
+
+def _to_csv(headers: list[str], rows: list[list[str]], notes: list[str]) -> str:
+ stream = io.StringIO()
+ writer = csv.writer(stream, lineterminator="\n")
+ writer.writerow(headers)
+ writer.writerows(rows)
+ writer.writerow([])
+ writer.writerow(["Disclosure notes"])
+ for note in notes:
+ writer.writerow([note])
+ return stream.getvalue()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Generate a bounded descriptive cohort table from local aggregate JSON "
+ "with primary and complementary disclosure suppression."
+ )
+ )
+ parser.add_argument("input", help="Local aggregate JSON")
+ parser.add_argument("-o", "--output", help="Optional .md or .csv output")
+ parser.add_argument(
+ "--min-cell-size",
+ type=int,
+ default=11,
+ help="Operational suppression threshold (default: 11; not a legal standard)",
+ )
+ args = parser.parse_args()
+ if not 2 <= args.min_cell_size <= 1_000:
+ parser.error("--min-cell-size must be between 2 and 1000")
+
+ try:
+ document = load_json_object(args.input)
+ log, headers, rows, notes = _build_table(document, args.min_cell_size)
+ title = require_nonempty_text(document["metadata"].get("title"), "metadata.title")
+ if args.output:
+ if args.output.lower().endswith(".csv"):
+ text = _to_csv(headers, rows, notes)
+ write_text(args.output, text, {".csv"})
+ elif args.output.lower().endswith(".md"):
+ text = _to_markdown(title, headers, rows, notes)
+ write_text(args.output, text, {".md"})
+ else:
+ raise InputError("Output must end in .md or .csv")
+ else:
+ print(_to_markdown(title, headers, rows, notes), end="")
+ if log.errors:
+ for error in log.errors:
+ print(f"ERROR: {error}", file=sys.stderr)
+ return 1
+ except InputError as exc:
+ print(f"ERROR: {exc}", file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/create_cohort_tables.py b/skills/clinical-decision-support/scripts/create_cohort_tables.py
deleted file mode 100755
index d8299867..00000000
--- a/skills/clinical-decision-support/scripts/create_cohort_tables.py
+++ /dev/null
@@ -1,524 +0,0 @@
-#!/usr/bin/env python3
-"""
-Generate Clinical Cohort Tables for Baseline Characteristics and Outcomes
-
-Creates publication-ready tables with:
-- Baseline demographics (Table 1 style)
-- Efficacy outcomes
-- Safety/adverse events
-- Statistical comparisons between groups
-
-Dependencies: pandas, numpy, scipy
-"""
-
-import pandas as pd
-import numpy as np
-from scipy import stats
-from pathlib import Path
-import argparse
-
-
-def calculate_p_value(data, variable, group_col='group', var_type='categorical'):
- """
- Calculate appropriate p-value for group comparison.
-
- Parameters:
- data: DataFrame
- variable: Column name to compare
- group_col: Grouping variable
- var_type: 'categorical', 'continuous_normal', 'continuous_nonnormal'
-
- Returns:
- p-value (float)
- """
-
- groups = data[group_col].unique()
-
- if len(groups) != 2:
- return np.nan # Only handle 2-group comparisons
-
- group1_data = data[data[group_col] == groups[0]][variable].dropna()
- group2_data = data[data[group_col] == groups[1]][variable].dropna()
-
- if var_type == 'categorical':
- # Chi-square or Fisher's exact test
- contingency = pd.crosstab(data[variable], data[group_col])
-
- # Check if Fisher's exact is needed (expected count < 5)
- if contingency.min().min() < 5:
- # Fisher's exact (2x2 only)
- if contingency.shape == (2, 2):
- _, p_value = stats.fisher_exact(contingency)
- else:
- # Use chi-square but note limitation
- _, p_value, _, _ = stats.chi2_contingency(contingency)
- else:
- _, p_value, _, _ = stats.chi2_contingency(contingency)
-
- elif var_type == 'continuous_normal':
- # Independent t-test
- _, p_value = stats.ttest_ind(group1_data, group2_data, equal_var=False)
-
- elif var_type == 'continuous_nonnormal':
- # Mann-Whitney U test
- _, p_value = stats.mannwhitneyu(group1_data, group2_data, alternative='two-sided')
-
- else:
- raise ValueError("var_type must be 'categorical', 'continuous_normal', or 'continuous_nonnormal'")
-
- return p_value
-
-
-def format_continuous_variable(data, variable, group_col, distribution='normal'):
- """
- Format continuous variable for table display.
-
- Returns:
- Dictionary with formatted strings for each group and p-value
- """
-
- groups = data[group_col].unique()
- results = {}
-
- for group in groups:
- group_data = data[data[group_col] == group][variable].dropna()
-
- if distribution == 'normal':
- # Mean ± SD
- mean = group_data.mean()
- std = group_data.std()
- results[group] = f"{mean:.1f} ± {std:.1f}"
- else:
- # Median [IQR]
- median = group_data.median()
- q1 = group_data.quantile(0.25)
- q3 = group_data.quantile(0.75)
- results[group] = f"{median:.1f} [{q1:.1f}-{q3:.1f}]"
-
- # Calculate p-value
- var_type = 'continuous_normal' if distribution == 'normal' else 'continuous_nonnormal'
- p_value = calculate_p_value(data, variable, group_col, var_type)
- results['p_value'] = f"{p_value:.3f}" if p_value < 0.001 else f"{p_value:.2f}" if p_value < 1.0 else "—"
-
- return results
-
-
-def format_categorical_variable(data, variable, group_col):
- """
- Format categorical variable for table display.
-
- Returns:
- List of dictionaries for each category with counts and percentages
- """
-
- groups = data[group_col].unique()
- categories = data[variable].dropna().unique()
-
- results = []
-
- for category in categories:
- row = {'category': category}
-
- for group in groups:
- group_data = data[data[group_col] == group]
- count = (group_data[variable] == category).sum()
- total = group_data[variable].notna().sum()
- percentage = (count / total * 100) if total > 0 else 0
- row[group] = f"{count} ({percentage:.0f}%)"
-
- results.append(row)
-
- # Calculate p-value for overall categorical variable
- p_value = calculate_p_value(data, variable, group_col, 'categorical')
- results[0]['p_value'] = f"{p_value:.3f}" if p_value < 0.001 else f"{p_value:.2f}" if p_value < 1.0 else "—"
-
- return results
-
-
-def generate_baseline_table(data, group_col='group', output_file='table1_baseline.csv'):
- """
- Generate Table 1: Baseline characteristics.
-
- Customize the variables list for your specific cohort.
- """
-
- groups = data[group_col].unique()
-
- # Initialize results list
- table_rows = []
-
- # Header row
- header = {
- 'Characteristic': 'Characteristic',
- **{group: f"{group} (n={len(data[data[group_col]==group])})" for group in groups},
- 'p_value': 'p-value'
- }
- table_rows.append(header)
-
- # Age (continuous)
- if 'age' in data.columns:
- age_results = format_continuous_variable(data, 'age', group_col, distribution='nonnormal')
- row = {'Characteristic': 'Age, years (median [IQR])'}
- for group in groups:
- row[group] = age_results[group]
- row['p_value'] = age_results['p_value']
- table_rows.append(row)
-
- # Sex (categorical)
- if 'sex' in data.columns:
- table_rows.append({'Characteristic': 'Sex, n (%)', **{g: '' for g in groups}, 'p_value': ''})
- sex_results = format_categorical_variable(data, 'sex', group_col)
- for sex_row in sex_results:
- row = {'Characteristic': f" {sex_row['category']}"}
- for group in groups:
- row[group] = sex_row[group]
- row['p_value'] = sex_row.get('p_value', '')
- table_rows.append(row)
-
- # ECOG Performance Status (categorical)
- if 'ecog_ps' in data.columns:
- table_rows.append({'Characteristic': 'ECOG PS, n (%)', **{g: '' for g in groups}, 'p_value': ''})
- ecog_results = format_categorical_variable(data, 'ecog_ps', group_col)
- for ecog_row in ecog_results:
- row = {'Characteristic': f" {ecog_row['category']}"}
- for group in groups:
- row[group] = ecog_row[group]
- row['p_value'] = ecog_row.get('p_value', '')
- table_rows.append(row)
-
- # Convert to DataFrame and save
- df_table = pd.DataFrame(table_rows)
- df_table.to_csv(output_file, index=False)
- print(f"Baseline characteristics table saved to: {output_file}")
-
- return df_table
-
-
-def generate_efficacy_table(data, group_col='group', output_file='table2_efficacy.csv'):
- """
- Generate efficacy outcomes table.
-
- Expected columns:
- - best_response: CR, PR, SD, PD
- - Additional binary outcomes (response, disease_control, etc.)
- """
-
- groups = data[group_col].unique()
- table_rows = []
-
- # Header
- header = {
- 'Outcome': 'Outcome',
- **{group: f"{group} (n={len(data[data[group_col]==group])})" for group in groups},
- 'p_value': 'p-value'
- }
- table_rows.append(header)
-
- # Objective Response Rate (ORR = CR + PR)
- if 'best_response' in data.columns:
- for group in groups:
- group_data = data[data[group_col] == group]
- cr_pr = ((group_data['best_response'] == 'CR') | (group_data['best_response'] == 'PR')).sum()
- total = len(group_data)
- orr = cr_pr / total * 100
-
- # Calculate exact binomial CI (Clopper-Pearson)
- ci_lower, ci_upper = _binomial_ci(cr_pr, total)
-
- if group == groups[0]:
- orr_row = {'Outcome': 'ORR, n (%) [95% CI]'}
-
- orr_row[group] = f"{cr_pr} ({orr:.0f}%) [{ci_lower:.0f}-{ci_upper:.0f}]"
-
- # P-value for ORR difference
- contingency = pd.crosstab(
- data['best_response'].isin(['CR', 'PR']),
- data[group_col]
- )
- _, p_value, _, _ = stats.chi2_contingency(contingency)
- orr_row['p_value'] = f"{p_value:.3f}" if p_value >= 0.001 else "<0.001"
- table_rows.append(orr_row)
-
- # Individual response categories
- for response in ['CR', 'PR', 'SD', 'PD']:
- row = {'Outcome': f" {response}"}
- for group in groups:
- group_data = data[data[group_col] == group]
- count = (group_data['best_response'] == response).sum()
- total = len(group_data)
- pct = count / total * 100
- row[group] = f"{count} ({pct:.0f}%)"
- row['p_value'] = ''
- table_rows.append(row)
-
- # Disease Control Rate (DCR = CR + PR + SD)
- if 'best_response' in data.columns:
- dcr_row = {'Outcome': 'DCR, n (%) [95% CI]'}
- for group in groups:
- group_data = data[data[group_col] == group]
- dcr_count = group_data['best_response'].isin(['CR', 'PR', 'SD']).sum()
- total = len(group_data)
- dcr = dcr_count / total * 100
- ci_lower, ci_upper = _binomial_ci(dcr_count, total)
- dcr_row[group] = f"{dcr_count} ({dcr:.0f}%) [{ci_lower:.0f}-{ci_upper:.0f}]"
-
- # P-value
- contingency = pd.crosstab(
- data['best_response'].isin(['CR', 'PR', 'SD']),
- data[group_col]
- )
- _, p_value, _, _ = stats.chi2_contingency(contingency)
- dcr_row['p_value'] = f"{p_value:.3f}" if p_value >= 0.001 else "<0.001"
- table_rows.append(dcr_row)
-
- # Save table
- df_table = pd.DataFrame(table_rows)
- df_table.to_csv(output_file, index=False)
- print(f"Efficacy table saved to: {output_file}")
-
- return df_table
-
-
-def generate_safety_table(data, ae_columns, group_col='group', output_file='table3_safety.csv'):
- """
- Generate adverse events table.
-
- Parameters:
- data: DataFrame with AE data
- ae_columns: List of AE column names (each should have values 0-5 for CTCAE grades)
- group_col: Grouping variable
- output_file: Output CSV path
- """
-
- groups = data[group_col].unique()
- table_rows = []
-
- # Header
- header = {
- 'Adverse Event': 'Adverse Event',
- **{f'{group}_any': f'Any Grade' for group in groups},
- **{f'{group}_g34': f'Grade 3-4' for group in groups}
- }
-
- for ae in ae_columns:
- if ae not in data.columns:
- continue
-
- row = {'Adverse Event': ae.replace('_', ' ').title()}
-
- for group in groups:
- group_data = data[data[group_col] == group][ae].dropna()
- total = len(group_data)
-
- # Any grade (Grade 1-5)
- any_grade = (group_data > 0).sum()
- any_pct = any_grade / total * 100 if total > 0 else 0
- row[f'{group}_any'] = f"{any_grade} ({any_pct:.0f}%)"
-
- # Grade 3-4
- grade_34 = (group_data >= 3).sum()
- g34_pct = grade_34 / total * 100 if total > 0 else 0
- row[f'{group}_g34'] = f"{grade_34} ({g34_pct:.0f}%)"
-
- table_rows.append(row)
-
- # Save table
- df_table = pd.DataFrame(table_rows)
- df_table.to_csv(output_file, index=False)
- print(f"Safety table saved to: {output_file}")
-
- return df_table
-
-
-def generate_latex_table(df, caption, label='table'):
- """
- Convert DataFrame to LaTeX table code.
-
- Returns:
- String with LaTeX table code
- """
-
- latex_code = "\\begin{table}[H]\n"
- latex_code += "\\centering\n"
- latex_code += "\\small\n"
- latex_code += "\\begin{tabular}{" + "l" * len(df.columns) + "}\n"
- latex_code += "\\toprule\n"
-
- # Header
- header_row = " & ".join([f"\\textbf{{{col}}}" for col in df.columns])
- latex_code += header_row + " \\\\\n"
- latex_code += "\\midrule\n"
-
- # Data rows
- for _, row in df.iterrows():
- # Handle indentation for subcategories (lines starting with spaces)
- first_col = str(row.iloc[0])
- if first_col.startswith(' '):
- first_col = '\\quad ' + first_col.strip()
-
- data_row = [first_col] + [str(val) if pd.notna(val) else '—' for val in row.iloc[1:]]
- latex_code += " & ".join(data_row) + " \\\\\n"
-
- latex_code += "\\bottomrule\n"
- latex_code += "\\end{tabular}\n"
- latex_code += f"\\caption{{{caption}}}\n"
- latex_code += f"\\label{{tab:{label}}}\n"
- latex_code += "\\end{table}\n"
-
- return latex_code
-
-
-def _binomial_ci(successes, trials, confidence=0.95):
- """
- Calculate exact binomial confidence interval (Clopper-Pearson method).
-
- Returns:
- Lower and upper bounds as percentages
- """
-
- if trials == 0:
- return 0.0, 0.0
-
- alpha = 1 - confidence
-
- # Use beta distribution
- from scipy.stats import beta
-
- if successes == 0:
- lower = 0.0
- else:
- lower = beta.ppf(alpha/2, successes, trials - successes + 1)
-
- if successes == trials:
- upper = 1.0
- else:
- upper = beta.ppf(1 - alpha/2, successes + 1, trials - successes)
-
- return lower * 100, upper * 100
-
-
-def create_example_data():
- """Create example dataset for testing."""
-
- np.random.seed(42)
- n = 100
-
- data = pd.DataFrame({
- 'patient_id': [f'PT{i:03d}' for i in range(1, n+1)],
- 'group': np.random.choice(['Biomarker+', 'Biomarker-'], n),
- 'age': np.random.normal(62, 10, n),
- 'sex': np.random.choice(['Male', 'Female'], n),
- 'ecog_ps': np.random.choice(['0-1', '2'], n, p=[0.8, 0.2]),
- 'stage': np.random.choice(['III', 'IV'], n, p=[0.3, 0.7]),
- 'best_response': np.random.choice(['CR', 'PR', 'SD', 'PD'], n, p=[0.05, 0.35, 0.40, 0.20]),
- 'fatigue_grade': np.random.choice([0, 1, 2, 3], n, p=[0.3, 0.4, 0.2, 0.1]),
- 'nausea_grade': np.random.choice([0, 1, 2, 3], n, p=[0.4, 0.35, 0.20, 0.05]),
- 'neutropenia_grade': np.random.choice([0, 1, 2, 3, 4], n, p=[0.5, 0.2, 0.15, 0.10, 0.05]),
- })
-
- return data
-
-
-def main():
- parser = argparse.ArgumentParser(description='Generate clinical cohort tables')
- parser.add_argument('input_file', type=str, nargs='?', default=None,
- help='CSV file with cohort data (if not provided, uses example data)')
- parser.add_argument('-o', '--output-dir', type=str, default='tables',
- help='Output directory (default: tables)')
- parser.add_argument('--group-col', type=str, default='group',
- help='Column name for grouping variable')
- parser.add_argument('--example', action='store_true',
- help='Generate tables using example data')
-
- args = parser.parse_args()
-
- # Create output directory
- output_dir = Path(args.output_dir)
- output_dir.mkdir(parents=True, exist_ok=True)
-
- # Load or create data
- if args.example or args.input_file is None:
- print("Generating example dataset...")
- data = create_example_data()
- else:
- print(f"Loading data from {args.input_file}...")
- data = pd.read_csv(args.input_file)
-
- print(f"Dataset: {len(data)} patients, {len(data[args.group_col].unique())} groups")
- print(f"Groups: {data[args.group_col].value_counts().to_dict()}")
-
- # Generate Table 1: Baseline characteristics
- print("\nGenerating baseline characteristics table...")
- baseline_table = generate_baseline_table(
- data,
- group_col=args.group_col,
- output_file=output_dir / 'table1_baseline.csv'
- )
-
- # Generate LaTeX code for baseline table
- latex_code = generate_latex_table(
- baseline_table,
- caption="Baseline patient demographics and clinical characteristics",
- label="baseline"
- )
- with open(output_dir / 'table1_baseline.tex', 'w') as f:
- f.write(latex_code)
- print(f"LaTeX code saved to: {output_dir}/table1_baseline.tex")
-
- # Generate Table 2: Efficacy outcomes
- if 'best_response' in data.columns:
- print("\nGenerating efficacy outcomes table...")
- efficacy_table = generate_efficacy_table(
- data,
- group_col=args.group_col,
- output_file=output_dir / 'table2_efficacy.csv'
- )
-
- latex_code = generate_latex_table(
- efficacy_table,
- caption="Treatment efficacy outcomes by group",
- label="efficacy"
- )
- with open(output_dir / 'table2_efficacy.tex', 'w') as f:
- f.write(latex_code)
-
- # Generate Table 3: Safety (identify AE columns)
- ae_columns = [col for col in data.columns if col.endswith('_grade')]
- if ae_columns:
- print("\nGenerating safety table...")
- safety_table = generate_safety_table(
- data,
- ae_columns=ae_columns,
- group_col=args.group_col,
- output_file=output_dir / 'table3_safety.csv'
- )
-
- latex_code = generate_latex_table(
- safety_table,
- caption="Treatment-emergent adverse events by group (CTCAE v5.0)",
- label="safety"
- )
- with open(output_dir / 'table3_safety.tex', 'w') as f:
- f.write(latex_code)
-
- print(f"\nAll tables generated successfully in {output_dir}/")
- print("Files created:")
- print(" - table1_baseline.csv / .tex")
- print(" - table2_efficacy.csv / .tex (if response data available)")
- print(" - table3_safety.csv / .tex (if AE data available)")
-
-
-if __name__ == '__main__':
- main()
-
-
-# Example usage:
-# python create_cohort_tables.py cohort_data.csv -o tables/
-# python create_cohort_tables.py --example # Generate example tables
-#
-# Input CSV format:
-# patient_id,group,age,sex,ecog_ps,stage,best_response,fatigue_grade,nausea_grade,...
-# PT001,Biomarker+,65,Male,0-1,IV,PR,1,0,...
-# PT002,Biomarker-,58,Female,0-1,III,SD,2,1,...
-# ...
-
diff --git a/skills/clinical-decision-support/scripts/decision_logic_traceability.py b/skills/clinical-decision-support/scripts/decision_logic_traceability.py
new file mode 100644
index 00000000..d9de7810
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/decision_logic_traceability.py
@@ -0,0 +1,313 @@
+#!/usr/bin/env python3
+"""Validate and export research/governance decision-logic traceability."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import io
+import re
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ validate_references,
+ write_text,
+)
+
+MAX_NODES = 200
+NODE_ID = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{0,63}$")
+ALLOWED_NODE_TYPES = {
+ "input_check",
+ "data_quality_gate",
+ "evidence_rule",
+ "validation_gate",
+ "documentation_gate",
+ "human_review",
+ "release_gate",
+ "monitoring_gate",
+}
+ALLOWED_OUTPUT_KINDS = {
+ "include_evidence",
+ "exclude_evidence",
+ "flag_for_review",
+ "validation_status",
+ "documentation_status",
+ "release_hold",
+ "monitoring_status",
+}
+PROHIBITED_LOGIC = (
+ "diagnose",
+ "prescribe",
+ "administer",
+ "dose ",
+ "dosing",
+ "triage",
+ "urgent",
+ "alarm",
+ "alert clinician",
+ "treatment selection",
+ "therapy recommendation",
+ "bedside",
+ "patient-specific",
+)
+
+
+def _safe_csv(value: Any) -> str:
+ text = str(value).replace("\r", " ").replace("\n", " ")
+ if text.startswith(("=", "+", "-", "@")):
+ return "'" + text
+ return text
+
+
+def _has_cycle(edges: dict[str, list[str]]) -> bool:
+ visiting: set[str] = set()
+ visited: set[str] = set()
+
+ def visit(node: str) -> bool:
+ if node in visiting:
+ return True
+ if node in visited:
+ return False
+ visiting.add(node)
+ for dependency in edges[node]:
+ if visit(dependency):
+ return True
+ visiting.remove(node)
+ visited.add(node)
+ return False
+
+ return any(visit(node) for node in edges)
+
+
+def validate_matrix(
+ document: dict[str, Any]
+) -> tuple[IssueLog, list[dict[str, str]]]:
+ log = IssueLog()
+ normalized: list[dict[str, str]] = []
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version")
+ known_sources = source_ids(document)
+ metadata = document.get("metadata")
+ if not isinstance(metadata, dict):
+ raise InputError("metadata must be an object")
+ for field in (
+ "logic_id",
+ "title",
+ "version",
+ "status",
+ "owner",
+ "purpose",
+ "change_summary",
+ "monitoring_plan",
+ "retirement_criteria",
+ ):
+ require_nonempty_text(metadata.get(field), f"metadata.{field}")
+ if metadata.get("decision_role") != "research_governance_only":
+ log.errors.append(
+ "metadata.decision_role must be research_governance_only"
+ )
+ if metadata.get("data_level") not in {"aggregate", "synthetic", "metadata_only"}:
+ log.errors.append(
+ "metadata.data_level must be aggregate, synthetic, or metadata_only"
+ )
+ if metadata.get("patient_care_use") is not False:
+ log.errors.append("metadata.patient_care_use must be false")
+ if metadata.get("executable_logic") is not False:
+ log.errors.append("metadata.executable_logic must be false")
+
+ nodes = require_list(document.get("nodes"), "nodes", maximum=MAX_NODES)
+ if not nodes:
+ raise InputError("At least one traceability node is required")
+ node_ids: set[str] = set()
+ for index, node in enumerate(nodes):
+ field = f"nodes[{index}]"
+ if not isinstance(node, dict):
+ raise InputError(f"{field} must be an object")
+ node_id = require_nonempty_text(
+ node.get("id"), f"{field}.id", max_length=64
+ )
+ if not NODE_ID.fullmatch(node_id):
+ raise InputError(f"{field}.id has an unsafe or invalid format")
+ if node_id in node_ids:
+ raise InputError(f"Duplicate node id: {node_id}")
+ node_ids.add(node_id)
+
+ edges: dict[str, list[str]] = {}
+ for index, node in enumerate(nodes):
+ field = f"nodes[{index}]"
+ node_id = str(node["id"])
+ node_type = require_nonempty_text(node.get("type"), f"{field}.type")
+ if node_type not in ALLOWED_NODE_TYPES:
+ log.errors.append(f"{field}.type is unsupported")
+ precondition = require_nonempty_text(
+ node.get("precondition"), f"{field}.precondition"
+ )
+ statement = require_nonempty_text(
+ node.get("logic_statement"), f"{field}.logic_statement"
+ )
+ output_kind = require_nonempty_text(
+ node.get("output_kind"), f"{field}.output_kind"
+ )
+ if output_kind not in ALLOWED_OUTPUT_KINDS:
+ log.errors.append(f"{field}.output_kind is unsupported")
+ output_value = require_nonempty_text(
+ node.get("output_value"), f"{field}.output_value"
+ )
+ rationale = require_nonempty_text(
+ node.get("rationale"), f"{field}.rationale"
+ )
+ owner = require_nonempty_text(node.get("owner"), f"{field}.owner")
+ reviewer = require_nonempty_text(
+ node.get("reviewer_role"), f"{field}.reviewer_role"
+ )
+ status = require_nonempty_text(node.get("status"), f"{field}.status")
+ if status not in {"draft", "validated", "retired"}:
+ log.errors.append(f"{field}.status is unsupported")
+ combined = f"{precondition} {statement} {output_value}".lower()
+ found = [phrase for phrase in PROHIBITED_LOGIC if phrase in combined]
+ if found:
+ log.errors.append(
+ f"{field} contains prohibited clinical logic: {', '.join(found)}"
+ )
+
+ dependencies = require_list(
+ node.get("dependency_ids", []),
+ f"{field}.dependency_ids",
+ maximum=30,
+ )
+ normalized_dependencies: list[str] = []
+ for dep_index, dependency in enumerate(dependencies):
+ dep = require_nonempty_text(
+ dependency,
+ f"{field}.dependency_ids[{dep_index}]",
+ max_length=64,
+ )
+ if dep not in node_ids:
+ log.errors.append(f"{field} references unknown dependency: {dep}")
+ if dep == node_id:
+ log.errors.append(f"{field} cannot depend on itself")
+ if dep in node_ids and dep != node_id:
+ normalized_dependencies.append(dep)
+ edges[node_id] = normalized_dependencies
+
+ source_refs = validate_references(
+ node.get("source_ids"), known_sources, f"{field}.source_ids"
+ )
+ tests = require_list(
+ node.get("validation_tests"), f"{field}.validation_tests", maximum=30
+ )
+ if not tests:
+ log.errors.append(f"{field} requires at least one validation test")
+ normalized_tests = [
+ require_nonempty_text(test, f"{field}.validation_tests[{test_index}]")
+ for test_index, test in enumerate(tests)
+ ]
+ normalized.append(
+ {
+ "node_id": node_id,
+ "type": node_type,
+ "dependencies": "; ".join(normalized_dependencies),
+ "precondition": precondition,
+ "logic_statement": statement,
+ "output_kind": output_kind,
+ "output_value": output_value,
+ "source_ids": "; ".join(source_refs),
+ "rationale": rationale,
+ "validation_tests": "; ".join(normalized_tests),
+ "owner": owner,
+ "reviewer_role": reviewer,
+ "status": status,
+ }
+ )
+
+ if _has_cycle(edges):
+ log.errors.append("Dependency graph contains a cycle")
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ if review.get("required") is not True:
+ log.errors.append("human_review.required must be true")
+ require_nonempty_text(
+ review.get("approval_boundary"), "human_review.approval_boundary"
+ )
+ if metadata.get("status") == "validated" and review.get("completed") is not True:
+ log.errors.append(
+ "Validated matrix status requires completed human review"
+ )
+ elif review.get("completed") is not True:
+ log.warnings.append("Human review is not recorded as complete")
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ if log.ok:
+ log.info.append("Research/governance traceability matrix is structurally valid")
+ return log, normalized
+
+
+def _csv_text(rows: list[dict[str, str]]) -> str:
+ fieldnames = [
+ "node_id",
+ "type",
+ "dependencies",
+ "precondition",
+ "logic_statement",
+ "output_kind",
+ "output_value",
+ "source_ids",
+ "rationale",
+ "validation_tests",
+ "owner",
+ "reviewer_role",
+ "status",
+ ]
+ stream = io.StringIO()
+ writer = csv.DictWriter(stream, fieldnames=fieldnames, lineterminator="\n")
+ writer.writeheader()
+ for row in rows:
+ writer.writerow({key: _safe_csv(row[key]) for key in fieldnames})
+ return stream.getvalue()
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate research/governance decision logic and emit a CSV traceability "
+ "matrix. The tool never executes logic."
+ )
+ )
+ parser.add_argument("input", help="Local matrix JSON")
+ parser.add_argument("-o", "--output", help="Optional local CSV output")
+ parser.add_argument(
+ "--strict", action="store_true", help="Return failure when warnings are present"
+ )
+ args = parser.parse_args()
+
+ try:
+ document = load_json_object(args.input)
+ log, rows = validate_matrix(document)
+ if args.output:
+ write_text(args.output, _csv_text(rows), {".csv"})
+ else:
+ print(_csv_text(rows), end="")
+ for message in log.errors:
+ print(f"ERROR: {message}", file=sys.stderr)
+ for message in log.warnings:
+ print(f"WARNING: {message}", file=sys.stderr)
+ except InputError as exc:
+ print(f"ERROR: {exc}", file=sys.stderr)
+ return 2
+ if not log.ok or (args.strict and log.warnings):
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/deidentification_checklist.py b/skills/clinical-decision-support/scripts/deidentification_checklist.py
new file mode 100644
index 00000000..c7c62490
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/deidentification_checklist.py
@@ -0,0 +1,260 @@
+#!/usr/bin/env python3
+"""Check documentation of a de-identification process without reading health data."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ print_report,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ validate_references,
+ write_json,
+)
+
+SAFE_HARBOR_IDS = {
+ "names",
+ "geography",
+ "dates_and_ages",
+ "telephone_numbers",
+ "fax_numbers",
+ "email_addresses",
+ "social_security_numbers",
+ "medical_record_numbers",
+ "health_plan_numbers",
+ "account_numbers",
+ "certificate_license_numbers",
+ "vehicle_identifiers",
+ "device_identifiers",
+ "web_urls",
+ "ip_addresses",
+ "biometric_identifiers",
+ "full_face_images",
+ "other_unique_identifiers",
+}
+ALLOWED_STATUS = {
+ "not_present",
+ "removed",
+ "generalized",
+ "expert_reviewed",
+ "unresolved",
+}
+PLACEHOLDER_MARKERS = ("REPLACE_", "REQUIRES_", "YYYY-MM-DD")
+
+
+def _find_placeholders(value: Any, location: str = "$") -> list[str]:
+ findings: list[str] = []
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ findings.extend(_find_placeholders(nested, f"{location}.{key}"))
+ elif isinstance(value, list):
+ for index, nested in enumerate(value):
+ findings.extend(_find_placeholders(nested, f"{location}[{index}]"))
+ elif isinstance(value, str) and any(marker in value for marker in PLACEHOLDER_MARKERS):
+ findings.append(location)
+ return findings
+
+
+def check_documentation(document: dict[str, Any]) -> tuple[IssueLog, dict[str, Any]]:
+ log = IssueLog()
+ summary: dict[str, Any] = {
+ "method": None,
+ "documentation_complete": False,
+ "deidentification_determined": False,
+ "hipaa_compliance_determined": False,
+ "unresolved_categories": [],
+ }
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version")
+ require_nonempty_text(document.get("checklist_id"), "checklist_id")
+ require_nonempty_text(document.get("title"), "title")
+ known_sources = source_ids(document)
+ validate_references(document.get("source_ids"), known_sources, "source_ids")
+
+ method = require_nonempty_text(document.get("method"), "method")
+ summary["method"] = method
+ if method not in {"safe_harbor", "expert_determination", "undecided"}:
+ log.errors.append("method is unsupported")
+ if method == "undecided":
+ log.errors.append("A qualified human must select and document a method")
+
+ boundary = document.get("data_boundary")
+ if not isinstance(boundary, dict):
+ raise InputError("data_boundary must be an object")
+ if boundary.get("raw_data_supplied") is not False:
+ log.errors.append("data_boundary.raw_data_supplied must be false")
+ if boundary.get("metadata_only") is not True:
+ log.errors.append("data_boundary.metadata_only must be true")
+ for field in ("data_context", "recipient_context", "release_context"):
+ require_nonempty_text(boundary.get(field), f"data_boundary.{field}")
+
+ entries = require_list(
+ document.get("identifier_categories"),
+ "identifier_categories",
+ maximum=18,
+ )
+ observed_ids: set[str] = set()
+ for index, entry in enumerate(entries):
+ field = f"identifier_categories[{index}]"
+ if not isinstance(entry, dict):
+ raise InputError(f"{field} must be an object")
+ identifier = require_nonempty_text(entry.get("id"), f"{field}.id")
+ if identifier not in SAFE_HARBOR_IDS:
+ log.errors.append(f"{field}.id is not a Safe Harbor category")
+ if identifier in observed_ids:
+ log.errors.append(f"Duplicate identifier category: {identifier}")
+ observed_ids.add(identifier)
+ status = require_nonempty_text(entry.get("status"), f"{field}.status")
+ if status not in ALLOWED_STATUS:
+ log.errors.append(f"{field}.status is unsupported")
+ evidence = require_nonempty_text(entry.get("evidence"), f"{field}.evidence")
+ if status == "unresolved":
+ summary["unresolved_categories"].append(identifier)
+ if evidence.lower().startswith(("example:", "value:")):
+ log.errors.append(
+ f"{field}.evidence must not contain an example identifier or value"
+ )
+ missing_ids = sorted(SAFE_HARBOR_IDS - observed_ids)
+ extra_ids = sorted(observed_ids - SAFE_HARBOR_IDS)
+ if missing_ids:
+ log.errors.append("Missing Safe Harbor categories: " + ", ".join(missing_ids))
+ if extra_ids:
+ log.errors.append("Unexpected categories: " + ", ".join(extra_ids))
+
+ safe_harbor = document.get("safe_harbor_review")
+ if not isinstance(safe_harbor, dict):
+ raise InputError("safe_harbor_review must be an object")
+ for field in (
+ "actual_knowledge",
+ "free_text",
+ "derived_fields",
+ "date_age_zip_rules",
+ ):
+ require_nonempty_text(safe_harbor.get(field), f"safe_harbor_review.{field}")
+ if method == "safe_harbor":
+ if summary["unresolved_categories"]:
+ log.errors.append("Safe Harbor review has unresolved identifier categories")
+ if safe_harbor.get("completed") is not True:
+ log.errors.append("safe_harbor_review.completed must be true")
+ require_nonempty_text(
+ safe_harbor.get("reviewer_role"), "safe_harbor_review.reviewer_role"
+ )
+ require_nonempty_text(
+ safe_harbor.get("review_date"), "safe_harbor_review.review_date"
+ )
+
+ expert = document.get("expert_determination_review")
+ if not isinstance(expert, dict):
+ raise InputError("expert_determination_review must be an object")
+ if method == "expert_determination":
+ for field in (
+ "expert_qualification_reference",
+ "method_document_reference",
+ "risk_threshold_rationale",
+ "residual_risk",
+ "validity_period",
+ "change_triggers",
+ "review_date",
+ ):
+ require_nonempty_text(
+ expert.get(field), f"expert_determination_review.{field}"
+ )
+ if expert.get("completed") is not True:
+ log.errors.append(
+ "expert_determination_review.completed must be true"
+ )
+
+ residual = document.get("residual_risk_review")
+ if not isinstance(residual, dict):
+ raise InputError("residual_risk_review must be an object")
+ for field in (
+ "linkage",
+ "differencing",
+ "rare_combinations",
+ "longitudinal_patterns",
+ "geography",
+ "genomics",
+ "prior_releases",
+ ):
+ require_nonempty_text(residual.get(field), f"residual_risk_review.{field}")
+ if residual.get("completed") is not True:
+ log.errors.append("residual_risk_review.completed must be true")
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ if review.get("required") is not True:
+ log.errors.append("human_review.required must be true")
+ require_nonempty_text(review.get("role"), "human_review.role")
+ require_nonempty_text(
+ review.get("approval_boundary"), "human_review.approval_boundary"
+ )
+ if review.get("completed") is not True:
+ log.errors.append("human_review.completed must be true")
+
+ governance = document.get("governance")
+ if not isinstance(governance, dict):
+ raise InputError("governance must be an object")
+ for field in (
+ "version",
+ "owner",
+ "change_summary",
+ "auditability",
+ "monitoring",
+ ):
+ require_nonempty_text(governance.get(field), f"governance.{field}")
+
+ if document.get("compliance_claims") is not False:
+ log.errors.append("compliance_claims must be false")
+ if review.get("completed") is True:
+ placeholders = _find_placeholders(document)
+ if placeholders:
+ log.errors.append(
+ "Unresolved template placeholders remain: "
+ + ", ".join(placeholders[:10])
+ )
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ summary["documentation_complete"] = log.ok
+ if log.ok:
+ log.info.append(
+ "Process documentation is complete; no de-identification or compliance determination was made"
+ )
+ return log, summary
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Check metadata documenting Safe Harbor or Expert Determination work. "
+ "The script never reads a dataset and never determines compliance."
+ )
+ )
+ parser.add_argument("input", help="Local checklist JSON")
+ parser.add_argument("-o", "--output", help="Optional local JSON report")
+ args = parser.parse_args()
+
+ try:
+ document = load_json_object(args.input)
+ log, summary = check_documentation(document)
+ report = log.as_dict()
+ report["deidentification_review"] = summary
+ if args.output:
+ write_json(args.output, report)
+ print_report(report)
+ except InputError as exc:
+ print_report(IssueLog(errors=[str(exc)]).as_dict())
+ return 2
+ return 0 if report["status"] == "pass" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/evidence_profile_check.py b/skills/clinical-decision-support/scripts/evidence_profile_check.py
new file mode 100644
index 00000000..1fab0ea4
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/evidence_profile_check.py
@@ -0,0 +1,259 @@
+#!/usr/bin/env python3
+"""Check a human-authored GRADE evidence profile without assigning grades."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ print_report,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ validate_references,
+ write_json,
+)
+
+DOMAINS = (
+ "risk_of_bias",
+ "inconsistency",
+ "indirectness",
+ "imprecision",
+ "publication_bias",
+)
+DOMAIN_JUDGMENTS = {"not_serious", "serious", "very_serious", "unassessed"}
+UPGRADING = ("large_effect", "dose_response", "residual_confounding")
+UPGRADING_JUDGMENTS = {"none", "present", "unassessed", "not_applicable"}
+CERTAINTY_LEVELS = {"high", "moderate", "low", "very_low", "unassessed"}
+PLACEHOLDER_MARKERS = ("REPLACE_", "REQUIRES_", "YYYY-MM-DD")
+
+
+def _profile_has_recommendation_key(value: Any) -> bool:
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ if str(key).strip().lower() in {
+ "recommendation",
+ "recommendation_strength",
+ "treatment_recommendation",
+ }:
+ return True
+ if _profile_has_recommendation_key(nested):
+ return True
+ elif isinstance(value, list):
+ return any(_profile_has_recommendation_key(item) for item in value)
+ return False
+
+
+def _find_placeholders(value: Any, location: str = "$") -> list[str]:
+ findings: list[str] = []
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ findings.extend(_find_placeholders(nested, f"{location}.{key}"))
+ elif isinstance(value, list):
+ for index, nested in enumerate(value):
+ findings.extend(_find_placeholders(nested, f"{location}[{index}]"))
+ elif isinstance(value, str) and any(marker in value for marker in PLACEHOLDER_MARKERS):
+ findings.append(location)
+ return findings
+
+
+def check_profile(document: dict[str, Any]) -> tuple[IssueLog, list[dict[str, str]]]:
+ log = IssueLog()
+ summaries: list[dict[str, str]] = []
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version")
+ require_nonempty_text(document.get("profile_id"), "profile_id")
+ require_nonempty_text(document.get("title"), "title")
+ if document.get("data_level") not in {"published_aggregate_evidence", "synthetic"}:
+ log.errors.append(
+ "data_level must be published_aggregate_evidence or synthetic"
+ )
+ if document.get("human_judgments_required") is not True:
+ log.errors.append("human_judgments_required must be true")
+ if document.get("auto_grade") is not False:
+ log.errors.append("auto_grade must be false")
+ if _profile_has_recommendation_key(document):
+ log.errors.append(
+ "Recommendation fields are outside the evidence-profile checker"
+ )
+ governance = document.get("governance")
+ if not isinstance(governance, dict):
+ raise InputError("governance must be an object")
+ for field in (
+ "version",
+ "owner",
+ "change_summary",
+ "auditability",
+ "update_plan",
+ ):
+ require_nonempty_text(governance.get(field), f"governance.{field}")
+
+ question = document.get("question")
+ if not isinstance(question, dict):
+ raise InputError("question must be an object")
+ for field in ("population", "intervention_or_exposure", "comparator", "setting"):
+ require_nonempty_text(question.get(field), f"question.{field}")
+
+ known_sources = source_ids(document)
+ outcomes = require_list(document.get("outcomes"), "outcomes", maximum=50)
+ if not outcomes:
+ log.errors.append("At least one outcome is required")
+
+ names: set[str] = set()
+ for index, outcome in enumerate(outcomes):
+ prefix = f"outcomes[{index}]"
+ if not isinstance(outcome, dict):
+ raise InputError(f"{prefix} must be an object")
+ name = require_nonempty_text(outcome.get("name"), f"{prefix}.name")
+ if name in names:
+ log.errors.append(f"Duplicate outcome name: {name}")
+ names.add(name)
+ importance = require_nonempty_text(
+ outcome.get("importance"), f"{prefix}.importance"
+ )
+ if importance not in {"critical", "important", "not_important"}:
+ log.errors.append(f"{prefix}.importance has an unsupported value")
+ for field in (
+ "effect_measure",
+ "effect_estimate",
+ "uncertainty_interval",
+ "participants",
+ "studies",
+ "time_horizon",
+ ):
+ require_nonempty_text(outcome.get(field), f"{prefix}.{field}")
+
+ domains = outcome.get("domains")
+ if not isinstance(domains, dict):
+ raise InputError(f"{prefix}.domains must be an object")
+ for domain_name in DOMAINS:
+ domain = domains.get(domain_name)
+ field = f"{prefix}.domains.{domain_name}"
+ if not isinstance(domain, dict):
+ raise InputError(f"{field} must be an object")
+ judgment = require_nonempty_text(
+ domain.get("judgment"), f"{field}.judgment"
+ )
+ if judgment not in DOMAIN_JUDGMENTS:
+ log.errors.append(f"{field}.judgment is unsupported")
+ if judgment == "unassessed":
+ log.errors.append(f"{field} requires a human judgment")
+ require_nonempty_text(domain.get("rationale"), f"{field}.rationale")
+ require_nonempty_text(
+ domain.get("reviewer_role"), f"{field}.reviewer_role"
+ )
+ validate_references(
+ domain.get("source_ids"), known_sources, f"{field}.source_ids"
+ )
+
+ upgrading = outcome.get("upgrading")
+ if not isinstance(upgrading, dict):
+ raise InputError(f"{prefix}.upgrading must be an object")
+ for item_name in UPGRADING:
+ item = upgrading.get(item_name)
+ field = f"{prefix}.upgrading.{item_name}"
+ if not isinstance(item, dict):
+ raise InputError(f"{field} must be an object")
+ judgment = require_nonempty_text(
+ item.get("judgment"), f"{field}.judgment"
+ )
+ if judgment not in UPGRADING_JUDGMENTS:
+ log.errors.append(f"{field}.judgment is unsupported")
+ if judgment == "unassessed":
+ log.errors.append(f"{field} requires a human judgment")
+ require_nonempty_text(item.get("rationale"), f"{field}.rationale")
+ if judgment == "present":
+ validate_references(
+ item.get("source_ids"), known_sources, f"{field}.source_ids"
+ )
+
+ certainty = outcome.get("certainty")
+ if not isinstance(certainty, dict):
+ raise InputError(f"{prefix}.certainty must be an object")
+ if certainty.get("human_judgment") is not True:
+ log.errors.append(f"{prefix}.certainty.human_judgment must be true")
+ level = require_nonempty_text(
+ certainty.get("level"), f"{prefix}.certainty.level"
+ )
+ if level not in CERTAINTY_LEVELS:
+ log.errors.append(f"{prefix}.certainty.level is unsupported")
+ if level == "unassessed":
+ log.errors.append(f"{prefix}.certainty requires a human judgment")
+ require_nonempty_text(
+ certainty.get("rationale"), f"{prefix}.certainty.rationale"
+ )
+ require_nonempty_text(
+ certainty.get("reviewer_role"), f"{prefix}.certainty.reviewer_role"
+ )
+ require_nonempty_text(
+ certainty.get("judgment_date"), f"{prefix}.certainty.judgment_date"
+ )
+ validate_references(
+ certainty.get("source_ids"),
+ known_sources,
+ f"{prefix}.certainty.source_ids",
+ )
+ summaries.append(
+ {
+ "outcome": name,
+ "importance": importance,
+ "human_entered_certainty": level,
+ }
+ )
+
+ review = document.get("profile_review")
+ if not isinstance(review, dict):
+ raise InputError("profile_review must be an object")
+ for field in ("prepared_by_role", "reviewed_by_role", "review_date"):
+ require_nonempty_text(review.get(field), f"profile_review.{field}")
+ if review.get("completed") is not True:
+ log.errors.append("profile_review.completed must be true")
+ placeholders = _find_placeholders(document)
+ if placeholders:
+ log.errors.append(
+ "Unresolved template placeholders remain: "
+ + ", ".join(placeholders[:10])
+ )
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ if log.ok:
+ log.info.append(
+ "Profile is structurally complete; all certainty labels remain human judgments"
+ )
+ return log, summaries
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Check completeness and citation traceability of a human-authored "
+ "GRADE evidence profile. This tool never assigns certainty."
+ )
+ )
+ parser.add_argument("input", help="Local evidence-profile JSON")
+ parser.add_argument("-o", "--output", help="Optional local JSON report")
+ args = parser.parse_args()
+
+ try:
+ document = load_json_object(args.input)
+ log, summaries = check_profile(document)
+ report = log.as_dict()
+ report["outcomes"] = summaries
+ report["auto_grade_performed"] = False
+ if args.output:
+ write_json(args.output, report)
+ print_report(report)
+ except InputError as exc:
+ print_report(IssueLog(errors=[str(exc)]).as_dict())
+ return 2
+ return 0 if report["status"] == "pass" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/generate_schematic.py b/skills/clinical-decision-support/scripts/generate_schematic.py
deleted file mode 100644
index 43331870..00000000
--- a/skills/clinical-decision-support/scripts/generate_schematic.py
+++ /dev/null
@@ -1,139 +0,0 @@
-#!/usr/bin/env python3
-"""
-Scientific schematic generation using Nano Banana 2.
-
-Generate any scientific diagram by describing it in natural language.
-Nano Banana 2 handles everything automatically with smart iterative refinement.
-
-Smart iteration: Only regenerates if quality is below threshold for your document type.
-Quality review: Uses Gemini 3.6 Flash for professional scientific evaluation.
-
-Usage:
- # Generate for journal paper (highest quality threshold)
- python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal
-
- # Generate for presentation (lower threshold, faster)
- python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation
-
- # Generate for poster
- python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster
-"""
-
-import argparse
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-
-def main():
- """Command-line interface."""
- parser = argparse.ArgumentParser(
- description="Generate scientific schematics using AI with smart iterative refinement",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-How it works:
- Simply describe your diagram in natural language
- Nano Banana 2 generates it automatically with:
- - Smart iteration (only regenerates if quality is below threshold)
- - Quality review by Gemini 3.6 Flash
- - Document-type aware quality thresholds
- - Publication-ready output
-
-Document Types (quality thresholds):
- journal 8.5/10 - Nature, Science, peer-reviewed journals
- conference 8.0/10 - Conference papers
- thesis 8.0/10 - Dissertations, theses
- grant 8.0/10 - Grant proposals
- preprint 7.5/10 - arXiv, bioRxiv, etc.
- report 7.5/10 - Technical reports
- poster 7.0/10 - Academic posters
- presentation 6.5/10 - Slides, talks
- default 7.5/10 - General purpose
-
-Examples:
- # Generate for journal paper (strict quality)
- python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal
-
- # Generate for poster (moderate quality)
- python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster
-
- # Generate for slides (faster, lower threshold)
- python generate_schematic.py "System diagram" -o system.png --doc-type presentation
-
- # Custom max iterations
- python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2
-
- # Verbose output
- python generate_schematic.py "Circuit diagram" -o circuit.png -v
-
-Environment Variables:
- OPENROUTER_API_KEY Required for AI generation
- """
- )
-
- parser.add_argument("prompt",
- help="Description of the diagram to generate")
- parser.add_argument("-o", "--output", required=True,
- help="Output file path")
- parser.add_argument("--doc-type", default="default",
- choices=["journal", "conference", "poster", "presentation",
- "report", "grant", "thesis", "preprint", "default"],
- help="Document type for quality threshold (default: default)")
- parser.add_argument("--iterations", type=int, default=2,
- help="Maximum refinement iterations (default: 2, max: 2)")
- parser.add_argument("--api-key",
- help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")
- parser.add_argument("-v", "--verbose", action="store_true",
- help="Verbose output")
-
- args = parser.parse_args()
-
- # Check for API key
- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")
- if not api_key:
- print("Error: OPENROUTER_API_KEY environment variable not set")
- print("\nFor AI generation, you need an OpenRouter API key.")
- print("Get one at: https://openrouter.ai/keys")
- print("\nSet it with:")
- print(" export OPENROUTER_API_KEY='your_api_key'")
- print("\nOr use --api-key flag")
- sys.exit(1)
-
- # Find AI generation script
- script_dir = Path(__file__).parent
- ai_script = script_dir / "generate_schematic_ai.py"
-
- if not ai_script.exists():
- print(f"Error: AI generation script not found: {ai_script}")
- sys.exit(1)
-
- # Build command
- cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]
-
- if args.doc_type != "default":
- cmd.extend(["--doc-type", args.doc_type])
-
- # Enforce max 2 iterations
- iterations = min(args.iterations, 2)
- if iterations != 2:
- cmd.extend(["--iterations", str(iterations)])
-
- if args.verbose:
- cmd.append("-v")
-
- # Execute — pass API key via environment to avoid exposure in process listings
- try:
- env = os.environ.copy()
- if api_key:
- env["OPENROUTER_API_KEY"] = api_key
- result = subprocess.run(cmd, check=False, env=env)
- sys.exit(result.returncode)
- except Exception as e:
- print(f"Error executing AI generation: {e}")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/skills/clinical-decision-support/scripts/generate_schematic_ai.py b/skills/clinical-decision-support/scripts/generate_schematic_ai.py
deleted file mode 100644
index 651b6c76..00000000
--- a/skills/clinical-decision-support/scripts/generate_schematic_ai.py
+++ /dev/null
@@ -1,817 +0,0 @@
-#!/usr/bin/env python3
-"""
-AI-powered scientific schematic generation using Nano Banana 2.
-
-This script uses a smart iterative refinement approach:
-1. Generate initial image with Nano Banana 2
-2. AI quality review using Gemini 3.6 Flash for scientific critique
-3. Only regenerate if quality is below threshold for document type
-4. Repeat until quality meets standards (max iterations)
-
-Requirements:
- - OPENROUTER_API_KEY environment variable
- - requests library
-
-Usage:
- python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png
- python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2
- python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster
-"""
-
-import argparse
-import base64
-import json
-import os
-import sys
-import time
-from pathlib import Path
-from typing import Optional, Dict, Any, List, Tuple
-
-try:
- import requests
-except ImportError:
- print("Error: requests library not found. Install with: pip install requests")
- sys.exit(1)
-
-# Try to load .env file from multiple potential locations
-def _load_env_file():
- """Load .env file from current directory or script directory only."""
- try:
- from dotenv import load_dotenv
- except ImportError:
- return False
-
- for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:
- if candidate.exists():
- load_dotenv(dotenv_path=candidate, override=False)
- return True
-
- return False
-
-
-class ScientificSchematicGenerator:
- """Generate scientific schematics using AI with smart iterative refinement.
-
- Uses Gemini 3.6 Flash for quality review to determine if regeneration is needed.
- Multiple passes only occur if the generated schematic doesn't meet the
- quality threshold for the target document type.
- """
-
- # Quality thresholds by document type (score out of 10)
- # Higher thresholds for more formal publications
- QUALITY_THRESHOLDS = {
- "journal": 8.5, # Nature, Science, etc. - highest standards
- "conference": 8.0, # Conference papers - high standards
- "poster": 7.0, # Academic posters - good quality
- "presentation": 6.5, # Slides/talks - clear but less formal
- "report": 7.5, # Technical reports - professional
- "grant": 8.0, # Grant proposals - must be compelling
- "thesis": 8.0, # Dissertations - formal academic
- "preprint": 7.5, # arXiv, etc. - good quality
- "default": 7.5, # Default threshold
- }
-
- # Scientific diagram best practices prompt template
- SCIENTIFIC_DIAGRAM_GUIDELINES = """
-Create a high-quality scientific diagram with these requirements:
-
-VISUAL QUALITY:
-- Clean white or light background (no textures or gradients)
-- High contrast for readability and printing
-- Professional, publication-ready appearance
-- Sharp, clear lines and text
-- Adequate spacing between elements to prevent crowding
-
-TYPOGRAPHY:
-- Clear, readable sans-serif fonts (Arial, Helvetica style)
-- Minimum 10pt font size for all labels
-- Consistent font sizes throughout
-- All text horizontal or clearly readable
-- No overlapping text
-
-SCIENTIFIC STANDARDS:
-- Accurate representation of concepts
-- Clear labels for all components
-- Include scale bars, legends, or axes where appropriate
-- Use standard scientific notation and symbols
-- Include units where applicable
-
-ACCESSIBILITY:
-- Colorblind-friendly color palette (use Okabe-Ito colors if using color)
-- High contrast between elements
-- Redundant encoding (shapes + colors, not just colors)
-- Works well in grayscale
-
-LAYOUT:
-- Logical flow (left-to-right or top-to-bottom)
-- Clear visual hierarchy
-- Balanced composition
-- Appropriate use of whitespace
-- No clutter or unnecessary decorative elements
-
-IMPORTANT - NO FIGURE NUMBERS:
-- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image
-- Do NOT add captions or titles like "Figure: ..." at the top or bottom
-- Figure numbers and captions are added separately in the document/LaTeX
-- The diagram should contain only the visual content itself
-"""
-
- def __init__(self, api_key: Optional[str] = None, verbose: bool = False):
- """
- Initialize the generator.
-
- Args:
- api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)
- verbose: Print detailed progress information
- """
- # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file
- self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")
-
- # If not found in environment, try loading from .env file
- if not self.api_key:
- _load_env_file()
- self.api_key = os.getenv("OPENROUTER_API_KEY")
-
- if not self.api_key:
- raise ValueError(
- "OPENROUTER_API_KEY not found. Please either:\n"
- " 1. Set the OPENROUTER_API_KEY environment variable\n"
- " 2. Add OPENROUTER_API_KEY to your .env file\n"
- " 3. Pass api_key parameter to the constructor\n"
- "Get your API key from: https://openrouter.ai/keys"
- )
-
- self.verbose = verbose
- self._last_error = None # Track last error for better reporting
- self.base_url = "https://openrouter.ai/api/v1"
- # Nano Banana 2 - Google's advanced image generation model
- # https://openrouter.ai/google/gemini-3.6-flash
- self.image_model = "google/gemini-3.1-flash-image-preview"
- # Gemini 3.6 Flash for quality review - excellent vision and reasoning
- self.review_model = "google/gemini-3.6-flash"
-
- def _log(self, message: str):
- """Log message if verbose mode is enabled."""
- if self.verbose:
- print(f"[{time.strftime('%H:%M:%S')}] {message}")
-
- def _make_request(self, model: str, messages: List[Dict[str, Any]],
- modalities: Optional[List[str]] = None) -> Dict[str, Any]:
- """
- Make a request to OpenRouter API.
-
- Args:
- model: Model identifier
- messages: List of message dictionaries
- modalities: Optional list of modalities (e.g., ["image", "text"])
-
- Returns:
- API response as dictionary
- """
- headers = {
- "Authorization": f"Bearer {self.api_key}",
- "Content-Type": "application/json",
- "HTTP-Referer": "https://github.com/scientific-writer",
- "X-Title": "Scientific Schematic Generator"
- }
-
- payload = {
- "model": model,
- "messages": messages
- }
-
- if modalities:
- payload["modalities"] = modalities
-
- self._log(f"Making request to {model}...")
-
- try:
- response = requests.post(
- f"{self.base_url}/chat/completions",
- headers=headers,
- json=payload,
- timeout=120
- )
-
- # Try to get response body even on error
- try:
- response_json = response.json()
- except json.JSONDecodeError:
- response_json = {"raw_text": response.text[:500]}
-
- # Check for HTTP errors but include response body in error message
- if response.status_code != 200:
- error_detail = response_json.get("error", response_json)
- self._log(f"HTTP {response.status_code}: {error_detail}")
- raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")
-
- return response_json
- except requests.exceptions.Timeout:
- raise RuntimeError("API request timed out after 120 seconds")
- except requests.exceptions.RequestException as e:
- raise RuntimeError(f"API request failed: {str(e)}")
-
- def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:
- """
- Extract base64-encoded image from API response.
-
- For Nano Banana 2, images are returned in the 'images' field of the message,
- not in the 'content' field.
-
- Args:
- response: API response dictionary
-
- Returns:
- Image bytes or None if not found
- """
- try:
- choices = response.get("choices", [])
- if not choices:
- self._log("No choices in response")
- return None
-
- message = choices[0].get("message", {})
-
- # IMPORTANT: Nano Banana 2 returns images in the 'images' field
- images = message.get("images", [])
- if images and len(images) > 0:
- self._log(f"Found {len(images)} image(s) in 'images' field")
-
- # Get first image
- first_image = images[0]
- if isinstance(first_image, dict):
- # Extract image_url
- if first_image.get("type") == "image_url":
- url = first_image.get("image_url", {})
- if isinstance(url, dict):
- url = url.get("url", "")
-
- if url and url.startswith("data:image"):
- # Extract base64 data after comma
- if "," in url:
- base64_str = url.split(",", 1)[1]
- # Clean whitespace
- base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Extracted base64 data (length: {len(base64_str)})")
- return base64.b64decode(base64_str)
-
- # Fallback: check content field (for other models or future changes)
- content = message.get("content", "")
-
- if self.verbose:
- self._log(f"Content type: {type(content)}, length: {len(str(content))}")
-
- # Handle string content
- if isinstance(content, str) and "data:image" in content:
- import re
- match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)
- if match:
- base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Found image in content field (length: {len(base64_str)})")
- return base64.b64decode(base64_str)
-
- # Handle list content
- if isinstance(content, list):
- for i, block in enumerate(content):
- if isinstance(block, dict) and block.get("type") == "image_url":
- url = block.get("image_url", {})
- if isinstance(url, dict):
- url = url.get("url", "")
- if url and url.startswith("data:image") and "," in url:
- base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')
- self._log(f"Found image in content block {i}")
- return base64.b64decode(base64_str)
-
- self._log("No image data found in response")
- return None
-
- except Exception as e:
- self._log(f"Error extracting image: {str(e)}")
- import traceback
- if self.verbose:
- traceback.print_exc()
- return None
-
- def _image_to_base64(self, image_path: str) -> str:
- """
- Convert image file to base64 data URL.
-
- Args:
- image_path: Path to image file
-
- Returns:
- Base64 data URL string
- """
- with open(image_path, "rb") as f:
- image_data = f.read()
-
- # Determine image type from extension
- ext = Path(image_path).suffix.lower()
- mime_type = {
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".gif": "image/gif",
- ".webp": "image/webp"
- }.get(ext, "image/png")
-
- base64_data = base64.b64encode(image_data).decode("utf-8")
- return f"data:{mime_type};base64,{base64_data}"
-
- def generate_image(self, prompt: str) -> Optional[bytes]:
- """
- Generate an image using Nano Banana 2.
-
- Args:
- prompt: Description of the diagram to generate
-
- Returns:
- Image bytes or None if generation failed
- """
- self._last_error = None # Reset error
-
- messages = [
- {
- "role": "user",
- "content": prompt
- }
- ]
-
- try:
- response = self._make_request(
- model=self.image_model,
- messages=messages,
- modalities=["image", "text"]
- )
-
- # Debug: print response structure if verbose
- if self.verbose:
- self._log(f"Response keys: {response.keys()}")
- if "error" in response:
- self._log(f"API Error: {response['error']}")
- if "choices" in response and response["choices"]:
- msg = response["choices"][0].get("message", {})
- self._log(f"Message keys: {msg.keys()}")
- # Show content preview without printing huge base64 data
- content = msg.get("content", "")
- if isinstance(content, str):
- preview = content[:200] + "..." if len(content) > 200 else content
- self._log(f"Content preview: {preview}")
- elif isinstance(content, list):
- self._log(f"Content is list with {len(content)} items")
- for i, item in enumerate(content[:3]):
- if isinstance(item, dict):
- self._log(f" Item {i}: type={item.get('type')}")
-
- # Check for API errors in response
- if "error" in response:
- error_msg = response["error"]
- if isinstance(error_msg, dict):
- error_msg = error_msg.get("message", str(error_msg))
- self._last_error = f"API Error: {error_msg}"
- print(f"✗ {self._last_error}")
- return None
-
- image_data = self._extract_image_from_response(response)
- if image_data:
- self._log(f"✓ Generated image ({len(image_data)} bytes)")
- else:
- self._last_error = "No image data in API response - model may not support image generation"
- self._log(f"✗ {self._last_error}")
- # Additional debug info when image extraction fails
- if self.verbose and "choices" in response:
- msg = response["choices"][0].get("message", {})
- self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")
-
- return image_data
- except RuntimeError as e:
- self._last_error = str(e)
- self._log(f"✗ Generation failed: {self._last_error}")
- return None
- except Exception as e:
- self._last_error = f"Unexpected error: {str(e)}"
- self._log(f"✗ Generation failed: {self._last_error}")
- import traceback
- if self.verbose:
- traceback.print_exc()
- return None
-
- def review_image(self, image_path: str, original_prompt: str,
- iteration: int, doc_type: str = "default",
- max_iterations: int = 2) -> Tuple[str, float, bool]:
- """
- Review generated image using Gemini 3.6 Flash for quality analysis.
-
- Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to
- evaluate the schematic quality and determine if regeneration is needed.
-
- Args:
- image_path: Path to the generated image
- original_prompt: Original user prompt
- iteration: Current iteration number
- doc_type: Document type (journal, poster, presentation, etc.)
- max_iterations: Maximum iterations allowed
-
- Returns:
- Tuple of (critique text, quality score 0-10, needs_improvement bool)
- """
- # Use Gemini 3.6 Flash for review - excellent vision and analysis
- image_data_url = self._image_to_base64(image_path)
-
- # Get quality threshold for this document type
- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),
- self.QUALITY_THRESHOLDS["default"])
-
- review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.
-
-ORIGINAL REQUEST: {original_prompt}
-
-DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)
-ITERATION: {iteration}/{max_iterations}
-
-Carefully evaluate this diagram on these criteria:
-
-1. **Scientific Accuracy** (0-2 points)
- - Correct representation of concepts
- - Proper notation and symbols
- - Accurate relationships shown
-
-2. **Clarity and Readability** (0-2 points)
- - Easy to understand at a glance
- - Clear visual hierarchy
- - No ambiguous elements
-
-3. **Label Quality** (0-2 points)
- - All important elements labeled
- - Labels are readable (appropriate font size)
- - Consistent labeling style
-
-4. **Layout and Composition** (0-2 points)
- - Logical flow (top-to-bottom or left-to-right)
- - Balanced use of space
- - No overlapping elements
-
-5. **Professional Appearance** (0-2 points)
- - Publication-ready quality
- - Clean, crisp lines and shapes
- - Appropriate colors/contrast
-
-RESPOND IN THIS EXACT FORMAT:
-SCORE: [total score 0-10]
-
-STRENGTHS:
-- [strength 1]
-- [strength 2]
-
-ISSUES:
-- [issue 1 if any]
-- [issue 2 if any]
-
-VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]
-
-If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.
-If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""
-
- messages = [
- {
- "role": "user",
- "content": [
- {
- "type": "text",
- "text": review_prompt
- },
- {
- "type": "image_url",
- "image_url": {
- "url": image_data_url
- }
- }
- ]
- }
- ]
-
- try:
- # Use Gemini 3.6 Flash for high-quality review
- response = self._make_request(
- model=self.review_model,
- messages=messages
- )
-
- # Extract text response
- choices = response.get("choices", [])
- if not choices:
- return "Image generated successfully", 8.0
-
- message = choices[0].get("message", {})
- content = message.get("content", "")
-
- # Check reasoning field (Nano Banana 2 puts analysis here)
- reasoning = message.get("reasoning", "")
- if reasoning and not content:
- content = reasoning
-
- if isinstance(content, list):
- # Extract text from content blocks
- text_parts = []
- for block in content:
- if isinstance(block, dict) and block.get("type") == "text":
- text_parts.append(block.get("text", ""))
- content = "\n".join(text_parts)
-
- # Try to extract score
- score = 7.5 # Default score if extraction fails
- import re
-
- # Look for SCORE: X or SCORE: X/10 format
- score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)
- if score_match:
- score = float(score_match.group(1))
- else:
- # Fallback: look for any score pattern
- score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)
- if score_match:
- score = float(score_match.group(1))
-
- # Determine if improvement is needed based on verdict or score
- needs_improvement = False
- if "NEEDS_IMPROVEMENT" in content.upper():
- needs_improvement = True
- elif score < threshold:
- needs_improvement = True
-
- self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")
- self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")
-
- return (content if content else "Image generated successfully",
- score,
- needs_improvement)
- except Exception as e:
- self._log(f"Review skipped: {str(e)}")
- # Don't fail the whole process if review fails - assume acceptable
- return "Image generated successfully (review skipped)", 7.5, False
-
- def improve_prompt(self, original_prompt: str, critique: str,
- iteration: int) -> str:
- """
- Improve the generation prompt based on critique.
-
- Args:
- original_prompt: Original user prompt
- critique: Review critique from previous iteration
- iteration: Current iteration number
-
- Returns:
- Improved prompt for next generation
- """
- improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}
-
-USER REQUEST: {original_prompt}
-
-ITERATION {iteration}: Based on previous feedback, address these specific improvements:
-{critique}
-
-Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""
-
- return improved_prompt
-
- def generate_iterative(self, user_prompt: str, output_path: str,
- iterations: int = 2,
- doc_type: str = "default") -> Dict[str, Any]:
- """
- Generate scientific schematic with smart iterative refinement.
-
- Only regenerates if the quality score is below the threshold for the
- specified document type. This saves API calls and time when the first
- generation is already good enough.
-
- Args:
- user_prompt: User's description of desired diagram
- output_path: Path to save final image
- iterations: Maximum refinement iterations (default: 2, max: 2)
- doc_type: Document type for quality threshold (journal, poster, etc.)
-
- Returns:
- Dictionary with generation results and metadata
- """
- output_path = Path(output_path)
- output_dir = output_path.parent
- output_dir.mkdir(parents=True, exist_ok=True)
-
- base_name = output_path.stem
- extension = output_path.suffix or ".png"
-
- # Get quality threshold for this document type
- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),
- self.QUALITY_THRESHOLDS["default"])
-
- results = {
- "user_prompt": user_prompt,
- "doc_type": doc_type,
- "quality_threshold": threshold,
- "iterations": [],
- "final_image": None,
- "final_score": 0.0,
- "success": False,
- "early_stop": False,
- "early_stop_reason": None
- }
-
- current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}
-
-USER REQUEST: {user_prompt}
-
-Generate a publication-quality scientific diagram that meets all the guidelines above."""
-
- print(f"\n{'='*60}")
- print(f"Generating Scientific Schematic")
- print(f"{'='*60}")
- print(f"Description: {user_prompt}")
- print(f"Document Type: {doc_type}")
- print(f"Quality Threshold: {threshold}/10")
- print(f"Max Iterations: {iterations}")
- print(f"Output: {output_path}")
- print(f"{'='*60}\n")
-
- for i in range(1, iterations + 1):
- print(f"\n[Iteration {i}/{iterations}]")
- print("-" * 40)
-
- # Generate image
- print(f"Generating image...")
- image_data = self.generate_image(current_prompt)
-
- if not image_data:
- error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')
- print(f"✗ Generation failed: {error_msg}")
- results["iterations"].append({
- "iteration": i,
- "success": False,
- "error": error_msg
- })
- continue
-
- # Save iteration image
- iter_path = output_dir / f"{base_name}_v{i}{extension}"
- with open(iter_path, "wb") as f:
- f.write(image_data)
- print(f"✓ Saved: {iter_path}")
-
- # Review image using Gemini 3.6 Flash
- print(f"Reviewing image with Gemini 3.6 Flash...")
- critique, score, needs_improvement = self.review_image(
- str(iter_path), user_prompt, i, doc_type, iterations
- )
- print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")
-
- # Save iteration results
- iteration_result = {
- "iteration": i,
- "image_path": str(iter_path),
- "prompt": current_prompt,
- "critique": critique,
- "score": score,
- "needs_improvement": needs_improvement,
- "success": True
- }
- results["iterations"].append(iteration_result)
-
- # Check if quality is acceptable - STOP EARLY if so
- if not needs_improvement:
- print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")
- print(f" No further iterations needed!")
- results["final_image"] = str(iter_path)
- results["final_score"] = score
- results["success"] = True
- results["early_stop"] = True
- results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"
- break
-
- # If this is the last iteration, we're done regardless
- if i == iterations:
- print(f"\n⚠ Maximum iterations reached")
- results["final_image"] = str(iter_path)
- results["final_score"] = score
- results["success"] = True
- break
-
- # Quality below threshold - improve prompt for next iteration
- print(f"\n⚠ Quality below threshold ({score} < {threshold})")
- print(f"Improving prompt based on feedback...")
- current_prompt = self.improve_prompt(user_prompt, critique, i + 1)
-
- # Copy final version to output path
- if results["success"] and results["final_image"]:
- final_iter_path = Path(results["final_image"])
- if final_iter_path != output_path:
- import shutil
- shutil.copy(final_iter_path, output_path)
- print(f"\n✓ Final image: {output_path}")
-
- # Save review log
- log_path = output_dir / f"{base_name}_review_log.json"
- with open(log_path, "w") as f:
- json.dump(results, f, indent=2)
- print(f"✓ Review log: {log_path}")
-
- print(f"\n{'='*60}")
- print(f"Generation Complete!")
- print(f"Final Score: {results['final_score']}/10")
- if results["early_stop"]:
- print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")
- print(f"{'='*60}\n")
-
- return results
-
-
-def main():
- """Command-line interface."""
- parser = argparse.ArgumentParser(
- description="Generate scientific schematics using AI with smart iterative refinement",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- # Generate a flowchart for a journal paper
- python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal
-
- # Generate neural network architecture for presentation (lower threshold)
- python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation
-
- # Generate with custom max iterations for poster
- python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster
-
- # Verbose output
- python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v
-
-Document Types (quality thresholds):
- journal 8.5/10 - Nature, Science, peer-reviewed journals
- conference 8.0/10 - Conference papers
- thesis 8.0/10 - Dissertations, theses
- grant 8.0/10 - Grant proposals
- preprint 7.5/10 - arXiv, bioRxiv, etc.
- report 7.5/10 - Technical reports
- poster 7.0/10 - Academic posters
- presentation 6.5/10 - Slides, talks
- default 7.5/10 - General purpose
-
-Note: Multiple iterations only occur if quality is BELOW the threshold.
- If the first generation meets the threshold, no extra API calls are made.
-
-Environment:
- OPENROUTER_API_KEY OpenRouter API key (required)
- """
- )
-
- parser.add_argument("prompt", help="Description of the diagram to generate")
- parser.add_argument("-o", "--output", required=True,
- help="Output image path (e.g., diagram.png)")
- parser.add_argument("--iterations", type=int, default=2,
- help="Maximum refinement iterations (default: 2, max: 2)")
- parser.add_argument("--doc-type", default="default",
- choices=["journal", "conference", "poster", "presentation",
- "report", "grant", "thesis", "preprint", "default"],
- help="Document type for quality threshold (default: default)")
- parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")
- parser.add_argument("-v", "--verbose", action="store_true",
- help="Verbose output")
-
- args = parser.parse_args()
-
- # Check for API key
- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")
- if not api_key:
- print("Error: OPENROUTER_API_KEY environment variable not set")
- print("\nSet it with:")
- print(" export OPENROUTER_API_KEY='your_api_key'")
- print("\nOr provide via --api-key flag")
- sys.exit(1)
-
- # Validate iterations - enforce max of 2
- if args.iterations < 1 or args.iterations > 2:
- print("Error: Iterations must be between 1 and 2")
- sys.exit(1)
-
- try:
- generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)
- results = generator.generate_iterative(
- user_prompt=args.prompt,
- output_path=args.output,
- iterations=args.iterations,
- doc_type=args.doc_type
- )
-
- if results["success"]:
- print(f"\n✓ Success! Image saved to: {args.output}")
- if results.get("early_stop"):
- print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")
- sys.exit(0)
- else:
- print(f"\n✗ Generation failed. Check review log for details.")
- sys.exit(1)
- except Exception as e:
- print(f"\n✗ Error: {str(e)}")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/skills/clinical-decision-support/scripts/generate_survival_analysis.py b/skills/clinical-decision-support/scripts/generate_survival_analysis.py
deleted file mode 100755
index 98f1d41e..00000000
--- a/skills/clinical-decision-support/scripts/generate_survival_analysis.py
+++ /dev/null
@@ -1,422 +0,0 @@
-#!/usr/bin/env python3
-"""
-Generate Kaplan-Meier Survival Curves for Clinical Decision Support Documents
-
-This script creates publication-quality survival curves with:
-- Kaplan-Meier survival estimates
-- 95% confidence intervals
-- Log-rank test statistics
-- Hazard ratios with confidence intervals
-- Number at risk tables
-- Median survival annotations
-
-Dependencies: lifelines, matplotlib, pandas, numpy
-"""
-
-import pandas as pd
-import numpy as np
-import matplotlib.pyplot as plt
-from lifelines import KaplanMeierFitter
-from lifelines.statistics import logrank_test, multivariate_logrank_test
-from lifelines import CoxPHFitter
-import argparse
-from pathlib import Path
-
-
-def load_survival_data(filepath):
- """
- Load survival data from CSV file.
-
- Expected columns:
- - patient_id: Unique patient identifier
- - time: Survival time (months or days)
- - event: Event indicator (1=event occurred, 0=censored)
- - group: Stratification variable (e.g., 'Biomarker+', 'Biomarker-')
- - Optional: Additional covariates for Cox regression
-
- Returns:
- pandas.DataFrame
- """
- df = pd.read_csv(filepath)
-
- # Validate required columns
- required_cols = ['patient_id', 'time', 'event', 'group']
- missing = [col for col in required_cols if col not in df.columns]
- if missing:
- raise ValueError(f"Missing required columns: {missing}")
-
- # Convert event to boolean if needed
- df['event'] = df['event'].astype(bool)
-
- return df
-
-
-def calculate_median_survival(kmf):
- """Calculate median survival with 95% CI."""
- median = kmf.median_survival_time_
- ci = kmf.confidence_interval_survival_function_
-
- # Find time when survival crosses 0.5
- if median == np.inf:
- return None, None, None
-
- # Get CI at median
- idx = np.argmin(np.abs(kmf.survival_function_.index - median))
- lower_ci = ci.iloc[idx]['KM_estimate_lower_0.95']
- upper_ci = ci.iloc[idx]['KM_estimate_upper_0.95']
-
- return median, lower_ci, upper_ci
-
-
-def generate_kaplan_meier_plot(data, time_col='time', event_col='event',
- group_col='group', output_path='survival_curve.pdf',
- title='Kaplan-Meier Survival Curve',
- xlabel='Time (months)', ylabel='Survival Probability'):
- """
- Generate Kaplan-Meier survival curve comparing groups.
-
- Parameters:
- data: DataFrame with survival data
- time_col: Column name for survival time
- event_col: Column name for event indicator
- group_col: Column name for stratification
- output_path: Path to save figure
- title: Plot title
- xlabel: X-axis label (specify units)
- ylabel: Y-axis label
- """
-
- # Create figure and axis
- fig, ax = plt.subplots(figsize=(10, 6))
-
- # Get unique groups
- groups = data[group_col].unique()
-
- # Colors for groups (colorblind-friendly)
- colors = ['#0173B2', '#DE8F05', '#029E73', '#CC78BC', '#CA9161']
-
- kmf_models = {}
- median_survivals = {}
-
- # Plot each group
- for i, group in enumerate(groups):
- group_data = data[data[group_col] == group]
-
- # Fit Kaplan-Meier
- kmf = KaplanMeierFitter()
- kmf.fit(group_data[time_col], group_data[event_col], label=str(group))
-
- # Plot survival curve
- kmf.plot_survival_function(ax=ax, ci_show=True, color=colors[i % len(colors)],
- linewidth=2, alpha=0.8)
-
- # Store model
- kmf_models[group] = kmf
-
- # Calculate median survival
- median, lower, upper = calculate_median_survival(kmf)
- median_survivals[group] = (median, lower, upper)
-
- # Log-rank test
- if len(groups) == 2:
- group1_data = data[data[group_col] == groups[0]]
- group2_data = data[data[group_col] == groups[1]]
-
- results = logrank_test(
- group1_data[time_col], group2_data[time_col],
- group1_data[event_col], group2_data[event_col]
- )
-
- p_value = results.p_value
- test_statistic = results.test_statistic
-
- # Add log-rank test result to plot
- ax.text(0.02, 0.15, f'Log-rank test:\np = {p_value:.4f}',
- transform=ax.transAxes, fontsize=10,
- verticalalignment='top',
- bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
- else:
- # Multivariate log-rank for >2 groups
- results = multivariate_logrank_test(data[time_col], data[group_col], data[event_col])
- p_value = results.p_value
- test_statistic = results.test_statistic
-
- ax.text(0.02, 0.15, f'Log-rank test:\np = {p_value:.4f}\n({len(groups)} groups)',
- transform=ax.transAxes, fontsize=10,
- verticalalignment='top',
- bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
-
- # Add median survival annotations
- y_pos = 0.95
- for group, (median, lower, upper) in median_survivals.items():
- if median is not None:
- ax.text(0.98, y_pos, f'{group}: {median:.1f} months (95% CI {lower:.1f}-{upper:.1f})',
- transform=ax.transAxes, fontsize=9, ha='right',
- verticalalignment='top')
- else:
- ax.text(0.98, y_pos, f'{group}: Not reached',
- transform=ax.transAxes, fontsize=9, ha='right',
- verticalalignment='top')
- y_pos -= 0.05
-
- # Formatting
- ax.set_xlabel(xlabel, fontsize=12, fontweight='bold')
- ax.set_ylabel(ylabel, fontsize=12, fontweight='bold')
- ax.set_title(title, fontsize=14, fontweight='bold', pad=15)
- ax.legend(loc='lower left', frameon=True, fontsize=10)
- ax.grid(True, alpha=0.3, linestyle='--')
- ax.set_ylim([0, 1.05])
-
- plt.tight_layout()
-
- # Save figure
- plt.savefig(output_path, dpi=300, bbox_inches='tight')
- print(f"Survival curve saved to: {output_path}")
-
- # Also save as PNG for easy viewing
- png_path = Path(output_path).with_suffix('.png')
- plt.savefig(png_path, dpi=300, bbox_inches='tight')
- print(f"PNG version saved to: {png_path}")
-
- plt.close()
-
- return kmf_models, p_value
-
-
-def generate_number_at_risk_table(data, time_col='time', event_col='event',
- group_col='group', time_points=None):
- """
- Generate number at risk table for survival analysis.
-
- Parameters:
- data: DataFrame with survival data
- time_points: List of time points for risk table (if None, auto-generate)
-
- Returns:
- DataFrame with number at risk at each time point
- """
-
- if time_points is None:
- # Auto-generate time points (every 6 months up to max time)
- max_time = data[time_col].max()
- time_points = np.arange(0, max_time + 6, 6)
-
- groups = data[group_col].unique()
- risk_table = pd.DataFrame(index=time_points, columns=groups)
-
- for group in groups:
- group_data = data[data[group_col] == group]
-
- for t in time_points:
- # Number at risk = patients who haven't had event and haven't been censored before time t
- at_risk = len(group_data[group_data[time_col] >= t])
- risk_table.loc[t, group] = at_risk
-
- return risk_table
-
-
-def calculate_hazard_ratio(data, time_col='time', event_col='event', group_col='group',
- reference_group=None):
- """
- Calculate hazard ratio using Cox proportional hazards regression.
-
- Parameters:
- data: DataFrame
- reference_group: Reference group for comparison (if None, uses first group)
-
- Returns:
- Hazard ratio, 95% CI, p-value
- """
-
- # Encode group as binary for Cox regression
- groups = data[group_col].unique()
- if len(groups) != 2:
- print("Warning: Cox HR calculation assumes 2 groups. Using first 2 groups.")
- groups = groups[:2]
-
- if reference_group is None:
- reference_group = groups[0]
-
- # Create binary indicator (1 for comparison group, 0 for reference)
- data_cox = data.copy()
- data_cox['group_binary'] = (data_cox[group_col] != reference_group).astype(int)
-
- # Fit Cox model
- cph = CoxPHFitter()
- cph.fit(data_cox[[time_col, event_col, 'group_binary']],
- duration_col=time_col, event_col=event_col)
-
- # Extract results
- hr = np.exp(cph.params_['group_binary'])
- ci = np.exp(cph.confidence_intervals_.loc['group_binary'].values)
- p_value = cph.summary.loc['group_binary', 'p']
-
- return hr, ci[0], ci[1], p_value
-
-
-def generate_report(data, output_dir, prefix='survival'):
- """
- Generate comprehensive survival analysis report.
-
- Creates:
- - Kaplan-Meier curves (PDF and PNG)
- - Number at risk table (CSV)
- - Statistical summary (TXT)
- - LaTeX table code (TEX)
- """
-
- output_dir = Path(output_dir)
- output_dir.mkdir(parents=True, exist_ok=True)
-
- # Generate survival curve
- kmf_models, logrank_p = generate_kaplan_meier_plot(
- data,
- output_path=output_dir / f'{prefix}_kaplan_meier.pdf',
- title='Survival Analysis by Group'
- )
-
- # Number at risk table
- risk_table = generate_number_at_risk_table(data)
- risk_table.to_csv(output_dir / f'{prefix}_number_at_risk.csv')
-
- # Calculate hazard ratio
- hr, ci_lower, ci_upper, hr_p = calculate_hazard_ratio(data)
-
- # Generate statistical summary
- with open(output_dir / f'{prefix}_statistics.txt', 'w') as f:
- f.write("SURVIVAL ANALYSIS STATISTICAL SUMMARY\n")
- f.write("=" * 60 + "\n\n")
-
- groups = data['group'].unique()
- for group in groups:
- kmf = kmf_models[group]
- median = kmf.median_survival_time_
-
- # Calculate survival rates at common time points
- try:
- surv_12m = kmf.survival_function_at_times(12).values[0]
- surv_24m = kmf.survival_function_at_times(24).values[0] if data['time'].max() >= 24 else None
- except:
- surv_12m = None
- surv_24m = None
-
- f.write(f"Group: {group}\n")
- f.write(f" N = {len(data[data['group'] == group])}\n")
- f.write(f" Events = {data[data['group'] == group]['event'].sum()}\n")
- f.write(f" Median survival: {median:.1f} months\n" if median != np.inf else " Median survival: Not reached\n")
- if surv_12m is not None:
- f.write(f" 12-month survival rate: {surv_12m*100:.1f}%\n")
- if surv_24m is not None:
- f.write(f" 24-month survival rate: {surv_24m*100:.1f}%\n")
- f.write("\n")
-
- f.write(f"Log-Rank Test:\n")
- f.write(f" p-value = {logrank_p:.4f}\n")
- f.write(f" Interpretation: {'Significant' if logrank_p < 0.05 else 'Not significant'} difference in survival\n\n")
-
- if len(groups) == 2:
- f.write(f"Hazard Ratio ({groups[1]} vs {groups[0]}):\n")
- f.write(f" HR = {hr:.2f} (95% CI {ci_lower:.2f}-{ci_upper:.2f})\n")
- f.write(f" p-value = {hr_p:.4f}\n")
- f.write(f" Interpretation: {groups[1]} has {((1-hr)*100):.0f}% {'reduction' if hr < 1 else 'increase'} in risk\n")
-
- # Generate LaTeX table code
- with open(output_dir / f'{prefix}_latex_table.tex', 'w') as f:
- f.write("% LaTeX table code for survival outcomes\n")
- f.write("\\begin{table}[H]\n")
- f.write("\\centering\n")
- f.write("\\small\n")
- f.write("\\begin{tabular}{lcccc}\n")
- f.write("\\toprule\n")
- f.write("\\textbf{Endpoint} & \\textbf{Group A} & \\textbf{Group B} & \\textbf{HR (95\\% CI)} & \\textbf{p-value} \\\\\n")
- f.write("\\midrule\n")
-
- # Add median survival row
- for i, group in enumerate(groups):
- kmf = kmf_models[group]
- median = kmf.median_survival_time_
- if i == 0:
- f.write(f"Median survival, months (95\\% CI) & ")
- if median != np.inf:
- f.write(f"{median:.1f} & ")
- else:
- f.write("NR & ")
- else:
- if median != np.inf:
- f.write(f"{median:.1f} & ")
- else:
- f.write("NR & ")
-
- f.write(f"{hr:.2f} ({ci_lower:.2f}-{ci_upper:.2f}) & {hr_p:.3f} \\\\\n")
-
- # Add 12-month survival rate
- f.write("12-month survival rate (\\%) & ")
- for group in groups:
- kmf = kmf_models[group]
- try:
- surv_12m = kmf.survival_function_at_times(12).values[0]
- f.write(f"{surv_12m*100:.0f}\\% & ")
- except:
- f.write("-- & ")
- f.write("-- & -- \\\\\n")
-
- f.write("\\bottomrule\n")
- f.write("\\end{tabular}\n")
- f.write(f"\\caption{{Survival outcomes by group (log-rank p={logrank_p:.3f})}}\n")
- f.write("\\end{table}\n")
-
- print(f"\nAnalysis complete! Files saved to {output_dir}/")
- print(f" - Survival curves: {prefix}_kaplan_meier.pdf/png")
- print(f" - Statistics: {prefix}_statistics.txt")
- print(f" - LaTeX table: {prefix}_latex_table.tex")
- print(f" - Risk table: {prefix}_number_at_risk.csv")
-
-
-def main():
- parser = argparse.ArgumentParser(description='Generate Kaplan-Meier survival curves')
- parser.add_argument('input_file', type=str, help='CSV file with survival data')
- parser.add_argument('-o', '--output', type=str, default='survival_output',
- help='Output directory (default: survival_output)')
- parser.add_argument('-t', '--title', type=str, default='Kaplan-Meier Survival Curve',
- help='Plot title')
- parser.add_argument('-x', '--xlabel', type=str, default='Time (months)',
- help='X-axis label')
- parser.add_argument('-y', '--ylabel', type=str, default='Survival Probability',
- help='Y-axis label')
- parser.add_argument('--time-col', type=str, default='time',
- help='Column name for time variable')
- parser.add_argument('--event-col', type=str, default='event',
- help='Column name for event indicator')
- parser.add_argument('--group-col', type=str, default='group',
- help='Column name for grouping variable')
-
- args = parser.parse_args()
-
- # Load data
- print(f"Loading data from {args.input_file}...")
- data = load_survival_data(args.input_file)
- print(f"Loaded {len(data)} patients")
- print(f"Groups: {data[args.group_col].value_counts().to_dict()}")
-
- # Generate analysis
- generate_report(
- data,
- output_dir=args.output,
- prefix='survival'
- )
-
-
-if __name__ == '__main__':
- main()
-
-
-# Example usage:
-# python generate_survival_analysis.py survival_data.csv -o figures/ -t "PFS by PD-L1 Status"
-#
-# Input CSV format:
-# patient_id,time,event,group
-# PT001,12.3,1,PD-L1+
-# PT002,8.5,1,PD-L1-
-# PT003,18.2,0,PD-L1+
-# ...
-
diff --git a/skills/clinical-decision-support/scripts/model_biomarker_evaluation.py b/skills/clinical-decision-support/scripts/model_biomarker_evaluation.py
new file mode 100644
index 00000000..8c834587
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/model_biomarker_evaluation.py
@@ -0,0 +1,345 @@
+#!/usr/bin/env python3
+"""Create a bounded report from aggregate model/biomarker validation counts."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ finite_number,
+ load_json_object,
+ nonnegative_int,
+ print_report,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ write_json,
+)
+
+MAX_GROUPS = 12
+MAX_BINS = 30
+MAX_GROUP_N = 10_000_000
+
+
+def _wilson(successes: int, total: int) -> dict[str, Any]:
+ if total <= 0:
+ return {"estimate": None, "ci95": [None, None]}
+ z = 1.959963984540054
+ proportion = successes / total
+ denominator = 1.0 + (z * z / total)
+ center = (proportion + z * z / (2.0 * total)) / denominator
+ margin = (
+ z
+ * math.sqrt(
+ proportion * (1.0 - proportion) / total
+ + z * z / (4.0 * total * total)
+ )
+ / denominator
+ )
+ return {
+ "estimate": round(proportion, 6),
+ "ci95": [round(max(0.0, center - margin), 6), round(min(1.0, center + margin), 6)],
+ }
+
+
+def _small_nonzero(values: list[int], minimum: int) -> bool:
+ return any(0 < value < minimum for value in values)
+
+
+def _metric(successes: int, total: int) -> dict[str, Any]:
+ return _wilson(successes, total)
+
+
+def _calibration_summary(
+ bins: list[Any], group_name: str, minimum: int, expected_events: int
+) -> tuple[dict[str, Any], bool]:
+ total = 0
+ events = 0
+ weighted_predicted = 0.0
+ weighted_absolute_gap = 0.0
+ sensitive = False
+ for index, entry in enumerate(bins):
+ field = f"groups[{group_name}].calibration_bins[{index}]"
+ if not isinstance(entry, dict):
+ raise InputError(f"{field} must be an object")
+ count = nonnegative_int(entry.get("n"), f"{field}.n")
+ observed = nonnegative_int(
+ entry.get("observed_events"), f"{field}.observed_events"
+ )
+ predicted = finite_number(
+ entry.get("mean_predicted_probability"),
+ f"{field}.mean_predicted_probability",
+ )
+ if count == 0 or observed > count:
+ raise InputError(f"{field} has inconsistent counts")
+ if not 0.0 <= predicted <= 1.0:
+ raise InputError(f"{field}.mean_predicted_probability must be in [0, 1]")
+ observed_rate = observed / count
+ total += count
+ events += observed
+ weighted_predicted += count * predicted
+ weighted_absolute_gap += count * abs(predicted - observed_rate)
+ sensitive = sensitive or _small_nonzero(
+ [count, observed, count - observed], minimum
+ )
+ if events != expected_events:
+ raise InputError(
+ f"Calibration observed events for {group_name} do not match confusion counts"
+ )
+ if total == 0:
+ raise InputError(f"Calibration bins for {group_name} are empty")
+ if sensitive:
+ return (
+ {
+ "suppressed": True,
+ "reason": "One or more calibration cells are below the disclosure threshold",
+ },
+ True,
+ )
+ observed_rate = events / total
+ mean_predicted = weighted_predicted / total
+ return (
+ {
+ "suppressed": False,
+ "n": total,
+ "observed_rate": round(observed_rate, 6),
+ "mean_predicted_probability": round(mean_predicted, 6),
+ "calibration_in_the_large_gap": round(mean_predicted - observed_rate, 6),
+ "weighted_absolute_calibration_gap": round(
+ weighted_absolute_gap / total, 6
+ ),
+ "limitations": (
+ "Aggregate-bin calibration is approximate and cannot estimate a "
+ "calibration slope or replace individual-level validation."
+ ),
+ },
+ False,
+ )
+
+
+def evaluate(
+ document: dict[str, Any], minimum: int
+) -> tuple[IssueLog, dict[str, Any]]:
+ log = IssueLog()
+ report: dict[str, Any] = {
+ "report_type": "aggregate_model_biomarker_evaluation",
+ "individual_output_generated": False,
+ "clinical_classification_generated": False,
+ "recommendation_generated": False,
+ "groups": [],
+ "subgroup_performance_differences": {},
+ }
+ metric_values: dict[str, list[tuple[str, float]]] = {}
+
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version")
+ known_sources = source_ids(document)
+ metadata = document.get("metadata")
+ if not isinstance(metadata, dict):
+ raise InputError("metadata must be an object")
+ for field in (
+ "evaluation_id",
+ "title",
+ "evaluation_target",
+ "target_version",
+ "purpose",
+ "population",
+ "setting",
+ "outcome",
+ "outcome_horizon",
+ "threshold",
+ "threshold_source_id",
+ "validation_dataset",
+ "data_cut_date",
+ ):
+ require_nonempty_text(metadata.get(field), f"metadata.{field}")
+ if metadata.get("data_level") not in {"aggregate", "synthetic"}:
+ log.errors.append("metadata.data_level must be aggregate or synthetic")
+ if metadata.get("person_level_output") is not False:
+ log.errors.append("metadata.person_level_output must be false")
+ if metadata.get("threshold_pre_specified") is not True:
+ log.errors.append("metadata.threshold_pre_specified must be true")
+ if metadata.get("threshold_source_id") not in known_sources:
+ log.errors.append("metadata.threshold_source_id must reference sources")
+ if metadata.get("external_validation") is not True:
+ log.warnings.append("Independent external validation is not documented")
+ if metadata.get("human_review_required") is not True:
+ log.errors.append("metadata.human_review_required must be true")
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ if review.get("required") is not True:
+ log.errors.append("human_review.required must be true")
+ roles = require_list(review.get("roles"), "human_review.roles", maximum=20)
+ if not roles:
+ log.errors.append("At least one human-review role is required")
+ for index, role in enumerate(roles):
+ require_nonempty_text(role, f"human_review.roles[{index}]")
+ if review.get("completed") is not True:
+ log.warnings.append("Human review is not recorded as complete")
+
+ governance = document.get("governance")
+ if not isinstance(governance, dict):
+ raise InputError("governance must be an object")
+ for field in (
+ "owner",
+ "version_and_change_control",
+ "monitoring",
+ "auditability",
+ "human_factors",
+ "rollback_and_retirement",
+ ):
+ require_nonempty_text(governance.get(field), f"governance.{field}")
+
+ groups = require_list(document.get("groups"), "groups", maximum=MAX_GROUPS)
+ if not groups:
+ raise InputError("At least one aggregate group is required")
+ names: set[str] = set()
+ for index, group in enumerate(groups):
+ field = f"groups[{index}]"
+ if not isinstance(group, dict):
+ raise InputError(f"{field} must be an object")
+ name = require_nonempty_text(group.get("name"), f"{field}.name", max_length=100)
+ if name in names:
+ raise InputError(f"Duplicate group name: {name}")
+ names.add(name)
+ n = nonnegative_int(group.get("n"), f"{field}.n")
+ if n == 0 or n > MAX_GROUP_N:
+ raise InputError(f"{field}.n must be between 1 and {MAX_GROUP_N}")
+ confusion = group.get("confusion")
+ if not isinstance(confusion, dict):
+ raise InputError(f"{field}.confusion must be an object")
+ tp = nonnegative_int(confusion.get("tp"), f"{field}.confusion.tp")
+ fp = nonnegative_int(confusion.get("fp"), f"{field}.confusion.fp")
+ tn = nonnegative_int(confusion.get("tn"), f"{field}.confusion.tn")
+ fn = nonnegative_int(confusion.get("fn"), f"{field}.confusion.fn")
+ cells = [tp, fp, tn, fn]
+ if sum(cells) != n:
+ raise InputError(f"{field}.confusion counts must sum to n")
+
+ group_result: dict[str, Any] = {"name": name}
+ if n < minimum or _small_nonzero(cells, minimum):
+ group_result.update(
+ {
+ "suppressed": True,
+ "reason": (
+ "Group or contributing confusion cell is below the "
+ "disclosure threshold"
+ ),
+ }
+ )
+ else:
+ metrics = {
+ "sensitivity": _metric(tp, tp + fn),
+ "specificity": _metric(tn, tn + fp),
+ "positive_predictive_value": _metric(tp, tp + fp),
+ "negative_predictive_value": _metric(tn, tn + fn),
+ "accuracy": _metric(tp + tn, n),
+ "prevalence": _metric(tp + fn, n),
+ }
+ sensitivity = metrics["sensitivity"]["estimate"]
+ specificity = metrics["specificity"]["estimate"]
+ metrics["balanced_accuracy"] = {
+ "estimate": round((sensitivity + specificity) / 2.0, 6),
+ "ci95": None,
+ }
+ group_result.update(
+ {"suppressed": False, "n": n, "metrics": metrics}
+ )
+ for metric_name, metric in metrics.items():
+ estimate = metric.get("estimate")
+ if estimate is not None:
+ metric_values.setdefault(metric_name, []).append(
+ (name, float(estimate))
+ )
+
+ bins = require_list(
+ group.get("calibration_bins"),
+ f"{field}.calibration_bins",
+ maximum=MAX_BINS,
+ )
+ calibration, _ = _calibration_summary(
+ bins, name, minimum, expected_events=tp + fn
+ )
+ if not calibration.get("suppressed") and calibration["n"] != n:
+ raise InputError(f"{field}.calibration_bins counts must sum to n")
+ group_result["calibration"] = calibration
+ report["groups"].append(group_result)
+
+ for metric_name, values in metric_values.items():
+ if len(values) < 2:
+ continue
+ estimates = [value for _, value in values]
+ low_name, low = min(values, key=lambda item: item[1])
+ high_name, high = max(values, key=lambda item: item[1])
+ report["subgroup_performance_differences"][metric_name] = {
+ "maximum_absolute_difference": round(high - low, 6),
+ "lowest_group": low_name,
+ "highest_group": high_name,
+ "interpretation": (
+ "Descriptive difference only; it is not a fairness judgment "
+ "and may reflect case mix, measurement, sampling, or model behavior."
+ ),
+ }
+ if len(groups) < 2:
+ log.warnings.append("Only one group supplied; subgroup comparisons are unavailable")
+ if not report["subgroup_performance_differences"]:
+ log.warnings.append(
+ "Subgroup differences were not estimable after disclosure suppression"
+ )
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ report["disclosure_threshold"] = minimum
+ report["limitations"] = [
+ "Input is aggregate and cannot support person-level output.",
+ "Metrics do not establish clinical validity, clinical utility, safety, or fairness.",
+ "Wilson intervals do not account for clustering, repeated observations, censoring, or verification bias.",
+ "Calibration bins are lossy summaries and cannot estimate calibration slope.",
+ ]
+ if log.ok:
+ log.info.append("Aggregate evaluation completed without person-level output")
+ return log, report
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Report bounded descriptive performance from local aggregate counts. "
+ "Never emits a person-level class or clinical recommendation."
+ )
+ )
+ parser.add_argument("input", help="Local aggregate JSON")
+ parser.add_argument("-o", "--output", help="Optional local JSON report")
+ parser.add_argument(
+ "--min-cell-size",
+ type=int,
+ default=11,
+ help="Suppress contributing nonzero cells below this value (default: 11)",
+ )
+ args = parser.parse_args()
+ if not 2 <= args.min_cell_size <= 1_000:
+ parser.error("--min-cell-size must be between 2 and 1000")
+
+ try:
+ document = load_json_object(args.input)
+ log, details = evaluate(document, args.min_cell_size)
+ result = log.as_dict()
+ result["evaluation"] = details
+ if args.output:
+ write_json(args.output, result)
+ print_report(result)
+ except InputError as exc:
+ print_report(IssueLog(errors=[str(exc)]).as_dict())
+ return 2
+ return 0 if result["status"] == "pass" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/survival_plan_validator.py b/skills/clinical-decision-support/scripts/survival_plan_validator.py
new file mode 100644
index 00000000..40d3cd02
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/survival_plan_validator.py
@@ -0,0 +1,294 @@
+#!/usr/bin/env python3
+"""Validate an estimand-led survival-analysis plan without reading subject rows."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ print_report,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ validate_references,
+ write_json,
+)
+
+ALLOWED_METHODS = {
+ "kaplan_meier",
+ "cox_proportional_hazards",
+ "flexible_parametric",
+ "restricted_mean_survival_time",
+ "accelerated_failure_time",
+ "cumulative_incidence",
+ "cause_specific_hazard",
+ "fine_gray",
+ "multi_state",
+ "other_justified",
+}
+COMPETING_METHODS = {
+ "cumulative_incidence",
+ "cause_specific_hazard",
+ "fine_gray",
+ "multi_state",
+ "other_justified",
+}
+
+
+def validate_plan(document: dict[str, Any]) -> IssueLog:
+ log = IssueLog()
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version")
+ known_sources = source_ids(document)
+
+ metadata = document.get("metadata")
+ if not isinstance(metadata, dict):
+ raise InputError("metadata must be an object")
+ for field in ("plan_id", "title", "version", "status", "purpose", "data_cut_date"):
+ require_nonempty_text(metadata.get(field), f"metadata.{field}")
+ if metadata.get("data_level") not in {"aggregate", "synthetic", "plan_only"}:
+ log.errors.append("metadata.data_level must be aggregate, synthetic, or plan_only")
+ if metadata.get("raw_rows_supplied") is not False:
+ log.errors.append("metadata.raw_rows_supplied must be false")
+ if metadata.get("patient_care_use") is not False:
+ log.errors.append("metadata.patient_care_use must be false")
+ if metadata.get("human_review_required") is not True:
+ log.errors.append("metadata.human_review_required must be true")
+
+ estimand = document.get("estimand")
+ if not isinstance(estimand, dict):
+ raise InputError("estimand must be an object")
+ for field in (
+ "population",
+ "condition_or_comparison",
+ "endpoint_variable",
+ "population_summary",
+ "time_horizon",
+ "rationale",
+ ):
+ require_nonempty_text(estimand.get(field), f"estimand.{field}")
+ intercurrent = require_list(
+ estimand.get("intercurrent_events"),
+ "estimand.intercurrent_events",
+ maximum=30,
+ )
+ if not intercurrent:
+ log.errors.append(
+ "estimand.intercurrent_events must document events or explicitly state none"
+ )
+ for index, item in enumerate(intercurrent):
+ if not isinstance(item, dict):
+ raise InputError(f"estimand.intercurrent_events[{index}] must be an object")
+ require_nonempty_text(
+ item.get("event"), f"estimand.intercurrent_events[{index}].event"
+ )
+ require_nonempty_text(
+ item.get("strategy"), f"estimand.intercurrent_events[{index}].strategy"
+ )
+ require_nonempty_text(
+ item.get("rationale"), f"estimand.intercurrent_events[{index}].rationale"
+ )
+
+ endpoint = document.get("endpoint")
+ if not isinstance(endpoint, dict):
+ raise InputError("endpoint must be an object")
+ for field in (
+ "time_zero",
+ "event_definition",
+ "time_scale",
+ "ascertainment",
+ "follow_up_end",
+ "delayed_entry",
+ "same_time_rules",
+ ):
+ require_nonempty_text(endpoint.get(field), f"endpoint.{field}")
+ censoring = require_list(
+ endpoint.get("censoring_rules"), "endpoint.censoring_rules", maximum=30
+ )
+ if not censoring:
+ log.errors.append("At least one censoring rule is required")
+ for index, rule in enumerate(censoring):
+ require_nonempty_text(rule, f"endpoint.censoring_rules[{index}]")
+ competing = require_list(
+ endpoint.get("competing_events"), "endpoint.competing_events", maximum=20
+ )
+ for index, event in enumerate(competing):
+ require_nonempty_text(event, f"endpoint.competing_events[{index}]")
+
+ analysis = document.get("analysis")
+ if not isinstance(analysis, dict):
+ raise InputError("analysis must be an object")
+ primary_method = require_nonempty_text(
+ analysis.get("primary_method"), "analysis.primary_method"
+ )
+ if primary_method not in ALLOWED_METHODS:
+ log.errors.append(f"Unsupported analysis.primary_method: {primary_method}")
+ for field in (
+ "effect_measure",
+ "analysis_population",
+ "covariate_strategy",
+ "missing_data",
+ "multiplicity",
+ "uncertainty",
+ "software_and_version",
+ "model_diagnostics",
+ ):
+ require_nonempty_text(analysis.get(field), f"analysis.{field}")
+
+ ph_assessment = require_nonempty_text(
+ analysis.get("proportional_hazards_assessment"),
+ "analysis.proportional_hazards_assessment",
+ )
+ non_ph_strategy = require_nonempty_text(
+ analysis.get("non_proportional_hazards_strategy"),
+ "analysis.non_proportional_hazards_strategy",
+ )
+ effect_measure = str(analysis.get("effect_measure", "")).lower()
+ if (
+ primary_method == "cox_proportional_hazards"
+ or "hazard ratio" in effect_measure
+ ):
+ if ph_assessment.lower() in {"none", "not applicable", "n/a"}:
+ log.errors.append(
+ "A proportional-hazards assessment is required for a hazard-ratio plan"
+ )
+ if non_ph_strategy.lower() in {"none", "not applicable", "n/a"}:
+ log.errors.append(
+ "Pre-specify an alternative if proportional hazards is not supported"
+ )
+
+ competing_method = require_nonempty_text(
+ analysis.get("competing_risk_method"),
+ "analysis.competing_risk_method",
+ )
+ if competing:
+ if competing_method not in COMPETING_METHODS:
+ log.errors.append(
+ "A competing-risk method is required when competing events are listed"
+ )
+ if (
+ primary_method == "kaplan_meier"
+ and "absolute" in effect_measure
+ ):
+ log.errors.append(
+ "Kaplan-Meier with competing events cannot be the sole absolute-incidence method"
+ )
+ elif competing_method not in {"not_applicable", "none"}:
+ log.warnings.append(
+ "A competing-risk method is named but no competing events are listed"
+ )
+
+ bias = document.get("bias_controls")
+ if not isinstance(bias, dict):
+ raise InputError("bias_controls must be an object")
+ for field in (
+ "informative_censoring",
+ "immortal_time",
+ "time_dependent_confounding",
+ "outcome_misclassification",
+ "informative_visits",
+ ):
+ require_nonempty_text(bias.get(field), f"bias_controls.{field}")
+
+ sensitivity = require_list(
+ document.get("sensitivity_analyses"),
+ "sensitivity_analyses",
+ maximum=30,
+ )
+ if len(sensitivity) < 2:
+ log.warnings.append("Fewer than two sensitivity analyses are specified")
+ for index, item in enumerate(sensitivity):
+ require_nonempty_text(item, f"sensitivity_analyses[{index}]")
+
+ subgroups = document.get("subgroups")
+ if not isinstance(subgroups, dict):
+ raise InputError("subgroups must be an object")
+ for field in (
+ "prespecification",
+ "interaction_testing",
+ "multiplicity",
+ "precision_and_disclosure",
+ ):
+ require_nonempty_text(subgroups.get(field), f"subgroups.{field}")
+
+ validation = document.get("validation")
+ if not isinstance(validation, dict):
+ raise InputError("validation must be an object")
+ for field in (
+ "internal_validation",
+ "external_validation",
+ "calibration",
+ "subgroup_performance",
+ ):
+ require_nonempty_text(validation.get(field), f"validation.{field}")
+ if "not performed" in str(validation.get("external_validation")).lower():
+ log.warnings.append("External validation is documented as not performed")
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ roles = require_list(review.get("roles"), "human_review.roles", maximum=20)
+ if not roles:
+ log.errors.append("At least one human-review role is required")
+ for index, role in enumerate(roles):
+ require_nonempty_text(role, f"human_review.roles[{index}]")
+ require_nonempty_text(review.get("approval_boundary"), "human_review.approval_boundary")
+ if review.get("completed") is not True:
+ log.warnings.append("Human review is not recorded as complete")
+
+ governance = document.get("governance")
+ if not isinstance(governance, dict):
+ raise InputError("governance must be an object")
+ for field in (
+ "owner",
+ "change_control",
+ "auditability",
+ "monitoring",
+ "retirement",
+ ):
+ require_nonempty_text(governance.get(field), f"governance.{field}")
+
+ validate_references(document.get("source_ids"), known_sources, "source_ids")
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ if log.ok:
+ log.info.append("Survival plan contains the required estimand and analysis fields")
+ return log
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a local survival-analysis plan. No subject-level data are read "
+ "and no survival model is fitted."
+ )
+ )
+ parser.add_argument("input", help="Local plan JSON")
+ parser.add_argument("-o", "--output", help="Optional local JSON report")
+ parser.add_argument(
+ "--strict", action="store_true", help="Return failure when warnings are present"
+ )
+ args = parser.parse_args()
+
+ try:
+ document = load_json_object(args.input)
+ report = validate_plan(document).as_dict()
+ if args.output:
+ write_json(args.output, report)
+ print_report(report)
+ except InputError as exc:
+ print_report(IssueLog(errors=[str(exc)]).as_dict())
+ return 2
+ if report["status"] != "pass" or (args.strict and report["warnings"]):
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/validate_cds_artifact.py b/skills/clinical-decision-support/scripts/validate_cds_artifact.py
new file mode 100644
index 00000000..43fdac1d
--- /dev/null
+++ b/skills/clinical-decision-support/scripts/validate_cds_artifact.py
@@ -0,0 +1,269 @@
+#!/usr/bin/env python3
+"""Validate intended use and governance fields for research-only CDS artifacts."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from typing import Any
+
+from _common import (
+ InputError,
+ IssueLog,
+ load_json_object,
+ print_report,
+ require_list,
+ require_nonempty_text,
+ source_ids,
+ write_json,
+)
+
+ALLOWED_TYPES = {
+ "aggregate_cohort_evaluation",
+ "evidence_profile",
+ "model_biomarker_evaluation",
+ "research_analysis_plan",
+ "governance_traceability",
+ "privacy_process_checklist",
+}
+ALLOWED_STATUSES = {"draft", "evaluation_only", "retired"}
+ALLOWED_DATA_LEVELS = {"aggregate", "synthetic", "aggregate_and_synthetic"}
+REQUIRED_PROHIBITIONS = {
+ "patient-specific",
+ "diagnosis",
+ "treatment recommendation",
+ "dosing",
+ "triage",
+ "autonomous decision",
+ "alarm",
+ "bedside",
+ "live clinical",
+ "regulatory compliance",
+ "hipaa compliance",
+}
+UNSAFE_OUTPUT_KEYS = {
+ "alarm",
+ "care_plan",
+ "clinical_action",
+ "diagnosis",
+ "dose",
+ "dosing",
+ "patient_class",
+ "patient_prediction",
+ "recommendation",
+ "treatment_recommendation",
+ "triage",
+ "urgency",
+}
+PLACEHOLDER_MARKERS = ("REPLACE_", "REQUIRES_", "YYYY-MM-DD")
+
+
+def _find_unsafe_keys(value: Any, location: str = "$") -> list[str]:
+ findings: list[str] = []
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ normalized = str(key).strip().lower()
+ if normalized in UNSAFE_OUTPUT_KEYS:
+ findings.append(f"{location}.{key}")
+ findings.extend(_find_unsafe_keys(nested, f"{location}.{key}"))
+ elif isinstance(value, list):
+ for index, nested in enumerate(value):
+ findings.extend(_find_unsafe_keys(nested, f"{location}[{index}]"))
+ return findings
+
+
+def _find_placeholders(value: Any, location: str = "$") -> list[str]:
+ findings: list[str] = []
+ if isinstance(value, dict):
+ for key, nested in value.items():
+ findings.extend(_find_placeholders(nested, f"{location}.{key}"))
+ elif isinstance(value, list):
+ for index, nested in enumerate(value):
+ findings.extend(_find_placeholders(nested, f"{location}[{index}]"))
+ elif isinstance(value, str) and any(marker in value for marker in PLACEHOLDER_MARKERS):
+ findings.append(location)
+ return findings
+
+
+def validate_artifact(document: dict[str, Any]) -> IssueLog:
+ log = IssueLog()
+ try:
+ require_nonempty_text(document.get("schema_version"), "schema_version", max_length=20)
+ known_sources = source_ids(document)
+ if not known_sources:
+ log.errors.append("At least one source is required")
+
+ artifact = document.get("artifact")
+ if not isinstance(artifact, dict):
+ raise InputError("artifact must be an object")
+ for field in ("id", "title", "version", "owner", "date", "change_summary"):
+ require_nonempty_text(artifact.get(field), f"artifact.{field}")
+ artifact_type = require_nonempty_text(
+ artifact.get("type"), "artifact.type", max_length=100
+ )
+ if artifact_type not in ALLOWED_TYPES:
+ log.errors.append(f"artifact.type is not allowed: {artifact_type}")
+ status = require_nonempty_text(
+ artifact.get("status"), "artifact.status", max_length=30
+ )
+ if status not in ALLOWED_STATUSES:
+ log.errors.append(
+ "artifact.status must be draft, evaluation_only, or retired"
+ )
+
+ intended = document.get("intended_use")
+ if not isinstance(intended, dict):
+ raise InputError("intended_use must be an object")
+ require_nonempty_text(intended.get("purpose"), "intended_use.purpose")
+ users = require_list(
+ intended.get("intended_users"), "intended_use.intended_users", maximum=20
+ )
+ if not users:
+ log.errors.append("At least one intended user role is required")
+ for index, user in enumerate(users):
+ require_nonempty_text(user, f"intended_use.intended_users[{index}]")
+ if intended.get("population_scope") != "aggregate_or_synthetic_only":
+ log.errors.append(
+ "intended_use.population_scope must be aggregate_or_synthetic_only"
+ )
+ if intended.get("decision_role") != "research_evaluation_governance_only":
+ log.errors.append(
+ "intended_use.decision_role must be "
+ "research_evaluation_governance_only"
+ )
+ boundary = require_nonempty_text(
+ intended.get("boundary_statement"), "intended_use.boundary_statement"
+ ).lower()
+ if "not for patient care or live clinical use" not in boundary:
+ log.errors.append(
+ "Boundary statement must say: Not for patient care or live clinical use"
+ )
+
+ prohibited = require_list(
+ document.get("prohibited_uses"), "prohibited_uses", maximum=40
+ )
+ prohibited_text = " ".join(
+ require_nonempty_text(item, f"prohibited_uses[{index}]")
+ for index, item in enumerate(prohibited)
+ ).lower()
+ missing = sorted(
+ phrase for phrase in REQUIRED_PROHIBITIONS if phrase not in prohibited_text
+ )
+ if missing:
+ log.errors.append(
+ "prohibited_uses is missing required concepts: " + ", ".join(missing)
+ )
+
+ data = document.get("data_governance")
+ if not isinstance(data, dict):
+ raise InputError("data_governance must be an object")
+ if data.get("data_level") not in ALLOWED_DATA_LEVELS:
+ log.errors.append("data_governance.data_level must be aggregate or synthetic")
+ if data.get("phi_supplied") is not False:
+ log.errors.append("data_governance.phi_supplied must be false")
+ if data.get("raw_rows_supplied") is not False:
+ log.errors.append("data_governance.raw_rows_supplied must be false")
+ for field in ("provenance", "data_cut_date", "disclosure_policy"):
+ require_nonempty_text(data.get(field), f"data_governance.{field}")
+
+ limitations = require_list(
+ document.get("limitations"), "limitations", maximum=40
+ )
+ if len(limitations) < 3:
+ log.errors.append("At least three limitations are required")
+ for index, limitation in enumerate(limitations):
+ require_nonempty_text(limitation, f"limitations[{index}]")
+
+ review = document.get("human_review")
+ if not isinstance(review, dict):
+ raise InputError("human_review must be an object")
+ if review.get("required") is not True:
+ log.errors.append("human_review.required must be true")
+ roles = require_list(review.get("roles"), "human_review.roles", maximum=20)
+ if not roles:
+ log.errors.append("At least one human review role is required")
+ for index, role in enumerate(roles):
+ require_nonempty_text(role, f"human_review.roles[{index}]")
+ require_nonempty_text(
+ review.get("approval_boundary"), "human_review.approval_boundary"
+ )
+ if review.get("completed") is not True:
+ log.warnings.append("Human review is not recorded as complete")
+
+ validation = document.get("validation")
+ if not isinstance(validation, dict):
+ raise InputError("validation must be an object")
+ for field in (
+ "external_validation",
+ "calibration",
+ "subgroup_fairness",
+ "uncertainty",
+ "human_factors",
+ ):
+ require_nonempty_text(validation.get(field), f"validation.{field}")
+
+ lifecycle = document.get("lifecycle")
+ if not isinstance(lifecycle, dict):
+ raise InputError("lifecycle must be an object")
+ for field in (
+ "monitoring_plan",
+ "change_control",
+ "audit_plan",
+ "retirement_criteria",
+ ):
+ require_nonempty_text(lifecycle.get(field), f"lifecycle.{field}")
+
+ if document.get("compliance_claims") is not False:
+ log.errors.append("compliance_claims must be false")
+
+ unsafe_locations = _find_unsafe_keys(document)
+ if unsafe_locations:
+ log.errors.append(
+ "Unsafe clinical-output keys are prohibited: "
+ + ", ".join(unsafe_locations[:10])
+ )
+ placeholders = _find_placeholders(document)
+ if placeholders:
+ log.errors.append(
+ "Unresolved template placeholders remain: "
+ + ", ".join(placeholders[:10])
+ )
+ except InputError as exc:
+ log.errors.append(str(exc))
+
+ if log.ok:
+ log.info.append("Required intended-use and governance fields are complete")
+ return log
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a bounded local JSON metadata artifact. Structural checks only; "
+ "never a clinical or compliance determination."
+ )
+ )
+ parser.add_argument("input", help="Local JSON artifact")
+ parser.add_argument("-o", "--output", help="Optional local JSON report")
+ parser.add_argument(
+ "--strict", action="store_true", help="Return failure when warnings are present"
+ )
+ args = parser.parse_args()
+
+ try:
+ document = load_json_object(args.input)
+ result = validate_artifact(document).as_dict()
+ if args.output:
+ write_json(args.output, result)
+ print_report(result)
+ except InputError as exc:
+ result = IssueLog(errors=[str(exc)]).as_dict()
+ print_report(result)
+ return 2
+ if result["status"] != "pass" or (args.strict and result["warnings"]):
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/clinical-decision-support/scripts/validate_cds_document.py b/skills/clinical-decision-support/scripts/validate_cds_document.py
deleted file mode 100755
index 41082e46..00000000
--- a/skills/clinical-decision-support/scripts/validate_cds_document.py
+++ /dev/null
@@ -1,335 +0,0 @@
-#!/usr/bin/env python3
-"""
-Validate Clinical Decision Support Documents for Quality and Completeness
-
-Checks for:
-- Evidence citations for all recommendations
-- Statistical reporting completeness
-- Biomarker nomenclature consistency
-- Required sections present
-- HIPAA de-identification
-- GRADE recommendation format
-
-Dependencies: None (pure Python)
-"""
-
-import re
-import argparse
-from pathlib import Path
-from collections import defaultdict
-
-
-class CDSValidator:
- """Validator for clinical decision support documents."""
-
- def __init__(self, filepath):
- self.filepath = filepath
- with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
- self.content = f.read()
-
- self.errors = []
- self.warnings = []
- self.info = []
-
- def validate_all(self):
- """Run all validation checks."""
-
- print(f"Validating: {self.filepath}")
- print("="*70)
-
- self.check_required_sections()
- self.check_evidence_citations()
- self.check_recommendation_grading()
- self.check_statistical_reporting()
- self.check_hipaa_identifiers()
- self.check_biomarker_nomenclature()
-
- return self.generate_report()
-
- def check_required_sections(self):
- """Check if required sections are present."""
-
- # Cohort analysis required sections
- cohort_sections = [
- 'cohort characteristics',
- 'biomarker',
- 'outcomes',
- 'statistical analysis',
- 'clinical implications',
- 'references'
- ]
-
- # Treatment recommendation required sections
- rec_sections = [
- 'evidence',
- 'recommendation',
- 'monitoring',
- 'references'
- ]
-
- content_lower = self.content.lower()
-
- # Check which document type
- is_cohort = 'cohort' in content_lower
- is_recommendation = 'recommendation' in content_lower
-
- if is_cohort:
- missing = [sec for sec in cohort_sections if sec not in content_lower]
- if missing:
- self.warnings.append(f"Cohort analysis may be missing sections: {', '.join(missing)}")
- else:
- self.info.append("All cohort analysis sections present")
-
- if is_recommendation:
- missing = [sec for sec in rec_sections if sec not in content_lower]
- if missing:
- self.errors.append(f"Recommendation document missing required sections: {', '.join(missing)}")
- else:
- self.info.append("All recommendation sections present")
-
- def check_evidence_citations(self):
- """Check that recommendations have citations."""
-
- # Find recommendation statements
- rec_pattern = r'(recommend|should|prefer|suggest|consider)(.*?)(?:\n\n|\Z)'
- recommendations = re.findall(rec_pattern, self.content, re.IGNORECASE | re.DOTALL)
-
- # Find citations
- citation_patterns = [
- r'\[\d+\]', # Numbered citations [1]
- r'\(.*?\d{4}\)', # Author year (Smith 2020)
- r'et al\.', # Et al citations
- r'NCCN|ASCO|ESMO', # Guideline references
- ]
-
- uncited_recommendations = []
-
- for i, (_, rec_text) in enumerate(recommendations):
- has_citation = any(re.search(pattern, rec_text) for pattern in citation_patterns)
-
- if not has_citation:
- snippet = rec_text[:60].strip() + '...'
- uncited_recommendations.append(snippet)
-
- if uncited_recommendations:
- self.warnings.append(f"Found {len(uncited_recommendations)} recommendations without citations")
- for rec in uncited_recommendations[:3]: # Show first 3
- self.warnings.append(f" - {rec}")
- else:
- self.info.append(f"All {len(recommendations)} recommendations have citations")
-
- def check_recommendation_grading(self):
- """Check for GRADE-style recommendation strength."""
-
- # Look for GRADE notation (1A, 1B, 2A, 2B, 2C)
- grade_pattern = r'GRADE\s*[12][A-C]|Grade\s*[12][A-C]|\(?\s*[12][A-C]\s*\)?'
- grades = re.findall(grade_pattern, self.content, re.IGNORECASE)
-
- # Look for strong/conditional language
- strong_pattern = r'(strong|we recommend|should)'
- conditional_pattern = r'(conditional|weak|we suggest|may consider|could consider)'
-
- strong_count = len(re.findall(strong_pattern, self.content, re.IGNORECASE))
- conditional_count = len(re.findall(conditional_pattern, self.content, re.IGNORECASE))
-
- if grades:
- self.info.append(f"Found {len(grades)} GRADE-style recommendations")
- else:
- self.warnings.append("No GRADE-style recommendation grading found (1A, 1B, 2A, etc.)")
-
- if strong_count > 0 or conditional_count > 0:
- self.info.append(f"Recommendation language: {strong_count} strong, {conditional_count} conditional")
- else:
- self.warnings.append("No clear recommendation strength language (strong/conditional) found")
-
- def check_statistical_reporting(self):
- """Check for proper statistical reporting."""
-
- # Check for p-values
- p_values = re.findall(r'p\s*[=<>]\s*[\d.]+', self.content, re.IGNORECASE)
-
- # Check for confidence intervals
- ci_pattern = r'95%\s*CI|confidence interval'
- cis = re.findall(ci_pattern, self.content, re.IGNORECASE)
-
- # Check for hazard ratios
- hr_pattern = r'HR\s*[=:]\s*[\d.]+'
- hrs = re.findall(hr_pattern, self.content)
-
- # Check for sample sizes
- n_pattern = r'n\s*=\s*\d+'
- sample_sizes = re.findall(n_pattern, self.content, re.IGNORECASE)
-
- if not p_values:
- self.warnings.append("No p-values found - statistical significance not reported")
- else:
- self.info.append(f"Found {len(p_values)} p-values")
-
- if hrs and not cis:
- self.warnings.append("Hazard ratios reported without confidence intervals")
-
- if not sample_sizes:
- self.warnings.append("Sample sizes (n=X) not clearly reported")
-
- # Check for common statistical errors
- if 'p=0.00' in self.content or 'p = 0.00' in self.content:
- self.warnings.append("Found p=0.00 (should report as p<0.001 instead)")
-
- def check_hipaa_identifiers(self):
- """Check for potential HIPAA identifiers."""
-
- # 18 HIPAA identifiers (simplified check for common ones)
- identifiers = {
- 'Names': r'Dr\.\s+[A-Z][a-z]+|Patient:\s*[A-Z][a-z]+',
- 'Specific dates': r'\d{1,2}/\d{1,2}/\d{4}', # MM/DD/YYYY
- 'Phone numbers': r'\d{3}[-.]?\d{3}[-.]?\d{4}',
- 'Email addresses': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
- 'SSN': r'\d{3}-\d{2}-\d{4}',
- 'MRN': r'MRN\s*:?\s*\d+',
- }
-
- found_identifiers = []
-
- for identifier_type, pattern in identifiers.items():
- matches = re.findall(pattern, self.content)
- if matches:
- found_identifiers.append(f"{identifier_type}: {len(matches)} instance(s)")
-
- if found_identifiers:
- self.errors.append("Potential HIPAA identifiers detected:")
- for identifier in found_identifiers:
- self.errors.append(f" - {identifier}")
- self.errors.append(" ** Ensure proper de-identification before distribution **")
- else:
- self.info.append("No obvious HIPAA identifiers detected (basic check only)")
-
- def check_biomarker_nomenclature(self):
- """Check for consistent biomarker nomenclature."""
-
- # Common biomarker naming issues
- issues = []
-
- # Check for gene names (should be italicized in LaTeX)
- gene_names = ['EGFR', 'ALK', 'ROS1', 'BRAF', 'KRAS', 'HER2', 'TP53', 'BRCA1', 'BRCA2']
- for gene in gene_names:
- # Check if gene appears but not in italics (\textit{} or \emph{})
- if gene in self.content:
- if f'\\textit{{{gene}}}' not in self.content and f'\\emph{{{gene}}}' not in self.content:
- if '.tex' in self.filepath.suffix:
- issues.append(f"{gene} should be italicized in LaTeX (\\textit{{{gene}}})")
-
- # Check for protein vs gene naming
- # HER2 (protein) vs ERBB2 (gene) - both valid
- # Check for mutation nomenclature (HGVS format)
- hgvs_pattern = r'p\.[A-Z]\d+[A-Z]' # e.g., p.L858R
- hgvs_mutations = re.findall(hgvs_pattern, self.content)
-
- if hgvs_mutations:
- self.info.append(f"Found {len(hgvs_mutations)} HGVS protein nomenclature (e.g., p.L858R)")
-
- # Warn about non-standard mutation format
- if 'EGFR mutation' in self.content and 'exon' not in self.content.lower():
- self.warnings.append("EGFR mutation mentioned - specify exon/variant (e.g., exon 19 deletion)")
-
- if issues:
- self.warnings.extend(issues)
-
- def generate_report(self):
- """Generate validation report."""
-
- print("\n" + "="*70)
- print("VALIDATION REPORT")
- print("="*70)
-
- if self.errors:
- print(f"\n❌ ERRORS ({len(self.errors)}):")
- for error in self.errors:
- print(f" {error}")
-
- if self.warnings:
- print(f"\n⚠️ WARNINGS ({len(self.warnings)}):")
- for warning in self.warnings:
- print(f" {warning}")
-
- if self.info:
- print(f"\n✓ PASSED CHECKS ({len(self.info)}):")
- for info in self.info:
- print(f" {info}")
-
- # Overall status
- print("\n" + "="*70)
- if self.errors:
- print("STATUS: ❌ VALIDATION FAILED - Address errors before distribution")
- return False
- elif self.warnings:
- print("STATUS: ⚠️ VALIDATION PASSED WITH WARNINGS - Review recommended")
- return True
- else:
- print("STATUS: ✓ VALIDATION PASSED - Document meets quality standards")
- return True
-
- def save_report(self, output_file):
- """Save validation report to file."""
-
- with open(output_file, 'w') as f:
- f.write("CLINICAL DECISION SUPPORT DOCUMENT VALIDATION REPORT\n")
- f.write("="*70 + "\n")
- f.write(f"Document: {self.filepath}\n")
- f.write(f"Validated: {Path.cwd()}\n\n")
-
- if self.errors:
- f.write(f"ERRORS ({len(self.errors)}):\n")
- for error in self.errors:
- f.write(f" - {error}\n")
- f.write("\n")
-
- if self.warnings:
- f.write(f"WARNINGS ({len(self.warnings)}):\n")
- for warning in self.warnings:
- f.write(f" - {warning}\n")
- f.write("\n")
-
- if self.info:
- f.write(f"PASSED CHECKS ({len(self.info)}):\n")
- for info in self.info:
- f.write(f" - {info}\n")
-
- print(f"\nValidation report saved to: {output_file}")
-
-
-def main():
- parser = argparse.ArgumentParser(description='Validate clinical decision support documents')
- parser.add_argument('input_file', type=str, help='Document to validate (.tex, .md, .txt)')
- parser.add_argument('-o', '--output', type=str, default=None,
- help='Save validation report to file')
- parser.add_argument('--strict', action='store_true',
- help='Treat warnings as errors')
-
- args = parser.parse_args()
-
- # Validate
- validator = CDSValidator(args.input_file)
- passed = validator.validate_all()
-
- # Save report if requested
- if args.output:
- validator.save_report(args.output)
-
- # Exit code
- if args.strict and (validator.errors or validator.warnings):
- exit(1)
- elif validator.errors:
- exit(1)
- else:
- exit(0)
-
-
-if __name__ == '__main__':
- main()
-
-
-# Example usage:
-# python validate_cds_document.py cohort_analysis.tex
-# python validate_cds_document.py treatment_recommendations.tex -o validation_report.txt
-# python validate_cds_document.py document.tex --strict # Warnings cause failure
-
diff --git a/skills/clinical-decision-support/tests/test_scripts.py b/skills/clinical-decision-support/tests/test_scripts.py
new file mode 100644
index 00000000..daf3a367
--- /dev/null
+++ b/skills/clinical-decision-support/tests/test_scripts.py
@@ -0,0 +1,268 @@
+"""Synthetic tests for the research-only clinical-decision-support helpers."""
+
+from __future__ import annotations
+
+import ast
+import copy
+import json
+import re
+import sys
+import unittest
+from pathlib import Path
+
+sys.dont_write_bytecode = True
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = ROOT / "scripts"
+ASSETS = ROOT / "assets"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common # noqa: E402
+import cohort_table_generator # noqa: E402
+import decision_logic_traceability # noqa: E402
+import deidentification_checklist # noqa: E402
+import evidence_profile_check # noqa: E402
+import model_biomarker_evaluation # noqa: E402
+import survival_plan_validator # noqa: E402
+import validate_cds_artifact # noqa: E402
+
+
+def load_asset(filename: str) -> dict:
+ return json.loads((ASSETS / filename).read_text(encoding="utf-8"))
+
+
+def resolve_placeholders(value):
+ if isinstance(value, dict):
+ return {key: resolve_placeholders(nested) for key, nested in value.items()}
+ if isinstance(value, list):
+ return [resolve_placeholders(nested) for nested in value]
+ if isinstance(value, str):
+ if "YYYY-MM-DD" in value:
+ return "2026-07-23"
+ if "REPLACE_" in value or "REQUIRES_" in value:
+ return "Synthetic completed human entry."
+ return value
+
+
+class StaticSafetyTests(unittest.TestCase):
+ def test_scripts_have_no_network_secret_or_dynamic_code_imports(self) -> None:
+ banned_import_roots = {
+ "aiohttp",
+ "httpx",
+ "openai",
+ "pickle",
+ "requests",
+ "socket",
+ "urllib",
+ }
+ banned_calls = {"eval", "exec"}
+ for path in sorted(SCRIPTS.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ roots = {alias.name.split(".")[0] for alias in node.names}
+ self.assertFalse(
+ roots & banned_import_roots,
+ f"{path.name} imports a prohibited module",
+ )
+ if isinstance(node, ast.ImportFrom) and node.module:
+ self.assertNotIn(
+ node.module.split(".")[0],
+ banned_import_roots,
+ f"{path.name} imports a prohibited module",
+ )
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ self.assertNotIn(
+ node.func.id,
+ banned_calls,
+ f"{path.name} uses dynamic code execution",
+ )
+ source = path.read_text(encoding="utf-8")
+ self.assertNotIn("os.environ", source)
+ self.assertNotIn("getenv(", source)
+ self.assertNotIn("API_KEY", source)
+
+ def test_assets_declare_safety_fields(self) -> None:
+ for path in sorted(ASSETS.glob("*.json")):
+ document = json.loads(path.read_text(encoding="utf-8"))
+ self.assertIn("intended_use", document, path.name)
+ self.assertIn("limitations", document, path.name)
+ self.assertIn("human_review", document, path.name)
+ self.assertIn("prohibited_uses", document, path.name)
+
+ def test_url_like_input_path_is_rejected(self) -> None:
+ with self.assertRaises(_common.InputError):
+ _common.local_input_path("https://example.invalid/data.json")
+
+ def test_documented_local_paths_exist(self) -> None:
+ pattern = re.compile(r"\b(?:assets|references|scripts)/[A-Za-z0-9_.-]+")
+ documents = [ROOT / "SKILL.md", *sorted((ROOT / "references").glob("*.md"))]
+ missing: list[str] = []
+ for document in documents:
+ for relative in pattern.findall(document.read_text(encoding="utf-8")):
+ if not (ROOT / relative).is_file():
+ missing.append(f"{document.name}: {relative}")
+ self.assertEqual(missing, [])
+
+ def test_no_bytecode_artifacts(self) -> None:
+ artifacts = [
+ str(path.relative_to(ROOT))
+ for path in ROOT.rglob("*")
+ if path.suffix in {".pyc", ".pyo"}
+ ]
+ self.assertEqual(artifacts, [])
+
+ def test_skill_is_progressively_disclosed_and_versioned(self) -> None:
+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertLess(len(text.splitlines()), 500)
+ self.assertIn('version: "2.0"', text)
+ self.assertIn("license: MIT", text)
+ self.assertIn("metadata:\n version:", text)
+
+
+class ArtifactValidatorTests(unittest.TestCase):
+ def test_unresolved_artifact_template_fails_closed(self) -> None:
+ document = load_asset("artifact_intended_use_template.json")
+ result = validate_cds_artifact.validate_artifact(document)
+ self.assertFalse(result.ok)
+ self.assertTrue(
+ any("placeholders" in error for error in result.errors), result.errors
+ )
+
+ def test_completed_safe_artifact_passes_structural_checks(self) -> None:
+ document = copy.deepcopy(load_asset("artifact_intended_use_template.json"))
+ document["artifact"].update(
+ {
+ "id": "SYNTHETIC-ARTIFACT-001",
+ "owner": "research governance owner",
+ "date": "2026-07-23",
+ }
+ )
+ document["data_governance"]["data_cut_date"] = "2026-07-23"
+ document["validation"].update(
+ {
+ "external_validation": "Planned before transportability claims.",
+ "calibration": "Aggregate calibration review planned.",
+ "subgroup_fairness": "Prespecified subgroup review planned.",
+ "uncertainty": "Intervals and limitations will be reported.",
+ "human_factors": "Not evaluated; live use is outside scope.",
+ }
+ )
+ document["sources"][0].update(
+ {
+ "citation": "Synthetic governance source, version 1.",
+ "url": "not_applicable_for_local_synthetic_source",
+ "accessed": "2026-07-23",
+ }
+ )
+ result = validate_cds_artifact.validate_artifact(document)
+ self.assertTrue(result.ok, result.errors)
+ self.assertTrue(result.warnings)
+
+
+class EvidenceProfileTests(unittest.TestCase):
+ def test_unresolved_template_requires_human_judgments(self) -> None:
+ document = load_asset("evidence_profile_template.json")
+ result, _ = evidence_profile_check.check_profile(document)
+ self.assertFalse(result.ok)
+ self.assertTrue(
+ any("human judgment" in error for error in result.errors),
+ result.errors,
+ )
+
+ def test_complete_human_profile_passes_without_auto_grading(self) -> None:
+ document = resolve_placeholders(
+ copy.deepcopy(load_asset("evidence_profile_template.json"))
+ )
+ outcome = document["outcomes"][0]
+ for domain in outcome["domains"].values():
+ domain["judgment"] = "not_serious"
+ domain["rationale"] = "Human reviewers found no serious concern and cited the source."
+ domain["reviewer_role"] = "systematic-review methodologist"
+ for item in outcome["upgrading"].values():
+ item["judgment"] = "not_applicable"
+ item["rationale"] = "Human reviewers judged the consideration not applicable."
+ outcome["certainty"].update(
+ {
+ "human_judgment": True,
+ "level": "moderate",
+ "rationale": "Human panel rationale after explicit domain review.",
+ "reviewer_role": "GRADE panel chair",
+ "judgment_date": "2026-07-23",
+ }
+ )
+ document["profile_review"]["completed"] = True
+ result, summaries = evidence_profile_check.check_profile(document)
+ self.assertTrue(result.ok, result.errors)
+ self.assertEqual(summaries[0]["human_entered_certainty"], "moderate")
+ self.assertFalse(document["auto_grade"])
+
+
+class AggregateEvaluationTests(unittest.TestCase):
+ def test_model_evaluation_is_aggregate_and_bounded(self) -> None:
+ document = load_asset("aggregate_model_evaluation_template.json")
+ log, report = model_biomarker_evaluation.evaluate(document, minimum=11)
+ self.assertTrue(log.ok, log.errors)
+ self.assertFalse(report["individual_output_generated"])
+ self.assertFalse(report["clinical_classification_generated"])
+ self.assertFalse(report["recommendation_generated"])
+ self.assertEqual(len(report["groups"]), 2)
+ self.assertFalse(report["groups"][0]["suppressed"])
+ self.assertIn("sensitivity", report["groups"][0]["metrics"])
+
+ def test_cohort_table_applies_complementary_suppression(self) -> None:
+ document = load_asset("aggregate_cohort_table_template.json")
+ log, _, rows, notes = cohort_table_generator._build_table(document, 11)
+ self.assertTrue(log.ok, log.errors)
+ self.assertEqual(rows[-1][1], "SUPP")
+ self.assertEqual(rows[-1][2], "SUPP-C")
+ self.assertTrue(any("Complementary suppression" in note for note in notes))
+
+
+class PlanAndTraceabilityTests(unittest.TestCase):
+ def test_survival_plan_passes_with_recorded_review_warning(self) -> None:
+ document = load_asset("survival_analysis_plan_template.json")
+ result = survival_plan_validator.validate_plan(document)
+ self.assertTrue(result.ok, result.errors)
+ self.assertTrue(any("Human review" in warning for warning in result.warnings))
+
+ def test_traceability_matrix_is_non_executable(self) -> None:
+ document = load_asset("decision_logic_traceability_template.json")
+ result, rows = decision_logic_traceability.validate_matrix(document)
+ self.assertTrue(result.ok, result.errors)
+ self.assertFalse(document["metadata"]["executable_logic"])
+ self.assertEqual(len(rows), 3)
+ allowed = decision_logic_traceability.ALLOWED_OUTPUT_KINDS
+ self.assertTrue(all(row["output_kind"] in allowed for row in rows))
+
+
+class PrivacyChecklistTests(unittest.TestCase):
+ def test_unresolved_template_fails_closed(self) -> None:
+ document = load_asset("deidentification_checklist_template.json")
+ result, summary = deidentification_checklist.check_documentation(document)
+ self.assertFalse(result.ok)
+ self.assertFalse(summary["documentation_complete"])
+ self.assertFalse(summary["hipaa_compliance_determined"])
+
+ def test_complete_safe_harbor_documentation_is_not_compliance_claim(self) -> None:
+ document = resolve_placeholders(
+ copy.deepcopy(load_asset("deidentification_checklist_template.json"))
+ )
+ document["method"] = "safe_harbor"
+ for entry in document["identifier_categories"]:
+ entry["status"] = "not_present"
+ entry["evidence"] = (
+ "Qualified reviewer documented the category as absent in the inventory."
+ )
+ document["safe_harbor_review"]["completed"] = True
+ document["residual_risk_review"]["completed"] = True
+ document["human_review"]["completed"] = True
+ result, summary = deidentification_checklist.check_documentation(document)
+ self.assertTrue(result.ok, result.errors)
+ self.assertTrue(summary["documentation_complete"])
+ self.assertFalse(summary["deidentification_determined"])
+ self.assertFalse(summary["hipaa_compliance_determined"])
+
+
+if __name__ == "__main__":
+ unittest.main()