# Project: HAD Digital MVP Skeleton

## Architecture

### System Architecture Overview
The HAD Digital MVP (Hospitalisation à Domicile Oncology Care Platform) is designed as a zero-dependency, local-first standalone Windows application.

```
+-------------------------------------------------------------------------+
|                  HAD Digital MVP - Standalone Architecture              |
+-------------------------------------------------------------------------+
| [Client Browser] (Chrome / Edge / Firefox)                              |
|        ^                                                                |
|        | HTTP / REST (127.0.0.1:8080) - HttpOnly Session Cookies       |
|        v                                                                |
| [ThreadingHTTPServer] (Pure Python Stdlib, zero external dependencies)  |
|    ├── Static Asset Handler (serves bundled HTML5 / CSS3 / Vanilla JS)  |
|    ├── REST API Router (19 endpoints: auth, reports, timeline, etc.)   |
|    └── Security Headers (CSP, X-Content-Type-Options, X-Frame-Options)  |
|        │                                                                |
|        ├──> [CTCAE Grading Engine] <── [ctcae_rules.json] (Bundled)     |
|        ├──> [Alert Engine] (Routine / Urgent / Emergency routing)       |
|        ├──> [Audit Logger] (Immutable append-only audit trail)          |
|        └──> [User Store & Auth] (scrypt password hashing + salt)        |
|                 │                                                       |
|                 v                                                       |
|        [Database Manager] (SQLite with WAL mode, foreign keys, thread-local)
|                 │                                                       |
|                 v                                                       |
|        [Persistent Data Storage] (Outside sys._MEIPASS)                 |
|        ├── data/had.db (Users, Patients, Reports, Grades, Timeline)     |
|        └── logs/audit.log                                               |
+-------------------------------------------------------------------------+
```

### Storage Decoupling Architecture
To prevent the PyInstaller `_MEIPASS` ephemeral data-loss bug:
- `get_bundle_dir()`: Resolves to `sys._MEIPASS` when frozen (or project root when in dev mode) for read-only bundled assets (`static/`, `data/ctcae_rules.json`, `guidance/guidance.json`).
- `get_data_dir()`: Resolves to persistent storage outside `sys._MEIPASS`:
  - Portable mode: `Path(sys.executable).parent / "data"` (if writable).
  - Installed fallback: `%LOCALAPPDATA%\HAD Digital\data`.
  - Configurable override: `HAD_DB_PATH` environment variable.

---

## Feature Inventory

