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

# Encore Health OS Platform - Architecture Documentation

> Architectural documentation for the Encore Health OS Platform.

Architectural documentation for the Encore Health OS Platform.

***

## Overview

The Encore Health OS Platform is a multi-tenant, healthcare-grade ERP system built on modern web technologies with strict architectural boundaries. It is designed to run behavioral health and recovery housing operations end-to-end.

***

## Structure

**Status note:** The PF feature list and core rollout labels below are a **high-level sketch** for orientation. For current implementation status, use [`specs/README.md`](../../specs/README.md) and each core’s `src/cores/{core}/AGENTS.md`.

### Platform Foundation (PF)

Core capabilities that all domain cores depend on:

**Identity & Access:**

* PF-01: Organization & Site Management
* PF-02: Role-Based Access Control (RBAC)
* PF-06: User Profile Management

**Platform Services:**

* PF-03: App Launcher & Module Switcher
* PF-04: Audit Logging System
* PF-07: Error Handling & Monitoring
* PF-08: Platform Forms Integration Layer

**Data & Communication:**

* PF-09: Form Analytics (pending)
* PF-10: Notifications System
* PF-11: Document Management System
* PF-12: Reporting Engine

### Domain Cores

PF plus eleven domain cores are represented in the codebase: **CE, CL, FA, FM, FW, GR, HR, IT, LO, PM, RH**. Implementation depth varies by spec; **do not treat this page as a release roadmap.**

* **Specifications:** [`specs/README.md`](../../specs/README.md)
* **Per-core implementation notes:** `src/cores/{core}/AGENTS.md` (e.g. [`src/cores/hr/AGENTS.md`](../../src/cores/hr/AGENTS.md))
* **User and operator guides:** [docs/index.md](../index.md) (Documentation by Category)

***

## Key Principles

1. **Bounded Contexts**: Each core owns its domain, no cross-core dependencies
2. **Platform Foundation Only**: Cores depend only on PF, not each other
3. **Explicit Integration Contracts**: Cross-core communication via defined APIs/events
4. **RLS-First Security**: Multi-tenant isolation enforced at database level
5. **Spec-First Delivery**: No feature without written specification

***

## Integration Patterns (Constitution Section 1.3)

### Pattern 1: Platform Integration Layer

**When to Use:** Cross-cutting capabilities needed by multiple cores (e.g., forms, notifications)

**Structure:**

```
/src/platform/<capability>/
  ├── index.ts           # Public API exports
  ├── types.ts           # Type definitions
  ├── hooks/             # React Query hooks
  └── components/        # Reusable components
```

**Example:** Platform Forms Integration (PF-08)

```tsx theme={null}
// Cores import from platform, NOT from fw
import { FormEmbed } from '@/platform/forms';

// In RH core
<FormEmbed formId="resident-intake" onSuccess={handleSubmit} />
```

### Pattern 2: Event-Based Integration

**When to Use:** Asynchronous workflows, loose coupling between cores

**Structure:**

```sql theme={null}
-- Core publishes domain event
SELECT pg_notify('resident_admitted', json_build_object(
  'resident_id', NEW.id,
  'organization_id', NEW.organization_id
));

-- Other cores subscribe via triggers or edge functions
```

**Example:** Automation Engine (FW-03) listens to form events

### Pattern 3: API Contracts

**When to Use:** Synchronous request-response interactions

**Structure:**

```typescript theme={null}
// Define contract in spec
interface ResidentCensusRequest {
  organization_id: string;
  site_id: string;
  date: string;
}

// Implement as edge function
export async function getCensus(req: ResidentCensusRequest): Promise<CensusData>
```

***

## Data Flow

### Multi-Tenant Request Flow

```
User Request
  → Auth Middleware (Supabase Auth)
  → Organization Context (PF-01)
  → RLS Policies (PF-02 + per-table)
  → Core Business Logic
  → Audit Log (PF-04)
  → Response
```

