Source: https://github.com/aipoch/medical-research-skills
Protocol Deviation Classifier
Clinical trial protocol deviation classification tool, based on GCP and ICH E6 guidelines, automatically determines whether deviations belong to "major deviations" or "minor deviations".
Quick Check
Use this command to verify that the packaged script entry point can be parsed before deeper execution.
python -m py_compile scripts/main.py
Audit-Ready Commands
Use these concrete commands for validation. They are intentionally self-contained and avoid placeholder paths.
python -m py_compile scripts/main.py
python scripts/main.py --help
python scripts/main.py --input "Audit validation sample with explicit symptoms, history, assessment, and next-step plan." --format json
When to Use
- Use this skill when the task needs Determine whether an incident in a clinical trial is a "major deviation.
- Use this skill for data analysis tasks that require explicit assumptions, bounded scope, and a reproducible output format.
- Use this skill when you need a documented fallback path for missing inputs, execution errors, or partial evidence.
When NOT to Use
- Do not use for classifying adverse events (use a MedDRA coding tool).
- Do not use as the final authority on deviation severity — classification must be confirmed by clinical QA personnel.
- Do not use for non-clinical-trial compliance issues (e.g., manufacturing, lab QC).
- Do not use when the deviation description is too vague to assess impact on safety, data integrity, or scientific validity — request clarification first.
Workflow
- Receive deviation: Collect the deviation description, type category, and optional severity factors (safety_impact, data_impact, scientific_impact). If the description is vague, request clarification before proceeding.
- Assess impact dimensions: Evaluate the deviation against three dimensions — Subject Safety (none/low/medium/high), Data Integrity (none/low/medium/high), and Scientific Validity (none/low/medium/high). Use the classification standards tables above as reference.
- Apply classification rules: Any dimension = High → Major Deviation. Safety = Medium AND (Data OR Science) = Medium+ → Major Deviation. Otherwise → Minor Deviation.
- Generate output: Return classification with confidence score, rationale, regulatory basis (ICH E6 section references), and recommended actions. Use the JSON output format for batch processing.
- Fallback: If the deviation type is not in the classification standards table, classify based on the three impact dimensions alone and flag for manual QA review.
Features
- Automatic Classification: Automatically determines severity based on deviation description
- Risk Assessment: Assesses impact on subject safety, data integrity, and scientific validity
- Regulatory Basis: Classification basis complies with GCP, ICH E6, and FDA/EMA guidelines
- Report Generation: Generates deviation classification reports that meet regulatory requirements
- Chinese Support: Full support for Chinese clinical trial scenarios
Deviation Classification Standards
Major/Critical Deviation
Deviations that may affect trial data integrity, subject safety, or trial scientific validity:
| Category |
Examples |
| Informed Consent |
Performing research procedures without informed consent, using expired/incorrect informed consent forms |
| Inclusion/Exclusion Criteria |
Enrolling subjects who don't meet inclusion criteria, enrolling subjects who meet exclusion criteria |
| Investigational Product |
Overdose administration, contraindicated concomitant medication, incorrect route of administration, randomization error |
| Safety |
Not performing safety monitoring as required by protocol, missing SAE/SUSAR reports, delayed reporting |
| Blinding |
Unblinding by unauthorized personnel, unrecorded emergency unblinding procedures |
| Data Integrity |
Falsifying/fabricating data, systematic missing of critical data |
| Prohibited Operations |
Violating key operational procedures of trial protocol, not performing key efficacy assessments |
Minor Deviation
Deviations unlikely to affect trial data integrity, subject safety, or trial scientific validity:
| Category |
Examples |
| Visit Window |
Slightly exceeding visit time window (e.g., within a few days), delay of non-critical visits |
| Sample Collection |
Minor timing deviations in non-critical sample collection, slight delays in sample processing |
| Questionnaire Completion |
Quality of life questionnaires/diary cards submitted a few days late |
| Data Recording |
Delays in non-critical data recording, spelling/formatting errors |
| Procedure Execution |
Adjustment of secondary procedure execution order, omission of non-critical assessments (e.g., height measurement) |
| Documentation |
Delays in source document signatures, missing secondary documents (e.g., non-critical examination reports) |
Usage
Python API
from scripts.main import DeviationClassifier
# Initialize classifier
classifier = DeviationClassifier()
# Classify single deviation
result = classifier.classify(
description="Subject visit delayed by 2 days",
deviation_type="Visit Window"
)
print(result.classification) # "Minor Deviation"
print(result.confidence) # 0.92
print(result.rationale) # Classification rationale explanation
# Batch classification
deviations = [
{"description": "Blood sample collected without informed consent", "type": "Informed Consent"},
{"description": "Quality of life questionnaire submitted 3 days late", "type": "Data Collection"}
]
batch_results = classifier.classify_batch(deviations)
# Generate report
report = classifier.generate_report(batch_results)
CLI Usage
# Classify single deviation
python scripts/main.py classify --description "Subject visit delayed by 2 days" --type "Visit Window"
# Batch classification from file
python scripts/main.py batch --input deviations.json --output report.json
# Interactive classification
python scripts/main.py interactive
# Assess deviation impact
python scripts/main.py assess \
--description "Subject accidentally took double dose of investigational drug" \
--safety-impact high \
--data-impact medium \
--scientific-impact medium
Input Format
JSON Input File Format:
[
{
"id": "DEV-001",
"description": "Subject visit delayed by 2 days",
"type": "Visit Window",
"occurrence_date": "2024-01-15",
"severity_factors": {
"safety_impact": "none",
"data_impact": "low",
"scientific_impact": "low"
}
},
{
"id": "DEV-002",
"description": "Blood collection performed without informed consent",
"type": "Informed Consent",
"severity_factors": {
"safety_impact": "high",
"data_impact": "high",
"scientific_impact": "high"
}
}
]
Output Format
Classification Result:
{
"id": "DEV-001",
"classification": "Minor Deviation",
"classification_en": "Minor Deviation",
"confidence": 0.92,
"rationale": "Visit time window slightly delayed (2 days), does not affect subject safety, data integrity, or trial scientific validity.",
"risk_factors": {
"safety_risk": "none",
"data_integrity_risk": "low",
"scientific_validity_risk": "none"
},
"regulatory_basis": [
"ICH E6(R2) Section 4.5",
"GCP Section 6.4.4"
],
"recommended_actions": [
"Document in file",
"Track trends"
]
}
Classification Algorithm
Classification based on the following assessment dimensions:
Subject Safety Impact (Safety Impact)
- None: No impact
- Low: Minor impact
- Medium: Moderate impact
- High: Serious impact
Data Integrity Impact (Data Integrity Impact)
- None: No impact
- Low: Minor impact on non-critical data
- Medium: Partial impact on critical data
- High: Serious damage to critical data
Trial Scientific Validity Impact (Scientific Validity Impact)
- None: No impact
- Low: Minor impact on statistical power
- Medium: May affect primary endpoint
- High: Seriously affects trial conclusion
Classification Rules:
- Any dimension is High → Major Deviation
- Safety dimension is Medium and Data/Science either is Medium+ → Major Deviation
- Other cases → Minor Deviation
Regulatory Basis
- ICH E6(R2) Good Clinical Practice Guideline
- ICH E6(R3) Good Clinical Practice Guideline (Draft)
- FDA 21 CFR Part 312 (IND Regulations)
- FDA Guidance for Industry: Oversight of Clinical Investigations
- EMA Reflection Paper on Risk Based Quality Management
- NMPA Good Clinical Practice for Drug Clinical Trials
Dependencies
- Python 3.8+
- No third-party dependencies (pure Python standard library implementation)
Notes
- This tool provides classification recommendations, final determination must be confirmed by clinical quality assurance personnel
- Serious/critical deviations must be reported to sponsor and ethics committee immediately
- It is recommended to regularly review deviation trends and implement CAPA (Corrective and Preventive Actions)
- Classification standards may vary by regulatory agency, trial type, and protocol requirements
Risk Assessment
| Risk Indicator |
Assessment |
Level |
| Code Execution |
Python/R scripts executed locally |
Medium |
| Network Access |
No external API calls |
Low |
| File System Access |
Read input files, write output files |
Medium |
| Instruction Tampering |
Standard prompt guidelines |
Low |
| Data Exposure |
Output files saved to workspace |
Low |
Security Checklist
Prerequisites
# Python dependencies
pip install -r requirements.txt
Evaluation Criteria
Success Metrics
Test Cases
- Basic Functionality: Standard input → Expected output
- Edge Case: Invalid input → Graceful error handling
- Performance: Large dataset → Acceptable processing time
Lifecycle Status
- Current Stage: Draft
- Next Review Date: 2026-03-06
- Known Issues: None
- Planned Improvements:
- Performance optimization
- Additional feature support
Output Requirements
Every final response should make these items explicit when they are relevant:
- Objective or requested deliverable
- Inputs used and assumptions introduced
- Workflow or decision path
- Core result, recommendation, or artifact
- Constraints, risks, caveats, or validation needs
- Unresolved items and next-step checks
Error Handling
- If required inputs are missing, state exactly which fields are missing and request only the minimum additional information.
- If the task goes outside the documented scope, stop instead of guessing or silently widening the assignment.
- If
scripts/main.py fails, report the failure point, summarize what still can be completed safely, and provide a manual fallback.
- Do not fabricate files, citations, data, search results, or execution outcomes.
Input Validation
This skill accepts requests that match the documented purpose of protocol-deviation-classifier and include enough context to complete the workflow safely.
Do not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:
protocol-deviation-classifier only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.
Response Template
Use the following fixed structure for non-trivial requests:
- Objective
- Inputs Received
- Assumptions
- Workflow
- Deliverable
- Risks and Limits
- Next Checks
If the request is simple, you may compress the structure, but still keep assumptions and limits explicit when they affect correctness.
Inputs to Collect
- Required inputs: the user goal, the primary data or source file, and the requested output format.
- Optional inputs: output directory, formatting preferences, and validation constraints.
- If a required input is unavailable, return a short clarification request before continuing.
Output Contract
- Return a short summary, the main deliverables, and any assumptions that materially affect interpretation.
- If execution is partial, label what succeeded, what failed, and the next safe recovery step.
- Keep the final answer within the documented scope of the skill.
Validation and Safety Rules
- Validate identifiers, file paths, and user-provided parameters before execution.
- Do not fabricate results, metrics, citations, or downstream conclusions.
- Use safe fallback behavior when dependencies, credentials, or required inputs are missing.
- Surface any execution failure with a concise diagnosis and recovery path.
1---2name: protocol-deviation-classifier3description: Classify clinical trial protocol deviations as major or minor based on ICH E6/GCP guidelines. Three-impact-dimension assessment (safety, data integrity, scientific validity), confidence scoring, and regulatory compliance reporting with recommended actions.4license: MIT5---6> **Source**: [https://github.com/aipoch/medical-research-skills](https://github.com/aipoch/medical-research-skills)
7
8
9# Protocol Deviation Classifier
10
11Clinical trial protocol deviation classification tool, based on GCP and ICH E6 guidelines, automatically determines whether deviations belong to "major deviations" or "minor deviations".
12
13## Quick Check
14
15Use this command to verify that the packaged script entry point can be parsed before deeper execution.
16
17```bash
18python -m py_compile scripts/main.py
19```
20
21## Audit-Ready Commands
22
23Use these concrete commands for validation. They are intentionally self-contained and avoid placeholder paths.
24
25```bash
26python -m py_compile scripts/main.py
27python scripts/main.py --help
28python scripts/main.py --input "Audit validation sample with explicit symptoms, history, assessment, and next-step plan." --format json
29```
30
31## When to Use
32
33- Use this skill when the task needs Determine whether an incident in a clinical trial is a "major deviation.
34- Use this skill for data analysis tasks that require explicit assumptions, bounded scope, and a reproducible output format.
35- Use this skill when you need a documented fallback path for missing inputs, execution errors, or partial evidence.
36
37## When NOT to Use
38
39- Do not use for classifying adverse events (use a MedDRA coding tool).
40- Do not use as the final authority on deviation severity — classification must be confirmed by clinical QA personnel.
41- Do not use for non-clinical-trial compliance issues (e.g., manufacturing, lab QC).
42- Do not use when the deviation description is too vague to assess impact on safety, data integrity, or scientific validity — request clarification first.
43
44## Workflow
45
461. **Receive deviation**: Collect the deviation description, type category, and optional severity factors (safety_impact, data_impact, scientific_impact). If the description is vague, request clarification before proceeding.
472. **Assess impact dimensions**: Evaluate the deviation against three dimensions — Subject Safety (none/low/medium/high), Data Integrity (none/low/medium/high), and Scientific Validity (none/low/medium/high). Use the classification standards tables above as reference.
483. **Apply classification rules**: Any dimension = High → Major Deviation. Safety = Medium AND (Data OR Science) = Medium+ → Major Deviation. Otherwise → Minor Deviation.
494. **Generate output**: Return classification with confidence score, rationale, regulatory basis (ICH E6 section references), and recommended actions. Use the JSON output format for batch processing.
505. **Fallback**: If the deviation type is not in the classification standards table, classify based on the three impact dimensions alone and flag for manual QA review.
51
52## Features
53
54- **Automatic Classification**: Automatically determines severity based on deviation description
55- **Risk Assessment**: Assesses impact on subject safety, data integrity, and scientific validity
56- **Regulatory Basis**: Classification basis complies with GCP, ICH E6, and FDA/EMA guidelines
57- **Report Generation**: Generates deviation classification reports that meet regulatory requirements
58- **Chinese Support**: Full support for Chinese clinical trial scenarios
59
60## Deviation Classification Standards
61
62### Major/Critical Deviation
63
64Deviations that may affect trial data integrity, subject safety, or trial scientific validity:
65
66| Category | Examples |
67|------|------|
68| Informed Consent | Performing research procedures without informed consent, using expired/incorrect informed consent forms |
69| Inclusion/Exclusion Criteria | Enrolling subjects who don't meet inclusion criteria, enrolling subjects who meet exclusion criteria |
70| Investigational Product | Overdose administration, contraindicated concomitant medication, incorrect route of administration, randomization error |
71| Safety | Not performing safety monitoring as required by protocol, missing SAE/SUSAR reports, delayed reporting |
72| Blinding | Unblinding by unauthorized personnel, unrecorded emergency unblinding procedures |
73| Data Integrity | Falsifying/fabricating data, systematic missing of critical data |
74| Prohibited Operations | Violating key operational procedures of trial protocol, not performing key efficacy assessments |
75
76### Minor Deviation
77
78Deviations unlikely to affect trial data integrity, subject safety, or trial scientific validity:
79
80| Category | Examples |
81|------|------|
82| Visit Window | Slightly exceeding visit time window (e.g., within a few days), delay of non-critical visits |
83| Sample Collection | Minor timing deviations in non-critical sample collection, slight delays in sample processing |
84| Questionnaire Completion | Quality of life questionnaires/diary cards submitted a few days late |
85| Data Recording | Delays in non-critical data recording, spelling/formatting errors |
86| Procedure Execution | Adjustment of secondary procedure execution order, omission of non-critical assessments (e.g., height measurement) |
87| Documentation | Delays in source document signatures, missing secondary documents (e.g., non-critical examination reports) |
88
89## Usage
90
91### Python API
92
93```python
94from scripts.main import DeviationClassifier
95
96# Initialize classifier
97classifier = DeviationClassifier()
98
99# Classify single deviation
100result = classifier.classify(
101 description="Subject visit delayed by 2 days",
102 deviation_type="Visit Window"
103)
104print(result.classification) # "Minor Deviation"
105print(result.confidence) # 0.92
106print(result.rationale) # Classification rationale explanation
107
108# Batch classification
109deviations = [
110 {"description": "Blood sample collected without informed consent", "type": "Informed Consent"},
111 {"description": "Quality of life questionnaire submitted 3 days late", "type": "Data Collection"}
112]
113batch_results = classifier.classify_batch(deviations)
114
115# Generate report
116report = classifier.generate_report(batch_results)
117```
118
119### CLI Usage
120
121```text
122# Classify single deviation
123python scripts/main.py classify --description "Subject visit delayed by 2 days" --type "Visit Window"
124
125# Batch classification from file
126python scripts/main.py batch --input deviations.json --output report.json
127
128# Interactive classification
129python scripts/main.py interactive
130
131# Assess deviation impact
132python scripts/main.py assess \
133 --description "Subject accidentally took double dose of investigational drug" \
134 --safety-impact high \
135 --data-impact medium \
136 --scientific-impact medium
137```
138
139### Input Format
140
141**JSON Input File Format:**
142
143```json
144[
145 {
146 "id": "DEV-001",
147 "description": "Subject visit delayed by 2 days",
148 "type": "Visit Window",
149 "occurrence_date": "2024-01-15",
150 "severity_factors": {
151 "safety_impact": "none",
152 "data_impact": "low",
153 "scientific_impact": "low"
154 }
155 },
156 {
157 "id": "DEV-002",
158 "description": "Blood collection performed without informed consent",
159 "type": "Informed Consent",
160 "severity_factors": {
161 "safety_impact": "high",
162 "data_impact": "high",
163 "scientific_impact": "high"
164 }
165 }
166]
167```
168
169### Output Format
170
171**Classification Result:**
172
173```json
174{
175 "id": "DEV-001",
176 "classification": "Minor Deviation",
177 "classification_en": "Minor Deviation",
178 "confidence": 0.92,
179 "rationale": "Visit time window slightly delayed (2 days), does not affect subject safety, data integrity, or trial scientific validity.",
180 "risk_factors": {
181 "safety_risk": "none",
182 "data_integrity_risk": "low",
183 "scientific_validity_risk": "none"
184 },
185 "regulatory_basis": [
186 "ICH E6(R2) Section 4.5",
187 "GCP Section 6.4.4"
188 ],
189 "recommended_actions": [
190 "Document in file",
191 "Track trends"
192 ]
193}
194```
195
196## Classification Algorithm
197
198Classification based on the following assessment dimensions:
199
2001. **Subject Safety Impact** (Safety Impact)
201 - None: No impact
202 - Low: Minor impact
203 - Medium: Moderate impact
204 - High: Serious impact
205
2062. **Data Integrity Impact** (Data Integrity Impact)
207 - None: No impact
208 - Low: Minor impact on non-critical data
209 - Medium: Partial impact on critical data
210 - High: Serious damage to critical data
211
2123. **Trial Scientific Validity Impact** (Scientific Validity Impact)
213 - None: No impact
214 - Low: Minor impact on statistical power
215 - Medium: May affect primary endpoint
216 - High: Seriously affects trial conclusion
217
218**Classification Rules:**
219- Any dimension is High → Major Deviation
220- Safety dimension is Medium and Data/Science either is Medium+ → Major Deviation
221- Other cases → Minor Deviation
222
223## Regulatory Basis
224
225- ICH E6(R2) Good Clinical Practice Guideline
226- ICH E6(R3) Good Clinical Practice Guideline (Draft)
227- FDA 21 CFR Part 312 (IND Regulations)
228- FDA Guidance for Industry: Oversight of Clinical Investigations
229- EMA Reflection Paper on Risk Based Quality Management
230- NMPA Good Clinical Practice for Drug Clinical Trials
231
232## Dependencies
233
234- Python 3.8+
235- No third-party dependencies (pure Python standard library implementation)
236
237## Notes
238
2391. This tool provides classification recommendations, final determination must be confirmed by clinical quality assurance personnel
2402. Serious/critical deviations must be reported to sponsor and ethics committee immediately
2413. It is recommended to regularly review deviation trends and implement CAPA (Corrective and Preventive Actions)
2424. Classification standards may vary by regulatory agency, trial type, and protocol requirements
243
244## Risk Assessment
245
246| Risk Indicator | Assessment | Level |
247|----------------|------------|-------|
248| Code Execution | Python/R scripts executed locally | Medium |
249| Network Access | No external API calls | Low |
250| File System Access | Read input files, write output files | Medium |
251| Instruction Tampering | Standard prompt guidelines | Low |
252| Data Exposure | Output files saved to workspace | Low |
253
254## Security Checklist
255
256- [ ] No hardcoded credentials or API keys
257- [ ] No unauthorized file system access (../)
258- [ ] Output does not expose sensitive information
259- [ ] Prompt injection protections in place
260- [ ] Input file paths validated (no ../ traversal)
261- [ ] Output directory restricted to workspace
262- [ ] Script execution in sandboxed environment
263- [ ] Error messages sanitized (no stack traces exposed)
264- [ ] Dependencies audited
265
266## Prerequisites
267
268```text
269# Python dependencies
270pip install -r requirements.txt
271```
272
273## Evaluation Criteria
274
275### Success Metrics
276- [ ] Successfully executes main functionality
277- [ ] Output meets quality standards
278- [ ] Handles edge cases gracefully
279- [ ] Performance is acceptable
280
281### Test Cases
2821. **Basic Functionality**: Standard input → Expected output
2832. **Edge Case**: Invalid input → Graceful error handling
2843. **Performance**: Large dataset → Acceptable processing time
285
286## Lifecycle Status
287
288- **Current Stage**: Draft
289- **Next Review Date**: 2026-03-06
290- **Known Issues**: None
291- **Planned Improvements**:
292 - Performance optimization
293 - Additional feature support
294
295## Output Requirements
296
297Every final response should make these items explicit when they are relevant:
298
299- Objective or requested deliverable
300- Inputs used and assumptions introduced
301- Workflow or decision path
302- Core result, recommendation, or artifact
303- Constraints, risks, caveats, or validation needs
304- Unresolved items and next-step checks
305
306## Error Handling
307
308- If required inputs are missing, state exactly which fields are missing and request only the minimum additional information.
309- If the task goes outside the documented scope, stop instead of guessing or silently widening the assignment.
310- If `scripts/main.py` fails, report the failure point, summarize what still can be completed safely, and provide a manual fallback.
311- Do not fabricate files, citations, data, search results, or execution outcomes.
312
313## Input Validation
314
315This skill accepts requests that match the documented purpose of `protocol-deviation-classifier` and include enough context to complete the workflow safely.
316
317Do not continue the workflow when the request is out of scope, missing a critical input, or would require unsupported assumptions. Instead respond:
318
319> `protocol-deviation-classifier` only handles its documented workflow. Please provide the missing required inputs or switch to a more suitable skill.
320
321## Response Template
322
323Use the following fixed structure for non-trivial requests:
324
3251. Objective
3262. Inputs Received
3273. Assumptions
3284. Workflow
3295. Deliverable
3306. Risks and Limits
3317. Next Checks
332
333If the request is simple, you may compress the structure, but still keep assumptions and limits explicit when they affect correctness.
334
335
336## Inputs to Collect
337
338- Required inputs: the user goal, the primary data or source file, and the requested output format.
339- Optional inputs: output directory, formatting preferences, and validation constraints.
340- If a required input is unavailable, return a short clarification request before continuing.
341
342
343## Output Contract
344
345- Return a short summary, the main deliverables, and any assumptions that materially affect interpretation.
346- If execution is partial, label what succeeded, what failed, and the next safe recovery step.
347- Keep the final answer within the documented scope of the skill.
348
349
350## Validation and Safety Rules
351
352- Validate identifiers, file paths, and user-provided parameters before execution.
353- Do not fabricate results, metrics, citations, or downstream conclusions.
354- Use safe fallback behavior when dependencies, credentials, or required inputs are missing.
355- Surface any execution failure with a concise diagnosis and recovery path.