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

# AGENTS — AI Quick Reference

> Always-loaded quick reference for AI agents (Claude Code, Cursor, Lovable, Copilot). Patterns, decision trees, regulatory checks, and the "AI must never" list.

> **This page is synced from `/AGENTS.md` at the repository root.** Edit the source file — this published copy is regenerated by `npm run docs:sync-canonical`. See the [governance index](/governance/index) for related documents.

# Encore OS Platform - AI Agent Instructions

**Version:** 1.26.1
**Last Updated:** 2026-05-25

> **Purpose:** Concise AI quick-reference. **Hierarchy:** `constitution.md` > `AI_GUIDE.md` > this file > `.cursor/rules/*`. **When documents conflict, `constitution.md` wins.** Document versions: [docs/VERSIONS.md](/VERSIONS).

***

## Agent Bootstrap (Scoped Reading)

This file is auto-loaded as a project rule. Use task-scoped reading to keep context focused and avoid loading unrelated documentation.

### Minimum required context

| Task type                              | Read first                                                                                                                                                                                                                                                                                                                       |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Any task                               | This file + `.cursor/rules/constitution.mdc` (already always-applied)                                                                                                                                                                                                                                                            |
| Database / migrations                  | `constitution.md` §5, `.cursor/rules/database-patterns.mdc`, `.cursor/rules/database-migrations.md`                                                                                                                                                                                                                              |
| Security / RLS / PHI                   | `constitution.md` §4, §5.2.9, §5.7; `.cursor/rules/security-patterns.md`, `.cursor/rules/security-rls.md`, `.cursor/rules/security-phi.md`, `.cursor/rules/security-auth.md`                                                                                                                                                     |
| New feature specs                      | `AI_GUIDE.md` (`#decision-trees`, `#spec-review-checklist`), `specs/_templates/SPEC_GUIDE.md`                                                                                                                                                                                                                                    |
| UI / forms / navigation                | `constitution.md` §6.7; `.cursor/rules/form-patterns.md`, `.cursor/rules/form-libraries.md`, `.cursor/rules/form-core.md`, `.cursor/rules/tab-patterns.md`, `.cursor/rules/route-patterns.md`                                                                                                                                    |
| Edge functions                         | `constitution.md` §5.8-§5.9, `.cursor/rules/edge-functions.md`                                                                                                                                                                                                                                                                   |
| Cross-core integration                 | `constitution.md` §1.3, `.cursor/rules/integration-patterns.md`, `docs/architecture/integrations/`                                                                                                                                                                                                                               |
| Testing / verification                 | `constitution.md` §3, `.cursor/rules/testing.md`, `.cursor/rules/pre-flight-checklist.md`                                                                                                                                                                                                                                        |
| Permissions                            | `constitution.md` §4.4, `.cursor/rules/permission-patterns.md`                                                                                                                                                                                                                                                                   |
| Settings / configurability / picklists | `constitution.md` §5.2.3–§5.2.4, `.cursor/rules/tenant-configurability.md`                                                                                                                                                                                                                                                       |
| Regulated CL/PM/HR/RH/GR work          | `.cursor/rules/regulatory-compliance.md` + relevant core `src/cores/{core}/AGENTS.md`                                                                                                                                                                                                                                            |
| ONC / FHIR / interoperability          | `docs/compliance/ONC_CERTIFICATION_GAP_MATRIX.md`, `docs/compliance/ONC_REGULATORY_READINESS_IMPLEMENTATION_PLAN.md`, `.cursor/rules/regulatory-compliance.md`                                                                                                                                                                   |
| Authoring any `docs/` Mintlify page    | **`docs/development/phase2b-authoring-guide.md`** — canonical page template, MDX-safety rules (blank line after every `import`; no raw `<`/`{` in prose; no body H1), `audience: user\|admin` frontmatter, gate-parsed citation format, owner sign-off transform. Scaffold with `npm run docs:gapfill`; never fabricate behavior |

### Core-scoped reading

Before editing a specific area, read the nearest AGENTS file for that scope:

* Platform: `src/platform/AGENTS.md`
* Shared: `src/shared/AGENTS.md`
* Integrations: `src/integrations/AGENTS.md`
* Cores: `src/cores/{hr,fw,rh,fa,gr,fm,lo,it,ce,cl,pm}/AGENTS.md`

***

## Quick Reference (Start Here)

**Pattern index:** [.cursor/rules/quick-reference.mdc](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/quick-reference.mdc)

