> ## 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 – Lovable Reference Appendix

> Purpose: Detailed reference material moved out of LOVABLE_CUSTOM_KNOWLEDGE.md to keep the main file under 300 lines. This file is NOT pasted into Lovable Custo…

**Purpose:** Detailed reference material moved out of `LOVABLE_CUSTOM_KNOWLEDGE.md` to keep the main file under 300 lines. This file is NOT pasted into Lovable Custom Knowledge — reference it on demand when implementing CL/PM features or setting performance targets.

***

## Table of Contents

* [Quick Reference](#quick-reference)
* [Performance Targets](#performance-targets)
* [Testing Requirements](#testing-requirements)
* [Database Pattern Reference](#database-pattern-reference)
* [Error Handling Reference](#error-handling-reference)
* [UI Component Patterns](#ui-component-patterns)
* [Automation Governance](#automation-governance)
* [Authoritative External References (for AI Accuracy)](#authoritative-external-references-for-ai-accuracy)

***

## Quick Reference

| I need to...                                  | Pattern                                               | Location                                                                                |
| --------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Validate performance budget                   | Lighthouse/Web Vitals + API p95 targets               | [Performance Targets](#performance-targets)                                             |
| Determine minimum test coverage expectations  | Feature-type matrix (Unit/RLS/Integration/E2E)        | [Testing Requirements](#testing-requirements)                                           |
| Apply DB table/index/soft-delete rules        | Table categories, indexes, soft delete                | [Database Pattern Reference](#database-pattern-reference)                               |
| Map Supabase/Postgres errors to user messages | Error codes and retry rules                           | [Error Handling Reference](#error-handling-reference)                                   |
| Use form layout, page templates, icon sizes   | ResponsiveFormLayout, OverviewPageWrapper, icon scale | [UI Component Patterns](#ui-component-patterns)                                         |
| Govern automations (FW, cron, webhooks)       | Circuit breaker, dry-run, logging                     | [Automation Governance](#automation-governance)                                         |
| Find authoritative regulatory/source links    | Spec-mapped external reference table                  | [Authoritative External References](#authoritative-external-references-for-ai-accuracy) |

***

## Performance Targets

* Lighthouse Performance: **85+**, PWA: **90+**
* First Contentful Paint: **\< 2s**
* Largest Contentful Paint: **\< 2.5s**
* CLS: **\< 0.1**
* Time to Interactive: **\< 3.5s on 3G**
* API p95: **\< 500ms** reads, **\< 2s** writes

**Mandatory patterns:** Route code splitting (`React.lazy`), Suspense boundaries, skeleton loaders, QueryClient defaults (`staleTime: 5min, gcTime: 10min`), font optimization (max 2-3 families, `font-display: swap`), preconnect hints.

***

## Testing Requirements

| Feature Type    | Unit | RLS      | Integration | E2E      |
| --------------- | ---- | -------- | ----------- | -------- |
| Database schema | —    | Required | —           | —        |
| CRUD operations | 80%  | Required | Optional    | —        |
| Business logic  | 80%  | Required | Required    | —        |
| Critical flows  | 80%  | Required | Required    | Required |

* Propose tests alongside code, not as TODO.
* RLS tests verify tenant isolation.
* No placeholder assertions (`expect(true).toBe(true)`).

***

## Database Pattern Reference

**Table category matrix:** Determines which columns each table type requires.

| Category           | custom\_fields | deleted\_at | organization\_id       | site\_id         | Audit columns |
| ------------------ | -------------- | ----------- | ---------------------- | ---------------- | ------------- |
| Business Entity    | Required       | Optional    | Required               | Where applicable | Yes           |
| Transaction        | Required       | No          | Required               | Where applicable | Yes           |
| Junction           | No             | No          | Required (or via join) | Where applicable | Optional      |
| Audit              | No             | No          | As in source           | —                | N/A           |
| Config / Reference | No             | No          | As needed              | —                | Optional      |
| Module settings    | No             | No          | Required               | Optional         | Yes           |

**Index naming:** `idx_{core}_{entity}_org` on `organization_id`; `idx_{core}_{entity}_site` partial on `site_id WHERE site_id IS NOT NULL`; index every FK column used in joins. Unique constraints should be explicitly named.

**Soft delete:** Add partial unique index excluding soft-deleted rows if uniqueness is required on active rows. App queries: `.is('deleted_at', null)`.

**Human-readable IDs:** Use module-specific prefix + sequence or generation function; optional trigger for auto-fill. See `.cursor/rules/database-patterns.mdc` for full pattern.

**Module settings:** Table `{core}_module_settings` (key, value, organization\_id, etc.); admin UI at `/{core}/settings`; RLS: view for org users, insert/update for org\_admin only; use `set_updated_at` trigger.

***

## Error Handling Reference

**Error code mapping (Supabase/Postgres):**

| Code     | Meaning           | User-facing message (sanitized)                              |
| -------- | ----------------- | ------------------------------------------------------------ |
| PGRST116 | No rows returned  | "No matching records." or context-specific empty state       |
| 42501    | Permission denied | "You don't have permission to perform this action."          |
| 429      | Rate limit        | Retry with backoff; show "Please try again in a moment."     |
| 23505    | Unique violation  | "A record with this value already exists." or field-specific |
| 23503    | FK violation      | "Cannot complete: related record missing or in use."         |

**Retry logic:** Do not retry permission (42501) or validation errors. Retry network/transient failures with `failureCount < 2` (e.g. in `useQuery` retry option). Use `sanitizeErrorMessage(error)` for all user-facing messages.

***

## UI Component Patterns

**Form layout:** Use `ResponsiveFormLayout` for multi-field forms; columns 1/2/3, spacing sm/md/lg. Form actions: Cancel left, Submit right; disable submit while submitting; use descriptive button labels.

**Page templates:** `OverviewPageWrapper` for module landing pages (supports pull-to-refresh, `refreshQueryKeys`). `MobileTableWrapper` for responsive tables. See `docs/development/UI_UX_STANDARDS.md`.

**Icon sizes:** `icon-xs` (14px) through `icon-lg` (24px); `icon-touch` (44×44px) for icon-only buttons (touch target). See `docs/development/ICON_GUIDE.md`.

**Touch-safe actions:** Actions must be always visible or in a clear control; no hover-only actions. Use `CardActionsMenu` for multiple actions on a card. Native dialogs (`window.prompt`, `confirm`, `alert`) are prohibited; use `Dialog`/`AlertDialog`/toast.

***

## Automation Governance

Per constitution §12:

* **Approval:** High-risk automations (bulk operations, external API writes, financial/clinical side effects) require explicit approval and dry-run testing.
* **Circuit breaker:** After 5 consecutive failures, pause the automation and surface alert; do not retry indefinitely.
* **Logging:** Use `fw_automation_logs` (or equivalent) for automation runs; log run id, status, error message, and timestamp.
* **Rate limits:** Respect external API rate limits; use exponential backoff and queue where appropriate.
* **Dry-run:** Where possible, support a dry-run mode that logs intended actions without executing them.

***

## Authoritative External References (for AI Accuracy)

When implementing CL or PM features, prefer these authoritative sources over training data.

| Category                         | Source                                              | URL                                                                                                                                                          | Specs                      |
| -------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |
| SUD Confidentiality              | 42 CFR Part 2 (eCFR — current)                      | [eCFR 42 CFR Part 2](https://www.ecfr.gov/current/title-42/chapter-I/subchapter-A/part-2)                                                                    | CL-11                      |
| SUD Confidentiality — Final Rule | 2024 Final Rule (compliance deadline: Feb 16, 2026) | [Federal Register 2024-02544](https://www.federalregister.gov/documents/2024/02/16/2024-02544/confidentiality-of-substance-use-disorder-sud-patient-records) | CL-11                      |
| SUD Confidentiality Guidance     | 42 CFR Part 2 HHS Fact Sheet                        | [HHS Fact Sheet](https://www.hhs.gov/hipaa/for-professionals/regulatory-initiatives/fact-sheet-42-cfr-part-2-final-rule/index.html)                          | CL-11                      |
| Prior Auth                       | CMS-0057-F                                          | [CMS-0057-F Final Rule](https://www.cms.gov/cms-interoperability-and-prior-authorization-final-rule-cms-0057-f)                                              | PM-10                      |
| AZ Medicaid                      | AHCCCS AMPM                                         | [AHCCCS AMPM](https://azahcccs.gov/shared/MedicalPolicyManual/)                                                                                              | CL-02 through CL-04, PM-07 |
| AZ BH Billing                    | AHCCCS CBHSG                                        | [AHCCCS Covered BH Services Guide](https://www.azahcccs.gov/PlansProviders/Downloads/MedicalCodingResources/AHCCCSCoveredBHServicesManual.pdf)               | PM-07, PM-08               |
| Accreditation                    | Joint Commission CAMBHC                             | [Joint Commission CAMBHC](https://www.jointcommission.org/en-us/accreditation/behavioral-health-care-and-human-services)                                     | CL-15                      |
| Quality                          | NCQA HEDIS                                          | [NCQA HEDIS Measures](https://www.ncqa.org/hedis/measures/)                                                                                                  | CL-10, CL-15               |
| Outcomes                         | SAMHSA Quality                                      | [SAMHSA Quality Measurement](https://www.samhsa.gov/substance-use/treatment/advancing-quality-measurement-behavioral-health)                                 | CL-10                      |
| Outcomes                         | SAMHSA NOMs                                         | [SAMHSA NOMs](https://www.samhsa.gov/data/faq/samhsas-national-outcomes-measures-noms-collected-mh-cld/)                                                     | CL-10                      |
| Interop                          | HL7 US Core 7.0 (STU7; superseded by STU8)          | [HL7 US Core STU7](https://hl7.org/fhir/us/core/STU7/)                                                                                                       | CL-16                      |
| BH FHIR                          | US BH Profiles IG                                   | [US Behavioral Health Profiles IG](https://build.fhir.org/ig/HL7/us-behavioral-health-profiles/)                                                             | CL-16                      |
| Prior Auth FHIR                  | Da Vinci PAS STU 2.1                                | [Da Vinci PAS STU2.1](https://hl7.org/fhir/us/davinci-pas/STU2.1/)                                                                                           | PM-10                      |
| Prior Auth FHIR                  | Da Vinci CRD STU 2.0.1                              | [Da Vinci CRD STU2.0.1](https://hl7.org/fhir/us/davinci-crd/STU2.0.1/)                                                                                       | PM-10                      |
| Prior Auth FHIR                  | Da Vinci DTR STU 2.0.1                              | [Da Vinci DTR STU2](https://hl7.org/fhir/us/davinci-dtr/STU2/)                                                                                               | PM-10                      |
| Suicide Risk                     | Columbia C-SSRS                                     | [Columbia C-SSRS](https://cssrs.columbia.edu/)                                                                                                               | CL-07                      |
| Depression                       | PHQ Screeners                                       | [PHQ Screeners](https://www.phqscreeners.com/)                                                                                                               | CL-02, CL-07               |
| SUD LOC                          | ASAM Criteria                                       | [ASAM Criteria](https://www.asam.org/asam-criteria)                                                                                                          | CL-02                      |

Full reference table with all URLs: see root `AGENTS.md` > Authoritative External References.