| # | Feature | Description | Milestone | Source |
|---|---------|-------------|-----------|--------|
| 1 | User Login (`/api/login`) | Authenticates credentials using scrypt; returns `ok: true`, user object, and sets `HAD_SESSION` cookie | M1 | ORIGINAL_REQUEST §R2 |
| 2 | User Logout (`/api/logout`) | Clears active session and expires session cookie | M1 | Survey |
| 3 | Session Check (`/api/whoami`) | Returns active session role/profile or `{authenticated: false}` | M1 | Survey |
| 4 | Account Lockout | Locks account for 30 minutes after 5 consecutive failed login attempts | M1 | Survey |
| 5 | List Patients (`/api/patients`) | Retrieves patient roster filtered by caller role | M1 | Survey |
| 6 | Patient Detail (`/api/patients/{id}`) | Retrieves patient demographics, active regimen, recent grades, alerts | M1 | Survey |
| 7 | Patient Self-Report (`/api/reports`) | Ingests toxicity symptoms, auto-grades via CTCAE, logs audit & timeline, routes alerts | M1 | ORIGINAL_REQUEST §R2 |
| 8 | Clinician Observation Entry | Clinicians submit home-visit clinical findings and vital signs | M1 | Survey |
| 9 | List Reports (`/api/reports`) | Returns historical toxicity reports for a specified patient | M1 | ORIGINAL_REQUEST §R2 |
| 10 | CTCAE Automated Grading Engine | Evaluates symptom inputs against CTCAE v5.0 thresholds; assigns grades 1-5 | M1 | Survey |
| 11 | List Grades (`/api/grades`) | Retrieves graded toxicity assessments for a patient | M1 | Survey |
| 12 | List Symptoms (`/api/symptoms`) | Enumerates configured CTCAE symptom terms and categories | M1 | Survey |
| 13 | Confirm Provisional Grade | Oncologist confirms or overrides provisional automated grade | M1 | Survey |
| 14 | Tiered Alert Routing | Routes grades to Routine (timeline), Urgent (HAD nurse), or Emergency (oncologist) | M1 | Survey |
| 15 | List Alerts (`/api/alerts`) | Retrieves alerts filtered by patient, status, or role | M1 | Survey |
| 16 | Acknowledge Alert (`/api/alerts/{id}/ack`) | Clinician marks an alert acknowledged with timestamp | M1 | Survey |
| 17 | Care Coordination Timeline (`/api/timeline`) | Unified chronological stream of reports, grades, alerts, and care notes | M1 | ORIGINAL_REQUEST §R2 |
| 18 | Treatment Plan View (`/api/treatment-plan`) | Displays protocol name, regimen, cycles, drugs, supportive care | M1 | Survey |
| 19 | Send Message (`/api/messages`) | Secure direct or role-directed care team messaging | M1 | Survey |
| 20 | List Messages (`/api/messages`) | Lists messages where caller is sender, recipient, or role member | M1 | Survey |
| 21 | Toxicity Summary Export (`/api/export/summary`) | Compiles structured JSON summary with patient metadata and grade history | M1 | Survey |
| 22 | Patient Guidance (`/api/guidance`) | Delivers actionable French guidance per symptom and grade | M1 | Survey |
| 23 | Immutable Audit Log (`/api/audit-log`) | Records timestamped actions, resources, IPs; admin access | M1 | Survey |
| 24 | Pluggable AI Assistant (`/api/chat`) | Natural language assistant supporting stub (offline) and glm (online) | M1 | Survey |
| 25 | Demo Data Auto-Seeder | Seeds realistic patients, treatment plans, users across all 8 roles on first run | M1 | Survey |
| 26 | Persistent SQLite Storage Engine | Decouples read-only bundle from persistent writable SQLite DB with WAL mode | M1 | ORIGINAL_REQUEST §R1 |
| 27 | Responsive UI Shell & Navigation | Mobile-first SPA shell, vanilla JS router, role-customized nav bar, modal overlays | M2 | ORIGINAL_REQUEST §R3 |
| 28 | UI Login & Auth View | Login form handling `ok: true`, error display, demo credential helper buttons | M2 | ORIGINAL_REQUEST §R2, §R3 |
| 29 | Patient Toxicity Reporting Form | Interactive symptom questionnaire supporting multiple symptom domains and submission | M2 | ORIGINAL_REQUEST §R2, §R3 |
| 30 | Clinician Care Timeline View | Interactive chronological stream displaying reports, grades, alerts, and filters | M2 | ORIGINAL_REQUEST §R2, §R3 |
| 31 | PyInstaller Single-File Packaging | Single-file Windows `.exe` bundle embedding Python runtime, server, and static assets | M3 | ORIGINAL_REQUEST §R1 |
| 32 | Automated Build Script (`04_Build/build_exe.py`) | Automation script executing PyInstaller build, verifying zero external runtime dependencies | M3 | ORIGINAL_REQUEST §Criteria |
| 33 | Programmatic Verification Script (`05_Test/verify_mvp.py`) | CLI verification harness testing launch, health ping, auth, submission, persistence, and timeline | M4 | ORIGINAL_REQUEST §Criteria |
| 34 | E2E Test Suite Tiers 1-4 | Opaque-box test suite covering feature coverage, boundary values, pairwise, and clinical workflows | Test Track | Test Methodology |
| 35 | Tier 5 Adversarial Hardening | White-box stress, concurrency, brute-force lockout, and security hardening tests | M4 | Quality Standard |

---

## Milestones

| # | Name | Scope | Dependencies | Status |
|---|------|-------|-------------|--------|
| Test Track | E2E Testing Suite Track | Design and implement opaque-box E2E test suite (Tiers 1-4) in `05_Test/` and publish `TEST_READY.md` | none | DONE |
| M1 | Core Server & Storage Engine | Resolve `_MEIPASS` data-loss trap, fix API contract inconsistencies (login `ok: true`, report payload flexibility), ensure persistent SQLite WAL database, auth, and REST endpoints | none | DONE |
| M2 | Responsive Local Frontend | Fix UI login handler, update demo credentials display, verify responsive toxicity questionnaire and care timeline view in `MVP/static/` | M1 | DONE |
| M3 | Packaging & Build Automation | Implement `04_Build/build_exe.py` and `HAD Digital.spec` for single-file Windows `.exe` packaging with bloat exclusions | M1, M2 | DONE |
| M4 | E2E Verification & Hardening | Phase 1: Verify 100% pass on E2E test suite (Tiers 1-4) against both Python server and standalone `.exe` using `05_Test/verify_mvp.py`. Phase 2: Tier 5 Adversarial Coverage Hardening | Test Track, M3 | DONE (Gate PASS) |

