diff --git a/.codex/skills-index.json b/.codex/skills-index.json index 70360d2..bf2d38d 100644 --- a/.codex/skills-index.json +++ b/.codex/skills-index.json @@ -231,7 +231,7 @@ "name": "quality-documentation-manager", "source": "../../ra-qm-team/quality-documentation-manager", "category": "ra-qm", - "description": "Senior Quality Documentation Manager for comprehensive documentation control and regulatory document review. Provides document management system design, change control, configuration management, and regulatory documentation oversight. Use for document control system implementation, regulatory document review, change management, and documentation compliance verification." + "description": "Document control system management for medical device QMS. Covers document numbering, version control, change management, and 21 CFR Part 11 compliance. Use for document control procedures, change control workflow, document numbering, version management, electronic signature compliance, or regulatory documentation review." }, { "name": "quality-manager-qmr", diff --git a/ra-qm-team/quality-documentation-manager/SKILL.md b/ra-qm-team/quality-documentation-manager/SKILL.md index d00189b..17f1b08 100644 --- a/ra-qm-team/quality-documentation-manager/SKILL.md +++ b/ra-qm-team/quality-documentation-manager/SKILL.md @@ -1,265 +1,437 @@ --- name: quality-documentation-manager -description: Senior Quality Documentation Manager for comprehensive documentation control and regulatory document review. Provides document management system design, change control, configuration management, and regulatory documentation oversight. Use for document control system implementation, regulatory document review, change management, and documentation compliance verification. +description: Document control system management for medical device QMS. Covers document numbering, version control, change management, and 21 CFR Part 11 compliance. Use for document control procedures, change control workflow, document numbering, version management, electronic signature compliance, or regulatory documentation review. +triggers: + - document control + - document numbering + - version control + - change control + - document approval + - electronic signature + - 21 CFR Part 11 + - audit trail + - document lifecycle + - controlled document + - document master list + - record retention --- -# Senior Quality Documentation Manager +# Quality Documentation Manager -Expert-level quality documentation management with comprehensive document control system design, regulatory documentation oversight, change management, and configuration control for medical device organizations. +Document control system design and management for ISO 13485-compliant quality management systems, including numbering conventions, approval workflows, change control, and electronic record compliance. -## Core Documentation Management Competencies +--- -### 1. Document Control System Design (ISO 13485 Clause 4.2.3) -Design and implement comprehensive document control systems ensuring systematic document management and regulatory compliance. +## Table of Contents + +- [Document Control Workflow](#document-control-workflow) +- [Document Numbering System](#document-numbering-system) +- [Approval and Review Process](#approval-and-review-process) +- [Change Control Process](#change-control-process) +- [21 CFR Part 11 Compliance](#21-cfr-part-11-compliance) +- [Reference Documentation](#reference-documentation) +- [Tools](#tools) + +--- + +## Document Control Workflow + +Implement document control from creation through obsolescence: + +1. Assign document number per numbering procedure +2. Create document using controlled template +3. Route for review to required reviewers +4. Address review comments and document responses +5. Obtain required approval signatures +6. Assign effective date and distribute +7. Update Document Master List +8. **Validation:** Document accessible at point of use; obsolete versions removed + +### Document Lifecycle Stages + +| Stage | Definition | Actions Required | +|-------|------------|------------------| +| Draft | Under creation or revision | Author editing, not for use | +| Review | Circulated for review | Reviewers provide feedback | +| Approved | All signatures obtained | Ready for training/distribution | +| Effective | Training complete, released | Available for use | +| Superseded | Replaced by newer revision | Remove from active use | +| Obsolete | No longer applicable | Archive per retention schedule | + +### Document Types and Prefixes + +| Prefix | Document Type | Typical Content | +|--------|---------------|-----------------| +| QM | Quality Manual | QMS overview, scope, policy | +| SOP | Standard Operating Procedure | Process-level procedures | +| WI | Work Instruction | Task-level step-by-step | +| TF | Template/Form | Controlled forms | +| SPEC | Specification | Product/process specs | +| PLN | Plan | Quality/project plans | + +### Required Reviewers by Document Type + +| Document Type | Required Reviewers | Required Approvers | +|---------------|-------------------|-------------------| +| SOP | Process Owner, QA | QA Manager, Process Owner | +| WI | Area Supervisor, QA | Area Manager | +| SPEC | Engineering, QA | Engineering Manager, QA | +| TF | Process Owner | QA | +| Design Documents | Design Team, QA | Design Control Authority | + +--- + +## Document Numbering System + +Assign consistent document numbers for identification and retrieval. + +### Numbering Format + +Standard format: `PREFIX-CATEGORY-SEQUENCE[-REVISION]` -**Document Control System Framework:** ``` -DOCUMENT CONTROL SYSTEM ARCHITECTURE -├── Document Classification and Structure -│ ├── Document type taxonomy and hierarchy -│ ├── Document numbering and identification -│ ├── Version control and revision management -│ └── Document status and lifecycle tracking -├── Document Creation and Approval -│ ├── Document templates and standardization -│ ├── Review and approval workflows -│ ├── Author and reviewer role assignment -│ └── Quality assurance and validation -├── Document Distribution and Access -│ ├── Controlled distribution management -│ ├── Access permission and security -│ ├── Electronic document system integration -│ └── External document coordination -├── Document Maintenance and Updates -│ ├── Periodic review scheduling -│ ├── Change control procedures -│ ├── Impact assessment and validation -│ └── Obsolete document management -└── Document Retention and Disposal - ├── Retention period determination - ├── Archive management system - ├── Legal hold and litigation support - └── Secure disposal procedures +Example: SOP-02-001-A + +SOP = Document type (Standard Operating Procedure) +02 = Category code (Document Control) +001 = Sequential number +A = Revision indicator ``` -### 2. Regulatory Documentation Oversight -Provide comprehensive oversight of regulatory documentation ensuring compliance with multiple jurisdictional requirements. +### Category Codes -**Regulatory Documentation Framework:** -1. **Multi-jurisdictional Documentation Management** - - **EU MDR Technical Documentation**: Annex II and III compliance verification - - **FDA Submission Documentation**: 510(k), PMA, and De Novo documentation oversight - - **ISO Standard Documentation**: ISO 13485, ISO 14971, and related standard compliance - - **International Market Documentation**: Health Canada, TGA, and other market requirements +| Code | Functional Area | Description | +|------|-----------------|-------------| +| 01 | Quality Management | QMS procedures, management review | +| 02 | Document Control | This area | +| 03 | Human Resources | Training, competency | +| 04 | Design & Development | Design control processes | +| 05 | Purchasing | Supplier management | +| 06 | Production | Manufacturing procedures | +| 07 | Quality Control | Inspection, testing | +| 08 | CAPA | Corrective/preventive actions | +| 09 | Risk Management | ISO 14971 processes | +| 10 | Regulatory Affairs | Submissions, compliance | -2. **Documentation Quality Assurance** - - **Content Review and Validation**: Technical accuracy and regulatory compliance - - **Format and Structure Verification**: Regulatory template and guideline adherence - - **Cross-reference and Traceability**: Document linkage and relationship management - - **Decision Point**: Approve documentation for regulatory submission or internal use +### Numbering Workflow -3. **Regulatory Submission Coordination** - - **Submission Package Assembly**: Document compilation and organization - - **Regulatory Authority Communication**: Documentation-related queries and responses - - **Post-submission Updates**: Amendment and variation documentation - - **Market Access Documentation**: Product registration and certification support +1. Author requests document number from Document Control +2. Document Control verifies category assignment +3. Document Control assigns next available sequence number +4. Number recorded in Document Master List +5. Author creates document using assigned number +6. **Validation:** Number format matches standard; no duplicates in Master List -### 3. Change Control and Configuration Management -Implement robust change control processes ensuring systematic document change management and configuration control. +### Revision Designation + +| Change Type | Revision Increment | Example | +|-------------|-------------------|---------| +| Major revision | Increment number | Rev 01 → Rev 02 | +| Minor revision | Increment sub-revision | Rev 01 → Rev 01.1 | +| Administrative | No change or letter suffix | Rev 01 → Rev 01a | + +See `references/document-control-procedures.md` for complete numbering guidance. + +--- + +## Approval and Review Process + +Obtain required reviews and approvals before document release. + +### Review Workflow + +1. Author completes document draft +2. Author submits for review via routing form or DMS +3. Reviewers assigned based on document type +4. Reviewers provide comments within review period (5-10 business days) +5. Author addresses comments and documents responses +6. Author resubmits revised document +7. Approvers sign and date +8. **Validation:** All required reviewers completed; all comments addressed with documented disposition + +### Comment Disposition + +| Disposition | Action Required | +|-------------|-----------------| +| Accept | Incorporate comment as written | +| Accept with modification | Incorporate with changes, document rationale | +| Reject | Do not incorporate, document justification | +| Defer | Address in future revision, document reason | + +### Approval Matrix -**Change Control Process Framework:** ``` -DOCUMENT CHANGE CONTROL WORKFLOW -├── Change Request Initiation -│ ├── Change identification and justification -│ ├── Impact assessment and analysis -│ ├── Stakeholder notification and consultation -│ └── Change request documentation -├── Change Review and Approval -│ ├── Technical review and validation -│ ├── Regulatory impact assessment -│ ├── Risk assessment and mitigation -│ ├── Resource requirement evaluation -│ └── Change approval authorization -├── Change Implementation -│ ├── Document update and revision -│ ├── Training and communication -│ ├── System update and deployment -│ └── Verification and validation -├── Change Verification and Closure -│ ├── Implementation verification -│ ├── Effectiveness assessment -│ ├── Stakeholder confirmation -│ └── Change record completion -└── Post-Change Monitoring - ├── Performance monitoring - ├── Issue identification and resolution - ├── Lessons learned capture - └── Process improvement integration +Document Level 1 (Policy/QM): CEO or delegate + QA Manager +Document Level 2 (SOP): Department Manager + QA Manager +Document Level 3 (WI/TF): Area Supervisor + QA Representative ``` -### 4. Document Management System (DMS) Implementation -Design and implement comprehensive electronic document management systems ensuring efficient document operations and compliance. +### Signature Requirements -**DMS Implementation Strategy:** -1. **System Requirements and Selection** - - Functional requirement definition and validation - - Regulatory compliance requirement integration - - System evaluation and vendor selection - - **Decision Point**: Select DMS technology and implementation approach +| Element | Requirement | +|---------|-------------| +| Name | Printed name of signer | +| Signature | Handwritten or electronic signature | +| Date | Date signature applied | +| Role | Function/role of signer | -2. **System Design and Configuration** - - **For Document Storage**: Follow references/dms-storage-design.md - - **For Workflow Management**: Follow references/workflow-automation.md - - **For Integration**: Follow references/system-integration-guide.md - - User interface design and experience optimization +--- -3. **System Validation and Deployment** - - System testing and validation protocols - - User training and competency verification - - Phased rollout and change management - - Performance monitoring and optimization +## Change Control Process -## Advanced Documentation Applications +Manage document changes systematically through review and approval. -### Technical Documentation Management -Manage complex technical documentation ensuring accuracy, consistency, and regulatory compliance. +### Change Control Workflow -**Technical Documentation Categories:** -- **Design and Development Documentation**: Design inputs, outputs, reviews, verification, validation -- **Risk Management Documentation**: ISO 14971 risk management file and reports -- **Clinical Documentation**: Clinical evaluation reports, clinical investigation protocols -- **Manufacturing Documentation**: Process specifications, work instructions, validation reports -- **Post-Market Documentation**: Surveillance reports, vigilance documentation, CAPA records +1. Identify need for document change +2. Complete Change Request Form with justification +3. Document Control assigns change number and logs request +4. Route to reviewers for impact assessment +5. Obtain approvals based on change classification +6. Author implements approved changes +7. Update revision number and change history +8. **Validation:** Changes match approved scope; change history complete -### Electronic Signature and 21 CFR Part 11 Compliance -Implement electronic signature systems ensuring FDA 21 CFR Part 11 compliance and regulatory acceptance. +### Change Classification -**Electronic Signature Framework:** -1. **21 CFR Part 11 Compliance Implementation** - - Electronic signature system validation and qualification - - User authentication and authorization management - - Audit trail and system security implementation - - **System Controls**: Access controls, operational controls, authority checks +| Class | Definition | Approval Level | Examples | +|-------|------------|----------------|----------| +| Administrative | No content impact | Document Control | Typos, formatting | +| Minor | Limited content change | Process Owner + QA | Clarifications | +| Major | Significant content change | Full review cycle | New requirements | +| Emergency | Urgent safety/compliance | Expedited + retrospective | Safety issues | -2. **Electronic Record Management** - - Electronic record integrity and authenticity - - Record retention and archive management - - System migration and legacy data management - - Regulatory inspection readiness and support +### Impact Assessment Checklist -### Multi-language Documentation Management -Manage multi-language documentation ensuring consistency, accuracy, and regulatory compliance across global markets. +| Impact Area | Assessment Questions | +|-------------|---------------------| +| Training | Does change require retraining? | +| Equipment | Does change affect equipment or systems? | +| Validation | Does change require revalidation? | +| Regulatory | Does change affect regulatory filings? | +| Other Documents | Which related documents need updating? | +| Records | What records are affected? | -**Multi-language Documentation Strategy:** -- **Translation Management**: Professional translation coordination and quality assurance -- **Linguistic Validation**: Medical and technical terminology accuracy verification -- **Cultural Adaptation**: Local market requirement integration and customization -- **Version Synchronization**: Multi-language document version control and alignment +### Change History Documentation -## Document Control Performance and Quality +Each document must include change history: -### Documentation Quality Metrics -Monitor comprehensive documentation quality metrics ensuring continuous improvement and regulatory compliance. +``` +| Revision | Date | Description | Author | Approver | +|----------|------|-------------|--------|----------| +| 01 | 2023-01-15 | Initial release | J. Smith | M. Jones | +| 02 | 2024-03-01 | Updated workflow | J. Smith | M. Jones | +``` -**Documentation Quality KPIs:** -- **Document Accuracy**: Error rates, correction frequency, review effectiveness -- **Compliance Rate**: Regulatory requirement adherence and audit findings -- **Process Efficiency**: Document cycle times, approval durations, update frequencies -- **User Satisfaction**: Stakeholder feedback, usability assessment, training effectiveness -- **System Performance**: DMS uptime, access speed, search effectiveness +--- -### Document Control Audit and Assessment -Conduct systematic document control audits ensuring compliance and continuous improvement. +## 21 CFR Part 11 Compliance -**Document Control Audit Framework:** -1. **Document Control System Assessment** - - Document control procedure compliance verification - - System functionality and performance evaluation - - User competency and training assessment - - **Regulatory Compliance Verification**: Multi-jurisdictional requirement adherence +Implement electronic record and signature controls for FDA compliance. -2. **Documentation Quality Review** - - Document accuracy and completeness assessment - - Regulatory compliance and guideline adherence - - Cross-reference and traceability verification - - Version control and change management effectiveness +### Part 11 Scope -### Continuous Improvement and Optimization -Implement continuous improvement processes ensuring document control system optimization and stakeholder satisfaction. +| Applies To | Does Not Apply To | +|------------|-------------------| +| Records required by FDA regulations | Paper records | +| Records submitted to FDA | Internal non-regulated documents | +| Electronic signatures on required records | General email communication | -**Improvement Framework:** -- **Process Optimization**: Workflow streamlining and automation opportunities -- **Technology Enhancement**: System upgrade and functionality improvement -- **User Experience Improvement**: Interface optimization and training effectiveness -- **Regulatory Alignment**: Evolving regulatory requirement integration and compliance +### Electronic Record Controls -## Cross-functional Documentation Coordination +1. Validate system for accuracy and reliability +2. Implement secure audit trail for all changes +3. Restrict system access to authorized individuals +4. Generate accurate copies in human-readable format +5. Protect records throughout retention period +6. **Validation:** Audit trail captures who, what, when for all changes -### Quality System Integration -Ensure seamless integration of documentation management with quality management system processes. +### Audit Trail Requirements -**QMS Integration Points:** -- **Management Review**: Documentation performance reporting and metrics -- **Internal Audit**: Document control compliance verification and improvement -- **CAPA Integration**: Documentation-related corrective and preventive actions -- **Training Management**: Document-based training and competency verification +| Requirement | Implementation | +|-------------|----------------| +| Secure | Cannot be modified by users | +| Computer-generated | System creates automatically | +| Time-stamped | Date and time of each action | +| Original values | Previous values retained | +| User identity | Who made each change | -### Regulatory Affairs Coordination -Coordinate closely with regulatory affairs team ensuring regulatory documentation accuracy and compliance. +### Electronic Signature Requirements -**Regulatory Coordination Framework:** -- **Submission Support**: Regulatory documentation preparation and quality assurance -- **Regulatory Intelligence**: Guidance document monitoring and implementation -- **Authority Communication**: Documentation-related query response and clarification -- **Compliance Monitoring**: Multi-jurisdictional documentation requirement tracking +| Requirement | Implementation | +|-------------|----------------| +| Unique to individual | Not shared between persons | +| At least 2 components | User ID + password minimum | +| Signature manifestation | Name, date/time, meaning displayed | +| Linked to record | Cannot be excised or copied | -### Cross-functional Training and Support -Provide comprehensive training and support ensuring organizational document management competency. +### Signature Manifestation -**Training and Support Program:** -- **Document Author Training**: Document creation, review, and approval procedures -- **System User Training**: DMS functionality and best practice utilization -- **Regulatory Documentation Training**: Specific regulatory requirement and guideline training -- **Ongoing Support**: Help desk, troubleshooting, and continuous learning support +Every electronic signature must display: -## Regulatory Documentation Standards +| Element | Example | +|---------|---------| +| Printed name | John Smith | +| Date and time | 2024-03-15 14:32:05 EST | +| Meaning | Approved for Release | -### International Documentation Standards -Ensure compliance with international documentation standards and regulatory expectations. +### System Controls Checklist -**Standards Compliance Framework:** -- **ISO 13485 Documentation**: Quality management system documentation requirements -- **IEC 62304 Documentation**: Medical device software lifecycle documentation -- **ISO 14971 Documentation**: Risk management documentation and reporting -- **ICH Guidelines**: Clinical documentation standards and harmonization +**Access Controls:** +- [ ] Unique user ID for each person +- [ ] Password complexity enforced +- [ ] Account lockout after failed attempts +- [ ] Session timeout after inactivity -### Documentation Best Practices -Implement industry best practices ensuring documentation excellence and regulatory acceptance. +**Audit Trail:** +- [ ] All record creation logged +- [ ] All modifications logged with old/new values +- [ ] User identity captured +- [ ] Date/time stamp on all entries -**Best Practice Implementation:** -- **Plain Language**: Clear, concise, and understandable documentation -- **Visual Communication**: Diagrams, flowcharts, and graphical representations -- **Modular Design**: Reusable documentation components and templates -- **Accessibility**: Universal design and multi-format accessibility +**Security:** +- [ ] Role-based access control +- [ ] Encryption for data at rest and in transit +- [ ] Regular backup and tested recovery -## Resources +See `references/21cfr11-compliance-guide.md` for detailed compliance requirements. -### scripts/ -- `document-control-dashboard.py`: Comprehensive document management performance monitoring -- `change-control-automation.py`: Document change workflow automation and tracking -- `regulatory-doc-validator.py`: Regulatory documentation compliance verification -- `dms-performance-monitor.py`: Document management system performance optimization +--- -### references/ -- `document-control-procedures.md`: Comprehensive document control implementation guide -- `regulatory-documentation-standards.md`: Multi-jurisdictional documentation requirements -- `dms-storage-design.md`: Document management system architecture and design -- `workflow-automation.md`: Document workflow optimization and automation -- `21cfr11-compliance-guide.md`: Electronic signature and record compliance framework +## Reference Documentation -### assets/ -- `document-templates/`: Standardized document templates and formats -- `change-control-forms/`: Change request and approval documentation templates -- `training-materials/`: Document management training and competency programs -- `audit-checklists/`: Document control compliance verification checklists +### Document Control Procedures + +`references/document-control-procedures.md` contains: + +- Document numbering system and format +- Document lifecycle stages and transitions +- Review and approval workflow details +- Change control process with classification criteria +- Distribution and access control methods +- Record retention periods and disposal procedures +- Document Master List requirements + +### 21 CFR Part 11 Compliance Guide + +`references/21cfr11-compliance-guide.md` contains: + +- Part 11 scope and applicability +- Electronic record requirements (§11.10) +- Electronic signature requirements (§11.50, 11.100, 11.200) +- System control specifications +- Validation approach and documentation +- Compliance checklist and gap assessment template +- Common FDA deficiencies and prevention + +--- + +## Tools + +### Document Validator + +```bash +# Validate document metadata +python scripts/document_validator.py --doc document.json + +# Interactive validation mode +python scripts/document_validator.py --interactive + +# JSON output for integration +python scripts/document_validator.py --doc document.json --output json + +# Generate sample document JSON +python scripts/document_validator.py --sample > sample_doc.json +``` + +Validates: +- Document numbering convention compliance +- Title and status requirements +- Date validation (effective, review due) +- Approval requirements by document type +- Change history completeness +- 21 CFR Part 11 controls (audit trail, signatures) + +### Sample Document Input + +```json +{ + "number": "SOP-02-001", + "title": "Document Control Procedure", + "doc_type": "SOP", + "revision": "03", + "status": "Effective", + "effective_date": "2024-01-15", + "review_date": "2025-01-15", + "author": "J. Smith", + "approver": "M. Jones", + "change_history": [ + {"revision": "01", "date": "2022-01-01", "description": "Initial release"}, + {"revision": "02", "date": "2023-01-15", "description": "Updated workflow"}, + {"revision": "03", "date": "2024-01-15", "description": "Added e-signature requirements"} + ], + "has_audit_trail": true, + "has_electronic_signature": true, + "signature_components": 2 +} +``` + +--- + +## Document Control Metrics + +Track document control system performance. + +### Key Performance Indicators + +| Metric | Target | Calculation | +|--------|--------|-------------| +| Document cycle time | <30 days | Average days from draft to effective | +| Review completion rate | >95% | Reviews completed on time / Total reviews | +| Change request backlog | <10 | Open change requests at month end | +| Overdue review rate | <5% | Documents past review date / Total effective | +| Audit finding rate | <2 per audit | Document control findings per internal audit | + +### Periodic Review Schedule + +| Document Type | Review Frequency | +|---------------|------------------| +| Policy | Every 3 years | +| SOP | Every 2 years | +| WI | Every 2 years | +| Specifications | As needed or with product changes | +| Forms/Templates | Every 3 years | + +--- + +## Regulatory Requirements + +### ISO 13485:2016 Clause 4.2 + +| Sub-clause | Requirement | +|------------|-------------| +| 4.2.1 | Quality management system documentation | +| 4.2.2 | Quality manual | +| 4.2.3 | Medical device file (technical documentation) | +| 4.2.4 | Control of documents | +| 4.2.5 | Control of records | + +### FDA 21 CFR 820 + +| Section | Requirement | +|---------|-------------| +| 820.40 | Document controls | +| 820.180 | General record requirements | +| 820.181 | Device master record | +| 820.184 | Device history record | +| 820.186 | Quality system record | + +### Common Audit Findings + +| Finding | Prevention | +|---------|------------| +| Obsolete documents in use | Implement distribution control | +| Missing approval signatures | Enforce workflow before release | +| Incomplete change history | Require history update with each revision | +| No periodic review schedule | Establish and enforce review calendar | +| Inadequate audit trail | Validate DMS for Part 11 compliance | diff --git a/ra-qm-team/quality-documentation-manager/assets/example_asset.txt b/ra-qm-team/quality-documentation-manager/assets/example_asset.txt deleted file mode 100644 index d0ac204..0000000 --- a/ra-qm-team/quality-documentation-manager/assets/example_asset.txt +++ /dev/null @@ -1,24 +0,0 @@ -# Example Asset File - -This placeholder represents where asset files would be stored. -Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed. - -Asset files are NOT intended to be loaded into context, but rather used within -the output Claude produces. - -Example asset files from other skills: -- Brand guidelines: logo.png, slides_template.pptx -- Frontend builder: hello-world/ directory with HTML/React boilerplate -- Typography: custom-font.ttf, font-family.woff2 -- Data: sample_data.csv, test_dataset.json - -## Common Asset Types - -- Templates: .pptx, .docx, boilerplate directories -- Images: .png, .jpg, .svg, .gif -- Fonts: .ttf, .otf, .woff, .woff2 -- Boilerplate code: Project directories, starter files -- Icons: .ico, .svg -- Data files: .csv, .json, .xml, .yaml - -Note: This is a text placeholder. Actual assets can be any file type. diff --git a/ra-qm-team/quality-documentation-manager/references/21cfr11-compliance-guide.md b/ra-qm-team/quality-documentation-manager/references/21cfr11-compliance-guide.md new file mode 100644 index 0000000..5028b41 --- /dev/null +++ b/ra-qm-team/quality-documentation-manager/references/21cfr11-compliance-guide.md @@ -0,0 +1,398 @@ +# 21 CFR Part 11 Compliance Guide + +Electronic records and electronic signatures compliance for FDA-regulated systems. + +--- + +## Table of Contents + +- [Part 11 Overview](#part-11-overview) +- [Electronic Record Requirements](#electronic-record-requirements) +- [Electronic Signature Requirements](#electronic-signature-requirements) +- [System Controls](#system-controls) +- [Validation Requirements](#validation-requirements) +- [Compliance Checklist](#compliance-checklist) + +--- + +## Part 11 Overview + +### Scope and Applicability + +21 CFR Part 11 applies to electronic records and signatures used to meet FDA predicate rule requirements. + +| Applies To | Does Not Apply To | +|------------|-------------------| +| Records required by FDA regulations | Paper records | +| Records submitted to FDA | Internal documents not required by regulation | +| Electronic signatures on required records | Digital communication (email) for general purposes | +| Systems creating/maintaining regulated records | Non-regulated systems | + +### Key Terms + +| Term | Definition | +|------|------------| +| Electronic Record | Any combination of text, graphics, data in digital form | +| Electronic Signature | Computer data compilation intended as legally binding signature | +| Digital Signature | Electronic signature based on cryptographic methods | +| Closed System | Environment with controlled access by responsible persons | +| Open System | Environment with uncontrolled access | +| Audit Trail | Secure, computer-generated, time-stamped record | + +### Predicate Rules + +Part 11 does not create new record requirements. It governs HOW records are maintained when electronic: + +| Predicate Rule | Record Type | +|----------------|-------------| +| 21 CFR 820 (QSR) | Device Master Records, Device History Records | +| 21 CFR 211 (cGMP) | Batch records, laboratory records | +| 21 CFR 58 (GLP) | Study records, raw data | +| 21 CFR 11.10(e) | Records required to be maintained | + +--- + +## Electronic Record Requirements + +### General Requirements (§11.10) + +Closed systems must implement controls including: + +1. **System Validation** - Accuracy, reliability, consistent intended performance +2. **Record Generation** - Accurate and complete copies in human-readable form +3. **Record Protection** - Throughout retention period +4. **Access Control** - Limit system access to authorized individuals +5. **Audit Trail** - Secure, computer-generated, time-stamped record +6. **Operational Checks** - Enforce permitted sequencing of steps +7. **Authority Checks** - Restrict functions to authorized individuals +8. **Device Checks** - Determine validity of input/output devices +9. **Training** - Personnel education and experience +10. **Documentation** - Written policies and accountability + +### Audit Trail Requirements + +| Requirement | Implementation | +|-------------|----------------| +| Secure | Cannot be modified or deleted by users | +| Computer-generated | System creates automatically, not manually entered | +| Time-stamped | Date and time of each action recorded | +| Independent | Stored separately from application data | +| Original values | Previous values retained when modified | +| Who, what, when | User identity, action taken, date/time | +| Reason for change | Where required by predicate rule | + +### Audit Trail Entries + +| Event Type | Data Captured | +|------------|---------------| +| Record Creation | User, date/time, initial values | +| Record Modification | User, date/time, old value, new value, reason | +| Record Deletion | User, date/time, reason (if permitted) | +| Login/Logout | User, date/time, success/failure | +| Signature Application | User, date/time, signature meaning | +| Failed Access | User attempted, date/time, reason | + +### Record Copy Requirements + +Must be able to generate accurate and complete copies: + +| Format | Requirement | +|--------|-------------| +| Electronic | Export in standard format (PDF, XML) | +| Paper | Human-readable printout | +| FDA Inspection | Provide copies upon request | +| Audit Trail | Include with record or separately | + +--- + +## Electronic Signature Requirements + +### General Requirements (§11.50, 11.100) + +| Requirement | Implementation | +|-------------|----------------| +| Unique to individual | Not shared between persons | +| Not reused | Identifier not assigned to another person | +| Identity verification | Verify identity before assignment | +| Certification | Certify to FDA that signatures are binding | + +### Signature Components (§11.200) + +| Type | Components Required | +|------|---------------------| +| Non-biometric | At least two distinct identification components | +| - First signing | Both components (user ID + password) | +| - Subsequent signings | At least one component within controlled session | +| Biometric | Biometric designed for individual identification | + +### Signature Manifestations (§11.50) + +Electronic signatures must include: + +| Element | Requirement | +|---------|-------------| +| Printed name | Full name of signer | +| Date and time | When signature was applied | +| Meaning | Purpose of signature (e.g., review, approval, responsibility) | + +### Signature/Record Linking (§11.70) + +| Requirement | Implementation | +|-------------|----------------| +| Linked to record | Signature cannot be excised, copied, or transferred | +| Cannot falsify | Technical controls prevent counterfeiting | +| Cannot repudiate | Signer cannot deny signing | + +### Signature Certification + +Organizations must submit certification to FDA (§11.100(c)): + +``` +SAMPLE CERTIFICATION LETTER + +[Date] + +Food and Drug Administration +[Appropriate Center Address] + +Subject: Electronic Signature Certification + +[Company Name] hereby certifies that all electronic signatures +used in our FDA-regulated systems are the legally binding +equivalent of traditional handwritten signatures. + +This certification is made in accordance with 21 CFR Part 11, +Section 11.100(c). + +Sincerely, +[Authorized Representative] +[Title] +``` + +--- + +## System Controls + +### Administrative Controls + +| Control | Implementation | +|---------|----------------| +| Written policies | SOPs for electronic records and signatures | +| Roles and responsibilities | Defined system access roles | +| Training program | Initial and periodic training | +| Periodic review | Regular assessment of controls | +| Accountability | Individual responsibility for actions | + +### Operational Controls + +| Control | Implementation | +|---------|----------------| +| Sequence enforcement | System enforces step order | +| Time limits | Session timeout after inactivity | +| Event logging | All significant events recorded | +| Error handling | System prevents invalid operations | +| Backup/recovery | Regular backup and tested recovery | + +### Technical Controls + +| Control | Implementation | +|---------|----------------| +| User authentication | Unique ID + password minimum | +| Password complexity | Minimum length, character requirements | +| Password expiration | Periodic change requirement | +| Account lockout | Lock after failed attempts | +| Access control | Role-based permissions | +| Encryption | Data in transit and at rest | + +### Password Requirements + +| Requirement | Specification | +|-------------|---------------| +| Minimum length | 8 characters minimum | +| Complexity | Upper, lower, number, special character | +| History | Cannot reuse last 12 passwords | +| Expiration | Maximum 90 days | +| Lockout | 5 failed attempts, 30-minute lockout | +| Initial password | Must change on first login | + +### Session Controls + +| Control | Specification | +|---------|---------------| +| Inactivity timeout | Maximum 15 minutes | +| Session duration | Maximum 8 hours | +| Concurrent sessions | Limit or prevent | +| Re-authentication | Required for sensitive operations | + +--- + +## Validation Requirements + +### Validation Approach + +| Phase | Activities | +|-------|------------| +| Planning | Validation plan, requirements, risk assessment | +| Specification | User requirements, functional specifications | +| Configuration | System setup, security configuration | +| Testing | IQ, OQ, PQ protocols and execution | +| Release | Validation summary report, release approval | +| Maintenance | Change control, periodic review | + +### Validation Documentation + +| Document | Purpose | +|----------|---------| +| Validation Plan | Scope, approach, responsibilities, schedule | +| User Requirements | What system must do (business requirements) | +| Functional Specification | How system will meet requirements | +| Design Specification | Technical implementation details | +| Test Protocols | IQ, OQ, PQ test procedures | +| Test Results | Executed protocols with evidence | +| Traceability Matrix | Requirements to test coverage | +| Validation Summary Report | Overall validation conclusion | + +### Testing Categories + +**Installation Qualification (IQ):** +- System installed per specifications +- Hardware and software inventory +- Configuration documentation + +**Operational Qualification (OQ):** +- Functions operate as specified +- Audit trail verification +- Security control testing +- Error handling verification + +**Performance Qualification (PQ):** +- System performs in production environment +- User acceptance testing +- Integration testing +- Load/stress testing (if applicable) + +### Part 11 Specific Testing + +| Test Area | Verification | +|-----------|--------------| +| Audit trail | All CRUD operations recorded correctly | +| Access control | Role permissions enforced | +| Electronic signatures | Signature components and linking | +| Record integrity | Data cannot be altered without detection | +| Backup/restore | Records restored accurately | +| Session controls | Timeout and lockout function | +| Password controls | Complexity and expiration enforced | + +--- + +## Compliance Checklist + +### System Assessment Checklist + +**Administrative Controls:** +- [ ] Written policies for electronic records and signatures +- [ ] Defined roles and responsibilities +- [ ] Training program documented and executed +- [ ] Periodic review schedule established +- [ ] Accountability measures in place + +**Access Controls:** +- [ ] Unique user identification for each person +- [ ] User IDs not shared or reassigned +- [ ] Password complexity requirements enforced +- [ ] Password expiration implemented +- [ ] Account lockout after failed attempts +- [ ] Role-based access control implemented +- [ ] Access periodically reviewed + +**Audit Trail:** +- [ ] All record creation captured +- [ ] All record modifications captured +- [ ] Previous values retained +- [ ] User identity recorded +- [ ] Date/time stamp on all entries +- [ ] Audit trail secure from modification +- [ ] Audit trail available for review + +**Electronic Signatures:** +- [ ] Signatures unique to individual +- [ ] At least two identification components +- [ ] Signature manifestation includes name, date/time, meaning +- [ ] Signatures linked to records +- [ ] Certification letter submitted to FDA + +**Record Management:** +- [ ] Accurate copies can be generated +- [ ] Human-readable format available +- [ ] Records protected throughout retention +- [ ] Backup and recovery tested + +**System Controls:** +- [ ] Session timeout implemented +- [ ] Operational sequence enforcement +- [ ] Input/output device validation +- [ ] Error handling documented + +**Validation:** +- [ ] System validated for intended use +- [ ] Validation documentation complete +- [ ] Change control procedures in place +- [ ] Periodic review conducted + +### Gap Assessment Template + +``` +PART 11 GAP ASSESSMENT + +System: [System Name] +Assessment Date: [Date] +Assessor: [Name] + +| Requirement | §11 Reference | Current State | Gap | Remediation | Priority | +|-------------|---------------|---------------|-----|-------------|----------| +| Audit trail | 11.10(e) | [Description] | [Y/N] | [Action] | [H/M/L] | +| Access control | 11.10(d) | [Description] | [Y/N] | [Action] | [H/M/L] | +| E-signatures | 11.50 | [Description] | [Y/N] | [Action] | [H/M/L] | + +Summary: +- Total requirements assessed: [Number] +- Requirements met: [Number] +- Gaps identified: [Number] +- Remediation timeline: [Date] +``` + +### Periodic Review Schedule + +| Review Type | Frequency | Scope | +|-------------|-----------|-------| +| Access review | Quarterly | User access appropriateness | +| Audit trail review | Monthly | Sample review of audit entries | +| Security review | Annually | Controls effectiveness | +| Validation review | Annually or on change | System still validated | +| Policy review | Annually | SOPs current and followed | + +--- + +## Common Deficiencies + +### FDA Warning Letter Themes + +| Deficiency | Root Cause | Prevention | +|------------|------------|------------| +| Shared user accounts | Convenience over compliance | Enforce unique accounts | +| Inadequate audit trail | System limitation | Validate audit trail | +| Missing signatures | Process gap | Enforce signature workflow | +| Incomplete validation | Time/resource constraints | Plan adequate resources | +| No change control | Process not followed | Enforce change control | +| Password sharing | Culture issue | Training and enforcement | + +### Remediation Priorities + +| Priority | Deficiency Type | Timeline | +|----------|-----------------|----------| +| Critical | Audit trail missing/modifiable | Immediate | +| Critical | Signatures can be falsified | Immediate | +| High | Shared accounts in production | 30 days | +| High | Validation gaps | 60 days | +| Medium | Training gaps | 90 days | +| Low | Documentation gaps | 120 days | diff --git a/ra-qm-team/quality-documentation-manager/references/api_reference.md b/ra-qm-team/quality-documentation-manager/references/api_reference.md deleted file mode 100644 index bf7ecf9..0000000 --- a/ra-qm-team/quality-documentation-manager/references/api_reference.md +++ /dev/null @@ -1,34 +0,0 @@ -# Reference Documentation for Quality Documentation Manager - -This is a placeholder for detailed reference documentation. -Replace with actual reference content or delete if not needed. - -Example real reference docs from other skills: -- product-management/references/communication.md - Comprehensive guide for status updates -- product-management/references/context_building.md - Deep-dive on gathering context -- bigquery/references/ - API references and query examples - -## When Reference Docs Are Useful - -Reference docs are ideal for: -- Comprehensive API documentation -- Detailed workflow guides -- Complex multi-step processes -- Information too lengthy for main SKILL.md -- Content that's only needed for specific use cases - -## Structure Suggestions - -### API Reference Example -- Overview -- Authentication -- Endpoints with examples -- Error codes -- Rate limits - -### Workflow Guide Example -- Prerequisites -- Step-by-step instructions -- Common patterns -- Troubleshooting -- Best practices diff --git a/ra-qm-team/quality-documentation-manager/references/document-control-procedures.md b/ra-qm-team/quality-documentation-manager/references/document-control-procedures.md new file mode 100644 index 0000000..5b21859 --- /dev/null +++ b/ra-qm-team/quality-documentation-manager/references/document-control-procedures.md @@ -0,0 +1,340 @@ +# Document Control Procedures + +Implementation guide for ISO 13485-compliant document control systems. + +--- + +## Table of Contents + +- [Document Numbering System](#document-numbering-system) +- [Document Lifecycle](#document-lifecycle) +- [Review and Approval Workflow](#review-and-approval-workflow) +- [Change Control Process](#change-control-process) +- [Distribution and Access Control](#distribution-and-access-control) +- [Record Retention](#record-retention) + +--- + +## Document Numbering System + +### Numbering Format + +Standard format: `[PREFIX]-[CATEGORY]-[SEQUENCE]-[REVISION]` + +| Component | Format | Example | Description | +|-----------|--------|---------|-------------| +| PREFIX | 2-3 letters | SOP, WI, TF | Document type identifier | +| CATEGORY | 2-3 digits | 01, 02, 10 | Functional area code | +| SEQUENCE | 3-4 digits | 001, 0001 | Sequential number within category | +| REVISION | Letter or number | A, 01 | Revision indicator | + +### Document Type Prefixes + +| Prefix | Document Type | Description | +|--------|---------------|-------------| +| QM | Quality Manual | Top-level QMS description | +| SOP | Standard Operating Procedure | Process procedures | +| WI | Work Instruction | Task-level instructions | +| TF | Template/Form | Controlled forms and templates | +| POL | Policy | Policy statements | +| SPEC | Specification | Product/process specifications | +| PLN | Plan | Project and quality plans | +| RPT | Report | Technical and quality reports | + +### Category Codes + +| Code | Functional Area | Examples | +|------|-----------------|----------| +| 01 | Quality Management | QMS procedures, audits | +| 02 | Document Control | This area | +| 03 | Human Resources | Training, competency | +| 04 | Design & Development | Design control | +| 05 | Purchasing | Supplier management | +| 06 | Production | Manufacturing | +| 07 | Quality Control | Inspection, testing | +| 08 | CAPA | Corrective/preventive actions | +| 09 | Risk Management | ISO 14971 processes | +| 10 | Regulatory Affairs | Submissions, compliance | + +### Numbering Workflow + +1. Author requests document number from Document Control +2. Document Control verifies category and assigns next sequence number +3. Document number recorded in Document Master List +4. Author creates document using assigned number +5. **Validation:** Number format matches standard; no duplicates exist + +--- + +## Document Lifecycle + +### Lifecycle Stages + +``` +DRAFT → REVIEW → APPROVED → EFFECTIVE → SUPERSEDED → OBSOLETE + │ │ │ │ │ │ + │ │ │ │ │ └── Archived/Destroyed + │ │ │ │ └── New revision effective + │ │ │ └── Training complete, distribution done + │ │ └── All approvals obtained + │ └── Under review/revision + └── Initial creation +``` + +### Stage Definitions + +| Stage | Definition | Actions Required | +|-------|------------|------------------| +| Draft | Document under creation or revision | Author editing, not for use | +| Review | Circulated for review and comment | Reviewers provide feedback | +| Approved | All required signatures obtained | Ready for training/distribution | +| Effective | Training complete, document released | Available for use | +| Superseded | Replaced by newer revision | Remove from active use | +| Obsolete | No longer applicable | Archive per retention schedule | + +### Document Status Indicators + +| Status | Indicator | Location | +|--------|-----------|----------| +| Draft | "DRAFT" watermark | Header or footer | +| Approved | Approval signatures with dates | Signature page | +| Effective | Effective date | Header | +| Obsolete | "OBSOLETE" stamp | Across all pages | + +--- + +## Review and Approval Workflow + +### Document Review Workflow + +1. Author completes document draft +2. Author submits for review via DMS or routing form +3. Reviewers assigned based on document type and content +4. Reviewers provide comments within review period (typically 5-10 business days) +5. Author addresses comments and documents responses +6. Author resubmits for approval +7. Approvers sign and date +8. **Validation:** All required reviewers completed; all comments addressed + +### Required Reviewers by Document Type + +| Document Type | Required Reviewers | Required Approvers | +|---------------|-------------------|-------------------| +| SOP | Process Owner, QA | QA Manager, Process Owner | +| WI | Area Supervisor, QA | Area Manager | +| SPEC | Engineering, QA | Engineering Manager, QA | +| TF | Process Owner | QA | +| POL | Department Heads | Management Representative | +| Design Documents | Design Team, QA | Design Control Authority | + +### Approval Matrix + +``` +APPROVAL AUTHORITY MATRIX + +Document Level 1 (Policy): CEO or delegate + QA Manager +Document Level 2 (SOP): Department Manager + QA Manager +Document Level 3 (WI/TF): Area Supervisor + QA Representative + +Regulatory Submissions: RA Manager + QA Manager + Technical Expert +Design Documents: Design Authority + QA Manager +``` + +### Review Comment Template + +``` +REVIEW COMMENT LOG + +Document: [Document Number and Title] +Reviewer: [Name, Role] +Review Date: [Date] + +| Section | Line/Para | Comment | Disposition | Response | +|---------|-----------|---------|-------------|----------| +| [Ref] | [Location] | [Issue/suggestion] | Accept/Reject/Modify | [Explanation] | +``` + +--- + +## Change Control Process + +### Change Request Workflow + +1. Identify need for document change +2. Complete Change Request Form (CRF) +3. Submit CRF to Document Control +4. Document Control assigns change number +5. Route to reviewers for impact assessment +6. Obtain approvals based on change classification +7. Author implements approved changes +8. **Validation:** Changes match approved scope; version number incremented + +### Change Classification + +| Class | Definition | Approval Level | Examples | +|-------|------------|----------------|----------| +| Administrative | No impact on content meaning | Document Control | Typos, formatting, references | +| Minor | Limited content change, no process impact | Process Owner + QA | Clarifications, minor additions | +| Major | Significant content change, process impact | Full review cycle | New requirements, process changes | +| Emergency | Urgent change required for safety/compliance | Expedited approval + retrospective review | Safety issues, regulatory mandates | + +### Change Impact Assessment + +| Impact Area | Assessment Questions | +|-------------|---------------------| +| Training | Does change require retraining? Who? | +| Equipment | Does change affect equipment or systems? | +| Validation | Does change require revalidation? | +| Regulatory | Does change affect regulatory filings? | +| Other Documents | Which related documents need updating? | +| Records | What records are affected? | + +### Version Control Rules + +| Change Type | Version Increment | Example | +|-------------|-------------------|---------| +| Major revision | Increment revision number | Rev 01 → Rev 02 | +| Minor revision | Increment sub-revision | Rev 01 → Rev 01.1 | +| Administrative | No version change (or sub-increment) | Rev 01 → Rev 01a | +| Draft iterations | Use draft version | Draft 1, Draft 2 | + +### Change History Template + +``` +DOCUMENT CHANGE HISTORY + +| Revision | Date | Description of Change | Author | Approver | +|----------|------|----------------------|--------|----------| +| 01 | YYYY-MM-DD | Initial release | [Name] | [Name] | +| 02 | YYYY-MM-DD | [Change description] | [Name] | [Name] | +``` + +--- + +## Distribution and Access Control + +### Distribution Methods + +| Method | Use Case | Control Mechanism | +|--------|----------|-------------------| +| Electronic (DMS) | Primary method | Access permissions | +| Controlled Print | Manufacturing floor | Signature log | +| Uncontrolled Copy | External distribution | Watermark "UNCONTROLLED" | +| Reference Copy | Training/archive | Watermark "REFERENCE ONLY" | + +### Access Permission Levels + +| Level | Permissions | Typical Roles | +|-------|-------------|---------------| +| Read | View documents only | General users | +| Print | View and print controlled copies | Area supervisors | +| Review | View, print, add comments | Reviewers | +| Author | Create, edit drafts | Document authors | +| Approve | Approve documents | Approvers | +| Admin | Full system access | Document Control | + +### Controlled Print Log + +``` +CONTROLLED PRINT LOG + +Document: [Document Number] +Revision: [Revision Number] + +| Copy # | Location | Issued To | Date Issued | Date Returned | Signature | +|--------|----------|-----------|-------------|---------------|-----------| +| 001 | Production Area 1 | [Name] | [Date] | [Date] | [Sig] | +| 002 | QC Lab | [Name] | [Date] | [Date] | [Sig] | +``` + +### Obsolete Document Control + +1. Mark document as "OBSOLETE" in DMS +2. Notify copy holders of obsolescence +3. Collect and destroy controlled prints +4. Update Document Master List +5. Archive master copy per retention schedule +6. **Validation:** No obsolete copies remain in active use areas + +--- + +## Record Retention + +### Retention Periods + +| Record Type | Retention Period | Basis | +|-------------|------------------|-------| +| Device Master Record (DMR) | Life of device + 2 years | 21 CFR 820.181 | +| Device History Record (DHR) | Life of device + 2 years | 21 CFR 820.184 | +| Design History File (DHF) | Life of device + 2 years | 21 CFR 820.30 | +| Quality Records | 2 years beyond device discontinuation | ISO 13485 | +| Training Records | Duration of employment + 3 years | Best practice | +| Audit Records | 7 years | Best practice | +| Complaint Records | Life of device + 2 years | 21 CFR 820.198 | +| CAPA Records | 7 years | Best practice | +| Calibration Records | 2 years beyond equipment disposal | Best practice | +| Supplier Records | Life of relationship + 3 years | Best practice | + +### Archive Requirements + +| Requirement | Specification | +|-------------|---------------| +| Storage Conditions | Temperature 15-25°C, RH 30-60% | +| Access Control | Restricted to authorized personnel | +| Indexing | Searchable by document number, date, type | +| Media | Original format or validated conversion | +| Backup | Offsite backup for electronic records | +| Integrity Checks | Periodic verification of record legibility | + +### Disposal Procedure + +1. Verify retention period has expired +2. Check for legal holds or ongoing litigation +3. Obtain disposal authorization +4. Execute secure destruction (shred paper, wipe electronic) +5. Document disposal in Disposal Log +6. **Validation:** No premature disposal; disposal documented + +### Disposal Log Template + +``` +RECORD DISPOSAL LOG + +| Document/Record ID | Description | Retention Expired | Disposal Date | Method | Witness | +|--------------------|-------------|-------------------|---------------|--------|---------| +| [ID] | [Description] | [Date] | [Date] | Shred/Wipe | [Name] | +``` + +--- + +## Document Master List + +### Master List Content + +| Field | Description | Required | +|-------|-------------|----------| +| Document Number | Unique identifier | Yes | +| Title | Document title | Yes | +| Current Revision | Active revision number | Yes | +| Effective Date | Date document became effective | Yes | +| Status | Draft/Effective/Obsolete | Yes | +| Process Owner | Responsible party | Yes | +| Review Date | Next scheduled review | Yes | +| Category | Functional area | Yes | +| Storage Location | Physical or electronic location | Yes | + +### Master List Maintenance + +- Update within 24 hours of document status change +- Review quarterly for accuracy +- Audit annually for completeness +- Archive historical versions + +### Sample Master List Entry + +``` +| Doc # | Title | Rev | Eff Date | Status | Owner | Review Date | +|-------|-------|-----|----------|--------|-------|-------------| +| SOP-02-001 | Document Control | 03 | 2024-01-15 | Effective | QA Mgr | 2025-01-15 | +| WI-06-012 | Assembly Line Setup | 02 | 2024-03-01 | Effective | Prod Mgr | 2025-03-01 | +``` diff --git a/ra-qm-team/quality-documentation-manager/scripts/document_validator.py b/ra-qm-team/quality-documentation-manager/scripts/document_validator.py new file mode 100644 index 0000000..cc02e69 --- /dev/null +++ b/ra-qm-team/quality-documentation-manager/scripts/document_validator.py @@ -0,0 +1,646 @@ +#!/usr/bin/env python3 +""" +Document Validator - Quality Documentation Compliance Checker + +Validates document metadata, numbering conventions, and control requirements +for ISO 13485 and 21 CFR Part 11 compliance. + +Usage: + python document_validator.py --doc document.json + python document_validator.py --interactive + python document_validator.py --doc document.json --output json +""" + +import argparse +import json +import re +import sys +from dataclasses import dataclass, field, asdict +from datetime import datetime, timedelta +from typing import List, Dict, Optional, Tuple +from enum import Enum + + +class DocumentType(Enum): + QM = "Quality Manual" + SOP = "Standard Operating Procedure" + WI = "Work Instruction" + TF = "Template/Form" + POL = "Policy" + SPEC = "Specification" + PLN = "Plan" + RPT = "Report" + + +class DocumentStatus(Enum): + DRAFT = "Draft" + REVIEW = "Under Review" + APPROVED = "Approved" + EFFECTIVE = "Effective" + SUPERSEDED = "Superseded" + OBSOLETE = "Obsolete" + + +class Severity(Enum): + CRITICAL = "Critical" + MAJOR = "Major" + MINOR = "Minor" + INFO = "Info" + + +@dataclass +class ValidationFinding: + rule: str + severity: Severity + message: str + recommendation: str + + +@dataclass +class Document: + number: str + title: str + doc_type: str + revision: str + status: str + effective_date: Optional[str] = None + review_date: Optional[str] = None + author: Optional[str] = None + approver: Optional[str] = None + approval_date: Optional[str] = None + change_history: List[Dict] = field(default_factory=list) + has_audit_trail: bool = False + has_electronic_signature: bool = False + signature_components: int = 0 + + +@dataclass +class ValidationResult: + document_number: str + validation_date: str + total_findings: int + critical_findings: int + major_findings: int + minor_findings: int + compliance_score: float + findings: List[Dict] + recommendations: List[str] + + +class DocumentValidator: + """Validator for quality documentation compliance.""" + + # Document number pattern: PREFIX-CATEGORY-SEQUENCE-REVISION + DOC_NUMBER_PATTERN = r'^([A-Z]{2,4})-(\d{2,3})-(\d{3,4})(?:-([A-Z]|\d{2}))?$' + + # Valid document type prefixes + VALID_PREFIXES = ['QM', 'SOP', 'WI', 'TF', 'POL', 'SPEC', 'PLN', 'RPT'] + + # Category codes + VALID_CATEGORIES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10'] + + def __init__(self, document: Document): + self.document = document + self.today = datetime.now() + self.findings: List[ValidationFinding] = [] + + def validate(self) -> ValidationResult: + """Run all validation checks.""" + self._validate_document_number() + self._validate_title() + self._validate_status_lifecycle() + self._validate_dates() + self._validate_approvals() + self._validate_change_history() + self._validate_electronic_controls() + + # Calculate compliance score + score = self._calculate_compliance_score() + + # Generate recommendations + recommendations = self._generate_recommendations() + + # Count findings by severity + critical = len([f for f in self.findings if f.severity == Severity.CRITICAL]) + major = len([f for f in self.findings if f.severity == Severity.MAJOR]) + minor = len([f for f in self.findings if f.severity == Severity.MINOR]) + + return ValidationResult( + document_number=self.document.number, + validation_date=self.today.strftime("%Y-%m-%d"), + total_findings=len(self.findings), + critical_findings=critical, + major_findings=major, + minor_findings=minor, + compliance_score=round(score, 1), + findings=[asdict(f) for f in self.findings], + recommendations=recommendations + ) + + def _validate_document_number(self): + """Validate document numbering convention.""" + number = self.document.number + + if not number: + self.findings.append(ValidationFinding( + rule="DOC-NUM-001", + severity=Severity.CRITICAL, + message="Document number is missing", + recommendation="Assign document number per numbering procedure" + )) + return + + match = re.match(self.DOC_NUMBER_PATTERN, number) + if not match: + self.findings.append(ValidationFinding( + rule="DOC-NUM-002", + severity=Severity.MAJOR, + message=f"Document number '{number}' does not match standard format", + recommendation="Use format: PREFIX-CATEGORY-SEQUENCE[-REVISION] (e.g., SOP-02-001-A)" + )) + return + + prefix, category, sequence, revision = match.groups() + + if prefix not in self.VALID_PREFIXES: + self.findings.append(ValidationFinding( + rule="DOC-NUM-003", + severity=Severity.MAJOR, + message=f"Invalid document type prefix: {prefix}", + recommendation=f"Use one of: {', '.join(self.VALID_PREFIXES)}" + )) + + if category not in self.VALID_CATEGORIES: + self.findings.append(ValidationFinding( + rule="DOC-NUM-004", + severity=Severity.MINOR, + message=f"Non-standard category code: {category}", + recommendation=f"Standard categories are: {', '.join(self.VALID_CATEGORIES)}" + )) + + def _validate_title(self): + """Validate document title.""" + title = self.document.title + + if not title: + self.findings.append(ValidationFinding( + rule="DOC-TTL-001", + severity=Severity.MAJOR, + message="Document title is missing", + recommendation="Provide descriptive document title" + )) + return + + if len(title) < 10: + self.findings.append(ValidationFinding( + rule="DOC-TTL-002", + severity=Severity.MINOR, + message="Document title is very short", + recommendation="Use descriptive title that clearly identifies content" + )) + + if len(title) > 100: + self.findings.append(ValidationFinding( + rule="DOC-TTL-003", + severity=Severity.MINOR, + message="Document title exceeds recommended length", + recommendation="Keep title under 100 characters" + )) + + def _validate_status_lifecycle(self): + """Validate document status and lifecycle.""" + status = self.document.status + + if not status: + self.findings.append(ValidationFinding( + rule="DOC-STS-001", + severity=Severity.MAJOR, + message="Document status is missing", + recommendation="Assign appropriate document status" + )) + return + + valid_statuses = [s.value for s in DocumentStatus] + if status not in valid_statuses: + self.findings.append(ValidationFinding( + rule="DOC-STS-002", + severity=Severity.MAJOR, + message=f"Invalid document status: {status}", + recommendation=f"Use one of: {', '.join(valid_statuses)}" + )) + + # Check status-specific requirements + if status == DocumentStatus.EFFECTIVE.value: + if not self.document.effective_date: + self.findings.append(ValidationFinding( + rule="DOC-STS-003", + severity=Severity.MAJOR, + message="Effective document missing effective date", + recommendation="Add effective date for effective documents" + )) + + if status == DocumentStatus.APPROVED.value: + if not self.document.approval_date: + self.findings.append(ValidationFinding( + rule="DOC-STS-004", + severity=Severity.MAJOR, + message="Approved document missing approval date", + recommendation="Add approval date for approved documents" + )) + + def _validate_dates(self): + """Validate document dates.""" + # Check effective date + if self.document.effective_date: + try: + eff_date = datetime.strptime(self.document.effective_date, "%Y-%m-%d") + if eff_date > self.today: + self.findings.append(ValidationFinding( + rule="DOC-DTE-001", + severity=Severity.INFO, + message="Effective date is in the future", + recommendation="Verify planned effective date is correct" + )) + except ValueError: + self.findings.append(ValidationFinding( + rule="DOC-DTE-002", + severity=Severity.MINOR, + message="Invalid effective date format", + recommendation="Use YYYY-MM-DD format for dates" + )) + + # Check review date + if self.document.review_date: + try: + review_date = datetime.strptime(self.document.review_date, "%Y-%m-%d") + if review_date < self.today: + self.findings.append(ValidationFinding( + rule="DOC-DTE-003", + severity=Severity.MAJOR, + message="Document is overdue for review", + recommendation="Initiate periodic review process" + )) + elif review_date < self.today + timedelta(days=30): + self.findings.append(ValidationFinding( + rule="DOC-DTE-004", + severity=Severity.MINOR, + message="Document review due within 30 days", + recommendation="Plan for upcoming review" + )) + except ValueError: + self.findings.append(ValidationFinding( + rule="DOC-DTE-005", + severity=Severity.MINOR, + message="Invalid review date format", + recommendation="Use YYYY-MM-DD format for dates" + )) + else: + if self.document.status == DocumentStatus.EFFECTIVE.value: + self.findings.append(ValidationFinding( + rule="DOC-DTE-006", + severity=Severity.MINOR, + message="Effective document missing review date", + recommendation="Add next review date (typically 1-3 years from effective)" + )) + + def _validate_approvals(self): + """Validate document approval information.""" + if self.document.status in [DocumentStatus.APPROVED.value, DocumentStatus.EFFECTIVE.value]: + if not self.document.author: + self.findings.append(ValidationFinding( + rule="DOC-APR-001", + severity=Severity.MAJOR, + message="Document author not identified", + recommendation="Document author on signature page" + )) + + if not self.document.approver: + self.findings.append(ValidationFinding( + rule="DOC-APR-002", + severity=Severity.CRITICAL, + message="Document approver not identified", + recommendation="Obtain required approval signatures" + )) + + def _validate_change_history(self): + """Validate change history completeness.""" + history = self.document.change_history + + if not history: + self.findings.append(ValidationFinding( + rule="DOC-CHG-001", + severity=Severity.MAJOR, + message="Document change history is missing", + recommendation="Include change history table with revision descriptions" + )) + return + + for i, entry in enumerate(history): + if not entry.get('revision'): + self.findings.append(ValidationFinding( + rule="DOC-CHG-002", + severity=Severity.MINOR, + message=f"Change history entry {i+1} missing revision number", + recommendation="Include revision number for each history entry" + )) + + if not entry.get('description'): + self.findings.append(ValidationFinding( + rule="DOC-CHG-003", + severity=Severity.MINOR, + message=f"Change history entry {i+1} missing description", + recommendation="Include description of changes for each revision" + )) + + if not entry.get('date'): + self.findings.append(ValidationFinding( + rule="DOC-CHG-004", + severity=Severity.MINOR, + message=f"Change history entry {i+1} missing date", + recommendation="Include date for each history entry" + )) + + def _validate_electronic_controls(self): + """Validate 21 CFR Part 11 requirements for electronic documents.""" + # Audit trail check + if not self.document.has_audit_trail: + self.findings.append(ValidationFinding( + rule="P11-AUD-001", + severity=Severity.MAJOR, + message="Electronic document lacks audit trail", + recommendation="Enable audit trail for 21 CFR Part 11 compliance" + )) + + # Electronic signature check + if self.document.has_electronic_signature: + if self.document.signature_components < 2: + self.findings.append(ValidationFinding( + rule="P11-SIG-001", + severity=Severity.CRITICAL, + message="Electronic signature uses fewer than 2 identification components", + recommendation="Use at least 2 components (e.g., user ID + password)" + )) + else: + if self.document.status in [DocumentStatus.APPROVED.value, DocumentStatus.EFFECTIVE.value]: + self.findings.append(ValidationFinding( + rule="P11-SIG-002", + severity=Severity.INFO, + message="Document uses handwritten signatures", + recommendation="Consider electronic signatures for efficiency" + )) + + def _calculate_compliance_score(self) -> float: + """Calculate compliance score based on findings.""" + if not self.findings: + return 100.0 + + # Weight by severity + deductions = { + Severity.CRITICAL: 25, + Severity.MAJOR: 10, + Severity.MINOR: 3, + Severity.INFO: 0 + } + + total_deduction = sum(deductions[f.severity] for f in self.findings) + score = max(0, 100 - total_deduction) + + return score + + def _generate_recommendations(self) -> List[str]: + """Generate prioritized recommendations.""" + recommendations = [] + + # Critical findings + critical = [f for f in self.findings if f.severity == Severity.CRITICAL] + if critical: + recommendations.append( + f"URGENT: {len(critical)} critical finding(s) require immediate attention" + ) + + # Major findings + major = [f for f in self.findings if f.severity == Severity.MAJOR] + if major: + recommendations.append( + f"ACTION: {len(major)} major finding(s) should be addressed within 30 days" + ) + + # Review overdue + review_overdue = [f for f in self.findings if f.rule == "DOC-DTE-003"] + if review_overdue: + recommendations.append( + "REVIEW: Document is overdue for periodic review. Initiate review process." + ) + + # Part 11 gaps + p11_findings = [f for f in self.findings if f.rule.startswith("P11")] + if p11_findings: + recommendations.append( + f"COMPLIANCE: {len(p11_findings)} 21 CFR Part 11 gap(s) identified" + ) + + if not recommendations: + recommendations.append("Document passes validation checks") + + return recommendations + + +def format_text_output(result: ValidationResult) -> str: + """Format validation result as text report.""" + lines = [ + "=" * 70, + "DOCUMENT VALIDATION REPORT", + "=" * 70, + f"Document: {result.document_number}", + f"Validation Date: {result.validation_date}", + f"Compliance Score: {result.compliance_score}%", + "", + "FINDINGS SUMMARY", + "-" * 40, + f" Critical: {result.critical_findings}", + f" Major: {result.major_findings}", + f" Minor: {result.minor_findings}", + f" Total: {result.total_findings}", + ] + + if result.findings: + lines.extend([ + "", + "DETAILED FINDINGS", + "-" * 40, + ]) + + for finding in result.findings: + severity = finding['severity'] + lines.append(f"\n[{severity}] {finding['rule']}") + lines.append(f" Issue: {finding['message']}") + lines.append(f" Action: {finding['recommendation']}") + + lines.extend([ + "", + "RECOMMENDATIONS", + "-" * 40, + ]) + + for i, rec in enumerate(result.recommendations, 1): + lines.append(f"{i}. {rec}") + + lines.append("=" * 70) + return "\n".join(lines) + + +def interactive_mode(): + """Run interactive document validation.""" + print("=" * 60) + print("Document Validator - Interactive Mode") + print("=" * 60) + + print("\nEnter document information:\n") + + number = input("Document Number (e.g., SOP-02-001): ").strip() + title = input("Document Title: ").strip() + + print("\nDocument Types: QM, SOP, WI, TF, POL, SPEC, PLN, RPT") + doc_type = input("Document Type: ").strip().upper() + + revision = input("Revision (e.g., 01 or A): ").strip() + + print("\nStatuses: Draft, Under Review, Approved, Effective, Superseded, Obsolete") + status = input("Status: ").strip() + + effective_date = input("Effective Date (YYYY-MM-DD, or Enter to skip): ").strip() or None + review_date = input("Next Review Date (YYYY-MM-DD, or Enter to skip): ").strip() or None + + author = input("Author Name (or Enter to skip): ").strip() or None + approver = input("Approver Name (or Enter to skip): ").strip() or None + + has_audit = input("Has Audit Trail? (y/n): ").strip().lower() == 'y' + has_esig = input("Uses Electronic Signatures? (y/n): ").strip().lower() == 'y' + + sig_components = 0 + if has_esig: + sig_input = input("Number of signature components (e.g., 2): ").strip() + sig_components = int(sig_input) if sig_input.isdigit() else 0 + + doc = Document( + number=number, + title=title, + doc_type=doc_type, + revision=revision, + status=status, + effective_date=effective_date, + review_date=review_date, + author=author, + approver=approver, + has_audit_trail=has_audit, + has_electronic_signature=has_esig, + signature_components=sig_components + ) + + validator = DocumentValidator(doc) + result = validator.validate() + print("\n" + format_text_output(result)) + + +def main(): + parser = argparse.ArgumentParser( + description="Quality Documentation Validator" + ) + parser.add_argument( + "--doc", + type=str, + help="JSON file with document metadata" + ) + 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 document JSON" + ) + + args = parser.parse_args() + + if args.interactive: + interactive_mode() + return + + if args.sample: + sample = { + "number": "SOP-02-001", + "title": "Document Control Procedure", + "doc_type": "SOP", + "revision": "03", + "status": "Effective", + "effective_date": "2024-01-15", + "review_date": "2025-01-15", + "author": "J. Smith", + "approver": "M. Jones", + "approval_date": "2024-01-10", + "change_history": [ + {"revision": "01", "date": "2022-01-01", "description": "Initial release"}, + {"revision": "02", "date": "2023-01-15", "description": "Updated approval workflow"}, + {"revision": "03", "date": "2024-01-15", "description": "Added electronic signature requirements"} + ], + "has_audit_trail": True, + "has_electronic_signature": True, + "signature_components": 2 + } + print(json.dumps(sample, indent=2)) + return + + if args.doc: + with open(args.doc, "r") as f: + data = json.load(f) + + doc = Document( + number=data.get("number", ""), + title=data.get("title", ""), + doc_type=data.get("doc_type", ""), + revision=data.get("revision", ""), + status=data.get("status", ""), + effective_date=data.get("effective_date"), + review_date=data.get("review_date"), + author=data.get("author"), + approver=data.get("approver"), + approval_date=data.get("approval_date"), + change_history=data.get("change_history", []), + has_audit_trail=data.get("has_audit_trail", False), + has_electronic_signature=data.get("has_electronic_signature", False), + signature_components=data.get("signature_components", 0) + ) + else: + # Demo document + doc = Document( + number="SOP-02-001", + title="Document Control", + doc_type="SOP", + revision="01", + status="Effective", + effective_date="2024-01-15", + author="J. Smith", + has_audit_trail=True, + has_electronic_signature=True, + signature_components=2 + ) + + validator = DocumentValidator(doc) + result = validator.validate() + + if args.output == "json": + print(json.dumps(asdict(result), indent=2)) + else: + print(format_text_output(result)) + + +if __name__ == "__main__": + main() diff --git a/ra-qm-team/quality-documentation-manager/scripts/example.py b/ra-qm-team/quality-documentation-manager/scripts/example.py deleted file mode 100755 index e8e403b..0000000 --- a/ra-qm-team/quality-documentation-manager/scripts/example.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 -""" -Example helper script for quality-documentation-manager - -This is a placeholder script that can be executed directly. -Replace with actual implementation or delete if not needed. - -Example real scripts from other skills: -- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields -- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images -""" - -def main(): - print("This is an example script for quality-documentation-manager") - # TODO: Add actual script logic here - # This could be data processing, file conversion, API calls, etc. - -if __name__ == "__main__": - main()