### Cross-Module Communication

```
Core A (e.g., RH)
  → Platform Integration Layer (e.g., PF-08 Forms)
  → FW Core (via abstraction)
  → Response back through Platform Layer
  → Core A continues processing
```

**See:** [patterns/DATA\_FLOW.md](patterns/DATA_FLOW.md) for detailed flow diagrams

***

## Security Model

### Layers of Defense

1. **Authentication:** Supabase Auth (JWT tokens)
2. **Organization Context:** PF-01 sets current\_organization\_id
3. **RLS Policies:** Database-level enforcement
4. **RBAC Functions:** Security definer functions (PF-02)
5. **Audit Logging:** All actions logged (PF-04)

### RLS Policy Template

```sql theme={null}
-- Standard multi-tenant policy
CREATE POLICY "Users can only see own org data"
ON <table_name>
FOR SELECT
TO authenticated
USING (
  organization_id IN (
    SELECT organization_id 
    FROM pf_user_roles 
    WHERE user_id = auth.uid()
  )
);

-- Role-based policy
CREATE POLICY "Admins can update"
ON <table_name>
FOR UPDATE
TO authenticated
USING (
  has_role(auth.uid(), 'org_admin') OR
  has_role(auth.uid(), 'platform_admin')
)
WITH CHECK (same);
```

***

## Testing Strategy

### Test Pyramid

**Unit Tests** (30%)

* Business logic functions
* Validation schemas
* Utility functions

**Integration Tests** (50%)

* RLS policies (critical!)
* Database functions
* API endpoints
* Cross-module integrations

**E2E Tests** (20%)

* Critical user journeys
* Auth flows
* Multi-tenant isolation
* Compliance workflows

### RLS Testing Approach

See `tests/README.md` for comprehensive RLS testing framework.

**Key Pattern:**

```typescript theme={null}
// Test multi-tenant isolation
const { data: org1Data } = await client1
  .from('table')
  .select('*');

const { data: org2Data } = await client2
  .from('table')
  .select('*');

// Verify no cross-org data
expect(org1Data.some(row => row.organization_id === org2.id)).toBe(false);
```

***

## Performance Targets (Constitution Section 5.6)

### API Response Times (p95)

* Read operations: \< 500ms
* Write operations: \< 2s
* Report queries: \< 30s (with timeout)
* Cached queries: \< 1s

### Page Load Times (p95)

* Initial load: \< 3s
* Navigation: \< 1s
* Form render: \< 500ms

### Database Performance

* All foreign keys indexed
* Full-text search with GIN indexes
* Query timeout: 30s max
* Connection pooling: 15-25 connections

***

## Monitoring & Observability

### Key Metrics

* API response times (p50, p95, p99)
* Error rates by endpoint
* Database query performance
* RLS policy execution time
* Audit log write latency

### Logging Standards

```typescript theme={null}
// Structured logging
logger.info({
  module: 'rh',
  action: 'admit_resident',
  user_id: userId,
  org_id: orgId,
  correlation_id: requestId,
  duration_ms: elapsed
});
```

**Standards:**

* Use structured JSON logs
* Include correlation IDs for tracing
* Do NOT log PHI, PII, or secrets
* Retention: 30 days (info), 90 days (errors), 1 year (audit)

***

## Deployment Model

### Environments

* **Local:** Developer machines (Docker + Supabase CLI)
* **Dev:** Shared development environment
* **Staging:** Pre-production testing
* **Production:** Live system with HA

### Deployment Flow

```
Code Push
  → CI/CD Pipeline (GitHub Actions)
  → Run Tests (unit + integration + RLS)
  → Build Frontend
  → Deploy Database Migrations
  → Deploy Edge Functions
  → Deploy Frontend
  → Smoke Tests
  → Rollback if Failed
```

**See:** Constitution Section 5.5 for deployment and rollback procedures

***

## Technology Stack

### Frontend

