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.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Redesign clinical reports safety
Timothy Kassiscc223d5ef144
diff --git a/skills/clinical-reports/SKILL.md b/skills/clinical-reports/SKILL.mdindex 6925a291..71beb7f2 100644--- a/skills/clinical-reports/SKILL.md+++ b/skills/clinical-reports/SKILL.md@@ -1,1131 +1,248 @@---name: clinical-reports-description: Write comprehensive clinical reports including case reports (CARE guidelines), diagnostic reports (radiology/pathology/lab), clinical trial reports (ICH-E3, SAE, CSR), and patient documentation (SOAP, H&P, discharge summaries). Full support with templates, regulatory compliance (HIPAA, FDA, ICH-GCP), and validation tools.-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: Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.+license: MIT+compatibility: Requires Python 3.11+ only for optional dependency-free local scripts; no network access, credentials, external models, or image services.+metadata:+ version: "2.0"+ skill-author: K-Dense Inc.----# Clinical Report Writing+# Clinical Reports-## Overview+## Purpose-Clinical report writing is the process of documenting medical information with precision, accuracy, and compliance with regulatory standards. This skill covers four major categories of clinical reports: case reports for journal publication, diagnostic reports for clinical practice, clinical trial reports for regulatory submission, and patient documentation for medical records. Apply this skill for healthcare documentation, research dissemination, and regulatory compliance.+Prepare **draft reporting structures**, aggregate tables, and review manifests from verified authorized facts. Route each artifact to the correct reporting guidance, preserve provenance, and stop when source support or qualified review is missing.-**Critical Principle: Clinical reports must be accurate, complete, objective, and compliant with applicable regulations (HIPAA, FDA, ICH-GCP).** Patient privacy and data integrity are paramount. All clinical documentation must support evidence-based decision-making and meet professional standards.+This skill does not establish legal, regulatory, ethical, journal, accreditation, or institutional compliance. Its scripts check structure and internal consistency only.-## When to Use This Skill+## Non-Negotiable Boundary-This skill should be used when:-- Writing clinical case reports for journal submission (CARE guidelines)-- Creating diagnostic reports (radiology, pathology, laboratory)-- Documenting clinical trial data and adverse events-- Preparing clinical study reports (CSR) for regulatory submission-- Writing patient progress notes, SOAP notes, and clinical summaries-- Drafting discharge summaries, H&P documents, or consultation notes-- Ensuring HIPAA compliance and proper de-identification-- Validating clinical documentation for completeness and accuracy-- Preparing serious adverse event (SAE) reports-- Creating data safety monitoring board (DSMB) reports+Never:-## Visual Enhancement with Scientific Schematics+- diagnose, recommend treatment, choose or change dosing, triage, or provide return precautions;+- interpret images, specimens, raw laboratory results, symptoms, or other clinical observations;+- invent, infer, normalize, “complete,” or silently reconcile observations, results, dates, units, denominators, causality, expectedness, seriousness, outcomes, or conclusions;+- create an individual case safety report from patient-level narrative or decide reportability;+- sign, attest, approve, file, transmit, submit, amend a source record, or act as a licensed clinician, pathologist, radiologist, laboratorian, safety physician, statistician, privacy officer, attorney, or regulatory professional;+- use real PHI in examples, assets, tests, prompts, logs, or external services;+- call an external LLM, image service, API, or another skill.-**⚠️ MANDATORY: Every clinical report MUST include at least 1 AI-generated figure using the scientific-schematics skill.**+All generated artifacts must remain visibly marked:-This is not optional. Clinical reports benefit greatly from visual elements. Before finalizing any document:-1. Generate at minimum ONE schematic or diagram (e.g., patient timeline, diagnostic algorithm, or treatment workflow)-2. For case reports: include clinical progression timeline-3. For trial reports: include CONSORT flow diagram+> DRAFT — NOT FOR CLINICAL USE, SIGNATURE, FILING, OR SUBMISSION. Populate only from verified authorized source records. Qualified review and sign-off are required.-**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+If the request crosses a boundary, stop the unsafe portion. Offer a blank structured template, a source-fact manifest, or a deterministic structural check. Direct clinical or regulatory decisions to the responsible qualified professional.++## Input Gate++Proceed only when all conditions are true:++1. **Purpose is explicit**: publication draft, diagnostic-report scaffold, trial-results manuscript, protocol reporting review, CSR draft, aggregate safety table, or aggregate research summary.+2. **Data class is allowed**: `synthetic`, `deidentified`, or `aggregate`.+3. **Authority is documented**: the requester is authorized to use the records for the stated purpose.+4. **Local-only handling is feasible**: no upload, remote API, telemetry, or credential is needed.+5. **Minimum necessary is defined**: exclude fields not needed for the artifact.+6. **Provenance exists**: every populated field or claim maps to one or more verified source-fact IDs.+7. **Review owner is identified**: qualified clinical, statistical, safety, privacy, legal, journal, and/or regulatory review as applicable.++Do not accept raw free-text patient records when a structured source-fact manifest can be supplied. Do not copy direct identifiers into this skill’s templates or scripts.++## Route Before Drafting++| Artifact | Primary route | Important boundary |+|---|---|---|+| Case report for publication | CARE 2013 checklist and 2017 explanation | Publication consent, privacy, journal policy, and clinical accuracy require human verification |+| Radiology draft scaffold | ACR 2025 communication practice parameter plus modality-specific ACR material | A qualified radiologist authors findings/impression and handles nonroutine communication |+| Pathology draft scaffold | Current specimen-specific CAP Cancer Protocol, if applicable | A qualified pathologist selects the protocol/version and authors diagnosis |+| Laboratory draft scaffold | 42 CFR 493.1291 and laboratory policy | The performing laboratory controls results, reference intervals, corrections, and release |+| Randomized-trial results report | CONSORT 2025 plus every applicable current extension | CONSORT is reporting guidance, not a conduct or submission standard |+| Randomized-trial protocol report | SPIRIT 2025 plus applicable extensions | SPIRIT is for protocols, not results or CSRs |+| Clinical Study Report | ICH E3 plus E3 Q&A; consider ICH E6(R3) and regional requirements | E3 is adaptable guidance, not a rigid universal template |+| Pre-approval safety report | ICH E2A; E2B(R3) for electronic ICSR data; applicable regional law/guidance | Qualified sponsor/investigator safety assessment controls reportability and timing |+| Post-approval individual safety report | ICH E2D(R1), E2B(R3), and regional requirements | Do not automate case assessment, coding, or submission |+| Aggregate safety presentation | Protocol/SAP, ICH E3, CONSORT Harms, and applicable FDA/ICH guidance | Aggregate tables never determine individual-case reportability |+| Aggregate research summary | Study-design-specific reporting guideline and source protocol/SAP | State population, estimand, denominator, missingness, and limitations exactly as verified |++Read `references/report_type_routing.md` before choosing a route. Use the dated primary-source ledger in `references/sources.md`; check the live official source when requirements could have changed.++## Safe Drafting Workflow++### 1. Create a source-fact manifest++Use `assets/provenance_manifest_template.json`. Record only local record locators, field paths, verification state, verifier role, verification date, and a SHA-256 value hash. Do not duplicate source content or direct identifiers.++Every draft claim or populated field must cite one or more fact IDs. Unsupported content remains `null` or `missing`; never replace it with plausible text.++### 2. Generate the correct template-**How to generate schematics:**```bash-python scripts/generate_schematic.py "your diagram description" -o figures/output.png+PYTHONDONTWRITEBYTECODE=1 python3 scripts/generate_report_template.py --list+PYTHONDONTWRITEBYTECODE=1 python3 scripts/generate_report_template.py \+ --type case-report \+ --output ./case-report-draft.json```-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+The generator copies a fail-closed JSON template. It does not populate clinical content, create directories, overwrite files by default, or certify readiness.-**When to add schematics:**-- Patient case timelines and clinical progression diagrams-- Diagnostic algorithm flowcharts-- Treatment protocol workflows-- Anatomical diagrams for case reports-- Clinical trial participant flow diagrams (CONSORT)-- Adverse event classification trees-- Any complex concept that benefits from visualization+### 3. Populate verified fields only-For detailed guidance on creating schematics, refer to the scientific-schematics skill documentation.+- Keep `draft_status` unchanged.+- Replace `null` only when a verified fact ID supports the field.+- Preserve uncertainty and “not assessed” exactly as recorded.+- Do not translate a raw observation into a diagnosis, code, grade, stage, seriousness, causality, expectedness, or recommendation.+- Use `not_applicable_with_rationale` only when a qualified reviewer supplied the rationale.+- Keep source record and draft separate.----+### 4. Run deterministic checks++CARE structure:++```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/validate_case_report.py \+ ./case-report-draft.json+```++ICH E3, CONSORT 2025, or SPIRIT 2025 structure:++```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/validate_trial_report.py \+ ./trial-report-manifest.json+```-## Core Capabilities--### 1. Clinical Case Reports for Journal Publication--Clinical case reports describe unusual clinical presentations, novel diagnoses, or rare complications. They contribute to medical knowledge and are published in peer-reviewed journals.--#### CARE Guidelines Compliance--The CARE (CAse REport) guidelines provide a standardized framework for case report writing. All case reports should follow this checklist:--**Title**-- Include the words "case report" or "case study"-- Indicate the area of focus-- Example: "Unusual Presentation of Acute Myocardial Infarction in a Young Patient: A Case Report"--**Keywords**-- 2-5 keywords for indexing and searchability-- Use MeSH (Medical Subject Headings) terms when possible--**Abstract** (structured or unstructured, 150-250 words)-- Introduction: What is unique or novel about the case?-- Patient concerns: Primary symptoms and key medical history-- Diagnoses: Primary and secondary diagnoses-- Interventions: Key treatments and procedures-- Outcomes: Clinical outcome and follow-up-- Conclusions: Main takeaway or clinical lesson--**Introduction**-- Brief background on the medical condition-- Why this case is novel or important-- Literature review of similar cases (brief)-- What makes this case worth reporting--**Patient Information**-- Demographics (age, sex, race/ethnicity if relevant)-- Medical history, family history, social history-- Relevant comorbidities-- **De-identification**: Remove or alter 18 HIPAA identifiers-- **Patient consent**: Document informed consent for publication--**Clinical Findings**-- Chief complaint and presenting symptoms-- Physical examination findings-- Timeline of symptoms (consider timeline figure or table)-- Relevant clinical observations--**Timeline**-- Chronological summary of key events-- Dates of symptoms, diagnosis, interventions, outcomes-- Can be presented as a table or figure-- Example format:- - Day 0: Initial presentation with symptoms X, Y, Z- - Day 2: Diagnostic test A performed, revealed finding B- - Day 5: Treatment initiated with drug C- - Day 14: Clinical improvement noted- - Month 3: Follow-up examination shows complete resolution--**Diagnostic Assessment**-- Diagnostic tests performed (labs, imaging, procedures)-- Results and interpretation-- Differential diagnosis considered-- Rationale for final diagnosis-- Challenges in diagnosis--**Therapeutic Interventions**-- Medications (names, dosages, routes, duration)-- Procedures or surgeries performed-- Non-pharmacological interventions-- Reasoning for treatment choices-- Alternative treatments considered--**Follow-up and Outcomes**-- Clinical outcome (resolution, improvement, unchanged, worsened)-- Follow-up duration and frequency-- Long-term outcomes if available-- Patient-reported outcomes-- Adherence to treatment--**Discussion**-- Strengths and novelty of the case-- How this case compares to existing literature-- Limitations of the case report-- Potential mechanisms or explanations-- Clinical implications and lessons learned-- Unanswered questions or areas for future research--**Patient Perspective** (optional but encouraged)-- Patient's experience and viewpoint-- Impact on quality of life-- Patient-reported outcomes-- Quote from patient if appropriate--**Informed Consent**-- Statement documenting patient consent for publication-- If patient deceased or unable to consent, describe proxy consent-- For pediatric cases, parental/guardian consent-- Example: "Written informed consent was obtained from the patient for publication of this case report and accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal."--For detailed CARE guidelines, refer to `references/case_report_guidelines.md`.--#### Journal-Specific Requirements--Different journals have specific formatting requirements:-- Word count limits (typically 1500-3000 words)-- Number of figures/tables allowed-- Reference style (AMA, Vancouver, APA)-- Structured vs. unstructured abstract-- Supplementary materials policies--Check journal instructions for authors before submission.--#### De-identification and Privacy--**18 HIPAA Identifiers to Remove or Alter:**-1. Names-2. Geographic subdivisions smaller than state-3. Dates (except year)-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-18. Any other unique identifying characteristic--**Best Practices:**-- Use "the patient" instead of names-- Report age ranges (e.g., "a woman in her 60s") or exact age if relevant-- Use approximate dates or time intervals (e.g., "3 months prior")-- Remove institution names unless necessary-- Blur or crop identifying features in images-- Obtain explicit consent for any potentially identifying information--### 2. Clinical Diagnostic Reports--Diagnostic reports communicate findings from imaging studies, pathological examinations, and laboratory tests. They must be clear, accurate, and actionable.--#### Radiology Reports--Radiology reports follow a standardized structure to ensure clarity and completeness.--**Standard Structure:**--**1. Patient Demographics**-- Patient name (or ID in research contexts)-- Date of birth or age-- Medical record number-- Examination date and time--**2. Clinical Indication**-- Reason for examination-- Relevant clinical history-- Specific clinical question to be answered-- Example: "Rule out pulmonary embolism in patient with acute dyspnea"--**3. Technique**-- Imaging modality (X-ray, CT, MRI, ultrasound, PET, etc.)-- Anatomical region examined-- Contrast administration (type, route, volume)-- Protocol or sequence used-- Technical quality and limitations-- Example: "Contrast-enhanced CT of the chest, abdomen, and pelvis was performed using 100 mL of intravenous iodinated contrast. Oral contrast was not administered."--**4. Comparison**-- Prior imaging studies available for comparison-- Dates of prior studies-- Stability or change from prior imaging-- Example: "Comparison: CT chest from [date]"--**5. Findings**-- Systematic description of imaging findings-- Organ-by-organ or region-by-region approach-- Positive findings first, then pertinent negatives-- Measurements of lesions or abnormalities-- Use of standardized terminology (ACR lexicon, RadLex)-- Example:- - Lungs: Bilateral ground-glass opacities, predominant in the lower lobes. No consolidation or pleural effusion.- - Mediastinum: No lymphadenopathy. Heart size normal.- - Abdomen: Liver, spleen, pancreas unremarkable. No free fluid.--**6. Impression/Conclusion**-- Concise summary of key findings-- Answers to the clinical question-- Differential diagnosis if applicable-- Recommendations for follow-up or additional studies-- Level of suspicion or diagnostic certainty-- Example:- - "1. Bilateral ground-glass opacities consistent with viral pneumonia or atypical infection. COVID-19 cannot be excluded. Clinical correlation recommended.- - 2. No evidence of pulmonary embolism.- - 3. Recommend follow-up imaging in 4-6 weeks to assess resolution."--**Structured Reporting:**--Many radiology departments use structured reporting templates for common examinations:-- Lung nodule reporting (Lung-RADS)-- Breast imaging (BI-RADS)-- Liver imaging (LI-RADS)-- Prostate imaging (PI-RADS)-- CT colonography (C-RADS)--Structured reports improve consistency, reduce ambiguity, and facilitate data extraction.--For radiology reporting standards, see `references/diagnostic_reports_standards.md`.--#### Pathology Reports--Pathology reports document microscopic findings from tissue specimens and provide diagnostic conclusions.--**Surgical Pathology Report Structure:**--**1. Patient Information**-- Patient name and identifiers-- Date of birth, age, sex-- Ordering physician-- Medical record number-- Specimen received date--**2. Specimen Information**-- Specimen type (biopsy, excision, resection)-- Anatomical site-- Laterality if applicable-- Number of specimens/blocks/slides-- Example: "Skin, left forearm, excisional biopsy"--**3. Clinical History**-- Relevant clinical information-- Indication for biopsy-- Prior diagnoses-- Example: "History of melanoma. New pigmented lesion, rule out recurrence."--**4. Gross Description**-- Macroscopic appearance of specimen-- Size, weight, color, consistency-- Orientation markers if present-- Sectioning and sampling approach-- Example: "The specimen consists of an ellipse of skin measuring 2.5 x 1.0 x 0.5 cm. A pigmented lesion measuring 0.6 cm in diameter is present on the surface. The specimen is serially sectioned and entirely submitted in cassettes A1-A3."--**5. Microscopic Description**-- Histological findings-- Cellular characteristics-- Architectural patterns-- Presence of malignancy-- Margins if applicable-- Special stains or immunohistochemistry results--**6. Diagnosis**-- Primary diagnosis-- Grade and stage if applicable (cancer)-- Margin status-- Lymph node status if applicable-- Synoptic reporting for cancers (CAP protocols)-- Example:- - "MALIGNANT MELANOMA, SUPERFICIAL SPREADING TYPE- - Breslow thickness: 1.2 mm- - Clark level: IV- - Mitotic rate: 3/mm²- - Ulceration: Absent- - Margins: Negative (closest margin 0.4 cm)- - Lymphovascular invasion: Not identified"--**7. Comment** (if needed)-- Additional context or interpretation-- Differential diagnosis-- Recommendations for additional studies-- Clinical correlation suggestions--**Synoptic Reporting:**--The College of American Pathologists (CAP) provides synoptic reporting templates for cancer specimens. These checklists ensure all relevant diagnostic elements are documented.--Key elements for cancer reporting:-- Tumor site-- Tumor size-- Histologic type-- Histologic grade-- Extent of invasion-- Lymph-vascular invasion-- Perineural invasion-- Margins-- Lymph nodes (number examined, number positive)-- Pathologic stage (TNM classification)-- Ancillary studies (molecular markers, biomarkers)--#### Laboratory Reports--Laboratory reports communicate test results for clinical specimens (blood, urine, tissue, etc.).--**Standard Components:**--**1. Patient and Specimen Information**-- Patient identifiers-- Specimen type (blood, serum, urine, CSF, etc.)-- Collection date and time-- Received date and time-- Ordering provider--**2. Test Name and Method**-- Full test name-- Methodology (immunoassay, spectrophotometry, PCR, etc.)-- Laboratory accession number--**3. Results**-- Quantitative or qualitative result-- Units of measurement-- Reference range (normal values)-- Flags for abnormal values (H = high, L = low)-- Critical values highlighted-- Example:- - Hemoglobin: 8.5 g/dL (L) [Reference: 12.0-16.0 g/dL]- - White Blood Cell Count: 15.2 x10³/μL (H) [Reference: 4.5-11.0 x10³/μL]--**4. Interpretation** (when applicable)-- Clinical significance of results-- Suggested follow-up or additional testing-- Correlation with diagnosis-- Drug levels and therapeutic ranges--**5. Quality Control Information**-- Specimen adequacy-- Specimen quality issues (hemolyzed, lipemic, clotted)-- Delays in processing-- Technical limitations--**Critical Value Reporting:**-- Life-threatening results require immediate notification-- Examples: glucose <40 or >500 mg/dL, potassium <2.5 or >6.5 mEq/L-- Document notification time and recipient--For laboratory standards and terminology, see `references/diagnostic_reports_standards.md`.--### 3. Clinical Trial Reports--Clinical trial reports document the conduct, results, and safety of clinical research studies. These reports are essential for regulatory submissions and scientific publication.--#### Serious Adverse Event (SAE) Reports--SAE reports document unexpected serious adverse reactions during clinical trials. Regulatory requirements mandate timely reporting to IRBs, sponsors, and regulatory agencies.--**Definition of Serious Adverse Event:**-An adverse event is serious if it:-- Results in death-- Is life-threatening-- Requires inpatient hospitalization or prolongation of existing hospitalization-- Results in persistent or significant disability/incapacity-- Is a congenital anomaly/birth defect-- Requires intervention to prevent permanent impairment or damage--**SAE Report Components:**--**1. Study Information**-- Protocol number and title-- Study phase-- Sponsor name-- Principal investigator-- IND/IDE number (if applicable)-- Clinical trial registry number (NCT number)--**2. Patient Information (De-identified)**-- Subject ID or randomization number-- Age, sex, race/ethnicity-- Study arm or treatment group-- Date of informed consent-- Date of first study intervention--**3. Event Information**-- Event description (narrative)-- Date of onset-- Date of resolution (or ongoing)-- Severity (mild, moderate, severe)-- Seriousness criteria met-- Outcome (recovered, recovering, not recovered, fatal, unknown)--**4. Causality Assessment**-- Relationship to study intervention (unrelated, unlikely, possible, probable, definite)-- Relationship to study procedures-- Relationship to underlying disease-- Rationale for causality determination--**5. Action Taken**-- Modification of study intervention (dose reduction, temporary hold, permanent discontinuation)-- Concomitant medications or treatments administered-- Hospitalization details-- Outcome and follow-up plan--**6. Expectedness**-- Expected per protocol or investigator's brochure-- Unexpected event requiring expedited reporting-- Comparison to known safety profile--**7. Narrative**-- Detailed description of the event-- Timeline of events-- Clinical course and management-- Laboratory and diagnostic test results-- Final diagnosis or conclusion--**8. Reporter Information**-- Name and contact of reporter-- Report date-- Signature--**Regulatory Timelines:**-- Fatal or life-threatening unexpected SAEs: 7 days for preliminary report, 15 days for complete report-- Other serious unexpected events: 15 days-- IRB notification: per institutional policy, typically within 5-10 days--For detailed SAE reporting guidance, see `references/clinical_trial_reporting.md`.--#### Clinical Study Reports (CSR)--Clinical study reports are comprehensive documents summarizing the design, conduct, and results of clinical trials. They are submitted to regulatory agencies as part of drug approval applications.--**ICH-E3 Structure:**--The ICH E3 guideline defines the structure and content of clinical study reports.--**Main Sections:**--**1. Title Page**-- Study title and protocol number-- Sponsor and investigator information-- Report date and version--**2. Synopsis** (5-15 pages)-- Brief summary of entire study-- Objectives, methods, results, conclusions-- Key efficacy and safety findings-- Can stand alone--**3. Table of Contents**--**4. List of Abbreviations and Definitions**--**5. Ethics** (Section 2)-- IRB/IEC approvals-- Informed consent process-- GCP compliance statement--**6. Investigators and Study Administrative Structure** (Section 3)-- List of investigators and sites-- Study organization-- Monitoring and quality assurance--**7. Introduction** (Section 4)-- Background and rationale-- Study objectives and purpose--**8. Study Objectives and Plan** (Section 5)-- Overall design and plan-- Objectives (primary and secondary)-- Endpoints (efficacy and safety)-- Sample size determination--**9. Study Patients** (Section 6)-- Inclusion and exclusion criteria-- Patient disposition-- Protocol deviations-- Demographic and baseline characteristics--**10. Efficacy Evaluation** (Section 7)-- Data sets analyzed (ITT, PP, safety)-- Demographic and other baseline characteristics-- Efficacy results for primary and secondary endpoints-- Subgroup analyses-- Dropouts and missing data--**11. Safety Evaluation** (Section 8)-- Extent of exposure-- Adverse events (summary tables)-- Serious adverse events (narratives)-- Laboratory values-- Vital signs and physical findings-- Deaths and other serious events--**12. Discussion and Overall Conclusions** (Section 9)-- Interpretation of results-- Benefit-risk assessment-- Clinical implications--**13. Tables, Figures, and Graphs** (Section 10)--**14. Reference List** (Section 11)--**15. Appendices** (Section 12)-- Study protocol and amendments-- Sample case report forms-- List of investigators and ethics committees-- Patient information and consent forms-- Investigator's brochure references-- Publications based on the study--**Key Principles:**-- Objectivity and transparency-- Comprehensive data presentation-- Adherence to statistical analysis plan-- Clear presentation of safety data-- Integration of appendices--For ICH-E3 templates and detailed guidance, see `references/clinical_trial_reporting.md` and `assets/clinical_trial_csr_template.md`.--#### Protocol Deviations--Protocol deviations are departures from the approved study protocol. They must be documented, assessed, and reported.--**Categories:**-- **Minor deviation**: Does not significantly impact patient safety or data integrity-- **Major deviation**: May impact patient safety, data integrity, or study conduct-- **Violation**: Serious deviation requiring immediate action and reporting--**Documentation Requirements:**-- Description of deviation-- Date of occurrence-- Subject ID affected-- Impact on safety and data-- Corrective and preventive actions (CAPA)-- Root cause analysis-- Preventive measures implemented--### 4. Patient Clinical Documentation--Patient documentation records clinical encounters, progress, and care plans. Accurate documentation supports continuity of care, billing, and legal protection.--#### SOAP Notes--SOAP notes are the most common format for progress notes in clinical practice.--**Structure:**--**S - Subjective**-- Patient's reported symptoms and concerns-- History of present illness (HPI)-- Review of systems (ROS) relevant to visit-- Patient's own words (use quotes when helpful)-- Example: "Patient reports worsening shortness of breath over the past 3 days, particularly with exertion. Denies chest pain, fever, or cough."--**O - Objective**-- Measurable clinical findings-- Vital signs (temperature, blood pressure, heart rate, respiratory rate, oxygen saturation)-- Physical examination findings (organized by system)-- Laboratory and imaging results-- Example:- - Vitals: T 98.6°F, BP 142/88, HR 92, RR 22, SpO2 91% on room air- - General: Mild respiratory distress- - Cardiovascular: Regular rhythm, no murmurs- - Pulmonary: Bilateral crackles at bases- - Extremities: 2+ pitting edema bilaterally--**A - Assessment**-- Clinical impression or diagnosis-- Differential diagnosis-- Severity and stability-- Progress toward treatment goals-- Example:- - "1. Acute decompensated heart failure, NYHA Class III- - 2. Hypertension, poorly controlled- - 3. Chronic kidney disease, stage 3"--**P - Plan**-- Diagnostic plan (further testing)-- Therapeutic plan (medications, procedures)-- Patient education and counseling-- Follow-up arrangements-- Example:- - "Diagnostics: BNP, chest X-ray, echocardiogram- - Therapeutics: Increase furosemide to 40 mg PO BID, continue lisinopril 10 mg daily, strict fluid restriction to 1.5 L/day- - Education: Signs of worsening heart failure, daily weights- - Follow-up: Cardiology appointment in 1 week, call if weight gain >2 lbs in 1 day"--**Documentation Tips:**-- Be concise but complete-- Use standard medical abbreviations-- Document time of encounter-- Sign and date all notes-- Avoid speculation or judgment-- Document medical necessity for billing-- Include patient's response to treatment--For SOAP note templates and examples, see `assets/soap_note_template.md`.--#### History and Physical (H&P)--The H&P is a comprehensive assessment performed at admission or initial encounter.--**Components:**--**1. Chief Complaint (CC)**-- Brief statement of why patient is seeking care-- Use patient's own words-- Example: "Chest pain for 2 hours"--**2. History of Present Illness (HPI)**-- Detailed chronological narrative of current problem-- Use OPQRST mnemonic for pain:- - Onset: When did it start?- - Provocation/Palliation: What makes it better or worse?- - Quality: What does it feel like?- - Region/Radiation: Where is it? Does it spread?- - Severity: How bad is it (0-10 scale)?- - Timing: Constant or intermittent? Duration?-- Associated symptoms-- Prior evaluations or treatments--**3. Past Medical History (PMH)**-- Chronic medical conditions-- Previous hospitalizations-- Surgeries and procedures-- Example: "Hypertension (diagnosed 2015), type 2 diabetes mellitus (diagnosed 2018), prior appendectomy (2010)"--**4. Medications**-- Current medications with doses and frequencies-- Over-the-counter medications-- Herbal supplements-- Allergies and reactions--**5. Allergies**-- Drug allergies with type of reaction-- Food allergies-- Environmental allergies-- Example: "Penicillin (rash), shellfish (anaphylaxis)"--**6. Family History (FH)**-- Medical conditions in first-degree relatives-- Age and cause of death of parents-- Hereditary conditions-- Example: "Father with coronary artery disease (MI at age 55), mother with breast cancer (diagnosed age 62)"--**7. Social History (SH)**-- Tobacco use (pack-years)-- Alcohol use (drinks per week)-- Illicit drug use-- Occupation-- Living situation-- Sexual history if relevant-- Example: "Former smoker, quit 5 years ago (20 pack-year history). Occasional alcohol (2-3 drinks/week). Works as accountant. Lives with spouse."--**8. Review of Systems (ROS)**-- Systematic review of symptoms by organ system-- Typically 10-14 systems-- Pertinent positives and negatives-- Systems: Constitutional, Eyes, ENT, Cardiovascular, Respiratory, GI, GU, Musculoskeletal, Skin, Neurological, Psychiatric, Endocrine, Hematologic/Lymphatic, Allergic/Immunologic--**9. Physical Examination**-- Vital signs-- General appearance-- Systematic examination by organ system-- HEENT, Neck, Cardiovascular, Pulmonary, Abdomen, Extremities, Neurological, Skin-- Use standard terminology and abbreviations--**10. Assessment and Plan**-- Problem list with assessment and plan for each-- Numbered list format-- Diagnostic and therapeutic plans-- Disposition (admit, discharge, transfer)--For H&P templates, see `assets/history_physical_template.md`.--#### Discharge Summaries--Discharge summaries document the hospital stay and communicate care plan to outpatient providers.--**Required Elements:**--**1. Patient Identification**-- Name, date of birth, medical record number-- Admission and discharge dates-- Attending physician-- Admitting and discharge diagnoses--**2. Reason for Hospitalization**-- Brief description of presenting problem-- Chief complaint--**3. Hospital Course**-- Chronological narrative of key events-- Significant findings and procedures-- Response to treatment-- Complications-- Consultations obtained-- Organized by problem or chronologically--**4. Discharge Diagnoses**-- Primary diagnosis-- Secondary diagnoses-- Complications-- Comorbidities--**5. Procedures Performed**-- Surgeries-- Invasive procedures-- Diagnostic procedures--**6. Discharge Medications**-- Complete medication list with instructions-- Changes from admission medications-- New medications with indications--**7. Discharge Condition**-- Stable, improved, unchanged, expired-- Functional status-- Mental status--**8. Discharge Disposition**-- Home, skilled nursing facility, rehabilitation, hospice-- With or without services--**9. Follow-up Plans**-- Appointments scheduled-- Recommended follow-up timing-- Pending tests or studies-- Referrals--**10. Patient Instructions**-- Activity restrictions-- Dietary restrictions-- Wound care-- Warning signs to seek care-- Medication instructions--**Best Practices:**-- Complete within 24-48 hours of discharge-- Use clear language for outpatient providers-- Highlight important pending results-- Document code status discussions-- Include patient education provided--For discharge summary templates, see `assets/discharge_summary_template.md`.--## Regulatory Compliance and Privacy--### HIPAA Compliance--The Health Insurance Portability and Accountability Act (HIPAA) mandates protection of patient health information.--**Key Requirements:**-- Minimum necessary disclosure-- Patient authorization for use beyond treatment/payment/operations-- Secure storage and transmission-- Audit trails for electronic records-- Breach notification procedures--**De-identification Methods:**-1. **Safe Harbor Method**: Remove 18 identifiers-2. **Expert Determination**: Statistical method confirming low re-identification risk+Aggregate adverse-event table:-**Business Associate Agreements:**-Required when PHI is shared with third parties for services+```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/format_adverse_events.py \+ ./aggregate-ae.csv --metadata ./safety-aggregate.json \+ --output ./aggregate-ae-table.md+```-For detailed HIPAA guidance, see `references/regulatory_compliance.md`.+Terminology schema:-### FDA Regulations+```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/terminology_validator.py \+ ./terminology-manifest.json+```-Clinical trial documentation must comply with FDA regulations:-- 21 CFR Part 11 (Electronic Records and Signatures)-- 21 CFR Part 50 (Informed Consent)-- 21 CFR Part 56 (IRB Standards)-- 21 CFR Part 312 (IND Regulations)+De-identification process documentation:-### ICH-GCP Guidelines+```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/check_deidentification.py \+ ./deidentification-process.json+```-Good Clinical Practice (GCP) guidelines ensure quality and ethical standards in clinical trials:-- Protocol adherence-- Informed consent documentation-- Source document requirements-- Audit trails and data integrity-- Investigator responsibilities--For ICH-GCP compliance, see `references/regulatory_compliance.md`.--## Medical Terminology and Standards--### Standardized Nomenclature--**SNOMED CT (Systematized Nomenclature of Medicine - Clinical Terms)**-- Comprehensive clinical terminology-- Used for electronic health records-- Enables semantic interoperability+Traceability and consistency:-**LOINC (Logical Observation Identifiers Names and Codes)**-- Standard for laboratory and clinical observations-- Facilitates data exchange and reporting--**ICD-10-CM (International Classification of Diseases, 10th Revision, Clinical Modification)**-- Diagnosis coding for billing and epidemiology-- Required for reimbursement+```bash+PYTHONDONTWRITEBYTECODE=1 python3 scripts/provenance_validator.py ./provenance.json+PYTHONDONTWRITEBYTECODE=1 python3 scripts/consistency_checker.py ./consistency.json+```-**CPT (Current Procedural Terminology)**-- Procedure coding for billing-- Maintained by AMA+These tools use the Python standard library, local bounded files, and no network, dynamic evaluation, serialization code execution, or patient-record extraction. A successful result still says review is required.-### Abbreviation Standards+### 5. Apply the right review-**Acceptable Abbreviations:**-Use standard abbreviations to improve efficiency while maintaining clarity.+At minimum:-**Do Not Use List (Joint Commission):**-- U (unit) - write "unit"-- IU (international unit) - write "international unit"-- QD, QOD (daily, every other day) - write "daily" or "every other day"-- Trailing zero (X.0 mg) - never use after decimal-- Lack of leading zero (.X mg) - always use before decimal (0.X mg)-- MS, MSO4, MgSO4 - write "morphine sulfate" or "magnesium sulfate"+- clinical facts and interpretations: qualified clinician for the specialty;+- statistical results, populations, estimands, denominators, and missingness: qualified statistician;+- safety coding, seriousness, causality, expectedness, and reportability: qualified safety professional;+- HIPAA, consent, authorization, and disclosure: privacy/legal/institutional review;+- CSR or regulatory safety output: sponsor regulatory and medical review;+- publication: all accountable authors and target-journal checks.-For comprehensive terminology standards, see `references/medical_terminology.md`.+Never sign or submit on another person’s behalf.-## Quality Assurance and Validation+## Case Reports-### Documentation Quality Principles+Use `assets/case_report_template.json` and `references/case_report_guidelines.md`.-**Completeness:**-- All required elements present-- No missing data fields-- Comprehensive patient information+- CARE’s current core checklist remains the 2013 checklist.+- Report only what the verified record supports.+- Do not turn a case into clinical advice or generalize causality from one case.+- Patient perspective and informed-consent status must be recorded accurately; do not draft a false consent statement.+- De-identification and consent are separate controls. Consent does not erase privacy risk.-**Accuracy:**-- Factually correct information-- Verified data sources-- Appropriate clinical reasoning+## Diagnostic Report Scaffolds-**Timeliness:**-- Documented contemporaneously or shortly after encounter-- Time-sensitive reports prioritized-- Regulatory deadlines met+Use the radiology, pathology, or laboratory JSON asset and `references/diagnostic_reports_standards.md`.-**Clarity:**-- Clear and unambiguous language-- Organized logical structure-- Appropriate use of medical terminology+- The assets are field maps, not diagnostic authoring systems.+- Never generate findings, impressions, diagnoses, grades, stages, reference intervals, critical thresholds, or follow-up recommendations.+- Preserve preliminary/final/corrected status and source-system version.+- Use current, exact CAP protocol and version for the specimen; do not maintain a generic cancer staging default.+- Communication and correction actions remain with the responsible clinical service.-**Compliance:**-- Regulatory requirements met-- Privacy protections in place-- Institutional policies followed--### Validation Checklists--For each report type, use validation checklists to ensure quality:-- Case report CARE checklist-- Diagnostic report completeness-- SAE report regulatory compliance-- Clinical documentation billing requirements--Validation scripts are available in the `scripts/` directory.--## Data Presentation in Clinical Reports--### Tables and Figures--**Tables for Clinical Data:**-- Demographic and baseline characteristics-- Adverse events summary-- Laboratory values over time-- Efficacy outcomes--**Table Design Principles:**-- Clear column headers with units-- Footnotes for abbreviations and statistical notes-- Consistent formatting-- Appropriate precision (significant figures)--**Figures for Clinical Data:**-- Kaplan-Meier survival curves-- Forest plots for subgroup analyses-- Patient flow diagrams (CONSORT)-- Timeline figures for case reports-- Before-and-after images--**Image Guidelines:**-- High resolution (300 dpi minimum)-- Appropriate scale bars-- Annotations for key features-- De-identified (no patient identifiers visible)-- Informed consent for recognizable images--For data presentation standards, see `references/data_presentation.md`.--## Integration with Other Skills--This clinical reports skill integrates with:-- **Scientific Writing**: For clear, professional medical writing-- **Peer Review**: For quality assessment of case reports-- **Citation Management**: For literature references in case reports-- **Research Grants**: For clinical trial protocol development-- **Literature Review**: For background sections in case reports--## Workflow for Clinical Report Writing--### Case Report Workflow--**Phase 1: Case Identification and Consent (Week 1)**-- Identify novel or educational case-- Obtain patient informed consent-- De-identify patient information-- Collect clinical data and images--**Phase 2: Literature Review (Week 1-2)**-- Search for similar cases-- Review relevant pathophysiology-- Identify knowledge gaps-- Determine novelty and significance--**Phase 3: Drafting (Week 2-3)**-- Write structured outline following CARE guidelines-- Draft all sections (abstract through discussion)-- Create timeline and figures-- Format references--**Phase 4: Internal Review (Week 3-4)**-- Co-author review-- Attending physician review-- Institutional review if required-- Patient review of de-identified draft--**Phase 5: Journal Selection and Submission (Week 4-5)**-- Select appropriate journal-- Format per journal guidelines-- Prepare cover letter-- Submit manuscript--**Phase 6: Revision (Variable)**-- Respond to peer reviewer comments-- Revise manuscript-- Resubmit--### Diagnostic Report Workflow--**Real-time Workflow:**-- Review clinical indication and prior studies-- Interpret imaging, pathology, or laboratory findings-- Dictate or type report using structured format-- Peer review for complex cases-- Final sign-out and distribution-- Critical value notification if applicable--**Turnaround Time Benchmarks:**-- STAT reports: <1 hour-- Routine reports: 24-48 hours-- Complex cases: 2-5 days-- Pending additional studies: documented delay--### Clinical Trial Report Workflow--**SAE Report: 24 hours to 15 days**-- Event identified by site-- Initial assessment and documentation-- Causality and expectedness determination-- Report completion and review-- Submission to sponsor, IRB, FDA (as required)-- Follow-up reporting until resolution--**CSR: 6-12 months post-study completion**-- Database lock and data cleaning-- Statistical analysis per SAP-- Drafting by medical writer-- Review by biostatistician and clinical team-- Quality control review-- Final approval and regulatory submission--## Resources--This skill includes comprehensive reference files and templates:--### Reference Files--- `references/case_report_guidelines.md` - CARE guidelines, journal requirements, writing tips-- `references/diagnostic_reports_standards.md` - ACR, CAP, laboratory reporting standards-- `references/clinical_trial_reporting.md` - ICH-E3, CONSORT, SAE reporting, CSR structure-- `references/patient_documentation.md` - SOAP notes, H&P, discharge summaries, coding-- `references/regulatory_compliance.md` - HIPAA, 21 CFR Part 11, ICH-GCP, FDA requirements-- `references/medical_terminology.md` - SNOMED, LOINC, ICD-10, abbreviations, nomenclature-- `references/data_presentation.md` - Tables, figures, safety data, CONSORT diagrams-- `references/peer_review_standards.md` - Review criteria for clinical manuscripts--### Template Assets--- `assets/case_report_template.md` - Structured case report following CARE guidelines-- `assets/radiology_report_template.md` - Standard radiology report format-- `assets/pathology_report_template.md` - Surgical pathology report with synoptic elements-- `assets/lab_report_template.md` - Clinical laboratory report format-- `assets/clinical_trial_sae_template.md` - Serious adverse event report form-- `assets/clinical_trial_csr_template.md` - Clinical study report outline per ICH-E3-- `assets/soap_note_template.md` - SOAP progress note format-- `assets/history_physical_template.md` - Comprehensive H&P template-- `assets/discharge_summary_template.md` - Hospital discharge summary-- `assets/consult_note_template.md` - Consultation note format-- `assets/quality_checklist.md` - Quality assurance checklist for all report types-- `assets/hipaa_compliance_checklist.md` - Privacy and de-identification checklist--### Automation Scripts--- `scripts/validate_case_report.py` - Check CARE guideline compliance and completeness-- `scripts/validate_trial_report.py` - Verify ICH-E3 structure and required elements-- `scripts/check_deidentification.py` - Scan for 18 HIPAA identifiers in text-- `scripts/format_adverse_events.py` - Generate AE summary tables from data-- `scripts/generate_report_template.py` - Interactive template selection and generation-- `scripts/extract_clinical_data.py` - Parse structured data from clinical reports-- `scripts/compliance_checker.py` - Verify regulatory compliance requirements-- `scripts/terminology_validator.py` - Validate medical terminology and coding--Load these resources as needed when working on specific clinical reports.--## Common Pitfalls to Avoid--### Case Reports-- **Privacy violations**: Inadequate de-identification or missing consent-- **Lack of novelty**: Reporting common or well-documented cases-- **Insufficient detail**: Missing key clinical information-- **Poor literature review**: Failure to contextualize within existing knowledge-- **Overgeneralization**: Drawing broad conclusions from single case--### Diagnostic Reports-- **Vague language**: Using ambiguous terms like "unremarkable" without specifics-- **Incomplete comparison**: Not reviewing prior imaging-- **Missing clinical correlation**: Failing to answer clinical question-- **Technical jargon**: Overuse of terminology without explanation-- **Delayed critical value notification**: Not communicating urgent findings--### Clinical Trial Reports-- **Late reporting**: Missing regulatory deadlines for SAE reporting-- **Incomplete causality**: Inadequate causality assessment-- **Data inconsistencies**: Discrepancies between data sources-- **Protocol deviations**: Unreported or inadequately documented deviations-- **Selective reporting**: Omitting negative or unfavorable results--### Patient Documentation-- **Illegibility**: Poor handwriting in paper records-- **Copy-forward errors**: Propagating outdated information-- **Insufficient detail**: Vague or incomplete documentation affecting billing-- **Lack of medical necessity**: Not documenting indication for services-- **Missing signatures**: Unsigned or undated notes--## Final Checklist--Before finalizing any clinical report, verify:--- [ ] All required sections complete-- [ ] Patient privacy protected (HIPAA compliance)-- [ ] Informed consent obtained (if applicable)-- [ ] Accurate and verified clinical data-- [ ] Appropriate medical terminology and coding-- [ ] Clear, professional language-- [ ] Proper formatting per guidelines-- [ ] References cited appropriately-- [ ] Figures and tables labeled correctly-- [ ] Spell-checked and proofread-- [ ] Regulatory requirements met-- [ ] Institutional policies followed-- [ ] Signatures and dates present-- [ ] Quality assurance review completed+The former SOAP, H&P, consultation, and discharge-summary interfaces were removed. Do not recreate patient-care notes, medication plans, triage instructions, billing support, or disposition advice.----+## Trial, CSR, and Safety Reporting++Read `references/clinical_trial_reporting.md` and `references/safety_reporting.md`.++- CONSORT 2025 has 30 minimum items for randomized-trial results; select relevant extensions from the current official catalogue.+- SPIRIT 2025 has 34 minimum items for randomized-trial protocols and supersedes SPIRIT 2013.+- ICH E3 remains the CSR basis; its 2012 Q&A explicitly permits justified adaptation.+- ICH E6(R3) consolidated Principles, Annex 1, and Annex 2 were adopted on 16 June 2026; regional implementation can differ.+- Distinguish seriousness from severity and an adverse event from a suspected adverse reaction.+- ICH E2B(R3) defines electronic ICSR data/message structure; it is not an aggregate-table format or a reportability decision rule.+- ICH E2D(R1), adopted 15 September 2025, addresses post-approval individual case safety reporting; aggregate periodic reporting is addressed separately.+- FDA requirements and electronic submission routes are role-, product-, study-, and date-specific. This skill never files or transmits.++## Privacy++Read `references/privacy_and_deidentification.md`.++- Handle only the minimum necessary data locally.+- HHS recognizes Safe Harbor and Expert Determination under 45 CFR 164.514(b).+- Safe Harbor also requires no actual knowledge that remaining information can identify an individual.+- Expert Determination must be performed and documented by an appropriately qualified expert.+- A checklist or pattern scan cannot establish de-identification or HIPAA compliance.+- Rare conditions, small cells, dates, free text, images, metadata, and combinations of quasi-identifiers can retain re-identification risk.++## Assets++All assets contain synthetic schemas only and start blocked:++- `assets/case_report_template.json`+- `assets/radiology_report_template.json`+- `assets/pathology_report_template.json`+- `assets/lab_report_template.json`+- `assets/clinical_trial_csr_template.json`+- `assets/clinical_trial_results_template.json`+- `assets/trial_protocol_reporting_checklist.json`+- `assets/clinical_trial_safety_aggregate_template.json`+- `assets/adverse_event_aggregate_input_template.csv`+- `assets/research_summary_template.json`+- `assets/deidentification_process_checklist.json`+- `assets/quality_review_checklist.json`+- `assets/provenance_manifest_template.json`+- `assets/terminology_manifest_template.json`+- `assets/consistency_manifest_template.json`++## References++- `references/README.md` — safe use and file map+- `references/report_type_routing.md` — artifact-to-guidance routing+- `references/case_report_guidelines.md` — CARE structure and publication safeguards+- `references/diagnostic_reports_standards.md` — ACR, CAP, and CLIA boundaries+- `references/clinical_trial_reporting.md` — CONSORT 2025, SPIRIT 2025, ICH E3/E6(R3)+- `references/safety_reporting.md` — ICH E2/FDA safety distinctions+- `references/privacy_and_deidentification.md` — HHS methods and limitations+- `references/medical_terminology.md` — versioned terminology and schema checks+- `references/data_presentation.md` — denominators, units, missingness, and aggregate tables+- `references/professional_review.md` — ethics, accountability, and sign-off+- `references/sources.md` — official source ledger, checked 2026-07-23-**Final Note**: Clinical report writing requires attention to detail, medical accuracy, regulatory compliance, and clear communication. Whether documenting patient care, reporting research findings, or communicating diagnostic results, the quality of clinical reports directly impacts patient safety, healthcare delivery, and medical knowledge advancement. Always prioritize accuracy, privacy, and professionalism in all clinical documentation.+## Final Handoff+State:+1. artifact type and exact guidance/version used;+2. allowed data class and local-only handling;+3. unresolved `null`, `missing`, conflicts, and unsupported claims;+4. provenance and deterministic-check results;+5. required qualified reviewers;+6. the draft/non-submission warning.++Never say “compliant,” “HIPAA-safe,” “validated clinically,” “approved,” “ready to file,” or “ready to submit.”diff --git a/skills/clinical-reports/assets/adverse_event_aggregate_input_template.csv b/skills/clinical-reports/assets/adverse_event_aggregate_input_template.csvnew file mode 100644index 00000000..4a747f56--- /dev/null+++ b/skills/clinical-reports/assets/adverse_event_aggregate_input_template.csv@@ -0,0 +1 @@+analysis_set,treatment_group,meddra_version,system_organ_class,preferred_term,subjects_affected,event_count,denominatordiff --git a/skills/clinical-reports/assets/case_report_template.json b/skills/clinical-reports/assets/case_report_template.jsonnew file mode 100644index 00000000..3bcf113a--- /dev/null+++ b/skills/clinical-reports/assets/case_report_template.json@@ -0,0 +1,43 @@+{+ "schema_version": "2.0",+ "artifact_kind": "case_report_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_SUBMISSION",+ "safety_notice": "Populate only from verified authorized synthetic or de-identified source facts. Do not infer clinical content. Qualified clinical, privacy, legal, authorship, and journal review is required.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "provenance_manifest": null,+ "guidance": {+ "name": "CARE",+ "checklist_version": "2013",+ "explanation_version": "2017",+ "target_journal_instructions_checked": false+ },+ "care_items": {+ "title": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "key_words": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "abstract": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "introduction": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "patient_information": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "clinical_findings": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "timeline": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "diagnostic_assessment": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "therapeutic_intervention": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "follow_up_and_outcomes": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "discussion": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "patient_perspective": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "informed_consent": {"status": "missing", "source_fact_ids": [], "rationale": null}+ },+ "privacy": {+ "deidentification_process_record": null,+ "publication_consent_record": null,+ "image_or_media_included": false,+ "reidentification_risk_reviewed": false+ },+ "review": {+ "qualified_clinical_review": "pending",+ "privacy_legal_review": "pending",+ "accountable_author_review": "pending",+ "submission_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/case_report_template.md b/skills/clinical-reports/assets/case_report_template.mddeleted file mode 100644index ee0ec3ad..00000000--- a/skills/clinical-reports/assets/case_report_template.md+++ /dev/null@@ -1,352 +0,0 @@-# Clinical Case Report Template--## Title--[Insert descriptive title that includes "Case Report" or "Case Study" and indicates the clinical focus]--Example: Unusual Presentation of Acute Appendicitis in an Elderly Patient: A Case Report--## Author Information--[Author names, affiliations, ORCID IDs]--**Corresponding Author:**-[Name]-[Email]-[Institution]--## Keywords--[2-5 keywords, preferably MeSH terms]--Example: Appendicitis, Atypical presentation, Elderly, Diagnostic imaging--## Abstract--### Introduction-[What is unique about this case? Why is it worth reporting? 1-2 sentences]--### Patient Concerns-[Primary symptoms and chief complaint]--### Diagnosis-[Final diagnosis, how it was reached]--### Interventions-[Key treatments provided]--### Outcomes-[Clinical outcome and follow-up status]--### Lessons-[Main takeaway messages for clinicians]--**Word count:** [150-250 words]--## Introduction--[Background information - 2-4 paragraphs]--**Paragraph 1:** Background on the condition-- Epidemiology of the condition-- Typical clinical presentation-- Standard diagnostic approach-- Current treatment guidelines--**Paragraph 2:** Why this case is novel-- What makes this case unusual or important-- Gap in medical knowledge addressed-- Literature review showing rarity or uniqueness-- Clinical significance--**Paragraph 3:** Objectives-- Purpose of reporting this case-- Learning points to be highlighted--## Patient Information--**Demographics:**-- Age: [e.g., "A 72-year-old" or "A woman in her 70s"]-- Sex: [Male/Female]-- Ethnicity: [if relevant to case]-- Occupation: [if relevant]--**Medical History:**-- Past medical history: [chronic conditions]-- Past surgical history: [prior surgeries]-- Family history: [relevant family history]-- Social history: [tobacco, alcohol, occupation, living situation]--**Medications:**-- Current medications: [list with doses]-- Allergies: [drug allergies and reactions]--**Presenting Symptoms:**-- Chief complaint: ["Patient's words" or clinical presentation]-- Duration of symptoms-- Severity and characteristics-- Associated symptoms-- Relevant review of systems--## Clinical Findings--**Physical Examination:**-- Vital signs: [T, BP, HR, RR, SpO2]-- General appearance: [overall state]-- Systematic examination by organ system:- - HEENT: [findings]- - Cardiovascular: [findings]- - Respiratory: [findings]- - Abdomen: [findings]- - Neurological: [findings]- - Other relevant systems: [findings]--**Pertinent Negatives:**-[Important negative findings]--## Timeline--| Date/Time | Event |-|-----------|-------|-| [Day -X or Date] | [Initial symptom onset] |-| [Day 0 or Date] | [Presentation to healthcare] |-| [Day 0 or Date] | [Initial evaluation and tests] |-| [Day X or Date] | [Diagnosis confirmed] |-| [Day X or Date] | [Treatment initiated] |-| [Day X or Date] | [Hospital discharge or follow-up] |-| [Month X or Date] | [Long-term follow-up] |--*Note: Use relative days (Day 0, Day 1) or approximate dates (Month 1, Month 3) to protect patient privacy*--## Diagnostic Assessment--### Initial Diagnostic Workup--**Laboratory Tests:**-| Test | Result | Reference Range | Interpretation |-|------|--------|----------------|----------------|-| [Test name] | [Value with units] | [Normal range] | [High/Low/Normal] |--**Imaging Studies:**-- [Modality] ([Date]): [Key findings]-- [Include images if applicable, with labels and arrows pointing to key findings]--**Other Diagnostic Procedures:**-- [Procedure name] ([Date]): [Findings]--### Differential Diagnosis--**Diagnoses Considered:**-1. [Primary differential]- - Supporting evidence:- - Evidence against:-2. [Alternative diagnosis]- - Supporting evidence:- - Evidence against:-3. [Additional differentials as appropriate]--### Diagnostic Challenges--[Describe any difficulties in reaching the diagnosis]-- Atypical presentation-- Misleading initial findings-- Diagnostic delays-- Complex decision-making--### Final Diagnosis--**Confirmed Diagnosis:** [Final diagnosis with ICD-10 code if applicable]--**Diagnostic Reasoning:**-[Explain how diagnosis was reached, key diagnostic features, confirmatory tests]--## Therapeutic Intervention--### Treatment Approach--**Initial Management:**-- [Immediate interventions]-- [Supportive care]-- [Monitoring]--**Definitive Treatment:**-1. **Pharmacological Interventions:**- - [Drug name]: [Dose, route, frequency, duration]- - Indication: [Why prescribed]- - Response: [Patient response to treatment]--2. **Procedural/Surgical Interventions:**- - [Procedure name] performed on [date/day]- - Indication: [Why performed]- - Technique: [Brief description]- - Findings: [Intraoperative or procedural findings]- - Complications: [Any complications or none]--3. **Other Interventions:**- - [Physical therapy, dietary modifications, etc.]--**Alternative Treatments Considered:**-[Other treatment options that were considered and why they were not pursued]--**Changes to Interventions:**-[Any modifications to treatment plan]-- Date of change:-- Reason for change:-- New intervention:--## Follow-up and Outcomes--**Immediate Outcome:**-[Outcome during hospitalization or initial treatment period]-- Clinical response:-- Laboratory or imaging follow-up:-- Complications:-- Length of hospitalization (if applicable):--**Short-term Follow-up:** ([Timeframe, e.g., 1 month])-- Clinical status:-- Follow-up tests:-- Adherence to treatment:-- Any issues or concerns:--**Long-term Follow-up:** ([Timeframe, e.g., 6 months, 1 year])-- Clinical status:-- Recovery or resolution:-- Functional status:-- Quality of life:-- Recurrence or complications:--**Patient-Reported Outcomes:**-[Symptoms, quality of life, patient satisfaction]--## Discussion--**Paragraph 1: Summary and Significance**-[Briefly summarize the case and state its significance]--**Paragraph 2: Literature Review**-[Review similar cases in the literature]-- Number of similar cases reported-- Comparison to this case-- What is novel about this case-- [Cite relevant references]--**Paragraph 3: Clinical Implications**-[What can clinicians learn from this case?]-- Recognition of atypical presentations-- Diagnostic pearls-- Treatment considerations-- When to consider this diagnosis--**Paragraph 4: Pathophysiology or Mechanism (if applicable)**-[Explain underlying mechanism, why this occurred, contributing factors]--**Paragraph 5: Strengths and Limitations**-[Acknowledge limitations of case report]-- Single case report limitations-- Cannot establish causation-- Generalizability concerns-- Strengths of comprehensive evaluation--**Paragraph 6: Future Directions**-[Unanswered questions, areas for future research]--## Learning Points--- [Point 1: Concise, actionable clinical lesson]-- [Point 2: Key diagnostic or treatment pearl]-- [Point 3: When to consider this diagnosis]-- [Point 4: (optional) Additional takeaway]--## Patient Perspective--[Optional but encouraged: Patient's own description of experience, in their own words if possible]--"[Patient quote describing their experience, symptoms, treatment, or outcome]"--[Or narrative description of patient's perspective, impact on quality of life, satisfaction with care]--## Informed Consent--Written informed consent was obtained from the patient for publication of this case report and any accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal on request.--[OR if patient deceased/unable to consent:]--Written informed consent was obtained from the patient's next of kin for publication of this case report, as the patient was deceased [or unable to provide consent due to...] at the time of manuscript preparation.--## Conflicts of Interest--The authors declare that they have no conflicts of interest.--## Funding--This case report received no specific grant from any funding agency in the public, commercial, or not-for-profit sectors.--[OR: This work was supported by [funding source and grant number]]--## Acknowledgments--[Acknowledge contributors who do not meet authorship criteria, providers who cared for patient, etc.]--## References--[Format according to journal requirements - typically AMA, Vancouver, or APA]--1. [First reference - Author(s). Title. Journal. Year;Volume(Issue):Pages.]-2. [Second reference...]-------## CARE Checklist Completion--Use the CARE checklist to ensure all required elements are included:--- [ ] Title includes "case report"-- [ ] Keywords provided (2-5)-- [ ] Structured/unstructured abstract-- [ ] Introduction with background and novelty-- [ ] Patient demographics (de-identified)-- [ ] Clinical findings-- [ ] Timeline-- [ ] Diagnostic assessment-- [ ] Therapeutic interventions-- [ ] Follow-up and outcomes-- [ ] Discussion with literature review-- [ ] Patient perspective (if possible)-- [ ] Informed consent statement-- [ ] All 18 HIPAA identifiers removed-- [ ] References formatted correctly-- [ ] Figures/tables labeled and referenced-- [ ] Word count within journal limits-------## De-identification Checklist--Verify all HIPAA identifiers removed:--- [ ] Names (patient, family, providers)-- [ ] Geographic locations smaller than state-- [ ] Exact dates (use year only or relative time)-- [ ] Phone numbers-- [ ] Email addresses-- [ ] Medical record numbers-- [ ] Account numbers-- [ ] License numbers-- [ ] Device serial numbers-- [ ] URLs-- [ ] IP addresses-- [ ] Biometric identifiers-- [ ] Full-face photos (cropped or blurred)-- [ ] Any other identifying information-------**Notes:**-- Adapt this template to your specific journal's requirements-- Check word count limits (typically 1500-3000 words)-- Follow journal's reference style-- Include institutional review/ethics exemption if applicable-- Consider attaching CARE checklist when submitting--diff --git a/skills/clinical-reports/assets/clinical_trial_csr_template.json b/skills/clinical-reports/assets/clinical_trial_csr_template.jsonnew file mode 100644index 00000000..d5ca3bd9--- /dev/null+++ b/skills/clinical-reports/assets/clinical_trial_csr_template.json@@ -0,0 +1,51 @@+{+ "schema_version": "2.0",+ "artifact_kind": "clinical_study_report_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_FILING_OR_SUBMISSION",+ "safety_notice": "Populate only from verified aggregate trial outputs and authorized source-fact manifests. Do not invent analyses, efficacy, safety, conclusions, or appendices. Qualified medical, statistical, safety, privacy, quality, and regulatory review is required.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "guidance": {+ "base": "ICH E3",+ "base_version": "Step 4 1995-11-30",+ "qa_version": "R1 2012-07-06",+ "gcp_version_considered": "ICH E6(R3) consolidated 2026-06-16",+ "regional_adoption_verified": false+ },+ "study_metadata": {+ "protocol_reference": null,+ "sap_reference": null,+ "data_cut_reference": null,+ "analysis_output_reference": null,+ "coding_dictionary_versions": []+ },+ "sections": {+ "title_page": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "synopsis": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "table_of_contents": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "abbreviations_and_definitions": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "ethics": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "investigators_and_administration": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "introduction": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "study_objectives": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "investigational_plan": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "study_patients": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "efficacy_evaluation": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "safety_evaluation": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "discussion_and_conclusions": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "tables_figures_graphs_not_in_text": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "reference_list": {"status": "missing", "source_fact_ids": [], "rationale": null},+ "appendices": {"status": "missing", "source_fact_ids": [], "rationale": null}+ },+ "provenance_manifest": null,+ "review": {+ "medical_review": "pending",+ "statistical_review": "pending",+ "safety_review": "pending",+ "privacy_legal_review": "pending",+ "quality_review": "pending",+ "regulatory_review": "pending",+ "submission_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/clinical_trial_csr_template.md b/skills/clinical-reports/assets/clinical_trial_csr_template.mddeleted file mode 100644index 7f2c8e04..00000000--- a/skills/clinical-reports/assets/clinical_trial_csr_template.md+++ /dev/null@@ -1,353 +0,0 @@-# Clinical Study Report (CSR) Template-## ICH-E3 Format-------# TITLE PAGE--**Study Title:** [Full descriptive title including compound, indication, phase]--**Protocol Number:** [Sponsor protocol number]-**Protocol Version:** [Final protocol version and date]--**Sponsor:** [Company name and address]-**Compound/Drug Name:** [Generic and proprietary names, compound code]-**Indication:** [Therapeutic area and specific indication studied]--**Study Phase:** [I / II / III / IV]-**Study Type:** [Interventional / Observational]--**Report Date:** [MM/DD/YYYY]-**Report Version:** [Version number]--**Medical Expert:** [Name, MD, Title]-**Biostatistician:** [Name, PhD, Title]--**Confidentiality Statement:**-"This document contains confidential information belonging to [Sponsor]. It may not be reproduced or distributed without permission."-------# SYNOPSIS--**Title:** [Abbreviated title]--**Protocol Number:** [Number]-**Study Phase:** [Phase]-**Study Period:** [Start date - End date]--## Study Objectives--**Primary Objective:**-[State primary objective clearly and concisely]--**Secondary Objectives:**-- [Secondary objective 1]-- [Secondary objective 2]--## Methodology--**Study Design:**-[Randomized, double-blind, placebo-controlled, parallel-group, etc.]--**Study Population:**-- Target population: [Patient population]-- Key inclusion criteria: [Main criteria]-- Key exclusion criteria: [Main criteria]--**Sample Size:**-- Planned: [N participants]-- Randomized: [N participants]-- Completed: [N participants]--**Treatment:**-- Treatment A: [Drug name, dose, route, frequency]-- Treatment B: [Comparator/placebo]-- Treatment duration: [Weeks/months]-- Follow-up duration: [Weeks/months]--**Endpoints:**--Primary:-- [Primary endpoint definition and timepoint]--Secondary:-- [Secondary endpoint 1]-- [Secondary endpoint 2]--**Statistical Methods:**-[Brief description of analysis approach, significance level, handling of multiplicity]--## Results--**Participant Disposition:**-- Screened: [N]-- Randomized: [N Treatment A, N Treatment B]-- Completed: [N Treatment A, N Treatment B]-- Discontinued: [N overall, % - main reasons]--**Demographics and Baseline:**-[Summary of key baseline characteristics, comparability across groups]--**Efficacy Results:**--Primary Endpoint:-- [Result for Treatment A vs B, effect size, 95% CI, p-value]--Secondary Endpoints:-- [Results for each secondary endpoint]--**Safety Results:**-- Any AE: [% Treatment A vs B]-- Treatment-related AE: [% Treatment A vs B]-- Serious AE: [% Treatment A vs B]-- Discontinuations due to AE: [% Treatment A vs B]-- Deaths: [N Treatment A vs B]-- Common AEs (≥5%): [List with percentages]--## Conclusions--[Overall conclusions regarding efficacy and safety, benefit-risk assessment]-------# TABLE OF CONTENTS--[Detailed table of contents with page numbers]-------# LIST OF ABBREVIATIONS--| Abbreviation | Definition |-|--------------|------------|-| AE | Adverse Event |-| ANCOVA | Analysis of Covariance |-| CI | Confidence Interval |-| CSR | Clinical Study Report |-| FAS | Full Analysis Set |-| GCP | Good Clinical Practice |-| ICF | Informed Consent Form |-| ITT | Intent-to-Treat |-| PP | Per-Protocol |-| SAE | Serious Adverse Event |-| SD | Standard Deviation |-| [Add study-specific abbreviations] | |-------# ETHICS (Section 2)--## 2.1 Independent Ethics Committee (IEC) or Institutional Review Board (IRB)--[List of all IECs/IRBs that approved the study]--| Site Number | Institution | IRB/IEC Name | Approval Date |-|-------------|------------|--------------|---------------|-| 001 | [Institution] | [IRB name] | [MM/DD/YYYY] |--## 2.2 Ethical Conduct of the Study--This study was conducted in accordance with:-- ICH Good Clinical Practice (GCP) E6(R2)-- Declaration of Helsinki (current version)-- Applicable regulatory requirements-- Sponsor Standard Operating Procedures--## 2.3 Patient Information and Consent--Informed consent was obtained from all participants before any study-specific procedures. The informed consent process included:-- Written information about study purpose, procedures, risks, and benefits-- Opportunity to ask questions-- Voluntary participation with right to withdraw-- Signatures of participant and person obtaining consent-- Copy provided to participant-------# INVESTIGATORS AND STUDY ADMINISTRATIVE STRUCTURE (Section 3)--## 3.1 Investigators and Study Centers--[Table listing all investigators, sites, and enrollment]--| Site No. | Investigator | Institution | City, Country | Subjects Enrolled |-|----------|--------------|-------------|---------------|-------------------|-| 001 | [Name, MD] | [Institution] | [City, Country] | [N] |--**Coordinating Investigator:** [Name, if applicable]--## 3.2 Study Administrative Structure--**Sponsor:**-- Medical Monitor: [Name, credentials]-- Project Manager: [Name]-- Biostatistician: [Name, credentials]--**Contract Research Organization (CRO):** [Name, if applicable]-- [Responsibilities]--## 3.3 Responsibilities of Parties Involved--[Description of sponsor, investigator, CRO, DSMB responsibilities]-------# INTRODUCTION (Section 4)--## 4.1 Background--[Detailed background on disease/condition, unmet medical need, treatment landscape]--## 4.2 Nonclinical Studies--[Summary of relevant preclinical pharmacology, toxicology, and safety findings]--## 4.3 Previous Clinical Studies--[Summary of prior clinical experience with investigational product]--## 4.4 Study Rationale and Objectives--[Justification for conducting this study, specific objectives]-------# STUDY OBJECTIVES AND PLAN (Section 5)--## 5.1 Objectives and Endpoints--**Primary Objective:**-[Objective statement]--**Primary Endpoint:**-[Detailed endpoint definition, measurement method, timepoint]--**Secondary Objectives:**-1. [Objective]-2. [Objective]--**Secondary Endpoints:**-1. [Endpoint definition]-2. [Endpoint definition]--## 5.2 Study Design--[Detailed description of study design with diagram if helpful]--**Design Type:** [Parallel, crossover, factorial, etc.]-**Blinding:** [Double-blind, open-label, etc.]-**Randomization:** [1:1, 2:1, stratified, etc.]-**Duration:** [Treatment period, follow-up period]--**Study Schema:**-[Flow diagram showing screening, randomization, treatment periods, follow-up]--## 5.3 Study Population--**Key Inclusion Criteria:**-1. [Criterion]-2. [Criterion]--**Key Exclusion Criteria:**-1. [Criterion]-2. [Criterion]--## 5.4 Treatments--**Investigational Product:**-- Name: [Generic, trade, code]-- Formulation: [Tablet, capsule, injection]-- Dose: [Dose and regimen]-- Route: [PO, IV, SC, etc.]-- Packaging and labeling: [Description]--**Comparator:**-[Similar details for comparator or placebo]--**Concomitant Medications:**-[Permitted and prohibited medications]--## 5.5 Sample Size Determination--**Target Sample Size:** [N per group, N total]--**Justification:**-- Assumed effect size: [Value]-- Variability (SD): [Value]-- Type I error (α): [0.05]-- Power (1-β): [80% or 90%]-- Expected dropout rate: [%]-- Two-sided test--## 5.6 Statistical Analysis Plan--**Analysis Populations:**-- Full Analysis Set (FAS): [Definition]-- Per-Protocol Set (PPS): [Definition]-- Safety Analysis Set: [Definition]--**Statistical Methods:**-- Primary endpoint: [Method - e.g., ANCOVA with baseline as covariate]-- Secondary endpoints: [Methods]-- Handling of missing data: [Approach]-- Multiplicity adjustment: [Method if applicable]-- Interim analyses: [If planned]--**Significance Level:** α = 0.05 (two-sided)-------# STUDY PATIENTS (Section 6)--## 6.1 Disposition of Patients--**Participant Flow (CONSORT Diagram):**--[Include detailed CONSORT diagram showing screening through analysis]--**Summary Table:**--| Category | Treatment A | Treatment B | Total |-|----------|-------------|-------------|-------|-| Screened | N | N | N |-| Screen failures | N (%) | N (%) | N (%) |-| Randomized | N | N | N |-| Received treatment | N (%) | N (%) | N (%) |-| Completed | N (%) | N (%) | N (%) |-| Discontinued | N (%) | N (%) | N (%) |-| - Adverse event | N (%) | N (%) | N (%) |-| - Lack of efficacy | N (%) | N (%) | N (%) |-| - Lost to follow-up | N (%) | N (%) | N (%) |-| - Withdrawal of consent | N (%) | N (%) | N (%) |-| - Other | N (%) | N (%) | N (%) |--## 6.2 Protocol Deviations--**Major Protocol Deviations:**-[Summary of major deviations, impact on data, subjects affected]--**Important Protocol Deviations by Category:**--| Deviation Type | Treatment A | Treatment B | Total |-|----------------|-------------|-------------|-------|-| Inclusion/exclusion criteria | N (%) | N (%) | N (%) |-| Dosing errors | N (%) | N (%) | N (%) |-| Prohibited medications | N (%) | N (%) | N (%) |-| Missed visits | N (%) | N (%) | N (%) |-------(Continues with sections 7-14 following ICH-E3 structure...)-------**Note:** This is an abbreviated template. A complete CSR following ICH-E3 is typically 50-300 pages with extensive appendices. Key sections to complete:-- Section 7: Efficacy Evaluation-- Section 8: Safety Evaluation-- Section 9: Discussion and Overall Conclusions-- Section 10: Tables, Figures, and Graphs-- Section 11: References-- Section 12-14: Appendices (Protocol, CRFs, Investigator list, etc.)--diff --git a/skills/clinical-reports/assets/clinical_trial_results_template.json b/skills/clinical-reports/assets/clinical_trial_results_template.jsonnew file mode 100644index 00000000..8044a7f4--- /dev/null+++ b/skills/clinical-reports/assets/clinical_trial_results_template.json@@ -0,0 +1,66 @@+{+ "schema_version": "2.0",+ "artifact_kind": "randomized_trial_results_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_PUBLICATION_OR_SUBMISSION",+ "safety_notice": "This manifest tracks CONSORT item coverage only. It cannot design analyses, create results, infer participant flow, assess harms, or establish trial validity.",+ "data_classification": "aggregate",+ "authorized_purpose": null,+ "authorization_verified": false,+ "guidance": {+ "base": "CONSORT 2025",+ "item_count": 30,+ "statement_and_explanation_checked": false,+ "applicable_extensions": [],+ "applicable_extensions_reviewed": false,+ "extension_conflicts_resolved_by_methodologist": false+ },+ "study_metadata": {+ "protocol_reference": null,+ "sap_reference": null,+ "registry_reference": null,+ "data_cut_reference": null,+ "analysis_output_reference": null+ },+ "checklist_items": {+ "C01": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C02": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C03": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C04": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C05": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C06": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C07": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C08": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C09": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C10": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C11": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C12": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C13": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C14": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C15": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C16": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C17": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C18": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C19": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C20": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C21": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C22": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C23": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C24": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C25": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C26": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C27": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C28": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C29": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "C30": {"status": "missing", "source_fact_ids": [], "official_item_locator": null}+ },+ "not_applicable_rationales": {},+ "participant_flow_source_fact_ids": [],+ "provenance_manifest": null,+ "review": {+ "accountable_author_review": "pending",+ "methodologist_review": "pending",+ "statistical_review": "pending",+ "safety_review": "pending",+ "publication_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/clinical_trial_sae_template.md b/skills/clinical-reports/assets/clinical_trial_sae_template.mddeleted file mode 100644index eb4112c6..00000000--- a/skills/clinical-reports/assets/clinical_trial_sae_template.md+++ /dev/null@@ -1,359 +0,0 @@-# Serious Adverse Event (SAE) Report Template--## Report Information--**Report Type:** [ ] Initial Report [ ] Follow-up Report [ ] Final Report-**Report Number:** [SAE-YYYY-####]-**Report Date:** [MM/DD/YYYY]-**Reporter:** [Name and title]-**Reporter Contact:** [Email and phone]--**Follow-up Number:** [If follow-up: #1, #2, etc.]-**Previous Report Date:** [If follow-up]-------## Study Information--**Protocol Number:** [Protocol ID]-**Protocol Title:** [Full study title]-**Study Phase:** [ ] Phase I [ ] Phase II [ ] Phase III [ ] Phase IV-**Study Sponsor:** [Sponsor name]-**IND/IDE Number:** [IND or IDE number if applicable]-**ClinicalTrials.gov ID:** [NCT number]--**Principal Investigator:** [Name]-**Site Number:** [Site ID]-**Site Name:** [Institution name]-------## Subject Information (De-identified)--**Subject ID / Randomization Number:** [ID only, no name]-**Subject Initials:** [XX] (if permitted by regulatory authority)-**Age:** [Years] OR **Date of Birth:** [Year only: YYYY]-**Sex:** [ ] Male [ ] Female [ ] Other-**Race:** [Category]-**Ethnicity:** [Hispanic or Latino / Not Hispanic or Latino]-**Weight:** [kg]-**Height:** [cm]--**Study Arm / Treatment Group:** [ ] Treatment A [ ] Treatment B [ ] Placebo [ ] Blinded--**Date of Informed Consent:** [MM/DD/YYYY]-**Date of First Study Drug:** [MM/DD/YYYY]-**Date of Last Study Drug:** [MM/DD/YYYY]-**Study Drug Status at Time of Event:** [ ] Ongoing [ ] Completed [ ] Discontinued-------## Adverse Event Information--**Reported Term (Verbatim):** [Exact term reported by investigator/patient]--**MedDRA Coding:**-- **Preferred Term (PT):** [MedDRA PT]-- **System Organ Class (SOC):** [MedDRA SOC]-- **MedDRA Version:** [e.g., 25.0]--**Event Description:**-[Detailed narrative description of the adverse event]--**Date of Onset:** [MM/DD/YYYY]-**Time of Onset:** [HH:MM] (if known and relevant)-**Date of Resolution:** [MM/DD/YYYY] OR [ ] Ongoing-**Duration:** [Days/hours if resolved]--**Event Location:** [ ] Inpatient [ ] Outpatient [ ] Home [ ] Other: ________-------## Seriousness Criteria--**This event is considered serious because it resulted in or required:**--- [ ] **Death** - Date of death: [MM/DD/YYYY]-- [ ] **Life-threatening** - Immediate risk of death at time of event-- [ ] **Hospitalization (initial or prolonged)** - Dates: [MM/DD/YYYY to MM/DD/YYYY]-- [ ] **Persistent or significant disability/incapacity**-- [ ] **Congenital anomaly/birth defect**-- [ ] **Medically important event** - Explanation: _________________--**Hospitalization Details (if applicable):**-- Admission Date: [MM/DD/YYYY]-- Discharge Date: [MM/DD/YYYY] OR [ ] Still hospitalized-- Hospital Name: [Name and location]-- ICU Admission: [ ] Yes [ ] No- - If yes, dates: [MM/DD/YYYY to MM/DD/YYYY]-------## Severity Assessment--**Severity (Intensity):**-- [ ] **Mild** - Noticeable but does not interfere with daily activities-- [ ] **Moderate** - Interferes with daily activities but manageable-- [ ] **Severe** - Prevents usual daily activities, requires intervention--*Note: Severity is not the same as seriousness*-------## Outcome--- [ ] **Recovered/Resolved** - Complete resolution, returned to baseline-- [ ] **Recovering/Resolving** - Improving but not yet fully resolved-- [ ] **Not Recovered/Not Resolved** - Ongoing without improvement-- [ ] **Recovered/Resolved with Sequelae** - Persistent effects remain-- [ ] **Fatal** - Event resulted in death-- [ ] **Unknown** - Unable to determine outcome--**Date of Final Outcome (if resolved):** [MM/DD/YYYY]-------## Causality Assessment--**Relationship to Study Drug:**-- [ ] **Not Related** - Clearly due to other cause-- [ ] **Unlikely Related** - Doubtful connection to study drug-- [ ] **Possibly Related** - Could be related, but other causes possible-- [ ] **Probably Related** - More likely related to study drug than other causes-- [ ] **Definitely Related** - Certain relationship to study drug--**Relationship to Study Procedures:**-- [ ] Not Related [ ] Unlikely [ ] Possibly [ ] Probably [ ] Definitely--**Relationship to Underlying Disease:**-- [ ] Not Related [ ] Unlikely [ ] Possibly [ ] Probably [ ] Definitely--**Relationship to Concomitant Medications:**-- [ ] Not Related [ ] Unlikely [ ] Possibly [ ] Probably [ ] Definitely-- Suspected medication(s): _____________________--**Rationale for Causality Assessment:**-[Detailed explanation of causality determination, including temporal relationship, biological plausibility, dechallenge/rechallenge if applicable, alternative explanations]-------## Expectedness--**Is this event expected based on the Investigator's Brochure or protocol?**-- [ ] **Expected** - Listed in IB/protocol with similar characteristics-- [ ] **Unexpected** - Not listed OR more severe than documented--**Reference:** [IB version and section, or protocol section]-------## Action Taken with Study Drug--- [ ] **No change** - Study drug continued at same dose-- [ ] **Dose reduced** - New dose: ______ (from ______)-- [ ] **Dose increased** - New dose: ______ (from ______)-- [ ] **Drug interrupted** - Dates: [MM/DD to MM/DD]- - [ ] Resumed [ ] Not resumed-- [ ] **Drug permanently discontinued** - Date: [MM/DD/YYYY]-- [ ] **Not applicable** - Event occurred after study drug discontinued--**Dechallenge:** [ ] Positive (improved after stopping) [ ] Negative [ ] Not done--**Rechallenge:** [ ] Positive (recurred after restarting) [ ] Negative [ ] Not done-------## Treatment and Interventions--**Treatments Given for This Event:**--1. **[Medication/Procedure]**- - Dose/Details: _________________- - Route: _________________- - Start Date: [MM/DD/YYYY]- - Stop Date: [MM/DD/YYYY] OR [ ] Ongoing- - Response: [ ] Effective [ ] Partially effective [ ] Not effective--2. **[Additional treatments]**--**Hospitalization Interventions:**-- [ ] IV fluids-- [ ] Oxygen therapy-- [ ] Mechanical ventilation-- [ ] Surgical intervention - Procedure: ______________-- [ ] ICU care-- [ ] Other: ______________-------## Relevant Medical History--**Pre-existing Conditions Relevant to This Event:**-[List conditions that may be related to the event]--**Concomitant Medications at Time of Event:**--| Medication | Indication | Dose/Frequency | Start Date | Stop Date |-|------------|-----------|----------------|------------|-----------|-| [Name] | [Indication] | [Dose] | [MM/DD/YYYY] | [MM/DD/YYYY or Ongoing] |-------## Laboratory and Diagnostic Tests--**Relevant Laboratory Values:**--| Test | Result | Units | Reference Range | Date | Relation to Event |-|------|--------|-------|----------------|------|-------------------|-| [Test] | [Value] | [Units] | [Range] | [MM/DD] | [Before/During/After] |--**Imaging/Diagnostic Studies:**-- **[Study type] ([Date]):** [Key findings]--**ECG/Monitoring:**-[Results if relevant]-------## Detailed Event Narrative--[Comprehensive chronological narrative of the event]--**Minimum elements to include:**-- Patient demographics and study participation timeline-- Relevant medical history-- Chronological description of event development-- Symptoms, signs, and clinical course-- Diagnostic workup and results-- Treatments administered and response-- Clinical outcome and current status-- Investigator's assessment of causality and reasoning--**Example Structure:**-```-A [age]-year-old [sex] with a history of [relevant medical conditions] enrolled in-Study [protocol] on [date] and was randomized to [treatment arm]. The patient had-been receiving [study drug] at [dose] for [duration] when, on [date], the patient-developed [initial symptoms].--[Describe progression of symptoms, timeline, clinical findings...]--[Describe diagnostic workup performed and results...]--[Describe treatments given and patient response...]--[Describe outcome and current status...]--The investigator assessed this event as [causality] related to study drug because-[reasoning]. Alternative explanations include [list alternative causes considered].-```-------## Investigator Assessment--**Investigator's Comments:**-[Additional relevant information, clinical interpretation, conclusions]--**Does this event meet criteria for expedited reporting to regulatory authorities?**-- [ ] Yes - Fatal or life-threatening unexpected SAE-- [ ] Yes - Other unexpected SAE-- [ ] No - Expected event-------## Follow-up Information Required--**Information Pending (if initial or follow-up report):**-- [ ] Final outcome-- [ ] Laboratory results-- [ ] Pathology report-- [ ] Imaging results-- [ ] Autopsy results (if death)-- [ ] Consultant reports-- [ ] Medical records-- [ ] Dechallenge/rechallenge information-- [ ] Other: ______________--**Expected Date for Follow-up Report:** [MM/DD/YYYY]-------## Regulatory Reporting--**Sponsor Safety Assessment:**-[To be completed by sponsor]-- Expectedness: [ ] Expected [ ] Unexpected-- Relationship: [ ] Related [ ] Not related-- Reportable to FDA/EMA: [ ] Yes [ ] No-- Timeline: [ ] 7-day [ ] 15-day [ ] Annual--**IRB Notification:**-- Reported to IRB: [ ] Yes [ ] No [ ] Not required-- Date reported: [MM/DD/YYYY]-- IRB determination: _______________-------## Signatures--**Investigator Signature:**--**Name:** [Principal Investigator name]-**Title:** [MD, credentials]-**Signature:** ____________________-**Date:** [MM/DD/YYYY]--**I certify that this report is accurate and complete to the best of my knowledge.**-------**Sponsor Representative (if applicable):**--**Name:** [Name]-**Title:** [Medical Monitor, Safety Officer]-**Signature:** ____________________-**Date:** [MM/DD/YYYY]-------## Attachments--- [ ] Relevant laboratory reports-- [ ] Imaging reports-- [ ] Pathology reports-- [ ] Discharge summary-- [ ] Death certificate (if applicable)-- [ ] Autopsy report (if applicable)-- [ ] Consultant notes-- [ ] Other: ______________-------## Distribution List--- [ ] Study Sponsor-- [ ] FDA (if applicable)-- [ ] IRB/IEC-- [ ] Data Safety Monitoring Board (if applicable)-- [ ] Site regulatory files-------## Notes--**Regulatory Timeline Requirements:**-- **Fatal or life-threatening unexpected SAEs:** 7 days for preliminary report, 15 days for complete-- **Other serious unexpected events:** 15 days-- **IRB notification:** Per institutional policy (typically 5-10 days)--**Key Points:**-- Complete all sections accurately-- Provide detailed narrative-- Include temporal relationships-- Document all sources of information-- Follow up until event resolved-- Maintain patient confidentiality-- Use only de-identified information--diff --git a/skills/clinical-reports/assets/clinical_trial_safety_aggregate_template.json b/skills/clinical-reports/assets/clinical_trial_safety_aggregate_template.jsonnew file mode 100644index 00000000..e13adc2a--- /dev/null+++ b/skills/clinical-reports/assets/clinical_trial_safety_aggregate_template.json@@ -0,0 +1,49 @@+{+ "schema_version": "2.0",+ "artifact_kind": "clinical_trial_safety_aggregate_draft",+ "draft_status": "BLOCKED_INCOMPLETE_NOT_AN_INDIVIDUAL_CASE_SAFETY_REPORT",+ "safety_notice": "Aggregate display only. Do not use for individual-case assessment, reportability, transmission, causality, expectedness, seriousness, filing, or submission.",+ "data_classification": "aggregate",+ "authorized_purpose": null,+ "authorization_verified": false,+ "local_only_handling_confirmed": false,+ "analysis_metadata": {+ "protocol_reference": null,+ "sap_reference": null,+ "data_cut_reference": null,+ "analysis_set": null,+ "counting_rule": null,+ "threshold_rule": null,+ "meddra_version": null,+ "meddra_language": null,+ "coding_source_reference": null+ },+ "input_csv": "adverse_event_aggregate_input_template.csv",+ "required_columns": [+ "analysis_set",+ "treatment_group",+ "meddra_version",+ "system_organ_class",+ "preferred_term",+ "subjects_affected",+ "event_count",+ "denominator"+ ],+ "prohibited_content": [+ "patient identifiers",+ "subject identifiers",+ "case identifiers",+ "verbatim terms",+ "narratives",+ "exact event dates",+ "contact information"+ ],+ "provenance_manifest": null,+ "review": {+ "safety_coding_review": "pending",+ "statistical_review": "pending",+ "privacy_review": "pending",+ "regulatory_review": "pending",+ "submission_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/consistency_manifest_template.json b/skills/clinical-reports/assets/consistency_manifest_template.jsonnew file mode 100644index 00000000..66a46a56--- /dev/null+++ b/skills/clinical-reports/assets/consistency_manifest_template.json@@ -0,0 +1,15 @@+{+ "schema_version": "2.0",+ "artifact_kind": "consistency_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Structured arithmetic and format checks only. Do not include identifiers or free-text patient records. The checker does not choose an authoritative source or change values.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "provenance_manifest": null,+ "dates": [],+ "date_ranges": [],+ "quantities": [],+ "proportions": [],+ "totals": []+}diff --git a/skills/clinical-reports/assets/consult_note_template.md b/skills/clinical-reports/assets/consult_note_template.mddeleted file mode 100644index 783f481a..00000000--- a/skills/clinical-reports/assets/consult_note_template.md+++ /dev/null@@ -1,305 +0,0 @@-# Consultation Note Template--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age/Sex:** [years, M/F]--**Consultation Date:** [MM/DD/YYYY]-**Consultation Time:** [HH:MM]-**Location:** [Floor, Room number]--**Requesting Service:** [Primary team]-**Requesting Physician:** [Name]-**Consulting Service:** [Cardiology, Nephrology, etc.]-**Consulting Physician:** [Name and credentials]-------## Reason for Consultation--[Specific clinical question or reason for consultation]--Example: "Please evaluate and manage acute kidney injury in setting of heart failure exacerbation."-------## History of Present Illness (Focused on Consultation Question)--[Relevant history focused on the consultation question]--[Patient Name] is a [age]-year-old [sex] with a history of [relevant conditions] currently admitted to [service] for [admission diagnosis] who is being consulted for [specific issue].--[Chronological narrative relevant to consultation question]--**Timeline of Current Issue:**-- [Key events leading to consultation]-- [Current status]-- [Treatments tried]-------## Relevant Past Medical History--1. [Condition relevant to consultation]-2. [Additional relevant conditions]--[Only include history pertinent to consultation question]-------## Current Medications--[List medications relevant to consultation question]--| Medication | Dose | Route | Frequency | Relevant to: |-|------------|------|-------|-----------|--------------|-| [Drug] | [mg] | [route] | [freq] | [Why relevant] |-------## Allergies--| Allergen | Reaction |-|----------|----------|-| [Drug/substance] | [Reaction] |-------## Relevant Social/Family History--[Only include if pertinent to consultation]-------## Review of Systems (Focused)--[Focus on systems relevant to consultation question]--**[Relevant system]:** [Findings]-**[Additional relevant systems]:** [Findings]-------## Physical Examination--**Vital Signs:**-- Temperature: _____ °F-- Blood Pressure: _____/_____ mmHg-- Heart Rate: _____ bpm-- Respiratory Rate: _____ breaths/min-- Oxygen Saturation: _____% on [O2 status]-- Weight: _____ kg (if relevant)--**General:**-[Overall appearance, distress level]--**[Focused Examination Relevant to Consultation]:**--**Example for Cardiology Consult:**-- **Cardiovascular:**- - JVP: [cm H2O]- - PMI: [location]- - Heart sounds: [S1, S2, murmurs, gallops, rubs]- - Peripheral pulses: [quality]- - Edema: [location and severity]--**Example for Pulmonary Consult:**-- **Pulmonary:**- - Respiratory effort: [description]- - Auscultation: [breath sounds, wheezes, crackles]- - Percussion: [findings]--[Include other relevant systems, may abbreviate or defer non-pertinent systems]-------## Pertinent Laboratory and Imaging Data--**Labs ([Date]):**--[Include only labs relevant to consultation]--| Test | Result | Reference Range | Trend |-|------|--------|----------------|-------|-| [Relevant lab] | [Value] | [Range] | [↑/↓/→] |--**Imaging/Diagnostics:**--**[Study] ([Date]):** [Relevant findings]--**ECG ([Date]):** [Relevant findings]--**Other Studies:** [Relevant results]-------## Assessment--**Consultant's Assessment of [Specific Problem]:**--[Detailed assessment of the consultation question]--**Differential Diagnosis:**-1. [Most likely diagnosis] - [supporting evidence]-2. [Alternative diagnosis] - [evidence for/against]-3. [Additional considerations]--**Severity/Acuity:** [Assessment of severity]--**Contributing Factors:** [What is contributing to the problem]--**Prognosis:** [Short-term and long-term outlook]-------## Recommendations--**[Problem Being Addressed]:**--**Diagnostic Recommendations:**-1. [Specific test] - [Rationale]-2. [Additional studies] - [Why needed]--**Therapeutic Recommendations:**-1. **[Intervention/Medication]:**- - [Specific dose, route, frequency]- - [Duration]- - [Rationale]- - [Monitoring parameters]--2. **[Additional treatments]**--3. **[Procedures if recommended]:**- - [Procedure name]- - [Indication]- - [Timing]--**Monitoring Recommendations:**-- [What to monitor]-- [How often]-- [Target parameters]--**Follow-up Recommendations:**-- [ ] Will follow along as consultant during hospitalization-- [ ] Recommend follow-up in [Specialty] clinic in [timeframe]-- [ ] Recommend re-consultation if [specific circumstances]-- [ ] No further consultation needed unless [conditions]--**Additional Recommendations:**-- [Lifestyle modifications]-- [Patient education points]-- [Precautions]--**Recommendations Summary for Primary Team:**-[Concise bulleted list of key recommendations that can be quickly reviewed]-1. [Action item 1]-2. [Action item 2]-3. [Action item 3]-------## Consultantdiscussion with Primary Team--**Discussed with:** [Name, role]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Topics discussed:** [Key points discussed]-**Plan agreed upon:** [Agreement or modifications]-------## Follow-up Plan--**Consultant will:**-- [ ] Round daily until [condition met or discharge]-- [ ] Re-evaluate in [X] days-- [ ] Available for questions or changes in clinical status-- [ ] Recommend outpatient follow-up in [timeframe]--**Primary team to:**-- [ ] Implement above recommendations-- [ ] Notify consultant if [specific circumstances]-- [ ] Monitor [specific parameters]-------## Signature--**Consultant:** [Name, MD/DO, credentials]-**Service:** [Consulting service]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Pager/Contact:** [Number]-**Signature:** ____________________--**Co-signature (if fellow or resident):**-**Attending:** [Name, credentials]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Signature:** ____________________-------## Template Notes--**Key Principles for Consultation Notes:**--1. **Answer the question:** Directly address the specific consultation request-2. **Be focused:** Include only information relevant to the consultation-3. **Be specific:** Provide clear, actionable recommendations-4. **Be concise:** Respect primary team's time-5. **Be available:** Make follow-up plan clear--**Common Consultation Types:**--**Cardiology:**-- Pre-operative risk assessment-- Arrhythmia management-- Heart failure management-- Chest pain evaluation--**Nephrology:**-- Acute kidney injury-- Chronic kidney disease management-- Electrolyte abnormalities-- Dialysis initiation/management--**Infectious Disease:**-- Antibiotic selection-- Fever of unknown origin-- Complex infections-- HIV management--**Endocrinology:**-- Diabetes management-- Thyroid disorders-- Adrenal insufficiency-- Calcium disorders--**Psychiatry:**-- Capacity assessment-- Depression/anxiety management-- Agitation management-- Substance withdrawal--**Pain Management:**-- Chronic pain consultation-- Post-operative pain control-- Cancer pain management--**Palliative Care:**-- Goals of care discussion-- Symptom management-- End-of-life care planning--**Tips for Effective Consultations:**--- Call the referring provider before seeing patient to clarify question-- Introduce yourself to patient and explain your role-- Review chart thoroughly before examination-- Be respectful of primary team's care-- Make specific recommendations, not vague suggestions-- Document same day as consultation-- Communicate recommendations verbally when appropriate-- Be available for questions-- Follow up consistently if ongoing consultation--diff --git a/skills/clinical-reports/assets/deidentification_process_checklist.json b/skills/clinical-reports/assets/deidentification_process_checklist.jsonnew file mode 100644index 00000000..df42bd27--- /dev/null+++ b/skills/clinical-reports/assets/deidentification_process_checklist.json@@ -0,0 +1,56 @@+{+ "schema_version": "2.0",+ "artifact_kind": "deidentification_process_checklist",+ "process_status": "BLOCKED_NOT_ASSESSED",+ "safety_notice": "This checklist cannot guarantee de-identification or HIPAA compliance. Safe Harbor requires all regulatory conditions, including no actual knowledge of identifiability. Expert Determination requires an appropriately qualified expert.",+ "data_scope": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "local_only_handling_confirmed": false,+ "minimum_necessary_reviewed": false,+ "method": "not_selected",+ "safe_harbor_identifiers": {+ "names": "not_assessed",+ "geographic_subdivisions": "not_assessed",+ "dates_and_ages": "not_assessed",+ "telephone_numbers": "not_assessed",+ "fax_numbers": "not_assessed",+ "email_addresses": "not_assessed",+ "social_security_numbers": "not_assessed",+ "medical_record_numbers": "not_assessed",+ "health_plan_numbers": "not_assessed",+ "account_numbers": "not_assessed",+ "certificate_and_license_numbers": "not_assessed",+ "vehicle_identifiers": "not_assessed",+ "device_identifiers": "not_assessed",+ "urls": "not_assessed",+ "ip_addresses": "not_assessed",+ "biometric_identifiers": "not_assessed",+ "full_face_images": "not_assessed",+ "other_unique_characteristics_or_codes": "not_assessed"+ },+ "actual_knowledge_review": {+ "completed_by_authorized_privacy_reviewer": false,+ "record_reference": null+ },+ "expert_determination": {+ "completed_by_qualified_expert": false,+ "expert_documentation_reference": null,+ "anticipated_recipient_and_conditions_documented": false+ },+ "synthetic_or_aggregate_rationale": {+ "origin_verified": false,+ "record_reference": null+ },+ "residual_risk_review": {+ "free_text": "not_assessed",+ "small_cells_and_rare_cases": "not_assessed",+ "images_and_metadata": "not_assessed",+ "linked_data_and_quasi_identifiers": "not_assessed"+ },+ "review": {+ "privacy_legal_review": "pending",+ "institutional_release_review": "pending",+ "release_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/discharge_summary_template.md b/skills/clinical-reports/assets/discharge_summary_template.mddeleted file mode 100644index 03419380..00000000--- a/skills/clinical-reports/assets/discharge_summary_template.md+++ /dev/null@@ -1,453 +0,0 @@-# Discharge Summary Template--## Patient Information--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age:** [years]-**Sex:** [M/F]--**Admission Date:** [MM/DD/YYYY]-**Discharge Date:** [MM/DD/YYYY]-**Length of Stay:** [X days]--**Admitting Service:** [Medicine/Surgery/Cardiology/etc.]-**Attending Physician:** [Name]-**Primary Care Physician:** [Name and contact]-**Consulting Services:** [List specialties that saw patient]-------## Admission Diagnosis--[Primary reason for hospitalization]--Example: "Acute decompensated heart failure"-------## Discharge Diagnoses--[Numbered list, prioritized by clinical significance]--**Primary Diagnosis:**-1. [Primary diagnosis with ICD-10 code]--**Secondary Diagnoses:**-2. [Secondary diagnosis with ICD-10 code]-3. [Additional diagnosis with ICD-10 code]-4. [Comorbidity with ICD-10 code]--Example:-```-1. Acute decompensated heart failure (I50.23)-2. Acute kidney injury on chronic kidney disease stage 3 (N17.9, N18.3)-3. Hypokalemia (E87.6)-4. Type 2 diabetes mellitus (E11.9)-5. Coronary artery disease (I25.10)-```-------## Hospital Course--[Comprehensive yet concise narrative of hospital stay - can be organized chronologically or by problem]--### Chronological Format:--**[Date Range or Hospital Day 1-X]:**--[Patient Name] was admitted to the [service] service with [chief complaint/presenting problem]. On presentation, patient was [clinical status]. Initial workup revealed [key findings].--[Description of key events, interventions, and response to treatment organized by day or by problem]--**Hospital Day 1:** [Events and interventions]--**Hospital Day 2-3:** [Progression, response to treatment]--**Hospital Day 4-7:** [Continued treatment, consultations, procedures]--**Final Hospital Days:** [Stabilization, preparation for discharge]--### Problem-Based Format (Alternative):--**1. [Primary Problem]**-- Presentation and initial management-- Diagnostic workup-- Treatment course-- Response and outcome-- Status at discharge--**2. [Secondary Problem]**-- [Similar structure]--**3. [Additional Problems]**--### Key Events and Interventions--**Consultations Obtained:**-- [Specialty] consulted on [date] for [reason]: [Recommendations]--**Procedures Performed:**-- [Procedure name] on [date]: [Indication, findings, complications if any]--**Significant Diagnostic Studies:**-- [Test/imaging] on [date]: [Key findings relevant to discharge care]--**Complications:**-- [Any complications that occurred]: [How managed]-------## Procedures Performed During Hospitalization--1. [Procedure name] ([Date])- - Indication: [Why performed]- - Findings: [Key findings]- - Complications: [None / specific complications]--2. [Additional procedures]-------## Hospital Course Summary (Brief Version)--[One paragraph summary suitable for quick reference]--Example:-```-Mr. [Name] was admitted with acute decompensated heart failure in the setting of-medication non-adherence. He was diuresed with IV furosemide with net negative-5 liters over 3 days, with significant improvement in dyspnea and resolution of-lower extremity edema. Echocardiogram showed EF 30%, similar to prior. Kidney-function improved to baseline with diuresis. He was transitioned to oral diuretics-on hospital day 3 and remained stable. Patient was ambulating without dyspnea on-room air by discharge. Comprehensive heart failure education was provided.-```-------## Discharge Physical Examination--**Vital Signs:**-- Temperature: \_\_\_\_\_ °F-- Blood Pressure: \_\_\_\_\_/\_\_\_\_\_ mmHg-- Heart Rate: \_\_\_\_\_ bpm-- Respiratory Rate: \_\_\_\_\_ breaths/min-- Oxygen Saturation: \_\_\_\_\_% on [room air / O2]-- Weight: \_\_\_\_\_ kg (Admission weight: \_\_\_\_\_ kg)--**General:** [Appearance, distress level]--**Cardiovascular:** [Heart sounds, edema]--**Pulmonary:** [Breath sounds, work of breathing]--**Abdomen:** [Tenderness, bowel sounds, distention]--**Extremities:** [Edema, pulses]--**Neurological:** [Mental status, focal deficits]--**Wounds/Incisions (if applicable):** [Healing status]-------## Pertinent Laboratory and Imaging Results--### Discharge Labs ([Date])--| Test | Result | Reference Range |-|------|--------|----------------|-| WBC | [Value] | [Range] |-| Hemoglobin | [Value] | [Range] |-| Platelets | [Value] | [Range] |-| Sodium | [Value] | [Range] |-| Potassium | [Value] | [Range] |-| Creatinine | [Value] | [Range] |-| [Other relevant labs] | [Value] | [Range] |--### Imaging/Diagnostic Studies--**[Study name] ([Date]):** [Key findings relevant to outpatient management]-------## Discharge Medications--[Complete list with clear indication of changes from admission]--### New Medications (Started During Hospitalization)--1. **[Medication name]** [dose] [route] [frequency]- - Indication: [Why prescribed]- - Duration: [If limited duration]- - Special instructions: [With food, time of day, etc.]--### Changed Medications (Dose or Frequency Modified)--2. **[Medication name]** [NEW dose] [route] [frequency]- - **CHANGED FROM:** [Previous dose and frequency]- - Reason for change: [Why modified]--### Continued Medications (No change from home medications)--3. **[Medication name]** [dose] [route] [frequency]- - **CONTINUED** from home regimen--### Discontinued Medications (Stopped During Hospitalization)--4. **[Medication name]** - **DISCONTINUED**- - Reason: [Why stopped]--### Complete Medication List for Patient--[Consolidated list in simple format for patient]--```-1. Furosemide 40 mg by mouth once daily [NEW - for fluid management]-2. Carvedilol 12.5 mg by mouth twice daily [CONTINUED]-3. Lisinopril 20 mg by mouth once daily [CONTINUED]-4. Metformin 1000 mg by mouth twice daily [CONTINUED]-5. Aspirin 81 mg by mouth once daily [CONTINUED]-```-------## Discharge Condition--**Overall Status:** [Stable / Improved / Baseline / Requires continued care]--**Specific Assessments:**-- Hemodynamic status: [Stable]-- Respiratory status: [Room air / Oxygen requirement]-- Mental status: [Alert and oriented x3 / Other]-- Functional status: [Ambulatory / Requires assistance / Bedbound]-- Pain control: [Adequate / Inadequate]-- Wound healing (if applicable): [Appropriate / Delayed]--Example:-```-Patient is hemodynamically stable, ambulatory without assistance, no supplemental-oxygen requirement, euvolemic on physical exam, pain well-controlled, and has-returned to baseline functional status.-```-------## Discharge Disposition--[Where patient is going after hospital discharge]--Options:-- Home with self-care-- Home with home health services-- Skilled nursing facility-- Acute rehabilitation facility-- Long-term acute care hospital-- Hospice (home or facility)-- Left against medical advice (AMA)-- Transferred to another acute care facility--**Discharge Disposition:** [Selection from above]--**Services Arranged:**-- [ ] Home health nursing-- [ ] Physical therapy-- [ ] Occupational therapy-- [ ] Durable medical equipment: [List items]-- [ ] Home oxygen: [Flow rate and delivery method]-- [ ] Other: [Specify]-------## Follow-Up Appointments--1. **[Specialty/PCP]** with Dr. [Name]- - Date/Time: [Scheduled date and time] OR [Within X days/weeks]- - Location: [Clinic name and address]- - Phone: [Contact number]- - Purpose: [What needs to be addressed]--2. **[Additional appointments]**--### Pending Studies/Labs at Discharge--- [Test name]: [When due, where to go, reason]-- Results will be sent to: [Provider name]--### Referrals Placed--- [Specialty]: [Reason for referral, contact information]-------## Patient Instructions--### Activity--- [Specific activity restrictions or recommendations]-- Example: "Resume normal activities as tolerated. Avoid heavy lifting >10 lbs for 2 weeks."--### Diet--- [Dietary restrictions or recommendations]-- Example: "Low sodium diet (less than 2 grams per day). Fluid restriction to 2 liters per day."--### Wound Care (if applicable)--- [Incision care instructions]-- [Dressing change frequency]-- [When stitches/staples should be removed]--### Self-Monitoring--- [What patient should monitor at home]-- Example: "Weigh yourself every morning. Call doctor if weight gain >2 lbs in 1 day or >5 lbs in 1 week."--### Equipment/Supplies--- [Equipment provided or prescribed]-- [How to use]--### Medications--- [General medication instructions]-- [Importance of compliance]-- [What to do if dose missed]-------## Return Precautions / Warning Signs--**Call your doctor or return to emergency department if you experience:**--- [Specific warning signs relevant to condition]-- [When to seek immediate care vs. call doctor]--Example for heart failure:-```-- Worsening shortness of breath or difficulty breathing-- Chest pain or pressure-- Severe swelling in legs or abdomen-- Weight gain more than 2 lbs in one day or 5 lbs in one week-- Dizziness, lightheadedness, or fainting-- Fever >101°F-- Any other concerning symptoms-```--**Emergency Contact Numbers:**-- Primary care physician: [Phone]-- Specialty clinic: [Phone]-- After-hours nurse line: [Phone]-- 911 for emergencies-------## Patient Education Provided--Topics discussed with patient and/or family:-- [ ] Disease process and prognosis-- [ ] Medication purpose, dosing, and side effects-- [ ] Warning signs and when to seek care-- [ ] Activity and dietary restrictions-- [ ] Follow-up appointments-- [ ] Use of medical equipment-- [ ] [Other specific topics]--**Patient/Family Understanding:**-[Patient and family verbalize understanding of discharge instructions / Teach-back method used and patient able to repeat key points / Interpreter used]--**Written Materials Provided:**-- [ ] Discharge instructions-- [ ] Medication list-- [ ] Disease-specific education materials-- [ ] Emergency contact information-- [ ] Appointment information-------## Code Status at Discharge--**Code Status:** [Full code / DNR / DNI / Other limitations]--[If changed during hospitalization, note when and why]-------## Additional Information--### Advance Directives--- [ ] Advance directive on file-- [ ] Healthcare proxy designated: [Name and contact]-- [ ] Living will present--### Social Situation--[Relevant social factors affecting discharge plan]-- Living situation: [Lives alone / with family / assisted living]-- Caregiver support: [Available / Limited / None]-- Transportation: [Adequate / Needs assistance]-- Barriers to compliance: [Financial / Cognitive / Language / Other]--### Pending Issues at Discharge--[Tests or consultations still pending that require outpatient follow-up]-------## Signature--**Prepared by:**-[Physician name, credentials]-[Pager/Contact number]--**Cosigned by (if resident/fellow):**-[Attending physician name]--**Date and Time:** [MM/DD/YYYY at HH:MM]--**Electronically signed:** [Yes/No]-------## Template Completion Checklist--- [ ] All discharge diagnoses listed with ICD-10 codes-- [ ] Hospital course summarized clearly-- [ ] All procedures documented-- [ ] Discharge medications reconciled and clearly marked (new/changed/continued/stopped)-- [ ] Follow-up appointments scheduled or timeframe provided-- [ ] Patient education documented-- [ ] Return precautions specific to patient's conditions-- [ ] Pending tests/results documented with follow-up plan-- [ ] Code status documented-- [ ] Completed within 24-48 hours of discharge (institutional requirement)-- [ ] Sent to primary care physician and relevant specialists-- [ ] Copy provided to patient-------## Notes--**Timing Requirements:**-- CMS requires completion within 30 days-- Many hospitals require 24-48 hours-- Should be available for follow-up appointments--**Distribution:**-- Send to primary care physician-- Send to referring physician-- Send to consulting specialists involved in care-- Provide copy to patient-- Upload to shared HIE (Health Information Exchange)--**Quality Measures:**-- Medication reconciliation required-- Clear communication of changes-- Specific follow-up plans-- Patient education documented--diff --git a/skills/clinical-reports/assets/hipaa_compliance_checklist.md b/skills/clinical-reports/assets/hipaa_compliance_checklist.mddeleted file mode 100644index d1d64ffe..00000000--- a/skills/clinical-reports/assets/hipaa_compliance_checklist.md+++ /dev/null@@ -1,395 +0,0 @@-# HIPAA Compliance Checklist for Clinical Reports--## 18 HIPAA Identifiers - De-identification Checklist--Verify that ALL of the following identifiers have been removed or altered:--- [ ] **1. Names** - Patient name, family members, healthcare providers (unless necessary and consented)--- [ ] **2. Geographic subdivisions smaller than state**- - No street addresses- - No cities (unless >20,000 population and part of ZIP can be kept if >20,000)- - No counties- - First 3 digits of ZIP code acceptable only if geographic unit >20,000 people- - All other portions of ZIP codes removed--- [ ] **3. Dates** (except year)- - No exact dates of birth (year only acceptable; year of birth for those >89 must be aggregated)- - No admission dates- - No discharge dates- - No dates of service- - No dates of death- - Use relative time periods (e.g., "3 months prior") or years only--- [ ] **4. Telephone numbers**- - No phone numbers of any kind- - Including patient, family, provider contact numbers--- [ ] **5. Fax numbers**- - No fax numbers--- [ ] **6. Email addresses**- - No email addresses for patient or related individuals--- [ ] **7. Social Security numbers**- - No SSN or partial SSN--- [ ] **8. Medical record numbers**- - No MRN, hospital ID, or clinic numbers- - Use coded study ID or case number if needed--- [ ] **9. Health plan beneficiary numbers**- - No insurance ID numbers- - No policy numbers--- [ ] **10. Account numbers**- - No billing account numbers- - No financial account information--- [ ] **11. Certificate/license numbers**- - No driver's license numbers- - No professional license numbers (unless for author credentials)--- [ ] **12. Vehicle identifiers and serial numbers**- - No license plate numbers- - No VIN numbers--- [ ] **13. Device identifiers and serial numbers**- - No pacemaker serial numbers- - No implant device serial numbers- - Generic device description acceptable (e.g., "implantable cardioverter-defibrillator")--- [ ] **14. Web URLs**- - No personal websites- - No URLs identifying individuals--- [ ] **15. IP addresses**- - No IP addresses--- [ ] **16. Biometric identifiers**- - No fingerprints- - No voiceprints- - No retinal scans- - No other biometric data--- [ ] **17. Full-face photographs and comparable images**- - No full-face photographs without consent- - Crop or blur faces if showing- - Remove identifying features (jewelry, tattoos, birthmarks if not clinically relevant)- - Black bars over eyes NOT sufficient- - Ensure no reflection or background identification--- [ ] **18. Any other unique identifying characteristic or code**- - No unique characteristics that could identify individual- - No rare disease combinations that could identify- - Consider if combination of remaining data points could identify individual-------## Additional De-identification Considerations--### Ages and Dates--- [ ] Patients aged ≤89: Exact age or age range acceptable-- [ ] Patients aged >89: Must be aggregated to "90 or older" or ">89 years"-- [ ] Dates: Use only years OR use relative time periods- - Example: "3 months prior to presentation" instead of "on January 15, 2023"- - Example: "admitted in 2023" instead of "admitted on March 10, 2023"--### Geographic Information--- [ ] State or country is acceptable-- [ ] Removed specific cities (unless population >20,000 and no other identifying information)-- [ ] Removed hospital/clinic names-- [ ] Use general descriptors: "a community hospital in the Midwest" or "a tertiary care center"--### Rare Conditions and Combinations--- [ ] Consider if very rare disease alone could identify patient-- [ ] Consider if combination of:- - Age + diagnosis + geographic area + timeframe could identify patient-- [ ] May need to be vague about certain unique details-- [ ] Balance between providing clinical information and protecting privacy--### Images and Figures--- [ ] All patient identifiers removed from image headers/metadata-- [ ] DICOM data stripped-- [ ] Dates removed from images-- [ ] Medical record numbers removed-- [ ] Faces cropped, blurred, or obscured-- [ ] Identifying marks removed or obscured:- - Tattoos- - Jewelry- - Birthmarks or unique scars (if not clinically relevant)-- [ ] Scale bars and annotations do not contain identifying information-- [ ] Background environment de-identified (room numbers, nameplates, etc.)--### Voice and Video--- [ ] No audio recordings with patient voice (unless consent obtained)-- [ ] No video showing identifiable features (unless consent obtained)-- [ ] If video necessary, face must be obscured-------## Informed Consent Checklist (for Case Reports/Publications)--### Consent Requirements--- [ ] Informed consent obtained BEFORE publication submission-- [ ] Consent obtained from patient directly (if capable)-- [ ] If patient deceased or incapacitated, consent from legal representative or next of kin-- [ ] For pediatric cases, parental/guardian consent obtained--### Consent Form Elements--The informed consent form must include:--- [ ] Purpose of publication (education, medical knowledge)-- [ ] What will be published (case details, images, outcomes)-- [ ] Journal or publication venue (if known)-- [ ] Open access vs. subscription (public availability)-- [ ] De-identification efforts explained-- [ ] Potential for re-identification acknowledged-- [ ] No effect on clinical care-- [ ] Right to withdraw consent (timing limitations)-- [ ] Contact information for questions-- [ ] Patient signature and date-- [ ] Witness signature (if required)--### Consent Documentation--- [ ] Signed consent form on file-- [ ] Copy provided to patient-- [ ] Consent available for editor review-- [ ] Statement in manuscript confirming consent obtained--**Example statement for manuscript:**-"Written informed consent was obtained from the patient for publication of this case report and any accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal on request."-------## Safe Harbor vs. Expert Determination--### Safe Harbor Method--- [ ] All 18 identifiers removed-- [ ] No actual knowledge that remaining information could identify individual-- [ ] Most straightforward method-- [ ] Recommended for most clinical reports--### Expert Determination Method--- [ ] Qualified statistician/expert determined very small re-identification risk-- [ ] Methodology documented-- [ ] Analysis methods specified-- [ ] Conclusion documented-- [ ] May allow retention of some data elements-- [ ] Requires statistical expertise--**Method used:** [ ] Safe Harbor [ ] Expert Determination-------## Minimum Necessary Standard--### Use and Disclosure--- [ ] Only minimum PHI necessary for purpose is used-- [ ] Purpose of disclosure clearly defined-- [ ] Limited to relevant information only-- [ ] Consider de-identified data or limited data set as alternatives--### Exceptions to Minimum Necessary--Minimum necessary does NOT apply to:-- Treatment purposes (providers may need full information)-- Patient-authorized disclosures-- Disclosures required by law-- Disclosures to HHS for compliance investigation-------## Authorization for Use/Disclosure of PHI--### When Authorization Required--Authorization needed for:-- [ ] Research (unless IRB waiver granted)-- [ ] Marketing purposes-- [ ] Sale of PHI-- [ ] Psychotherapy notes-- [ ] Uses beyond treatment, payment, operations (TPO)--### Authorization Elements--If authorization required, it must include:--- [ ] Specific description of PHI to be used/disclosed-- [ ] Person(s) authorized to make disclosure-- [ ] Person(s) to receive information-- [ ] Purpose of disclosure-- [ ] Expiration date or event-- [ ] Right to revoke and how-- [ ] Right to refuse to sign-- [ ] Potential for re-disclosure by recipient-- [ ] Patient signature and date-------## Limited Data Set--### Limited Data Set Option--A limited data set removes 16 of 18 identifiers but may retain:-- [ ] Dates (admission, discharge, service, birth, death)-- [ ] Geographic information (city, state, ZIP code)--### Requirements for Limited Data Set--- [ ] Data Use Agreement (DUA) required-- [ ] DUA specifies permitted uses-- [ ] Only for research, public health, or healthcare operations-- [ ] Recipient agrees not to re-identify-- [ ] Recipient agrees to safeguard data-------## Security Safeguards Checklist--### Administrative Safeguards--- [ ] Security management process in place-- [ ] Workforce security measures-- [ ] Access management (role-based)-- [ ] Security training for workforce-- [ ] Incident response procedures--### Physical Safeguards--- [ ] Facility access controls-- [ ] Workstation use policies-- [ ] Workstation security measures-- [ ] Device and media controls-- [ ] Secure disposal procedures--### Technical Safeguards--- [ ] Access controls (unique user IDs, passwords)-- [ ] Audit controls and logging-- [ ] Integrity controls-- [ ] Transmission security (encryption)-- [ ] Automatic logoff after inactivity-------## Breach Notification Checklist--### If Unauthorized Disclosure Occurs--- [ ] Determine if breach occurred (unauthorized access/use/disclosure)-- [ ] Assess risk of harm to individual-- [ ] If breach affects <500 individuals:- - Notify individual within 60 days- - Report to HHS annually-- [ ] If breach affects ≥500 individuals:- - Notify individuals within 60 days- - Notify HHS within 60 days- - Notify media if affects ≥500 in a state/jurisdiction-- [ ] Document breach and response-- [ ] Implement corrective action--### Breach Notification Content--Notification must include:-- [ ] Description of breach-- [ ] Types of information involved-- [ ] Steps individuals should take-- [ ] What organization is doing-- [ ] Contact for questions-------## Research-Specific Compliance--### IRB/Privacy Board Considerations--- [ ] IRB approval obtained (if research)-- [ ] HIPAA authorization obtained OR waiver granted-- [ ] Waiver justification documented:- - Minimal risk to privacy- - Research cannot practically be conducted without waiver- - Research cannot practically be conducted without PHI- - Plan to protect identifiers- - Plan to destroy identifiers when appropriate--### Clinical Trial Reporting--- [ ] Subject identified by ID number only-- [ ] No names in regulatory submissions-- [ ] Initials only if required by regulatory authority-- [ ] Dates limited to year or relative time-- [ ] Protocol includes privacy protections-------## Special Populations--### Pediatric Cases--- [ ] Parent/guardian consent obtained-- [ ] Child assent obtained (if age-appropriate)-- [ ] Extra care with identifiable photos-- [ ] School information removed--### Deceased Patients--- [ ] HIPAA protections apply for 50 years post-death-- [ ] Next of kin consent for publication-- [ ] Autopsy information de-identified--### Mental Health and Substance Abuse--- [ ] Extra protections under 42 CFR Part 2-- [ ] Explicit consent for disclosure-- [ ] Cannot re-disclose without consent-------## Final Compliance Verification--**Reviewed by:** ____________________-**Date:** ____________________-**Signature:** ____________________--**Compliance Status:** [ ] Compliant [ ] Needs revision [ ] Not compliant--**Issues identified:**-1. [Issue]-2. [Issue]--**Corrective actions:**-1. [Action]-2. [Action]--**Re-review required:** [ ] Yes [ ] No-**Re-review date:** ____________________-------## Documentation to Maintain--Keep on file:-- [ ] Signed patient consent (if applicable)-- [ ] IRB approval (if research)-- [ ] HIPAA waiver (if applicable)-- [ ] De-identification verification-- [ ] Data use agreement (if limited data set)-- [ ] Authorization forms (if applicable)-- [ ] Training records for personnel handling PHI-- [ ] Audit logs--**Retention period:** Minimum 6 years per HIPAA requirement--diff --git a/skills/clinical-reports/assets/history_physical_template.md b/skills/clinical-reports/assets/history_physical_template.mddeleted file mode 100644index 1e8b0020..00000000--- a/skills/clinical-reports/assets/history_physical_template.md+++ /dev/null@@ -1,305 +0,0 @@-# History and Physical Examination (H&P) Template--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age:** [years]-**Sex:** [M/F]--**Date of Admission/Encounter:** [MM/DD/YYYY]-**Time:** [HH:MM]-**Location:** [Hospital floor, Clinic, ED]-**Admitting Service:** [Medicine, Surgery, etc.]-**Attending Physician:** [Name]-------## Chief Complaint (CC)--"[Patient's stated reason for seeking care, in quotes]"-------## History of Present Illness (HPI)--[Patient Name] is a [age]-year-old [sex] with a history of [relevant PMHx] who presents with [chief complaint].--[Use OPQRST format for symptoms, provide chronological narrative]--**Onset:** [When did symptoms start? Sudden vs gradual onset?]-**Location:** [Where? Does it radiate?]-**Duration:** [How long?]-**Character:** [Quality - sharp, dull, pressure, etc.]-**Aggravating factors:** [What makes it worse?]-**Relieving factors:** [What makes it better?]-**Timing:** [Constant or intermittent? Pattern?]-**Severity:** [0-10 scale for pain, functional impact]-**Associated symptoms:** [Other symptoms?]--**Prior evaluations and treatments:**-**Why presenting now:**-------## Past Medical History (PMH)--1. [Condition] - diagnosed [year], [current status]-2. [Condition] - diagnosed [year], [treatment]-3. [Additional conditions]--[ ] No known medical problems-------## Past Surgical History (PSH)--1. [Procedure] ([year]) - [indication, complications if any]-2. [Procedure] ([year])--[ ] No prior surgeries-------## Medications--| Medication | Dose | Route | Frequency | Indication |-|------------|------|-------|-----------|------------|-| [Drug name] | [mg] | [PO/IV/etc] | [BID/etc] | [Why prescribed] |--[ ] No current medications-------## Allergies--| Allergen | Reaction |-|----------|----------|-| [Drug/Food/Environmental] | [Type of reaction] |--[ ] No known drug allergies (NKDA)-------## Family History (FH)--- **Father:** [Age/deceased at age X], [medical conditions]-- **Mother:** [Age/deceased at age X], [medical conditions]-- **Siblings:** [Number], [relevant conditions]-- **Children:** [Number], [relevant conditions]--[Note hereditary conditions relevant to patient's presentation]--[ ] Non-contributory-------## Social History (SH)--**Tobacco:** [Current/former/never], [pack-years if applicable]-**Alcohol:** [Frequency and amount, CAGE questions if indicated]-**Illicit drugs:** [Current/former/never, type, route]-**Occupation:** [Current or former occupation]-**Living situation:** [Lives alone/with family, housing type]-**Marital status:** [Single/married/divorced/widowed]-**Sexual history:** [If relevant]-**Exercise:** [Type and frequency]-**Diet:** [General diet description]-**Functional status:** [ADL independence, baseline activity level]-------## Review of Systems (ROS)--[Systematic review - check relevant systems]--**Constitutional:** [ ] Fever [ ] Chills [ ] Night sweats [ ] Weight loss [ ] Weight gain [ ] Fatigue-**Eyes:** [ ] Vision changes [ ] Eye pain [ ] Discharge-**ENT:** [ ] Hearing loss [ ] Tinnitus [ ] Sinus problems [ ] Sore throat-**Cardiovascular:** [ ] Chest pain [ ] Palpitations [ ] Edema [ ] Orthopnea [ ] PND [ ] Claudication-**Respiratory:** [ ] Dyspnea [ ] Cough [ ] Wheezing [ ] Hemoptysis-**Gastrointestinal:** [ ] Nausea [ ] Vomiting [ ] Diarrhea [ ] Constipation [ ] Abdominal pain [ ] Melena [ ] Hematochezia-**Genitourinary:** [ ] Dysuria [ ] Frequency [ ] Urgency [ ] Hematuria [ ] Incontinence-**Musculoskeletal:** [ ] Joint pain [ ] Swelling [ ] Stiffness [ ] Back pain [ ] Weakness-**Skin:** [ ] Rash [ ] Lesions [ ] Itching [ ] Changes in moles-**Neurological:** [ ] Headache [ ] Dizziness [ ] Syncope [ ] Seizures [ ] Weakness [ ] Numbness [ ] Tingling-**Psychiatric:** [ ] Depression [ ] Anxiety [ ] Sleep disturbance-**Endocrine:** [ ] Heat/cold intolerance [ ] Polyuria [ ] Polydipsia [ ] Polyphagia-**Hematologic/Lymphatic:** [ ] Easy bruising [ ] Bleeding [ ] Lymph node swelling-**Allergic/Immunologic:** [ ] Seasonal allergies [ ] Frequent infections--**All other systems reviewed and negative** [ ]-------## Physical Examination--**Vital Signs:**-- Temperature: _____ °F (oral/axillary/tympanic)-- Blood Pressure: _____/_____ mmHg ([right arm, sitting])-- Heart Rate: _____ bpm (regular/irregular)-- Respiratory Rate: _____ breaths/min-- Oxygen Saturation: _____% on [room air / O2 at ___ L/min]-- Height: _____ cm / inches-- Weight: _____ kg / lbs-- BMI: _____ kg/m²-- Pain Score: ___/10--**General:**-[Overall appearance, apparent vs stated age, nutritional status, distress level]--**HEENT:**-- Head: [Normocephalic, atraumatic, scalp lesions]-- Eyes: [PERRLA, EOMI, conjunctiva, sclera, fundoscopy if done]-- Ears: [TMs, canals, hearing]-- Nose: [Nares, septum, discharge, sinus tenderness]-- Throat: [Oropharynx, tonsils, dentition, mucosa]--**Neck:**-[Supple/stiff, lymphadenopathy, thyroid, JVP, carotid bruits]--**Cardiovascular:**-- Inspection: [PMI, precordial movement]-- Palpation: [PMI location, thrills, lifts]-- Auscultation: [Rate, rhythm, S1/S2, murmurs/rubs/gallops, location and radiation]-- Peripheral pulses: [Radial, femoral, DP, PT - rate quality bilaterally]-- Extremities: [Edema, cyanosis, clubbing]--**Pulmonary:**-- Inspection: [Respiratory effort, use of accessory muscles, chest wall deformities]-- Palpation: [Tactile fremitus, chest expansion]-- Percussion: [Resonance, dullness]-- Auscultation: [Breath sounds, adventitious sounds - location and quality]--**Abdomen:**-- Inspection: [Contour, scars, distention, visible peristalsis]-- Auscultation: [Bowel sounds - present, hyperactive, hypoactive, absent]-- Percussion: [Tympany, dullness, liver span, spleen]-- Palpation: [Soft/firm, tenderness, masses, organomegaly, rebound, guarding, Murphy's sign]--**Musculoskeletal:**-- Inspection: [Deformities, swelling, erythema]-- Palpation: [Tenderness, warmth]-- Range of motion: [Active and passive, limitations]-- Strength: [5-point scale by major muscle groups]-- Gait: [Normal, antalgic, ataxic, spastic]--**Skin:**-[Color, temperature, moisture, turgor, lesions, rashes, wounds]--**Neurological:**-- Mental Status: [Alert, oriented x3 (person, place, time), speech, memory]-- Cranial Nerves: [II-XII - document abnormalities]-- Motor: [Strength 5-point scale, tone, bulk, fasciculations]-- Sensory: [Light touch, pinprick, proprioception, vibration]-- Reflexes: [Deep tendon reflexes 0-4+ scale, Babinski]-- Coordination: [Finger-to-nose, heel-to-shin, rapid alternating movements]-- Gait: [Already documented above or describe here]--**Psychiatric:**-[Mood, affect, thought process, thought content, judgment, insight]--**Genitourinary:** (if applicable)-[Defer/document findings if examined]--**Rectal:** (if applicable)-[Defer/document findings if examined]-------## Laboratory and Imaging Results--[Include relevant results available at time of H&P]--**Labs ([Date]):**--| Test | Result | Reference Range | Flag |-|------|--------|----------------|------|-| WBC | [Value] | [Range] | [H/L/-] |-| Hemoglobin | [Value] | [Range] | [H/L/-] |-| [Additional labs] | | | |--**Imaging ([Study], [Date]):**-[Key findings]--**ECG ([Date]):**-[Rate, rhythm, intervals, axis, ST-T changes, other findings]--**Other Studies:**-------## Assessment and Plan--**Assessment:**--[Patient summary statement in one sentence]--**Problem List:**--**1. [Primary Problem/Diagnosis] ([ICD-10 code])**--**Assessment:** [Brief description of problem, severity, stability]--**Plan:**-- **Diagnostics:** [Labs, imaging, consultations needed]-- **Therapeutics:** [Medications, procedures, interventions]- - [Medication]: [dose, route, frequency] for [indication]-- **Monitoring:** [What to monitor, how often]-- **Follow-up:** [When and with whom]-- **Disposition:** [Admit to floor/ICU, discharge, observation]--**2. [Secondary Problem] ([ICD-10 code])**--**Assessment:** [Description]--**Plan:**-- [Diagnostics]-- [Therapeutics]-- [Monitoring]--**3. [Additional Problems]**-[Continue for all active problems]--**Code Status:** [Full code / DNR / DNI / Other]--**Prophylaxis:**-- DVT prophylaxis: [Pharmacologic and/or mechanical]-- GI prophylaxis: [If indicated]-- Aspiration precautions: [If indicated]--**Disposition:** [Admit to service, location (floor/ICU), level of care]-------## Signature--**Physician:** [Name, credentials]-**Level:** [Intern, Resident, Attending]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Signature:** ____________________--**Co-signature (if applicable):**-**Attending:** [Name, credentials]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Signature:** ____________________-------## Template Completion Checklist--- [ ] Chief complaint documented-- [ ] HPI comprehensive (≥4 HPI elements for billing)-- [ ] PMH reviewed-- [ ] Medications reconciled-- [ ] Allergies documented-- [ ] ROS performed (≥10 systems for comprehensive)-- [ ] Complete physical exam documented (≥8 systems for comprehensive)-- [ ] Labs/imaging reviewed-- [ ] Assessment and plan for each problem-- [ ] Code status documented-- [ ] Prophylaxis addressed-- [ ] Disposition clear-- [ ] Completed within 24 hours of admission (TJC requirement)-- [ ] Signed and dated--diff --git a/skills/clinical-reports/assets/lab_report_template.json b/skills/clinical-reports/assets/lab_report_template.jsonnew file mode 100644index 00000000..9150036e--- /dev/null+++ b/skills/clinical-reports/assets/lab_report_template.json@@ -0,0 +1,36 @@+{+ "schema_version": "2.0",+ "artifact_kind": "laboratory_report_scaffold",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_RELEASE",+ "safety_notice": "Copy only released, verified laboratory source facts. Do not calculate, convert, interpret, flag, suppress, set reference intervals, set critical thresholds, notify, correct, release, or sign.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "guidance": {+ "base": "42 CFR 493.1291",+ "scope_verified_by_laboratory": false,+ "specialty_requirements": null,+ "state_accreditor_and_local_policy_versions": null+ },+ "report_status": null,+ "source_system_record": null,+ "fields": {+ "performing_laboratory": {"status": "missing", "source_fact_ids": []},+ "specimen": {"status": "missing", "source_fact_ids": []},+ "test_and_method": {"status": "missing", "source_fact_ids": []},+ "released_result": {"status": "missing", "source_fact_ids": []},+ "released_units": {"status": "missing", "source_fact_ids": []},+ "released_reference_interval": {"status": "missing", "source_fact_ids": []},+ "released_flags_or_comments": {"status": "missing", "source_fact_ids": []},+ "referral_laboratory_information": {"status": "missing", "source_fact_ids": []},+ "original_and_corrected_report_linkage": {"status": "missing", "source_fact_ids": []},+ "documented_notification_record": {"status": "missing", "source_fact_ids": []}+ },+ "provenance_manifest": null,+ "review": {+ "authorized_laboratory_review": "pending",+ "privacy_review": "pending",+ "released_from_authorized_system": false,+ "signature_present": false+ }+}diff --git a/skills/clinical-reports/assets/lab_report_template.md b/skills/clinical-reports/assets/lab_report_template.mddeleted file mode 100644index d7092945..00000000--- a/skills/clinical-reports/assets/lab_report_template.md+++ /dev/null@@ -1,309 +0,0 @@-# Laboratory Report Template--## Patient Information--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age/Sex:** [Age years, M/F]--**Ordering Physician:** [Name]-**Location:** [Inpatient unit / Outpatient clinic]-------## Specimen Information--**Specimen Type:** [Blood / Serum / Plasma / Urine / CSF / Other]-**Collection Date/Time:** [MM/DD/YYYY at HH:MM]-**Received Date/Time:** [MM/DD/YYYY at HH:MM]-**Reported Date/Time:** [MM/DD/YYYY at HH:MM]--**Accession Number:** [Lab accession number]-**Specimen Condition:** [Acceptable / See comments]-**Fasting Status:** [Fasting / Non-fasting / Unknown] (if relevant)-------## Laboratory Results--| Test Name | Result | Units | Reference Range | Flag |-|-----------|--------|-------|----------------|------|-| [Test] | [Value] | [Unit] | [Normal range] | [L/H/Critical] |--### Example: Complete Blood Count (CBC)--| Test | Result | Units | Reference Range | Flag |-|------|--------|-------|----------------|------|-| White Blood Cell Count | 12.5 | × 10³/μL | 4.5-11.0 | H |-| Hemoglobin | 10.2 | g/dL | 12.0-16.0 (F), 14.0-18.0 (M) | L |-| Hematocrit | 31.5 | % | 36.0-48.0 (F), 42.0-52.0 (M) | L |-| Platelet Count | 245 | × 10³/μL | 150-400 | - |-| MCV | 88.5 | fL | 80.0-100.0 | - |-| MCH | 29.5 | pg | 27.0-33.0 | - |-| MCHC | 33.2 | g/dL | 32.0-36.0 | - |-| RDW | 14.5 | % | 11.5-14.5 | - |--**Differential:**-| Cell Type | Result | Units | Reference Range | Flag |-|-----------|--------|-------|----------------|------|-| Neutrophils | 75 | % | 40-70 | H |-| Lymphocytes | 15 | % | 20-40 | L |-| Monocytes | 7 | % | 2-10 | - |-| Eosinophils | 2 | % | 1-4 | - |-| Basophils | 1 | % | 0-2 | - |--### Example: Basic Metabolic Panel (BMP)--| Test | Result | Units | Reference Range | Flag |-|------|--------|-------|----------------|------|-| Sodium | 138 | mEq/L | 136-145 | - |-| Potassium | 3.2 | mEq/L | 3.5-5.0 | L |-| Chloride | 102 | mEq/L | 98-107 | - |-| CO2 | 24 | mEq/L | 22-30 | - |-| Blood Urea Nitrogen | 28 | mg/dL | 7-20 | H |-| Creatinine | 1.8 | mg/dL | 0.6-1.2 (F), 0.7-1.3 (M) | H |-| Glucose | 145 | mg/dL | 70-100 (fasting) | H |-| eGFR | 42 | mL/min/1.73m² | >60 | L |-------## Interpretation / Comments--[Clinical interpretation when applicable]--**Example for Anemia:**-```-Normocytic anemia with elevated WBC. Differential diagnosis includes anemia of chronic-disease, recent blood loss, or hemolysis. Consider reticulocyte count, iron studies,-and peripheral smear for further evaluation. Clinical correlation recommended.-```--**Example for Electrolyte Abnormality:**-```-Hypokalemia detected (K+ 3.2 mEq/L). Common causes include diuretic use, GI losses, or-inadequate intake. Recommend potassium repletion and follow-up testing. Moderate-azotemia present, consistent with acute kidney injury or chronic kidney disease.-Clinical correlation with patient history and prior results recommended.-```-------## Critical Values--[If any results meet criteria for critical values]--**Critical Result:** [Test name] = [Value] [Units]-**Reference Range:** [Normal range]-**Significance:** [Life-threatening, requires immediate action]--**Notification:**-- **Called to:** [Name and title of person notified]-- **Date/Time:** [MM/DD/YYYY at HH:MM]-- **Read-back verified:** [Yes]-- **Notified by:** [Lab personnel name]--**Example Critical Values:**-- Glucose <40 mg/dL or >500 mg/dL-- Potassium <2.5 mEq/L or >6.5 mEq/L-- Sodium <120 mEq/L or >160 mEq/L-- Hemoglobin <5.0 g/dL-- Platelets <20 × 10³/μL-- WBC <1.0 × 10³/μL or >50 × 10³/μL-- INR >5.0 (on warfarin)-- Positive blood culture-- Positive CSF Gram stain-------## Quality Control--**Specimen Quality:** [Acceptable / See note]--**QC Notes:**-- [X] Specimen collected in appropriate tube-- [X] Specimen adequately labeled-- [X] Specimen volume sufficient-- [X] No hemolysis, lipemia, or icterus-- [X] Specimen processed within acceptable time--**Issues (if any):**-- [ ] Hemolyzed - may affect [specific tests]-- [ ] Clotted - unable to perform coagulation studies-- [ ] Insufficient volume - limited testing performed-- [ ] Delayed processing - stability concerns for [specific analytes]-------## Methodology--**Test Method:** [Instrumentation and methodology]--Examples:-- **CBC:** Automated cell counter (Sysmex XN-1000)-- **Chemistry:** Spectrophotometry (Beckman AU5800)-- **Glucose:** Enzymatic assay, hexokinase method-- **HbA1c:** HPLC (high-performance liquid chromatography)-- **Troponin:** High-sensitivity immunoassay-- **Drug levels:** Liquid chromatography-mass spectrometry (LC-MS/MS)-------## Special Tests Examples--### Hemoglobin A1c--| Test | Result | Units | Interpretation |-|------|--------|-------|----------------|-| HbA1c | 8.5 | % | Consistent with poorly controlled diabetes |-| HbA1c | 8.5 | % (69 mmol/mol) | Target <7% for most patients |--**Reference Ranges:**-- Non-diabetic: 4.0-5.6%-- Prediabetes: 5.7-6.4%-- Diabetes diagnosis: ≥6.5%-- Treatment target: <7% (individualized)--### Lipid Panel--| Test | Result | Units | Reference Range | Desirable |-|------|--------|-------|----------------|-----------|-| Total Cholesterol | 245 | mg/dL | - | <200 |-| LDL Cholesterol | 160 | mg/dL | - | <100 |-| HDL Cholesterol | 38 | mg/dL | - | >40 (M), >50 (F) |-| Triglycerides | 235 | mg/dL | - | <150 |-| VLDL Cholesterol (calc) | 47 | mg/dL | - | <30 |--### Coagulation Studies--| Test | Result | Units | Reference Range | Flag |-|------|--------|-------|----------------|------|-| PT | 18.5 | seconds | 11.0-13.5 | H |-| INR | 2.8 | ratio | 0.8-1.2 | H |-| PTT | 42 | seconds | 25-35 | H |--**Therapeutic Ranges (INR):**-- Atrial fibrillation: 2.0-3.0-- Mechanical heart valve: 2.5-3.5-- DVT/PE treatment: 2.0-3.0--### Thyroid Function Tests--| Test | Result | Units | Reference Range | Flag |-|------|--------|-------|----------------|------|-| TSH | 8.5 | μIU/mL | 0.4-4.0 | H |-| Free T4 | 0.7 | ng/dL | 0.8-1.8 | L |-| Free T3 | 2.1 | pg/mL | 2.3-4.2 | L |--**Interpretation:** Findings consistent with primary hypothyroidism--### Urinalysis--**Physical Examination:**-- Color: [Yellow / Amber / Other]-- Clarity: [Clear / Cloudy / Turbid]-- Specific Gravity: [1.005-1.030]--**Chemical Examination:**-| Test | Result | Reference |-|------|--------|-----------|-| pH | 6.0 | 5.0-8.0 |-| Protein | Trace | Negative |-| Glucose | Negative | Negative |-| Ketones | Negative | Negative |-| Blood | 2+ | Negative |-| Bilirubin | Negative | Negative |-| Urobilinogen | Normal | Normal |-| Nitrite | Negative | Negative |-| Leukocyte Esterase | Positive | Negative |--**Microscopic Examination (if indicated):**-- WBCs: [number] /hpf (normal <5)-- RBCs: [number] /hpf (normal <3)-- Epithelial cells: [Few/Moderate/Many]-- Bacteria: [None/Few/Moderate/Many]-- Casts: [Type and number]-- Crystals: [Type if present]-------## Microbiology Report Format--### Culture Results--**Specimen Source:** [Blood / Urine / Sputum / Wound / Other]-**Collection:** [Date and time]--**Gram Stain:**-[Results of Gram stain if performed]-Example: "Many Gram-positive cocci in clusters, many WBCs"--**Culture Results:**--**Organism:** [Identified organism]-**Quantity:** [Light / Moderate / Heavy growth] or [CFU count]--**Antimicrobial Susceptibility Testing:**--| Antibiotic | Result | MIC (μg/mL) |-|------------|--------|-------------|-| [Drug name] | S/I/R | [Value] |--Example:-| Antibiotic | Result | MIC |-|------------|--------|-----|-| Ampicillin | R | >16 |-| Ceftriaxone | S | ≤1 |-| Levofloxacin | S | 0.5 |-| Vancomycin | S | 1 |--**Interpretation:** S = Susceptible, I = Intermediate, R = Resistant-------## Molecular/Genetic Testing--**Test:** [Specific test name]-**Method:** [PCR / Sequencing / Array / Other]-**Result:** [Detected / Not detected / Variant identified]--**Interpretation:**-[Clinical significance of result]-------## Reference Laboratory Results--[For send-out tests]--**Test:** [Name]-**Performed by:** [Reference lab name and location]-**Result:** [Value]-**Reference Range:** [Range]-**Method:** [Methodology]-**Reported:** [Date]-------## Laboratory Director Signature--**Medical Director:**-[Name, MD]-[Board Certifications]-[CLIA License Number]--**Electronically signed:** [Date]-------## LOINC Codes (for interoperability)--[LOINC codes for each test when applicable for electronic reporting]--Example:-- Hemoglobin: 718-7-- Glucose: 2345-7-- Creatinine: 2160-0-- TSH: 3016-3--diff --git a/skills/clinical-reports/assets/pathology_report_template.json b/skills/clinical-reports/assets/pathology_report_template.jsonnew file mode 100644index 00000000..0c85cf14--- /dev/null+++ b/skills/clinical-reports/assets/pathology_report_template.json@@ -0,0 +1,36 @@+{+ "schema_version": "2.0",+ "artifact_kind": "pathology_report_scaffold",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_SIGNATURE",+ "safety_notice": "This scaffold cannot examine specimens or author observations, diagnosis, grade, stage, margins, biomarkers, or recommendations. A qualified pathologist must select current protocols and author the report.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "protocol_selection": {+ "cap_protocol_title": null,+ "cap_protocol_version": null,+ "specimen_and_procedure_scope_verified": false,+ "biomarker_protocol_title_and_version": null,+ "staging_system_and_edition": null,+ "local_policy_version": null+ },+ "report_status": null,+ "source_system_record": null,+ "fields": {+ "specimen_information": {"status": "missing", "source_fact_ids": []},+ "clinical_information_as_submitted": {"status": "missing", "source_fact_ids": []},+ "gross_observations_authored_by_pathologist": {"status": "missing", "source_fact_ids": []},+ "microscopic_observations_authored_by_pathologist": {"status": "missing", "source_fact_ids": []},+ "diagnosis_authored_by_pathologist": {"status": "missing", "source_fact_ids": []},+ "synoptic_data_element_response_pairs": {"status": "missing", "source_fact_ids": []},+ "ancillary_and_biomarker_results": {"status": "missing", "source_fact_ids": []},+ "correction_or_addendum_linkage": {"status": "missing", "source_fact_ids": []}+ },+ "provenance_manifest": null,+ "review": {+ "qualified_pathologist_review": "pending",+ "privacy_review": "pending",+ "final_report_created_in_authorized_system": false,+ "signature_present": false+ }+}diff --git a/skills/clinical-reports/assets/pathology_report_template.md b/skills/clinical-reports/assets/pathology_report_template.mddeleted file mode 100644index 0b924dc7..00000000--- a/skills/clinical-reports/assets/pathology_report_template.md+++ /dev/null@@ -1,249 +0,0 @@-# Surgical Pathology Report Template--## Patient and Specimen Information--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age:** [years]-**Sex:** [M/F]--**Accession Number:** [PathologyAccessionNumber]-**Specimen Received:** [Date and time]-**Report Date:** [Date]--**Ordering Physician:** [Name]-**Clinical Service:** [Department]-------## Specimen(s) Submitted--**Specimen A:** [Description of specimen]-Example: "Skin, left forearm, excisional biopsy"--**Specimen B:** [If multiple specimens]-------## Clinical History / Indication--[Relevant clinical information provided by clinician]--Example: "72-year-old woman with enlarging pigmented lesion on left forearm. Clinical concern for melanoma. Previous biopsy showed atypical melanocytic proliferation."-------## Gross Description--**Specimen A labeled "[Specimen label]":**--**Description:**-- Received [fresh/in formalin]-- Consists of [specimen type] measuring [dimensions in cm]-- [External surface description]-- [Cut surface/sectioning description]-- [Lesion description if applicable]-- [Orientation markers if present]-- [Inking for margins]--**Sampling:**-- [How specimen was sectioned]-- [Cassette labeling]-- [Percent of tissue submitted]--**Example:**-```-Specimen A labeled "Skin, left forearm, excisional biopsy":-Received fresh is an oriented ellipse of skin measuring 3.5 x 1.2 x 0.8 cm with a-suture indicating superior. The epidermis contains a 1.1 cm diameter irregularly-pigmented lesion located 1.5 cm from superior, 1.2 cm from inferior, 0.8 cm from-medial, and 1.2 cm from lateral margins. Inking: superior blue, inferior black,-medial green, lateral red, deep yellow. Serially sectioned perpendicular to long-axis into 10 slices. Entirely submitted in cassettes A1-A4.-```-------## Microscopic Description--[Detailed histological findings]--**Architecture:**-[Structural patterns observed]--**Cytology:**-[Cell type, nuclear features, cytoplasm, pleomorphism]--**Special Features:**-[Necrosis, mitoses, invasion, margins]--**Stains/Immunohistochemistry Results:**-[Results of special stains or immunostains]--**Example:**-```-Sections show skin with an asymmetric melanocytic proliferation composed of-epithelioid and spindled melanocytes arranged in irregular nests at the-dermoepidermal junction with extension into the papillary and reticular dermis.-Melanocytes show marked cytologic atypia with nuclear enlargement, hyperchromasia,-and prominent nucleoli. Mitotic activity is present with 4 mitoses per mm².-No ulceration identified. The lesion extends to a Breslow depth of 1.8 mm-(Clark level IV). Margins are free of tumor (closest margin: deep, 0.3 cm).-```-------## Diagnosis--**Specimen A, Skin, left forearm, excisional biopsy:**--**[DIAGNOSIS IN CAPITAL LETTERS]**--**Example Format:**-```-MALIGNANT MELANOMA, SUPERFICIAL SPREADING TYPE--Pathologic features:-- Breslow thickness: 1.8 mm-- Clark level: IV-- Mitotic rate: 4/mm²-- Ulceration: Absent-- Margins: Negative for melanoma (closest margin deep, 0.3 cm)-- Lymphovascular invasion: Not identified-- Perineural invasion: Not identified-- Regression: Absent-- Tumor-infiltrating lymphocytes: Present, non-brisk-- Microsatellites: Absent-```--**For Cancer Specimens - Synoptic Format (CAP Protocol):**--```-SYNOPTIC REPORT FOR [CANCER TYPE]--Procedure: [Type of resection]-Tumor Site: [Specific location]-Tumor Size: [Greatest dimension in cm]-Histologic Type: [WHO classification]-Histologic Grade: [Grading system and result]-Depth of Invasion: [Measured in mm if applicable]-Lymphovascular Invasion: [Present / Not identified]-Perineural Invasion: [Present / Not identified]-Margins:- - [Margin name]: [Negative/Positive, distance if negative]- - [All margins listed]-Regional Lymph Nodes:- - Number examined: [X]- - Number with metastasis: [Y]- - Extranodal extension: [Present/Absent]-Pathologic Stage (AJCC 8th edition): [pTNM]-Additional Findings: [Other relevant findings]-```-------## Ancillary Studies--**Immunohistochemistry:**--| Antibody | Result | Interpretation |-|----------|--------|----------------|-| [Marker name] | [Positive/Negative, pattern] | [Clinical significance] |--**Example:**-| Antibody | Result | Interpretation |-|----------|--------|----------------|-| S100 | Positive, diffuse | Supports melanocytic lineage |-| Melan-A | Positive, diffuse | Supports melanocytic lineage |-| HMB-45 | Positive, patchy | Supports melanoma |-| Ki-67 | 30% | High proliferative index |--**Molecular/Genetic Testing:**-[Results of molecular tests if performed]-- BRAF mutation: [Detected/Not detected]-- [Other relevant tests]-------## Comment--[Additional interpretive information, differential diagnosis, recommendations]--**Example:**-```-The morphologic and immunohistochemical findings are diagnostic of melanoma. The-Breslow thickness of 1.8 mm places this tumor in the T2 category (AJCC 8th edition).-Sentinel lymph node biopsy is recommended for staging. BRAF mutation testing may be-considered for treatment planning. Close clinical follow-up is recommended.-```-------## Signature--**Pathologist:**-[Name, MD]-[Board Certification]-[License number]--**Electronically signed:** [Date and time]--**Gross examination by:** [Name, credentials]-**Microscopic examination by:** [Name, MD]-------## Template Notes for Different Specimen Types--### Breast Biopsy--**Key Elements:**-- Histologic type (invasive ductal, lobular, etc.)-- Nottingham grade (tubule formation, nuclear grade, mitotic count)-- Size of invasive component-- DCIS if present (grade, extent)-- ER/PR/HER2 status-- Margins for all components-- Lymph nodes if present--### Colon Resection--**Key Elements:**-- Tumor site and size-- Histologic type and grade-- Depth of invasion (T stage)-- Lymph nodes (number positive/total examined)-- Margins (proximal, distal, radial/circumferential)-- Lymphovascular and perineural invasion-- Tumor deposits-- MSI/MMR status--### Prostate Biopsy/Resection--**Key Elements:**-- Gleason score (pattern 1 + pattern 2 = total)-- Grade group (1-5)-- Percent involvement per core/specimen-- Extraprostatic extension (if radical prostatectomy)-- Seminal vesicle invasion-- Margins-- Perineural invasion-------## Frozen Section Report (if applicable)--**Frozen Section Diagnosis:**--**Specimen:** [Description]-**Clinical Question:** [Reason for frozen]-**Frozen Section Diagnosis:** [Diagnosis given intraoperatively]-**Time:** [Time reported]-**Pathologist:** [Name]--**Note:** Permanent sections to follow.--**Final Diagnosis:** [State if concordant or discordant with frozen]--diff --git a/skills/clinical-reports/assets/provenance_manifest_template.json b/skills/clinical-reports/assets/provenance_manifest_template.jsonnew file mode 100644index 00000000..65594c48--- /dev/null+++ b/skills/clinical-reports/assets/provenance_manifest_template.json@@ -0,0 +1,17 @@+{+ "schema_version": "2.0",+ "artifact_kind": "provenance_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Record local source locators, field paths, hashes, and verification metadata only. Do not copy PHI or patient narratives into this manifest.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "facts": [],+ "claims": [],+ "review": {+ "source_owner_review": "pending",+ "quality_review": "pending",+ "privacy_review": "pending",+ "release_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/quality_checklist.md b/skills/clinical-reports/assets/quality_checklist.mddeleted file mode 100644index 090139e6..00000000--- a/skills/clinical-reports/assets/quality_checklist.md+++ /dev/null@@ -1,338 +0,0 @@-# Clinical Report Quality Assurance Checklist--## General Quality Standards--### Completeness-- [ ] All required sections present-- [ ] No blank fields or missing information-- [ ] All relevant clinical information included-- [ ] Timeline of events clear and complete-- [ ] All diagnostic tests and results documented-- [ ] All treatments and interventions documented-- [ ] Follow-up plan specified--### Accuracy-- [ ] Patient demographics correct-- [ ] Dates and times accurate-- [ ] Laboratory values with correct units and reference ranges-- [ ] Medication names, doses, and frequencies correct-- [ ] Diagnoses coded correctly (ICD-10)-- [ ] Procedures coded correctly (CPT if applicable)-- [ ] No contradictory information--### Clarity-- [ ] Clear, professional language-- [ ] Medical terminology used appropriately-- [ ] Abbreviations defined or standard only-- [ ] Logical organization and flow-- [ ] Legible (if handwritten)-- [ ] No ambiguous statements-- [ ] Clinical reasoning clearly explained--### Timeliness-- [ ] Documented in real-time or shortly after encounter-- [ ] Discharge summary completed within 24-48 hours-- [ ] Critical results communicated immediately-- [ ] Regulatory reporting deadlines met-------## Case Report Quality Checklist--### CARE Guidelines Compliance-- [ ] Title includes "case report"-- [ ] Keywords provided (2-5 MeSH terms)-- [ ] Structured abstract with all elements-- [ ] Introduction explains novelty-- [ ] Patient information present and de-identified-- [ ] Clinical findings documented-- [ ] Timeline provided (table or figure)-- [ ] Diagnostic assessment detailed-- [ ] Therapeutic interventions described-- [ ] Follow-up and outcomes reported-- [ ] Discussion with literature review-- [ ] Patient perspective included (if possible)-- [ ] Informed consent statement present--### Privacy and Ethics-- [ ] Informed consent obtained and documented-- [ ] All 18 HIPAA identifiers removed-- [ ] Dates removed or approximated-- [ ] Ages reported appropriately (>89 aggregated)-- [ ] Geographic information limited to state-- [ ] Images de-identified or consented-- [ ] IRB approval if applicable--### Scientific Quality-- [ ] Novelty clearly established-- [ ] Literature search comprehensive-- [ ] Differential diagnosis considered-- [ ] Causality addressed-- [ ] Limitations acknowledged-- [ ] Learning points actionable-- [ ] References current and relevant-------## Clinical Trial Report Quality Checklist--### SAE Report Checklist-- [ ] All administrative information complete-- [ ] Subject de-identified (ID number only)-- [ ] Event description detailed-- [ ] MedDRA coding applied-- [ ] Seriousness criteria documented-- [ ] Severity assessed-- [ ] Outcome specified-- [ ] Causality assessment completed with rationale-- [ ] Expectedness determined-- [ ] Action taken with study drug documented-- [ ] Treatment for event described-- [ ] Narrative comprehensive and chronological-- [ ] Critical findings communicated if applicable-- [ ] Regulatory timelines met (7-day, 15-day)--### Clinical Study Report (CSR) Checklist-- [ ] ICH-E3 structure followed-- [ ] Synopsis complete and accurate-- [ ] All sections numbered correctly-- [ ] Abbreviations defined-- [ ] Ethics approvals documented-- [ ] Investigator list complete-- [ ] Study design clearly described-- [ ] Sample size justified-- [ ] Statistical methods specified-- [ ] CONSORT diagram included-- [ ] Baseline demographics table-- [ ] Primary endpoint results-- [ ] All secondary endpoints reported-- [ ] Adverse events summarized-- [ ] Individual SAE narratives included-- [ ] Discussion and conclusions present-- [ ] Appendices complete (protocol, CRFs, etc.)-------## Diagnostic Report Quality Checklist--### Radiology Report-- [ ] Patient demographics complete-- [ ] Clinical indication documented-- [ ] Comparison studies noted-- [ ] Technique described-- [ ] Findings systematic and comprehensive-- [ ] Measurements provided for abnormalities-- [ ] Impression summarizes key findings-- [ ] Answers clinical question-- [ ] Recommendations specified-- [ ] Critical results communicated-- [ ] Structured reporting used if applicable (BI-RADS, Lung-RADS, etc.)-- [ ] Report signed and dated--### Pathology Report-- [ ] Specimen labeled correctly-- [ ] Clinical history provided-- [ ] Gross description detailed-- [ ] Microscopic description comprehensive-- [ ] Diagnosis clear and specific-- [ ] Cancer staging complete (if applicable)-- [ ] Margins documented-- [ ] Lymph nodes quantified-- [ ] Synoptic reporting used for cancer (CAP protocol)-- [ ] Immunohistochemistry results included-- [ ] Molecular results included if applicable-- [ ] Report signed by pathologist--### Laboratory Report-- [ ] Specimen type documented-- [ ] Collection time documented-- [ ] Results with units-- [ ] Reference ranges provided-- [ ] Critical values flagged-- [ ] Critical values communicated-- [ ] Specimen quality noted-- [ ] Methodology specified (if relevant)-- [ ] Interpretation provided (when applicable)-- [ ] LOINC codes assigned (for interoperability)-- [ ] Report signed and dated-------## Patient Documentation Quality Checklist--### SOAP Note-- [ ] Chief complaint documented-- [ ] HPI comprehensive (≥4 elements)-- [ ] Review of systems performed-- [ ] Vital signs recorded-- [ ] Physical exam documented (relevant systems)-- [ ] Assessment with differential diagnosis-- [ ] Plan specific and actionable-- [ ] Return precautions provided-- [ ] Follow-up arranged-- [ ] Documentation supports billing level-- [ ] Signed, dated, and timed--### History and Physical (H&P)-- [ ] Chief complaint-- [ ] Detailed HPI-- [ ] Past medical history-- [ ] Past surgical history-- [ ] Medications reconciled-- [ ] Allergies documented-- [ ] Family history-- [ ] Social history-- [ ] Review of systems (≥10 systems for comprehensive)-- [ ] Complete physical exam (≥8 systems)-- [ ] Laboratory and imaging results-- [ ] Assessment and plan for each problem-- [ ] Code status documented-- [ ] Completed within 24 hours of admission-- [ ] Signed and cosigned (if required)--### Discharge Summary-- [ ] Admission and discharge dates-- [ ] Length of stay-- [ ] Admission diagnosis-- [ ] Discharge diagnoses (ICD-10 coded)-- [ ] Hospital course narrative-- [ ] Procedures performed-- [ ] Discharge medications reconciled-- [ ] New/changed/discontinued medications clearly marked-- [ ] Discharge condition-- [ ] Discharge disposition-- [ ] Follow-up appointments-- [ ] Patient instructions-- [ ] Return precautions-- [ ] Pending tests documented-- [ ] Code status-- [ ] Completed within 24-48 hours-- [ ] Sent to outpatient providers-------## Regulatory Compliance Checklist--### HIPAA Compliance-- [ ] Only minimum necessary PHI disclosed-- [ ] PHI secured and protected-- [ ] Patient authorization obtained (if required)-- [ ] Business associate agreement (if applicable)-- [ ] Audit trail maintained (electronic records)-- [ ] Breach notification procedures followed-- [ ] De-identification performed correctly--### FDA/ICH-GCP Compliance (Clinical Trials)-- [ ] GCP principles followed-- [ ] Informed consent documented-- [ ] IRB approval current-- [ ] Protocol adherence documented-- [ ] Source documentation adequate-- [ ] ALCOA-CCEA principles met-- [ ] 21 CFR Part 11 compliance (electronic records)-- [ ] Safety reporting timelines met-- [ ] Essential documents maintained-------## Writing Quality Checklist--### Grammar and Style-- [ ] Correct spelling-- [ ] Proper grammar-- [ ] Appropriate punctuation-- [ ] Consistent verb tense-- [ ] Professional tone-- [ ] Objective language-- [ ] No personal pronouns in formal reports-- [ ] Active voice used appropriately--### Format and Presentation-- [ ] Consistent formatting-- [ ] Appropriate font and size-- [ ] Adequate margins-- [ ] Page numbers (if applicable)-- [ ] Headers/footers appropriate-- [ ] Tables properly formatted with labels-- [ ] Figures high quality with legends-- [ ] References formatted correctly--### Medical Terminology-- [ ] Terminology accurate-- [ ] Abbreviations standard only-- [ ] Abbreviations defined on first use-- [ ] Units of measurement correct-- [ ] Drug names correct (generic preferred)-- [ ] Anatomical terms correct-- [ ] Coding accurate (ICD-10, CPT, MedDRA)-------## Documentation Integrity Checklist--### Legal and Ethical Standards-- [ ] Facts documented, not opinions-- [ ] Patient quotes when relevant-- [ ] Non-compliance documented objectively-- [ ] No alterations to original record-- [ ] Addendums used for corrections-- [ ] Addendums clearly labeled-- [ ] All entries signed and dated-- [ ] Authorship clear--### Billing and Coding Support-- [ ] Medical necessity documented-- [ ] Complexity of care documented-- [ ] Time documented (if time-based billing)-- [ ] ICD-10 codes appropriate and specific-- [ ] CPT codes match documented services-- [ ] Modifiers appropriate-- [ ] Documentation supports level of service billed-------## Final Review Checklist--Before finalizing any clinical report:--- [ ] Read through entire document-- [ ] Check for completeness-- [ ] Verify all data accuracy-- [ ] Ensure logical flow-- [ ] Check spelling and grammar-- [ ] Verify patient identifiers correct (or removed if de-identified)-- [ ] Ensure compliance with regulations-- [ ] Confirm all required signatures-- [ ] Verify proper distribution-- [ ] Archive copy appropriately-------## Quality Metrics to Track--- [ ] Report turnaround time-- [ ] Amendment/addendum rate-- [ ] Critical value communication time-- [ ] Completeness score-- [ ] Accuracy rate (errors per report)-- [ ] Compliance rate-- [ ] Patient safety events related to documentation-- [ ] Peer review feedback-------**Quality Assurance Reviewer:**--**Name:** ____________________-**Date:** ____________________-**Signature:** ____________________--**Quality Score:** _____ / 100--**Issues Identified:**-1. [Issue and recommendation]-2. [Issue and recommendation]--**Follow-up Required:** [ ] Yes [ ] No--diff --git a/skills/clinical-reports/assets/quality_review_checklist.json b/skills/clinical-reports/assets/quality_review_checklist.jsonnew file mode 100644index 00000000..0c392762--- /dev/null+++ b/skills/clinical-reports/assets/quality_review_checklist.json@@ -0,0 +1,34 @@+{+ "schema_version": "2.0",+ "artifact_kind": "clinical_report_quality_review",+ "review_status": "BLOCKED_NOT_ASSESSED",+ "safety_notice": "A completed checklist records review activity only. It does not prove clinical correctness, compliance, approval, or readiness for signature, filing, publication, or submission.",+ "artifact_reference": null,+ "artifact_kind_reviewed": null,+ "guidance_and_version": [],+ "checks": {+ "allowed_data_class_confirmed": "not_assessed",+ "authorized_purpose_confirmed": "not_assessed",+ "minimum_necessary_confirmed": "not_assessed",+ "draft_warning_present": "not_assessed",+ "required_structure_present": "not_assessed",+ "all_populated_fields_have_verified_fact_ids": "not_assessed",+ "unsupported_claims_absent": "not_assessed",+ "source_conflicts_exposed": "not_assessed",+ "dates_and_chronology_checked": "not_assessed",+ "units_and_precision_checked": "not_assessed",+ "counts_denominators_and_percentages_checked": "not_assessed",+ "missingness_and_suppression_disclosed": "not_assessed",+ "terminology_versions_recorded": "not_assessed",+ "privacy_process_reviewed": "not_assessed",+ "consent_authorization_or_ethics_status_verified_if_applicable": "not_assessed",+ "clinical_specialist_review_completed": "not_assessed",+ "statistical_review_completed_if_applicable": "not_assessed",+ "safety_review_completed_if_applicable": "not_assessed",+ "privacy_legal_review_completed": "not_assessed",+ "regulatory_or_journal_review_completed_if_applicable": "not_assessed"+ },+ "unresolved_items": [],+ "review_record_references": [],+ "release_or_submission_authorized": false+}diff --git a/skills/clinical-reports/assets/radiology_report_template.json b/skills/clinical-reports/assets/radiology_report_template.jsonnew file mode 100644index 00000000..4363940e--- /dev/null+++ b/skills/clinical-reports/assets/radiology_report_template.json@@ -0,0 +1,34 @@+{+ "schema_version": "2.0",+ "artifact_kind": "radiology_report_scaffold",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_SIGNATURE",+ "safety_notice": "This scaffold cannot interpret images or author findings, impressions, urgency, or recommendations. A qualified radiologist must author and sign the report in an authorized clinical system.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "guidance": {+ "base": "ACR Practice Parameter for Communication of Diagnostic Imaging Findings",+ "revision": "2025",+ "modality_specific_source": null,+ "local_policy_version": null+ },+ "report_status": null,+ "source_system_record": null,+ "fields": {+ "examination": {"status": "missing", "source_fact_ids": []},+ "clinical_indication": {"status": "missing", "source_fact_ids": []},+ "technique_and_limitations": {"status": "missing", "source_fact_ids": []},+ "comparison": {"status": "missing", "source_fact_ids": []},+ "findings_authored_by_radiologist": {"status": "missing", "source_fact_ids": []},+ "impression_authored_by_radiologist": {"status": "missing", "source_fact_ids": []},+ "nonroutine_communication_record": {"status": "missing", "source_fact_ids": []},+ "correction_or_addendum_linkage": {"status": "missing", "source_fact_ids": []}+ },+ "provenance_manifest": null,+ "review": {+ "qualified_radiologist_review": "pending",+ "privacy_review": "pending",+ "final_report_created_in_authorized_system": false,+ "signature_present": false+ }+}diff --git a/skills/clinical-reports/assets/radiology_report_template.md b/skills/clinical-reports/assets/radiology_report_template.mddeleted file mode 100644index 9299303a..00000000--- a/skills/clinical-reports/assets/radiology_report_template.md+++ /dev/null@@ -1,318 +0,0 @@-# Radiology Report Template--## Patient Information--**Patient Name:** [Last, First]-**Medical Record Number:** [MRN]-**Date of Birth:** [MM/DD/YYYY]-**Age:** [years]-**Sex:** [M/F]-**Exam Date:** [MM/DD/YYYY]-**Exam Time:** [HH:MM]-**Accession Number:** [Number]--**Referring Physician:** [Name]-**Ordering Service:** [Service/Department]-------## Examination--**Exam Type:** [CT/MRI/X-Ray/Ultrasound/PET/Nuclear Medicine scan]-**Body Part:** [Anatomical region - e.g., Chest, Abdomen and Pelvis, Brain]-**Contrast:** [Yes - IV/Oral/Both | No]-**Laterality:** [Right/Left/Bilateral if applicable]-------## Clinical Indication--[Reason for examination, relevant clinical history, specific question to be answered]--Example: "Rule out pulmonary embolism in patient with acute dyspnea and chest pain. History of recent surgery."-------## Comparison--**Prior Studies:**-[Modality] of [body part] from [date]: [Available/Not available for comparison]--Example: "CT chest without contrast from 6 months prior (01/15/2023) available for comparison"--OR: "No prior imaging available for comparison"-------## Technique--[Detailed description of imaging parameters and protocol]--**For CT:**-```-Multidetector CT of the [body region] was performed [without/with] intravenous-contrast. [Volume] mL of [iodinated contrast agent name] was administered-intravenously. Images were acquired in the [arterial/venous/delayed] phase(s).-Multiplanar reconstructions were performed.--Technical quality: [Adequate / Limited by motion artifact / Limited by patient body habitus]-Radiation dose (DLP): [mGy-cm]-```--**For MRI:**-```-MRI of the [body region] was performed [without/with] intravenous contrast-using the following sequences: [list sequences - T1, T2, FLAIR, DWI, etc.]-[Volume] mL of [gadolinium-based contrast agent] was administered intravenously.-Multiplanar imaging was obtained.--Technical quality: [Adequate / Limited by motion artifact]-```--**For X-Ray:**-```-[Number] views of the [body part] were obtained: [AP/PA/Lateral/Oblique]-Technical quality: [Adequate penetration and positioning / Limited by...]-```--**For Ultrasound:**-```-Real-time ultrasound examination of the [body part] was performed using-[linear/curved] array transducer.-Technical quality: [Adequate / Limited by bowel gas / Limited by body habitus]-```-------## Findings--[Systematic, comprehensive description of findings organized by anatomical region or organ system]--### [Region/Organ 1]--[Detailed findings - size, density/intensity, enhancement pattern, abnormalities]--**Normal statement:** "[Organ] is normal in size, contour, and [attenuation/signal intensity]. No focal lesions."--**Abnormal statement:** "[Description of abnormality with measurements]"--Example:-```-Lungs:-- Bilateral ground-glass opacities are present, predominant in the lower lobes.-- Right lower lobe consolidation measuring 4.5 x 3.2 cm with air bronchograms.-- No pleural effusion or pneumothorax.-- Airways are patent bilaterally.-```--### [Region/Organ 2]--[Findings]--### [Additional Regions as Applicable]--**For Chest CT:**-- Lungs-- Airways-- Pleura-- Mediastinum and Hila-- Heart and Great Vessels-- Chest Wall-- Upper Abdomen (if included)-- Bones--**For Abdomen/Pelvis CT:**-- Liver-- Gallbladder-- Spleen-- Pancreas-- Kidneys and Adrenals-- Gastrointestinal Tract-- Peritoneum and Mesentery-- Retroperitoneum-- Bladder-- Pelvic Organs-- Vasculature-- Lymph Nodes-- Bones-- Soft Tissues--**For Brain MRI:**-- Brain Parenchyma-- Ventricles and Cisterns-- Extra-axial Spaces-- Vascular Structures-- Orbits (if included)-- Skull Base and Calvarium--### Measurements (if applicable)--| Structure | Measurement | Normal Range |-|-----------|-------------|--------------|-| [Lesion/mass] | [Size in cm, 3 dimensions] | - |-| [Organ] | [Size] | [Normal size] |-------## Impression--[Concise summary of key findings with clinical interpretation]--**Format as numbered list in order of clinical importance:**--1. **[Most important finding]** - [Diagnosis or differential, clinical significance]- - [Additional details, comparison to prior if applicable]- - [Recommendation if any]--2. **[Second finding]** - [Interpretation]--3. **[Additional findings]**--**Alternative format for normal study:**-```-No acute intrathoracic abnormality.-Specifically, no evidence of pulmonary embolism.-```--**Recommendations (if applicable):**-- [Further imaging, follow-up imaging interval, clinical correlation, biopsy, etc.]-- [Timeframe for follow-up]--Example:-```-Recommend follow-up CT in 3 months to assess for interval change.-Clinical correlation with laboratory values recommended.-Consider PET/CT for further characterization if clinically indicated.-```-------## Communication of Critical Results--[If critical/urgent finding]--**Critical finding:** [Description]--**Communicated to:** [Name and role of person notified]-**Date/Time:** [MM/DD/YYYY at HH:MM]-**Method:** [Phone call / Page / In person]-**Read back verified:** [Yes]-------## Structured Reporting (if applicable)--### For Lung Nodules (Lung-RADS):-**Category:** [Lung-RADS 0/1/2/3/4A/4B/4X]-**Recommendation:** [Per Lung-RADS guidelines]--### For Breast Imaging (BI-RADS):-**Category:** [BI-RADS 0/1/2/3/4/5/6]-**Recommendation:** [Per BI-RADS guidelines]--### For Liver Lesions (LI-RADS):-**Category:** [LI-RADS 1/2/3/4/5/M/TIV]-**Features:** [Arterial phase hyperenhancement, washout, capsule, size, growth]--### For Prostate (PI-RADS):-**Score:** [PI-RADS 1/2/3/4/5]-**Location:** [Peripheral zone / Transition zone]-------## Signature--**Interpreted by:**-[Radiologist name, MD]-[Board certification]-[NPI number if required]--**Electronically signed:** [Date and time]--**Dictated:** [Date and time]-**Transcribed:** [Date and time]-**Signed:** [Date and time]-------## Template Notes--### General Principles--**Be systematic:**-- Use consistent order (head to toe, outside to inside)-- Don't skip regions even if normal-- Include pertinent negatives--**Be specific:**-- Provide measurements (size in 3 dimensions for masses)-- Describe location precisely-- Use standardized terminology (RadLex)-- Quantify when possible--**Be clear:**-- Avoid ambiguous language-- Make impression stand-alone-- Answer the clinical question directly-- State what IS present, not just what isn't--**Communication:**-- Critical findings require immediate verbal notification-- Document communication-- Provide specific recommendations-- Suggest next steps when appropriate--### Measurement Guidelines--**Lesions/Masses:**-- Three dimensions: [length x width x height in cm]-- Use consistent measurement method for follow-up--**Lymph Nodes:**-- Short axis diameter in cm-- Note morphology (round vs. oval)--**Organ Sizes:**-- Use established normal ranges-- Age and sex appropriate--### Comparison Statements--**Improved:**-"Interval decrease in size of right upper lobe mass from 3.5 cm to 2.1 cm."--**Stable:**-"Unchanged 8 mm left lower lobe nodule, stable for 2 years."--**Worsened:**-"Interval increase in bilateral pleural effusions, now moderate on the right."--**New finding:**-"New 1.5 cm right adrenal nodule, not present on prior CT."--### Differential Diagnosis Language--**Definite:** "Consistent with..."-**Probable:** "Most likely represents..." or "Favors..."-**Possible:** "Suggestive of..." or "Differential diagnosis includes..."-**Uncertain:** "Cannot exclude..." or "Consider..."--### Recommendations--**Follow-up imaging:**-- Specify modality, timing, and what to assess-- "Recommend CT chest in 6-12 months to assess stability"--**Further characterization:**-- "Consider MRI for further characterization"-- "Ultrasound correlation recommended"--**Clinical correlation:**-- "Clinical correlation with tumor markers recommended"-- "Correlate with patient symptoms and physical examination"--**Biopsy/Intervention:**-- "Consider biopsy for definitive diagnosis"-- "Amenable to image-guided biopsy if clinically indicated"--diff --git a/skills/clinical-reports/assets/research_summary_template.json b/skills/clinical-reports/assets/research_summary_template.jsonnew file mode 100644index 00000000..a41f6dd4--- /dev/null+++ b/skills/clinical-reports/assets/research_summary_template.json@@ -0,0 +1,36 @@+{+ "schema_version": "2.0",+ "artifact_kind": "aggregate_clinical_research_summary_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_DECISION_MAKING",+ "safety_notice": "Summarize only verified aggregate research outputs. Do not generate patient-level content, clinical advice, causal conclusions, or unverified interpretations.",+ "data_classification": "aggregate",+ "authorized_purpose": null,+ "authorization_verified": false,+ "reporting_route": {+ "study_design": null,+ "base_reporting_guideline_and_version": null,+ "applicable_extensions": [],+ "protocol_reference": null,+ "sap_reference": null,+ "registry_reference": null+ },+ "sections": {+ "scope_and_population": {"status": "missing", "source_fact_ids": []},+ "methods": {"status": "missing", "source_fact_ids": []},+ "analysis_set_and_estimand": {"status": "missing", "source_fact_ids": []},+ "results": {"status": "missing", "source_fact_ids": []},+ "missingness_and_exclusions": {"status": "missing", "source_fact_ids": []},+ "safety_summary_if_applicable": {"status": "missing", "source_fact_ids": []},+ "limitations": {"status": "missing", "source_fact_ids": []},+ "interpretation_by_accountable_authors": {"status": "missing", "source_fact_ids": []},+ "funding_and_conflicts": {"status": "missing", "source_fact_ids": []}+ },+ "provenance_manifest": null,+ "review": {+ "accountable_author_review": "pending",+ "statistical_review": "pending",+ "clinical_review": "pending",+ "privacy_review": "pending",+ "publication_authorized": false+ }+}diff --git a/skills/clinical-reports/assets/soap_note_template.md b/skills/clinical-reports/assets/soap_note_template.mddeleted file mode 100644index af761743..00000000--- a/skills/clinical-reports/assets/soap_note_template.md+++ /dev/null@@ -1,253 +0,0 @@-# SOAP Note Template--## Patient Information--**Patient Name:** [Last, First] or [Patient ID for teaching/research contexts]-**Date of Birth:** [MM/DD/YYYY]-**Medical Record Number:** [MRN]-**Date of Visit:** [MM/DD/YYYY]-**Time:** [HH:MM]-**Location:** [Clinic, Hospital Floor, ED, etc.]-**Provider:** [Your name and credentials]-------## S - SUBJECTIVE--### Chief Complaint (CC)-"[Patient's chief complaint in their own words]"--### History of Present Illness (HPI)--[Patient Name] is a [age]-year-old [sex] with a history of [relevant PMHx] who presents with [chief complaint].--**Onset:** [When did symptoms start? Sudden or gradual?]--**Location:** [Where is the symptom? Does it radiate?]--**Duration:** [How long has this been going on?]--**Characterization:** [Describe the quality - sharp, dull, burning, etc.]--**Aggravating factors:** [What makes it worse?]--**Relieving factors:** [What makes it better?]--**Timing:** [Constant or intermittent? Frequency?]--**Severity:** [How bad is it? 0-10 scale if pain]--**Associated symptoms:** [Other symptoms occurring with this?]--**Prior treatment and response:** [What has patient tried? Did it help?]--**Functional impact:** [How does this affect daily activities?]--**Review of Systems (pertinent to visit):**-- Constitutional: [fever, chills, weight change, fatigue, night sweats]-- [Other relevant systems based on chief complaint]-- **Pertinent negatives:** [Important symptoms patient denies]-------## O - OBJECTIVE--### Vital Signs-- Temperature: \_\_\_\_\_ °F (oral/axillary/tympanic)-- Blood Pressure: \_\_\_\_\_/\_\_\_\_\_ mmHg-- Heart Rate: \_\_\_\_\_ bpm-- Respiratory Rate: \_\_\_\_\_ breaths/min-- Oxygen Saturation: \_\_\_\_\_% on [room air / O2 at \_\_ L/min]-- Height: \_\_\_\_\_ cm / inches-- Weight: \_\_\_\_\_ kg / lbs-- BMI: \_\_\_\_\_ kg/m²-- Pain Score: \_\_\_/10--### Physical Examination--**General Appearance:**-[Well-appearing, no distress / ill-appearing / mild/moderate/severe distress]--**HEENT:**-- Head: [Normocephalic, atraumatic]-- Eyes: [PERRLA, EOMI, conjunctiva, sclera]-- Ears: [TMs clear bilaterally, canals patent]-- Nose: [Nares patent, no discharge]-- Throat: [Oropharynx clear, no erythema or exudate, mucosa moist]--**Neck:**-[Supple, no lymphadenopathy, no thyromegaly, no JVD, carotids 2+ without bruits]--**Cardiovascular:**-[RRR, normal S1/S2, no murmurs/rubs/gallops] OR [describe abnormalities]-[Peripheral pulses: radial 2+/2+ bilaterally, dorsalis pedis 2+/2+ bilaterally]--**Pulmonary:**-[Lungs clear to auscultation bilaterally, no wheezes/rales/rhonchi, normal work of breathing] OR [describe abnormalities]--**Abdomen:**-[Soft, non-tender, non-distended, normoactive bowel sounds, no masses, no hepatosplenomegaly, no rebound/guarding]--**Extremities:**-[No edema, no cyanosis, no clubbing, full range of motion, no joint swelling or tenderness]--**Skin:**-[Warm and dry, no rashes, no lesions, normal turgor, capillary refill <2 sec]--**Neurological:**-- Mental status: [Alert and oriented to person, place, time]-- Cranial nerves: [II-XII intact] OR [specify abnormalities]-- Motor: [5/5 strength all extremities, normal tone]-- Sensory: [Intact to light touch and pinprick]-- Reflexes: [2+ symmetric, downgoing Babinski]-- Gait: [Normal / not assessed]-- Coordination: [Finger-to-nose intact, rapid alternating movements normal]--**Psychiatric:**-[Normal mood and affect, thought process logical and goal-directed, no SI/HI]--### Laboratory Results (if applicable)-| Test | Result | Reference Range | Flag |-|------|--------|----------------|------|-| [Test name] | [Value] [unit] | [Range] | [H/L/-] |--### Imaging Results (if applicable)-[Modality] ([Date]): [Key findings]--### Other Diagnostic Tests-[ECG, etc.]: [Results]-------## A - ASSESSMENT--### Problem List with Assessment--**1. [Primary Problem/Diagnosis] ([ICD-10 code])**- - [Brief assessment: severity, stability, progress toward goals]- - [Relevant exam and lab findings supporting diagnosis]- - [Differential diagnosis if uncertain]--**2. [Secondary Problem/Diagnosis] ([ICD-10 code])**- - [Assessment]--**3. [Additional problems as needed]**--### Overall Assessment-[Summary statement about patient's overall status, response to treatment, trajectory]-------## P - PLAN--### Problem-Based Plan--**1. [Primary Problem]**--**Diagnostics:**-- [Further tests, labs, imaging, consultations needed]-- [Rationale for testing]--**Therapeutics:**-- [Medications:]- - [Drug name] [dose] [route] [frequency] x [duration]- - Indication: [Why prescribed]-- [Procedures or interventions]-- [Non-pharmacological interventions]--**Monitoring:**-- [What to monitor, how often]-- [Parameters for follow-up labs or imaging]--**Education:**-- [Topics discussed with patient]-- [Patient understanding verified]-- [Written materials provided]--**Follow-up:**-- [When and where]-- [Specific goals for follow-up visit]--**Return Precautions:**-- [When to seek urgent/emergency care]-- [Warning signs discussed]--**2. [Secondary Problem]**--**Diagnostics:**-- [Tests or studies]--**Therapeutics:**-- [Medications or interventions]--**Monitoring:**-- [Parameters to follow]--**3. [Additional Problems]**-[Plan for each problem]--### Overall Plan Summary-- Total new prescriptions: [number]-- Referrals placed: [specialty, reason]-- Follow-up appointment: [date/timeframe and with whom]-- Patient verbalized understanding of plan: [Yes/No, questions answered]-- Time spent: [Total time and time spent on counseling/coordination if relevant for billing]-------## Billing Information (if applicable)--**CPT Code:** [E/M code - 99201-99215 for office visits]--**Level of Service Justification:**-- History: [Problem focused / Expanded / Detailed / Comprehensive]-- Exam: [Problem focused / Expanded / Detailed / Comprehensive]-- Medical Decision Making: [Straightforward / Low / Moderate / High complexity]- - Number of diagnoses/management options: [Minimal / Limited / Multiple / Extensive]- - Amount of data to review: [Minimal / Limited / Moderate / Extensive]- - Risk: [Minimal / Low / Moderate / High]--[OR if time-based:]-- Total time: [minutes]-- Time spent on counseling/coordination: [minutes] (>50% of visit)-------## Signature--[Provider name, credentials]-[Electronic signature or handwritten signature]-[Date and time of documentation]-------## Notes for Using This Template--**Best Practices:**-- Document as soon as possible after encounter-- Be specific and objective in observations-- Avoid copy-forward errors-- Review and update problem list-- Sign and date all entries-- Use standard abbreviations only--**Billing Considerations:**-- Document medical necessity-- Match documentation level to billing code-- For time-based billing, document total time and counseling time-- Include relevant history, exam, and MDM elements--**Legal Considerations:**-- Document facts, not opinions-- Quote patient when relevant-- Document non-compliance objectively-- Never alter records - use addendum for corrections-- Ensure legibility--**Customization:**-- Adapt level of detail to setting (quick outpatient visit vs. complex hospital consultation)-- Include or exclude sections as relevant-- Follow institutional templates if required-- Use problem-oriented approach consistently--diff --git a/skills/clinical-reports/assets/terminology_manifest_template.json b/skills/clinical-reports/assets/terminology_manifest_template.jsonnew file mode 100644index 00000000..19545318--- /dev/null+++ b/skills/clinical-reports/assets/terminology_manifest_template.json@@ -0,0 +1,11 @@+{+ "schema_version": "2.0",+ "artifact_kind": "terminology_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Record only codes already selected and verified by qualified reviewers. Syntax or local-dictionary matching does not validate clinical meaning.",+ "data_classification": null,+ "authorized_purpose": null,+ "authorization_verified": false,+ "provenance_manifest": null,+ "entries": []+}diff --git a/skills/clinical-reports/assets/trial_protocol_reporting_checklist.json b/skills/clinical-reports/assets/trial_protocol_reporting_checklist.jsonnew file mode 100644index 00000000..84c6e610--- /dev/null+++ b/skills/clinical-reports/assets/trial_protocol_reporting_checklist.json@@ -0,0 +1,70 @@+{+ "schema_version": "2.0",+ "artifact_kind": "randomized_trial_protocol_reporting_manifest",+ "draft_status": "BLOCKED_INCOMPLETE_REPORTING_CHECKLIST_NOT_A_PROTOCOL_OR_ETHICS_APPROVAL",+ "safety_notice": "This manifest tracks SPIRIT reporting-item coverage only. It does not design, approve, register, conduct, amend, or submit a trial protocol.",+ "data_classification": "aggregate",+ "authorized_purpose": null,+ "authorization_verified": false,+ "guidance": {+ "base": "SPIRIT 2025",+ "item_count": 34,+ "statement_and_explanation_checked": false,+ "applicable_extensions": [],+ "applicable_extensions_reviewed": false,+ "extension_conflicts_resolved_by_methodologist": false+ },+ "protocol_metadata": {+ "authorized_protocol_reference": null,+ "protocol_version": null,+ "registry_reference": null,+ "ethics_record_reference": null+ },+ "checklist_items": {+ "S01": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S02": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S03": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S04": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S05": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S06": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S07": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S08": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S09": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S10": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S11": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S12": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S13": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S14": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S15": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S16": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S17": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S18": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S19": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S20": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S21": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S22": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S23": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S24": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S25": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S26": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S27": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S28": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S29": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S30": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S31": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S32": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S33": {"status": "missing", "source_fact_ids": [], "official_item_locator": null},+ "S34": {"status": "missing", "source_fact_ids": [], "official_item_locator": null}+ },+ "not_applicable_rationales": {},+ "participant_timeline_source_fact_ids": [],+ "provenance_manifest": null,+ "review": {+ "investigator_sponsor_review": "pending",+ "methodologist_review": "pending",+ "statistical_review": "pending",+ "safety_review": "pending",+ "ethics_regulatory_review": "pending",+ "protocol_approved": false+ }+}diff --git a/skills/clinical-reports/references/README.md b/skills/clinical-reports/references/README.mdindex 865798f8..fa5f1f43 100644--- a/skills/clinical-reports/references/README.md+++ b/skills/clinical-reports/references/README.md@@ -1,236 +1,34 @@-# Clinical Reports Skill+# Clinical Reports References-## Overview+These references support local, deterministic drafting and review. They are not clinical, legal, regulatory, privacy, publication, or accreditation advice and do not establish compliance.-Comprehensive skill for writing clinical reports including case reports, diagnostic reports, clinical trial reports, and patient documentation. Provides full support with templates, regulatory compliance, and validation tools.+## Safety boundary-## What's Included+- Use only synthetic, de-identified, or aggregate data.+- Populate drafts only from verified authorized source facts.+- Do not diagnose, treat, dose, triage, interpret raw observations, fabricate results, sign, file, or submit.+- Do not use external models, APIs, image tools, or cross-skill calls.+- Keep every output marked as a draft requiring qualified review.-### 📋 Four Major Report Types+## File map-1. **Clinical Case Reports** - CARE-compliant case reports for medical journal publication-2. **Diagnostic Reports** - Radiology (ACR), pathology (CAP), and laboratory reports-3. **Clinical Trial Reports** - SAE reports, Clinical Study Reports (ICH-E3), DSMB reports-4. **Patient Documentation** - SOAP notes, H&P, discharge summaries, consultation notes+| File | Use |+|---|---|+| `report_type_routing.md` | Select the artifact and exact source family before drafting |+| `case_report_guidelines.md` | CARE case-report structure, consent, and publication safeguards |+| `diagnostic_reports_standards.md` | Radiology, pathology, and laboratory field boundaries |+| `clinical_trial_reporting.md` | CONSORT 2025, SPIRIT 2025, ICH E3, and ICH E6(R3) |+| `safety_reporting.md` | ICH E2 and FDA safety-reporting distinctions |+| `privacy_and_deidentification.md` | HHS de-identification methods and process limits |+| `medical_terminology.md` | Versioned terminology and syntax-versus-semantics limits |+| `data_presentation.md` | Aggregate tables, denominators, units, dates, and missingness |+| `professional_review.md` | Ethics, accountability, review, and sign-off |+| `sources.md` | Dated official-source ledger |-### 📚 Reference Files (8 comprehensive guides)+## Source handling-- `case_report_guidelines.md` - CARE guidelines, de-identification, journal requirements-- `diagnostic_reports_standards.md` - ACR, CAP, CLSI standards, structured reporting systems-- `clinical_trial_reporting.md` - ICH-E3, CONSORT, SAE reporting, MedDRA coding-- `patient_documentation.md` - SOAP notes, H&P, discharge summary standards-- `regulatory_compliance.md` - HIPAA, 21 CFR Part 11, ICH-GCP, FDA regulations-- `medical_terminology.md` - SNOMED-CT, LOINC, ICD-10, CPT codes-- `data_presentation.md` - Clinical tables, figures, Kaplan-Meier curves-- `peer_review_standards.md` - Review criteria for clinical manuscripts+`sources.md` records primary or official sources checked on 2026-07-23. Requirements, regional adoption, controlled terminologies, and professional standards can change. Before real-world use, a qualified reviewer must verify the current official source, applicable jurisdiction, institution, sponsor procedure, protocol, statistical analysis plan, and target-journal instructions.-### 📄 Templates (12 professional templates)--- `case_report_template.md` - Structured case report following CARE guidelines-- `soap_note_template.md` - SOAP progress note format-- `history_physical_template.md` - Complete H&P examination template-- `discharge_summary_template.md` - Hospital discharge documentation-- `consult_note_template.md` - Specialist consultation format-- `radiology_report_template.md` - Imaging report with structured reporting-- `pathology_report_template.md` - Surgical pathology with CAP synoptic elements-- `lab_report_template.md` - Clinical laboratory test results-- `clinical_trial_sae_template.md` - Serious adverse event report form-- `clinical_trial_csr_template.md` - Clinical study report outline (ICH-E3)-- `quality_checklist.md` - Quality assurance for all report types-- `hipaa_compliance_checklist.md` - Privacy and de-identification verification--### 🔧 Validation Scripts (8 automation tools)--- `validate_case_report.py` - Check CARE guideline compliance and completeness-- `check_deidentification.py` - Scan for 18 HIPAA identifiers in reports-- `validate_trial_report.py` - Verify ICH-E3 structure and required elements-- `format_adverse_events.py` - Generate AE summary tables from CSV data-- `generate_report_template.py` - Interactive template selection and generation-- `extract_clinical_data.py` - Parse and extract structured clinical data-- `compliance_checker.py` - Verify regulatory compliance requirements-- `terminology_validator.py` - Validate medical terminology and prohibited abbreviations--## Quick Start--### Generate a Template--```bash-cd .claude/skills/clinical-reports/scripts-python generate_report_template.py--# Or specify type directly-python generate_report_template.py --type case_report --output my_case_report.md-```--### Validate a Case Report--```bash-python validate_case_report.py my_case_report.md-```--### Check De-identification--```bash-python check_deidentification.py my_case_report.md-```--### Validate Clinical Trial Report--```bash-python validate_trial_report.py my_csr.md-```--## Key Features--### CARE Guidelines Compliance-- Complete CARE checklist coverage-- De-identification verification-- Informed consent documentation-- Timeline creation assistance-- Literature review integration--### Regulatory Compliance-- **HIPAA** - Privacy protection, 18 identifier removal, Safe Harbor method-- **FDA** - 21 CFR Parts 11, 50, 56, 312 compliance-- **ICH-GCP** - Good Clinical Practice standards-- **ALCOA-CCEA** - Data integrity principles--### Professional Standards-- **ACR** - American College of Radiology reporting standards-- **CAP** - College of American Pathologists synoptic reporting-- **CLSI** - Clinical Laboratory Standards Institute-- **CONSORT** - Clinical trial reporting-- **ICH-E3** - Clinical study report structure--### Medical Coding Systems-- **ICD-10-CM** - Diagnosis coding-- **CPT** - Procedure coding-- **SNOMED-CT** - Clinical terminology-- **LOINC** - Laboratory observation codes-- **MedDRA** - Medical dictionary for regulatory activities--## Common Use Cases--### 1. Publishing a Clinical Case Report--```-> Create a clinical case report for a 65-year-old patient with atypical- presentation of acute appendicitis--> Check this case report for HIPAA compliance-> Validate against CARE guidelines-```--### 2. Writing Diagnostic Reports--```-> Generate a radiology report template for chest CT-> Create a pathology report for colon resection specimen with adenocarcinoma-> Write a laboratory report for complete blood count-```--### 3. Clinical Trial Documentation--```-> Write a serious adverse event report for hospitalization due to pneumonia-> Create a clinical study report outline for phase 3 diabetes trial-> Generate adverse events summary table from trial data-```--### 4. Patient Clinical Notes--```-> Create a SOAP note for follow-up visit-> Generate an H&P for patient admitted with chest pain-> Write a discharge summary for heart failure hospitalization-> Create a cardiology consultation note-```--## Workflow Examples--### Case Report Workflow--1. **Obtain informed consent** from patient-2. **Generate template**: `python generate_report_template.py --type case_report`-3. **Write case report** following CARE structure-4. **Validate compliance**: `python validate_case_report.py case_report.md`-5. **Check de-identification**: `python check_deidentification.py case_report.md`-6. **Submit to journal** with CARE checklist--### Clinical Trial SAE Workflow--1. **Generate SAE template**: `python generate_report_template.py --type sae`-2. **Complete SAE form** within 24 hours of event-3. **Assess causality** using WHO-UMC or Naranjo criteria-4. **Validate completeness**: `python validate_trial_report.py sae_report.md`-5. **Submit to sponsor** within regulatory timelines (7 or 15 days)-6. **Notify IRB** per institutional policy--## Best Practices--### Privacy and Ethics-✓ Always obtain informed consent for case reports-✓ Remove all 18 HIPAA identifiers before publication-✓ Use de-identification validation scripts-✓ Document consent in manuscript-✓ Consider re-identification risk for rare conditions--### Clinical Quality-✓ Use professional medical terminology-✓ Follow structured reporting templates-✓ Include all required elements-✓ Document chronology clearly-✓ Support diagnoses with evidence--### Regulatory Compliance-✓ Meet SAE reporting timelines (7-day, 15-day)-✓ Follow ICH-E3 structure for CSRs-✓ Maintain ALCOA-CCEA data integrity-✓ Document protocol adherence-✓ Use MedDRA coding for adverse events--### Documentation Standards-✓ Sign and date all clinical notes-✓ Document medical necessity-✓ Use standard abbreviations only-✓ Avoid prohibited abbreviations (JCAHO "Do Not Use" list)-✓ Maintain legibility and completeness--## Integration--The clinical-reports skill integrates seamlessly with:--- **scientific-writing** - For clear, professional medical writing-- **peer-review** - For quality assessment of case reports-- **citation-management** - For literature references in case reports-- **research-grants** - For clinical trial protocol development--## Resources--### External Standards-- CARE Guidelines: https://www.care-statement.org/-- ICH-E3 Guideline: https://database.ich.org/sites/default/files/E3_Guideline.pdf-- CONSORT Statement: http://www.consort-statement.org/-- HIPAA: https://www.hhs.gov/hipaa/-- ACR Practice Parameters: https://www.acr.org/Clinical-Resources/Practice-Parameters-and-Technical-Standards-- CAP Cancer Protocols: https://www.cap.org/protocols-and-guidelines--### Professional Organizations-- American Medical Association (AMA)-- American College of Radiology (ACR)-- College of American Pathologists (CAP)-- Clinical Laboratory Standards Institute (CLSI)-- International Council for Harmonisation (ICH)--## Support--For issues or questions about the clinical-reports skill:-1. Check the comprehensive reference files-2. Review templates for examples-3. Run validation scripts to identify issues-4. Consult the SKILL.md for detailed guidance--## License--Part of the Claude Scientific Writer project. See main LICENSE file.+## Terminology+“Required” in these references means required by the cited source within its stated scope, not universally required. “Complete” means structurally present in a manifest, not clinically correct. Script results never authorize use, release, signature, filing, or submission.diff --git a/skills/clinical-reports/references/case_report_guidelines.md b/skills/clinical-reports/references/case_report_guidelines.mdindex a8091b62..c9a0ba30 100644--- a/skills/clinical-reports/references/case_report_guidelines.md+++ b/skills/clinical-reports/references/case_report_guidelines.md@@ -1,570 +1,72 @@-# Clinical Case Report Guidelines+# CARE Case-Report Drafting-## CARE Guidelines (CAse REport)+## Current source-The CARE guidelines provide a framework for transparent and complete reporting of clinical cases. The CARE checklist ensures that case reports contain all necessary information for readers to assess the validity and applicability of the findings.+The official CARE site continues to identify the **2013 CARE Checklist** as the core checklist. The 2017 explanation and elaboration supplies rationale and examples. CARE is reporting guidance for case reports; it does not authorize record access, establish consent, prove de-identification, or replace journal instructions.-### CARE Checklist Items+## Thirteen checklist headings-#### Title (1 item)+Preserve the official structure:-**1. Title**-- Include the words "case report" or "case study" in the title-- Indicate the area of focus-- Be specific about the condition or intervention-- Examples:- - Good: "Delayed Presentation of Aortic Dissection Mimicking Pneumonia: A Case Report"- - Poor: "An Interesting Case"+1. title;+2. key words;+3. abstract;+4. introduction;+5. patient information;+6. clinical findings;+7. timeline;+8. diagnostic assessment;+9. therapeutic intervention;+10. follow-up and outcomes;+11. discussion;+12. patient perspective;+13. informed consent.-#### Keywords (1 item)+Use the official checklist and explanation for subitems. The local validator checks only that all headings have an allowed status and verified fact references; it does not judge clinical accuracy or CARE adherence.-**2. Keywords**-- Provide 2-5 keywords-- Use MeSH (Medical Subject Headings) terms when possible-- Facilitate indexing and search+## Safe use-ability-- Examples: "aortic dissection," "atypical presentation," "diagnostic imaging"+- Begin with `assets/case_report_template.json`.+- Use de-identified source facts, not copied charts or free-text records.+- Keep direct identifiers and contact details out of the draft manifest.+- Represent chronology with relative study/case offsets when authorized and scientifically adequate; do not alter chronology to disguise conflicts.+- Preserve diagnostic and therapeutic statements as attributed facts from authorized records. Do not independently diagnose, rationalize treatment, or recommend care.+- Attribute the patient perspective to an authorized source; never invent a quote.+- Keep uncertainty, missing follow-up, adverse outcomes, and limitations visible.+- Do not claim novelty until an accountable author has reviewed the literature.+- Avoid causal or general treatment claims from a single case.-#### Abstract (4 items)+## Consent and privacy-**3a. Introduction**-- What is unique about this case?-- Why is it worth reporting?-- 1-2 sentences+CARE includes informed consent as an item, but a template cannot obtain or verify consent.-**3b. Patient's main concerns and important clinical findings**-- Primary symptoms-- Key physical examination or diagnostic findings+- Record only a consent status verified by the responsible human reviewer.+- Do not create a stock statement asserting that consent was obtained.+- Consent for publication and HIPAA de-identification are separate questions.+- De-identification does not necessarily remove all re-identification risk, particularly for rare conditions, small communities, images, unusual timelines, or distinctive combinations.+- Journal, institution, law, ethics-board policy, and circumstances involving minors, deceased persons, or persons unable to consent require qualified review.-**3c. Main diagnoses, therapeutics interventions, and outcomes**-- Final diagnosis-- Key treatments-- Clinical outcome+## Fail-closed statuses-**3d. Conclusion**-- What are the main takeaway messages?-- Clinical implications+Each CARE item uses one of:-**Abstract Length:** Typically 150-250 words, structured or unstructured depending on journal+- `verified_present` — supported by one or more verified source-fact IDs;+- `not_applicable_with_rationale` — a qualified reviewer supplied a recorded rationale;+- `missing` — blocks structural readiness;+- `conflict` — source records disagree and human resolution is required.-#### Introduction (2 items)+The consent item cannot be waived by the script. A missing or unresolved consent status blocks publication handoff.-**4. Background**-- Brief background on the medical condition-- Epidemiology if relevant-- Current understanding and management-- 2-4 paragraphs+## Qualified review-**5. Why is this case novel?**-- What makes this case worth reporting?-- Unique presentation, diagnosis, or outcome-- Contribution to medical knowledge-- Literature gap being addressed+Before any journal handoff, accountable authors and the appropriate clinical, privacy/legal, and institutional reviewers must verify:-#### Patient Information (4 items)--**6. Patient demographics and other information**-- Age, sex, race/ethnicity (if relevant)-- Occupation (if relevant to case)-- Living situation (if relevant)-- Example: "A 45-year-old African American woman"--**7. Main symptoms of patient**-- Chief complaint-- Presenting symptoms-- Duration and characteristics-- Example: "Presented with sudden onset severe chest pain radiating to the back, associated with dyspnea"--**8. Medical, family, and psychosocial history**-- Relevant past medical history-- Medications and allergies-- Family history of relevant conditions-- Social history (smoking, alcohol, drugs, occupation)-- Prior treatments or interventions--**9. Relevant past interventions and outcomes**-- Prior hospitalizations-- Previous treatments for same or related conditions-- Outcomes of prior interventions--#### Clinical Findings (1 item)--**10. Describe the relevant physical examination findings**-- Vital signs-- Physical examination by system-- Pertinent positive findings-- Important negative findings-- Example:- - "Vital signs: BP 180/110 mmHg (right arm), 140/80 mmHg (left arm), HR 105 bpm, RR 24/min- - Cardiovascular: Diastolic murmur heard over left sternal border, diminished pulse in left radial artery- - Pulmonary: Decreased breath sounds in left lung base"--#### Timeline (1 item)--**11. Describe important dates and times in this case**-- Chronological summary of events-- Onset of symptoms-- Healthcare encounters-- Diagnostic procedures-- Interventions-- Outcomes and follow-up--**Timeline Format Options:**-1. **Table format:**--| Date | Event |-|------|-------|-| Day 0 | Onset of chest pain and dyspnea |-| Day 0, 2 hours | Presented to emergency department |-| Day 0, 4 hours | CT angiography performed, diagnosed with aortic dissection |-| Day 0, 6 hours | Emergency surgery performed |-| Day 7 | Discharged home in stable condition |-| Month 3 | Follow-up imaging shows complete healing |--2. **Figure/graphic timeline**-3. **Narrative timeline embedded in text**--#### Diagnostic Assessment (5 items)--**12a. Diagnostic methods**-- List all diagnostic tests performed-- Laboratory tests-- Imaging studies-- Procedures (biopsy, catheterization, etc.)-- Pathology results-- Genetic testing if applicable--**12b. Diagnostic challenges**-- Difficulty in reaching diagnosis-- Atypical presentations-- Misleading initial findings-- Time to diagnosis--**12c. Diagnostic reasoning**-- Differential diagnosis considered-- Clinical reasoning process-- Why certain tests were ordered-- How diagnosis was narrowed--**12d. Prognostic characteristics**-- Severity of condition-- Staging if applicable-- Risk factors-- Expected prognosis--**12e. Strengths and limitations of diagnostic approaches**-- Appropriateness of diagnostic methods-- Limitations of tests used-- Alternative approaches considered--#### Therapeutic Intervention (4 items)--**13a. Types of interventions**-- Pharmacological interventions (medications with doses, routes, duration)-- Procedural or surgical interventions-- Lifestyle interventions-- Psychosocial interventions-- Complementary/alternative therapies-- Preventive interventions--Example:-- "Labetalol IV drip initiated for blood pressure control-- Emergency open surgical repair of ascending aortic dissection performed-- Post-operative anticoagulation withheld-- Beta-blocker and ACE inhibitor initiated post-operatively"--**13b. Administration of interventions**-- Timing of interventions-- Setting (emergency, inpatient, outpatient)-- Healthcare providers involved-- Patient adherence--**13c. Changes to interventions**-- Modifications during course of treatment-- Dose adjustments-- Changes due to adverse effects-- Switches to alternative therapies-- Rationale for changes--**13d. Strengths and limitations**-- Why these interventions were chosen-- Evidence supporting interventions-- Alternatives considered-- Limitations or barriers to treatment--#### Follow-Up and Outcomes (2 items)--**14a. Clinician and patient-assessed outcomes**-- Objective clinical outcomes-- Laboratory or imaging results-- Functional outcomes-- Patient-reported outcomes-- Quality of life-- Adverse events or complications--**14b. Important follow-up diagnostic and other test results**-- Follow-up imaging-- Laboratory monitoring-- Functional assessments-- Long-term outcomes-- Time points of follow-up--#### Discussion (5 items)--**15a. Strengths and limitations**-- What makes this case valuable?-- Limitations in diagnosis or treatment-- Limitations of case report methodology-- Generalizability--**15b. Relevant medical literature**-- Comparison to similar published cases-- Relationship to current understanding-- Novel aspects compared to literature-- Number and quality of similar cases--**15c. Rationale for conclusions**-- Why these conclusions are drawn-- Strength of evidence-- Alternative explanations considered--**15d. Main takeaways**-- Clinical lessons learned-- Practical implications for clinicians-- Educational value-- Contribution to medical knowledge--**15e. Future research or clinical care**-- Questions raised by this case-- Suggestions for future research-- Implications for clinical practice-- Areas needing further investigation--#### Patient Perspective (1 item)--**16. Patient's perspective or experience**-- Patient's own description of experience-- Impact on quality of life-- Patient's priorities and preferences-- Satisfaction with care-- Direct quotes when appropriate (with consent)--Example: "The patient stated: 'I thought I was having a heart attack, but the pain was different than I expected. I'm grateful the doctors figured out what was wrong so quickly.'"--This section is optional but encouraged as it provides valuable patient-centered information.--#### Informed Consent (1 item)--**17. Informed consent statement**-- Document that informed consent was obtained-- Specify what consent covers (case details, images, etc.)-- State that consent is available for review-- For pediatric cases, document parental/guardian consent-- For deceased patients or those unable to consent, document proxy consent--Examples:-- "Written informed consent was obtained from the patient for publication of this case report and accompanying images. A copy of the written consent is available for review by the Editor-in-Chief of this journal."-- "The patient provided written informed consent for publication of this case report. All identifying information has been removed to protect patient privacy."-- "Written informed consent was obtained from the patient's next of kin for publication of this case report as the patient was deceased at the time of manuscript preparation."--## Journal-Specific Requirements--### High-Impact Medical Journals--#### The Lancet-- Case reports rarely accepted (only if exceptional clinical significance)-- Prefer brief case reports (500-600 words, 1 figure)-- Structured abstract required-- Maximum 10 references--#### New England Journal of Medicine (NEJM)-- Clinical Problem-Solving format for diagnostic challenges-- Case Records of the Massachusetts General Hospital (CPC format)-- Brief case reports in Images in Clinical Medicine-- Strict word limits (typically <750 words for Images)--#### JAMA-- Brief case reports in Clinical Challenge format-- Focus on diagnostic reasoning-- Maximum 600 words-- 1-2 figures allowed--### Specialty Journals--#### BMJ Case Reports-- All case reports must follow CARE guidelines-- Structured abstract required-- Learning points section required (3-5 bullet points)-- Patient consent form required-- Word limit: 3000 words (excluding abstract and references)--#### Journal of Medical Case Reports-- Strictly follows CARE guidelines-- Open access publication-- Structured abstract: Background, Case presentation, Conclusions-- Timeline required-- Patient perspective encouraged--#### American Journal of Case Reports-- Open access-- Follows CARE guidelines-- Structured abstract required-- Minimum 1500 words-- No upper word limit--## De-identification and Privacy--### 18 HIPAA Identifiers to Remove--Complete list of protected health information (PHI) that must be removed for Safe Harbor de-identification:--1. **Names** - Patient name, family members' names, healthcare provider names-2. **Geographic subdivisions smaller than state** - Street addresses, cities, counties, ZIP codes (can keep first 3 digits if >20,000 people in area)-3. **Dates** - Exact dates of birth, admission, discharge, death (keep year or use intervals)-4. **Telephone numbers** - Any phone numbers related to patient-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** - License plates, VINs-13. **Device identifiers and serial numbers** - Pacemakers, implants (unless generic)-14. **Web URLs**-15. **IP addresses**-16. **Biometric identifiers** - Fingerprints, voice prints, retinal scans-17. **Full-face photographs** - Must obscure or obtain consent-18. **Any other unique identifying characteristic or code**--### De-identification Best Practices--**Age Reporting:**-- For adults: Can use exact age or age ranges (e.g., "a woman in her 50s")-- For patients >89 years: Must aggregate (e.g., "a woman in her 90s" or ">89 years")-- For pediatric cases: Use months for infants, years for children--**Date Reporting:**-- Use relative time intervals instead of exact dates-- Example: "Three months prior to presentation..." instead of "On January 15, 2023..."-- Can keep year if needed for context-- Use "Day 0, Day 1, Day 2" for timelines--**Location:**-- State or country acceptable-- Remove city, hospital name, specific clinic-- Example: "A community hospital in the Midwest" or "A tertiary care center in California"--**Rare Conditions:**-- Very rare conditions may themselves be identifying-- Consider whether the combination of diagnosis, location, and timeframe could identify patient-- May need to be vague about certain details--**Images:**-- Crop or blur faces-- Remove jewelry, tattoos, or identifying marks-- Crop images to show only relevant clinical findings-- Consider using illustrations instead of photographs-- Black bars over eyes are NOT sufficient-- Get explicit consent for recognizable images--**Pathology and Imaging:**-- Remove patient identifiers from image headers-- Remove dates from images-- Remove medical record numbers from labels--## Writing Style and Language--### Clarity and Precision--**Use clear, specific language:**-- Good: "The patient's hemoglobin decreased from 12.5 g/dL to 7.2 g/dL over 48 hours"-- Poor: "The patient's blood count dropped significantly"--**Avoid ambiguous terms:**-- Instead of "several," specify the number-- Instead of "recently," give timeframe-- Instead of "significant," provide exact values and p-values if applicable--**Use active voice when appropriate:**-- Good: "We diagnosed the patient with acute appendicitis"-- Acceptable: "The patient was diagnosed with acute appendicitis"--### Professional Tone--- Objective and factual-- Avoid sensationalism-- Respectful toward patient and healthcare team-- Avoid value judgments-- Focus on clinical facts and medical reasoning--### Tense--- **Abstract**: Usually past tense-- **Introduction**: Present tense for background, past tense for case description-- **Case presentation**: Past tense-- **Discussion**: Present tense for established knowledge, past tense for this case--### Common Mistakes to Avoid--1. **Insufficient novelty** - Reporting common presentations without unique aspects-2. **Missing informed consent** - Failing to obtain or document consent-3. **Inadequate de-identification** - Leaving identifiable information-4. **Poor literature review** - Not contextualizing within existing knowledge-5. **Excessive length** - Including unnecessary details-6. **Lack of structure** - Not following CARE guidelines or journal format-7. **Overgeneralization** - Drawing broad conclusions from one case-8. **Missing timeline** - Not providing clear chronology-9. **Vague outcomes** - Not clearly describing clinical outcome-10. **No learning points** - Failing to articulate clinical lessons--## Learning Points Format--Many journals require a "Learning Points" or "Key Messages" section with 3-5 bulleted takeaways.--**Characteristics of good learning points:**-- Concise (1-2 sentences each)-- Clinically actionable-- Generalizable beyond this specific case-- Focus on diagnosis, treatment, or recognition-- Avoid overgeneralization--**Example:**-- "Aortic dissection can present with atypical symptoms that mimic pneumonia, including cough and dyspnea without chest pain."-- "Blood pressure differential between arms >20 mmHg should raise suspicion for aortic dissection."-- "CT angiography is the gold standard for diagnosing acute aortic dissection and should be performed urgently in high-risk patients."--## Literature Search Strategies--**Databases to search:**-- PubMed/MEDLINE-- Embase-- Google Scholar-- Scopus-- Web of Science--**Search terms:**-- Disease or condition name-- Key clinical features-- Treatment or intervention-- Use MeSH terms-- Combine with "case report" or "case series"--**When citing literature:**-- Cite most relevant and recent cases-- Include systematic reviews if available-- Cite original descriptions of rare conditions-- Balance supporting and contrasting evidence-- Typically 15-30 references for case report--## Ethical Considerations--### Informed Consent--**Required elements:**-- Purpose of publication-- What will be published (case details, images, outcomes)-- De-identification efforts-- Open access considerations (public availability)-- No effect on clinical care-- Right to withdraw-- Contact for questions--**Timing:**-- Best obtained during or shortly after clinical care-- Can be obtained retrospectively if patient available-- For deceased patients, next of kin consent--**Special situations:**-- Pediatric patients: Parent/guardian consent-- Incapacitated patients: Legal representative consent-- Deceased patients: Next of kin consent-- Patients lost to follow-up: Discuss with editor--### Authorship--**ICMJE criteria for authorship (all must be met):**-1. Substantial contributions to conception/design or acquisition/analysis/interpretation of data-2. Drafting or critically revising for important intellectual content-3. Final approval of version to be published-4. Agreement to be accountable for all aspects of the work--**Common authorship roles in case reports:**-- First author: Primary writer, often junior physician/trainee-- Senior author: Attending physician, supervisor-- Co-authors: Contributing specialists, consultants-- Acknowledgments: Contributors not meeting authorship criteria--## Submission Process--### Cover Letter Elements--- Brief introduction of the case-- Statement of novelty and significance-- Confirmation of CARE guideline adherence-- Statement that manuscript is not under consideration elsewhere-- Disclosure of any conflicts of interest-- Corresponding author contact information--### Required Documents--- Manuscript (following journal format)-- CARE checklist (completed)-- Patient consent form-- Copyright transfer agreement-- Conflict of interest disclosure-- ORCID iDs for all authors-- Cover letter--### Revision and Peer Review--**Common reviewer requests:**-- Expand literature review-- Clarify timeline-- Add more detail to diagnostics or treatment-- Improve discussion of pathophysiology-- Strengthen learning points-- Verify consent documentation-- Improve image quality--**Response to reviewers:**-- Address each comment point-by-point-- Provide line numbers for changes-- Justify if not making requested change-- Thank reviewers for feedback-- Proofread revised manuscript--## Case Report Formats by Type--### Diagnostic Challenge--Focus on diagnostic reasoning process, differential diagnosis, and key diagnostic clues.--### Rare Disease or Presentation--Emphasize rarity, epidemiology, and contribution to medical knowledge about the condition.--### Adverse Drug Reaction--Include drug details (dose, duration), timeline, causality assessment (Naranjo scale), and outcome after discontinuation.--### Treatment Innovation--Describe novel treatment approach, rationale, outcome, and comparison to standard treatment.--### Unexpected Outcome--Describe unexpected response to treatment or unusual disease course.--## Supplementary Resources--- CARE website: https://www.care-statement.org/-- CARE checklist: Available in multiple languages-- Example case reports: Review published cases in target journal-- Medical writing courses: Many institutions offer case report writing workshops-------This reference provides comprehensive guidance for writing clinical case reports following CARE guidelines. Refer to this document when preparing case reports for journal submission, and use the CARE checklist to ensure completeness before submission.+- source accuracy and chronology;+- consent and authorization;+- privacy and image/metadata handling;+- terminology and clinical interpretation;+- discussion claims and citations;+- conflicts, limitations, and adverse outcomes;+- the target journal’s current instructions.+A structural result of `STRUCTURE_COMPLETE_REVIEW_REQUIRED` is not permission to submit.diff --git a/skills/clinical-reports/references/clinical_trial_reporting.md b/skills/clinical-reports/references/clinical_trial_reporting.mdindex 08179136..ddd62c43 100644--- a/skills/clinical-reports/references/clinical_trial_reporting.md+++ b/skills/clinical-reports/references/clinical_trial_reporting.md@@ -1,693 +1,97 @@-# Clinical Trial Reporting Standards+# Clinical-Trial Reporting-## ICH-E3: Structure and Content of Clinical Study Reports+## Keep the artifacts distinct-The International Council for Harmonisation (ICH) E3 guideline defines the structure and content of clinical study reports (CSRs) for regulatory submission.+- **Protocol**: planned design and conduct. Route randomized-trial protocols to SPIRIT 2025.+- **Results manuscript**: completed trial reporting for publication. Route randomized-trial results to CONSORT 2025.+- **Clinical Study Report (CSR)**: integrated clinical and statistical report of an individual study. Route to ICH E3 and its Q&A.+- **Safety report**: individual or aggregate safety communication. Route separately; see `safety_reporting.md`.-### CSR Overview+One checklist does not substitute for another.-**Purpose:**-- Provide comprehensive description of study design, conduct, and results-- Support regulatory decision-making-- Document evidence of safety and efficacy+## CONSORT 2025-**Audience:**-- Regulatory authorities (FDA, EMA, PMDA, etc.)-- Medical reviewers-- Statistical reviewers-- Clinical pharmacology reviewers+The official SPIRIT–CONSORT site describes CONSORT 2025 as a **30-item** minimum checklist plus a participant flow diagram for results of randomized trials. The primary statement was published 14 April 2025.-**Length:** Typically 50-300 pages (main text), with extensive appendices+Use the statement, expanded checklist, and explanation/elaboration together. Check the current extension catalogue for every applicable design, data, intervention, and population extension. In particular, consider the current harms extension for adverse-event reporting.-### Main Sections of ICH-E3 CSR+The local template stores item IDs `C01`–`C30`; it does not reproduce, reinterpret, or score the checklist. A qualified methodologist must map each item to the official wording and resolve interactions with extensions.-#### Section 1: Title Page+Do not:-**Required elements:**-- Full study title-- Protocol number and version-- Sponsor name and address-- Compound/drug name and code-- Study phase-- Indication-- Report date and version number-- Report authors-- Confidentiality statement+- fabricate a flow count or reason;+- infer analysis populations, endpoints, estimands, missing-data methods, or harms;+- add a figure when no verified data support it;+- treat a reporting checklist as proof of valid conduct or analysis.-#### Section 2: Synopsis+## SPIRIT 2025-**Length:** 5-15 pages+SPIRIT 2025 is the current reporting guideline for randomized-trial protocols. It was published 28 April 2025, contains **34 minimum items** plus a participant timeline figure, and supersedes SPIRIT 2013.-**Content:**-- Brief summary of entire CSR-- Must be understandable as standalone document-- Cover all major sections+Notable updated areas include open science, harms assessment, intervention/comparator description, and patient/public involvement. Use the statement, expanded checklist, explanation/elaboration, and applicable extensions together.-**Standard synopsis elements:**-1. Study identifier and title-2. Study objectives-3. Methodology:- - Study design- - Number and description of patients- - Diagnosis and main criteria for inclusion- - Study treatments- - Duration of treatment- - Criteria for evaluation- - Statistical methods-4. Results:- - Number of patients enrolled, completed, discontinued- - Efficacy results- - Safety results-5. Conclusions+The local template stores item IDs `S01`–`S34`. It checks item coverage only. It does not create a protocol, design a trial, select endpoints, specify interventions or doses, perform ethics review, or authorize conduct.-#### Section 3: Ethics+## ICH E3 Clinical Study Reports-**3.1 Independent Ethics Committee/Institutional Review Board**-- Names and locations of all IRBs-- Dates of initial approval-- Dates of protocol amendment approvals-- Documentation of continuing review+ICH E3 reached Step 4 on 30 November 1995. The current E3 Q&A (R1), dated 6 July 2012, states that E3 is guidance rather than a rigid required template and may be adapted with justified additions, deletions, renaming, or reordering.-**3.2 Ethical Conduct of Study**-- Statement of compliance with GCP and Declaration of Helsinki-- Protocol adherence-- Informed consent process+The structural validator expects these canonical sections:-**3.3 Patient Information and Consent**-- Description of informed consent procedures-- Consent form versions used-- Process for re-consent if applicable+1. Title Page+2. Synopsis+3. Table of Contents for the Individual Clinical Study Report+4. List of Abbreviations and Definitions of Terms+5. Ethics+6. Investigators and Study Administrative Structure+7. Introduction+8. Study Objectives+9. Investigational Plan+10. Study Patients+11. Efficacy Evaluation+12. Safety Evaluation+13. Discussion and Overall Conclusions+14. Tables, Figures, and Graphs Referred to but Not Included in the Text+15. Reference List+16. Appendices-#### Section 4: Investigators and Study Administrative Structure+Use `not_applicable_with_rationale` only when the study design and a qualified regulatory reviewer support the adaptation. The validator does not assess scientific content, appendices, eCTD placement, regional acceptability, or submission readiness.-**4.1 Investigators**-- List of principal investigators by site-- Site addresses and enrollment-- Coordinating investigator (if applicable)+## ICH E6(R3)-**4.2 Administrative Structure**-- Sponsor personnel and roles-- CRO involvement (if applicable)-- Monitoring procedures-- Data management organization-- Statistical analysis organization+ICH adopted E6(R3) Principles and Annex 1 on 6 January 2025, Annex 2 on 3 June 2026, and a consolidated final guideline on 16 June 2026.-**4.3 Study Monitoring and Quality Assurance**-- Monitoring procedures and frequency-- Source document verification-- Quality control procedures-- Audits performed+The guideline:-#### Section 5: Introduction+- applies to interventional trials of investigational products intended for regulatory submission, while principles may be applicable more broadly under local requirements;+- uses flexible, fit-for-purpose, proportionate, risk-based approaches;+- emphasizes participant rights, safety, and well-being and reliable results;+- requires attention to data governance, records, security, quality management, provenance, and traceability;+- expects the sponsor to describe the trial quality-management approach in the CSR.-**5.1 Background**-- Disease or condition being studied-- Current treatment landscape-- Unmet medical need+Step 4 adoption does not prove regional implementation. A qualified regulatory professional must verify the applicable adopted version and transition rules.-**5.2 Investigational Product**-- Pharmacology and mechanism of action-- Nonclinical findings-- Prior clinical experience-- Known safety profile+## Data integrity and provenance-**5.3 Non-Investigational Therapy**-- Comparator drugs or placebo-- Concomitant medications allowed/prohibited+For every populated field:-#### Section 6: Study Objectives+- retain the protocol/SAP-defined population and endpoint language;+- identify the verified source and field path;+- preserve prespecified versus post hoc status;+- preserve database-cut and coding-dictionary versions;+- report denominators and missingness explicitly;+- record transformations and reconciliation decisions made by accountable humans;+- expose unresolved discrepancies.-**6.1 Primary Objective**-- Main research question-- Clearly stated and specific-- Example: "To evaluate the efficacy of Drug X compared to placebo in reducing HbA1c in patients with type 2 diabetes mellitus over 24 weeks of treatment"+Do not copy subject-level listings into local examples or tests. Use aggregate manifests and hashes.-**6.2 Secondary Objectives**-- Additional research questions-- Supportive efficacy endpoints-- Safety objectives-- Exploratory objectives+## Review owners-**6.3 Endpoints**-- Primary endpoint definition and measurement-- Secondary endpoints-- Safety endpoints-- Pharmacokinetic endpoints (if applicable)-- Biomarker endpoints (if applicable)--#### Section 7: Investigational Plan--**7.1 Overall Study Design and Plan**-- Study design type (parallel, crossover, factorial, etc.)-- Randomization and blinding-- Study phases or periods-- Duration of treatment and follow-up-- Dosing regimen-- Study flow diagram (patient flowchart)--**7.2 Sample Size**-- Target enrollment-- Sample size justification-- Power calculation assumptions:- - Expected effect size- - Variability estimates- - Type I error (alpha)- - Power (1 - beta)- - Drop-out rate assumptions--**7.3 Statistical Methods**-- Analysis populations (ITT, PP, safety)-- Handling of missing data-- Interim analyses (if planned)-- Multiplicity adjustments-- Subgroup analyses-- Sensitivity analyses--**7.4 Changes to Protocol**-- Protocol amendments and rationale-- Impact on study conduct and analysis--#### Section 8: Study Patients--**8.1 Inclusion and Exclusion Criteria**-- Key inclusion criteria-- Key exclusion criteria-- Rationale for criteria--**8.2 Demographic and Baseline Characteristics**-- Age, sex, race/ethnicity-- Disease severity or stage-- Prior therapies-- Baseline values of key endpoints-- Comparability across treatment groups--**8.3 Patient Disposition**-- Number screened-- Number randomized-- Number completing study-- Number withdrawn (by reason)-- Number lost to follow-up-- CONSORT flow diagram--**8.4 Protocol Deviations**-- Major protocol deviations-- Minor protocol deviations-- Impact on efficacy and safety analyses-- Corrective actions taken--**8.5 Demographic and Other Baseline Characteristics**-- Detailed demographic tables-- Baseline disease characteristics-- Stratification factors-- Medical history-- Prior/concomitant medications--#### Section 9: Efficacy Evaluation--**9.1 Data Sets Analyzed**-- Intent-to-treat (ITT) population-- Per-protocol (PP) population-- Modified ITT-- Other analysis sets-- Justification for population definitions--**9.2 Demographic and Baseline Characteristics**-- Demographics by analysis population-- Baseline comparability--**9.3 Measurements of Treatment Compliance**-- Drug accountability-- Pill counts or diary compliance-- Plasma drug levels (if measured)-- Percent of planned dose received--**9.4 Efficacy Results**--**9.4.1 Primary Endpoint**-- Results for primary endpoint-- Statistical analysis-- Effect size and confidence intervals-- P-values-- Subgroup analyses--**9.4.2 Secondary Endpoints**-- Results for each secondary endpoint-- Statistical analyses-- Hierarchy of testing (if applicable)--**9.4.3 Other Efficacy Endpoints**-- Exploratory endpoints-- Post-hoc analyses-- Responder analyses--**9.5 Dropouts and Missing Data**-- Patterns of missing data-- Reasons for dropout-- Sensitivity analyses for missing data--#### Section 10: Safety Evaluation--**10.1 Extent of Exposure**-- Duration of exposure-- Dose intensity-- Dose delays or reductions-- Treatment discontinuations due to adverse events--**10.2 Adverse Events**--**10.2.1 Overview of Adverse Events**-- Summary tables (any AE, treatment-related, serious, leading to discontinuation)-- Percentage of patients with AEs-- Comparison across treatment groups--**10.2.2 Common Adverse Events**-- AEs occurring in ≥5% or ≥10% of patients-- Sorted by frequency-- Preferred terms and system organ class (MedDRA)--**10.2.3 Serious Adverse Events**-- Definition of SAE-- Summary table of SAEs-- Individual narratives for each SAE-- Causality assessment-- Outcome--**10.2.4 Adverse Events Leading to Discontinuation**-- AEs leading to study drug discontinuation-- Frequency and type-- Relationship to study drug--**10.2.5 Deaths**-- All deaths during study and follow-up-- Detailed narratives for each death-- Relationship to study drug-- Autopsy findings (if available)--**10.3 Clinical Laboratory Evaluations**-- Laboratory abnormalities-- Shift tables (normal to abnormal, abnormal to normal)-- Mean changes from baseline-- Laboratory values meeting protocol-defined criteria-- Hepatotoxicity monitoring (if applicable)--**10.4 Vital Signs and Physical Findings**-- Vital signs (BP, HR, temperature, respiratory rate)-- Mean changes from baseline-- Clinically significant changes-- Physical examination findings--**10.5 ECG Evaluation**-- QTc interval changes-- Other ECG abnormalities-- Clinically significant ECG findings--**10.6 Special Safety Evaluations**-- Immunogenicity (for biologics)-- Pregnancy outcomes (if applicable)-- Abuse potential (if applicable)-- Withdrawal or rebound effects-- Dependency potential--#### Section 11: Discussion and Overall Conclusions--**11.1 Efficacy Discussion**-- Interpretation of efficacy results-- Clinical significance of findings-- Consistency with prior studies-- Limitations--**11.2 Safety Discussion**-- Safety profile overview-- Notable safety findings-- Comparison to known safety profile-- Risk-benefit assessment--**11.3 Benefit-Risk Assessment**-- Overall benefit-risk conclusion-- Subpopulations with favorable/unfavorable benefit-risk-- Implications for dosing or patient selection--**11.4 Clinical Implications**-- Place in therapy-- Target patient population-- Comparison to existing therapies--#### Section 12: Tables, Figures, and Graphs--Comprehensive set of tables and figures for efficacy and safety data.--**Common tables:**-- Demographic and baseline characteristics-- Patient disposition-- Extent of exposure-- Efficacy results (primary and secondary endpoints)-- Adverse event summary-- Common adverse events-- Serious adverse events-- Deaths-- Laboratory abnormalities-- Vital signs--**Common figures:**-- Study design schematic-- Patient disposition flowchart (CONSORT)-- Kaplan-Meier curves (survival, time to event)-- Forest plots (subgroup analyses)-- Mean change over time plots--#### Section 13: References--- Publications cited in CSR-- Relevant literature-- Regulatory guidelines-- Prior study reports--#### Section 14: Appendices--**Required appendices:**-- Study protocol and amendments-- Sample case report forms-- Investigator list with IRB information-- Patient information and informed consent forms-- List of patients receiving study drug-- Randomization scheme-- Audit certificates (if applicable)-- Documentation of statistical methods-- Publications based on study--**Optional appendices:**-- Individual patient data listings-- SAE narratives-- Laboratory normals and conversion factors-- Investigator signatures--### Statistical Analysis Plan (SAP)--**SAP Components:**-- Analysis populations-- Handling of missing data-- Statistical tests to be used-- Adjustment for multiplicity-- Interim analysis plan-- Subgroup analyses-- Sensitivity analyses-- Safety analyses--**SAP Timing:**-- Finalized before database lock-- Amendments documented with rationale--## CONSORT (Consolidated Standards of Reporting Trials)--CONSORT guidelines promote transparent and complete reporting of randomized controlled trials.--### CONSORT 2010 Checklist--#### Title and Abstract-- **1a. Title**: Identification as randomized trial in title-- **1b. Abstract**: Structured summary covering trial design, methods, results, conclusions--#### Introduction-- **2a. Background**: Scientific background and explanation of rationale-- **2b. Objectives**: Specific objectives or hypotheses--#### Methods - Participants-- **3a. Eligibility**: Eligibility criteria for participants-- **3b. Settings**: Settings and locations of data collection--#### Methods - Interventions-- **4a. Interventions**: Details of interventions for each group-- **4b. Details**: Sufficient details to allow replication--#### Methods - Outcomes-- **5. Outcomes**: Clearly defined primary and secondary outcome measures-- **6a. Sample size**: How sample size was determined-- **6b. Interim analyses**: When applicable, explanation of interim analyses--#### Methods - Randomization-- **7a. Sequence generation**: Method of random sequence generation-- **7b. Allocation concealment**: Mechanism of allocation concealment-- **8a. Implementation**: Who generated allocation, enrolled, and assigned participants-- **8b. Blinding**: Whether participants, care providers, outcome assessors were blinded--#### Methods - Statistical-- **9. Statistical methods**: Methods for primary and secondary outcomes-- **10. Additional analyses**: Subgroup or adjusted analyses--#### Results - Participant Flow-- **11a. Enrollment**: Numbers screened, randomized, allocated-- **11b. Losses and exclusions**: For each group, losses and exclusions after randomization-- **12. Recruitment**: Dates defining recruitment and follow-up periods-- **13a. Baseline**: Baseline demographic and clinical characteristics-- **13b. Baseline comparability**: Numbers analyzed in each group--#### Results - Outcomes and Estimation-- **14a. Outcomes**: For primary and secondary outcomes, results for each group-- **14b. Binary outcomes**: For binary outcomes, effect sizes and confidence intervals-- **15. Ancillary analyses**: Results of other analyses performed--#### Results - Harms-- **16. Harms**: All important harms or unintended effects in each group--#### Discussion-- **17a. Limitations**: Trial limitations, addressing biases, imprecision-- **17b. Generalizability**: Generalizability (external validity) of trial findings-- **18. Interpretation**: Interpretation consistent with results, balancing benefits and harms-- **19. Registration**: Registration number and name of trial registry-- **20. Protocol**: Where full trial protocol can be accessed-- **21. Funding**: Sources of funding, role of funders--### CONSORT Flow Diagram--Standard format showing patient flow through trial:-```-Assessed for eligibility (n=)- ↓-Randomized (n=)- ├─ Allocated to intervention (n=)- │ ├─ Received intervention (n=)- │ └─ Did not receive intervention (n=)- │ Give reasons- ├─ Allocated to control (n=)- │ ├─ Received control (n=)- │ └─ Did not receive control (n=)- │ Give reasons- ↓-Lost to follow-up (n=)- Give reasons-Discontinued intervention (n=)- Give reasons- ↓-Analyzed (n=)-Excluded from analysis (n=)- Give reasons-```--## Serious Adverse Event (SAE) Reporting--### Definition of Serious Adverse Event--An adverse event or suspected adverse reaction is considered serious if it:-- Results in death-- Is life-threatening-- Requires inpatient hospitalization or prolongation of existing hospitalization-- Results in persistent or significant disability/incapacity-- Is a congenital anomaly/birth defect-- Requires intervention to prevent permanent impairment or damage (device-related)-- Other medically important events (based on medical judgment)--### SAE Report Components--**1. Administrative Information**-- Report type (initial, follow-up, final)-- Report number-- Date of report-- Reporter information-- Sponsor information-- Study identifier (protocol number, NCT number)--**2. Patient Information (De-identified)**-- Subject ID or randomization number-- Initials (if permitted)-- Age or date of birth (year only)-- Sex-- Race/ethnicity-- Weight-- Height--**3. Study Information**-- Study phase (I, II, III, IV)-- Study design (randomized, open-label, etc.)-- Treatment arm or randomization-- Date of first study drug-- Date of last study drug--**4. Event Information**-- Reported term (verbatim)-- MedDRA preferred term-- System organ class-- Date of onset-- Time of onset (if relevant)-- Date of resolution (or ongoing)-- Duration--**5. Seriousness Criteria**-- Death: Yes/No-- Life-threatening: Yes/No-- Hospitalization required: Yes/No-- Hospitalization prolonged: Yes/No-- Disability/incapacity: Yes/No-- Congenital anomaly: Yes/No-- Medically significant: Yes/No--**6. Severity**-- Mild: Noticeable but does not interfere with daily activities-- Moderate: Interferes with daily activities but manageable-- Severe: Prevents usual daily activities, requires intervention--Note: Severity ≠ Seriousness--**7. Outcome**-- Recovered/resolved-- Recovering/resolving-- Not recovered/not resolved-- Recovered/resolved with sequelae-- Fatal-- Unknown--**8. Causality Assessment**-- Relationship to study drug:- - Not related- - Unlikely related- - Possibly related- - Probably related- - Definitely related-- Relationship to study procedures-- Relationship to underlying disease-- Relationship to concomitant medications-- Reasoning for determination--**9. Expectedness**-- Expected (per Investigator's Brochure or protocol)-- Unexpected (not in IB or more severe than documented)--**10. Action Taken with Study Drug**-- No change-- Dose reduced-- Dose increased-- Drug interrupted (temporarily held)-- Drug discontinued-- Not applicable (event occurred after discontinuation)--**11. Treatments/Interventions for Event**-- Medications administered-- Procedures performed-- Hospitalization details-- ICU admission-- Surgical intervention--**12. Event Narrative**-- Detailed description of event-- Timeline of events-- Clinical course-- Relevant medical history-- Concomitant medications-- Diagnostic test results-- Treatment and response-- Outcome and current status--**Example narrative:**-```-A 58-year-old male (Subject ID: 12345) enrolled in Study XYZ-301, a Phase 3-randomized trial of Drug X vs. placebo for heart failure. On Day 42 of treatment-(15-Feb-2024), the patient presented to the emergency department with sudden onset-severe chest pain, diaphoresis, and dyspnea. ECG showed ST-segment elevation in-leads V2-V4. Troponin I was elevated at 12.5 ng/mL (normal <0.04). The patient was-diagnosed with acute ST-elevation myocardial infarction and underwent emergent-cardiac catheterization revealing 95% occlusion of the left anterior descending-artery. Percutaneous coronary intervention with drug-eluting stent placement was-performed successfully. The patient was admitted to the cardiac intensive care unit.-Study drug was permanently discontinued on Day 42. The patient recovered and was-discharged on Day 47 (20-Feb-2024) in stable condition. This event was assessed as-unlikely related to study drug by the investigator, as the patient had significant-underlying coronary artery disease risk factors including diabetes, hypertension,-and smoking history.-```--### Regulatory Reporting Timelines--**FDA IND Safety Reporting (21 CFR 312.32):**-- **Fatal or life-threatening unexpected SAEs**: 7 calendar days for preliminary report, 15 days for complete report-- **Other serious unexpected events**: 15 calendar days-- **Annual safety reports**: Within 60 days of anniversary of IND--**EMA Expedited Reporting:**-- **Fatal or life-threatening unexpected events**: 7 days initial, 8 additional days for complete report-- **Other unexpected serious events**: 15 days--**IRB Reporting:**-- Per institutional policy-- Typically 5-10 days for serious unexpected events-- Some institutions require reporting within 24-48 hours--### MedDRA Coding--**MedDRA (Medical Dictionary for Regulatory Activities):**-- Standardized medical terminology for regulatory communication-- Hierarchical structure:- - SOC (System Organ Class) - highest level- - HLGT (High Level Group Term)- - HLT (High Level Term)- - PT (Preferred Term) - used for coding AEs- - LLT (Lowest Level Term) - verbatim terms--**Example:**-- Verbatim term: "bad headache"-- LLT: Headache-- PT: Headache-- HLT: Headaches NEC-- HLGT: Neurological disorders NEC-- SOC: Nervous system disorders--### Causality Assessment Methods--**WHO-UMC Causality Categories:**-- **Certain**: Event cannot be explained by other factors-- **Probable/Likely**: Event more likely related to drug than other factors-- **Possible**: Event could be related to drug, but other factors cannot be ruled out-- **Unlikely**: Event likely explained by other factors-- **Conditional/Unclassified**: More data needed-- **Unassessable/Unclassifiable**: Information insufficient--**Naranjo Algorithm (for ADRs):**-Scoring system based on 10 questions:-- Score ≥9: Definite-- Score 5-8: Probable-- Score 1-4: Possible-- Score ≤0: Doubtful--## Data Safety Monitoring Board (DSMB)--**Purpose:**-- Independent review of safety data-- Monitoring benefit-risk-- Recommendations on study continuation--**DSMB Charter Elements:**-- Membership and qualifications-- Roles and responsibilities-- Meeting frequency-- Data reviewed-- Decision-making criteria-- Communication procedures-- Confidentiality--**DSMB Reports:**-- Open reports (all parties can see)-- Closed reports (DSMB and sponsor only)-- Recommendations: Continue, modify, or terminate study-------This reference provides comprehensive guidance for clinical trial reporting following ICH-E3 and CONSORT guidelines, as well as SAE reporting requirements. Use these standards when preparing regulatory submissions and trial publications.+- accountable clinical author: clinical interpretation;+- trial statistician: analysis populations, estimands, methods, outputs, and denominators;+- safety physician/professional: safety interpretation and individual-case decisions;+- data management/quality: source lineage and reconciliation;+- privacy/legal/ethics: authorization and disclosure;+- regulatory professional: CSR structure, regional rules, and submission package.+No script result replaces any of these reviews.diff --git a/skills/clinical-reports/references/data_presentation.md b/skills/clinical-reports/references/data_presentation.mdindex f4b103d1..1b9581ae 100644--- a/skills/clinical-reports/references/data_presentation.md+++ b/skills/clinical-reports/references/data_presentation.md@@ -1,530 +1,92 @@-# Data Presentation in Clinical Reports+# Aggregate Data Presentation-## Tables for Clinical Data+Present verified outputs without changing their meaning. Do not calculate a clinical conclusion, select an analysis, or repair source discrepancies.-### Table Design Principles+## Mandatory table metadata-**General guidelines:**-- Clear, concise title describing table contents-- Column headers with units-- Row labels aligned left, data aligned appropriately (numbers right, text left)-- Footnotes for abbreviations, statistical notation, special cases-- Consistent decimal places (typically 1-2 for percentages, 1-3 for continuous variables)-- Consistent formatting throughout document+Every table should identify:-**Title placement:**-- Above table-- Numbered sequentially (Table 1, Table 2, etc.)-- Descriptive enough to stand alone+- artifact and analysis purpose;+- data cut and source-output version;+- analysis population/set;+- treatment/group labels;+- denominator for every group and row when it varies;+- whether a value is a subject count, event count, observation count, or estimate;+- units, time point/window, and summary statistic;+- missing, unknown, not assessed, suppressed, or not applicable values;+- coding dictionary/version/language where applicable;+- statistical method and multiplicity status only when copied from a verified output;+- provenance manifest and reviewer status.-**Footnote symbols (in order):**-- *, †, ‡, §, ||, ¶, #-- Or use superscript letters (a, b, c...)-- Or use superscript numbers if not confused with references+## Counts and denominators-### Demographic and Baseline Characteristics Table+- Show `n/N (%)`, not a percentage alone, unless the governing output specifies another form.+- Require `0 <= n <= N` and `N > 0`.+- Recalculate only for consistency checking; do not silently replace the reported percentage.+- State the rounding rule and tolerance.+- Do not add subgroup percentages when the subgroup denominator is unknown.+- Do not infer that denominators are randomized, treated, evaluable, or safety populations.+- Keep event counts distinct from subjects affected; event counts can exceed the number of subjects.+- Do not sum non-mutually-exclusive categories.-**Purpose:** Describe study population at baseline+## Dates and time-**Standard format:**+- Use ISO 8601 in structured manifests.+- Preserve source timezone and precision.+- Distinguish event date, collection date, database cut, report date, and verification date.+- Flag start-after-end and conflicting dates.+- Do not impute a missing day, month, timezone, or chronology.+- For de-identified case reports, use an authorized relative timeline; do not distort intervals.-```-Table 1. Baseline Demographics and Clinical Characteristics+## Units and precision-Characteristic Treatment Group Control Group Total- (N=150) (N=145) (N=295)-─────────────────────────────────────────────────────────────────────────-Age, years- Mean (SD) 64.2 (8.5) 63.8 (9.1) 64.0 (8.8)- Median (IQR) 65 (58-71) 64 (57-70) 64 (58-71)- Range 45-82 43-85 43-85+- Preserve source units.+- Require a unit for every dimensional quantity.+- Use one verified unit per comparable series or expose the mismatch.+- Do not convert or normalize without an authorized traceable conversion rule.+- Preserve clinically meaningful precision; do not create extra significant digits.+- Identify SD, SE, CI, IQR, range, and denominator explicitly.-Sex, n (%)- Male 95 (63.3) 88 (60.7) 183 (62.0)- Female 55 (36.7) 57 (39.3) 112 (38.0)+## Missing and suppressed values-Race, n (%)- White 110 (73.3) 105 (72.4) 215 (72.9)- Black/African American 25 (16.7) 28 (19.3) 53 (18.0)- Asian 10 (6.7) 8 (5.5) 18 (6.1)- Other 5 (3.3) 4 (2.8) 9 (3.0)+Keep these states distinct:-BMI, kg/m²- Mean (SD) 28.5 (4.2) 28.1 (4.5) 28.3 (4.4)+- `missing`;+- `not_collected`;+- `not_assessed`;+- `unknown`;+- `not_applicable`;+- `suppressed_for_privacy`;+- `zero`.-Baseline HbA1c, %- Mean (SD) 8.9 (1.2) 9.0 (1.3) 9.0 (1.2)+Never convert a blank to zero. State small-cell suppression rules and ensure totals or complementary cells do not reveal suppressed values.-Disease duration, years- Median (IQR) 6 (3-10) 5 (3-9) 6 (3-10)+## Adverse-event tables-Prior medications, n (%)- Metformin 135 (90.0) 130 (89.7) 265 (89.8)- Sulfonylurea 45 (30.0) 42 (29.0) 87 (29.5)- Insulin 20 (13.3) 18 (12.4) 38 (12.9)-─────────────────────────────────────────────────────────────────────────-SD = standard deviation; IQR = interquartile range; BMI = body mass index;-HbA1c = hemoglobin A1c-```+For term-level aggregate tables:-**Key elements:**-- Sample size for each group (N=)-- Continuous variables: mean (SD), median (IQR), range-- Categorical variables: n (%)-- No p-values for baseline comparisons (debated but generally not recommended)+- state MedDRA version and language;+- state analysis set and denominator;+- state counting rule from the verified SAP/output;+- show subjects affected and event count separately;+- do not add p-values or causal labels;+- do not interpret between-group differences;+- preserve threshold rules exactly;+- have safety and statistical reviewers verify deduplication, hierarchy, and population.-### Efficacy Results Table+## Figures-**Purpose:** Present primary and secondary endpoint results+No figure is mandatory. Create one only when requested, supported by verified aggregate data, allowed by the target guidance, and reviewable without external image generation.-**Example:**+A CONSORT flow diagram is part of CONSORT 2025 reporting, but every count and reason must come from verified trial outputs. A missing count remains missing; do not create a decorative or inferred diagram.-```-Table 2. Primary and Secondary Efficacy Endpoints at Week 24+## Deterministic consistency check-Endpoint Treatment Control Difference P-value- (N=150) (N=145) (95% CI)-──────────────────────────────────────────────────────────────────────────────────-Primary Endpoint-Change in HbA1c from baseline, %- Mean (SE) -1.8 (0.1) -0.6 (0.1) -1.2 <0.001- 95% CI (-2.0, -1.6) (-0.8, -0.4) (-1.5, -0.9)+`consistency_checker.py` can inspect:-Secondary Endpoints-Change in FPG, mg/dL- Mean (SE) -42.5 (3.2) -15.2 (3.4) -27.3 <0.001- 95% CI (-48.8, -36.2) (-21.9, -8.5) (-36.4, -18.2)--% achieving HbA1c <7%- n (%) 78 (52.0) 25 (17.2) - <0.001- 95% CI (43.9, 60.1) (11.4, 24.5)--Change in body weight, kg- Mean (SE) -3.2 (0.4) -0.5 (0.4) -2.7 <0.001- 95% CI (-4.0, -2.4) (-1.3, 0.3) (-3.8, -1.6)-──────────────────────────────────────────────────────────────────────────────-SE = standard error; CI = confidence interval; HbA1c = hemoglobin A1c;-FPG = fasting plasma glucose-```--**Statistical presentation:**-- Point estimates with measures of precision (SE or CI)-- p-values (consider adjustment for multiplicity)-- Effect size (difference or ratio) with 95% CI-- Significance level noted (e.g., p<0.05, p<0.01, p<0.001)--### Adverse Events Table--**Purpose:** Summarize safety data--**Example:**--```-Table 3. Summary of Adverse Events--Event Category Treatment Control P-value- (N=150) (N=145)- n (%) n (%)-──────────────────────────────────────────────────────────────────────────-Any adverse event 120 (80.0) 95 (65.5) 0.004--Treatment-related adverse events 85 (56.7) 42 (29.0) <0.001--Serious adverse events 12 (8.0) 8 (5.5) 0.412--Adverse events leading to 8 (5.3) 4 (2.8) 0.257-discontinuation--Deaths 0 (0.0) 1 (0.7) 0.492--Common adverse events (≥5% in any group)- Nausea 45 (30.0) 12 (8.3) <0.001- Diarrhea 38 (25.3) 10 (6.9) <0.001- Headache 22 (14.7) 18 (12.4) 0.568- Hypoglycemia 18 (12.0) 5 (3.4) 0.007- Dizziness 12 (8.0) 8 (5.5) 0.412-──────────────────────────────────────────────────────────────────────────-Adverse events coded using MedDRA version 24.0-```--**Key elements:**-- Overall AE summary-- Serious AEs highlighted-- Deaths reported-- Common AEs (typically ≥5% or ≥10% threshold)-- MedDRA coding indicated--### Laboratory Abnormalities Table--**Shift tables showing changes from baseline:**--```-Table 4. Laboratory Values Meeting Predefined Criteria for Abnormality--Laboratory Parameter Treatment Control- (N=150) (N=145)- n (%) n (%)-──────────────────────────────────────────────────────────────────────────-ALT >3× ULN 8 (5.3) 3 (2.1)-AST >3× ULN 5 (3.3) 2 (1.4)-Total bilirubin >2× ULN 2 (1.3) 1 (0.7)-Creatinine >1.5× baseline 12 (8.0) 5 (3.4)-Hemoglobin <10 g/dL 3 (2.0) 2 (1.4)-Platelets <100 × 10³/μL 1 (0.7) 0 (0.0)-──────────────────────────────────────────────────────────────────────────-ULN = upper limit of normal; ALT = alanine aminotransferase;-AST = aspartate aminotransferase-```--### Patient Disposition Table (CONSORT Format)--```-Table 5. Patient Disposition--Disposition Treatment Control Total- (N=150) (N=145) (N=295)-────────────────────────────────────────────────────────────────────────────-Screened - - 425--Randomized 150 145 295--Completed study 135 (90.0) 130 (89.7) 265 (89.8)--Discontinued, n (%) 15 (10.0) 15 (10.3) 30 (10.2)- Adverse event 8 (5.3) 4 (2.8) 12 (4.1)- Lack of efficacy 2 (1.3) 5 (3.4) 7 (2.4)- Lost to follow-up 3 (2.0) 4 (2.8) 7 (2.4)- Withdrawal of consent 2 (1.3) 2 (1.4) 4 (1.4)--Included in efficacy analysis- ITT population 150 (100) 145 (100) 295 (100)- Per-protocol population 142 (94.7) 138 (95.2) 280 (94.9)--Included in safety analysis 150 (100) 145 (100) 295 (100)-────────────────────────────────────────────────────────────────────────────-ITT = intent-to-treat-```--## Figures for Clinical Data--### Figure Design Principles--**General guidelines:**-- Clear, concise caption/legend below figure-- Numbered sequentially (Figure 1, Figure 2, etc.)-- Axis labels with units-- Legible font size (minimum 8-10 point)-- High resolution (300 dpi for print, 150 dpi for web)-- Color-blind friendly palette-- Black and white compatible (use different symbols/patterns)--**Figure caption:**-- Describes what is shown-- Explains symbols, error bars, statistical annotations-- Defines abbreviations-- Provides context for interpretation--### CONSORT Flow Diagram--**Purpose:** Show patient flow through randomized trial--```- Assessed for eligibility (n=425)- │- ┌─────────────────────┴─────────────────────┐- │ │- Excluded (n=130) │- • Not meeting inclusion criteria (n=85) │- • Declined to participate (n=32) │- • Other reasons (n=13) │- │- Randomized (n=295)- │- ┌───────────────────────────────┴───────────────────────────────┐- │ │- Allocated to Treatment (n=150) Allocated to Control (n=145)- • Received allocated intervention (n=148) • Received allocated intervention (n=143)- • Did not receive allocated intervention (n=2) • Did not receive allocated intervention (n=2)- Reasons: withdrew consent before treatment Reasons: withdrew consent before treatment- │ │- ┌───────────┴────────────┐ ┌──────────────┴─────────────┐- │ │ │ │- Lost to follow-up (n=3) Discontinued (n=12) Lost to follow-up (n=4) Discontinued (n=11)- • Adverse events (n=8) • Adverse events (n=4)- • Lack of efficacy (n=2) • Lack of efficacy (n=5)- • Withdrew consent (n=2) • Withdrew consent (n=2)- │ │- Analyzed (n=150) Analyzed (n=145)- • ITT analysis (n=150) • ITT analysis (n=145)- • Per-protocol analysis (n=142) • Per-protocol analysis (n=138)- • Excluded from analysis (n=0) • Excluded from analysis (n=0)-```--### Kaplan-Meier Survival Curve--**Purpose:** Show time-to-event data--**Elements:**-- X-axis: Time (weeks, months, years)-- Y-axis: Probability of event-free survival (0 to 1 or 0% to 100%)-- Separate curves for each treatment group-- Censored observations marked (often with vertical tick marks)-- Number at risk table below graph-- Median survival time indicated-- Log-rank p-value-- Hazard ratio with 95% CI--**Caption example:**-```-Figure 1. Kaplan-Meier Curves for Overall Survival--Kaplan-Meier estimates of overall survival in the treatment and control groups.-Tick marks indicate censored observations. Number at risk shown below graph.-Log-rank p<0.001. Median survival: Treatment 24.5 months (95% CI: 22.1-26.8),-Control 18.2 months (95% CI: 16.5-20.1). Hazard ratio 0.68 (95% CI: 0.55-0.84).-```--### Forest Plot--**Purpose:** Display subgroup analyses or meta-analysis results--**Elements:**-- Point estimates (squares or diamonds)-- Size of symbol proportional to precision (inverse variance) or sample size-- Horizontal lines showing 95% CI-- Vertical line at null effect (HR=1.0, OR=1.0, or difference=0)-- Subgroup labels on left-- Effect size values on right-- Overall estimate (if meta-analysis)-- Heterogeneity statistics (I², p-value)--**Caption example:**-```-Figure 2. Forest Plot of Treatment Effect by Subgroup--Effect of treatment vs. control on primary endpoint across pre-specified subgroups.-Squares represent point estimates; horizontal lines represent 95% confidence intervals.-Square size is proportional to subgroup sample size. Overall effect shown as diamond.-p-value for interaction testing heterogeneity of treatment effect across subgroups.-```--### Box Plot--**Purpose:** Show distribution of continuous variable--**Elements:**-- Box: IQR (25th to 75th percentile)-- Line in box: Median-- Whiskers: Extend to most extreme data point within 1.5 × IQR-- Outliers: Points beyond whiskers (often shown as circles)-- X-axis: Groups or time points-- Y-axis: Continuous variable with units--### Scatter Plot with Regression--**Purpose:** Show relationship between two continuous variables--**Elements:**-- X-axis: Independent variable-- Y-axis: Dependent variable-- Individual data points-- Regression line (if appropriate)-- Regression equation-- R² value-- P-value for slope-- 95% confidence interval for regression line (optional, shown as shaded area)--### Spaghetti Plot--**Purpose:** Show individual trajectories over time--**Elements:**-- X-axis: Time-- Y-axis: Outcome variable-- Individual patient lines (often semi-transparent)-- Mean trajectory (bold line)-- Separate colors for treatment groups--### Bar Chart--**Purpose:** Compare proportions or means across groups--**Elements:**-- Clear separation between bars-- Error bars (SEM or 95% CI)-- Y-axis starts at 0 (do not truncate for bar charts)-- Group labels on X-axis-- Value labels on Y-axis with units-- Statistical significance indicated (p-values or asterisks)--**Avoid:**-- 3D bar charts (distort perception)-- Excessive decoration-- Truncated Y-axis for bars--### Line Graph--**Purpose:** Show changes over time--**Elements:**-- X-axis: Time (with consistent intervals)-- Y-axis: Outcome variable-- Separate lines for each group (different colors/patterns)-- Data points marked (circles, squares, triangles)-- Error bars at each time point (SE or 95% CI)-- Legend identifying groups-- Grid lines (optional, light gray)--### Histogram--**Purpose:** Show distribution of continuous variable--**Elements:**-- X-axis: Variable (divided into bins)-- Y-axis: Frequency or density-- Appropriate bin width (not too few, not too many)-- Overlay normal distribution curve (if testing normality)--## Special Considerations for Clinical Data--### Presenting Proportions--**Numerator and denominator:**-- Always provide both: 25/100 (25%)-- Not just percentage (25%)--**Percentages:**-- No decimal places if n<100-- 1 decimal place if n≥100-- Never report >1 decimal place for percentages--**Confidence intervals for proportions:**-- Wilson score interval or exact binomial (better than Wald for small samples)-- Always report with percentage--### Presenting Continuous Data--**Measures of central tendency:**-- Mean for normally distributed data-- Median for skewed data or ordinal data-- Report both if distribution unclear--**Measures of dispersion:**-- **Standard deviation (SD)**: Describes variability in data-- **Standard error (SE)**: Describes precision of mean estimate-- **95% Confidence interval**: Preferred for inferential statistics-- **Interquartile range (IQR)**: With median for skewed data-- **Range**: Min to max--**When to use each:**-- Descriptive statistics → Mean (SD) or Median (IQR)-- Inferential statistics → Mean (95% CI) or Mean (SE)-- Never use ± without specifying SD, SE, or CI--### Presenting P-values--**Reporting guidelines:**-- Report exact p-values to 2-3 decimal places (p=0.042)-- For very small p-values, use p<0.001 (not p=0.000)-- Do not report as "NS" or "p=NS"-- For non-significant results, report exact p-value (p=0.18, not p>0.05)-- Specify two-tailed unless pre-specified one-tailed-- Correct for multiple comparisons when appropriate-- Report significance threshold used (α=0.05 is standard)--**Avoid:**-- p<0.05 (report exact value)-- p=0.00 (impossible)-- Multiple decimal places (p=0.04235891)--### Statistical Significance Indicators--**Options:**-1. Report p-values in table-2. Use asterisks with legend:- - *p<0.05- - **p<0.01- - ***p<0.001-3. Use confidence intervals (preferred)--### Confidence Intervals--**Reporting:**-- 95% CI is standard-- Format: (lower limit, upper limit)-- Or: lower limit to upper limit-- Or: lower limit-upper limit--**Interpretation:**-- If CI for difference excludes 0 → significant-- If CI for ratio excludes 1 → significant-- Width of CI indicates precision--### Missing Data--**Indicate clearly:**-- Footnote explaining missing data-- State clearly if analysis is complete case-- Describe imputation method if used-- Report amount of missing data per variable--### Decimal Places and Rounding--**General rules:**-- Report to level of measurement precision-- Consistent decimal places within table-- Round p-values to 2-3 decimal places-- Round percentages to 0-1 decimal place-- Round means/medians to 1-2 decimal places-- Include appropriate significant figures--## Software for Creating Figures--**Statistical software:**-- R (ggplot2) - highly customizable-- GraphPad Prism - user-friendly for biomedical-- SAS, Stata, SPSS - comprehensive statistical packages-- Python (matplotlib, seaborn) - flexible and powerful--**General graphics software:**-- Adobe Illustrator - professional publication-quality-- Inkscape - free vector graphics editor-- PowerPoint - basic graphs, easy to use-- BioRender - biological schematics and figures--## Color Schemes--**Color-blind friendly palettes:**-- Avoid red-green combinations-- Use blue-orange, blue-yellow-- Include shape/pattern differences-- Test figures in grayscale--**Recommended palettes:**-- ColorBrewer (designed for data visualization)-- Viridis (perceptually uniform)-- IBM Color Blind Safe Palette--## Image Quality Standards--**Resolution:**-- 300 dpi for print publication-- 150 dpi for web/screen-- Vector graphics (PDF, SVG) preferred for graphs--**File formats:**-- TIFF or EPS for print-- PNG for web-- PDF for vector graphics-- JPEG acceptable for photographs (high quality)--**Image editing:**-- No manipulation that alters data-- Only acceptable adjustments: brightness, contrast, color balance applied to entire image-- Document all adjustments-- Provide original images if requested-------This reference provides comprehensive guidance for presenting clinical data in tables and figures following best practices and publication standards. Use these guidelines to create clear, accurate, and professional data presentations.+- ISO date and range ordering;+- unit-label consistency;+- `n/N (%)` arithmetic;+- component-total arithmetic.+It reports mismatches and review needs. It does not change the input, choose the correct source, or validate clinical/statistical meaning.diff --git a/skills/clinical-reports/references/diagnostic_reports_standards.md b/skills/clinical-reports/references/diagnostic_reports_standards.mdindex c9d0ea55..3cabdaaf 100644--- a/skills/clinical-reports/references/diagnostic_reports_standards.md+++ b/skills/clinical-reports/references/diagnostic_reports_standards.md@@ -1,629 +1,76 @@-# Diagnostic Reports Standards+# Diagnostic-Report Scaffolds-## Radiology Reporting Standards+These assets are structured field maps for authorized clinical services. They do not interpret data or produce a report suitable for patient care.-### American College of Radiology (ACR) Guidelines+## Radiology-The ACR provides comprehensive practice parameters for diagnostic imaging reporting to ensure quality, consistency, and communication effectiveness.+The ACR **Practice Parameter for Communication of Diagnostic Imaging Findings**, revised 2025 (Resolution 9), addresses diagnostic imaging reports, final-report principles, preliminary reports, nonroutine communication, informal communication, and organizational communication policies.-#### Core Radiology Report Components+Use `assets/radiology_report_template.json` only to map verified facts such as:-**1. Patient Demographics**-- Patient name and/or unique identifier-- Date of birth or age-- Sex-- Medical record number-- Examination date and time-- Referring physician+- examination identity and status;+- clinical indication as supplied;+- technique and documented limitations;+- comparison-source references;+- findings and impression authored by the qualified interpreting professional;+- nonroutine-communication record references;+- amendments/corrections and report version.-**2. Procedure/Examination**-- Specific examination performed-- Anatomical region-- Laterality (right, left, bilateral)-- Technique and protocol-- Example: "MRI Brain without and with Contrast"+Do not:-**3. Clinical Indication**-- Reason for examination-- Relevant clinical history-- Specific clinical question-- ICD-10 codes (when required)-- Example: "Headache and visual disturbances. Rule out intracranial mass."+- inspect or interpret images;+- generate normal findings, pertinent negatives, differential diagnoses, urgency, follow-up, or management recommendations;+- select BI-RADS, LI-RADS, Lung-RADS, PI-RADS, or another category;+- infer that a preliminary report is final;+- initiate, simulate, or document a communication that did not occur.-**4. Comparison**-- Prior relevant imaging studies-- Dates of prior studies-- Modality of prior studies-- Availability for comparison-- Example: "Comparison: CT head without contrast from 6 months prior (January 15, 2023)"+The responsible radiologist and organization control report content, communication, correction, and signature.-**5. Technique**-- Imaging parameters and protocol-- Contrast administration details:- - Type (iodinated, gadolinium)- - Route (IV, oral, rectal)- - Volume administered- - Timing of imaging-- Technical quality statement-- Radiation dose (for CT)-- Limitations or technical issues-- Example:- ```- Technique: Multiplanar T1 and T2-weighted sequences were obtained through- the brain without and with IV contrast. 15 mL of gadolinium-based contrast- agent was administered intravenously. Technical quality is adequate.- ```+## Pathology-**6. Findings**-- Systematic description of imaging findings-- Organized by anatomical region or organ system-- Measurements of abnormalities (size, volume)-- Specific descriptive terminology-- Pertinent positive findings-- Relevant negative findings-- Comparison to prior studies when available+CAP publishes and updates organ- and specimen-specific Cancer Protocols. The CAP template page showed protocol updates on 17 June 2026 and a Breast DCIS correction on 24 June 2026 when checked. Protocol versions and required/core or conditional elements can change.-**Organization approaches:**-- Organ-by-organ (for abdomen/pelvis)-- Region-by-region (for chest)-- System-by-system (for spine)-- Compartment-by-compartment (for musculoskeletal)+Use `assets/pathology_report_template.json` only after a qualified pathologist selects:-**7. Impression/Conclusion**-- Summary of key findings-- Diagnosis or differential diagnosis-- Answers to clinical question-- Level of concern or urgency-- Comparison to prior (improved, stable, worsened)-- Recommendations for further imaging or clinical management-- Clear and concise (often numbered list)+- exact organ/site and specimen/procedure;+- current CAP protocol title and version, if applicable;+- applicable biomarker protocol and staging edition;+- local laboratory/reporting requirements.-Example:-```-IMPRESSION:-1. 3.2 cm enhancing mass in the right frontal lobe with surrounding vasogenic- edema, most consistent with high-grade glioma. Metastasis cannot be excluded.- Clinical correlation and tissue sampling recommended.-2. No acute intracranial hemorrhage or herniation.-3. Recommend neurosurgical consultation.-```+For CAP synoptic reporting within its scope, core and conditionally required data elements are represented as data-element/response pairs; applicability depends on the exact current protocol.-**8. Critical Results Communication**-- Urgent or unexpected findings requiring immediate action-- Direct communication to ordering provider documented-- Time, date, and recipient of verbal communication-- Example: "Critical result: Acute pulmonary embolism. Dr. Smith paged at 14:35 on [date]."+Do not:-### Structured Reporting Systems+- generate a gross or microscopic observation;+- determine diagnosis, grade, stage, margin status, biomarker interpretation, or adequacy;+- apply a generic cancer checklist in place of the current exact protocol;+- convert `cannot be determined` or `not applicable` into a definitive value;+- create a signature or final diagnosis.-#### Lung-RADS (Lung CT Screening Reporting and Data System)+## Laboratory-Used for lung cancer screening CT interpretation.+For applicable US nonwaived testing, 42 CFR 493.1291 addresses accurate and timely transmission, required report information, referral-laboratory handling, accessibility, and corrected reports. The exact regulation and laboratory policy control.-**Categories:**-- **Lung-RADS 0**: Incomplete - additional imaging needed-- **Lung-RADS 1**: Negative - no nodules, definitely benign nodules-- **Lung-RADS 2**: Benign appearance or behavior - nodules with very low likelihood of malignancy-- **Lung-RADS 3**: Probably benign - short-interval follow-up suggested-- **Lung-RADS 4A**: Suspicious - 3-month follow-up or PET/CT-- **Lung-RADS 4B**: Very suspicious - 3-month follow-up or PET/CT, consider biopsy-- **Lung-RADS 4X**: Very suspicious with additional features, consider biopsy+Use `assets/lab_report_template.json` only to map results already released by the performing laboratory or verified source system. Preserve:-**Management recommendations included for each category**+- report status and version;+- performing laboratory/source-system reference;+- specimen and test identifiers held in the authorized system, not copied into examples;+- result, units, reference interval, flags, method, and comments exactly as released;+- correction link to both original and corrected reports;+- documented notification reference when one exists.-#### BI-RADS (Breast Imaging Reporting and Data System)+Do not:-Standardized lexicon for breast imaging (mammography, ultrasound, MRI).+- calculate, normalize, convert, interpret, flag, or suppress a patient result;+- supply a reference interval or “critical” threshold;+- infer specimen adequacy;+- recommend follow-up or treatment;+- alter a referral laboratory’s result or interpretation;+- release or sign a report.-**Categories:**-- **BI-RADS 0**: Incomplete - need additional imaging-- **BI-RADS 1**: Negative - no abnormalities-- **BI-RADS 2**: Benign findings-- **BI-RADS 3**: Probably benign - short-interval follow-up (6 months)-- **BI-RADS 4**: Suspicious - biopsy recommended- - 4A: Low suspicion- - 4B: Moderate suspicion- - 4C: High suspicion-- **BI-RADS 5**: Highly suggestive of malignancy - biopsy recommended-- **BI-RADS 6**: Known biopsy-proven malignancy+## Privacy and record integrity-**Descriptors:**-- Mass: Shape, margin, density-- Calcifications: Morphology, distribution-- Asymmetry: Type and characteristics-- Associated features--#### LI-RADS (Liver Imaging Reporting and Data System)--For reporting liver observations in patients at risk for hepatocellular carcinoma.--**Categories:**-- **LI-RADS 1**: Definitely benign-- **LI-RADS 2**: Probably benign-- **LI-RADS 3**: Intermediate probability of malignancy-- **LI-RADS 4**: Probably HCC-- **LI-RADS 5**: Definitely HCC-- **LI-RADS M**: Probably or definitely malignant, not HCC-specific-- **LI-RADS TIV**: Tumor in vein--**Major features assessed:**-- Size-- Enhancement pattern (arterial phase hyperenhancement, washout)-- Capsule appearance-- Threshold growth--#### PI-RADS (Prostate Imaging Reporting and Data System)--For multiparametric MRI of the prostate.--**Assessment categories:**-- **PI-RADS 1**: Very low - clinically significant cancer highly unlikely-- **PI-RADS 2**: Low - clinically significant cancer unlikely-- **PI-RADS 3**: Intermediate - equivocal-- **PI-RADS 4**: High - clinically significant cancer likely-- **PI-RADS 5**: Very high - clinically significant cancer highly likely--**Evaluation:**-- Peripheral zone: DWI/ADC primary determinant-- Transition zone: T2-weighted primary determinant-- DCE (dynamic contrast-enhanced): Used for PI-RADS 3 lesions in peripheral zone--### RadLex and Standardized Terminology--**RadLex** is a comprehensive lexicon for radiology developed by the Radiological Society of North America (RSNA).--**Benefits:**-- Standardized terminology-- Improved communication-- Enables data mining and analytics-- Facilitates decision support systems-- Consistent report structure--**Common RadLex terms:**-- Anatomical structures-- Imaging observations-- Disease entities-- Procedures--### Radiological Measurements--**Linear measurements:**-- Use bidimensional (length × width) or tridimensional (length × width × height)-- Report largest dimension for nodules/masses-- Consistent measurement methodology for follow-up-- Perpendicular measurements when possible--**Volumetric measurements:**-- More accurate for follow-up of irregular lesions-- Automated or semi-automated software-- Particularly useful for lung nodules--**Response assessment:**-- RECIST 1.1 (Response Evaluation Criteria in Solid Tumors)- - Target lesions: sum of longest diameters (maximum 5 lesions, 2 per organ)- - Complete response, partial response, stable disease, progressive disease--## Pathology Reporting Standards--### College of American Pathologists (CAP) Protocols--CAP cancer protocols provide standardized synoptic reporting templates for cancer specimens.--#### Synoptic Reporting Elements--**Core elements for all cancer specimens:**--**1. Specimen Information**-- Procedure type (biopsy, excision, resection)-- Specimen laterality-- Specimen integrity and adequacy--**2. Tumor Site**-- Anatomical site and subsite-- Precise location within organ--**3. Tumor Size**-- Greatest dimension in cm-- Additional dimensions if 3D measurement relevant-- Method of measurement (gross vs. microscopic)--**4. Histologic Type**-- WHO classification-- Specific subtype-- Percentage of each component in mixed tumors--**5. Histologic Grade**-- Grading system used (e.g., Nottingham, Fuhrman, Gleason)-- Grade category (well, moderately, poorly differentiated OR G1, G2, G3)-- Individual component scores if applicable--**6. Extent of Invasion**-- Depth of invasion (measured in mm)-- Involvement of adjacent structures-- Lymphovascular invasion (present/not identified)-- Perineural invasion (present/not identified)--**7. Margins**-- Closest margin distance-- Margin status for each margin assessed (negative/positive)-- Specific margin(s) involved if positive--**8. Lymph Nodes**-- Number of lymph nodes examined-- Number of lymph nodes with metastasis-- Size of largest metastatic deposit-- Extranodal extension (present/absent)--**9. Pathologic Stage (pTNM)**-- pT: Primary tumor extent-- pN: Regional lymph nodes-- pM: Distant metastasis (if known)-- AJCC Cancer Staging Manual edition used--**10. Additional Findings**-- Treatment effect (if post-neoadjuvant therapy)-- Associated lesions (dysplasia, carcinoma in situ)-- Background tissue (cirrhosis, inflammation)--**11. Ancillary Studies**-- Immunohistochemistry results-- Molecular/genetic testing results-- Biomarker status (e.g., ER, PR, HER2 for breast; MSI for colon)-- FISH or other cytogenetic results--#### Organ-Specific CAP Protocols--**Breast Cancer:**-- Histologic type (invasive ductal, lobular, special types)-- Nottingham grade (tubule formation, nuclear pleomorphism, mitotic count)-- ER/PR status (percentage and intensity)-- HER2 status (IHC score, FISH if needed)-- Ki-67 proliferation index-- DCIS component (if present)-- Response to neoadjuvant therapy (residual cancer burden)--**Colorectal Cancer:**-- Histologic type (adenocarcinoma, mucinous, etc.)-- Grade-- Depth of invasion (into submucosa, muscularis propria, pericolic tissue, etc.)-- Tumor deposits-- Lymph nodes (number positive/total examined)-- Margins (proximal, distal, radial/circumferential)-- MSI/MMR status-- KRAS, NRAS, BRAF mutations--**Prostate Cancer:**-- Gleason score (primary + secondary pattern)-- Grade group (1-5)-- Percentage of tissue involved-- Extraprostatic extension-- Seminal vesicle invasion-- Surgical margin status-- Lymph nodes if sampled--**Lung Cancer:**-- Histologic type (adenocarcinoma, squamous, small cell, etc.)-- Grade (for NSCLC)-- Invasion depth-- Visceral pleural invasion-- Distance to margins-- Lymph nodes-- Molecular markers (EGFR, ALK, ROS1, PD-L1)--### Gross Pathology Description--**Essential elements:**-- Specimen labeling and identification-- Type of specimen-- Dimensions and weight-- Orientation markers (if present)-- External surface description-- Cut surface appearance-- Lesion description:- - Size (3 dimensions)- - Location- - Color- - Consistency- - Borders (well-circumscribed, infiltrative)- - Distance to margins-- Sampling approach (how tissue was sectioned and submitted)--**Example:**-```-GROSS DESCRIPTION:-Received fresh, labeled with patient name and "left breast, lumpectomy" is an-oriented lumpectomy specimen measuring 8.5 x 6.0 x 4.0 cm, with a suture-indicating superior margin. Inking: superior - blue, inferior - black, medial --green, lateral - red, anterior - orange, posterior - yellow. Serially sectioned-to reveal a firm, gray-white mass measuring 2.1 x 1.8 x 1.5 cm, located 2.5 cm-from superior, 3.0 cm from inferior, 2.0 cm from medial, 3.5 cm from lateral,-1.5 cm from anterior, and 1.8 cm from posterior margins. Representative sections-submitted as follows: A1-A3 tumor, A4 superior margin, A5 medial margin, A6-posterior margin.-```--### Microscopic Description--**Key elements:**-- Architectural pattern-- Cellular characteristics- - Cell type- - Nuclear features (size, shape, chromatin, nucleoli)- - Cytoplasmic features- - Mitotic activity-- Degree of differentiation-- Invasion pattern-- Special features (necrosis, hemorrhage, calcification)-- Stroma and background tissue-- Lymphovascular or perineural invasion-- Margins (distance and status)-- Lymph nodes (description of metastases)--### Frozen Section Reporting--**Indications:**-- Intraoperative diagnosis-- Margin assessment-- Lymph node evaluation-- Tissue triage--**Report format:**-- "Frozen section diagnosis" clearly labeled-- Intraoperative consultation note-- Time of frozen section-- Specimen description-- Frozen section diagnosis-- Note: "Permanent sections to follow"--**Frozen section disclaimers:**-- Limited by frozen artifact-- Final diagnosis on permanent sections-- Defer to permanent sections for definitive diagnosis--### Diagnostic Certainty Language--**Definitive:**-- "Consistent with..."-- "Diagnostic of..."-- "Positive for..."--**Probable:**-- "Consistent with..."-- "Favor..."-- "Most likely..."--**Possible:**-- "Suggestive of..."-- "Cannot exclude..."-- "Differential diagnosis includes..."--**Defer:**-- "Defer to..."-- "Recommend..."-- "Additional studies pending..."--## Laboratory Reporting Standards--### Clinical Laboratory Standards Institute (CLSI) Guidelines--CLSI provides standards for laboratory testing and reporting.--#### Laboratory Report Components--**1. Patient Demographics**-- Patient name and identifier-- Date of birth or age-- Sex-- Ordering provider--**2. Specimen Information**-- Specimen type (blood, serum, plasma, urine, CSF, etc.)-- Collection date and time-- Received date and time-- Specimen condition-- Fasting status (if relevant)--**3. Test Information**-- Test name (full, not just abbreviation)-- Test code-- Methodology-- Accession or specimen number--**4. Results**-- Quantitative value with units-- Qualitative result (positive/negative, detected/not detected)-- Reference range or interval-- Flags for abnormal results- - H = High- - L = Low- - Critical or panic values highlighted--**5. Reference Intervals**-- Age-specific-- Sex-specific-- Population-specific (when relevant)-- Method-specific-- Units clearly stated--**Example:**-```-Test: Hemoglobin A1c-Result: 8.2% (H)-Reference Range: 4.0-5.6% (non-diabetic)-Method: HPLC-Interpretation: Consistent with poorly controlled diabetes-```--**6. Interpretative Comments**-- When result requires context-- Suggests additional testing-- Explains interferences or limitations-- Provides clinical guidance--**7. Quality Control**-- Delta checks (comparison to prior values)-- Critical values and read-back procedure-- Specimen quality issues (hemolysis, lipemia, icterus)-- Dilutions performed-- Repeat testing if needed--### LOINC (Logical Observation Identifiers Names and Codes)--Standard coding system for laboratory and clinical observations.--**LOINC code components:**-- Component (analyte measured)-- Property (mass, substance concentration, etc.)-- Timing (point in time, 24-hour)-- System (specimen type)-- Scale (quantitative, ordinal, nominal)-- Method (when relevant)--**Example:**-- Hemoglobin A1c in Blood: 4548-4-- Glucose in Serum/Plasma: 2345-7-- Creatinine in Serum/Plasma: 2160-0--### Critical Value Reporting--**Definition:** Results that indicate life-threatening conditions requiring immediate clinical action.--**Critical value examples:**-- Glucose: <40 mg/dL or >500 mg/dL-- Potassium: <2.5 mEq/L or >6.5 mEq/L-- Sodium: <120 mEq/L or >160 mEq/L-- Calcium: <6.0 mg/dL or >13.0 mg/dL-- WBC: <1.0 × 10³/μL or >50 × 10³/μL-- Hemoglobin: <5.0 g/dL-- Platelets: <20 × 10³/μL-- INR: >5.0 (on warfarin)-- Positive blood culture-- Positive CSF culture or gram stain--**Critical value procedure:**-1. Result identified by laboratory-2. Immediate contact with ordering provider or designee-3. Read-back verification-4. Documentation:- - Date and time- - Person contacted- - Person receiving notification- - Test and result-5. Follow facility policy for unable to reach provider--### Microbiology Reporting--**Culture reports:**-- Specimen type and source-- Organisms identified-- Quantity (light, moderate, heavy growth)-- Antimicrobial susceptibility results-- Interpretation (susceptible, intermediate, resistant)-- MIC values when applicable--**Gram stain reports:**-- Bacteria present (Gram-positive/negative, morphology)-- Quantity and cellular context-- WBCs or other cells present--**Preliminary reports:**-- Issued before final identification-- Clearly labeled "PRELIMINARY"-- Final report to follow--**Final reports:**-- Definitive organism identification-- Complete susceptibility panel-- Interpretative comments--### Molecular Pathology/Genomics Reporting--**Components:**-- Gene(s) tested-- Variant(s) detected-- Classification (pathogenic, likely pathogenic, VUS, likely benign, benign)-- Allele frequency-- Methodology (NGS, Sanger sequencing, PCR, etc.)-- Reference sequence-- Clinical significance and interpretation-- Recommendations (treatment implications, family testing)-- Limitations of testing--**Example:**-```-Test: BRCA1/BRCA2 Full Gene Sequencing-Result: PATHOGENIC VARIANT DETECTED-Gene: BRCA1-Variant: c.68_69delAG (p.Glu23ValfsTer17)-Classification: Pathogenic-Interpretation: This variant is associated with increased risk of breast and-ovarian cancer. Genetic counseling and risk-reducing strategies recommended.-Family testing should be considered.-```--### Point-of-Care Testing (POCT)--**Requirements:**-- Same quality standards as central laboratory-- Operator competency documentation-- Quality control documentation-- Maintenance records-- Result documentation in medical record--**Common POCT:**-- Blood glucose-- Hemoglobin/hematocrit-- INR-- Blood gas-- Pregnancy test-- Urinalysis-- Rapid strep-- Influenza--## Quality Indicators for Diagnostic Reports--### Radiology Quality Metrics--- Report turnaround time (routine vs. urgent)-- Critical result communication time-- Report error rates-- Addendum rate-- Referring physician satisfaction--**Benchmarks:**-- Routine reports: <24 hours-- Urgent reports: <4 hours-- STAT reports: <1 hour-- Critical findings: Immediate verbal communication--### Pathology Quality Metrics--- Turnaround time (TAT) for different specimen types-- Frozen section accuracy-- Amendment rate-- Specimen adequacy rate-- Immunohistochemistry QC--**TAT benchmarks:**-- Surgical pathology routine: 2-3 days-- Surgical pathology complex: 5-7 days-- Cytology: 1-2 days-- Frozen section: 15-20 minutes intraoperatively--### Laboratory Quality Metrics--- TAT from collection to result-- Critical value notification time-- Specimen rejection rate-- Proficiency testing performance-- Delta check failure rate--**TAT benchmarks:**-- STAT laboratory: <60 minutes-- Routine laboratory: 2-4 hours-- Send-out tests: Per reference laboratory-------This reference provides comprehensive standards for diagnostic reporting across radiology, pathology, and laboratory medicine. Refer to these guidelines to ensure reports meet professional standards and regulatory requirements.+Operational diagnostic reports often require identifiers for positive patient matching. This skill does not process those production records. It accepts only synthetic, de-identified, or aggregate manifests. Use institution-controlled systems for real clinical records and follow applicable access, retention, correction, audit, and disclosure procedures.+Every draft scaffold must remain `DRAFT_NOT_FOR_CLINICAL_USE` until the responsible licensed service reviews and completes it in its authorized system.diff --git a/skills/clinical-reports/references/medical_terminology.md b/skills/clinical-reports/references/medical_terminology.mdindex 1f0cf038..ed9dd95e 100644--- a/skills/clinical-reports/references/medical_terminology.md+++ b/skills/clinical-reports/references/medical_terminology.md@@ -1,588 +1,84 @@-# Medical Terminology and Coding Standards+# Versioned Terminology and Schema Checks-## Standard Nomenclature Systems+Terminology selection and coding are clinical/regulatory tasks. The local checker validates manifest shape and code syntax; it does not confirm that a code exists, is current, matches a display, or is clinically appropriate.-### SNOMED CT (Systematized Nomenclature of Medicine - Clinical Terms)+## Required manifest fields-**Purpose:** Comprehensive clinical terminology for electronic health records+For every coded item record:-**Coverage:**-- Clinical findings-- Symptoms-- Diagnoses-- Procedures-- Body structures-- Organisms-- Substances-- Pharmaceutical products-- Specimens+- `system`: controlled system name;+- `system_uri`: canonical identifier supplied by the implementing organization;+- `code`;+- `display`;+- `version`;+- `language`;+- `source_fact_id`;+- `coding_status`: `verified_by_qualified_reviewer` or `unverified`;+- `verified_by_role` and `verified_at` when verified.-**Structure:**-- Concepts with unique identifiers-- Descriptions (preferred and synonyms)-- Relationships between concepts-- Hierarchical organization+Do not infer a code from narrative text.-**Example:**-- Concept: Myocardial infarction-- SNOMED CT code: 22298006-- Parent: Heart disease-- Children: Acute myocardial infarction, Old myocardial infarction+## MedDRA-**Benefits:**-- Enables semantic interoperability-- Supports clinical decision support-- Facilitates data analytics-- International standard+- ICH developed MedDRA for regulatory information about human medical products.+- MedDRA 29.0 was released in March 2026, with a transition date of 4 May 2026.+- MedDRA uses a multiaxial hierarchy and version-specific currency/relationships.+- State exact version and language.+- Use the study/sponsor-authorized version, official licensed files, and current Points to Consider.+- Do not assume the newest release is the required release.-### LOINC (Logical Observation Identifiers Names and Codes)+The aggregate adverse-event formatter accepts SOC and PT labels as supplied and does not validate hierarchy, codes, or coding quality.-**Purpose:** Universal code system for laboratory and clinical observations+## LOINC-**Components of LOINC code:**-1. **Component** (analyte or measurement): What is measured-2. **Property**: What characteristic (mass, volume, etc.)-3. **Timing**: When measured (point in time, 24-hour)-4. **System**: Specimen or system (serum, urine, arterial blood)-5. **Scale**: Type of result (quantitative, ordinal, nominal)-6. **Method**: How measured (when relevant to interpretation)+LOINC identifies health observations, measurements, and documents. LOINC 2.82 was released 24 February 2026 and was current when checked.-**Examples:**-- **Glucose [Mass/volume] in Serum or Plasma**: 2345-7- - Component: Glucose- - Property: Mass concentration- - Timing: Point in time- - System: Serum/Plasma- - Scale: Quantitative+- A valid-looking `number-checkdigit` string is only syntactic evidence.+- The method, property, timing, system/specimen, scale, and version can affect meaning.+- Verify against the official release or authorized terminology service.+- Review the LOINC license and third-party content terms.-- **Hemoglobin A1c/Hemoglobin.total in Blood**: 4548-4- - Component: Hemoglobin A1c/Hemoglobin.total- - Property: Mass fraction- - Timing: Point in time- - System: Blood- - Scale: Quantitative+## SNOMED CT-**LOINC Parts:**-- Document types-- Survey instruments-- Clinical attachments-- Radiology codes-- Pathology codes+SNOMED CT concept identifiers are not clinically validated by their numeric shape.-### ICD-10-CM (International Classification of Diseases, 10th Revision, Clinical Modification)+- Use the applicable international edition, national extension, and effective date.+- Verify concept activity, module, description, and reference-set membership.+- Comply with SNOMED International and national licensing/distribution requirements.+- Do not embed or redistribute licensed terminology content through these assets.-**Purpose:** Diagnosis and procedure coding for billing, epidemiology, and health statistics+## ICD-10-CM-**Structure:**-- Alphanumeric codes (3-7 characters)-- First character: letter (except U)-- Characters 2-3: numbers-- Characters 4-7: alphanumeric (decimal after 3rd character)-- Laterality, severity, encounter type specified+ICD-10-CM changes by fiscal-year release and may require encounter, laterality, or placeholder characters.-**Code structure example:**-- **S72.001A**: Fracture of unspecified part of neck of right femur, initial encounter- - S: Injury category- - 72: Femur- - 001: Unspecified part of neck- - A: Initial encounter for closed fracture- - Right side indicated by 1 in 5th position+- Record the exact release and applicable jurisdiction.+- Verify with official CDC/CMS files and coding guidance.+- A regex match cannot establish billability, specificity, sequencing, or clinical correctness.+- This skill does not support billing or reimbursement decisions.-**Common categories:**-- A00-B99: Infectious diseases-- C00-D49: Neoplasms-- E00-E89: Endocrine, nutritional, metabolic-- F01-F99: Mental and behavioral-- G00-G99: Nervous system-- I00-I99: Circulatory system-- J00-J99: Respiratory system-- K00-K95: Digestive system-- M00-M99: Musculoskeletal-- N00-N99: Genitourinary-- S00-T88: Injury, poisoning+## UCUM and units-**Seventh character extensions:**-- A: Initial encounter-- D: Subsequent encounter-- S: Sequela+Record the original unit exactly and, when an organization uses UCUM, record the verified UCUM expression separately. Do not automatically convert units in a report draft.-**Placeholder X:**-- Used when code requires 7th character but fewer than 6 characters-- Example: T36.0X5A (Adverse effect of penicillins, initial encounter)+Any conversion must have:-**Combination codes:**-- Single code describing two diagnoses or diagnosis with manifestation-- Example: E11.21 (Type 2 diabetes with diabetic nephropathy)+- an authorized rule and version;+- original value/unit;+- converted value/unit;+- precision/rounding rule;+- source-fact and reviewer traceability.-### CPT (Current Procedural Terminology)+The consistency checker flags missing or inconsistent unit labels but performs no clinical conversion.-**Purpose:** Procedure and service coding for billing+## Optional local dictionary-**Maintained by:** American Medical Association (AMA)+`terminology_validator.py --dictionary <file.json>` can compare code/display/version tuples with a caller-supplied local dictionary. The dictionary must be an authorized bounded JSON file.-**Categories:**-- **Category I**: Procedures and services (5-digit numeric codes)-- **Category II**: Performance measurement (4 digits + F)-- **Category III**: Emerging technology (4 digits + T)+A match means only “matched this supplied dictionary.” It does not prove:-**Category I Sections:**-- 00100-01999: Anesthesia-- 10000-69990: Surgery-- 70000-79999: Radiology-- 80000-89999: Pathology and Laboratory-- 90000-99999: Medicine-- 99000-99607: Evaluation and Management (E/M)--**E/M Codes (commonly used):**-- **99201-99215**: Office visits (new and established)-- **99221-99239**: Hospital inpatient services-- **99281-99285**: Emergency department visits-- **99291-99292**: Critical care-- **99304-99318**: Nursing facility services--**Modifiers:**-- Two-digit codes appended to CPT codes-- Indicate service was altered but not changed-- Examples:- - -25: Significant, separately identifiable E/M service- - -50: Bilateral procedure- - -59: Distinct procedural service- - -76: Repeat procedure by same physician- - -RT/LT: Right/Left side--### RxNorm--**Purpose:** Normalized names for clinical drugs and drug delivery devices--**Structure:**-- Includes brand and generic names-- Dose forms-- Strengths-- Links to other drug vocabularies (NDC, SNOMED CT)--**Example:**-- Concept: Amoxicillin 500 MG Oral Capsule-- RxNorm CUI: 308191-- Ingredients: Amoxicillin-- Strength: 500 MG-- Dose Form: Oral Capsule--## Medical Abbreviations--### Acceptable Standard Abbreviations--**Time:**-- q: every (q4h = every 4 hours)-- qd: daily (avoid - use "daily")-- bid: twice daily-- tid: three times daily-- qid: four times daily-- qhs: at bedtime-- prn: as needed-- ac: before meals-- pc: after meals-- hs: at bedtime--**Routes:**-- PO: by mouth (per os)-- IV: intravenous-- IM: intramuscular-- SC/SQ/subcut: subcutaneous-- SL: sublingual-- PR: per rectum-- NG: nasogastric-- GT: gastrostomy tube-- TD: transdermal-- inh: inhaled--**Frequency:**-- stat: immediately-- now: immediately-- continuous: without interruption-- PRN: as needed--**Laboratory:**-- CBC: complete blood count-- BMP: basic metabolic panel-- CMP: comprehensive metabolic panel-- LFTs: liver function tests-- PT/INR: prothrombin time/international normalized ratio-- PTT/aPTT: partial thromboplastin time/activated PTT-- ESR: erythrocyte sedimentation rate-- CRP: C-reactive protein-- ABG: arterial blood gas-- UA: urinalysis-- HbA1c: hemoglobin A1c--**Diagnoses:**-- HTN: hypertension-- DM: diabetes mellitus-- CHF: congestive heart failure-- CAD: coronary artery disease-- COPD: chronic obstructive pulmonary disease-- CVA: cerebrovascular accident-- MI: myocardial infarction-- PE: pulmonary embolism-- DVT: deep vein thrombosis-- UTI: urinary tract infection-- CKD: chronic kidney disease-- ESRD: end-stage renal disease--**Physical Examination:**-- HEENT: head, eyes, ears, nose, throat-- PERRLA: pupils equal, round, reactive to light and accommodation-- EOMI: extraocular movements intact-- JVP: jugular venous pressure-- RRR: regular rate and rhythm-- CTAB: clear to auscultation bilaterally-- BS: bowel sounds or breath sounds (context dependent)-- NT/ND: non-tender, non-distended-- FROM: full range of motion--**Vital Signs:**-- BP: blood pressure-- HR: heart rate-- RR: respiratory rate-- T or Temp: temperature-- SpO2: oxygen saturation-- Wt: weight-- Ht: height-- BMI: body mass index--### Do Not Use Abbreviations (Joint Commission)--**Prohibited abbreviations:**--| Abbreviation | Intended Meaning | Problem | Use Instead |-|--------------|------------------|---------|-------------|-| U | Unit | Mistaken for 0, 4, or cc | Write "unit" |-| IU | International Unit | Mistaken for IV or 10 | Write "international unit" |-| Q.D., QD, q.d., qd | Daily | Mistaken for each other | Write "daily" |-| Q.O.D., QOD, q.o.d., qod | Every other day | Mistaken for QD or QID | Write "every other day" |-| Trailing zero (X.0 mg) | X mg | Decimal point missed | Never write zero after decimal (write X mg) |-| Lack of leading zero (.X mg) | 0.X mg | Decimal point missed | Always write zero before decimal (write 0.X mg) |-| MS, MSO4, MgSO4 | Morphine sulfate or magnesium sulfate | Confused for each other | Write "morphine sulfate" or "magnesium sulfate" |--**Additional problematic abbreviations:**-- µg: micrograms (mistaken for mg) → write "mcg"-- cc: cubic centimeters → write "mL"-- hs: half-strength or hour of sleep → write "half-strength" or "bedtime"-- TIW: three times a week → write "three times weekly"-- SC, SQ: subcutaneous → write "subcut" or "subcutaneous"-- D/C: discharge or discontinue → write full word-- AS, AD, AU: left ear, right ear, both ears → write "left ear," "right ear," "both ears"-- OS, OD, OU: left eye, right eye, both eyes → write "left eye," "right eye," "both eyes"--## Medication Nomenclature--### Generic vs. Brand Names--**Best practice:** Use generic names in medical documentation--**Examples:**-- Acetaminophen (generic) vs. Tylenol (brand)-- Ibuprofen (generic) vs. Advil, Motrin (brand)-- Atorvastatin (generic) vs. Lipitor (brand)-- Metformin (generic) vs. Glucophage (brand)-- Lisinopril (generic) vs. Zestril, Prinivil (brand)--**When to include brand:**-- Patient education (recognition)-- Novel drugs without generic-- Narrow therapeutic index drugs with bioequivalence issues-- Biologic products--### Dosage Forms--**Solid oral:**-- Tablet-- Capsule-- Caplet-- Chewable tablet-- Orally disintegrating tablet (ODT)-- Extended-release (ER, XR, SR)-- Delayed-release (DR)--**Liquid oral:**-- Solution-- Suspension-- Syrup-- Elixir-- Drops--**Parenteral:**-- Solution for injection-- Powder for injection (reconstituted)-- Intravenous infusion-- Intramuscular injection-- Subcutaneous injection--**Topical:**-- Cream-- Ointment-- Gel-- Lotion-- Paste-- Patch (transdermal)-- Foam-- Spray--**Other:**-- Suppository (rectal, vaginal)-- Inhaler (MDI, DPI)-- Nebulizer solution-- Ophthalmic (drops, ointment)-- Otic (drops)-- Nasal spray--### Prescription Writing Elements--**Complete prescription includes:**-1. Patient name and DOB-2. Date-3. Medication name (generic preferred)-4. Strength/concentration-5. Dosage form-6. Quantity to dispense-7. Directions (Sig)-8. Number of refills-9. Prescriber signature and credentials-10. DEA number (for controlled substances)--**Sig (Directions for use):**-- Clear, specific instructions-- Route of administration-- Frequency-- Duration (if applicable)-- Special instructions--**Example:**-- "Take one tablet by mouth twice daily with food for 10 days"-- "Apply thin layer to affected area three times daily"-- "Instill 1 drop in each eye every 4 hours while awake"--## Anatomical Terminology--### Directional Terms--**Superior/Inferior:**-- Superior: toward the head-- Inferior: toward the feet-- Cranial: toward the head-- Caudal: toward the tail/feet--**Anterior/Posterior:**-- Anterior: toward the front-- Posterior: toward the back-- Ventral: toward the belly-- Dorsal: toward the back--**Medial/Lateral:**-- Medial: toward the midline-- Lateral: away from the midline--**Proximal/Distal:**-- Proximal: closer to the trunk or point of origin-- Distal: farther from the trunk or point of origin--**Superficial/Deep:**-- Superficial: toward the surface-- Deep: away from the surface--### Body Planes--**Sagittal plane:** Divides body into right and left-- Midsagittal: exactly through midline-- Parasagittal: parallel to midline--**Coronal (frontal) plane:** Divides body into anterior and posterior--**Transverse (axial) plane:** Divides body into superior and inferior--### Anatomical Position--- Standing upright-- Feet parallel-- Arms at sides-- Palms facing forward-- Head facing forward--### Regional Terms--**Head and Neck:**-- Cephalic: head-- Frontal: forehead-- Orbital: eye-- Nasal: nose-- Oral: mouth-- Cervical: neck-- Occipital: back of head--**Trunk:**-- Thoracic: chest-- Abdominal: abdomen-- Pelvic: pelvis-- Lumbar: lower back-- Sacral: sacrum--**Extremities:**-- Brachial: arm-- Antebrachial: forearm-- Carpal: wrist-- Manual: hand-- Digital: fingers/toes-- Femoral: thigh-- Crural: leg-- Tarsal: ankle-- Pedal: foot--## Laboratory Units and Conversions--### Common Laboratory Units--**Hematology:**-- RBC: × 10⁶/μL or × 10¹²/L-- WBC: × 10³/μL or × 10⁹/L-- Hemoglobin: g/dL or g/L-- Hematocrit: % or fraction-- Platelets: × 10³/μL or × 10⁹/L-- MCV: fL-- MCHC: g/dL or g/L--**Chemistry:**-- Glucose: mg/dL or mmol/L-- BUN: mg/dL or mmol/L-- Creatinine: mg/dL or μmol/L-- Sodium, potassium, chloride: mEq/L or mmol/L-- Calcium: mg/dL or mmol/L-- Albumin: g/dL or g/L-- Bilirubin: mg/dL or μmol/L-- Cholesterol: mg/dL or mmol/L--**Therapeutic Drug Levels:**-- Usually: mcg/mL, ng/mL, or μmol/L--### Unit Conversions (Selected)--**Glucose:**-- mg/dL ÷ 18 = mmol/L-- mmol/L × 18 = mg/dL--**Creatinine:**-- mg/dL × 88.4 = μmol/L-- μmol/L ÷ 88.4 = mg/dL--**Bilirubin:**-- mg/dL × 17.1 = μmol/L-- μmol/L ÷ 17.1 = mg/dL--**Cholesterol:**-- mg/dL × 0.0259 = mmol/L-- mmol/L × 38.67 = mg/dL--**Hemoglobin:**-- g/dL × 10 = g/L-- g/L ÷ 10 = g/dL--## Grading and Staging Systems--### Cancer Staging (TNM)--**T (Primary Tumor):**-- TX: Cannot be assessed-- T0: No evidence of primary tumor-- Tis: Carcinoma in situ-- T1-T4: Size and/or extent of primary tumor--**N (Regional Lymph Nodes):**-- NX: Cannot be assessed-- N0: No regional lymph node metastasis-- N1-N3: Involvement of regional lymph nodes--**M (Distant Metastasis):**-- M0: No distant metastasis-- M1: Distant metastasis present--**Stage Grouping:**-- Stage 0: Tis N0 M0-- Stage I-III: Various T and N combinations, M0-- Stage IV: Any T, any N, M1--### NYHA Heart Failure Classification--- **Class I**: No limitation. Ordinary physical activity does not cause symptoms-- **Class II**: Slight limitation. Comfortable at rest, ordinary activity causes symptoms-- **Class III**: Marked limitation. Comfortable at rest, less than ordinary activity causes symptoms-- **Class IV**: Unable to carry out any physical activity without symptoms. Symptoms at rest--### Child-Pugh Score (Liver Disease)--**Parameters:** Bilirubin, albumin, INR, ascites, encephalopathy--**Classes:**-- **Class A (5-6 points)**: Well-compensated-- **Class B (7-9 points)**: Significant functional compromise-- **Class C (10-15 points)**: Decompensated--### Glasgow Coma Scale--**Eye Opening (1-4):**-- 4: Spontaneous-- 3: To speech-- 2: To pain-- 1: None--**Verbal Response (1-5):**-- 5: Oriented-- 4: Confused-- 3: Inappropriate words-- 2: Incomprehensible sounds-- 1: None--**Motor Response (1-6):**-- 6: Obeys commands-- 5: Localizes pain-- 4: Withdraws from pain-- 3: Abnormal flexion-- 2: Extension-- 1: None--**Total Score:** 3-15 (3 = worst, 15 = best)-- Severe: ≤8-- Moderate: 9-12-- Mild: 13-15--## Medical Prefixes and Suffixes--### Common Prefixes--- **a-/an-**: without, absence (anemia, aphasia)-- **brady-**: slow (bradycardia)-- **dys-**: abnormal, difficult (dyspnea, dysuria)-- **hyper-**: excessive, above (hypertension, hyperglycemia)-- **hypo-**: below, deficient (hypotension, hypoglycemia)-- **poly-**: many (polyuria, polydipsia)-- **tachy-**: fast (tachycardia, tachypnea)-- **macro-**: large (macrocephaly)-- **micro-**: small (microcephaly)-- **hemi-**: half (hemiplegia)-- **bi-/di-**: two (bilateral, diplopia)--### Common Suffixes--- **-algia**: pain (arthralgia, neuralgia)-- **-ectomy**: surgical removal (appendectomy, cholecystectomy)-- **-emia**: blood condition (anemia, leukemia)-- **-itis**: inflammation (appendicitis, arthritis)-- **-oma**: tumor (carcinoma, melanoma)-- **-osis**: abnormal condition (cirrhosis, osteoporosis)-- **-pathy**: disease (neuropathy, nephropathy)-- **-penia**: deficiency (thrombocytopenia, neutropenia)-- **-plasty**: surgical repair (rhinoplasty, angioplasty)-- **-scopy**: visual examination (colonoscopy, bronchoscopy)-- **-stomy**: surgical opening (colostomy, tracheostomy)-------This reference provides comprehensive medical terminology, coding systems, abbreviations, and nomenclature standards. Use these guidelines to ensure accurate, standardized clinical documentation.+- the dictionary is official, complete, current, or licensed for the use;+- the chosen code is appropriate;+- the clinical statement is true;+- the report is compliant or ready for release.+Without a dictionary, the strongest result is `SCHEMA_VALID_SYNTAX_ONLY_REVIEW_REQUIRED`.diff --git a/skills/clinical-reports/references/patient_documentation.md b/skills/clinical-reports/references/patient_documentation.mddeleted file mode 100644index 4da33f71..00000000--- a/skills/clinical-reports/references/patient_documentation.md+++ /dev/null@@ -1,744 +0,0 @@-# Patient Documentation Standards--## SOAP Notes--SOAP (Subjective, Objective, Assessment, Plan) is the standard format for progress notes in clinical practice.--### Purpose and Use--**When to use SOAP notes:**-- Daily progress notes in hospital-- Outpatient visit documentation-- Subspecialty consultations-- Follow-up visits-- Documenting response to treatment--**Benefits:**-- Standardized structure-- Organized clinical reasoning-- Facilitates communication-- Supports billing and coding-- Legal documentation--### SOAP Components--#### S - Subjective--**Definition:** Information reported by the patient (symptoms, concerns, history)--**Elements to include:**-- Chief complaint or reason for visit-- History of present illness (HPI)-- Review of systems (ROS) relevant to visit-- Patient's description of symptoms-- Response to prior treatments-- Functional impact-- Patient concerns or questions--**HPI Elements (use OPQRST for pain/symptoms):**-- **O**nset: When did it start? Sudden or gradual?-- **P**rovocation/Palliation: What makes it better or worse?-- **Q**uality: What does it feel like? (sharp, dull, burning, etc.)-- **R**egion/Radiation: Where is it? Does it spread?-- **S**everity: How bad is it? (0-10 scale)-- **T**iming: Constant or intermittent? Duration? Frequency?--**Associated symptoms:**-- Other symptoms occurring with primary complaint-- Pertinent negatives (absence of expected symptoms)--**Response to treatment:**-- Medications taken and effect-- Prior interventions and outcomes-- Compliance with treatment plan--**Example Subjective section:**-```-S: Patient reports persistent cough for 5 days, productive of yellow sputum. Associated-with fever to 101.5°F, measured at home yesterday. Denies shortness of breath, chest-pain, or hemoptysis. Started on azithromycin 2 days ago by urgent care, with minimal-improvement. Reports decreased appetite but able to maintain hydration. Denies recent-travel or sick contacts.-```--#### O - Objective--**Definition:** Measurable, observable clinical data--**Elements to include:**--**Vital Signs:**-- Temperature (°F or °C)-- Blood pressure (mmHg)-- Heart rate (bpm)-- Respiratory rate (breaths/min)-- Oxygen saturation (%)-- Height and weight (calculate BMI)-- Pain score if applicable--**General Appearance:**-- Overall appearance (well, ill, distressed)-- Age appropriateness-- Nutritional status-- Hygiene-- Affect and behavior--**Physical Examination by System:**-- Organized head-to-toe or by systems-- Relevant findings for presenting complaint-- Include pertinent positives and negatives--**Standard examination systems:**-1. **HEENT** (Head, Eyes, Ears, Nose, Throat)-2. **Neck** (thyroid, lymph nodes, JVD, carotids)-3. **Cardiovascular** (heart sounds, murmurs, peripheral pulses, edema)-4. **Pulmonary/Respiratory** (breath sounds, work of breathing)-5. **Abdomen** (bowel sounds, tenderness, organomegaly, masses)-6. **Extremities** (edema, pulses, ROM, deformities)-7. **Neurological** (mental status, cranial nerves, motor, sensory, reflexes, gait)-8. **Skin** (rashes, lesions, wounds)-9. **Psychiatric** (mood, affect, thought process/content)--**Laboratory and Imaging Results:**-- Relevant test results-- Include reference ranges for abnormal values-- Note timing of tests relative to visit--**Example Objective section:**-```-O: Vitals: T 100.8°F, BP 128/82, HR 92, RR 18, SpO2 96% on room air-General: Alert, mild respiratory distress, appears mildly ill-HEENT: Oropharynx without erythema or exudates, TMs clear bilaterally-Neck: No lymphadenopathy, no JVD-Cardiovascular: Regular rate and rhythm, no murmurs-Pulmonary: Decreased breath sounds right lower lobe, dullness to percussion, egophony-present. No wheezes.-Abdomen: Soft, non-tender, no organomegaly-Extremities: No edema, pulses 2+ bilaterally-Neurological: Alert and oriented x3, no focal deficits--Labs (drawn today):-WBC 14.2 x10³/μL (H) [ref 4.5-11.0]-Hemoglobin 13.5 g/dL-Platelets 245 x10³/μL-CRP 8.5 mg/dL (H) [ref <0.5]--Chest X-ray: Right lower lobe consolidation consistent with pneumonia-```--#### A - Assessment--**Definition:** Clinical impression, diagnosis, and evaluation of patient status--**Elements to include:**-- Primary diagnosis or problem-- Secondary diagnoses or problems-- Differential diagnosis if uncertain-- Severity assessment-- Progress toward treatment goals-- Complications or new problems--**Format:**-- Problem list (numbered)-- Each problem with brief assessment-- Include ICD-10 codes when appropriate for billing--**Example Assessment section:**-```-A:-1. Community-acquired pneumonia (CAP), right lower lobe (J18.1)- - Moderate severity (CURB-65 score 1)- - Appropriate for outpatient management- - Minimal improvement on azithromycin, likely bacterial etiology--2. Dehydration, mild (E86.0)- - Secondary to decreased PO intake--3. Type 2 diabetes mellitus (E11.9)- - Well-controlled, continue home medications-```--#### P - Plan--**Definition:** Diagnostic and therapeutic interventions--**Elements to include:**-- Diagnostic plan (further testing, imaging, referrals)-- Therapeutic plan (medications, procedures, therapies)-- Patient education and counseling-- Follow-up arrangements-- Specific instructions for patient-- Return precautions (when to seek urgent care)--**Medication documentation:**-- Drug name (generic preferred)-- Dose and route-- Frequency-- Duration-- Indication--**Plan organization:**-- By problem (matches assessment)-- By intervention type (diagnostics, therapeutics, education)--**Example Plan section:**-```-P:-1. Community-acquired pneumonia:- Diagnostics: None additional at this time- Therapeutics:- - Discontinue azithromycin- - Start amoxicillin-clavulanate 875/125 mg PO BID x 7 days- - Supportive care: adequate hydration, rest, acetaminophen for fever- Education:- - Explained bacterial pneumonia diagnosis and antibiotic change- - Discussed expected improvement within 48-72 hours- - Return precautions: worsening dyspnea, high fever >103°F, confusion- Follow-up: Phone call in 48 hours to assess response, clinic visit in 1 week--2. Dehydration:- - Encourage PO fluids, goal 2 liters/day- - Sports drinks or electrolyte solutions acceptable--3. Type 2 diabetes:- - Continue metformin 1000 mg PO BID- - Home glucose monitoring- - Follow-up with endocrinology as scheduled--Patient verbalized understanding and agreement with plan.-```--### SOAP Note Best Practices--**Documentation standards:**-- Write legibly if handwritten-- Use standard abbreviations only-- Date and time each entry-- Sign and credential all entries-- Document in real-time or as soon as possible-- Avoid copy-forward errors-- Review and update problem list--**Billing considerations:**-- Document medical necessity-- Match documentation to billing level-- Include required elements for E/M coding-- Document time for time-based billing--**Legal considerations:**-- Document facts, not opinions or judgment-- Quote patient when relevant-- Document non-compliance objectively-- Never alter records-- Use addendums for corrections--## History and Physical (H&P)--### Purpose--- Comprehensive baseline assessment-- Document patient status at admission or initial encounter-- Guide diagnosis and treatment planning-- Required within 24 hours of admission (TJC requirement)--### H&P Components--#### Header Information--- Patient name, DOB, MRN-- Date and time of examination-- Admitting diagnosis-- Attending physician-- Service-- Location (ED, floor, ICU)--#### Chief Complaint (CC)--**Definition:** Brief statement of why patient is seeking care--**Format:**-- One sentence-- Use patient's own words (in quotes)-- Example: CC: "I can't catch my breath"--#### History of Present Illness (HPI)--**Purpose:** Detailed chronological narrative of current problem--**Required elements (for billing):**-- Location-- Quality-- Severity-- Duration-- Timing-- Context-- Modifying factors-- Associated signs/symptoms--**Structure:**-- Opening statement (demographics, presenting problem)-- Chronological description-- Symptom characterization-- Prior workup or treatment-- What prompted presentation now--**Example:**-```-HPI: Mr. Smith is a 65-year-old man with history of CHF (EF 35%) who presents with-3 days of progressive dyspnea on exertion. Patient reports dyspnea now occurs with-walking 10 feet (baseline 1-2 blocks). Associated with orthopnea (now requiring-3 pillows, baseline 1) and lower extremity swelling. Denies chest pain, palpitations,-or syncope. Reports medication compliance but notes running out of furosemide 2 days-ago. Weight increased 8 lbs over past week. Has not been monitoring daily weights-at home. Presented to ED today when dyspnea worsened and developed while at rest.-```--#### Past Medical History (PMH)--**Include:**-- Chronic medical conditions-- Previous hospitalizations-- Major illnesses-- Injuries-- Childhood illnesses (if relevant)--**Format:**-```-PMH:-1. Heart failure with reduced ejection fraction (2018), EF 35% on echo 6 months ago-2. Coronary artery disease, s/p CABG (2019)-3. Type 2 diabetes mellitus (2010)-4. Hypertension (2005)-5. Chronic kidney disease stage 3 (baseline Cr 1.8 mg/dL)-6. Hyperlipidemia-```--#### Past Surgical History (PSH)--**Include:**-- All surgeries and procedures-- Dates (year acceptable if exact date unknown)-- Complications if any--**Format:**-```-PSH:-1. CABG x4 (2019), complicated by post-op atrial fibrillation-2. Cholecystectomy (2015)-3. Appendectomy (childhood)-```--#### Medications--**Documentation:**-- Generic name preferred-- Dose, route, frequency-- Indication if not obvious-- Include over-the-counter medications-- Herbal supplements-- Note if patient unable to provide list--**Format:**-```-Medications:-1. Furosemide 40 mg PO daily (ran out 2 days ago)-2. Carvedilol 12.5 mg PO BID-3. Lisinopril 20 mg PO daily-4. Spironolactone 25 mg PO daily-5. Metformin 1000 mg PO BID-6. Atorvastatin 40 mg PO daily-7. Aspirin 81 mg PO daily-8. Multivitamin daily-```--#### Allergies--**Document:**-- Drug allergies with reaction-- Food allergies-- Environmental allergies-- NKDA if no known allergies--**Format:**-```-Allergies:-1. Penicillin → anaphylaxis (childhood)-2. Shellfish → hives-3. ACE inhibitors → angioedema-```--#### Family History (FH)--**Include:**-- First-degree relatives (parents, siblings, children)-- Age and health status or age at death and cause-- Relevant hereditary conditions-- Family history of presenting condition if relevant--**Format:**-```-Family History:-Father: CAD, MI age 58, alive age 85-Mother: Breast cancer, deceased age 72-Brother: Type 2 diabetes-Sister: Healthy-Children: 2 sons, both healthy-```--#### Social History (SH)--**Include:**-- Tobacco use (current, former, never; pack-years if applicable)-- Alcohol use (drinks per week, CAGE questions if indicated)-- Illicit drug use (current, former, never; type and route)-- Occupation-- Living situation (alone, with family, assisted living, etc.)-- Marital status-- Sexual history (if relevant)-- Exercise habits-- Diet-- Functional status--**Format:**-```-Social History:-Tobacco: Former smoker, quit 10 years ago (30 pack-year history)-Alcohol: 2-3 beers per week, denies binge drinking-Illicit drugs: Denies-Occupation: Retired electrician-Living situation: Lives at home with wife, 2-story house, bedroom upstairs-Marital status: Married-Exercise: Unable to exercise due to dyspnea-Diet: Low sodium diet (usually adherent)-Functional status: Independent in ADLs at baseline-```--#### Review of Systems (ROS)--**Purpose:** Systematic screening for symptoms by body system--**Requirements:**-- Minimum 10 systems for comprehensive exam-- Pertinent positives and negatives-- "All other systems reviewed and negative" acceptable if documented--**Systems:**-1. **Constitutional**: Fever, chills, night sweats, weight change, fatigue-2. **Eyes**: Vision changes, pain, discharge-3. **ENT**: Hearing loss, tinnitus, sinus problems, sore throat-4. **Cardiovascular**: Chest pain, palpitations, edema, claudication-5. **Respiratory**: Cough, dyspnea, wheezing, hemoptysis-6. **Gastrointestinal**: Nausea, vomiting, diarrhea, constipation, abdominal pain-7. **Genitourinary**: Dysuria, frequency, hematuria, incontinence-8. **Musculoskeletal**: Joint pain, swelling, stiffness, weakness-9. **Skin**: Rashes, lesions, itching, changes in moles-10. **Neurological**: Headache, dizziness, syncope, seizures, weakness, numbness-11. **Psychiatric**: Mood changes, depression, anxiety, sleep disturbance-12. **Endocrine**: Heat/cold intolerance, polyuria, polydipsia-13. **Hematologic/Lymphatic**: Easy bruising, bleeding, lymph node swelling-14. **Allergic/Immunologic**: Seasonal allergies, frequent infections--**Format:**-```-ROS:-Constitutional: Denies fever, chills. Reports fatigue and weight gain (8 lbs).-Cardiovascular: Reports dyspnea, orthopnea, lower extremity edema. Denies chest pain,-palpitations, syncope.-Respiratory: Denies cough, wheezing, hemoptysis.-Gastrointestinal: Denies nausea, vomiting, diarrhea, constipation, abdominal pain.-All other systems reviewed and negative.-```--#### Physical Examination--**General organization:**-- Vital signs first-- General appearance-- Systematic examination head-to-toe--**Vital signs:**-```-Vitals: T 98.2°F, BP 142/88, HR 105, RR 24, SpO2 88% on room air → 95% on 2L NC-Height: 5'10", Weight: 195 lbs (baseline 187 lbs), BMI 28-```--**System examinations:**--**General:** Well-developed, obese man in moderate respiratory distress, sitting upright in bed--**HEENT:**-- Head: Normocephalic, atraumatic-- Eyes: PERRLA, EOMI, no scleral icterus-- Ears: TMs clear bilaterally-- Nose: Nares patent, no discharge-- Throat: Oropharynx without erythema or exudates--**Neck:** Supple, no lymphadenopathy, JVP elevated to 12 cm, no thyromegaly--**Cardiovascular:**-- Inspection: No visible PMI-- Palpation: PMI laterally displaced-- Auscultation: Tachycardic regular rhythm, S3 gallop present, 2/6 holosystolic murmur at apex radiating to axilla-- Peripheral pulses: 2+ radial, 1+ dorsalis pedis bilaterally--**Pulmonary:**-- Inspection: Increased work of breathing, using accessory muscles-- Palpation: Tactile fremitus symmetric-- Percussion: Dullness to percussion at bilateral bases-- Auscultation: Bilateral crackles halfway up lung fields, no wheezes--**Abdomen:**-- Inspection: Obese, no distention-- Auscultation: Normoactive bowel sounds-- Percussion: Tympanic-- Palpation: Soft, non-tender, no masses, no hepatosplenomegaly--**Extremities:** 3+ pitting edema to mid-calf bilaterally, no cyanosis or clubbing--**Skin:** Warm and dry, no rashes--**Neurological:**-- Mental status: Alert and oriented to person, place, time-- Cranial nerves: II-XII intact-- Motor: 5/5 strength all extremities-- Sensory: Intact to light touch-- Reflexes: 2+ symmetric-- Gait: Deferred due to respiratory distress-- Cerebellar: Finger-to-nose intact--**Psychiatric:** Anxious affect appropriate to illness, normal thought process--#### Laboratory and Imaging--**Include:**-- All relevant labs with reference ranges-- Imaging studies with key findings-- ECG findings-- Other diagnostic tests--**Example:**-```-Laboratory Data:-CBC: WBC 8.5, Hgb 11.2 (L), Hct 34%, Plt 245-BMP: Na 132 (L), K 3.2 (L), Cl 98, CO2 30, BUN 45 (H), Cr 2.1 (H, baseline 1.8), glucose 145-Troponin: <0.04 (normal)-BNP: 1250 pg/mL (H, elevated)--Imaging:-Chest X-ray: Cardiomegaly, bilateral pleural effusions, pulmonary vascular congestion-consistent with volume overload--ECG: Sinus tachycardia at 105 bpm, left ventricular hypertrophy, no acute ST-T changes-```--#### Assessment and Plan--**Format:** Problem-based with numbered problem list--**Example:**-```-Assessment and Plan:--65-year-old man with history of CHF (EF 35%) presenting with acute decompensated-heart failure.--1. Acute decompensated heart failure (I50.23)- - NYHA Class IV symptoms- - Volume overload on exam and imaging- - Precipitated by medication non-adherence (ran out of furosemide)- - BNP elevated at 1250- Diagnostics:- - Echocardiogram to assess current EF and valvular function- - Daily weights and strict I/O- Therapeutics:- - Furosemide 40 mg IV BID, goal negative 1-2L daily- - Continue carvedilol, lisinopril, spironolactone- - Oxygen 2L NC, goal SpO2 >92%- - Low sodium diet (<2g/day), fluid restriction 1.5L/day- - Telemetry monitoring- Follow-up: Will reassess after diuresis, goal discharge in 3-5 days--2. Acute kidney injury on CKD stage 3 (N17.9, N18.3)- - Cr 2.1 from baseline 1.8, likely prerenal from poor forward flow- - Monitor daily, expect improvement with diuresis- - Hold nephrotoxic agents--3. Hypokalemia (E87.6)- - K 3.2, likely from prior diuretic use- - Replete K 40 mEq PO x1, then reassess- - Continue spironolactone for K-sparing effect--4. Hyponatremia (E87.1)- - Na 132, likely dilutional from volume overload- - Expect improvement with diuresis- - Fluid restriction as above--5. Type 2 diabetes mellitus (E11.9)- - Well-controlled- - Continue home metformin- - Monitor glucose while hospitalized--6. Coronary artery disease (I25.10)- - Stable, no acute coronary syndrome- - Continue aspirin, statin, beta-blocker--Code status: Full code-Disposition: Admit to telemetry floor-```--## Discharge Summary--### Purpose--- Communicate hospital care to outpatient providers-- Document hospital course and outcomes-- Ensure continuity of care-- Meet regulatory requirements (TJC, CMS)--### Timing--**Requirements:**-- Complete within 30 days of discharge (CMS)-- Many hospitals require within 24-48 hours-- Available at time of follow-up appointment--### Components--#### Header--- Patient demographics-- Admission date and discharge date-- Length of stay-- Attending physician-- Consulting services-- Primary care physician--#### Admission Diagnosis--Principal reason for hospitalization--#### Discharge Diagnosis--**Format:** Numbered list, prioritized--**Example:**-```-Discharge Diagnoses:-1. Acute decompensated heart failure-2. Acute kidney injury on chronic kidney disease stage 3-3. Hypokalemia-4. Hyponatremia-5. Coronary artery disease-6. Type 2 diabetes mellitus-```--#### Hospital Course--**Content:**-- Chronological narrative or problem-based-- Key events and interventions-- Response to treatment-- Procedures performed-- Consultations-- Complications-- Significant test results--**Example (brief):**-```-Hospital Course:-Mr. Smith was admitted with acute decompensated heart failure in the setting of-medication non-adherence. He was diuresed with IV furosemide with net negative-5 liters over 3 days, with significant improvement in dyspnea and resolution of-lower extremity edema. Echocardiogram showed persistent reduced EF of 30%, similar-to prior. Kidney function improved to baseline with diuresis. Electrolytes were-repleted and normalized. Patient was transitioned to oral furosemide on hospital-day 3 and remained stable. He was ambulating without dyspnea on room air by-discharge. Comprehensive heart failure education was provided.-```--#### Procedures--```-Procedures:-1. Echocardiogram transthoracic (hospital day 1)-```--#### Discharge Medications--**Format:**-- Complete list with instructions-- **NEW** medications highlighted-- **CHANGED** medications noted-- **DISCONTINUED** medications listed--**Example:**-```-Discharge Medications:-1. Furosemide 60 mg PO daily [INCREASED from 40 mg]-2. Carvedilol 12.5 mg PO BID [UNCHANGED]-3. Lisinopril 20 mg PO daily [UNCHANGED]-4. Spironolactone 25 mg PO daily [UNCHANGED]-5. Metformin 1000 mg PO BID [UNCHANGED]-6. Atorvastatin 40 mg PO daily [UNCHANGED]-7. Aspirin 81 mg PO daily [UNCHANGED]-```--#### Discharge Condition--```-Discharge Condition:-Hemodynamically stable, ambulatory, no supplemental oxygen requirement, euvolemic-on exam, baseline functional status restored.-```--#### Discharge Disposition--```-Discharge Disposition:-Home with self-care-```--#### Follow-up Plans--**Include:**-- Appointments scheduled-- Recommended follow-up timing-- Pending tests or studies at discharge-- Referrals made--**Example:**-```-Follow-up:-1. Cardiology appointment with Dr. Jones on [date] at [time]-2. Primary care with Dr. Smith in 1 week-3. Home health for vital sign monitoring and medication reconciliation-4. Repeat BMP in 1 week (arranged, lab slip provided)-```--#### Patient Instructions--**Include:**-- Activity restrictions-- Dietary restrictions-- Wound care (if applicable)-- Equipment or home services-- Monitoring instructions (daily weights, glucose, BP)-- Return precautions--**Example:**-```-Patient Instructions:-1. Weigh yourself daily every morning, call doctor if gain >2 lbs in 1 day or >5 lbs- in 1 week-2. Low sodium diet (<2 grams per day)-3. Fluid restriction 2 liters per day-4. Take all medications as prescribed, do not run out of medications-5. Activity: Resume normal activities as tolerated-6. Return to ER or call 911 if: severe shortness of breath, chest pain, severe swelling,- or other concerning symptoms-```-------This reference provides comprehensive standards for patient clinical documentation including SOAP notes, H&P, and discharge summaries. Use these guidelines to ensure complete, accurate, and compliant clinical documentation.-diff --git a/skills/clinical-reports/references/peer_review_standards.md b/skills/clinical-reports/references/peer_review_standards.mddeleted file mode 100644index 031995ed..00000000--- a/skills/clinical-reports/references/peer_review_standards.md+++ /dev/null@@ -1,585 +0,0 @@-# Peer Review Standards for Clinical Manuscripts--## Overview of Clinical Manuscript Peer Review--### Purpose--Peer review ensures that clinical manuscripts meet standards for scientific rigor, ethical conduct, and clear communication before publication.--**Objectives:**-- Assess scientific validity and methodology-- Evaluate clinical significance-- Verify ethical compliance-- Ensure clarity and completeness-- Improve manuscript quality--**Types of peer review:**-- Single-blind (reviewer knows author, author doesn't know reviewer)-- Double-blind (both parties anonymous)-- Open peer review (both parties known)-- Post-publication peer review--### Reviewer Responsibilities--**Accept reviews only when:**-- Qualified in the subject area-- No conflicts of interest-- Adequate time available (typically 2-3 weeks)-- Can provide constructive, unbiased evaluation--**Maintain confidentiality:**-- Do not share manuscript content-- Do not use information for personal advantage-- Do not involve others without editor permission--**Provide timely review:**-- Complete within requested timeframe-- Notify editor promptly if unable to complete--## Case Report Review Criteria--### CARE Guideline Compliance--**Verify manuscript includes:**-- [ ] Title identifies it as case report-- [ ] Keywords provided (2-5)-- [ ] Structured or unstructured abstract-- [ ] Introduction explaining why case is novel-- [ ] Patient information (de-identified)-- [ ] Clinical findings-- [ ] Timeline of events-- [ ] Diagnostic assessment-- [ ] Therapeutic interventions-- [ ] Follow-up and outcomes-- [ ] Discussion with literature review-- [ ] Patient perspective (if applicable)-- [ ] Informed consent statement--### Novelty and Significance--**Assess:**-- Is this case truly novel or does it add to medical knowledge?-- What makes this case worth reporting?-- Is the condition rare or presentation unusual?-- Does it challenge existing knowledge?-- Are there clinical lessons that can be generalized?--**Red flags:**-- Common presentation of common condition-- Single case without unique features-- Overgeneralization from single case-- Lack of literature review showing novelty--### Privacy and Ethical Considerations--**Verify:**-- Informed consent obtained and documented-- Patient adequately de-identified (18 HIPAA identifiers removed)-- No identifiable images without explicit consent-- Dates removed or approximated-- Geographic information limited to state/country-- Age appropriate (exact age or range)-- Institutional identifiers removed--**Ethical concerns:**-- Missing consent documentation-- Identifiable information present-- Lack of IRB approval for retrospective chart review (if applicable)-- Vulnerable populations without additional protections--### Clinical Quality--**Diagnostic process:**-- Appropriate workup for presenting symptoms-- Differential diagnosis considered-- Logical progression to final diagnosis-- Adequate documentation of findings--**Treatment:**-- Evidence-based interventions-- Rationale for treatment choices-- Alternative treatments considered-- Appropriate monitoring and follow-up--**Outcome:**-- Clear description of clinical outcome-- Follow-up duration appropriate-- Complications documented-- Long-term outcome if available--### Literature Review--**Assess:**-- Adequate search of existing literature-- Similar cases identified and discussed-- Current understanding of condition reviewed-- Case appropriately contextualized-- References current and relevant-- Comparison to prior cases--### Writing Quality--**Structure:**-- Logical flow and organization-- CARE guideline structure followed-- Clear, concise writing-- Appropriate medical terminology--**Clarity:**-- Medical jargon explained-- Timeline clear and easy to follow-- Chronology of events logical-- Conclusions supported by case details--## Clinical Trial Manuscript Review Criteria--### Study Design and Methodology--**Assess:**-- Appropriate study design for research question-- Clear objectives and hypotheses-- Well-defined primary and secondary endpoints-- Adequate sample size with power calculation-- Randomization and blinding appropriate-- Control group appropriate--**Red flags:**-- Post-hoc changes to endpoints-- Underpowered study claiming equivalence-- Inappropriate statistical methods-- Lack of blinding when feasible-- Selection bias in enrollment--### CONSORT Compliance--**Verify:**-- Title identifies as randomized trial-- Structured abstract-- Trial registration number provided-- Protocol accessible-- CONSORT flow diagram included-- Baseline characteristics table-- All outcomes reported (not just significant ones)-- Adverse events reported-- Funding source disclosed-- Conflicts of interest declared--### Randomization and Allocation--**Assess:**-- Adequate sequence generation method-- Allocation concealment appropriate-- Baseline characteristics balanced-- Stratification factors specified-- Crossovers and protocol deviations documented--### Participant Flow--**Verify:**-- Number screened reported-- Exclusion reasons provided-- Number randomized clear-- Dropouts and reasons documented-- Lost to follow-up minimized and explained-- ITT and per-protocol analyses specified-- CONSORT diagram complete and accurate--### Outcome Measures--**Primary outcome:**-- Clearly defined a priori-- Clinically meaningful-- Appropriate for research question-- Measured reliably and validly-- Statistical analysis appropriate--**Secondary outcomes:**-- Pre-specified in protocol-- Analyzed appropriately-- Multiple comparison correction if needed-- Not over-interpreted if underpowered--**Exploratory outcomes:**-- Clearly labeled as exploratory or post-hoc-- Not given same weight as primary-- Hypothesis-generating, not confirmatory--### Statistical Analysis--**Assess:**-- Analysis plan specified before unblinding-- Appropriate statistical tests-- Assumptions verified (normality, etc.)-- Missing data handled appropriately-- Multiplicity adjustments when needed-- Confidence intervals provided-- Effect sizes reported--**Common issues:**-- p-hacking (selective reporting)-- Multiple testing without correction-- Inappropriate subgroup analyses-- Switching between ITT and per-protocol analyses-- Missing data ignored or improperly handled--### Safety Reporting--**Verify:**-- All adverse events reported-- Serious adverse events detailed-- Deaths fully described-- Causality assessed-- Laboratory abnormalities reported-- Discontinuations due to AEs documented--### Clinical Significance--**Assess:**-- Statistical significance vs. clinical significance-- Magnitude of effect clinically meaningful-- Number needed to treat (NNT) if applicable-- Benefit-risk ratio favorable-- Generalizability to practice-- Cost-effectiveness considerations--## Diagnostic Study Review Criteria--### STARD Guidelines (Standards for Reporting Diagnostic Accuracy Studies)--**Assess compliance:**-- Study design described-- Participant selection criteria-- Sampling method-- Data collection procedure-- Reference standard defined-- Index test described in detail-- Blinding addressed-- Flow of participants clear-- 2×2 table provided-- Diagnostic accuracy estimates--### Reference Standard--**Verify:**-- Appropriate gold standard used-- Same reference standard for all participants-- Reference standard performed regardless of index test result-- Time between index test and reference standard appropriate-- Independent interpretation of index test and reference standard--### Test Performance--**Required metrics:**-- Sensitivity and specificity-- Positive and negative predictive values (with prevalence)-- Likelihood ratios-- ROC curve and AUC (if continuous outcome)-- 95% confidence intervals for all estimates--**Consider:**-- Pre-test and post-test probabilities-- Clinical utility beyond accuracy-- Comparison to existing tests-- Cost and availability--### Spectrum and Verification Bias--**Assess:**-- Spectrum of disease severity included-- Avoiding spectrum bias (only severe cases)-- Verification bias avoided (all participants get reference standard)-- Differential verification avoided (different reference standards for different participants)--## Observational Study Review Criteria--### STROBE Guidelines (Strengthening the Reporting of Observational Studies in Epidemiology)--**For cohort, case-control, or cross-sectional studies, verify:**-- Title and abstract identify study design-- Background and rationale clear-- Objectives specified-- Study design present in methods-- Setting described-- Participants described-- Variables clearly defined-- Data sources and measurement detailed-- Bias addressed-- Study size justified-- Statistical methods described-- Results reported with effect sizes and CIs--### Exposure and Outcome Assessment--**Assess:**-- Exposure clearly defined-- Outcome clearly defined-- Measurement methods valid and reliable-- Blinding of assessors when possible-- Consistent measurement across groups-- Time relationship between exposure and outcome appropriate--### Confounding and Bias--**Verify:**-- Potential confounders identified-- Adjustment for confounders in analysis-- Residual confounding discussed-- Selection bias addressed-- Information bias considered-- Sensitivity analyses performed--### Causality--**Bradford Hill Criteria consideration:**-- Strength of association-- Consistency across studies-- Specificity-- Temporality (exposure precedes outcome)-- Biological gradient (dose-response)-- Plausibility-- Coherence with existing knowledge-- Experimental evidence-- Analogy--**Avoid:**-- Causal language for observational studies without strong evidence-- Confusing association with causation--## Systematic Review and Meta-Analysis Review Criteria--### PRISMA Guidelines--**Verify:**-- Title identifies as systematic review/meta-analysis-- Structured abstract-- Research question (PICO format)-- Protocol and registration (PROSPERO)-- Search strategy comprehensive-- Study selection process described-- Data extraction process-- Quality assessment of included studies-- Synthesis methods appropriate-- Results with forest plots-- Assessment of heterogeneity-- Publication bias assessed-- Certainty of evidence (GRADE)--### Search Strategy--**Assess:**-- Multiple databases searched-- Search terms comprehensive-- Limits and filters justified-- Gray literature considered-- Hand-searching of references-- Contact with authors for missing data-- Search reproducible--### Study Selection--**Verify:**-- Inclusion/exclusion criteria pre-specified-- Independent screening by ≥2 reviewers-- Disagreements resolved appropriately-- PRISMA flow diagram complete-- Excluded studies with reasons--### Quality Assessment--**Assess:**-- Appropriate quality assessment tool used- - RCTs: Cochrane Risk of Bias tool- - Observational: Newcastle-Ottawa Scale- - Diagnostic: QUADAS-2-- Independent quality assessment-- Results of quality assessment reported-- Quality incorporated into synthesis--### Statistical Methods--**For meta-analysis:**-- Fixed vs. random effects model justified-- Heterogeneity assessed (I², Q statistic)-- Forest plot provided-- Publication bias assessed (funnel plot, Egger's test)-- Sensitivity analyses performed-- Subgroup analyses pre-specified--### GRADE Assessment--**Certainty of evidence:**-- High: Very confident in effect estimate-- Moderate: Moderately confident-- Low: Limited confidence-- Very low: Very little confidence--**Factors decreasing certainty:**-- Risk of bias-- Inconsistency-- Indirectness-- Imprecision-- Publication bias--## Manuscript Quality Assessment--### Structure and Organization--**Assess:**-- Logical flow from introduction through discussion-- Sections appropriately organized-- Figures and tables support text-- Supplementary materials appropriate--### Writing Quality--**Clarity:**-- Clear, concise language-- Jargon minimized and defined-- Abbreviations defined at first use-- Consistent terminology--**Grammar and style:**-- Correct grammar and spelling-- Appropriate verb tense (past for study results, present for established facts)-- Active voice when appropriate-- Concise without sacrificing clarity--### References--**Verify:**-- Adequate number of references-- Current literature included-- Key papers cited-- References formatted correctly-- All citations in reference list and vice versa-- No excessive self-citation--### Tables and Figures--**Assess:**-- Appropriate for data type-- Clear labels and legends-- High quality images-- Can stand alone-- No redundancy with text-- Statistical notation correct--## Ethical Considerations in Review--### Conflicts of Interest--**Disclose and recuse if:**-- Personal relationship with authors-- Financial interest in outcome-- Competing research-- Strong bias for or against topic-- Institutional conflict--### Fair and Constructive Review--**Provide:**-- Balanced assessment of strengths and weaknesses-- Specific, actionable suggestions-- Respectful tone-- Objective evaluation-- Recognition of limitations of study design--**Avoid:**-- Personal attacks-- Dismissive language-- Demanding unreasonable revisions-- Expecting perfect study-- Imposing personal preferences over standards--### Confidentiality--**Maintain:**-- Do not share manuscript-- Do not discuss with colleagues without permission-- Do not use ideas or data-- Destroy copies after review--## Recommendation Categories--**Accept:**-- Manuscript meets publication standards-- Minor editing only--**Minor revisions:**-- Small issues that can be addressed-- No additional data required-- Typically one round of revision--**Major revisions:**-- Significant concerns requiring substantial changes-- May require additional analyses-- May require additional data or experiments-- Typically re-reviewed--**Reject:**-- Fundamental flaws that cannot be corrected-- Insufficient novelty or significance-- Unethical conduct-- Fraudulent data--**Reject and resubmit:**-- Study has potential but needs substantial work-- Essentially new submission after major changes--## Writing the Review Report--### Structure--**Summary:**-- Brief overview (2-3 sentences)-- Overall assessment-- Key strengths (2-3 points)-- Key weaknesses (2-3 points)-- Recommendation--**Major comments:**-- Numbered-- Significant issues affecting validity, interpretation, or impact-- Specific and actionable-- Prioritized--**Minor comments:**-- Numbered-- Editorial, formatting, or clarification issues-- Line-specific comments-- Table/figure comments--### Tone and Language--**Use:**-- Professional, collegial tone-- "The authors state..." not "You state..."-- "This study shows..." not "Your study shows..."-- Constructive criticism-- Suggestions for improvement--**Avoid:**-- Harsh or dismissive language-- Personal pronouns-- Sarcasm-- Vague criticism-- Unreasonable demands--### Specific and Actionable Feedback--**Good:**-"The sample size calculation (page 8) does not account for expected dropout rate. Please revise to include expected dropout and explain how this affects enrollment targets."--**Poor:**-"Sample size is inadequate."--**Good:**-"Figure 2 would be clearer if error bars represented 95% CI rather than SEM. Please revise and update figure legend accordingly."--**Poor:**-"Figure 2 is confusing."-------This reference provides comprehensive peer review standards for clinical manuscripts including case reports, clinical trials, diagnostic studies, observational studies, and systematic reviews. Use these criteria to conduct thorough, constructive peer reviews.-diff --git a/skills/clinical-reports/references/privacy_and_deidentification.md b/skills/clinical-reports/references/privacy_and_deidentification.mdnew file mode 100644index 00000000..eaabd78c--- /dev/null+++ b/skills/clinical-reports/references/privacy_and_deidentification.md@@ -0,0 +1,84 @@+# Privacy and De-identification++This reference documents a review process. It is not legal advice, a technical de-identification service, or evidence of HIPAA compliance.++## HHS framework++HHS guidance under 45 CFR 164.514(b) describes two methods:++1. **Expert Determination** — a person with appropriate knowledge and experience applies generally accepted statistical and scientific principles and documents that re-identification risk is very small under the anticipated conditions.+2. **Safe Harbor** — specified identifiers are removed and the covered entity has no actual knowledge that remaining information could identify an individual.++A local script cannot perform Expert Determination, establish “no actual knowledge,” or decide whether an organization is a covered entity or business associate.++## Safe Harbor identifier categories++The responsible privacy professional must review the exact regulation and HHS guidance. The categories include:++1. names;+2. geographic subdivisions smaller than a state, subject to the specific ZIP-code rule;+3. date elements more specific than year directly related to an individual, plus the age rule for persons over 89;+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 or license numbers;+12. vehicle identifiers and serial numbers;+13. device identifiers and serial numbers;+14. URLs;+15. IP addresses;+16. biometric identifiers;+17. full-face photographs and comparable images;+18. other unique identifying numbers, characteristics, or codes.++Removal of obvious patterns is insufficient. Initials, partial identifiers, metadata, free text, rare events, small cells, unusual dates, images, and combined quasi-identifiers may still identify a person.++## Minimum necessary++HHS states that covered entities generally take reasonable steps to limit uses, disclosures, and requests for PHI to the minimum necessary for the purpose. HHS also lists exceptions, including certain treatment disclosures, disclosures to the individual, authorized uses/disclosures, uses/disclosures required for HIPAA administration, HHS enforcement, and uses/disclosures required by law.++Do not apply the phrase mechanically. The responsible privacy/legal reviewer determines scope, exceptions, authorization, waiver, limited-data-set rules, and any more protective law or policy.++## Local process++1. Define purpose, recipient, authority, jurisdiction, and data class.+2. Exclude fields not needed for the purpose.+3. Keep source records in the authorized system; use field-path references and hashes in the draft workspace.+4. Select Safe Harbor, Expert Determination, or a documented synthetic/aggregate-data rationale through the responsible reviewer.+5. Review structured fields, free text, attachments, images, headers, filenames, metadata, and linked data.+6. Review combinations and small-cell/rare-case risk.+7. Record actual-knowledge review or Expert Determination documentation as applicable.+8. Verify access controls, storage, transmission, retention, and deletion under organizational policy.+9. Obtain privacy/legal/institutional approval for the intended disclosure.+10. Re-review after every content, recipient, or purpose change.++## What the checklist does++`assets/deidentification_process_checklist.json` and `scripts/check_deidentification.py` verify that required process fields are documented. They deliberately:++- do not scan patient free text;+- do not output detected identifiers;+- do not label a document `COMPLIANT`, `SAFE`, or `DEIDENTIFIED`;+- do not substitute for Expert Determination or legal review;+- remain blocked when required human review is missing.++The strongest successful result is `PROCESS_DOCUMENTED_REVIEW_REQUIRED`.++## Consent and authorization++Publication consent, research consent, HIPAA authorization, IRB/Privacy Board waiver, and permission to use an image are distinct. Do not infer one from another or generate a stock assertion.++Record only the status and local documentation reference verified by the responsible human. Never store a signed consent form or direct identifier in this skill’s assets, tests, or example manifests.++## Incident handling++If real PHI is unexpectedly present:++1. stop processing;+2. do not echo, copy, transform, or upload it;+3. preserve only the minimum operational information needed under policy;+4. notify the authorized privacy/security contact through the institution’s process;+5. do not independently determine breach status or notification duties.diff --git a/skills/clinical-reports/references/professional_review.md b/skills/clinical-reports/references/professional_review.mdnew file mode 100644index 00000000..49b7226c--- /dev/null+++ b/skills/clinical-reports/references/professional_review.md@@ -0,0 +1,78 @@+# Professional, Ethical, and Human Review++## Accountability++Automation may organize verified facts but cannot assume professional accountability. A named, qualified human must review each domain and take responsibility in the authorized system.++The ICMJE Recommendations, updated January 2026, retain four authorship criteria: substantive contribution; drafting or critical review; final approval; and accountability for accuracy and integrity. Writing assistance alone does not confer authorship. An AI system cannot be an author or approve a manuscript.++## Research ethics++The World Medical Association states that the **2024 Declaration of Helsinki** is the current official version. It applies to medical research involving human participants, including identifiable material or data, and emphasizes:++- participant rights and interests over research goals;+- privacy and confidentiality;+- scientific validity and a documented protocol;+- independent research-ethics review;+- informed consent;+- transparency and reporting.++This skill neither performs ethics review nor determines whether an activity is research, exempt, or authorized.++## Clinical-record confidentiality++AMA Code of Medical Ethics Opinion 3.3.2 states that information recorded in patient care is confidential regardless of form and identifies access restriction, audit capability, security/integrity, retrieval, sharing, third-party access, and disposition as responsibilities for electronic records.++Use institution-controlled systems for real clinical records. Local draft manifests should contain source locators and hashes rather than PHI.++## Required reviewers by artifact++| Domain | Reviewer responsibility |+|---|---|+| Clinical case facts | Qualified clinician verifies facts, uncertainty, chronology, and interpretation |+| Radiology | Qualified radiologist authors findings/impression and communication status |+| Pathology | Qualified pathologist selects protocol/version and authors diagnosis |+| Laboratory | Authorized laboratory professional verifies released result, method, status, and corrections |+| Statistics | Qualified statistician verifies analysis set, estimand, method, denominator, missingness, and output |+| Safety | Qualified safety professional verifies coding, seriousness, severity, causality, expectedness, and reportability |+| Privacy/legal | Authorized reviewer verifies data use, consent/authorization, disclosure, de-identification method, and jurisdiction |+| Regulatory | Qualified professional verifies adopted guidance, regional requirements, format, and submission process |+| Publication | All accountable authors verify content and current journal instructions |++## Review record++Record:++- reviewer role, not a fabricated name;+- scope reviewed;+- source version and data cut;+- unresolved conflicts and limitations;+- review date;+- decision in the authorized workflow;+- reference to the real sign-off record.++Do not place a signature, license number, direct contact detail, or copied approval document in a synthetic asset.++## Prohibited claims++Never state that a script or checklist proves:++- clinical correctness;+- HIPAA compliance or de-identification;+- GCP compliance;+- CARE, CONSORT, SPIRIT, ICH, ACR, CAP, or CLIA compliance;+- ethics approval or informed consent;+- regulatory reportability;+- readiness for signature, filing, publication, or submission.++Permitted script language is limited to structural findings such as `BLOCKED`, `STRUCTURE_COMPLETE_REVIEW_REQUIRED`, or `PROCESS_DOCUMENTED_REVIEW_REQUIRED`.++## Corrections and conflicts++- Never overwrite a source fact.+- Keep original and corrected versions linked.+- Expose conflicting sources and stop dependent claims.+- Require the responsible reviewer to resolve conflicts in the authorized system.+- Re-run structural and consistency checks after any correction.++No local script signs, timestamps an approval, files, transmits, or submits an artifact.diff --git a/skills/clinical-reports/references/regulatory_compliance.md b/skills/clinical-reports/references/regulatory_compliance.mddeleted file mode 100644index 7ddeaa6e..00000000--- a/skills/clinical-reports/references/regulatory_compliance.md+++ /dev/null@@ -1,577 +0,0 @@-# Regulatory Compliance for Clinical Reports--## HIPAA (Health Insurance Portability and Accountability Act)--### Overview--HIPAA Privacy Rule protects individually identifiable health information (Protected Health Information, PHI). All clinical reports must comply with HIPAA requirements for privacy and security.--### Protected Health Information (PHI)--**Definition:** Individually identifiable health information held or transmitted by covered entities or business associates in any form or medium.--**Covered Entities:**-- Healthcare providers-- Health plans-- Healthcare clearinghouses--**Business Associates:**-- Third parties providing services involving PHI-- Require Business Associate Agreement (BAA)--### 18 HIPAA Identifiers--These identifiers must be removed for Safe Harbor de-identification:--1. **Names**-2. **Geographic subdivisions smaller than state** (except first 3 digits of ZIP if >20,000 people)-3. **Dates** (except year) - birth, admission, discharge, death-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** (fingerprints, voiceprints)-17. **Full-face photographs and comparable images**-18. **Any other unique identifying characteristic or code**--### De-identification Methods--#### Method 1: Safe Harbor--Remove all 18 identifiers AND have no actual knowledge that remaining information could be used to identify the individual.--**Implementation:**-- Remove/redact all 18 identifiers-- Ages over 89 must be aggregated to "90 or older"-- Dates can keep year only-- Geographic areas can include state only-- Documentation that no identifying information remains--#### Method 2: Expert Determination--Statistical/scientific analysis demonstrating that risk of re-identification is very small.--**Requirements:**-- Performed by qualified statistician or expert-- Documented analysis methods-- Conclusion that re-identification risk is very small-- Maintained documentation--### HIPAA Minimum Necessary Standard--**Principle:** Use, disclose, and request only the minimum PHI necessary to accomplish purpose.--**Exceptions:**-- Treatment purposes (providers need full information)-- Patient-authorized disclosures-- Required by law--**Implementation:**-- Role-based access controls-- Purpose-specific disclosures-- Limited data sets when feasible--### Patient Authorization--**When required:**-- Uses/disclosures beyond treatment, payment, operations (TPO)-- Marketing purposes-- Sale of PHI-- Psychotherapy notes-- Research (unless waiver obtained)--**Required elements of authorization:**-- Specific description of PHI to be used/disclosed-- Person(s) authorized to make disclosure-- Person(s) to receive information-- Purpose of disclosure-- Expiration date or event-- Patient signature and date-- Right to revoke-- Potential for re-disclosure by recipient--### HIPAA Security Rule (Electronic PHI)--**Administrative Safeguards:**-- Security management process-- Workforce security-- Information access management-- Security awareness and training-- Security incident procedures--**Physical Safeguards:**-- Facility access controls-- Workstation use and security-- Device and media controls--**Technical Safeguards:**-- Access control-- Audit controls-- Integrity controls-- Transmission security--### Breach Notification Rule--**Breach definition:** Unauthorized acquisition, access, use, or disclosure of PHI that compromises security or privacy.--**Notification requirements:**-- **Individual notification:** Without unreasonable delay, no later than 60 days-- **Media notification:** If breach affects >500 residents of a state or jurisdiction-- **HHS notification:** Within 60 days if >500 individuals; annually if <500-- **Business associate notification to covered entity:** Without unreasonable delay--**Content of notification:**-- Description of breach-- Types of information involved-- Steps individuals should take to protect themselves-- What entity is doing to investigate/mitigate-- Contact procedures for questions--### Penalties for HIPAA Violations--**Civil penalties (per violation):**-- Tier 1: $100-$50,000 (unknowing)-- Tier 2: $1,000-$50,000 (reasonable cause)-- Tier 3: $10,000-$50,000 (willful neglect, corrected)-- Tier 4: $50,000-$1.9M (willful neglect, not corrected)--**Criminal penalties:**-- Knowingly obtaining PHI: Up to $50,000 and/or 1 year-- Under false pretenses: Up to $100,000 and/or 5 years-- Intent to sell/transfer/use for commercial advantage: Up to $250,000 and/or 10 years--### Research and HIPAA--**HIPAA authorization for research:**-- Specific to research study-- Describes PHI to be used-- States that PHI may not be necessary for treatment--**Waiver of authorization:**-- IRB or Privacy Board approval-- Minimal risk to privacy-- Research could not practically be conducted without waiver-- Research could not practically be conducted without access to PHI-- Plan to protect identifiers-- Plan to destroy identifiers when appropriate-- Written assurances--**Limited data sets:**-- Remove 16 of 18 identifiers (may keep dates and geographic subdivisions)-- Data use agreement required-- Only for research, public health, or healthcare operations--## 21 CFR Part 11 (Electronic Records and Electronic Signatures)--### Scope--FDA regulation establishing criteria for electronic records and electronic signatures to be considered trustworthy, reliable, and equivalent to paper records.--**Applies to:**-- Clinical trial data-- Regulatory submissions-- Manufacturing records-- Laboratory records-- Any record required by FDA regulations--### Electronic Records Requirements--**System validation:**-- Validation documentation-- Accuracy, reliability, consistent performance-- Ability to discern invalid or altered records--**Audit trails:**-- Secure, computer-generated, time-stamped audit trail-- Record of:- - Date and time of entry/modification- - User making change- - Previous values changed-- Cannot be modified or deleted by users-- Retained for records retention period--**Operational checks:**-- Authority checks (user authorization)-- Device checks (valid input devices)-- Education and training-- Confirmation of intent (e.g., "Are you sure?")--**Record retention:**-- Electronic copies as accurate as paper-- Protection from loss (backups)-- Protection from unauthorized access-- Ability to produce readable copies for FDA inspection--### Electronic Signatures Requirements--**General requirements:**-- Unique to one individual-- Not reused or reassigned-- Verification of identity before establishing-- Certification to FDA that electronic signatures are legally binding--**Components:**-- Unique ID-- Password or biometric-- Two distinct components when executed--**Controls:**-- Session timeout for inactivity-- Periodic password changes-- Prevention of password reuse-- Detection and reporting of unauthorized use-- Secure storage of passwords-- Unique electronic signatures (not shared)--**Electronic signature manifestations:**-Must include:-- Printed name of signer-- Date and time of signing-- Meaning of signature (e.g., review, approval, authorship)--### Closed vs. Open Systems--**Closed system:**-- Access limited to authorized individuals-- Within a single organization-- Less stringent requirements--**Open system:**-- Not controlled by persons responsible for content-- Accessible to unauthorized persons-- Requires additional measures:- - Encryption- - Digital signatures- - Other authentication/security measures--### Hybrid Systems (Paper + Electronic)--**Requirements:**-- Clear procedures for hybrid system use-- Maintain record integrity-- Paper records linked to electronic-- Cannot delete electronic records after printing-- Must preserve audit trails--### Legacy Systems--**Grandfather clause:**-- Systems in use before August 20, 1997 may be grandfathered-- Must demonstrate trustworthiness without full Part 11 compliance-- Must validate and document reliability-- Should have migration plan to compliant system--## ICH-GCP (Good Clinical Practice)--### Overview--International ethical and scientific quality standard for designing, conducting, recording, and reporting trials involving human subjects.--**Purpose:**-- Protect rights, safety, and well-being of trial subjects-- Ensure credibility of clinical trial data--**Regulatory adoption:**-- FDA recognizes ICH-GCP (E6)-- Required for studies supporting regulatory submissions--### Principles of ICH-GCP--**1. Ethics:** Clinical trials should be conducted in accordance with ethical principles (Declaration of Helsinki, local laws)--**2. Risk-benefit:** Trials should be scientifically sound with favorable risk-benefit ratio--**3. Rights and welfare:** Rights, safety, and well-being of subjects take precedence over science and society--**4. Available information:** Trials should use available nonclinical and clinical information--**5. Quality:** Trials should be scientifically sound and described in clear, detailed protocol--**6. Compliance:** Trials should comply with approved protocol--**7. Qualified personnel:** Trials should be conducted by qualified individuals--**8. Informed consent:** Freely given informed consent should be obtained from each subject--**9. Privacy:** Confidentiality of subject records must be protected--**10. Quality assurance:** Systems with procedures ensuring quality of data generated--**11. Investigational products:** Manufactured, handled, and stored per GMP; used per approved protocol--**12. Documentation:** Documentation systems should allow accurate reporting, interpretation, and verification--**13. Quality management:** Sponsor should implement quality management system--### Essential Documents--**Before trial initiation:**-- Investigator's Brochure-- Protocol and amendments-- Sample CRF-- IRB/IEC approval-- Informed consent forms-- Financial disclosure-- Curriculum vitae of investigators-- Normal laboratory values-- Certifications (lab, equipment)-- Decoding procedures for blinded trials-- Monitoring plan-- Sample labels-- Instructions for handling investigational products--**During trial:**-- Updates to investigator's brochure-- Protocol amendments and approvals-- Continuing IRB review-- Informed consent updates-- Curriculum vitae updates-- Monitoring visit reports-- Source documents-- Signed/dated consent forms-- CRFs-- Correspondence with regulatory authorities--**After trial:**-- Final report-- Documentation of investigational product destruction-- Samples of labels and labeling-- Post-study access to investigational product (if applicable)--### Investigator Responsibilities--**Qualifications:**-- Qualified by education, training, and experience-- Has adequate resources-- Has adequate time-- Has access to subjects--**Compliance:**-- Conduct trial per protocol-- Obtain IRB approval before trial-- Obtain informed consent-- Report adverse events-- Maintain essential documents-- Allow monitoring and auditing-- Retain records--**Safety reporting:**-- Immediately report SAEs to sponsor-- Report to IRB per requirements-- Report to regulatory authority per requirements--### Source Documentation--**Source documents:**-- Original documents, data, and records-- Examples: hospital records, clinical charts, laboratory notes, ECGs, pharmacy records-- Must support data in CRFs--**Source data verification (SDV):**-- Comparison of CRF data to source documents-- Required by monitors-- Can be 100% or risk-based sampling--**Good documentation practice:**-- Contemporaneous (record in real-time or soon after)-- Legible-- Indelible-- Original (or certified copy)-- Accurate-- Complete-- Attributable (signed/initialed and dated)-- Not retrospectively changed without documentation--**Corrections to source:**-- Single line through error-- Reason for change-- Date and initials-- Original entry still legible-- Never use correction fluid/whiteout-- Never obliterate original entry--### Record Retention--**Minimum retention:**-- 2 years after last approval of marketing application (US)-- At least 2 years after formal discontinuation of clinical development-- Longer if required by local regulations-- 25 years for some countries (e.g., Japan for new drugs)--**Documents to retain:**-- Protocols and amendments-- CRFs-- Source documents-- Signed informed consents-- IRB correspondence-- Monitoring reports-- Audit certificates-- Regulatory correspondence-- Final study report--## FDA Regulations--### 21 CFR Part 50 (Informed Consent)--**Elements of informed consent:**-1. Statement that study involves research-2. Description of purpose, duration, procedures-3. Experimental procedures identified-4. Reasonably foreseeable risks or discomforts-5. Benefits to subject or others-6. Alternative procedures or treatments-7. Confidentiality protections-8. Compensation and treatments for injury (if >minimal risk)-9. Who to contact for questions-10. Statement that participation is voluntary-11. Statement that refusal will involve no penalty or loss of benefits-12. Statement that subject may discontinue at any time--**Additional elements (when appropriate):**-- Unforeseeable risks to subject or embryo/fetus-- Circumstances of study termination by investigator-- Additional costs to subject-- Consequences of withdrawal-- New findings that may affect willingness to participate-- Approximate number of subjects--**Documentation:**-- Written consent required (unless waived)-- Copy provided to subject-- Subject or legally authorized representative must sign-- Person obtaining consent must sign-- Date of consent--**Vulnerable populations:**-- Children: Parental permission + assent (if capable)-- Prisoners: Additional protections-- Pregnant women: Additional protections for fetus-- Cognitively impaired: Legal representative consent--### 21 CFR Part 56 (IRB Standards)--**IRB composition:**-- At least 5 members-- Varying backgrounds-- At least one scientist-- At least one non-scientist-- At least one member not affiliated with institution-- No member may participate in review of study in which member has conflicting interest--**IRB review criteria:**-- Risks minimized-- Risks reasonable in relation to benefits-- Selection of subjects equitable-- Informed consent obtained and documented-- Data monitoring when appropriate-- Privacy and confidentiality protected-- Additional safeguards for vulnerable populations--**IRB review types:**-- Full board review-- Expedited review (certain categories of minimal risk)-- Exempt (certain categories)--**Continuing review:**-- At least annually-- More frequent if determined by IRB-- Review of progress, new information, consent process--**Documentation:**-- Written procedures-- Meeting minutes-- Review determinations-- Correspondence-- Retention of records for 3 years--### 21 CFR Part 312 (IND Regulations)--**IND requirements:**-- Investigator's Brochure-- Protocol(s)-- Chemistry, manufacturing, and controls information-- Pharmacology and toxicology information-- Previous human experience-- Additional information (if applicable)--**IND amendments:**-- Protocol amendments-- Information amendments-- Safety reports-- Annual reports--**Safety reporting:**-- IND safety reports (7-day and 15-day)-- Fatal or life-threatening unexpected: 7 days (preliminary), 15 days (complete)-- Other serious unexpected: 15 days-- Annual safety reports--**General investigational plan:**-- Rationale for drug or study-- Indications to be studied-- Approach to evaluating drug-- Kinds of trials planned (Phase 1, 2, 3)-- Estimated duration of study--## EU Clinical Trials Regulation (CTR)--**EU CTR 536/2014** (replaced Clinical Trials Directive 2001/20/EC)--**Key requirements:**-- Single submission portal (CTIS - Clinical Trials Information System)-- Single assessment by multiple member states-- Transparency requirements (EudraCT database)-- Public disclosure of clinical trial results-- Layperson summary of results required--**Timelines:**-- Assessment: 60 days (Part I), additional time for Part II-- Substantial modifications: 38 days-- Safety reporting: Within specified timelines to EudraVigilance--## Good Documentation Practice (GDP)--### Principles--**ALCOA-CCEA:**-- **A**ttributable: Who performed action and when-- **L**egible: Readable and permanent-- **C**ontemporaneous: Recorded when performed-- **O**riginal: First capture of information (or certified copy)-- **A**ccurate: Correct and truthful--Additional:-- **C**omplete: All data captured-- **C**onsistent: Chronological sequence, no discrepancies-- **E**nduring: Durable throughout retention period-- **A**vailable: Accessible for review when needed--### Data Integrity--**MHRA (UK) data integrity guidance:**-- Data governance (ownership, quality)-- Risk assessment-- Change management-- Training-- Regular audit--**Common data integrity issues:**-- Back-dating of records-- Deletion or hiding of data-- Repeat testing without documentation-- Transcription errors-- Missing metadata-- Inadequate audit trails-------This reference provides comprehensive guidance for regulatory compliance in clinical reports and clinical trials, including HIPAA, FDA regulations, ICH-GCP, and EU requirements. Ensure all clinical documentation adheres to applicable regulations.-diff --git a/skills/clinical-reports/references/report_type_routing.md b/skills/clinical-reports/references/report_type_routing.mdnew file mode 100644index 00000000..65e90eda--- /dev/null+++ b/skills/clinical-reports/references/report_type_routing.md@@ -0,0 +1,57 @@+# Report-Type Routing++Select one route before opening a template. Do not merge routes merely because artifacts share clinical data.++## Decision sequence++1. Is the artifact a patient-care record?+ Stop. This skill does not create SOAP notes, H&Ps, consultation notes, discharge summaries, prescriptions, orders, triage instructions, or signed diagnostic reports.+2. Is it a single clinical case intended for publication?+ Use CARE.+3. Is it a diagnostic-report scaffold controlled by a clinical service?+ Use ACR, the current specimen-specific CAP protocol, or CLIA as applicable.+4. Is it a randomized-trial protocol?+ Use SPIRIT 2025 and applicable extensions.+5. Is it a randomized-trial results manuscript?+ Use CONSORT 2025 and applicable extensions.+6. Is it an integrated report of one clinical study for regulatory review?+ Use ICH E3 plus E3 Q&A, with ICH E6(R3) and regional requirements as applicable.+7. Is it individual pre-approval safety information?+ Route to ICH E2A, E2B(R3), protocol/sponsor procedures, and regional requirements. Do not automate the reportability decision.+8. Is it individual post-approval safety information?+ Route to ICH E2D(R1), E2B(R3), marketing-authorisation-holder procedures, and regional requirements. Do not automate.+9. Is it an aggregate safety table?+ Use the protocol/SAP, ICH E3, CONSORT Harms when applicable, and the relevant regional aggregate-analysis guidance.+10. Is it an aggregate research summary?+ Use the reporting guideline for the actual design and the verified protocol/SAP. Do not imply clinical applicability.++## Route matrix++| Artifact | Base source | Add-ons | Do not substitute |+|---|---|---|---|+| Case report | CARE 2013 | CARE 2017 explanation; target journal | CONSORT, CSR, or diagnostic-report rules |+| Radiology scaffold | ACR 2025 communication parameter | Current modality/program standard and local policy | A generic impression generator |+| Cancer pathology scaffold | Current CAP protocol for exact organ/specimen | Current biomarker protocol and local policy | A static generic TNM checklist |+| Laboratory scaffold | 42 CFR 493.1291 for applicable US nonwaived testing | Method, specialty, state, accreditor, and laboratory policy | Hardcoded reference or critical ranges |+| Trial protocol | SPIRIT 2025 | Current design/data/intervention extensions | CONSORT results checklist |+| Randomized results | CONSORT 2025 | Current design/data/intervention extensions; CONSORT Harms | SPIRIT protocol checklist |+| CSR | ICH E3 and E3 Q&A | E6(R3), protocol, SAP, regional submission rules | CONSORT alone |+| Pre-approval ICSR | ICH E2A and E2B(R3) | Regional law/guidance and sponsor procedure | Aggregate formatter |+| Post-approval ICSR | ICH E2D(R1) and E2B(R3) | Regional law/guidance and MAH procedure | Pre-approval timing rules |+| Periodic aggregate safety | ICH E2C(R2), where applicable | Regional periodic-report rules | E2B message schema |++## CONSORT/SPIRIT extension selection++The base statements address standard randomized trials. Check the live official extension catalogue for:++- design: adaptive, cluster, cluster-crossover, crossover, dose-finding, factorial, multi-arm, non-inferiority/equivalence, N-of-1, pilot/feasibility, pragmatic, stepped-wedge, routine-data, or within-person;+- data: abstracts, harms, outcomes, patient-reported outcomes, surrogate outcomes, equity, and pathology;+- intervention/population: non-pharmacological, AI, social/psychological, children/adolescents, or other specialty extensions.++Some current extensions were developed against CONSORT 2010 or SPIRIT 2013. Use the current extension with the 2025 base statement, document any conflict, and have a qualified methodologist resolve it. Do not silently renumber or reinterpret extension items.++## Jurisdiction and role gate++ICH Step 4 adoption does not itself prove implementation in a jurisdiction. FDA guidance is generally nonbinding but regulations are legally operative within scope. Institutional policy, protocol, contracts, ethics determinations, and sponsor procedures may add or change duties.++Record the jurisdiction, regulated-product category, responsible role, source version/date, and reviewer before drafting. If any is unknown, mark the route `BLOCKED_UNRESOLVED`.diff --git a/skills/clinical-reports/references/safety_reporting.md b/skills/clinical-reports/references/safety_reporting.mdnew file mode 100644index 00000000..f9a7c67c--- /dev/null+++ b/skills/clinical-reports/references/safety_reporting.md@@ -0,0 +1,109 @@+# Safety Reporting Boundaries++Safety reporting is role-, product-, phase-, source-, jurisdiction-, and time-dependent. This skill formats verified aggregate counts only. It does not determine seriousness, severity, causality, expectedness, reportability, clock start, destination, format, or follow-up.++## Core distinctions++- **Adverse event (AE)**: an untoward medical occurrence temporally associated with a medicinal product; causality is not required.+- **Adverse reaction / suspected adverse reaction**: a causal relationship is at least reasonably possible or otherwise meets the applicable regional definition.+- **Seriousness**: outcome or regulatory criterion such as death, life-threatening experience at the time, hospitalization, disability/incapacity, congenital anomaly, or another medically important event.+- **Severity**: intensity. A severe event is not automatically serious; a serious event need not be severe in intensity.+- **Expectedness**: comparison with the applicable reference safety information under the governing procedure.++Only an authorized qualified safety professional may make or approve these assessments.++## ICH routes++### E2A — pre-approval expedited reporting++ICH E2A (Step 4, 27 October 1994) defines standards for expedited reporting during clinical development. It describes minimum information for an initial report and the distinction among serious, unexpected, and suspected reactions.++Do not apply E2A as a universal post-approval rule or encode its timelines without the current regional requirement and sponsor procedure.++### E2B(R3) — ICSR electronic data and message specification++E2B(R3) defines data elements and electronic transmission for individual case safety reports. It covers pre- and post-approval ICSRs within scope. It does not:++- decide whether a case is reportable;+- define an aggregate safety table;+- replace E2A, E2D(R1), or regional rules;+- validate clinical coding or narrative accuracy.++The ICH index listed E2B(R3) Q&As at Step 5 dated 18 July 2025 when checked. Use the current implementation guide, Q&As, code lists, regional implementation guide, and receiving-system rules.++### E2D(R1) — post-approval individual cases++ICH adopted E2D(R1), **Post-Approval Safety Data: Definitions and Standards for Management and Reporting of Individual Case Safety Reports**, on 15 September 2025.++It addresses post-approval ICSR sources and case management, including organized data collection systems, literature, digital platforms, and patient-support programs. It explicitly directs users to:++- E2B for ICSR structure/format/data elements;+- E2C for periodic aggregate safety reporting;+- regional/local requirements where they differ.++Do not use the aggregate formatter for an ICSR or use E2D(R1) to invent missing case data.++### E2C(R2) — periodic aggregate reporting++Where applicable, E2C(R2) addresses periodic benefit-risk evaluation reporting. Applicability and regional format require qualified review. Aggregate tables in this skill are display aids, not periodic reports.++## FDA IND safety reporting++For applicable US IND studies, 21 CFR 312.32 controls sponsor IND safety reporting. FDA issued final sponsor and investigator safety-reporting guidances in December 2025. The sponsor guidance includes aggregate-data assessment considerations; the investigator guidance clarifies investigator-to-sponsor and IRB responsibilities.++FDA’s IND safety-reporting page, current 23 June 2026 when checked, states:++- sponsors report qualifying potential serious risks under 21 CFR 312.32;+- unexpected fatal or life-threatening suspected adverse reactions have a 7-calendar-day outer limit after the relevant sponsor determination/receipt described by the regulation;+- other qualifying reports generally use the applicable 15-calendar-day requirement;+- as of 1 April 2026, commercial IND reports under 21 CFR 312.32(c)(1)(i) use FDA AEMS with E2B(R3), with stated exemptions for noncommercial INDs;+- other categories described on the page use the applicable eCTD route.++This summary is not a reporting clock or filing instruction. The responsible sponsor, investigator, IRB/IEC, and regulatory professionals must consult the current regulation, guidance, protocol, and procedures for each event.++## Aggregate formatter input++`format_adverse_events.py` accepts only aggregate rows:++- analysis set;+- treatment group;+- MedDRA version;+- system organ class;+- preferred term;+- subjects affected;+- event count;+- denominator.++It also requires a populated `clinical_trial_safety_aggregate_template.json` sidecar+that records authorization, protocol/SAP/data-cut references, analysis set, counting+and threshold rules, MedDRA version/language, provenance, and pending human reviews.++It rejects row-level identifiers, verbatim narratives, case IDs, and onset dates. It checks arithmetic and group consistency but does not verify:++- MedDRA term/code validity;+- coding quality or hierarchy placement;+- treatment relatedness;+- seriousness or fatality;+- analysis-set correctness;+- deduplication;+- whether a subject appears in multiple terms or SOCs;+- statistical inference.++## MedDRA caveats++MedDRA 29.0 (March 2026; transition date 4 May 2026) was current when this skill was refreshed. A report must use the study/sponsor-authorized dictionary version, not automatically the newest version.++State the exact version and language. Terms can change currency, names, or hierarchy across releases; codes can persist through renames. Use licensed official files and MedDRA Points to Consider. A syntax checker cannot validate coding.++## Required handoff++Every aggregate table must disclose:++- analysis set and denominator per group;+- whether values are subjects, events, or both;+- MedDRA version and language;+- counting rules and threshold supplied by the protocol/SAP;+- missing or suppressed cells;+- no inferential claim unless separately verified;+- qualified safety and statistical review required;+- not suitable for individual-case submission.diff --git a/skills/clinical-reports/references/sources.md b/skills/clinical-reports/references/sources.mdnew file mode 100644index 00000000..015ef5fd--- /dev/null+++ b/skills/clinical-reports/references/sources.md@@ -0,0 +1,75 @@+# Official Source Ledger++**Research cutoff and access date:** 2026-07-23+**Method:** targeted `parallel-cli search` restricted to official or primary-source domains, followed by review of returned primary-source excerpts.+**Use:** source routing and version awareness only. Always verify the live source, jurisdictional adoption, and local requirements before real-world use.++## Case reports++- **CARE Case Report Guidelines — home and current toolkit.** Identifies the 2013 checklist and 2017 explanation. <https://www.care-statement.org/>+- **2013 CARE Checklist.** Thirteen main reporting items. <https://www.care-statement.org/checklist>+- **CARE publications.** Primary 2013 statement and 2017 explanation/elaboration references. <https://www.care-statement.org/publications>++## Randomized-trial protocols and results++- **SPIRIT–CONSORT official site.** SPIRIT 2025: 34-item protocol checklist and figure. CONSORT 2025: 30-item results checklist and flow diagram. <https://www.consort-spirit.org/>+- **CONSORT/SPIRIT extension catalogue.** Current design, data, intervention, and population extensions; catalogue notes which base statement each extension used. <https://www.consort-spirit.org/extensions>+- **CONSORT 2025 primary statement.** Published 2025-04-14. <https://www.bmj.com/content/389/bmj-2024-081123>+- **SPIRIT 2025 primary statement.** Published 2025-04-28; states that SPIRIT 2025 supersedes SPIRIT 2013. <https://www.bmj.com/content/389/bmj-2024-081477>+- **SPIRIT 2025 explanation and elaboration.** Published 2025-04-28. <https://www.bmj.com/content/389/bmj-2024-081660>++## ICH clinical-study and GCP guidance++- **ICH E3 — Structure and Content of Clinical Study Reports.** Step 4, 1995-11-30. <https://database.ich.org/sites/default/files/E3_Guideline.pdf>+- **ICH E3 Questions & Answers (R1).** Current version dated 2012-07-06; clarifies that E3 is adaptable guidance, not a rigid template. <https://database.ich.org/sites/default/files/E3_Q%26As_R1_Q%26As.pdf>+- **ICH E6(R3) consolidated final guideline.** Principles, Annex 1, and Annex 2; adopted 2026-06-16. <https://database.ich.org/sites/default/files/ICH%20E6%28R3%29_Step4_FinalConsolidatedGuideline_2026_0616_.pdf>+- **ICH E6(R3) Annex 2 final.** Adopted 2026-06-03. <https://database.ich.org/sites/default/files/ICH_E6%28R3%29_Annex%202_Guideline_Step%204_2026_0603_0.pdf>+- **FDA ICH guidance index.** FDA’s current US ICH guidance entry point; verify regional adoption here. Content current 2026-04-16 when checked. <https://www.fda.gov/science-research/clinical-trials-and-human-subject-protection/ich-guidance-documents>++## Safety reporting++- **ICH E2A — Clinical Safety Data Management: Definitions and Standards for Expedited Reporting.** Step 4, 1994-10-27. <https://database.ich.org/sites/default/files/E2A_Guideline.pdf>+- **ICH E2B(R3) ICSR specification and related files.** Current implementation-guide, Q&A, code-list, and alignment entry point. <https://www.ich.org/page/e2br3-individual-case-safety-report-icsr-specification-and-related-files>+- **ICH guideline index.** Listed E2B(R3) Q&As at Step 5 dated 2025-07-18 and E2D(R1) at Step 5 dated 2025-09-15 when checked. <https://www.ich.org/page/search-index-ich-guidelines>+- **ICH E2D(R1) — Post-Approval Safety Data: Definitions and Standards for Management and Reporting of Individual Case Safety Reports.** Adopted 2025-09-15. <https://database.ich.org/sites/default/files/ICH_E2D%28R1%29_Step4_FinalGuideline_2025_0819.pdf>+- **21 CFR 312.32 — IND safety reporting.** Current eCFR text; verify current effective text and official annual CFR. <https://www.ecfr.gov/current/title-21/chapter-I/subchapter-D/part-312/subpart-B/section-312.32>+- **FDA IND Application Reporting: IND Safety Reports.** Content current 2026-06-23; includes AEMS/E2B(R3) electronic route effective 2026-04-01 within stated scope. <https://www.fda.gov/drugs/investigational-new-drug-ind-application/ind-application-reporting-ind-safety-reports>+- **FDA Sponsor Responsibilities — Safety Reporting Requirements and Safety Assessment for IND and BA/BE Studies.** Final guidance, December 2025. <https://www.fda.gov/regulatory-information/search-fda-guidance-documents/sponsor-responsibilities-safety-reporting-requirements-and-safety-assessment-ind-and>+- **FDA Investigator Responsibilities — Safety Reporting for Investigational Drugs and Devices.** Final guidance, December 2025. <https://www.fda.gov/regulatory-information/search-fda-guidance-documents/investigator-responsibilities-safety-reporting-investigational-drugs-and-devices>+- **FDA Postmarketing Adverse Event Reporting Compliance Program.** Content current 2025-12-19 when checked. <https://www.fda.gov/drugs/surveillance-post-drug-approval-activities/postmarketing-adverse-event-reporting-compliance-program>++## Privacy and de-identification++- **HHS Guidance Regarding Methods for De-identification of PHI.** Safe Harbor and Expert Determination under 45 CFR 164.514(b); page reviewed 2026-03-20. <https://www.hhs.gov/hipaa/for-professionals/privacy/special-topics/de-identification/index.html>+- **HHS Minimum Necessary Requirement.** 45 CFR 164.502(b) and 164.514(d), scope and exceptions. <https://www.hhs.gov/hipaa/for-professionals/privacy/guidance/minimum-necessary-requirement/index.html>++## Diagnostic reporting++- **ACR Practice Parameter for Communication of Diagnostic Imaging Findings.** Revised 2025 (Resolution 9). <https://gravitas.acr.org/PPTS/GetDocumentView?docId=74>+- **ACR Practice Parameters & Technical Standards portal.** Current modality- and program-specific source. <https://gravitas.acr.org/PPTS>+- **CAP Cancer Protocol Templates.** Current protocol downloads and 2026 change notices; page showed updates through 2026-06-24 when checked. <https://www.cap.org/protocols-and-guidelines/cancer-reporting-tools/cancer-protocol-templates>+- **CAP Cancer Protocols.** Current scope and synoptic-reporting entry point. <https://www.cap.org/protocols-and-guidelines/cancer-reporting-tools/cancer-protocols>+- **42 CFR 493.1291 — Test report.** CLIA postanalytic report requirements for applicable testing, including corrected-report handling. <https://www.ecfr.gov/current/title-42/chapter-IV/subchapter-G/part-493/subpart-K/subject-group-ECFR9482366886d579f/section-493.1291>+- **42 CFR 493.1105 — Retention requirements.** Includes original, preliminary, final, and corrected-report retention provisions within scope. <https://www.ecfr.gov/current/title-42/chapter-IV/subchapter-G/part-493/subpart-J/section-493.1105>++## Terminology++- **ICH MedDRA.** Governance, purpose, and Points to Consider. <https://www.ich.org/page/meddra>+- **MedDRA English support documentation.** Lists MedDRA 29.0 (March 2026), transition date 2026-05-04, and versioned support documents. <https://www.meddra.org/how-to-use/support-documentation/english/welcome>+- **MedDRA 29.0 Introductory Guide.** March 2026 hierarchy and version context. <https://alt.meddra.org/files_acrobat/intguide_29_0_English.pdf>+- **LOINC.** Version 2.82 released 2026-02-24; next release listed for August 2026 when checked. <https://loinc.org/>+- **SNOMED International licensing.** Member/non-member use and licensing conditions. <https://www.snomed.org/licensing>+- **NLM SNOMED CT licensing.** US distribution and licensing entry point. <https://www.nlm.nih.gov/healthit/snomedct/snomed_licensing.html>++## Ethics and professional publication guidance++- **WMA Declaration of Helsinki.** Current official version adopted October 2024; previous versions superseded for current use. <https://www.wma.net/policies-post/wma-declaration-of-helsinki>+- **ICMJE Recommendations.** Updated January 2026; authorship, accountability, participant protection, privacy, and publication practices. <https://www.icmje.org/icmje-recommendations.pdf>+- **AMA Code of Medical Ethics Opinion 3.3.2 — Confidentiality & Electronic Medical Records.** Electronic-record confidentiality, access, audit, security, integrity, sharing, and disposition. <https://code-medical-ethics.ama-assn.org/ethics-opinions/confidentiality-electronic-medical-records>++## Known source limitations++- eCFR is continuously updated but identifies itself as an unofficial online edition; use the current official annual CFR and legal review when status matters.+- ICH Step 4 documents require regional adoption/implementation review.+- Controlled terminologies and professional standards can change after this ledger date.+- Journal instructions, local policies, protocols, SAPs, contracts, and ethics determinations are not captured here.diff --git a/skills/clinical-reports/scripts/_common.py b/skills/clinical-reports/scripts/_common.pynew file mode 100644index 00000000..d1417e74--- /dev/null+++ b/skills/clinical-reports/scripts/_common.py@@ -0,0 +1,263 @@+#!/usr/bin/env python3+"""Bounded local-file and validation helpers for clinical-reports scripts."""++from __future__ import annotations++import json+import math+import re+from datetime import date, datetime+from pathlib import Path+from typing import Any, Iterable++MAX_JSON_BYTES = 1_000_000+MAX_CSV_BYTES = 5_000_000+MAX_CSV_ROWS = 10_000+MAX_NODES = 25_000+MAX_DEPTH = 24+MAX_TEXT_LENGTH = 2_000++ALLOWED_DATA_CLASSES = {"synthetic", "deidentified", "aggregate"}+IDENTIFIER_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:-]{0,127}$")+SHA256_RE = re.compile(r"^[a-f0-9]{64}$")+++class ValidationError(ValueError):+ """Raised for fail-closed input validation errors."""+++def _reject_nonlocal(raw: str) -> None:+ if not raw or "\x00" in raw:+ raise ValidationError("path must be a non-empty local filesystem path")+ if "://" in raw or raw.startswith(("file:", "\\\\")):+ raise ValidationError("URLs, URI schemes, and network paths are not allowed")+++def local_input_path(+ raw: str,+ *,+ suffixes: Iterable[str],+ max_bytes: int,+) -> Path:+ """Resolve a bounded, regular, non-symlink local input file."""+ _reject_nonlocal(raw)+ path = Path(raw).expanduser()+ if path.is_symlink():+ raise ValidationError("symbolic-link inputs are not allowed")+ try:+ resolved = path.resolve(strict=True)+ except FileNotFoundError as exc:+ raise ValidationError(f"input file does not exist: {path}") from exc+ if not resolved.is_file():+ raise ValidationError("input must be a regular file")+ allowed = {suffix.lower() for suffix in suffixes}+ if resolved.suffix.lower() not in allowed:+ raise ValidationError(f"input suffix must be one of: {sorted(allowed)}")+ size = resolved.stat().st_size+ if size <= 0:+ raise ValidationError("input file is empty")+ if size > max_bytes:+ raise ValidationError(f"input exceeds {max_bytes} bytes")+ return resolved+++def local_output_path(+ raw: str,+ *,+ suffixes: Iterable[str],+ overwrite: bool,+) -> Path:+ """Resolve a local output whose existing parent directory is trusted."""+ _reject_nonlocal(raw)+ path = Path(raw).expanduser()+ allowed = {suffix.lower() for suffix in suffixes}+ if path.suffix.lower() not in allowed:+ raise ValidationError(f"output suffix must be one of: {sorted(allowed)}")+ if path.exists():+ if path.is_symlink() or not path.is_file():+ raise ValidationError("existing output must be a regular non-symlink file")+ if not overwrite:+ raise ValidationError("output exists; pass --overwrite to replace it")+ parent = path.parent+ if parent.is_symlink():+ raise ValidationError("symbolic-link output directories are not allowed")+ try:+ resolved_parent = parent.resolve(strict=True)+ except FileNotFoundError as exc:+ raise ValidationError("output parent directory must already exist") from exc+ if not resolved_parent.is_dir():+ raise ValidationError("output parent is not a directory")+ return resolved_parent / path.name+++def _object_without_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise ValidationError(f"duplicate JSON key: {key}")+ result[key] = value+ return result+++def _check_tree(value: Any, *, depth: int = 0, counter: list[int] | None = None) -> None:+ if counter is None:+ counter = [0]+ counter[0] += 1+ if counter[0] > MAX_NODES:+ raise ValidationError(f"JSON exceeds {MAX_NODES} nodes")+ if depth > MAX_DEPTH:+ raise ValidationError(f"JSON exceeds maximum depth {MAX_DEPTH}")+ if isinstance(value, dict):+ for key, child in value.items():+ if not isinstance(key, str) or len(key) > 128:+ raise ValidationError("JSON object keys must be strings of at most 128 characters")+ _check_tree(child, depth=depth + 1, counter=counter)+ elif isinstance(value, list):+ for child in value:+ _check_tree(child, depth=depth + 1, counter=counter)+ elif isinstance(value, str):+ if len(value) > MAX_TEXT_LENGTH:+ raise ValidationError(+ f"JSON strings may not exceed {MAX_TEXT_LENGTH} characters"+ )+ if any(ord(char) < 32 and char not in "\t\n\r" for char in value):+ raise ValidationError("JSON strings contain disallowed control characters")+ elif isinstance(value, float) and not math.isfinite(value):+ raise ValidationError("non-finite numbers are not allowed")+++def load_json_object(raw_path: str) -> tuple[Path, dict[str, Any]]:+ """Load a bounded JSON object with duplicate-key and depth checks."""+ path = local_input_path(+ raw_path,+ suffixes={".json"},+ max_bytes=MAX_JSON_BYTES,+ )+ try:+ value = json.loads(+ path.read_text(encoding="utf-8"),+ object_pairs_hook=_object_without_duplicates,+ parse_constant=lambda token: (_ for _ in ()).throw(+ ValidationError(f"invalid JSON number: {token}")+ ),+ )+ except UnicodeDecodeError as exc:+ raise ValidationError("JSON input must be UTF-8") from exc+ except json.JSONDecodeError as exc:+ raise ValidationError(f"invalid JSON: {exc.msg}") from exc+ if not isinstance(value, dict):+ raise ValidationError("top-level JSON value must be an object")+ _check_tree(value)+ return path, value+++def write_json_report(+ report: dict[str, Any],+ raw_output: str | None,+ *,+ overwrite: bool,+) -> None:+ """Print JSON or write it to an explicitly bounded local path."""+ rendered = json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False) + "\n"+ if raw_output is None:+ print(rendered, end="")+ return+ output = local_output_path(+ raw_output,+ suffixes={".json"},+ overwrite=overwrite,+ )+ output.write_text(rendered, encoding="utf-8")+++def require_data_class(value: Any) -> str:+ """Require an allowed, explicitly declared data class."""+ if value not in ALLOWED_DATA_CLASSES:+ raise ValidationError(+ f"data classification must be one of: {sorted(ALLOWED_DATA_CLASSES)}"+ )+ return str(value)+++def require_exact_keys(+ value: Any,+ expected: Iterable[str],+ field: str,+) -> dict[str, Any]:+ """Reject missing and unknown fields in a structured object."""+ if not isinstance(value, dict):+ raise ValidationError(f"{field} must be an object")+ expected_set = set(expected)+ missing = sorted(expected_set - set(value))+ extra = sorted(set(value) - expected_set)+ if missing or extra:+ details = []+ if missing:+ details.append(f"missing={missing}")+ if extra:+ details.append(f"unknown={extra}")+ raise ValidationError(f"{field} fields are invalid ({'; '.join(details)})")+ return value+++def require_identifier(value: Any, field: str) -> str:+ """Require a bounded machine identifier."""+ if not isinstance(value, str) or not IDENTIFIER_RE.fullmatch(value):+ raise ValidationError(f"{field} must match {IDENTIFIER_RE.pattern}")+ return value+++def require_string(value: Any, field: str, *, max_length: int = 256) -> str:+ """Require a non-empty bounded string."""+ if not isinstance(value, str):+ raise ValidationError(f"{field} must be a string")+ normalized = value.strip()+ if not normalized or len(normalized) > max_length:+ raise ValidationError(f"{field} must contain 1-{max_length} characters")+ return normalized+++def require_bool(value: Any, field: str) -> bool:+ """Require an actual JSON boolean."""+ if not isinstance(value, bool):+ raise ValidationError(f"{field} must be a boolean")+ return value+++def require_nonnegative_int(value: Any, field: str) -> int:+ """Require an integer count without accepting booleans."""+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise ValidationError(f"{field} must be a non-negative integer")+ return value+++def parse_iso_date(value: Any, field: str) -> date:+ """Parse an ISO calendar date without inferring missing precision."""+ text = require_string(value, field, max_length=10)+ try:+ return date.fromisoformat(text)+ except ValueError as exc:+ raise ValidationError(f"{field} must be YYYY-MM-DD") from exc+++def parse_iso_datetime(value: Any, field: str) -> datetime:+ """Parse an ISO datetime and require an explicit timezone."""+ text = require_string(value, field, max_length=40)+ try:+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))+ except ValueError as exc:+ raise ValidationError(f"{field} must be an ISO 8601 datetime") from exc+ if parsed.tzinfo is None:+ raise ValidationError(f"{field} must include a timezone")+ return parsed+++def error_report(tool: str, exc: Exception) -> dict[str, Any]:+ """Return a non-sensitive machine-readable error."""+ return {+ "tool": tool,+ "status": "BLOCKED_INVALID_INPUT",+ "errors": [str(exc)],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }diff --git a/skills/clinical-reports/scripts/check_deidentification.py b/skills/clinical-reports/scripts/check_deidentification.pyold mode 100755new mode 100644index 728a113b..d601251d--- a/skills/clinical-reports/scripts/check_deidentification.py+++ b/skills/clinical-reports/scripts/check_deidentification.py@@ -1,346 +1,298 @@#!/usr/bin/env python3-"""-Check clinical reports for HIPAA identifiers that need removal.+"""Validate de-identification process documentation without scanning patient text."""-Scans text for 18 HIPAA identifiers and flags potential privacy violations.--Usage:- python check_deidentification.py <input_file>- python check_deidentification.py <input_file> --output violations.json-"""+from __future__ import annotationsimport argparse-import json-import re-from pathlib import Path-from typing import Dict, List+import sys+from typing import Any+sys.dont_write_bytecode = True-# 18 HIPAA Identifiers patterns-HIPAA_IDENTIFIERS = {- "1_names": {- "description": "Names (patient, family, providers)",- "patterns": [- r"\b(Dr\.|Mr\.|Mrs\.|Ms\.)\s+[A-Z][a-z]+",- r"\b[A-Z][a-z]+,\s+[A-Z][a-z]+\b", # Last, First- ],- "severity": "HIGH"- },- "2_geographic": {- "description": "Geographic subdivisions smaller than state",- "patterns": [- r"\b\d+\s+[A-Z][a-z]+\s+(Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Dr)\b",- r"\b[A-Z][a-z]+,\s+[A-Z]{2}\s+\d{5}\b", # City, ST ZIP- ],- "severity": "HIGH"- },- "3_dates": {- "description": "Dates (except year)",- "patterns": [- r"\b(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/\d{4}\b",- r"\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},\s+\d{4}\b",- r"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b",- ],- "severity": "HIGH"- },- "4_telephone": {- "description": "Telephone numbers",- "patterns": [- r"\b\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b",- r"\b1-\d{3}-\d{3}-\d{4}\b",- ],- "severity": "HIGH"- },- "5_fax": {- "description": "Fax numbers",- "patterns": [- r"(?i)fax[:]\s*\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",- ],- "severity": "HIGH"- },- "6_email": {- "description": "Email addresses",- "patterns": [- r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",- ],- "severity": "HIGH"- },- "7_ssn": {- "description": "Social Security numbers",- "patterns": [- r"\b\d{3}-\d{2}-\d{4}\b",- r"\b\d{9}\b",- ],- "severity": "CRITICAL"- },- "8_mrn": {- "description": "Medical record numbers",- "patterns": [- r"(?i)(mrn|medical\s+record\s+(number|#))[:]\s*\d+",- r"(?i)patient\s+id[:]\s*\d+",- ],- "severity": "HIGH"- },- "9_health_plan": {- "description": "Health plan beneficiary numbers",- "patterns": [- r"(?i)(insurance|policy)\s+(number|#|id)[:]\s*[A-Z0-9]+",- ],- "severity": "HIGH"- },- "10_account": {- "description": "Account numbers",- "patterns": [- r"(?i)account\s+(number|#)[:]\s*\d+",- ],- "severity": "MEDIUM"- },- "11_license": {- "description": "Certificate/license numbers",- "patterns": [- r"(?i)(driver[']?s\s+license|DL)[:]\s*[A-Z0-9]+",- ],- "severity": "MEDIUM"- },- "12_vehicle": {- "description": "Vehicle identifiers",- "patterns": [- r"(?i)(license\s+plate|VIN)[:]\s*[A-Z0-9]+",- ],- "severity": "MEDIUM"- },- "13_device": {- "description": "Device identifiers and serial numbers",- "patterns": [- r"(?i)(serial|device)\s+(number|#)[:]\s*[A-Z0-9-]+",- ],- "severity": "MEDIUM"- },- "14_url": {- "description": "Web URLs",- "patterns": [- r"https?://[^\s]+",- r"www\.[^\s]+",- ],- "severity": "MEDIUM"- },- "15_ip": {- "description": "IP addresses",- "patterns": [- r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",- ],- "severity": "HIGH"- },- "16_biometric": {- "description": "Biometric identifiers",- "patterns": [- r"(?i)(fingerprint|voiceprint|retinal\s+scan)",- ],- "severity": "CRITICAL"- },- "17_photos": {- "description": "Full-face photographs",- "patterns": [- r"(?i)(photograph|photo|image).*face",- r"\.(jpg|jpeg|png|gif)\b",- ],- "severity": "HIGH"- },- "18_unique": {- "description": "Any other unique identifying characteristic",- "patterns": [- r"(?i)(tattoo|birthmark|scar).*unique",- ],- "severity": "MEDIUM"- },-}---def check_identifiers(text: str) -> Dict:- """Check text for HIPAA identifiers."""- violations = {}- total_issues = 0-- for identifier_id, config in HIPAA_IDENTIFIERS.items():- matches = []- for pattern in config["patterns"]:- found = re.findall(pattern, text, re.IGNORECASE)- matches.extend(found)-- if matches:- # Remove duplicates, limit to first 5 examples- unique_matches = list(set(matches))[:5]- violations[identifier_id] = {- "description": config["description"],- "severity": config["severity"],- "count": len(matches),- "examples": unique_matches- }- total_issues += len(matches)-- return {- "total_violations": len(violations),- "total_instances": total_issues,- "violations": violations- }+from _common import ( # noqa: E402+ ValidationError,+ error_report,+ load_json_object,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_string,+ write_json_report,+)--def check_age_compliance(text: str) -> Dict:- """Check if ages >89 are properly aggregated."""- age_pattern = r"\b(\d{2,3})\s*(?:year|yr)s?[\s-]?old\b"- ages = [int(age) for age in re.findall(age_pattern, text, re.IGNORECASE)]-- violations = [age for age in ages if age > 89]-- return {- "ages_over_89": len(violations),- "examples": violations[:5] if violations else [],- "compliant": len(violations) == 0- }+TOOL = "check_deidentification"+SAFE_HARBOR_KEYS = (+ "names",+ "geographic_subdivisions",+ "dates_and_ages",+ "telephone_numbers",+ "fax_numbers",+ "email_addresses",+ "social_security_numbers",+ "medical_record_numbers",+ "health_plan_numbers",+ "account_numbers",+ "certificate_and_license_numbers",+ "vehicle_identifiers",+ "device_identifiers",+ "urls",+ "ip_addresses",+ "biometric_identifiers",+ "full_face_images",+ "other_unique_characteristics_or_codes",+)+RESIDUAL_KEYS = (+ "free_text",+ "small_cells_and_rare_cases",+ "images_and_metadata",+ "linked_data_and_quasi_identifiers",+)+METHODS = {+ "safe_harbor",+ "expert_determination",+ "not_applicable_synthetic_or_aggregate",+}+CLEAR_STATUSES = {"cleared_by_authorized_reviewer", "not_present_by_design"}+RESIDUAL_CLEAR_STATUSES = {+ "reviewed_no_unresolved_issue",+ "not_applicable_with_rationale",+}+TOP_LEVEL_FIELDS = {+ "schema_version",+ "artifact_kind",+ "process_status",+ "safety_notice",+ "data_scope",+ "authorized_purpose",+ "authorization_verified",+ "local_only_handling_confirmed",+ "minimum_necessary_reviewed",+ "method",+ "safe_harbor_identifiers",+ "actual_knowledge_review",+ "expert_determination",+ "synthetic_or_aggregate_rationale",+ "residual_risk_review",+ "review",+}-def generate_report(filename: str) -> Dict:- """Generate de-identification compliance report."""- filepath = Path(filename)-- if not filepath.exists():- raise FileNotFoundError(f"File not found: {filename}")-- with open(filepath, 'r', encoding='utf-8') as f:- text = f.read()-- identifier_check = check_identifiers(text)- age_check = check_age_compliance(text)-- # Determine overall compliance- critical_violations = sum(- 1 for v in identifier_check["violations"].values()- if v["severity"] == "CRITICAL"- )- high_violations = sum(- 1 for v in identifier_check["violations"].values()- if v["severity"] == "HIGH"- )-- if critical_violations > 0 or high_violations >= 3:- status = "NON_COMPLIANT"- elif high_violations > 0 or not age_check["compliant"]:- status = "NEEDS_REVIEW"- else:- status = "COMPLIANT"-- report = {- "filename": str(filename),- "status": status,- "identifier_violations": identifier_check,- "age_compliance": age_check,- "recommendation": get_recommendation(status, identifier_check, age_check)- }-- return report+def _required_true(+ data: dict[str, Any],+ field: str,+ errors: list[str],+) -> None:+ try:+ if not require_bool(data.get(field), field):+ errors.append(f"{field} must be true")+ except ValidationError as exc:+ errors.append(str(exc))-def get_recommendation(status: str, identifiers: Dict, ages: Dict) -> str:- """Generate recommendation based on findings."""- if status == "COMPLIANT":- return "Document appears compliant. Perform final manual review before publication."-- recommendations = []-- if identifiers["total_violations"] > 0:- recommendations.append(- f"Remove or redact {identifiers['total_instances']} identified HIPAA identifiers."+def validate_process(data: dict[str, Any]) -> dict[str, Any]:+ """Validate recorded process gates without asserting de-identification."""+ errors: list[str] = []+ warnings: list[str] = []+ try:+ require_exact_keys(data, TOP_LEVEL_FIELDS, "checklist")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("process_status") != "BLOCKED_NOT_ASSESSED":+ raise ValidationError("process_status must remain BLOCKED_NOT_ASSESSED")+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ require_exact_keys(+ data.get("safe_harbor_identifiers"),+ SAFE_HARBOR_KEYS,+ "safe_harbor_identifiers",)-- if not ages["compliant"]:- recommendations.append(- f"Aggregate {ages['ages_over_89']} age(s) >89 years to '90 or older' or '>89 years'."+ require_exact_keys(+ data.get("actual_knowledge_review"),+ {"completed_by_authorized_privacy_reviewer", "record_reference"},+ "actual_knowledge_review",)-- return " ".join(recommendations)+ require_exact_keys(+ data.get("expert_determination"),+ {+ "completed_by_qualified_expert",+ "expert_documentation_reference",+ "anticipated_recipient_and_conditions_documented",+ },+ "expert_determination",+ )+ require_exact_keys(+ data.get("synthetic_or_aggregate_rationale"),+ {"origin_verified", "record_reference"},+ "synthetic_or_aggregate_rationale",+ )+ require_exact_keys(+ data.get("residual_risk_review"),+ RESIDUAL_KEYS,+ "residual_risk_review",+ )+ require_exact_keys(+ data.get("review"),+ {+ "privacy_legal_review",+ "institutional_release_review",+ "release_authorized",+ },+ "review",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ if data.get("artifact_kind") != "deidentification_process_checklist":+ errors.append("artifact_kind must be deidentification_process_checklist")+ try:+ data_scope = require_data_class(data.get("data_scope"))+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ except ValidationError as exc:+ errors.append(str(exc))+ data_scope = ""++ for field in (+ "authorization_verified",+ "local_only_handling_confirmed",+ "minimum_necessary_reviewed",+ ):+ _required_true(data, field, errors)+ method = data.get("method")+ if method not in METHODS:+ errors.append(f"method must be one of {sorted(METHODS)}")+ elif method == "safe_harbor":+ statuses = data.get("safe_harbor_identifiers")+ if not isinstance(statuses, dict):+ errors.append("safe_harbor_identifiers must be an object")+ else:+ missing = sorted(set(SAFE_HARBOR_KEYS) - set(statuses))+ extra = sorted(set(statuses) - set(SAFE_HARBOR_KEYS))+ if missing:+ errors.append(f"missing Safe Harbor categories: {missing}")+ if extra:+ errors.append(f"unexpected Safe Harbor categories: {extra}")+ for key in SAFE_HARBOR_KEYS:+ if statuses.get(key) not in CLEAR_STATUSES:+ errors.append(f"safe_harbor_identifiers.{key} is not cleared")+ actual = data.get("actual_knowledge_review")+ if not isinstance(actual, dict):+ errors.append("actual_knowledge_review must be an object")+ else:+ try:+ if not require_bool(+ actual.get("completed_by_authorized_privacy_reviewer"),+ "actual_knowledge_review.completed_by_authorized_privacy_reviewer",+ ):+ errors.append("authorized actual-knowledge review is required")+ require_string(+ actual.get("record_reference"),+ "actual_knowledge_review.record_reference",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ elif method == "expert_determination":+ expert = data.get("expert_determination")+ if not isinstance(expert, dict):+ errors.append("expert_determination must be an object")+ else:+ try:+ if not require_bool(+ expert.get("completed_by_qualified_expert"),+ "expert_determination.completed_by_qualified_expert",+ ):+ errors.append("qualified Expert Determination is required")+ require_string(+ expert.get("expert_documentation_reference"),+ "expert_determination.expert_documentation_reference",+ )+ if not require_bool(+ expert.get("anticipated_recipient_and_conditions_documented"),+ "expert_determination.anticipated_recipient_and_conditions_documented",+ ):+ errors.append("anticipated recipient and conditions must be documented")+ except ValidationError as exc:+ errors.append(str(exc))+ elif method == "not_applicable_synthetic_or_aggregate":+ if data_scope not in {"synthetic", "aggregate"}:+ errors.append(+ "not_applicable_synthetic_or_aggregate requires synthetic or aggregate scope"+ )+ rationale = data.get("synthetic_or_aggregate_rationale")+ if not isinstance(rationale, dict):+ errors.append("synthetic_or_aggregate_rationale must be an object")+ else:+ try:+ if not require_bool(+ rationale.get("origin_verified"),+ "synthetic_or_aggregate_rationale.origin_verified",+ ):+ errors.append("synthetic or aggregate origin must be verified")+ require_string(+ rationale.get("record_reference"),+ "synthetic_or_aggregate_rationale.record_reference",+ )+ except ValidationError as exc:+ errors.append(str(exc))-def print_report(report: Dict):- """Print human-readable report."""- print("=" * 70)- print("HIPAA DE-IDENTIFICATION CHECK")- print(f"File: {report['filename']}")- print("=" * 70)- print()-- print(f"Overall Status: {report['status']}")- print()-- if report["identifier_violations"]["total_violations"] == 0:- print("✓ No HIPAA identifiers detected")+ residual = data.get("residual_risk_review")+ if not isinstance(residual, dict):+ errors.append("residual_risk_review must be an object")else:- print(f"⚠ Found {report['identifier_violations']['total_violations']} types of violations")- print(f" Total instances: {report['identifier_violations']['total_instances']}")- print()-- print("Violations by type:")- print("-" * 70)-- for id_type, details in sorted(- report["identifier_violations"]["violations"].items(),- key=lambda x: {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2}[x[1]["severity"]]- ):- severity_symbol = "⚠⚠⚠" if details["severity"] == "CRITICAL" else "⚠⚠" if details["severity"] == "HIGH" else "⚠"- print(f"{severity_symbol} [{details['severity']:8}] {details['description']}")- print(f" Count: {details['count']}")- print(f" Examples:")- for example in details["examples"]:- print(f" - {example}")- print()-- age_check = report["age_compliance"]- if age_check["compliant"]:- print("✓ Age reporting compliant (no ages >89 or properly aggregated)")+ for key in RESIDUAL_KEYS:+ if residual.get(key) not in RESIDUAL_CLEAR_STATUSES:+ errors.append(f"residual_risk_review.{key} is unresolved")++ review = data.get("review")+ if not isinstance(review, dict):+ errors.append("review must be an object")else:- print(f"⚠ Age compliance issue: {age_check['ages_over_89']} age(s) >89 detected")- print(f" Ages must be aggregated to '90 or older' or '>89 years'")- print(f" Ages found: {age_check['examples']}")-- print()- print("Recommendation:")- print(report["recommendation"])- print("=" * 70)+ for field in ("privacy_legal_review", "institutional_release_review"):+ if review.get(field) != "completed":+ warnings.append(f"review.{field} remains required")+ if review.get("release_authorized") is not False:+ errors.append("review.release_authorized must remain false")++ return {+ "tool": TOOL,+ "status": "BLOCKED" if errors else "PROCESS_DOCUMENTED_REVIEW_REQUIRED",+ "method": method,+ "errors": errors,+ "warnings": warnings,+ "limitations": [+ "No patient text or files were scanned.",+ "Does not establish de-identification, no-actual-knowledge, Expert Determination, or HIPAA compliance.",+ ],+ "review_required": True,+ "authorizes_release_or_submission": False,+ }-def main():- """Main entry point."""+def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(- description="Check clinical reports for HIPAA identifiers"+ description=(+ "Check bounded JSON de-identification process documentation. "+ "Never labels data HIPAA-compliant or guaranteed de-identified."+ ))- parser.add_argument("input_file", help="Path to clinical report file")- parser.add_argument("--output", "-o", help="Output JSON report to file")- parser.add_argument("--json", action="store_true", help="Output JSON to stdout")-- args = parser.parse_args()-+ parser.add_argument("input_file", help="Local process checklist (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)try:- report = generate_report(args.input_file)-- if args.json:- print(json.dumps(report, indent=2))- else:- print_report(report)-- if args.output:- with open(args.output, 'w') as f:- json.dump(report, f, indent=2)- print(f"\nJSON report saved to: {args.output}")-- # Exit with non-zero if violations found- exit_code = 0 if report["status"] == "COMPLIANT" else 1- return exit_code-- except Exception as e:- print(f"Error: {e}")- return 1+ _, data = load_json_object(args.input_file)+ report = validate_process(data)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)+ try:+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return 0 if report["status"] == "PROCESS_DOCUMENTED_REVIEW_REQUIRED" else 1if __name__ == "__main__":- import sys- sys.exit(main())-+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/compliance_checker.py b/skills/clinical-reports/scripts/compliance_checker.pydeleted file mode 100755index dece5cd1..00000000--- a/skills/clinical-reports/scripts/compliance_checker.py+++ /dev/null@@ -1,78 +0,0 @@-#!/usr/bin/env python3-"""-Check clinical reports for regulatory compliance (HIPAA, GCP, FDA).--Usage:- python compliance_checker.py <report_file>-"""--import argparse-import json-import re---COMPLIANCE_CHECKS = {- "hipaa": {- "consent_statement": r"(?i)(informed\s+consent|written\s+consent).*obtained",- "deidentification": r"(?i)(de-identif|anonymi[sz])",- },- "gcp": {- "irb_approval": r"(?i)(IRB|IEC|ethics\s+committee).*approv",- "protocol_compliance": r"(?i)protocol",- "informed_consent": r"(?i)informed\s+consent",- },- "fda": {- "study_id": r"(?i)(IND|IDE|protocol)\s+(number|#)[:]\s*\S+",- "safety_reporting": r"(?i)(adverse\s+event|SAE)",- }-}---def check_compliance(filename: str) -> dict:- """Check regulatory compliance."""- with open(filename, 'r', encoding='utf-8') as f:- content = f.read()-- results = {}- for regulation, checks in COMPLIANCE_CHECKS.items():- reg_results = {}- for check_name, pattern in checks.items():- reg_results[check_name] = bool(re.search(pattern, content))- results[regulation] = reg_results-- return {"filename": filename, "compliance": results}---def main():- """Main entry point."""- parser = argparse.ArgumentParser(description="Check regulatory compliance")- parser.add_argument("input_file", help="Path to clinical report")- parser.add_argument("--json", action="store_true")-- args = parser.parse_args()-- try:- report = check_compliance(args.input_file)-- if args.json:- print(json.dumps(report, indent=2))- else:- print("\nRegulatory Compliance Check:\n")- for reg, checks in report["compliance"].items():- print(f"{reg.upper()}:")- for check, passed in checks.items():- symbol = "✓" if passed else "✗"- print(f" {symbol} {check}")- print()-- return 0-- except Exception as e:- print(f"Error: {e}")- return 1---if __name__ == "__main__":- import sys- sys.exit(main())-diff --git a/skills/clinical-reports/scripts/consistency_checker.py b/skills/clinical-reports/scripts/consistency_checker.pynew file mode 100644index 00000000..05c7a87a--- /dev/null+++ b/skills/clinical-reports/scripts/consistency_checker.py@@ -0,0 +1,390 @@+#!/usr/bin/env python3+"""Check structured dates, units, denominators, percentages, and totals."""++from __future__ import annotations++import argparse+import math+import sys+from typing import Any++sys.dont_write_bytecode = True++from _common import ( # noqa: E402+ ValidationError,+ error_report,+ load_json_object,+ parse_iso_date,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_identifier,+ require_nonnegative_int,+ require_string,+ write_json_report,+)++TOOL = "consistency_checker"+TOP_LEVEL_FIELDS = {+ "schema_version",+ "artifact_kind",+ "manifest_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "provenance_manifest",+ "dates",+ "date_ranges",+ "quantities",+ "proportions",+ "totals",+}+++def _array(data: dict[str, Any], field: str, errors: list[str]) -> list[Any]:+ value = data.get(field, [])+ if not isinstance(value, list):+ errors.append(f"{field} must be an array")+ return []+ if len(value) > 10_000:+ errors.append(f"{field} may contain at most 10,000 items")+ return value[:10_000]+ return value+++def _finite_number(value: Any, field: str) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValidationError(f"{field} must be a number")+ number = float(value)+ if not math.isfinite(number):+ raise ValidationError(f"{field} must be finite")+ return number+++def _track_id(+ value: Any,+ field: str,+ seen: set[str],+ errors: list[str],+) -> str | None:+ try:+ identifier = require_identifier(value, field)+ except ValidationError as exc:+ errors.append(str(exc))+ return None+ if identifier in seen:+ errors.append(f"duplicate check id: {identifier}")+ seen.add(identifier)+ return identifier+++def validate_consistency(data: dict[str, Any]) -> dict[str, Any]:+ """Return deterministic discrepancies without changing any values."""+ errors: list[str] = []+ discrepancies: list[str] = []+ warnings: list[str] = []+ seen_ids: set[str] = set()+ checked = 0++ try:+ require_exact_keys(data, TOP_LEVEL_FIELDS, "manifest")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("manifest_status") != "BLOCKED_INCOMPLETE":+ raise ValidationError("manifest_status must remain BLOCKED_INCOMPLETE")+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ if not require_bool(data.get("authorization_verified"), "authorization_verified"):+ raise ValidationError("authorization_verified must be true")+ require_string(data.get("provenance_manifest"), "provenance_manifest")+ except ValidationError as exc:+ errors.append(str(exc))+ if data.get("artifact_kind") != "consistency_manifest":+ errors.append("artifact_kind must be consistency_manifest")+ try:+ require_data_class(data.get("data_classification"))+ except ValidationError as exc:+ errors.append(str(exc))++ for index, item in enumerate(_array(data, "dates", errors)):+ try:+ item = require_exact_keys(+ item,+ {"id", "date", "source_fact_id"},+ f"dates[{index}]",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ check_id = _track_id(item.get("id"), f"dates[{index}].id", seen_ids, errors)+ try:+ parse_iso_date(item.get("date"), f"dates[{index}].date")+ require_identifier(+ item.get("source_fact_id"),+ f"dates[{index}].source_fact_id",+ )+ checked += 1+ except ValidationError as exc:+ errors.append(str(exc))+ if check_id is None:+ continue++ for index, item in enumerate(_array(data, "date_ranges", errors)):+ try:+ item = require_exact_keys(+ item,+ {"id", "start", "end", "source_fact_id"},+ f"date_ranges[{index}]",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ check_id = _track_id(+ item.get("id"),+ f"date_ranges[{index}].id",+ seen_ids,+ errors,+ )+ try:+ start = parse_iso_date(item.get("start"), f"date_ranges[{index}].start")+ end = parse_iso_date(item.get("end"), f"date_ranges[{index}].end")+ require_identifier(+ item.get("source_fact_id"),+ f"date_ranges[{index}].source_fact_id",+ )+ checked += 1+ if start > end and check_id:+ discrepancies.append(f"{check_id}: start date is after end date")+ except ValidationError as exc:+ errors.append(str(exc))++ series_units: dict[str, str] = {}+ for index, item in enumerate(_array(data, "quantities", errors)):+ try:+ item = require_exact_keys(+ item,+ {+ "id",+ "series_id",+ "value",+ "unit",+ "expected_unit",+ "source_fact_id",+ },+ f"quantities[{index}]",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ check_id = _track_id(+ item.get("id"),+ f"quantities[{index}].id",+ seen_ids,+ errors,+ )+ try:+ series_id = require_identifier(+ item.get("series_id"),+ f"quantities[{index}].series_id",+ )+ _finite_number(item.get("value"), f"quantities[{index}].value")+ unit = require_string(+ item.get("unit"),+ f"quantities[{index}].unit",+ max_length=80,+ )+ require_identifier(+ item.get("source_fact_id"),+ f"quantities[{index}].source_fact_id",+ )+ checked += 1+ prior = series_units.get(series_id)+ if prior is not None and prior != unit and check_id:+ discrepancies.append(+ f"{check_id}: unit {unit!r} differs from prior series unit {prior!r}"+ )+ else:+ series_units[series_id] = unit+ expected = item.get("expected_unit")+ if expected is not None:+ expected_unit = require_string(+ expected,+ f"quantities[{index}].expected_unit",+ max_length=80,+ )+ if expected_unit != unit and check_id:+ discrepancies.append(+ f"{check_id}: unit does not match expected_unit"+ )+ except ValidationError as exc:+ errors.append(str(exc))++ for index, item in enumerate(_array(data, "proportions", errors)):+ try:+ item = require_exact_keys(+ item,+ {+ "id",+ "numerator",+ "denominator",+ "reported_percent",+ "tolerance_percentage_points",+ "source_fact_id",+ },+ f"proportions[{index}]",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ check_id = _track_id(+ item.get("id"),+ f"proportions[{index}].id",+ seen_ids,+ errors,+ )+ try:+ numerator = require_nonnegative_int(+ item.get("numerator"),+ f"proportions[{index}].numerator",+ )+ denominator = require_nonnegative_int(+ item.get("denominator"),+ f"proportions[{index}].denominator",+ )+ reported = _finite_number(+ item.get("reported_percent"),+ f"proportions[{index}].reported_percent",+ )+ tolerance = _finite_number(+ item.get("tolerance_percentage_points", 0.05),+ f"proportions[{index}].tolerance_percentage_points",+ )+ require_identifier(+ item.get("source_fact_id"),+ f"proportions[{index}].source_fact_id",+ )+ checked += 1+ if denominator == 0:+ errors.append(f"proportions[{index}].denominator must be greater than zero")+ elif numerator > denominator and check_id:+ discrepancies.append(f"{check_id}: numerator exceeds denominator")+ elif not 0 <= reported <= 100 and check_id:+ discrepancies.append(f"{check_id}: reported_percent is outside 0-100")+ elif tolerance < 0:+ errors.append(+ f"proportions[{index}].tolerance_percentage_points must be non-negative"+ )+ else:+ calculated = numerator / denominator * 100+ if abs(calculated - reported) > tolerance and check_id:+ discrepancies.append(+ f"{check_id}: reported_percent differs from n/N beyond tolerance"+ )+ except ValidationError as exc:+ errors.append(str(exc))++ for index, item in enumerate(_array(data, "totals", errors)):+ try:+ item = require_exact_keys(+ item,+ {"id", "components", "reported_total", "source_fact_ids"},+ f"totals[{index}]",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ check_id = _track_id(+ item.get("id"),+ f"totals[{index}].id",+ seen_ids,+ errors,+ )+ try:+ components = item.get("components")+ if not isinstance(components, list) or not components:+ raise ValidationError(f"totals[{index}].components must be non-empty")+ parsed_components = [+ require_nonnegative_int(value, f"totals[{index}].components")+ for value in components+ ]+ reported_total = require_nonnegative_int(+ item.get("reported_total"),+ f"totals[{index}].reported_total",+ )+ source_fact_ids = item.get("source_fact_ids")+ if not isinstance(source_fact_ids, list) or not source_fact_ids:+ raise ValidationError(+ f"totals[{index}].source_fact_ids must be non-empty"+ )+ for fact_id in source_fact_ids:+ require_identifier(fact_id, f"totals[{index}].source_fact_ids")+ checked += 1+ if sum(parsed_components) != reported_total and check_id:+ discrepancies.append(f"{check_id}: components do not equal reported_total")+ except ValidationError as exc:+ errors.append(str(exc))++ if checked == 0:+ errors.append("manifest contains no valid checks")+ if not discrepancies and not errors:+ warnings.append("No discrepancy was found within the declared checks and tolerances.")++ status = (+ "BLOCKED_INVALID_SCHEMA"+ if errors+ else "DISCREPANCIES_REQUIRE_RESOLUTION"+ if discrepancies+ else "CONSISTENT_WITHIN_DECLARED_TOLERANCES_REVIEW_REQUIRED"+ )+ return {+ "tool": TOOL,+ "status": status,+ "checks_completed": checked,+ "errors": errors,+ "discrepancies": discrepancies,+ "warnings": warnings,+ "limitations": [+ "No source was chosen as authoritative and no value was changed.",+ "Arithmetic and format checks do not validate clinical or statistical meaning.",+ ],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check bounded structured dates, units, n/N percentages, and totals. "+ "Does not infer, convert, reconcile, or alter values."+ )+ )+ parser.add_argument("input_file", help="Local consistency manifest (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ _, data = load_json_object(args.input_file)+ report = validate_consistency(data)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)+ try:+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return (+ 0+ if report["status"]+ == "CONSISTENT_WITHIN_DECLARED_TOLERANCES_REVIEW_REQUIRED"+ else 1+ )+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/extract_clinical_data.py b/skills/clinical-reports/scripts/extract_clinical_data.pydeleted file mode 100755index 7fdae48a..00000000--- a/skills/clinical-reports/scripts/extract_clinical_data.py+++ /dev/null@@ -1,102 +0,0 @@-#!/usr/bin/env python3-"""-Extract structured clinical data from reports.--Usage:- python extract_clinical_data.py <report_file>-"""--import argparse-import json-import re---def extract_vital_signs(content: str) -> dict:- """Extract vital signs."""- vitals = {}- patterns = {- "temperature": r"(?i)temp(?:erature)?[:]\s*([\d.]+)\s*°?F",- "bp": r"(?i)BP[:]\s*(\d+/\d+)",- "hr": r"(?i)HR[:]\s*(\d+)",- "rr": r"(?i)RR[:]\s*(\d+)",- "spo2": r"(?i)SpO2[:]\s*([\d.]+)%",- }-- for vital, pattern in patterns.items():- match = re.search(pattern, content)- if match:- vitals[vital] = match.group(1)-- return vitals---def extract_demographics(content: str) -> dict:- """Extract patient demographics."""- demographics = {}- patterns = {- "age": r"(?i)(\d+)[\s-]year[\s-]old",- "sex": r"(?i)(male|female|M|F)",- }-- for demo, pattern in patterns.items():- match = re.search(pattern, content)- if match:- demographics[demo] = match.group(1)-- return demographics---def extract_medications(content: str) -> list:- """Extract medication list."""- meds = []- # Simple pattern for common medication format- pattern = r"(?i)(\w+)\s+(\d+\s*mg)\s+(PO|IV|SC)\s+(daily|BID|TID|QID)"- matches = re.findall(pattern, content)-- for match in matches:- meds.append({- "drug": match[0],- "dose": match[1],- "route": match[2],- "frequency": match[3]- })-- return meds---def main():- """Main entry point."""- parser = argparse.ArgumentParser(description="Extract clinical data")- parser.add_argument("input_file", help="Path to clinical report")- parser.add_argument("--output", "-o", help="Output JSON file")-- args = parser.parse_args()-- try:- with open(args.input_file, 'r', encoding='utf-8') as f:- content = f.read()-- extracted_data = {- "demographics": extract_demographics(content),- "vital_signs": extract_vital_signs(content),- "medications": extract_medications(content),- }-- if args.output:- with open(args.output, 'w') as f:- json.dump(extracted_data, f, indent=2)- print(f"✓ Data extracted to: {args.output}")- else:- print(json.dumps(extracted_data, indent=2))-- return 0-- except Exception as e:- print(f"Error: {e}")- return 1---if __name__ == "__main__":- import sys- sys.exit(main())-diff --git a/skills/clinical-reports/scripts/format_adverse_events.py b/skills/clinical-reports/scripts/format_adverse_events.pyold mode 100755new mode 100644index 5b65dcb0..e09a4f81--- a/skills/clinical-reports/scripts/format_adverse_events.py+++ b/skills/clinical-reports/scripts/format_adverse_events.py@@ -1,103 +1,455 @@#!/usr/bin/env python3-"""-Format adverse event data into tables for clinical trial reports.+"""Format bounded aggregate adverse-event counts into a review-only Markdown table."""-Converts CSV or structured data into formatted AE summary tables.--Usage:- python format_adverse_events.py <ae_data.csv>-"""+from __future__ import annotationsimport argparseimport csv-from collections import defaultdict+import re+import sys+from dataclasses import dataclassfrom pathlib import Path+sys.dont_write_bytecode = True++from _common import ( # noqa: E402+ MAX_CSV_BYTES,+ MAX_CSV_ROWS,+ ValidationError,+ load_json_object,+ local_input_path,+ local_output_path,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_string,+)++TOOL = "format_adverse_events"+REQUIRED_COLUMNS = (+ "analysis_set",+ "treatment_group",+ "meddra_version",+ "system_organ_class",+ "preferred_term",+ "subjects_affected",+ "event_count",+ "denominator",+)+FORBIDDEN_HEADER_FRAGMENTS = {+ "patient",+ "subject_id",+ "participant",+ "case_id",+ "initial",+ "name",+ "email",+ "phone",+ "address",+ "narrative",+ "verbatim",+ "onset",+ "date",+ "mrn",+}+VERSION_RE = re.compile(r"^\d{1,2}\.\d$")+METADATA_FIELDS = {+ "schema_version",+ "artifact_kind",+ "draft_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "local_only_handling_confirmed",+ "analysis_metadata",+ "input_csv",+ "required_columns",+ "prohibited_content",+ "provenance_manifest",+ "review",+}+ANALYSIS_METADATA_FIELDS = {+ "protocol_reference",+ "sap_reference",+ "data_cut_reference",+ "analysis_set",+ "counting_rule",+ "threshold_rule",+ "meddra_version",+ "meddra_language",+ "coding_source_reference",+}+++@dataclass(frozen=True)+class AggregateRow:+ analysis_set: str+ treatment_group: str+ meddra_version: str+ system_organ_class: str+ preferred_term: str+ subjects_affected: int+ event_count: int+ denominator: int+++def validate_aggregate_metadata(+ data: dict[str, object],+ *,+ input_name: str,+) -> dict[str, object]:+ """Require an authorized aggregate-only sidecar manifest."""+ require_exact_keys(data, METADATA_FIELDS, "metadata")+ if data.get("schema_version") != "2.0":+ raise ValidationError("metadata schema_version must be 2.0")+ if data.get("artifact_kind") != "clinical_trial_safety_aggregate_draft":+ raise ValidationError(+ "metadata artifact_kind must be clinical_trial_safety_aggregate_draft"+ )+ if (+ data.get("draft_status")+ != "BLOCKED_INCOMPLETE_NOT_AN_INDIVIDUAL_CASE_SAFETY_REPORT"+ ):+ raise ValidationError("metadata must preserve the blocked non-ICSR status")+ require_string(data.get("safety_notice"), "metadata.safety_notice", max_length=1000)+ if require_data_class(data.get("data_classification")) != "aggregate":+ raise ValidationError("AE formatter accepts aggregate data only")+ require_string(data.get("authorized_purpose"), "metadata.authorized_purpose")+ if not require_bool(+ data.get("authorization_verified"),+ "metadata.authorization_verified",+ ):+ raise ValidationError("metadata.authorization_verified must be true")+ if not require_bool(+ data.get("local_only_handling_confirmed"),+ "metadata.local_only_handling_confirmed",+ ):+ raise ValidationError("metadata.local_only_handling_confirmed must be true")+ require_string(data.get("provenance_manifest"), "metadata.provenance_manifest")+ if data.get("input_csv") != input_name:+ raise ValidationError("metadata.input_csv must equal the aggregate CSV filename")+ if data.get("required_columns") != list(REQUIRED_COLUMNS):+ raise ValidationError("metadata.required_columns does not match the formatter schema")+ prohibited = data.get("prohibited_content")+ if not isinstance(prohibited, list) or not prohibited:+ raise ValidationError("metadata.prohibited_content must be non-empty")++ analysis = require_exact_keys(+ data.get("analysis_metadata"),+ ANALYSIS_METADATA_FIELDS,+ "metadata.analysis_metadata",+ )+ for field in ANALYSIS_METADATA_FIELDS:+ require_string(+ analysis.get(field),+ f"metadata.analysis_metadata.{field}",+ max_length=500,+ )+ if not VERSION_RE.fullmatch(str(analysis["meddra_version"])):+ raise ValidationError("metadata MedDRA version must look like 29.0")++ review = require_exact_keys(+ data.get("review"),+ {+ "safety_coding_review",+ "statistical_review",+ "privacy_review",+ "regulatory_review",+ "submission_authorized",+ },+ "metadata.review",+ )+ if review.get("submission_authorized") is not False:+ raise ValidationError("metadata.review.submission_authorized must remain false")+ return data+++def load_aggregate_metadata(+ raw_path: str,+ *,+ input_name: str,+) -> dict[str, object]:+ """Load a bounded aggregate metadata sidecar."""+ _, data = load_json_object(raw_path)+ return validate_aggregate_metadata(data, input_name=input_name)+++def _label(value: str | None, field: str) -> str:+ if value is None:+ raise ValidationError(f"{field} is required")+ text = value.strip()+ if (+ not 1 <= len(text) <= 200+ or not text[0].isalnum()+ or any(char in "|`<>\r\n" or ord(char) < 32 for char in text)+ ):+ raise ValidationError(+ f"{field} must be a bounded label without markup or line breaks"+ )+ return text+++def _count(value: str | None, field: str) -> int:+ if value is None or not re.fullmatch(r"\d{1,9}", value.strip()):+ raise ValidationError(f"{field} must be a non-negative integer")+ return int(value)-def format_ae_summary_table(data: list) -> str:- """Generate AE summary table in markdown format."""- # Group by treatment arm- arm_stats = defaultdict(lambda: {- 'total': 0,- 'any_ae': 0,- 'related_ae': 0,- 'sae': 0,- 'deaths': 0,- 'discontinuations': 0- })-- for row in data:- arm = row.get('treatment_arm', 'Unknown')- arm_stats[arm]['total'] += 1-- if row.get('any_ae', '').lower() == 'yes':- arm_stats[arm]['any_ae'] += 1- if row.get('related', '').lower() == 'yes':- arm_stats[arm]['related_ae'] += 1- if row.get('serious', '').lower() == 'yes':- arm_stats[arm]['sae'] += 1- if row.get('fatal', '').lower() == 'yes':- arm_stats[arm]['deaths'] += 1- if row.get('discontinuation', '').lower() == 'yes':- arm_stats[arm]['discontinuations'] += 1-- # Generate table- table = "| Category | " + " | ".join(arm_stats.keys()) + " |\n"- table += "|----------|" + "|".join(["--------"] * len(arm_stats)) + "|\n"-- categories = [- ('Total N', 'total'),- ('Any AE', 'any_ae'),- ('Treatment-related AE', 'related_ae'),- ('Serious AE', 'sae'),- ('Deaths', 'deaths'),- ('Discontinuation due to AE', 'discontinuations')++def load_aggregate_csv(raw_path: str) -> list[AggregateRow]:+ """Load and validate aggregate-only AE rows."""+ path = local_input_path(+ raw_path,+ suffixes={".csv"},+ max_bytes=MAX_CSV_BYTES,+ )+ try:+ path.read_text(encoding="utf-8-sig")+ except UnicodeDecodeError as exc:+ raise ValidationError("CSV input must be UTF-8") from exc+ handle = path.open("r", encoding="utf-8-sig", newline="")++ rows: list[AggregateRow] = []+ with handle:+ reader = csv.DictReader(handle)+ if reader.fieldnames is None:+ raise ValidationError("CSV header is required")+ normalized_headers = [header.strip() for header in reader.fieldnames]+ lowered = {header.lower() for header in normalized_headers}+ for header in lowered:+ if any(fragment in header for fragment in FORBIDDEN_HEADER_FRAGMENTS):+ raise ValidationError(f"row-level or sensitive column is prohibited: {header}")+ if set(normalized_headers) != set(REQUIRED_COLUMNS):+ raise ValidationError(+ f"CSV columns must be exactly: {list(REQUIRED_COLUMNS)}"+ )++ for line_number, raw in enumerate(reader, start=2):+ if len(rows) >= MAX_CSV_ROWS:+ raise ValidationError(f"CSV exceeds {MAX_CSV_ROWS} data rows")+ if None in raw:+ raise ValidationError(f"row {line_number} contains extra columns")+ row = AggregateRow(+ analysis_set=_label(raw.get("analysis_set"), f"row {line_number} analysis_set"),+ treatment_group=_label(+ raw.get("treatment_group"),+ f"row {line_number} treatment_group",+ ),+ meddra_version=_label(+ raw.get("meddra_version"),+ f"row {line_number} meddra_version",+ ),+ system_organ_class=_label(+ raw.get("system_organ_class"),+ f"row {line_number} system_organ_class",+ ),+ preferred_term=_label(+ raw.get("preferred_term"),+ f"row {line_number} preferred_term",+ ),+ subjects_affected=_count(+ raw.get("subjects_affected"),+ f"row {line_number} subjects_affected",+ ),+ event_count=_count(+ raw.get("event_count"),+ f"row {line_number} event_count",+ ),+ denominator=_count(+ raw.get("denominator"),+ f"row {line_number} denominator",+ ),+ )+ if not VERSION_RE.fullmatch(row.meddra_version):+ raise ValidationError(+ f"row {line_number} MedDRA version must look like 29.0"+ )+ if row.denominator == 0:+ raise ValidationError(f"row {line_number} denominator must be greater than zero")+ if row.subjects_affected > row.denominator:+ raise ValidationError(+ f"row {line_number} subjects_affected exceeds denominator"+ )+ if row.event_count < row.subjects_affected:+ raise ValidationError(+ f"row {line_number} event_count is less than subjects_affected"+ )+ rows.append(row)++ if not rows:+ raise ValidationError("CSV must contain at least one aggregate data row")++ group_metadata: dict[tuple[str, str], tuple[int, str]] = {}+ row_keys: set[tuple[str, str, str, str]] = set()+ for row in rows:+ group = (row.analysis_set, row.treatment_group)+ metadata = (row.denominator, row.meddra_version)+ if group in group_metadata and group_metadata[group] != metadata:+ raise ValidationError(+ f"inconsistent denominator or MedDRA version for group {group}"+ )+ group_metadata[group] = metadata+ row_key = (+ row.analysis_set,+ row.treatment_group,+ row.system_organ_class,+ row.preferred_term,+ )+ if row_key in row_keys:+ raise ValidationError(f"duplicate aggregate row: {row_key}")+ row_keys.add(row_key)+ return rows+++def render_markdown(+ rows: list[AggregateRow],+ *,+ metadata: dict[str, object],+ expected_meddra_version: str | None = None,+) -> str:+ """Render rows without inferring missing cells or statistical comparisons."""+ versions = sorted({row.meddra_version for row in rows})+ if len(versions) != 1:+ raise ValidationError("one table may contain exactly one MedDRA version")+ analysis_metadata = metadata["analysis_metadata"]+ if not isinstance(analysis_metadata, dict):+ raise ValidationError("metadata.analysis_metadata must be an object")+ metadata_version = str(analysis_metadata["meddra_version"])+ if versions != [metadata_version]:+ raise ValidationError(+ "CSV MedDRA version does not match metadata.analysis_metadata.meddra_version"+ )+ if expected_meddra_version is not None:+ if not VERSION_RE.fullmatch(expected_meddra_version):+ raise ValidationError("--expected-meddra-version must look like 29.0")+ if versions != [expected_meddra_version]:+ raise ValidationError(+ f"input MedDRA versions {versions} do not match expected "+ f"{expected_meddra_version}"+ )++ analysis_sets = sorted({row.analysis_set for row in rows})+ if len(analysis_sets) != 1:+ raise ValidationError(+ "one output table may contain exactly one analysis_set"+ )+ if analysis_sets[0] != analysis_metadata["analysis_set"]:+ raise ValidationError(+ "CSV analysis_set does not match metadata.analysis_metadata.analysis_set"+ )+ groups = sorted({row.treatment_group for row in rows})+ denominators = {+ group: next(row.denominator for row in rows if row.treatment_group == group)+ for group in groups+ }+ lookup = {+ (row.system_organ_class, row.preferred_term, row.treatment_group): row+ for row in rows+ }+ terms = sorted({(row.system_organ_class, row.preferred_term) for row in rows})++ headers = ["System organ class", "Preferred term"]+ for group in groups:+ headers.extend(+ [+ f"{group}: subjects n/N (%)",+ f"{group}: events",+ ]+ )+ lines = [+ "# Draft aggregate adverse-event table",+ "",+ "> DRAFT — aggregate display only. Not an ICSR, reportability decision, "+ "clinical interpretation, filing, or submission. Qualified safety and "+ "statistical review is required.",+ "",+ f"- Analysis set: {analysis_sets[0]}",+ f"- MedDRA version(s), as supplied and not terminology-validated: {', '.join(versions)}",+ f"- MedDRA language, as supplied: {analysis_metadata['meddra_language']}",+ f"- Counting rule, as supplied: {analysis_metadata['counting_rule']}",+ f"- Threshold rule, as supplied: {analysis_metadata['threshold_rule']}",+ "- Missing group/term cells are shown as an em dash and are not assumed to be zero.",+ "- Subjects and events are distinct; event counts may exceed subject counts.",+ "",+ "| " + " | ".join(headers) + " |",+ "| " + " | ".join(["---"] * len(headers)) + " |",]-- for cat_name, cat_key in categories:- row_data = [cat_name]- for arm_data in arm_stats.values():- count = arm_data[cat_key]- total = arm_data['total']- pct = (count / total * 100) if total > 0 and cat_key != 'total' else 0- value = f"{count}" if cat_key == 'total' else f"{count} ({pct:.1f}%)"- row_data.append(value)- table += "| " + " | ".join(row_data) + " |\n"-- return table---def main():- """Main entry point."""- parser = argparse.ArgumentParser(description="Format AE data into tables")- parser.add_argument("input_file", help="Path to AE data CSV")- parser.add_argument("--output", "-o", help="Output markdown file")-- args = parser.parse_args()-+ for soc, term in terms:+ cells = [soc, term]+ for group in groups:+ row = lookup.get((soc, term, group))+ if row is None:+ cells.extend(["—", "—"])+ continue+ percent = row.subjects_affected / row.denominator * 100+ cells.extend(+ [+ f"{row.subjects_affected}/{row.denominator} ({percent:.1f}%)",+ str(row.event_count),+ ]+ )+ lines.append("| " + " | ".join(cells) + " |")+ lines.extend(+ [+ "",+ "Denominators by treatment group: "+ + "; ".join(f"{group} N={denominators[group]}" for group in groups)+ + ".",+ "",+ "No MedDRA semantic validation, deduplication, inference, causal assessment, "+ "or between-group testing was performed.",+ ]+ )+ return "\n".join(lines) + "\n"+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Format aggregate-only AE CSV rows as review-only Markdown. "+ "Rejects row-level identifiers and performs no safety assessment."+ )+ )+ parser.add_argument("input_file", help="Local aggregate CSV")+ parser.add_argument(+ "--metadata",+ required=True,+ help="Authorized aggregate safety metadata sidecar (.json)",+ )+ parser.add_argument("-o", "--output", help="Optional local Markdown output")+ parser.add_argument("--expected-meddra-version")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)try:- with open(args.input_file, 'r') as f:- reader = csv.DictReader(f)- data = list(reader)-- table = format_ae_summary_table(data)-+ rows = load_aggregate_csv(args.input_file)+ input_name = Path(args.input_file).name+ metadata = load_aggregate_metadata(+ args.metadata,+ input_name=input_name,+ )+ rendered = render_markdown(+ rows,+ metadata=metadata,+ expected_meddra_version=args.expected_meddra_version,+ )if args.output:- with open(args.output, 'w') as f:- f.write(table)- print(f"✓ Table saved to: {args.output}")+ output = local_output_path(+ args.output,+ suffixes={".md"},+ overwrite=args.overwrite,+ )+ output.write_text(rendered, encoding="utf-8")else:- print("\nAdverse Events Summary Table:\n")- print(table)-+ print(rendered, end="")return 0-- except Exception as e:- print(f"Error: {e}")+ except (OSError, ValidationError, csv.Error) as exc:+ print(f"{TOOL}: BLOCKED_INVALID_INPUT: {exc}", file=sys.stderr)return 1if __name__ == "__main__":- import sys- sys.exit(main())-+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/generate_report_template.py b/skills/clinical-reports/scripts/generate_report_template.pyold mode 100755new mode 100644index 3143bc7a..341f33ad--- a/skills/clinical-reports/scripts/generate_report_template.py+++ b/skills/clinical-reports/scripts/generate_report_template.py@@ -1,163 +1,115 @@#!/usr/bin/env python3-"""-Interactive template generator for clinical reports.+"""Copy a fail-closed structured clinical-report template to a local path."""-Helps users select and generate appropriate clinical report templates.--Usage:- python generate_report_template.py- python generate_report_template.py --type case_report --output my_case_report.md-"""+from __future__ import annotationsimport argparse-import shutil+import sysfrom pathlib import Path+sys.dont_write_bytecode = True-TEMPLATES = {- "case_report": "case_report_template.md",- "soap_note": "soap_note_template.md",- "h_and_p": "history_physical_template.md",- "discharge_summary": "discharge_summary_template.md",- "consult_note": "consult_note_template.md",- "radiology": "radiology_report_template.md",- "pathology": "pathology_report_template.md",- "lab": "lab_report_template.md",- "sae": "clinical_trial_sae_template.md",- "csr": "clinical_trial_csr_template.md",-}+from _common import ( # noqa: E402+ ValidationError,+ load_json_object,+ local_input_path,+ local_output_path,+)-DESCRIPTIONS = {- "case_report": "Clinical Case Report (CARE guidelines)",- "soap_note": "SOAP Progress Note",- "h_and_p": "History and Physical Examination",- "discharge_summary": "Hospital Discharge Summary",- "consult_note": "Consultation Note",- "radiology": "Radiology/Imaging Report",- "pathology": "Surgical Pathology Report",- "lab": "Laboratory Report",- "sae": "Serious Adverse Event Report",- "csr": "Clinical Study Report (ICH-E3)",+TOOL = "generate_report_template"+TEMPLATES = {+ "case-report": "case_report_template.json",+ "radiology-scaffold": "radiology_report_template.json",+ "pathology-scaffold": "pathology_report_template.json",+ "lab-scaffold": "lab_report_template.json",+ "csr": "clinical_trial_csr_template.json",+ "trial-results": "clinical_trial_results_template.json",+ "trial-protocol-checklist": "trial_protocol_reporting_checklist.json",+ "safety-aggregate": "clinical_trial_safety_aggregate_template.json",+ "adverse-event-csv": "adverse_event_aggregate_input_template.csv",+ "research-summary": "research_summary_template.json",+ "deidentification-checklist": "deidentification_process_checklist.json",+ "quality-review": "quality_review_checklist.json",+ "provenance": "provenance_manifest_template.json",+ "terminology": "terminology_manifest_template.json",+ "consistency": "consistency_manifest_template.json",}-def get_template_dir() -> Path:- """Get the templates directory path."""- script_dir = Path(__file__).parent- template_dir = script_dir.parent / "assets"- return template_dir+def template_directory() -> Path:+ """Return the fixed bundled asset directory."""+ return Path(__file__).resolve().parent.parent / "assets"-def list_templates():- """List available templates."""- print("\nAvailable Clinical Report Templates:")- print("=" * 60)- for i, (key, desc) in enumerate(DESCRIPTIONS.items(), 1):- print(f"{i:2}. {key:20} - {desc}")- print("=" * 60)+def list_templates() -> str:+ """Return a stable machine-readable-friendly list."""+ lines = ["Available fail-closed templates:"]+ lines.extend(f"- {name}: {TEMPLATES[name]}" for name in sorted(TEMPLATES))+ return "\n".join(lines) + "\n"-def generate_template(template_type: str, output_file: str = None):- """Generate template file."""+def generate_template(+ template_type: str,+ raw_output: str,+ *,+ overwrite: bool = False,+) -> Path:+ """Copy one fixed asset without interpolation or clinical content."""if template_type not in TEMPLATES:- raise ValueError(f"Invalid template type: {template_type}")-- template_filename = TEMPLATES[template_type]- template_path = get_template_dir() / template_filename-- if not template_path.exists():- raise FileNotFoundError(f"Template not found: {template_path}")-- if output_file is None:- output_file = f"new_{template_filename}"-- shutil.copy(template_path, output_file)- print(f"✓ Template created: {output_file}")- print(f" Type: {DESCRIPTIONS[template_type]}")- print(f" Source: {template_filename}")-- return output_file---def interactive_mode():- """Interactive template selection."""- list_templates()- print()-- while True:- choice = input("Select template number (or 'q' to quit): ").strip()-- if choice.lower() == 'q':- print("Goodbye!")- return-- try:- idx = int(choice) - 1- template_types = list(TEMPLATES.keys())-- if 0 <= idx < len(template_types):- template_type = template_types[idx]- output_file = input(f"Output filename (default: new_{TEMPLATES[template_type]}): ").strip()-- if not output_file:- output_file = None-- generate_template(template_type, output_file)-- another = input("\nGenerate another template? (y/n): ").strip().lower()- if another != 'y':- print("Goodbye!")- return- else:- print()- list_templates()- print()- else:- print("Invalid selection. Please try again.")- except (ValueError, IndexError):- print("Invalid input. Please enter a number or 'q' to quit.")---def main():- """Main entry point."""- parser = argparse.ArgumentParser(- description="Generate clinical report templates"- )- parser.add_argument(- "--type",- choices=list(TEMPLATES.keys()),- help="Template type to generate"+ raise ValidationError(f"unknown template type: {template_type}")+ source = template_directory() / TEMPLATES[template_type]+ suffix = source.suffix.lower()+ validated_source = local_input_path(+ str(source),+ suffixes={suffix},+ max_bytes=1_000_000,)- parser.add_argument(- "--output",- "-o",- help="Output filename"+ if suffix == ".json":+ load_json_object(str(validated_source))+ output = local_output_path(+ raw_output,+ suffixes={suffix},+ overwrite=overwrite,)- parser.add_argument(- "--list",- action="store_true",- help="List available templates"+ output.write_bytes(validated_source.read_bytes())+ return output+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Copy a bundled fail-closed JSON/CSV template. No interpolation, "+ "network access, clinical inference, signing, filing, or submission."+ ))-- args = parser.parse_args()-+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument("--list", action="store_true", help="List template types")+ mode.add_argument("--type", choices=sorted(TEMPLATES), help="Template type")+ parser.add_argument("-o", "--output", help="Required local output when --type is used")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ if args.list:+ if args.output:+ print("--output is not used with --list", file=sys.stderr)+ return 2+ print(list_templates(), end="")+ return 0+ if not args.output:+ print("--output is required with --type", file=sys.stderr)+ return 2try:- if args.list:- list_templates()- elif args.type:- generate_template(args.type, args.output)- else:- # Interactive mode- interactive_mode()-+ output = generate_template(args.type, args.output, overwrite=args.overwrite)+ print(f"Created blocked draft template: {output}")+ print("Qualified review is required; this output is not for clinical use or submission.")return 0-- except Exception as e:- print(f"Error: {e}")+ except (OSError, ValidationError) as exc:+ print(f"{TOOL}: BLOCKED: {exc}", file=sys.stderr)return 1if __name__ == "__main__":- import sys- sys.exit(main())-+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/generate_schematic.py b/skills/clinical-reports/scripts/generate_schematic.pydeleted file mode 100644index 43331870..00000000--- a/skills/clinical-reports/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-reports/scripts/generate_schematic_ai.py b/skills/clinical-reports/scripts/generate_schematic_ai.pydeleted file mode 100644index 651b6c76..00000000--- a/skills/clinical-reports/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-reports/scripts/provenance_validator.py b/skills/clinical-reports/scripts/provenance_validator.pynew file mode 100644index 00000000..8a943891--- /dev/null+++ b/skills/clinical-reports/scripts/provenance_validator.py@@ -0,0 +1,263 @@+#!/usr/bin/env python3+"""Validate source-fact-to-claim traceability without opening source records."""++from __future__ import annotations++import argparse+import re+import sys+from typing import Any++sys.dont_write_bytecode = True++from _common import ( # noqa: E402+ SHA256_RE,+ ValidationError,+ error_report,+ load_json_object,+ parse_iso_date,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_identifier,+ require_string,+ write_json_report,+)++TOOL = "provenance_validator"+LOCAL_LOCATOR_RE = re.compile(r"^local:[A-Za-z0-9_./:-]{1,280}$")+SOURCE_KINDS = {+ "synthetic_record",+ "deidentified_record",+ "aggregate_output",+ "protocol",+ "statistical_analysis_plan",+ "published_source",+ "authorized_system_record",+}+FACT_FIELDS = {+ "fact_id",+ "source_record_kind",+ "record_locator",+ "field_path",+ "value_hash_sha256",+ "verification_status",+ "verified_by_role",+ "verified_at",+ "source_version",+}+CLAIM_FIELDS = {+ "claim_id",+ "artifact_field_path",+ "fact_ids",+ "support_status",+}+TOP_LEVEL_FIELDS = {+ "schema_version",+ "artifact_kind",+ "manifest_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "facts",+ "claims",+ "review",+}+++def validate_provenance(data: dict[str, Any]) -> dict[str, Any]:+ """Validate bounded metadata links while preserving source separation."""+ errors: list[str] = []+ warnings: list[str] = []+ try:+ require_exact_keys(data, TOP_LEVEL_FIELDS, "manifest")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("manifest_status") != "BLOCKED_INCOMPLETE":+ raise ValidationError("manifest_status must remain BLOCKED_INCOMPLETE")+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ except ValidationError as exc:+ errors.append(str(exc))+ if data.get("artifact_kind") != "provenance_manifest":+ errors.append("artifact_kind must be provenance_manifest")+ try:+ require_data_class(data.get("data_classification"))+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ if not require_bool(data.get("authorization_verified"), "authorization_verified"):+ errors.append("authorization_verified must be true")+ except ValidationError as exc:+ errors.append(str(exc))++ facts = data.get("facts")+ claims = data.get("claims")+ if not isinstance(facts, list) or not facts:+ errors.append("facts must be a non-empty array")+ facts = []+ if not isinstance(claims, list) or not claims:+ errors.append("claims must be a non-empty array")+ claims = []+ if len(facts) > 10_000:+ errors.append("facts may contain at most 10,000 items")+ if len(claims) > 10_000:+ errors.append("claims may contain at most 10,000 items")++ fact_ids: set[str] = set()+ for index, fact in enumerate(facts[:10_000]):+ try:+ fact = require_exact_keys(fact, FACT_FIELDS, f"facts[{index}]")+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ try:+ fact_id = require_identifier(fact.get("fact_id"), f"facts[{index}].fact_id")+ if fact_id in fact_ids:+ errors.append(f"duplicate fact_id: {fact_id}")+ fact_ids.add(fact_id)+ if fact.get("source_record_kind") not in SOURCE_KINDS:+ errors.append(f"facts[{index}].source_record_kind is invalid")+ locator = require_string(+ fact.get("record_locator"),+ f"facts[{index}].record_locator",+ max_length=286,+ )+ if not LOCAL_LOCATOR_RE.fullmatch(locator):+ errors.append(+ f"facts[{index}].record_locator must be a local: locator"+ )+ require_string(+ fact.get("field_path"),+ f"facts[{index}].field_path",+ max_length=300,+ )+ value_hash = require_string(+ fact.get("value_hash_sha256"),+ f"facts[{index}].value_hash_sha256",+ max_length=64,+ )+ if not SHA256_RE.fullmatch(value_hash):+ errors.append(f"facts[{index}].value_hash_sha256 is invalid")+ if fact.get("verification_status") != "verified":+ errors.append(f"facts[{index}] is not verified")+ require_string(+ fact.get("verified_by_role"),+ f"facts[{index}].verified_by_role",+ max_length=100,+ )+ parse_iso_date(fact.get("verified_at"), f"facts[{index}].verified_at")+ require_string(+ fact.get("source_version"),+ f"facts[{index}].source_version",+ max_length=100,+ )+ except ValidationError as exc:+ errors.append(str(exc))++ claim_ids: set[str] = set()+ referenced_facts: set[str] = set()+ for index, claim in enumerate(claims[:10_000]):+ try:+ claim = require_exact_keys(claim, CLAIM_FIELDS, f"claims[{index}]")+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ try:+ claim_id = require_identifier(+ claim.get("claim_id"),+ f"claims[{index}].claim_id",+ )+ if claim_id in claim_ids:+ errors.append(f"duplicate claim_id: {claim_id}")+ claim_ids.add(claim_id)+ require_string(+ claim.get("artifact_field_path"),+ f"claims[{index}].artifact_field_path",+ max_length=300,+ )+ links = claim.get("fact_ids")+ if not isinstance(links, list) or not links:+ errors.append(f"claims[{index}].fact_ids must be a non-empty array")+ links = []+ for linked in links:+ linked_id = require_identifier(linked, f"claims[{index}].fact_ids")+ referenced_facts.add(linked_id)+ if linked_id not in fact_ids:+ errors.append(+ f"claims[{index}] references unknown fact_id {linked_id}"+ )+ if claim.get("support_status") != "supported_by_verified_facts":+ errors.append(f"claims[{index}] is not marked supported_by_verified_facts")+ except ValidationError as exc:+ errors.append(str(exc))++ unused = sorted(fact_ids - referenced_facts)+ if unused:+ warnings.append(f"{len(unused)} verified facts are not linked to a claim")++ review = data.get("review")+ try:+ review = require_exact_keys(+ review,+ {+ "source_owner_review",+ "quality_review",+ "privacy_review",+ "release_authorized",+ },+ "review",+ )+ for field in ("source_owner_review", "quality_review", "privacy_review"):+ if review.get(field) != "completed":+ warnings.append(f"review.{field} remains required")+ if review.get("release_authorized") is not False:+ errors.append("review.release_authorized must remain false")+ except ValidationError as exc:+ errors.append(str(exc))++ return {+ "tool": TOOL,+ "status": "BLOCKED" if errors else "TRACEABILITY_COMPLETE_REVIEW_REQUIRED",+ "fact_count": len(facts),+ "claim_count": len(claims),+ "linked_fact_count": len(referenced_facts),+ "errors": errors,+ "warnings": warnings,+ "limitations": [+ "Source records were not opened and hash values were not recomputed.",+ "Traceability metadata does not establish source truth or clinical correctness.",+ ],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check bounded local source-fact traceability metadata. "+ "Does not open source records or copy clinical content."+ )+ )+ parser.add_argument("input_file", help="Local provenance manifest (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ _, data = load_json_object(args.input_file)+ report = validate_provenance(data)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)+ try:+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return 0 if report["status"] == "TRACEABILITY_COMPLETE_REVIEW_REQUIRED" else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/terminology_validator.py b/skills/clinical-reports/scripts/terminology_validator.pyold mode 100755new mode 100644index f92a536b..80fb3967--- a/skills/clinical-reports/scripts/terminology_validator.py+++ b/skills/clinical-reports/scripts/terminology_validator.py@@ -1,133 +1,277 @@#!/usr/bin/env python3-"""-Validate medical terminology and coding in clinical reports.+"""Check terminology-manifest schema and optional caller-supplied local dictionary."""-Usage:- python terminology_validator.py <report_file>-"""+from __future__ import annotationsimport argparse-import jsonimport re+import sys+from typing import Any+sys.dont_write_bytecode = True-# Common medical abbreviations that should be avoided (JCAHO "Do Not Use" list)-DO_NOT_USE = {- "U": "Unit",- "IU": "International Unit",- "QD": "daily",- "QOD": "every other day",- "MS": "morphine sulfate or magnesium sulfate",- "MSO4": "morphine sulfate",- "MgSO4": "magnesium sulfate",+from _common import ( # noqa: E402+ ValidationError,+ error_report,+ load_json_object,+ parse_iso_date,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_identifier,+ require_string,+ write_json_report,+)++TOOL = "terminology_validator"+CODE_PATTERNS = {+ "MedDRA": re.compile(r"^\d{8}$"),+ "LOINC": re.compile(r"^\d{1,7}-\d$"),+ "SNOMED_CT": re.compile(r"^[1-9]\d{5,17}$"),+ "ICD_10_CM": re.compile(r"^[A-Z][0-9A-Z]{2}(?:\.[0-9A-Z]{1,4})?$"),+ "UCUM": re.compile(r"^[A-Za-z0-9%.\[\]{}()/*^+'_-]{1,80}$"),+}+CODING_STATUSES = {"verified_by_qualified_reviewer", "unverified"}+TOP_LEVEL_FIELDS = {+ "schema_version",+ "artifact_kind",+ "manifest_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "provenance_manifest",+ "entries",+}+ENTRY_FIELDS = {+ "system",+ "system_uri",+ "code",+ "display",+ "version",+ "language",+ "source_fact_id",+ "coding_status",+ "verified_by_role",+ "verified_at",}-# Common abbreviations with potential ambiguity-AMBIGUOUS = ["cc", "hs", "TIW", "SC", "SQ", "D/C", "AS", "AD", "AU", "OS", "OD", "OU"]---def check_do_not_use_abbreviations(content: str) -> dict:- """Check for prohibited abbreviations."""- violations = {}-- for abbrev, meaning in DO_NOT_USE.items():- # Word boundary pattern to avoid false positives- pattern = rf"\b{re.escape(abbrev)}\b"- matches = re.findall(pattern, content)- if matches:- violations[abbrev] = {- "count": len(matches),- "should_use": meaning,- "severity": "HIGH"- }-- return violations---def check_ambiguous_abbreviations(content: str) -> dict:- """Check for ambiguous abbreviations."""- found = {}-- for abbrev in AMBIGUOUS:- pattern = rf"\b{re.escape(abbrev)}\b"- matches = re.findall(pattern, content, re.IGNORECASE)- if matches:- found[abbrev] = {- "count": len(matches),- "severity": "MEDIUM"- }-- return found---def validate_icd10_format(content: str) -> list:- """Check ICD-10 code format."""- # ICD-10 format: Letter + 2 digits + optional decimal + 0-4 more digits- pattern = r"\b[A-Z]\d{2}\.?\d{0,4}\b"- codes = re.findall(pattern, content)- return list(set(codes)) # Unique codes---def main():- """Main entry point."""- parser = argparse.ArgumentParser(description="Validate medical terminology")- parser.add_argument("input_file", help="Path to clinical report")- parser.add_argument("--json", action="store_true")-- args = parser.parse_args()-++def _validate_entry(entry: Any, index: int) -> tuple[str, str, str, str, list[str]]:+ entry = require_exact_keys(entry, ENTRY_FIELDS, f"entries[{index}]")+ system = require_string(entry.get("system"), f"entries[{index}].system", max_length=32)+ if system not in CODE_PATTERNS:+ raise ValidationError(+ f"entries[{index}].system must be one of {sorted(CODE_PATTERNS)}"+ )+ require_string(+ entry.get("system_uri"),+ f"entries[{index}].system_uri",+ max_length=200,+ )+ code = require_string(entry.get("code"), f"entries[{index}].code", max_length=80)+ if not CODE_PATTERNS[system].fullmatch(code):+ raise ValidationError(f"entries[{index}].code fails {system} syntax")+ display = require_string(+ entry.get("display"),+ f"entries[{index}].display",+ max_length=500,+ )+ version = require_string(+ entry.get("version"),+ f"entries[{index}].version",+ max_length=80,+ )+ require_string(entry.get("language"), f"entries[{index}].language", max_length=32)+ require_identifier(+ entry.get("source_fact_id"),+ f"entries[{index}].source_fact_id",+ )+ status = entry.get("coding_status")+ if status not in CODING_STATUSES:+ raise ValidationError(f"entries[{index}].coding_status is invalid")+ warnings: list[str] = []+ if status == "verified_by_qualified_reviewer":+ require_string(+ entry.get("verified_by_role"),+ f"entries[{index}].verified_by_role",+ max_length=100,+ )+ parse_iso_date(entry.get("verified_at"), f"entries[{index}].verified_at")+ else:+ warnings.append(f"entries[{index}] remains unverified")+ if system == "MedDRA" and not re.fullmatch(r"\d{1,2}\.\d", version):+ warnings.append(f"entries[{index}] MedDRA version has an unusual format")+ return system, version, code, display, warnings+++def _load_dictionary(raw_path: str) -> dict[tuple[str, str, str], str]:+ _, data = load_json_object(raw_path)+ require_exact_keys(+ data,+ {"schema_version", "artifact_kind", "entries"},+ "dictionary",+ )+ if data.get("schema_version") != "2.0":+ raise ValidationError("dictionary schema_version must be 2.0")+ if data.get("artifact_kind") != "terminology_dictionary":+ raise ValidationError("dictionary artifact_kind must be terminology_dictionary")+ entries = data.get("entries")+ if not isinstance(entries, list) or not entries:+ raise ValidationError("dictionary entries must be a non-empty array")+ if len(entries) > 20_000:+ raise ValidationError("dictionary may contain at most 20,000 entries")+ dictionary: dict[tuple[str, str, str], str] = {}+ for index, entry in enumerate(entries):+ entry = require_exact_keys(+ entry,+ {"system", "version", "code", "display"},+ f"dictionary entries[{index}]",+ )+ system = require_string(+ entry.get("system"),+ f"dictionary entries[{index}].system",+ max_length=32,+ )+ version = require_string(+ entry.get("version"),+ f"dictionary entries[{index}].version",+ max_length=80,+ )+ code = require_string(+ entry.get("code"),+ f"dictionary entries[{index}].code",+ max_length=80,+ )+ display = require_string(+ entry.get("display"),+ f"dictionary entries[{index}].display",+ max_length=500,+ )+ key = (system, version, code)+ if key in dictionary and dictionary[key] != display:+ raise ValidationError(f"dictionary contains conflicting duplicate at index {index}")+ dictionary[key] = display+ return dictionary+++def validate_terminology_manifest(+ data: dict[str, Any],+ dictionary: dict[tuple[str, str, str], str] | None = None,+) -> dict[str, Any]:+ """Validate schema and optional exact tuple matches."""+ errors: list[str] = []+ warnings: list[str] = []try:- with open(args.input_file, 'r', encoding='utf-8') as f:- content = f.read()-- do_not_use = check_do_not_use_abbreviations(content)- ambiguous = check_ambiguous_abbreviations(content)- icd10_codes = validate_icd10_format(content)-- report = {- "filename": args.input_file,- "do_not_use_violations": do_not_use,- "ambiguous_abbreviations": ambiguous,- "icd10_codes_found": icd10_codes,- "total_issues": len(do_not_use) + len(ambiguous)- }-- if args.json:- print(json.dumps(report, indent=2))- else:- print("\nTerminology Validation Report:\n")-- if do_not_use:- print("❌ DO NOT USE Abbreviations Found:")- for abbrev, details in do_not_use.items():- print(f" {abbrev}: {details['count']} occurrence(s)")- print(f" → Use '{details['should_use']}' instead")- print()- else:- print("✓ No prohibited abbreviations found\n")-- if ambiguous:- print("⚠ Ambiguous Abbreviations Found:")- for abbrev, details in ambiguous.items():- print(f" {abbrev}: {details['count']} occurrence(s)")- print(" Consider spelling out for clarity\n")-- if icd10_codes:- print(f"ℹ ICD-10 codes detected: {len(icd10_codes)}")- for code in icd10_codes[:5]:- print(f" - {code}")- if len(icd10_codes) > 5:- print(f" ... and {len(icd10_codes) - 5} more")- print()-- return 0 if not do_not_use else 1-- except Exception as e:- print(f"Error: {e}")- return 1+ require_exact_keys(data, TOP_LEVEL_FIELDS, "manifest")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("manifest_status") != "BLOCKED_INCOMPLETE":+ raise ValidationError("manifest_status must remain BLOCKED_INCOMPLETE")+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ if not require_bool(data.get("authorization_verified"), "authorization_verified"):+ raise ValidationError("authorization_verified must be true")+ require_string(data.get("provenance_manifest"), "provenance_manifest")+ except ValidationError as exc:+ errors.append(str(exc))+ if data.get("artifact_kind") != "terminology_manifest":+ errors.append("artifact_kind must be terminology_manifest")+ try:+ require_data_class(data.get("data_classification"))+ except ValidationError as exc:+ errors.append(str(exc))+ entries = data.get("entries")+ if not isinstance(entries, list) or not entries:+ errors.append("entries must be a non-empty array")+ entries = []+ if len(entries) > 5_000:+ errors.append("entries may contain at most 5,000 items")-if __name__ == "__main__":- import sys- sys.exit(main())+ seen: set[tuple[str, str, str]] = set()+ verified_count = 0+ dictionary_match_count = 0+ for index, entry in enumerate(entries[:5_000]):+ try:+ system, version, code, display, entry_warnings = _validate_entry(+ entry,+ index,+ )+ warnings.extend(entry_warnings)+ key = (system, version, code)+ if key in seen:+ errors.append(f"entries[{index}] duplicates a prior system/version/code")+ seen.add(key)+ if entry.get("coding_status") == "verified_by_qualified_reviewer":+ verified_count += 1+ if dictionary is not None:+ expected_display = dictionary.get(key)+ if expected_display is None:+ errors.append(f"entries[{index}] is absent from the supplied dictionary")+ elif expected_display != display:+ errors.append(+ f"entries[{index}] display does not match the supplied dictionary"+ )+ else:+ dictionary_match_count += 1+ except ValidationError as exc:+ errors.append(str(exc))+ if dictionary is None:+ warnings.append(+ "No local dictionary supplied; code existence, currency, and display were not checked."+ )+ success_status = "SCHEMA_VALID_SYNTAX_ONLY_REVIEW_REQUIRED"+ else:+ success_status = "SCHEMA_AND_LOCAL_DICTIONARY_MATCH_REVIEW_REQUIRED"++ return {+ "tool": TOOL,+ "status": "BLOCKED" if errors else success_status,+ "entry_count": len(entries),+ "qualified_reviewer_verified_count": verified_count,+ "local_dictionary_match_count": dictionary_match_count,+ "errors": errors,+ "warnings": warnings,+ "limitations": [+ "Syntax or local-dictionary matching does not establish clinical correctness.",+ "Caller is responsible for dictionary authority, version, license, and completeness.",+ ],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check a bounded terminology JSON manifest. Optional dictionary comparison "+ "uses a caller-supplied local JSON file and never calls a network service."+ )+ )+ parser.add_argument("input_file", help="Local terminology manifest (.json)")+ parser.add_argument("--dictionary", help="Optional authorized local dictionary (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ _, data = load_json_object(args.input_file)+ dictionary = _load_dictionary(args.dictionary) if args.dictionary else None+ report = validate_terminology_manifest(data, dictionary)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)+ try:+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return 0 if report["status"].startswith("SCHEMA_") else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/validate_case_report.py b/skills/clinical-reports/scripts/validate_case_report.pyold mode 100755new mode 100644index 459a0566..b0086d57--- a/skills/clinical-reports/scripts/validate_case_report.py+++ b/skills/clinical-reports/scripts/validate_case_report.py@@ -1,334 +1,278 @@#!/usr/bin/env python3-"""-Validate case reports against CARE (CAse REport) guidelines.+"""Validate a structured CARE coverage manifest without reading patient narrative."""-This script checks a clinical case report for compliance with CARE guidelines-and provides a checklist of required elements.--Usage:- python validate_case_report.py <input_file.md|.txt>- python validate_case_report.py <input_file> --output report.json-"""+from __future__ import annotationsimport argparse-import json-import re-from pathlib import Path-from typing import Dict, List, Tuple+import sys+from typing import Any+sys.dont_write_bytecode = True-class CareValidator:- """Validator for CARE guideline compliance."""-- # CARE checklist items with regex patterns- CARE_REQUIREMENTS = {- "title": {- "name": "Title contains 'case report'",- "pattern": r"(?i)(case\s+report|case\s+study)",- "section": "Title",- "required": True- },- "keywords": {- "name": "Keywords provided (2-5)",- "pattern": r"(?i)keywords?[:]\s*(.+)",- "section": "Keywords",- "required": True- },- "abstract": {- "name": "Abstract present",- "pattern": r"(?i)##?\s*abstract",- "section": "Abstract",- "required": True- },- "introduction": {- "name": "Introduction explaining novelty",- "pattern": r"(?i)##?\s*introduction",- "section": "Introduction",- "required": True- },- "patient_info": {- "name": "Patient demographics present",- "pattern": r"(?i)(patient\s+information|demographics?)",- "section": "Patient Information",- "required": True- },- "clinical_findings": {- "name": "Clinical findings documented",- "pattern": r"(?i)(clinical\s+findings?|physical\s+exam)",- "section": "Clinical Findings",- "required": True- },- "timeline": {- "name": "Timeline of events",- "pattern": r"(?i)(timeline|chronology)",- "section": "Timeline",- "required": True- },- "diagnostic": {- "name": "Diagnostic assessment",- "pattern": r"(?i)diagnostic\s+(assessment|evaluation|workup)",- "section": "Diagnostic Assessment",- "required": True- },- "therapeutic": {- "name": "Therapeutic interventions",- "pattern": r"(?i)(therapeutic\s+intervention|treatment)",- "section": "Therapeutic Interventions",- "required": True- },- "followup": {- "name": "Follow-up and outcomes",- "pattern": r"(?i)(follow[\-\s]?up|outcomes?)",- "section": "Follow-up and Outcomes",- "required": True- },- "discussion": {- "name": "Discussion with literature review",- "pattern": r"(?i)##?\s*discussion",- "section": "Discussion",- "required": True- },- "consent": {- "name": "Informed consent statement",- "pattern": r"(?i)(informed\s+consent|written\s+consent|consent.*obtained)",- "section": "Informed Consent",- "required": True- },- }-- # HIPAA identifiers to check for- HIPAA_PATTERNS = {- "dates": r"\b(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/\d{4}\b",- "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",- "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",- "ssn": r"\b\d{3}-\d{2}-\d{4}\b",- "mrn": r"(?i)(mrn|medical\s+record)[:]\s*\d+",- "zip_full": r"\b\d{5}-\d{4}\b",- }-- def __init__(self, filename: str):- """Initialize validator with input file."""- self.filename = Path(filename)- self.content = self._read_file()- self.results = {}-- def _read_file(self) -> str:- """Read input file content."""+from _common import ( # noqa: E402+ ValidationError,+ error_report,+ load_json_object,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_identifier,+ require_string,+ write_json_report,+)++TOOL = "validate_case_report"+CARE_ITEMS = (+ "title",+ "key_words",+ "abstract",+ "introduction",+ "patient_information",+ "clinical_findings",+ "timeline",+ "diagnostic_assessment",+ "therapeutic_intervention",+ "follow_up_and_outcomes",+ "discussion",+ "patient_perspective",+ "informed_consent",+)+ALLOWED_ITEM_STATUSES = {+ "verified_present",+ "not_applicable_with_rationale",+ "missing",+ "conflict",+}+NA_ALLOWED = {"patient_perspective"}+TOP_LEVEL_FIELDS = {+ "schema_version",+ "artifact_kind",+ "draft_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "provenance_manifest",+ "guidance",+ "care_items",+ "privacy",+ "review",+}+EXPECTED_DRAFT_STATUS = (+ "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_SUBMISSION"+)+++def _fact_ids(item: dict[str, Any], field: str) -> list[str]:+ value = item.get("source_fact_ids")+ if not isinstance(value, list):+ raise ValidationError(f"{field}.source_fact_ids must be an array")+ return [require_identifier(fact_id, f"{field}.source_fact_ids") for fact_id in value]+++def validate_case_manifest(data: dict[str, Any]) -> dict[str, Any]:+ """Return fail-closed structural findings for a CARE manifest."""+ errors: list[str] = []+ warnings: list[str] = []++ try:+ require_exact_keys(data, TOP_LEVEL_FIELDS, "manifest")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("artifact_kind") != "case_report_draft":+ raise ValidationError("artifact_kind must be case_report_draft")+ if data.get("draft_status") != EXPECTED_DRAFT_STATUS:+ raise ValidationError(+ "draft_status must preserve the blocked non-clinical-use warning"+ )+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ require_data_class(data.get("data_classification"))+ if not require_bool(data.get("authorization_verified"), "authorization_verified"):+ errors.append("authorization_verified must be true")+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ require_string(data.get("provenance_manifest"), "provenance_manifest")+ except ValidationError as exc:+ errors.append(str(exc))++ guidance = data.get("guidance")+ try:+ guidance = require_exact_keys(+ guidance,+ {+ "name",+ "checklist_version",+ "explanation_version",+ "target_journal_instructions_checked",+ },+ "guidance",+ )+ if guidance.get("name") != "CARE":+ errors.append("guidance.name must be CARE")+ if guidance.get("checklist_version") != "2013":+ errors.append("guidance.checklist_version must be 2013")+ if guidance.get("explanation_version") != "2017":+ errors.append("guidance.explanation_version must be 2017")+ if guidance.get("target_journal_instructions_checked") is not True:+ warnings.append("target journal instructions remain to be checked")+ except ValidationError as exc:+ errors.append(str(exc))++ items = data.get("care_items")+ if not isinstance(items, dict):+ errors.append("care_items must be an object")+ items = {}+ missing_keys = sorted(set(CARE_ITEMS) - set(items))+ extra_keys = sorted(set(items) - set(CARE_ITEMS))+ if missing_keys:+ errors.append(f"missing CARE item keys: {missing_keys}")+ if extra_keys:+ errors.append(f"unexpected CARE item keys: {extra_keys}")++ coverage: dict[str, str] = {}+ for key in CARE_ITEMS:+ item = items.get(key)+ if not isinstance(item, dict):+ errors.append(f"care_items.{key} must be an object")+ continuetry:- with open(self.filename, 'r', encoding='utf-8') as f:- return f.read()- except FileNotFoundError:- raise FileNotFoundError(f"File not found: {self.filename}")- except Exception as e:- raise Exception(f"Error reading file: {e}")-- def validate_care_compliance(self) -> Dict[str, Dict]:- """Validate compliance with CARE guidelines."""- results = {}-- for key, item in self.CARE_REQUIREMENTS.items():- pattern = item["pattern"]- found = bool(re.search(pattern, self.content))-- results[key] = {- "name": item["name"],- "section": item["section"],- "required": item["required"],- "found": found,- "status": "PASS" if found else "FAIL" if item["required"] else "WARNING"- }-- self.results["care_compliance"] = results- return results-- def check_deidentification(self) -> Dict[str, List[str]]:- """Check for potential HIPAA identifier violations."""- violations = {}-- for identifier, pattern in self.HIPAA_PATTERNS.items():- matches = re.findall(pattern, self.content)- if matches:- violations[identifier] = matches[:5] # Limit to first 5 examples-- self.results["hipaa_violations"] = violations- return violations-- def check_word_count(self) -> Dict[str, int]:- """Check word count and provide limits guidance."""- words = len(re.findall(r'\b\w+\b', self.content))-- word_count = {- "total_words": words,- "typical_min": 1500,- "typical_max": 3000,- "status": "ACCEPTABLE" if 1500 <= words <= 3500 else "CHECK"- }-- self.results["word_count"] = word_count- return word_count-- def check_references(self) -> Dict[str, any]:- """Check for presence of references."""- ref_patterns = [- r"##?\s*references",- r"\[\d+\]",- r"\d+\.\s+[A-Z][a-z]+.*\d{4}", # Numbered references- ]-- has_refs = any(re.search(p, self.content, re.IGNORECASE) for p in ref_patterns)- ref_count = len(re.findall(r"\[\d+\]", self.content))-- references = {- "has_references": has_refs,- "estimated_count": ref_count,- "recommended_min": 10,- "status": "ACCEPTABLE" if ref_count >= 10 else "LOW"- }-- self.results["references"] = references- return references-- def generate_report(self) -> Dict:- """Generate comprehensive validation report."""- if not self.results:- self.validate_care_compliance()- self.check_deidentification()- self.check_word_count()- self.check_references()-- # Calculate overall compliance- care = self.results["care_compliance"]- total_required = sum(1 for v in care.values() if v["required"])- passed = sum(1 for v in care.values() if v["required"] and v["found"])- compliance_rate = (passed / total_required * 100) if total_required > 0 else 0-- report = {- "filename": str(self.filename),- "compliance_rate": round(compliance_rate, 1),- "care_compliance": care,- "hipaa_violations": self.results["hipaa_violations"],- "word_count": self.results["word_count"],- "references": self.results["references"],- "overall_status": "PASS" if compliance_rate >= 90 and not self.results["hipaa_violations"] else "NEEDS_REVISION"- }-- return report-- def print_report(self):- """Print human-readable validation report."""- report = self.generate_report()-- print("=" * 70)- print(f"CARE Guideline Validation Report")- print(f"File: {report['filename']}")- print("=" * 70)- print()-- print(f"Overall Compliance: {report['compliance_rate']}%")- print(f"Status: {report['overall_status']}")- print()-- print("CARE Checklist:")- print("-" * 70)- for key, item in report["care_compliance"].items():- status_symbol = "✓" if item["found"] else "✗"- print(f"{status_symbol} [{item['status']:8}] {item['name']}")- print()-- if report["hipaa_violations"]:- print("HIPAA DE-IDENTIFICATION WARNINGS:")- print("-" * 70)- for identifier, examples in report["hipaa_violations"].items():- print(f"⚠ {identifier.upper()}: {len(examples)} instance(s) found")- for ex in examples[:3]:- print(f" Example: {ex}")- print()- else:- print("✓ No obvious HIPAA identifiers detected")- print()-- wc = report["word_count"]- print(f"Word Count: {wc['total_words']} words")- print(f" Typical range: {wc['typical_min']}-{wc['typical_max']} words")- print(f" Status: {wc['status']}")- print()-- refs = report["references"]- print(f"References: {refs['estimated_count']} citation(s) detected")- print(f" Recommended minimum: {refs['recommended_min']}")- print(f" Status: {refs['status']}")- print()-- print("=" * 70)-- # Recommendations- issues = []- if report['compliance_rate'] < 100:- missing = [v["name"] for v in report["care_compliance"].values() if v["required"] and not v["found"]]- issues.append(f"Missing required sections: {', '.join(missing)}")-- if report["hipaa_violations"]:- issues.append("HIPAA identifiers detected - review de-identification")-- if refs["status"] == "LOW":- issues.append("Low reference count - consider adding more citations")-- if issues:- print("RECOMMENDATIONS:")- for i, issue in enumerate(issues, 1):- print(f"{i}. {issue}")- else:- print("✓ Case report meets CARE guidelines!")-- print("=" * 70)+ item = require_exact_keys(+ item,+ {"status", "source_fact_ids", "rationale"},+ f"care_items.{key}",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ status = item.get("status")+ coverage[key] = str(status)+ if status not in ALLOWED_ITEM_STATUSES:+ errors.append(f"care_items.{key}.status is invalid")+ continue+ try:+ facts = _fact_ids(item, f"care_items.{key}")+ except ValidationError as exc:+ errors.append(str(exc))+ facts = []+ if status == "verified_present" and not facts:+ errors.append(f"care_items.{key} requires at least one verified source fact")+ elif status == "not_applicable_with_rationale":+ if key not in NA_ALLOWED:+ errors.append(f"care_items.{key} cannot be marked not applicable")+ try:+ require_string(+ item.get("rationale"),+ f"care_items.{key}.rationale",+ max_length=500,+ )+ except ValidationError as exc:+ errors.append(str(exc))+ elif status in {"missing", "conflict"}:+ errors.append(f"care_items.{key} is {status}")+ privacy = data.get("privacy")+ try:+ privacy = require_exact_keys(+ privacy,+ {+ "deidentification_process_record",+ "publication_consent_record",+ "image_or_media_included",+ "reidentification_risk_reviewed",+ },+ "privacy",+ )+ for field in ("deidentification_process_record", "publication_consent_record"):+ try:+ require_string(privacy.get(field), f"privacy.{field}")+ except ValidationError as exc:+ errors.append(str(exc))+ try:+ if not require_bool(+ privacy.get("reidentification_risk_reviewed"),+ "privacy.reidentification_risk_reviewed",+ ):+ errors.append("privacy.reidentification_risk_reviewed must be true")+ except ValidationError as exc:+ errors.append(str(exc))+ try:+ require_bool(privacy.get("image_or_media_included"), "privacy.image_or_media_included")+ except ValidationError as exc:+ errors.append(str(exc))+ except ValidationError as exc:+ errors.append(str(exc))++ review = data.get("review")+ try:+ review = require_exact_keys(+ review,+ {+ "qualified_clinical_review",+ "privacy_legal_review",+ "accountable_author_review",+ "submission_authorized",+ },+ "review",+ )+ for field in (+ "qualified_clinical_review",+ "privacy_legal_review",+ "accountable_author_review",+ ):+ if review.get(field) != "completed":+ warnings.append(f"review.{field} remains required")+ if review.get("submission_authorized") is not False:+ errors.append("submission_authorized must remain false in this draft manifest")+ except ValidationError as exc:+ errors.append(str(exc))-def main():- """Main entry point."""+ status = "BLOCKED" if errors else "STRUCTURE_COMPLETE_REVIEW_REQUIRED"+ return {+ "tool": TOOL,+ "status": status,+ "guidance": "CARE 2013 with 2017 explanation",+ "coverage": coverage,+ "errors": errors,+ "warnings": warnings,+ "limitations": [+ "Structure and provenance metadata only; no clinical-content validation.",+ "Does not establish consent, de-identification, CARE adherence, or journal readiness.",+ ],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }+++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(- description="Validate clinical case reports against CARE guidelines"+ description=(+ "Check a bounded JSON CARE coverage manifest. "+ "Does not read patient narrative or claim compliance."+ ))+ parser.add_argument("input_file", help="Local case-report manifest (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report path")parser.add_argument(- "input_file",- help="Path to case report file (Markdown or text)"- )- parser.add_argument(- "--output",- "-o",- help="Output JSON report to file"- )- parser.add_argument(- "--json",+ "--overwrite",action="store_true",- help="Output JSON to stdout instead of human-readable report"+ help="Allow replacing an existing output file",)-- args = parser.parse_args()-+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ _, data = load_json_object(args.input_file)+ report = validate_case_manifest(data)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)try:- validator = CareValidator(args.input_file)- report = validator.generate_report()-- if args.json:- print(json.dumps(report, indent=2))- else:- validator.print_report()-- if args.output:- with open(args.output, 'w') as f:- json.dumps(report, f, indent=2)- print(f"\nJSON report saved to: {args.output}")-- # Exit with non-zero if validation failed- exit_code = 0 if report["overall_status"] == "PASS" else 1- return exit_code-- except Exception as e:- print(f"Error: {e}", file=sys.stderr)- return 1+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return 0 if report["status"] == "STRUCTURE_COMPLETE_REVIEW_REQUIRED" else 1if __name__ == "__main__":- import sys- sys.exit(main())-+ raise SystemExit(main())diff --git a/skills/clinical-reports/scripts/validate_trial_report.py b/skills/clinical-reports/scripts/validate_trial_report.pyold mode 100755new mode 100644index 16618b93..b4772ee8--- a/skills/clinical-reports/scripts/validate_trial_report.py+++ b/skills/clinical-reports/scripts/validate_trial_report.py@@ -1,89 +1,534 @@#!/usr/bin/env python3-"""-Validate clinical trial reports against ICH-E3 structure.+"""Validate structured ICH E3, CONSORT 2025, or SPIRIT 2025 coverage."""-Checks Clinical Study Reports (CSR) for ICH-E3 compliance.--Usage:- python validate_trial_report.py <csr_file.md>-"""+from __future__ import annotationsimport argparse-import json-import re-from pathlib import Path---ICH_E3_SECTIONS = {- "title_page": "Title Page",- "synopsis": "Synopsis (2)",- "toc": "Table of Contents (3)",- "abbreviations": "List of Abbreviations (4)",- "ethics": "Ethics (Section 2)",- "investigators": "Investigators and Study Administrative Structure (Section 3)",- "introduction": "Introduction (Section 4)",- "objectives": "Study Objectives and Plan (Section 5)",- "study_patients": "Study Patients (Section 6)",- "efficacy": "Efficacy Evaluation (Section 7)",- "safety": "Safety Evaluation (Section 8)",- "discussion": "Discussion and Overall Conclusions (Section 9)",- "tables_figures": "Tables, Figures, and Graphs (Section 10)",- "references": "References (Section 11)",- "appendices": "Appendices (Section 12-14)",+import sys+from typing import Any++sys.dont_write_bytecode = True++from _common import ( # noqa: E402+ ValidationError,+ error_report,+ load_json_object,+ require_bool,+ require_data_class,+ require_exact_keys,+ require_identifier,+ require_string,+ write_json_report,+)++TOOL = "validate_trial_report"+ALLOWED_STATUSES = {+ "verified_present",+ "not_applicable_with_rationale",+ "missing",+ "conflict",}+E3_SECTIONS = (+ "title_page",+ "synopsis",+ "table_of_contents",+ "abbreviations_and_definitions",+ "ethics",+ "investigators_and_administration",+ "introduction",+ "study_objectives",+ "investigational_plan",+ "study_patients",+ "efficacy_evaluation",+ "safety_evaluation",+ "discussion_and_conclusions",+ "tables_figures_graphs_not_in_text",+ "reference_list",+ "appendices",+)+COMMON_TOP_FIELDS = {+ "schema_version",+ "artifact_kind",+ "draft_status",+ "safety_notice",+ "data_classification",+ "authorized_purpose",+ "authorization_verified",+ "guidance",+ "provenance_manifest",+ "review",+}+ROUTES = {+ "clinical_study_report_draft": {+ "container": "sections",+ "keys": E3_SECTIONS,+ "guidance": "ICH E3 Step 4 1995-11-30 with Q&A R1 2012-07-06",+ "review_fields": (+ "medical_review",+ "statistical_review",+ "safety_review",+ "privacy_legal_review",+ "quality_review",+ "regulatory_review",+ ),+ "authorization_field": "submission_authorized",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_FILING_OR_SUBMISSION",+ "top_fields": COMMON_TOP_FIELDS | {"study_metadata", "sections"},+ "metadata_name": "study_metadata",+ "item_fields": {"status", "source_fact_ids", "rationale"},+ },+ "randomized_trial_results_draft": {+ "container": "checklist_items",+ "keys": tuple(f"C{number:02d}" for number in range(1, 31)),+ "guidance": "CONSORT 2025",+ "review_fields": (+ "accountable_author_review",+ "methodologist_review",+ "statistical_review",+ "safety_review",+ ),+ "authorization_field": "publication_authorized",+ "draft_status": (+ "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_PUBLICATION_OR_SUBMISSION"+ ),+ "top_fields": COMMON_TOP_FIELDS+ | {+ "study_metadata",+ "checklist_items",+ "not_applicable_rationales",+ "participant_flow_source_fact_ids",+ },+ "metadata_name": "study_metadata",+ "item_fields": {"status", "source_fact_ids", "official_item_locator"},+ },+ "randomized_trial_protocol_reporting_manifest": {+ "container": "checklist_items",+ "keys": tuple(f"S{number:02d}" for number in range(1, 35)),+ "guidance": "SPIRIT 2025",+ "review_fields": (+ "investigator_sponsor_review",+ "methodologist_review",+ "statistical_review",+ "safety_review",+ "ethics_regulatory_review",+ ),+ "authorization_field": "protocol_approved",+ "draft_status": (+ "BLOCKED_INCOMPLETE_REPORTING_CHECKLIST_NOT_A_PROTOCOL_OR_ETHICS_APPROVAL"+ ),+ "top_fields": COMMON_TOP_FIELDS+ | {+ "protocol_metadata",+ "checklist_items",+ "not_applicable_rationales",+ "participant_timeline_source_fact_ids",+ },+ "metadata_name": "protocol_metadata",+ "item_fields": {"status", "source_fact_ids", "official_item_locator"},+ },+}+++def _validate_guidance(+ artifact_kind: str,+ guidance: Any,+ errors: list[str],+) -> None:+ if not isinstance(guidance, dict):+ errors.append("guidance must be an object")+ return+ if artifact_kind == "clinical_study_report_draft":+ try:+ guidance = require_exact_keys(+ guidance,+ {+ "base",+ "base_version",+ "qa_version",+ "gcp_version_considered",+ "regional_adoption_verified",+ },+ "guidance",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ return+ if guidance.get("base") != "ICH E3":+ errors.append("CSR guidance.base must be ICH E3")+ if guidance.get("base_version") != "Step 4 1995-11-30":+ errors.append("CSR base_version is not the supported ICH E3 version")+ if guidance.get("qa_version") != "R1 2012-07-06":+ errors.append("CSR qa_version is not the supported E3 Q&A version")+ if (+ guidance.get("gcp_version_considered")+ != "ICH E6(R3) consolidated 2026-06-16"+ ):+ errors.append("CSR must record consideration of current ICH E6(R3)")+ if guidance.get("regional_adoption_verified") is not True:+ errors.append("CSR regional adoption/version review is required")+ elif artifact_kind == "randomized_trial_results_draft":+ try:+ guidance = require_exact_keys(+ guidance,+ {+ "base",+ "item_count",+ "statement_and_explanation_checked",+ "applicable_extensions",+ "applicable_extensions_reviewed",+ "extension_conflicts_resolved_by_methodologist",+ },+ "guidance",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ return+ if guidance.get("base") != "CONSORT 2025" or guidance.get("item_count") != 30:+ errors.append("results manifest must declare CONSORT 2025 with 30 items")+ if guidance.get("statement_and_explanation_checked") is not True:+ errors.append("CONSORT statement and explanation must be checked")+ if guidance.get("applicable_extensions_reviewed") is not True:+ errors.append("applicable CONSORT extensions must be reviewed")+ extensions = guidance.get("applicable_extensions")+ if not isinstance(extensions, list):+ errors.append("guidance.applicable_extensions must be an array")+ else:+ for index, extension in enumerate(extensions):+ try:+ require_string(+ extension,+ f"guidance.applicable_extensions[{index}]",+ max_length=200,+ )+ except ValidationError as exc:+ errors.append(str(exc))+ try:+ conflicts_resolved = require_bool(+ guidance.get("extension_conflicts_resolved_by_methodologist"),+ "guidance.extension_conflicts_resolved_by_methodologist",+ )+ if extensions and not conflicts_resolved:+ errors.append("extension conflicts require methodologist resolution")+ except ValidationError as exc:+ errors.append(str(exc))+ elif artifact_kind == "randomized_trial_protocol_reporting_manifest":+ try:+ guidance = require_exact_keys(+ guidance,+ {+ "base",+ "item_count",+ "statement_and_explanation_checked",+ "applicable_extensions",+ "applicable_extensions_reviewed",+ "extension_conflicts_resolved_by_methodologist",+ },+ "guidance",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ return+ if guidance.get("base") != "SPIRIT 2025" or guidance.get("item_count") != 34:+ errors.append("protocol manifest must declare SPIRIT 2025 with 34 items")+ if guidance.get("statement_and_explanation_checked") is not True:+ errors.append("SPIRIT statement and explanation must be checked")+ if guidance.get("applicable_extensions_reviewed") is not True:+ errors.append("applicable SPIRIT extensions must be reviewed")+ extensions = guidance.get("applicable_extensions")+ if not isinstance(extensions, list):+ errors.append("guidance.applicable_extensions must be an array")+ else:+ for index, extension in enumerate(extensions):+ try:+ require_string(+ extension,+ f"guidance.applicable_extensions[{index}]",+ max_length=200,+ )+ except ValidationError as exc:+ errors.append(str(exc))+ try:+ conflicts_resolved = require_bool(+ guidance.get("extension_conflicts_resolved_by_methodologist"),+ "guidance.extension_conflicts_resolved_by_methodologist",+ )+ if extensions and not conflicts_resolved:+ errors.append("extension conflicts require methodologist resolution")+ except ValidationError as exc:+ errors.append(str(exc))+++def _validate_metadata(+ artifact_kind: str,+ value: Any,+ errors: list[str],+ warnings: list[str],+) -> None:+ if artifact_kind == "clinical_study_report_draft":+ fields = {+ "protocol_reference",+ "sap_reference",+ "data_cut_reference",+ "analysis_output_reference",+ "coding_dictionary_versions",+ }+ try:+ metadata = require_exact_keys(value, fields, "study_metadata")+ for field in fields - {"coding_dictionary_versions"}:+ require_string(metadata.get(field), f"study_metadata.{field}")+ versions = metadata.get("coding_dictionary_versions")+ if not isinstance(versions, list) or not versions:+ raise ValidationError(+ "study_metadata.coding_dictionary_versions must be non-empty"+ )+ for index, version in enumerate(versions):+ require_string(+ version,+ f"study_metadata.coding_dictionary_versions[{index}]",+ max_length=100,+ )+ except ValidationError as exc:+ errors.append(str(exc))+ elif artifact_kind == "randomized_trial_results_draft":+ fields = {+ "protocol_reference",+ "sap_reference",+ "registry_reference",+ "data_cut_reference",+ "analysis_output_reference",+ }+ try:+ metadata = require_exact_keys(value, fields, "study_metadata")+ for field in fields:+ require_string(metadata.get(field), f"study_metadata.{field}")+ except ValidationError as exc:+ errors.append(str(exc))+ else:+ fields = {+ "authorized_protocol_reference",+ "protocol_version",+ "registry_reference",+ "ethics_record_reference",+ }+ try:+ metadata = require_exact_keys(value, fields, "protocol_metadata")+ for field in fields - {"ethics_record_reference"}:+ require_string(metadata.get(field), f"protocol_metadata.{field}")+ if metadata.get("ethics_record_reference") is None:+ warnings.append("protocol_metadata.ethics_record_reference remains pending")+ else:+ require_string(+ metadata.get("ethics_record_reference"),+ "protocol_metadata.ethics_record_reference",+ )+ except ValidationError as exc:+ errors.append(str(exc))+++def _validated_fact_ids(value: Any, field: str) -> list[str]:+ if not isinstance(value, list):+ raise ValidationError(f"{field} must be an array")+ return [require_identifier(item, field) for item in value]++def validate_trial_manifest(data: dict[str, Any]) -> dict[str, Any]:+ """Return structural findings without evaluating trial content."""+ errors: list[str] = []+ warnings: list[str] = []+ artifact_kind = data.get("artifact_kind")+ route = ROUTES.get(artifact_kind)+ if route is None:+ return {+ "tool": TOOL,+ "status": "BLOCKED",+ "errors": [f"unsupported artifact_kind: {artifact_kind!r}"],+ "warnings": [],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,+ }++ try:+ require_exact_keys(data, route["top_fields"], "manifest")+ if data.get("schema_version") != "2.0":+ raise ValidationError("schema_version must be 2.0")+ if data.get("draft_status") != route["draft_status"]:+ raise ValidationError(+ "draft_status must preserve the blocked non-use/non-submission warning"+ )+ require_string(data.get("safety_notice"), "safety_notice", max_length=1000)+ require_data_class(data.get("data_classification"))+ require_string(data.get("authorized_purpose"), "authorized_purpose")+ if not require_bool(data.get("authorization_verified"), "authorization_verified"):+ errors.append("authorization_verified must be true")+ require_string(data.get("provenance_manifest"), "provenance_manifest")+ except ValidationError as exc:+ errors.append(str(exc))++ _validate_guidance(str(artifact_kind), data.get("guidance"), errors)+ _validate_metadata(+ str(artifact_kind),+ data.get(route["metadata_name"]),+ errors,+ warnings,+ )++ container_name = str(route["container"])+ expected_keys = tuple(route["keys"])+ container = data.get(container_name)+ if not isinstance(container, dict):+ errors.append(f"{container_name} must be an object")+ container = {}+ missing_keys = sorted(set(expected_keys) - set(container))+ extra_keys = sorted(set(container) - set(expected_keys))+ if missing_keys:+ errors.append(f"missing {container_name} keys: {missing_keys}")+ if extra_keys:+ errors.append(f"unexpected {container_name} keys: {extra_keys}")++ coverage: dict[str, str] = {}+ rationale_map = data.get("not_applicable_rationales", {})+ if container_name == "checklist_items" and not isinstance(rationale_map, dict):+ errors.append("not_applicable_rationales must be an object")+ rationale_map = {}+ for key in expected_keys:+ item = container.get(key)+ if not isinstance(item, dict):+ errors.append(f"{container_name}.{key} must be an object")+ continue+ try:+ item = require_exact_keys(+ item,+ route["item_fields"],+ f"{container_name}.{key}",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ continue+ status = item.get("status")+ coverage[key] = str(status)+ if status not in ALLOWED_STATUSES:+ errors.append(f"{container_name}.{key}.status is invalid")+ continue+ try:+ facts = _validated_fact_ids(+ item.get("source_fact_ids"),+ f"{container_name}.{key}.source_fact_ids",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ facts = []+ if status == "verified_present":+ if not facts:+ errors.append(f"{container_name}.{key} requires a verified source fact")+ if container_name == "checklist_items":+ try:+ require_string(+ item.get("official_item_locator"),+ f"{container_name}.{key}.official_item_locator",+ )+ except ValidationError as exc:+ errors.append(str(exc))+ elif status == "not_applicable_with_rationale":+ try:+ require_string(+ (+ item.get("rationale")+ if container_name == "sections"+ else rationale_map.get(key)+ ),+ (+ f"{container_name}.{key}.rationale"+ if container_name == "sections"+ else f"not_applicable_rationales.{key}"+ ),+ max_length=500,+ )+ except ValidationError as exc:+ errors.append(str(exc))+ else:+ errors.append(f"{container_name}.{key} is {status}")++ if artifact_kind == "randomized_trial_results_draft":+ try:+ flow_facts = _validated_fact_ids(+ data.get("participant_flow_source_fact_ids"),+ "participant_flow_source_fact_ids",+ )+ if not flow_facts:+ errors.append("participant flow requires verified source facts")+ except ValidationError as exc:+ errors.append(str(exc))+ elif artifact_kind == "randomized_trial_protocol_reporting_manifest":+ try:+ timeline_facts = _validated_fact_ids(+ data.get("participant_timeline_source_fact_ids"),+ "participant_timeline_source_fact_ids",+ )+ if not timeline_facts:+ errors.append("participant timeline requires verified source facts")+ except ValidationError as exc:+ errors.append(str(exc))++ review = data.get("review")+ try:+ review = require_exact_keys(+ review,+ {*route["review_fields"], route["authorization_field"]},+ "review",+ )+ for field in route["review_fields"]:+ if review.get(field) != "completed":+ warnings.append(f"review.{field} remains required")+ authorization_field = str(route["authorization_field"])+ if review.get(authorization_field) is not False:+ errors.append(f"review.{authorization_field} must remain false")+ except ValidationError as exc:+ errors.append(str(exc))-def validate_ich_e3(filename: str) -> dict:- """Validate CSR structure against ICH-E3."""- with open(filename, 'r', encoding='utf-8') as f:- content = f.read()-- results = {}- for section_id, section_name in ICH_E3_SECTIONS.items():- # Simple pattern matching for section headers- pattern = rf"(?i)##?\s*{re.escape(section_name.split('(')[0].strip())}"- found = bool(re.search(pattern, content))- results[section_id] = {"name": section_name, "found": found}-- compliance_rate = sum(1 for r in results.values() if r["found"]) / len(results) * 100-return {- "filename": filename,- "compliance_rate": round(compliance_rate, 1),- "sections": results,- "status": "PASS" if compliance_rate >= 90 else "NEEDS_REVISION"+ "tool": TOOL,+ "artifact_kind": artifact_kind,+ "guidance": route["guidance"],+ "status": "BLOCKED" if errors else "STRUCTURE_COMPLETE_REVIEW_REQUIRED",+ "coverage": coverage,+ "errors": errors,+ "warnings": warnings,+ "limitations": [+ "Checks item keys, statuses, and provenance references only.",+ "Does not validate conduct, analyses, clinical content, compliance, or submission format.",+ ],+ "review_required": True,+ "authorizes_clinical_use_or_submission": False,}-def main():- """Main entry point."""- parser = argparse.ArgumentParser(description="Validate CSR against ICH-E3")- parser.add_argument("input_file", help="Path to CSR file")- parser.add_argument("--json", action="store_true", help="Output JSON")-- args = parser.parse_args()-+def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Check a bounded JSON ICH E3, CONSORT 2025, or SPIRIT 2025 "+ "coverage manifest; never claims compliance."+ )+ )+ parser.add_argument("input_file", help="Local trial-report manifest (.json)")+ parser.add_argument("-o", "--output", help="Optional local JSON report path")+ parser.add_argument("--overwrite", action="store_true")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)try:- report = validate_ich_e3(args.input_file)-- if args.json:- print(json.dumps(report, indent=2))- else:- print(f"\nICH-E3 Compliance: {report['compliance_rate']}%")- print(f"Status: {report['status']}\n")- print("Section Checklist:")- for section, details in report["sections"].items():- symbol = "✓" if details["found"] else "✗"- print(f"{symbol} {details['name']}")-- return 0 if report["status"] == "PASS" else 1-- except Exception as e:- print(f"Error: {e}")- return 1+ _, data = load_json_object(args.input_file)+ report = validate_trial_manifest(data)+ except (OSError, ValidationError) as exc:+ report = error_report(TOOL, exc)+ try:+ write_json_report(report, args.output, overwrite=args.overwrite)+ except (OSError, ValidationError) as exc:+ print(str(exc), file=sys.stderr)+ return 2+ return 0 if report["status"] == "STRUCTURE_COMPLETE_REVIEW_REQUIRED" else 1if __name__ == "__main__":- import sys- sys.exit(main())-+ raise SystemExit(main())diff --git a/skills/clinical-reports/tests/test_scripts.py b/skills/clinical-reports/tests/test_scripts.pynew file mode 100644index 00000000..0da583d7--- /dev/null+++ b/skills/clinical-reports/tests/test_scripts.py@@ -0,0 +1,490 @@+#!/usr/bin/env python3+"""Synthetic, dependency-free tests for clinical-reports local tooling."""++from __future__ import annotations++import json+import re+import sys+import tempfile+import unittest+from pathlib import Path++sys.dont_write_bytecode = True++SKILL_ROOT = Path(__file__).resolve().parents[1]+SCRIPTS = SKILL_ROOT / "scripts"+ASSETS = SKILL_ROOT / "assets"+sys.path.insert(0, str(SCRIPTS))++from _common import ValidationError # noqa: E402+from check_deidentification import validate_process # noqa: E402+from consistency_checker import validate_consistency # noqa: E402+from format_adverse_events import ( # noqa: E402+ load_aggregate_csv,+ render_markdown,+ validate_aggregate_metadata,+)+from generate_report_template import generate_template # noqa: E402+from provenance_validator import validate_provenance # noqa: E402+from terminology_validator import validate_terminology_manifest # noqa: E402+from validate_case_report import CARE_ITEMS, validate_case_manifest # noqa: E402+from validate_trial_report import E3_SECTIONS, validate_trial_manifest # noqa: E402+++def valid_case_manifest() -> dict:+ return {+ "schema_version": "2.0",+ "artifact_kind": "case_report_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_CLINICAL_USE_OR_SUBMISSION",+ "safety_notice": "Synthetic draft test; qualified review required.",+ "data_classification": "synthetic",+ "authorized_purpose": "synthetic structural test",+ "authorization_verified": True,+ "provenance_manifest": "local:synthetic-provenance.json",+ "guidance": {+ "name": "CARE",+ "checklist_version": "2013",+ "explanation_version": "2017",+ "target_journal_instructions_checked": True,+ },+ "care_items": {+ key: {+ "status": "verified_present",+ "source_fact_ids": [f"FACT-{index:02d}"],+ "rationale": None,+ }+ for index, key in enumerate(CARE_ITEMS, start=1)+ },+ "privacy": {+ "deidentification_process_record": "local:synthetic-deid.json",+ "publication_consent_record": "local:synthetic-consent-status",+ "image_or_media_included": False,+ "reidentification_risk_reviewed": True,+ },+ "review": {+ "qualified_clinical_review": "completed",+ "privacy_legal_review": "completed",+ "accountable_author_review": "completed",+ "submission_authorized": False,+ },+ }+++def valid_csr_manifest() -> dict:+ return {+ "schema_version": "2.0",+ "artifact_kind": "clinical_study_report_draft",+ "draft_status": "BLOCKED_INCOMPLETE_DRAFT_NOT_FOR_FILING_OR_SUBMISSION",+ "safety_notice": "Synthetic aggregate CSR structure test; review required.",+ "data_classification": "aggregate",+ "authorized_purpose": "synthetic CSR structure test",+ "authorization_verified": True,+ "provenance_manifest": "local:synthetic-provenance.json",+ "guidance": {+ "base": "ICH E3",+ "base_version": "Step 4 1995-11-30",+ "qa_version": "R1 2012-07-06",+ "gcp_version_considered": "ICH E6(R3) consolidated 2026-06-16",+ "regional_adoption_verified": True,+ },+ "study_metadata": {+ "protocol_reference": "local:synthetic-protocol",+ "sap_reference": "local:synthetic-sap",+ "data_cut_reference": "local:synthetic-data-cut",+ "analysis_output_reference": "local:synthetic-output",+ "coding_dictionary_versions": ["MedDRA 29.0 synthetic test"],+ },+ "sections": {+ key: {+ "status": "verified_present",+ "source_fact_ids": [f"FACT-E3-{index:02d}"],+ "rationale": None,+ }+ for index, key in enumerate(E3_SECTIONS, start=1)+ },+ "review": {+ "medical_review": "completed",+ "statistical_review": "completed",+ "safety_review": "completed",+ "privacy_legal_review": "completed",+ "quality_review": "completed",+ "regulatory_review": "completed",+ "submission_authorized": False,+ },+ }+++def valid_aggregate_metadata(input_name: str) -> dict:+ return {+ "schema_version": "2.0",+ "artifact_kind": "clinical_trial_safety_aggregate_draft",+ "draft_status": "BLOCKED_INCOMPLETE_NOT_AN_INDIVIDUAL_CASE_SAFETY_REPORT",+ "safety_notice": "Synthetic aggregate display only; qualified review required.",+ "data_classification": "aggregate",+ "authorized_purpose": "synthetic formatter test",+ "authorization_verified": True,+ "local_only_handling_confirmed": True,+ "analysis_metadata": {+ "protocol_reference": "local:synthetic-protocol",+ "sap_reference": "local:synthetic-sap",+ "data_cut_reference": "local:synthetic-data-cut",+ "analysis_set": "Safety set",+ "counting_rule": "synthetic subject and event counts",+ "threshold_rule": "all synthetic terms",+ "meddra_version": "29.0",+ "meddra_language": "English",+ "coding_source_reference": "local:synthetic-coding-output",+ },+ "input_csv": input_name,+ "required_columns": [+ "analysis_set",+ "treatment_group",+ "meddra_version",+ "system_organ_class",+ "preferred_term",+ "subjects_affected",+ "event_count",+ "denominator",+ ],+ "prohibited_content": ["patient-level content"],+ "provenance_manifest": "local:synthetic-provenance",+ "review": {+ "safety_coding_review": "pending",+ "statistical_review": "pending",+ "privacy_review": "pending",+ "regulatory_review": "pending",+ "submission_authorized": False,+ },+ }+++class StructuralValidatorTests(unittest.TestCase):+ def test_complete_case_structure_still_requires_review(self) -> None:+ report = validate_case_manifest(valid_case_manifest())+ self.assertEqual(report["status"], "STRUCTURE_COMPLETE_REVIEW_REQUIRED")+ self.assertFalse(report["authorizes_clinical_use_or_submission"])++ def test_missing_case_item_blocks(self) -> None:+ manifest = valid_case_manifest()+ manifest["care_items"]["timeline"]["status"] = "missing"+ report = validate_case_manifest(manifest)+ self.assertEqual(report["status"], "BLOCKED")+ self.assertTrue(any("timeline" in item for item in report["errors"]))++ def test_unknown_case_field_blocks(self) -> None:+ manifest = valid_case_manifest()+ manifest["patient_name"] = "SYNTHETIC-NOT-A-PERSON"+ report = validate_case_manifest(manifest)+ self.assertEqual(report["status"], "BLOCKED")+ self.assertTrue(any("unknown" in item for item in report["errors"]))++ def test_complete_ich_e3_structure_still_requires_review(self) -> None:+ report = validate_trial_manifest(valid_csr_manifest())+ self.assertEqual(report["status"], "STRUCTURE_COMPLETE_REVIEW_REQUIRED")+ self.assertEqual(len(report["coverage"]), 16)++ def test_complete_consort_2025_coverage_still_requires_review(self) -> None:+ manifest = json.loads(+ (ASSETS / "clinical_trial_results_template.json").read_text(encoding="utf-8")+ )+ manifest["authorized_purpose"] = "synthetic CONSORT coverage test"+ manifest["authorization_verified"] = True+ manifest["provenance_manifest"] = "local:synthetic-provenance"+ manifest["guidance"]["statement_and_explanation_checked"] = True+ manifest["guidance"]["applicable_extensions_reviewed"] = True+ manifest["study_metadata"] = {+ key: f"local:synthetic-{key}"+ for key in (+ "protocol_reference",+ "sap_reference",+ "registry_reference",+ "data_cut_reference",+ "analysis_output_reference",+ )+ }+ for key, item in manifest["checklist_items"].items():+ item["status"] = "verified_present"+ item["source_fact_ids"] = [f"FACT-{key}"]+ item["official_item_locator"] = f"CONSORT-2025-{key}"+ manifest["participant_flow_source_fact_ids"] = ["FACT-FLOW"]+ for field in (+ "accountable_author_review",+ "methodologist_review",+ "statistical_review",+ "safety_review",+ ):+ manifest["review"][field] = "completed"+ report = validate_trial_manifest(manifest)+ self.assertEqual(report["status"], "STRUCTURE_COMPLETE_REVIEW_REQUIRED")+ self.assertEqual(len(report["coverage"]), 30)++ def test_complete_spirit_2025_coverage_still_requires_review(self) -> None:+ manifest = json.loads(+ (ASSETS / "trial_protocol_reporting_checklist.json").read_text(+ encoding="utf-8"+ )+ )+ manifest["authorized_purpose"] = "synthetic SPIRIT coverage test"+ manifest["authorization_verified"] = True+ manifest["provenance_manifest"] = "local:synthetic-provenance"+ manifest["guidance"]["statement_and_explanation_checked"] = True+ manifest["guidance"]["applicable_extensions_reviewed"] = True+ manifest["protocol_metadata"] = {+ "authorized_protocol_reference": "local:synthetic-protocol",+ "protocol_version": "SYNTHETIC-1",+ "registry_reference": "local:synthetic-registry",+ "ethics_record_reference": "local:synthetic-ethics-status",+ }+ for key, item in manifest["checklist_items"].items():+ item["status"] = "verified_present"+ item["source_fact_ids"] = [f"FACT-{key}"]+ item["official_item_locator"] = f"SPIRIT-2025-{key}"+ manifest["participant_timeline_source_fact_ids"] = ["FACT-TIMELINE"]+ for field in (+ "investigator_sponsor_review",+ "methodologist_review",+ "statistical_review",+ "safety_review",+ "ethics_regulatory_review",+ ):+ manifest["review"][field] = "completed"+ report = validate_trial_manifest(manifest)+ self.assertEqual(report["status"], "STRUCTURE_COMPLETE_REVIEW_REQUIRED")+ self.assertEqual(len(report["coverage"]), 34)+++class AggregateFormatterTests(unittest.TestCase):+ def test_formats_synthetic_aggregate_rows(self) -> None:+ content = (+ "analysis_set,treatment_group,meddra_version,system_organ_class,"+ "preferred_term,subjects_affected,event_count,denominator\n"+ "Safety set,Group A,29.0,General disorders,Headache,2,3,10\n"+ "Safety set,Group B,29.0,General disorders,Headache,1,1,8\n"+ )+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "aggregate.csv"+ path.write_text(content, encoding="utf-8")+ rows = load_aggregate_csv(str(path))+ metadata = valid_aggregate_metadata(path.name)+ validate_aggregate_metadata(metadata, input_name=path.name)+ rendered = render_markdown(+ rows,+ metadata=metadata,+ expected_meddra_version="29.0",+ )+ self.assertIn("2/10 (20.0%)", rendered)+ self.assertIn("not an icsr", rendered.lower())+ self.assertNotIn("p-value", rendered.lower())++ def test_rejects_row_level_identifier_column(self) -> None:+ content = (+ "analysis_set,treatment_group,meddra_version,system_organ_class,"+ "preferred_term,subjects_affected,event_count,denominator,subject_id\n"+ "Safety set,Group A,29.0,General disorders,Headache,1,1,10,SYN-001\n"+ )+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "aggregate.csv"+ path.write_text(content, encoding="utf-8")+ with self.assertRaises(ValidationError):+ load_aggregate_csv(str(path))+++class ProcessAndSchemaTests(unittest.TestCase):+ def test_terminology_local_dictionary_match_is_not_clinical_validation(self) -> None:+ manifest = {+ "schema_version": "2.0",+ "artifact_kind": "terminology_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Synthetic terminology test; qualified review required.",+ "data_classification": "synthetic",+ "authorized_purpose": "synthetic terminology schema test",+ "authorization_verified": True,+ "provenance_manifest": "local:synthetic-provenance",+ "entries": [+ {+ "system": "LOINC",+ "system_uri": "urn:synthetic:loinc",+ "code": "1234-5",+ "display": "Synthetic observation",+ "version": "2.82",+ "language": "en",+ "source_fact_id": "FACT-TERM-01",+ "coding_status": "verified_by_qualified_reviewer",+ "verified_by_role": "synthetic terminology reviewer",+ "verified_at": "2026-07-23",+ }+ ],+ }+ dictionary = {("LOINC", "2.82", "1234-5"): "Synthetic observation"}+ report = validate_terminology_manifest(manifest, dictionary)+ self.assertEqual(+ report["status"],+ "SCHEMA_AND_LOCAL_DICTIONARY_MATCH_REVIEW_REQUIRED",+ )+ self.assertIn("does not establish clinical correctness", report["limitations"][0])++ def test_synthetic_deidentification_process_never_claims_compliance(self) -> None:+ manifest = {+ "schema_version": "2.0",+ "artifact_kind": "deidentification_process_checklist",+ "process_status": "BLOCKED_NOT_ASSESSED",+ "safety_notice": "Synthetic process test; this cannot establish compliance.",+ "data_scope": "synthetic",+ "authorized_purpose": "synthetic test",+ "authorization_verified": True,+ "local_only_handling_confirmed": True,+ "minimum_necessary_reviewed": True,+ "method": "not_applicable_synthetic_or_aggregate",+ "safe_harbor_identifiers": {+ key: "not_assessed"+ for key in (+ "names",+ "geographic_subdivisions",+ "dates_and_ages",+ "telephone_numbers",+ "fax_numbers",+ "email_addresses",+ "social_security_numbers",+ "medical_record_numbers",+ "health_plan_numbers",+ "account_numbers",+ "certificate_and_license_numbers",+ "vehicle_identifiers",+ "device_identifiers",+ "urls",+ "ip_addresses",+ "biometric_identifiers",+ "full_face_images",+ "other_unique_characteristics_or_codes",+ )+ },+ "actual_knowledge_review": {+ "completed_by_authorized_privacy_reviewer": False,+ "record_reference": None,+ },+ "expert_determination": {+ "completed_by_qualified_expert": False,+ "expert_documentation_reference": None,+ "anticipated_recipient_and_conditions_documented": False,+ },+ "synthetic_or_aggregate_rationale": {+ "origin_verified": True,+ "record_reference": "local:synthetic-origin",+ },+ "residual_risk_review": {+ "free_text": "not_applicable_with_rationale",+ "small_cells_and_rare_cases": "not_applicable_with_rationale",+ "images_and_metadata": "not_applicable_with_rationale",+ "linked_data_and_quasi_identifiers": "not_applicable_with_rationale",+ },+ "review": {+ "privacy_legal_review": "completed",+ "institutional_release_review": "completed",+ "release_authorized": False,+ },+ }+ report = validate_process(manifest)+ self.assertEqual(report["status"], "PROCESS_DOCUMENTED_REVIEW_REQUIRED")+ self.assertNotIn("COMPLIANT", json.dumps(report).upper())++ def test_provenance_links_verified_fact_without_content(self) -> None:+ manifest = {+ "schema_version": "2.0",+ "artifact_kind": "provenance_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Synthetic traceability test; qualified review required.",+ "data_classification": "aggregate",+ "authorized_purpose": "synthetic traceability test",+ "authorization_verified": True,+ "facts": [+ {+ "fact_id": "FACT-001",+ "source_record_kind": "aggregate_output",+ "record_locator": "local:synthetic/output.json",+ "field_path": "$.counts.total",+ "value_hash_sha256": "a" * 64,+ "verification_status": "verified",+ "verified_by_role": "synthetic data reviewer",+ "verified_at": "2026-07-23",+ "source_version": "SYNTHETIC-1",+ }+ ],+ "claims": [+ {+ "claim_id": "CLAIM-001",+ "artifact_field_path": "$.sections.results",+ "fact_ids": ["FACT-001"],+ "support_status": "supported_by_verified_facts",+ }+ ],+ "review": {+ "source_owner_review": "completed",+ "quality_review": "completed",+ "privacy_review": "completed",+ "release_authorized": False,+ },+ }+ report = validate_provenance(manifest)+ self.assertEqual(report["status"], "TRACEABILITY_COMPLETE_REVIEW_REQUIRED")++ def test_consistency_detects_denominator_mismatch(self) -> None:+ manifest = {+ "schema_version": "2.0",+ "artifact_kind": "consistency_manifest",+ "manifest_status": "BLOCKED_INCOMPLETE",+ "safety_notice": "Synthetic arithmetic test; qualified review required.",+ "data_classification": "aggregate",+ "authorized_purpose": "synthetic consistency test",+ "authorization_verified": True,+ "provenance_manifest": "local:synthetic-provenance",+ "dates": [],+ "date_ranges": [],+ "quantities": [],+ "totals": [],+ "proportions": [+ {+ "id": "CHECK-001",+ "numerator": 2,+ "denominator": 10,+ "reported_percent": 25.0,+ "tolerance_percentage_points": 0.05,+ "source_fact_id": "FACT-001",+ }+ ],+ }+ report = validate_consistency(manifest)+ self.assertEqual(report["status"], "DISCREPANCIES_REQUIRE_RESOLUTION")+++class AssetAndGeneratorTests(unittest.TestCase):+ def test_bundled_path_references_exist(self) -> None:+ markdown_files = [SKILL_ROOT / "SKILL.md", *(SKILL_ROOT / "references").glob("*.md")]+ pattern = re.compile(r"`((?:assets|references|scripts)/[A-Za-z0-9_./-]+)`")+ for markdown in markdown_files:+ for relative in pattern.findall(markdown.read_text(encoding="utf-8")):+ self.assertTrue((SKILL_ROOT / relative).is_file(), f"{markdown.name}: {relative}")++ def test_every_json_asset_parses_and_contains_no_obvious_real_phi(self) -> None:+ email = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")+ ssn = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")+ phone = re.compile(r"\b\d{3}[-.]\d{3}[-.]\d{4}\b")+ for path in ASSETS.glob("*.json"):+ text = path.read_text(encoding="utf-8")+ json.loads(text)+ self.assertIsNone(email.search(text), path.name)+ self.assertIsNone(ssn.search(text), path.name)+ self.assertIsNone(phone.search(text), path.name)+ self.assertNotIn("OPENROUTER", text)++ def test_generator_copies_blocked_template_without_interpolation(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ output = Path(tmp) / "case.json"+ generated = generate_template("case-report", str(output))+ data = json.loads(generated.read_text(encoding="utf-8"))+ self.assertIn("BLOCKED", data["draft_status"])+ self.assertFalse(data["authorization_verified"])+++if __name__ == "__main__":+ unittest.main()