# 🧬 Sirona AI — Technical Specification & Clinical Architecture Blueprint

This document details the clinical intelligence, database synchronization, safety engineering, and offline caching mechanics of the **Sirona AI Triage System**.

---

## 1. Product Vision & Global Health Mandate

Sirona AI is designed to serve as a **high-fidelity primary triage, symptom analysis, and wellness reference assistant**. It targets the massive global healthcare access gap, particularly in underserved regions (such as rural areas in Sub-Saharan Africa, South Asia, and remote parts of Latin America) where clinical resources are scarce and physical doctor visits may be delayed by days or weeks.

```
                    ┌────────────────────────────────┐
                    │      User Inputs Symptoms       │
                    │   (Text, Speech, Photo, Map)   │
                    └───────────────┬────────────────┘
                                    ▼
                    ┌────────────────────────────────┐
                    │    Semantic Safety Filters     │
                    │     (Category A, B, and C)     │
                    └───────────────┬────────────────┘
                                    ├────────────────────────┐
                                    ▼ (Pass)                 ▼ (Fail)
                    ┌────────────────────────────────┐ ┌──────────────────┐
                    │   Injected Medical Context     │ │  Safety Overrides│
                    │  (PubMed, NIH, WHO, FDA, etc.)  │ │  & Emergency Lock│
                    └───────────────┬────────────────┘ └──────────────────┘
                                    ▼
                    ┌────────────────────────────────┐
                    │   Low-Temp Inference Pipeline  │
                    │   (Groq Llama-4 Scout, T=0.15) │
                    └───────────────┬────────────────┘
                                    ▼
                    ┌────────────────────────────────┐
                    │   Structured Output Validator  │
                    │      (Differential Triage)     │
                    └───────────────┬────────────────┘
                                    ▼
                    ┌────────────────────────────────┐
                    │    Urgency Gates & Lockdown    │
                    │    (Score 0-100 Classification)│
                    └───────────────┬────────────────┘
                                    ├────────────────────────┐
                         ▼ (Score < 60)              ▼ (Score >= 60)
            ┌──────────────────────────────┐  ┌──────────────────────────────┐
            │  Detailed Clinical Analysis  │  │  Emergency Safety Protocol   │
            │  • Top 3 Differential (DDx)  │  │  • Strip Drug Protocols      │
            │  • Pathophysiology Summary   │  │  • Lock input forms          │
            │  • Therapeutic Protocol      │  │  • Doctor Referral Banner    │
            │  • Diagnostic Workup Recommendations│  │  • 30-min Safety Countdown   │
            │  • Red Flags & Warning Signs │  └──────────────────────────────┘
            │  • Print-ready A4 PDF Export │
            └──────────────────────────────┘
```

---

## 2. Mathematical Triage Urgency Score Model

Sirona AI evaluates symptom severity by combining patient metadata, symptom descriptions, and raw vital metrics into a single Medical Urgency Score ($M$) mapped from $0$ to $100$:

$$M = w_1 \cdot S_{base} + w_2 \cdot P_{level} + w_3 \cdot V_{metrics} + S_{override}$$

Where:
1. **$S_{base}$ (Base Symptom Severity - 0 to 40)**: 
   * Determined through semantic processing of the primary text input.
   * Cross-references indicators of vital organ distress, sudden onset, or localized pain clusters.
2. **$P_{level}$ (Pain Scale - 0 to 15)**: 
   * Maps directly to the interactive 1-to-10 severity slider.
   * Evaluated as: $P_{level} = \text{Slider Value} \cdot 1.5$
3. **$V_{metrics}$ (Vital Indicators - 0 to 25)**: 
   * **Heart Rate (HR)**: Points added for severe bradycardia ($< 50$ BPM) or extreme tachycardia ($> 110$ BPM).
   * **Blood Oxygen ($SpO_2$)**: Points added based on hypoxemia:
     * $SpO_2 \ge 95\%$: $0$ points
     * $90\% \le SpO_2 \le 94\%$: $+15$ points
     * $SpO_2 < 90\%$: $+25$ points (Critical Hypoxia signature)
4. **$S_{override}$ (Emergency Override - $+50$ to $+100$)**:
   * Instantly engaged if visual markers (e.g. deep cyanosis) or critical keywords (e.g. crushing chest pain radiating to left arm) are flagged. This forces $M \ge 75$.

### Urgency Classifications:
* **Routine Care ($M < 50$)**: Mild, self-limiting symptoms. Detailed AI-assisted guidance, home remedy summaries, and follow-up consultation chat enabled.
* **Moderate Monitoring ($50 \le M < 60$)**: Potential for escalation. Requires careful observations; home care protocols are accompanied by warning markers.
* **Urgent Care Referral ($60 \le M < 75$)**: Acute symptoms. Detailed drug protocols are stripped, input forms are locked, and Zocdoc referral links are rendered.
* **Emergency Override ($M \ge 75$)**: Immediate life-threatening signature. High-contrast danger screen overrides the interface, and standard forms are locked.

---

## 3. Injected Medical Registry Datasets

During execution, Sirona AI's query constructor retrieves context from **10 global databases** to ground the inference, preventing medical hallucinations:

