Skip to main content
Canadian Healthcare AI

Canadian Healthcare AI

HPOA Comparison Tool Tech Stack and Interactions

This page documents the architecture, governance model, retrieval workflow, and security controls used within the HPOA Comparison Tool. The system is designed to demonstrate practical, governance-aware AI implementation within Canadian healthcare and regulatory environments.

System overview

HPOA Comparison Tool System Architecture

The diagram below maps the full request lifecycle from public access through session authentication, retrieval, model inference, and user export.

System architecture diagram for the HPOA Comparison Tool showing public website, protected access, session validation, retrieval, Claude synthesis, citations, and export workflow.

Diagrams as code

Architecture source

The diagram above is generated from the D2 source below, allowing the system architecture to evolve alongside the codebase.

View D2 sourcedocs/hpoa-system-architecture.d2
# HPOA Comparison Tool - System Architecture
# Source of truth for architecture documentation.
# Render to SVG: d2 docs/hpoa-system-architecture.d2 docs/hpoa-system-architecture.svg
# Render to PNG: d2 docs/hpoa-system-architecture.d2 docs/hpoa-system-architecture.png

direction: down

# ── Styles ────────────────────────────────────────────────────────────────────

classes: {
  workflow: {
    style.fill: "#EBF0F7"
    style.stroke: "#7A9BBF"
    style.border-radius: 6
  }
  auth: {
    style.fill: "#FEF8ED"
    style.stroke: "#C4943A"
    style.border-radius: 6
  }
  retrieval: {
    style.fill: "#EDF4ED"
    style.stroke: "#5A8A5A"
    style.border-radius: 6
  }
  security: {
    style.fill: "#F3EDF7"
    style.stroke: "#8A6BA8"
    style.border-radius: 6
  }
  stack: {
    style.fill: "#F5F4F0"
    style.stroke: "#B8B4A8"
    style.border-radius: 6
  }
}

# ── Main workflow ─────────────────────────────────────────────────────────────

public_website: Public Website {
  class: workflow
  label: "Public Website\nExplains tools, governance, services, contact"
}

hpoa_page: HPOA Comparison Tool Page {
  class: workflow
  label: "HPOA Comparison Tool Page\nLayout and purpose visible to all visitors\nPrompting bar is locked"
}

password_unlock: Password Unlock {
  class: auth
  label: "Password Unlock\nPOST /api/hpoa-verify\nValidates HPOA_TOOL_PASSWORD (timing-safe)\nCreates 6-hour session token\nIP rate limit: 5 attempts / 15 min"
}

protected_prompt: Protected Prompt Submission {
  class: workflow
  label: "Protected Prompt Submission\nPOST /api/hpoa-query\nServer-side session validation\nRate limit: 20 prompts / 10 min\nPHI guard, input validation, logging"
}

retrieval_rag: Retrieval (RAG) {
  class: retrieval
  label: "Retrieval (RAG)\nSupabase statute_chunks table\npgvector cosine similarity search\nHPOA and HPA legislative sections"
}

model_answer: Model Answer (LLM) {
  class: retrieval
  label: "Model Answer\nAnthropic Claude\nUser question + retrieved statute chunks\nPlain-language answer with citations"
}

user_output: User Output and Exports {
  class: workflow
  label: "User Output and Exports\nAnswer panel (plain language)\nCitations (statute references)\nPDF session export\nOptional email delivery"
}

# ── Supporting infrastructure ─────────────────────────────────────────────────

session_store: Temporary Session Store {
  shape: cylinder
  class: auth
  label: "Temporary Session Store\nSupabase - hpoa_sessions\nsession_id (UUID)\ncreated_at, expires_at (6 hrs)\nip_address, user_agent\nrevoked_at (nullable)"
}

security_layer: Security Layer {
  class: security
  label: "Security Layer\nSession validation\nIP-based rate limiting\nPHI detection (client and server)\nInput validation\nCSP and HTTP security headers\nStructured event logging"
}

