diff --git a/ra-qm-team/qms-audit-expert/SKILL.md b/ra-qm-team/qms-audit-expert/SKILL.md index 3be2aeb..35baad4 100644 --- a/ra-qm-team/qms-audit-expert/SKILL.md +++ b/ra-qm-team/qms-audit-expert/SKILL.md @@ -1,238 +1,323 @@ --- name: qms-audit-expert -description: Senior QMS Audit Expert for internal and external quality management system auditing. Provides ISO 13485 audit expertise, audit program management, nonconformity identification, and corrective action verification. Use for internal audit planning, external audit preparation, audit execution, and audit follow-up activities. +description: ISO 13485 internal audit expertise for medical device QMS. Covers audit planning, execution, nonconformity classification, and CAPA verification. Use for internal audit planning, audit execution, finding classification, external audit preparation, or audit program management. +triggers: + - ISO 13485 audit + - internal audit + - QMS audit + - audit planning + - nonconformity classification + - CAPA verification + - audit checklist + - audit finding + - external audit prep + - audit schedule --- -# Senior QMS Audit Expert +# QMS Audit Expert -Expert-level quality management system auditing with comprehensive knowledge of ISO 13485, audit methodologies, nonconformity management, and audit program optimization for medical device organizations. +ISO 13485 internal audit methodology for medical device quality management systems. -## Core QMS Auditing Competencies +--- -### 1. ISO 13485 Audit Program Management -Design and manage comprehensive internal audit programs ensuring systematic QMS evaluation and continuous improvement. +## Table of Contents + +- [Audit Planning Workflow](#audit-planning-workflow) +- [Audit Execution](#audit-execution) +- [Nonconformity Management](#nonconformity-management) +- [External Audit Preparation](#external-audit-preparation) +- [Reference Documentation](#reference-documentation) +- [Tools](#tools) + +--- + +## Audit Planning Workflow + +Plan risk-based internal audit program: + +1. List all QMS processes requiring audit +2. Assign risk level to each process (High/Medium/Low) +3. Review previous audit findings and trends +4. Determine audit frequency by risk level +5. Assign qualified auditors (verify independence) +6. Create annual audit schedule +7. Communicate schedule to process owners +8. **Validation:** All ISO 13485 clauses covered within cycle + +### Risk-Based Audit Frequency + +| Risk Level | Frequency | Criteria | +|------------|-----------|----------| +| High | Quarterly | Design control, CAPA, production validation | +| Medium | Semi-annual | Purchasing, training, document control | +| Low | Annual | Infrastructure, management review (if stable) | + +### Audit Scope by Clause + +| Clause | Process | Focus Areas | +|--------|---------|-------------| +| 4.2 | Document Control | Document approval, distribution, obsolete control | +| 5.6 | Management Review | Inputs complete, decisions documented, actions tracked | +| 6.2 | Training | Competency defined, records complete, effectiveness verified | +| 7.3 | Design Control | Inputs, reviews, V&V, transfer, changes | +| 7.4 | Purchasing | Supplier evaluation, incoming inspection | +| 7.5 | Production | Work instructions, process validation, DHR | +| 7.6 | Calibration | Equipment list, calibration status, out-of-tolerance | +| 8.2.2 | Internal Audit | Schedule compliance, auditor independence | +| 8.3 | NC Product | Identification, segregation, disposition | +| 8.5 | CAPA | Root cause, implementation, effectiveness | + +### Auditor Independence + +Verify auditor independence before assignment: + +- [ ] Auditor not responsible for area being audited +- [ ] No direct reporting relationship to auditee +- [ ] Not involved in recent activities under audit +- [ ] Documented qualification for audit scope + +--- + +## Audit Execution + +Conduct systematic internal audit: + +1. Prepare audit plan (scope, criteria, schedule) +2. Review relevant documentation before audit +3. Conduct opening meeting with auditee +4. Collect evidence (records, interviews, observation) +5. Classify findings (Major/Minor/Observation) +6. Conduct closing meeting with preliminary findings +7. Prepare audit report within 5 business days +8. **Validation:** All scope items covered, findings supported by evidence + +### Evidence Collection + +| Method | Use For | Documentation | +|--------|---------|---------------| +| Document review | Procedures, records | Document number, version, date | +| Interview | Process understanding | Interviewee name, role, summary | +| Observation | Actual practice | What, where, when observed | +| Record trace | Process flow | Record IDs, dates, linkage | + +### Audit Questions by Clause + +**Document Control (4.2):** +- Show me the document master list +- How do you control obsolete documents? +- Show me evidence of document change approval + +**Design Control (7.3):** +- Show me the Design History File for [product] +- Who participates in design reviews? +- Show me design input to output traceability + +**CAPA (8.5):** +- Show me the CAPA log with open items +- How do you determine root cause? +- Show me effectiveness verification records + +See `references/iso13485-audit-guide.md` for complete question sets. + +### Finding Documentation + +Document each finding with: -**Audit Program Framework:** ``` -QMS AUDIT PROGRAM MANAGEMENT -├── Annual Audit Planning -│ ├── Risk-based audit scheduling -│ ├── Process audit scope definition -│ ├── Auditor competency management -│ └── Resource allocation planning -├── Audit Execution Management -│ ├── Audit preparation and logistics -│ ├── Audit team coordination -│ ├── Audit conduct and documentation -│ └── Audit report generation -├── Audit Follow-up and Closure -│ ├── Nonconformity management -│ ├── Corrective action verification -│ ├── Effectiveness assessment -│ └── Audit cycle completion -└── Audit Program Improvement - ├── Audit performance analysis - ├── Auditor feedback and development - ├── Methodology enhancement - └── Best practice implementation +Requirement: [Specific ISO 13485 clause or procedure] +Evidence: [What was observed, reviewed, or heard] +Gap: [How evidence fails to meet requirement] ``` -### 2. Risk-Based Audit Planning (ISO 13485 Clause 8.2.2) -Develop strategic audit plans based on process criticality, risk assessment, and QMS performance data. - -**Risk-Based Audit Planning Process:** -1. **QMS Risk Assessment for Auditing** - - Process risk evaluation and criticality analysis - - Previous audit results and trend analysis - - Regulatory requirement changes and impact - - **Decision Point**: Determine audit frequency and scope based on risk level - -2. **Audit Schedule Development** - - **High-Risk Processes**: Quarterly or semi-annual auditing - - **Medium-Risk Processes**: Annual auditing with focused reviews - - **Low-Risk Processes**: Extended cycle auditing with surveillance - - **Special Audits**: Event-driven or complaint-triggered audits - -3. **Audit Scope and Criteria Definition** - - ISO 13485 clause-specific auditing - - Process-based audit scope definition - - Regulatory requirement integration - - Customer-specific requirement inclusion - -### 3. Audit Execution and Methodology -Conduct systematic and effective audits using proven methodologies ensuring comprehensive QMS assessment. - -**Audit Execution Process:** -1. **Audit Preparation** - - **Pre-audit Document Review**: Follow scripts/audit-prep-checklist.py - - **Audit Plan Development**: Scope, objectives, criteria, methods - - **Auditor Assignment**: Competency matching and independence verification - - **Auditee Communication**: Schedule, expectations, and logistics - -2. **Audit Conduct** - - **Opening Meeting**: Audit introduction and expectation setting - - **Evidence Collection**: Interviews, document review, observation - - **Finding Development**: Nonconformity identification and classification - - **Closing Meeting**: Audit summary and preliminary findings presentation - -3. **Audit Documentation and Reporting** - - **Audit Report Preparation**: Findings, evidence, and recommendations - - **Nonconformity Documentation**: Detailed description and requirements - - **Audit Summary**: Executive summary and improvement opportunities - - **Report Distribution**: Stakeholder communication and follow-up planning - -### 4. Auditor Competency Management -Develop and maintain auditor competency ensuring effective audit execution and professional development. - -**Auditor Competency Framework:** +**Example:** ``` -AUDITOR COMPETENCY REQUIREMENTS -├── Technical Competency -│ ├── ISO 13485 standard knowledge -│ ├── Medical device industry understanding -│ ├── QMS process comprehension -│ └── Regulatory requirement familiarity -├── Audit Methodology Skills -│ ├── Audit planning and preparation -│ ├── Interview and communication techniques -│ ├── Evidence collection and analysis -│ └── Report writing and presentation -├── Personal Attributes -│ ├── Independence and objectivity -│ ├── Professional ethics and integrity -│ ├── Analytical and critical thinking -│ └── Continuous learning mindset -└── Industry-Specific Knowledge - ├── Medical device regulations - ├── Risk management principles - ├── Design control requirements - └── Post-market surveillance obligations +Requirement: ISO 13485:2016 Clause 7.6 requires calibration +at specified intervals. + +Evidence: Calibration records for pH meter (EQ-042) show +last calibration 2024-01-15. Calibration interval is +12 months. Today is 2025-03-20. + +Gap: Equipment is 2 months overdue for calibration, +representing a gap in calibration program execution. ``` -## Advanced Audit Applications +--- -### Process-Based Auditing -Implement process-based audit methodologies ensuring comprehensive process evaluation and improvement identification. +## Nonconformity Management -**Process-Based Audit Approach:** -1. **Process Understanding and Mapping** - - Process flow analysis and documentation - - Input-output relationship evaluation - - Process performance metrics review - - Process interaction assessment +Classify and manage audit findings: -2. **Process Audit Execution** - - **Management Processes**: Management review, resource management, communication - - **Core Processes**: Design controls, purchasing, production, delivery - - **Support Processes**: Document control, training, infrastructure, work environment - - **Monitoring Processes**: Customer satisfaction, internal audit, product monitoring +1. Evaluate finding against classification criteria +2. Assign severity (Major/Minor/Observation) +3. Document finding with objective evidence +4. Communicate to process owner +5. Initiate CAPA for Major/Minor findings +6. Track to closure +7. Verify effectiveness at follow-up +8. **Validation:** Finding closed only after effective CAPA -### External Audit Preparation and Coordination -Prepare organization for external audits including regulatory inspections and certification body assessments. +### Classification Criteria -**External Audit Preparation:** -1. **Pre-audit Readiness Assessment** - - Internal audit completion and closure verification - - Documentation review and compliance verification - - Personnel training and role assignment - - **Mock Audit Execution**: Full-scale external audit simulation +| Category | Definition | CAPA Required | Timeline | +|----------|------------|---------------|----------| +| Major | Systematic failure or absence of element | Yes | 30 days | +| Minor | Isolated lapse or partial implementation | Recommended | 60 days | +| Observation | Improvement opportunity | Optional | As appropriate | -2. **External Audit Coordination** - - **For Regulatory Inspections**: Follow references/regulatory-inspection-guide.md - - **For Certification Body Audits**: Follow references/certification-audit-guide.md - - **For Customer Audits**: Follow references/customer-audit-guide.md - - Audit logistics and resource coordination +### Classification Decision -3. **External Audit Support** - - Auditor escort and facility coordination - - Documentation provision and explanation - - Technical expert availability and consultation - - Real-time issue resolution and escalation +``` +Is required element absent or failed? +├── Yes → Systematic (multiple instances)? → MAJOR +│ └── No → Could affect product safety? → MAJOR +│ └── No → MINOR +└── No → Deviation from procedure? + ├── Yes → Recurring? → MAJOR + │ └── No → MINOR + └── No → Improvement opportunity? → OBSERVATION +``` -### Specialized Audit Areas -Conduct specialized audits addressing specific QMS areas and regulatory requirements. +### CAPA Integration -**Specialized Audit Types:** -- **Design Control Audits**: ISO 13485 Clause 7.3 comprehensive assessment -- **Risk Management Audits**: ISO 14971 integration and effectiveness -- **Software Audits**: IEC 62304 compliance and software lifecycle -- **Post-Market Surveillance Audits**: Vigilance and feedback system effectiveness -- **Supplier Audits**: Supply chain quality and risk management +| Finding Severity | CAPA Depth | Verification | +|------------------|------------|--------------| +| Major | Full root cause analysis (5-Why, Fishbone) | Next audit or within 6 months | +| Minor | Immediate cause identification | Next scheduled audit | +| Observation | Not required | Noted at next audit | -## Nonconformity and CAPA Integration +See `references/nonconformity-classification.md` for detailed guidance. -### Nonconformity Identification and Classification -Systematically identify and classify nonconformities ensuring appropriate corrective action initiation. +--- -**Nonconformity Classification System:** -- **Major Nonconformity**: Systematic failure or absence of QMS requirements -- **Minor Nonconformity**: Isolated incident or partial implementation failure -- **Observation**: Improvement opportunity or potential future nonconformity -- **Best Practice**: Exemplary implementation or innovation identification +## External Audit Preparation -### CAPA Integration and Verification -Coordinate with CAPA processes ensuring effective corrective action implementation and verification. +Prepare for certification body or regulatory audit: -**CAPA Integration Process:** -1. **CAPA Initiation**: Audit finding translation to CAPA requirements -2. **Root Cause Analysis Support**: Audit evidence provision and validation -3. **Corrective Action Verification**: Implementation effectiveness assessment -4. **Follow-up Audit Planning**: CAPA effectiveness verification auditing +1. Complete all scheduled internal audits +2. Verify all findings closed with effective CAPA +3. Review documentation for currency and accuracy +4. Conduct management review with audit as input +5. Prepare facility and personnel +6. Conduct mock audit (full scope) +7. Brief personnel on audit protocol +8. **Validation:** Mock audit findings addressed before external audit -## Audit Performance and Continuous Improvement +### Pre-Audit Readiness Checklist -### Audit Program Performance Metrics -Monitor audit program effectiveness ensuring continuous improvement and value demonstration. +**Documentation:** +- [ ] Quality Manual current +- [ ] Procedures reflect actual practice +- [ ] Records complete and retrievable +- [ ] Previous audit findings closed -**Audit Performance KPIs:** -- **Audit Schedule Compliance**: Planned vs. actual audit completion rates -- **Finding Quality**: Finding accuracy, significance, and actionability -- **Auditor Performance**: Competency assessments and feedback scores -- **CAPA Effectiveness**: Corrective action success rates and recurrence prevention -- **Process Improvement**: Audit-driven improvement identification and implementation +**Personnel:** +- [ ] Key personnel available during audit +- [ ] Subject matter experts identified +- [ ] Personnel briefed on audit protocol +- [ ] Escorts assigned -### Audit Program Optimization -Continuously improve audit program effectiveness through methodology enhancement and best practice adoption. +**Facility:** +- [ ] Work areas organized +- [ ] Documents at point of use current +- [ ] Equipment calibration status visible +- [ ] Nonconforming product segregated -**Audit Program Improvement Framework:** -1. **Audit Effectiveness Analysis** - - Audit finding trends and pattern analysis - - Process improvement opportunity identification - - Stakeholder feedback collection and analysis - - **Decision Point**: Determine audit program modification needs +### Mock Audit Protocol -2. **Methodology Enhancement** - - Audit technique optimization and standardization - - Technology integration and automation opportunities - - Auditor training and development programs - - Best practice sharing and knowledge management +1. Use external auditor or qualified internal auditor +2. Cover full scope of upcoming external audit +3. Simulate actual audit conditions (timing, formality) +4. Document findings as for real audit +5. Address all Major and Minor findings before external audit +6. Brief management on readiness status -### Industry Benchmarking and Best Practices -Maintain awareness of industry audit best practices and regulatory expectations. +--- -**Benchmarking Activities:** -- **Regulatory Guidance Monitoring**: FDA, EU, and other authority audit expectations -- **Industry Standards Evolution**: ISO 13485 updates and audit methodology changes -- **Professional Development**: Auditor certification and continuing education -- **Peer Learning**: Industry audit community participation and knowledge sharing +## Reference Documentation -## Resources +### ISO 13485 Audit Guide -### scripts/ -- `audit-schedule-optimizer.py`: Risk-based audit planning and schedule optimization -- `audit-prep-checklist.py`: Comprehensive audit preparation automation -- `nonconformity-tracker.py`: Audit finding and CAPA integration management -- `audit-performance-analyzer.py`: Audit program effectiveness monitoring +`references/iso13485-audit-guide.md` contains: -### references/ -- `iso13485-audit-guide.md`: Complete ISO 13485 audit methodology and checklists -- `process-audit-procedures.md`: Process-based audit execution frameworks -- `regulatory-inspection-guide.md`: Regulatory audit preparation and response -- `certification-audit-guide.md`: Certification body audit coordination -- `auditor-competency-framework.md`: Auditor development and assessment criteria +- Clause-by-clause audit methodology +- Sample audit questions for each clause +- Evidence collection requirements +- Common nonconformities by clause +- Finding severity classification -### assets/ -- `audit-templates/`: Audit plan, checklist, and report templates -- `audit-checklists/`: ISO 13485 clause-specific audit checklists -- `training-materials/`: Auditor training and competency development programs -- `nonconformity-forms/`: Standardized nonconformity documentation templates +### Nonconformity Classification + +`references/nonconformity-classification.md` contains: + +- Severity classification criteria and decision tree +- Impact vs. occurrence matrix +- CAPA integration requirements +- Finding documentation templates +- Closure requirements by severity + +--- + +## Tools + +### Audit Schedule Optimizer + +```bash +# Generate optimized audit schedule +python scripts/audit_schedule_optimizer.py --processes processes.json + +# Interactive mode +python scripts/audit_schedule_optimizer.py --interactive + +# JSON output for integration +python scripts/audit_schedule_optimizer.py --processes processes.json --output json +``` + +Generates risk-based audit schedule considering: +- Process risk level +- Previous findings +- Days since last audit +- Criticality scores + +**Output includes:** +- Prioritized audit schedule +- Quarterly distribution +- Overdue audit alerts +- Resource recommendations + +### Sample Process Input + +```json +{ + "processes": [ + { + "name": "Design Control", + "iso_clause": "7.3", + "risk_level": "HIGH", + "last_audit_date": "2024-06-15", + "previous_findings": 2 + }, + { + "name": "Document Control", + "iso_clause": "4.2", + "risk_level": "MEDIUM", + "last_audit_date": "2024-09-01", + "previous_findings": 0 + } + ] +} +``` + +--- + +## Audit Program Metrics + +Track audit program effectiveness: + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Schedule compliance | >90% | Audits completed on time | +| Finding closure rate | >95% | Findings closed by due date | +| Repeat findings | <10% | Same finding in consecutive audits | +| CAPA effectiveness | >90% | Verified effective at follow-up | +| Auditor utilization | 4 days/month | Audit days per qualified auditor | diff --git a/ra-qm-team/qms-audit-expert/assets/example_asset.txt b/ra-qm-team/qms-audit-expert/assets/example_asset.txt deleted file mode 100644 index d0ac204..0000000 --- a/ra-qm-team/qms-audit-expert/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/qms-audit-expert/references/api_reference.md b/ra-qm-team/qms-audit-expert/references/api_reference.md deleted file mode 100644 index ab76926..0000000 --- a/ra-qm-team/qms-audit-expert/references/api_reference.md +++ /dev/null @@ -1,34 +0,0 @@ -# Reference Documentation for Qms Audit Expert - -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/qms-audit-expert/references/iso13485-audit-guide.md b/ra-qm-team/qms-audit-expert/references/iso13485-audit-guide.md new file mode 100644 index 0000000..f34b821 --- /dev/null +++ b/ra-qm-team/qms-audit-expert/references/iso13485-audit-guide.md @@ -0,0 +1,388 @@ +# ISO 13485 Audit Guide + +Clause-by-clause audit methodology with sample questions and common findings. + +--- + +## Table of Contents + +- [Audit Approach](#audit-approach) +- [Clause 4: Quality Management System](#clause-4-quality-management-system) +- [Clause 5: Management Responsibility](#clause-5-management-responsibility) +- [Clause 6: Resource Management](#clause-6-resource-management) +- [Clause 7: Product Realization](#clause-7-product-realization) +- [Clause 8: Measurement and Improvement](#clause-8-measurement-and-improvement) +- [Common Nonconformities](#common-nonconformities) + +--- + +## Audit Approach + +### Risk-Based Audit Planning + +Prioritize audit focus based on: + +| Risk Level | Audit Frequency | Scope Depth | +|------------|-----------------|-------------| +| High | Quarterly | Full clause review | +| Medium | Semi-annual | Targeted review | +| Low | Annual | Sampling-based | + +### Evidence Collection Methods + +| Method | Best For | Examples | +|--------|----------|----------| +| Document review | Procedures, records | SOPs, DHF, batch records | +| Interview | Process understanding | Operators, supervisors | +| Observation | Actual practice | Production, calibration | +| Tracing | Process flow | Order to delivery | + +--- + +## Clause 4: Quality Management System + +### 4.1 General Requirements + +**Audit Questions:** +- Show me documentation of your QMS scope and exclusions +- How do you identify processes needed for the QMS? +- Show me evidence of outsourced process control + +**Evidence to Review:** +- [ ] Quality Manual or QMS description +- [ ] Process interaction diagram +- [ ] Outsourced process agreements + +**Common Findings:** +- Scope exclusions not justified +- Outsourced processes not controlled +- Process interactions not defined + +### 4.2 Documentation Requirements + +**4.2.1-4.2.2 Quality Manual and Documents** + +**Audit Questions:** +- Where is your documented quality policy? +- Show me the procedure for document control +- How do you ensure documents are current at point of use? + +**Evidence to Review:** +- [ ] Quality Manual +- [ ] Document master list +- [ ] Sample of controlled documents + +**4.2.4 Control of Records** + +**Audit Questions:** +- What is your record retention policy? +- Show me the procedure for record storage and protection +- How do you ensure record legibility and retrievability? + +**Evidence to Review:** +- [ ] Record control procedure +- [ ] Retention schedule +- [ ] Sample record retrieval test + +**Common Findings:** +- Obsolete documents in use +- Records not legible or retrievable +- Retention periods not defined for all record types + +--- + +## Clause 5: Management Responsibility + +### 5.1-5.2 Management Commitment and Customer Focus + +**Audit Questions:** +- How does top management demonstrate commitment to QMS? +- Show me evidence of customer requirement determination +- How are regulatory requirements communicated? + +**Evidence to Review:** +- [ ] Quality policy communication +- [ ] Management review minutes +- [ ] Customer feedback records + +### 5.4 Planning + +**Audit Questions:** +- Where are your quality objectives documented? +- Show me the plan for achieving quality objectives +- How do you maintain QMS integrity during changes? + +**Evidence to Review:** +- [ ] Quality objectives (measurable, time-bound) +- [ ] Quality planning documentation +- [ ] Change management records + +### 5.5 Responsibility and Authority + +**Audit Questions:** +- Where are responsibilities and authorities defined? +- Who is the management representative? +- How is QMS performance communicated to top management? + +**Evidence to Review:** +- [ ] Organization chart +- [ ] Job descriptions with QMS responsibilities +- [ ] Management representative appointment + +### 5.6 Management Review + +**Audit Questions:** +- Show me management review records from last 12 months +- What inputs are included in management review? +- What decisions and actions resulted? + +**Required Review Inputs:** +- [ ] Audit results +- [ ] Customer feedback (including complaints) +- [ ] Process performance and product conformity +- [ ] CAPA status +- [ ] Changes affecting QMS +- [ ] Recommendations for improvement +- [ ] New/revised regulatory requirements + +**Common Findings:** +- Management review not conducted at planned intervals +- Required inputs missing +- Action items not tracked to completion + +--- + +## Clause 6: Resource Management + +### 6.1-6.2 Human Resources + +**Audit Questions:** +- How do you determine competency requirements? +- Show me training records for personnel affecting quality +- How do you evaluate training effectiveness? + +**Evidence to Review:** +- [ ] Competency requirements by role +- [ ] Training records +- [ ] Effectiveness evaluations + +### 6.3-6.4 Infrastructure and Work Environment + +**Audit Questions:** +- How do you determine infrastructure requirements? +- Show me maintenance records for critical equipment +- How is work environment controlled for product conformity? + +**Evidence to Review:** +- [ ] Equipment list with maintenance schedules +- [ ] Environmental monitoring records +- [ ] Contamination control procedures (if applicable) + +**Common Findings:** +- Training effectiveness not evaluated +- Preventive maintenance not performed on schedule +- Environmental conditions not monitored + +--- + +## Clause 7: Product Realization + +### 7.1 Planning of Product Realization + +**Audit Questions:** +- Show me the quality plan for a recent product +- How do you determine verification and validation activities? +- What records are required to demonstrate conformity? + +**Evidence to Review:** +- [ ] Quality plan or project plan +- [ ] Risk management integration +- [ ] Required records defined + +### 7.2 Customer-Related Processes + +**Audit Questions:** +- How do you determine customer requirements? +- Show me the contract review process +- How do you handle customer communications? + +**Evidence to Review:** +- [ ] Contract/order review records +- [ ] Customer requirement documentation +- [ ] Communication records + +### 7.3 Design and Development + +**Audit Questions (per phase):** + +| Phase | Key Questions | +|-------|---------------| +| Planning | Show me design plan with stages, reviews, responsibilities | +| Inputs | How are regulatory requirements identified? | +| Outputs | Show me design outputs addressing inputs | +| Review | Who participated in design reviews? | +| Verification | Show me verification activities and results | +| Validation | Show me validation under actual use conditions | +| Transfer | How was design transferred to production? | +| Changes | Show me design change control records | + +**Evidence to Review:** +- [ ] Design History File (DHF) +- [ ] Design review records with participants +- [ ] Verification/validation protocols and reports +- [ ] Design change requests + +### 7.4 Purchasing + +**Audit Questions:** +- How do you evaluate and select suppliers? +- Show me approved supplier list with evaluation criteria +- How do you verify purchased product? + +**Evidence to Review:** +- [ ] Supplier evaluation procedure +- [ ] Approved supplier list +- [ ] Incoming inspection records +- [ ] Supplier audit records + +### 7.5 Production and Service Provision + +**Audit Questions:** +- Show me work instructions for production +- How are special processes validated? +- Show me traceability records for a product lot + +**Evidence to Review:** +- [ ] Production work instructions +- [ ] Process validation records +- [ ] Device history records (DHR) +- [ ] Traceability records + +### 7.6 Control of Monitoring and Measuring Equipment + +**Audit Questions:** +- Show me calibration records for measuring equipment +- How do you handle out-of-tolerance conditions? +- How is software used for monitoring validated? + +**Evidence to Review:** +- [ ] Equipment calibration records +- [ ] Calibration procedure +- [ ] Out-of-tolerance investigation records + +**Common Findings:** +- Design inputs not completely addressed in outputs +- Supplier evaluations not performed or documented +- Process validation not maintained after changes +- Calibration overdue + +--- + +## Clause 8: Measurement and Improvement + +### 8.2.1 Feedback + +**Audit Questions:** +- How do you collect customer feedback? +- Show me complaint handling records +- How is feedback data used for improvement? + +**Evidence to Review:** +- [ ] Complaint procedure +- [ ] Complaint log with trending +- [ ] Feedback to design/production + +### 8.2.2 Internal Audit + +**Audit Questions:** +- Show me the internal audit schedule +- How do you ensure auditor independence? +- Show me audit records and follow-up actions + +**Evidence to Review:** +- [ ] Audit program/schedule +- [ ] Auditor qualification records +- [ ] Audit reports and findings +- [ ] CAPA records from audits + +### 8.2.3-8.2.4 Monitoring and Measurement + +**Audit Questions:** +- How do you monitor process performance? +- Show me product acceptance records +- What happens when acceptance criteria not met? + +**Evidence to Review:** +- [ ] Process monitoring data +- [ ] Inspection records +- [ ] Nonconforming product records + +### 8.3 Control of Nonconforming Product + +**Audit Questions:** +- Show me the procedure for nonconforming product +- How do you prevent unintended use of nonconforming product? +- Who authorizes concessions/deviations? + +**Evidence to Review:** +- [ ] NC product procedure +- [ ] NC product records +- [ ] Concession authorizations + +### 8.4 Analysis of Data + +**Audit Questions:** +- What data do you analyze for QMS effectiveness? +- Show me trend analysis for complaints, NC, CAPA +- How does data drive improvement? + +**Evidence to Review:** +- [ ] Data analysis reports +- [ ] Trend charts +- [ ] Management review inputs + +### 8.5 CAPA + +**Audit Questions:** +- Show me the CAPA procedure +- How do you determine root cause? +- Show me CAPA effectiveness verification + +**Evidence to Review:** +- [ ] CAPA procedure +- [ ] Open/closed CAPA log +- [ ] Root cause analysis records +- [ ] Effectiveness verification records + +**Common Findings:** +- Complaint trending not performed +- CAPA not initiated for recurring issues +- Root cause analysis superficial +- Effectiveness verification not documented + +--- + +## Common Nonconformities + +### Top 10 ISO 13485 Audit Findings + +| Rank | Clause | Finding | +|------|--------|---------| +| 1 | 7.3 | Design inputs not traceable to outputs | +| 2 | 8.5 | CAPA effectiveness not verified | +| 3 | 4.2.4 | Records not retrievable or legible | +| 4 | 7.4 | Supplier evaluation not documented | +| 5 | 6.2 | Training effectiveness not evaluated | +| 6 | 7.5.2 | Process validation not maintained | +| 7 | 8.2.2 | Internal audits not covering all clauses | +| 8 | 5.6 | Management review inputs incomplete | +| 9 | 7.6 | Calibration records incomplete | +| 10 | 8.3 | NC product control inadequate | + +### Finding Severity Classification + +| Severity | Definition | Response Required | +|----------|------------|-------------------| +| Major | Systematic failure, absence of element | CAPA within 30 days | +| Minor | Isolated lapse, partial implementation | Correction within 60 days | +| Observation | Improvement opportunity | Optional action | diff --git a/ra-qm-team/qms-audit-expert/references/nonconformity-classification.md b/ra-qm-team/qms-audit-expert/references/nonconformity-classification.md new file mode 100644 index 0000000..21ea8d2 --- /dev/null +++ b/ra-qm-team/qms-audit-expert/references/nonconformity-classification.md @@ -0,0 +1,221 @@ +# Nonconformity Classification + +Severity classification, CAPA integration, and finding documentation guidance. + +--- + +## Table of Contents + +- [Classification Criteria](#classification-criteria) +- [Severity Matrix](#severity-matrix) +- [CAPA Integration](#capa-integration) +- [Finding Documentation](#finding-documentation) +- [Closure Requirements](#closure-requirements) + +--- + +## Classification Criteria + +### Nonconformity Definitions + +| Category | Definition | Examples | +|----------|------------|----------| +| Major NC | Systematic failure or absence of required element | No design control procedure, no CAPA system | +| Minor NC | Isolated lapse or partial implementation | Single missing signature, one overdue calibration | +| Observation | Improvement opportunity, potential future NC | Trending toward noncompliance, unclear procedure | + +### Classification Decision Tree + +``` +Is required element absent or failed? +├── Yes → Is failure systematic (multiple instances)? +│ ├── Yes → MAJOR NONCONFORMITY +│ └── No → Could it cause product safety issue? +│ ├── Yes → MAJOR NONCONFORMITY +│ └── No → MINOR NONCONFORMITY +└── No → Is there deviation from procedure? + ├── Yes → Isolated or recurring? + │ ├── Isolated → MINOR NONCONFORMITY + │ └── Recurring → MAJOR NONCONFORMITY + └── No → Is there improvement opportunity? + ├── Yes → OBSERVATION + └── No → NO FINDING +``` + +--- + +## Severity Matrix + +### Impact vs. Occurrence Matrix + +| | Low Occurrence (1 instance) | Medium (2-3 instances) | High (Systematic) | +|---|---|---|---| +| **High Impact** (Safety/Efficacy) | Major | Major | Major | +| **Medium Impact** (Quality/Compliance) | Minor | Major | Major | +| **Low Impact** (Administrative) | Observation | Minor | Minor | + +### Clause-Specific Severity Guidance + +| Clause | Major If... | Minor If... | +|--------|-------------|-------------| +| 4.2 Document Control | No document control system | Single obsolete document in use | +| 5.6 Management Review | Not conducted >12 months | Missing single input | +| 6.2 Training | No competency defined | Single training record missing | +| 7.3 Design Control | No design reviews | Review participant missing | +| 7.4 Purchasing | No supplier evaluation | Single evaluation overdue | +| 7.5 Production | Special process not validated | Minor deviation from WI | +| 8.2.2 Internal Audit | No audit program | Audit overdue <90 days | +| 8.5 CAPA | No CAPA system | Effectiveness not verified | + +--- + +## CAPA Integration + +### Finding-to-CAPA Workflow + +1. **Classify finding** (Major/Minor/Observation) +2. **Document finding** with objective evidence +3. **Determine CAPA requirement** (see table below) +4. **Initiate CAPA** with finding as source +5. **Track resolution** through closure +6. **Verify effectiveness** at follow-up audit +7. **Validation:** Finding closed only after CAPA effective + +### CAPA Requirement by Severity + +| Severity | CAPA Required | Timeline | Verification | +|----------|---------------|----------|--------------| +| Major | Yes | 30 days for root cause, 90 days for implementation | Next audit or within 6 months | +| Minor | Recommended | 60 days for correction | Next scheduled audit | +| Observation | Optional | As appropriate | Noted at next audit | + +### Root Cause Depth by Severity + +| Severity | Root Cause Analysis Required | +|----------|------------------------------| +| Major | Full 5-Why or Fishbone, systemic causes | +| Minor | Immediate cause identification | +| Observation | Not required | + +--- + +## Finding Documentation + +### Finding Statement Structure + +``` +FINDING STATEMENT TEMPLATE: + +Requirement: [Specific clause or procedure requirement] +Evidence: [What was observed, reviewed, or heard] +Gap: [How the evidence fails to meet the requirement] + +Example: +Requirement: ISO 13485:2016 Clause 8.2.2 requires internal audits +at planned intervals to determine QMS conformity. + +Evidence: Audit schedule shows Design Control audit planned for +Q2 2024. No audit records exist. Interview with QA Manager +confirmed audit was not conducted. + +Gap: Internal audit for Design Control process not conducted as +planned, representing a gap in audit program execution. +``` + +### Evidence Types and Requirements + +| Evidence Type | How to Document | Retention | +|---------------|-----------------|-----------| +| Document | Reference document number, version, date | Copy in audit file | +| Interview | Interviewee name, role, statement summary | Notes in audit file | +| Observation | What, where, when observed | Photo if appropriate | +| Record | Record identifier, date, content observed | Copy in audit file | + +### Finding Writing Guidelines + +**Do:** +- State objective evidence clearly +- Reference specific requirements +- Use factual, neutral language +- Include document/record identifiers + +**Don't:** +- Use judgmental language ("poor", "inadequate") +- Generalize without evidence ("always", "never") +- Combine multiple findings +- Include corrective action suggestions + +--- + +## Closure Requirements + +### Closure Criteria by Severity + +**Major Nonconformity:** +- [ ] Root cause analysis completed +- [ ] Corrective action implemented +- [ ] Effectiveness verified (objective evidence) +- [ ] No recurrence observed +- [ ] QA Manager sign-off +- [ ] Auditor verification + +**Minor Nonconformity:** +- [ ] Immediate correction completed +- [ ] Root cause addressed (if applicable) +- [ ] Evidence of correction reviewed +- [ ] QA Manager sign-off + +**Observation:** +- [ ] Action taken (if any) documented +- [ ] Noted for future reference + +### Verification Methods + +| Method | When to Use | +|--------|-------------| +| Record review | Correction documented in records | +| Interview | Process change understood by personnel | +| Observation | Physical correction verified | +| Follow-up audit | Systematic correction verified over time | + +### Closure Documentation + +``` +CLOSURE RECORD TEMPLATE: + +Finding ID: [NC-YYYY-XXX] +Original Finding: [Brief description] +Severity: [Major/Minor/Observation] + +Corrective Action Taken: +[Description of action implemented] + +Evidence of Implementation: +[Document numbers, dates, observations] + +Effectiveness Verification: +[Method used, results, date] + +Closure Approved By: [Name, Role, Date] +``` + +--- + +## Audit Finding Log + +### Log Template + +| ID | Date | Clause | Finding | Severity | Status | Due Date | Closed Date | +|----|------|--------|---------|----------|--------|----------|-------------| +| NC-2024-001 | | | | | | | | +| NC-2024-002 | | | | | | | | + +### Status Definitions + +| Status | Definition | +|--------|------------| +| Open | Finding documented, CAPA not started | +| In Progress | CAPA underway | +| Pending Verification | Action complete, awaiting verification | +| Closed | Effectiveness verified | +| Escalated | Overdue or ineffective, requires management attention | diff --git a/ra-qm-team/qms-audit-expert/scripts/audit_schedule_optimizer.py b/ra-qm-team/qms-audit-expert/scripts/audit_schedule_optimizer.py new file mode 100644 index 0000000..d431606 --- /dev/null +++ b/ra-qm-team/qms-audit-expert/scripts/audit_schedule_optimizer.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +""" +Audit Schedule Optimizer - Risk-Based Internal Audit Planning + +Generates optimized audit schedules based on process risk levels, +previous findings, and resource constraints. + +Usage: + python audit_schedule_optimizer.py --processes processes.json + python audit_schedule_optimizer.py --interactive + python audit_schedule_optimizer.py --processes processes.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 RiskLevel(Enum): + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + + +class AuditFrequency(Enum): + QUARTERLY = 90 + SEMI_ANNUAL = 180 + ANNUAL = 365 + EXTENDED = 540 # 18 months + + +@dataclass +class Process: + name: str + iso_clause: str + risk_level: RiskLevel + last_audit_date: Optional[str] = None + previous_findings: int = 0 + criticality_score: int = 5 # 1-10 scale + notes: str = "" + + +@dataclass +class AuditSlot: + process_name: str + iso_clause: str + scheduled_date: str + risk_level: str + priority_score: float + days_overdue: int = 0 + rationale: str = "" + + +@dataclass +class AuditSchedule: + generated_date: str + schedule_period: str + total_audits: int + audits_by_quarter: Dict[str, int] + schedule: List[Dict] + recommendations: List[str] + + +class AuditScheduleOptimizer: + """Optimizer for risk-based audit scheduling.""" + + # Frequency mapping by risk level + FREQUENCY_MAP = { + RiskLevel.HIGH: AuditFrequency.QUARTERLY, + RiskLevel.MEDIUM: AuditFrequency.SEMI_ANNUAL, + RiskLevel.LOW: AuditFrequency.ANNUAL, + } + + # ISO 13485 required processes + REQUIRED_PROCESSES = [ + ("Document Control", "4.2"), + ("Management Review", "5.6"), + ("Training and Competency", "6.2"), + ("Design Control", "7.3"), + ("Purchasing", "7.4"), + ("Production Control", "7.5"), + ("Equipment Calibration", "7.6"), + ("Customer Feedback", "8.2.1"), + ("Internal Audit", "8.2.2"), + ("Nonconforming Product", "8.3"), + ("CAPA", "8.5"), + ] + + def __init__(self, processes: List[Process], audit_days_per_month: int = 4): + self.processes = processes + self.audit_days_per_month = audit_days_per_month + self.today = datetime.now() + + def calculate_priority_score(self, process: Process) -> float: + """Calculate audit priority score based on multiple factors.""" + score = 0.0 + + # Base risk score (40% weight) + risk_scores = {RiskLevel.HIGH: 10, RiskLevel.MEDIUM: 6, RiskLevel.LOW: 3} + score += risk_scores[process.risk_level] * 0.4 + + # Overdue factor (30% weight) + if process.last_audit_date: + last_audit = datetime.strptime(process.last_audit_date, "%Y-%m-%d") + days_since = (self.today - last_audit).days + required_frequency = self.FREQUENCY_MAP[process.risk_level].value + overdue_ratio = days_since / required_frequency + score += min(overdue_ratio * 10, 10) * 0.3 + else: + # Never audited = highest priority + score += 10 * 0.3 + + # Previous findings factor (20% weight) + findings_score = min(process.previous_findings * 2, 10) + score += findings_score * 0.2 + + # Criticality factor (10% weight) + score += process.criticality_score * 0.1 + + return round(score, 2) + + def get_days_overdue(self, process: Process) -> int: + """Calculate days overdue for audit.""" + if not process.last_audit_date: + return 365 # Assume 1 year overdue if never audited + + last_audit = datetime.strptime(process.last_audit_date, "%Y-%m-%d") + required_frequency = self.FREQUENCY_MAP[process.risk_level].value + next_due = last_audit + timedelta(days=required_frequency) + days_overdue = (self.today - next_due).days + + return max(0, days_overdue) + + def generate_schedule(self, months_ahead: int = 12) -> AuditSchedule: + """Generate optimized audit schedule.""" + # Calculate priority scores + prioritized = [] + for process in self.processes: + priority = self.calculate_priority_score(process) + overdue = self.get_days_overdue(process) + prioritized.append((process, priority, overdue)) + + # Sort by priority (descending) + prioritized.sort(key=lambda x: x[1], reverse=True) + + # Generate schedule slots + schedule = [] + current_date = self.today + audits_per_quarter = {"Q1": 0, "Q2": 0, "Q3": 0, "Q4": 0} + + for process, priority, overdue in prioritized: + # Determine schedule date based on priority + if overdue > 0: + # Overdue: schedule within next 30 days + scheduled_date = current_date + timedelta(days=min(30, overdue // 10 + 7)) + elif priority > 7: + # High priority: within 60 days + scheduled_date = current_date + timedelta(days=30) + elif priority > 4: + # Medium priority: within 120 days + scheduled_date = current_date + timedelta(days=90) + else: + # Low priority: within 180 days + scheduled_date = current_date + timedelta(days=180) + + # Cap at months_ahead + max_date = current_date + timedelta(days=months_ahead * 30) + if scheduled_date > max_date: + scheduled_date = max_date + + # Track quarter distribution + quarter = f"Q{(scheduled_date.month - 1) // 3 + 1}" + audits_per_quarter[quarter] += 1 + + # Generate rationale + rationale_parts = [] + if overdue > 0: + rationale_parts.append(f"{overdue} days overdue") + if process.previous_findings > 0: + rationale_parts.append(f"{process.previous_findings} previous findings") + if process.risk_level == RiskLevel.HIGH: + rationale_parts.append("high-risk process") + rationale = "; ".join(rationale_parts) if rationale_parts else "Scheduled per frequency" + + slot = AuditSlot( + process_name=process.name, + iso_clause=process.iso_clause, + scheduled_date=scheduled_date.strftime("%Y-%m-%d"), + risk_level=process.risk_level.value, + priority_score=priority, + days_overdue=overdue, + rationale=rationale + ) + schedule.append(slot) + + # Generate recommendations + recommendations = self._generate_recommendations(prioritized) + + return AuditSchedule( + generated_date=self.today.strftime("%Y-%m-%d"), + schedule_period=f"{self.today.strftime('%Y-%m-%d')} to {(self.today + timedelta(days=months_ahead * 30)).strftime('%Y-%m-%d')}", + total_audits=len(schedule), + audits_by_quarter=audits_per_quarter, + schedule=[asdict(s) for s in schedule], + recommendations=recommendations + ) + + def _generate_recommendations(self, prioritized: List) -> List[str]: + """Generate recommendations based on analysis.""" + recommendations = [] + + # Check for overdue audits + overdue_count = sum(1 for _, _, overdue in prioritized if overdue > 0) + if overdue_count > 0: + recommendations.append( + f"URGENT: {overdue_count} process(es) overdue for audit. " + "Prioritize these to maintain compliance." + ) + + # Check for high-risk processes + high_risk_count = sum(1 for p, _, _ in prioritized if p.risk_level == RiskLevel.HIGH) + if high_risk_count > 3: + recommendations.append( + f"High audit burden: {high_risk_count} high-risk processes. " + "Consider quarterly resource allocation." + ) + + # Check for processes with multiple findings + finding_processes = [(p.name, p.previous_findings) for p, _, _ in prioritized if p.previous_findings >= 3] + if finding_processes: + names = ", ".join([name for name, _ in finding_processes[:3]]) + recommendations.append( + f"Recurring issues in: {names}. " + "Consider focused audits or process improvement initiatives." + ) + + # Check for never-audited processes + never_audited = [p.name for p, _, _ in prioritized if not p.last_audit_date] + if never_audited: + recommendations.append( + f"Never audited: {', '.join(never_audited[:3])}. " + "Include in next audit cycle." + ) + + if not recommendations: + recommendations.append("Audit program is on track. Maintain scheduled frequency.") + + return recommendations + + +def format_text_output(schedule: AuditSchedule) -> str: + """Format schedule as text report.""" + lines = [ + "=" * 70, + "AUDIT SCHEDULE OPTIMIZATION REPORT", + "=" * 70, + f"Generated: {schedule.generated_date}", + f"Period: {schedule.schedule_period}", + f"Total Audits: {schedule.total_audits}", + "", + "Quarterly Distribution:", + ] + + for q, count in schedule.audits_by_quarter.items(): + bar = "█" * count + "░" * (10 - count) + lines.append(f" {q}: {bar} {count}") + + lines.extend([ + "", + "-" * 70, + "AUDIT SCHEDULE", + "-" * 70, + f"{'Process':<25} {'Clause':<8} {'Date':<12} {'Risk':<8} {'Priority':<8}", + "-" * 70, + ]) + + for audit in schedule.schedule: + lines.append( + f"{audit['process_name']:<25} " + f"{audit['iso_clause']:<8} " + f"{audit['scheduled_date']:<12} " + f"{audit['risk_level']:<8} " + f"{audit['priority_score']:<8}" + ) + + lines.extend([ + "", + "-" * 70, + "RECOMMENDATIONS", + "-" * 70, + ]) + + for i, rec in enumerate(schedule.recommendations, 1): + lines.append(f"{i}. {rec}") + + lines.append("=" * 70) + return "\n".join(lines) + + +def interactive_mode(): + """Run interactive schedule generation.""" + print("=" * 60) + print("Audit Schedule Optimizer - Interactive Mode") + print("=" * 60) + + processes = [] + print("\nEnter processes (blank name to finish):\n") + + while True: + name = input("Process name (or Enter to finish): ").strip() + if not name: + break + + clause = input("ISO 13485 clause (e.g., 7.3): ").strip() + risk = input("Risk level (H/M/L): ").strip().upper() + risk_level = { + "H": RiskLevel.HIGH, + "M": RiskLevel.MEDIUM, + "L": RiskLevel.LOW + }.get(risk, RiskLevel.MEDIUM) + + last_audit = input("Last audit date (YYYY-MM-DD, or Enter if never): ").strip() + if not last_audit: + last_audit = None + + findings = input("Previous findings count (default 0): ").strip() + findings = int(findings) if findings.isdigit() else 0 + + processes.append(Process( + name=name, + iso_clause=clause, + risk_level=risk_level, + last_audit_date=last_audit, + previous_findings=findings + )) + + print(f"Added: {name}\n") + + if not processes: + print("No processes entered. Using default ISO 13485 processes.") + processes = [ + Process(name=name, iso_clause=clause, risk_level=RiskLevel.MEDIUM) + for name, clause in AuditScheduleOptimizer.REQUIRED_PROCESSES + ] + + optimizer = AuditScheduleOptimizer(processes) + schedule = optimizer.generate_schedule() + print("\n" + format_text_output(schedule)) + + +def main(): + parser = argparse.ArgumentParser( + description="Risk-Based Audit Schedule Optimizer" + ) + parser.add_argument( + "--processes", + type=str, + help="JSON file with process definitions" + ) + 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( + "--months", + type=int, + default=12, + help="Planning horizon in months" + ) + + args = parser.parse_args() + + if args.interactive: + interactive_mode() + return + + if args.processes: + with open(args.processes, "r") as f: + data = json.load(f) + + processes = [] + for p in data.get("processes", []): + risk = RiskLevel[p.get("risk_level", "MEDIUM").upper()] + processes.append(Process( + name=p["name"], + iso_clause=p.get("iso_clause", ""), + risk_level=risk, + last_audit_date=p.get("last_audit_date"), + previous_findings=p.get("previous_findings", 0), + criticality_score=p.get("criticality_score", 5) + )) + else: + # Use default processes + processes = [ + Process(name=name, iso_clause=clause, risk_level=RiskLevel.MEDIUM) + for name, clause in AuditScheduleOptimizer.REQUIRED_PROCESSES + ] + + optimizer = AuditScheduleOptimizer(processes) + schedule = optimizer.generate_schedule(args.months) + + if args.output == "json": + print(json.dumps(asdict(schedule), indent=2)) + else: + print(format_text_output(schedule)) + + +if __name__ == "__main__": + main() diff --git a/ra-qm-team/qms-audit-expert/scripts/example.py b/ra-qm-team/qms-audit-expert/scripts/example.py deleted file mode 100755 index 223c0b0..0000000 --- a/ra-qm-team/qms-audit-expert/scripts/example.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 -""" -Example helper script for qms-audit-expert - -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 qms-audit-expert") - # TODO: Add actual script logic here - # This could be data processing, file conversion, API calls, etc. - -if __name__ == "__main__": - main()