diff --git a/.github/AI_CODER_INSTRUCTIONS.md b/.github/AI_CODER_INSTRUCTIONS.md
deleted file mode 100644
index 890b708ec67d5578c89c94bdcd5800fa0ee9ccfc..0000000000000000000000000000000000000000
--- a/.github/AI_CODER_INSTRUCTIONS.md
+++ /dev/null
@@ -1,998 +0,0 @@
-# YAZ Care Platform - AI Coder Instructions v7.0.0
-
-**Version**: 7.0.0 (Intelligence Platform Edition)
-**Date**: March 6, 2026
-**Sprint**: 41 of 52
-**Status**: β
PRODUCTION - Multi-Domain Intelligence Platform
-
-> **π― v7.0.0 UPGRADE**: This document extends v5.3.0 with **Domain Engines**, **Intelligence Packaging**,
-> and **Multi-Domain Architecture** β the foundational concepts that make YAZ a universal platform:
->
-> | Concept | Description |
-> |---------|-------------|
-> | **Domain Engines** | Specialized subsystems per professional field (Surgio, Movio, Bankoβ¦) |
-> | **Intelligences** | Packaged expertise modules created by professionals |
-> | **24 Pillars** | Domain-agnostic primitives that all engines compose |
-> | **Marketplace** | Discover, install, fork, and monetise intelligence modules |
-> | **Dual Licensing** | Open (AGPL-3.0) for learners/NGOs, Licensed for commercial |
-
----
-
-## π Quick Start
-
-**Before coding, verify you understand:**
-1. The 9 Commandments β [COMMANDMENTS.md](../docs/COMMANDMENTS.md) - **NON-NEGOTIABLE**
-2. DDD Standards β [DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md)
-3. Domain Engines β [DOMAIN_ENGINES.md](../docs/architecture/DOMAIN_ENGINES.md)
-4. Intelligence Packaging β [INTELLIGENCE_PACKAGING.md](../docs/architecture/INTELLIGENCE_PACKAGING.md)
-5. The Four Pillars Architecture β This document (Part 9)
-6. Governance hierarchy and case management patterns
-
----
-
-## π PUBLIC vs INTERNAL Visibility Rules
-
-### β οΈ CRITICAL: User-Facing Exposure Rules
-
-| Layer | PUBLIC (User-Visible) | INTERNAL (Backend Only) |
-|-------|----------------------|------------------------|
-| **Operating Companies** | β
YAZ, AYRAD, AZUL, EFRI, LUIZ | β Never expose parent entities |
-| **Products/Apps** | β
Surgio, Clinica, Labo, Pharma, etc. | β Governance structure |
-| **Tenants** | β
Hospital names, clinic names | β Tenant IDs in URLs |
-| **Legal Entities** | β NEVER in UI/docs/web | β
Database & admin only |
-
-### What Users See vs What Backend Uses
-
-```
-USER-FACING (Web, Docs, UI):
-βββ YAZ Care Platform (brand)
-βββ Apps: Surgio, Clinica, Labo, Pharma, Hospi...
-βββ Tenant: "Hospital ABC", "Clinic XYZ"
-βββ Features: Cases, Reports, Analytics
-
-BACKEND-ONLY (Database, Admin, Internal):
-βββ LegalEntity (governance layer - NEVER expose)
-βββ System (operational config)
-βββ Contract (licensing agreements)
-βββ SLAMetric (performance tracking)
-```
-
-### β
DO: User-Facing Content
-```html
-
-
YAZ Care Platform
-Powered by AYRAD Intelligence
-
-
-
-```
-
-### β DON'T: Never Expose Governance
-```html
-
-
-
-
-
-Licensed by YEMA Holding
-```
-
----
-
-## π Part 1: Internal Governance Architecture
-
-> **π INTERNAL ONLY**: This section is for backend developers.
-> Never expose these concepts in user-facing UI, documentation, or APIs.
-
-### Governance Hierarchy (DATABASE ONLY)
-
-The platform implements a 4-tier governance hierarchy stored in database:
-
-```
-[INTERNAL - Database Schema: governance]
-LegalEntity (parent_trust)
- βββ LegalEntity (holding_company)
- βββ LegalEntity (foundation)
- βββ System (yaz, ayrad, azul, efri, luiz)
- βββ Tenant (hospital-a, clinic-b)
- βββ Users & Cases
-```
-
-### Internal Database Models
-
-| Model | Location | Visibility |
-|-------|----------|------------|
-| `LegalEntity` | [src/core/database/governance.py](../src/core/database/governance.py) | π Admin API only |
-| `LegalEntityKind` | [src/core/database/governance.py](../src/core/database/governance.py) | π Internal enum |
-| `System` | [src/core/database/governance.py](../src/core/database/governance.py) | β οΈ Brand names public |
-| `Contract` | [src/core/governance/contracts.py](../src/core/governance/contracts.py) | π Internal only |
-
-### LegalEntityKind Enum (INTERNAL)
-
-```python
-# src/core/database/governance.py - INTERNAL USE ONLY
-class LegalEntityKind(str, Enum):
- """
- π INTERNAL: Types of legal entities in governance hierarchy.
- Never expose kind names or hierarchy to users.
- """
- TRUST = "trust" # Parent asset protection
- HOLDING_FOR_PROFIT = "holding_for_profit" # Commercial licensing
- FOUNDATION_NON_PROFIT = "foundation_non_profit" # OSS stewardship
-```
-
-### SystemType Enum (PARTIALLY PUBLIC)
-
-```python
-# src/core/database/governance.py
-class SystemType(str, Enum):
- """
- System types - Brand names (YAZ, AYRAD) are PUBLIC.
- Internal classification is PRIVATE.
- """
- SOFTWARE_VENDOR = "software_vendor" # YAZ Care Platform (PUBLIC brand)
- OPERATOR = "operator" # AYRAD Intelligence (PUBLIC brand)
- SERVICE_PROVIDER = "service_provider" # AZUL (PUBLIC brand)
- RESEARCH_ENTITY = "research_entity" # Research partners
-```
-
-### Contract Model (INTERNAL ONLY)
-
-```python
-# src/core/governance/contracts.py - ADMIN ACCESS ONLY
-class Contract(SQLModel, table=True):
- """
- π INTERNAL: Contracts between legal entities.
- Never expose contract details to regular users.
- """
- __tablename__ = "contracts"
- __table_args__ = {"schema": "governance"}
-
- id: UUID = Field(default_factory=uuid4, primary_key=True)
- contract_type: ContractType
- licensor_id: UUID
- licensee_id: UUID
- effective_date: datetime
- expiration_date: datetime
- sla_metrics: List[SLAMetric]
-```
-
----
-
-## π Part 2: Domain-Agnostic Case Management
-
-### Universal Vocabulary (EXISTING)
-
-All case types across YAZ tools share a common vocabulary. **These enums exist**:
-
-| Enum | Location | Purpose |
-|------|----------|---------|
-| `CaseStatus` | [src/core/domain/cases.py](../src/core/domain/cases.py) | DRAFT β ARCHIVED lifecycle |
-| `CaseType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | SURGICAL, CLINICAL, LABORATORY, etc. |
-| `CasePriority` | [src/core/domain/cases.py](../src/core/domain/cases.py) | ROUTINE β STAT |
-| `InteractionType` | [src/core/domain/cases.py](../src/core/domain/cases.py) | VIEW, EDIT, COMMENT, etc. |
-
-### CaseStatus Enum (EXISTING)
-
-```python
-# src/core/domain/cases.py (Lines 38-65)
-class CaseStatus(str, Enum):
- """
- Universal case status across all YAZ tools.
-
- Workflow: DRAFT β PENDING β ACTIVE β ON_HOLD β COMPLETED β ARCHIVED
- Terminal states: CANCELLED, ARCHIVED
- """
- DRAFT = "draft" # Initial creation
- PENDING = "pending" # Awaiting approval/action
- ACTIVE = "active" # In progress
- ON_HOLD = "on_hold" # Temporarily paused
- COMPLETED = "completed" # Successfully finished
- CANCELLED = "cancelled" # Terminated early
- ARCHIVED = "archived" # Stored for records
-```
-
-### CaseType Enum (EXISTING)
-
-```python
-# src/core/domain/cases.py (Lines 67-95)
-class CaseType(str, Enum):
- """
- Domain-specific case types mapping to YAZ tools.
- """
- SURGICAL = "surgical" # Surgio
- CLINICAL = "clinical" # Clinica
- LABORATORY = "laboratory" # Labo
- PHARMACEUTICAL = "pharmaceutical" # Pharma
- ADMINISTRATIVE = "administrative" # Hospi
- FINANCIAL = "financial" # Banko, Insura
- EDUCATIONAL = "educational" # Educa, Trena
- LOGISTICS = "logistics" # Movio, Stoka
- FIELD = "field" # Campo
- ACCOMMODATION = "accommodation" # Lodger
- MANUFACTURING = "manufacturing" # Fabrica
-```
-
-### CasePriority Enum (EXISTING)
-
-```python
-# src/core/domain/cases.py (Lines 97-115)
-class CasePriority(str, Enum):
- """
- Universal priority levels for clinical urgency.
- """
- ROUTINE = "routine" # Standard processing
- URGENT = "urgent" # Elevated priority
- STAT = "stat" # Immediate action required
- CRITICAL = "critical" # Life-threatening emergency
-```
-
-### BaseCase Aggregate Root (EXISTING)
-
-```python
-# src/core/domain/cases.py (Lines 222-350)
-@dataclass
-class BaseCase(ABC):
- """
- Abstract base case aggregate root.
- All domain-specific cases should extend this.
-
- Provides:
- - Universal case lifecycle management
- - Cross-tool case linking
- - Interaction tracking
- - Event publishing
- """
- id: UUID = field(default_factory=uuid4)
- tenant_id: str = ""
- case_type: CaseType = CaseType.CLINICAL
- case_number: str = ""
- status: CaseStatus = CaseStatus.DRAFT
- priority: CasePriority = CasePriority.ROUTINE
- subject_id: Optional[UUID] = None
- owner_id: str = ""
- linked_cases: List[CaseLink] = field(default_factory=list)
- _uncommitted_events: List[DomainEvent] = field(default_factory=list)
-```
-
-### Domain Events (EXISTING)
-
-```python
-# src/core/domain/cases.py (Lines 130-200)
-@dataclass(frozen=True)
-class CaseCreatedEvent(DomainEvent):
- """Emitted when a new case is created"""
- event_type: str = "case.created"
- case_id: str = ""
- case_type: str = ""
- subject_id: str = ""
-
-@dataclass(frozen=True)
-class CaseStatusChangedEvent(DomainEvent):
- """Emitted when case status changes"""
- event_type: str = "case.status_changed"
- case_id: str = ""
- old_status: str = ""
- new_status: str = ""
- changed_by: str = ""
- reason: str = ""
-```
-
-### Cross-Domain Case API (EXISTING)
-
-The platform has a unified case API for cross-tool interactions:
-
-```python
-# src/core/api/cases.py (507 lines)
-# Provides:
-# - GET /api/v1/cases/search - Cross-domain case search
-# - POST /api/v1/cases/link - Link cases across tools
-# - POST /api/v1/cases/interaction - Record case interactions
-# - POST /api/v1/cases/status - Change case status
-# - POST /api/v1/cases/assign - Assign cases
-# - POST /api/v1/cases/escalate - Escalate priority
-```
-
----
-
-## ποΈ Part 3: Engine Architecture & Registry
-
-> **Key Principle**: Surgio, Clinica, Labo, etc. are **domain engines** β specialized subsystems
-> encapsulating professional intelligence. Each engine implements the `DomainEngine` ABC
-> and composes platform pillars. Any professional can create their own domain engine
-> to solve cases in any field and commercialise them via the Marketplace.
-
-### Tool Registration (EXISTING)
-
-All tools are registered in [src/apps_routes.py](../src/apps_routes.py):
-
-```python
-# src/apps_routes.py (Lines 10-120)
-APPS = {
- "surgio": {"name": "Surgio", "icon": "scissors", ...},
- "clinica": {"name": "Clinica", "icon": "clipboard-list", ...},
- "labo": {"name": "Labo", "icon": "flask-conical", ...},
- "pharma": {"name": "Pharma", "icon": "pill", ...},
- "hospi": {"name": "Hospi", "icon": "building-2", ...},
- "medio": {"name": "Medio", "icon": "heart-pulse", ...},
- "educa": {"name": "Educa", "icon": "book-open", ...},
- "insura": {"name": "Insura", "icon": "shield-check", ...},
- "movio": {"name": "Movio", "icon": "package", ...},
- "stoka": {"name": "Stoka", "icon": "layers", ...},
- "campo": {"name": "Campo", "icon": "map-pin", ...},
- "banko": {"name": "Banko", "icon": "wallet", ...},
- "lodger": {"name": "Lodger", "icon": "home", ...},
- "fabrica": {"name": "Fabrica", "icon": "cog", ...},
- "trena": {"name": "Trena", "icon": "graduation-cap", ...},
- "security": {"name": "Security", "icon": "shield-check", ...},
-}
-```
-
-### Tool Directory Structure
-
-Each tool follows this standard structure:
-
-```
-src/apps/{tool_slug}/
-βββ __init__.py # Package init, exports
-βββ models.py # SQLModel domain models
-βββ schemas.py # Pydantic V2 request/response
-βββ routes.py # FastAPI routes (or router.py)
-βββ services/ # Business logic layer
-β βββ __init__.py
-β βββ {app}_service.py
-βββ tests/
- βββ test_{app}.py
-```
-
-### Template Structure
-
-```
-src/ui/templates/
-βββ shared/
-β βββ base.html # Base template with nav
-β βββ app_base.html # App-specific base
-βββ apps/
-β βββ surgio.html # Simple app dashboard
-β βββ clinica.html
-β βββ ... (per-app templates)
-βββ {app_slug}/
-β βββ dashboard.html # Rich dashboard
-β βββ list.html # Entity list view
-β βββ detail.html # Entity detail view
-β βββ new.html # Create form
-βββ cases/
- βββ dashboard.html # Cross-domain case view
- βββ list.html # Case list
- βββ detail.html # Case detail
-```
-
----
-
-## π¨ Part 4: UI/UX Patterns
-
-### Dashboard Template Pattern (EXISTING)
-
-All app dashboards follow this structure:
-
-```html
-
-{% extends "shared/app_base.html" %}
-
-{% set app_config = {
- 'slug': 'surgio',
- 'name': 'Surgio',
- 'icon': 'scissors',
- 'gradient_from': '#7c8ab8',
- 'gradient_to': '#9b7cb8'
-} %}
-
-{% block dashboard_content %}
-
-
- {% include "shared/components/stat_card.html" %}
-
-
-
-
-
-
-
-
-
-{% endblock %}
-```
-
-### Color Palette (v2.0 Minimalist)
-
-```css
-/* src/ui/static/css/theme.css */
-:root {
- /* Light Mode */
- --bg: #f8f9fa;
- --surface: #ffffff;
- --border: #e5e7eb;
- --text: #1f2937;
- --text-muted: #6b7280;
-
- --primary: #5c6bc0;
- --primary-hover: #4a5ab8;
- --success: #56a066;
- --warning: #c2883b;
- --error: #c74b4b;
-}
-
-[data-theme="dark"] {
- --bg: #111827;
- --surface: #1f2937;
- --border: #374151;
- --text: #f9fafb;
- --text-muted: #9ca3af;
-
- --primary: #7c8aca;
- --primary-hover: #8b97d1;
-}
-```
-
-### HTMX Patterns (EXISTING)
-
-```html
-
-
-
-
-
-
-
-
-```
-
----
-
-## π Part 5: Security & Multi-Tenancy
-
-### Tenant Isolation (MANDATORY)
-
-**Every query MUST filter by tenant_id first**:
-
-```python
-# β
CORRECT - Always filter by tenant_id
-from sqlalchemy import select
-
-query = select(SurgeryCase).where(
- SurgeryCase.tenant_id == tenant_id, # MANDATORY FIRST
- SurgeryCase.status == 'active'
-)
-
-# β WRONG - No tenant filter = SECURITY BREACH
-query = select(SurgeryCase) # Returns ALL tenants' data!
-```
-
-### RBAC System (EXISTING)
-
-```python
-# src/core/security/rbac.py
-from core.security.rbac import require_permission, Permission
-
-@router.get("/cases/{case_id}")
-@require_permission(Permission("surgio", "read", "cases"))
-async def get_case(
- case_id: UUID,
- current_user: User = Depends(get_current_user),
- tenant_id: UUID = Depends(verify_tenant_access)
-):
- """Get case with RBAC enforcement"""
- pass
-```
-
-### Audit Logging (EXISTING)
-
-```python
-# src/core/security/audit.py
-from core.security.audit import audit_log
-
-@audit_log(
- action="case.viewed",
- resource_type="surgical_case",
- phi_access=True # Marks PHI access for HIPAA
-)
-async def get_case_details(case_id: UUID):
- pass
-```
-
----
-
-## π Part 6: Performance Standards
-
-### SLA Targets (EXISTING)
-
-| Operation | Target | Enforcement |
-|-----------|--------|-------------|
-| API Response (p95) | <200ms | Prometheus alert |
-| List Operations | <100ms | Indexed queries |
-| Algorithm Execution | <50ms | Caching |
-| Cache Hit Rate | >90% | 4-tier strategy |
-| WebSocket Latency | <20ms | Connection pooling |
-
-### 4-Tier Caching (EXISTING)
-
-```python
-# src/core/cache/strategy.py
-CACHE_TIERS = {
- "request": {"ttl": 5, "scope": "in-memory"}, # functools.lru_cache
- "session": {"ttl": 60, "scope": "redis"}, # User session data
- "tenant": {"ttl": 3600, "scope": "redis"}, # Tenant config
- "global": {"ttl": 86400, "scope": "redis"} # Reference data
-}
-```
-
-### Query Optimization (MANDATORY)
-
-```python
-# β
GOOD - Indexed, specific columns, eager loading
-from sqlalchemy.orm import selectinload
-
-query = select(SurgeryCase.id, SurgeryCase.case_number, SurgeryCase.status).where(
- SurgeryCase.tenant_id == tenant_id # Uses index
-).options(
- selectinload(SurgeryCase.team_members) # Prevent N+1
-).order_by(
- SurgeryCase.created_at.desc()
-).limit(50)
-
-# β BAD - SELECT *, no index, N+1 queries
-query = select(SurgeryCase) # Loads all columns
-for case in cases:
- case.team_members # N+1 query!
-```
-
----
-
-## π§ͺ Part 7: Testing Standards
-
-### Coverage Requirements
-
-| Type | Target | Location |
-|------|--------|----------|
-| Unit Tests | 85%+ | `tests/unit/` |
-| Integration Tests | All APIs | `tests/integration/` |
-| Isolation Tests | 15 mandatory | `tests/isolation/` |
-| Performance Tests | SLA validation | `tests/performance/` |
-
-### Test Pattern (EXISTING)
-
-```python
-# tests/apps/surgio/test_case_service.py
-import pytest
-from uuid import uuid4
-
-@pytest.mark.asyncio
-async def test_case_creation_with_tenant():
- """Unit test for case creation"""
- tenant_id = uuid4()
- case = await case_service.create(
- data=CaseCreate(procedure_name="Total Knee Replacement"),
- tenant_id=tenant_id,
- user_id=uuid4()
- )
- assert case.tenant_id == tenant_id
- assert case.status == CaseStatus.DRAFT
-
-
-@pytest.mark.isolation
-async def test_tenant_isolation():
- """MANDATORY: Verify tenant isolation"""
- tenant_a = uuid4()
- tenant_b = uuid4()
-
- case = await case_service.create(data, tenant_a, user_id)
-
- # Tenant B cannot access Tenant A's case
- result = await case_service.get(case.id, tenant_b)
- assert result is None
-
-
-@pytest.mark.performance
-async def test_case_creation_sla():
- """Verify <200ms SLA"""
- import time
-
- start = time.time()
- await case_service.create(data, tenant_id, user_id)
- duration_ms = (time.time() - start) * 1000
-
- assert duration_ms < 200, f"SLA violation: {duration_ms}ms"
-```
-
----
-
-## π οΈ Part 8: Development Workflow
-
-### 1. Creating a New Tool
-
-```bash
-# Use the generator script
-python scripts/generators/create_app.py \
- --name newtool \
- --display-name "New Tool" \
- --category clinical \
- --standards "HL7 FHIR"
-
-# Creates:
-# src/apps/newapp/
-# βββ __init__.py
-# βββ models.py
-# βββ schemas.py
-# βββ routes.py
-# βββ services/
-# src/ui/templates/newapp/
-# βββ dashboard.html
-```
-
-### 2. Creating a New Entity
-
-Follow the 5-phase workflow in [CODEBASE_CREATION_LOGIC.md](../docs/architecture/CODEBASE_CREATION_LOGIC.md):
-
-1. **Domain Model** (`models.py`)
-2. **API Schemas** (`schemas.py`)
-3. **Business Logic** (`services/`)
-4. **Routes** (`routes.py`)
-5. **Tests** (`tests/`)
-
-### 3. Running the Platform
-
-```bash
-# Development with hot reload
-python main.py serve --debug --port 8000
-
-# Or use the VS Code task
-# Tasks: Run Task β "Start Dev Server (Hot Reload)"
-
-# Tests
-pytest tests/ -v --cov=src --cov-fail-under=85
-
-# Type checking
-mypy src/
-
-# Formatting
-black src/ tests/ && isort src/ tests/
-```
-
----
-
-## π Related Documentation
-
-| Document | Purpose | Location |
-|----------|---------|----------|
-| **COMMANDMENTS** | 7 unbreakable rules | [docs/COMMANDMENTS.md](../docs/COMMANDMENTS.md) |
-| **PRACTICES** | Best practices guide | [docs/PRACTICES.md](../docs/PRACTICES.md) |
-| **DDD_STANDARDS** | Domain patterns | [docs/architecture/DDD_STANDARDS.md](../docs/architecture/DDD_STANDARDS.md) |
-| **ACCESS_SECURITY** | RBAC, audit, secrets | [docs/architecture/ACCESS_SECURITY.md](../docs/architecture/ACCESS_SECURITY.md) |
-| **TARGET** | Technology roadmap | [docs/TARGET.md](../docs/TARGET.md) |
-| **UI_UX_SYSTEM** | Design system v2.0 | [docs/architecture/UI_UX_SYSTEM.md](../docs/architecture/UI_UX_SYSTEM.md) |
-
----
-
-## β
AI Assistant Checklist
-
-Before submitting code, verify:
-
-### Code Quality
-- [ ] All type hints present (100% coverage)
-- [ ] Docstrings with clinical context
-- [ ] Tests written (85%+ coverage)
-- [ ] No mypy errors
-
-### Security
-- [ ] tenant_id filter on every query
-- [ ] No PHI in logs
-- [ ] RBAC decorators applied
-- [ ] Audit logging for sensitive ops
-
-### Performance
-- [ ] Queries use indexes
-- [ ] No N+1 queries (use selectinload)
-- [ ] Caching for expensive operations
-- [ ] <200ms SLA validated
-
-### Standards
-- [ ] Follows DDD patterns
-- [ ] Uses existing enums (CaseStatus, CaseType)
-- [ ] Extends base classes (BaseCase, BaseService)
-- [ ] Events raised for state changes
-
----
-
-**Last Updated**: February 05, 2026
-**Maintainer**: YAZ Care Development Team
-**Status**: β
v5.3.0 - Production Ready with Four Pillars Architecture
-
----
-
-## ποΈ Part 9: The Four Pillars Architecture (v5.3.0)
-
-> **CRITICAL**: These are **architectural instructions**, not code examples. They define how to design,
-> implement, test, deploy, and maintain the foundational services.
-
-### Core Philosophy
-
-- Services are **primitives**, not features
-- Domain packs **compose** services, not implement them
-- Everything is **configurable** via schemas
-- Everything is **auditable** via events
-- Everything is **extensible** without core changes
-
-### Architecture Overview
-
-```
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β DOMAIN PACK LAYER β
-β (Healthcare, Logistics, Insurance, Manufacturing, Education...) β
-β β
-β Domain Packs DO: β
-β - Define schemas (checklist templates, journal entry types) β
-β - Configure monitors (vital signs, inventory levels) β
-β - Define protocol workflows (surgical pathways, shipping routes) β
-β - Provide UI templates and visualizations β
-β β
-β Domain Packs DO NOT: β
-β - Implement core service logic β
-β - Manage multi-tenancy β
-β - Handle event sourcing β
-β - Control access permissions β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β CORE SERVICE LAYER (The 4 Pillars) β
-β β
-β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββ β
-β β CHECKLIST β β JOURNAL β β MONITOR β βPROTOCOLβ β
-β β SERVICE β β SERVICE β β SERVICE β βWORKFLOWβ β
-β β β β β β β βSERVICE β β
-β β - Templates β β - Streams β β - Defs β β - Defs β β
-β β - Instances β β - Entries β β - Instances β β - Runs β β
-β β - Responses β β - Amendments β β - Alerts β β - Stepsβ β
-β β - Validation β β - Signatures β β - Trends β β - Transβ β
-β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββ β
-β β
-β All services share: β
-β - Event sourcing pattern β
-β - Hash chain integrity β
-β - Multi-tenant isolation β
-β - RBAC enforcement β
-β - Metrics & tracing β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- β
- βΌ
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-β INFRASTRUCTURE LAYER β
-β β
-β - Event Store (append-only, hash-chained) β
-β - Parameter Store (versioned, audited) β
-β - Evidence Store (immutable attachments) β
-β - Audit Log (compliance, forensics) β
-β - Notification Bus (real-time alerts) β
-βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-```
-
-### Pillar 1: Checklist Service
-
-**Purpose**: Structured, sequential task completion with validation.
-
-**Core Entities**:
-| Entity | Purpose | Storage |
-|--------|---------|---------|
-| `ChecklistTemplate` | Reusable blueprint | `checklist.templates` |
-| `ChecklistInstance` | Active execution | `checklist.instances` |
-| `ChecklistItemResponse` | User responses | `checklist.responses` |
-
-**Input Types**: `boolean`, `text_input`, `numeric_input`, `choice`, `multi_choice`,
-`signature`, `photo`, `barcode`, `measurement`, `timestamp`, `calculated`
-
-**API Endpoints**:
-```
-POST /api/v1/checklists/templates
-GET /api/v1/checklists/templates/{id}
-POST /api/v1/checklists/instances
-POST /api/v1/checklists/instances/{id}/respond
-POST /api/v1/checklists/instances/{id}/complete
-```
-
-**Domain Pack Example** (Surgical Care):
-```python
-WHO_SSC_TEMPLATE = {
- "name": "WHO Surgical Safety Checklist 2.0",
- "version": "2.0.0",
- "domain": "surgical_care",
- "items": [
- {"item_id": "confirm_patient", "type": "boolean", "required": True},
- {"item_id": "site_marked", "type": "choice", "required": True}
- ]
-}
-```
-
-### Pillar 2: Journal Service
-
-**Purpose**: Chronological, append-only documentation with amendments.
-
-**Core Entities**:
-| Entity | Purpose | Storage |
-|--------|---------|---------|
-| `JournalStream` | Container for entries | `journal.streams` |
-| `JournalEntry` | Immutable record | `journal.entries` |
-| `Amendment` | Entry corrections | `journal.amendments` |
-
-**Entry Types**: `narrative`, `observation`, `assessment`, `plan`, `procedure_note`,
-`progress_note`, `incident`, `handoff`, `communication`
-
-**Key Feature**: Hash chain integrity (each entry includes prev_hash)
-
-**API Endpoints**:
-```
-POST /api/v1/journal/streams
-POST /api/v1/journal/streams/{id}/entries
-POST /api/v1/journal/entries/{id}/amend
-POST /api/v1/journal/entries/{id}/sign
-GET /api/v1/journal/search
-POST /api/v1/journal/streams/{id}/export
-```
-
-### Pillar 3: Monitor Service
-
-**Purpose**: Continuous parameter surveillance with alerting.
-
-**Monitor Types**:
-| Type | Description | Use Case |
-|------|-------------|----------|
-| `threshold` | Value crosses limit | HR > 120 bpm |
-| `range` | Value outside bounds | BP 90-140 mmHg |
-| `trend` | Rate of change | Temp rising 0.5Β°C/hr |
-| `composite` | Multiple parameters | SIRS criteria |
-| `statistical` | Westgard QC rules | Lab QC |
-| `heartbeat` | Missing signal | Device offline |
-
-**Core Entities**:
-| Entity | Purpose | Storage |
-|--------|---------|---------|
-| `MonitorDefinition` | Reusable blueprint | `monitor.definitions` |
-| `MonitorInstance` | Active monitor | `monitor.instances` |
-| `Alert` | Triggered notification | `monitor.alerts` |
-
-**API Endpoints**:
-```
-POST /api/v1/monitors/definitions
-POST /api/v1/monitors/instances
-POST /api/v1/monitors/instances/{id}/evaluate
-POST /api/v1/monitors/alerts/{id}/acknowledge
-POST /api/v1/monitors/alerts/{id}/resolve
-```
-
-### Pillar 4: Protocol Workflow Service
-
-**Purpose**: Multi-step coordinated processes with state machine execution.
-
-**Core Concepts**:
-- **States**: Discrete phases (pre-op, timeout, incision, closure)
-- **Transitions**: How to move between states
-- **Guards**: Conditions that must be met (checklist complete)
-- **Actions**: What happens on transition (notify team)
-- **Timeouts**: Max time in state before alert
-
-**Core Entities**:
-| Entity | Purpose | Storage |
-|--------|---------|---------|
-| `ProtocolDefinition` | State machine blueprint | `protocol.definitions` |
-| `ProtocolRun` | Active execution | `protocol.runs` |
-| `StateTransition` | Transition record | `protocol.state_transitions` |
-
-**Guard Types**: `checklist_complete`, `parameter_value`, `journal_entry_exists`,
-`time_elapsed`, `alert_resolved`, `user_role`
-
-**Action Types**: `initiate_checklist`, `create_journal_entry`, `start_monitor`,
-`stop_monitor`, `notify`, `set_variable`
-
-**API Endpoints**:
-```
-POST /api/v1/protocols/definitions
-POST /api/v1/protocols/runs
-POST /api/v1/protocols/runs/{id}/transition
-POST /api/v1/protocols/runs/{id}/abort
-GET /api/v1/protocols/runs/{id}/status
-```
-
-### Service Composition Patterns
-
-**Pattern 1: Protocol Orchestrates Checklist + Journal**
-```
-Protocol Run β State "Pre-Op" β Initiate Checklist β
-User completes β Auto Journal Entry β Guard passes β Next State
-```
-
-**Pattern 2: Monitor Triggers Protocol Transition**
-```
-Monitor evaluates β Threshold exceeded β Alert β
-Protocol listens β Auto-transition to Emergency State
-```
-
-**Pattern 3: Cross-Service References**
-```json
-{
- "protocol_run_variables": {
- "checklist_pre_op": "01HWFX7K...",
- "journal_stream": "01HWFX9N...",
- "monitor_heart_rate": "01HWFXAP..."
- }
-}
-```
-
-### Implementation Roadmap
-
-| Phase | Timeline | Focus |
-|-------|----------|-------|
-| 1 | Weeks 1-2 | Foundation: DB schemas, service modules |
-| 2 | Weeks 3-4 | Surgical Care domain pack pilot |
-| 3 | Weeks 5-8 | Healthcare tools integration |
-| 4 | Weeks 9-12 | Non-healthcare tools (logistics, inventory) |
-| 5 | Weeks 13-14 | Optimization & documentation |
-
-### Testing Requirements
-
-| Service | Unit | Integration | Performance | Isolation |
-|---------|------|-------------|-------------|-----------|
-| Checklist | Template/response validation | Full lifecycle | <50ms p95 | 15 tests |
-| Journal | Hash computation, amendments | Entry chain | <100ms p95 | 15 tests |
-| Monitor | Threshold evaluation, trends | Alert escalation | <30ms p95 | 15 tests |
-| Protocol | Guard/action execution | State machine | <200ms p95 | 15 tests |
-
-### Event Types Summary
-
-```python
-# Checklist Events
-checklist.template_created, checklist.initiated, checklist.item_responded,
-checklist.completed, checklist.abandoned
-
-# Journal Events
-journal.stream_created, journal.entry_added, journal.entry_amended,
-journal.entry_signed, journal.stream_closed
-
-# Monitor Events
-monitor.started, monitor.evaluated, monitor.alert_triggered,
-monitor.alert_acknowledged, monitor.alert_resolved
-
-# Protocol Events
-protocol.started, protocol.state_transitioned, protocol.action_executed,
-protocol.completed, protocol.aborted
-```
-
----
-
-## β
AI Assistant Checklist (v5.3.0 Extended)
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
deleted file mode 100755
index ed6d22e38d1fb048e6c1cd73ccf405194b881075..0000000000000000000000000000000000000000
--- a/.github/CODEOWNERS
+++ /dev/null
@@ -1,9 +0,0 @@
-* @yaz-care/platform-team
-/src/apps/surgio/ @yaz-care/surgio-team
-/src/apps/clinica/ @yaz-care/clinica-team
-/src/apps/educa/ @yaz-care/educa-team
-/src/apps/insura/ @yaz-care/insura-team
-/src/apps/movit/ @yaz-care/movit-team
-/deployment/ @yaz-care/devops-team
-/docs/ @yaz-care/docs-team
-/.github/ @yaz-care/platform-team
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
deleted file mode 100644
index 42a0f7537d2af44c352c2b5b65ff71bcafe28bb5..0000000000000000000000000000000000000000
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ /dev/null
@@ -1,208 +0,0 @@
-## Pull Request Description
-
-### Summary
-
-
-### Related Issues
-
-Closes #
-
-### Type of Change
-- [ ] π Bug fix (non-breaking change which fixes an issue)
-- [ ] β¨ New feature (non-breaking change which adds functionality)
-- [ ] π₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
-- [ ] π Documentation update
-- [ ] π§ Configuration change
-- [ ] β»οΈ Code refactoring
-- [ ] π§ͺ Test update
-- [ ] β‘ Performance improvement
-
-### Clinical Context
-
-- **Workflow**:
-- **Standards**:
-- **User Impact**:
-
----
-
-## Code Quality Checklist
-
-### General Requirements
-- [ ] **Type Hints**: All functions/methods have complete type hints (Python 3.9+)
-- [ ] **Docstrings**: Functions include docstrings with clinical/business context
-- [ ] **Error Handling**: Uses `StandardErrorResponse` patterns
-- [ ] **Code Style**: Follows PEP 8, passes `black` and `flake8`
-- [ ] **No Hardcoded Values**: Configuration in environment variables
-
-### Multi-Tenancy
-- [ ] **Tenant Isolation**: `tenant_id` validated in all operations
-- [ ] **Database Queries**: All queries filtered by tenant schema
-- [ ] **Cache Keys**: All cache keys prefixed with `tenant:{tenant_id}:`
-- [ ] **No Cross-Tenant Access**: Integration test verifies isolation
-- [ ] **Tenant Context**: Propagated through all service calls
-
-### Security & Compliance
-- [ ] **No Secrets**: No API keys, passwords, or secrets in code
-- [ ] **Input Validation**: All user inputs validated with Pydantic
-- [ ] **SQL Injection**: Only parameterized queries used
-- [ ] **XSS Prevention**: All output properly escaped
-- [ ] **Audit Logging**: PHI access logged with cryptographic verification
-- [ ] **HIPAA Compliant**: No PHI in application logs
-- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints
-
-### Performance
-- [ ] **SLA Target**: Documented and tested (<200ms p95 for API endpoints)
-- [ ] **Database Queries**: No N+1 patterns, uses eager loading
-- [ ] **Caching**: Implements appropriate caching tier (1-4)
-- [ ] **Async Operations**: Long-running tasks use background workers
-- [ ] **Resource Limits**: No unbounded queries or memory allocations
-
-### Observability
-- [ ] **Structured Logging**: Uses `structlog` with required fields
-- [ ] **Distributed Tracing**: OpenTelemetry spans with clinical context
-- [ ] **Metrics**: Prometheus metrics for key operations
-- [ ] **Trace Context**: `trace_id` included in all logs
-- [ ] **Healthcare Metrics**: App-specific metrics (bed occupancy, wait times, etc.)
-
-### Testing
-- [ ] **Unit Tests**: Added/updated with β₯85% coverage
-- [ ] **Integration Tests**: Critical workflows tested
-- [ ] **Test Isolation**: Tests don't depend on each other
-- [ ] **Performance Tests**: Validates SLA compliance
-- [ ] **Multi-Tenancy Tests**: Verifies tenant isolation
-- [ ] **All Tests Pass**: β
`pytest` runs successfully
-
-### Standards Compliance
-- [ ] **Clinical Standards**: CLSI/ACGME/ASA/WHO compliance verified (if applicable)
-- [ ] **Medical Coding**: ICD-10/CPT codes validated
-- [ ] **Laboratory**: CLSI standards followed (if applicable)
-- [ ] **Surgical**: WHO checklist implemented (if applicable)
-- [ ] **Education**: ACGME requirements met (if applicable)
-
-### Documentation
-- [ ] **API Documentation**: OpenAPI/Swagger updated
-- [ ] **Architecture Docs**: Updated if architecture changes
-- [ ] **README**: Updated if setup process changes
-- [ ] **CHANGELOG**: Entry added for this change
-- [ ] **Migration Guide**: Included if breaking change
-
----
-
-## Testing Evidence
-
-### Test Results
-```bash
-# Paste output of pytest run
-pytest tests/ -v
-```
-
-### Coverage Report
-```bash
-# Paste coverage summary
-pytest --cov=src --cov-report=term-missing
-```
-
-### Performance Benchmarks
-
-- **Before**: p95 = ___ ms
-- **After**: p95 = ___ ms
-- **Improvement**: ___%
-
----
-
-## Deployment Considerations
-
-### Database Migrations
-- [ ] **Migration Required**: Yes / No
-- [ ] **Migration Tested**: Forward and backward migrations tested
-- [ ] **Data Migration**: Data migration script included (if needed)
-- [ ] **Rollback Plan**: Documented rollback procedure
-
-### Configuration Changes
-- [ ] **Environment Variables**: New variables documented
-- [ ] **Feature Flags**: Feature flag added (if needed)
-- [ ] **Cache Invalidation**: Cache keys invalidated if needed
-
-### Dependencies
-- [ ] **New Dependencies**: Added to `requirements.txt` with version pinning
-- [ ] **Security Scan**: Dependencies scanned for vulnerabilities
-- [ ] **License Check**: New dependencies have compatible licenses
-
-### Monitoring & Alerts
-- [ ] **Metrics Added**: New Prometheus metrics defined
-- [ ] **Dashboards Updated**: Grafana dashboards include new metrics
-- [ ] **Alerts Configured**: Alerts set for SLA violations
-- [ ] **Logging Verified**: Logs searchable in Kibana
-
----
-
-## Reviewer Checklist
-
-### Code Review
-- [ ] Code is clear and maintainable
-- [ ] Architecture patterns followed
-- [ ] No code duplication
-- [ ] Error handling is comprehensive
-- [ ] Security best practices followed
-
-### Testing Review
-- [ ] Tests cover edge cases
-- [ ] Test data is realistic
-- [ ] Tests are deterministic
-- [ ] Performance benchmarks met
-
-### Documentation Review
-- [ ] Documentation is accurate
-- [ ] Examples are clear
-- [ ] Clinical context explained
-- [ ] Breaking changes highlighted
-
----
-
-## Additional Notes
-
-### Breaking Changes
-
-
-### Known Limitations
-
-
-### Follow-up Tasks
-
-- [ ]
-- [ ]
-
----
-
-## Screenshots / Demo
-
-
----
-
-## Pre-Merge Checklist
-
-**Before merging, ensure:**
-- [ ] All CI/CD checks passing
-- [ ] At least 2 approvals from reviewers
-- [ ] No unresolved comments
-- [ ] Merge conflicts resolved
-- [ ] CHANGELOG.md updated
-- [ ] Documentation deployed
-- [ ] Deployment plan reviewed
-
----
-
-**By submitting this PR, I confirm that:**
-- β
My code follows YAZ Care Platform coding standards
-- β
I have performed a self-review of my own code
-- β
I have commented my code, particularly in hard-to-understand areas
-- β
I have made corresponding changes to the documentation
-- β
My changes generate no new warnings
-- β
I have added tests that prove my fix is effective or that my feature works
-- β
New and existing unit tests pass locally with my changes
-- β
Any dependent changes have been merged and published
-
----
-
-**Reviewer:** @reviewer-username
-**Estimated Review Time:**
diff --git a/.github/README.md b/.github/README.md
deleted file mode 100644
index e45dd21443b98399c21a2bf27722a8d315e1a653..0000000000000000000000000000000000000000
--- a/.github/README.md
+++ /dev/null
@@ -1,296 +0,0 @@
-# .github Folder Organization
-
-This folder contains GitHub-specific configuration and documentation for the YAZ Care platform.
-
-## π Folder Structure
-
-```
-.github/
-βββ AI_CODER_INSTRUCTIONS.md # π€ Master guide for AI coding assistants
-βββ CODEOWNERS # Code ownership assignments
-βββ PULL_REQUEST_TEMPLATE.md # PR template
-βββ README.md # This file
-β
-βββ config/ # Configuration files
-β βββ .flake8 # Python linting rules
-β βββ .pre-commit-config.yaml # Pre-commit hooks
-β
-βββ docs/ # GitHub documentation
-β βββ COPILOT_GUIDE.md # GitHub Copilot quick reference
-β βββ DOCUMENTATION_INDEX.md # Legacy doc index (moved to docs/00-INDEX.md)
-β
-βββ prompts/ # Reusable AI prompts library
-β βββ advanced-patterns.md
-β βββ clinical-decision-support.md
-β βββ database-patterns.md
-β βββ multi-tenancy-patterns.md
-β βββ observability-patterns.md
-β βββ security-compliance.md
-β βββ testing-protocol.md
-β βββ testing-strategies.md
-β
-βββ workflows/ # GitHub Actions CI/CD
- βββ quality-gates.yml # π₯ Main CI/CD pipeline (8 stages)
- βββ deploy-enhanced.yml # Production deployment (blue-green)
- βββ security-scanning.yml # Security vulnerability scanning
- βββ ci-tests.yml # Test automation
- βββ [other workflows]
-```
-
-## π€ AI Coder Instructions
-
-**Primary File**: [`AI_CODER_INSTRUCTIONS.md`](./AI_CODER_INSTRUCTIONS.md)
-
-This is the **authoritative guide** for any AI coding assistant (GitHub Copilot, Claude, ChatGPT, etc.) working on the YAZ Care platform.
-
-**Contents**:
-- Platform overview (17 healthcare modules, 50K+ LOC)
-- Core mandate & principles (patient safety, multi-tenancy, HIPAA, performance, quality)
-- Architecture patterns (DDD, event-driven, CQRS, multi-tenant)
-- Code generation standards (type hints, docstrings, error handling, logging)
-- Clinical standards compliance (CLSI, ASA, WHO, ACGME)
-- Security & HIPAA requirements (encryption, audit logging, access control)
-- Performance engineering (4-tier caching, database optimization)
-- Testing requirements (85%+ coverage, multi-tenancy tests)
-- File organization & naming conventions
-- Development workflow (5-phase cycle)
-- Common patterns & templates
-- Troubleshooting guide
-- Future iterations roadmap
-- References & resources
-
-**Usage**:
-```bash
-# For AI assistants
-"Read .github/AI_CODER_INSTRUCTIONS.md before starting any implementation"
-
-# For new developers
-"Review .github/AI_CODER_INSTRUCTIONS.md during onboarding"
-
-# For code reviews
-"Verify implementation follows .github/AI_CODER_INSTRUCTIONS.md standards"
-```
-
-## π Documentation Locations
-
-### Primary Documentation
-- **Main Docs**: `/docs/` - Comprehensive platform documentation
-- **Quick Navigation**: `/docs/00-INDEX.md` - Fast access to all docs
-- **Module Docs**: `/docs/06-modules/{module_name}/README.md` - Per-module guides
-- **Development**: `/docs/03-development/` - Developer guides and templates
-
-### GitHub-Specific Docs
-- **AI Instructions**: `.github/AI_CODER_INSTRUCTIONS.md` - This folder
-- **Copilot Guide**: `.github/docs/COPILOT_GUIDE.md` - Quick reference
-- **Prompts Library**: `.github/prompts/` - Reusable prompts
-
-## π§ Configuration Files
-
-### Linting & Formatting
-```bash
-# Flake8 (Python linting)
-flake8 src/ tests/ --config=.github/config/.flake8
-
-# Black (Python formatting)
-black src/ tests/
-
-# isort (Import sorting)
-isort src/ tests/
-```
-
-### Pre-commit Hooks
-```bash
-# Install hooks
-pre-commit install --config .github/config/.pre-commit-config.yaml
-
-# Run manually
-pre-commit run --all-files --config .github/config/.pre-commit-config.yaml
-```
-
-## π CI/CD Workflows
-
-### Main Pipeline: `quality-gates.yml`
-
-**8-Stage Quality Gates**:
-1. **Checkout & Setup** - Python 3.11, dependencies
-2. **Linting** - flake8, black, isort
-3. **Type Checking** - mypy strict mode
-4. **Unit Tests** - pytest with coverage (85%+ target)
-5. **Integration Tests** - API endpoint validation
-6. **Security Scan** - Bandit, Safety
-7. **Performance Tests** - Locust load testing
-8. **Documentation** - MkDocs build
-
-**Triggers**:
-- Push to `master` or `develop`
-- Pull requests
-- Manual workflow dispatch
-
-### Deployment: `deploy-enhanced.yml`
-
-**Blue-Green Deployment**:
-1. Deploy to staging (blue environment)
-2. Run smoke tests
-3. Switch traffic to blue
-4. Monitor metrics (5 minutes)
-5. Rollback if errors >1%
-6. Mark green environment as standby
-
-**Manual approval required for production**
-
-### Security: `security-scanning.yml`
-
-**Scans**:
-- Dependency vulnerabilities (Safety)
-- Code security issues (Bandit)
-- Secrets detection (Gitleaks)
-- Container image scanning (Trivy)
-
-## π Prompts Library
-
-Located in `.github/prompts/`, these are reusable AI prompts for common tasks:
-
-| Prompt File | Purpose |
-|-------------|---------|
-| `clinical-decision-support.md` | Healthcare algorithm patterns |
-| `multi-tenancy-patterns.md` | Tenant isolation best practices |
-| `observability-patterns.md` | Tracing, metrics, logging |
-| `security-compliance.md` | HIPAA/audit logging checklist |
-| `testing-protocol.md` | Test patterns and coverage |
-| `database-patterns.md` | Query optimization, indexing |
-| `advanced-patterns.md` | CQRS, event sourcing, DDD |
-
-**Usage**:
-```bash
-# Reference in AI prompts
-"Follow patterns in .github/prompts/multi-tenancy-patterns.md"
-
-# Copy template
-cp .github/prompts/testing-protocol.md src/apps/new_module/tests/
-```
-
-## π οΈ Common Tasks
-
-### For AI Assistants
-
-**Before starting any task**:
-```bash
-# 1. Read AI instructions
-cat .github/AI_CODER_INSTRUCTIONS.md
-
-# 2. Check module documentation
-cat docs/06-modules/{module_name}/README.md
-
-# 3. Review relevant prompt
-cat .github/prompts/{relevant_pattern}.md
-```
-
-### For Developers
-
-**Setting up development environment**:
-```bash
-# 1. Install pre-commit hooks
-pre-commit install --config .github/config/.pre-commit-config.yaml
-
-# 2. Run quality checks
-make lint # Uses .github/config/.flake8
-make typecheck # mypy strict
-make test # pytest with coverage
-
-# 3. Review documentation
-open docs/00-INDEX.md
-```
-
-### For Code Reviewers
-
-**PR review checklist**:
-- [ ] Follows `.github/AI_CODER_INSTRUCTIONS.md` standards
-- [ ] All quality gates passing (`.github/workflows/quality-gates.yml`)
-- [ ] Multi-tenancy tests included
-- [ ] HIPAA audit logging implemented
-- [ ] Performance targets documented and met
-- [ ] Documentation updated
-
-## π Contributing Guidelines
-
-### File Organization Rules
-
-**Configuration files** β `.github/config/`
-- Linting configs (`.flake8`, `.pylintrc`)
-- Pre-commit hooks (`.pre-commit-config.yaml`)
-- Editor configs (`.editorconfig`)
-
-**Documentation** β `.github/docs/`
-- GitHub-specific guides
-- Quick references
-- Legacy documentation
-
-**Reusable Prompts** β `.github/prompts/`
-- AI coding patterns
-- Best practices
-- Template prompts
-
-**CI/CD Workflows** β `.github/workflows/`
-- GitHub Actions YAML files
-- Deployment pipelines
-- Automation scripts
-
-### Naming Conventions
-
-**Workflows**: `kebab-case.yml`
-```
-quality-gates.yml
-deploy-enhanced.yml
-security-scanning.yml
-```
-
-**Documentation**: `SCREAMING_SNAKE_CASE.md` (top-level), `kebab-case.md` (subdirs)
-```
-AI_CODER_INSTRUCTIONS.md
-CODEOWNERS
-docs/copilot-guide.md
-```
-
-**Prompts**: `kebab-case.md`
-```
-multi-tenancy-patterns.md
-clinical-decision-support.md
-```
-
-## π Quick Links
-
-### Documentation
-- [Main Documentation](../docs/README.md)
-- [Quick Navigation](../docs/00-INDEX.md)
-- [Development Guide](../docs/03-development/README.md)
-
-### AI Resources
-- [AI Coder Instructions](./AI_CODER_INSTRUCTIONS.md) β
-- [Copilot Guide](./docs/COPILOT_GUIDE.md)
-- [Prompts Library](./prompts/)
-
-### Configuration
-- [Linting Config](./config/.flake8)
-- [Pre-commit Hooks](./config/.pre-commit-config.yaml)
-
-### CI/CD
-- [Quality Gates Workflow](./workflows/quality-gates.yml)
-- [Deployment Workflow](./workflows/deploy-enhanced.yml)
-- [All Workflows](./workflows/)
-
-## π Status
-
-| Component | Status | Notes |
-|-----------|--------|-------|
-| **AI Instructions** | β
Complete | v5.0.0 (Dec 26, 2025) |
-| **Folder Organization** | β
Complete | Organized into 4 subdirectories |
-| **Quality Gates** | β
Active | 8-stage pipeline |
-| **Deployment** | β
Active | Blue-green strategy |
-| **Security Scanning** | β
Active | Daily scans |
-| **Documentation** | β
Up-to-date | Synchronized with main docs |
-
----
-
-**Last Updated**: December 26, 2025
-**Maintained By**: YAZ Care Platform Team
-**Status**: π’ Organized and Production-Ready
diff --git a/.github/config/.flake8 b/.github/config/.flake8
deleted file mode 100644
index bfcead4159cc695a71940822912fce0ba0ef0816..0000000000000000000000000000000000000000
--- a/.github/config/.flake8
+++ /dev/null
@@ -1,20 +0,0 @@
-[flake8]
-max-line-length = 88
-extend-ignore = E203, W503, E501
-exclude =
- .git,
- __pycache__,
- .pytest_cache,
- htmlcov,
- build,
- dist,
- *.egg-info,
- .tox,
- .coverage,
- migrations,
- venv,
- virtualenv
-per-file-ignores =
- __init__.py:F401
- tests/*:S101,S106
-max-complexity = 10
\ No newline at end of file
diff --git a/.github/config/.pre-commit-config.yaml b/.github/config/.pre-commit-config.yaml
deleted file mode 100755
index 3cd860ace46be98f853e9fd8c2a4e1150a9d6739..0000000000000000000000000000000000000000
--- a/.github/config/.pre-commit-config.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-repos:
- - repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.4.8
- hooks:
- - id: ruff
- args: [--fix]
- - id: ruff-format
-
- - repo: local
- hooks:
- - id: no-star-imports
- name: Prevent star imports
- entry: bash -c 'if grep -r "from .* import \*" src/ --include="*.py" | grep -v "# noqa"; then echo "β Star imports found!"; exit 1; fi'
- language: system
- pass_filenames: false
- stages: [pre-commit]
diff --git a/.github/copilot-prompts/advanced-patterns.md b/.github/copilot-prompts/advanced-patterns.md
deleted file mode 100644
index de4bd7ed7dfafe9a56a74b4ae9f800c06bea4b50..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/advanced-patterns.md
+++ /dev/null
@@ -1,847 +0,0 @@
-# Advanced Development Patterns for YAZ Care Platform
-
-## Overview
-This document covers advanced patterns for building sophisticated healthcare features, including TOPSIS decision-making, event-driven architecture, background processing, and integration patterns.
-
-## 1. TOPSIS Multi-Criteria Decision Making
-
-### Clinical Context
-TOPSIS (Technique for Order Preference by Similarity to Ideal Solution) is used for complex clinical decisions involving multiple weighted criteria, such as surgical case prioritization, treatment plan selection, and resource allocation.
-
-### Implementation Pattern
-
-```python
-from typing import List, Dict, Any, Optional
-import numpy as np
-from pydantic import BaseModel, Field
-import structlog
-
-logger = structlog.get_logger()
-
-class CriterionWeight(BaseModel):
- """Weight configuration for TOPSIS criterion."""
- name: str
- weight: float = Field(..., gt=0, le=1)
- benefit: bool = True # True if higher is better, False if lower is better
- min_threshold: Optional[float] = None
- max_threshold: Optional[float] = None
-
-class TOPSISDecision(BaseModel):
- """TOPSIS analysis result."""
- alternative_id: str
- score: float = Field(..., ge=0, le=1)
- rank: int
- distance_to_ideal: float
- distance_to_negative: float
- criteria_scores: Dict[str, float]
- metadata: Dict[str, Any] = {}
-
-class TOPSISAnalyzer:
- """
- Multi-criteria decision analysis using TOPSIS.
-
- Clinical Context: Supports evidence-based clinical decision-making
- with multiple weighted factors (efficacy, safety, cost, accessibility).
-
- Standards: Follows AHRQ (Agency for Healthcare Research and Quality)
- comparative effectiveness research guidelines.
-
- Performance: <100ms for up to 100 alternatives, <500ms for 1000+
- """
-
- def __init__(
- self,
- criteria: List[CriterionWeight],
- tenant_id: str
- ):
- self.criteria = criteria
- self.tenant_id = tenant_id
- self._validate_weights()
-
- def _validate_weights(self) -> None:
- """Ensure weights sum to 1.0."""
- total_weight = sum(c.weight for c in self.criteria)
- if not (0.99 <= total_weight <= 1.01):
- raise ValueError(f"Weights must sum to 1.0, got {total_weight}")
-
- async def analyze(
- self,
- alternatives: List[Dict[str, Any]],
- user_id: str,
- trace_context: Optional[Dict[str, Any]] = None
- ) -> List[TOPSISDecision]:
- """
- Perform TOPSIS analysis on alternatives.
-
- Args:
- alternatives: List of options with criterion values
- user_id: For audit logging
- trace_context: OpenTelemetry context
-
- Returns:
- Ranked list of alternatives with scores
-
- Raises:
- ValueError: Invalid input data
-
- Performance: O(n*m) where n=alternatives, m=criteria
- """
- if not alternatives:
- raise ValueError("At least one alternative required")
-
- logger.info(
- "topsis_analysis_started",
- tenant_id=self.tenant_id,
- user_id=user_id,
- alternative_count=len(alternatives),
- criteria_count=len(self.criteria)
- )
-
- # Step 1: Build decision matrix
- matrix = self._build_matrix(alternatives)
-
- # Step 2: Normalize matrix
- normalized = self._normalize_matrix(matrix)
-
- # Step 3: Apply weights
- weighted = self._apply_weights(normalized)
-
- # Step 4: Calculate ideal and negative-ideal solutions
- ideal = self._calculate_ideal_solution(weighted)
- negative_ideal = self._calculate_negative_ideal(weighted)
-
- # Step 5: Calculate distances and scores
- decisions = []
- for idx, alt in enumerate(alternatives):
- d_positive = np.linalg.norm(weighted[idx] - ideal)
- d_negative = np.linalg.norm(weighted[idx] - negative_ideal)
-
- score = d_negative / (d_positive + d_negative) if (d_positive + d_negative) > 0 else 0
-
- decisions.append(TOPSISDecision(
- alternative_id=alt["id"],
- score=float(score),
- rank=0, # Will be assigned after sorting
- distance_to_ideal=float(d_positive),
- distance_to_negative=float(d_negative),
- criteria_scores={
- c.name: float(weighted[idx][i])
- for i, c in enumerate(self.criteria)
- },
- metadata=alt.get("metadata", {})
- ))
-
- # Step 6: Rank alternatives
- decisions.sort(key=lambda x: x.score, reverse=True)
- for rank, decision in enumerate(decisions, start=1):
- decision.rank = rank
-
- logger.info(
- "topsis_analysis_completed",
- tenant_id=self.tenant_id,
- top_alternative=decisions[0].alternative_id if decisions else None,
- top_score=decisions[0].score if decisions else None
- )
-
- return decisions
-
- def _build_matrix(self, alternatives: List[Dict[str, Any]]) -> np.ndarray:
- """Build decision matrix from alternatives."""
- matrix = []
- for alt in alternatives:
- row = [alt.get(c.name, 0.0) for c in self.criteria]
- matrix.append(row)
- return np.array(matrix)
-
- def _normalize_matrix(self, matrix: np.ndarray) -> np.ndarray:
- """Normalize using vector normalization."""
- norms = np.linalg.norm(matrix, axis=0)
- return matrix / norms
-
- def _apply_weights(self, normalized: np.ndarray) -> np.ndarray:
- """Apply criterion weights to normalized matrix."""
- weights = np.array([c.weight for c in self.criteria])
- return normalized * weights
-
- def _calculate_ideal_solution(self, weighted: np.ndarray) -> np.ndarray:
- """Calculate ideal solution (best values for each criterion)."""
- ideal = []
- for i, criterion in enumerate(self.criteria):
- if criterion.benefit:
- ideal.append(np.max(weighted[:, i]))
- else:
- ideal.append(np.min(weighted[:, i]))
- return np.array(ideal)
-
- def _calculate_negative_ideal(self, weighted: np.ndarray) -> np.ndarray:
- """Calculate negative-ideal solution (worst values)."""
- negative_ideal = []
- for i, criterion in enumerate(self.criteria):
- if criterion.benefit:
- negative_ideal.append(np.min(weighted[:, i]))
- else:
- negative_ideal.append(np.max(weighted[:, i]))
- return np.array(negative_ideal)
-
-# Example Usage in Surgio Module
-async def prioritize_surgical_cases(
- tenant_id: str,
- user_id: str,
- cases: List[Dict[str, Any]]
-) -> List[TOPSISDecision]:
- """
- Prioritize surgical cases using TOPSIS.
-
- Clinical Context: Operating room scheduling with multiple factors
- Standards: ASA guidelines, hospital capacity planning
- Performance: <200ms for typical case load (50 cases)
- """
- criteria = [
- CriterionWeight(name="urgency_score", weight=0.35, benefit=True),
- CriterionWeight(name="patient_asa_class", weight=0.25, benefit=False), # Lower is better
- CriterionWeight(name="procedure_duration_hours", weight=0.15, benefit=False),
- CriterionWeight(name="resource_availability", weight=0.15, benefit=True),
- CriterionWeight(name="days_waiting", weight=0.10, benefit=True)
- ]
-
- analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id=tenant_id)
- return await analyzer.analyze(alternatives=cases, user_id=user_id)
-```
-
-### Testing TOPSIS Implementation
-
-```python
-import pytest
-import numpy as np
-
-def test_topsis_surgical_prioritization_high_urgency():
- """Test TOPSIS correctly prioritizes high-urgency cases."""
- criteria = [
- CriterionWeight(name="urgency_score", weight=0.5, benefit=True),
- CriterionWeight(name="asa_class", weight=0.5, benefit=False)
- ]
-
- cases = [
- {"id": "case-1", "urgency_score": 9, "asa_class": 2}, # High urgency, low risk
- {"id": "case-2", "urgency_score": 5, "asa_class": 1}, # Medium urgency, very low risk
- {"id": "case-3", "urgency_score": 8, "asa_class": 4}, # High urgency, high risk
- ]
-
- analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant")
- results = await analyzer.analyze(alternatives=cases, user_id="test-user")
-
- # Case-1 should rank highest (high urgency + low risk)
- assert results[0].alternative_id == "case-1"
- assert results[0].rank == 1
- assert results[0].score > 0.6
-
-@pytest.mark.performance
-async def test_topsis_performance_large_dataset():
- """Verify TOPSIS meets performance target with large dataset."""
- import time
-
- criteria = [
- CriterionWeight(name="factor1", weight=0.5, benefit=True),
- CriterionWeight(name="factor2", weight=0.5, benefit=False)
- ]
-
- # Generate 500 alternatives
- cases = [
- {"id": f"case-{i}", "factor1": np.random.rand(), "factor2": np.random.rand()}
- for i in range(500)
- ]
-
- analyzer = TOPSISAnalyzer(criteria=criteria, tenant_id="test-tenant")
-
- start = time.time()
- results = await analyzer.analyze(alternatives=cases, user_id="test-user")
- duration_ms = (time.time() - start) * 1000
-
- assert duration_ms < 500 # Must complete in <500ms
- assert len(results) == 500
- assert all(r.rank > 0 for r in results)
-```
-
----
-
-## 2. Event-Driven Architecture Patterns
-
-### Domain Events for Cross-App Communication
-
-```python
-from typing import Dict, Any, Optional
-from datetime import datetime
-from pydantic import BaseModel, Field
-from enum import Enum
-import structlog
-
-logger = structlog.get_logger()
-
-class EventType(str, Enum):
- """Domain event types."""
- PATIENT_ADMITTED = "patient.admitted"
- SURGERY_SCHEDULED = "surgery.scheduled"
- LAB_RESULT_CRITICAL = "lab.result.critical"
- MEDICATION_PRESCRIBED = "medication.prescribed"
- MEDICATION_INTERACTION_DETECTED = "medication.interaction.detected"
-
-class DomainEvent(BaseModel):
- """Base class for all domain events."""
- event_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
- event_type: EventType
- tenant_id: str
- timestamp: datetime = Field(default_factory=datetime.utcnow)
- source_app: str
- user_id: str
- payload: Dict[str, Any]
- metadata: Dict[str, Any] = {}
- trace_id: Optional[str] = None
-
-class EventPublisher:
- """
- Publish domain events to message queue (Redis Streams).
-
- Performance: <10ms per event publish
- Reliability: At-least-once delivery guarantee
- """
-
- def __init__(self, redis_client, tenant_id: str):
- self.redis = redis_client
- self.tenant_id = tenant_id
- self.stream_prefix = f"events:{tenant_id}"
-
- async def publish(
- self,
- event: DomainEvent,
- user_id: str
- ) -> str:
- """
- Publish event to Redis Stream.
-
- Returns:
- Event ID for tracking
- """
- stream_key = f"{self.stream_prefix}:{event.event_type.value}"
-
- event_data = {
- "event_id": event.event_id,
- "payload": json.dumps(event.payload),
- "metadata": json.dumps(event.metadata),
- "timestamp": event.timestamp.isoformat(),
- "user_id": user_id,
- "trace_id": event.trace_id or "unknown"
- }
-
- # Publish to Redis Stream
- stream_id = await self.redis.xadd(stream_key, event_data)
-
- logger.info(
- "event_published",
- event_type=event.event_type.value,
- event_id=event.event_id,
- stream_id=stream_id,
- tenant_id=self.tenant_id
- )
-
- return event.event_id
-
-class EventSubscriber:
- """
- Subscribe to domain events from message queue.
-
- Pattern: Consumer group for load balancing and reliability
- """
-
- def __init__(
- self,
- redis_client,
- tenant_id: str,
- consumer_group: str,
- consumer_name: str
- ):
- self.redis = redis_client
- self.tenant_id = tenant_id
- self.consumer_group = consumer_group
- self.consumer_name = consumer_name
- self.handlers: Dict[EventType, callable] = {}
-
- def register_handler(
- self,
- event_type: EventType,
- handler: callable
- ) -> None:
- """Register handler function for event type."""
- self.handlers[event_type] = handler
-
- async def start_consuming(self) -> None:
- """Start consuming events from subscribed streams."""
- streams = {
- f"events:{self.tenant_id}:{et.value}": ">"
- for et in self.handlers.keys()
- }
-
- while True:
- try:
- # Read from multiple streams
- events = await self.redis.xreadgroup(
- groupname=self.consumer_group,
- consumername=self.consumer_name,
- streams=streams,
- count=10,
- block=5000 # 5 second timeout
- )
-
- for stream, messages in events:
- for message_id, data in messages:
- await self._process_event(stream, message_id, data)
-
- except Exception as e:
- logger.error(
- "event_consumption_error",
- error=str(e),
- tenant_id=self.tenant_id
- )
- await asyncio.sleep(1)
-
- async def _process_event(
- self,
- stream: str,
- message_id: str,
- data: Dict[str, Any]
- ) -> None:
- """Process individual event."""
- try:
- event_type_str = stream.split(":")[-1]
- event_type = EventType(event_type_str)
-
- handler = self.handlers.get(event_type)
- if handler:
- await handler(data)
-
- # Acknowledge message
- await self.redis.xack(stream, self.consumer_group, message_id)
-
- logger.info(
- "event_processed",
- event_type=event_type_str,
- message_id=message_id
- )
- except Exception as e:
- logger.error(
- "event_processing_error",
- error=str(e),
- message_id=message_id
- )
-
-# Example: Cross-app event handling
-# Pharma app listens for surgery scheduled events to prepare medications
-
-async def handle_surgery_scheduled(event_data: Dict[str, Any]) -> None:
- """
- Handle surgery scheduled event in Pharma app.
-
- Clinical Context: Preoperative medication preparation
- """
- payload = json.loads(event_data["payload"])
- patient_id = payload["patient_id"]
- surgery_datetime = payload["scheduled_datetime"]
- procedure_type = payload["procedure_type"]
-
- # Retrieve patient medications
- medications = await get_patient_medications(
- tenant_id=event_data["tenant_id"],
- patient_id=patient_id
- )
-
- # Check for medications that need adjustment before surgery
- preop_adjustments = await check_preoperative_medication_adjustments(
- medications=medications,
- procedure_type=procedure_type
- )
-
- if preop_adjustments:
- # Publish event for clinical team
- await publish_event(
- event_type=EventType.MEDICATION_ADJUSTMENT_REQUIRED,
- payload={
- "patient_id": patient_id,
- "surgery_id": payload["surgery_id"],
- "adjustments": preop_adjustments
- }
- )
-```
-
----
-
-## 3. Background Job Processing
-
-### Celery Task Patterns
-
-```python
-from celery import Celery, Task
-from typing import Dict, Any
-import structlog
-
-logger = structlog.get_logger()
-
-# Celery app configuration
-celery_app = Celery(
- "yaz_care",
- broker="redis://localhost:6379/0",
- backend="redis://localhost:6379/1"
-)
-
-celery_app.conf.update(
- task_serializer="json",
- accept_content=["json"],
- result_serializer="json",
- timezone="UTC",
- enable_utc=True,
- task_track_started=True,
- task_time_limit=3600, # 1 hour max
- task_soft_time_limit=3300, # 55 minutes soft limit
-)
-
-class TenantTask(Task):
- """Base task with tenant context."""
-
- def __call__(self, *args, **kwargs):
- """Inject tenant context into task execution."""
- tenant_id = kwargs.get("tenant_id")
- if not tenant_id:
- raise ValueError("tenant_id required for all tasks")
-
- logger.info(
- "task_started",
- task_name=self.name,
- tenant_id=tenant_id,
- task_id=self.request.id
- )
-
- try:
- result = super().__call__(*args, **kwargs)
- logger.info(
- "task_completed",
- task_name=self.name,
- tenant_id=tenant_id,
- task_id=self.request.id
- )
- return result
- except Exception as e:
- logger.error(
- "task_failed",
- task_name=self.name,
- tenant_id=tenant_id,
- task_id=self.request.id,
- error=str(e)
- )
- raise
-
-@celery_app.task(base=TenantTask, bind=True, max_retries=3)
-def generate_clinical_report(
- self,
- tenant_id: str,
- report_type: str,
- patient_id: str,
- date_range: Dict[str, str],
- user_id: str
-) -> Dict[str, Any]:
- """
- Generate comprehensive clinical report (long-running task).
-
- Clinical Context: Regulatory compliance reporting, quality metrics
- Performance: May take 5-30 minutes depending on data volume
- """
- try:
- # Step 1: Gather data from multiple sources
- encounters = fetch_encounters(tenant_id, patient_id, date_range)
- lab_results = fetch_lab_results(tenant_id, patient_id, date_range)
- medications = fetch_medications(tenant_id, patient_id, date_range)
-
- # Step 2: Analyze and aggregate
- report_data = {
- "encounter_summary": analyze_encounters(encounters),
- "lab_trends": analyze_lab_trends(lab_results),
- "medication_adherence": calculate_adherence(medications),
- }
-
- # Step 3: Generate PDF
- pdf_path = generate_pdf_report(report_data, report_type)
-
- # Step 4: Store and notify
- report_id = store_report(tenant_id, patient_id, pdf_path)
-
- notify_user(user_id, f"Report {report_id} ready for review")
-
- return {
- "success": True,
- "report_id": report_id,
- "file_path": pdf_path
- }
-
- except Exception as exc:
- # Retry with exponential backoff
- raise self.retry(exc=exc, countdown=60 * (2 ** self.request.retries))
-
-@celery_app.task(base=TenantTask)
-def process_lab_results_batch(
- tenant_id: str,
- lab_results: List[Dict[str, Any]],
- user_id: str
-) -> Dict[str, Any]:
- """
- Process batch of lab results (CLSI validation, delta checks).
-
- Clinical Context: Quality control, panic value detection
- Standards: CLSI EP17-A2, CLSI GP27
- Performance: ~1000 results per minute
- """
- validated = []
- rejected = []
- alerts = []
-
- for result in lab_results:
- try:
- # Validate against QC rules
- qc_status = validate_qc_rules(result)
-
- if not qc_status.passed:
- rejected.append({
- "result_id": result["id"],
- "reason": qc_status.reason
- })
- continue
-
- # Perform delta check
- delta_check = perform_delta_check(tenant_id, result)
-
- if delta_check.significant_change:
- alerts.append({
- "result_id": result["id"],
- "type": "delta_check_failed",
- "details": delta_check.details
- })
-
- # Check panic values
- if is_panic_value(result):
- alerts.append({
- "result_id": result["id"],
- "type": "panic_value",
- "value": result["value"],
- "reference_range": result["reference_range"]
- })
-
- # Send immediate notification
- notify_critical_result(tenant_id, result, user_id)
-
- validated.append(result)
-
- except Exception as e:
- logger.error(
- "lab_result_processing_error",
- result_id=result.get("id"),
- error=str(e)
- )
- rejected.append({
- "result_id": result.get("id"),
- "reason": f"Processing error: {str(e)}"
- })
-
- return {
- "processed": len(lab_results),
- "validated": len(validated),
- "rejected": len(rejected),
- "alerts": len(alerts),
- "alert_details": alerts
- }
-
-# Task scheduling with Celery Beat
-celery_app.conf.beat_schedule = {
- "daily-quality-metrics": {
- "task": "calculate_daily_quality_metrics",
- "schedule": crontab(hour=2, minute=0), # 2 AM daily
- },
- "hourly-cache-cleanup": {
- "task": "cleanup_expired_cache",
- "schedule": crontab(minute=0), # Every hour
- },
-}
-```
-
----
-
-## 4. Integration Patterns
-
-### External API Integration with Retry Logic
-
-```python
-from typing import Optional, Dict, Any
-import httpx
-from tenacity import (
- retry,
- stop_after_attempt,
- wait_exponential,
- retry_if_exception_type
-)
-import structlog
-
-logger = structlog.get_logger()
-
-class ExternalAPIClient:
- """
- Base client for external healthcare API integrations.
-
- Features:
- - Automatic retry with exponential backoff
- - Circuit breaker pattern
- - Request/response logging
- - Performance monitoring
- """
-
- def __init__(
- self,
- base_url: str,
- api_key: str,
- tenant_id: str,
- timeout: int = 30
- ):
- self.base_url = base_url
- self.api_key = api_key
- self.tenant_id = tenant_id
- self.timeout = timeout
- self.client = httpx.AsyncClient(
- base_url=base_url,
- timeout=timeout,
- headers={
- "Authorization": f"Bearer {api_key}",
- "X-Tenant-ID": tenant_id,
- "User-Agent": "YAZCare/3.8.0"
- }
- )
-
- @retry(
- retry=retry_if_exception_type((httpx.TimeoutException, httpx.NetworkError)),
- stop=stop_after_attempt(3),
- wait=wait_exponential(multiplier=1, min=2, max=10)
- )
- async def get(
- self,
- endpoint: str,
- params: Optional[Dict[str, Any]] = None,
- user_id: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- GET request with retry logic.
-
- Performance: Includes timeout and retry budget in SLA
- """
- logger.info(
- "external_api_request",
- method="GET",
- endpoint=endpoint,
- tenant_id=self.tenant_id,
- user_id=user_id
- )
-
- try:
- response = await self.client.get(endpoint, params=params)
- response.raise_for_status()
-
- logger.info(
- "external_api_response",
- method="GET",
- endpoint=endpoint,
- status_code=response.status_code,
- duration_ms=response.elapsed.total_seconds() * 1000
- )
-
- return response.json()
-
- except httpx.HTTPStatusError as e:
- logger.error(
- "external_api_error",
- method="GET",
- endpoint=endpoint,
- status_code=e.response.status_code,
- error=str(e)
- )
- raise
-
- async def post(
- self,
- endpoint: str,
- data: Dict[str, Any],
- user_id: Optional[str] = None
- ) -> Dict[str, Any]:
- """POST request with retry logic."""
- # Similar implementation to GET
- pass
-
-# Example: FDA Drug Interaction API Integration
-class FDADrugInteractionClient(ExternalAPIClient):
- """
- Client for FDA Drug Interaction API.
-
- Clinical Context: Real-time drug-drug interaction checking
- Standards: FDA Orange Book, RxNorm
- """
-
- def __init__(self, tenant_id: str):
- super().__init__(
- base_url="https://api.fda.gov/drug",
- api_key=os.getenv("FDA_API_KEY"),
- tenant_id=tenant_id
- )
-
- async def check_interactions(
- self,
- drug_names: List[str],
- user_id: str
- ) -> Dict[str, Any]:
- """
- Check drug-drug interactions.
-
- Performance: <500ms target (includes external API call)
- Caching: Results cached for 24h (Tier 4)
- """
- # Check cache first
- cache_key = f"fda:interactions:{':'.join(sorted(drug_names))}"
- cached = await redis.get(cache_key)
- if cached:
- logger.info("fda_interaction_cache_hit", drugs=drug_names)
- return json.loads(cached)
-
- # Call FDA API
- interactions = await self.get(
- endpoint="/interaction.json",
- params={"drug_name": drug_names},
- user_id=user_id
- )
-
- # Cache result
- await redis.setex(
- cache_key,
- 86400, # 24 hours
- json.dumps(interactions)
- )
-
- return interactions
-```
-
----
-
-## Summary
-
-These advanced patterns enable:
-- β
Sophisticated multi-criteria clinical decision-making (TOPSIS)
-- β
Decoupled cross-app communication (Event-Driven Architecture)
-- β
Long-running background processing (Celery)
-- β
Reliable external API integrations with retry logic
-- β
Performance monitoring and caching at all layers
-
-**Always include**:
-- Clinical context in docstrings
-- Performance targets and monitoring
-- Comprehensive error handling
-- Audit logging for compliance
-- Unit and integration tests
diff --git a/.github/copilot-prompts/clinical-decision-support.md b/.github/copilot-prompts/clinical-decision-support.md
deleted file mode 100644
index d112cd4c928c20f0e31e13f3795473e837e79416..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/clinical-decision-support.md
+++ /dev/null
@@ -1,525 +0,0 @@
-# Clinical Decision Support Prompts
-
-## Template: New Clinical Algorithm
-
-### Prompt Structure
-```
-Create a clinical decision support service for [CLINICAL_TASK]
-
-Requirements:
-- Clinical Context: [Describe medical workflow]
-- Input: [Patient data, clinical measurements]
-- Algorithm: [TOPSIS/Rule-based/ML model]
-- Standards: [CLSI/ACGME/ASA/WHO compliance]
-- Output: [Risk score/Recommendation/Alert]
-- Performance: <200ms p95
-- Multi-tenancy: Isolated by tenant_id
-- Observability: Trace clinical decisions
-
-Example Pattern (from Surgio):
-- Input validation with Pydantic
-- Business logic in service layer
-- Database queries with tenant isolation
-- Structured response with metadata
-- Comprehensive test coverage
-- Audit logging for clinical decisions
-
-Include:
-1. Service class with type hints
-2. Pydantic models for validation
-3. Unit tests (happy path + edge cases)
-4. Integration test with database
-5. Performance benchmark test
-6. Documentation with clinical rationale
-```
-
-## Example: Sepsis Screening Algorithm
-
-### Prompt
-```
-Create a sepsis screening clinical decision support service for Clinica app.
-
-Clinical Context:
-Implement early sepsis detection using SIRS (Systemic Inflammatory Response Syndrome)
-criteria and qSOFA (quick Sequential Organ Failure Assessment) scoring. This supports
-emergency department triage and ICU monitoring workflows.
-
-Input Data:
-- Vital signs: temperature, heart rate, respiratory rate, blood pressure
-- Laboratory: WBC count, lactate level
-- Clinical observations: altered mental status, oxygen saturation
-- Patient demographics: age, comorbidities
-
-Algorithm:
-Rule-based scoring system combining:
-1. SIRS criteria (β₯2 of 4 criteria)
-2. qSOFA score (β₯2 of 3 criteria)
-3. Lactate level risk stratification
-4. TOPSIS for overall risk prioritization
-
-Standards: WHO Sepsis-3 definitions, Surviving Sepsis Campaign guidelines
-
-Output:
-- Risk score (0.0-1.0)
-- Severity classification (low/moderate/high/critical)
-- Recommended interventions
-- Time-sensitive alerts (if critical)
-- Supporting evidence (which criteria met)
-
-Performance: Target <100ms (pure calculation), <150ms (with DB lookup)
-
-Multi-tenancy: All queries filtered by tenant_id, cache keys prefixed
-
-Observability:
-- Log: sepsis_screening_started/completed with patient_id (hashed)
-- Trace: span for each scoring component
-- Metrics: screening_duration_ms, high_risk_alert_count
-```
-
-### Expected Implementation Pattern
-
-```python
-from __future__ import annotations
-from typing import Dict, Any, Optional, List
-from pydantic import BaseModel, Field, validator
-from datetime import datetime
-import structlog
-from opentelemetry import trace
-
-logger = structlog.get_logger()
-tracer = trace.get_tracer(__name__)
-
-
-class VitalSigns(BaseModel):
- """Patient vital signs for sepsis screening."""
- temperature: float = Field(..., ge=35.0, le=42.0, description="Temperature in Celsius")
- heart_rate: int = Field(..., ge=40, le=200, description="Heart rate in bpm")
- respiratory_rate: int = Field(..., ge=8, le=40, description="Respiratory rate per minute")
- systolic_bp: int = Field(..., ge=60, le=250, description="Systolic blood pressure")
- oxygen_saturation: Optional[float] = Field(None, ge=50.0, le=100.0)
-
- @validator('temperature')
- def validate_temperature_range(cls, v):
- if v < 36.0 or v > 38.3:
- logger.warning("abnormal_temperature_detected", temp=v)
- return v
-
-
-class LabResults(BaseModel):
- """Laboratory results for sepsis assessment."""
- wbc_count: Optional[float] = Field(None, ge=0, le=50, description="WBC count in thousands/ΞΌL")
- lactate_level: Optional[float] = Field(None, ge=0, le=20, description="Lactate in mmol/L")
-
-
-class SepsisScreeningRequest(BaseModel):
- """Complete sepsis screening input."""
- patient_id: str
- vital_signs: VitalSigns
- lab_results: LabResults
- altered_mental_status: bool = False
- timestamp: datetime = Field(default_factory=datetime.utcnow)
-
-
-class SepsisRiskResponse(BaseModel):
- """Sepsis risk assessment result."""
- risk_score: float = Field(..., ge=0.0, le=1.0)
- severity: str = Field(..., regex="^(low|moderate|high|critical)$")
- sirs_score: int = Field(..., ge=0, le=4)
- qsofa_score: int = Field(..., ge=0, le=3)
- recommendations: List[str]
- alerts: List[str]
- criteria_met: Dict[str, bool]
- screening_timestamp: datetime
-
-
-class SepsisScreeningService:
- """
- Clinical decision support service for sepsis screening.
-
- Implements SIRS and qSOFA scoring with risk stratification per
- Surviving Sepsis Campaign guidelines and WHO Sepsis-3 definitions.
-
- Standards Compliance:
- - WHO Sepsis-3 definitions
- - Surviving Sepsis Campaign guidelines
- - SIRS criteria (β₯2 indicates systemic inflammation)
- - qSOFA score (β₯2 indicates organ dysfunction)
-
- Performance: <150ms p95 (including database queries)
- """
-
- async def screen_patient(
- self,
- tenant_id: str,
- user_id: str,
- screening_data: SepsisScreeningRequest,
- trace_context: Optional[Dict[str, Any]] = None
- ) -> SepsisRiskResponse:
- """
- Perform sepsis risk screening for a patient.
-
- Clinical Context:
- Early sepsis detection is critical for mortality reduction. This service
- identifies patients at risk using validated clinical criteria and triggers
- time-sensitive interventions when indicated.
-
- Args:
- tenant_id: Multi-tenant isolation key
- user_id: Clinician performing screening (audit trail)
- screening_data: Vital signs and lab results
- trace_context: OpenTelemetry span context
-
- Returns:
- SepsisRiskResponse with risk score, severity, and recommendations
-
- Raises:
- ValidationError: Invalid clinical data
- TenantIsolationError: Cross-tenant access attempt
-
- Performance: Target <100ms calculation, <150ms with DB
- """
- with tracer.start_as_current_span("sepsis_screening") as span:
- span.set_attribute("tenant.id", tenant_id)
- span.set_attribute("user.id", user_id)
- span.set_attribute("patient.id", screening_data.patient_id)
-
- logger.info(
- "sepsis_screening_started",
- tenant_id=tenant_id,
- user_id=user_id,
- patient_id=screening_data.patient_id,
- trace_id=format(span.get_span_context().trace_id, '032x')
- )
-
- # Calculate SIRS score
- sirs_score = self._calculate_sirs_score(screening_data)
- span.set_attribute("sirs.score", sirs_score)
-
- # Calculate qSOFA score
- qsofa_score = self._calculate_qsofa_score(screening_data)
- span.set_attribute("qsofa.score", qsofa_score)
-
- # Overall risk using TOPSIS
- risk_score = self._calculate_risk_score(sirs_score, qsofa_score, screening_data)
-
- # Determine severity
- severity = self._determine_severity(risk_score, sirs_score, qsofa_score)
-
- # Generate recommendations
- recommendations = self._generate_recommendations(severity, screening_data)
-
- # Generate alerts
- alerts = self._generate_alerts(severity, screening_data)
-
- # Track criteria met
- criteria_met = self._track_criteria(screening_data, sirs_score, qsofa_score)
-
- response = SepsisRiskResponse(
- risk_score=risk_score,
- severity=severity,
- sirs_score=sirs_score,
- qsofa_score=qsofa_score,
- recommendations=recommendations,
- alerts=alerts,
- criteria_met=criteria_met,
- screening_timestamp=datetime.utcnow()
- )
-
- logger.info(
- "sepsis_screening_completed",
- tenant_id=tenant_id,
- risk_score=risk_score,
- severity=severity,
- trace_id=format(span.get_span_context().trace_id, '032x')
- )
-
- return response
-
- def _calculate_sirs_score(self, data: SepsisScreeningRequest) -> int:
- """Calculate SIRS score (0-4)."""
- score = 0
- vitals = data.vital_signs
-
- # Temperature: <36Β°C or >38.3Β°C
- if vitals.temperature < 36.0 or vitals.temperature > 38.3:
- score += 1
-
- # Heart rate: >90 bpm
- if vitals.heart_rate > 90:
- score += 1
-
- # Respiratory rate: >20/min
- if vitals.respiratory_rate > 20:
- score += 1
-
- # WBC: <4k or >12k
- if data.lab_results.wbc_count:
- if data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0:
- score += 1
-
- return score
-
- def _calculate_qsofa_score(self, data: SepsisScreeningRequest) -> int:
- """Calculate qSOFA score (0-3)."""
- score = 0
-
- # Altered mental status
- if data.altered_mental_status:
- score += 1
-
- # Respiratory rate β₯22/min
- if data.vital_signs.respiratory_rate >= 22:
- score += 1
-
- # Systolic BP β€100 mmHg
- if data.vital_signs.systolic_bp <= 100:
- score += 1
-
- return score
-
- def _calculate_risk_score(
- self,
- sirs_score: int,
- qsofa_score: int,
- data: SepsisScreeningRequest
- ) -> float:
- """Calculate overall risk score using TOPSIS."""
- # Normalize scores
- sirs_normalized = sirs_score / 4.0
- qsofa_normalized = qsofa_score / 3.0
-
- # Lactate risk
- lactate_risk = 0.0
- if data.lab_results.lactate_level:
- if data.lab_results.lactate_level > 4.0:
- lactate_risk = 1.0
- elif data.lab_results.lactate_level > 2.0:
- lactate_risk = 0.5
-
- # Weighted combination (TOPSIS-style)
- weights = [0.4, 0.4, 0.2] # SIRS, qSOFA, lactate
- risk_score = (
- weights[0] * sirs_normalized +
- weights[1] * qsofa_normalized +
- weights[2] * lactate_risk
- )
-
- return min(risk_score, 1.0)
-
- def _determine_severity(
- self,
- risk_score: float,
- sirs_score: int,
- qsofa_score: int
- ) -> str:
- """Determine severity classification."""
- if qsofa_score >= 2 or risk_score >= 0.7:
- return "critical"
- elif sirs_score >= 3 or risk_score >= 0.5:
- return "high"
- elif sirs_score >= 2 or risk_score >= 0.3:
- return "moderate"
- else:
- return "low"
-
- def _generate_recommendations(
- self,
- severity: str,
- data: SepsisScreeningRequest
- ) -> List[str]:
- """Generate clinical recommendations."""
- recommendations = []
-
- if severity == "critical":
- recommendations.extend([
- "IMMEDIATE: Initiate sepsis bundle within 1 hour",
- "Obtain blood cultures before antibiotics",
- "Administer broad-spectrum antibiotics",
- "Begin fluid resuscitation (30 mL/kg crystalloid)",
- "Consider ICU admission",
- "Measure lactate level if not done",
- "Continuous hemodynamic monitoring"
- ])
- elif severity == "high":
- recommendations.extend([
- "Urgent sepsis workup required",
- "Obtain blood cultures",
- "Consider early antibiotics",
- "IV fluid resuscitation",
- "Repeat vital signs q30min",
- "Senior clinician review"
- ])
- elif severity == "moderate":
- recommendations.extend([
- "Close monitoring recommended",
- "Repeat screening in 2-4 hours",
- "Consider source of infection",
- "Ensure adequate hydration"
- ])
- else:
- recommendations.append("Continue routine monitoring")
-
- return recommendations
-
- def _generate_alerts(
- self,
- severity: str,
- data: SepsisScreeningRequest
- ) -> List[str]:
- """Generate time-sensitive alerts."""
- alerts = []
-
- if severity == "critical":
- alerts.append("CRITICAL: High sepsis risk - Immediate intervention required")
-
- if data.lab_results.lactate_level and data.lab_results.lactate_level > 4.0:
- alerts.append("ALERT: Lactate >4 mmol/L - Severe sepsis likely")
-
- if data.vital_signs.systolic_bp < 90:
- alerts.append("ALERT: Hypotension - Possible septic shock")
-
- return alerts
-
- def _track_criteria(
- self,
- data: SepsisScreeningRequest,
- sirs_score: int,
- qsofa_score: int
- ) -> Dict[str, bool]:
- """Track which clinical criteria were met."""
- vitals = data.vital_signs
-
- return {
- "sirs_temperature": vitals.temperature < 36.0 or vitals.temperature > 38.3,
- "sirs_heart_rate": vitals.heart_rate > 90,
- "sirs_respiratory_rate": vitals.respiratory_rate > 20,
- "sirs_wbc": bool(
- data.lab_results.wbc_count and
- (data.lab_results.wbc_count < 4.0 or data.lab_results.wbc_count > 12.0)
- ),
- "qsofa_altered_mental": data.altered_mental_status,
- "qsofa_respiratory": vitals.respiratory_rate >= 22,
- "qsofa_hypotension": vitals.systolic_bp <= 100,
- "sirs_positive": sirs_score >= 2,
- "qsofa_positive": qsofa_score >= 2,
- "elevated_lactate": bool(
- data.lab_results.lactate_level and
- data.lab_results.lactate_level > 2.0
- )
- }
-
-
-# Unit Tests
-import pytest
-
-def test_sepsis_high_risk():
- """Test sepsis screening with high-risk indicators."""
- screening_data = SepsisScreeningRequest(
- patient_id="patient-001",
- vital_signs=VitalSigns(
- temperature=39.5,
- heart_rate=120,
- respiratory_rate=25,
- systolic_bp=95,
- oxygen_saturation=92.0
- ),
- lab_results=LabResults(
- wbc_count=15.0,
- lactate_level=3.5
- ),
- altered_mental_status=True
- )
-
- service = SepsisScreeningService()
-
- # Test SIRS score calculation
- sirs_score = service._calculate_sirs_score(screening_data)
- assert sirs_score >= 3, "High-risk patient should have SIRS β₯3"
-
- # Test qSOFA score calculation
- qsofa_score = service._calculate_qsofa_score(screening_data)
- assert qsofa_score >= 2, "High-risk patient should have qSOFA β₯2"
-
- # Test risk score
- risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data)
- assert risk_score > 0.6, "High-risk patient should have risk score >0.6"
-
- # Test severity
- severity = service._determine_severity(risk_score, sirs_score, qsofa_score)
- assert severity in ["high", "critical"], "Should be classified as high/critical"
-
-
-def test_sepsis_low_risk():
- """Test sepsis screening with low-risk indicators."""
- screening_data = SepsisScreeningRequest(
- patient_id="patient-002",
- vital_signs=VitalSigns(
- temperature=37.0,
- heart_rate=75,
- respiratory_rate=16,
- systolic_bp=120,
- oxygen_saturation=98.0
- ),
- lab_results=LabResults(
- wbc_count=7.5,
- lactate_level=1.2
- ),
- altered_mental_status=False
- )
-
- service = SepsisScreeningService()
-
- sirs_score = service._calculate_sirs_score(screening_data)
- assert sirs_score == 0, "Low-risk patient should have SIRS = 0"
-
- qsofa_score = service._calculate_qsofa_score(screening_data)
- assert qsofa_score == 0, "Low-risk patient should have qSOFA = 0"
-
- risk_score = service._calculate_risk_score(sirs_score, qsofa_score, screening_data)
- assert risk_score < 0.3, "Low-risk patient should have risk score <0.3"
-
- severity = service._determine_severity(risk_score, sirs_score, qsofa_score)
- assert severity == "low", "Should be classified as low risk"
-
-
-@pytest.mark.asyncio
-async def test_sepsis_screening_integration(async_client, tenant_context):
- """Integration test for sepsis screening endpoint."""
- response = await async_client.post(
- "/api/v1/clinica/sepsis/screen",
- json={
- "patient_id": "patient-001",
- "vital_signs": {
- "temperature": 39.5,
- "heart_rate": 120,
- "respiratory_rate": 25,
- "systolic_bp": 95,
- "oxygen_saturation": 92.0
- },
- "lab_results": {
- "wbc_count": 15.0,
- "lactate_level": 3.5
- },
- "altered_mental_status": True
- },
- headers={"X-Tenant-ID": tenant_context["tenant_id"]}
- )
-
- assert response.status_code == 200
- data = response.json()
-
- assert "risk_score" in data
- assert "severity" in data
- assert data["severity"] in ["low", "moderate", "high", "critical"]
- assert len(data["recommendations"]) > 0
-```
-
-## Additional Use Cases
-
-### 1. Stroke Risk Assessment (FAST Score)
-### 2. Cardiac Risk Stratification (HEART Score)
-### 3. Pneumonia Severity Index (PSI/PORT Score)
-### 4. Venous Thromboembolism Risk (Wells Score)
-### 5. Delirium Screening (CAM-ICU)
-
-See individual templates for each clinical algorithm.
diff --git a/.github/copilot-prompts/database-patterns.md b/.github/copilot-prompts/database-patterns.md
deleted file mode 100644
index b7d033f2fb9dde6195a2d1c2776c398f19374d96..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/database-patterns.md
+++ /dev/null
@@ -1,772 +0,0 @@
-# Database Design and Migration Patterns for YAZ Care Platform
-
-## Overview
-This guide covers PostgreSQL database design patterns for multi-tenant healthcare applications, including schema design, indexing strategies, migrations with Alembic, and query optimization.
-
-## Architecture: Schema-Per-Tenant Multi-Tenancy
-
-### Database Structure
-```
-PostgreSQL Database: yaz_care
-βββ public schema (system tables, shared metadata)
-β βββ tenants
-β βββ users
-β βββ audit_logs
-β βββ system_config
-βββ tenant_{tenant_id} schema (isolated per tenant)
-β βββ patients
-β βββ encounters
-β βββ clinical_notes
-β βββ lab_results
-β βββ medications
-β βββ ... (all clinical data)
-βββ shared schema (reference data)
- βββ icd10_codes
- βββ drug_database
- βββ clinical_protocols
- βββ reference_ranges
-```
-
-## 1. Model Design Patterns
-
-### Base Model with Tenant Isolation
-
-```python
-from sqlmodel import SQLModel, Field
-from datetime import datetime
-from typing import Optional
-from uuid import uuid4
-
-class TenantBaseModel(SQLModel):
- """
- Base model for all tenant-specific tables.
-
- Required Fields:
- - id: Primary key (UUID)
- - tenant_id: Foreign key to tenants table (indexed)
- - created_at: Audit timestamp
- - updated_at: Audit timestamp
- - created_by: User who created record
- - updated_by: User who last updated record
- """
-
- id: str = Field(
- default_factory=lambda: str(uuid4()),
- primary_key=True,
- description="Unique identifier (UUID)"
- )
-
- tenant_id: str = Field(
- index=True,
- nullable=False,
- foreign_key="public.tenants.id",
- description="Multi-tenant isolation key"
- )
-
- created_at: datetime = Field(
- default_factory=datetime.utcnow,
- nullable=False,
- description="Record creation timestamp (UTC)"
- )
-
- updated_at: datetime = Field(
- default_factory=datetime.utcnow,
- nullable=False,
- description="Record last update timestamp (UTC)"
- )
-
- created_by: str = Field(
- nullable=False,
- foreign_key="public.users.id",
- description="User ID who created this record"
- )
-
- updated_by: Optional[str] = Field(
- default=None,
- foreign_key="public.users.id",
- description="User ID who last updated this record"
- )
-
- is_deleted: bool = Field(
- default=False,
- nullable=False,
- description="Soft delete flag (HIPAA retention)"
- )
-
- deleted_at: Optional[datetime] = Field(
- default=None,
- description="Soft delete timestamp"
- )
-
- deleted_by: Optional[str] = Field(
- default=None,
- foreign_key="public.users.id",
- description="User who soft-deleted this record"
- )
-
-### Example: Patient Model
-
-```python
-from sqlmodel import SQLModel, Field, Relationship
-from typing import Optional, List
-from datetime import date
-from enum import Enum
-
-class Gender(str, Enum):
- """Gender options (HL7 FHIR R4 standard)."""
- MALE = "male"
- FEMALE = "female"
- OTHER = "other"
- UNKNOWN = "unknown"
-
-class Patient(TenantBaseModel, table=True):
- """
- Patient demographic and identification information.
-
- Clinical Context: Central patient registry for all clinical applications
- Standards: HL7 FHIR R4 Patient Resource, HIPAA PHI
- Security: Contains PHI - all access must be audited
- """
-
- __tablename__ = "patients"
- __table_args__ = (
- {"schema": "clinica"}, # Tenant-specific schema
- )
-
- # Identifiers
- mrn: str = Field(
- unique=True,
- index=True,
- nullable=False,
- max_length=50,
- description="Medical Record Number (facility-specific)"
- )
-
- national_id: Optional[str] = Field(
- default=None,
- max_length=50,
- description="National ID number (SSN, passport, etc.) - encrypted"
- )
-
- # Demographics (PHI)
- first_name: str = Field(
- nullable=False,
- max_length=100,
- description="Patient first name"
- )
-
- middle_name: Optional[str] = Field(
- default=None,
- max_length=100,
- description="Patient middle name"
- )
-
- last_name: str = Field(
- nullable=False,
- max_length=100,
- description="Patient last name"
- )
-
- date_of_birth: date = Field(
- nullable=False,
- description="Date of birth (for age calculation)"
- )
-
- gender: Gender = Field(
- nullable=False,
- description="Administrative gender (HL7 FHIR)"
- )
-
- # Contact Information (PHI)
- primary_phone: Optional[str] = Field(
- default=None,
- max_length=20,
- description="Primary contact phone number"
- )
-
- email: Optional[str] = Field(
- default=None,
- max_length=255,
- description="Email address"
- )
-
- address_line1: Optional[str] = Field(
- default=None,
- max_length=255,
- description="Street address line 1"
- )
-
- address_line2: Optional[str] = Field(
- default=None,
- max_length=255,
- description="Street address line 2"
- )
-
- city: Optional[str] = Field(
- default=None,
- max_length=100,
- description="City"
- )
-
- state: Optional[str] = Field(
- default=None,
- max_length=50,
- description="State/Province"
- )
-
- postal_code: Optional[str] = Field(
- default=None,
- max_length=20,
- description="ZIP/Postal code"
- )
-
- country: str = Field(
- default="US",
- max_length=2,
- description="ISO 3166-1 alpha-2 country code"
- )
-
- # Clinical Metadata
- blood_type: Optional[str] = Field(
- default=None,
- max_length=10,
- description="Blood type (A+, B-, O+, etc.)"
- )
-
- allergies: Optional[List[str]] = Field(
- default=None,
- sa_column=Column(JSON),
- description="Known allergies (JSON array)"
- )
-
- # Relationships
- encounters: List["Encounter"] = Relationship(back_populates="patient")
- lab_results: List["LabResult"] = Relationship(back_populates="patient")
- medications: List["Medication"] = Relationship(back_populates="patient")
-
- # Computed Properties
- @property
- def age_years(self) -> int:
- """Calculate current age in years."""
- today = date.today()
- age = today.year - self.date_of_birth.year
- if (today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day):
- age -= 1
- return age
-
- @property
- def full_name(self) -> str:
- """Return formatted full name."""
- parts = [self.first_name]
- if self.middle_name:
- parts.append(self.middle_name)
- parts.append(self.last_name)
- return " ".join(parts)
-
- class Config:
- """Pydantic configuration."""
- json_schema_extra = {
- "example": {
- "mrn": "MRN-2024-001234",
- "first_name": "John",
- "last_name": "Doe",
- "date_of_birth": "1980-05-15",
- "gender": "male",
- "primary_phone": "+1-555-0123",
- "email": "john.doe@example.com"
- }
- }
-
-## 2. Indexing Strategy
-
-### Required Indexes for Multi-Tenant Tables
-
-```sql
--- Primary key index (automatic)
-CREATE UNIQUE INDEX idx_patients_pkey ON clinica.patients(id);
-
--- Tenant isolation index (CRITICAL - must be on ALL tenant tables)
-CREATE INDEX idx_patients_tenant_id ON clinica.patients(tenant_id);
-
--- Unique business key within tenant
-CREATE UNIQUE INDEX idx_patients_tenant_mrn ON clinica.patients(tenant_id, mrn);
-
--- Foreign key indexes
-CREATE INDEX idx_patients_created_by ON clinica.patients(created_by);
-CREATE INDEX idx_patients_updated_by ON clinica.patients(updated_by);
-
--- Search indexes
-CREATE INDEX idx_patients_last_name ON clinica.patients(tenant_id, last_name);
-CREATE INDEX idx_patients_dob ON clinica.patients(tenant_id, date_of_birth);
-
--- Soft delete filter
-CREATE INDEX idx_patients_active ON clinica.patients(tenant_id, is_deleted)
- WHERE is_deleted = false;
-
--- Composite indexes for common queries
-CREATE INDEX idx_patients_search ON clinica.patients(tenant_id, last_name, first_name)
- WHERE is_deleted = false;
-
--- Full-text search (for patient search)
-CREATE INDEX idx_patients_fulltext ON clinica.patients
- USING gin(to_tsvector('english', first_name || ' ' || last_name));
-```
-
-### Index Performance Guidelines
-
-```python
-"""
-Index Design Principles:
-
-1. **Always Index tenant_id**: First column in multi-column indexes
-2. **Index Foreign Keys**: For JOIN performance
-3. **Composite Indexes**: Order matters - most selective first
-4. **Partial Indexes**: Use WHERE clause for filtered queries
-5. **Index Cardinality**: High-cardinality columns first
-6. **Avoid Over-Indexing**: Each index costs write performance
-
-Performance Targets:
-- Simple queries (indexed): <10ms
-- Complex queries (multiple JOINs): <50ms
-- Full-table scans: Avoid entirely in production
-
-Use EXPLAIN ANALYZE to verify:
-```sql
-EXPLAIN ANALYZE
-SELECT * FROM clinica.patients
-WHERE tenant_id = 'acme-hospital'
- AND last_name = 'Smith'
- AND is_deleted = false;
-```
-```
-
-## 3. Alembic Migration Patterns
-
-### Migration File Template
-
-```python
-"""Add patients table for Clinica module
-
-Revision ID: 001_add_patients_table
-Revises:
-Create Date: 2025-12-24 10:00:00.000000
-
-Clinical Context: Central patient registry for demographic and identification data
-Standards: HL7 FHIR R4 Patient Resource
-"""
-from alembic import op
-import sqlalchemy as sa
-from sqlalchemy.dialects import postgresql
-from datetime import datetime
-
-# revision identifiers
-revision = '001_add_patients_table'
-down_revision = None
-branch_labels = None
-depends_on = None
-
-def upgrade() -> None:
- """
- Create patients table with multi-tenant support.
-
- Checklist:
- - [ ] tenant_id column (nullable=False, indexed)
- - [ ] Audit timestamps (created_at, updated_at)
- - [ ] Audit users (created_by, updated_by)
- - [ ] Soft delete (is_deleted, deleted_at, deleted_by)
- - [ ] Foreign keys with ON DELETE CASCADE
- - [ ] Unique constraints within tenant
- - [ ] Indexes for common queries
- """
-
- # Create clinica schema if not exists
- op.execute("CREATE SCHEMA IF NOT EXISTS clinica")
-
- # Create patients table
- op.create_table(
- 'patients',
- sa.Column('id', sa.String(36), primary_key=True),
- sa.Column('tenant_id', sa.String(36), nullable=False),
- sa.Column('mrn', sa.String(50), nullable=False),
- sa.Column('national_id', sa.String(50), nullable=True),
- sa.Column('first_name', sa.String(100), nullable=False),
- sa.Column('middle_name', sa.String(100), nullable=True),
- sa.Column('last_name', sa.String(100), nullable=False),
- sa.Column('date_of_birth', sa.Date(), nullable=False),
- sa.Column('gender', sa.String(20), nullable=False),
- sa.Column('primary_phone', sa.String(20), nullable=True),
- sa.Column('email', sa.String(255), nullable=True),
- sa.Column('address_line1', sa.String(255), nullable=True),
- sa.Column('address_line2', sa.String(255), nullable=True),
- sa.Column('city', sa.String(100), nullable=True),
- sa.Column('state', sa.String(50), nullable=True),
- sa.Column('postal_code', sa.String(20), nullable=True),
- sa.Column('country', sa.String(2), nullable=False, server_default='US'),
- sa.Column('blood_type', sa.String(10), nullable=True),
- sa.Column('allergies', postgresql.JSON, nullable=True),
- sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
- sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
- sa.Column('created_by', sa.String(36), nullable=False),
- sa.Column('updated_by', sa.String(36), nullable=True),
- sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default='false'),
- sa.Column('deleted_at', sa.DateTime(), nullable=True),
- sa.Column('deleted_by', sa.String(36), nullable=True),
- schema='clinica'
- )
-
- # Foreign keys
- op.create_foreign_key(
- 'fk_patients_tenant_id',
- 'patients', 'tenants',
- ['tenant_id'], ['id'],
- source_schema='clinica',
- referent_schema='public',
- ondelete='CASCADE'
- )
-
- op.create_foreign_key(
- 'fk_patients_created_by',
- 'patients', 'users',
- ['created_by'], ['id'],
- source_schema='clinica',
- referent_schema='public'
- )
-
- # Indexes
- op.create_index(
- 'idx_patients_tenant_id',
- 'patients',
- ['tenant_id'],
- schema='clinica'
- )
-
- op.create_index(
- 'idx_patients_tenant_mrn',
- 'patients',
- ['tenant_id', 'mrn'],
- unique=True,
- schema='clinica'
- )
-
- op.create_index(
- 'idx_patients_last_name',
- 'patients',
- ['tenant_id', 'last_name'],
- schema='clinica'
- )
-
- op.create_index(
- 'idx_patients_active',
- 'patients',
- ['tenant_id', 'is_deleted'],
- schema='clinica',
- postgresql_where=sa.text('is_deleted = false')
- )
-
- # Updated_at trigger
- op.execute("""
- CREATE OR REPLACE FUNCTION update_updated_at_column()
- RETURNS TRIGGER AS $$
- BEGIN
- NEW.updated_at = NOW();
- RETURN NEW;
- END;
- $$ language 'plpgsql';
- """)
-
- op.execute("""
- CREATE TRIGGER update_patients_updated_at
- BEFORE UPDATE ON clinica.patients
- FOR EACH ROW
- EXECUTE FUNCTION update_updated_at_column();
- """)
-
-def downgrade() -> None:
- """Rollback patients table creation."""
- op.drop_table('patients', schema='clinica')
- op.execute("DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE")
-```
-
-### Migration Best Practices
-
-```python
-"""
-Migration Safety Checklist:
-
-1. **Backward Compatibility**:
- - New columns should be nullable OR have defaults
- - Don't drop columns in production (use soft delete)
- - Use ALTER TABLE ADD COLUMN instead of DROP/CREATE
-
-2. **Data Migration**:
- - Include data transformation logic
- - Test with production-sized datasets
- - Use batch processing for large tables
-
-3. **Rollback Strategy**:
- - Always implement downgrade()
- - Test rollback before deploying
- - Keep migrations atomic
-
-4. **Performance**:
- - Create indexes CONCURRENTLY in production
- - Avoid long-running transactions
- - Test migration time on production-sized data
-
-5. **Multi-Tenancy**:
- - Apply schema changes to ALL tenant schemas
- - Verify tenant isolation after migration
- - Test with multiple tenants
-
-Example: Safe Column Addition
-"""
-
-def upgrade():
- # Add column with default (fast, no table rewrite)
- op.add_column(
- 'patients',
- sa.Column('preferred_language', sa.String(10), nullable=True),
- schema='clinica'
- )
-
- # Backfill data in batches (for large tables)
- connection = op.get_bind()
- connection.execute("""
- UPDATE clinica.patients
- SET preferred_language = 'en'
- WHERE preferred_language IS NULL
- """)
-
- # Make NOT NULL after backfill
- op.alter_column(
- 'patients',
- 'preferred_language',
- nullable=False,
- schema='clinica'
- )
-```
-
-## 4. Query Optimization Patterns
-
-### Repository Pattern with Optimized Queries
-
-```python
-from typing import List, Optional
-from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy import select, and_, func
-from sqlalchemy.orm import selectinload
-import structlog
-
-logger = structlog.get_logger()
-
-class PatientRepository:
- """
- Repository for patient data access with optimized queries.
-
- Performance: All queries <50ms for typical loads
- Multi-Tenancy: All queries auto-filter by tenant_id
- """
-
- def __init__(self, session: AsyncSession, tenant_id: str):
- self.session = session
- self.tenant_id = tenant_id
-
- async def get_by_id(self, patient_id: str) -> Optional[Patient]:
- """
- Get patient by ID (tenant-scoped).
-
- Performance: <10ms (indexed lookup)
- """
- stmt = select(Patient).where(
- and_(
- Patient.tenant_id == self.tenant_id,
- Patient.id == patient_id,
- Patient.is_deleted == False
- )
- )
-
- result = await self.session.execute(stmt)
- return result.scalar_one_or_none()
-
- async def get_by_mrn(self, mrn: str) -> Optional[Patient]:
- """
- Get patient by MRN (Medical Record Number).
-
- Performance: <10ms (unique index lookup)
- """
- stmt = select(Patient).where(
- and_(
- Patient.tenant_id == self.tenant_id,
- Patient.mrn == mrn,
- Patient.is_deleted == False
- )
- )
-
- result = await self.session.execute(stmt)
- return result.scalar_one_or_none()
-
- async def search_by_name(
- self,
- last_name: str,
- first_name: Optional[str] = None,
- limit: int = 50
- ) -> List[Patient]:
- """
- Search patients by name.
-
- Performance: <50ms (composite index on tenant_id + last_name + first_name)
- """
- conditions = [
- Patient.tenant_id == self.tenant_id,
- Patient.last_name.ilike(f"{last_name}%"),
- Patient.is_deleted == False
- ]
-
- if first_name:
- conditions.append(Patient.first_name.ilike(f"{first_name}%"))
-
- stmt = (
- select(Patient)
- .where(and_(*conditions))
- .order_by(Patient.last_name, Patient.first_name)
- .limit(limit)
- )
-
- result = await self.session.execute(stmt)
- return result.scalars().all()
-
- async def get_with_encounters(
- self,
- patient_id: str
- ) -> Optional[Patient]:
- """
- Get patient with encounters (eager loading to avoid N+1).
-
- Performance: <100ms (single query with JOIN)
- """
- stmt = (
- select(Patient)
- .options(selectinload(Patient.encounters)) # Eager load
- .where(
- and_(
- Patient.tenant_id == self.tenant_id,
- Patient.id == patient_id,
- Patient.is_deleted == False
- )
- )
- )
-
- result = await self.session.execute(stmt)
- return result.scalar_one_or_none()
-
- async def count_active_patients(self) -> int:
- """
- Count active patients for tenant.
-
- Performance: <20ms (index-only scan)
- """
- stmt = select(func.count(Patient.id)).where(
- and_(
- Patient.tenant_id == self.tenant_id,
- Patient.is_deleted == False
- )
- )
-
- result = await self.session.execute(stmt)
- return result.scalar_one()
-
- async def batch_create(
- self,
- patients: List[Patient],
- user_id: str
- ) -> List[Patient]:
- """
- Batch create patients (optimized for ETL/import).
-
- Performance: ~1000 records per second
- """
- # Set audit fields
- for patient in patients:
- patient.tenant_id = self.tenant_id
- patient.created_by = user_id
-
- # Bulk insert
- self.session.add_all(patients)
- await self.session.flush()
-
- logger.info(
- "patients_batch_created",
- tenant_id=self.tenant_id,
- count=len(patients),
- user_id=user_id
- )
-
- return patients
-```
-
-### Query Performance Monitoring
-
-```python
-import time
-from functools import wraps
-
-def monitor_query_performance(func):
- """
- Decorator to monitor database query performance.
-
- Logs slow queries (>50ms) for optimization review.
- """
- @wraps(func)
- async def wrapper(*args, **kwargs):
- start = time.time()
-
- try:
- result = await func(*args, **kwargs)
- duration_ms = (time.time() - start) * 1000
-
- if duration_ms > 50:
- logger.warning(
- "slow_query_detected",
- function=func.__name__,
- duration_ms=duration_ms,
- args=str(args)[:100], # Truncate for logging
- )
-
- return result
- finally:
- duration_ms = (time.time() - start) * 1000
- logger.info(
- "query_completed",
- function=func.__name__,
- duration_ms=duration_ms
- )
-
- return wrapper
-
-# Usage
-class OptimizedRepository:
- @monitor_query_performance
- async def get_patient(self, patient_id: str):
- # Query implementation
- pass
-```
-
-## Summary
-
-Key database design principles:
-- β
Always include tenant_id in multi-tenant tables (indexed, non-nullable)
-- β
Use schema-per-tenant for strong isolation
-- β
Index foreign keys and common query columns
-- β
Implement soft delete for HIPAA retention
-- β
Use audit columns (created_at, updated_at, created_by, updated_by)
-- β
Test migrations with production-sized data
-- β
Monitor query performance and optimize slow queries
-- β
Use repository pattern for query encapsulation
-- β
Implement proper cascade deletes
-- β
Document clinical context in table/column comments
-
-**Performance Targets**:
-- Indexed lookups: <10ms
-- Simple queries: <50ms
-- Complex queries with JOINs: <200ms
-- Batch operations: 1000+ records/second
diff --git a/.github/copilot-prompts/multi-tenancy-patterns.md b/.github/copilot-prompts/multi-tenancy-patterns.md
deleted file mode 100644
index ae2fccacae9d45aa94d8d72ff80841a49e9412d9..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/multi-tenancy-patterns.md
+++ /dev/null
@@ -1,725 +0,0 @@
-# Multi-Tenancy Implementation Patterns
-
-## Overview
-YAZ Care Platform uses **schema-per-tenant** isolation in PostgreSQL for strong data separation with shared infrastructure efficiency.
-
-## Architecture Pattern
-
-### Tenant Isolation Strategy
-```
-Database: PostgreSQL
-βββ public schema (shared metadata, system tables)
-βββ tenant_acme_hospital schema
-β βββ patients
-β βββ encounters
-β βββ clinical_notes
-β βββ ...
-βββ tenant_city_clinic schema
-β βββ patients
-β βββ encounters
-β βββ ...
-βββ ...
-```
-
-## Template: Add Multi-Tenant Support to Existing Endpoint
-
-### Prompt Structure
-```
-Add multi-tenant support to [ENDPOINT_NAME] in [APP_NAME] application.
-
-Current Implementation:
-[Paste current code without tenant isolation]
-
-Required Changes:
-1. Extract tenant_id from request context (X-Tenant-ID header or JWT)
-2. Validate tenant access rights (user belongs to tenant)
-3. Apply tenant schema filter to all database queries
-4. Add tenant_id prefix to all cache keys
-5. Verify no cross-tenant data leakage in responses
-6. Add audit logging with tenant_id
-7. Add integration test for tenant isolation
-
-Security Checklist:
-- [ ] tenant_id extracted from authenticated JWT token
-- [ ] Database queries use SET search_path to tenant schema
-- [ ] Cache keys prefixed: f"tenant:{tenant_id}:..."
-- [ ] Error messages don't leak other tenant info
-- [ ] Audit log includes tenant_id for all operations
-- [ ] Test verifies tenant A cannot access tenant B data
-- [ ] No raw SQL queries without tenant filter
-
-Performance Impact:
-- Schema switching adds ~5ms overhead per request
-- Cache hit rate should remain >80%
-- No N+1 query patterns introduced
-- Connection pool shared across tenants
-
-Reference: Sprint 29 multi-tenancy tests (6/6 passing)
-```
-
-## Implementation Pattern: Database Layer
-
-### 1. Tenant Context Middleware
-```python
-from __future__ import annotations
-from typing import Optional
-from fastapi import Request, HTTPException, status
-from sqlalchemy import text
-from sqlalchemy.ext.asyncio import AsyncSession
-import structlog
-
-logger = structlog.get_logger()
-
-
-class TenantContext:
- """
- Multi-tenant context for request isolation.
-
- Manages tenant identification, validation, and database schema switching.
- Ensures no cross-tenant data access.
- """
-
- def __init__(self, tenant_id: str, user_id: str):
- self.tenant_id = tenant_id
- self.user_id = user_id
- self.schema_name = f"tenant_{tenant_id.replace('-', '_')}"
-
- @classmethod
- async def from_request(cls, request: Request) -> TenantContext:
- """
- Extract and validate tenant context from request.
-
- Args:
- request: FastAPI request object
-
- Returns:
- TenantContext with validated tenant_id
-
- Raises:
- HTTPException: If tenant validation fails
- """
- # Extract from header (API calls)
- tenant_id = request.headers.get("X-Tenant-ID")
-
- # If not in header, extract from JWT token
- if not tenant_id:
- user = getattr(request.state, "user", None)
- if user and hasattr(user, "tenant_id"):
- tenant_id = user.tenant_id
-
- if not tenant_id:
- logger.error("missing_tenant_id", path=request.url.path)
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Tenant ID is required (X-Tenant-ID header or JWT)"
- )
-
- # Extract user_id for audit
- user_id = getattr(request.state, "user_id", "unknown")
-
- # Validate tenant exists and user has access
- await cls._validate_tenant_access(tenant_id, user_id)
-
- logger.info(
- "tenant_context_created",
- tenant_id=tenant_id,
- user_id=user_id
- )
-
- return cls(tenant_id=tenant_id, user_id=user_id)
-
- @staticmethod
- async def _validate_tenant_access(tenant_id: str, user_id: str) -> None:
- """
- Validate user has access to tenant.
-
- Args:
- tenant_id: Tenant identifier
- user_id: User identifier
-
- Raises:
- HTTPException: If validation fails
- """
- # TODO: Check user_tenants table
- # For now, assume valid if tenant_id provided
- pass
-
- async def set_search_path(self, db: AsyncSession) -> None:
- """
- Set PostgreSQL search_path to tenant schema.
-
- CRITICAL: Must be called before any database queries
- to ensure tenant isolation.
-
- Args:
- db: Database session
- """
- await db.execute(
- text(f"SET search_path TO {self.schema_name}, public")
- )
- logger.debug(
- "search_path_set",
- tenant_id=self.tenant_id,
- schema=self.schema_name
- )
-
-
-# FastAPI Dependency
-async def get_tenant_context(request: Request) -> TenantContext:
- """FastAPI dependency for tenant context injection."""
- return await TenantContext.from_request(request)
-```
-
-### 2. Multi-Tenant Repository Pattern
-
-```python
-from __future__ import annotations
-from typing import List, Optional, Generic, TypeVar
-from sqlalchemy import select
-from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy.orm import DeclarativeMeta
-import structlog
-
-logger = structlog.get_logger()
-
-T = TypeVar('T', bound=DeclarativeMeta)
-
-
-class TenantRepository(Generic[T]):
- """
- Base repository with multi-tenant isolation.
-
- All database operations automatically filtered by tenant schema.
- """
-
- def __init__(
- self,
- db: AsyncSession,
- tenant_context: TenantContext,
- model: type[T]
- ):
- self.db = db
- self.tenant_context = tenant_context
- self.model = model
-
- async def _ensure_tenant_schema(self) -> None:
- """Ensure database search_path is set to tenant schema."""
- await self.tenant_context.set_search_path(self.db)
-
- async def get_by_id(self, id: str) -> Optional[T]:
- """
- Get entity by ID within tenant scope.
-
- Args:
- id: Entity identifier
-
- Returns:
- Entity if found in tenant schema, None otherwise
- """
- await self._ensure_tenant_schema()
-
- result = await self.db.execute(
- select(self.model).where(self.model.id == id)
- )
- entity = result.scalar_one_or_none()
-
- logger.debug(
- "entity_retrieved",
- tenant_id=self.tenant_context.tenant_id,
- model=self.model.__name__,
- id=id,
- found=entity is not None
- )
-
- return entity
-
- async def list(
- self,
- skip: int = 0,
- limit: int = 100,
- filters: Optional[dict] = None
- ) -> List[T]:
- """
- List entities within tenant scope.
-
- Args:
- skip: Pagination offset
- limit: Max results
- filters: Additional filters
-
- Returns:
- List of entities in tenant schema
- """
- await self._ensure_tenant_schema()
-
- query = select(self.model)
-
- # Apply filters
- if filters:
- for key, value in filters.items():
- if hasattr(self.model, key):
- query = query.where(getattr(self.model, key) == value)
-
- query = query.offset(skip).limit(limit)
-
- result = await self.db.execute(query)
- entities = result.scalars().all()
-
- logger.info(
- "entities_listed",
- tenant_id=self.tenant_context.tenant_id,
- model=self.model.__name__,
- count=len(entities),
- skip=skip,
- limit=limit
- )
-
- return list(entities)
-
- async def create(self, entity: T) -> T:
- """
- Create entity in tenant schema.
-
- Args:
- entity: Entity to create
-
- Returns:
- Created entity with ID
- """
- await self._ensure_tenant_schema()
-
- self.db.add(entity)
- await self.db.flush()
- await self.db.refresh(entity)
-
- logger.info(
- "entity_created",
- tenant_id=self.tenant_context.tenant_id,
- model=self.model.__name__,
- entity_id=getattr(entity, 'id', None)
- )
-
- return entity
-
- async def update(self, entity: T) -> T:
- """
- Update entity in tenant schema.
-
- Args:
- entity: Entity with updated fields
-
- Returns:
- Updated entity
- """
- await self._ensure_tenant_schema()
-
- await self.db.flush()
- await self.db.refresh(entity)
-
- logger.info(
- "entity_updated",
- tenant_id=self.tenant_context.tenant_id,
- model=self.model.__name__,
- entity_id=getattr(entity, 'id', None)
- )
-
- return entity
-
- async def delete(self, id: str) -> bool:
- """
- Delete entity from tenant schema.
-
- Args:
- id: Entity identifier
-
- Returns:
- True if deleted, False if not found
- """
- await self._ensure_tenant_schema()
-
- entity = await self.get_by_id(id)
- if not entity:
- return False
-
- await self.db.delete(entity)
- await self.db.flush()
-
- logger.info(
- "entity_deleted",
- tenant_id=self.tenant_context.tenant_id,
- model=self.model.__name__,
- entity_id=id
- )
-
- return True
-```
-
-### 3. Multi-Tenant Cache Pattern
-
-```python
-from __future__ import annotations
-from typing import Optional, Any
-from redis.asyncio import Redis
-import json
-import structlog
-
-logger = structlog.get_logger()
-
-
-class TenantCache:
- """
- Multi-tenant Redis cache with automatic key prefixing.
-
- Ensures cache isolation between tenants.
- """
-
- def __init__(self, redis: Redis, tenant_context: TenantContext):
- self.redis = redis
- self.tenant_context = tenant_context
-
- def _make_key(self, key: str) -> str:
- """
- Create tenant-prefixed cache key.
-
- Args:
- key: Base cache key
-
- Returns:
- Prefixed key: "tenant:{tenant_id}:{key}"
- """
- return f"tenant:{self.tenant_context.tenant_id}:{key}"
-
- async def get(self, key: str) -> Optional[Any]:
- """
- Get value from tenant cache.
-
- Args:
- key: Cache key (will be prefixed)
-
- Returns:
- Cached value or None
- """
- prefixed_key = self._make_key(key)
- value = await self.redis.get(prefixed_key)
-
- if value:
- logger.debug(
- "cache_hit",
- tenant_id=self.tenant_context.tenant_id,
- key=key
- )
- return json.loads(value)
-
- logger.debug(
- "cache_miss",
- tenant_id=self.tenant_context.tenant_id,
- key=key
- )
- return None
-
- async def set(
- self,
- key: str,
- value: Any,
- ttl: int = 3600
- ) -> None:
- """
- Set value in tenant cache.
-
- Args:
- key: Cache key (will be prefixed)
- value: Value to cache (JSON-serializable)
- ttl: Time to live in seconds
- """
- prefixed_key = self._make_key(key)
- await self.redis.setex(
- prefixed_key,
- ttl,
- json.dumps(value)
- )
-
- logger.debug(
- "cache_set",
- tenant_id=self.tenant_context.tenant_id,
- key=key,
- ttl=ttl
- )
-
- async def delete(self, key: str) -> None:
- """Delete value from tenant cache."""
- prefixed_key = self._make_key(key)
- await self.redis.delete(prefixed_key)
-
- logger.debug(
- "cache_deleted",
- tenant_id=self.tenant_context.tenant_id,
- key=key
- )
-
- async def clear_tenant_cache(self) -> int:
- """
- Clear all cache entries for current tenant.
-
- Returns:
- Number of keys deleted
- """
- pattern = self._make_key("*")
- keys = []
- async for key in self.redis.scan_iter(match=pattern):
- keys.append(key)
-
- if keys:
- deleted = await self.redis.delete(*keys)
- else:
- deleted = 0
-
- logger.info(
- "tenant_cache_cleared",
- tenant_id=self.tenant_context.tenant_id,
- keys_deleted=deleted
- )
-
- return deleted
-```
-
-### 4. Multi-Tenant API Endpoint Pattern
-
-```python
-from __future__ import annotations
-from fastapi import APIRouter, Depends, HTTPException, status
-from sqlalchemy.ext.asyncio import AsyncSession
-from typing import List
-import structlog
-
-from src.infrastructure.database import get_db
-from src.core.models.patient import Patient
-from src.core.schemas.patient import PatientCreate, PatientResponse
-
-logger = structlog.get_logger()
-router = APIRouter(prefix="/api/v1/patients", tags=["patients"])
-
-
-@router.post("/", response_model=PatientResponse, status_code=status.HTTP_201_CREATED)
-async def create_patient(
- patient_data: PatientCreate,
- tenant_context: TenantContext = Depends(get_tenant_context),
- db: AsyncSession = Depends(get_db)
-):
- """
- Create new patient in tenant scope.
-
- Multi-Tenancy: Patient created in tenant-specific schema.
- Security: Requires valid JWT with tenant_id.
- Audit: All operations logged with tenant_id and user_id.
- """
- logger.info(
- "patient_create_started",
- tenant_id=tenant_context.tenant_id,
- user_id=tenant_context.user_id
- )
-
- # Create repository with tenant context
- repo = TenantRepository(db, tenant_context, Patient)
-
- # Create patient entity
- patient = Patient(**patient_data.dict())
- patient = await repo.create(patient)
-
- await db.commit()
-
- logger.info(
- "patient_created",
- tenant_id=tenant_context.tenant_id,
- patient_id=patient.id
- )
-
- return PatientResponse.from_orm(patient)
-
-
-@router.get("/{patient_id}", response_model=PatientResponse)
-async def get_patient(
- patient_id: str,
- tenant_context: TenantContext = Depends(get_tenant_context),
- db: AsyncSession = Depends(get_db)
-):
- """
- Get patient by ID within tenant scope.
-
- Multi-Tenancy: Only returns patient if in same tenant schema.
- Returns 404 if patient not found OR in different tenant.
- """
- repo = TenantRepository(db, tenant_context, Patient)
- patient = await repo.get_by_id(patient_id)
-
- if not patient:
- logger.warning(
- "patient_not_found",
- tenant_id=tenant_context.tenant_id,
- patient_id=patient_id
- )
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail="Patient not found"
- )
-
- return PatientResponse.from_orm(patient)
-
-
-@router.get("/", response_model=List[PatientResponse])
-async def list_patients(
- skip: int = 0,
- limit: int = 100,
- tenant_context: TenantContext = Depends(get_tenant_context),
- db: AsyncSession = Depends(get_db)
-):
- """
- List all patients in tenant scope.
-
- Multi-Tenancy: Only returns patients from current tenant schema.
- """
- repo = TenantRepository(db, tenant_context, Patient)
- patients = await repo.list(skip=skip, limit=limit)
-
- return [PatientResponse.from_orm(p) for p in patients]
-```
-
-## Integration Tests
-
-```python
-import pytest
-from httpx import AsyncClient
-
-
-@pytest.mark.integration
-async def test_multi_tenant_isolation(async_client: AsyncClient):
- """
- Critical test: Verify tenant A cannot access tenant B data.
-
- This is the most important multi-tenancy test - ensures
- strong data isolation between tenants.
- """
- # Create patient in tenant A
- response_a = await async_client.post(
- "/api/v1/patients",
- json={
- "mrn": "MRN-A-001",
- "first_name": "Alice",
- "last_name": "Smith",
- "date_of_birth": "1980-01-01"
- },
- headers={"X-Tenant-ID": "tenant-a"}
- )
- assert response_a.status_code == 201
- patient_id = response_a.json()["id"]
-
- # Attempt to access from tenant B (should fail)
- response_b = await async_client.get(
- f"/api/v1/patients/{patient_id}",
- headers={"X-Tenant-ID": "tenant-b"}
- )
-
- # Should return 404, not 403 (don't leak existence)
- assert response_b.status_code == 404
- assert "not found" in response_b.json()["detail"].lower()
-
-
-@pytest.mark.integration
-async def test_tenant_list_isolation(async_client: AsyncClient):
- """Verify list operations only return tenant-specific data."""
- # Create patients in both tenants
- await async_client.post(
- "/api/v1/patients",
- json={"mrn": "MRN-A-001", "first_name": "Alice", "last_name": "A", "date_of_birth": "1980-01-01"},
- headers={"X-Tenant-ID": "tenant-a"}
- )
- await async_client.post(
- "/api/v1/patients",
- json={"mrn": "MRN-B-001", "first_name": "Bob", "last_name": "B", "date_of_birth": "1985-01-01"},
- headers={"X-Tenant-ID": "tenant-b"}
- )
-
- # List for tenant A
- response_a = await async_client.get(
- "/api/v1/patients",
- headers={"X-Tenant-ID": "tenant-a"}
- )
- patients_a = response_a.json()
-
- # List for tenant B
- response_b = await async_client.get(
- "/api/v1/patients",
- headers={"X-Tenant-ID": "tenant-b"}
- )
- patients_b = response_b.json()
-
- # Verify separation
- assert len(patients_a) == 1
- assert len(patients_b) == 1
- assert patients_a[0]["mrn"] == "MRN-A-001"
- assert patients_b[0]["mrn"] == "MRN-B-001"
-
-
-@pytest.mark.integration
-async def test_cache_isolation(async_client: AsyncClient, redis_client):
- """Verify cache keys are properly tenant-prefixed."""
- # Create patient in tenant A
- response = await async_client.post(
- "/api/v1/patients",
- json={"mrn": "MRN-001", "first_name": "Test", "last_name": "User", "date_of_birth": "1990-01-01"},
- headers={"X-Tenant-ID": "tenant-a"}
- )
- patient_id = response.json()["id"]
-
- # Check cache keys
- keys = []
- async for key in redis_client.scan_iter(match="tenant:tenant-a:*"):
- keys.append(key.decode())
-
- # Should have tenant-prefixed keys
- assert any("tenant:tenant-a:" in key for key in keys)
-
- # Should NOT have keys for other tenants
- async for key in redis_client.scan_iter(match="tenant:tenant-b:*"):
- pytest.fail("Found tenant B cache keys when only tenant A was used")
-```
-
-## Performance Considerations
-
-### Schema Switching Overhead
-- **Cost**: ~5ms per request for `SET search_path`
-- **Mitigation**: Connection pooling per tenant (if needed)
-- **Monitoring**: Track p95 latency by tenant
-
-### Cache Hit Rates
-- **Target**: >80% cache hit rate per tenant
-- **Key Strategy**: Prefix all keys with `tenant:{tenant_id}:`
-- **Monitoring**: Track hit/miss rates per tenant
-
-### Database Connections
-- **Current**: Shared connection pool (100 connections)
-- **Scaling**: Consider per-tenant pools at 1000+ tenants
-- **Monitoring**: Track connection usage by tenant
-
-## Migration to Multi-Tenancy
-
-### Checklist for Adding Tenant Support
-- [ ] Add `TenantContext` dependency to endpoint
-- [ ] Use `TenantRepository` for all database operations
-- [ ] Prefix cache keys with tenant_id
-- [ ] Add integration test for tenant isolation
-- [ ] Verify no raw SQL without tenant filter
-- [ ] Update API documentation
-- [ ] Add audit logging with tenant_id
-- [ ] Performance test with multiple tenants
-
-### Common Pitfalls
-1. **Forgetting search_path**: Always call `set_search_path()` before queries
-2. **Cache key collisions**: Always prefix with tenant_id
-3. **Leaking existence**: Return 404, not 403 for missing cross-tenant resources
-4. **Background jobs**: Ensure async tasks include tenant_id
-5. **Aggregations**: Verify tenant filter applied to all joins
-
-## Reference
-- Sprint 29: Multi-tenancy implementation (6/6 tests passing)
-- Database schema per tenant pattern
-- PostgreSQL search_path documentation
diff --git a/.github/copilot-prompts/observability-patterns.md b/.github/copilot-prompts/observability-patterns.md
deleted file mode 100644
index 5eb4574afdcbb43180d0dbdcce874cb5eeea3bfb..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/observability-patterns.md
+++ /dev/null
@@ -1,738 +0,0 @@
-# Observability Patterns - Tracing, Metrics, and Logging
-
-## Overview
-YAZ Care Platform uses OpenTelemetry for distributed tracing, Prometheus for metrics, and structured logging with ELK stack.
-
-**Sprint 32 Implementation**: 12,300 LOC added for comprehensive observability
-
-## Architecture
-
-```
-Request Flow:
-Client β API Gateway β FastAPI App β Service Layer β Database
- β β β β
- Traces Traces Traces Traces
- Logs Logs Logs Logs
- Metrics Metrics Metrics Metrics
- β β β β
- Jaeger Prometheus Elasticsearch
- β β β
- Grafana (unified dashboards)
-```
-
-## Template: Add Full Observability to Service
-
-### Prompt Structure
-```
-Add comprehensive observability to [SERVICE_NAME] in [APP_NAME].
-
-Requirements:
-1. Distributed Tracing (OpenTelemetry)
- - Create span for each operation
- - Add clinical/business context attributes
- - Propagate trace_id to all downstream calls
- - Handle async operations properly
-
-2. Structured Logging
- Required fields:
- - timestamp (ISO 8601)
- - log_level (DEBUG/INFO/WARNING/ERROR)
- - trace_id (from OpenTelemetry)
- - tenant_id (multi-tenant context)
- - user_id (audit trail)
- - component (app name)
- - message (human-readable)
- - context (structured data)
-
-3. Metrics (Prometheus)
- - Request counter by endpoint and status
- - Latency histogram (p50/p95/p99)
- - Error rate counter
- - Healthcare-specific metrics
-
-4. Performance Target: <200ms p95
-
-Reference: Sprint 32 observability implementation
-```
-
-## Implementation Pattern
-
-### 1. Distributed Tracing with OpenTelemetry
-
-```python
-from __future__ import annotations
-from typing import Optional, Dict, Any
-from opentelemetry import trace
-from opentelemetry.trace import Status, StatusCode
-from opentelemetry.sdk.trace import TracerProvider
-from opentelemetry.sdk.trace.export import BatchSpanProcessor
-from opentelemetry.exporter.jaeger.thrift import JaegerExporter
-from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
-from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
-from opentelemetry.instrumentation.redis import RedisInstrumentor
-import structlog
-
-logger = structlog.get_logger()
-
-
-def setup_tracing(service_name: str = "yaz-care-platform"):
- """
- Initialize OpenTelemetry distributed tracing.
-
- Exports spans to Jaeger for visualization and analysis.
- """
- # Configure Jaeger exporter
- jaeger_exporter = JaegerExporter(
- agent_host_name="localhost",
- agent_port=6831,
- )
-
- # Set up tracer provider
- provider = TracerProvider()
- processor = BatchSpanProcessor(jaeger_exporter)
- provider.add_span_processor(processor)
-
- trace.set_tracer_provider(provider)
-
- logger.info("tracing_initialized", service_name=service_name)
-
-
-def instrument_app(app):
- """
- Instrument FastAPI application for automatic tracing.
-
- Args:
- app: FastAPI application instance
- """
- # Instrument FastAPI
- FastAPIInstrumentor.instrument_app(app)
-
- # Instrument SQLAlchemy
- SQLAlchemyInstrumentor().instrument()
-
- # Instrument Redis
- RedisInstrumentor().instrument()
-
- logger.info("app_instrumented")
-
-
-# Service-level tracing pattern
-tracer = trace.get_tracer(__name__)
-
-
-class ClinicalService:
- """Example service with comprehensive tracing."""
-
- async def perform_clinical_assessment(
- self,
- tenant_id: str,
- user_id: str,
- patient_id: str,
- assessment_data: Dict[str, Any]
- ) -> Dict[str, Any]:
- """
- Clinical assessment with distributed tracing.
-
- Creates spans for each major operation:
- - Overall assessment
- - Data validation
- - Risk calculation
- - Database operations
- - Cache operations
- """
- with tracer.start_as_current_span("clinical_assessment") as span:
- # Add clinical context to span
- span.set_attribute("tenant.id", tenant_id)
- span.set_attribute("user.id", user_id)
- span.set_attribute("patient.id", patient_id)
- span.set_attribute("assessment.type", assessment_data.get("type"))
- span.set_attribute("service.name", "clinica")
-
- try:
- # Validation span
- with tracer.start_as_current_span("validate_input") as validation_span:
- validation_span.set_attribute("fields_count", len(assessment_data))
- validated_data = await self._validate_assessment(assessment_data)
- validation_span.set_status(Status(StatusCode.OK))
-
- # Risk calculation span
- with tracer.start_as_current_span("calculate_risk") as risk_span:
- risk_span.set_attribute("algorithm", "topsis")
- risk_score = await self._calculate_risk(validated_data)
- risk_span.set_attribute("risk.score", risk_score)
- risk_span.set_attribute("risk.severity", self._classify_risk(risk_score))
- risk_span.set_status(Status(StatusCode.OK))
-
- # Database operation span
- with tracer.start_as_current_span("save_assessment") as db_span:
- db_span.set_attribute("db.system", "postgresql")
- db_span.set_attribute("db.operation", "insert")
- db_span.set_attribute("db.table", "clinical_assessments")
- assessment_id = await self._save_assessment(
- tenant_id,
- patient_id,
- validated_data,
- risk_score
- )
- db_span.set_attribute("assessment.id", assessment_id)
- db_span.set_status(Status(StatusCode.OK))
-
- # Cache operation span
- with tracer.start_as_current_span("cache_result") as cache_span:
- cache_span.set_attribute("cache.system", "redis")
- cache_span.set_attribute("cache.operation", "set")
- await self._cache_result(tenant_id, patient_id, risk_score)
- cache_span.set_status(Status(StatusCode.OK))
-
- # Success
- span.set_attribute("result.status", "success")
- span.set_status(Status(StatusCode.OK))
-
- return {
- "assessment_id": assessment_id,
- "risk_score": risk_score,
- "severity": self._classify_risk(risk_score)
- }
-
- except Exception as e:
- # Record error in span
- span.set_status(Status(StatusCode.ERROR, str(e)))
- span.record_exception(e)
- logger.error(
- "clinical_assessment_failed",
- tenant_id=tenant_id,
- patient_id=patient_id,
- error=str(e),
- trace_id=format(span.get_span_context().trace_id, '032x')
- )
- raise
-
- async def _validate_assessment(self, data: Dict[str, Any]) -> Dict[str, Any]:
- """Validation logic."""
- # Implementation
- return data
-
- async def _calculate_risk(self, data: Dict[str, Any]) -> float:
- """Risk calculation logic."""
- # Implementation
- return 0.75
-
- def _classify_risk(self, score: float) -> str:
- """Risk classification."""
- if score >= 0.8:
- return "critical"
- elif score >= 0.6:
- return "high"
- elif score >= 0.4:
- return "moderate"
- else:
- return "low"
-
- async def _save_assessment(
- self,
- tenant_id: str,
- patient_id: str,
- data: Dict[str, Any],
- risk_score: float
- ) -> str:
- """Save to database."""
- # Implementation
- return "assessment-123"
-
- async def _cache_result(
- self,
- tenant_id: str,
- patient_id: str,
- risk_score: float
- ) -> None:
- """Cache result."""
- # Implementation
- pass
-```
-
-### 2. Structured Logging
-
-```python
-import structlog
-import logging
-import sys
-from datetime import datetime
-from opentelemetry import trace
-
-
-def setup_structured_logging():
- """
- Configure structured logging with required fields.
-
- Outputs JSON logs for ELK stack ingestion.
- """
- structlog.configure(
- processors=[
- structlog.contextvars.merge_contextvars,
- structlog.stdlib.filter_by_level,
- structlog.stdlib.add_logger_name,
- structlog.stdlib.add_log_level,
- structlog.processors.TimeStamper(fmt="iso"),
- structlog.processors.StackInfoRenderer(),
- structlog.processors.format_exc_info,
- structlog.processors.UnicodeDecoder(),
- structlog.processors.JSONRenderer()
- ],
- wrapper_class=structlog.stdlib.BoundLogger,
- context_class=dict,
- logger_factory=structlog.stdlib.LoggerFactory(),
- cache_logger_on_first_use=True,
- )
-
- # Configure standard logging
- logging.basicConfig(
- format="%(message)s",
- stream=sys.stdout,
- level=logging.INFO,
- )
-
-
-# Usage pattern
-logger = structlog.get_logger()
-
-
-class ClinicalWorkflowLogger:
- """
- Logger wrapper for clinical workflows.
-
- Automatically includes required context fields.
- """
-
- def __init__(
- self,
- tenant_id: str,
- user_id: str,
- component: str
- ):
- self.logger = logger.bind(
- tenant_id=tenant_id,
- user_id=user_id,
- component=component
- )
-
- def _add_trace_context(self) -> Dict[str, str]:
- """Add OpenTelemetry trace context to log."""
- span = trace.get_current_span()
- if span.is_recording():
- ctx = span.get_span_context()
- return {
- "trace_id": format(ctx.trace_id, '032x'),
- "span_id": format(ctx.span_id, '016x')
- }
- return {}
-
- def info(self, event: str, **kwargs):
- """Log info event with trace context."""
- self.logger.info(event, **{**kwargs, **self._add_trace_context()})
-
- def warning(self, event: str, **kwargs):
- """Log warning event with trace context."""
- self.logger.warning(event, **{**kwargs, **self._add_trace_context()})
-
- def error(self, event: str, **kwargs):
- """Log error event with trace context."""
- self.logger.error(event, **{**kwargs, **self._add_trace_context()})
-
- def debug(self, event: str, **kwargs):
- """Log debug event with trace context."""
- self.logger.debug(event, **{**kwargs, **self._add_trace_context()})
-
-
-# Usage example
-async def clinical_decision_workflow(tenant_id: str, user_id: str):
- """Example workflow with structured logging."""
- log = ClinicalWorkflowLogger(
- tenant_id=tenant_id,
- user_id=user_id,
- component="clinica"
- )
-
- log.info(
- "clinical_decision_started",
- patient_id="patient-123",
- decision_type="sepsis_screening"
- )
-
- try:
- # Workflow logic
- result = await perform_screening()
-
- log.info(
- "clinical_decision_completed",
- patient_id="patient-123",
- risk_score=result["risk_score"],
- severity=result["severity"],
- duration_ms=123
- )
-
- except Exception as e:
- log.error(
- "clinical_decision_failed",
- patient_id="patient-123",
- error=str(e),
- error_type=type(e).__name__
- )
- raise
-
-
-# Sample log output (JSON):
-# {
-# "event": "clinical_decision_started",
-# "timestamp": "2025-12-21T10:30:00.123456Z",
-# "level": "info",
-# "tenant_id": "acme-hospital",
-# "user_id": "dr.smith@acme.com",
-# "component": "clinica",
-# "patient_id": "patient-123",
-# "decision_type": "sepsis_screening",
-# "trace_id": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
-# "span_id": "a1b2c3d4e5f6g7h8"
-# }
-```
-
-### 3. Metrics with Prometheus
-
-```python
-from __future__ import annotations
-from prometheus_client import Counter, Histogram, Gauge, Info
-from typing import Callable
-from functools import wraps
-import time
-
-
-# Define metrics
-api_requests_total = Counter(
- 'api_requests_total',
- 'Total API requests',
- ['endpoint', 'method', 'status', 'tenant_id']
-)
-
-api_request_duration_seconds = Histogram(
- 'api_request_duration_seconds',
- 'API request latency',
- ['endpoint', 'method', 'tenant_id'],
- buckets=(0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 2.5, 5.0)
-)
-
-api_errors_total = Counter(
- 'api_errors_total',
- 'Total API errors',
- ['endpoint', 'method', 'error_type', 'tenant_id']
-)
-
-# Healthcare-specific metrics
-bed_occupancy_rate = Gauge(
- 'bed_occupancy_rate',
- 'Current bed occupancy percentage',
- ['tenant_id', 'facility_id', 'unit_type']
-)
-
-or_utilization_rate = Gauge(
- 'or_utilization_rate',
- 'Operating room utilization percentage',
- ['tenant_id', 'facility_id', 'or_number']
-)
-
-lab_turnaround_time_seconds = Histogram(
- 'lab_turnaround_time_seconds',
- 'Lab test turnaround time',
- ['tenant_id', 'test_type', 'priority'],
- buckets=(300, 600, 900, 1800, 3600, 7200, 14400, 28800) # 5min to 8hr
-)
-
-clinical_decisions_total = Counter(
- 'clinical_decisions_total',
- 'Clinical decision support invocations',
- ['tenant_id', 'decision_type', 'severity']
-)
-
-sepsis_screenings_total = Counter(
- 'sepsis_screenings_total',
- 'Sepsis screening counts',
- ['tenant_id', 'severity', 'positive']
-)
-
-
-# Decorator for automatic metrics
-def track_api_metrics(endpoint: str):
- """
- Decorator to automatically track API metrics.
-
- Usage:
- @track_api_metrics("/api/v1/patients")
- async def create_patient(...):
- ...
- """
- def decorator(func: Callable):
- @wraps(func)
- async def wrapper(*args, **kwargs):
- tenant_id = kwargs.get('tenant_context', TenantContext('unknown', 'unknown')).tenant_id
- method = kwargs.get('method', 'unknown')
-
- start_time = time.time()
- status = "success"
-
- try:
- result = await func(*args, **kwargs)
- return result
-
- except Exception as e:
- status = "error"
- api_errors_total.labels(
- endpoint=endpoint,
- method=method,
- error_type=type(e).__name__,
- tenant_id=tenant_id
- ).inc()
- raise
-
- finally:
- duration = time.time() - start_time
-
- api_requests_total.labels(
- endpoint=endpoint,
- method=method,
- status=status,
- tenant_id=tenant_id
- ).inc()
-
- api_request_duration_seconds.labels(
- endpoint=endpoint,
- method=method,
- tenant_id=tenant_id
- ).observe(duration)
-
- return wrapper
- return decorator
-
-
-# Healthcare metrics tracking
-class HealthcareMetrics:
- """Track healthcare-specific metrics."""
-
- @staticmethod
- def update_bed_occupancy(
- tenant_id: str,
- facility_id: str,
- unit_type: str,
- occupancy_rate: float
- ):
- """Update bed occupancy gauge."""
- bed_occupancy_rate.labels(
- tenant_id=tenant_id,
- facility_id=facility_id,
- unit_type=unit_type
- ).set(occupancy_rate)
-
- @staticmethod
- def update_or_utilization(
- tenant_id: str,
- facility_id: str,
- or_number: str,
- utilization_rate: float
- ):
- """Update OR utilization gauge."""
- or_utilization_rate.labels(
- tenant_id=tenant_id,
- facility_id=facility_id,
- or_number=or_number
- ).set(utilization_rate)
-
- @staticmethod
- def record_lab_turnaround(
- tenant_id: str,
- test_type: str,
- priority: str,
- duration_seconds: float
- ):
- """Record lab turnaround time."""
- lab_turnaround_time_seconds.labels(
- tenant_id=tenant_id,
- test_type=test_type,
- priority=priority
- ).observe(duration_seconds)
-
- @staticmethod
- def record_clinical_decision(
- tenant_id: str,
- decision_type: str,
- severity: str
- ):
- """Record clinical decision invocation."""
- clinical_decisions_total.labels(
- tenant_id=tenant_id,
- decision_type=decision_type,
- severity=severity
- ).inc()
-
- @staticmethod
- def record_sepsis_screening(
- tenant_id: str,
- severity: str,
- positive: bool
- ):
- """Record sepsis screening result."""
- sepsis_screenings_total.labels(
- tenant_id=tenant_id,
- severity=severity,
- positive=str(positive).lower()
- ).inc()
-
-
-# Usage example
-@track_api_metrics("/api/v1/clinica/sepsis/screen")
-async def sepsis_screening_endpoint(
- request: SepsisScreeningRequest,
- tenant_context: TenantContext
-):
- """API endpoint with automatic metrics tracking."""
- # Screening logic
- result = await perform_sepsis_screening(tenant_context.tenant_id, request)
-
- # Track healthcare-specific metrics
- HealthcareMetrics.record_clinical_decision(
- tenant_id=tenant_context.tenant_id,
- decision_type="sepsis_screening",
- severity=result.severity
- )
-
- HealthcareMetrics.record_sepsis_screening(
- tenant_id=tenant_context.tenant_id,
- severity=result.severity,
- positive=result.severity in ["high", "critical"]
- )
-
- return result
-```
-
-### 4. FastAPI Integration
-
-```python
-from fastapi import FastAPI, Request
-from prometheus_client import make_asgi_app
-import time
-
-
-def setup_observability(app: FastAPI):
- """
- Configure complete observability for FastAPI app.
-
- - Distributed tracing
- - Structured logging
- - Prometheus metrics
- """
- # Setup tracing
- setup_tracing("yaz-care-platform")
- instrument_app(app)
-
- # Setup logging
- setup_structured_logging()
-
- # Expose metrics endpoint
- metrics_app = make_asgi_app()
- app.mount("/metrics", metrics_app)
-
- # Request timing middleware
- @app.middleware("http")
- async def track_request_metrics(request: Request, call_next):
- start_time = time.time()
-
- response = await call_next(request)
-
- duration = time.time() - start_time
-
- # Extract tenant from request
- tenant_id = request.headers.get("X-Tenant-ID", "unknown")
-
- # Track metrics
- api_request_duration_seconds.labels(
- endpoint=request.url.path,
- method=request.method,
- tenant_id=tenant_id
- ).observe(duration)
-
- api_requests_total.labels(
- endpoint=request.url.path,
- method=request.method,
- status="success" if response.status_code < 400 else "error",
- tenant_id=tenant_id
- ).inc()
-
- return response
-
- logger.info("observability_configured")
-```
-
-## Grafana Dashboard Configuration
-
-```yaml
-# Example dashboard for healthcare metrics
-apiVersion: 1
-dashboards:
- - name: YAZ Care - Clinical Operations
- panels:
- - title: API Latency (p95)
- targets:
- - expr: histogram_quantile(0.95, rate(api_request_duration_seconds_bucket[5m]))
- thresholds:
- - value: 0.2 # 200ms SLA
- color: green
- - value: 0.5
- color: yellow
- - value: 1.0
- color: red
-
- - title: Sepsis Screenings by Severity
- targets:
- - expr: rate(sepsis_screenings_total[5m])
- legend: "{{severity}}"
-
- - title: Bed Occupancy Rate
- targets:
- - expr: bed_occupancy_rate
- legend: "{{unit_type}}"
-
- - title: OR Utilization
- targets:
- - expr: or_utilization_rate
- legend: "OR {{or_number}}"
-
- - title: Error Rate
- targets:
- - expr: rate(api_errors_total[5m])
- thresholds:
- - value: 0.01 # 1% error rate SLA
-```
-
-## Best Practices
-
-### 1. Always Include Trace Context
-- Pass trace_id through all service calls
-- Include in logs for correlation
-- Add to error responses for debugging
-
-### 2. Sensitive Data Handling
-- NEVER log PHI (patient identifiers, clinical details)
-- Log patient_id as hashed value only
-- Use separate audit log for PHI access
-
-### 3. Performance
-- Use sampling for high-volume traces (1-10%)
-- Batch span exports
-- Async metric updates
-
-### 4. Alerting
-- Alert on SLA violations (p95 > 200ms)
-- Alert on error rate > 1%
-- Alert on PHI access anomalies
-
-## Reference
-- Sprint 32: Observability implementation (12,300 LOC)
-- OpenTelemetry Python documentation
-- Prometheus best practices
-- ELK stack integration
diff --git a/.github/copilot-prompts/security-compliance.md b/.github/copilot-prompts/security-compliance.md
deleted file mode 100644
index 6e34a4dfa33e96f5dc3a860f3facc40925593e27..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/security-compliance.md
+++ /dev/null
@@ -1,417 +0,0 @@
-# Security & Compliance Patterns
-
-## HIPAA Audit Logging Checklist
-
-### Every PHI Access Must Be Logged
-
-```python
-from __future__ import annotations
-from typing import Optional, Dict, Any
-from datetime import datetime
-import hashlib
-import hmac
-import structlog
-
-logger = structlog.get_logger()
-
-
-class AuditLogger:
- """
- HIPAA-compliant audit logging for PHI access.
-
- Requirements:
- - Cryptographic verification of logs
- - Immutable audit trail
- - No PHI content in logs (metadata only)
- - Complete access tracking
- """
-
- def __init__(self, secret_key: str):
- self.secret_key = secret_key.encode()
-
- def _generate_signature(self, audit_data: Dict[str, Any]) -> str:
- """Generate HMAC-SHA256 signature for audit log entry."""
- message = f"{audit_data['timestamp']}:{audit_data['tenant_id']}:{audit_data['user_id']}:{audit_data['action']}:{audit_data['resource_id']}"
- signature = hmac.new(
- self.secret_key,
- message.encode(),
- hashlib.sha256
- ).hexdigest()
- return signature
-
- async def log_phi_access(
- self,
- tenant_id: str,
- user_id: str,
- action: str,
- resource_type: str,
- resource_id: str,
- ip_address: str,
- user_agent: str,
- access_granted: bool,
- reason: Optional[str] = None,
- additional_context: Optional[Dict[str, Any]] = None
- ) -> str:
- """
- Log PHI access with cryptographic verification.
-
- Args:
- tenant_id: Tenant identifier
- user_id: User accessing PHI
- action: Action performed (view, edit, delete, export)
- resource_type: Type of resource (patient, encounter, note)
- resource_id: Resource identifier (NEVER include PHI)
- ip_address: Source IP address
- user_agent: Client user agent
- access_granted: Whether access was granted
- reason: Justification for access
- additional_context: Additional non-PHI metadata
-
- Returns:
- Audit log ID
- """
- audit_log = {
- "timestamp": datetime.utcnow().isoformat(),
- "tenant_id": tenant_id,
- "user_id": user_id,
- "action": action,
- "resource_type": resource_type,
- "resource_id": resource_id, # Use ID, never PHI
- "ip_address": ip_address,
- "user_agent": user_agent,
- "access_granted": access_granted,
- "reason": reason,
- "additional_context": additional_context or {}
- }
-
- # Generate cryptographic signature
- audit_log["signature"] = self._generate_signature(audit_log)
-
- # Log to audit system (separate from application logs)
- logger.info(
- "phi_access_audit",
- **audit_log,
- component="audit"
- )
-
- # Store in immutable audit database
- audit_id = await self._store_audit_log(audit_log)
-
- return audit_id
-
- async def _store_audit_log(self, audit_log: Dict[str, Any]) -> str:
- """Store audit log in immutable database."""
- # Implementation: Write to append-only audit table
- return "audit-12345"
-
-
-# Usage pattern
-audit_logger = AuditLogger(secret_key="your-secret-key")
-
-@router.get("/api/v1/patients/{patient_id}")
-async def get_patient(
- patient_id: str,
- request: Request,
- tenant_context: TenantContext = Depends(get_tenant_context)
-):
- """Get patient with HIPAA audit logging."""
-
- # Log PHI access attempt
- await audit_logger.log_phi_access(
- tenant_id=tenant_context.tenant_id,
- user_id=tenant_context.user_id,
- action="patient_record_viewed",
- resource_type="patient",
- resource_id=patient_id, # ID only, no PHI
- ip_address=request.client.host,
- user_agent=request.headers.get("user-agent", "unknown"),
- access_granted=True,
- reason="clinical_care"
- )
-
- # Fetch patient data
- patient = await get_patient_from_db(patient_id, tenant_context)
-
- return patient
-```
-
-## Input Validation & Sanitization
-
-```python
-from pydantic import BaseModel, validator, Field
-from typing import Optional
-import re
-
-
-class SecurePatientInput(BaseModel):
- """Secure patient input with comprehensive validation."""
-
- mrn: str = Field(..., min_length=1, max_length=50)
- first_name: str = Field(..., min_length=1, max_length=100)
- last_name: str = Field(..., min_length=1, max_length=100)
- email: Optional[str] = Field(None, max_length=255)
- phone: Optional[str] = Field(None, max_length=20)
-
- @validator('mrn')
- def validate_mrn(cls, v):
- """Validate MRN format - alphanumeric only."""
- if not re.match(r'^[A-Za-z0-9\-]+$', v):
- raise ValueError("MRN must be alphanumeric")
- return v
-
- @validator('first_name', 'last_name')
- def validate_name(cls, v):
- """Sanitize names - letters, spaces, hyphens only."""
- if not re.match(r"^[A-Za-z\s\-']+$", v):
- raise ValueError("Name contains invalid characters")
- return v.strip()
-
- @validator('email')
- def validate_email(cls, v):
- """Validate email format."""
- if v and not re.match(r'^[\w\.\-]+@[\w\.\-]+\.\w+$', v):
- raise ValueError("Invalid email format")
- return v.lower() if v else None
-
- @validator('phone')
- def validate_phone(cls, v):
- """Sanitize phone number."""
- if v:
- # Remove non-numeric characters
- cleaned = re.sub(r'[^\d+]', '', v)
- if len(cleaned) < 10:
- raise ValueError("Phone number too short")
- return cleaned
- return None
-
-
-# SQL Injection Prevention
-# ALWAYS use parameterized queries
-async def get_patient_secure(patient_id: str, tenant_id: str):
- """Secure database query - parameterized."""
- # β CORRECT - Parameterized query
- query = text("""
- SELECT * FROM patients
- WHERE id = :patient_id
- """)
- result = await db.execute(query, {"patient_id": patient_id})
-
- # β WRONG - String concatenation (SQL injection risk)
- # query = f"SELECT * FROM patients WHERE id = '{patient_id}'" # NEVER DO THIS!
-
-
-# XSS Prevention
-from markupsafe import escape
-
-def render_patient_note(note_content: str) -> str:
- """Render clinical note with XSS prevention."""
- # Escape HTML to prevent XSS
- safe_content = escape(note_content)
- return safe_content
-```
-
-## Authentication & Authorization
-
-```python
-from fastapi import Depends, HTTPException, status
-from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
-import jwt
-from datetime import datetime, timedelta
-
-
-security = HTTPBearer()
-
-
-class AuthService:
- """JWT-based authentication service."""
-
- SECRET_KEY = "your-secret-key" # Store in environment variable
- ALGORITHM = "RS256" # Use RS256 for production
- ACCESS_TOKEN_EXPIRE_MINUTES = 15
-
- @classmethod
- def create_access_token(cls, user_id: str, tenant_id: str, roles: list[str]) -> str:
- """Create JWT access token."""
- expires = datetime.utcnow() + timedelta(minutes=cls.ACCESS_TOKEN_EXPIRE_MINUTES)
-
- payload = {
- "sub": user_id,
- "tenant_id": tenant_id,
- "roles": roles,
- "exp": expires,
- "iat": datetime.utcnow(),
- "type": "access"
- }
-
- token = jwt.encode(payload, cls.SECRET_KEY, algorithm=cls.ALGORITHM)
- return token
-
- @classmethod
- def verify_token(cls, token: str) -> dict:
- """Verify and decode JWT token."""
- try:
- payload = jwt.decode(
- token,
- cls.SECRET_KEY,
- algorithms=[cls.ALGORITHM]
- )
- return payload
- except jwt.ExpiredSignatureError:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Token has expired"
- )
- except jwt.JWTError:
- raise HTTPException(
- status_code=status.HTTP_401_UNAUTHORIZED,
- detail="Invalid token"
- )
-
-
-async def get_current_user(
- credentials: HTTPAuthorizationCredentials = Depends(security)
-) -> dict:
- """Dependency for extracting current user from JWT."""
- token = credentials.credentials
- payload = AuthService.verify_token(token)
- return payload
-
-
-# Role-based access control
-class RBACPermissions:
- """Define role-based permissions."""
-
- ROLES = {
- "physician": ["read:patients", "write:patients", "read:clinical_notes", "write:clinical_notes"],
- "nurse": ["read:patients", "write:vital_signs", "read:clinical_notes"],
- "admin": ["read:*", "write:*", "delete:*"],
- "billing": ["read:patients", "read:encounters", "write:claims"]
- }
-
- @classmethod
- def has_permission(cls, user_roles: list[str], required_permission: str) -> bool:
- """Check if user has required permission."""
- for role in user_roles:
- permissions = cls.ROLES.get(role, [])
- if required_permission in permissions or "write:*" in permissions or "read:*" in permissions:
- return True
- return False
-
-
-def require_permission(permission: str):
- """Decorator to require specific permission."""
- def decorator(func):
- async def wrapper(*args, current_user: dict = Depends(get_current_user), **kwargs):
- user_roles = current_user.get("roles", [])
-
- if not RBACPermissions.has_permission(user_roles, permission):
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail=f"Permission denied: {permission} required"
- )
-
- return await func(*args, current_user=current_user, **kwargs)
- return wrapper
- return decorator
-
-
-# Usage
-@router.post("/api/v1/patients")
-@require_permission("write:patients")
-async def create_patient(
- patient_data: PatientCreate,
- current_user: dict = Depends(get_current_user)
-):
- """Create patient - requires write:patients permission."""
- # Implementation
- pass
-```
-
-## Secrets Management
-
-```python
-import os
-from typing import Optional
-
-
-class SecureConfig:
- """Secure configuration management - NEVER hardcode secrets."""
-
- @staticmethod
- def get_secret(key: str, default: Optional[str] = None) -> str:
- """Get secret from environment variable."""
- value = os.getenv(key, default)
-
- if value is None:
- raise ValueError(f"Required secret '{key}' not found in environment")
-
- return value
-
- # Database credentials
- DATABASE_URL = get_secret.__func__("DATABASE_URL")
- DATABASE_PASSWORD = get_secret.__func__("DATABASE_PASSWORD")
-
- # JWT secrets
- JWT_SECRET_KEY = get_secret.__func__("JWT_SECRET_KEY")
- JWT_ALGORITHM = get_secret.__func__("JWT_ALGORITHM", "RS256")
-
- # Encryption keys
- ENCRYPTION_KEY = get_secret.__func__("ENCRYPTION_KEY")
-
- # API keys
- THIRD_PARTY_API_KEY = get_secret.__func__("THIRD_PARTY_API_KEY")
-
-
-# .env file (never commit to git!)
-"""
-DATABASE_URL=postgresql://user:password@localhost:5432/yaz_care
-DATABASE_PASSWORD=secure_password_here
-JWT_SECRET_KEY=your_jwt_secret_key_here
-ENCRYPTION_KEY=your_encryption_key_here
-"""
-
-# .gitignore (always include)
-"""
-.env
-.env.local
-.env.production
-*.pem
-*.key
-secrets/
-"""
-```
-
-## Security Checklist
-
-Before deploying any feature:
-
-- [ ] **Input Validation**: All user inputs validated with Pydantic
-- [ ] **SQL Injection**: Only parameterized queries used
-- [ ] **XSS Prevention**: All output escaped
-- [ ] **CSRF Protection**: CSRF tokens on state-changing operations
-- [ ] **Authentication**: JWT tokens with short expiry
-- [ ] **Authorization**: RBAC/ABAC enforced on all endpoints
-- [ ] **Secrets Management**: No hardcoded secrets
-- [ ] **Audit Logging**: All PHI access logged with signature
-- [ ] **Encryption**: AES-256 at rest, TLS 1.3 in transit
-- [ ] **Multi-Tenancy**: Tenant isolation verified
-- [ ] **Rate Limiting**: Applied to all public endpoints
-- [ ] **Security Headers**: CSP, HSTS, X-Frame-Options set
-- [ ] **Dependency Scanning**: No known vulnerabilities
-- [ ] **Penetration Testing**: Security review completed
-
-## Compliance Requirements
-
-### HIPAA
-- [ ] PHI encrypted at rest and in transit
-- [ ] Audit logs for all PHI access
-- [ ] Access controls enforced
-- [ ] Data breach notification process
-- [ ] Business associate agreements
-
-### GDPR
-- [ ] Right to access (data export)
-- [ ] Right to erasure (data deletion)
-- [ ] Data portability
-- [ ] Consent management
-- [ ] Data processing agreements
diff --git a/.github/copilot-prompts/testing-protocol.md b/.github/copilot-prompts/testing-protocol.md
deleted file mode 100644
index d9c7a481383c81f217868814c52fd1d0ec4f857e..0000000000000000000000000000000000000000
--- a/.github/copilot-prompts/testing-protocol.md
+++ /dev/null
@@ -1,925 +0,0 @@
-# Testing Protocol - YAZ Care Platform
-
-> **Purpose**: Comprehensive testing guidelines for all code changes in the YAZ Care healthcare platform
-> **Target**: 85%+ test coverage, <200ms p95 latency, 100% multi-tenant isolation
-> **Updated**: December 26, 2025
-
----
-
-## Table of Contents
-
-1. [Test Types & When to Use](#test-types--when-to-use)
-2. [Unit Test Patterns](#unit-test-patterns)
-3. [Integration Test Patterns](#integration-test-patterns)
-4. [E2E Test Patterns](#e2e-test-patterns)
-5. [Performance Test Patterns](#performance-test-patterns)
-6. [Security Test Patterns](#security-test-patterns)
-7. [Multi-Tenancy Test Patterns](#multi-tenancy-test-patterns)
-8. [Clinical Standards Test Patterns](#clinical-standards-test-patterns)
-9. [Test Data Management](#test-data-management)
-10. [CI/CD Integration](#cicd-integration)
-
----
-
-## Test Types & When to Use
-
-### Decision Tree
-
-```
-Is it testing a single function/method in isolation?
-ββ YES β Unit Test
-ββ NO β Is it testing interaction between multiple components?
- ββ YES β Integration Test
- ββ NO β Is it testing complete user workflow?
- ββ YES β E2E Test
- ββ NO β Is it testing performance/load?
- ββ YES β Performance Test
- ββ NO β Security/Compliance Test
-```
-
-### Test Coverage Requirements
-
-| Test Type | Coverage Target | Execution Time | Frequency |
-|-----------|----------------|----------------|-----------|
-| Unit Tests | 85%+ per module | <5s per module | Every commit |
-| Integration Tests | All critical workflows | <30s per test | Every PR |
-| E2E Tests | Happy path + error scenarios | <2min per test | Pre-merge |
-| Performance Tests | SLA validation | <5min | Daily + pre-release |
-| Security Tests | OWASP Top 10 | <10min | Daily |
-| Multi-Tenancy Tests | Isolation verification | <1min | Every commit |
-
----
-
-## Unit Test Patterns
-
-### Pattern 1: Service Layer Business Logic
-
-**When to Use**: Testing business logic in service classes (e.g., risk calculations, validation rules)
-
-**Template**:
-```python
-import pytest
-from uuid import UUID
-from datetime import datetime
-from src.apps.{module}.services.{entity}_service import {Entity}Service
-from src.apps.{module}.domain.models import {Entity}
-
-class Test{Entity}Service:
- """Test suite for {Entity}Service business logic"""
-
- @pytest.fixture
- def service(self):
- """Create service instance with mocked dependencies"""
- return {Entity}Service()
-
- @pytest.fixture
- def valid_{entity}_data(self):
- """Valid {entity} data for testing"""
- return {
- "name": "Test Entity",
- "tenant_id": "tenant-test-001",
- # Add required fields
- }
-
- def test_create_{entity}_success(self, service, valid_{entity}_data):
- """Test successful {entity} creation with valid data"""
- # Arrange
- data = valid_{entity}_data
-
- # Act
- result = await service.create_{entity}(**data)
-
- # Assert
- assert result.id is not None
- assert result.name == data["name"]
- assert result.tenant_id == data["tenant_id"]
- assert result.created_at is not None
-
- def test_create_{entity}_missing_required_field(self, service):
- """Test {entity} creation fails with missing required field"""
- # Arrange
- invalid_data = {"tenant_id": "tenant-test-001"} # Missing 'name'
-
- # Act & Assert
- with pytest.raises(ValidationError) as exc_info:
- await service.create_{entity}(**invalid_data)
-
- assert "name" in str(exc_info.value)
-
- def test_create_{entity}_invalid_tenant_id(self, service, valid_{entity}_data):
- """Test {entity} creation fails with invalid tenant_id format"""
- # Arrange
- valid_{entity}_data["tenant_id"] = "invalid-format"
-
- # Act & Assert
- with pytest.raises(ValidationError) as exc_info:
- await service.create_{entity}(**valid_{entity}_data)
-
- assert "tenant_id" in str(exc_info.value)
-```
-
-**Real Example**: `tests/apps/surgio/test_surgical_case_service.py`
-
----
-
-### Pattern 2: Clinical Algorithm Testing
-
-**When to Use**: Testing clinical decision support algorithms (e.g., risk scores, screening tools)
-
-**Template**:
-```python
-import pytest
-from src.apps.clinica.services.clinical_algorithms import (
- calculate_sepsis_risk,
- SepsisRiskResult
-)
-
-class TestSepsisRiskCalculation:
- """Test sepsis risk calculation algorithm (qSOFA + SIRS + Sepsis-3)"""
-
- def test_high_risk_sepsis_detection(self):
- """
- Test high-risk sepsis detection with critical indicators
-
- Clinical Context: Patient with fever, tachycardia, hypotension
- Expected: High risk score (>0.8), immediate intervention recommended
- Standards: Surviving Sepsis Campaign 2021
- """
- # Arrange - High-risk patient data
- patient_data = {
- "temperature": 39.5, # Celsius - fever
- "heart_rate": 125, # bpm - tachycardia
- "respiratory_rate": 28, # breaths/min - tachypnea
- "systolic_bp": 85, # mmHg - hypotension
- "wbc_count": 18000, # cells/ΞΌL - elevated
- "lactate": 3.5, # mmol/L - elevated
- "glasgow_coma": 13 # Altered mental status
- }
-
- # Act
- result = calculate_sepsis_risk(patient_data)
-
- # Assert
- assert isinstance(result, SepsisRiskResult)
- assert result.score > 0.8, "High-risk patient should have score >0.8"
- assert result.severity == "high"
- assert result.qsofa_score >= 2, "qSOFA β₯2 indicates sepsis"
- assert "immediate_intervention" in result.recommendations
- assert "blood_cultures" in result.recommendations
- assert "broad_spectrum_antibiotics" in result.recommendations
-
- def test_moderate_risk_sepsis_detection(self):
- """Test moderate-risk sepsis with some indicators"""
- patient_data = {
- "temperature": 38.2,
- "heart_rate": 105,
- "respiratory_rate": 22,
- "systolic_bp": 105,
- "wbc_count": 13000,
- "lactate": 2.0,
- "glasgow_coma": 15
- }
-
- result = calculate_sepsis_risk(patient_data)
-
- assert 0.4 < result.score < 0.8
- assert result.severity == "moderate"
- assert "monitoring" in result.recommendations
-
- def test_low_risk_normal_patient(self):
- """Test low-risk with normal vital signs"""
- patient_data = {
- "temperature": 37.0,
- "heart_rate": 75,
- "respiratory_rate": 16,
- "systolic_bp": 120,
- "wbc_count": 8000,
- "lactate": 1.0,
- "glasgow_coma": 15
- }
-
- result = calculate_sepsis_risk(patient_data)
-
- assert result.score < 0.4
- assert result.severity == "low"
- assert result.qsofa_score < 2
-
- def test_missing_vital_signs_handling(self):
- """Test graceful handling of missing data"""
- patient_data = {
- "temperature": 38.5,
- "heart_rate": 110
- # Missing other vitals
- }
-
- result = calculate_sepsis_risk(patient_data)
-
- assert result.data_completeness < 1.0
- assert "incomplete_data" in result.warnings
-
- def test_edge_case_borderline_values(self):
- """Test behavior with borderline clinical values"""
- patient_data = {
- "temperature": 38.0, # Just at fever threshold
- "heart_rate": 90, # Upper normal
- "respiratory_rate": 20, # Upper normal
- "systolic_bp": 100, # Lower normal
- "wbc_count": 12000, # Borderline elevated
- "lactate": 2.0, # Upper normal
- "glasgow_coma": 15
- }
-
- result = calculate_sepsis_risk(patient_data)
-
- # Should not trigger high-risk alerts with borderline values
- assert result.score < 0.7
-```
-
-**Key Principles**:
-- Test high/moderate/low risk scenarios
-- Include edge cases and borderline values
-- Test missing/incomplete data handling
-- Document clinical context and standards
-- Assert on specific clinical recommendations
-
----
-
-## Integration Test Patterns
-
-### Pattern 3: API Endpoint Testing
-
-**When to Use**: Testing complete API workflows from request to response
-
-**Template**:
-```python
-import pytest
-from httpx import AsyncClient
-from src.main import app
-
-@pytest.mark.asyncio
-class TestPatientAPI:
- """Integration tests for Patient API endpoints"""
-
- @pytest.fixture
- async def async_client(self):
- """Create async HTTP client for testing"""
- async with AsyncClient(app=app, base_url="http://test") as client:
- yield client
-
- @pytest.fixture
- async def auth_headers(self, async_client):
- """Get authentication headers with JWT token"""
- # Login as test user
- response = await async_client.post(
- "/api/v1/auth/login",
- json={
- "username": "test.clinician@hospital.com",
- "password": "test_password_123"
- }
- )
- token = response.json()["data"]["access_token"]
-
- return {
- "Authorization": f"Bearer {token}",
- "X-Tenant-ID": "tenant-test-001"
- }
-
- async def test_create_patient_success(self, async_client, auth_headers):
- """Test successful patient creation via API"""
- # Arrange
- patient_data = {
- "first_name": "John",
- "last_name": "Doe",
- "date_of_birth": "1980-01-15",
- "gender": "male",
- "mrn": "MRN-12345"
- }
-
- # Act
- response = await async_client.post(
- "/api/v1/clinica/patients",
- json=patient_data,
- headers=auth_headers
- )
-
- # Assert
- assert response.status_code == 201
- data = response.json()["data"]
- assert data["first_name"] == "John"
- assert data["last_name"] == "Doe"
- assert "id" in data
- assert "created_at" in data
-
- # Verify audit log created
- audit_response = await async_client.get(
- f"/api/v1/audit/logs?resource_id={data['id']}",
- headers=auth_headers
- )
- assert audit_response.status_code == 200
- assert len(audit_response.json()["data"]) > 0
-
- async def test_create_patient_unauthorized(self, async_client):
- """Test patient creation fails without authentication"""
- patient_data = {"first_name": "John", "last_name": "Doe"}
-
- response = await async_client.post(
- "/api/v1/clinica/patients",
- json=patient_data
- )
-
- assert response.status_code == 401
- assert "authentication" in response.json()["error"].lower()
-
- async def test_create_patient_invalid_data(self, async_client, auth_headers):
- """Test patient creation with invalid data returns 400"""
- invalid_data = {
- "first_name": "", # Empty name
- "date_of_birth": "invalid-date"
- }
-
- response = await async_client.post(
- "/api/v1/clinica/patients",
- json=invalid_data,
- headers=auth_headers
- )
-
- assert response.status_code == 400
- error = response.json()
- assert error["error"] == "validation_error"
- assert "first_name" in error["details"]
-
- async def test_get_patient_by_id(self, async_client, auth_headers):
- """Test retrieving patient by ID"""
- # Create patient first
- create_response = await async_client.post(
- "/api/v1/clinica/patients",
- json={"first_name": "Jane", "last_name": "Smith", "mrn": "MRN-67890"},
- headers=auth_headers
- )
- patient_id = create_response.json()["data"]["id"]
-
- # Retrieve patient
- response = await async_client.get(
- f"/api/v1/clinica/patients/{patient_id}",
- headers=auth_headers
- )
-
- assert response.status_code == 200
- data = response.json()["data"]
- assert data["id"] == patient_id
- assert data["first_name"] == "Jane"
-
- async def test_list_patients_pagination(self, async_client, auth_headers):
- """Test patient list endpoint with pagination"""
- # Create multiple patients
- for i in range(25):
- await async_client.post(
- "/api/v1/clinica/patients",
- json={"first_name": f"Patient{i}", "last_name": "Test", "mrn": f"MRN-{i}"},
- headers=auth_headers
- )
-
- # Test pagination
- response = await async_client.get(
- "/api/v1/clinica/patients?page=1&per_page=10",
- headers=auth_headers
- )
-
- assert response.status_code == 200
- data = response.json()
- assert data["page"] == 1
- assert data["per_page"] == 10
- assert len(data["data"]) == 10
- assert data["total"] >= 25
-```
-
----
-
-## Multi-Tenancy Test Patterns
-
-### Pattern 4: Tenant Isolation Testing
-
-**When to Use**: Verifying data isolation between tenants (CRITICAL for every feature)
-
-**Template**:
-```python
-import pytest
-from uuid import uuid4
-
-@pytest.mark.asyncio
-class TestMultiTenantIsolation:
- """Test multi-tenant data isolation for {Entity}"""
-
- @pytest.fixture
- async def tenant_a_data(self, async_client):
- """Create test data for Tenant A"""
- tenant_id = "tenant-a-001"
- auth_headers = await get_auth_headers(async_client, tenant_id)
-
- # Create entity in Tenant A
- response = await async_client.post(
- "/api/v1/{module}/{entity}",
- json={"name": "Tenant A Entity", "value": "confidential_a"},
- headers=auth_headers
- )
-
- return {
- "tenant_id": tenant_id,
- "entity_id": response.json()["data"]["id"],
- "headers": auth_headers
- }
-
- @pytest.fixture
- async def tenant_b_data(self, async_client):
- """Create test data for Tenant B"""
- tenant_id = "tenant-b-002"
- auth_headers = await get_auth_headers(async_client, tenant_id)
-
- # Create entity in Tenant B
- response = await async_client.post(
- "/api/v1/{module}/{entity}",
- json={"name": "Tenant B Entity", "value": "confidential_b"},
- headers=auth_headers
- )
-
- return {
- "tenant_id": tenant_id,
- "entity_id": response.json()["data"]["id"],
- "headers": auth_headers
- }
-
- async def test_tenant_cannot_read_other_tenant_data(
- self,
- async_client,
- tenant_a_data,
- tenant_b_data
- ):
- """
- Verify Tenant B cannot read Tenant A's data
-
- Security Context: Multi-tenant data isolation (HIPAA requirement)
- Expected: 404 Not Found (not 403 to avoid information disclosure)
- """
- # Tenant B attempts to access Tenant A's entity
- response = await async_client.get(
- f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}",
- headers=tenant_b_data["headers"]
- )
-
- # Should return 404 (not 403) to avoid leaking entity existence
- assert response.status_code == 404
- assert "not found" in response.json()["message"].lower()
-
- async def test_tenant_cannot_update_other_tenant_data(
- self,
- async_client,
- tenant_a_data,
- tenant_b_data
- ):
- """Verify Tenant B cannot update Tenant A's data"""
- response = await async_client.put(
- f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}",
- json={"name": "Malicious Update"},
- headers=tenant_b_data["headers"]
- )
-
- assert response.status_code == 404
-
- async def test_tenant_cannot_delete_other_tenant_data(
- self,
- async_client,
- tenant_a_data,
- tenant_b_data
- ):
- """Verify Tenant B cannot delete Tenant A's data"""
- response = await async_client.delete(
- f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}",
- headers=tenant_b_data["headers"]
- )
-
- assert response.status_code == 404
-
- # Verify Tenant A's data still exists
- verify_response = await async_client.get(
- f"/api/v1/{module}/{entity}/{tenant_a_data['entity_id']}",
- headers=tenant_a_data["headers"]
- )
- assert verify_response.status_code == 200
-
- async def test_list_endpoint_filters_by_tenant(
- self,
- async_client,
- tenant_a_data,
- tenant_b_data
- ):
- """Verify list endpoint only returns tenant's own data"""
- # Tenant A lists entities
- response_a = await async_client.get(
- f"/api/v1/{module}/{entity}",
- headers=tenant_a_data["headers"]
- )
-
- data_a = response_a.json()["data"]
- tenant_a_ids = [item["id"] for item in data_a]
-
- # Tenant B's entity ID should NOT appear in Tenant A's list
- assert tenant_b_data["entity_id"] not in tenant_a_ids
-
- # Tenant A's entity ID SHOULD appear
- assert tenant_a_data["entity_id"] in tenant_a_ids
-
- async def test_database_query_includes_tenant_filter(self, db_session):
- """Verify raw database queries include tenant_id filter"""
- from sqlalchemy import text
-
- # Attempt query without tenant_id (should fail or return empty)
- query = text("SELECT * FROM {schema}.{table} WHERE id = :id")
- result = await db_session.execute(
- query,
- {"id": tenant_a_data["entity_id"]}
- )
-
- # Without search_path or tenant_id filter, should not find data
- assert result.rowcount == 0 or result is None
-```
-
-**Critical Rules**:
-1. Every API endpoint MUST have tenant isolation test
-2. Return 404 (not 403) to avoid information disclosure
-3. Test create, read, update, delete, and list operations
-4. Verify raw database queries include tenant filters
-5. Test with at least 2 different tenants
-
----
-
-## Performance Test Patterns
-
-### Pattern 5: API Latency Testing
-
-**When to Use**: Validating SLA compliance (<200ms p95 latency)
-
-**Template**:
-```python
-import pytest
-import time
-from statistics import mean, median
-from typing import List
-
-@pytest.mark.performance
-class TestAPIPerformance:
- """Performance tests for API endpoints (SLA: <200ms p95)"""
-
- async def measure_endpoint_latency(
- self,
- async_client,
- method: str,
- url: str,
- headers: dict,
- iterations: int = 100
- ) -> List[float]:
- """Measure endpoint latency over multiple iterations"""
- latencies = []
-
- for _ in range(iterations):
- start = time.time()
-
- if method == "GET":
- response = await async_client.get(url, headers=headers)
- elif method == "POST":
- response = await async_client.post(url, json={}, headers=headers)
-
- latency_ms = (time.time() - start) * 1000
- latencies.append(latency_ms)
-
- assert response.status_code in [200, 201, 400] # Valid responses
-
- return latencies
-
- def calculate_percentiles(self, latencies: List[float]):
- """Calculate latency percentiles"""
- sorted_latencies = sorted(latencies)
- n = len(sorted_latencies)
-
- return {
- "p50": sorted_latencies[int(n * 0.50)],
- "p95": sorted_latencies[int(n * 0.95)],
- "p99": sorted_latencies[int(n * 0.99)],
- "mean": mean(latencies),
- "median": median(latencies),
- "min": min(latencies),
- "max": max(latencies)
- }
-
- async def test_patient_list_latency(self, async_client, auth_headers):
- """
- Test patient list endpoint latency
-
- Performance Target: <200ms p95
- Load: 100 sequential requests
- """
- # Arrange - Pre-populate database
- for i in range(50):
- await async_client.post(
- "/api/v1/clinica/patients",
- json={"first_name": f"Patient{i}", "last_name": "Test"},
- headers=auth_headers
- )
-
- # Act - Measure latency
- latencies = await self.measure_endpoint_latency(
- async_client,
- "GET",
- "/api/v1/clinica/patients?page=1&per_page=20",
- auth_headers,
- iterations=100
- )
-
- # Assert
- percentiles = self.calculate_percentiles(latencies)
-
- print(f"\nPatient List Latency:")
- print(f" P50: {percentiles['p50']:.2f}ms")
- print(f" P95: {percentiles['p95']:.2f}ms")
- print(f" P99: {percentiles['p99']:.2f}ms")
- print(f" Mean: {percentiles['mean']:.2f}ms")
-
- # SLA assertion
- assert percentiles['p95'] < 200, \
- f"P95 latency {percentiles['p95']:.2f}ms exceeds SLA of 200ms"
-
- async def test_concurrent_request_performance(self, async_client, auth_headers):
- """Test API performance under concurrent load"""
- import asyncio
-
- async def make_request():
- start = time.time()
- response = await async_client.get(
- "/api/v1/clinica/patients",
- headers=auth_headers
- )
- return (time.time() - start) * 1000
-
- # Simulate 50 concurrent requests
- tasks = [make_request() for _ in range(50)]
- latencies = await asyncio.gather(*tasks)
-
- percentiles = self.calculate_percentiles(latencies)
-
- assert percentiles['p95'] < 200
- assert max(latencies) < 500, "No request should exceed 500ms"
-```
-
----
-
-## Security Test Patterns
-
-### Pattern 6: Authentication & Authorization Testing
-
-**Template**:
-```python
-@pytest.mark.security
-class TestAuthenticationSecurity:
- """Security tests for authentication and authorization"""
-
- async def test_endpoint_requires_authentication(self, async_client):
- """Verify protected endpoint rejects unauthenticated requests"""
- response = await async_client.get("/api/v1/clinica/patients")
-
- assert response.status_code == 401
- assert "authentication" in response.json()["error"].lower()
-
- async def test_expired_token_rejected(self, async_client):
- """Verify expired JWT tokens are rejected"""
- expired_token = generate_expired_token()
-
- response = await async_client.get(
- "/api/v1/clinica/patients",
- headers={"Authorization": f"Bearer {expired_token}"}
- )
-
- assert response.status_code == 401
- assert "expired" in response.json()["message"].lower()
-
- async def test_insufficient_permissions_denied(self, async_client):
- """Verify users without required permissions cannot access endpoint"""
- # Login as user with limited permissions
- token = await get_auth_token(async_client, role="nurse")
-
- # Attempt admin-only action
- response = await async_client.delete(
- "/api/v1/clinica/patients/patient-123",
- headers={"Authorization": f"Bearer {token}"}
- )
-
- assert response.status_code == 403
- assert "permission" in response.json()["message"].lower()
-
- async def test_sql_injection_protection(self, async_client, auth_headers):
- """Verify SQL injection attempts are blocked"""
- malicious_inputs = [
- "'; DROP TABLE patients; --",
- "1' OR '1'='1",
- "admin'--",
- "1 UNION SELECT * FROM users--"
- ]
-
- for malicious_input in malicious_inputs:
- response = await async_client.get(
- f"/api/v1/clinica/patients?search={malicious_input}",
- headers=auth_headers
- )
-
- # Should either return 400 (validation error) or safe results
- assert response.status_code in [200, 400]
- # Database should still be intact (verify critical table exists)
-
- async def test_xss_protection(self, async_client, auth_headers):
- """Verify XSS payloads are sanitized"""
- xss_payload = ""
-
- response = await async_client.post(
- "/api/v1/clinica/patients",
- json={"first_name": xss_payload, "last_name": "Test"},
- headers=auth_headers
- )
-
- # Either rejected or sanitized
- if response.status_code == 201:
- data = response.json()["data"]
- assert ""
-
- response = await async_client.post(
- "/api/v1/clinica/patients",
- json={"first_name": xss_payload, "last_name": "Test"},
- headers=auth_headers
- )
-
- # Either rejected or sanitized
- if response.status_code == 201:
- data = response.json()["data"]
- assert "|javascript:|onerror=|onload=|