# YAZ Platform β€” AI Coder Commandments **Version**: 8.4.6 **Date**: May 4, 2026 **Status**: ⚑ MANDATORY β€” Violation = Build Failure --- ## πŸ—οΈ PLATFORM vs ENGINES vs INTELLIGENCES (CRITICAL v7.0.0) > **Platform** = Domain-agnostic orchestration layer (events, cases, actors, resources, 24 pillars) > **Engines** = Domain-specific subsystems encapsulating professional intelligence (Surgio, Movio, Banko…) > **Intelligences** = Packaged expertise modules created by professionals, deployed via marketplace ``` PLATFORM (Static Infrastructure) ENGINES (Domain Subsystems) INTELLIGENCES (Packaged Expertise) β”œβ”€β”€ core/database/ β”œβ”€β”€ Surgio (surgery) β”œβ”€β”€ Appendectomy Protocol (Dr. E) β”œβ”€β”€ core/auth/ β”œβ”€β”€ Clinica (clinical care) β”œβ”€β”€ NEWS2 Early Warning (NHS) β”œβ”€β”€ core/engines/ β”œβ”€β”€ Movio (mobility/transport) β”œβ”€β”€ Route Optimization (LogiCo) β”œβ”€β”€ core/intelligence/ β”œβ”€β”€ Banko (finance) β”œβ”€β”€ Claims Workflow (InsureTech) β”œβ”€β”€ core/marketplace/ β”œβ”€β”€ Insura (insurance) └── QC Westgard Pack (LabPro) β”œβ”€β”€ core/pillars/ (24 services) β”œβ”€β”€ Stay (hospitality) └── core/{services}/ └── ... any professional domain [Published via /api/v1/intelligences] ``` **Key Principle**: Medicine is simply one operational domain. The same architecture orchestrates a surgical case, a transport operation, an insurance contract, or a hospitality service. Any professional can create domain engines and intelligence modules to solve cases in any field and commercialise them. --- ## πŸ—οΈ Four Pillars Compliance (v5.3.0) > **NEW**: The Four Pillars architecture requires compliance with these additional rules. | Pillar | Service | Commandment Alignment | |--------|---------|----------------------| | 1 | **CHECKLIST** | Commandments 1, 3, 4, 6 (Schema-driven, tenant-isolated, tested, audited) | | 2 | **JOURNAL** | Commandments 3, 5, 6 (Hash-chain integrity, observable, HIPAA compliant) | | 3 | **MONITOR** | Commandments 2, 5 (Performance-critical, metrics-driven) | | 4 | **PROTOCOL** | Commandments 1, 4, 7 (Config-driven workflows, typed, proven patterns) | **Core Principle**: Services are **primitives**, not features. Domain packs **compose** services, not implement them. --- ## The 11 Unbreakable Rules These commandments are **non-negotiable**. Every AI coder, human developer, and automated tool MUST comply. Violation triggers CI/CD pipeline rejection. --- ## 1. πŸ”’ ZERO CORE CHANGES - Config Over Code > **Never modify core logic. All customization via config/tenant settings/workflow packs only.** ### What This Means for YAZ The domain-agnostic case engine in `/src/core/` is **immutable**. New features ship as: | Customization Type | Location | Example | |-------------------|----------|---------| | **App Settings** | `config/app.yml` | Performance tuning, feature flags | | **Tenant Config** | `governance.tenants` table | Branding, limits, enabled tools | | **Workflow Packs** | `apps.{app}/workflows/` | Custom clinical pathways | | **Feature Flags** | `governance.system_tools.config` | A/B testing, gradual rollouts | | **API Versioning** | `/api/v1/`, `/api/v2/` | Non-breaking evolution | ### βœ… DO ```python # Add feature via config @dataclass(frozen=True) class ServiceConfig: FEATURE_NEWS2_ENABLED: bool = True # Toggle via config FEATURE_QSOFA_THRESHOLD: float = 0.6 # Tunable parameter ``` ### ❌ DON'T ```python # NEVER hardcode business logic in core class BaseService: def calculate_risk(self): if patient.age > 65: # DON'T! This belongs in config return "high_risk" ``` ### Enforcement - **CI Check**: `scripts/validation/check_core_immutability.py` - **Protected Paths**: `/src/core/database/`, `/src/core/multitenancy/`, `/src/core/services/base*.py` - **Exceptions**: Require ADMIN approval + architecture review --- ## 2. ⚑ PERFORMANCE FIRST - Sub-200ms or Die > **P95 <200ms for all operations. No bloat, no N+1 queries, no lazy loading anti-patterns.** ### Current YAZ Benchmarks (Baseline) | Operation | Target | Actual | Status | |-----------|--------|--------|--------| | API Response (p95) | <100ms | 47ms | βœ… | | Cache Hit Rate | >90% | 94.7% | βœ… | | WebSocket Latency | <20ms | <20ms | βœ… | | List Operations | <100ms | ~50ms | βœ… | | Algorithm Execution | <50ms | ~30ms | βœ… | ### Performance Patterns (MANDATORY) ```python # src/core/services/base_service.py - Already enforced @dataclass(frozen=True) class ServiceConfig: SLA_LIST_MS: int = 100 # List operations SLA_GET_MS: int = 50 # Get operations SLA_CRUD_MS: int = 200 # CRUD operations SLA_ALGORITHM_MS: int = 50 # Clinical algorithms ``` ### βœ… DO ```python # Eager loading (prevent N+1) query = select(SurgeryCase).options( selectinload(SurgeryCase.team_members), selectinload(SurgeryCase.checklist) ).where(SurgeryCase.tenant_id == tenant_id) # Indexed tenant queries (ALWAYS first filter) query = select(Patient).where( Patient.tenant_id == tenant_id, # Most selective first Patient.status == 'active' ).limit(50) # 4-tier caching strategy @cache(ttl=ServiceConfig.CACHE_TTL_TENANT) # 1 hour async def get_tenant_config(tenant_id: UUID): ... ``` ### ❌ DON'T ```python # N+1 query (KILLS performance) for case in cases: case.patients = await get_patients(case.id) # N+1! # SELECT * (wasteful) query = select(Patient) # BAD - loads all columns # Missing tenant filter (security + performance) query = select(Patient).where(Patient.status == 'active') # No tenant_id! ``` ### Enforcement - **Load Testing**: `infra/load-testing/` - Locust scripts run on every PR - **P95 Check**: Prometheus alerts if p95 >200ms for 5 minutes - **Index Validation**: `scripts/database/check_indexes.py` --- ## 3. πŸ›‘οΈ TENANT ISOLATION IS SACRED > **Schema-per-tenant PostgreSQL RLS enforced. Never cross tenant boundaries.** ### YAZ Multi-Tenancy Architecture ``` Strategy: Schema-per-tenant (PostgreSQL schemas) Enforcement: Every query MUST include tenant_id filter Testing: 15+ isolation tests run on every PR Breach: = Catastrophic failure β†’ immediate rollback ``` ### Implementation Patterns ```python # src/core/repositories/base.py - MANDATORY pattern class BaseRepository: def _apply_tenant_filter(self, query): """ALWAYS applies tenant filter - no exceptions.""" return query.where(self.model.tenant_id == self.tenant_id) # src/apps/_common/crud_service.py - Line 117 query = select(self.model).where(self.model.tenant_id == tenant_id) ``` ### βœ… DO ```python # Every query starts with tenant_id async def get_patients(tenant_id: UUID) -> List[Patient]: query = select(Patient).where( Patient.tenant_id == tenant_id # MANDATORY FIRST ) return await session.execute(query) # Test tenant isolation in every PR @pytest.mark.isolation async def test_tenant_cannot_see_other_tenant_data(): patient_a = await create_patient(tenant_a.id) result = await get_patient(patient_a.id, tenant_b.id) assert result is None # MUST be None ``` ### ❌ DON'T ```python # NEVER query without tenant_id patients = await session.execute(select(Patient)) # SECURITY BREACH! # NEVER bypass tenant middleware @router.get("/admin/all-patients") # Cross-tenant route = FORBIDDEN async def get_all_patients(): ... ``` ### Enforcement - **Query Linting**: `scripts/validation/check_tenant_filters.py` - **Test Suite**: `tests/isolation/` - 15 mandatory tests - **CI Gate**: PRs fail if any isolation test fails --- ## 4. βœ… TYPE SAFETY + TESTS = NON-NEGOTIABLE > **100% type hints, docstrings mandatory, 85%+ test coverage minimum.** ### YAZ Quality Standards | Metric | Target | Current | Status | |--------|--------|---------|--------| | Type Hint Coverage | 100% | 95%+ | πŸ”„ | | Docstring Coverage | 100% | 90%+ | πŸ”„ | | Test Coverage | 85%+ | 85% | βœ… | | Mypy Pass | 100% | 100% | βœ… | ### βœ… DO ```python # Complete type hints (Python 3.11+) async def calculate_surgical_risk( patient_data: PatientVitals, procedure_code: str, tenant_id: UUID, user_id: UUID ) -> RiskAssessment: """ Calculate preoperative surgical risk using ASA criteria. Clinical Context: Preoperative risk stratification Standards: ASA Physical Status Classification System Performance: <50ms target Security: PHI level HIGH, audit logged Args: patient_data: Patient vital signs and history procedure_code: CPT procedure code tenant_id: Tenant identifier for isolation user_id: Requesting user for audit trail Returns: RiskAssessment with score, level, and recommendations Raises: ValidationError: If patient data is incomplete TenantIsolationError: If tenant mismatch detected """ ... ``` ### Testing Requirements ```python # tests/apps/surgio/test_risk_service.py @pytest.mark.asyncio async def test_high_risk_patient(): """Unit test for algorithm logic""" ... @pytest.mark.integration async def test_risk_calculation_api(): """Integration test for full workflow""" ... @pytest.mark.isolation async def test_risk_tenant_isolation(): """Tenant isolation verification""" ... @pytest.mark.performance async def test_risk_calculation_sla(): """Performance SLA verification (<50ms)""" start = time.time() result = await calculate_risk(...) assert (time.time() - start) * 1000 < 50 ``` ### Enforcement - **Pre-Commit**: `mypy src/` must pass - **Coverage Gate**: `pytest --cov-fail-under=85` - **Docstring Check**: `pydocstyle src/` --- ## 5. πŸ“Š OBSERVABILITY EVERYWHERE > **Structured logging, OpenTelemetry traces, Prometheus metrics on every service.** ### YAZ Observability Stack | Component | Tool | Location | |-----------|------|----------| | Logging | Structlog (JSON) | `/src/core/observability/` | | Tracing | OpenTelemetry | `/src/core/observability/` | | Metrics | Prometheus | `/src/monitoring/prometheus_metrics.py` | | Dashboards | Grafana | 4 production dashboards | | Alerts | 8 production rules | `alert-rules.yml` | ### βœ… DO ```python # Structured logging (NO PHI) import structlog logger = structlog.get_logger(__name__) logger.info( "surgery_case_created", case_id=str(case.id), # Safe: UUID only tenant_id=str(tenant_id), user_id=str(user_id), procedure_code=procedure_code, duration_ms=duration_ms, trace_id=trace_id, sensitive=True # Marks PHI access for audit ) # Prometheus metrics from prometheus_client import Histogram, Counter request_duration = Histogram( 'yaz_request_duration_seconds', 'Request duration in seconds', ['method', 'endpoint', 'status', 'tenant'] ) # OpenTelemetry tracing from opentelemetry import trace tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("calculate_surgical_risk") as span: span.set_attribute("case.id", str(case_id)) span.set_attribute("risk.level", risk_level) ``` ### ❌ DON'T ```python # NEVER log PHI logger.info(f"Patient {patient.name} SSN: {patient.ssn}") # HIPAA VIOLATION! # NEVER use print() in production print(f"Debug: {data}") # Use structured logging! # NEVER skip error tracking try: risky_operation() except Exception: pass # Silent failures = blind spots! ``` ### Enforcement - **Log Format**: JSON only, validated by CI - **Alert Coverage**: Every service must have SLA alerts - **Trace Sampling**: 100% for errors, 10% for success --- ## 6. πŸ₯ HIPAA COMPLIANCE IS DEFAULT > **PHI encryption, audit trails, FDA 21 CFR Part 11 electronic signatures.** ### YAZ Security Standards | Requirement | Implementation | Location | |-------------|----------------|----------| | Encryption at Rest | AES-256 | PostgreSQL TDE | | Encryption in Transit | TLS 1.3 | Nginx/FastAPI | | Audit Logging | Cryptographic signatures | `/src/core/security/audit_immutable.py` | | Access Control | RBAC + ABAC | `/src/core/security/rbac.py` | | PHI Protection | Field-level encryption | `/src/core/security/encryption.py` | ### βœ… DO ```python # Use to_dict_safe() for logging (removes PHI) class Patient(SQLModel): def to_dict_safe(self) -> dict: """Safe dict without PHI for logging.""" return { "id": str(self.id), "tenant_id": str(self.tenant_id), "status": self.status # Exclude: name, ssn, dob, medical_history } # Audit all PHI access @audit_log(action="patient.viewed", resource_type="patient", phi_access=True) async def get_patient(patient_id: UUID): ... # Encrypt sensitive fields from core.security.encryption import encrypt_field patient.ssn = encrypt_field(ssn_value, tenant_key) ``` ### ❌ DON'T ```python # NEVER expose PHI in responses return {"patient_name": patient.full_name, "ssn": patient.ssn} # BAD! # NEVER skip audit logging for PHI async def view_patient(patient_id: UUID): return await db.get(patient_id) # No audit trail! # NEVER hardcode encryption keys AES_KEY = "my-secret-key-123" # USE ENV VARS! ``` ### Enforcement - **Security Headers**: Validated in every response - **Audit Trail**: Cryptographically signed, immutable - **PHI Detection**: `scripts/security/scan_phi.py` --- ## 7. 🎯 MINIMIZE DEPENDENCIES, MAXIMIZE STANDARDS > **Proven libraries only. Clinical standards to the letter. Less code = fewer bugs.** ### YAZ Approved Stack | Category | Approved | Forbidden | |----------|----------|-----------| | **Web Framework** | FastAPI | Flask, Django | | **ORM** | SQLModel, SQLAlchemy | Peewee, Tortoise | | **Database** | PostgreSQL 16+ | MySQL, MongoDB | | **Cache** | Redis 7+ | Memcached | | **Validation** | Pydantic V2 | Marshmallow, Cerberus | | **Async** | asyncio, HTTPX | requests (sync) | | **Frontend** | HTMX, Alpine.js | React, Vue, Angular | ### Clinical Standards (MANDATORY) | Domain | Standard | Reference | |--------|----------|-----------| | Laboratory | CLSI C24-A4, CAP, ISO 15189 | Westgard rules | | Surgical | ASA Physical Status, WHO SSC 2.0 | Risk classification | | Clinical | HL7 FHIR R4, SNOMED CT, LOINC | Interoperability | | Pharmacy | FDA, USP, ISMP | Drug safety | | Education | ACGME Milestones, EPA | Training | | Compliance | HIPAA, FDA 21 CFR Part 11 | Regulatory | ### βœ… DO ```python # Use proven patterns from base classes from core.services.base_service import BaseService class SurgeryService(BaseService): """ Inherits: logging, caching, tracing, error handling Future platform upgrades = automatic for all services """ pass # Use config-driven features FEATURE_FLAGS = { "news2_calculator": True, "ai_recommendations": tenant.subscription == "enterprise" } ``` ### ❌ DON'T ```python # NEVER add experimental dependencies from some_unmaintained_package import magic # FORBIDDEN! # NEVER reinvent the wheel class MyCustomORM: # Use SQLModel! pass # NEVER diverge from clinical standards def calculate_asa_score(): return random.choice(["I", "II", "III"]) # Must follow ASA criteria! ``` ### Enforcement - **Dependency Audit**: `pip-audit` in CI - **Import Validation**: Only approved packages - **Standards Compliance**: Clinical algorithm review required --- ## 8. πŸ—οΈ FOUR PILLARS SERVICE PATTERNS (v5.3.0) > **Domain-agnostic services that form the backbone of all domain operations.** ### Service Compliance Matrix | Service | DB Schema | Performance Target | Testing Requirement | |---------|-----------|-------------------|---------------------| | **CHECKLIST** | `checklist.*` | <50ms p95 | Template/response validation | | **JOURNAL** | `journal.*` | <100ms p95 | Hash chain verification | | **MONITOR** | `monitor.*` | <30ms p95 | Threshold evaluation tests | | **PROTOCOL** | `protocol.*` | <200ms p95 | State machine integration | ### βœ… DO ```python # Use schema-driven configuration (Checklist) checklist_template = { "name": "WHO Surgical Safety Checklist", "version": "2.0.0", "domain": "surgical_care", "items": [...] # Config, not code } # Append-only with hash chain (Journal) entry = JournalEntry( content=content, prev_hash=previous_entry.hash, # Integrity chain signature=sign(content, user_key) # Audit trail ) # Event-driven state transitions (Protocol) protocol.raise_event(StateTransitionEvent( from_state="pre_op", to_state="timeout", guard_passed=True )) ``` ### ❌ DON'T ```python # NEVER hardcode checklist items in code class SurgicalChecklist: items = ["confirm_patient", "site_marked"] # Use templates! # NEVER mutate journal entries entry.content = "modified" # FORBIDDEN - append-only! # NEVER skip guards in protocol transitions protocol.force_transition("completed") # Must pass guards! ``` ### Enforcement - **Schema Validation**: All templates validated at load time - **Hash Verification**: Journal entries verified on read - **Guard Enforcement**: Protocol transitions blocked without guard pass - **Tenant Isolation**: 15 isolation tests per service (60 total) --- ## 9. 🌐 DOMAIN-AGNOSTIC BY DESIGN (v7.0.0) > **Platform code must never assume a single domain. Healthcare is one engine among many.** ### What This Means Every platform primitive (cases, events, protocols, checklists, journals, monitors) must work for ANY domain β€” surgery, logistics, insurance, finance, education, hospitality, manufacturing. ### βœ… DO ```python # Domain-agnostic case model class BaseCase(ABC): case_type: CaseType # Surgical, logistics, financial, etc. subject_id: UUID # Patient, shipment, contract, guest subject_type: str # "patient", "shipment", "policy", "guest" # Engine-specific extensions via composition class SurgicalCase(BaseCase): procedure_code: str # Domain-specific asa_score: int # Domain-specific ``` ### ❌ DON'T ```python # NEVER assume healthcare in platform code class BaseCase: patient_id: UUID # WRONG! Not all cases have patients diagnosis: str # WRONG! Domain-specific # NEVER hardcode domain vocabulary in core def get_risk_level(patient): # WRONG! Risk calculation belongs in engine, not platform pass ``` ### Enforcement - **Domain Audit**: `scripts/validation/check_domain_agnostic.py` - **Engine Interface**: All engines implement `DomainEngine` ABC - **Vocabulary Check**: No domain-specific terms in `/src/core/` (except enums) --- ## 10. 🧬 TRACES IS THE BACKBONE (v8.0.0) > **Every case flows through TRACES's Universal Case Model. Every engine creates cases via TRACES. No exceptions.** ### What This Means TRACES is the universal case tracking backbone. It provides the 9-facet Universal Case Model (Context, Constants, Variables, Predicted, Targeted, Real Life, Findings, Blockers, Readiness) that every domain engine uses. ### βœ… DO ```python # Create cases through TRACES via the engine's case service case = await traces_service.create_case( tenant_id=tenant_id, engine_id=engine.slug, context={"subject": {"name": "Case Subject"}, "reason": "Elective procedure"}, targeted_value={"plan": "Complete by day 2", "metrics": {"target_time": 60}}, ) # Use UCM facets for outcome analysis gap = case.real_life_value["operative_time"] - case.predicted_value["operative_time"] ``` ### ❌ DON'T ```python # NEVER create cases outside TRACES class SurgicalCase(SQLModel, table=True): # WRONG! Use TrackerCase __tablename__ = "surgical_cases" # Don't create separate case tables # NEVER skip the Universal Case Model case.domain_data = {"everything": "in one blob"} # Use UCM facets instead ``` ### Enforcement - **UCM Compliance**: All engines must populate UCM facets, not just `domain_data` - **Case Router**: `CaseRouter` dispatches case creation to correct engine via TRACES - **Documentation**: See [UNIVERSAL_CASE_MODEL.md](./architecture/UNIVERSAL_CASE_MODEL.md) --- ## 11. πŸ”„ WRAP FIRST, EXTEND SECOND, MIGRATE THIRD (v8.0.0) > **Never big-bang rewrite. Wrap existing code, extend with new interfaces, migrate gradually.** ### What This Means When evolving the platform: 1. **WRAP**: Create adapters around existing code β€” old behavior unchanged 2. **EXTEND**: Add new interfaces (V2 APIs, new fields) alongside old ones 3. **MIGRATE**: Gradually move consumers to new interface β€” never force, never rush ### βœ… DO ```python # WRAP β€” Adapter pattern for backward compatibility class CaseAdapter: @staticmethod def to_ucm_context(case: TrackerCase) -> Dict: if case.context: # New field populated return case.context return {"subject": {"name": case.subject_name}} # Synthesize from old # EXTEND β€” V2 alongside V1 @router.post("/api/v1/cases/") # KEEP FOREVER async def create_case_v1(data: CaseCreate): ... @router.post("/api/v2/cases/") # NEW β€” uses UCM natively async def create_case_v2(data: CaseCreateV2): ... ``` ### ❌ DON'T ```python # NEVER remove old API endpoints # /api/v1/cases/ must work forever # NEVER rename database columns ALTER TABLE traces.cases RENAME COLUMN subject_name TO ... # FORBIDDEN # NEVER make existing nullable columns required ALTER TABLE traces.cases ALTER COLUMN notes SET NOT NULL; # FORBIDDEN ``` ### Enforcement - **Migration Reviews**: All Alembic migrations must be ADD-only (no DROP, no RENAME) - **API Versioning**: V1 endpoints never removed, only deprecated - **Backward Compat Tests**: Every migration must pass existing test suite unchanged --- ## Quick Reference Card ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ YAZ CODER COMMANDMENTS (v8.4.6) β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1. ZERO CORE CHANGES β†’ Config/tenant settings only β”‚ β”‚ 2. PERFORMANCE FIRST β†’ <200ms p95, 94.7% cache hit β”‚ β”‚ 3. TENANT ISOLATION β†’ tenant_id filter on EVERY query β”‚ β”‚ 4. TYPE SAFETY + TESTS β†’ 100% hints, 85%+ coverage β”‚ β”‚ 5. OBSERVABILITY β†’ Structured logs, traces, metrics β”‚ β”‚ 6. HIPAA COMPLIANCE β†’ Encrypt, audit, never log PHI β”‚ β”‚ 7. MINIMAL DEPENDENCIES β†’ Proven stack, clinical standards β”‚ β”‚ 8. FOUR PILLARS PATTERNS β†’ Schema-driven, hash-chain, guards β”‚ β”‚ 9. DOMAIN-AGNOSTIC β†’ Platform never assumes one domain β”‚ β”‚ 10. TRACES IS BACKBONE β†’ Every case via Universal Case Modelβ”‚ β”‚ 11. WRAP FIRST β†’ Never rewrite, always extend β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ VIOLATION = BUILD FAILURE = NO MERGE = NO DEPLOY ``` --- ## Enforcement Pipeline ### Pre-Commit Hooks ```bash # .pre-commit-config.yaml - mypy src/ # Type checking - black src/ tests/ # Formatting - isort src/ tests/ # Import sorting - bandit -r src/ # Security scan ``` ### CI/CD Gates ```yaml # Every PR must pass: - tenant_isolation_tests # 15 isolation tests - coverage_check # β‰₯85% coverage - performance_baseline # p95 <200ms - security_scan # Zero critical vulnerabilities - dependency_audit # No vulnerable packages ``` ### Monitoring Alerts ```yaml # Production alerts (config/observability/prometheus/alert-rules.yml): - api_latency_high # p95 >200ms for 5 minutes - error_rate_elevated # >1% errors for 2 minutes - tenant_isolation_breach # ANY cross-tenant access - phi_access_anomaly # 3x normal PHI access rate ``` --- ## Related Documentation | Document | Purpose | |----------|---------| | [PRACTICES.md](./PRACTICES.md) | Complete best practices guide | | [DDD_STANDARDS.md](./architecture/DDD_STANDARDS.md) | Domain-driven design patterns | | [ACCESS_SECURITY.md](./architecture/ACCESS_SECURITY.md) | Security & RBAC details | | [UNIVERSAL_CASE_MODEL.md](./architecture/UNIVERSAL_CASE_MODEL.md) | UCM specification | | [DOMAIN_ENGINES.md](./architecture/DOMAIN_ENGINES.md) | Engine architecture | | [copilot-instructions.md](../.github/copilot-instructions.md) | AI coding assistant config | --- **Remember**: Every line of code touches professional operations. Speed saves lives. Security protects trust. Quality prevents harm. **Violation of these commandments is not a code review commentβ€”it's a build failure.**