Skill: alirezarezvani/fda-consultant-specialist (version 2.1.1)

--- name: "fda-consultant-specialist" description: FDA regulatory consultant for medical device companies. Provides 510(k)/PMA/De Novo pathway guidance, QSR (21 CFR 820) compliance, HIPAA assessments, and device cybersecurity. Use when user mentions FDA submission, 510(k), PMA, De Novo, QSR, premarket, predicate device, substantial equivalence, HIPAA medical device, or FDA cybersecurity. --- # FDA Consultant Specialist FDA regulatory consulting for medical device manufacturers covering submission pathways, Quality System Regulation (QSR), HIPAA compliance, and device cybersecurity requirements. ## Table of Contents - [FDA Pathway Selection](#fda-pathway-selection) - [510(k) Submission Process](#510k-submission-process) - [QSR Compliance](#qsr-compliance) - [HIPAA for Medical Devices](#hipaa-for-medical-devices) - [Device Cybersecurity](#device-cybersecurity) - [Resources](#resources) --- ## FDA Pathway Selection Determine the appropriate FDA regulatory pathway based on device classification and predicate availability. ### Decision Framework ``` Predicate device exists? ├── YES → Substantially equivalent? │ ├── YES → 510(k) Pathway │ │ ├── No design changes → Abbreviated 510(k) │ │ ├── Manufacturing only → Special 510(k) │ │ └── Design/performance → Traditional 510(k) │ └── NO → PMA or De Novo └── NO → Novel device? ├── Low-to-moderate risk → De Novo └── High risk (Class III) → PMA ``` ### Pathway Comparison | Pathway | When to Use | Timeline | Cost | |---------|-------------|----------|------| | 510(k) Traditional | Predicate exists, design changes | 90 days | $21,760 | | 510(k) Special | Manufacturing changes only | 30 days | $21,760 | | 510(k) Abbreviated | Guidance/standard conformance | 30 days | $21,760 | | De Novo | Novel, low-moderate risk | 150 days | $134,676 | | PMA | Class III, no predicate | 180+ days | $425,000+ | ### Pre-Submission Strategy 1. Identify product code and classification 2. Search 510(k) database for predicates 3. Assess substantial equivalence feasibility 4. Prepare Q-Sub questions for FDA 5. Schedule Pre-Sub meeting if needed **Reference:** See [fda_submission_guide.md](references/fda_submission_guide.md) for pathway decision matrices and submission requirements. --- ## 510(k) Submission Process ### Workflow ``` Phase 1: Planning ├── Step 1: Identify predicate device(s) ├── Step 2: Compare intended use and technology ├── Step 3: Determine testing requirements └── Checkpoint: SE argument feasible? Phase 2: Preparation ├── Step 4: Complete performance testing ├── Step 5: Prepare device description ├── Step 6: Document SE comparison ├── Step 7: Finalize labeling └── Checkpoint: All required sections complete? Phase 3: Submission ├── Step 8: Assemble submission package ├── Step 9: Submit via eSTAR ├── Step 10: Track acknowledgment └── Checkpoint: Submission accepted? Phase 4: Review ├── Step 11: Monitor review status ├── Step 12: Respond to AI requests ├── Step 13: Receive decision └── Verification: SE letter received? ``` ### Required Sections (21 CFR 807.87) | Section | Content | |---------|---------| | Cover Letter | Submission type, device ID, contact info | | Form 3514 | CDRH premarket review cover sheet | | Device Description | Physical description, principles of operation | | Indications for Use | Form 3881, patient population, use environment | | SE Comparison | Side-by-side comparison with predicate | | Performance Testing | Bench, biocompatibility, electrical safety | | Software Documentation | Level of concern, hazard analysis (IEC 62304) | | Labeling | IFU, package labels, warnings | | 510(k) Summary | Public summary of submission | ### Common RTA Issues | Issue | Prevention | |-------|------------| | Missing user fee | Verify payment before submission | | Incomplete Form 3514 | Review all fields, ensure signature | | No predicate identified | Confirm K-number in FDA database | | Inadequate SE comparison | Address all technological characteristics | --- ## QSR Compliance Quality System Regulation (21 CFR Part 820) requirements for medical device manufacturers. ### Key Subsystems | Section | Title | Focus | |---------|-------|-------| | 820.20 | Management Responsibility | Quality policy, org structure, management review | | 820.30 | Design Controls | Input, output, review, verification, validation | | 820.40 | Document Controls | Approval, distribution, change control | | 820.50 | Purchasing Controls | Supplier qualification, purchasing data | | 820.70 | Production Controls | Process validation, environmental controls | | 820.100 | CAPA | Root cause analysis, corrective actions | | 820.181 | Device Master Record | Specifications, procedures, acceptance criteria | ### Design Controls Workflow (820.30) ``` Step 1: Design Input └── Capture user needs, intended use, regulatory requirements Verification: Inputs reviewed and approved? Step 2: Design Output └── Create specifications, drawings, software architecture Verification: Outputs traceable to inputs? Step 3: Design Review └── Conduct reviews at each phase milestone Verification: Review records with signatures? Step 4: Design Verification └── Perform testing against specifications Verification: All tests pass acceptance criteria? Step 5: Design Validation └── Confirm device meets user needs in actual use conditions Verification: Validation report approved? Step 6: Design Transfer └── Release to production with DMR complete Verification: Transfer checklist complete? ``` ### CAPA Process (820.100) 1. **Identify**: Document nonconformity or potential problem 2. **Investigate**: Perform root cause analysis (5 Whys, Fishbone) 3. **Plan**: Define corrective/preventive actions 4. **Implement**: Execute actions, update documentation 5. **Verify**: Confirm implementation complete 6. **Effectiveness**: Monitor for recurrence (30-90 days) 7. **Close**: Management approval and closure **Reference:** See [qsr_compliance_requirements.md](references/qsr_compliance_requirements.md) for detailed QSR implementation guidance. --- ## HIPAA for Medical Devices HIPAA requirements for devices that create, store, transmit, or access Protected Health Information (PHI). ### Applicability | Device Type | HIPAA Applies | |-------------|---------------| | Standalone diagnostic (no data transmission) | No | | Connected device transmitting patient data | Yes | | Device with EHR integration | Yes | | SaMD storing patient information | Yes | | Wellness app (no diagnosis) | Only if stores PHI | ### Required Safeguards ``` Administrative (§164.308) ├── Security officer designation ├── Risk analysis and management ├── Workforce training ├── Incident response procedures └── Business associate agreements Physical (§164.310) ├── Facility access controls ├── Workstation security └── Device disposal procedures Technical (§164.312) ├── Access control (unique IDs, auto-logoff) ├── Audit controls (logging) ├── Integrity controls (checksums, hashes) ├── Authentication (MFA recommended) └── Transmission security (TLS 1.2+) ``` ### Risk Assessment Steps 1. Inventory all systems handling ePHI 2. Document data flows (collection, storage, transmission) 3. Identify threats and vulnerabilities 4. Assess likelihood and impact 5. Determine risk levels 6. Implement controls 7. Document residual risk **Reference:** See [hipaa_compliance_framework.md](references/hipaa_compliance_framework.md) for implementation checklists and BAA templates. --- ## Device Cybersecurity FDA cybersecurity requirements for connected medical devices. ### Premarket Requirements | Element | Description | |---------|-------------| | Threat Model | STRIDE analysis, attack trees, trust boundaries | | Security Controls | Authentication, encryption, access control | | SBOM | Software Bill of Materials (CycloneDX or SPDX) | | Security Testing | Penetration testing, vulnerability scanning | | Vulnerability Plan | Disclosure process, patch management | ### Device Tier Classification **Tier 1 (Higher Risk):** - Connects to network/internet - Cybersecurity incident could cause patient harm **Tier 2 (Standard Risk):** - All other connected devices ### Postmarket Obligations 1. Monitor NVD and ICS-CERT for vulnerabilities 2. Assess applicability to device components 3. Develop and test patches 4. Communicate with customers 5. Report to FDA per guidance ### Coordinated Vulnerability Disclosure ``` Researcher Report ↓ Acknowledgment (48 hours) ↓ Initial Assessment (5 days) ↓ Fix Development ↓ Coordinated Public Disclosure ``` **Reference:** See [device_cybersecurity_guidance.md](references/device_cybersecurity_guidance.md) for SBOM format examples and threat modeling templates. --- ## Resources ### scripts/ | Script | Purpose | |--------|---------| | `fda_submission_tracker.py` | Track 510(k)/PMA/De Novo submission milestones and timelines | | `qsr_compliance_checker.py` | Assess 21 CFR 820 compliance against project documentation | | `hipaa_risk_assessment.py` | Evaluate HIPAA safeguards in medical device software | ### references/ | File | Content | |------|---------| | `fda_submission_guide.md` | 510(k), De Novo, PMA submission requirements and checklists | | `qsr_compliance_requirements.md` | 21 CFR 820 implementation guide with templates | | `hipaa_compliance_framework.md` | HIPAA Security Rule safeguards and BAA requirements | | `device_cybersecurity_guidance.md` | FDA cybersecurity requirements, SBOM, threat modeling | | `fda_capa_requirements.md` | CAPA process, root cause analysis, effectiveness verification | ### Usage Examples ```bash # Track FDA submission status python scripts/fda_submission_tracker.py /path/to/project --type 510k # Assess QSR compliance python scripts/qsr_compliance_checker.py /path/to/project --section 820.30 # Run HIPAA risk assessment python scripts/hipaa_risk_assessment.py /path/to/project --category technical ```

path: references/device_cybersecurity_guidance.md
content: # Medical Device Cybersecurity Guidance

Complete framework for FDA cybersecurity requirements based on FDA guidance documents and recognized consensus standards.

---

## Table of Contents

