🧩 Module Spec · M4 DRPA · Doctor PA · MediEco · 26 April 2026
← Modules M4 · DRPA DETAIL · Phase 1 Sprint 1.3 · 8 Jun - 21 Jun 2026

M4 — Doctor Personal Assistant

Co-pilot klinikal untuk doktor: 6-tab Quick Access (Profile · History · Prescriptions · Lab · Imaging · Billing) per Doc Zam canonical mock, ambient SOAP scribe (audio→note), CDSS, order set drafting, semantic patient history retrieval. Doktor sentiasa pegang keputusan akhir.

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

US-4.1 (Doktor · Pre-consult)

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

US-4.2 (Doktor · Ambient scribe)

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.

US-4.3 (Doktor · CDSS)

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.

US-4.4 (Doktor · Order set)

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.

US-4.5 (Doktor · History recall)

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.

US-4.6 (Doktor · Sign-off)

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

MUSTFR-4.1 Encounter create: auto-generate ID format ENC-YYYY-MMDD-NNN (Doc Zam canonical) · link to patient + doctor + clinic + room
MUSTFR-4.2 Briefing receive: consume briefing packet from M2 (atau M1 langsung kalau no M2) · render structured ringkasan
MUSTFR-4.3 6-tab Quick Access UI: Profile · Medical History · Prescriptions · Lab Results · Imaging · Billing — per Doc Zam mock
MUSTFR-4.4 Ambient scribe: WebRTC audio capture · stream to Whisper-Large · live transcript · upon end → SOAP draft via Llama 70B
MUSTFR-4.5 SOAP edit-in-place: doktor boleh edit S/O/A/P fields · live save · markdown preserve
MUSTFR-4.6 CDSS suggestions: based on extracted simptom + history + vitals · output DDx top-5 + citation per item · confidence score
MUSTFR-4.7 Order set composer: AI suggest order set per CDSS hypothesis · doktor pilih checkbox · dispatch ke lab/imaging system
MUSTFR-4.8 e-Prescription: RX generated dgn drug code (NPRA) · send to M5 pharmacy queue · doktor sign + clinical justification
MUSTFR-4.9 Patient history search: tanya AI dlm chat sidebar "pesakit ni..." → pgvector semantic search → return cited past encounters
MUSTFR-4.10 Sign-off workflow: single-tap finalise · SOAP locked · RX sent · billing trigger · patient instruction generate · audit log
MUSTFR-4.11 HITL on all orders: AI cadang ≠ AI execute. Doktor approve eksplisit untuk: orders, RX, controlled drugs, surgery refer, DNR, paeds dose >2× standard
SHOULDFR-4.12 Vitals chart: trend line BP/HR/HbA1c/weight per past 6 months · auto-flag abnormal
SHOULDFR-4.13 Patient instruction PDF: auto-generate dlm BM/EN · dose schedule · red flags · follow-up date · WhatsApp delivery
SHOULDFR-4.14 Cross-clinic referral: generate digital referral letter ke specialist/hospital (M3 routing)
SHOULDFR-4.15 Auto ICD-10 coding: dari SOAP A/P fields · suggest top-3 codes · doktor confirm
MAYFR-4.16 Voice command shortcuts: "Hey MediEco, draft RX paracetamol 500mg PRN" · privacy-aware
MAYFR-4.17 Telemedicine link: deep-link to existing 3rd-party video platform (Zoom · Doxy)

4. ⚙️ Non-Functional Requirements

AspectTargetNotes
Briefing packet load<1sPre-fetched on appointment book event
SOAP draft generation<15s untuk 10-min audioStreaming Whisper + Llama 70B chunked
CDSS suggestion latencyp99 <3sLlama 70B + cached CPG retrieval
History semantic search<500mspgvector HNSW index
UI responsiveness60fps · TTI <2sFilament + Livewire optimised
Doktor time savings target≥30%vs baseline manual SOAP · measured pilot
Citation coverage100% suggestionsNPRA · MOH CPG · WHO · hospital SOP
Audio retention30 hari encrypted then purgeSOAP text retained per MOH 7-yr
Concurrent doctors per server≥20 simultaneous encountersPilot scale
RBAC enforcementper-tenant per-roledoctor only see own clinic patients
Token usage / encounter~7K tokens (full)~10K w/ ambient scribe transcript

5. 🗄️ Data Model