* React 18 + TypeScript
* Vite (build tool)
* TailwindCSS + shadcn/ui
* TanStack Query (data fetching)
* React Router (navigation)

### Backend

* Supabase (Postgres + Auth + Storage + Realtime)
* Edge Functions (Deno runtime)
* Row-Level Security (RLS)
* pg\_cron (scheduled jobs)

### DevOps

* GitHub Actions (CI/CD)
* Vitest (testing framework)
* Docker (local development)

***

## Directory Structure

* **patterns/** - Reusable architecture patterns (custom fields, data flow, etc.)
* **standards/** - Architecture standards and conventions (navigation, terminology)
* **analysis/** - Analysis and recommendation documents
* **integrations/** - Cross-core integration contracts
* **decisions/** - Architecture Decision Records (ADRs)
* **deprecation/** - Deprecation notices
* **archive/** - Historical architecture documentation

## Documentation Files

### Core Architecture

* **README.md** (this file) - Architecture overview
* **standards/CORE\_DEPENDENCIES.md** - Module dependency structure
* **patterns/DATA\_FLOW\.md** - Detailed request flows and integration patterns
* **patterns/ORGANIZATIONAL\_DATA.md** - Organizational entity structure
* **standards/TERMINOLOGY.md** - Unified glossary of platform terms

### Integration Documentation

* **integrations/README.md** - Integration documentation overview and single source of truth (see [Integration Documentation](integrations/index.md))
  * **Note:** Replaces the previous `INTEGRATION_CONTRACTS.md` (archived 2025-01-22)
* **integrations/PLATFORM\_INTEGRATION\_LAYERS.md** - Platform integration layers (Pattern 1)
* **integrations/EVENT\_CONTRACTS.md** - Event-based integration contracts (Pattern 2)
* **integrations/API\_CONTRACTS.md** - API-based integration contracts (Pattern 3)
* **integrations/CROSS\_CORE\_INTEGRATIONS.md** - Integration matrix
* **integrations/DATA\_MODELS.md** - Core data models
* **patterns/INTEGRATION\_EXAMPLES.md** - Integration pattern examples

### Design Decisions & Analysis

* **integrations/PF-60-rag-infrastructure-INTEGRATION.md** - Current platform AI/RAG integration strategy reference
* **[Clarity Analysis](../guides/use-cases/clarity-analysis.md)** - Forms vs Data Manager overlap analysis (includes wizards and templates)
* **[PF/FW Documentation Review](reviews/PF-FW-DOCUMENTS-REVIEW-2026-02-01.md)** - Wizard and template terminology review
* **Historical:** [Documentation inventory (archived 2025-01-22)](../archive/analysis/DOCUMENTATION_INVENTORY_architecture_2025-01-22.md) — point-in-time architecture file list
* **Historical:** [Consolidation recommendations (archived 2025-01-22)](../archive/analysis/CONSOLIDATION_RECOMMENDATIONS_2025-01-22.md) — superseded notes
* **analysis/IT\_MODULE\_RECOMMENDATION.md** - IT module recommendation
* **Permissions System:** See [Permissions System Guide](../pf/permissions-system-guide.md) and [Quick Reference](../pf/permissions-quick-reference.md)
* **decisions/ADR-001-form-analytics-architecture.md** - Architecture Decision Record

### Navigation & UX Standards

* **standards/NAVIGATION\_STANDARD.md** - Complete navigation standards, policies, and implementation guidelines
* **standards/navigation-quick-reference.md** - Quick reference for navigation implementation tasks
* **reviews/NAVIGATION\_AUDIT.md** - Navigation and routing audit checklist (routes, sidebar, mobile nav, breadcrumbs)
* **Mobile Navigation Guide:** See `docs/development/mobile-navigation-guide.md` - Mobile navigation patterns
* **Breadcrumb Guide:** See `docs/development/breadcrumb-implementation-guide.md` - Breadcrumb implementation
* **UI/UX Standards:** See `docs/development/UI_UX_STANDARDS.md` - Complete UI/UX standards
* **Spacing & UX Standards:** See `docs/development/SPACING_AND_UX_STANDARDS.md` - Spacing patterns and responsive design

### Customization

* **patterns/CUSTOM\_FIELDS\_GUIDE.md** - Custom fields implementation guide

### Deprecation

* **deprecation/pf\_user\_roles.md** - Deprecation notice for pf\_user\_roles

### Related Documentation

* **[constitution.md](../../constitution.md)** (current: see docs/VERSIONS.md) - Full architectural guardrails
* **[AI\_GUIDE.md](../../AI_GUIDE.md)** (current: see docs/VERSIONS.md) - AI contribution guidelines (for AI agents writing code)
* **/specs/** - Feature specifications
* **/tests/README.md** - Testing documentation
* **/docs/guides/use-cases/** - Practical use case guides

## See Also

### Integration Documentation

* **[Integration Documentation](integrations/index.md)** (v2.1.0) - Single source of truth for all cross-core integrations
* **[Platform Integration Layers](integrations/PLATFORM_INTEGRATION_LAYERS.md)** - Pattern 1: Shared utilities
* **[Event Contracts](integrations/EVENT_CONTRACTS.md)** - Pattern 2: Event-based integration
* **[API Contracts](integrations/API_CONTRACTS.md)** - Pattern 3: Synchronous APIs
* **[Cross-Core Integrations](integrations/CROSS_CORE_INTEGRATIONS.md)** - Integration matrix
* **[IT Integration Contracts](integrations/IT_INTEGRATION_CONTRACTS.md)** - IT module integration documentation
* **[Integration Examples](patterns/INTEGRATION_EXAMPLES.md)** - Code examples for all patterns

### Design Decisions

* **[PF-60 RAG Infrastructure Integration](integrations/rag-infrastructure-integration.md)** - Current platform AI/RAG integration strategy reference
* **[Design Decisions](decisions/)** - Architecture Decision Records (ADRs)

### Data & Flow

* **[Data Flow](patterns/DATA_FLOW.md)** - Detailed request flows and integration patterns
* **[Organizational Data](patterns/ORGANIZATIONAL_DATA.md)** - Organizational entity structure
* **[Core Dependencies](standards/CORE_DEPENDENCIES.md)** - Module dependency structure
* **[Data Models](integrations/DATA_MODELS.md)** - Core data models and relationships

### Standards & Guidelines

* **[Navigation Standard](standards/NAVIGATION_STANDARD.md)** (v1.0.0) - Navigation patterns and policies
* **[Terminology](standards/TERMINOLOGY.md)** - Unified glossary of platform terms
* **[Custom Fields Guide](patterns/CUSTOM_FIELDS_GUIDE.md)** - Custom fields implementation guide
* **[Spacing & UX Standards](../development/SPACING_AND_UX_STANDARDS.md)** (v1.0.0) - Spacing and UX patterns

### Documentation Management

* **[Documentation inventory (archived)](../archive/analysis/DOCUMENTATION_INVENTORY_architecture_2025-01-22.md)** — historical architecture file list (2025-01-22)
* **[Consolidation recommendations (archived)](../archive/analysis/CONSOLIDATION_RECOMMENDATIONS_2025-01-22.md)** — historical consolidation notes
* **[Documentation Standards](../DOCUMENTATION_STANDARDS.md)** — standards, maintenance, and high-traffic paths

***

## References

* `/constitution.md` - Full architectural guardrails
* `/AI_GUIDE.md` - AI contribution guidelines
* `/specs/` - Feature specifications
* `/tests/README.md` - Testing documentation
* [Supabase RLS Documentation](https://supabase.com/docs/guides/auth/row-level-security)

***

For questions, contact technical owners listed in `/constitution.md`.

**Version:** 1.0.1\
**Last Updated:** 2026-05-13\
**Status:** Active\
**Maintained by:** Platform Foundation Team
