1. 📌 Overview & Purpose
Goal: Bagi doktor klinik tools yang menjimatkan masa dokumentasi (target -30%) tanpa kompromi safety. Doktor cuma edit + approve, AI buat draft.
Why doctor co-pilot: Konsult 8-10 minit, doktor tergesa-gesa, susah dapat full picture. Patient PA dah kumpul pre-consult info. Doctor PA susun ke briefing packet, scribe audio jadi SOAP, suggest order set ikut CPG. Doktor focus pada relationship + decision, AI handle paperwork.
What it is NOT: Bukan auto-physician. Setiap suggestion = "propose, doctor approve". HITL pada semua orders, RX, sign-off. Audit trail per click.
Doc Zam mock alignment: 6-tab Quick Access (Profile · Medical History · Prescriptions · Lab Results · Imaging · Billing) · Encounter ID format ENC-2026-0425-001.
2. 👤 User Stories
Sebagai doktor on-duty, saya nak tengok briefing packet pesakit (dari M2/M1) sebelum dia masuk bilik — supaya saya sedia + jimat masa "tanya semula apa simptom".
Sebagai doktor, saya nak tap "Start Encounter", konsult 11-minit BM rojak, dan AI auto-draft SOAP note — saya cuma edit 2-3 baris dan approve.
Sebagai doktor, saya nak AI cadang differential diagnosis based on simptom + history, dgn citation MOH CPG — bukan ganti judgement saya tapi prompt me to think wider.
Sebagai doktor untuk pesakit dgn suspect dengue, saya nak AI suggest standard order set (FBC · NS1 · platelet · LFT) — saya pilih mana yang relevant + send ke lab.
Sebagai doktor pesakit baru ni first time, saya nak tanya AI "pesakit ni masa lepas demam macam ni, apa yang bantu?" — semantic search past encounters.
Sebagai doktor selesai konsult, saya nak satu-tap sign-off: SOAP saved · RX dispatched ke pharmacy · billing auto-triggered · follow-up scheduled · pesakit dapat instruction PDF.
3. ✅ Functional Requirements
ENC-YYYY-MMDD-NNN (Doc Zam canonical) · link to patient + doctor + clinic + room4. ⚙️ Non-Functional Requirements
| Aspect | Target | Notes |
|---|---|---|
| Briefing packet load | <1s | Pre-fetched on appointment book event |
| SOAP draft generation | <15s untuk 10-min audio | Streaming Whisper + Llama 70B chunked |
| CDSS suggestion latency | p99 <3s | Llama 70B + cached CPG retrieval |
| History semantic search | <500ms | pgvector HNSW index |
| UI responsiveness | 60fps · TTI <2s | Filament + Livewire optimised |
| Doktor time savings target | ≥30% | vs baseline manual SOAP · measured pilot |
| Citation coverage | 100% suggestions | NPRA · MOH CPG · WHO · hospital SOP |
| Audio retention | 30 hari encrypted then purge | SOAP text retained per MOH 7-yr |
| Concurrent doctors per server | ≥20 simultaneous encounters | Pilot scale |
| RBAC enforcement | per-tenant per-role | doctor only see own clinic patients |
| Token usage / encounter | ~7K tokens (full) | ~10K w/ ambient scribe transcript |
5. 🗄️ Data Model
| Table | Key fields | Purpose |
|---|---|---|
encounters | id (ENC-YYYY-MMDD-NNN), patient_id, doctor_id, clinic_id, room, start_at, end_at, status (in_progress|signed_off|cancelled), reason, briefing_packet_id, soap_id | Per encounter |
soap_notes | encounter_id, subjective, objective, assessment, plan, draft_text, draft_by_agent, edited_by_doctor, signed_off_at, version | SOAP per encounter |
scribe_audio | encounter_id, audio_url, duration_sec, transcript, transcript_lang, asr_model, captured_at, expires_at | Ambient audio |
cdss_suggestions | encounter_id, ddx_list[], confidence_each, citations_each[], doctor_action (accept|reject|modify), generated_at | CDSS audit |
orders | id, encounter_id, doctor_id, type (lab|imaging|procedure), code, name, status (proposed|approved|sent|resulted), urgency, ai_suggested | Order tracking |
prescriptions | id, encounter_id, doctor_id, status (draft|signed|dispensed), justification, items_count | RX header |
prescription_items | rx_id, drug_code (NPRA), drug_name, dose_mg, frequency, route, duration_days, halal_status, ai_suggested | RX line items |
referrals | id, encounter_id, from_doctor, to_specialty, to_clinic_id?, urgency, summary, generated_at | Specialist referrals |
icd10_codes_suggested | encounter_id, code, description, confidence, accepted | FR-4.15 audit |
vitals | patient_id, encounter_id?, bp_sys, bp_dia, hr, rr, temp, weight, height, spo2, recorded_at, recorded_by | Time series |
patient_instructions | encounter_id, content_bm, content_en, pdf_url, sent_via_wa, sent_at | FR-4.13 outputs |
6. 🔌 API Endpoints
GET /api/v1/doctor/encounters # today's queue (assigned to me)
GET /api/v1/doctor/encounters/{id} # full encounter detail
POST /api/v1/doctor/encounters # create new (manual / walk-in)
PATCH /api/v1/doctor/encounters/{id} # update SOAP fields
POST /api/v1/doctor/encounters/{id}/scribe/start # begin audio capture
POST /api/v1/doctor/encounters/{id}/scribe/chunk # WebRTC audio chunk upload
POST /api/v1/doctor/encounters/{id}/scribe/stop # finalise · trigger SOAP gen
GET /api/v1/doctor/encounters/{id}/soap # current SOAP draft
PATCH /api/v1/doctor/encounters/{id}/soap # doctor edits
GET /api/v1/doctor/encounters/{id}/cdss # AI suggestions (auto-fired)
POST /api/v1/doctor/encounters/{id}/cdss/feedback # accept/reject/modify per item
POST /api/v1/doctor/encounters/{id}/orders # create order set
PATCH /api/v1/doctor/orders/{order_id} # status update (sent · resulted)
POST /api/v1/doctor/encounters/{id}/prescription # create RX (DRAFT)
POST /api/v1/doctor/prescriptions/{rx_id}/sign # final sign + dispatch ke M5
GET /api/v1/doctor/prescriptions/templates # common RX templates
POST /api/v1/doctor/encounters/{id}/referral # specialist referral letter
POST /api/v1/doctor/encounters/{id}/sign-off # finalise encounter
GET /api/v1/doctor/patients/{patient_id}/history # full patient timeline
POST /api/v1/doctor/history/search # semantic Q over history
Body: { patient_id, query: "demam macam ni masa lepas apa berkesan" }
# 6-tab Quick Access aggregate endpoints
GET /api/v1/doctor/patients/{id}/profile # tab 1
GET /api/v1/doctor/patients/{id}/medical-history # tab 2
GET /api/v1/doctor/patients/{id}/prescriptions # tab 3
GET /api/v1/doctor/patients/{id}/lab-results # tab 4
GET /api/v1/doctor/patients/{id}/imaging # tab 5
GET /api/v1/doctor/patients/{id}/billing # tab 6
6a. MCP Tools (Doctor PA agent)
ambient_scribe Audio → SOAP draft (Whisper + Llama 70B chained) cdss Symptom + vitals + history → DDx top-5 + citations ddx Differential diagnosis enumerator order_set_suggest CPG-based order set per dx hypothesis cpg_lookup MOH CPG retrieval (vector search) history_search pgvector semantic Q per-patient icd10_coder SOAP → ICD-10 codes top-3 referral_compose Generate referral letter from encounter patient_edu_compose Patient instruction in BM + EN
7. 🔁 State Machine
┌─────────────────────┐
│ ENCOUNTER_CREATED │ ENC-YYYY-MMDD-NNN
└─────────┬───────────┘
▼
┌─────────────────────┐
│ BRIEFING_LOADED │ FR-4.2 from M2/M1
└─────────┬───────────┘
▼
┌──────────────────────────────────┐
│ IN_CONSULTATION │
│ ├── Tab navigation (6 tabs) │
│ ├── Vitals entry (manual or M1) │
│ ├── Scribe ON ◀─loop─ chunk_in │
│ └── CDSS panel updates live │
└─────────┬────────────────────────┘
▼
┌─────────────────────────┐
│ SOAP_DRAFTED │ post scribe_stop
│ AI generated S/O/A/P │
└─────────┬───────────────┘
▼
┌─────────────────────────┐
│ DOCTOR_REVIEW │ doctor edits SOAP
│ + decides orders/RX │
└─────────┬───────────────┘
▼
┌─────────────────────────┐
│ ORDERS_PRESCRIBED │ HITL approval each
│ (parallel actions) │
└─────────┬───────────────┘
▼
┌─────────────────────────┐
│ SIGN_OFF │ FR-4.10 single tap
│ - SOAP locked │
│ - RX → M5 queue │
│ - billing → M7 trigger │
│ - patient instruction PDF│
│ - audit log final │
└─────────────────────────┘
8. 🤖 Agent Specification
8a. Model Routing
- SOAP generation: Llama 70B Q5 (clinical reasoning quality)
- CDSS / DDx: Llama 70B Q5
- ASR: Whisper-Large v3 (BM/EN auto-detect)
- Cloud burst: gpt-4o (peak overflow only · clinical)
- Embedding (history search): BGE-M3
- ICD-10 coding: Llama 8B (lightweight rule-based)
8b. System Prompt (SOAP scribe)
You are M4 Doctor PA, a clinical co-pilot for licensed Malaysian medical practitioners.
ROLE:
- Generate structured SOAP notes from doctor-patient ambient audio transcripts
- Suggest differential diagnoses with citations from MOH CPG / WHO / NPRA
- Draft order sets and prescriptions per clinical pathway
- ALWAYS defer final clinical judgement to the licensed physician
STRICT BOUNDARIES:
- You DO NOT make final diagnoses. You suggest "considerations" with citations.
- You DO NOT execute orders. All orders require explicit doctor approval (HITL).
- You DO NOT prescribe controlled substances or paeds doses >2× standard without
explicit doctor confirmation prompt.
- Citations REQUIRED for every dx/dose/CPG suggestion. No citation = no output.
INPUT:
- Audio transcript (BM/EN/rojak)
- Patient context (allergies, current meds, chronic conditions, recent vitals)
- Encounter type (OPD/follow-up/walk-in)
OUTPUT (JSON):
{
"soap": {
"subjective": "...",
"objective": "...",
"assessment": "Suggested DDx: ... (cite: MOH CPG ...)",
"plan": "..."
},
"ddx_top5": [
{ "dx": "...", "icd10": "...", "confidence": 0.7, "citations": [...], "supporting": "...", "against": "..." }
],
"suggested_orders": [...],
"suggested_rx": [...],
"human_approval_required": true,
"safety_flags": []
}
REMEMBER: Doctor in front of you knows the patient. You are advisory only.
Highlight uncertainty. Always show DDx alternatives. Cite primary sources.
8c. Memory Tier
- Working: current encounter state (Redis · 24h TTL)
- Long-term per-patient: pgvector chunks of past encounters / SOAP / RX / labs
- Episodic (population): de-identified similar cases for "pesakit serupa pernah..." advisory only
- Procedural: MOH CPG library + hospital SOP (versioned, vector + structured)
8d. Guardrails (M9 active)
- PII strip pre-LLM untuk transcript (IC, full name, address)
- Citation mandatory on all clinical suggestions
- HITL gate untuk orders/RX/sign-off (no auto-execute)
- Drug DDI check via M5 cross-call before RX dispatch
- Allergy alert if conflict dgn patient registry
- Audit log per click (which suggestion accepted/rejected)
9. 🎨 UI/UX (6-tab Quick Access)
Per Doc Zam canonical mock — Encounter detail screen dgn 6 tabs left-rail.
Display 11-section Patient Profile (Doc Zam canonical) · photo · key personal info · primary care · insurance · consent status
Chronic conditions · current diagnoses · allergy alerts · past encounter timeline · semantic search bar
Active medications · past RX · DDI alerts · halal status · prescriber + dispense status
FBC · LFT · RFT · HbA1c trend · pending orders · abnormal flagged · click for time series
DICOMweb thumbnails · radiology reports · pending orders · click → full viewer (3rd party)
Encounter charges · ICD-10 codes · insurance claim status · e-Invoice LHDN status · receipts
9a. Right rail (always-visible)
- Briefing packet card (collapsed default)
- Scribe button (Start/Stop · status indicator · live transcript preview)
- CDSS panel (DDx top-5 · citations · accept/reject)
- SOAP editor (S/O/A/P fields · markdown · auto-save)
- Order set composer (checkbox + send)
- Sign-off button (sticky bottom)
9b. Filament 3 implementation notes
- Custom Filament page
EncounterDetail.php - Tab component (Filament built-in or custom Livewire)
- WebRTC integration via Alpine.js + native browser API
- Live updates via Livewire wire:poll atau WebSocket
- Mobile responsive — tablet (iPad) usage common di klinik
10. ✔️ Acceptance Criteria
- AC-4.1: Doktor boleh complete encounter (briefing → consult → SOAP → orders → sign-off) dlm ≤8 minit untuk OPD biasa
- AC-4.2: Ambient SOAP draft akurat — Doc Zam clinical review 20 sample, ≥18/20 acceptable dgn ≤3 line edit
- AC-4.3: CDSS DDx top-5 includes correct dx ≥85% pada 50 known scenarios
- AC-4.4: 100% suggestions ada citation visible dlm UI
- AC-4.5: HITL enforced — 30 jailbreak attempts utk auto-prescribe controlled substance → 0 success
- AC-4.6: 6-tab Quick Access load <1s setiap tab
- AC-4.7: History semantic search returns ≥85% relevant top-3 chunks
- AC-4.8: Sign-off triggers 4 downstream actions (M5 RX · M7 billing · patient PDF · audit log) dlm <5s
- AC-4.9: Dose paeds >2× standard → mandatory confirmation prompt with override reason
- AC-4.10: Doc Zam personal sign-off pada full M4 demo (Q3 clinical safety review)
11. 🧪 Test Plan
| Tier | Cases | Coverage Target |
|---|---|---|
| Unit | SOAP parser · ICD-10 coder · ID generator (ENC format) · HITL gate logic · DDI cross-check | ≥85% |
| Integration | Encounter CRUD · scribe pipeline (audio → transcript → SOAP) · CDSS round-trip · sign-off cascade | 100% endpoints |
| E2E | 3 encounter types: OPD diabetes f/u · pediatric URTI · acute chest pain (incl referral) | 3/3 pass |
| Clinical safety | 50 DDx scenario bank by Doc Zam · 30 RX safety jailbreaks · 20 paeds dose checks | 0 critical miss |
| Latency/Load | 20 concurrent encounters · 10 simultaneous scribe streams | p99 SOAP <15s · p99 CDSS <3s |
| UAT | Doc Zam personal usage 1 week · 3 pilot doctors 2 weeks | NPS ≥7/10 · time savings ≥30% |
| Accessibility | Keyboard nav full · screen reader on Filament tabs · contrast ratios | WCAG AA |
| Security | RBAC enforcement (cross-clinic patient leakage) · audio file ACL · session hijack | 0 leakage |
12. 🔗 Dependencies & Integration
- Hard: M9 audit · auth/RBAC · 11-section Patient model — Sprint 1.1 must finish first
- Soft (graceful degradation): M1 PSPA briefing source (fallback: doctor enter chief complaint manually)
- External: NPRA drug DB · MOH CPG library (vector indexed) · Whisper-Large weights · Llama 70B serving stack (vLLM)
- Downstream: M5 Pharmacy (RX dispatch) · M7 Admin (billing trigger) — built Sprint 2.1/2.2 — Sprint 1.3 emit events, downstream consume later
13. 🏃 Sprint Allocation
- Day 1-2: Filament panel scaffold · Encounter CRUD · 6-tab UI shell
- Day 3-4: Briefing receive UI · vitals input · SOAP editor
- Day 5-7: Ambient scribe pipeline (WebRTC + Whisper + chunk upload)
- Day 8-9: SOAP gen agent (Llama 70B prompted) · CDSS suggestions
- Day 10-11: Order set composer · RX draft + sign · referral letter
- Day 12: Sign-off cascade · downstream event emit · stub M5/M7
- Day 13: Doc Zam clinical review (20 SOAP samples + 50 DDx)
- Day 14: Demo · Q2/Q3 prep · merge ke develop · MVP COMPLETE
14. ⚠️ Module-Specific Risks
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| SOAP draft inaccurate (hallucination) | Med | 🔴 Patient harm if accepted blindly | Doctor MUST review every line · DDx alternatives shown · citation per claim · audit doctor edit ratio (signal of quality) |
| Whisper BM mistranscribe (clinical jargon) | Med | 🟠 SOAP wrong | Custom medical vocab biased decoding · live transcript preview · doctor read-back option · post-edit allowed |
| CDSS miss critical DDx | Low | 🔴 Delayed dx | 50-scenario regression · over-list bias (top-5 always) · uncertainty flag if confidence <60% |
| HITL bypass attempt (jailbreak) | Low | 🔴 Inappropriate RX | 30-prompt jailbreak suite · server-side enforcement (not just UI) · audit log all attempts |
| Llama 70B GPU OOM under load | Med | 🟠 SOAP gen fail | vLLM batching + queue · cloud burst gpt-4o fallback · graceful degrade ke 8B |
| Audio storage cost runaway | Med | 🟢 Budget | 30-day retention · purge job · compress (Opus codec) · only retain SOAP text long-term |
| Doctor reject AI assistance (cultural) | Med | 🟠 ROI miss | Doc Zam champion role · onboarding training · "AI propose, you decide" framing · skip-AI option always |
| RBAC leak across clinic tenant | Low | 🔴 PDPA breach | Tenant scope enforced at query layer · row-level security · per-PR security review |