TableKey fieldsPurpose
encountersid (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_idPer encounter
soap_notesencounter_id, subjective, objective, assessment, plan, draft_text, draft_by_agent, edited_by_doctor, signed_off_at, versionSOAP per encounter
scribe_audioencounter_id, audio_url, duration_sec, transcript, transcript_lang, asr_model, captured_at, expires_atAmbient audio
cdss_suggestionsencounter_id, ddx_list[], confidence_each, citations_each[], doctor_action (accept|reject|modify), generated_atCDSS audit
ordersid, encounter_id, doctor_id, type (lab|imaging|procedure), code, name, status (proposed|approved|sent|resulted), urgency, ai_suggestedOrder tracking
prescriptionsid, encounter_id, doctor_id, status (draft|signed|dispensed), justification, items_countRX header
prescription_itemsrx_id, drug_code (NPRA), drug_name, dose_mg, frequency, route, duration_days, halal_status, ai_suggestedRX line items
referralsid, encounter_id, from_doctor, to_specialty, to_clinic_id?, urgency, summary, generated_atSpecialist referrals
icd10_codes_suggestedencounter_id, code, description, confidence, acceptedFR-4.15 audit
vitalspatient_id, encounter_id?, bp_sys, bp_dia, hr, rr, temp, weight, height, spo2, recorded_at, recorded_byTime series
patient_instructionsencounter_id, content_bm, content_en, pdf_url, sent_via_wa, sent_atFR-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.

Tab 1 · 👤 Patient Profile

Display 11-section Patient Profile (Doc Zam canonical) · photo · key personal info · primary care · insurance · consent status

Tab 2 · 📋 Medical History

Chronic conditions · current diagnoses · allergy alerts · past encounter timeline · semantic search bar

Tab 3 · 💊 Prescriptions

Active medications · past RX · DDI alerts · halal status · prescriber + dispense status

Tab 4 · 🧪 Lab Results

FBC · LFT · RFT · HbA1c trend · pending orders · abnormal flagged · click for time series

Tab 5 · 🩻 Imaging

DICOMweb thumbnails · radiology reports · pending orders · click → full viewer (3rd party)

Tab 6 · 💰 Billing

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

TierCasesCoverage Target
UnitSOAP parser · ICD-10 coder · ID generator (ENC format) · HITL gate logic · DDI cross-check≥85%
IntegrationEncounter CRUD · scribe pipeline (audio → transcript → SOAP) · CDSS round-trip · sign-off cascade100% endpoints
E2E3 encounter types: OPD diabetes f/u · pediatric URTI · acute chest pain (incl referral)3/3 pass
Clinical safety50 DDx scenario bank by Doc Zam · 30 RX safety jailbreaks · 20 paeds dose checks0 critical miss
Latency/Load20 concurrent encounters · 10 simultaneous scribe streamsp99 SOAP <15s · p99 CDSS <3s
UATDoc Zam personal usage 1 week · 3 pilot doctors 2 weeksNPS ≥7/10 · time savings ≥30%
AccessibilityKeyboard nav full · screen reader on Filament tabs · contrast ratiosWCAG AA
SecurityRBAC enforcement (cross-clinic patient leakage) · audio file ACL · session hijack0 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

Sprint 1.3 · 8 Jun - 21 Jun 2026 (2 minggu)
  • 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
Capacity: 2 backend (Laravel + Python) · 1 frontend (Filament) · 1 prompt engineer · Doc Zam advisory 4h/week + intensive Day 13

14. ⚠️ Module-Specific Risks

RiskLikelihoodImpactMitigation
SOAP draft inaccurate (hallucination)Med🔴 Patient harm if accepted blindlyDoctor MUST review every line · DDx alternatives shown · citation per claim · audit doctor edit ratio (signal of quality)
Whisper BM mistranscribe (clinical jargon)Med🟠 SOAP wrongCustom medical vocab biased decoding · live transcript preview · doctor read-back option · post-edit allowed
CDSS miss critical DDxLow🔴 Delayed dx50-scenario regression · over-list bias (top-5 always) · uncertainty flag if confidence <60%
HITL bypass attempt (jailbreak)Low🔴 Inappropriate RX30-prompt jailbreak suite · server-side enforcement (not just UI) · audit log all attempts
Llama 70B GPU OOM under loadMed🟠 SOAP gen failvLLM batching + queue · cloud burst gpt-4o fallback · graceful degrade ke 8B
Audio storage cost runawayMed🟢 Budget30-day retention · purge job · compress (Opus codec) · only retain SOAP text long-term
Doctor reject AI assistance (cultural)Med🟠 ROI missDoc Zam champion role · onboarding training · "AI propose, you decide" framing · skip-AI option always
RBAC leak across clinic tenantLow🔴 PDPA breachTenant scope enforced at query layer · row-level security · per-PR security review