---

## Interface Contracts

### Client Frontend ↔ Backend REST API (`/api`)
- **Authentication**: `POST /api/login`
  - Request: `{"username": "...", "password": "..."}`
  - Response (200): `{"ok": true, "message": "Login successful", "user": {"id": 1, "username": "...", "role": "...", "display_name": "..."}}`
  - Cookie: `Set-Cookie: HAD_SESSION=<uuid>; Path=/; HttpOnly; SameSite=Lax`
- **Session Check**: `GET /api/whoami`
  - Response (200): `{"authenticated": true, "user": {...}}` or (401): `{"authenticated": false}`
- **Toxicity Report Submission**: `POST /api/reports`
  - Request format A (Flat): `{"patient_id": 1, "symptom_id": "nausea", "symptom_category": "gastrointestinal", "severity_score": 2, "notes": "..."}`
  - Request format B (Questionnaire Map): `{"patient_id": 1, "symptoms": {"nausea": 2, "fatigue": 1}, "notes": "..."}`
  - Response (201): `{"ok": true, "message": "Report submitted", "report_id": 8, "grading": {...}, "alert": {...}}`
- **Care Timeline**: `GET /api/timeline?patient_id=<id>`
  - Response (200): `{"events": [{"id": 1, "patient_id": 1, "event_type": "toxicity_report", "event_date": "...", "title": "...", "description": "...", "severity": "...", "metadata": {...}}, ...]}`

### Server Runtime ↔ Storage Engine
- `get_bundle_dir()`: Returns root directory of read-only assets (`static/`, `data/ctcae_rules.json`, `guidance/guidance.json`).
- `get_data_dir()`: Returns writable directory for `had.db` and logs. If `had.db` is missing, triggers idempotent `seed_demo_data()`.

---

## Code Layout

```
c:\AI Projects\Kais Project\
├── 00_Governance/                 # Governance & Project Status
├── 01_System/                     # System specifications & architecture docs
├── 02_Requirements/               # Functional requirements & CTCAE rules
├── 03_Architecture/               # Architecture documents & API contracts
├── 04_Build/                      # Automated build scripts & PyInstaller spec
│   ├── build_exe.py              # Automated build script packaging single-file .exe
│   └── HAD Digital.spec          # Single-file PyInstaller specification
├── 05_Test/                       # Comprehensive E2E test suite & verification harness
│   ├── verify_mvp.py             # Standalone programmatic verification script
│   ├── test_e2e_tier1.py         # Tier 1: Feature coverage tests
│   ├── test_e2e_tier2.py         # Tier 2: Boundary & corner cases
│   ├── test_e2e_tier3.py         # Tier 3: Cross-feature combination tests
│   ├── test_e2e_tier4.py         # Tier 4: Clinical workflow scenarios
│   └── test_e2e_tier5_adversarial.py # Tier 5: Adversarial hardening & stress tests
├── MVP/                           # Application source code
│   ├── app.py                    # ThreadingHTTPServer & REST API routing
│   ├── config_manager.py         # Storage path decoupling & configuration
│   ├── database.py               # SQLite WAL thread-local database manager
│   ├── user_store.py             # Scrypt authentication & session management
│   ├── ctcae_engine.py           # CTCAE v5.0 rule evaluation
│   ├── alert_engine.py           # Triage & alert routing
│   ├── audit_logger.py           # Immutable audit logging
│   ├── seed_demo.py              # Demo patient & user data seeder
│   ├── static/                   # Frontend assets
│   │   ├── index.html            # Single Page Application HTML shell
│   │   ├── app.css               # Responsive design & component styling
│   │   └── app.js                # Frontend routing, auth, form & timeline logic
│   ├── data/                     # ctcae_rules.json
│   └── guidance/                 # guidance.json
├── dist/                          # Output directory for compiled standalone .exe
│   └── HAD Digital.exe           # Single-file standalone Windows executable (9.78 MB)
└── PROJECT.md                     # Living project scope & architecture index
```
