CliniQ+
Clinical consultation, private record vault and continuing-care platform built with Next.js 16, React 19, TypeScript and Supabase PostgreSQL. Isolates live speech capture and structured delta extraction behind strict row-level security, clinician revision gates and a tamper-evident SHA-256 EMR audit chain.
Handling clinical ambiguity without unsafe chart writes
Naive speech-to-EMR loops fail silently under negated symptoms, dropped clinic connections, concurrent manual edits and allergy conflicts. Explore the failure modes below alongside the five-stage approval pipeline.
Audio states 'no fever for 3 wks; takes metformin daily'
0 false-positive symptoms or active med promotionDirect JSON extraction logs fever as active and stages home metformin inside new prescription orders.
Clinical meaning gate verifies verbatim source indices and negation scope, retracting fever while isolating metformin into history context.
Bounded WAV capture & operation-keyed transcript segments
Browser audio downsamples to 16 kHz mono 16-bit PCM (capped at 1 MiB / 30 s per clip or single-flight Opus relay) bound to a stable operation key, segment UUID and server-computed SHA-256 WAV digest.
Pre-registering a durable send marker before external speech transport lets interrupted requests recover cleanly without double-charging provider quotas.
Aborted sends remain locked against new capture while exposing save_retained recovery through the commit fence without retransmitting audio.
Seven interactive blueprints across every system boundary
Every trust boundary in CliniQ+ is mapped across seven interactive architecture diagrams covering request admission, role shells, approval sequences, document storage and data ownership. Switch tabs below or expand any view to search components (/) and trace request paths (R).
System architecture
Patient and care-team workspaces layered over Next.js route handlers, Supabase RLS policies, durable SQL workers and gated speech/LLM providers.
Scroll horizontally inside the frame or expand for zoom, node finder (/) and route tracing (R).
- Consultation drafts stay strictly isolated from sealed approved records
- Patient endpoints serve only signed clinician approvals
- External AI, OCR and speech dispatch pass server flags & token allowances
Six role-isolated workspaces over one shared clinical core
Routes reflect explicit authority rather than client-hidden tabs. Switching roles below shows which data each actor can mutate and what PostgreSQL row-level security excludes.
/consultations/doctor/patients/doctor/alertsClinician consultation & review
Split consultation workspace linking raw speech segments, incremental delta patches, drug-allergy warnings and atomic EMR sign-off.
- Start or resume consultations scoped strictly to active workspace patients
- Review delta operations alongside exact source transcript quotations
- Confirm uncertain findings and contraindication overrides prior to signing
- Author linked post-approval amendments referencing the original sealed revision
Private Storage, bounded parsing & lease-fenced cleanup
Patient uploads live inside a locked Storage bucket fronted by quotas, byte-signature checks, worker leases and automatic grant revocation whenever records are replaced.
Idempotent upload admission & magic-byte validation
PostgreSQL document_admit enforces per-account ceilings (10 active records, 10 versions/record, 40 MiB total), verifies binary magic headers and checks UTF-8 encoding before registering a private Storage key.
- Idempotent operation keys reconcile repeated upload retries cleanly without double-counting storage quota
- Expired uncommitted uploads are reclaimed after 15 minutes strictly by exact recorded object keys
- Bucket listing, public URLs and spoofed file extensions fail closed at the Storage boundary
4 MiB / 40 MiBAdmission quotaPer-file and per-patient Storage limits enforced atomically inside PostgreSQL before upload targets issue
20p / 100K charsPDF worker budgetSandboxed pdfjs-dist 6.4.299 parser capped at 100 chunks (150-char overlap) and 30s deadline
90s lease / 3 claimsFenced durabilityMonotonically increasing fence tokens reject delayed chunk writes after worker lease reclamation
15 min TTLOrphan reclamationSweeps exact recorded Storage keys for abandoned uploads without scanning buckets by prefix
6 chunks / 3,000 tokGrounded retrievalAuth filters chunks before ranking while reserving worst-case model tokens prior to dispatch
Multiples of 5Cohort k-thresholdingResearch exports round active participants down by 5 and suppress quarters with fewer than 5 opt-ins
Technologies by responsibility
Application & State
- Next.js 16 & React 19App Router role workspaces, server route admission and fail-closed session guards
- TypeScript & ZustandRevision-fenced dirty form memory and operation-key request reconciliation
- Self-Hosted Geist FontsBundled Fontsource typography for deterministic UI & CSP-safe A4 print sheets
Database & Storage
- Supabase PostgreSQL & RLSRow-level isolation across Auth accounts, workspace roles, care links and vaults
- Locked Private StorageSQL pre-registration, byte-signature checks and no-store RLS byte streaming
- SHA-256 Chain & Paise LedgerHash-linked clinical audit events alongside integer-paise encounter billing
Audio, Extraction & Docs
- Deepgram nova-2 & PCM WAV16 kHz mono WAV downsampling and single-flight Opus speech streaming
- Groq Llama 3.3 70B & Qwen 3.8Incremental delta extraction and optional scanned-page transcription review
- PDF.js 6.4.299 & CanvasIsolated local text chunker and bounded page rasterizer under memory limits
Verification & Recovery
- Vitest & Isolated Supabase SuitesMulti-actor Auth PKCE, cross-tenant RLS denial and Storage revocation suites
- Clinical Meaning ValidatorVerbatim source-quote, bilingual negation, unit match and dosage safety regressions
- Shared Recovery RunnerIdempotent reconciliation sweeping expired leases, orphans and medicine tasks
Verified properties and operational constraints
Verified Guarantees
- Supabase Auth sessions bind strictly to explicit active database accounts without email merging or metadata role escalation
- Clinician approval executes atomically in PostgreSQL, chaining actor, payload, timestamp and previous digest via SHA-256
- Private patient documents auto-revoke active clinician shares immediately whenever replacement versions upload
- Ambiguous timeouts retain operation identity so save_retained and reconciliation recover cleanly without double charges
- Patient vitals trend series preserve unit boundaries strictly and never coerce null clinical gaps to zero
Operational Bounds
- External AI, speech and OCR adapters stay gated behind server flags, exact actor scopes and pre-reserved token budgets
- PDF extraction enforces 20-page, 100K-char and 30-second bounds to protect serverless execution ceilings
- Encounter billing evaluates versioned integer-paise tariffs inside PostgreSQL without external payment gateway settlement
- Safety validators check allowlisted drug-allergy interactions while reserving final therapeutic judgment for the clinician
- Continuing-care dose reminders cap at 8 intervals per day across 90-day windows over explicit Asia/Kolkata or UTC zones