Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt

Use this file to discover all available pages before exploring further.

Version: 1.0.0 Last Updated: 2026-02-19 Status: 📝 Planned Spec Reference: specs/cl/specs/CL-09-lab-diagnostic-orders-results.md

Overview

CL-09 provides lab and diagnostic order entry, result ingestion, abnormal flagging, review workflows, and trending. This document defines all integration points, event contracts, API contracts, and external integration architecture.

Integration Matrix

IntegrationPatternDirectionStatus
CL-01 (Patient Chart)Data / UICL-09 → CL-01📝 Planned
CL-05 (Medication Management)Data (via CL-08 CDS)CL-05 → CL-08 → CL-09📝 Planned
CL-08 (Clinical Decision Support)EventCL-09 → CL-08📝 Planned
PF-10 (Notifications)EventCL-09 → PF-10📝 Planned
PF-70 (Code Libraries)Platform LayerPF-70 → CL-09📝 Planned
External LabsExternal APIBidirectional📝 Planned

Internal Integration Points

CL-01: Patient Chart Display

CL-09 orders and results are displayed in the patient chart under a “Labs & Orders” tab. Data Flow:
  • Chart queries cl_orders and cl_order_results filtered by chart_id and organization_id
  • Results display includes abnormal flagging with color-coded indicators
  • Trending view uses result_value_numeric for recharts time-series rendering
Query Pattern:
// Orders for a chart
const { data: orders } = await supabase
  .from('cl_orders')
  .select('*, cl_order_results(*)')
  .eq('organization_id', orgId)
  .eq('chart_id', chartId)
  .is('deleted_at', null)
  .order('created_at', { ascending: false });

// Trending query for a specific LOINC code
const { data: trends } = await supabase
  .from('cl_order_results')
  .select('result_value_numeric, created_at')
  .eq('organization_id', orgId)
  .eq('chart_id', chartId)
  .not('result_value_numeric', 'is', null)
  .order('created_at', { ascending: true });

CL-05 → CL-08 → CL-09: Monitoring Protocol Flow

Ownership:
  • CL-05 owns medication data and monitoring_protocol definitions
  • CL-08 evaluates monitoring gaps using CDS rules and generates reminder alerts
  • CL-09 provides the order entry action (clinician responds to CL-08 alert by creating an order)
Flow:
CL-05: cl_medications.monitoring_protocol = { frequency_days: 90, loinc_codes: ['2823-3'] }
  ↓ (evaluated at chart_open)
CL-08: CDS engine checks last order date for loinc_code vs frequency_days
  ↓ (gap detected)
CL-08: Creates cl_cds_alerts with type='monitoring', action_url='/cl/chart/{id}/orders/new?loinc=2823-3'
  ↓ (clinician clicks alert)
CL-09: Order entry pre-populated with LOINC code from alert
CDS Rule Type: monitoring (new rule type in CL-08 evaluation engine)

CL-08: Abnormal Result Alerts

When cl_lab_result_received event fires with abnormal_flag != ‘normal’:
  • CL-08 CDS engine evaluates the result
  • Creates cl_cds_alerts with severity based on abnormal_flag:
    • critical_low/critical_high → severity: critical
    • low/high → severity: moderate
    • abnormal → severity: low

PF-10: Notifications

TriggerNotification TypeRecipientsPriority
Abnormal/critical resultlab_result_abnormalOrdering providerhigh
Result received (normal)lab_result_receivedOrdering providernormal
Order status changelab_order_statusOrdering providerlow

PF-70: LOINC Code Library

cl_loinc_codes reference table is seeded with common BH codes. Future integration with PF-70 code library for comprehensive LOINC search.

Event Contracts

cl_lab_order_created

Channel: cl_pm_events Publisher: CL-09 Subscribers: PF-10, FW automations Trigger: Order status transitions from draft to ordered
{
  event_type: 'cl_lab_order_created';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  order_id: string;           // UUID
  chart_id: string;           // UUID
  ordering_provider_id: string; // UUID
  loinc_code: string | null;
  priority: 'stat' | 'urgent' | 'routine';
  lab_id: string | null;      // UUID — reference lab
}

cl_lab_result_received

