name: “qms-audit-expert”
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
QMS Audit Expert
ISO 13485 internal audit methodology for medical device quality management systems.
Table of Contents
Audit Planning Workflow
Plan risk-based internal audit program:
- List all QMS processes requiring audit
- Assign risk level to each process (High/Medium/Low)
- Review previous audit findings and trends
- Determine audit frequency by risk level
- Assign qualified auditors (verify independence)
- Create annual audit schedule
- Communicate schedule to process owners
- 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:
Audit Execution
Conduct systematic internal audit:
- Prepare audit plan (scope, criteria, schedule)
- Review relevant documentation before audit
- Conduct opening meeting with auditee
- Collect evidence (records, interviews, observation)
- Classify findings (Major/Minor/Observation)
- Conduct closing meeting with preliminary findings
- Prepare audit report within 5 business days
- 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:
Requirement: [Specific ISO 13485 clause or procedure]
Evidence: [What was observed, reviewed, or heard]
Gap: [How evidence fails to meet requirement]
Example:
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.
Classify and manage audit findings:
- Evaluate finding against classification criteria
- Assign severity (Major/Minor/Observation)
- Document finding with objective evidence
- Communicate to process owner
- Initiate CAPA for Major/Minor findings
- Track to closure
- Verify effectiveness at follow-up
- Validation: Finding closed only after effective CAPA
Classification Criteria
| 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 |
Classification Decision
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
CAPA Integration
| 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 |
See references/nonconformity-classification.md for detailed guidance.
External Audit Preparation
Prepare for certification body or regulatory audit:
- Complete all scheduled internal audits
- Verify all findings closed with effective CAPA
- Review documentation for currency and accuracy
- Conduct management review with audit as input
- Prepare facility and personnel
- Conduct mock audit (full scope)
- Brief personnel on audit protocol
- Validation: Mock audit findings addressed before external audit
Pre-Audit Readiness Checklist
Documentation:
Personnel:
Facility:
Mock Audit Protocol
- Use external auditor or qualified internal auditor
- Cover full scope of upcoming external audit
- Simulate actual audit conditions (timing, formality)
- Document findings as for real audit
- Address all Major and Minor findings before external audit
- Brief management on readiness status
Reference Documentation
ISO 13485 Audit Guide
references/iso13485-audit-guide.md contains:
- Clause-by-clause audit methodology
- Sample audit questions for each clause
- Evidence collection requirements
- Common nonconformities by clause
- Finding severity 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
Audit Schedule Optimizer
# 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
{
"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 |
ISO 13485 Audit Guide
Clause-by-clause audit methodology with sample questions and common findings.
Table of Contents
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
8.5 CAPA
Audit Questions:
- Show me the CAPA procedure
- How do you determine root cause?
- Show me CAPA effectiveness verification
Evidence to Review:
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 |
Nonconformity Classification
Severity classification, CAPA integration, and finding documentation guidance.
Table of Contents
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
- Classify finding (Major/Minor/Observation)
- Document finding with objective evidence
- Determine CAPA requirement (see table below)
- Initiate CAPA with finding as source
- Track resolution through closure
- Verify effectiveness at follow-up audit
- 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:
Minor Nonconformity:
Observation:
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 |
#!/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()