knowledge_base: Knowledge Base {
  shape: cylinder
  class: retrieval
  label: "Knowledge Base\nSupabase + pgvector\nstatute_chunks table\nEmbeddings (Voyage AI vectors)\nMetadata and source citations\nProvince, act, section"
}

llm_provider: LLM Provider {
  class: retrieval
  label: "LLM Provider\nAnthropic Claude API"
}

export_delivery: Export Delivery {
  class: workflow
  label: "Export Delivery\nServer-generated PDF\nOptional email delivery\nConfigurable by organizational\nprivacy and data residency requirements"
}

# ── Tech stack ────────────────────────────────────────────────────────────────

tech_stack: Tech Stack {
  class: stack
  label: "Tech Stack\nNext.js (Frontend and API routes)\nVercel (Hosting and edge delivery)\nSupabase + pgvector (Database, sessions, knowledge base)\nVoyage AI (Embedding model)\nAnthropic Claude (LLM inference)\nServer-generated PDF (Primary export)"
}

# ── Main workflow connections ─────────────────────────────────────────────────

public_website -> hpoa_page
hpoa_page -> password_unlock
password_unlock -> protected_prompt: "session validated"
protected_prompt -> retrieval_rag
retrieval_rag -> model_answer
model_answer -> user_output

# ── Supporting infrastructure connections ─────────────────────────────────────

password_unlock -> session_store: "creates"
protected_prompt -> security_layer: "enforces"
retrieval_rag -> knowledge_base: "queries"
model_answer -> llm_provider: "inference via"
user_output -> export_delivery: "delivers via"

# ── Tech stack reference ──────────────────────────────────────────────────────

user_output -> tech_stack: "powered by" {
  style.stroke-dash: 4
  style.stroke: "#B8B4A8"
}

Step 1 and 2

Public interface

The public website presents the tool's purpose, governance context, and access pathway before any interaction begins. The HPOA Comparison Tool page is visible to all visitors: the layout, scope description, and session structure are legible without authentication.

The prompting interface is locked at this stage. Users see the tool's purpose and can read about what questions the tool is designed to answer, but cannot submit queries until a valid session is established. This gate ensures that resource consumption and legislative retrieval only occur for authenticated sessions.

The public interface is served as a static Next.js page via Vercel edge infrastructure, with no server-side data fetching required for the unauthenticated view.

Step 3

Session protection

Authentication is handled through a dedicated API route at POST /api/hpoa-verify. When a user submits the access credential, the server validates it using a timing-safe comparison against the environment-stored password. The plaintext credential is never returned to the client or stored in the browser.

On successful authentication, the server creates a session record in a dedicated Supabase table. Each session is assigned an opaque UUID, timestamped with a six-hour expiry, and associated with the IP address and user agent of the authenticating request. Sessions can be revoked server-side via a revoked_at field without requiring credential rotation.

The session ID is stored in sessionStorage on the client and transmitted as a request header on all subsequent API calls. The server validates the session against the database on every protected request, confirming the record exists, has not been revoked, and has not expired.

IP-based rate limiting on the verify endpoint prevents brute-force credential attempts. After five failed attempts within fifteen minutes, further authentication requests from that IP are blocked for the remainder of the window.

Step 4 and 5

Retrieval and legislative search

Once a session is validated, the user's question is submitted to POST /api/hpoa-query. Before retrieval begins, the server performs a per-session rate limit check, capping usage at twenty prompts per ten-minute window to ensure fair access and prevent runaway consumption.

The question is converted into a vector embedding using Voyage AI's embedding model. This embedding is submitted to a pgvector similarity search against the statute_chunks table in Supabase, which contains indexed sections of the Health Professions and Occupations Act (HPOA) and the Health Professions Act (HPA).

Each chunk in the knowledge base carries structured metadata: province, act, section number, and source citation. The top-ranked chunks are retrieved and passed to the model as grounding context alongside the user's original question. This Retrieval-Augmented Generation (RAG) architecture ensures answers are grounded in specific legislative text rather than general model knowledge.

Step 6 and 7

Citation workflow

