Spaces:
Paused

yaz / docs /COMMANDMENTS.md
anaselamr's picture
docs(book): surgical thesis — Digital Instruments, Dr Anass El Amrani
63d2cfa
|
Raw History Blame Contribute Delete
25 kB

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

# 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

# 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)

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

# 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

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

# 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

# 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

# .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

# 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

# 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 Complete best practices guide
DDD_STANDARDS.md Domain-driven design patterns
ACCESS_SECURITY.md Security & RBAC details
UNIVERSAL_CASE_MODEL.md UCM specification
DOMAIN_ENGINES.md Engine architecture
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.