Projects/Healthcare Systems/CliniQ+

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.

Audit ChainSHA-256Hash-linked actor, revision payload & parent approval
Access Control6 WorkspacesServer RLS enforced across role & document grants
Document Worker90s Fence20p / 100K PDF parser with stale-write rejection
System Atlas7 DiagramsInteractive topology across 61 components
01 / Consultation Flow

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 promotion
Naive Voice-to-EMR

Direct JSON extraction logs fever as active and stages home metformin inside new prescription orders.

CliniQ+ Defense

Clinical meaning gate verifies verbatim source indices and negation scope, retracting fever while isolating metformin into history context.

POST /api/clinical/:id/speech

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.

Engineering rationale

Pre-registering a durable send marker before external speech transport lets interrupted requests recover cleanly without double-charging provider quotas.

Failure & retry behavior

Aborted sends remain locked against new capture while exposing save_retained recovery through the commit fence without retransmitting audio.

Priya Sharma · Encounter REV-04 (Audio & Segment)
Pre-send digestsha256:8c4e...d19a · 16 kHz mono WAV (14.2 s)
Segment SEG-09Right knee pain 3 wks; no fever; takes metformin 500 mg
Linked append SEG-10Aspirin allergy clarified without erasing SEG-09
Authority: SpeechCapture + /api/clinical/:id/speech
02 / System Architecture

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

App Router & Client UIDomain Routes & WorkerPostgreSQL RLS & StorageAuth & Approval GatesGated External AI
Diagram 01 of 07 · 8 components · 20 edges

System architecture

Patient and care-team workspaces layered over Next.js route handlers, Supabase RLS policies, durable SQL workers and gated speech/LLM providers.

New tab

Scroll horizontally inside the frame or expand for zoom, node finder (/) and route tracing (R).

Loading Overview...
  • 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
03 / Role Workspaces

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/alerts

Clinician 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
Clinicians cannot read patient vault uploads unless an explicit per-document share grant is active.
Active review · Priya Sharma (Knee pain)
REV-04Draft only1 Allergy alert
TranscriptSEG-09 · No fever · Metformin history
Safety gateDiclofenac blocked (aspirin allergy); Paracetamol staged
Approval RPCclinical_mutate -> emr_versions #01
04 / Vault & Recovery

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.

Patient uploads PDF, TXT, PNG or JPEG (max 4 MiB)

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
Private key registered; direct client upload completes without exposing service-role secrets
4 MiB / 40 MiBAdmission quota

Per-file and per-patient Storage limits enforced atomically inside PostgreSQL before upload targets issue

20p / 100K charsPDF worker budget

Sandboxed pdfjs-dist 6.4.299 parser capped at 100 chunks (150-char overlap) and 30s deadline

90s lease / 3 claimsFenced durability

Monotonically increasing fence tokens reject delayed chunk writes after worker lease reclamation

15 min TTLOrphan reclamation

Sweeps exact recorded Storage keys for abandoned uploads without scanning buckets by prefix

6 chunks / 3,000 tokGrounded retrieval

Auth filters chunks before ranking while reserving worst-case model tokens prior to dispatch

Multiples of 5Cohort k-thresholding

Research exports round active participants down by 5 and suppress quarters with fewer than 5 opt-ins

05 / Tech Stack

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
06 / Guarantees & Bounds

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
↑ ↓ Browse · Enter Open · Esc Close