Retrieved statute chunks and the user's question are submitted to Anthropic Claude. The model is instructed to produce a plain-language answer that stays within the bounds of the provided legislative text and clearly identifies which sections of the HPOA or HPA inform each part of its response.

Citations are rendered as structured references in the answer panel, linking each claim back to the specific section of legislation it draws from. This allows users to verify responses against the source text directly, rather than treating the model's output as a standalone interpretation.

Completed answers can be exported as a server-generated PDF, rendered with print-optimized styles including section breaks and pagination controls suited to formal review use cases. PDF export and on-screen citation review function independently of any external delivery infrastructure.

An optional email delivery layer allows users to send a session summary to a nominated address. Email delivery is configurable and may be disabled or replaced depending on organizational privacy requirements and data residency preferences. When enabled, email addresses are not stored beyond the delivery transaction and prompt text is not included in delivery payloads.

Security architecture

Governance and security controls

The security architecture operates in layers. At the network level, all routes are served with HTTP security headers including a Content Security Policy, X-Frame-Options: DENY, strict referrer policy, and permissions policy disabling camera, microphone, and geolocation. These headers are applied globally across all pages.

At the application level, all protected API routes validate the session token server-side before any processing occurs. Rate limiting operates at two tiers: per-IP on the authentication endpoint, and per-session on the query endpoint. Both tiers write structured log events to the hpoa_tool_logs table for operational monitoring.

PHI detection operates on both the client and server. The input validation layer screens submissions for common personal health information patterns, including health card numbers, clinical note indicators, and date-of-birth formats. Users are warned against submitting identifiable patient information before and during use.

All database access is governed by Supabase Row Level Security. The session table has no public policies; only the service role key can read or write session records. The knowledge base table is read-only for the application role and is not accessible through the public Supabase client.

Logs record event type, timestamp, session ID, IP address, user agent, and prompt length in characters. Full prompt text is not retained in logs.

Email delivery is not required for use of the HPOA Comparison Tool. PDF export and on-screen citation review function independently of transactional email infrastructure.

Scope and constraints

Intended use and limitations

The HPOA Comparison Tool is designed for general legislative and governance information. It is appropriate for health professionals, regulatory staff, and governance reviewers seeking plain-language explanations of how the incoming Health Professions and Occupations Act compares to the current Health Professions Act.

The tool is not a substitute for legal advice. Answers are grounded in indexed legislative text but may not reflect the most recent amendments, regulatory guidance, or formal legal interpretation. Any operational, regulatory, or legal decision should be verified against official sources such as bclaws.gov.bc.ca, the relevant regulatory college, or qualified legal counsel.

The retrieval system operates within the boundaries of its indexed corpus. Questions that fall outside the scope of the HPOA and HPA may receive partial or incomplete answers. The model is instructed to indicate when its grounding context is insufficient to answer a question with confidence.

This platform is a demonstration system. It is not approved for clinical use, patient-facing deployment, or any context where AI-generated content could influence direct patient care.

Infrastructure

Technology stack

Frontend + API

Next.js on Vercel

App Router with React Server Components. API routes run as Vercel serverless functions on Node.js runtime.

Knowledge base

Supabase with pgvector

PostgreSQL with pgvector extension. Statute chunks stored with dense vector embeddings. Row Level Security enforced on all tables.

Embeddings

Voyage AI

Semantic vector embeddings for both indexing and query-time similarity search. Retrieval uses cosine similarity.

Inference

Anthropic Claude

LLM inference for plain-language answer generation. Grounded against retrieved statute chunks with citation instructions.

Session store

Supabase (hpoa_sessions)

Server-side session table with UUID tokens, expiry timestamps, IP logging, and revocation support.

Optional delivery layer

Configurable transactional email

Email delivery may be disabled, self-hosted, or replaced depending on organizational privacy and data residency requirements.

Architecture docs

D2 architecture documentation

Version-controlled architecture diagrams used to document the system workflow, security layers, and retrieval architecture.

Security controls, rate limiting, session management, and retrieval protections continue to evolve as the platform matures.