Channel: cl_pm_events Publisher: CL-09 (ingestion edge function) Subscribers: CL-08 (abnormal alert evaluation), PF-10 Trigger: Result record inserted via ingestion or manual entry
{
  event_type: 'cl_lab_result_received';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  result_id: string;          // UUID
  order_id: string;           // UUID
  chart_id: string;           // UUID
  abnormal_flag: 'normal' | 'low' | 'high' | 'critical_low' | 'critical_high' | 'abnormal';
  result_code: string | null;
}

cl_lab_result_reviewed

Channel: cl_pm_events Publisher: CL-09 Subscribers: PF-10 Trigger: Clinician signs off on a result (reviewed_by/reviewed_at set)
{
  event_type: 'cl_lab_result_reviewed';
  organization_id: string;   // UUID
  timestamp: string;          // ISO 8601
  result_id: string;          // UUID
  order_id: string;           // UUID
  chart_id: string;           // UUID
  reviewed_by: string;        // UUID
}

External Integration: Lab Result Ingestion

Architecture

External Lab System (Quest, LabCorp, local)
  ↓ (HTTPS POST with API key)
Edge Function: cl-lab-result-ingestion
  ↓ (parse HL7v2 ORU or FHIR DiagnosticReport)
  ↓ (validate org_id + lab API key)
  ↓ (map to cl_order_results rows)
  ↓ (insert via service-role client)
  ↓ (publish cl_lab_result_received event)
  ↓ (return ACK/NAK response)

Edge Function: cl-lab-result-ingestion

Authentication: Custom API key per lab per organization. Stored in cl_reference_labs.connection_config.api_key (encrypted). verify_jwt: false. Request Format:
// Option A: FHIR DiagnosticReport (JSON)
POST /functions/v1/cl-lab-result-ingestion
Content-Type: application/json
X-Lab-API-Key: <api_key>

{
  "format": "fhir",
  "organization_id": "<uuid>",
  "resource": { /* FHIR DiagnosticReport */ }
}

// Option B: HL7v2 ORU (text)
POST /functions/v1/cl-lab-result-ingestion
Content-Type: text/plain
X-Lab-API-Key: <api_key>
X-Organization-ID: <uuid>

MSH|^~\&|LAB|...
PID|...
OBR|...
OBX|...
HL7v2 Parsing Strategy:
  • Custom segment parser in edge function (no external library dependency)
  • Parse MSH, PID, OBR, OBX segments
  • Map OBX-3 (LOINC) → result_code, OBX-5 → result_value/result_value_numeric, OBX-6 → result_units, OBX-7 → reference_range, OBX-8 → abnormal_flag
FHIR Mapping:
  • DiagnosticReport.result[] → individual cl_order_results rows
  • Observation.code.coding[0].code → result_code (LOINC)
  • Observation.valueQuantity.value → result_value_numeric
  • Observation.interpretation → abnormal_flag
Response:
  • 200 + ACK on success
  • 400 + NAK on validation failure
  • 401 on invalid API key
  • 500 + error on server failure

Security Controls

  1. TLS 1.2+ required for all inbound connections
  2. API key validation against cl_reference_labs.connection_config
  3. Service-role client for database operations (bypasses RLS)
  4. Audit logging — all ingested results logged to pf_audit_logs with source lab identifier
  5. PHI handling — result values stored only in RLS-protected tables; no PHI in edge function logs
  6. Rate limiting — per-lab rate limiting via pf_rate_limit_buckets

Security Patterns

  • All CL-09 tables use composite FKs (organization_id, entity_id) for tenant isolation
  • UPDATE RLS policies include WITH CHECK to prevent organization_id modification
  • DELETE is blocked on cl_orders and cl_order_results (soft delete via deleted_at)
  • Lab ingestion uses SECURITY DEFINER functions when inserting via service-role to maintain audit trails

  • Spec: specs/cl/specs/CL-09-lab-diagnostic-orders-results.md
  • Task Breakdown: specs/cl/tasks/CL-09-TASKS.md
  • CL-05 Integration: docs/architecture/integrations/CL-05-medication-management-INTEGRATION.md
  • CL-08 Integration: docs/architecture/integrations/CL-08-clinical-decision-support-INTEGRATION.md
  • Event Contracts: docs/architecture/integrations/EVENT_CONTRACTS.md
  • CROSS_CORE_INTEGRATIONS: docs/architecture/integrations/CROSS_CORE_INTEGRATIONS.md