- [Regulatory Framework](#regulatory-framework)
- [Premarket Cybersecurity](#premarket-cybersecurity)
- [Postmarket Cybersecurity](#postmarket-cybersecurity)
- [Threat Modeling](#threat-modeling)
- [Security Controls](#security-controls)
- [Software Bill of Materials](#software-bill-of-materials)
- [Vulnerability Management](#vulnerability-management)
- [Documentation Requirements](#documentation-requirements)

---

## Regulatory Framework

### FDA Guidance Documents

| Document | Scope | Key Requirements |
|----------|-------|------------------|
| Premarket Cybersecurity (2023) | 510(k), PMA, De Novo | Security design, SBOM, threat modeling |
| Postmarket Management (2016) | All marketed devices | Vulnerability monitoring, patching |
| Content of Premarket Submissions | Submission format | Documentation structure |

### PATCH Act Requirements (2023)

**Cyber Device Definition:**
- Contains software
- Can connect to internet
- May be vulnerable to cybersecurity threats

**Manufacturer Obligations:**
1. Submit plan to monitor, identify, and address vulnerabilities
2. Design, develop, and maintain processes to ensure device security
3. Provide software bill of materials (SBOM)
4. Comply with other requirements under section 524B

### Recognized Consensus Standards

| Standard | Scope | FDA Recognition |
|----------|-------|-----------------|
| IEC 62443 | Industrial automation security | Recognized |
| NIST Cybersecurity Framework | Security framework | Referenced |
| UL 2900 | Software cybersecurity | Recognized |
| AAMI TIR57 | Medical device cybersecurity | Referenced |
| IEC 81001-5-1 | Health software security | Recognized |

---

## Premarket Cybersecurity

### Cybersecurity Documentation Requirements

```
Cybersecurity Documentation Package:
├── 1. Security Risk Assessment
│   ├── Threat model
│   ├── Vulnerability assessment
│   ├── Risk analysis
│   └── Risk mitigation
├── 2. Security Architecture
│   ├── System diagram
│   ├── Data flow diagram
│   ├── Trust boundaries
│   └── Security controls
├── 3. Cybersecurity Testing
│   ├── Penetration testing
│   ├── Vulnerability scanning
│   ├── Fuzz testing
│   └── Security code review
├── 4. SBOM
│   ├── Software components
│   ├── Versions
│   └── Known vulnerabilities
├── 5. Vulnerability Management Plan
│   ├── Monitoring process
│   ├── Disclosure process
│   └── Patch management
└── 6. Labeling
    ├── Security instructions
    └── End-of-life plan
```

### Device Tier Classification

**Tier 1 - Higher Cybersecurity Risk:**
- Device can connect to another product or network
- A cybersecurity incident could directly result in patient harm

**Tier 2 - Standard Cybersecurity Risk:**
- Device NOT a Tier 1 device
- Still requires cybersecurity documentation

**Documentation Depth by Tier:**

| Element | Tier 1 | Tier 2 |
|---------|--------|--------|
| Threat model | Comprehensive | Basic |
| Penetration testing | Required | Recommended |
| SBOM | Required | Required |
| Security testing | Full suite | Core testing |

### Security by Design Principles

```markdown
## Secure Product Development Framework (SPDF)

### 1. Security Risk Management
- Integrate security into QMS
- Apply throughout product lifecycle
- Document security decisions

### 2. Security Architecture
- Defense in depth
- Least privilege
- Secure defaults
- Fail securely

### 3. Cybersecurity Testing
- Verify security controls
- Test for known vulnerabilities
- Validate threat mitigations

### 4. Cybersecurity Transparency
- SBOM provision
- Vulnerability disclosure
- Coordinated vulnerability disclosure

### 5. Cybersecurity Maintenance
- Monitor for vulnerabilities
- Provide timely updates
- Support throughout lifecycle
```

---

## Postmarket Cybersecurity

### Vulnerability Monitoring

**Sources to Monitor:**
- National Vulnerability Database (NVD)
- ICS-CERT advisories
- Third-party component vendors
- Security researcher reports
- Customer/user reports

**Monitoring Process:**

```
Daily/Weekly Monitoring:
├── NVD feed check
├── Vendor security bulletins
├── Security mailing lists
└── ISAC notifications

Monthly Review:
├── Component vulnerability analysis
├── Risk re-assessment
├── Patch status review
└── Trending threat analysis

Quarterly Assessment:
├── Comprehensive vulnerability scan
├── Third-party security audit
├── Update threat model
└── Security metrics review
```

### Vulnerability Assessment and Response

**CVSS-Based Triage:**

| CVSS Score | Severity | Response Timeframe |
|------------|----------|-------------------|
| 9.0-10.0 | Critical | 24-48 hours assessment |
| 7.0-8.9 | High | 1 week assessment |
| 4.0-6.9 | Medium | 30 days assessment |
| 0.1-3.9 | Low | Quarterly review |

**Exploitability Assessment:**

```markdown
## Vulnerability Exploitation Assessment

### Device-Specific Factors
- [ ] Is the vulnerability reachable in device configuration?
- [ ] Are mitigating controls in place?
- [ ] What is the attack surface exposure?
- [ ] What is the potential patient harm?

### Environment Factors
- [ ] Is exploit code publicly available?
- [ ] Is the vulnerability being actively exploited?
- [ ] What is the typical deployment environment?

### Risk Determination
Uncontrolled Risk = Exploitability × Impact × Exposure

| Risk Level | Action |
|------------|--------|
| Unacceptable | Immediate remediation |
| Elevated | Prioritized remediation |
| Acceptable | Monitor, routine update |
```

### Patch and Update Management

**Update Classification:**

| Type | Description | Regulatory Path |
|------|-------------|-----------------|
| Security patch | Addresses vulnerability only | May not require new submission |
| Software update | New features + security | Evaluate per guidance |
| Major upgrade | Significant changes | New 510(k) evaluation |

**FDA's Cybersecurity Policies:**

1. **Routine Updates:** Generally do not require premarket review
2. **Remediation of Vulnerabilities:** No premarket review if:
   - No new risks introduced
   - No changes to intended use
   - Adequate design controls followed

---

## Threat Modeling

### STRIDE Methodology

| Threat | Description | Device Example |
|--------|-------------|----------------|
| **S**poofing | Pretending to be someone/something else | Fake device identity |
| **T**ampering | Modifying data or code | Altering dosage parameters |
| **R**epudiation | Denying actions | Hiding malicious commands |
| **I**nformation Disclosure | Exposing information | PHI data leak |
| **D**enial of Service | Making resource unavailable | Device becomes unresponsive |
| **E**levation of Privilege | Gaining unauthorized access | Admin access from user |

### Threat Model Template

```markdown
## Device Threat Model

### 1. System Description
Device Name: _____________________
Device Type: _____________________
Intended Use: ____________________

### 2. Architecture Diagram
[Include system diagram with trust boundaries]

### 3. Data Flow Diagram
[Document data flows and data types]

### 4. Entry Points
| Entry Point | Protocol | Authentication | Data Type |
|-------------|----------|----------------|-----------|
| USB port | USB HID | None | Config data |
| Network | HTTPS | Certificate | PHI |
| Bluetooth | BLE | Pairing | Commands |

### 5. Assets
| Asset | Sensitivity | Integrity | Availability |
|-------|-------------|-----------|--------------|
| Patient data | High | High | Medium |
| Device firmware | High | Critical | High |
| Configuration | Medium | High | Medium |

### 6. Threat Analysis
| Threat ID | STRIDE | Entry Point | Asset | Mitigation |
|-----------|--------|-------------|-------|------------|
| T-001 | Spoofing | Network | Auth | Mutual TLS |
| T-002 | Tampering | USB | Firmware | Secure boot |
| T-003 | Information | Network | PHI | Encryption |

### 7. Risk Assessment
| Threat | Likelihood | Impact | Risk | Accept/Mitigate |
|--------|------------|--------|------|-----------------|
| T-001 | Medium | High | High | Mitigate |
| T-002 | Low | Critical | High | Mitigate |
| T-003 | Medium | High | High | Mitigate |
```

### Attack Trees

**Example: Unauthorized Access to Device**

```
Goal: Gain Unauthorized Access
├── 1. Physical Access Attack
│   ├── 1.1 Steal device
│   ├── 1.2 Access debug port
│   └── 1.3 Extract storage media
├── 2. Network Attack
│   ├── 2.1 Exploit unpatched vulnerability
│   ├── 2.2 Man-in-the-middle attack
│   └── 2.3 Credential theft
├── 3. Social Engineering
│   ├── 3.1 Phishing for credentials
│   └── 3.2 Insider threat
└── 4. Supply Chain Attack
    ├── 4.1 Compromised component
    └── 4.2 Malicious update
```

---

## Security Controls

### Authentication and Access Control

**Authentication Requirements:**

| Access Level | Authentication | Session Management |
|--------------|----------------|-------------------|
| Patient | PIN/biometric | Auto-logout |
| Clinician | Password + MFA | Timeout 15 min |
| Service | Certificate | Per-session |
| Admin | MFA + approval | Audit logged |

**Password Requirements:**
- Minimum 8 characters (12+ recommended)
- Complexity requirements
- Secure storage (hashed, salted)
- Account lockout after failed attempts
- Forced change on first use

### Encryption Requirements

**Data at Rest:**
- AES-256 for sensitive data
- Secure key storage (TPM, secure enclave)
- Key rotation procedures

**Data in Transit:**
- TLS 1.2 or higher
- Strong cipher suites
- Certificate validation
- Perfect forward secrecy

**Encryption Implementation Checklist:**

```markdown
## Encryption Controls

### Key Management
- [ ] Keys stored in hardware security module or equivalent
- [ ] Key generation uses cryptographically secure RNG
- [ ] Key rotation procedures documented
- [ ] Key revocation procedures documented
- [ ] Key escrow/recovery procedures (if applicable)

### Algorithm Selection
- [ ] AES-256 for symmetric encryption
- [ ] RSA-2048+ or ECDSA P-256+ for asymmetric
- [ ] SHA-256 or better for hashing
- [ ] No deprecated algorithms (MD5, SHA-1, DES)

### Implementation
- [ ] Using well-vetted cryptographic libraries
- [ ] Proper initialization vector handling
- [ ] Protection against timing attacks
- [ ] Secure key zeroing after use
```

### Secure Communications

**Network Security Controls:**

| Layer | Control | Implementation |
|-------|---------|----------------|
| Transport | TLS 1.2+ | Mutual authentication |
| Network | Firewall | Whitelist only |
| Application | API security | Rate limiting, validation |
| Data | Encryption | End-to-end |

### Code Integrity

**Secure Boot Chain:**

```
Root of Trust (Hardware)
    ↓
Bootloader (Signed)
    ↓
Operating System (Verified)
    ↓
Application (Authenticated)
    ↓
Configuration (Integrity-checked)
```

**Software Integrity Controls:**
- Code signing for all software
- Signature verification before execution
- Anti-rollback protection
- Secure update mechanism

---

## Software Bill of Materials

### SBOM Requirements

**NTIA Minimum Elements:**
1. Supplier name
2. Component name
3. Version of component
4. Other unique identifiers (PURL, CPE)
5. Dependency relationship
6. Author of SBOM data
7. Timestamp

### SBOM Formats

| Format | Standard | Use Case |
|--------|----------|----------|
| SPDX | ISO/IEC 5962:2021 | Comprehensive |
| CycloneDX | OWASP | Security-focused |
| SWID | ISO/IEC 19770-2 | Asset management |

### SBOM Template (CycloneDX)

```xml
<?xml version="1.0" encoding="UTF-8"?>
<bom xmlns="http://cyclonedx.org/schema/bom/1.4">
  <metadata>
    <timestamp>2024-01-15T00:00:00Z</timestamp>
    <tools>
      <tool>
        <vendor>Manufacturer</vendor>
        <name>SBOM Generator</name>
        <version>1.0.0</version>
      </tool>
    </tools>
    <component type="device">
      <name>Medical Device XYZ</name>
      <version>2.0.0</version>
      <supplier>
        <name>Device Manufacturer</name>
      </supplier>
    </component>
  </metadata>
  <components>
    <component type="library">
      <name>openssl</name>
      <version>1.1.1k</version>
      <purl>pkg:generic/openssl@1.1.1k</purl>
      <licenses>
        <license>
          <id>Apache-2.0</id>
        </license>
      </licenses>
    </component>
    <!-- Additional components -->
  </components>
  <dependencies>
    <dependency ref="device-xyz">
      <dependency ref="openssl"/>
    </dependency>
  </dependencies>
</bom>
```

### SBOM Management Process

```
1. Initial SBOM Creation
   └── During development, before submission

2. Vulnerability Monitoring
   └── Continuous monitoring against NVD

3. SBOM Updates
   └── With each software release

4. Customer Communication
   └── SBOM provided on request

5. FDA Submission
   └── Included in premarket submission
```

---

## Vulnerability Management

### Vulnerability Disclosure

**Coordinated Vulnerability Disclosure (CVD):**

```markdown
## Vulnerability Disclosure Policy

### Reporting
- Security contact: [REDACTED_SECRET]
- PGP key available at: [URL]
- Bug bounty program: [if applicable]

### Response Timeline
- Acknowledgment: Within 48 hours
- Initial assessment: Within 5 business days
- Status updates: Every 30 days
- Target remediation: Per severity

### Public Disclosure
- Coordinated with reporter
- After remediation available
- Include mitigations if patch delayed

### Safe Harbor
[Statement on not pursuing legal action against good-faith reporters]
```

### Vulnerability Response Process

```
Discovery
    ↓
Triage (CVSS + Exploitability)
    ↓
Risk Assessment
    ↓
Remediation Development
    ↓
Testing and Validation
    ↓
Deployment/Communication
    ↓
Verification
    ↓
Closure
```

### Customer Communication

**Security Advisory Template:**

```markdown
## Security Advisory

### Advisory ID: [ID]
### Published: [Date]
### Severity: [Critical/High/Medium/Low]

### Affected Products
- Product A, versions 1.0-2.0
- Product B, versions 3.0-3.5

### Description
[Description of vulnerability without exploitation details]

### Impact
[What could happen if exploited]

### Mitigation
[Steps to reduce risk before patch available]

### Remediation
- Patch version: X.X.X
- Download: [URL]
- Installation instructions: [Link]

### Credits
[Acknowledge reporter if agreed]

### References
- CVE-XXXX-XXXX
- Manufacturer reference: [ID]
```

---

## Documentation Requirements

### Premarket Submission Checklist

```markdown
## Cybersecurity Documentation for Premarket Submission

### Device Description (Tier 1 and 2)
- [ ] Cybersecurity risk level justification
- [ ] Global system diagram
- [ ] Data flow diagram

### Security Risk Management (Tier 1 and 2)
- [ ] Threat model
- [ ] Security risk assessment
- [ ] Traceability matrix

### Security Architecture (Tier 1 and 2)
- [ ] Defense-in-depth description
- [ ] Security controls list
- [ ] Trust boundaries identified

### Testing Documentation
#### Tier 1
- [ ] Penetration test report
- [ ] Vulnerability scan results
- [ ] Fuzz testing results
- [ ] Static code analysis
- [ ] Third-party component testing

#### Tier 2
- [ ] Security testing summary
- [ ] Known vulnerability analysis

### SBOM (Tier 1 and 2)
- [ ] Complete component inventory
- [ ] Known vulnerability assessment
- [ ] Support and update plan

### Vulnerability Management (Tier 1 and 2)
- [ ] Vulnerability handling policy
- [ ] Coordinated disclosure process
- [ ] Security update plan

### Labeling (Tier 1 and 2)
- [ ] User security instructions
- [ ] End-of-support date
- [ ] Security contact information
```

### Recommended File Structure

```
Cybersecurity_Documentation/
├── 01_Executive_Summary.pdf
├── 02_Device_Description/
│   ├── System_Diagram.pdf
│   └── Data_Flow_Diagram.pdf
├── 03_Security_Risk_Assessment/
│   ├── Threat_Model.pdf
│   ├── Risk_Assessment.pdf
│   └── Traceability_Matrix.xlsx
├── 04_Security_Architecture/
│   ├── Architecture_Description.pdf
│   ├── Security_Controls.pdf
│   └── Trust_Boundary_Analysis.pdf
├── 05_Security_Testing/
│   ├── Penetration_Test_Report.pdf
│   ├── Vulnerability_Scan_Results.pdf
│   ├── Fuzz_Testing_Report.pdf
│   └── Code_Analysis_Report.pdf
├── 06_SBOM/
│   ├── SBOM.xml (CycloneDX)
│   └── Vulnerability_Analysis.pdf
├── 07_Vulnerability_Management/
│   ├── Vulnerability_Policy.pdf
│   └── Disclosure_Process.pdf
└── 08_Labeling/
    └── Security_Instructions.pdf
```

---

## Quick Reference

### Common Cybersecurity Deficiencies

| Deficiency | Resolution |
|------------|------------|
| Incomplete threat model | Document all entry points, assets, threats |
| No SBOM provided | Generate using automated tools |
| Weak authentication | Implement MFA, strong passwords |
| Missing encryption | Add TLS 1.2+, AES-256 |
| No vulnerability management plan | Create monitoring and response procedures |
| Insufficient testing | Conduct penetration testing |

### Security Testing Requirements

| Test Type | Tier 1 | Tier 2 | Tools |
|-----------|--------|--------|-------|
| Penetration testing | Required | Recommended | Manual + automated |
| Vulnerability scanning | Required | Required | Nessus, OpenVAS |
| Fuzz testing | Required | Recommended | AFL, Peach |
| Static analysis | Required | Recommended | SonarQube, Coverity |
| Dynamic analysis | Required | Recommended | Burp Suite, ZAP |

### Recognized Standards Mapping

| FDA Requirement | IEC 62443 | NIST CSF |
|-----------------|-----------|----------|
| Threat modeling | SR 3 | ID.RA |
| Access control | SR 1, SR 2 | PR.AC |
| Encryption | SR 4 | PR.DS |
| Audit logging | SR 6 | PR.PT, DE.AE |
| Patch management | SR 7 | PR.MA |
| Incident response | SR 6 | RS.RP |


path: references/fda_capa_requirements.md
content: # FDA CAPA Requirements

Complete guide to Corrective and Preventive Action requirements per 21 CFR 820.100.

---

## Table of Contents

- [CAPA Regulation Overview](#capa-regulation-overview)
- [CAPA Sources](#capa-sources)
- [CAPA Process](#capa-process)
- [Root Cause Analysis](#root-cause-analysis)
- [Action Implementation](#action-implementation)
- [Effectiveness Verification](#effectiveness-verification)
- [Documentation Requirements](#documentation-requirements)
- [FDA Inspection Focus Areas](#fda-inspection-focus-areas)

---

## CAPA Regulation Overview

### 21 CFR 820.100 Requirements

```
§820.100 Corrective and preventive action

(a) Each manufacturer shall establish and maintain procedures for
implementing corrective and preventive action. The procedures shall
include requirements for:

(1) Analyzing processes, work operations, concessions, quality audit
    reports, quality records, service records, complaints, returned
    product, and other sources of quality data to identify existing
    and potential causes of nonconforming product, or other quality
    problems.

(2) Investigating the cause of nonconformities relating to product,
    processes, and the quality system.

(3) Identifying the action(s) needed to correct and prevent recurrence
    of nonconforming product and other quality problems.

(4) Verifying or validating the corrective and preventive action to
    ensure that such action is effective and does not adversely affect
    the finished device.

(5) Implementing and recording changes in methods and procedures needed
    to correct and prevent identified quality problems.

(6) Ensuring that information related to quality problems or nonconforming
    product is disseminated to those directly responsible for assuring
    the quality of such product or the prevention of such problems.

(7) Submitting relevant information on identified quality problems, as
    well as corrective and preventive actions, for management review.
```

### Definitions

| Term | Definition |
|------|------------|
| **Correction** | Action to eliminate a detected nonconformity |
| **Corrective Action** | Action to eliminate the cause of a detected nonconformity to prevent recurrence |
| **Preventive Action** | Action to eliminate the cause of a potential nonconformity to prevent occurrence |
| **Root Cause** | The fundamental reason for the occurrence of a problem |
| **Effectiveness** | Confirmation that actions achieved intended results |

### CAPA vs. Correction

```
Problem Detected
    ├── Correction (Immediate)
    │   └── Fix the immediate issue
    │       Example: Replace defective part
    │
    └── CAPA (Systemic)
        └── Address root cause
            Example: Fix process that caused defect
```

---

## CAPA Sources

### Data Sources for CAPA Input

**Internal Sources:**
- Nonconforming product reports (NCRs)
- Internal audit findings
- Process deviations
- Manufacturing data trends
- Equipment failures
- Employee observations
- Training deficiencies

**External Sources:**
- Customer complaints
- Service records
- Returned product
- Regulatory feedback (483s, warning letters)
- Adverse event reports (MDRs)
- Field safety corrective actions

### CAPA Threshold Criteria

**Mandatory CAPA Triggers:**

| Source | Threshold |
|--------|-----------|
| Audit findings | All major/critical findings |
| Customer complaints | Any safety-related |
| NCRs | Recurring (3+ occurrences) |
| Regulatory feedback | All observations |
| MDR/vigilance | All reportable events |

**Discretionary CAPA Evaluation:**

| Source | Consideration |
|--------|---------------|
| Trend data | Statistical significance |
| Process deviations | Impact assessment |
| Minor audit findings | Risk-based |
| Supplier issues | Frequency and severity |

### Trend Analysis

**Statistical Process Control:**

```markdown
## Monthly CAPA Trend Review

### Complaint Trending
- [ ] Complaints by product
- [ ] Complaints by failure mode
- [ ] Geographic distribution
- [ ] Customer type analysis

### NCR Trending
- [ ] NCRs by product/process
- [ ] NCRs by cause code
- [ ] NCRs by supplier
- [ ] Scrap/rework rates

### Threshold Monitoring
| Metric | Threshold | Current | Status |
|--------|-----------|---------|--------|
| Complaints/month | <10 | | |
| NCR rate | <2% | | |
| Recurring issues | 0 | | |
```

---

## CAPA Process

### CAPA Workflow

```
1. Initiation
   ├── Problem identification
   ├── Initial assessment
   └── CAPA determination

2. Investigation
   ├── Data collection
   ├── Root cause analysis
   └── Impact assessment

3. Action Planning
   ├── Correction (if applicable)
   ├── Corrective action
   └── Preventive action

4. Implementation
   ├── Execute actions
   ├── Document changes
   └── Train affected personnel

5. Verification
   ├── Verify implementation
   ├── Validate effectiveness
   └── Monitor for recurrence

6. Closure
   ├── Management approval
   ├── Final documentation
   └── Trend data update
```

### CAPA Form Template

```markdown
## CAPA Record

### Section 1: Identification
CAPA Number: ________________
Initiated By: ________________
Date Initiated: ______________
Priority: ☐ Critical ☐ Major ☐ Minor

Source:
☐ Audit Finding     ☐ Complaint        ☐ NCR
☐ Service Record    ☐ MDR              ☐ Trend Data
☐ Regulatory        ☐ Other: ____________

### Section 2: Problem Description
Products Affected: _______________________
Processes Affected: _____________________
Quantity/Scope: _________________________

Problem Statement:
[Clear, specific description of the nonconformity or potential problem]

### Section 3: Immediate Correction
Correction Taken: _______________________
Date Completed: _________________________
Verified By: ____________________________

### Section 4: Investigation
Investigation Lead: _____________________
Investigation Start Date: _______________

Data Collected:
☐ Complaint records      ☐ Production records
☐ Test data              ☐ Training records
☐ Process documentation  ☐ Supplier data

Root Cause Analysis Method:
☐ 5 Whys    ☐ Fishbone    ☐ Fault Tree    ☐ Other

Root Cause Statement:
[Specific, factual statement of the root cause]

Contributing Factors:
1. _____________________________________
2. _____________________________________

### Section 5: Action Plan

#### Corrective Actions
| Action | Owner | Target Date | Status |
|--------|-------|-------------|--------|
|        |       |             |        |

#### Preventive Actions
| Action | Owner | Target Date | Status |
|--------|-------|-------------|--------|
|        |       |             |        |

### Section 6: Verification
Verification Method: ____________________
Verification Criteria: __________________
Verification Date: _____________________
Verified By: ___________________________

Verification Results:
☐ Actions implemented as planned
☐ No adverse effects identified
☐ Documentation updated

### Section 7: Effectiveness Review
Effectiveness Review Date: ______________
Review Period: ________________________
Reviewer: _____________________________

Effectiveness Criteria:
[Specific, measurable criteria for success]

Results:
☐ Effective - problem has not recurred
☐ Not Effective - additional action required

Evidence:
[Reference to data showing effectiveness]

### Section 8: Closure
Closure Date: _________________________
Approved By: __________________________

Management Review Submitted: ☐ Yes ☐ No
Date: ________________________________
```

---

## Root Cause Analysis

### 5 Whys Technique

**Example: Device Fails Final Test**

```
Problem: 5% of devices fail functional test at final inspection

Why 1: Component X is out of tolerance
Why 2: Component X was accepted at incoming inspection
Why 3: Incoming inspection sampling missed defective lot
Why 4: Sampling plan inadequate for component criticality
Why 5: Risk classification of component not updated after design change

Root Cause: Risk classification process did not include design change trigger
```

**5 Whys Template:**

```markdown
## 5 Whys Analysis

Problem Statement: _________________________________

Why 1: _____________________________________________
Evidence: __________________________________________

Why 2: _____________________________________________
Evidence: __________________________________________

Why 3: _____________________________________________
Evidence: __________________________________________

Why 4: _____________________________________________
Evidence: __________________________________________

Why 5: _____________________________________________
Evidence: __________________________________________

Root Cause: ________________________________________

Verification: How do we know this is the root cause?
________________________________________________
```

### Fishbone (Ishikawa) Diagram

**Categories for Medical Device Manufacturing:**

```
                    ┌─────────────────────────────────────────┐
                    │              PROBLEM                     │
                    └─────────────────────────────────────────┘
                                       ▲
           ┌───────────────────────────┼───────────────────────────┐
           │                           │                           │
    ┌──────┴──────┐             ┌──────┴──────┐             ┌──────┴──────┐
    │  PERSONNEL  │             │   METHODS   │             │  MATERIALS  │
    │             │             │             │             │             │
    │ • Training  │             │ • SOP gaps  │             │ • Supplier  │
    │ • Skills    │             │ • Process   │             │ • Specs     │
    │ • Attention │             │ • Sequence  │             │ • Storage   │
    └─────────────┘             └─────────────┘             └─────────────┘
           │                           │                           │
           └───────────────────────────┼───────────────────────────┘
                                       │
    ┌──────────────┐            ┌──────┴──────┐            ┌──────────────┐
    │  MEASUREMENT │            │  EQUIPMENT  │            │ ENVIRONMENT  │
    │              │            │             │            │              │
    │ • Calibration│            │ • Maintenance│           │ • Temperature│
    │ • Method     │            │ • Capability │           │ • Humidity   │
    │ • Accuracy   │            │ • Tooling   │            │ • Cleanliness│
    └──────────────┘            └─────────────┘            └──────────────┘
```

### Fault Tree Analysis

**For Complex Failures:**

```
                    Top Event: Device Failure
                              │
              ┌───────────────┼───────────────┐
              │               │               │
           AND/OR          AND/OR          AND/OR
              │               │               │
        ┌─────┴─────┐   ┌─────┴─────┐   ┌─────┴─────┐
        │ Component │   │  Software │   │   User    │
        │  Failure  │   │  Failure  │   │   Error   │
        └─────┬─────┘   └─────┬─────┘   └─────┬─────┘
              │               │               │
         Basic Events    Basic Events    Basic Events
```

### Root Cause Categories

| Category | Examples | Evidence Sources |
|----------|----------|------------------|
| Design | Specification error, tolerance stack-up | DHF, design review records |
| Process | Procedure inadequate, sequence error | Process validation, work instructions |
| Personnel | Training gap, human error | Training records, interviews |
| Equipment | Calibration drift, maintenance | Calibration records, logs |
| Material | Supplier quality, storage | Incoming inspection, COCs |
| Environment | Temperature, contamination | Environmental monitoring |
| Management | Resource allocation, priorities | Management review records |

---

## Action Implementation

### Corrective Action Requirements

**Effective Corrective Actions:**
1. Address identified root cause
2. Are specific and measurable
3. Have assigned ownership
4. Have realistic target dates
5. Consider impact on other processes
6. Include verification method

**Action Types:**

| Type | Description | Example |
|------|-------------|---------|
| Process change | Modify procedure or method | Update SOP with additional step |
| Design change | Modify product design | Add tolerance specification |
| Training | Improve personnel capability | Conduct retraining |
| Equipment | Modify or replace equipment | Upgrade inspection equipment |
| Supplier | Address supplier quality | Audit supplier, add requirements |
| Documentation | Improve or add documentation | Create work instruction |

### Change Control Integration

```
CAPA Action Identified
        │
        ▼
Change Request Initiated
        │
        ▼
Impact Assessment
├── Regulatory impact
├── Product impact
├── Process impact
└── Documentation impact
        │
        ▼
Change Approved
        │
        ▼
Implementation
├── Document updates
├── Training
├── Validation (if required)
└── Effective date
        │
        ▼
CAPA Verification
```

### Training Requirements

**When Training is Required:**
- New or revised procedures
- New equipment or tools
- Process changes
- Findings related to personnel performance

**Training Documentation:**

```markdown
## CAPA-Related Training Record

CAPA Number: _______________
Training Subject: ___________
Training Date: ______________
Trainer: ___________________

Attendees:
| Name | Signature | Date |
|------|-----------|------|
|      |           |      |

Training Content:
- [ ] Root cause explanation
- [ ] Process/procedure changes
- [ ] New requirements
- [ ] Competency verification

Competency Verified By: _______________
Date: _______________
```

---

## Effectiveness Verification

### Verification vs. Validation

| Verification | Validation |
|--------------|------------|
| Actions implemented correctly | Actions achieved intended results |
| Short-term check | Long-term monitoring |
| Process-focused | Outcome-focused |

### Effectiveness Criteria

**SMART Criteria:**
- **S**pecific: Clearly defined outcome
- **M**easurable: Quantifiable metrics
- **A**chievable: Realistic expectations
- **R**elevant: Related to root cause
- **T**ime-bound: Defined monitoring period

**Examples:**

| Problem | Root Cause | Action | Effectiveness Criteria |
|---------|------------|--------|----------------------|
| 5% test failures | Inadequate sampling | Increase sampling | <1% failure rate for 3 months |
| Customer complaints | Unclear instructions | Revise IFU | Zero complaints on topic for 6 months |
| NCRs from supplier | No incoming inspection | Add inspection | Zero supplier NCRs for 90 days |

### Effectiveness Review Template

```markdown
## CAPA Effectiveness Review

CAPA Number: _______________
Review Date: _______________
Reviewer: __________________

### Review Criteria
Original Problem: _________________
Effectiveness Metric: ______________
Success Threshold: ________________
Review Period: ____________________

### Data Analysis
| Period | Metric Value | Threshold | Pass/Fail |
|--------|--------------|-----------|-----------|
| Month 1 |             |           |           |
| Month 2 |             |           |           |
| Month 3 |             |           |           |

### Conclusion
☐ Effective - Criteria met, CAPA may be closed
☐ Partially Effective - Additional monitoring required
☐ Not Effective - Additional actions required

### Evidence
[Reference to supporting data: complaint logs, NCR reports, audit results, etc.]

### Next Steps (if not effective)
___________________________________
___________________________________

### Approval
Reviewer Signature: _______________ Date: _______
Quality Approval: _________________ Date: _______
```

### Monitoring Period Guidelines

| CAPA Type | Minimum Monitoring |
|-----------|-------------------|
| Product quality | 3 production lots or 90 days |
| Process | 3 months of production |
| Complaints | 6 months |
| Audit findings | Until next audit |
| Supplier | 3 lots or 90 days |

---

## Documentation Requirements

### CAPA File Contents

```
CAPA File Structure:
├── CAPA Form (all sections completed)
├── Investigation Records
│   ├── Data collected
│   ├── Root cause analysis worksheets
│   └── Impact assessment
├── Action Documentation
│   ├── Action plans
│   ├── Change requests (if applicable)
│   └── Training records
├── Verification Evidence
│   ├── Implementation verification
│   ├── Effectiveness data
│   └── Trend analysis
└── Closure Documentation
    ├── Closure approval
    └── Management review submission
```

### Record Retention

Per 21 CFR 820.180:
- Records shall be retained for the design and expected life of the device
- Minimum of 2 years from date of release for commercial distribution

**CAPA Record Retention:**
- Retain for lifetime of product + 2 years
- Include all supporting documentation
- Maintain audit trail for changes

### Traceability

**Required Traceability:**
- CAPA to source (complaint, NCR, audit finding)
- CAPA to affected products/lots
- CAPA to corrective actions taken
- CAPA to verification evidence
- CAPA to management review

---

## FDA Inspection Focus Areas

### Common 483 Observations

| Observation | Prevention |
|-------------|------------|
| CAPA not initiated when required | Define clear CAPA triggers |
| Root cause analysis inadequate | Use structured RCA methods |
| Actions don't address root cause | Verify action-cause linkage |
| Effectiveness not verified | Define measurable criteria |
| CAPA not timely | Set and track target dates |
| Trend analysis not performed | Implement monthly trending |
| Management review missing CAPA input | Include in management review agenda |

### Inspection Preparation

**CAPA Readiness Checklist:**

```markdown
## FDA Inspection CAPA Preparation

### Documentation Review
- [ ] All CAPAs have complete documentation
- [ ] No overdue CAPAs
- [ ] Root cause documented with evidence
- [ ] Effectiveness verified and documented
- [ ] All open CAPAs have current status

### Metrics Available
- [ ] CAPA by source
- [ ] CAPA cycle time
- [ ] Overdue CAPA trend
- [ ] Effectiveness rate
- [ ] Recurring issues

### Process Evidence
- [ ] CAPA procedure current
- [ ] Training records complete
- [ ] Trend analysis documented
- [ ] Management review records show CAPA input

### Common Questions Prepared
- How do you initiate a CAPA?
- How do you determine root cause?
- How do you verify effectiveness?
- Show me your overdue CAPAs
- Show me CAPAs from complaints
```

### CAPA Metrics Dashboard

| Metric | Target | Calculation |
|--------|--------|-------------|
| On-time initiation | 100% | CAPAs initiated within 30 days |
| On-time closure | >90% | CAPAs closed by target date |
| Effectiveness rate | >85% | Effective at first review / Total |
| Average cycle time | <90 days | Average days to closure |
| Overdue CAPAs | 0 | CAPAs past target date |
| Recurring issues | <5% | Repeat CAPAs / Total |

---

## Quick Reference

### CAPA Decision Tree

```
Quality Issue Identified
        │
        ▼
Is it an isolated incident?
├── YES → Correction only (document, may not need CAPA)
│         Evaluate for trend
│
└── NO → Is it a systemic issue?
         ├── YES → Initiate CAPA
         │         Determine if Corrective or Preventive
         │
         └── MAYBE → Investigate further
                     Monitor for recurrence
                     May escalate to CAPA
```

### Root Cause vs. Symptom

| Symptom (NOT root cause) | Root Cause (Address this) |
|--------------------------|---------------------------|
| "Operator made error" | Training inadequate for task |
| "Component was defective" | Incoming inspection ineffective |
| "SOP not followed" | SOP unclear or impractical |
| "Equipment malfunctioned" | Maintenance schedule inadequate |
| "Supplier shipped wrong part" | Purchasing requirements unclear |

### Action Effectiveness Verification

| Action Type | Verification Method | Timeframe |
|-------------|---------------------|-----------|
| Procedure change | Audit for compliance | 30-60 days |
| Training | Competency assessment | Immediate |
| Design change | Product testing | Per protocol |
| Supplier action | Incoming inspection data | 3 lots |
| Equipment | Calibration/performance | Per schedule |

### Integration with Other Systems

| System | CAPA Integration Point |
|--------|------------------------|
| Complaints | Trigger for CAPA, complaint closure after CAPA |
| NCR | Trend to CAPA, NCR references CAPA |
| Audit | Findings generate CAPA, CAPA closure audit |
| Design Control | Design change via CAPA, DHF update |
| Supplier | Supplier CAPA, supplier audit findings |
| Risk Management | Risk file update post-CAPA |


path: references/fda_submission_guide.md
content: # FDA Submission Guide

Complete framework for 510(k), De Novo, and PMA submissions to the FDA.

---

## Table of Contents

- [Submission Pathway Selection](#submission-pathway-selection)
- [510(k) Premarket Notification](#510k-premarket-notification)
- [De Novo Classification](#de-novo-classification)
- [PMA Premarket Approval](#pma-premarket-approval)
- [Pre-Submission Program](#pre-submission-program)
- [FDA Review Timeline](#fda-review-timeline)

---

## Submission Pathway Selection

### Decision Matrix

```
Is there a legally marketed predicate device?
├── YES → Is your device substantially equivalent?
│   ├── YES → 510(k) Pathway
│   │   ├── No changes from predicate → Abbreviated 510(k)
│   │   ├── Manufacturing changes only → Special 510(k)
│   │   └── Design/performance changes → Traditional 510(k)
│   └── NO → PMA or De Novo
└── NO → Is it a novel low-to-moderate risk device?
    ├── YES → De Novo Classification Request
    └── NO → PMA Pathway (Class III)
```

### Classification Determination

| Class | Risk Level | Pathway | Examples |
|-------|------------|---------|----------|
| I | Low | Exempt or 510(k) | Bandages, stethoscopes |
| II | Moderate | 510(k) | Powered wheelchairs, pregnancy tests |
| III | High | PMA | Pacemakers, heart valves |

### Predicate Device Search

**Database Sources:**
1. FDA 510(k) Database: https://www.accessdata.fda.gov/scripts/cdrh/cfdocs/cfpmn/pmn.cfm
2. FDA Product Classification Database
3. FDA PMA Database
4. FDA De Novo Database

**Search Criteria:**
- Product code (3-letter code)
- Device name keywords
- Intended use similarity
- Technological characteristics

---

## 510(k) Premarket Notification

### Required Sections (21 CFR 807.87)

#### 1. Administrative Information

```
Cover Letter
├── Submission type (Traditional/Special/Abbreviated)
├── Device name and classification
├── Predicate device(s) identification
├── Contact information
└── Signature of authorized representative

CDRH Premarket Review Submission Cover Sheet (FDA Form 3514)
├── Section A: Applicant Information
├── Section B: Device Information
├── Section C: Submission Information
└── Section D: Truth and Accuracy Statement
```

#### 2. Device Description

| Element | Required Content |
|---------|------------------|
| Device Name | Trade name, common name, classification name |
| Intended Use | Disease/condition, patient population, use environment |
| Physical Description | Materials, dimensions, components |
| Principles of Operation | How the device achieves intended use |
| Accessories | Included items, optional components |
| Variants/Models | All versions included in submission |

#### 3. Substantial Equivalence Comparison

```
Comparison Table Format:
┌────────────────────┬─────────────────┬─────────────────┐
│ Characteristic     │ Subject Device  │ Predicate       │
├────────────────────┼─────────────────┼─────────────────┤
│ Intended Use       │ [Your device]   │ [Predicate]     │
│ Technological      │                 │                 │
│ Characteristics    │                 │                 │
│ Performance        │                 │                 │
│ Safety             │                 │                 │
└────────────────────┴─────────────────┴─────────────────┘

Substantial Equivalence Argument:
1. Same intended use? YES/NO
2. Same technological characteristics? YES/NO
3. If different technology, does it raise new safety/effectiveness questions? YES/NO
4. Performance data demonstrates equivalence? YES/NO
```

#### 4. Performance Testing

**Bench Testing:**
- Mechanical/structural testing
- Electrical safety (IEC 60601-1 if applicable)
- Biocompatibility (ISO 10993 series)
- Sterilization validation
- Shelf life/stability testing
- Software verification (IEC 62304 if applicable)

**Clinical Data (if required):**
- Clinical study summaries
- Literature review
- Adverse event data

#### 5. Labeling

**Required Elements:**
- Instructions for Use (IFU)
- Device labeling (package, carton)
- Indications for Use statement
- Contraindications, warnings, precautions
- Advertising materials (if applicable)

### 510(k) Acceptance Checklist

```markdown
## Pre-Submission Verification

- [ ] FDA Form 3514 complete and signed
- [ ] User fee payment ($21,760 for FY2024, small business exemptions available)
- [ ] Device description complete
- [ ] Predicate device identified with 510(k) number
- [ ] Substantial equivalence comparison table
- [ ] Indications for Use statement (FDA Form 3881)
- [ ] Performance data summary
- [ ] Labeling (IFU, device labels)
- [ ] 510(k) summary or statement
- [ ] Truthful and Accuracy statement signed
- [ ] Environmental assessment or categorical exclusion
```

---

## De Novo Classification

### Eligibility Criteria

1. Novel device with no legally marketed predicate
2. Low-to-moderate risk (would be Class I or II if predicate existed)
3. General controls alone (Class I) or with special controls (Class II) provide reasonable assurance of safety and effectiveness

### Required Content

#### Risk Assessment

```
Risk Analysis Requirements:
├── Hazard Identification
│   ├── Biological hazards
│   ├── Mechanical hazards
│   ├── Electrical hazards
│   ├── Use-related hazards
│   └── Cybersecurity hazards (if applicable)
├── Risk Estimation
│   ├── Probability of occurrence
│   ├── Severity of harm
│   └── Risk level (High/Medium/Low)
├── Risk Evaluation
│   ├── Acceptability criteria
│   └── Benefit-risk analysis
└── Risk Control Measures
    ├── Design controls
    ├── Protective measures
    └── Information for safety
```

#### Proposed Classification

| Classification | Controls | Rationale |
|----------------|----------|-----------|
| Class I | General controls only | Low risk, general controls adequate |
| Class II | General + Special controls | Moderate risk, special controls needed |

#### Special Controls (for Class II)

Define specific controls such as:
- Performance testing requirements
- Labeling requirements
- Post-market surveillance
- Patient registry
- Design specifications

---

## PMA Premarket Approval

### PMA Application Contents

#### Technical Sections

1. **Device Description and Intended Use**
   - Detailed design specifications
   - Operating principles
   - Complete indications for use

2. **Manufacturing Information**
   - Manufacturing process description
   - Quality system information
   - Facility registration

3. **Nonclinical Laboratory Studies**
   - Bench testing results
   - Animal studies (if applicable)
   - Biocompatibility testing

4. **Clinical Investigation**
   - IDE number and approval date
   - Clinical protocol
   - Clinical study results
   - Statistical analysis
   - Adverse events

5. **Labeling**
   - Complete labeling
   - Patient labeling (if applicable)

#### Clinical Data Requirements

```
Clinical Study Design:
├── Study Objectives
│   ├── Primary endpoint(s)
│   └── Secondary endpoint(s)
├── Study Population
│   ├── Inclusion criteria
│   ├── Exclusion criteria
│   └── Sample size justification
├── Study Design
│   ├── Randomized controlled trial
│   ├── Single-arm study with OPC
│   └── Other design with justification
├── Statistical Analysis Plan
│   ├── Analysis populations
│   ├── Statistical methods
│   └── Handling of missing data
└── Safety Monitoring
    ├── Adverse event definitions
    ├── Stopping rules
    └── DSMB oversight
```

### IDE (Investigational Device Exemption)

**When Required:**
- Significant risk device clinical studies
- Studies not exempt under 21 CFR 812.2

**IDE Application Content:**
- Investigational plan
- Manufacturing information
- Investigator agreements
- IRB approvals
- Informed consent forms
- Labeling
- Risk analysis

---

## Pre-Submission Program

### Q-Submission Types

| Type | Purpose | FDA Response |
|------|---------|--------------|
| Pre-Sub | Feedback on planned submission | Written feedback or meeting |
| Informational | Share information, no feedback | Acknowledgment only |
| Study Risk | Determination of study risk level | Risk determination |
| Agreement/Determination | Binding agreement on specific issue | Formal agreement |

### Pre-Sub Meeting Preparation

```
Pre-Submission Package:
1. Cover letter with meeting request
2. Device description
3. Regulatory history (if any)
4. Proposed submission pathway
5. Specific questions (maximum 5-6)
6. Supporting data/information

Meeting Types:
- Written response only (default)
- Teleconference (90 minutes)
- In-person meeting (90 minutes)
```

### Effective Question Formulation

**Good Question Format:**
```
Question: Does FDA agree that [specific proposal] is acceptable for [specific purpose]?

Background: [Brief context - 1-2 paragraphs]

Proposal: [Your specific proposal - detailed but concise]

Rationale: [Why you believe this is appropriate]
```

**Avoid:**
- Open-ended questions ("What should we do?")
- Multiple questions combined
- Questions already answered in guidance

---

## FDA Review Timeline

### Standard Review Times

| Submission Type | FDA Goal | Typical Range |
|----------------|----------|---------------|
| 510(k) Traditional | 90 days | 90-150 days |
| 510(k) Special | 30 days | 30-60 days |
| 510(k) Abbreviated | 30 days | 30-60 days |
| De Novo | 150 days | 150-300 days |
| PMA | 180 days | 12-24 months |
| Pre-Sub Response | 70-75 days | 60-90 days |

### Review Process Stages

```
510(k) Review Timeline:
Day 0: Submission received
Day 1-15: Acceptance review
├── Accept → Substantive review begins
└── Refuse to Accept (RTA) → 180 days to respond

Day 15-90: Substantive review
├── Additional Information (AI) request stops clock
├── Interactive review may occur
└── Decision by Day 90 goal

Decision:
├── Substantially Equivalent (SE) → Clearance letter
├── Not Substantially Equivalent (NSE) → Appeal or new submission
└── Withdrawn
```

### Additional Information Requests

**Response Best Practices:**
- Respond within 30-60 days
- Use FDA's question numbering
- Provide complete responses
- Include amended sections clearly marked
- Reference specific guidance documents

---

## Submission Best Practices

### Document Formatting

- Use PDF format (PDF/A preferred)
- Bookmarks for each section
- Hyperlinks to cross-references
- Table of contents with page numbers
- Consistent headers/footers

### eSTAR (Electronic Submission Template)

FDA's recommended electronic submission format for 510(k):
- Structured data entry
- Built-in validation
- Automatic formatting
- Reduced RTA rate

### Common Refuse to Accept (RTA) Issues

| Issue | Prevention |
|-------|------------|
| Missing user fee | Verify payment before submission |
| Incomplete Form 3514 | Review all fields, ensure signature |
| Missing predicate | Confirm predicate is legally marketed |
| Inadequate device description | Include all models, accessories |
| Missing Indications for Use | Use FDA Form 3881 |
| Incomplete SE comparison | Address all characteristics |


path: references/hipaa_compliance_framework.md
content: # HIPAA Compliance Framework for Medical Devices

Complete guide to HIPAA requirements for medical device manufacturers and software developers.

---

## Table of Contents

- [HIPAA Overview](#hipaa-overview)
- [Privacy Rule Requirements](#privacy-rule-requirements)
- [Security Rule Requirements](#security-rule-requirements)
- [Medical Device Considerations](#medical-device-considerations)
- [Risk Assessment](#risk-assessment)
- [Implementation Specifications](#implementation-specifications)
- [Business Associate Agreements](#business-associate-agreements)
- [Breach Notification](#breach-notification)

---

## HIPAA Overview

### Applicability to Medical Devices

| Entity Type | HIPAA Applicability |
|-------------|---------------------|
| Healthcare providers | Covered Entity (CE) |
| Health plans | Covered Entity (CE) |
| Healthcare clearinghouses | Covered Entity (CE) |
| Device manufacturers | Business Associate (BA) if handling PHI |
| SaMD developers | Business Associate (BA) if handling PHI |
| Cloud service providers | Business Associate (BA) |

### Protected Health Information (PHI)

**PHI Definition:** Individually identifiable health information transmitted or maintained in any form.

**18 HIPAA Identifiers:**

```
1. Names
2. Geographic data (smaller than state)
3. Dates (except year) related to individual
4. Phone numbers
5. Fax numbers
6. Email addresses
7. Social Security numbers
8. Medical record numbers
9. Health plan beneficiary numbers
10. Account numbers
11. Certificate/license numbers
12. Vehicle identifiers
13. Device identifiers and serial numbers
14. Web URLs
15. IP addresses
16. Biometric identifiers
17. Full face photos
18. Any other unique identifying number
```

### Electronic PHI (ePHI)

PHI that is created, stored, transmitted, or received in electronic form. Most relevant for:
- Connected medical devices
- Medical device software (SaMD)
- Mobile health applications
- Cloud-based healthcare systems

---

## Privacy Rule Requirements

### Minimum Necessary Standard

**Principle:** Limit PHI access, use, and disclosure to the minimum necessary to accomplish the intended purpose.

**Implementation:**
- Role-based access controls
- Access audit logging
- Data segmentation
- Need-to-know policies

### Patient Rights

| Right | Device Implication |
|-------|---------------------|
| Access | Provide mechanism to view/export data |
| Amendment | Allow corrections to patient data |
| Accounting of disclosures | Log all PHI disclosures |
| Restriction requests | Support data sharing restrictions |
| Confidential communications | Secure communication channels |

### Use and Disclosure

**Permitted Uses:**
- Treatment, Payment, Healthcare Operations (TPO)
- With patient authorization
- Public health activities
- Required by law
- Health oversight activities

**Medical Device Context:**
- Device data for treatment: Permitted
- Data analytics by manufacturer: Requires BAA or de-identification
- Research use: Requires authorization or IRB waiver

---

## Security Rule Requirements

### Administrative Safeguards

#### Security Management Process (§164.308(a)(1))

**Required Specifications:**

```markdown
## Security Management Process

### Risk Analysis
- [ ] Identify systems with ePHI
- [ ] Document potential threats and vulnerabilities
- [ ] Assess likelihood and impact
- [ ] Document current controls
- [ ] Determine risk levels

### Risk Management
- [ ] Implement security measures
- [ ] Document residual risk
- [ ] Management approval

### Sanction Policy
- [ ] Define workforce sanctions
- [ ] Document enforcement procedures

### Information System Activity Review
- [ ] Define audit procedures
- [ ] Review logs regularly
- [ ] Document findings
```

#### Workforce Security (§164.308(a)(3))

| Specification | Type | Implementation |
|---------------|------|----------------|
| Authorization/supervision | Addressable | Access approval process |
| Workforce clearance | Addressable | Background checks |
| Termination procedures | Addressable | Access revocation |

#### Information Access Management (§164.308(a)(4))

**Access Control Elements:**
- Access authorization
- Access establishment and modification
- Unique user identification
- Automatic logoff

#### Security Awareness and Training (§164.308(a)(5))

**Training Topics:**
- Security reminders
- Protection from malicious software
- Login monitoring
- Password management

#### Security Incident Procedures (§164.308(a)(6))

**Incident Response Requirements:**
1. Identify and document incidents
2. Report security incidents
3. Respond to mitigate harmful effects
4. Document outcomes

#### Contingency Plan (§164.308(a)(7))

```markdown
## Contingency Plan Components

### Data Backup Plan (Required)
- Backup frequency: _____
- Backup verification: _____
- Off-site storage: _____

### Disaster Recovery Plan (Required)
- Recovery time objective: _____
- Recovery point objective: _____
- Recovery procedures: _____

### Emergency Mode Operation (Required)
- Critical functions: _____
- Manual procedures: _____
- Communication plan: _____

### Testing and Revision (Addressable)
- Test frequency: _____
- Last test date: _____
- Revision history: _____

### Applications and Data Criticality (Addressable)
- Critical systems: _____
- Priority recovery order: _____
```

### Physical Safeguards

#### Facility Access Controls (§164.310(a)(1))

| Specification | Type | Implementation |
|---------------|------|----------------|
| Contingency operations | Addressable | Physical access during emergency |
| Facility security plan | Addressable | Physical access policies |
| Access control/validation | Addressable | Visitor management |
| Maintenance records | Addressable | Physical maintenance logs |

#### Workstation Use (§164.310(b))

**Requirements:**
- Policies for workstation use
- Physical environment considerations
- Secure positioning
- Screen privacy

#### Workstation Security (§164.310(c))

**Physical Safeguards:**
- Cable locks
- Restricted areas
- Surveillance
- Clean desk policy

#### Device and Media Controls (§164.310(d)(1))

**Critical for Medical Devices:**

```markdown
## Device and Media Controls

### Disposal (Required)
- [ ] Wipe procedures for devices with ePHI
- [ ] Certificate of destruction
- [ ] Media sanitization per NIST 800-88

### Media Re-use (Required)
- [ ] Sanitization before re-use
- [ ] Verification of removal
- [ ] Documentation

### Accountability (Addressable)
- [ ] Hardware inventory
- [ ] Movement tracking
- [ ] Responsibility assignment

### Data Backup and Storage (Addressable)
- [ ] Retrievable copies
- [ ] Secure storage location
- [ ] Access controls on backup media
```

### Technical Safeguards

#### Access Control (§164.312(a)(1))

| Specification | Type | Implementation |
|---------------|------|----------------|
| Unique user identification | Required | Individual accounts |
| Emergency access | Required | Break-glass procedures |
| Automatic logoff | Addressable | Session timeout |
| Encryption and decryption | Addressable | At-rest encryption |

#### Audit Controls (§164.312(b))

**Audit Log Contents:**
- User identification
- Event type
- Date and time
- Success/failure
- Affected data

**Medical Device Considerations:**
- Log all access to patient data
- Protect logs from tampering
- Retain logs per policy (minimum 6 years)
- Real-time alerting for critical events

#### Integrity (§164.312(c)(1))

**ePHI Integrity Controls:**
- Hash verification
- Digital signatures
- Version control
- Change detection

#### Person or Entity Authentication (§164.312(d))

**Authentication Methods:**
- Passwords (strong requirements)
- Biometrics
- Hardware tokens
- Multi-factor authentication (recommended)

#### Transmission Security (§164.312(e)(1))

| Specification | Type | Implementation |
|---------------|------|----------------|
| Integrity controls | Addressable | TLS, message authentication |
| Encryption | Addressable | TLS 1.2+, AES-256 |

---

## Medical Device Considerations

### Connected Medical Device Security

**Data Flow Analysis:**

```
Device → Local Network → Internet → Cloud → EHR
  │           │            │         │       │
  └─ ePHI at rest    ePHI in transit    ePHI at rest
     Encrypt          Encrypt TLS       Encrypt + Access Control
```

### SaMD (Software as a Medical Device)

**HIPAA Requirements for SaMD:**
1. Encryption of stored patient data
2. Secure authentication
3. Audit logging
4. Access controls
5. Secure communication protocols
6. Backup and recovery
7. Incident response

### Mobile Medical Applications

**Additional Considerations:**
- Device loss/theft protection
- Remote wipe capability
- App sandboxing
- Secure data storage
- API security

### Cloud-Based Devices

**Cloud Provider Requirements:**
- BAA with cloud provider
- Data residency (US only for HIPAA)
- Encryption key management
- Audit log access
- Incident notification

---

## Risk Assessment

### HIPAA Risk Assessment Process

```
Step 1: Scope Definition
├── Identify systems with ePHI
├── Document data flows
└── Identify business associates

Step 2: Threat Identification
├── Natural threats (fire, flood)
├── Human threats (hackers, insiders)
├── Environmental threats (power, HVAC)
└── Technical threats (malware, system failure)

Step 3: Vulnerability Assessment
├── Administrative controls
├── Physical controls
├── Technical controls
└── Gap analysis

Step 4: Risk Analysis
├── Likelihood assessment
├── Impact assessment
├── Risk level determination
└── Risk prioritization

Step 5: Risk Treatment
├── Accept
├── Mitigate
├── Transfer
└── Avoid

Step 6: Documentation
├── Risk register
├── Risk management plan
└── Remediation tracking
```

### Risk Assessment Template

```markdown
## HIPAA Risk Assessment

### System Information
System Name: _____________________
System Owner: ____________________
Date: ___________________________

### Asset Inventory
| Asset | ePHI Type | Location | Classification |
|-------|-----------|----------|----------------|
|       |           |          |                |

### Threat Analysis
| Threat | Likelihood (1-5) | Impact (1-5) | Risk Score |
|--------|------------------|--------------|------------|
|        |                  |              |            |

### Vulnerability Assessment
| Safeguard Category | Gap Identified | Severity | Remediation |
|--------------------|----------------|----------|-------------|
| Administrative     |                |          |             |
| Physical           |                |          |             |
| Technical          |                |          |             |

### Risk Treatment Plan
| Risk | Treatment | Owner | Timeline | Status |
|------|-----------|-------|----------|--------|
|      |           |       |          |        |

### Approval
Risk Assessment Approved: _______________ Date: _______
Next Assessment Due: _______________
```

---

## Implementation Specifications

### Required vs. Addressable

**Required:** Must be implemented as specified

**Addressable:**
1. Implement as specified, OR
2. Implement alternative measure, OR
3. Not implement if not reasonable and appropriate (document rationale)

### Implementation Status Matrix

| Safeguard | Specification | Type | Status | Evidence |
|-----------|---------------|------|--------|----------|
| §164.308(a)(1)(ii)(A) | Risk analysis | R | ☐ | |
| §164.308(a)(1)(ii)(B) | Risk management | R | ☐ | |
| §164.308(a)(3)(ii)(A) | Authorization/supervision | A | ☐ | |
| §164.308(a)(5)(ii)(A) | Security reminders | A | ☐ | |
| §164.310(a)(2)(i) | Contingency operations | A | ☐ | |
| §164.310(d)(2)(i) | Disposal | R | ☐ | |
| §164.312(a)(2)(i) | Unique user ID | R | ☐ | |
| §164.312(a)(2)(ii) | Emergency access | R | ☐ | |
| §164.312(a)(2)(iv) | Encryption (at rest) | A | ☐ | |
| §164.312(e)(2)(ii) | Encryption (transit) | A | ☐ | |

---

## Business Associate Agreements

### When Required

BAA required when business associate:
- Creates, receives, maintains, or transmits PHI
- Provides services involving PHI use/disclosure

### BAA Requirements

**Required Provisions:**
1. Permitted and required uses of PHI
2. Subcontractor requirements
3. Appropriate safeguards
4. Breach notification
5. Termination provisions
6. Return or destruction of PHI

### Medical Device Manufacturer BAA Template

```markdown
## Business Associate Agreement

This Agreement is entered into as of [Date] between:

COVERED ENTITY: [Healthcare Provider/Plan Name]
BUSINESS ASSOCIATE: [Device Manufacturer Name]

### 1. Definitions
[Standard HIPAA definitions]

### 2. Obligations of Business Associate

Business Associate agrees to:

a) Not use or disclose PHI other than as permitted
b) Use appropriate safeguards to prevent improper use/disclosure
c) Report any security incident or breach
d) Ensure subcontractors agree to same restrictions
e) Make PHI available for individual access
f) Make PHI available for amendment
g) Document and make available disclosures
h) Make internal practices available to HHS
i) Return or destroy PHI at termination

### 3. Permitted Uses and Disclosures

Business Associate may:
a) Use PHI for device operation and maintenance
b) Use PHI for quality improvement
c) De-identify PHI per HIPAA standards
d) Create aggregate data
e) Report to FDA as required

### 4. Security Requirements

Business Associate shall implement:
a) Administrative safeguards per §164.308
b) Physical safeguards per §164.310
c) Technical safeguards per §164.312

### 5. Breach Notification

Business Associate shall:
a) Report breaches within [60 days/contractual period]
b) Provide information for breach notification
c) Mitigate harmful effects

### 6. Term and Termination
[Standard termination provisions]

### Signatures

COVERED ENTITY: _________________ Date: _______
BUSINESS ASSOCIATE: _____________ Date: _______
```

---

## Breach Notification

### Breach Definition

**Breach:** Acquisition, access, use, or disclosure of unsecured PHI in a manner not permitted that compromises security or privacy.

**Exceptions:**
1. Unintentional acquisition by workforce member acting in good faith
2. Inadvertent disclosure between authorized persons
3. Good faith belief that unauthorized person couldn't retain information

### Risk Assessment for Breach

**Factors to Consider:**
1. Nature and extent of PHI involved
2. Unauthorized person who received PHI
3. Whether PHI was actually acquired/viewed
4. Extent to which risk has been mitigated

### Notification Requirements

| Audience | Timing | Method |
|----------|--------|--------|
| Individuals | 60 days from discovery | First-class mail or email |
| HHS | 60 days (if >500) | HHS breach portal |
| HHS | Annual (if <500) | Annual report |
| Media | 60 days (if >500 in state) | Prominent media outlet |

### Breach Response Procedure

```markdown
## Breach Response Procedure

### Phase 1: Detection and Containment (Immediate)
- [ ] Identify scope of breach
- [ ] Contain breach (stop ongoing access)
- [ ] Preserve evidence
- [ ] Notify incident response team
- [ ] Document timeline

### Phase 2: Investigation (1-14 days)
- [ ] Determine what PHI was involved
- [ ] Identify affected individuals
- [ ] Assess risk of harm
- [ ] Document investigation findings

### Phase 3: Risk Assessment (15-30 days)
- [ ] Apply four-factor risk assessment
- [ ] Determine if notification required
- [ ] Document decision rationale

### Phase 4: Notification (Within 60 days)
- [ ] Prepare individual notification letters
- [ ] Submit to HHS (if required)
- [ ] Media notification (if required)
- [ ] Retain copies of notifications

### Phase 5: Remediation (Ongoing)
- [ ] Implement corrective actions
- [ ] Update policies and procedures
- [ ] Train workforce
- [ ] Monitor for additional impact
```

### Breach Notification Content

**Individual Notification Must Include:**
1. Description of what happened
2. Types of PHI involved
3. Steps individuals should take
4. What entity is doing to investigate
5. What entity is doing to prevent future breaches
6. Contact information for questions

---

## Compliance Checklist

### Administrative Safeguards Checklist

```markdown
## Administrative Safeguards

- [ ] Security Management Process
  - [ ] Risk analysis completed and documented
  - [ ] Risk management plan in place
  - [ ] Sanction policy documented
  - [ ] Information system activity review conducted

- [ ] Assigned Security Responsibility
  - [ ] Security Officer designated
  - [ ] Contact information documented

- [ ] Workforce Security
  - [ ] Authorization procedures
  - [ ] Background checks (if applicable)
  - [ ] Termination procedures

- [ ] Information Access Management
  - [ ] Access authorization policies
  - [ ] Access establishment procedures
  - [ ] Access modification procedures

- [ ] Security Awareness and Training
  - [ ] Training program established
  - [ ] Security reminders distributed
  - [ ] Protection from malicious software training
  - [ ] Password management training

- [ ] Security Incident Procedures
  - [ ] Incident response plan
  - [ ] Incident documentation procedures
  - [ ] Reporting mechanisms

- [ ] Contingency Plan
  - [ ] Data backup plan
  - [ ] Disaster recovery plan
  - [ ] Emergency mode operation plan
  - [ ] Testing and revision procedures
```

### Technical Safeguards Checklist

```markdown
## Technical Safeguards

- [ ] Access Control
  - [ ] Unique user identification
  - [ ] Emergency access procedure
  - [ ] Automatic logoff
  - [ ] Encryption (at rest)

- [ ] Audit Controls
  - [ ] Audit logging implemented
  - [ ] Log review procedures
  - [ ] Log retention policy

- [ ] Integrity
  - [ ] Mechanism to authenticate ePHI
  - [ ] Integrity controls in place

- [ ] Authentication
  - [ ] Person/entity authentication
  - [ ] Strong password policy

- [ ] Transmission Security
  - [ ] Integrity controls (in transit)
  - [ ] Encryption (TLS 1.2+)
```

---

## Quick Reference

### Common HIPAA Violations

| Violation | Prevention |
|-----------|------------|
| Unauthorized access | Role-based access, MFA |
| Lost/stolen devices | Encryption, remote wipe |
| Improper disposal | NIST 800-88 sanitization |
| Insufficient training | Annual training program |
| Missing BAAs | BA inventory and tracking |
| Insufficient audit logs | Comprehensive logging |

### Penalty Structure

| Tier | Knowledge | Per Violation | Annual Maximum |
|------|-----------|---------------|----------------|
| 1 | Unknown | $100-$50,000 | $1,500,000 |
| 2 | Reasonable cause | $1,000-$50,000 | $1,500,000 |
| 3 | Willful neglect (corrected) | $10,000-$50,000 | $1,500,000 |
| 4 | Willful neglect (not corrected) | $50,000 | $1,500,000 |

### FDA-HIPAA Intersection

| Device Scenario | FDA | HIPAA |
|-----------------|-----|-------|
| Standalone diagnostic | 510(k)/PMA | If transmits PHI |
| Connected insulin pump | Class III PMA | Yes (patient data) |
| Wellness app (no diagnosis) | Exempt | If stores PHI |
| EHR-integrated device | May apply | Yes |
| Research device | IDE | IRB may waive |


path: references/qsr_compliance_requirements.md
content: # Quality System Regulation (QSR) Compliance

Complete guide to 21 CFR Part 820 requirements for medical device manufacturers.

---

## Table of Contents

- [QSR Overview](#qsr-overview)
- [Management Responsibility (820.20)](#management-responsibility-82020)
- [Design Controls (820.30)](#design-controls-82030)
- [Document Controls (820.40)](#document-controls-82040)
- [Purchasing Controls (820.50)](#purchasing-controls-82050)
- [Production and Process Controls (820.70-75)](#production-and-process-controls-82070-75)
- [CAPA (820.100)](#capa-820100)
- [Device Master Record (820.181)](#device-master-record-820181)
- [FDA Inspection Readiness](#fda-inspection-readiness)

---

## QSR Overview

### Applicability

The QSR applies to:
- Finished device manufacturers
- Specification developers
- Initial distributors of imported devices
- Contract manufacturers
- Repackagers and relabelers

### Exemptions

| Device Class | Exemption Status |
|--------------|------------------|
| Class I (most) | Exempt from design controls (820.30) |
| Class I (listed) | Fully exempt from QSR |
| Class II | Full QSR compliance |
| Class III | Full QSR compliance |

### QSR Structure

```
21 CFR Part 820 Subparts:
├── A - General Provisions (820.1-5)
├── B - Quality System Requirements (820.20-25)
├── C - Design Controls (820.30)
├── D - Document Controls (820.40)
├── E - Purchasing Controls (820.50)
├── F - Identification and Traceability (820.60-65)
├── G - Production and Process Controls (820.70-75)
├── H - Acceptance Activities (820.80-86)
├── I - Nonconforming Product (820.90)
├── J - Corrective and Preventive Action (820.100)
├── K - Labeling and Packaging Control (820.120-130)
├── L - Handling, Storage, Distribution, Installation (820.140-170)
├── M - Records (820.180-198)
├── N - Servicing (820.200)
└── O - Statistical Techniques (820.250)
```

---

## Management Responsibility (820.20)

### Quality Policy

**Requirements:**
- Documented quality policy
- Objectives for quality
- Commitment to meeting requirements
- Communicated throughout organization

**Quality Policy Template:**

```markdown
## Quality Policy Statement

[Company Name] is committed to designing, manufacturing, and distributing
medical devices that meet customer requirements and applicable regulatory
standards. We achieve this through:

1. Maintaining an effective Quality Management System
2. Continuous improvement of our processes
3. Compliance with 21 CFR Part 820 and applicable standards
4. Training and empowering employees
5. Supplier quality management

Approved by: _______________  Date: _______________
Management Representative
```

### Organization

| Role | Responsibilities | Documentation |
|------|------------------|---------------|
| Management Representative | QMS oversight, FDA liaison | Org chart, job description |
| Quality Manager | Day-to-day QMS operations | Procedures, authority matrix |
| Design Authority | Design control decisions | DHF sign-offs |
| Production Manager | Manufacturing compliance | Process documentation |

### Management Review

**Frequency:** At least annually (more frequently recommended)

**Required Inputs:**
1. Audit results (internal and external)
2. Customer feedback and complaints
3. Process performance metrics
4. Product conformity data
5. CAPA status
6. Changes affecting QMS
7. Recommendations for improvement

**Required Outputs:**
- Decisions on improvement actions
- Resource needs
- Quality objectives updates

**Management Review Agenda Template:**

```markdown
## Management Review Meeting

Date: _______________
Attendees: _______________

### Agenda Items

1. Review of previous action items
2. Quality objectives and metrics
3. Internal audit results
4. Customer complaints summary
5. CAPA status report
6. Supplier quality performance
7. Regulatory updates
8. Resource requirements
9. Improvement opportunities

### Decisions and Actions
| Item | Decision | Owner | Due Date |
|------|----------|-------|----------|
|      |          |       |          |

### Next Review Date: _______________
```

---

## Design Controls (820.30)

### When Required

Design controls are required for:
- Class II devices (most)
- Class III devices (all)
- Class I devices with software
- Class I devices on exemption list exceptions

### Design Control Process Flow

```
Design Input (820.30c)
    ↓
Design Output (820.30d)
    ↓
Design Review (820.30e)
    ↓
Design Verification (820.30f)
    ↓
Design Validation (820.30g)
    ↓
Design Transfer (820.30h)
    ↓
Design Changes (820.30i)
    ↓
Design History File (820.30j)
```

### Design Input Requirements

**Must Include:**
- Intended use and user requirements
- Patient population
- Performance requirements
- Safety requirements
- Regulatory requirements
- Risk management requirements

**Verification Criteria:**
- Complete (all requirements captured)
- Unambiguous (clear interpretation)
- Not conflicting
- Verifiable or validatable

### Design Output Requirements

| Output Type | Examples | Verification Method |
|-------------|----------|---------------------|
| Device specifications | Drawings, BOMs | Inspection, testing |
| Manufacturing specs | Process parameters | Process validation |
| Software specs | Source code, architecture | Software V&V |
| Labeling | IFU, labels | Review against inputs |

**Essential Requirements:**
- Traceable to design inputs
- Contains acceptance criteria
- Identifies critical characteristics

### Design Review

**Review Stages:**
1. Concept review (feasibility)
2. Design input review (requirements complete)
3. Preliminary design review (architecture)
4. Critical design review (detailed design)
5. Final design review (transfer readiness)

**Participants:**
- Representative of each design function
- Other specialists as needed
- Independent reviewers (no direct design responsibility)

**Documentation:**
- Meeting minutes
- Issues identified
- Resolution actions
- Approval signatures

### Design Verification

**Methods:**
- Inspections and measurements
- Bench testing
- Analysis and calculations
- Simulations
- Comparisons to similar designs

**Verification Matrix Template:**

```markdown
| Req ID | Requirement | Verification Method | Pass Criteria | Result |
|--------|-------------|---------------------|---------------|--------|
| REQ-001 | Dimension tolerance | Measurement | ±0.5mm | |
| REQ-002 | Tensile strength | Testing per ASTM | >500 MPa | |
| REQ-003 | Software function | Unit testing | 100% pass | |
```

### Design Validation

**Definition:** Confirmation that device meets user needs and intended uses

**Validation Requirements:**
- Use initial production units (or equivalent)
- Simulated or actual use conditions
- Includes software validation

**Validation Types:**
1. **Bench validation** - Laboratory simulated use
2. **Clinical validation** - Human subjects (may require IDE)
3. **Usability validation** - Human factors testing

### Design Transfer

**Transfer Checklist:**

```markdown
## Design Transfer Verification

- [ ] DMR complete and approved
- [ ] Manufacturing processes validated
- [ ] Training completed
- [ ] Inspection procedures established
- [ ] Supplier qualifications complete
- [ ] Labeling approved
- [ ] Risk analysis updated
- [ ] Regulatory clearance/approval obtained
```

### Design History File (DHF)

**Contents:**
- Design and development plan
- Design input records
- Design output records
- Design review records
- Design verification records
- Design validation records
- Design transfer records
- Design change records
- Risk management file

---

## Document Controls (820.40)

### Document Approval and Distribution

**Requirements:**
- Documents reviewed and approved before use
- Approved documents available at point of use
- Obsolete documents removed or marked
- Changes reviewed and approved

### Document Control Matrix

| Document Type | Author | Reviewer | Approver | Distribution |
|---------------|--------|----------|----------|--------------|
| SOPs | Process owner | QA | Quality Manager | Controlled |
| Work Instructions | Supervisor | QA | Manager | Controlled |
| Forms | QA | QA | Quality Manager | Controlled |
| Drawings | Engineer | Peer | Design Authority | Controlled |

### Change Control

**Change Request Process:**

```
1. Initiate Change Request
   └── Description, justification, impact assessment

2. Technical Review
   └── Engineering, quality, regulatory assessment

3. Change Classification
   ├── Minor: No regulatory impact
   ├── Moderate: May affect compliance
   └── Major: Regulatory submission required

4. Approval
   └── Change Control Board (CCB) or designated authority

5. Implementation
   └── Training, document updates, inventory actions

6. Verification
   └── Confirm change implemented correctly

7. Close Change Request
   └── Documentation complete
```

---

## Purchasing Controls (820.50)

### Supplier Qualification

**Qualification Criteria:**
- Quality system capability
- Product/service quality history
- Financial stability
- Regulatory compliance history

**Qualification Methods:**

| Method | When Used | Documentation |
|--------|-----------|---------------|
| On-site audit | Critical suppliers, high risk | Audit report |
| Questionnaire | Initial screening | Completed form |
| Certification review | ISO certified suppliers | Cert copies |
| Product qualification | Incoming inspection data | Test results |

### Approved Supplier List (ASL)

**ASL Requirements:**
- Supplier name and contact
- Products/services approved
- Qualification date and method
- Qualification status
- Re-evaluation schedule

### Purchasing Data

**Purchase Order Requirements:**
- Complete product specifications
- Quality requirements
- Applicable standards
- Inspection/acceptance requirements
- Right of access for verification

---

## Production and Process Controls (820.70-75)

### Process Validation (820.75)

**When Required:**
- Process output cannot be fully verified
- Deficiencies would only appear after use
- Examples: sterilization, welding, molding

**Validation Protocol Elements:**

```markdown
## Process Validation Protocol

### 1. Protocol Approval
Prepared by: _______________  Date: _______________
Approved by: _______________  Date: _______________

### 2. Process Description
[Describe process, equipment, materials, parameters]

### 3. Acceptance Criteria
| Parameter | Specification | Test Method |
|-----------|---------------|-------------|
|           |               |             |

### 4. Equipment Qualification
- IQ (Installation Qualification): _______________
- OQ (Operational Qualification): _______________
- PQ (Performance Qualification): _______________

### 5. Validation Runs
Number of runs: _____ (minimum 3)
Lot sizes: _____

### 6. Results Summary
| Run | Date | Parameters | Results | Pass/Fail |
|-----|------|------------|---------|-----------|
| 1   |      |            |         |           |
| 2   |      |            |         |           |
| 3   |      |            |         |           |

### 7. Conclusion
Process validated: Yes / No
Revalidation triggers: _____
```

### Environmental Controls (820.70(c))

**Controlled Conditions:**
- Temperature and humidity
- Particulate contamination (cleanrooms)
- ESD (electrostatic discharge)
- Lighting levels

**Monitoring Requirements:**
- Continuous or periodic monitoring
- Documented limits
- Out-of-specification procedures
- Calibrated equipment

### Personnel (820.70(d))

**Training Requirements:**
- Job-specific training
- Competency verification
- Retraining for significant changes
- Training records maintained

**Training Record Template:**

```markdown
## Training Record

Employee: _______________ ID: _______________
Position: _______________

| Training Topic | Trainer | Date | Method | Competency Verified |
|----------------|---------|------|--------|---------------------|
|                |         |      |        | Signature: ________ |
```

### Equipment (820.70(g))

**Requirements:**
- Maintenance schedule
- Calibration program
- Adjustment limits documented
- Inspection before use

### Calibration (820.72)

**Calibration Program Elements:**
1. Equipment identification
2. Calibration frequency
3. Calibration procedures
4. Accuracy requirements
5. Traceability to NIST standards
6. Out-of-tolerance actions

---

## CAPA (820.100)

### CAPA Sources

- Customer complaints
- Nonconforming product
- Audit findings
- Process monitoring
- Returned products
- MDR/Vigilance reports
- Trend analysis

### CAPA Process

```
1. Identification
   └── Problem statement, data collection

2. Investigation
   └── Root cause analysis (5 Whys, Fishbone, etc.)

3. Action Determination
   ├── Correction: Immediate fix
   └── Corrective/Preventive: Address root cause

4. Implementation
   └── Action execution, documentation

5. Verification
   └── Confirm actions completed

6. Effectiveness Review
   └── Problem recurrence check (30-90 days)

7. Closure
   └── Management approval
```

### Root Cause Analysis Tools

**5 Whys Example:**

```
Problem: Device failed during use

Why 1: Component failed
Why 2: Component was out of specification
Why 3: Incoming inspection did not detect
Why 4: Inspection procedure inadequate
Why 5: Procedure not updated for new component

Root Cause: Document control failure - procedure not updated
```

**Fishbone Categories:**
- Man (People)
- Machine (Equipment)
- Method (Process)
- Material
- Measurement
- Environment

### CAPA Metrics

| Metric | Target | Frequency |
|--------|--------|-----------|
| CAPA on-time closure | >90% | Monthly |
| Overdue CAPAs | <5 | Monthly |
| Effectiveness rate | >85% | Quarterly |
| Average days to closure | <60 | Monthly |

---

## Device Master Record (820.181)

### DMR Contents

```
Device Master Record
├── Device specifications
│   ├── Drawings
│   ├── Composition/formulation
│   └── Component specifications
├── Production process specifications
│   ├── Manufacturing procedures
│   ├── Assembly instructions
│   └── Process parameters
├── Quality assurance procedures
│   ├── Acceptance criteria
│   ├── Inspection procedures
│   └── Test methods
├── Packaging and labeling specifications
│   ├── Package drawings
│   ├── Label content
│   └── IFU content
├── Installation, maintenance, servicing procedures
└── Environmental requirements
```

### Device History Record (DHR) - 820.184

**DHR Contents:**
- Dates of manufacture
- Quantity manufactured
- Quantity released for distribution
- Acceptance records
- Primary identification label
- Device identification and control numbers

### Quality System Record (QSR) - 820.186

**QSR Contents:**
- Procedures and changes
- Calibration records
- Distribution records
- Complaint files
- CAPA records
- Audit reports

---

## FDA Inspection Readiness

### Pre-Inspection Preparation

**30-Day Readiness Checklist:**

```markdown
## FDA Inspection Readiness

### Documentation Review
- [ ] Quality manual current
- [ ] SOPs reviewed and approved
- [ ] Training records complete
- [ ] CAPA files complete
- [ ] Complaint files organized
- [ ] DMR/DHR accessible
- [ ] Management review records current

### Facility Review
- [ ] Controlled areas properly identified
- [ ] Equipment calibration current
- [ ] Environmental monitoring records available
- [ ] Storage conditions appropriate
- [ ] Quarantine areas clearly marked

### Personnel Preparation
- [ ] Escort team identified
- [ ] Subject matter experts briefed
- [ ] Front desk/reception notified
- [ ] Conference room reserved
- [ ] FDA credentials verification process

### Record Accessibility
- [ ] Electronic records accessible
- [ ] Backup copies available
- [ ] Audit trail functional
- [ ] Archive records retrievable
```

### During Inspection

**Escort Guidelines:**
1. One designated escort with investigator at all times
2. Answer questions truthfully and concisely
3. Don't volunteer information not requested
4. Request clarification if question unclear
5. Get help from SME for technical questions
6. Document all requests and commitments

**Record Request Tracking:**

| Request # | Date | Document Requested | Provided By | Date Provided |
|-----------|------|-------------------|-------------|---------------|
|           |      |                   |             |               |

### Post-Inspection

**FDA 483 Response:**
- Due within 15 business days
- Address each observation specifically
- Include corrective actions and timeline
- Provide evidence of completion where possible

**Response Format:**

```markdown
## Observation [Number]

### FDA Observation:
[Copy verbatim from Form 483]

### Company Response:

#### Understanding of Observation:
[Demonstrate understanding of the concern]

#### Immediate Correction:
[Actions already taken]

#### Root Cause Analysis:
[Investigation findings]

#### Corrective Actions:
| Action | Responsible | Target Date | Status |
|--------|-------------|-------------|--------|
|        |             |             |        |

#### Preventive Actions:
[Systemic improvements]

#### Verification:
[How effectiveness will be verified]
```

---

## Compliance Metrics Dashboard

### Key Performance Indicators

| Category | Metric | Target | Current |
|----------|--------|--------|---------|
| CAPA | On-time closure rate | >90% | |
| CAPA | Effectiveness rate | >85% | |
| Complaints | Response time (days) | <5 | |
| Training | Compliance rate | 100% | |
| Calibration | On-time rate | 100% | |
| Audit | Findings closure rate | >95% | |
| NCR | Recurring issues | <5% | |
| Supplier | Quality rate | >98% | |

### Trend Analysis

**Monthly Review Items:**
- Complaint trends by product/failure mode
- NCR trends by cause code
- CAPA effectiveness
- Supplier quality
- Production yields
- Customer feedback

---

## Quick Reference

### Common 483 Observations

| Observation | Prevention |
|-------------|------------|
| CAPA not effective | Verify effectiveness before closure |
| Training incomplete | Competency-based training records |
| Document control gaps | Regular procedure reviews |
| Complaint investigation | Thorough, documented investigations |
| Supplier controls weak | Robust qualification and monitoring |
| Validation inadequate | Follow IQ/OQ/PQ protocols |

### Regulatory Cross-References

| QSR Section | ISO 13485 Clause |
|-------------|------------------|
| 820.20 | 5.1, 5.5, 5.6 |
| 820.30 | 7.3 |
| 820.40 | 4.2.4 |
| 820.50 | 7.4 |
| 820.70 | 7.5.1 |
| 820.75 | 7.5.6 |
| 820.100 | 8.5.2, 8.5.3 |


path: scripts/fda_submission_tracker.py
content: #!/usr/bin/env python3
"""
FDA Submission Tracker

Tracks FDA submission status, calculates timelines, and monitors regulatory milestones
for 510(k), De Novo, and PMA submissions.

Usage:
    python fda_submission_tracker.py <project_dir>
    python fda_submission_tracker.py <project_dir> --type 510k
    python fda_submission_tracker.py <project_dir> --json
"""

import argparse
import json
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Any


# FDA review timeline targets (calendar days)
FDA_TIMELINES = {
    "510k_traditional": {
        "acceptance_review": 15,
        "substantive_review": 90,
        "total_goal": 90,
        "ai_response": 180  # Days to respond to Additional Information
    },
    "510k_special": {
        "acceptance_review": 15,
        "substantive_review": 30,
        "total_goal": 30,
        "ai_response": 180
    },
    "510k_abbreviated": {
        "acceptance_review": 15,
        "substantive_review": 30,
        "total_goal": 30,
        "ai_response": 180
    },
    "de_novo": {
        "acceptance_review": 60,
        "substantive_review": 150,
        "total_goal": 150,
        "ai_response": 180
    },
    "pma": {
        "acceptance_review": 45,
        "substantive_review": 180,
        "total_goal": 180,
        "ai_response": 180
    },
    "pma_supplement": {
        "acceptance_review": 15,
        "substantive_review": 180,
        "total_goal": 180,
        "ai_response": 180
    }
}

# Submission milestones by type
MILESTONES = {
    "510k": [
        {"id": "predicate_identified", "name": "Predicate Device Identified", "phase": "planning"},
        {"id": "testing_complete", "name": "Performance Testing Complete", "phase": "preparation"},
        {"id": "documentation_complete", "name": "Submission Documentation Complete", "phase": "preparation"},
        {"id": "submission_sent", "name": "Submission Sent to FDA", "phase": "submission"},
        {"id": "acknowledgment_received", "name": "FDA Acknowledgment Received", "phase": "review"},
        {"id": "acceptance_decision", "name": "Acceptance Review Complete", "phase": "review"},
        {"id": "ai_request", "name": "Additional Information Request", "phase": "review", "optional": True},
        {"id": "ai_response", "name": "AI Response Submitted", "phase": "review", "optional": True},
        {"id": "se_decision", "name": "Substantial Equivalence Decision", "phase": "decision"},
        {"id": "clearance_letter", "name": "510(k) Clearance Letter Received", "phase": "decision"}
    ],
    "de_novo": [
        {"id": "classification_determined", "name": "Classification Determination", "phase": "planning"},
        {"id": "special_controls_defined", "name": "Special Controls Defined", "phase": "preparation"},
        {"id": "risk_assessment_complete", "name": "Risk Assessment Complete", "phase": "preparation"},
        {"id": "testing_complete", "name": "Performance Testing Complete", "phase": "preparation"},
        {"id": "submission_sent", "name": "Submission Sent to FDA", "phase": "submission"},
        {"id": "acknowledgment_received", "name": "FDA Acknowledgment Received", "phase": "review"},
        {"id": "acceptance_decision", "name": "Acceptance Review Complete", "phase": "review"},
        {"id": "ai_request", "name": "Additional Information Request", "phase": "review", "optional": True},
        {"id": "ai_response", "name": "AI Response Submitted", "phase": "review", "optional": True},
        {"id": "classification_decision", "name": "De Novo Classification Decision", "phase": "decision"}
    ],
    "pma": [
        {"id": "ide_approved", "name": "IDE Approval (if required)", "phase": "planning", "optional": True},
        {"id": "clinical_complete", "name": "Clinical Study Complete", "phase": "preparation"},
        {"id": "clinical_report_complete", "name": "Clinical Study Report Complete", "phase": "preparation"},
        {"id": "documentation_complete", "name": "PMA Documentation Complete", "phase": "preparation"},
        {"id": "submission_sent", "name": "PMA Submission Sent to FDA", "phase": "submission"},
        {"id": "acknowledgment_received", "name": "FDA Acknowledgment Received", "phase": "review"},
        {"id": "filing_decision", "name": "Filing Decision", "phase": "review"},
        {"id": "ai_request", "name": "Major Deficiency Letter", "phase": "review", "optional": True},
        {"id": "ai_response", "name": "Deficiency Response Submitted", "phase": "review", "optional": True},
        {"id": "panel_meeting", "name": "Advisory Committee Meeting", "phase": "review", "optional": True},
        {"id": "approval_decision", "name": "PMA Approval Decision", "phase": "decision"}
    ]
}


def find_submission_config(project_dir: Path) -> Optional[Dict]:
    """Find and load submission configuration file."""
    config_paths = [
        project_dir / "fda_submission.json",
        project_dir / "regulatory" / "fda_submission.json",
        project_dir / ".fda" / "submission.json"
    ]

    for config_path in config_paths:
        if config_path.exists():
            try:
                with open(config_path) as f:
                    return json.load(f)
            except json.JSONDecodeError:
                continue

    return None


def calculate_timeline_status(submission_type: str, milestones: Dict[str, str]) -> Dict:
    """Calculate timeline status based on submission type and milestone dates."""
    timeline_config = FDA_TIMELINES.get(submission_type, FDA_TIMELINES["510k_traditional"])

    result = {
        "submission_type": submission_type,
        "timeline_config": timeline_config,
        "status": "not_started",
        "days_elapsed": 0,
        "days_remaining": None,
        "projected_decision_date": None,
        "on_track": None
    }

    # Check if submission has been sent
    if "submission_sent" in milestones:
        try:
            submission_date = datetime.strptime(milestones["submission_sent"], "%Y-%m-%d")
            today = datetime.now()
            result["days_elapsed"] = (today - submission_date).days

            # Check for AI hold
            ai_hold_days = 0
            if "ai_request" in milestones and "ai_response" in milestones:
                ai_request_date = datetime.strptime(milestones["ai_request"], "%Y-%m-%d")
                ai_response_date = datetime.strptime(milestones["ai_response"], "%Y-%m-%d")
                ai_hold_days = (ai_response_date - ai_request_date).days
            elif "ai_request" in milestones and "ai_response" not in milestones:
                ai_request_date = datetime.strptime(milestones["ai_request"], "%Y-%m-%d")
                ai_hold_days = (today - ai_request_date).days
                result["status"] = "ai_hold"

            # Calculate review days (excluding AI hold)
            review_days = result["days_elapsed"] - ai_hold_days

            # Determine status
            if "se_decision" in milestones or "approval_decision" in milestones or "classification_decision" in milestones:
                result["status"] = "complete"
            elif "acceptance_decision" in milestones:
                result["status"] = "substantive_review"
            elif "acknowledgment_received" in milestones:
                result["status"] = "acceptance_review"
            else:
                result["status"] = "submitted"

            # Calculate projected decision date
            if result["status"] not in ["complete", "ai_hold"]:
                goal_days = timeline_config["total_goal"]
                result["days_remaining"] = max(0, goal_days - review_days)
                result["projected_decision_date"] = (submission_date + timedelta(days=goal_days + ai_hold_days)).strftime("%Y-%m-%d")
                result["on_track"] = review_days <= goal_days

        except ValueError:
            pass

    return result


def analyze_milestone_status(submission_type: str, completed_milestones: Dict[str, str]) -> List[Dict]:
    """Analyze milestone completion status."""
    milestone_list = MILESTONES.get(submission_type.split("_")[0], MILESTONES["510k"])

    results = []
    for milestone in milestone_list:
        status = {
            "id": milestone["id"],
            "name": milestone["name"],
            "phase": milestone["phase"],
            "optional": milestone.get("optional", False),
            "completed": milestone["id"] in completed_milestones,
            "completion_date": completed_milestones.get(milestone["id"])
        }
        results.append(status)

    return results


def calculate_submission_readiness(project_dir: Path, submission_type: str) -> Dict:
    """Check submission readiness by looking for required documentation."""

    required_docs = {
        "510k": [
            {"name": "Device Description", "patterns": ["device_description*", "device_desc*"]},
            {"name": "Indications for Use", "patterns": ["indications*", "ifu*"]},
            {"name": "Substantial Equivalence", "patterns": ["substantial_equiv*", "se_comparison*", "predicate*"]},
            {"name": "Performance Testing", "patterns": ["performance*", "test_report*", "bench_test*"]},
            {"name": "Biocompatibility", "patterns": ["biocompat*", "iso_10993*"]},
            {"name": "Labeling", "patterns": ["label*", "ifu*", "instructions*"]},
            {"name": "Software Documentation", "patterns": ["software*", "iec_62304*"], "optional": True},
            {"name": "Sterilization Validation", "patterns": ["steriliz*", "sterility*"], "optional": True}
        ],
        "de_novo": [
            {"name": "Device Description", "patterns": ["device_description*", "device_desc*"]},
            {"name": "Risk Assessment", "patterns": ["risk*", "hazard*"]},
            {"name": "Special Controls", "patterns": ["special_control*"]},
            {"name": "Performance Testing", "patterns": ["performance*", "test_report*"]},
            {"name": "Labeling", "patterns": ["label*", "ifu*"]}
        ],
        "pma": [
            {"name": "Device Description", "patterns": ["device_description*"]},
            {"name": "Manufacturing Information", "patterns": ["manufacturing*", "production*"]},
            {"name": "Clinical Study Report", "patterns": ["clinical*", "csr*"]},
            {"name": "Nonclinical Testing", "patterns": ["nonclinical*", "bench*", "preclinical*"]},
            {"name": "Risk Analysis", "patterns": ["risk*", "fmea*"]},
            {"name": "Labeling", "patterns": ["label*", "ifu*"]}
        ]
    }

    docs_to_check = required_docs.get(submission_type.split("_")[0], required_docs["510k"])

    # Search common documentation directories
    doc_dirs = [
        project_dir / "regulatory",
        project_dir / "regulatory" / "fda",
        project_dir / "docs",
        project_dir / "documentation",
        project_dir / "dhf",
        project_dir
    ]

    results = []
    for doc in docs_to_check:
        found = False
        found_path = None

        for doc_dir in doc_dirs:
            if not doc_dir.exists():
                continue

            for pattern in doc["patterns"]:
                matches = list(doc_dir.glob(f"**/{pattern}"))
                matches.extend(list(doc_dir.glob(f"**/{pattern.upper()}")))
                if matches:
                    found = True
                    found_path = str(matches[0].relative_to(project_dir))
                    break

            if found:
                break

        results.append({
            "name": doc["name"],
            "required": not doc.get("optional", False),
            "found": found,
            "path": found_path
        })

    required_found = sum(1 for r in results if r["required"] and r["found"])
    required_total = sum(1 for r in results if r["required"])

    return {
        "documents": results,
        "required_complete": required_found,
        "required_total": required_total,
        "readiness_percentage": round((required_found / required_total) * 100, 1) if required_total > 0 else 0
    }


def generate_sample_config() -> Dict:
    """Generate sample submission configuration."""
    return {
        "submission_type": "510k_traditional",
        "device_name": "Example Medical Device",
        "product_code": "ABC",
        "predicate_device": {
            "name": "Predicate Device Name",
            "k_number": "K123456"
        },
        "milestones": {
            "predicate_identified": "2024-01-15",
            "testing_complete": "2024-03-01",
            "documentation_complete": "2024-03-15"
        },
        "contacts": {
            "regulatory_lead": "Name",
            "quality_lead": "Name"
        },
        "notes": "Add milestone dates as they are completed"
    }


def print_text_report(result: Dict) -> None:
    """Print human-readable report."""
    print("=" * 60)
    print("FDA SUBMISSION TRACKER REPORT")
    print("=" * 60)

    if "error" in result:
        print(f"\nError: {result['error']}")
        print(f"\nTo create a configuration file, run with --init")
        return

    # Basic info
    print(f"\nDevice: {result.get('device_name', 'Unknown')}")
    print(f"Submission Type: {result['submission_type']}")
    print(f"Product Code: {result.get('product_code', 'N/A')}")

    # Timeline status
    timeline = result["timeline_status"]
    print(f"\n--- Timeline Status ---")
    print(f"Status: {timeline['status'].upper()}")
    print(f"Days Elapsed: {timeline['days_elapsed']}")
    if timeline["days_remaining"] is not None:
        print(f"Days Remaining (FDA goal): {timeline['days_remaining']}")
    if timeline["projected_decision_date"]:
        print(f"Projected Decision Date: {timeline['projected_decision_date']}")
    if timeline["on_track"] is not None:
        status = "ON TRACK" if timeline["on_track"] else "BEHIND SCHEDULE"
        print(f"Timeline Status: {status}")

    # Milestones
    print(f"\n--- Milestones ---")
    for ms in result["milestones"]:
        status = "[X]" if ms["completed"] else "[ ]"
        optional = " (optional)" if ms["optional"] else ""
        date = f" - {ms['completion_date']}" if ms["completion_date"] else ""
        print(f"  {status} {ms['name']}{optional}{date}")

    # Readiness
    if "readiness" in result:
        print(f"\n--- Submission Readiness ---")
        readiness = result["readiness"]
        print(f"Readiness: {readiness['readiness_percentage']}% ({readiness['required_complete']}/{readiness['required_total']} required docs)")

        print("\n  Documents:")
        for doc in readiness["documents"]:
            status = "[X]" if doc["found"] else "[ ]"
            req = "(required)" if doc["required"] else "(optional)"
            path = f" - {doc['path']}" if doc["path"] else ""
            print(f"    {status} {doc['name']} {req}{path}")

    # Recommendations
    if result.get("recommendations"):
        print(f"\n--- Recommendations ---")
        for i, rec in enumerate(result["recommendations"], 1):
            print(f"  {i}. {rec}")

    print("\n" + "=" * 60)


def generate_recommendations(result: Dict) -> List[str]:
    """Generate actionable recommendations based on status."""
    recommendations = []

    timeline = result["timeline_status"]

    # Timeline recommendations
    if timeline["status"] == "ai_hold":
        recommendations.append("Priority: Respond to FDA Additional Information request within 180 days")
    elif timeline["on_track"] is False:
        recommendations.append("Warning: Submission is behind FDA review schedule - consider contacting FDA")

    # Milestone recommendations
    completed_phases = set()
    for ms in result["milestones"]:
        if ms["completed"]:
            completed_phases.add(ms["phase"])

    if "submission" not in completed_phases and "preparation" in completed_phases:
        recommendations.append("Ready for submission: Documentation complete, proceed with FDA submission")

    # Readiness recommendations
    if "readiness" in result:
        missing_required = [d for d in result["readiness"]["documents"] if d["required"] and not d["found"]]
        if missing_required:
            docs = ", ".join(d["name"] for d in missing_required[:3])
            recommendations.append(f"Missing required documentation: {docs}")

    return recommendations


def analyze_submission(project_dir: Path, submission_type: Optional[str] = None) -> Dict:
    """Main analysis function."""

    # Try to find existing configuration
    config = find_submission_config(project_dir)

    if config is None:
        # No config found - do basic analysis
        sub_type = submission_type or "510k_traditional"
        result = {
            "submission_type": sub_type,
            "config_found": False,
            "timeline_status": calculate_timeline_status(sub_type, {}),
            "milestones": analyze_milestone_status(sub_type, {}),
            "readiness": calculate_submission_readiness(project_dir, sub_type)
        }
    else:
        # Config found - full analysis
        sub_type = config.get("submission_type", submission_type or "510k_traditional")
        milestones = config.get("milestones", {})

        result = {
            "submission_type": sub_type,
            "device_name": config.get("device_name"),
            "product_code": config.get("product_code"),
            "predicate_device": config.get("predicate_device"),
            "config_found": True,
            "timeline_status": calculate_timeline_status(sub_type, milestones),
            "milestones": analyze_milestone_status(sub_type, milestones),
            "readiness": calculate_submission_readiness(project_dir, sub_type)
        }

    # Generate recommendations
    result["recommendations"] = generate_recommendations(result)

    return result


def main():
    parser = argparse.ArgumentParser(
        description="FDA Submission Tracker - Monitor 510(k), De Novo, and PMA submissions"
    )
    parser.add_argument(
        "project_dir",
        nargs="?",
        default=".",
        help="Project directory to analyze (default: current directory)"
    )
    parser.add_argument(
        "--type",
        choices=["510k", "510k_traditional", "510k_special", "510k_abbreviated",
                 "de_novo", "pma", "pma_supplement"],
        help="Submission type (overrides config file)"
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output in JSON format"
    )
    parser.add_argument(
        "--init",
        action="store_true",
        help="Create sample configuration file"
    )

    args = parser.parse_args()
    project_dir = Path(args.project_dir).resolve()

    if not project_dir.exists():
        print(f"Error: Directory not found: {project_dir}", file=sys.stderr)
        sys.exit(1)

    if args.init:
        config_path = project_dir / "fda_submission.json"
        if config_path.exists():
            print(f"Configuration file already exists: {config_path}")
            sys.exit(1)

        sample = generate_sample_config()
        if args.type:
            sample["submission_type"] = args.type

        with open(config_path, "w") as f:
            json.dump(sample, f, indent=2)

        print(f"Created sample configuration: {config_path}")
        print("Edit this file with your submission details and milestone dates.")
        return

    result = analyze_submission(project_dir, args.type)

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print_text_report(result)


if __name__ == "__main__":
    main()


path: scripts/hipaa_risk_assessment.py
content: #!/usr/bin/env python3
"""
HIPAA Risk Assessment Tool

Evaluates HIPAA compliance for medical device software and connected devices
by analyzing code and documentation for security safeguards.

Usage:
    python hipaa_risk_assessment.py <project_dir>
    python hipaa_risk_assessment.py <project_dir> --category technical
    python hipaa_risk_assessment.py <project_dir> --json
"""

import argparse
import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any, Tuple


# HIPAA Security Rule safeguards
HIPAA_SAFEGUARDS = {
    "administrative": {
        "title": "Administrative Safeguards (§164.308)",
        "controls": {
            "security_management": {
                "title": "Security Management Process",
                "requirement": "Risk analysis, risk management, sanction policy",
                "doc_patterns": ["risk_assessment*", "security_policy*", "sanction*"],
                "code_patterns": [],
                "weight": 10
            },
            "security_officer": {
                "title": "Assigned Security Responsibility",
                "requirement": "Designated security official",
                "doc_patterns": ["security_officer*", "hipaa_officer*", "privacy_officer*"],
                "code_patterns": [],
                "weight": 5
            },
            "workforce_security": {
                "title": "Workforce Security",
                "requirement": "Authorization/supervision, clearance, termination procedures",
                "doc_patterns": ["access_control*", "termination*", "hr_security*"],
                "code_patterns": [],
                "weight": 5
            },
            "access_management": {
                "title": "Information Access Management",
                "requirement": "Access authorization, establishment, modification",
                "doc_patterns": ["access_management*", "role_definition*", "access_control*"],
                "code_patterns": [r"role.*based", r"permission", r"authorization"],
                "weight": 8
            },
            "security_training": {
                "title": "Security Awareness and Training",
                "requirement": "Training program, security reminders",
                "doc_patterns": ["training*", "security_awareness*"],
                "code_patterns": [],
                "weight": 5
            },
            "incident_procedures": {
                "title": "Security Incident Procedures",
                "requirement": "Incident response and reporting",
                "doc_patterns": ["incident*", "breach*", "security_event*"],
                "code_patterns": [r"incident.*report", r"security.*alert", r"breach.*notify"],
                "weight": 8
            },
            "contingency_plan": {
                "title": "Contingency Plan",
                "requirement": "Backup, disaster recovery, emergency mode",
                "doc_patterns": ["contingency*", "disaster_recovery*", "backup*", "dr_plan*"],
                "code_patterns": [r"backup", r"recovery", r"failover"],
                "weight": 8
            },
            "evaluation": {
                "title": "Evaluation",
                "requirement": "Periodic security evaluations",
                "doc_patterns": ["security_audit*", "hipaa_audit*", "compliance_review*"],
                "code_patterns": [],
                "weight": 5
            },
            "baa": {
                "title": "Business Associate Contracts",
                "requirement": "Written contracts with business associates",
                "doc_patterns": ["baa*", "business_associate*", "vendor_agreement*"],
                "code_patterns": [],
                "weight": 5
            }
        }
    },
    "physical": {
        "title": "Physical Safeguards (§164.310)",
        "controls": {
            "facility_access": {
                "title": "Facility Access Controls",
                "requirement": "Physical access procedures and controls",
                "doc_patterns": ["facility_access*", "physical_security*", "access_control*"],
                "code_patterns": [],
                "weight": 5
            },
            "workstation_use": {
                "title": "Workstation Use",
                "requirement": "Policies for workstation use and security",
                "doc_patterns": ["workstation*", "endpoint*", "device_policy*"],
                "code_patterns": [],
                "weight": 3
            },
            "device_media": {
                "title": "Device and Media Controls",
                "requirement": "Disposal, media re-use, accountability",
                "doc_patterns": ["media_disposal*", "device_disposal*", "data_sanitization*"],
                "code_patterns": [r"secure.*delete", r"wipe", r"sanitize"],
                "weight": 5
            }
        }
    },
    "technical": {
        "title": "Technical Safeguards (§164.312)",
        "controls": {
            "access_control": {
                "title": "Access Control",
                "requirement": "Unique user ID, emergency access, auto logoff, encryption",
                "doc_patterns": ["access_control*", "authentication*", "session*"],
                "code_patterns": [
                    r"authentication",
                    r"authorize",
                    r"session.*timeout",
                    r"auto.*logout",
                    r"unique.*id",
                    r"user.*id"
                ],
                "weight": 10
            },
            "audit_controls": {
                "title": "Audit Controls",
                "requirement": "Record and examine activity in systems with ePHI",
                "doc_patterns": ["audit_log*", "access_log*", "security_log*"],
                "code_patterns": [
                    r"audit.*log",
                    r"access.*log",
                    r"log.*access",
                    r"security.*event",
                    r"logger"
                ],
                "weight": 10
            },
            "integrity": {
                "title": "Integrity Controls",
                "requirement": "Mechanism to authenticate ePHI",
                "doc_patterns": ["data_integrity*", "checksum*", "hash*"],
                "code_patterns": [
                    r"checksum",
                    r"hash",
                    r"hmac",
                    r"integrity.*check",
                    r"digital.*signature"
                ],
                "weight": 8
            },
            "authentication": {
                "title": "Person or Entity Authentication",
                "requirement": "Verify identity of person or entity seeking access",
                "doc_patterns": ["authentication*", "identity*", "mfa*", "2fa*"],
                "code_patterns": [
                    r"authenticate",
                    r"mfa",
                    r"two.*factor",
                    r"2fa",
                    r"multi.*factor",
                    r"oauth",
                    r"jwt"
                ],
                "weight": 10
            },
            "transmission_security": {
                "title": "Transmission Security",
                "requirement": "Encryption during transmission",
                "doc_patterns": ["encryption*", "tls*", "ssl*", "transport_security*"],
                "code_patterns": [
                    r"https",
                    r"tls",
                    r"ssl",
                    r"encrypt.*transit",
                    r"secure.*connection"
                ],
                "weight": 10
            }
        }
    }
}

# PHI data patterns to detect in code
PHI_PATTERNS = [
    (r"patient.*name", "Patient Name"),
    (r"ssn|social.*security", "Social Security Number"),
    (r"date.*of.*birth|dob", "Date of Birth"),
    (r"medical.*record", "Medical Record Number"),
    (r"health.*plan", "Health Plan ID"),
    (r"diagnosis|icd.*code", "Diagnosis/ICD Code"),
    (r"prescription|medication", "Medication/Prescription"),
    (r"insurance", "Insurance Information"),
    (r"phone.*number|telephone", "Phone Number"),
    (r"email.*address", "Email Address"),
    (r"address|street|city|zip", "Physical Address"),
    (r"biometric", "Biometric Data")
]

# Security vulnerability patterns (dynamic code execution, hardcoded secrets)
VULNERABILITY_PATTERNS = [
    (r"password.*=.*['\"]", "Hardcoded password"),
    (r"api.*key.*=.*['\"]", "Hardcoded API key"),
    (r"secret.*=.*['\"]", "Hardcoded secret"),
    (r"http://(?!localhost)", "Unencrypted HTTP connection"),
    (r"verify.*=.*False", "SSL verification disabled"),
    (r"dynamic.*code.*execution", "Dynamic code execution risk"),
    (r"disable.*ssl", "SSL disabled"),
    (r"insecure", "Insecure configuration")
]


def scan_documentation(project_dir: Path, patterns: List[str]) -> List[str]:
    """Scan for documentation matching patterns."""
    found = []
    doc_dirs = [
        project_dir / "docs",
        project_dir / "documentation",
        project_dir / "policies",
        project_dir / "compliance",
        project_dir / "hipaa",
        project_dir
    ]

    for doc_dir in doc_dirs:
        if not doc_dir.exists():
            continue

        for pattern in patterns:
            for ext in ["*.md", "*.pdf", "*.docx", "*.doc", "*.txt"]:
                try:
                    for match in doc_dir.glob(f"**/{pattern}{ext}"):
                        rel_path = str(match.relative_to(project_dir))
                        if rel_path not in found:
                            found.append(rel_path)
                except Exception:
                    continue

    return found


def scan_code_patterns(project_dir: Path, patterns: List[str]) -> List[Dict]:
    """Scan source code for patterns."""
    matches = []
    code_extensions = ["*.py", "*.js", "*.ts", "*.java", "*.cs", "*.go", "*.rb"]

    src_dirs = [
        project_dir / "src",
        project_dir / "app",
        project_dir / "lib",
        project_dir
    ]

    for src_dir in src_dirs:
        if not src_dir.exists():
            continue

        for ext in code_extensions:
            try:
                for file_path in src_dir.glob(f"**/{ext}"):
                    # Skip node_modules, venv, etc.
                    if any(skip in str(file_path) for skip in ["node_modules", "venv", ".venv", "__pycache__", ".git"]):
                        continue

                    try:
                        content = file_path.read_text(encoding='utf-8', errors='ignore')
                        for pattern in patterns:
                            if re.search(pattern, content, re.IGNORECASE):
                                rel_path = str(file_path.relative_to(project_dir))
                                matches.append({
                                    "file": rel_path,
                                    "pattern": pattern
                                })
                                break  # One match per file per control is enough
                    except Exception:
                        continue
            except Exception:
                continue

    return matches


def detect_phi_handling(project_dir: Path) -> Dict:
    """Detect potential PHI handling in code."""
    phi_found = []
    code_extensions = ["*.py", "*.js", "*.ts", "*.java", "*.cs", "*.go"]

    for ext in code_extensions:
        try:
            for file_path in project_dir.glob(f"**/{ext}"):
                if any(skip in str(file_path) for skip in ["node_modules", "venv", ".venv", "__pycache__", ".git"]):
                    continue

                try:
                    content = file_path.read_text(encoding='utf-8', errors='ignore')
                    rel_path = str(file_path.relative_to(project_dir))

                    for pattern, phi_type in PHI_PATTERNS:
                        if re.search(pattern, content, re.IGNORECASE):
                            phi_found.append({
                                "file": rel_path,
                                "phi_type": phi_type
                            })
                            break
                except Exception:
                    continue
        except Exception:
            continue

    return {
        "phi_detected": len(phi_found) > 0,
        "files_with_phi": phi_found,
        "phi_types": list(set(p["phi_type"] for p in phi_found))
    }


def detect_security_vulnerabilities(project_dir: Path) -> List[Dict]:
    """Scan for security vulnerabilities."""
    vulnerabilities = []
    code_extensions = ["*.py", "*.js", "*.ts", "*.java", "*.cs", "*.go", "*.yaml", "*.yml", "*.json"]

    for ext in code_extensions:
        try:
            for file_path in project_dir.glob(f"**/{ext}"):
                if any(skip in str(file_path) for skip in ["node_modules", "venv", ".venv", "__pycache__", ".git"]):
                    continue

                try:
                    content = file_path.read_text(encoding='utf-8', errors='ignore')
                    rel_path = str(file_path.relative_to(project_dir))

                    for pattern, vuln_type in VULNERABILITY_PATTERNS:
                        matches = re.findall(pattern, content, re.IGNORECASE)
                        if matches:
                            vulnerabilities.append({
                                "file": rel_path,
                                "vulnerability": vuln_type,
                                "count": len(matches)
                            })
                except Exception:
                    continue
        except Exception:
            continue

    return vulnerabilities


def assess_control(project_dir: Path, control_id: str, control_data: Dict) -> Dict:
    """Assess a single HIPAA control."""
    doc_evidence = scan_documentation(project_dir, control_data["doc_patterns"])
    code_evidence = scan_code_patterns(project_dir, control_data["code_patterns"]) if control_data["code_patterns"] else []

    # Determine compliance status
    has_docs = len(doc_evidence) > 0
    has_code = len(code_evidence) > 0

    if has_docs and (has_code or not control_data["code_patterns"]):
        status = "implemented"
        score = 100
    elif has_docs or has_code:
        status = "partial"
        score = 50
    else:
        status = "gap"
        score = 0

    return {
        "control_id": control_id,
        "title": control_data["title"],
        "requirement": control_data["requirement"],
        "status": status,
        "score": score,
        "weight": control_data["weight"],
        "weighted_score": (score * control_data["weight"]) / 100,
        "documentation": doc_evidence,
        "code_evidence": [e["file"] for e in code_evidence]
    }


def assess_category(project_dir: Path, category_id: str, category_data: Dict) -> Dict:
    """Assess a HIPAA safeguard category."""
    control_results = []
    total_weight = 0
    weighted_score = 0

    for control_id, control_data in category_data["controls"].items():
        result = assess_control(project_dir, control_id, control_data)
        control_results.append(result)
        total_weight += control_data["weight"]
        weighted_score += result["weighted_score"]

    category_score = round((weighted_score / total_weight) * 100, 1) if total_weight > 0 else 0

    return {
        "category": category_id,
        "title": category_data["title"],
        "score": category_score,
        "controls": control_results,
        "compliant": sum(1 for c in control_results if c["status"] == "implemented"),
        "partial": sum(1 for c in control_results if c["status"] == "partial"),
        "gaps": sum(1 for c in control_results if c["status"] == "gap")
    }


def calculate_risk_level(overall_score: float, vulnerabilities: List[Dict], phi_data: Dict) -> Dict:
    """Calculate overall HIPAA risk level."""
    # Base risk from compliance score
    if overall_score >= 80:
        base_risk = "LOW"
        base_score = 1
    elif overall_score >= 60:
        base_risk = "MEDIUM"
        base_score = 2
    elif overall_score >= 40:
        base_risk = "HIGH"
        base_score = 3
    else:
        base_risk = "CRITICAL"
        base_score = 4

    # Adjust for vulnerabilities
    critical_vulns = sum(1 for v in vulnerabilities if "password" in v["vulnerability"].lower() or "secret" in v["vulnerability"].lower())
    if critical_vulns > 0:
        base_score = min(4, base_score + 1)

    # Adjust for PHI handling
    if phi_data["phi_detected"] and base_score < 4:
        base_score = min(4, base_score + 0.5)

    # Map back to risk level
    risk_levels = {1: "LOW", 2: "MEDIUM", 3: "HIGH", 4: "CRITICAL"}
    final_risk = risk_levels.get(int(base_score), "HIGH")

    return {
        "risk_level": final_risk,
        "compliance_score": overall_score,
        "vulnerability_count": len(vulnerabilities),
        "phi_handling_detected": phi_data["phi_detected"]
    }


def generate_recommendations(assessment: Dict) -> List[str]:
    """Generate prioritized recommendations."""
    recommendations = []

    # Technical safeguards first (highest priority for software)
    for cat in assessment["categories"]:
        if cat["category"] == "technical":
            for control in cat["controls"]:
                if control["status"] == "gap":
                    recommendations.append(f"CRITICAL: Implement {control['title']} - {control['requirement']}")
                elif control["status"] == "partial":
                    recommendations.append(f"HIGH: Complete {control['title']} implementation")

    # Administrative safeguards
    for cat in assessment["categories"]:
        if cat["category"] == "administrative":
            for control in cat["controls"]:
                if control["status"] == "gap":
                    recommendations.append(f"MEDIUM: Document {control['title']} procedures")

    # Vulnerabilities
    for vuln in assessment.get("vulnerabilities", [])[:5]:
        recommendations.append(f"SECURITY: Fix {vuln['vulnerability']} in {vuln['file']}")

    return recommendations[:10]  # Top 10


def print_text_report(result: Dict) -> None:
    """Print human-readable report."""
    print("=" * 70)
    print("HIPAA SECURITY RULE COMPLIANCE ASSESSMENT")
    print("=" * 70)

    # Risk summary
    risk = result["risk_assessment"]
    print(f"\nRISK LEVEL: {risk['risk_level']}")
    print(f"Compliance Score: {risk['compliance_score']}%")
    print(f"Vulnerabilities Found: {risk['vulnerability_count']}")
    print(f"PHI Handling Detected: {'Yes' if risk['phi_handling_detected'] else 'No'}")

    # Category scores
    print("\n--- SAFEGUARD CATEGORIES ---")
    for cat in result["categories"]:
        status = "OK" if cat["score"] >= 70 else "NEEDS ATTENTION"
        print(f"  {cat['title']}: {cat['score']}% [{status}]")
        print(f"    Implemented: {cat['compliant']}, Partial: {cat['partial']}, Gaps: {cat['gaps']}")

    # Gaps
    print("\n--- COMPLIANCE GAPS ---")
    gap_count = 0
    for cat in result["categories"]:
        for control in cat["controls"]:
            if control["status"] == "gap":
                gap_count += 1
                print(f"  [{cat['category'].upper()}] {control['title']}")
                print(f"    Requirement: {control['requirement']}")
    if gap_count == 0:
        print("  No critical gaps identified")

    # PHI Detection
    if result["phi_detection"]["phi_detected"]:
        print("\n--- PHI HANDLING DETECTED ---")
        print(f"  PHI Types: {', '.join(result['phi_detection']['phi_types'])}")
        print(f"  Files: {len(result['phi_detection']['files_with_phi'])}")

    # Vulnerabilities
    if result["vulnerabilities"]:
        print("\n--- SECURITY VULNERABILITIES ---")
        for vuln in result["vulnerabilities"][:10]:
            print(f"  - {vuln['vulnerability']}: {vuln['file']}")

    # Recommendations
    if result["recommendations"]:
        print("\n--- RECOMMENDATIONS ---")
        for i, rec in enumerate(result["recommendations"], 1):
            print(f"  {i}. {rec}")

    print("\n" + "=" * 70)
    print(f"Assessment Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print("=" * 70)


def main():
    parser = argparse.ArgumentParser(
        description="HIPAA Risk Assessment Tool for Medical Device Software"
    )
    parser.add_argument(
        "project_dir",
        nargs="?",
        default=".",
        help="Project directory to analyze (default: current directory)"
    )
    parser.add_argument(
        "--category",
        choices=["administrative", "physical", "technical"],
        help="Assess specific safeguard category only"
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output in JSON format"
    )
    parser.add_argument(
        "--detailed",
        action="store_true",
        help="Include detailed evidence in output"
    )

    args = parser.parse_args()
    project_dir = Path(args.project_dir).resolve()

    if not project_dir.exists():
        print(f"Error: Directory not found: {project_dir}", file=sys.stderr)
        sys.exit(1)

    # Filter categories if specific one requested
    categories_to_assess = HIPAA_SAFEGUARDS
    if args.category:
        categories_to_assess = {args.category: HIPAA_SAFEGUARDS[args.category]}

    # Perform assessment
    category_results = []
    total_weight = 0
    weighted_score = 0

    for cat_id, cat_data in categories_to_assess.items():
        cat_result = assess_category(project_dir, cat_id, cat_data)
        category_results.append(cat_result)

        # Calculate weighted average
        cat_weight = sum(c["weight"] for c in cat_data["controls"].values())
        total_weight += cat_weight
        weighted_score += (cat_result["score"] * cat_weight) / 100

    overall_score = round((weighted_score / total_weight) * 100, 1) if total_weight > 0 else 0

    # Additional scans
    phi_detection = detect_phi_handling(project_dir)
    vulnerabilities = detect_security_vulnerabilities(project_dir)

    # Risk assessment
    risk_assessment = calculate_risk_level(overall_score, vulnerabilities, phi_detection)

    result = {
        "project_dir": str(project_dir),
        "assessment_date": datetime.now().isoformat(),
        "overall_score": overall_score,
        "risk_assessment": risk_assessment,
        "categories": category_results if args.detailed else [
            {
                "category": c["category"],
                "title": c["title"],
                "score": c["score"],
                "compliant": c["compliant"],
                "partial": c["partial"],
                "gaps": c["gaps"]
            }
            for c in category_results
        ],
        "phi_detection": phi_detection,
        "vulnerabilities": vulnerabilities,
        "recommendations": []
    }

    result["recommendations"] = generate_recommendations(result)

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print_text_report(result)


if __name__ == "__main__":
    main()


path: scripts/qsr_compliance_checker.py
content: #!/usr/bin/env python3
"""
QSR Compliance Checker

Assesses compliance with 21 CFR Part 820 (Quality System Regulation) by analyzing
project documentation and identifying gaps.

Usage:
    python qsr_compliance_checker.py <project_dir>
    python qsr_compliance_checker.py <project_dir> --section 820.30
    python qsr_compliance_checker.py <project_dir> --json
"""

import argparse
import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any


# QSR sections and requirements
QSR_REQUIREMENTS = {
    "820.20": {
        "title": "Management Responsibility",
        "subsections": {
            "820.20(a)": {
                "title": "Quality Policy",
                "required_evidence": ["quality_policy", "quality_manual", "quality_objectives"],
                "doc_patterns": ["quality_policy*", "quality_manual*", "qms_manual*"],
                "keywords": ["quality policy", "quality objectives", "management commitment"]
            },
            "820.20(b)": {
                "title": "Organization",
                "required_evidence": ["org_chart", "job_descriptions", "authority_matrix"],
                "doc_patterns": ["org_chart*", "organization*", "job_desc*", "authority*"],
                "keywords": ["organizational structure", "responsibility", "authority"]
            },
            "820.20(c)": {
                "title": "Management Review",
                "required_evidence": ["management_review_procedure", "management_review_records"],
                "doc_patterns": ["management_review*", "mgmt_review*", "qmr*"],
                "keywords": ["management review", "review meeting", "quality system effectiveness"]
            }
        }
    },
    "820.30": {
        "title": "Design Controls",
        "subsections": {
            "820.30(a)": {
                "title": "Design and Development Planning",
                "required_evidence": ["design_plan", "development_plan"],
                "doc_patterns": ["design_plan*", "dev_plan*", "development_plan*"],
                "keywords": ["design planning", "development phases", "design milestones"]
            },
            "820.30(b)": {
                "title": "Design Input",
                "required_evidence": ["design_input", "requirements_specification"],
                "doc_patterns": ["design_input*", "requirement*", "srs*", "prs*"],
                "keywords": ["design input", "requirements", "user needs", "intended use"]
            },
            "820.30(c)": {
                "title": "Design Output",
                "required_evidence": ["design_output", "specifications", "drawings"],
                "doc_patterns": ["design_output*", "specification*", "drawing*", "bom*"],
                "keywords": ["design output", "specifications", "acceptance criteria"]
            },
            "820.30(d)": {
                "title": "Design Review",
                "required_evidence": ["design_review_procedure", "design_review_records"],
                "doc_patterns": ["design_review*", "dr_record*", "dr_minutes*"],
                "keywords": ["design review", "review meeting", "design evaluation"]
            },
            "820.30(e)": {
                "title": "Design Verification",
                "required_evidence": ["verification_plan", "verification_results"],
                "doc_patterns": ["verification*", "test_report*", "dv_*"],
                "keywords": ["verification", "testing", "design verification"]
            },
            "820.30(f)": {
                "title": "Design Validation",
                "required_evidence": ["validation_plan", "validation_results"],
                "doc_patterns": ["validation*", "clinical*", "usability*", "val_*"],
                "keywords": ["validation", "user needs", "intended use", "clinical evaluation"]
            },
            "820.30(g)": {
                "title": "Design Transfer",
                "required_evidence": ["transfer_checklist", "transfer_verification"],
                "doc_patterns": ["transfer*", "production_release*"],
                "keywords": ["design transfer", "manufacturing", "production"]
            },
            "820.30(h)": {
                "title": "Design Changes",
                "required_evidence": ["change_control_procedure", "change_records"],
                "doc_patterns": ["change_control*", "ecn*", "eco*", "dcr*"],
                "keywords": ["design change", "change control", "modification"]
            },
            "820.30(i)": {
                "title": "Design History File",
                "required_evidence": ["dhf_index", "dhf"],
                "doc_patterns": ["dhf*", "design_history*"],
                "keywords": ["design history file", "DHF", "design records"]
            }
        }
    },
    "820.40": {
        "title": "Document Controls",
        "subsections": {
            "820.40(a)": {
                "title": "Document Approval and Distribution",
                "required_evidence": ["document_control_procedure"],
                "doc_patterns": ["document_control*", "doc_control*", "sop_document*"],
                "keywords": ["document approval", "document distribution", "controlled documents"]
            },
            "820.40(b)": {
                "title": "Document Changes",
                "required_evidence": ["document_change_procedure", "revision_history"],
                "doc_patterns": ["revision_history*", "document_change*"],
                "keywords": ["document change", "revision", "document modification"]
            }
        }
    },
    "820.50": {
        "title": "Purchasing Controls",
        "subsections": {
            "820.50(a)": {
                "title": "Evaluation of Suppliers",
                "required_evidence": ["supplier_qualification_procedure", "approved_supplier_list"],
                "doc_patterns": ["supplier*", "asl*", "vendor*"],
                "keywords": ["supplier evaluation", "approved supplier", "vendor qualification"]
            },
            "820.50(b)": {
                "title": "Purchasing Data",
                "required_evidence": ["purchasing_procedure", "purchase_order_requirements"],
                "doc_patterns": ["purchas*", "procurement*"],
                "keywords": ["purchasing data", "specifications", "quality requirements"]
            }
        }
    },
    "820.70": {
        "title": "Production and Process Controls",
        "subsections": {
            "820.70(a)": {
                "title": "General Process Controls",
                "required_evidence": ["manufacturing_procedures", "work_instructions"],
                "doc_patterns": ["manufacturing*", "production*", "work_instruction*", "wi_*"],
                "keywords": ["manufacturing process", "production", "process parameters"]
            },
            "820.70(b)": {
                "title": "Production and Process Changes",
                "required_evidence": ["process_change_procedure"],
                "doc_patterns": ["process_change*", "manufacturing_change*"],
                "keywords": ["process change", "production change", "change control"]
            },
            "820.70(c)": {
                "title": "Environmental Control",
                "required_evidence": ["environmental_control_procedure", "monitoring_records"],
                "doc_patterns": ["environmental*", "cleanroom*", "env_monitoring*"],
                "keywords": ["environmental control", "cleanroom", "contamination"]
            },
            "820.70(d)": {
                "title": "Personnel",
                "required_evidence": ["training_procedure", "training_records"],
                "doc_patterns": ["training*", "personnel*", "competency*"],
                "keywords": ["training", "personnel qualification", "competency"]
            },
            "820.70(e)": {
                "title": "Contamination Control",
                "required_evidence": ["contamination_control_procedure"],
                "doc_patterns": ["contamination*", "cleaning*", "hygiene*"],
                "keywords": ["contamination", "cleaning", "hygiene"]
            },
            "820.70(f)": {
                "title": "Buildings",
                "required_evidence": ["facility_requirements"],
                "doc_patterns": ["facility*", "building*"],
                "keywords": ["facility", "buildings", "manufacturing area"]
            },
            "820.70(g)": {
                "title": "Equipment",
                "required_evidence": ["equipment_maintenance_procedure", "maintenance_records"],
                "doc_patterns": ["equipment*", "maintenance*", "preventive_maintenance*"],
                "keywords": ["equipment", "maintenance", "calibration"]
            },
            "820.70(h)": {
                "title": "Manufacturing Material",
                "required_evidence": ["material_handling_procedure"],
                "doc_patterns": ["material*", "handling*", "storage*"],
                "keywords": ["manufacturing material", "handling", "storage"]
            },
            "820.70(i)": {
                "title": "Automated Processes",
                "required_evidence": ["software_validation", "automated_process_validation"],
                "doc_patterns": ["software_val*", "csv*", "automation*"],
                "keywords": ["software validation", "automated", "computer system"]
            }
        }
    },
    "820.72": {
        "title": "Inspection, Measuring, and Test Equipment",
        "subsections": {
            "820.72(a)": {
                "title": "Calibration",
                "required_evidence": ["calibration_procedure", "calibration_records"],
                "doc_patterns": ["calibration*", "cal_*"],
                "keywords": ["calibration", "accuracy", "measurement"]
            },
            "820.72(b)": {
                "title": "Calibration Standards",
                "required_evidence": ["calibration_standards", "traceability_records"],
                "doc_patterns": ["calibration_standard*", "nist*", "traceability*"],
                "keywords": ["calibration standards", "NIST", "traceability"]
            }
        }
    },
    "820.75": {
        "title": "Process Validation",
        "subsections": {
            "820.75(a)": {
                "title": "Process Validation Requirements",
                "required_evidence": ["process_validation_procedure", "validation_protocols"],
                "doc_patterns": ["process_validation*", "pv_*", "validation_protocol*"],
                "keywords": ["process validation", "IQ", "OQ", "PQ"]
            },
            "820.75(b)": {
                "title": "Validation Monitoring",
                "required_evidence": ["validation_monitoring", "revalidation_criteria"],
                "doc_patterns": ["revalidation*", "validation_monitoring*"],
                "keywords": ["monitoring", "revalidation", "process performance"]
            }
        }
    },
    "820.90": {
        "title": "Nonconforming Product",
        "subsections": {
            "820.90(a)": {
                "title": "Nonconforming Product Control",
                "required_evidence": ["ncr_procedure", "nonconforming_records"],
                "doc_patterns": ["ncr*", "nonconform*", "nc_*"],
                "keywords": ["nonconforming", "NCR", "disposition"]
            },
            "820.90(b)": {
                "title": "Nonconformance Review",
                "required_evidence": ["ncr_review_procedure"],
                "doc_patterns": ["ncr_review*", "mrb*"],
                "keywords": ["review", "disposition", "concession"]
            }
        }
    },
    "820.100": {
        "title": "Corrective and Preventive Action",
        "subsections": {
            "820.100(a)": {
                "title": "CAPA Procedure",
                "required_evidence": ["capa_procedure", "capa_records"],
                "doc_patterns": ["capa*", "corrective*", "preventive*"],
                "keywords": ["CAPA", "corrective action", "preventive action", "root cause"]
            }
        }
    },
    "820.120": {
        "title": "Device Labeling",
        "subsections": {
            "820.120": {
                "title": "Labeling Controls",
                "required_evidence": ["labeling_procedure", "label_inspection"],
                "doc_patterns": ["label*", "labeling*"],
                "keywords": ["labeling", "label inspection", "UDI"]
            }
        }
    },
    "820.180": {
        "title": "General Requirements - Records",
        "subsections": {
            "820.180": {
                "title": "Records Requirements",
                "required_evidence": ["records_management_procedure", "retention_schedule"],
                "doc_patterns": ["record*", "retention*", "archive*"],
                "keywords": ["records", "retention", "archive", "backup"]
            }
        }
    },
    "820.181": {
        "title": "Device Master Record",
        "subsections": {
            "820.181": {
                "title": "DMR Contents",
                "required_evidence": ["dmr_index", "dmr"],
                "doc_patterns": ["dmr*", "device_master*"],
                "keywords": ["device master record", "DMR", "specifications"]
            }
        }
    },
    "820.184": {
        "title": "Device History Record",
        "subsections": {
            "820.184": {
                "title": "DHR Contents",
                "required_evidence": ["dhr_template", "dhr_records"],
                "doc_patterns": ["dhr*", "device_history*", "batch_record*"],
                "keywords": ["device history record", "DHR", "production record"]
            }
        }
    },
    "820.198": {
        "title": "Complaint Files",
        "subsections": {
            "820.198": {
                "title": "Complaint Handling",
                "required_evidence": ["complaint_procedure", "complaint_records"],
                "doc_patterns": ["complaint*", "customer_feedback*"],
                "keywords": ["complaint", "customer feedback", "MDR"]
            }
        }
    }
}


def search_documentation(project_dir: Path, patterns: List[str], keywords: List[str]) -> Dict:
    """Search for documentation matching patterns and keywords."""
    result = {
        "documents_found": [],
        "keyword_matches": [],
        "evidence_strength": "none"
    }

    # Common documentation directories
    doc_dirs = [
        project_dir / "qms",
        project_dir / "quality",
        project_dir / "docs",
        project_dir / "documentation",
        project_dir / "procedures",
        project_dir / "sops",
        project_dir / "dhf",
        project_dir / "dmr",
        project_dir
    ]

    # Search for document patterns
    for doc_dir in doc_dirs:
        if not doc_dir.exists():
            continue

        for pattern in patterns:
            for ext in ["*.md", "*.pdf", "*.docx", "*.doc", "*.txt"]:
                full_pattern = f"**/{pattern}{ext}" if not pattern.endswith("*") else f"**/{pattern[:-1]}{ext}"
                try:
                    matches = list(doc_dir.glob(full_pattern))
                    for match in matches:
                        rel_path = str(match.relative_to(project_dir))
                        if rel_path not in result["documents_found"]:
                            result["documents_found"].append(rel_path)
                except Exception:
                    continue

    # Search for keywords in markdown and text files
    for doc_dir in doc_dirs:
        if not doc_dir.exists():
            continue

        for ext in ["*.md", "*.txt"]:
            try:
                for file_path in doc_dir.glob(f"**/{ext}"):
                    try:
                        content = file_path.read_text(encoding='utf-8', errors='ignore').lower()
                        for keyword in keywords:
                            if keyword.lower() in content:
                                rel_path = str(file_path.relative_to(project_dir))
                                if rel_path not in result["keyword_matches"]:
                                    result["keyword_matches"].append(rel_path)
                    except Exception:
                        continue
            except Exception:
                continue

    # Determine evidence strength
    if result["documents_found"] and result["keyword_matches"]:
        result["evidence_strength"] = "strong"
    elif result["documents_found"] or result["keyword_matches"]:
        result["evidence_strength"] = "partial"
    else:
        result["evidence_strength"] = "none"

    return result


def assess_section(project_dir: Path, section_id: str, section_data: Dict) -> Dict:
    """Assess compliance for a QSR section."""
    result = {
        "section": section_id,
        "title": section_data["title"],
        "subsections": [],
        "compliance_score": 0,
        "total_subsections": len(section_data["subsections"]),
        "compliant_subsections": 0
    }

    for subsection_id, subsection_data in section_data["subsections"].items():
        evidence = search_documentation(
            project_dir,
            subsection_data["doc_patterns"],
            subsection_data["keywords"]
        )

        subsection_result = {
            "subsection": subsection_id,
            "title": subsection_data["title"],
            "required_evidence": subsection_data["required_evidence"],
            "evidence_found": evidence,
            "status": "gap" if evidence["evidence_strength"] == "none" else (
                "partial" if evidence["evidence_strength"] == "partial" else "compliant"
            )
        }

        if subsection_result["status"] == "compliant":
            result["compliant_subsections"] += 1
        elif subsection_result["status"] == "partial":
            result["compliant_subsections"] += 0.5

        result["subsections"].append(subsection_result)

    if result["total_subsections"] > 0:
        result["compliance_score"] = round(
            (result["compliant_subsections"] / result["total_subsections"]) * 100, 1
        )

    return result


def generate_gap_report(assessment_results: List[Dict]) -> Dict:
    """Generate gap analysis report."""
    gaps = []
    recommendations = []

    for section in assessment_results:
        for subsection in section["subsections"]:
            if subsection["status"] != "compliant":
                gap = {
                    "section": subsection["subsection"],
                    "title": subsection["title"],
                    "status": subsection["status"],
                    "missing_evidence": subsection["required_evidence"]
                }
                gaps.append(gap)

                if subsection["status"] == "gap":
                    recommendations.append(
                        f"{subsection['subsection']}: Create documentation for {subsection['title']}"
                    )
                else:
                    recommendations.append(
                        f"{subsection['subsection']}: Enhance documentation for {subsection['title']}"
                    )

    return {
        "total_gaps": len([g for g in gaps if g["status"] == "gap"]),
        "total_partial": len([g for g in gaps if g["status"] == "partial"]),
        "gaps": gaps,
        "priority_recommendations": recommendations[:10]  # Top 10
    }


def calculate_overall_compliance(assessment_results: List[Dict]) -> Dict:
    """Calculate overall QSR compliance score."""
    total_subsections = 0
    compliant_subsections = 0

    section_scores = {}
    for section in assessment_results:
        total_subsections += section["total_subsections"]
        compliant_subsections += section["compliant_subsections"]
        section_scores[section["section"]] = section["compliance_score"]

    overall_score = round((compliant_subsections / total_subsections) * 100, 1) if total_subsections > 0 else 0

    # Determine compliance level
    if overall_score >= 90:
        level = "HIGH"
        color = "green"
    elif overall_score >= 70:
        level = "MEDIUM"
        color = "yellow"
    elif overall_score >= 50:
        level = "LOW"
        color = "orange"
    else:
        level = "CRITICAL"
        color = "red"

    return {
        "overall_score": overall_score,
        "compliance_level": level,
        "total_subsections": total_subsections,
        "compliant_subsections": compliant_subsections,
        "section_scores": section_scores
    }


def print_text_report(result: Dict) -> None:
    """Print human-readable compliance report."""
    print("=" * 70)
    print("21 CFR PART 820 (QSR) COMPLIANCE ASSESSMENT")
    print("=" * 70)

    # Overall compliance
    overall = result["overall_compliance"]
    print(f"\nOVERALL COMPLIANCE: {overall['overall_score']}% ({overall['compliance_level']})")
    print(f"Subsections Assessed: {overall['total_subsections']}")
    print(f"Compliant/Partial: {overall['compliant_subsections']}")

    # Section summary
    print("\n--- SECTION SCORES ---")
    for section in result["assessment"]:
        status = "OK" if section["compliance_score"] >= 70 else "GAP"
        print(f"  {section['section']} {section['title']}: {section['compliance_score']}% [{status}]")

    # Gap analysis
    gap_report = result["gap_report"]
    print(f"\n--- GAP ANALYSIS ---")
    print(f"Critical Gaps: {gap_report['total_gaps']}")
    print(f"Partial Compliance: {gap_report['total_partial']}")

    if gap_report["gaps"]:
        print("\n  Gaps Identified:")
        for gap in gap_report["gaps"][:15]:  # Show top 15
            status = "GAP" if gap["status"] == "gap" else "PARTIAL"
            print(f"    [{status}] {gap['section']}: {gap['title']}")

    # Recommendations
    if gap_report["priority_recommendations"]:
        print("\n--- PRIORITY RECOMMENDATIONS ---")
        for i, rec in enumerate(gap_report["priority_recommendations"], 1):
            print(f"  {i}. {rec}")

    print("\n" + "=" * 70)
    print(f"Assessment Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print("=" * 70)


def main():
    parser = argparse.ArgumentParser(
        description="QSR Compliance Checker - Assess 21 CFR 820 compliance"
    )
    parser.add_argument(
        "project_dir",
        nargs="?",
        default=".",
        help="Project directory to analyze (default: current directory)"
    )
    parser.add_argument(
        "--section",
        help="Analyze specific QSR section only (e.g., 820.30)"
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output in JSON format"
    )
    parser.add_argument(
        "--detailed",
        action="store_true",
        help="Include detailed evidence in output"
    )

    args = parser.parse_args()
    project_dir = Path(args.project_dir).resolve()

    if not project_dir.exists():
        print(f"Error: Directory not found: {project_dir}", file=sys.stderr)
        sys.exit(1)

    # Filter sections if specific one requested
    sections_to_assess = QSR_REQUIREMENTS
    if args.section:
        if args.section in QSR_REQUIREMENTS:
            sections_to_assess = {args.section: QSR_REQUIREMENTS[args.section]}
        else:
            print(f"Error: Unknown section: {args.section}", file=sys.stderr)
            print(f"Available sections: {', '.join(QSR_REQUIREMENTS.keys())}")
            sys.exit(1)

    # Perform assessment
    assessment_results = []
    for section_id, section_data in sections_to_assess.items():
        section_result = assess_section(project_dir, section_id, section_data)
        assessment_results.append(section_result)

    # Generate reports
    overall_compliance = calculate_overall_compliance(assessment_results)
    gap_report = generate_gap_report(assessment_results)

    result = {
        "project_dir": str(project_dir),
        "assessment_date": datetime.now().isoformat(),
        "overall_compliance": overall_compliance,
        "assessment": assessment_results if args.detailed else [
            {
                "section": s["section"],
                "title": s["title"],
                "compliance_score": s["compliance_score"],
                "status": "compliant" if s["compliance_score"] >= 70 else "gap"
            }
            for s in assessment_results
        ],
        "gap_report": gap_report
    }

    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print_text_report(result)


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)