
Capa Officer
- 112 installs
- 451 repo stars
- Updated July 21, 2026
- borghei/claude-skills
Draft and review CAPA records, root-cause analyses, and preventive action plans for regulated quality systems after deviations or audit findings.
About
Acts as a CAPA officer advisor for regulated environments. Helps structure deviation investigations, root-cause analysis, corrective and preventive action plans, and closure evidence so quality teams produce audit-ready CAPA documentation and sustained process fixes.
- Structures CAPA investigation narratives
- Separates corrective vs preventive actions
- Supports audit-ready documentation tone
- Prompts root-cause and effectiveness checks
- Aligns with regulated quality workflows
Capa Officer by the numbers
- 112 all-time installs (skills.sh)
- Ranked #631 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/borghei/claude-skills --skill capa-officerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 112 |
|---|---|
| repo stars | ★ 451 |
| Last updated | July 21, 2026 |
| Repository | borghei/claude-skills ↗ |
What it does
Draft and review CAPA records, root-cause analyses, and preventive action plans for regulated quality systems after deviations or audit findings.
Files
CAPA Officer
Corrective and Preventive Action (CAPA) management within Quality Management Systems, focusing on systematic root cause analysis, action implementation, and effectiveness verification.
---
Table of Contents
- CAPA Investigation Workflow
- Root Cause Analysis
- Corrective Action Planning
- Effectiveness Verification
- CAPA Metrics and Reporting
- Reference Documentation
- Tools
---
CAPA Investigation Workflow
Conduct systematic CAPA investigation from initiation through closure:
1. Document trigger event with objective evidence 2. Assess significance and determine CAPA necessity 3. Form investigation team with relevant expertise 4. Collect data and evidence systematically 5. Select and apply appropriate RCA methodology 6. Identify root cause(s) with supporting evidence 7. Develop corrective and preventive actions 8. Validation: Root cause explains all symptoms; if eliminated, problem would not recur
CAPA Necessity Determination
| Trigger Type | CAPA Required | Criteria |
|---|---|---|
| Customer complaint (safety) | Yes | Any complaint involving patient/user safety |
| Customer complaint (quality) | Evaluate | Based on severity and frequency |
| Internal audit finding (Major) | Yes | Systematic failure or absence of element |
| Internal audit finding (Minor) | Recommended | Isolated lapse or partial implementation |
| Nonconformance (recurring) | Yes | Same NC type occurring 3+ times |
| Nonconformance (isolated) | Evaluate | Based on severity and risk |
| External audit finding | Yes | All Major and Minor findings |
| Trend analysis | Evaluate | Based on trend significance |
Investigation Team Composition
| CAPA Severity | Required Team Members |
|---|---|
| Critical | CAPA Officer, Process Owner, QA Manager, Subject Matter Expert, Management Rep |
| Major | CAPA Officer, Process Owner, Subject Matter Expert |
| Minor | CAPA Officer, Process Owner |
Evidence Collection Checklist
- [ ] Problem description with specific details (what, where, when, who, how much)
- [ ] Timeline of events leading to issue
- [ ] Relevant records and documentation
- [ ] Interview notes from involved personnel
- [ ] Photos or physical evidence (if applicable)
- [ ] Related complaints, NCs, or previous CAPAs
- [ ] Process parameters and specifications
---
Root Cause Analysis
Select and apply appropriate RCA methodology based on problem characteristics.
RCA Method Selection Decision Tree
Is the issue safety-critical or involves system reliability?
├── Yes → Use FAULT TREE ANALYSIS
└── No → Is human error the suspected primary cause?
├── Yes → Use HUMAN FACTORS ANALYSIS
└── No → How many potential contributing factors?
├── 1-2 factors (linear causation) → Use 5 WHY ANALYSIS
├── 3-6 factors (complex, systemic) → Use FISHBONE DIAGRAM
└── Unknown/proactive assessment → Use FMEA5 Why Analysis
Use when: Single-cause issues with linear causation, process deviations with clear failure point.
Template:
PROBLEM: [Clear, specific statement]
WHY 1: Why did [problem] occur?
BECAUSE: [First-level cause]
EVIDENCE: [Supporting data]
WHY 2: Why did [first-level cause] occur?
BECAUSE: [Second-level cause]
EVIDENCE: [Supporting data]
WHY 3: Why did [second-level cause] occur?
BECAUSE: [Third-level cause]
EVIDENCE: [Supporting data]
WHY 4: Why did [third-level cause] occur?
BECAUSE: [Fourth-level cause]
EVIDENCE: [Supporting data]
WHY 5: Why did [fourth-level cause] occur?
BECAUSE: [Root cause]
EVIDENCE: [Supporting data]Example - Calibration Overdue:
PROBLEM: pH meter (EQ-042) found 2 months overdue for calibration
WHY 1: Why was calibration overdue?
BECAUSE: Equipment was not on calibration schedule
EVIDENCE: Calibration schedule reviewed, EQ-042 not listed
WHY 2: Why was it not on the schedule?
BECAUSE: Schedule not updated when equipment was purchased
EVIDENCE: Purchase date 2023-06-15, schedule dated 2023-01-01
WHY 3: Why was the schedule not updated?
BECAUSE: No process requires schedule update at equipment purchase
EVIDENCE: SOP-EQ-001 reviewed, no such requirement
WHY 4: Why is there no such requirement?
BECAUSE: Procedure written before equipment tracking was centralized
EVIDENCE: SOP last revised 2019, equipment system implemented 2021
WHY 5: Why has procedure not been updated?
BECAUSE: Periodic review did not assess compatibility with new systems
EVIDENCE: No review against new equipment system documented
ROOT CAUSE: Procedure review process does not assess compatibility
with organizational systems implemented after original procedure creation.Fishbone Diagram Categories (6M)
| Category | Focus Areas | Typical Causes |
|---|---|---|
| Man (People) | Training, competency, workload | Skill gaps, fatigue, communication |
| Machine (Equipment) | Calibration, maintenance, age | Wear, malfunction, inadequate capacity |
| Method (Process) | Procedures, work instructions | Unclear steps, missing controls |
| Material | Specifications, suppliers, storage | Out-of-spec, degradation, contamination |
| Measurement | Calibration, methods, interpretation | Instrument error, wrong method |
| Mother Nature | Temperature, humidity, cleanliness | Environmental excursions |
See references/rca-methodologies.md for complete method details and templates.
Root Cause Validation
Before proceeding to action planning, validate root cause:
- [ ] Root cause can be verified with objective evidence
- [ ] If root cause is eliminated, problem would not recur
- [ ] Root cause is within organizational control
- [ ] Root cause explains all observed symptoms
- [ ] No other significant causes remain unaddressed
---
Corrective Action Planning
Develop effective actions addressing identified root causes:
1. Define immediate containment actions 2. Develop corrective actions targeting root cause 3. Identify preventive actions for similar processes 4. Assign responsibilities and resources 5. Establish timeline with milestones 6. Define success criteria and verification method 7. Document in CAPA action plan 8. Validation: Actions directly address root cause; success criteria are measurable
Action Types
| Type | Purpose | Timeline | Example |
|---|---|---|---|
| Containment | Stop immediate impact | 24-72 hours | Quarantine affected product |
| Correction | Fix the specific occurrence | 1-2 weeks | Rework or replace affected items |
| Corrective | Eliminate root cause | 30-90 days | Revise procedure, add controls |
| Preventive | Prevent in other areas | 60-120 days | Extend solution to similar processes |
Action Plan Components
ACTION PLAN TEMPLATE
CAPA Number: [CAPA-XXXX]
Root Cause: [Identified root cause]
ACTION 1: [Specific action description]
- Type: [ ] Containment [ ] Correction [ ] Corrective [ ] Preventive
- Responsible: [Name, Title]
- Due Date: [YYYY-MM-DD]
- Resources: [Required resources]
- Success Criteria: [Measurable outcome]
- Verification Method: [How success will be verified]
ACTION 2: [Specific action description]
...
IMPLEMENTATION TIMELINE:
Week 1: [Milestone]
Week 2: [Milestone]
Week 4: [Milestone]
Week 8: [Milestone]
APPROVAL:
CAPA Owner: _____________ Date: _______
Process Owner: _____________ Date: _______
QA Manager: _____________ Date: _______Action Effectiveness Indicators
| Indicator | Target | Red Flag |
|---|---|---|
| Action scope | Addresses root cause completely | Treats only symptoms |
| Specificity | Measurable deliverables | Vague commitments |
| Timeline | Aggressive but achievable | No due dates or unrealistic |
| Resources | Identified and allocated | Not specified |
| Sustainability | Permanent solution | Temporary fix |
---
Effectiveness Verification
Verify corrective actions achieved intended results:
1. Allow adequate implementation period (minimum 30-90 days) 2. Collect post-implementation data 3. Compare to pre-implementation baseline 4. Evaluate against success criteria 5. Verify no recurrence during verification period 6. Document verification evidence 7. Determine CAPA effectiveness 8. Validation: All criteria met with objective evidence; no recurrence observed
Verification Timeline Guidelines
| CAPA Severity | Wait Period | Verification Window |
|---|---|---|
| Critical | 30 days | 30-90 days post-implementation |
| Major | 60 days | 60-180 days post-implementation |
| Minor | 90 days | 90-365 days post-implementation |
Verification Methods
| Method | Use When | Evidence Required |
|---|---|---|
| Data trend analysis | Quantifiable issues | Pre/post comparison, trend charts |
| Process audit | Procedure compliance issues | Audit checklist, interview notes |
| Record review | Documentation issues | Sample records, compliance rate |
| Testing/inspection | Product quality issues | Test results, pass/fail data |
| Interview/observation | Training issues | Interview notes, observation records |
Effectiveness Determination
Did recurrence occur during verification period?
├── Yes → CAPA INEFFECTIVE (re-investigate root cause)
└── No → Were all effectiveness criteria met?
├── Yes → CAPA EFFECTIVE (proceed to closure)
└── No → Extent of gap?
├── Minor gap → Extend verification or accept with justification
└── Significant gap → CAPA INEFFECTIVE (revise actions)See references/effectiveness-verification-guide.md for detailed procedures.
---
CAPA Metrics and Reporting
Monitor CAPA program performance through key indicators.
Key Performance Indicators
| Metric | Target | Calculation |
|---|---|---|
| CAPA cycle time | <60 days average | (Close Date - Open Date) / Number of CAPAs |
| Overdue rate | <10% | Overdue CAPAs / Total Open CAPAs |
| First-time effectiveness | >90% | Effective on first verification / Total verified |
| Recurrence rate | <5% | Recurred issues / Total closed CAPAs |
| Investigation quality | 100% root cause validated | Root causes validated / Total CAPAs |
Aging Analysis Categories
| Age Bucket | Status | Action Required |
|---|---|---|
| 0-30 days | On track | Monitor progress |
| 31-60 days | Monitor | Review for delays |
| 61-90 days | Warning | Escalate to management |
| >90 days | Critical | Management intervention required |
Management Review Inputs
Monthly CAPA status report includes:
- Open CAPA count by severity and status
- Overdue CAPA list with owners
- Cycle time trends
- Effectiveness rate trends
- Source analysis (complaints, audits, NCs)
- Recommendations for improvement
---
Reference Documentation
Root Cause Analysis Methodologies
references/rca-methodologies.md contains:
- Method selection decision tree
- 5 Why analysis template and example
- Fishbone diagram categories and template
- Fault Tree Analysis for safety-critical issues
- Human Factors Analysis for people-related causes
- FMEA for proactive risk assessment
- Hybrid approach guidance
Effectiveness Verification Guide
references/effectiveness-verification-guide.md contains:
- Verification planning requirements
- Verification method selection
- Effectiveness criteria definition (SMART)
- Closure requirements by severity
- Ineffective CAPA process
- Documentation templates
---
Tools
CAPA Tracker
# Generate CAPA status report
python scripts/capa_tracker.py --capas capas.json
# Interactive mode for manual entry
python scripts/capa_tracker.py --interactive
# JSON output for integration
python scripts/capa_tracker.py --capas capas.json --output json
# Generate sample data file
python scripts/capa_tracker.py --sample > sample_capas.jsonCalculates and reports:
- Summary metrics (open, closed, overdue, cycle time, effectiveness)
- Status distribution
- Severity and source analysis
- Aging report by time bucket
- Overdue CAPA list
- Actionable recommendations
Sample CAPA Input
{
"capas": [
{
"capa_number": "CAPA-2024-001",
"title": "Calibration overdue for pH meter",
"description": "pH meter EQ-042 found 2 months overdue",
"source": "AUDIT",
"severity": "MAJOR",
"status": "VERIFICATION",
"open_date": "2024-06-15",
"target_date": "2024-08-15",
"owner": "J. Smith",
"root_cause": "Procedure review gap",
"corrective_action": "Updated SOP-EQ-001"
}
]
}---
Regulatory Requirements
ISO 13485:2016 Clause 8.5
| Sub-clause | Requirement | Key Activities |
|---|---|---|
| 8.5.2 Corrective Action | Eliminate cause of nonconformity | NC review, cause determination, action evaluation, implementation, effectiveness review |
| 8.5.3 Preventive Action | Eliminate potential nonconformity | Trend analysis, cause determination, action evaluation, implementation, effectiveness review |
FDA 21 CFR 820.100
Required CAPA elements:
- Procedures for implementing corrective and preventive action
- Analyzing quality data sources (complaints, NCs, audits, service records)
- Investigating cause of nonconformities
- Identifying actions needed to correct and prevent recurrence
- Verifying actions are effective and do not adversely affect device
- Submitting relevant information for management review
Common FDA 483 Observations
| Observation | Root Cause Pattern |
|---|---|
| CAPA not initiated for recurring issue | Trend analysis not performed |
| Root cause analysis superficial | Inadequate investigation training |
| Effectiveness not verified | No verification procedure |
| Actions do not address root cause | Symptom treatment vs. cause elimination |
---
Troubleshooting
| Problem | Possible Cause | Resolution |
|---|---|---|
| Root cause analysis yields only symptoms | Investigation stopped too early or used wrong RCA method | Apply the RCA Method Selection Decision Tree; ensure at least 5 levels of "why" with evidence at each level |
| CAPA effectiveness verification fails repeatedly | Corrective action addresses symptoms, not true root cause | Re-open investigation, consider hybrid RCA approach (e.g., Fishbone + 5-Why), involve additional subject matter experts |
| CAPA cycle times consistently exceed 60-day target | Insufficient resources allocated or unclear ownership | Escalate during management review; assign dedicated CAPA coordinator; break complex CAPAs into phased actions |
| Overdue CAPA rate exceeds 10% | Lack of automated tracking or reminder system | Implement automated alerts via QMS software; run python scripts/capa_tracker.py --capas capas.json weekly to identify aging items |
| Auditors cite "superficial root cause analysis" | Inadequate training on RCA methodologies | Conduct RCA methodology training for investigation teams; use templates from references/rca-methodologies.md; require evidence at each analysis step |
| Recurring issues despite closed CAPAs | Preventive actions not extended to similar processes | During action planning, explicitly assess all analogous processes; add preventive actions targeting systemic causes, not just the specific instance |
| Stakeholders disagree on CAPA severity classification | No standardized severity criteria applied | Use the CAPA Necessity Determination table and Severity definitions consistently; document classification rationale with objective evidence |
---
Success Criteria
- First-time effectiveness rate exceeds 90% -- verified through post-implementation data collection showing no recurrence during the verification window
- Average CAPA cycle time under 60 days -- measured from open date to close date across all severity levels, tracked via
capa_tracker.pymetrics - Overdue rate maintained below 10% -- monitored through aging analysis with escalation triggers at 61-day and 90-day thresholds
- 100% of root causes validated with objective evidence -- every root cause passes the validation checklist (explains all symptoms, elimination prevents recurrence, within organizational control)
- All critical and major CAPAs include preventive actions -- corrective actions address the specific occurrence while preventive actions extend solutions to analogous processes
- Management review receives monthly CAPA status reports -- including open count by severity, overdue list, cycle time trends, and effectiveness rate trends
- Recurrence rate below 5% -- tracked by monitoring closed CAPAs for reappearance of the same issue type within 12 months of closure
---
Scope & Limitations
In Scope:
- CAPA investigation workflow from trigger event through closure
- Root cause analysis using 5-Why, Fishbone (6M), Fault Tree Analysis, Human Factors Analysis, and FMEA methodologies
- Corrective and preventive action planning, implementation tracking, and effectiveness verification
- CAPA metrics calculation, aging analysis, and management reporting
- Alignment with ISO 13485:2016 Clause 8.5 and FDA 21 CFR 820.100 requirements
Out of Scope:
- This skill does not replace a validated eQMS (electronic Quality Management System) for production CAPA tracking -- it provides analysis templates and metric calculations
- Statistical process control and advanced trend analysis requiring specialized SPC software
- Regulatory submission preparation (use
fda-consultant-specialistormdr-745-specialistfor submission-related CAPAs) - Supplier CAPA management beyond internal investigation (use
quality-manager-qms-iso13485for supplier qualification) - Clinical investigation CAPAs requiring medical/scientific expertise beyond procedural guidance
Important Notes:
- Under the FDA QMSR (effective February 2, 2026), CAPA requirements align with ISO 13485:2016 Clause 8.5 rather than the legacy 21 CFR 820.100 structure -- this skill covers both frameworks
- The
capa_tracker.pytool works with JSON input and does not connect to live QMS databases; export data from your eQMS for analysis
---
Integration Points
| Skill | Integration | When to Use |
|---|---|---|
quality-manager-qms-iso13485 | CAPA findings feed into QMS process improvements and supplier corrective actions | When root cause involves QMS process gaps or supplier nonconformances |
qms-audit-expert | Audit findings are a primary CAPA source; CAPA closure evidence supports audit follow-up | When CAPAs originate from internal or external audit findings |
risk-management-specialist | CAPA outcomes update risk assessments; FMEA results may trigger preventive CAPAs | When root cause analysis reveals previously unassessed risks |
fda-consultant-specialist | FDA 483 observations and warning letters require formal CAPA responses | When CAPA originates from FDA inspection findings |
mdr-745-specialist | EU MDR vigilance reports and FSCA may trigger CAPAs; CAPA data feeds PMS/PSUR | When post-market surveillance identifies safety or performance issues |
quality-documentation-manager | Document control updates resulting from CAPA actions; 21 CFR Part 11 compliance for electronic CAPA records | When corrective actions require SOP revisions or new document creation |
---
Tool Reference
capa_tracker.py
Tracks CAPA status, calculates metrics, identifies overdue items, and generates management review reports.
| Flag | Required | Description |
|---|---|---|
--capas <file> | Yes (unless --interactive or --sample) | Path to JSON file containing CAPA records |
--interactive | No | Launch interactive mode for manual CAPA entry |
--output <format> | No | Output format: json for machine-readable, default is human-readable text |
--sample | No | Generate a sample CAPA JSON file to stdout for use as a template |
Calculated Metrics:
- Total, open, closed, and overdue CAPA counts
- Average cycle time (days from open to close)
- First-time effectiveness rate (effective on first verification / total verified)
- Status distribution, severity breakdown, and source analysis
- Aging report bucketed by 0-30, 31-60, 61-90, and 90+ days
- Overdue CAPA list with owners and days past target
Example:
# Generate sample data, then analyze
python scripts/capa_tracker.py --sample > sample_capas.json
python scripts/capa_tracker.py --capas sample_capas.json
python scripts/capa_tracker.py --capas sample_capas.json --output jsonEffectiveness Verification Guide
CAPA effectiveness assessment procedures, verification methods, and closure criteria.
---
Table of Contents
- Verification Planning
- Verification Methods
- Effectiveness Criteria
- Closure Requirements
- Ineffective CAPA Process
- Documentation Templates
---
Verification Planning
When to Plan Verification
Verification planning must occur BEFORE corrective action implementation:
| Stage | Planning Activity | Owner |
|---|---|---|
| CAPA Initiation | Define preliminary verification approach | CAPA Owner |
| Root Cause Analysis | Refine criteria based on root cause | Investigation Team |
| Action Planning | Finalize verification method and timeline | CAPA Owner |
| Implementation | Schedule verification activities | Quality Assurance |
Verification Timeline Guidelines
| CAPA Severity | Minimum Wait Period | Verification Window |
|---|---|---|
| Critical (Safety) | 30 days | 30-90 days post-implementation |
| Major | 60 days | 60-180 days post-implementation |
| Minor | 90 days | 90-365 days post-implementation |
Rationale: Waiting period ensures sufficient data collection and accounts for process variation.
Verification Plan Components
VERIFICATION PLAN TEMPLATE
CAPA Number: [CAPA-XXXX]
Problem Statement: [Original issue]
Root Cause: [Identified root cause]
Corrective Action: [Implemented action]
VERIFICATION METHOD:
[ ] Data Trend Analysis
[ ] Process Audit
[ ] Record Review
[ ] Testing/Inspection
[ ] Interview/Observation
[ ] Multiple Methods (specify)
EFFECTIVENESS CRITERIA:
1. [Measurable criterion 1]
2. [Measurable criterion 2]
3. [Measurable criterion 3]
SUCCESS THRESHOLD:
- [Quantitative threshold, e.g., "Zero recurrence for 90 days"]
- [Qualitative threshold, e.g., "Procedure followed correctly 100%"]
DATA COLLECTION:
- Source: [Where data will come from]
- Sample Size: [Number of records/instances to review]
- Time Period: [Start and end dates]
- Responsible: [Who collects data]
VERIFICATION SCHEDULE:
- Implementation Complete: [Date]
- Waiting Period Ends: [Date]
- Verification Start: [Date]
- Verification Complete: [Date]
- Report Due: [Date]
APPROVAL:
CAPA Owner: _____________ Date: _______
Quality Assurance: _____________ Date: _______---
Verification Methods
1. Data Trend Analysis
Best for: Quantifiable issues with measurable outcomes (defect rates, cycle times, complaint trends)
Procedure: 1. Collect post-implementation data for defined period 2. Compare to pre-implementation baseline 3. Apply statistical analysis if sample size permits 4. Document trend direction and magnitude
Example Criteria:
- Defect rate reduced by ≥50% from baseline
- Zero recurrence of specific failure mode
- Process capability (Cpk) improved to ≥1.33
Evidence Required:
- Pre-implementation baseline data
- Post-implementation trend data
- Statistical analysis (if applicable)
- Trend charts with annotation
2. Process Audit
Best for: Procedure compliance issues, process control failures, systemic problems
Procedure: 1. Develop audit checklist based on corrective action 2. Conduct unannounced process audit 3. Interview operators and supervisors 4. Review records generated since implementation 5. Document compliance percentage
Example Criteria:
- 100% compliance with revised procedure
- All operators demonstrate competency
- No deviations observed during audit
Evidence Required:
- Audit checklist completed
- Interview notes
- Record samples reviewed
- Photos/observations (if applicable)
3. Record Review
Best for: Documentation issues, completeness problems, traceability failures
Procedure: 1. Define sample size based on volume (minimum 10 or 10%, whichever greater) 2. Review records generated post-implementation 3. Evaluate against specified requirements 4. Calculate compliance rate
Example Criteria:
- 100% of records meet completeness requirements
- All required signatures present
- Traceability maintained throughout
Evidence Required:
- List of records reviewed
- Compliance checklist results
- Non-compliance summary (if any)
4. Testing/Inspection
Best for: Product quality issues, equipment failures, specification non-conformances
Procedure: 1. Define test protocol based on corrective action 2. Conduct testing on post-implementation units 3. Compare results to acceptance criteria 4. Document pass/fail rates
Example Criteria:
- 100% of units pass revised inspection criteria
- All test results within specification
- Zero failures of targeted parameter
Evidence Required:
- Test protocol/method
- Test results data
- Pass/fail summary
- Comparison to pre-implementation results
5. Interview/Observation
Best for: Training issues, communication problems, human factors causes
Procedure: 1. Develop structured interview questions 2. Interview representative sample of affected personnel 3. Observe process execution in real-time 4. Document responses and observations
Example Criteria:
- All interviewed personnel demonstrate knowledge
- Observed practices match documented procedure
- No unsafe acts or workarounds observed
Evidence Required:
- Interview questions and responses
- Observation notes
- Training records (supporting)
---
Effectiveness Criteria
Defining Good Criteria
Criteria must be SMART:
| Element | Requirement | Example |
|---|---|---|
| Specific | Clearly defined what to measure | "Calibration overdue rate" not "equipment issues" |
| Measurable | Quantifiable or objectively verifiable | "<2% overdue rate" not "improved timeliness" |
| Achievable | Realistic given the corrective action | Within capability of implemented solution |
| Relevant | Directly related to root cause | Addresses the actual problem |
| Time-bound | Specified evaluation period | "For 90 consecutive days" |
Criteria by Issue Type
| Issue Type | Typical Criteria | Threshold |
|---|---|---|
| Nonconformance | Recurrence rate | Zero recurrence |
| Process deviation | Compliance rate | ≥95% compliance |
| Complaint | Complaint trend | ≥50% reduction |
| Calibration | Overdue rate | <2% overdue |
| Training | Competency pass rate | 100% pass |
| Documentation | Completeness rate | 100% complete |
| Supplier | Incoming reject rate | ≤1% reject rate |
Sample Size Guidelines
| Population Size | Minimum Sample |
|---|---|
| <10 | All (100%) |
| 10-50 | 10 |
| 51-100 | 15 |
| 101-500 | 20 |
| >500 | 25 or 10%, whichever less |
---
Closure Requirements
Closure Checklist
CAPA Closure Prerequisites:
- [ ] All corrective actions implemented
- [ ] Implementation evidence documented
- [ ] Verification waiting period complete
- [ ] Verification activities performed
- [ ] All effectiveness criteria met
- [ ] Verification evidence documented
- [ ] No recurrence during verification period
- [ ] CAPA owner review complete
- [ ] Quality Assurance review complete
- [ ] Documentation complete and filed
Effectiveness Status Determination
EFFECTIVENESS DECISION TREE:
Did recurrence occur during verification period?
├── Yes → CAPA INEFFECTIVE (escalate per ineffective process)
└── No → Were all effectiveness criteria met?
├── Yes → Were any related issues identified?
│ ├── Yes → Open new CAPA if needed, close original
│ └── No → CAPA EFFECTIVE - proceed to closure
└── No → How many criteria missed?
├── Minor gap (1 criterion, marginal miss) →
│ Extend verification period OR accept with justification
└── Significant gap → CAPA INEFFECTIVE
EFFECTIVENESS DETERMINATION:
[ ] EFFECTIVE - All criteria met, no recurrence
[ ] EFFECTIVE WITH CONDITIONS - Minor gap, justified acceptance
[ ] INEFFECTIVE - Significant gaps or recurrenceClosure Documentation
EFFECTIVENESS VERIFICATION REPORT
CAPA Number: [CAPA-XXXX]
Verification Complete Date: [Date]
Verified By: [Name, Title]
VERIFICATION SUMMARY:
| Criterion | Target | Actual | Status |
|-----------|--------|--------|--------|
| [Criterion 1] | [Target] | [Result] | ☑ Met / ☐ Not Met |
| [Criterion 2] | [Target] | [Result] | ☑ Met / ☐ Not Met |
| [Criterion 3] | [Target] | [Result] | ☑ Met / ☐ Not Met |
RECURRENCE CHECK:
- Recurrence during verification period: [ ] Yes [ ] No
- Related issues identified: [ ] Yes [ ] No
- If yes, describe: [Description]
EVIDENCE SUMMARY:
[List of evidence documents, record numbers, data sources]
EFFECTIVENESS DETERMINATION:
[ ] EFFECTIVE
[ ] EFFECTIVE WITH CONDITIONS: [Justification]
[ ] INEFFECTIVE: [Reason]
RECOMMENDED ACTION:
[ ] Close CAPA
[ ] Extend verification period to [Date]
[ ] Open new CAPA [CAPA-XXXX] for [Issue]
[ ] Re-investigate (return to root cause analysis)
APPROVALS:
CAPA Owner: _____________ Date: _______
Quality Assurance: _____________ Date: _______
Management (if Major/Critical): _____________ Date: _______---
Ineffective CAPA Process
Definition of Ineffective
CAPA is ineffective when: 1. Original problem recurs during or after verification period 2. Effectiveness criteria not met 3. Root cause still present 4. Corrective action created new problems
Ineffective CAPA Workflow
INEFFECTIVE CAPA DETECTED
│
├── 1. Immediate Actions
│ ├── Reopen CAPA (do not close as effective)
│ ├── Implement containment for recurrence
│ └── Notify CAPA owner and management
│
├── 2. Root Cause Re-evaluation
│ ├── Was original root cause correct?
│ │ ├── No → Conduct new root cause analysis
│ │ └── Yes → Was corrective action appropriate?
│ │ ├── No → Develop new corrective action
│ │ └── Yes → Was implementation adequate?
│ │ ├── No → Re-implement with improvements
│ │ └── Yes → Escalate (systemic issue)
│
├── 3. Escalation Criteria
│ ├── Second ineffective attempt → Management review required
│ ├── Safety-related recurrence → Immediate escalation
│ └── Pattern across multiple CAPAs → Systemic CAPA
│
└── 4. Documentation
├── Document ineffective status with evidence
├── Record re-investigation results
├── Update CAPA metrics/trending
└── Include in management reviewPreventing Ineffective CAPAs
| Common Cause | Prevention |
|---|---|
| Superficial root cause | Validate root cause before action |
| Action addresses symptom not cause | Ensure action targets root cause |
| Implementation incomplete | Verify implementation before verification |
| Insufficient verification period | Allow adequate time for data collection |
| Wrong verification method | Match method to issue type |
| Unclear success criteria | Define SMART criteria upfront |
---
Documentation Templates
Verification Evidence Log
VERIFICATION EVIDENCE LOG
CAPA Number: [CAPA-XXXX]
| Doc/Record # | Description | Date | Reviewed By | Finding |
|--------------|-------------|------|-------------|---------|
| [Number] | [Description] | [Date] | [Reviewer] | [Compliant/Finding] |
| [Number] | [Description] | [Date] | [Reviewer] | [Compliant/Finding] |
SUMMARY:
- Total records reviewed: [Number]
- Compliant: [Number] ([Percentage]%)
- Non-compliant: [Number] ([Percentage]%)
CONCLUSION:
[Statement on whether evidence supports effectiveness]Trend Analysis Summary
TREND ANALYSIS FOR CAPA VERIFICATION
CAPA Number: [CAPA-XXXX]
Metric: [What is being measured]
BASELINE (Pre-Implementation):
- Period: [Start] to [End]
- Value: [Baseline value]
- Data points: [Number]
POST-IMPLEMENTATION:
- Period: [Start] to [End]
- Value: [Current value]
- Data points: [Number]
CHANGE:
- Absolute change: [Value]
- Percentage change: [Percentage]%
- Target: [Target value/change]
- Status: [ ] Met [ ] Not Met
TREND CHART:
[Include or reference trend chart showing before/after comparison]
STATISTICAL SIGNIFICANCE (if applicable):
- Method: [t-test, chi-square, etc.]
- p-value: [Value]
- Conclusion: [Statistically significant / Not significant]Interview Summary Template
VERIFICATION INTERVIEW SUMMARY
CAPA Number: [CAPA-XXXX]
Interviewer: [Name]
Date: [Date]
INTERVIEWEE:
- Name: [Name]
- Role: [Job title]
- Department: [Department]
- Experience: [Years in role]
QUESTIONS AND RESPONSES:
Q1: [Question about awareness of change]
A1: [Response summary]
Knowledge demonstrated: [ ] Yes [ ] Partial [ ] No
Q2: [Question about implementation of change]
A2: [Response summary]
Compliance demonstrated: [ ] Yes [ ] Partial [ ] No
Q3: [Question about understanding rationale]
A3: [Response summary]
Understanding demonstrated: [ ] Yes [ ] Partial [ ] No
OBSERVATION NOTES:
[Any relevant observations during interview]
CONCLUSION:
[ ] Interviewee demonstrates full knowledge and compliance
[ ] Interviewee demonstrates partial knowledge (specify gaps)
[ ] Interviewee does not demonstrate required knowledgeRoot Cause Analysis Methodologies
Decision criteria, templates, and implementation guidance for RCA techniques.
---
Table of Contents
- Method Selection Matrix
- 5 Why Analysis
- Fishbone Diagram
- Fault Tree Analysis
- Human Factors Analysis
- Failure Mode and Effects Analysis
- Selecting the Right Method
---
Method Selection Matrix
When to Use Each Method
| Method | Use When | Problem Type | Team Size | Time Required |
|---|---|---|---|---|
| 5 Why | Single-cause issues, process deviations | Linear causation | 1-3 people | 30-60 min |
| Fishbone | Multi-factor problems, 3-6 contributing factors | Complex, systemic | 3-8 people | 2-4 hours |
| Fault Tree | Safety-critical failures, reliability issues | System failures | 2-5 people | 4-8 hours |
| Human Factors | Procedure/training-related issues | Human error | 3-6 people | 2-4 hours |
| FMEA | Systematic risk assessment, design review | Potential failures | 4-10 people | 8-16 hours |
Quick Selection Decision Tree
Is the issue safety-critical or involves system reliability?
├── Yes → Use FAULT TREE ANALYSIS
└── No → Is human error the suspected primary cause?
├── Yes → Use HUMAN FACTORS ANALYSIS
└── No → How many potential contributing factors?
├── 1-2 factors → Use 5 WHY ANALYSIS
├── 3-6 factors → Use FISHBONE DIAGRAM
└── Unknown/Many → Use FMEA (proactive) or Fishbone (reactive)---
5 Why Analysis
Overview
Simple, iterative technique asking "why" repeatedly (typically 5 times) to drill from symptoms to root cause.
When to Use
- Single-cause issues with linear causation
- Process deviations with clear failure point
- Quick investigations requiring rapid resolution
- Problems where symptoms clearly link to cause
When NOT to Use
- Complex multi-factor problems
- Safety-critical incidents requiring comprehensive analysis
- Issues with multiple interacting causes
- When systemic factors are suspected
5 Why Template
PROBLEM STATEMENT:
[Clear, specific description of what happened, when, where, and impact]
WHY 1: Why did [problem] occur?
BECAUSE: [First-level cause]
EVIDENCE: [Data/observation supporting this cause]
WHY 2: Why did [first-level cause] occur?
BECAUSE: [Second-level cause]
EVIDENCE: [Data/observation supporting this cause]
WHY 3: Why did [second-level cause] occur?
BECAUSE: [Third-level cause]
EVIDENCE: [Data/observation supporting this cause]
WHY 4: Why did [third-level cause] occur?
BECAUSE: [Fourth-level cause]
EVIDENCE: [Data/observation supporting this cause]
WHY 5: Why did [fourth-level cause] occur?
BECAUSE: [Root cause - typically systemic or management system failure]
EVIDENCE: [Data/observation supporting this cause]
ROOT CAUSE VALIDATION:
- [ ] Can the root cause be verified with evidence?
- [ ] If root cause is eliminated, would problem recur?
- [ ] Is the root cause within organizational control?
- [ ] Does the root cause explain all symptoms?Example: Calibration Overdue
PROBLEM: pH meter (EQ-042) found 2 months overdue for calibration
WHY 1: Why was calibration overdue?
BECAUSE: The equipment was not on the calibration schedule
EVIDENCE: Calibration schedule reviewed, EQ-042 not listed
WHY 2: Why was it not on the calibration schedule?
BECAUSE: The schedule was not updated when equipment was purchased
EVIDENCE: Purchase date 2023-06-15, schedule dated 2023-01-01
WHY 3: Why was the schedule not updated?
BECAUSE: No process requires schedule update at equipment purchase
EVIDENCE: Equipment procedure SOP-EQ-001 reviewed, no such requirement
WHY 4: Why is there no requirement to update the schedule?
BECAUSE: The procedure was written before equipment tracking was centralized
EVIDENCE: SOP-EQ-001 last revised 2019, equipment system implemented 2021
WHY 5: Why has the procedure not been updated?
BECAUSE: Periodic procedure review did not assess compatibility with new systems
EVIDENCE: No documented review of SOP-EQ-001 against new equipment system
ROOT CAUSE: Procedure review process does not assess compatibility
with organizational systems implemented after original procedure creation---
Fishbone Diagram
Overview
Also called Ishikawa or cause-and-effect diagram. Organizes potential causes into categories branching from the problem statement.
Standard Categories (6M)
| Category | Focus Areas | Typical Causes |
|---|---|---|
| Man (People) | Training, competency, workload | Skill gaps, fatigue, communication |
| Machine (Equipment) | Calibration, maintenance, age | Wear, malfunction, inadequate capacity |
| Method (Process) | Procedures, work instructions | Unclear steps, missing controls |
| Material | Specifications, suppliers, storage | Out-of-spec, degradation, contamination |
| Measurement | Calibration, methods, interpretation | Instrument error, wrong method |
| Mother Nature (Environment) | Temperature, humidity, cleanliness | Environmental excursions |
Fishbone Template
PROBLEM STATEMENT: [Effect being investigated]
┌── Man ────────────────┐
│ ├─ [Cause 1] │
│ ├─ [Cause 2] │
│ └─ [Cause 3] │
│ │
┌── Machine ────────┤ ├── Method ──────────┐
│ ├─ [Cause 1] │ │ ├─ [Cause 1] │
│ ├─ [Cause 2] │ PROBLEM │ ├─ [Cause 2] │
│ └─ [Cause 3] ├───────────────────────┤ └─ [Cause 3] │
│ │ │ │
├── Material ───────┤ ├── Measurement ─────┤
│ ├─ [Cause 1] │ │ ├─ [Cause 1] │
│ ├─ [Cause 2] │ │ ├─ [Cause 2] │
│ └─ [Cause 3] │ │ └─ [Cause 3] │
│ │
└── Environment ────────┘
├─ [Cause 1]
├─ [Cause 2]
└─ [Cause 3]
CAUSE PRIORITIZATION:
| Cause | Category | Likelihood | Evidence | Priority |
|-------|----------|------------|----------|----------|
| [Cause A] | Method | High | [Evidence] | 1 |
| [Cause B] | Man | Medium | [Evidence] | 2 |
ROOT CAUSES IDENTIFIED:
1. [Primary root cause with supporting evidence]
2. [Contributing cause with supporting evidence]Facilitation Guidelines
1. Assemble cross-functional team (3-8 people) 2. Define problem statement clearly before starting 3. Brainstorm causes without judgment first 4. Organize into categories after brainstorming 5. Drill down on each major cause (sub-causes) 6. Prioritize based on evidence and likelihood 7. Validate top causes with data
---
Fault Tree Analysis
Overview
Top-down, deductive analysis starting with undesired event and systematically identifying all potential causes using Boolean logic (AND/OR gates).
When to Use
- Safety-critical system failures
- Complex system reliability analysis
- Events with multiple failure pathways
- Regulatory-required investigations (FDA, MDR)
FTA Symbols
| Symbol | Name | Meaning |
|---|---|---|
| Rectangle | Top Event / Intermediate Event | Undesired event or intermediate fault |
| Circle | Basic Event | Primary fault requiring no further analysis |
| Diamond | Undeveloped Event | Event not fully analyzed (data limitation) |
| AND Gate | Requires all inputs | All child events must occur for parent |
| OR Gate | Requires any input | Any child event causes parent |
FTA Template
TOP EVENT: [Undesired event under investigation]
LEVEL 1 (Immediate Causes):
[Top Event]
│
└── OR GATE ──┬── [Cause 1.1]
├── [Cause 1.2]
└── [Cause 1.3]
LEVEL 2 (Contributing Causes):
[Cause 1.1]
│
└── AND GATE ──┬── [Cause 2.1]
└── [Cause 2.2]
MINIMAL CUT SETS:
(Combinations of basic events that cause top event)
1. {Basic Event A, Basic Event B} ← Both required (AND)
2. {Basic Event C} ← Single point failure (OR)
3. {Basic Event D, Basic Event E} ← Both required (AND)
CRITICAL PATH ANALYSIS:
Most likely failure pathway: [Description]
Single points of failure: [List]
RECOMMENDATIONS:
- Address single points of failure first
- Add redundancy where AND gates show vulnerability
- Prioritize controls on highest probability pathsCut Set Analysis
Minimal cut sets identify the smallest combination of basic events causing the top event:
- Single-element cut sets: Single points of failure (highest priority)
- Two-element cut sets: Dual failure scenarios
- Probability calculation: P(Top Event) = Union of P(Cut Sets)
---
Human Factors Analysis
Overview
Systematic analysis of human error focusing on cognitive, physical, and organizational factors contributing to performance failures.
HFACS Categories
Human Factors Analysis and Classification System:
| Level | Category | Examples |
|---|---|---|
| Unsafe Acts | Errors, violations | Skill-based, decision, perceptual errors |
| Preconditions | Conditions for unsafe acts | Fatigue, mental state, CRM, physical environment |
| Unsafe Supervision | Supervisory failures | Inadequate supervision, planned inappropriate ops |
| Organizational Influences | Organizational failures | Resource management, organizational climate |
Human Error Types
| Type | Description | Example | Mitigation |
|---|---|---|---|
| Slip | Execution error in routine task | Wrong button pressed | Error-proofing, forcing functions |
| Lapse | Memory failure | Forgot step in procedure | Checklists, reminders |
| Mistake | Planning/decision error | Wrong procedure selected | Training, decision aids |
| Violation | Intentional deviation | Skipped step to save time | Culture change, supervision |
Human Factors Investigation Template
INCIDENT DESCRIPTION:
[What happened, who was involved, when, where]
UNSAFE ACTS ANALYSIS:
Type of Error: [ ] Slip [ ] Lapse [ ] Mistake [ ] Violation
Description: [Specific action or inaction]
Task Being Performed: [Activity at time of error]
Experience Level: [Novice/Intermediate/Expert]
PRECONDITIONS FOR UNSAFE ACTS:
Cognitive Factors:
- [ ] Task complexity exceeded capability
- [ ] Time pressure
- [ ] Distraction/interruption
- [ ] Mental fatigue
Physical Factors:
- [ ] Physical fatigue
- [ ] Inadequate lighting
- [ ] Noise interference
- [ ] Workspace ergonomics
Team Factors:
- [ ] Communication breakdown
- [ ] Coordination failure
- [ ] Inadequate leadership
SUPERVISORY FACTORS:
- [ ] Inadequate supervision
- [ ] Failed to correct known problem
- [ ] Inappropriate staffing
- [ ] Authorized unnecessary risk
ORGANIZATIONAL FACTORS:
- [ ] Resource management deficiency
- [ ] Organizational process issue
- [ ] Organizational culture/climate
ROOT CAUSE(S):
[Human factors root causes identified]
CORRECTIVE ACTIONS:
| Action | Target Factor | Priority |
|--------|---------------|----------|
| [Action 1] | [Factor addressed] | High |
| [Action 2] | [Factor addressed] | Medium |---
Failure Mode and Effects Analysis
Overview
Proactive, systematic technique identifying potential failure modes, their causes, and effects before failures occur.
FMEA Types
| Type | Application | Scope |
|---|---|---|
| Design FMEA (DFMEA) | Product design | Component and system design failures |
| Process FMEA (PFMEA) | Manufacturing process | Process step failures |
| System FMEA | System-level analysis | System interaction failures |
Risk Priority Number (RPN)
RPN = Severity (S) × Occurrence (O) × Detection (D)
Severity Scale (1-10):
| Rating | Effect | Criteria |
|---|---|---|
| 10 | Hazardous | Failure affects safe operation, no warning |
| 8-9 | Very High | Primary function lost, high impact |
| 6-7 | High | Performance degraded, customer dissatisfied |
| 4-5 | Moderate | Some performance loss, moderate impact |
| 2-3 | Low | Minor effect, slight inconvenience |
| 1 | None | No discernible effect |
Occurrence Scale (1-10):
| Rating | Likelihood | Failure Rate |
|---|---|---|
| 10 | Very High | >1 in 10 |
| 7-9 | High | 1 in 20 - 1 in 100 |
| 4-6 | Moderate | 1 in 400 - 1 in 2,000 |
| 2-3 | Low | 1 in 15,000 - 1 in 150,000 |
| 1 | Remote | <1 in 1,500,000 |
Detection Scale (1-10):
| Rating | Detection | Criteria |
|---|---|---|
| 10 | Absolute Uncertainty | No inspection/control, defect will reach customer |
| 7-9 | Very Remote to Remote | Controls unlikely to detect |
| 4-6 | Moderate | Controls may detect |
| 2-3 | High | Controls likely to detect |
| 1 | Almost Certain | Controls will almost certainly detect |
FMEA Template
PROCESS/PRODUCT: [Name]
FMEA TEAM: [Members]
DATE: [Date]
| Item/Step | Failure Mode | Effect | S | Cause | O | Controls | D | RPN | Action |
|-----------|--------------|--------|---|-------|---|----------|---|-----|--------|
| [Item 1] | [How it fails] | [Impact] | 8 | [Why] | 4 | [Current] | 6 | 192 | [Action] |
| [Item 2] | [How it fails] | [Impact] | 6 | [Why] | 3 | [Current] | 4 | 72 | [Action] |
RPN THRESHOLD: Actions required for RPN > [threshold]
HIGH SEVERITY RULE: Actions required for S >= 9 regardless of RPN
ACTION PRIORITIZATION:
1. Address all items with S >= 9 first
2. Address items with highest RPN
3. Focus on reducing Occurrence (prevention)
4. Then improve Detection (inspection)---
Selecting the Right Method
Decision Flowchart
START: Investigation Required
│
├── Is this a proactive assessment (no failure yet)?
│ └── Yes → Use FMEA
│
├── Is the issue safety-critical?
│ └── Yes → Use FAULT TREE ANALYSIS
│
├── Is human error the primary concern?
│ └── Yes → Use HUMAN FACTORS ANALYSIS
│
├── Are there multiple contributing factors (3+)?
│ ├── Yes → Use FISHBONE DIAGRAM
│ └── No → Use 5 WHY ANALYSIS
│
└── Uncertain? → Start with 5 WHY, escalate to FISHBONE if neededHybrid Approach
For complex investigations, combine methods:
1. Initial screening: 5 Why for quick cause identification 2. Detailed analysis: Fishbone to explore all categories 3. Validation: Fault Tree for critical failure paths 4. Systemic factors: Human Factors for people-related causes 5. Prevention: FMEA for future risk mitigation
Documentation Requirements
| Method | Required Outputs | Retention |
|---|---|---|
| 5 Why | Completed template with evidence | CAPA record |
| Fishbone | Diagram + prioritized causes | CAPA record |
| Fault Tree | FTA diagram + cut set analysis | DHF/CAPA record |
| Human Factors | HFACS analysis + actions | CAPA record |
| FMEA | FMEA worksheet + action tracking | Design file |
#!/usr/bin/env python3
"""
CAPA Tracker - Corrective and Preventive Action Management Tool
Tracks CAPA status, calculates metrics, identifies overdue items,
and generates reports for management review.
Usage:
python capa_tracker.py --capas capas.json
python capa_tracker.py --interactive
python capa_tracker.py --capas capas.json --output json
"""
import argparse
import json
import sys
from dataclasses import dataclass, field, asdict
from datetime import datetime, timedelta
from typing import List, Dict, Optional
from enum import Enum
class CAPAStatus(Enum):
OPEN = "Open"
INVESTIGATION = "Investigation"
ACTION_PLANNING = "Action Planning"
IMPLEMENTATION = "Implementation"
VERIFICATION = "Verification"
CLOSED_EFFECTIVE = "Closed - Effective"
CLOSED_INEFFECTIVE = "Closed - Ineffective"
class CAPASeverity(Enum):
CRITICAL = "Critical"
MAJOR = "Major"
MINOR = "Minor"
class CAPASource(Enum):
COMPLAINT = "Customer Complaint"
AUDIT = "Internal Audit"
EXTERNAL_AUDIT = "External Audit"
NONCONFORMANCE = "Nonconformance"
MANAGEMENT_REVIEW = "Management Review"
TREND_ANALYSIS = "Trend Analysis"
REGULATORY = "Regulatory Feedback"
OTHER = "Other"
@dataclass
class CAPA:
capa_number: str
title: str
description: str
source: CAPASource
severity: CAPASeverity
status: CAPAStatus
open_date: str
target_date: str
owner: str
root_cause: str = ""
corrective_action: str = ""
verification_date: Optional[str] = None
close_date: Optional[str] = None
days_open: int = 0
is_overdue: bool = False
@dataclass
class CAPAMetrics:
total_capas: int
open_capas: int
closed_capas: int
overdue_capas: int
avg_cycle_time: float
effectiveness_rate: float
by_status: Dict[str, int]
by_severity: Dict[str, int]
by_source: Dict[str, int]
overdue_list: List[Dict]
recommendations: List[str]
class CAPATracker:
"""CAPA tracking and metrics calculator."""
# Target cycle times by severity (days)
TARGET_CYCLE_TIMES = {
CAPASeverity.CRITICAL: 30,
CAPASeverity.MAJOR: 60,
CAPASeverity.MINOR: 90,
}
def __init__(self, capas: List[CAPA]):
self.capas = capas
self.today = datetime.now()
self._calculate_derived_fields()
def _calculate_derived_fields(self):
"""Calculate days open and overdue status."""
for capa in self.capas:
open_date = datetime.strptime(capa.open_date, "%Y-%m-%d")
if capa.close_date:
close_date = datetime.strptime(capa.close_date, "%Y-%m-%d")
capa.days_open = (close_date - open_date).days
else:
capa.days_open = (self.today - open_date).days
target_date = datetime.strptime(capa.target_date, "%Y-%m-%d")
if not capa.close_date and self.today > target_date:
capa.is_overdue = True
def calculate_metrics(self) -> CAPAMetrics:
"""Calculate comprehensive CAPA metrics."""
total = len(self.capas)
# Status counts
closed_statuses = [CAPAStatus.CLOSED_EFFECTIVE, CAPAStatus.CLOSED_INEFFECTIVE]
open_capas = [c for c in self.capas if c.status not in closed_statuses]
closed_capas = [c for c in self.capas if c.status in closed_statuses]
overdue_capas = [c for c in self.capas if c.is_overdue]
# Average cycle time (closed CAPAs only)
if closed_capas:
avg_cycle = sum(c.days_open for c in closed_capas) / len(closed_capas)
else:
avg_cycle = 0.0
# Effectiveness rate
effective = [c for c in self.capas if c.status == CAPAStatus.CLOSED_EFFECTIVE]
ineffective = [c for c in self.capas if c.status == CAPAStatus.CLOSED_INEFFECTIVE]
if effective or ineffective:
effectiveness = len(effective) / (len(effective) + len(ineffective)) * 100
else:
effectiveness = 0.0
# Counts by category
by_status = {}
for status in CAPAStatus:
count = len([c for c in self.capas if c.status == status])
if count > 0:
by_status[status.value] = count
by_severity = {}
for severity in CAPASeverity:
count = len([c for c in self.capas if c.severity == severity])
if count > 0:
by_severity[severity.value] = count
by_source = {}
for source in CAPASource:
count = len([c for c in self.capas if c.source == source])
if count > 0:
by_source[source.value] = count
# Overdue list
overdue_list = []
for capa in sorted(overdue_capas, key=lambda c: c.days_open, reverse=True):
target = datetime.strptime(capa.target_date, "%Y-%m-%d")
days_overdue = (self.today - target).days
overdue_list.append({
"capa_number": capa.capa_number,
"title": capa.title,
"severity": capa.severity.value,
"status": capa.status.value,
"days_overdue": days_overdue,
"owner": capa.owner
})
# Generate recommendations
recommendations = self._generate_recommendations(
open_capas, overdue_capas, effectiveness, avg_cycle
)
return CAPAMetrics(
total_capas=total,
open_capas=len(open_capas),
closed_capas=len(closed_capas),
overdue_capas=len(overdue_capas),
avg_cycle_time=round(avg_cycle, 1),
effectiveness_rate=round(effectiveness, 1),
by_status=by_status,
by_severity=by_severity,
by_source=by_source,
overdue_list=overdue_list,
recommendations=recommendations
)
def _generate_recommendations(
self,
open_capas: List[CAPA],
overdue_capas: List[CAPA],
effectiveness: float,
avg_cycle: float
) -> List[str]:
"""Generate actionable recommendations."""
recommendations = []
# Overdue CAPAs
if overdue_capas:
critical_overdue = [c for c in overdue_capas if c.severity == CAPASeverity.CRITICAL]
if critical_overdue:
recommendations.append(
f"URGENT: {len(critical_overdue)} critical CAPA(s) overdue. "
"Escalate to management immediately."
)
else:
recommendations.append(
f"ACTION: {len(overdue_capas)} CAPA(s) overdue. "
"Review and update target dates or expedite closure."
)
# Effectiveness rate
if effectiveness < 80 and effectiveness > 0:
recommendations.append(
f"CONCERN: Effectiveness rate at {effectiveness:.0f}%. "
"Review root cause analysis quality and corrective action adequacy."
)
# Cycle time
if avg_cycle > 60:
recommendations.append(
f"IMPROVEMENT: Average cycle time is {avg_cycle:.0f} days. "
"Target is 60 days. Review investigation and approval bottlenecks."
)
# Investigation backlog
in_investigation = [c for c in open_capas if c.status == CAPAStatus.INVESTIGATION]
if len(in_investigation) > 5:
recommendations.append(
f"WORKLOAD: {len(in_investigation)} CAPAs in investigation phase. "
"Consider additional resources or prioritization."
)
# Stuck in verification
in_verification = [c for c in open_capas if c.status == CAPAStatus.VERIFICATION]
old_verification = [c for c in in_verification if c.days_open > 120]
if old_verification:
recommendations.append(
f"STALLED: {len(old_verification)} CAPA(s) in verification >120 days. "
"Complete effectiveness checks or extend with justification."
)
# Source patterns
complaint_capas = [c for c in self.capas if c.source == CAPASource.COMPLAINT]
if len(complaint_capas) > len(self.capas) * 0.4:
recommendations.append(
"TREND: >40% of CAPAs from customer complaints. "
"Review preventive action effectiveness and quality controls."
)
if not recommendations:
recommendations.append(
"CAPA program operating within targets. "
"Continue monitoring key metrics."
)
return recommendations
def get_aging_report(self) -> Dict:
"""Generate aging analysis of open CAPAs."""
open_statuses = [
CAPAStatus.OPEN, CAPAStatus.INVESTIGATION,
CAPAStatus.ACTION_PLANNING, CAPAStatus.IMPLEMENTATION,
CAPAStatus.VERIFICATION
]
open_capas = [c for c in self.capas if c.status in open_statuses]
aging_buckets = {
"0-30 days": [],
"31-60 days": [],
"61-90 days": [],
"91-120 days": [],
">120 days": []
}
for capa in open_capas:
days = capa.days_open
if days <= 30:
bucket = "0-30 days"
elif days <= 60:
bucket = "31-60 days"
elif days <= 90:
bucket = "61-90 days"
elif days <= 120:
bucket = "91-120 days"
else:
bucket = ">120 days"
aging_buckets[bucket].append({
"capa_number": capa.capa_number,
"title": capa.title,
"days_open": days,
"status": capa.status.value,
"severity": capa.severity.value
})
return aging_buckets
def format_text_output(metrics: CAPAMetrics, aging: Dict) -> str:
"""Format metrics as text report."""
lines = [
"=" * 70,
"CAPA STATUS REPORT",
"=" * 70,
f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
"",
"SUMMARY METRICS",
"-" * 40,
f"Total CAPAs: {metrics.total_capas}",
f"Open CAPAs: {metrics.open_capas}",
f"Closed CAPAs: {metrics.closed_capas}",
f"Overdue CAPAs: {metrics.overdue_capas}",
f"Avg Cycle Time: {metrics.avg_cycle_time} days",
f"Effectiveness Rate: {metrics.effectiveness_rate}%",
"",
"STATUS DISTRIBUTION",
"-" * 40,
]
for status, count in metrics.by_status.items():
bar = "█" * min(count, 20)
lines.append(f" {status:<25} {bar} {count}")
lines.extend([
"",
"SEVERITY DISTRIBUTION",
"-" * 40,
])
for severity, count in metrics.by_severity.items():
bar = "█" * min(count, 20)
lines.append(f" {severity:<25} {bar} {count}")
lines.extend([
"",
"SOURCE DISTRIBUTION",
"-" * 40,
])
for source, count in metrics.by_source.items():
bar = "█" * min(count, 20)
lines.append(f" {source:<25} {bar} {count}")
lines.extend([
"",
"AGING ANALYSIS",
"-" * 40,
])
for bucket, capas in aging.items():
lines.append(f" {bucket}: {len(capas)} CAPA(s)")
if metrics.overdue_list:
lines.extend([
"",
"OVERDUE CAPAs",
"-" * 40,
f"{'CAPA #':<12} {'Title':<25} {'Days':<6} {'Owner':<15}",
"-" * 60,
])
for item in metrics.overdue_list[:10]:
title = item["title"][:24] if len(item["title"]) > 24 else item["title"]
lines.append(
f"{item['capa_number']:<12} {title:<25} "
f"{item['days_overdue']:<6} {item['owner']:<15}"
)
if len(metrics.overdue_list) > 10:
lines.append(f"... and {len(metrics.overdue_list) - 10} more")
lines.extend([
"",
"RECOMMENDATIONS",
"-" * 40,
])
for i, rec in enumerate(metrics.recommendations, 1):
lines.append(f"{i}. {rec}")
lines.append("=" * 70)
return "\n".join(lines)
def interactive_mode():
"""Run interactive CAPA entry mode."""
print("=" * 60)
print("CAPA Tracker - Interactive Mode")
print("=" * 60)
capas = []
print("\nEnter CAPAs (blank CAPA number to finish):\n")
while True:
capa_num = input("CAPA Number (e.g., CAPA-2024-001): ").strip()
if not capa_num:
break
title = input("Title: ").strip()
description = input("Description: ").strip()
print("Source options: C=Complaint, A=Audit, N=Nonconformance, M=Management Review, T=Trend, O=Other")
source_input = input("Source [C/A/N/M/T/O]: ").strip().upper()
source_map = {
"C": CAPASource.COMPLAINT,
"A": CAPASource.AUDIT,
"N": CAPASource.NONCONFORMANCE,
"M": CAPASource.MANAGEMENT_REVIEW,
"T": CAPASource.TREND_ANALYSIS,
"O": CAPASource.OTHER
}
source = source_map.get(source_input, CAPASource.OTHER)
print("Severity: C=Critical, M=Major, I=Minor")
severity_input = input("Severity [C/M/I]: ").strip().upper()
severity_map = {
"C": CAPASeverity.CRITICAL,
"M": CAPASeverity.MAJOR,
"I": CAPASeverity.MINOR
}
severity = severity_map.get(severity_input, CAPASeverity.MINOR)
print("Status: O=Open, I=Investigation, P=Action Planning, M=Implementation, V=Verification, E=Closed Effective, N=Closed Ineffective")
status_input = input("Status [O/I/P/M/V/E/N]: ").strip().upper()
status_map = {
"O": CAPAStatus.OPEN,
"I": CAPAStatus.INVESTIGATION,
"P": CAPAStatus.ACTION_PLANNING,
"M": CAPAStatus.IMPLEMENTATION,
"V": CAPAStatus.VERIFICATION,
"E": CAPAStatus.CLOSED_EFFECTIVE,
"N": CAPAStatus.CLOSED_INEFFECTIVE
}
status = status_map.get(status_input, CAPAStatus.OPEN)
open_date = input("Open Date (YYYY-MM-DD): ").strip()
target_date = input("Target Date (YYYY-MM-DD): ").strip()
owner = input("Owner: ").strip()
close_date = None
if status in [CAPAStatus.CLOSED_EFFECTIVE, CAPAStatus.CLOSED_INEFFECTIVE]:
close_date = input("Close Date (YYYY-MM-DD): ").strip()
capas.append(CAPA(
capa_number=capa_num,
title=title,
description=description,
source=source,
severity=severity,
status=status,
open_date=open_date,
target_date=target_date,
owner=owner,
close_date=close_date if close_date else None
))
print(f"\nAdded: {capa_num}\n")
if not capas:
print("No CAPAs entered. Exiting.")
return
tracker = CAPATracker(capas)
metrics = tracker.calculate_metrics()
aging = tracker.get_aging_report()
print("\n" + format_text_output(metrics, aging))
def main():
parser = argparse.ArgumentParser(
description="CAPA Tracking and Metrics Tool"
)
parser.add_argument(
"--capas",
type=str,
help="JSON file with CAPA data"
)
parser.add_argument(
"--output",
choices=["text", "json"],
default="text",
help="Output format"
)
parser.add_argument(
"--interactive",
action="store_true",
help="Run in interactive mode"
)
parser.add_argument(
"--sample",
action="store_true",
help="Generate sample CAPA data file"
)
args = parser.parse_args()
if args.interactive:
interactive_mode()
return
if args.sample:
sample_data = {
"capas": [
{
"capa_number": "CAPA-2024-001",
"title": "Calibration overdue for pH meter",
"description": "pH meter EQ-042 found 2 months overdue",
"source": "AUDIT",
"severity": "MAJOR",
"status": "VERIFICATION",
"open_date": "2024-06-15",
"target_date": "2024-08-15",
"owner": "J. Smith",
"root_cause": "No trigger for schedule update at equipment purchase",
"corrective_action": "Updated SOP-EQ-001 to require schedule update"
},
{
"capa_number": "CAPA-2024-002",
"title": "Customer complaint - labeling error",
"description": "Wrong lot number on product label",
"source": "COMPLAINT",
"severity": "CRITICAL",
"status": "INVESTIGATION",
"open_date": "2024-09-01",
"target_date": "2024-10-01",
"owner": "M. Jones"
},
{
"capa_number": "CAPA-2024-003",
"title": "Training records incomplete",
"description": "Missing effectiveness verification for 3 operators",
"source": "AUDIT",
"severity": "MINOR",
"status": "CLOSED_EFFECTIVE",
"open_date": "2024-03-10",
"target_date": "2024-06-10",
"owner": "A. Brown",
"close_date": "2024-05-20"
}
]
}
print(json.dumps(sample_data, indent=2))
return
if args.capas:
with open(args.capas, "r") as f:
data = json.load(f)
capas = []
for c in data.get("capas", []):
try:
source = CAPASource[c.get("source", "OTHER").upper()]
except KeyError:
source = CAPASource.OTHER
try:
severity = CAPASeverity[c.get("severity", "MINOR").upper()]
except KeyError:
severity = CAPASeverity.MINOR
try:
status = CAPAStatus[c.get("status", "OPEN").upper()]
except KeyError:
status = CAPAStatus.OPEN
capas.append(CAPA(
capa_number=c["capa_number"],
title=c.get("title", ""),
description=c.get("description", ""),
source=source,
severity=severity,
status=status,
open_date=c["open_date"],
target_date=c["target_date"],
owner=c.get("owner", ""),
root_cause=c.get("root_cause", ""),
corrective_action=c.get("corrective_action", ""),
verification_date=c.get("verification_date"),
close_date=c.get("close_date")
))
else:
# Demo data if no file provided
capas = [
CAPA(
capa_number="CAPA-2024-001",
title="Calibration overdue",
description="pH meter overdue",
source=CAPASource.AUDIT,
severity=CAPASeverity.MAJOR,
status=CAPAStatus.VERIFICATION,
open_date="2024-06-15",
target_date="2024-08-15",
owner="J. Smith"
),
CAPA(
capa_number="CAPA-2024-002",
title="Labeling error complaint",
description="Wrong lot number",
source=CAPASource.COMPLAINT,
severity=CAPASeverity.CRITICAL,
status=CAPAStatus.INVESTIGATION,
open_date="2024-09-01",
target_date="2024-10-01",
owner="M. Jones"
),
CAPA(
capa_number="CAPA-2024-003",
title="Training records incomplete",
description="Missing effectiveness verification",
source=CAPASource.AUDIT,
severity=CAPASeverity.MINOR,
status=CAPAStatus.CLOSED_EFFECTIVE,
open_date="2024-03-10",
target_date="2024-06-10",
owner="A. Brown",
close_date="2024-05-20"
)
]
tracker = CAPATracker(capas)
metrics = tracker.calculate_metrics()
aging = tracker.get_aging_report()
if args.output == "json":
output = {
"metrics": asdict(metrics),
"aging": aging
}
print(json.dumps(output, indent=2))
else:
print(format_text_output(metrics, aging))
if __name__ == "__main__":
main()