| Database Registry | Core Data Extracted & Purpose | Integration Method |
| :--- | :--- | :--- |
| **PubMed** | Clinical abstract metadata to match symptom clusters with historical case files. | Local semantic search mapping |
| **OpenFDA** | Adverse drug event lists and recall alerts to cross-reference with current user medications. | Adverse events payload query |
| **WHO Guidelines** | Global outbreak data, travel alerts, and endemic disease sheets. | Local registry mapping |
| **CDC Surveillance** | Infection timelines, vector warnings, and public prevention protocols. | Prevention matching |
| **NIH Guidelines** | Clinical practice guidelines for working differential diagnoses. | Practice benchmarking |
| **ICD-11** | Standardized international classification of diseases and morbidity codes. | Code mapping injection |
| **SNOMED CT** | Comprehensive clinical terminology mappings to match concepts. | Terminology matching |
| **RxNorm** | Standardized nomenclature for clinical drugs to identify generic ingredients. | Drug CUI mapping |
| **DailyMed** | Official FDA drug labeling data containing warnings, contraindications, and dosages. | FDA labeling query |
| **MedlinePlus** | Plain-language patient summaries to cross-reference consumer medical tips. | Consumer guide indexing |

---

## 4. Multi-Tier Safety Shield & Verification

Sirona AI implements active security walls at both the interface level and the API logic level.

### 4.1 Input Safety Filters (Pre-API Stage)
All user inputs are parsed inside the client-side controller before transmission:
* **Category A (Life Threat & Crisis)**: Checks for self-harm keywords (`suicide`, `end my life`, `kill myself`, `overdose`) and physical emergencies (`massive crushing chest pain`, `severe arterial bleeding`).
  * *Action:* Blocks the submit button, clears local states, overrides the page with the `#emergency-danger-overlay`, and provides direct dials to regional suicide/crisis helplines (e.g., **988**, SMS **741741**, **911**, **112**).
* **Category B (Scope Restriction)**: Checks for coding keywords (`python`, `javascript`), general knowledge, weather, or sports queries.
  * *Action:* Blocks API transmission and renders a scoped helper warning card informing the user Sirona AI is restricted to healthcare triage.
* **Category C (Vague Input)**: Checks for single-word queries without clinical value (`pain`, `help`, `sick`).
  * *Action:* Prompts the user with structured advice explaining how to describe symptoms (duration, location, pain scale).

### 4.2 API Logic Protections (Inference Stage)
* **Low Temperature Settings (`0.15`)**: Inference is run at a minimal temperature to suppress creative phrasing, forcing deterministic, clinical database-compliant outputs.
* **Strict JSON Formatting Constraints**: The LLM is forced to respond in a structured JSON schema, which is parsed programmatically. If the parsing fails or keys are missing, the system catches the exception and falls back to safe offline routing.

### 4.3 Human-in-the-Loop (HITL) Protocol
Sirona AI terms explicitly define that it is a clinical decision support reference tool. It mandates that no triage report is clinical ground truth:
* All generated differential suggestions, SNOMED concept maps, and ICD-11 codes are labeled as "preliminary reference metrics."
* The final review and clinical directive must be validated by a licensed physician or human triage nurse (Human-in-the-Loop validation).

---

## 5. Offline-First Synchronization & PWA Architecture

To handle connections in remote regions, Sirona AI leverages a robust offline-first service worker (`sw.js`):

```
                     [ User Browser Cache ]
                                │
              ┌─────────────────┴─────────────────┐
              ▼ (Online)                          ▼ (Offline)
     [ Sync with Groq/Firebase ]         [ Local Offline Engine ]
              │                                   │
              │                                   ├─► Match Symptoms locally
              │                                   ├─► Map to emergency list
              ▼                                   ▼
    [ Sync Logs to Cloud ]               [ Write to LocalStorage ]
```

### 5.1 Local Fallback Triage Dictionary
If the network is unreachable, `report.js` calls `getFallbackGuidance(data)`. This parses the symptom logs locally against a compressed matching dictionary:
* Matches common emergency symptom clusters (like intense chest pressure, severe respiratory distress) to trigger localized alerts.
* Uses the input's severity slider value to force high urgency score states locally if the user reports severe pain.

### 5.2 Storage Namespacing
To prevent collision with guest sessions and protect user credentials:
* `sirona_user`: Stores the authenticated Firebase User ID and display profile.
* `sirona_history`: Local array of past check-ins, consultation notes, and urgency ratings, ensuring immediate access to past medical logs without needing cloud connectivity.

---

## 6. Regulatory & Legal Shield Compliance

Sirona AI enforces clear boundaries to ensure compliance with medical software standards:
* **Legal Page Integration (`legal/legal.html`)**: Consolidates Terms, Privacy Policy, and FAQ in a single tabbed center.
* **Absolute Legal Warnings**: All page footers, diagnostic summary blocks, and A4 PDF export cards feature high-visibility disclaimers:
  > **Clinical Disclaimer:** Sirona AI provides preliminary urgency scoring and database reference mapping for clinical informational support only. It does not construct a final diagnosis or substitute for professional emergency services or in-person physician evaluation. **Avoid: making legal or medical decisions.**