1. **Tenant filter:** `.eq('organization_id', orgId)` on mutations.
2. **Routes:** `React.lazy(() => import(...))` for route components.
3. **Loading:** `<Skeleton />`; never `return null`.
4. **Queries:** `staleTime: 5m`, `gcTime: 10m` on all `useQuery`.
5. **Errors:** `sanitizeErrorMessage(error)` for user-facing messages.
6. **Auth:** `useCurrentUser`; no ad-hoc `supabase.auth.getUser()`.
7. **Cores:** No direct core-to-core imports; use `@/platform/*` integration.
8. **Public docs:** Keep function-like exported APIs documented; run `npm run docs:comments:audit:changed`.
9. **Jurisdiction:** State Medicaid rules via **PF-96** jurisdiction profiles; never hardcode state-specific values as global constants.
10. **Duplication + visual regression governance:** For duplicated/recreated UI work, run `npm run audit:component-duplication` and perform targeted visual regression checks (Playwright and/or manual browser verification).
11. **Tabs:** Use `ScrollableTabsList` (never `TabsList` with `grid-cols-N` or `flex-wrap`); URL-sync tabs with `useTabUrlState` from `@/platform/tabs`; use `<TabBadge>` for counts; pass `aria-label` on every `TabsList`. See [.cursor/rules/tab-patterns.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/tab-patterns.md) and [docs/development/UI\_UX\_STANDARDS.md](/development/UI_UX_STANDARDS) § Tabs.
12. **Charts use the chart palette:** Series colors MUST be `hsl(var(--chart-N))` (N = 1-8) — never hex literals or hardcoded HSL strings — so charts adapt to dark mode and respect tenant rebranding. Module identity colors (`--module-{cl,fa,hr,...}`) are for nav/widget chrome only, not data series. See [docs/development/SEMANTIC\_COLORS.md § Chart Palette](/development/SEMANTIC_COLORS#chart-palette).
13. **Tenant-customizable surfaces use semantic tokens:** Anything a tenant might rebrand (page chrome, CTAs, status badges, dialog overlays, skeletons) MUST use semantic tokens (`bg-primary`, `bg-card-elevated`, `bg-[hsl(var(--overlay-scrim))]`, etc.) so PF-95 overrides and dark mode take effect. Do not pair `bg-info` with `text-primary-foreground` — use `text-info-foreground` (mode-aware). See [docs/development/SEMANTIC\_COLORS.md § Token Catalog Reference](/development/SEMANTIC_COLORS#token-catalog-reference) and the [PF-95 Mapping Table](/development/SEMANTIC_COLORS#tenant-theming-pf-95-mapping-table).
14. **Breadcrumbs:** Detail / edit pages MUST set a dynamic trailing crumb via `useEntityBreadcrumb(data, fn)` from `@/shared/lib/hooks/useEntityBreadcrumb` (or `useBreadcrumbLabel(label)` when the page does not fetch the entity itself). New `<Route>`s MUST add a Title-Case label to `BASE_ROUTE_LABELS` in `src/platform/navigation/route-labels.ts`. Pages MUST NOT import `@/shared/ui/breadcrumb` primitives directly. Enforced by `npm run audit:routes-navigation` and `npm run audit:breadcrumb-coverage` (both blocking under `validate:governance`). Full guide: [`docs/development/breadcrumb-implementation-guide.md`](/development/breadcrumb-implementation-guide).
15. **Mobile + gestures (PF-37):** Use `useIsMobile()` from `@/shared/lib/hooks/use-mobile` for the 768 px breakpoint (do **not** use `useMediaQuery` for it). Mobile-only components live under `src/cores/{core}/components/mobile/`; mobile variants of an existing component may colocate as `<Name>.mobile.tsx`. New file names use **Sheet** (not Drawer/Modal). For swipeable list rows use `SwipeableCardShell` from `@/platform/gestures`; do not implement custom gesture logic—use the shared `SwipeableCardShell` from `@/platform/gestures`; lightweight wrappers that only compose `SwipeableCardShell` to define actions/props (e.g., `<Something>Swipeable.tsx`) are acceptable. For core-level bottom navs use `BottomTabBar` from `@/platform/navigation/components/BottomTabBar` (do **not** copy CE's `MobileBottomNav`). Touch targets >= 44 x 44 px; pad fixed surfaces with `--safe-area-inset-*` CSS vars from `index.css`. All Phase-1 gesture hooks honor `prefers-reduced-motion` automatically. Full guides: [`docs/development/mobile-gesture-guide.md`](/development/mobile-gesture-guide) and [`docs/development/mobile-navigation-guide.md`](/development/mobile-navigation-guide).
16. **Tenant configurability & picklists:** Before hardcoding defaults, thresholds, option lists, or workflow toggles, apply the decision tree in [.cursor/rules/tenant-configurability.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/tenant-configurability.md). Use `{core}_module_settings` for org-configurable values (constitution §5.2.3), **PF-15 picklists** for user-managed option lists that vary by organization (§5.2.4), **PF-96 jurisdiction profiles** for state/Medicaid-variable rules, and **PF-45 feature flags** for rollout toggles. When defining status fields, categories, or dropdown options in a spec, evaluate whether they should be PF-15 picklists rather than `CHECK` constraints. Run `audit-tenant-configurability --core {core}` to find existing hardcoded values. See also [SPEC\_TEMPLATE.md](https://github.com/Encore-OS/encoreos/blob/development/specs/_templates/SPEC_TEMPLATE.md) § Settings Considerations and § Enums and Source Types.

***

## Landmines (Non-Discoverable)

* \[2026-05] Install with `npm ci --legacy-peer-deps`; peer dependency resolution can fail with plain `npm ci`.
* \[2026-05] `npm run build` completes in \~3-4s (production). The lucide-preprocess plugin is dev-only (`apply: 'serve'`); Rolldown tree-shakes the barrel natively in production. `experimental.lazyBarrel` is enabled for all barrel file optimizations.
* \[2026-05] `npm run typecheck` now uses `tsgo` (native Go compiler, \~30s). Use `npm run typecheck:tsc` for the JS-based fallback (slow, needs 16GB heap). First ESLint cold cache run takes \~2.5 min; subsequent runs are \~15s.
* \[2026-06] `npm run lint:ci` uses `--max-warnings 520` (see `package.json`); warning count is intentionally non-zero.
* \[2026-05] RLS helpers MUST use SECURITY DEFINER to avoid recursion when policies read protected tables (`constitution.md` §5.7).
* \[2026-05] PM-19 automation uses `pm_event` trigger config in `trigger_config` and is not registered in `fw_workflow_events`.
* \[2026-05] Prefer scoped reads over loading full `constitution.md` and `AI_GUIDE.md` for every task.
* \[2026-05] USCDI v3 is the ONC baseline as of Jan 1, 2026 (with ASTP/ONC enforcement discretion through Feb 28, 2026). All new FHIR work must target v3, not v1. US Core 6.1.0 is the conformance target.
* \[2026-05] HTI-2 non-finalized provisions ((g)(30)-(g)(33), CDS Hooks, Subscriptions) were officially withdrawn Dec 29, 2025. Do not implement withdrawn criteria.
* \[2026-05] OIG information blocking penalties (\$1M per violation for HIT developers) are live since Sept 2023. Joint HHS-OIG/ASTP enforcement alert issued Sept 4, 2025.
* \[2026-05] DEA Telemedicine Special Registration rule remains in flux; MAT-via-telehealth workflows must use feature flags for future in-person evaluation requirements.
* \[2026-05] EKRA (18 U.S.C. § 220) risk is P0 for Encore due to shared-founder NorthSight relationship — higher probability than ONC or info-blocking enforcement.

***

## Maintenance Workflow

* Run `npm run audit:agent-doc-staleness` monthly; use `:strict` in governance checks.
* Maintain `[YYYY-MM]` date markers for non-discoverable instructions in this file and high-traffic module AGENTS files.
* Use the `agents-memory-updater` subagent quarterly to propose freshness updates, then review manually before merging.
* Process details: `docs/development/AGENT_DOC_MAINTENANCE.md`.

***

## Pattern Library

**Canonical lookup table:** [.cursor/rules/quick-reference.mdc](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/quick-reference.mdc) (always applied in Cursor). **Interactive decision tree:** [.cursor/rules/pattern-decision-tree.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/pattern-decision-tree.md). Detailed rules live under `.cursor/rules/*.md` (e.g. [form-libraries.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/form-libraries.md), [performance-patterns.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/performance-patterns.md)).

**Common mistakes and fixes:** See [.cursor/rules/quick-reference.mdc](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/quick-reference.mdc) for the full table.

***

## Document Map

| Need                                         | Read                                                                | Also See                                                                                                                                                                             |
| -------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Guardrails, architecture, security           | `constitution.md`                                                   | —                                                                                                                                                                                    |
| Spec workflow, implementation process        | `AI_GUIDE.md`                                                       | `docs/development/SPEC_WORKFLOW.md`                                                                                                                                                  |
| **This quick reference**                     | **This file**                                                       | `.cursor/rules/quick-reference.mdc`                                                                                                                                                  |
| Tool-specific setup (Cursor/Claude/GitHub)   | `.cursor/README.md`, `CLAUDE.md`, `.github/copilot-instructions.md` | Then return here for policies                                                                                                                                                        |
| Pattern lookup, code snippets                | `.cursor/rules/quick-reference.mdc`, `.cursor/rules/*.md`           | Core-specific `src/*/AGENTS.md`                                                                                                                                                      |
| MCP                                          | `docs/development/MCP_USAGE.md`                                     | `.cursor/mcp.json` baseline: `github`, `supabase`, `supabase-prod`, `vercel`, `shadcn`, `TestSprite`, `fallow`, `stitch`, `encore-api-surface` (local HTTP; run `npm run mcp:serve`) |
| Cursor Cloud operation                       | `docs/development/CURSOR_CLOUD_WORKFLOW.md`                         | `.agents/skills/cloud-runbook/SKILL.md`                                                                                                                                              |
| EHR/PM context (CL/PM specs)                 | `docs/ehr_pm/ai-context/README.md`                                  | `docs/ehr_pm/research-20260216.md`                                                                                                                                                   |
| Migrations (CLI)                             | `docs/development/supabase/SUPABASE_CLI_LOCAL_WORKFLOW.md`          | `.github/instructions/database.instructions.md`, `docs/development/supabase/2026-05-28-new-projects-operator-runbook.md`                                                             |
| PR review (Bugbot)                           | `.cursor/BUGBOT.md`                                                 | `.github/pull_request_template.md`                                                                                                                                                   |
| Testing, E2E auth                            | `docs/testing/TESTING_SETUP_AND_RUN.md`                             | `.github/instructions/rls-tests.instructions.md`                                                                                                                                     |
| Regulatory compliance decision tree          | `.cursor/rules/regulatory-compliance.md`                            | `docs/compliance/REGULATORY_COMPLIANCE_TRACKER.md`                                                                                                                                   |
| ONC alignment / certification readiness      | `docs/compliance/ONC_CERTIFICATION_GAP_MATRIX.md`                   | `docs/compliance/ONC_CERTIFICATION_ROADMAP.md`, `docs/compliance/ONC_REGULATORY_READINESS_IMPLEMENTATION_PLAN.md`                                                                    |
| Authoritative external references            | `docs/compliance/AUTHORITATIVE_REFERENCES.md`                       | —                                                                                                                                                                                    |
| Pre-flight / pre-commit checklist            | `.cursor/rules/pre-flight-checklist.md`                             | —                                                                                                                                                                                    |
| GitHub Copilot instructions (path-scoped)    | `.github/instructions/*.instructions.md`                            | `.github/copilot-instructions.md`                                                                                                                                                    |
| Specs & deferred features                    | `specs/README.md`                                                   | `specs/DEFERRED_DASHBOARD.md`                                                                                                                                                        |
| Multi-state Medicaid / jurisdiction profiles | `specs/pf/specs/PF-96-medicaid-state-compliance-configuration.md`   | `specs/cross-cutting/MULTI-STATE-COMPLIANCE-ENHANCEMENT-CATALOG.md`                                                                                                                  |

***

## Decision Prioritization

1. Security & regulatory compliance 2. Architecture boundaries 3. Performance 4. User experience 5. Code quality. **Security & compliance > architecture > convenience.**

***

## Architecture Rules (CRITICAL)

* Declare owning core (`HR-xx`, `FA-xx`, etc.). Cores depend on **PF only**; no direct core-to-core imports.
* Cross-core: Platform integration layer (`@/platform/*`), event contracts, API contracts. See `docs/architecture/integrations/`.
* CL is downstream; PM and FA are distinct. References: `PLATFORM_INTEGRATION_LAYERS.md`, `EVENT_CONTRACTS.md`, `API_CONTRACTS.md`.
* **Cross-core FK exception (ADR-002):** By default, cross-core references use UUID columns only. CL tables may reference `pm_encounters.id` via database FK with `ON DELETE RESTRICT`; no other cross-core FK without an ADR. See `docs/architecture/decisions/ADR-002-cl-pm-cross-core-foreign-keys.md`, constitution §5.2.7.
* **Encounter lifecycle:** The encounter (`pm_encounters`) links scheduling, documentation, and billing. CL reads encounter context via `@/platform/scheduling`; shared types in `@/platform/types` (`EncounterContext`, `ChargeContext`, etc.). Diagram: `docs/architecture/integrations/CROSS_CORE_INTEGRATIONS.md` § Encounter Lifecycle.
* **Jurisdiction / state Medicaid compliance** is a **PF** responsibility (**PF-96**). CL, PM, GR consume jurisdiction data via `useJurisdictionProfile()` or `pf_resolve_jurisdiction_profile()` — no new state-specific schema columns (e.g., `ahcccs_*`) without routing through the jurisdiction profile system. Arizona AHCCCS rules are the **default profile**, not universal constants.

***

## What AI Must NEVER Do

* Break tenant isolation or skip mutation org filters.
* Introduce direct core-to-core imports.
* Make schema changes outside migration / declarative workflow (no Dashboard-only DDL).
* Create or apply database migrations via Supabase MCP (`apply_migration`) or the Supabase Dashboard — all schema changes are CLI-only: edit `supabase/schemas/**`, then `supabase db diff` → `supabase db push`.
* Expose internal errors or sensitive data.
* Ship unverified non-trivial changes.
* Rely on stale training-only library knowledge when Context7 is available.
* Write inline `pf_user_role_assignments` queries in edge functions — use `verifyOrgAccess()` or `verifyOrgRole()` from `_shared/auth.ts`.
* Hardcode state Medicaid rules (filing deadlines, assessment elements, billing thresholds, UI labels) as global constants — use **PF-96** jurisdiction profiles. Arizona/AHCCCS is one profile, not the universal default.
* Hardcode organization-configurable option lists (statuses, categories, reasons, types) as `CHECK` constraints or string enums when they should be **PF-15 picklists** — use picklists for any value list that organizations may need to customize. Use `CHECK` constraints only for true system constants (§5.2.4). Apply the decision tree in `.cursor/rules/tenant-configurability.md`.
* Hardcode business defaults, thresholds, intervals, or workflow toggles that should be **`{core}_module_settings`** — review against constitution §5.2.3 before introducing `const DEFAULT_*` or magic numbers. Run `audit-tenant-configurability --core {core}` when unsure.
* Send PHI to AI for compliance checking — use jurisdiction metadata + RAG (GR-06-EN-01), never patient-identifiable content.
* Ship FHIR resources that do not conform to US Core 6.1.0 profiles when CL-16/PM-55 features are in scope.
* Omit DS4P confidentiality codes on any FHIR resource or C-CDA document containing 42 CFR Part 2 SUD data.
* Implement controlled substance e-prescribing without DEA EPCS audit trail (21 CFR 1311).
* Bypass information blocking exception documentation when denying data access requests — OIG CMP penalties up to \$1M per violation are live.
* Implement withdrawn HTI-2 criteria ((g)(30)-(g)(33), CDS Hooks client, Subscriptions client) — these were officially withdrawn Dec 29, 2025.
* Duplicate this list in module docs; module files should link here and add only module-specific constraints.

***

## Other Patterns (Pointers)

* **Multi-state Medicaid compliance (PF-96):** `useJurisdictionProfile(siteId?)` for frontend; `pf_resolve_jurisdiction_profile(p_org_id, p_site_id)` for server-side; `getJurisdictionProfile(supabaseClient, orgId, siteId?)` for edge functions.
* **Whole-person care (CL):** Recovery-oriented, trauma-informed, person-centered, strengths-based (constitution §7.2). SDOH: CL-18; peer support: CL-19. Use PF-70 code library for ICD-10/CPT/HCPCS; never hard-code code lists. `.cursor/rules/cl-patterns.md`.
* **CL/PM integration:** Use `@/platform/clinical` and `@/platform/scheduling`. Shared types: `@/platform/types` (`EncounterContext`, `ChargeContext`, `DiagnosisReference`, etc.).
* **Wizards (PF-41):** Selection rule — data-capture only: FW-31 `MultiPageFormRenderer`; customizable business process: `ModuleWizardRenderer`; hardcoded regulatory/tightly-coupled flow: `WizardShell`; short dialog flow (\<=4 steps): `DialogWizardShell`; parallel navigation: tabs (not a wizard). See `docs/development/WIZARD_DEVELOPMENT_GUIDE.md`, `.cursor/rules/wizard-patterns.md`.
* **Bulk import:** `@/platform/csv`; progress UI; invalidate queries. `.cursor/rules/bulk-import-patterns.md`.
* **UI/UX:** Mobile-first; semantic tokens; `sm:max-w-*` dialogs; breadcrumbs/tabbed hub. Use shared **EmptyState** (`@/shared/components`); use *Dialog*/*Sheet* naming (not *Modal*). `docs/development/UI_UX_STANDARDS.md`.
* **Testing:** Tests for changed behavior; RLS/E2E where critical; run commands before claiming pass. `docs/testing/TESTING_SETUP_AND_RUN.md`.
* **Verifying UI-flow ACs (deep per-AC e2e):** Most HR/UI acceptance criteria are Gherkin UI flows — only a real browser e2e verifies the then-clause; unit/RLS tests prove FRs/isolation, not the UI. Run against the **local** stack (`PLAYWRIGHT_E2E=1 E2E_SUPABASE_OVERRIDE=1 VITE_SUPABASE_URL=http://127.0.0.1:54321 SUPABASE_REST_REACHABLE=true npx playwright test … --project=chromium-authenticated`; `npm run test:e2e:hr` targets dev2), reuse `tests/e2e/fixtures/hr-form-helpers.ts` (role+name targeting), **hand-set** the AC `verified` after a green run (`verify-acs` excludes `tests/e2e/**`), and assert real behaviour + flag drift (never weaken). Skill: `hr-e2e-browser-testing`. Pattern + findings: `docs/superpowers/plans/2026-06-19-hr-wsc-1546-findings.md`. **From an isolated worktree, run the local lane against a per-worktree `wtenv up` stack (54400+) — wtenv-aware + parallel-safe; the proven path for completing UI-bearing specs (docshot tail → `eos-spec signoff`/`complete`).** Recipe + gotchas: `.claude/rules/testing.md` §"wtenv — isolated per-worktree e2e/docshot stack".
* **Specs:** Required for DB changes, cross-core, complex logic. Templates in `specs/_templates/`. Before `create-spec`, run `npm run spec -- precedent --core {core} --topic "{feature}"` and check `specs/{core}/archive/` + `specs/SPEC_STATUS_REGISTRY.md` for prior art. Use `eos-spec next --spec {CORE-##}` for next action; `spec deferred --list` for deferred features; `specs/DEFERRED_DASHBOARD.md` for single view. TASKS files live under `specs/{core}/tasks/`.
* **ONC Alignment (Alignment-Only path):** Build to USCDI v3 + US Core 6.1.0 + SMART v2 + DS4P without formal certification. Certify when trigger fires. Gap matrix: `docs/compliance/ONC_CERTIFICATION_GAP_MATRIX.md`. Implementation plan: `docs/compliance/ONC_REGULATORY_READINESS_IMPLEMENTATION_PLAN.md`. Roadmap: `docs/compliance/ONC_CERTIFICATION_ROADMAP.md`.
* **Contexture/HIE (Arizona):** ADT and CCD exchange via Contexture for AHCCCS DAP/TI 2.0. See PF-108.
* **DEA EPCS (21 CFR 1311):** Required for MAT prescribing; third-party audit via Drummond. See CL-64.
* **DS4P (Part 2 + FHIR):** Confidentiality coding on all SUD data in FHIR/C-CDA; §170.315(b)(7)/(b)(8). See CL-63.
* **HITRUST e1:** Security assessment for hospital/payer procurement signal. See PF-109.
* **EKRA (18 U.S.C. § 220):** Anti-kickback for recovery treatment referrals. P0 legal priority due to NorthSight shared-founder structure. See PF-107.
* **Module-specific:** `src/platform/AGENTS.md`, `src/cores/{core}/AGENTS.md` (HR, FW, RH, FA, GR, FM, LO, IT, CE, CL, PM).

***

## Creating a New Spec (MANDATORY WORKFLOW — all agents)

> **This section applies to Warp (Oz), Cursor, Claude Code, and any AI agent asked to create a new feature specification.**

When the user asks you to **create a new spec** (any phrasing: "write a spec", "draft a spec", "spec out \[feature]", "create a specification for..."), you MUST:

### Step 1 — Read the spec-pipeline skill FIRST

Before writing a single line of spec content, read the full pipeline skill:

```
.agents/skills/spec-pipeline/SKILL.md
```

This is the authoritative source for the mandatory pipeline. Follow it exactly.

### Step 2 — Read the constitution and template

Also read:

* `constitution.md` — the non-negotiable guardrails (§2 Specification-First Delivery is the most relevant, but all sections apply)
* `specs/_templates/SPEC_TEMPLATE.md` — the required spec structure
* `specs/SPEC_STATUS_REGISTRY.md` — to determine the next available spec ID for the target core
* `specs/{core}/specs/` — scan existing specs to avoid duplicating prior art

### Step 3 — Run prior-art check

```
npm run spec -- precedent --core {core} --topic "{feature-name}"
```

Also check `specs/{core}/archive/` and search `specs/SPEC_STATUS_REGISTRY.md` for any archived or superseded specs covering the same ground.

### Step 4 — Execute the full spec pipeline

Follow ALL steps in order as defined in `.agents/skills/spec-pipeline/SKILL.md`:

| Step | Action                                           | Can Skip?                    |
| ---- | ------------------------------------------------ | ---------------------------- |
| 0    | Resolve spec ID and file path                    | No                           |
| 1    | `clarify-spec --auto-accept`                     | No                           |
| 2    | `validate-spec --auto-fix --auto-plan`           | No                           |
| 3    | `spec-reviewer` agent review                     | No                           |
| 3b   | `compliance-reviewer` (CL, PM, HR, RH, GR cores) | No for regulated cores       |
| 4    | `review-ux` (if feature has UI scope)            | Only if `--skip-ux` or no UI |
| 5    | Re-validate                                      | No                           |
| 6    | `validate-plan`                                  | Only if no plan exists       |
| 7    | discuss/CONTEXT (`superpowers:brainstorming`)    | Only if `--skip-discuss`     |
| 8    | `generate-tasks`                                 | No                           |

### Constitutional compliance checklist (verify before finalizing)

* [ ] Spec uses `specs/_templates/SPEC_TEMPLATE.md` structure
* [ ] Both status axes set: `status:` (org lifecycle) and `pipeline_status:` (authoring stage, born `stub`) — orthogonal, never derived from each other ([SPEC\_STATUS\_TAXONOMY.md](/development/SPEC_STATUS_TAXONOMY))
* [ ] Feature ID assigned from `SPEC_STATUS_REGISTRY.md` (format: `{CORE}-##`)
* [ ] Owning core declared; no cross-core imports
* [ ] Business entity tables include: `organization_id`, `custom_fields JSONB`, audit columns, RLS with `WITH CHECK`
* [ ] Permission keys listed (format: `{module}.{entity}.{action}`); seed migration planned
* [ ] Settings analysis table completed (§5.2.3); jurisdiction-scoped values routed to PF-96
* [ ] Integration contracts documented or added to `.intra-core-only.json`
* [ ] Regulated cores (CL/PM/HR/RH/GR): compliance section completed and sign-off obtained
* [ ] Navigation worksheet updated if feature adds routes
* [ ] `SPEC_STATUS_REGISTRY.md` updated with new entry

**NEVER jump straight to writing spec content without reading the skill and constitution first.**

***

## References

* [constitution.md](/governance/canonical/constitution) | [AI\_GUIDE.md](/governance/canonical/ai-guide) | [README.md](https://github.com/Encore-OS/encoreos/blob/development/README.md) | [docs/VERSIONS.md](/VERSIONS)
* [.cursor/rules/quick-reference.mdc](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/quick-reference.mdc) | [.cursor/rules/pattern-decision-tree.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/pattern-decision-tree.md)
* [.cursor/BUGBOT.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/BUGBOT.md) — PR review rules (Bugbot)
* [Documentation Standards](/DOCUMENTATION_STANDARDS) | [Documentation Hierarchy](/DOCUMENTATION_STANDARDS#document-hierarchy)
* **Compliance docs:** [REGULATORY\_COMPLIANCE\_TRACKER.md](/compliance/REGULATORY_COMPLIANCE_TRACKER) (CL/PM) | [FCRA\_TCPA\_COMPLIANCE\_TRACKING.md](/compliance/FCRA_TCPA_COMPLIANCE_TRACKING) (HR) | [ONC\_CERTIFICATION\_ROADMAP.md](/compliance/ONC_CERTIFICATION_ROADMAP) | [PHI\_CLASSIFICATION.md](/compliance/PHI_CLASSIFICATION)
* **Governance:** [.cursor/rules/RULES\_GOVERNANCE.md](https://github.com/Encore-OS/encoreos/blob/development/.cursor/rules/RULES_GOVERNANCE.md) — monthly governance cadence, PR checklist for AI config changes
* **Maintenance:** `docs/development/AGENT_DOC_MAINTENANCE.md` — staleness checks and periodic refresh workflow

**When in doubt: ask, don't guess. Default to the safest interpretation.**

***

## Cursor Cloud specific instructions

### Environment

* **Node.js 24** (`engines` in `package.json`, `.nvmrc` = `24`) and **npm 11.12.1** (via corepack) are required. The `.npmrc` has `legacy-peer-deps=true` so `npm ci` suffices.
* **Cloud VM PATH:** the platform may expose `/exec-daemon/node` (v22) ahead of nvm. Before install/build/dev, prepend Node 24: `export PATH="/home/ubuntu/.nvm/versions/node/v24.16.0/bin:$PATH"` (install with `nvm install 24` once per VM if missing). Verify with `node -v` → `v24.x`.
* **No `.env.local` is needed for the dev server.** Supabase credentials are resolved at build/dev time from `vite.config.ts` static defines (defaults to the `dev` project). Only override with env secrets if pointing at a different Supabase project.
* Test credentials: `TEST_USER_ADMIN_EMAIL` / `TEST_USER_ADMIN_PASSWORD` env vars point to the hosted dev/staging Supabase project. When unset, manual login against the default dev project works with `e2e-staff@northsightrecovery.com` / `StaffTest123!` (see `tests/e2e/fixtures/auth.fixture.ts`). For seeded local users (`admin@test-org-alpha.example` / `password`), use local Supabase — see `.agents/skills/cloud-runbook/SKILL.md` §3.

### Services

| Service         | Command       | Port | Notes                                                                                                                                                         |
| --------------- | ------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Vite Dev Server | `npm run dev` | 8080 | Main frontend; connects to hosted Supabase. Use a **tmux** session for long-running dev (e.g. `vite-dev-server`) so the process survives between agent turns. |

No Docker or local Supabase is needed for frontend development — the app connects to the remote Supabase project via env vars.

### Key commands

See `CLAUDE.md` and `.agents/skills/cloud-runbook/SKILL.md` for the full command reference. Summary:

* **Install:** `npm ci --legacy-peer-deps`
* **Dev server:** `npm run dev` (port 8080)
* **Typecheck:** `npm run typecheck` (uses `tsgo`, \~30s; `typecheck:tsc` for legacy JS-based checker)
* **Lint:** `npm run lint:ci` (pre-existing warnings expected; `--max-warnings 520`, near the ceiling — new warnings can break the gate)
* **Unit tests (no Supabase):** `SKIP_SUPABASE_TESTS=true npm run test:unit`
* **Full validation:** `npm run validate`

### Spec Pipeline (CRITICAL — read before any spec work)

When the user invokes `spec-pipeline`, `/spec-pipeline`, or any variant targeting a spec ID, the agent **MUST**:

1. **Read** `.cursor/commands/specs/spec-pipeline.md` (the authoritative command definition).
2. **Execute ALL 8 steps in order:**
   * Step 0: Resolve spec → Step 1: `clarify-spec` → Step 2: `validate-spec --auto-fix --auto-plan` → Step 3: `spec-reviewer` → Step 3b: `compliance-reviewer` (regulated cores) → Step 4: `review-ux` (if UI scope) → Step 5: Re-validate → Step 6: `validate-plan` → Step 7: discuss/CONTEXT (`superpowers:brainstorming`) → Step 8: `generate-tasks`
3. **NEVER skip directly to `generate-tasks`.** The pipeline produces 5–7 artifacts (refined spec, plan, CONTEXT.md, compliance sign-off, TASKS.md, changelog, open questions). Producing only TASKS.md means the pipeline was not followed.

**Also read:** `.agents/skills/spec-pipeline/SKILL.md` for the full checklist and failure modes.

This is the **#1 most common agent failure mode** — jumping straight to task generation without running validation, review, and compliance steps first.

### Gotchas

* `npm run build` is \~3–5s on a warm cache locally; **cold Cloud builds can take several minutes** (Babel + large chunks). The lucide-preprocess plugin is dev-only; Rolldown handles tree-shaking natively in production builds. NODE\_OPTIONS heap is 4GB (sufficient since Rolldown does heavy lifting in Rust).
* `SKIP_SUPABASE_TESTS=true npm run test:unit` is the fast gate (\~7 min cold). This snapshot had **6 pre-existing failures** in 2 files (10,151 passed); do not treat as an env-setup regression without checking the same commit on CI.
* `npm run typecheck` uses `tsgo` (native Go compiler, \~30s). The JS-based `tsc` is available via `npm run typecheck:tsc` (16GB heap; cold run can take 5+ min). ESLint first run builds cache (\~2.5 min); warm runs are \~15s.
* The `lint:ci` target uses `--max-warnings 520` (per `package.json`); the count sits near the ceiling (pre-existing warnings), leaving little headroom before the gate fails.
* The `jbloom@northsightrecovery.com` test account (`TEST_USER_ADMIN_EMAIL` / `TEST_USER_ADMIN_PASSWORD`) authenticates against the **dev** Supabase project (the default target). For a clean test environment with seed data (employees, beds, etc.), use `admin@test-org-alpha.example` / `password` against local Supabase.
* `corepack use npm@11.12.1` may trigger a full install and create a `corepack` entry in `package.json` — this is expected. Prefer `corepack enable && corepack prepare npm@11.12.1 --activate` in scripts to avoid modifying `package.json`.

***

## Multi-Agent Sandbox (encoreos GB10 host — opt-in)

Host-level isolation tooling on the always-on GB10 box. **Opt-in**; it does not replace the standard worktree workflow. The full host runbook is kept on the GB10 box itself, outside this repo.

* **Hardened devcontainer** (`.devcontainer/`): non-root `node`, `/workspace`-only bind mount (no `~/.ssh`, no agent forwarding), `--cap-drop=ALL` + only `NET_ADMIN`/`NET_RAW`/`SETUID`/`SETGID`, `--gpus=all` (GB10), and a default-deny egress allowlist (`init-firewall.sh`) run at `postStartCommand`. Use `devcontainer up --workspace-folder .` then `devcontainer exec ... bash`. This is the path for `--dangerously-skip-permissions` / GPU agents.
* **Dagger `container-use`** (MCP, user scope): per-agent Dagger container + git branch for CPU coding agents. When operating **inside** a container-use environment: use ONLY environment tools for file/code/shell ops; do NOT use the git CLI via `environment_run_cmd` (environment tools handle git; editing `.git` corrupts the env); and always tell the user to review via `container-use log <env_id>` and `container-use checkout <env_id>`. GPU passthrough is experimental — route GPU agents through the devcontainer instead.

***

## Learned User Preferences

* When implementing an attached plan file, do not edit the plan file itself.
* Entra ID and SSO setup for tenant admins must stay in Encore: Microsoft admin consent in-app, then an optional Microsoft sign-in toggle — no Supabase Dashboard access for customer IT staff.
* When resetting a messy local checkout, preserve only `.env.local` unless asked to keep more; archive or remove nested clones and untracked tool output rather than committing them.

## Learned Workspace Facts

* **eos-spec is the published `@encore-os/eos-spec` package** (exact-pinned devDep) — the in-tree `tools/eos-spec` fork is **retired** (#1831). Drive the spec pipeline via `npm run spec -- <cmd>`, the `eos-spec` bin, or `npx @encore-os/eos-spec <cmd>` (never `tsx tools/eos-spec/...`). `computeStage`/`PIPELINE`/embeddings all live in the package; repo-specific commands (`skill-coverage`, recall ratchet, `surface-hash`) live in `scripts/specs/`. Embedding vectors are at `.eos-spec/data` (gitignored, CI-rebuilt; `npm run spec:embeddings:build` → `eos-spec build-embeddings`). `precedent` takes `--topic <text>` (semantic auto when vectors present), not `--semantic`.
* **Canonical Supabase projects:** **dev2** = `anuwknikgsijbameytzr` (development), **prod2** = `aximlomrwfuhctxjhrsf` (production). The original `dev`/`prod` projects are **deprecated** — never target them for new live-stack work (execute\_sql, RLS verification, edge-fn checks). Live-verify on dev2 via `begin; … rollback;` with `set local role authenticated`.
* ⚠️ Editing `constitution.md` requires `npm run docs:sync-canonical` afterward (it regenerates the `docs/governance/canonical/constitution.md` mirror); the `docs:sync-canonical:check` gate fails on drift.
* NorthSight Recovery Encore `organization_id`: `b1f22038-94a2-49bd-b5fd-38e04342f8b4`; NorthSight Entra/SSO integration testing targets Supabase **dev2** (`anuwknikgsijbameytzr`).
* NorthSight Entra tenant ID: `894b815c-98a1-4651-b498-ce5122f9bfe6`; shared app registration client ID: `e02d8a52-e3e3-4569-a884-b7352619ec01` (details in `docs/integrations/ENTRA_ID_OVERVIEW.md`).
* Encore Entra Graph permission catalog: 18 scopes in `src/platform/integrations/entra-permissions.ts` (`GRAPH_PERMISSIONS`); UI permission counts should reflect live granted roles against that catalog.
* `eos-spec` discovers CONTEXT files only at `specs/{core}/specs/{ID}-CONTEXT.md`; mirror there if authored under `specs/{core}/context/`.
* Do not commit `.cursor/hooks/state/*` (continual-learning and other local IDE state).
* PF-111 Supabase edge AI calls authenticate to Vercel AI Gateway via the `AI_GATEWAY_API_KEY` Edge Function secret — not `VERCEL_OIDC_TOKEN` (OIDC applies only on Vercel-hosted runtimes).
