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

# Platform Integration Layers

> Version: 2.3.1 Last Updated: 2026-03-29 Constitution Reference: Section 1.3 (Integration Patterns - Pattern 1)

**Version:** 2.3.1\
**Last Updated:** 2026-03-29\
**Constitution Reference:** Section 1.3 (Integration Patterns - Pattern 1)

> **📌 For latest layer status, see `src/platform/AGENTS.md`** — This document provides detailed integration patterns; `src/platform/AGENTS.md` has the authoritative implementation status.

Platform Integration Layer provides shared capabilities that multiple cores need without violating architectural boundaries. All cores import from `/src/platform/` instead of directly from other cores.

***

## Quick Reference

| Layer       | Location                                           | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Status                                                                                                                                                                                        |
| ----------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| PF-08       | `@/platform/forms`                                 | Form integration                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | ✅ Complete                                                                                                                                                                                    |
| PF-15       | `@/platform/data-lookup`                           | Data lookup                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | ✅ Complete                                                                                                                                                                                    |
| PF-16       | `@/platform/custom-fields`                         | Custom fields                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | ✅ Complete                                                                                                                                                                                    |
| PF-17       | `@/platform/field-config`                          | Field configuration                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | ✅ Complete                                                                                                                                                                                    |
| PF-56       | `@/platform/upload`                                | File uploads                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | ✅ Complete                                                                                                                                                                                    |
| -           | `@/platform/csv`                                   | CSV parsing for bulk imports                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | ✅ Complete                                                                                                                                                                                    |
| CE-03       | `@/platform/telephony`                             | Telephony/calls                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | ✅ Complete                                                                                                                                                                                    |
| -           | `@/platform/workforce`                             | Workforce integration                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | ✅ Complete                                                                                                                                                                                    |
| -           | `@/platform/workflow`                              | Workflow canvas                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | ✅ Complete (GR-11)                                                                                                                                                                            |
| PF-73       | `@/platform/workflow`                              | Swim lane diagrams (canvas, CRUD, export, GR-11/GR-01 generation)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | ✅ Complete (Phase 1); Phase 2 📝 Planned                                                                                                                                                      |
| PF-65       | `@/platform/gusto`                                 | Gusto Embedded Payroll (SDK + proxy)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | ✅ Complete                                                                                                                                                                                    |
| PF-66       | `@/platform/realtime`                              | Realtime subscriptions, broadcast, presence                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            | ✅ Complete                                                                                                                                                                                    |
| PF-37       | `@/platform/gestures`                              | Mobile gesture system (swipe-to-dismiss, swipe-actions, pull-to-refresh, edge-swipe, pinch-to-zoom, multi-touch, custom gestures); `useGestureIntegration` ties preferences/haptics/analytics into all hooks; `SwipeableCardShell`, `SwipeableSheet` shared primitives. The navigation primitive `@/platform/navigation/components/BottomTabBar` is exported by the navigation module, not gestures. See [Mobile Gesture Guide v2.0.0](../../development/mobile-gesture-guide.md) and [PF-37 Phase 2/3 Integration](./phase-2-3-integration-pf-37.md). | ✅ Complete (Phase 1+2+3)                                                                                                                                                                      |
| PF-67       | `@/platform/messaging`                             | Internal real-time messaging, record threads                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | 📝 Planned                                                                                                                                                                                    |
| PF-70       | `@/platform/codes`                                 | Medical terminology & code libraries (ICD-10-CM, CPT, HCPCS, modifiers, validation)                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | 📝 Planned                                                                                                                                                                                    |
| PF-43       | `@/platform/quota`                                 | Tenant-scoped resource quotas (storage, API, users, workflows); `useResourceQuota` hook, `pf_check_resource_quota`; see [PF-43 Integration](./tenant-resource-quotas-integration.md)                                                                                                                                                                                                                                                                                                                                                                   | 📝 Planned                                                                                                                                                                                    |
| PF-51       | `@/platform/cache`                                 | Caching (query results, config, reference data); tenant-scoped keys                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | ✅ Complete                                                                                                                                                                                    |
| CL (EHR/PM) | `@/platform/clinical`                              | CL Consent Service ✅; Patient Context, Billing Adapter, Document Export 📝                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | 🟡 In Progress                                                                                                                                                                                |
| CL/PM       | `@/platform/scheduling`                            | Encounter/appointment context for CL-04, CL-14, CL-24                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | 📝 Planned (contract in README)                                                                                                                                                               |
| CL/PM       | `@/platform/types`                                 | Shared EncounterContext, ChargeContext, DiagnosisReference, etc.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | ✅ Implemented                                                                                                                                                                                 |
| PF-84       | `@/platform/calendar`                              | Business calendar service (hooks, business day utils, CalendarPicker, holiday templates/CSV import)                                                                                                                                                                                                                                                                                                                                                                                                                                                    | ✅ Complete (Phase 1)                                                                                                                                                                          |
| PF-85       | `@/cores/fw/pages/AutomationObservabilityPage.tsx` | Automation observability dashboard (real-time metrics, SLA compliance, alert thresholds)                                                                                                                                                                                                                                                                                                                                                                                                                                                               | ⚠️ Architectural Debt: Currently in FW core; should be moved to `@/platform/automation-observability` per spec. See [PF-85 Integration](./automation-observability-dashboard-integration.md). |
| PF-86       | `@/platform/email-signatures`                      | Organization/user email signatures (HTML/text, variable substitution, compliance disclaimers)                                                                                                                                                                                                                                                                                                                                                                                                                                                          | ✅ Complete                                                                                                                                                                                    |
| PF-96       | `@/platform/jurisdiction`                          | Jurisdiction profile system (state Medicaid compliance rules); `useJurisdictionProfile()` hook, `useClinicalRules()`, `useBillingRules()`, `useComplianceRules()` convenience hooks; `pf_resolve_jurisdiction_profile()` RPC                                                                                                                                                                                                                                                                                                                           | 📝 Planned                                                                                                                                                                                    |

## Overview

Platform Integration Layers follow **Pattern 1** from the architecture constitution. They provide:

* Reusable UI components
* Shared hooks and utilities
* Cross-core data access without direct dependencies
* Stable API contracts

**Prohibited:** Direct imports between cores (e.g., `import { x } from '@/cores/fa/...'` inside RH)

**Cross-Core FK Exception:** By default, cross-core table references use UUID columns with no database FK. For the CL-PM encounter entity only, a scoped exception allows a database FK from CL tables to `pm_encounters.id` with `ON DELETE RESTRICT`. See [ADR-002](../decisions/ADR-002-cl-pm-cross-core-foreign-keys.md) and constitution §1.2, §5.2.7.

***

## Status Legend

* ✅ **Complete** - Fully implemented and production-ready
* 🟡 **In Progress** - Partially implemented
* 📝 **Planned** - Specified but not yet implemented
* ❌ **Deprecated** - No longer recommended

***

## PF-08: Forms Integration Layer

**Location:** `/src/platform/forms/`\
**Status:** ✅ Complete\
**Implemented:** 2025-11-23\
**Version:** v1.1.0 (added form ownership)\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Components
export { FormEmbed } from './FormEmbed';
export { FormSelector } from './FormSelector';
export { FormRenderer } from './FormRenderer';
export { ModuleFormsPage } from './ModuleFormsPage'; // NEW v1.1.0

// Hooks
export { useFormList } from './useFormList';
export { useFormDefinition } from './useFormDefinition';
export { useFormSubmission } from './useFormSubmission';

// Types
export type { FormMetadata, FormDefinition, FormSubmission, CoreCode } from './types';
```

**Form Ownership (Added v1.1.0):**

* Forms have `owning_core` column to indicate domain ownership
* `useFormList` accepts `owningCore?: CoreCode` filter
* `FormSelector` accepts `owningCore?: CoreCode` prop
* Module-specific pages use `ModuleFormsPage` with core filter

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { FormEmbed, useFormList } from '@/platform/forms';

// Filter forms by owning core
const { forms } = useFormList({ owningCore: 'hr' });

// ❌ WRONG: Direct import from core
import { FormEmbed } from '@/cores/fw/forms';
```

**Module-Specific Forms Pages:**

```typescript theme={null}
// Example: HR Forms Page
import { ModuleFormsPage } from '@/platform/forms';

export default function HRFormsPage() {
  return (
    <ModuleFormsPage 
      owningCore="hr" 
      moduleDisplayName="HR"
      createFormPath="/hr/forms/new"
    />
  );
}
```

**Consumer Cores:**

* RH (Recovery Housing): Resident intake forms (`/rh/forms`)
* HR (Workforce): Onboarding forms (`/hr/forms`)
* GR (Governance): Policy acknowledgment forms (planned)
* FA (Finance): Payment forms (planned)

**Versioning:**

* Current: v1.1.0
* v1.1.0 Changes: Added `owning_core`, `ModuleFormsPage`, core filtering
* Breaking changes require version bump and migration guide

***

## FW-32: External Form Portal Integration

**Location:** `/src/cores/fw/components/portal/`, `/src/cores/fw/pages/`, `/supabase/functions/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-30

**Overview:**
External form portal system enabling public form access for unauthenticated users with spam protection, rate limiting, email verification, branding customization, and consent management.

**Public API:**

```typescript theme={null}
// Admin Components (internal use)
export { PortalConfigPanel } from '@/cores/fw/components/portal';
export { PortalUrlDisplay } from '@/cores/fw/components/portal';
export { PortalBrandingPreview } from '@/cores/fw/components/portal';
export { PortalLogoUpload } from '@/cores/fw/components/portal';
export { PortalQrCode, PortalQrCodeDialog } from '@/cores/fw/components/portal';

// Public Components (no auth required)
export { PortalFormRenderer } from '@/cores/fw/components/portal';
export { CaptchaWidget } from '@/cores/fw/components/portal';
export { SubmissionSuccess } from '@/cores/fw/components/portal';
export { VerificationPending } from '@/cores/fw/components/portal';

// Hooks
export { usePortalConfig } from '@/cores/fw/hooks';
export { usePortalConfigMutation } from '@/cores/fw/hooks';
export { usePortalLogoUpload } from '@/cores/fw/hooks';
export { usePublicPortal } from '@/cores/fw/hooks';
export { usePortalSubmission } from '@/cores/fw/hooks';

// Types
export type { PortalConfig, PortalSubmission, PortalConfigFormValues } from '@/cores/fw/types';
```

**Public Routes:**

| Route              | Component          | Auth | Purpose            |
| ------------------ | ------------------ | ---- | ------------------ |
| `/p/:accessToken`  | `PublicFormPage`   | None | Public form access |
| `/p/verify/:token` | `PortalVerifyPage` | None | Email verification |

**Edge Functions:**

| Function              | Purpose                               | JWT Required |
| --------------------- | ------------------------------------- | ------------ |
| `portal-get-config`   | Fetch form and portal config by token | No           |
| `portal-form-submit`  | Process public submissions            | No           |
| `portal-verify-email` | Verify email tokens                   | No           |

**Storage:**

| Bucket         | Purpose                   | Access                           |
| -------------- | ------------------------- | -------------------------------- |
| `portal-logos` | Organization portal logos | Public read, authenticated write |

**Security Features:**

* reCAPTCHA v3 / hCaptcha integration
* IP-based rate limiting (SHA-256 hashed)
* Honeypot spam detection
* Email verification with expiring tokens
* Consent checkbox requirement

**Usage Example:**

```typescript theme={null}
// Admin: Configure portal in FormEditor
<PortalConfigPanel
  formId={formId}
  organizationId={orgId}
  formName="Application Form"
/>

// Public: Access form via portal URL
// User visits: /p/abc123-token-uuid
// PublicFormPage renders with portal branding
```

**Consumer Features:**

* FW (Forms): Public form submissions
* RH: Resident intake applications
* HR: Job applications, public surveys
* Backward compatibility maintained for 90 days minimum

**Documentation:** See `/src/platform/forms/README.md` and Constitution Section 1.4

***

## Platform Workforce Integration Layer

**Location:** `/src/platform/workforce/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Components
export { EmployeeSelector } from './EmployeeSelector';
export { CredentialBadge } from './CredentialBadge';

// Hooks
export { useEmployeeLookup } from './useEmployeeLookup';
export { useCredentialCheck } from './useCredentialCheck';

// Types
export type {
  EmployeeLookupResult,
  CredentialCheckResult,
  EmployeeSelectorProps,
  CredentialBadgeProps,
} from './types';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { EmployeeSelector, useCredentialCheck } from '@/platform/workforce';

// Lookup and select employees
<EmployeeSelector 
  onSelect={(emp) => assignToCase(emp.id)} 
  requireCredentials={['RN_LICENSE']}
/>

// Verify credentials
const { checkCredentials } = useCredentialCheck();
const result = await checkCredentials(employeeId, 'BLS_CERT');
if (!result.isValid) {
  alert('Missing required credential');
}
```

**Consumer Cores:**

* RH (Recovery Housing): Assign staff to resident cases
* FA (Finance): Select employees for expense approval
* GR (Governance): Verify staff credentials for compliance
* HR-04 (Scheduling): Validate credentials before shift assignment

**Integration guidance:** Provider productivity analytics (CL–HR integration) is specified to use `@/platform/workforce` as the canonical module — see [CL-HR-PROVIDER-PRODUCTIVITY-INTEGRATION.md](CL-HR-PROVIDER-PRODUCTIVITY-INTEGRATION.md). When implemented, `getProviderProductivity()` will live here so the layer hosts multiple workforce metrics (employee lookup, credential check, productivity aggregates).

**CL-40 / CL-19 — Peer supporter identity (no CL→HR DB FK):** `cl_peer_encounters.peer_supporter_id` holds `hr_employees.id` as a logical reference only (constitution default: no cross-core FK outside ADR-002). **Platform:** expose validation through `@/platform/workforce` (employee lookup + credential checks) when creating or editing peer encounters; CL must not import HR core modules. **Database:** migrations SHOULD define `cl_peer_supporter_valid_for_org(p_organization_id UUID, p_peer_supporter_id UUID) RETURNS BOOLEAN` (SECURITY DEFINER, `SET search_path = public`) and use it in `cl_peer_encounters` INSERT/UPDATE with both **USING** (for UPDATE reads) and **WITH CHECK** (for INSERT/UPDATE writes) so tenant and employment invariants hold without a foreign key to `hr_employees`. See [CL-40-clinical-intake-INTEGRATION.md](clinical-intake-integration.md).

**Documentation:** See `/src/platform/workforce/README.md`

***

## PF-15: Data Lookup Integration Layer

**Location:** `/src/platform/data-lookup/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Hooks
export { useTableLookup } from './useTableLookup';

// Configuration
export { 
  LOOKUP_TABLES,
  getLookupTableConfig,
  getAvailableLookupTables,
  isTableAllowed,
} from './lookupTables';

// Types
export type {
  LookupTableConfig,
  LookupFieldSettings,
  LookupOption,
  UseTableLookupOptions,
  UseTableLookupReturn,
} from './types';
```

**Usage Example:**

```typescript theme={null}
import { useTableLookup } from '@/platform/data-lookup';

function MyComponent() {
  const { options, isLoading, error } = useTableLookup({
    table: 'hr_departments',
    organizationId: currentOrgId,
    filters: { is_active: true }
  });

  return (
    <Select>
      {options.map(opt => (
        <SelectItem key={opt.value} value={opt.value}>
          {opt.label}
        </SelectItem>
      ))}
    </Select>
  );
}
```

**Available Lookup Tables:**

* `hr_departments` - Department lookup
* `hr_positions` - Position lookup
* `pf_sites` - Site lookup
* `hr_employees` - Employee lookup (with special handler)

**Consumer Cores:**

* FW (Forms & Workflow): Dynamic form field lookups
* HR (Workforce): Department/position selectors
* RH (Recovery Housing): Site and staff selectors
* All cores: Generic table lookups for dropdowns

**Documentation:** See `/src/platform/data-lookup/README.md`

***

## PF-16: Custom Fields Integration Layer

**Location:** `/src/platform/custom-fields/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Types
export * from './types';

// Hooks
export { useCustomFieldDefinitions } from './hooks/useCustomFieldDefinitions';
export { useCustomFieldDefinition } from './hooks/useCustomFieldDefinition';
export { useCustomFieldMutation } from './hooks/useCustomFieldMutation';
export { useCustomFieldValidation } from './hooks/useCustomFieldValidation';

// Utils
export * from './utils';

// Components
export { CustomFieldDefinitionsTable } from './components/CustomFieldDefinitionsTable';
export { CustomFieldDefinitionForm } from './components/CustomFieldDefinitionForm';
export { CustomFieldInput } from './components/CustomFieldInput';
export { CustomFieldRenderer } from './components/CustomFieldRenderer';
export { CustomFieldsSection } from './components/CustomFieldsSection';
```

**Usage Example:**

```typescript theme={null}
import { CustomFieldsSection } from '@/platform/custom-fields';

<Form>
  {/* Standard fields */}
  <FormField name="first_name" />
  <FormField name="last_name" />
  
  {/* Custom fields section */}
  <CustomFieldsSection
    entityType="hr_employees"
    control={form.control}
    title="Additional Information"
  />
</Form>
```

**Supported Entity Types:**

* `hr_employees`, `hr_positions`, `hr_departments`
* `rh_residents`, `rh_beds`, `rh_facilities`
* `fa_invoices`, `fa_accounts`, `fa_vendors`
* `fw_forms`, `fw_form_submissions`
* `pf_documents`

**Consumer Cores:**

* All cores: Extend entity schemas without code changes
* HR: Employee badge numbers, external IDs
* RH: Resident metadata, case IDs
* FA: Invoice metadata, external references

**Documentation:** See `/src/platform/custom-fields/README.md`

***

## PF-17: Field Configuration Integration Layer

**Location:** `/src/platform/field-config/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Types
export * from './types';

// Field Type Registry
export { 
  FIELD_TYPE_REGISTRY,
  getFWFieldTypes,
  getAllFieldTypes,
  getOptionFieldTypes,
  supportsDataSource,
} from './fieldTypes';

// Hooks
export { useEntityFieldConfigs } from './hooks/useEntityFieldConfigs';
export { useEntityFieldConfig } from './hooks/useEntityFieldConfig';
export { useFieldConfigMutation } from './hooks/useFieldConfigMutation';
export { useFieldVisibility } from './hooks/useFieldVisibility';
export { useConditionalVisibility } from './hooks/useConditionalVisibility';

// Utils
export * from './utils';

// Components
export { FieldConfigTable } from './components/FieldConfigTable';
export { FieldConfigForm } from './components/FieldConfigForm';
export { ConditionalRuleBuilder } from './components/ConditionalRuleBuilder';
export { FieldConfigLayoutEditor } from './components/FieldConfigLayoutEditor';
export { DynamicFormRenderer } from './components/DynamicFormRenderer';
export { ConfigurableForm } from './components/ConfigurableForm';
export { ConfigurableDetailView } from './components/ConfigurableDetailView';
```

**Usage Example:**

```typescript theme={null}
import { ConfigurableForm } from '@/platform/field-config';

// Replace hardcoded forms with configurable forms
<ConfigurableForm
  entityType="hr_employees"
  viewContext="edit_form"
  initialData={employee}
  onSubmit={handleSubmit}
/>
```

**Features:**

* Field visibility control
* Role-based permissions
* Conditional logic
* Section grouping
* Multi-column layouts
* View contexts (create\_form, edit\_form, detail\_view, list\_view)

**Consumer Cores:**

* All cores: Configure field layouts without code changes
* HR: Customize employee forms per organization
* RH: Configure resident forms
* FA: Configure invoice/vendor forms

**Documentation:** See `/src/platform/field-config/README.md`

***

## PF-56: File Upload Integration Layer

**Location:** `/src/platform/upload/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2026-01-09

**Public API:**

```typescript theme={null}
// Service
export { uploadFile, deleteFile } from './service';
export type { UploadOptions, UploadResult, DeleteOptions } from './types';

// Validation
export { validateFile, validateFileType, validateFileSize, getOrganizationUploadSettings } from './validation';

// Image Processing
export { resizeImage, compressImage, generateThumbnail, processImage } from './image-utils';
export type { ImageProcessingOptions, ProcessedImageResult } from './types';

// Hooks
export { useFileUpload } from './hooks';
export type { UseFileUploadOptions, UseFileUploadReturn } from './hooks';
export { useOrganizationUploadSettings } from './hooks';

// Components
export { FileUploadDialog, FileUploadButton, DropZone } from './components';
export type { FileUploadDialogProps, FileUploadButtonProps, DropZoneProps } from './components';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { useFileUpload, FileUploadDialog } from '@/platform/upload';

function DocumentUpload({ organizationId, userId }) {
  const { upload, progress, isLoading, error } = useFileUpload({
    bucket: 'documents',
    organizationId,
    userId,
    entityType: 'documents',
    onSuccess: (result) => console.log('Uploaded:', result.url),
  });

  return (
    <FileUploadDialog
      bucket="documents"
      organizationId={organizationId}
      userId={userId}
      onUploadComplete={(result) => handleUpload(result)}
    />
  );
}

// ❌ WRONG: Direct Supabase storage calls
const { error } = await supabase.storage.from('documents').upload(path, file);
```

**Image Processing Example:**

```typescript theme={null}
import { uploadFile } from '@/platform/upload';

const result = await uploadFile(file, {
  bucket: 'avatars',
  organizationId,
  userId,
  entityType: 'avatars',
  imageOptions: {
    resize: true,
    maxDimensions: { width: 256, height: 256 },
    compress: true,
    quality: 0.9,
    generateThumbnail: true,
    thumbnailSize: { width: 48, height: 48 },
  },
});

console.log(result.url);          // Full-size image URL
console.log(result.thumbnailUrl); // Thumbnail URL (48x48)
```

**Features:**

* Tenant isolation (all paths include `organizationId`)
* File type and size validation from `pf_module_settings`
* Progress tracking with debouncing
* Cancellation support via AbortController
* Image processing (resize, compress, thumbnail)
* WebP support detection with JPEG fallback
* GIF handling preserves animation

**Consumer Cores:**

* PF (Platform): Document uploads, avatar uploads
* FW (Forms): Form submission attachments, portal logos
* HR (Workforce): Employee documents, credentials
* FA (Finance): Invoice attachments, receipts
* RH (Recovery Housing): Resident documents

**Documentation:** See `/src/platform/upload/README.md`

***

## CSV / Bulk Import Utilities

**Location:** `/src/platform/csv/`\
**Status:** ✅ Complete\
**Constitution Reference:** §5.10 (Bulk Import & Data Migration Standards)

Shared CSV parsing and formatting for all bulk import flows (HR employee/credential/oversight, CE contacts, Platform custom objects, FA template lines, etc.). Cores MUST use this module instead of implementing local `parseCsvLine`/`parseCsv`.

**Public API:**

* `parseCsvLine(line: string): string[]` — Parse a single CSV line (quoted fields, escaped quotes)
* `parseCsv(csvText: string): ParseCsvResult` — Parse full CSV (headers, rows, errors)
* `formatCsvValue(value: string): string` — Escape value for CSV output (template generation)
* `BULK_IMPORT_CHUNK_SIZE` — Standard batch size (50) for client-side chunked imports

**Usage:**

```typescript theme={null}
import { parseCsvLine, parseCsv, formatCsvValue, BULK_IMPORT_CHUNK_SIZE } from '@/platform/csv';
const { headers, rows, errors } = parseCsv(csvText);
```

**Consumer Cores:** HR, CE, Platform (data-manager, templates), FA

**Documentation:** See `/src/platform/csv/README.md`, `docs/guides/use-cases/bulk-import-migration.md`

***

## FW-17 → PF-17: Condition Builder Field Discovery

**Location:** `/src/cores/fw/hooks/useConditionAttributes.ts`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-06

**Pattern:** FW-17 Advanced Condition Builder integrates with PF-17 Field Configuration\
**Integration Point:** `useConditionAttributes` hook

**How It Works:**

1. `useConditionAttributes` fetches field configs from PF-17's `pf_entity_field_configs` table
2. `mapFieldConfigToAttribute()` converts PF-17 format to FW-17 `EntityAttribute` format
3. Standard fields from `STANDARD_FIELDS` are merged as fallback
4. Custom fields, picklists, and visibility are respected
5. Event payload fields (from FW-16) are optionally included

**Usage:**

```typescript theme={null}
import { useConditionAttributes } from '@/cores/fw/hooks/useConditionAttributes';

const { attributes, isLoading, search } = useConditionAttributes(organizationId, {
  entityFilter: ['hr_employees'],
  includeCustomFields: true,
  eventPayload: eventSchema, // Optional: for event triggers
});
```

**Files:**

* `src/cores/fw/hooks/useConditionAttributes.ts` - Main hook
* `src/cores/fw/utils/mapFieldConfigToAttribute.ts` - Type mapping utilities

**Consumer Features:**

* FW-17: Advanced Condition Builder attribute browser
* FW-16: Event-based trigger condition configuration

***

## FW-18: Workflow Variables Integration Layer

**Location:** `/src/cores/fw/components/variables/`, `/src/cores/fw/hooks/`, `/supabase/functions/_shared/expressionEvaluator.ts`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-06

**Public API:**

```typescript theme={null}
// Components
export { VariablePanel } from '@/cores/fw/components/variables/VariablePanel';
export { VariablePicker } from '@/cores/fw/components/variables/VariablePicker';
export { ExpressionInput } from '@/cores/fw/components/variables/ExpressionInput';
export { VariableValidationPanel } from '@/cores/fw/components/variables/VariableValidationPanel';
export { VariablePreviewPanel } from '@/cores/fw/components/variables/VariablePreviewPanel';
export { SampleDataProvider } from '@/cores/fw/components/variables/SampleDataProvider';

// Hooks
export { useWorkflowVariables } from '@/cores/fw/hooks/useWorkflowVariables';
export { useVariablePreview } from '@/cores/fw/hooks/useVariablePreview';
export { useExecutionVariables } from '@/cores/fw/hooks/useExecutionVariables';

// Utils
export { workflowVariableValidator } from '@/cores/fw/utils/workflowVariableValidator';
```

**Shared Expression Evaluator:**

```typescript theme={null}
// Edge function shared code
// Location: supabase/functions/_shared/expressionEvaluator.ts

interface ExpressionEvaluator {
  evaluate(expression: string, context: ExecutionContext): ExpressionResult;
  resolveTemplate(template: string, context: ExecutionContext): string;
}
```

**Integration Points:**

1. **FW-17 (Condition Builder):** Expression evaluation for condition values
2. **Automation Executor:** Variable initialization, SetVariable execution, template resolution
3. **Action Config Components:** VariablePicker integration for EmailActionConfig, WebhookActionConfig, RecordActionConfig

**Usage Example:**

```typescript theme={null}
// Using VariablePicker in action configuration
import { VariablePicker } from '@/cores/fw/components/variables/VariablePicker';

<FormField
  control={form.control}
  name="email.subject"
  render={({ field }) => (
    <div className="relative">
      <Input {...field} />
      <VariablePicker
        onInsert={(ref) => {
          const newValue = field.value + `{{${ref}}}`;
          field.onChange(newValue);
        }}
        triggerType={triggerType}
      />
    </div>
  )}
/>
```

**Runtime Variable Flow:**

1. **Initialization:** Variables loaded from `fw_workflow_definitions.variables`
2. **SetVariable Node:** Evaluates expression/literal and stores in context
3. **Template Resolution:** `{{variable}}` placeholders resolved in action configs
4. **Persistence:** Final variable state saved to `fw_automation_logs.execution_result.variables`

**Consumer Features:**

* Workflow variable definitions (VariablePanel)
* Expression templates with live preview (ExpressionInput)
* FW-19 Data Query: Variable storage for query results

***

## FW-16: Event Publishing Integration Layer

**Location:** `/src/platform/events/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-07

**Overview:**
FW-16 provides event-based workflow triggers, allowing cores to publish domain events that trigger workflows.

**Public API:**

```typescript theme={null}
// Functions
export { publishEvent } from './publishEvent';

// Hooks
export { usePublishEvent } from './usePublishEvent';

// Types
export type { KnownEventName, DomainEventInsert, PublishEventParams } from './types';
```

**Usage Example:**

```typescript theme={null}
import { publishEvent, usePublishEvent } from '@/platform/events';

// Direct function call
await publishEvent({
  event_name: 'hr_employee_hired',
  organization_id: employee.organization_id,
  payload: { employee_id: employee.id, department_id: employee.department_id },
});

// React hook (with loading state)
const { publish, isPublishing } = usePublishEvent();
await publish({
  event_name: 'rh_resident_admitted',
  organization_id: episode.organization_id,
  site_id: episode.site_id,
  payload: { episode_id: episode.id, resident_id: episode.resident_id },
});
```

**Database Tables:**

* `fw_workflow_events` - Global event registry (11 seed events)
* `fw_domain_events` - Organization-scoped event log

**Consumer Cores:**

* HR: Publish employee lifecycle events (hired, terminated)
* RH: Publish resident lifecycle events (admitted, discharged, phase advanced)
* FA: Publish financial events (invoice created, paid, budget approved)
* FW: Publish form submission events

**Consumer Features:**

* FW-16: Event-based workflow triggers
* FW-17: Event payload fields as condition attributes

**Documentation:** See `/src/platform/events/README.md`

***

## FW-33: Form Signature Integration Layer

**Location:** `/src/cores/fw/components/fields/SignatureField.tsx`\
**Status:** 📝 Planned\
**Version:** 1.0.0\
**Spec Reference:** [FW-33 Form Signature Capture](../../../specs/fw/archive/FW-33-form-signature-capture.md)

**Overview:**
FW-33 integrates platform signatures (PF-33) into the form builder as a field type. Forms can include signature fields that leverage the existing `SignatureCanvas` and `useSignature` infrastructure.

**Integration Pattern:**

* FW-33 does NOT create its own signature storage
* Uses `pf_signatures` via Platform Signature Layer (PF-33)
* Creates `fw_form_submission_signatures` junction table to link submissions to signatures

**Planned Public API:**

```typescript theme={null}
// Form Field Component
export { SignatureField } from '@/cores/fw/components/fields/SignatureField';

// Hooks
export { useFormSignature } from '@/cores/fw/hooks/useFormSignature';
export { useSignedPDF } from '@/cores/fw/hooks/useSignedPDF';
```

**Platform Dependencies:**

* `SignatureCanvas` from `@/platform/signatures`
* `useSignature` from `@/platform/signatures`
* `useSignatureRequests` from `@/platform/signatures`

**Edge Functions:**

* `generate-signed-pdf` - Creates PDF with embedded signatures

**Event Integration:**

* Publishes `fw_form_signature_captured` event
* Publishes `fw_signed_document_generated` event

**Consumer Cores:**

* HR: Employee acknowledgment forms, policy signatures
* RH: Resident consent forms, admission agreements
* GR: Policy compliance forms, attestations

***

## FW-29: Workflow Notifications & Alerts

**Location:** `/src/cores/fw/components/notifications/`, `/src/cores/fw/hooks/`, `/supabase/functions/workflow-notification-trigger/`, `/supabase/functions/process-alert-escalations/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-07

**Overview:**
FW-29 provides workflow-level notifications and alerts, integrating with PF-10 Notifications for delivery.

**Public API:**

```typescript theme={null}
// Components
export { WorkflowNotificationRulesEditor } from '@/cores/fw/components/notifications/WorkflowNotificationRulesEditor';
export { AlertRulesManager } from '@/cores/fw/components/notifications/AlertRulesManager';
export { AlertsDashboard } from '@/cores/fw/components/notifications/AlertsDashboard';
export { NotificationPreferencesPanel } from '@/cores/fw/components/notifications/NotificationPreferencesPanel';

// Hooks
export { useWorkflowNotifications } from '@/cores/fw/hooks/useWorkflowNotifications';
export { useWorkflowAlertRules } from '@/cores/fw/hooks/useWorkflowAlertRules';
export { useWorkflowAlerts } from '@/cores/fw/hooks/useWorkflowAlerts';
export { useWorkflowNotificationPreferences } from '@/cores/fw/hooks/useWorkflowNotificationPreferences';
export { useUnreadAlertCount } from '@/cores/fw/hooks/useUnreadAlertCount';
```

**Integration with PF-10:**

* Notifications are created in `pf_notifications` table via edge function
* Uses existing notification delivery infrastructure
* Respects user notification preferences

**Edge Functions:**

* `workflow-notification-trigger`: Called on execution status change, evaluates alert rules
* `process-alert-escalations`: Scheduled function (every 5 minutes) for escalation processing

**Database Tables:**

* `fw_workflow_notification_rules`: Notification rules per workflow
* `fw_workflow_alert_rules`: Alert condition rules
* `fw_workflow_alerts`: Active and historical alerts
* `fw_workflow_notification_preferences`: User preferences

**Consumer Features:**

* Workflow Editor: Notifications tab for configuring rules
* Alerts Dashboard: Centralized view of active alerts
* Settings: User notification preferences

***

## FW-19: Data Query Integration

**Location:** `/src/cores/fw/hooks/`, `/supabase/functions/workflow-query-action/`, `/supabase/functions/workflow-api-action/`\
**Status:** 📝 Planned\
**Version:** 1.0.0\
**Spec:** [FW-19-data-query-integration.md](../../../specs/fw/specs/FW-19-data-query-integration.md)

**Overview:**
FW-19 extends the workflow system with database query capabilities and enhanced API integration.

**Relationship to PF-15 (Data Lookup):**

* FW-19 Query Action extends PF-15's `lookupTables.ts` whitelist pattern
* Uses same organization-scoped query approach
* Adds `fw_query_whitelist` table for org-specific extensions beyond default tables
* Query results stored in FW-18 workflow variables

**Public API (Planned):**

```typescript theme={null}
// Hooks
export { useQueryWhitelist } from '@/cores/fw/hooks/useQueryWhitelist';
export { useApiConnections } from '@/cores/fw/hooks/useApiConnections';
export { useApiConnectionMutation } from '@/cores/fw/hooks/useApiConnectionMutation';

// Components
export { QueryActionConfig } from '@/cores/fw/components/actions/QueryActionConfig';
export { APIActionConfig } from '@/cores/fw/components/actions/APIActionConfig';
export { ConnectionManager } from '@/cores/fw/components/integrations/ConnectionManager';
export { WhitelistManager } from '@/cores/fw/components/integrations/WhitelistManager';
```

**Edge Functions (Planned):**

* `workflow-query-action` - Execute parameterized queries
* `workflow-api-action` - Execute external API calls with auth

**Database Tables:**

* `fw_api_connections` - Stores SFTP/API connection configs
* `fw_query_whitelist` - Organization-specific table whitelist

**Integration Pattern:**

1. Query Action uses PF-15 Data Lookup pattern for table validation
2. Results stored in FW-18 workflow variables
3. API connections stored securely with credential references to vault

**Consumer Features:**

* Query Data action node in workflow builder
* Enhanced API action with auth methods
* Connection management for reusable configs
* Whitelist management for org-specific tables

**Documentation:** See `specs/fw/FW-19-data-query-integration.md`

***

## FW-24: Workflow Testing & Sandbox

**Location:** `/src/cores/fw/hooks/`, `/src/cores/fw/components/testing/`, `/supabase/functions/sandbox-execute/`, `/supabase/functions/test-cases-run/`\
**Status:** 📝 Planned\
**Version:** 1.0.0\
**Spec:** [FW-24-workflow-testing-sandbox.md](../../../specs/fw/archive/FW-24-workflow-testing-sandbox.md)

**Overview:**
FW-24 provides isolated sandbox environment for workflow testing with test data management, automated test cases, and coverage reporting.

**Public API (Planned):**

```typescript theme={null}
// Hooks
export { useSandboxExecution } from '@/cores/fw/hooks/useSandboxExecution';
export { useTestDatasets } from '@/cores/fw/hooks/useTestDatasets';
export { useTestScenarios } from '@/cores/fw/hooks/useTestScenarios';
export { useTestCases } from '@/cores/fw/hooks/useTestCases';
export { useTestCoverage } from '@/cores/fw/hooks/useTestCoverage';

// Components
export { SandboxExecutionPanel } from '@/cores/fw/components/testing/SandboxExecutionPanel';
export { TestDatasetManager } from '@/cores/fw/components/testing/TestDatasetManager';
export { TestCaseEditor } from '@/cores/fw/components/testing/TestCaseEditor';
export { TestCoverageVisualization } from '@/cores/fw/components/testing/TestCoverageVisualization';
```

**Edge Functions:**

* `sandbox-execute`: Execute workflow in isolated sandbox
* `test-datasets-import`: Import test data from CSV/JSON
* `test-cases-run`: Execute test cases with assertions

**Integration Points:**

* PF-01 (Organizations): Tenant scoping for all test data
* PF-02 (RBAC): Permission checks (workflow edit for testing)
* FW-06: Workflow structure for sandbox execution
* FW-16: Mock event triggers for testing
* FW-18: Variable testing and validation

**Database Tables:**

* `fw_test_datasets` - Test data storage
* `fw_test_scenarios` - Scenario definitions
* `fw_test_cases` - Automated test cases
* `fw_sandbox_executions` - Execution history
* `fw_test_coverage` - Coverage metrics

**Consumer Features:**

* Sandbox workflow execution
* Test data import (CSV/JSON)
* Automated test case execution
* Coverage visualization dashboard

***

## FW-22: Workflow Execution Monitoring & Debugging

**Location:** `/src/cores/fw/components/monitoring/`, `/src/cores/fw/hooks/`, `/supabase/functions/workflow-debug-control/`\
**Status:** 📝 Planned\
**Version:** 1.0.0\
**Spec:** [FW-22-workflow-execution-monitoring.md](../../../specs/fw/archive/FW-22-workflow-execution-monitoring.md)

**Overview:**
FW-22 provides comprehensive workflow execution monitoring, debugging, and profiling capabilities.

**Public API (Planned):**

```typescript theme={null}
// Components
export { ExecutionDashboard } from '@/cores/fw/components/monitoring/ExecutionDashboard';
export { ExecutionTrace } from '@/cores/fw/components/monitoring/ExecutionTrace';
export { DebugControls } from '@/cores/fw/components/monitoring/DebugControls';
export { ExecutionReplay } from '@/cores/fw/components/monitoring/ExecutionReplay';
export { ExecutionLogs } from '@/cores/fw/components/monitoring/ExecutionLogs';

// Hooks
export { useExecutionLogs } from '@/cores/fw/hooks/useExecutionLogs';
export { useDebugSession } from '@/cores/fw/hooks/useDebugSession';
export { usePerformanceProfile } from '@/cores/fw/hooks/usePerformanceProfile';
export { useRealtimeExecutions } from '@/cores/fw/hooks/useRealtimeExecutions';
```

**Relationship to Platform Foundation:**

* **PF-01 (Organizations):** Tenant scoping for all monitoring data
* **PF-02 (RBAC):** Permission checks for debug mode (org\_admin, workflow owner)
* **PF-10 (Notifications):** Failed execution alerts via notification system

**Relationship to Supabase Realtime:**

* Realtime enabled for `fw_workflow_executions` for live dashboard updates
* Real-time monitoring of execution status changes
* Sub-second latency for active execution display

**Edge Functions:**

* `workflow-debug-control`: Debug session management (start/pause/resume/step)
* See [API Contracts](./API_CONTRACTS.md#fw-22-workflow-debug-control) for full API spec

**Database Tables:**

* `fw_execution_logs`: Searchable execution logs with context
* `fw_debug_sessions`: Debug session state and step history

**Consumer Features:**

* FW-06: Advanced Workflow Builder - Debug mode integration
* FW-07: Workflow Versioning - Compare executions across versions
* FW-18: Workflow Variables - Variable inspection during debugging

**Usage Example:**

```typescript theme={null}
// Real-time execution monitoring
import { useRealtimeExecutions } from '@/cores/fw/hooks/useRealtimeExecutions';

function ExecutionDashboard({ organizationId }) {
  const { executions, isLoading } = useRealtimeExecutions(organizationId);
  
  return (
    <div>
      {executions.map(exec => (
        <ExecutionCard 
          key={exec.id}
          execution={exec}
          onDebug={() => startDebugSession(exec.id)}
        />
      ))}
    </div>
  );
}

// Debug session management
import { useDebugSession } from '@/cores/fw/hooks/useDebugSession';

function DebugPanel({ executionId }) {
  const { 
    session, 
    start, 
    pause, 
    step, 
    resume, 
    variables 
  } = useDebugSession(executionId);
  
  return (
    <div>
      <DebugControls 
        onPause={pause}
        onStep={step}
        onResume={resume}
        status={session?.status}
      />
      <VariableInspector variables={variables} />
    </div>
  );
}
```

***

## PF-27: Platform AI Integration Layer

**Location:** `/src/platform/ai/`\
**Status:** 🟡 Phase 1 Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-06\
**Spec:** [PF-27-platform-ai.md](../../../specs/pf/specs/PF-27-platform-ai.md)

**Public API:**

```typescript theme={null}
// Components
export { AIAssistantPanel } from './components/AIAssistantPanel';
export { AISuggestionCard } from './components/AISuggestionCard';
export { AILoadingState } from './components/AILoadingState';
export { AIMessageBubble } from './components/AIMessageBubble';

// Hooks
export { useAIChat } from './hooks/useAIChat';
export { useAISuggestions } from './hooks/useAISuggestions';
// PF-62: AI Skills System (extended API)
export { useAISkills } from './hooks/useAISkills';
export { useAISkill } from './hooks/useAISkill';
export { useAISkillChat } from './hooks/useAISkillChat';
export { useCreateAISkill } from './hooks/useCreateAISkill';
export { useUpdateSkillOverride } from './hooks/useUpdateSkillOverride';
export { useModuleDefaultSkill } from './hooks/useModuleDefaultSkill';

// Utils
export { buildPrompt, buildSystemPrompt } from './utils/aiPromptBuilder';

// Types
export type { AIMessage, AIChatOptions, AIModuleContext, AISuggestion } from './types';
// PF-62: AI Skills System (extended types)
export type { AISkill, EffectiveSkill, CreateSkillInput, SkillOverrideInput } from './types';
```

**Edge Functions:**

* `ai-assistant` - Streaming AI chat with module-specific system prompts (OpenRouter)
* `ai-document-analyze` - Document analysis with structured output (OpenRouter, GPT-4o)
* `generate-report-narrative` - Report narrative generation (OpenRouter, GPT-4o)

**AI Provider:**

* **Primary:** OpenRouter (migrated from Lovable AI Gateway in PF-59)
* **Models:** Model selection based on module context:
  * GR, HR → Claude 3.5 Sonnet (compliance/policy)
  * FA, FW, RH, PF → GPT-4o (general/analysis)
  * LO, FM → GPT-4o Mini (fast tasks)

**Integration Points:**

* All cores can import via `@/platform/ai`
* Module context enables specialized AI behavior per core
* Shared aiPromptBuilder creates consistent prompts
* Model selection automatic based on `moduleContext.module`

**Usage Example:**

```typescript theme={null}
import { useAIChat, AIAssistantPanel } from '@/platform/ai';

function MyFeature() {
  const { messages, sendMessage, isLoading, error } = useAIChat({
    moduleContext: { module: 'hr', feature: 'onboarding' }
  });
  
  return <AIAssistantPanel />;
}
```

**Consumer Cores:**

* FW (Forms & Workflow): FW-30 Workflow optimization ✅ Planned (uses `useAIStructuredOutput` for suggestion generation)
* LO (Leadership): Meeting summaries, issue suggestions (planned)
* FA (Finance): Transaction categorization (planned)
* PF (Platform): Report generation (planned)

**Security Considerations:**

* Never send PHI/PII to external AI
* Edge functions handle OPENROUTER\_API\_KEY securely (via Supabase secrets)
* Rate limiting with 429/402 error handling (exponential backoff)
* Module context provides audit trail
* API keys never exposed to client

**PF-62 Extensions (AI Skills System):**

* **Status:** 📝 Planned
* **Version:** v1.1.0 (extends PF-27)
* **Spec:** [PF-62-ai-skills-system.md](../../../specs/pf/specs/PF-62-ai-skills-system.md)
* **New Hooks:** `useAISkills`, `useAISkill`, `useAISkillChat`, `useCreateAISkill`, `useUpdateSkillOverride`, `useModuleDefaultSkill`
* **New Components:** `AISkillsPage`, `AISkillsList`, `SkillConfigurationDialog`
* **Features:**
  * Specialized AI skills (Policy Writer, Risk Analyzer, Compliance Advisor, etc.)
  * Organization-specific skill customization
  * Module default skills
  * Skill-aware AI chat with merged prompts and RAG configuration
* **Dependencies:** PF-59 (AI Provider Migration), PF-60 (RAG Infrastructure), PF-27 (Platform AI)

**Related Specs:**

* `specs/pf/PF-27-platform-ai.md` - Original Platform AI specification
* `specs/pf/PF-59-ai-provider-migration.md` - OpenRouter migration (PF-59)
* `specs/pf/PF-60-rag-infrastructure.md` - RAG Infrastructure (PF-60)
* `specs/pf/PF-62-ai-skills-system.md` - AI Skills System (PF-62)
* `docs/architecture/analysis/AI_INTEGRATION_STRATEGY_2026.md` - Feature roadmap

**Documentation:** See `src/platform/ai/README.md` and `specs/pf/PF-27-platform-ai.md`

**Last Updated:** 2026-01-28 (PF-59 migration, PF-62 planned)

***

## PF-10: Notifications Integration Layer

**Location:** `/src/platform/notifications/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Components
export { NotificationCenter } from './NotificationCenter';
export { NotificationItem } from './NotificationItem';
export { NotificationsPage } from './NotificationsPage';
export { NotificationPreferencesPage } from './NotificationPreferencesPage';
export { NotificationDeliveryStatus } from './components/NotificationDeliveryStatus';

// Hooks
export { useNotifications, useUnreadCount } from './useNotifications';
export { useNotificationMutation } from './useNotificationMutation';
export { useNotificationPreferences } from './useNotificationPreferences';
export { useNotificationDelivery } from './hooks/useNotificationDelivery';
```

**Usage Example:**

```typescript theme={null}
import { useNotifications, useNotificationMutation } from '@/platform/notifications';

// Fetch notifications
const { data: notifications, isLoading } = useNotifications(20);
const { markAsRead, markAllAsRead } = useNotificationMutation();

// Mark notification as read
markAsRead.mutate(notificationId);
```

**Features:**

* Real-time notification delivery
* Multi-channel support (in\_app, email, sms)
* User preferences management
* Unread count tracking
* Notification center UI

**Consumer Cores:**

* All cores: Send notifications to users
* FW: Form submission notifications
* HR: Credential expiration alerts
* FA: Payment and budget alerts
* RH: Resident admission/discharge notifications

**Documentation:** See `/src/platform/notifications/` (README pending)

***

## PF-11: Documents Integration Layer

**Location:** `/src/platform/documents/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Hooks
export { useDocumentUpload } from './useDocumentUpload';
export { useDocumentSearch } from './useDocumentSearch';
export { useDocumentPreview } from './useDocumentPreview';
export { useDocumentVersions } from './useDocumentVersions';
export { useDocumentDownload } from './useDocumentDownload';
export { useDocumentDetail } from './useDocumentDetail';
export { useDocumentMutation } from './useDocumentMutation';
export { useDocumentPermissions } from './useDocumentPermissions';
export { useUserSearch } from './useUserSearch';
export { useDocumentApprovals } from './hooks/useDocumentApprovals';

// Components
export { DocumentLibrary } from './DocumentLibrary';
export { DocumentCard } from './DocumentCard';
export { DocumentUploadDialog } from './DocumentUploadDialog';
export { UploadVersionDialog } from './UploadVersionDialog';
export { DocumentPreview } from './DocumentPreview';
export { DocumentPreviewModal } from './DocumentPreviewModal';
export { ImageViewer } from './ImageViewer';
export { TextViewer } from './TextViewer';
export { DocumentDetailPage } from './DocumentDetailPage';
export { PermissionsManager } from './PermissionsManager';
```

**Usage Example:**

```typescript theme={null}
import { useDocumentUpload, DocumentLibrary } from '@/platform/documents';

// Upload document
const { mutate: uploadDocument } = useDocumentUpload();
uploadDocument({
  file: fileObject,
  title: 'Resident Agreement',
  category: 'legal',
  organizationId: orgId,
});

// Display document library
<DocumentLibrary organizationId={orgId} />
```

**Features:**

* Document upload and storage
* Version management
* Permission-based access control
* Full-text search
* Preview support (images, PDFs, text)
* Category and tag organization

**Consumer Cores:**

* All cores: Store and manage documents
* HR: Employee documents, credentials
* RH: Resident agreements, intake forms
* FA: Vendor contracts, invoices
* GR: Policy documents, training materials

**Documentation:** See `/src/platform/documents/` (README pending)

***

## PF-12: Reports Integration Layer

**Location:** `/src/platform/reports/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-03

**Public API:**

```typescript theme={null}
// Hooks
export { useReportList } from './useReportList';
export { useReportDefinition } from './useReportDefinition';
export { useReportExecution } from './useReportExecution';
export { useReportHistory } from './useReportHistory';
export { useCreateReport, useUpdateReport, useDeleteReport } from './useReportMutation';
export { useReportSchedules } from './hooks/useReportSchedules';
```

**Usage Example:**

```typescript theme={null}
import { useReportList, useReportExecution } from '@/platform/reports';

// List available reports
const { data: reports } = useReportList({ organizationId: orgId });

// Execute report
const { execute, executing, result } = useReportExecution();
await execute({
  reportId: report.id,
  params: { startDate: '2025-01-01', endDate: '2025-12-31' },
  format: 'json'
});
```

**Features:**

* Report definition management
* Parameterized report execution
* Multiple output formats (JSON, CSV, PDF)
* Report scheduling
* Execution history
* Organization and public reports

**Consumer Cores:**

* All cores: Generate and schedule reports
* HR: Employee reports, credential reports
* FA: Financial statements, budget reports
* RH: Census reports, attendance reports
* GR: Compliance reports, training reports

**Documentation:** See `/src/platform/reports/` (README pending)

***

## Versioning Strategy

### Breaking Changes

Breaking changes to platform integration layers MUST:

1. Be documented with version bump
2. Include migration guide for consumers
3. Maintain backward compatibility for 90 days minimum
4. Require explicit approval from technical owner

### Version Format

* **Semantic versioning:** v1.0.0 → v2.0.0 for breaking changes
* **Minor version:** v1.0.0 → v1.1.0 for new features (backward compatible)
* **Patch version:** v1.0.0 → v1.0.1 for bug fixes

***

## Integration Checklist

Before creating a new platform integration layer:

* [ ] Multiple cores need the functionality
* [ ] Functionality is domain-agnostic
* [ ] Public API defined and documented
* [ ] Versioning strategy defined
* [ ] Consumer cores identified
* [ ] Usage examples provided
* [ ] README created in `/src/platform/{layer}/`
* [ ] Added to this document

***

## PF-27: Platform AI Integration Layer

**Location:** `/src/platform/ai/`\
**Status:** ✅ Phase 3 Complete\
**Version:** v1.0.0\
**Last Verified:** 2025-12-08

**Public API:**

```typescript theme={null}
// Components
export { AIAssistantPanel } from './components/AIAssistantPanel';
export { AISuggestionCard } from './components/AISuggestionCard';
export { AILoadingState } from './components/AILoadingState';
export { AIMessageBubble } from './components/AIMessageBubble';
export { AIFeedbackButtons } from './components/AIFeedbackButtons';

// Hooks
export { useAIChat } from './hooks/useAIChat';
export { useAISuggestions } from './hooks/useAISuggestions';
export { useAIModuleEnabled } from './hooks/useAIModuleEnabled';
export { useAIStructuredOutput } from './hooks/useAIStructuredOutput';
export { useAIUsageStats } from './hooks/useAIUsageStats';
export { useAIConversations } from './hooks/useAIConversations';
export { useAIConversation } from './hooks/useAIConversation';
export { useAIFeedback } from './hooks/useAIFeedback';
export { useAIReportNarrative } from './hooks/useAIReportNarrative';

// Utils
export { buildPrompt, buildSystemPrompt } from './utils/aiPromptBuilder';

// Types
export type {
  AIMessage, AIRole, AIChatOptions, AIStreamCallbacks,
  AISuggestion, AIContext, AIPromptConfig, AIModuleContext,
  AIUsageLog, AIUsageStats, PHIDetectionResult, AIStructuredOutputOptions,
} from './types';
```

**Features:**

* Streaming chat via Lovable AI Gateway
* Module-aware context for specialized behavior
* Structured output with Zod validation
* PHI detection security layer
* Conversation persistence
* Prompt feedback system (thumbs up/down)
* Usage analytics per organization

**Consumer Cores:**

* All cores via `@/platform/ai` (see `docs/architecture/analysis/AI_INTEGRATION_STRATEGY_2026.md` for roadmap; not yet authored)
* PF-12 Reports: AI-generated report narratives (complete)
* LO: Meeting summaries (planned)
* FA: Transaction categorization (planned)
* FW-30: Workflow optimization (planned)

**Related Specs:**

* `specs/pf/PF-27-platform-ai.md` - Full specification
* `docs/architecture/analysis/AI_INTEGRATION_STRATEGY_2026.md` - Feature roadmap
* `specs/pf/PF-28-ai-shared-widgets.md` - Reusable AI widgets

**Documentation:** See `/src/platform/ai/README.md`

***

## PF-28: AI Widgets Integration Layer

**Location:** `/src/platform/ai/widgets/`\
**Status:** 📝 Planned\
**Version:** v0.1.0 (Draft)\
**Last Verified:** 2025-12-08

**Planned Widgets:**

```typescript theme={null}
// Phase 1 (Low Complexity)
export { AIQuickAction } from './AIQuickAction';      // Single-click AI action
export { AISummarizer } from './AISummarizer';        // Summarize text content

// Phase 2 (Medium Complexity)
export { AICategorizer } from './AICategorizer';      // Categorize with confidence

// Phase 3 (Higher Complexity)
export { AIDocumentAnalyzer } from './AIDocumentAnalyzer';  // Analyze documents
export { AIAssistantInline } from './AIAssistantInline';    // Compact inline assistant
```

**Dependencies:**

* PF-27 (Platform AI) - All hooks and utilities
* PF-11 (Documents) - For AIDocumentAnalyzer integration

**Consumer Cores:**

* All cores: Composable AI-powered UI components
* HR: Credential classification widget
* FA: Transaction categorization widget
* GR: Policy summarization widget

**Specification:** See `specs/pf/PF-28-ai-shared-widgets.md`

***

## PF-29: Tasks Integration Layer

**Location:** `/src/platform/tasks/`\
**Status:** ✅ Complete\
**Implemented:** 2025-12-17\
**Version:** v1.0.0

**Overview:**
PF-29 provides a unified task system enabling cross-module task management. Tasks can be linked to any source entity (goals, meetings, issues, etc.) through polymorphic source linking.

**Public API:**

```typescript theme={null}
// Hooks
export { useTasks } from './hooks/useTasks';
export { useTask } from './hooks/useTask';
export { useMyTasks } from './hooks/useMyTasks';
export { useTaskMutation } from './hooks/useTaskMutation';
export { useTaskComments } from './hooks/useTaskComments';
export { useTaskCommentMutation } from './hooks/useTaskCommentMutation';

// Components
export { TaskCard } from './components/TaskCard';
export { TaskFormDialog } from './components/TaskFormDialog';
export { TaskList } from './components/TaskList';
export { TaskDashboardWidget } from './components/TaskDashboardWidget';
export { SourceTasksPanel } from './components/SourceTasksPanel';
export { AddTaskButton } from './components/AddTaskButton';
export { TaskCommentThread } from './components/TaskCommentThread';

// Pages
export { MyTasksPage } from './pages/MyTasksPage';
export { TaskDetailPage } from './pages/TaskDetailPage';

// Types
export type {
  Task,
  TaskStatus,
  TaskPriority,
  TaskSourceType,
  TaskFilters,
  TaskFormData,
  TaskComment,
} from './types';
```

**Source Types Supported:**

* `goal` - LO-03 Goals
* `rock` - LO-02 Rocks
* `issue` - LO-07 Issues
* `headline` - LO-05 Headlines
* `meeting` - LO-06 Meetings
* `lo_todo` - Legacy LO-04 Todos (migrated)
* `form` - FW Form submissions
* `resident` - RH Residents
* `employee` - HR Employees
* `work_order` - FM Work orders

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { SourceTasksPanel, useTasks } from '@/platform/tasks';

// Display tasks linked to a goal
<SourceTasksPanel
  sourceType="goal"
  sourceId={goalId}
  title="Goal Tasks"
/>

// Fetch tasks for a source
const { data: tasks } = useTasks({
  organizationId,
  sourceType: 'meeting',
  sourceId: meetingId,
});
```

**Consumer Cores:**

* LO (Leadership OS): Goals, Meetings, Issues, Rocks integration
* RH (Recovery Housing): Resident-linked tasks (planned)
* HR (Workforce): Employee-linked tasks (planned)
* FA (Finance): Financial task tracking (planned)
* FM (Facilities): Work order tasks (planned)

**Database Tables:**

* `pf_tasks` - Main task table with polymorphic source linking
* `pf_task_comments` - Task comments/discussion

**Routes:**

* `/tasks` - My Tasks unified view
* `/tasks/:taskId` - Task detail page

**Documentation:** See `/src/platform/tasks/README.md`

***

## PF-37: Gestures Integration Layer

**Location:** `/src/platform/gestures/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2025-12-24

**Public API:**

```typescript theme={null}
// Hooks
export { useSwipeToDismiss } from './hooks/useSwipeToDismiss';
export { useSwipeActions } from './hooks/useSwipeActions';
export { usePullToRefresh } from './hooks/usePullToRefresh';
export { useEdgeSwipe } from './hooks/useEdgeSwipe';

// Components
export { SwipeableSheet } from './components/SwipeableSheet';
export { SwipeableListItem } from './components/SwipeableListItem';
export { PullToRefresh } from './components/PullToRefresh';

// Constants
export { GESTURE_THRESHOLDS, ANIMATION_CONFIG, ACTION_COLORS } from './constants';

// Types
export type { SwipeAction, SwipeDirection, GestureState } from './types';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { SwipeableListItem, PullToRefresh } from '@/platform/gestures';

// Swipeable list with actions
<SwipeableListItem
  leftActions={[{ id: 'delete', label: 'Delete', colorClass: 'destructive', onClick: handleDelete }]}
>
  <ItemContent />
</SwipeableListItem>

// Pull-to-refresh wrapper
<PullToRefresh onRefresh={async () => await refetch()}>
  <ScrollableList />
</PullToRefresh>
```

**Gesture Patterns:**

* **Swipe-to-Dismiss:** Sheets, dialogs, modals, toasts
* **Swipe-to-Reveal Actions:** List items, notifications, tasks
* **Pull-to-Refresh:** List pages, tables, dashboards
* **Edge Swipe Navigation:** Back navigation on detail pages

**Consumer Cores:**

* PF (Platform): MobileMenuSheet, TaskList
* FW (Workflow): ApprovalInbox
* All cores: List items, refreshable lists

**Accessibility:**

* All gestures have keyboard alternatives (ESC, Delete, Enter)
* WCAG 2.5.1 (Pointer Gestures) compliant
* WCAG 2.5.2 (Pointer Cancellation) compliant

**Documentation:** See `/src/platform/gestures/README.md` and `/docs/development/mobile-gesture-guide.md`

***

## PF-41: Wizards Integration Layer

**Location:** `/src/platform/wizards/`\
**Status:** 🟡 In Progress (Phase 1 Complete)\
**Implemented:** 2025-12-31\
**Version:** v1.0.0 (Phase 1 - Hooks only)

**Public API:**

```typescript theme={null}
// Types
export type {
  WizardTemplate,
  WizardModule,
  WizardType,
  WizardConfig,
  WizardStep,
  ParsedWizardTemplate,
} from './types';

export { DEFAULT_WIZARD_CONFIG } from './types';

// Hooks
export { useWizardTemplates } from './hooks/useWizardTemplates';
export { useWizardTemplateDetail } from './hooks/useWizardTemplateDetail';
export { useWizardTemplateMutation } from './hooks/useWizardTemplateMutation';
export { useActiveWizard } from './hooks/useActiveWizard';

// Components (Phase 2+)
// export { WizardBuilder } from './components/WizardBuilder';
// export { ModuleWizardRenderer } from './components/ModuleWizardRenderer';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { useActiveWizard, useWizardTemplates } from '@/platform/wizards';

// Get the active wizard for HR onboarding
const { data: wizard } = useActiveWizard({
  module: 'hr',
  wizardType: 'onboarding',
});

// List all wizard templates
const { data: templates } = useWizardTemplates({ module: 'hr' });

// ❌ WRONG: Direct database queries
const { data } = supabase.from('pf_wizard_templates').select('*');
```

**System vs Org Templates:**

* System templates (`is_template=true`): Platform defaults, read-only via UI
* Org templates (`is_template=false`): Customized per organization
* `useActiveWizard` resolves preference: org template > system template

**Permissions:**

| Permission          | Description                |
| ------------------- | -------------------------- |
| `pf.wizards.admin`  | Full administrative access |
| `pf.wizards.create` | Create new templates       |
| `pf.wizards.edit`   | Edit existing templates    |
| `pf.wizards.view`   | View templates (read-only) |
| `pf.wizards.clone`  | Clone templates            |

**Consumer Cores:**

* HR (Workforce): Employee onboarding wizards
* RH (Recovery Housing): Resident admission wizards
* FA (Finance): Setup wizards
* All cores: Module-specific configuration wizards

**Documentation:** See `/src/platform/wizards/README.md`

***

## PF-51: Caching Layer Integration Layer

**Location:** `/src/platform/cache/`\
**Status:** ✅ Complete — 2026-03-05\
**Spec:** [PF-51](../../../specs/pf/specs/PF-51-caching-layer-strategy.md)\
**Integration Doc:** [PF-51 Integration](./caching-layer-integration.md)

**Purpose:** Centralized, tenant-scoped caching for query results, configuration, and reference data. Cache keys use format `org-{orgId}:{namespace}:{key}`; all cores consume via `@/platform/cache`. No database tables; in-memory only for Phase 1.

**Public API (planned):**

* `cacheService`: `get`, `set`, `delete`, `clear`, `invalidate(pattern)`
* `useCachedQuery`: TanStack Query–backed cached query hook

**Consumer Cores:** All cores (via Platform Integration Layer).

**Documentation:** See [PF-51 Specification](../../../specs/pf/specs/PF-51-caching-layer-strategy.md) and [PF-51 Integration](./caching-layer-integration.md).

***

## PF-54: Formatting Utilities Integration Layer

**Location:** `/src/platform/formatting/`\
**Status:** 📝 Planned\
**Spec:** [PF-54](../../../specs/pf/specs/PF-54-formatting-utilities.md)\
**Last Verified:** 2026-01-07

**Public API:**

```typescript theme={null}
// Formatting Utilities
export { formatCurrency } from './utils';
export { formatDate, formatDateTime, formatTime } from './utils';
export { formatNumber } from './utils';
export { formatPercent } from './utils';
export { formatPhone } from './utils';

// Hooks
export { useFormattingPreferences } from './hooks';

// Components
export { FormattedCurrency } from './components';
export { FormattedDate } from './components';
export { FormattedNumber } from './components';

// Types
export type {
  CurrencyFormatOptions,
  NumberFormatOptions,
} from './types';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { 
  formatCurrency, 
  formatDate, 
  useFormattingPreferences 
} from '@/platform/formatting';

// Use with organization preferences
const { currency, locale, dateFormat } = useFormattingPreferences();
const formattedAmount = formatCurrency(1234.56, { currency, locale });
const formattedDate = formatDate(new Date(), dateFormat, locale);

// Use components
import { FormattedCurrency, FormattedDate } from '@/platform/formatting';

<FormattedCurrency value={1234.56} />
<FormattedDate value={new Date()} />
```

**Formatting Functions:**

* **Currency:** `formatCurrency(amount, options?)` - Locale-aware currency formatting
* **Date:** `formatDate(date, format?, locale?)` - Date formatting with custom formats
* **DateTime:** `formatDateTime(date, format?, locale?)` - Date and time formatting
* **Time:** `formatTime(date, format?, locale?)` - Time-only formatting
* **Number:** `formatNumber(value, options?)` - Locale-aware number formatting
* **Percentage:** `formatPercent(value, decimals?, locale?)` - Percentage formatting
* **Phone:** `formatPhone(phone, format?)` - Phone number formatting (US/international)

**Organization Preferences:**

* Currency code: `pf_module_settings.formatting_currency_code` (default: 'USD')
* Date format: `pf_module_settings.formatting_date_format` (default: 'MM/DD/YYYY')
* Locale: `pf_module_settings.formatting_locale` (default: 'en-US')
* Number decimals: `pf_module_settings.formatting_number_decimals` (default: 2)

**Consumer Cores:**

* All cores (HR, FA, RH, GR, FM, FW, LO, IT) will use formatting utilities
* Replaces duplicate formatting implementations across 8+ locations

**Migration Strategy:**

* Phase 1: Create centralized utilities
* Phase 2: Add organization preferences
* Phase 3: Create formatting components
* Phase 4: Migrate existing code (remove duplicates)

**Documentation:** See [PF-54 Specification](../../../specs/pf/specs/PF-54-formatting-utilities.md)

***

## PF-56: File Upload Framework Integration Layer

**Location:** `/src/platform/upload/`\
**Status:** 📝 Planned\
**Version:** 1.0.0 (planned)\
**Last Verified:** 2026-01-08

**Overview:**
Centralized file upload framework providing consistent upload functionality across all modules. Eliminates duplication across 4+ locations and ensures tenant isolation, file validation, progress tracking, and error handling.

**Public API:**

```typescript theme={null}
// Service
export { uploadFile, deleteFile } from './service';
export type { UploadOptions, UploadResult, UploadProgress, UploadError } from './service';

// Hooks
export { useFileUpload } from './hooks';
export { useOrganizationUploadSettings } from './hooks';

// Components
export { FileUploadDialog } from './components/FileUploadDialog';
export { FileUploadButton } from './components/FileUploadButton';
export { DropZone } from './components/DropZone';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { useFileUpload, FileUploadDialog } from '@/platform/upload';

// Use upload hook
const { upload, progress, isLoading, error } = useFileUpload({
  bucket: 'pf-documents',
  organizationId: orgId,
  userId: userId,
});

// Upload file
const result = await upload(file);

// Use upload dialog
<FileUploadDialog
  open={open}
  onClose={() => setOpen(false)}
  onUpload={(result) => handleUpload(result)}
  bucket="pf-documents"
  acceptedTypes={['image/jpeg', 'image/png', 'application/pdf']}
  maxSizeMb={25}
/>

// ❌ WRONG: Direct implementation or duplicate code
// Don't create custom upload logic in modules
```

**Features:**

* **Tenant Isolation:** All uploads scoped by `organizationId` in path
* **File Validation:** Type and size validation (configurable per organization)
* **Progress Tracking:** Real-time upload progress (0-100%, speed calculation)
* **Error Handling:** Structured error codes, retry logic (3 attempts for network errors)
* **Image Processing:** Resize, compression, thumbnail generation (optional)
* **Upload Cancellation:** Support for AbortSignal

**Storage Buckets (from PF-11):**

* `pf-avatars` - User profile avatars (public)
* `pf-documents` - General documents (private)
* `fw-submission-attachments` - Form submission files (private)

**Path Convention:**

```
{bucket}/{organization_id}/{entity_type}/{entity_id}/{filename}
```

**Settings (pf\_module\_settings):**

* `max_upload_size_mb` - Maximum file upload size (default: 25MB, range: 1-100MB)
* `allowed_file_types` - Array of allowed MIME types (default: common types)

**Consumer Cores:**

* **FW (Forms & Workflow):** Form attachment uploads
* **HR (Workforce):** Employee document/credential uploads
* **PF (Platform):** Avatar and logo uploads
* **FA (Finance):** Invoice/receipt uploads
* **RH (Recovery Housing):** Resident document uploads

**Migration Strategy:**

* Phase 1: Create centralized upload service
* Phase 2: Create upload components and hooks
* Phase 3: Add image processing (optional)
* Phase 4: Migrate existing upload code (remove duplicates)

**Security:**

* Path-based organization isolation enforced
* Storage bucket RLS policies from PF-11
* File validation before upload
* File name sanitization (prevents path traversal)

**Documentation:** See [PF-56 Specification](../../../specs/pf/specs/PF-56-file-upload-framework.md) and [PF-56 Implementation Plan](../../../specs/pf/plans/PF-56-file-upload-framework-PLAN.md)

***

## PF-57: Search/Filter/Sort/Pagination Framework

**Location:** `/src/platform/search/`, `/src/platform/filter/`, `/src/platform/sort/`, `/src/platform/pagination/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2026-01-08

**Public API:**

```typescript theme={null}
// Search utilities
import { useSearch, escapeILikePattern, buildILikeOrConditions } from '@/platform/search';

// Filter utilities
import { applyFilters, createFilter, createFilterGroup, FilterError } from '@/platform/filter';

// Sort utilities
import { applySorting, createSortConfig, createMultiSortConfig, SortError } from '@/platform/sort';

// Pagination utilities
import { calculatePagination, calculateRange, usePagination, useControlledPagination } from '@/platform/pagination';
```

**Usage Example:**

```typescript theme={null}
import { escapeILikePattern, buildILikeOrConditions } from '@/platform/search';
import { applySorting, createSortConfig } from '@/platform/sort';
import { calculateRange } from '@/platform/pagination';

// Build secure search query
const orConditions = buildILikeOrConditions(['name', 'email'], searchTerm);
query = query.or(orConditions);

// Apply sorting
query = applySorting(query, createSortConfig('created_at', 'desc'));

// Apply pagination
const [from, to] = calculateRange({ page, pageSize, total: 0 });
query = query.range(from, to);
```

**Consumer Cores:**

* All cores (HR, FA, RH, GR, FM, FW, LO, IT)

**Documentation:** See `/src/platform/search/README.md`, `/src/platform/filter/README.md`, `/src/platform/sort/README.md`, `/src/platform/pagination/README.md`

***

## PF-58: Data Table Integration Layer

**Location:** `/src/platform/table-v2/`\
**Status:** ✅ Complete (Phase 2-3-4 Expansion — 2026-03-06)\
**Version:** 2.0.0\
**Last Verified:** 2026-03-06

**Consumer Cores:** IT, FA, HR, PF, RH, GR, LO, FW, FM

**Migration Summary:**

* 25 tables migrated across all cores (100% complete)
* All previously exempted tables now migrated (RawDataTable, ScorecardTable)

**Public API:**

```typescript theme={null}
// Main Component
export { DataTable } from './DataTable';

// Sub-Components (Phase 1)
export { TablePagination } from './components/TablePagination';
export { SortableHeader } from './components/SortableHeader';
export { TableFilters } from './components/TableFilters';
export { BulkActionsBar } from './components/BulkActionsBar';

// Sub-Components (Phase 2)
export { InlineEditCell } from './components/InlineEditCell';
export { ResizableHeader } from './components/ResizableHeader';
export { VirtualizedTableBody } from './components/VirtualizedTableBody';

// Sub-Components (Phase 3)
export { ColumnManagerPanel } from './components/ColumnManagerPanel';
export { DraggableColumnItem } from './components/DraggableColumnItem';
export { ExportMenu } from './components/ExportMenu';

// Sub-Components (Phase 4)
export { GroupedRows, GroupedRowsControls } from './components/GroupedRows';

// Hooks (Phase 1)
export { useDataTable } from './hooks/useDataTable';

// Hooks (Phase 2)
export { useInlineEdit } from './hooks/useInlineEdit';
export { useColumnResize } from './hooks/useColumnResize';
export { useStickyColumn } from './hooks/useStickyColumn';
export { useVirtualizedRows } from './hooks/useVirtualizedRows';

// Hooks (Phase 3)
export { useColumnManager } from './hooks/useColumnManager';
export { useTableExport } from './hooks/useTableExport';

// Hooks (Phase 4)
export { useRowGrouping } from './hooks/useRowGrouping';

// Types
export type {
  Column,
  ColumnType,
  InlineEditType,
  EditOption,
  BulkAction,
  DataTableProps,
  PaginationConfig,
  SortingConfig,
  FilteringConfig,
  SelectionConfig,
  BulkActionsConfig,
  EmptyStateConfig,
  FooterConfig,
  FooterRow,
  FooterColumn,
  AggregateFunction,
  AggregateConfig,
  GroupNode,
  ExportFormat,
  ExportColumn,
} from './types';

// Utilities
export { formatCellValue, sanitizeValue, sanitizeHeader } from './utils';
```

**PF-57 Integration:**

* Uses `FilterGroup` from `@/platform/filter` for filter configuration
* Uses `SortConfig` from `@/platform/sort` for sort configuration
* Uses `applyFilterGroup` for client-side filtering in `useDataTable`
* Uses `escapeILikePattern` from `@/platform/search` for filter input security

**PF-47 Integration (Pending):**

* Temporary `BulkAction<T>` interface defined in `types.ts`
* Will be replaced with `@/platform/bulk-operations` when PF-47 is complete
* See TODO comment in `types.ts` for migration steps

**Usage Example:**

```typescript theme={null}
import { DataTable, useDataTable, type Column } from '@/platform/table-v2';

interface User {
  id: string;
  name: string;
  email: string;
  status: 'active' | 'inactive';
}

const columns: Column<User>[] = [
  { key: 'name', header: 'Name', accessor: (row) => row.name, sortable: true },
  { key: 'email', header: 'Email', accessor: (row) => row.email, filterable: true },
  { key: 'status', header: 'Status', accessor: (row) => row.status },
];

function UsersTable({ users }: { users: User[] }) {
  const {
    processedData,
    paginationProps,
    sortingProps,
    filteringProps,
    selectionProps,
  } = useDataTable({ data: users, columns });

  return (
    <>
      <TableFilters {...filteringProps} />
      <DataTable
        data={processedData}
        columns={columns}
        sorting={sortingProps}
        selection={selectionProps}
        enableColumnManager
        enableExport
        enableInlineEdit
      />
      <TablePagination {...paginationProps} />
    </>
  );
}
```

**Features (Phase 1 - Foundation):**

* Generic `<DataTable<T>>` with full TypeScript support
* Column types: text, number, date, currency, boolean, custom
* Row selection (single/multi) with "select all"
* Pagination with page size selector
* Column sorting (single/multi with Shift+click)
* Global search and per-column filters
* Bulk actions with confirmation dialogs
* Loading skeletons and empty states
* Mobile responsive with hideOnMobile support
* XSS protection via DOMPurify sanitization

**Features (Phase 2 - Advanced Interactions):**

* Inline cell editing (text, number, currency, boolean, date, select)
* Column resizing with localStorage persistence
* Sticky columns for horizontal scrolling
* Virtual scrolling for 10,000+ rows (planned)

**Features (Phase 3 - Column Customization & Export):**

* Column visibility toggling with localStorage persistence
* Drag-and-drop column reordering via @dnd-kit
* "Show All" / "Hide All" quick actions
* CSV export (built-in, no external dependency)
* Excel export with styled headers (via exceljs)
* Progress tracking for large exports

**Features (Phase 4 - Row Grouping):**

* Row grouping by column values
* Aggregate calculations (count, sum, average, min, max)
* Nested group support up to 3 levels
* Expand/collapse group controls with localStorage persistence

**Consumer Cores:**

* All cores: Replace custom table implementations
* HR: Employee lists, applicant tracking tables
* FA: Account lists, transaction tables, vendor lists
* RH: Resident lists, census tables

**Documentation:** See `/src/platform/table/README.md`

***

## PF-23/24/25/26: Data Manager Integration Layer

**Location:** `/src/platform/data-manager/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Last Verified:** 2026-01-08

**Specs:**

* [PF-23: Data Manager - Object Browser](../../../specs/pf/specs/PF-23-data-manager-object-browser.md)
* [PF-24: Custom Objects](../../../specs/pf/specs/PF-24-custom-objects.md)
* [PF-25: Raw Data Editor](../../../specs/pf/specs/PF-25-raw-data-editor.md)
* [PF-26: Object Permissions](../../../specs/pf/specs/PF-26-object-permissions.md)

**Public API:**

```typescript theme={null}
// Object Browser (PF-23)
export { useObjectMetadata } from './hooks/useObjectMetadata';
export { useObjectMetadataMutation } from './hooks/useObjectMetadataMutation';
export { useObjectCategories } from './hooks/useObjectCategories';
export { useObjectFavorites } from './hooks/useObjectFavorites';
export { useDiscoverObjects } from './hooks/useDiscoverObjects';
export { DataManagerPage } from './pages/DataManagerPage';
export { ObjectDetailPage } from './pages/ObjectDetailPage';

// Custom Objects (PF-24)
export { useCustomObjects } from './hooks/useCustomObjects';
export { useCustomObject } from './hooks/useCustomObject';
export { useCustomObjectMutation } from './hooks/useCustomObjectMutation';
export { useCustomObjectFields } from './hooks/useCustomObjectFields';
export { useCustomObjectRecords } from './hooks/useCustomObjectRecords';
export { CreateCustomObjectDialog } from './components/CreateCustomObjectDialog';
export { CustomObjectDetailPage } from './pages/CustomObjectDetailPage';

// Raw Data Editor (PF-25)
export { useRawData } from './hooks/useRawData';
export { useRawDataEdit } from './hooks/useRawDataEdit';
export { useRawDataExport } from './hooks/useRawDataExport';
export { useRawDataImport } from './hooks/useRawDataImport';
export { RawDataTable } from './components/RawDataTable';
export { RawDataImportWizard } from './components/RawDataImportWizard';

// Object Permissions (PF-26)
export { useObjectPermissions } from './hooks/useObjectPermissions';
export { useFieldPermissions } from './hooks/useFieldPermissions';
export { ObjectPermissionsTab } from './components/ObjectPermissionsTab';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Use Platform Integration Layer
import { useCustomObjects, useCustomObjectRecords } from '@/platform/data-manager';
import { useObjectMetadata } from '@/platform/data-manager';

// Browse all objects
const { objects } = useObjectMetadata({ categoryId, search });

// Create custom object
const { createCustomObject } = useCustomObjectMutation();
await createCustomObject({ name: 'Clinical Licenses', api_name: 'clinical_licenses' });

// Manage custom object records
const { records, createRecord } = useCustomObjectRecords('clinical_licenses');
await createRecord({ data: { license_number: 'RN-12345' } });
```

**Features:**

* Object discovery and metadata management
* Custom object creation and management
* Raw data browsing and inline editing
* CSV import/export for bulk operations
* Object-level and field-level permissions
* Category management and favorites

**Consumer Cores:**

* All cores: Browse objects, manage metadata
* HR: Clinical licenses, training classes
* FA: Custom financial entities (planned)
* RH: Incident tracking, program outcomes (planned)

**Documentation:** See `/src/platform/data-manager/README.md` and [Data Management Architecture](../DATA_MANAGEMENT_ARCHITECTURE.md)

***

## CE-03: Platform Telephony Integration Layer

**Location:** `/src/platform/telephony/`
**Status:** ✅ Complete
**Implemented:** v1.1.0 (Click-to-Call & Screen Pop via CE-03-E1)
**Last Verified:** 2026-01-27
**Spec:** [CE-03](../../../specs/ce/specs/CE-03-call-management-ringcentral.md), [CE-03-E1](../../../specs/ce/specs/CE-03-E1-click-to-call-screen-pop.md)

**Purpose:** Provides unified telephony capabilities (call management, RingCentral integration) for all cores needing phone communication features.

**Public API:**

```typescript theme={null}
// Hooks - Call Management
export { useCallLog } from './hooks/useCallLog';
export { useRecentCalls } from './hooks/useRecentCalls';
export { useCallDisposition } from './hooks/useCallDisposition';
export { useCreateCall } from './hooks/useCreateCall';

// Hooks - Click-to-Call & Screen Pop (CE-03-E1)
export { useClickToCall } from './hooks/useClickToCall';           // NEW v1.1.0
export { useIncomingCallNotification } from './hooks/useIncomingCallNotification'; // NEW v1.1.0

// Components - Call Management
export { CallLogWidget } from './components/CallLogWidget';
export { CallDispositionDialog } from './components/CallDispositionDialog';
export { CallRecordingPlayer } from './components/CallRecordingPlayer';
export { RecentCallsList } from './components/RecentCallsList';
export { ManualCallForm } from './components/ManualCallForm';

// Components - Click-to-Call & Screen Pop (CE-03-E1)
export { ClickToCallButton } from './components/ClickToCallButton';   // NEW v1.1.0
export { IncomingCallToast } from './components/IncomingCallToast';   // NEW v1.1.0
export { IncomingCallProvider } from './components/IncomingCallProvider'; // NEW v1.1.0

// Types
export type {
  Call, CallInsert, CallUpdate, CallWithRelations,
  CallFilters, CallDisposition, CallRecordingStatus, CallDirection,
  DispositionInput, FollowUpConfig,
} from './types';

// Utilities
export { normalizePhone, formatPhoneDisplay, isValidPhoneNumber } from './lib/phoneUtils';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { 
  useCallLog, 
  useClickToCall, 
  ClickToCallButton,
  IncomingCallProvider 
} from '@/platform/telephony';

// Call log and disposition
const { calls } = useCallLog({ organizationId });

// Click-to-call (CE-03-E1)
const { initiateCall, isInitiating } = useClickToCall();
await initiateCall({ toNumber: '+15551234567', contactId: 'uuid' });

// Or use the button component
<ClickToCallButton phoneNumber="+15551234567" contactId="uuid" variant="button" />

// Wrap app with screen pop provider
<IncomingCallProvider>
  {/* App content */}
</IncomingCallProvider>

// ❌ WRONG: Direct import from core
import { useCallLog } from '@/cores/ce/hooks/useCallLog';
```

**Features:**

* **Call Management (CE-03):** Call log viewing, disposition workflow, recording playback
* **Click-to-Call (CE-03-E1):** One-click dialing via RingCentral RingOut API
* **Screen Pop (CE-03-E1):** Real-time caller ID notification via Supabase Realtime

**Edge Functions:**

* `ringcentral-webhook` - Receives RingCentral telephony events
* `ringcentral-setup` - Manages subscription lifecycle
* `ringcentral-recording-proxy` - Secure recording access
* `ringcentral-ringout` - Initiates click-to-call (CE-03-E1)

**Database Tables:**

* `ce_calls` - Call records with disposition
* `ce_ringcentral_extensions` - User extension mapping
* `ce_ringcentral_subscriptions` - Webhook subscriptions
* `ce_ringout_sessions` - RingOut tracking (CE-03-E1)

**Consumer Cores:**

* CE: Primary consumer for CRM call features
* RH: Contact calls with residents/guardians (via CE contacts)
* HR: Employee phone contacts (potential future use)

**External Dependencies:**

* RingCentral API (JWT authentication)
* Supabase Realtime (screen pop)

**Documentation:**

* [CE-03 Spec](../../../specs/ce/specs/CE-03-call-management-ringcentral.md)
* [CE-03-E1 Spec](../../../specs/ce/specs/CE-03-E1-click-to-call-screen-pop.md)
* [Platform Telephony README](../../../src/platform/telephony/README.md)

***

## Workflow Canvas Integration Layer

**Location:** `/src/platform/workflow/`\
**Status:** ✅ Complete (GR-11 Implementation)\
**Created By:** GR-11 (Procedures Management)\
**Version:** 1.0.0\
**Spec Reference:** [GR-11 Procedures Management](../../../specs/gr/specs/GR-11-procedures-management.md)

**Purpose:** Exposes @xyflow/react workflow canvas capabilities for cross-core visual workflow editing.

**Public API:**

```typescript theme={null}
// Components
export { WorkflowCanvas } from './WorkflowCanvas';

// Types
export type { 
  WorkflowNodeType,
  WorkflowEdgeType,
  WorkflowCanvasProps,
  NodeTypeConfig,
} from './types';
```

**Usage Example:**

```typescript theme={null}
import { WorkflowCanvas } from '@/platform/workflow';
import { procedureNodeTypes, procedureEdgeTypes } from './nodeTypes';

<WorkflowCanvas
  nodes={nodes}
  edges={edges}
  nodeTypes={procedureNodeTypes}
  edgeTypes={procedureEdgeTypes}
  onNodesChange={handleNodesChange}
  onEdgesChange={handleEdgesChange}
  fitView
/>
```

**Patterns (Recommended):**

1. **Node Type Registration:** Define module-specific node types extending base types
2. **Edge Styling:** Use semantic colors for edge connections
3. **Canvas Controls:** Always include MiniMap, Controls, Background for usability
4. **Mobile Handling:** Canvas is read-only on mobile (\<768px)

**Anti-Patterns (Avoid):**

1. ❌ Direct @xyflow/react imports in cores - use platform layer
2. ❌ Storing raw React Flow nodes in database - convert to serializable format
3. ❌ Complex drag-drop on mobile - display read-only view instead

**Dependencies:**

| Dependency         | Version  | Purpose                    |
| ------------------ | -------- | -------------------------- |
| @xyflow/react      | ^12.10.0 | Core workflow canvas       |
| @xyflow/background | -        | Canvas background patterns |
| @xyflow/controls   | -        | Zoom/pan controls          |
| @xyflow/minimap    | -        | Navigation minimap         |

**Features:**

* React Flow integration (@xyflow/react) with custom node types
* Zoom, pan, and fit-to-view controls
* Mini-map for navigation in large workflows
* Grid snap with configurable increments
* Auto-save on changes
* Custom node types for procedure steps (Action, Decision, Reference, Verification, System)

**Consumer Cores:**

* GR: Visual procedure editor (GR-11) - ✅ Implemented
* FW: Advanced workflow builder (FW-06) - Original implementation
* Future: Other cores needing visual workflow capabilities

**Implementation Notes:**

* Wraps @xyflow/react workflow canvas functionality
* Provides stable API for cross-core consumption
* GR-11 creates procedure-specific node types on top of base canvas

**Documentation:** See `/src/platform/workflow/README.md` for complete implementation details.

**Common Usage Patterns:**

```typescript theme={null}
// ✅ CORRECT: Standard workflow canvas setup
import { 
  WorkflowCanvas, 
  useWorkflowCanvas,
  type WorkflowNode,
  type WorkflowEdge 
} from '@/platform/workflow';

function ProcedureEditor() {
  const initialNodes: WorkflowNode[] = [
    { id: '1', type: 'action', position: { x: 0, y: 0 }, data: { label: 'Start' } }
  ];
  const initialEdges: WorkflowEdge[] = [];

  const { 
    nodes, 
    edges, 
    onNodesChange, 
    onEdgesChange,
    onConnect,
    fitView 
  } = useWorkflowCanvas(initialNodes, initialEdges);

  return (
    <WorkflowCanvas
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      nodeTypes={customNodeTypes}
      fitView
    />
  );
}
```

**Typical Hook/Component Flow:**

1. Import `useWorkflowCanvas` hook and `WorkflowCanvas` component
2. Initialize with starting nodes and edges
3. Use hook to get state and handlers (`nodes`, `edges`, `onNodesChange`, `onEdgesChange`, `onConnect`)
4. Pass state and handlers to `WorkflowCanvas` component
5. Provide custom `nodeTypes` for domain-specific node rendering
6. Use `fitView` or other viewport controls for navigation

**Anti-patterns:**

```typescript theme={null}
// ❌ WRONG: Direct import from FW core
import { WorkflowCanvas } from '@/cores/fw/components/WorkflowCanvas';

// ❌ WRONG: Bypassing platform layer
import { ReactFlow } from '@xyflow/react';

// ❌ WRONG: Mutating nodes/edges directly
nodes[0].position.x = 100; // Use onNodesChange instead

// ❌ WRONG: Creating custom canvas implementation
// Use platform layer instead of reimplementing
```

**Internal Dependencies:**

* **FW-06 (Forms & Workflow)**: Source of truth for workflow canvas implementation
  * Original workflow canvas implementation in `/src/cores/fw/`
  * Platform layer wraps and exposes FW-06 functionality
  * FW-06 maintains the core workflow engine logic
* **Platform Foundation**: Base infrastructure for cross-core capabilities

**External Dependencies:**

* **@xyflow/react**: React Flow library for node-based graph visualization
  * Provides core canvas, node, and edge rendering
  * Handles zoom, pan, and viewport management
  * Manages node/edge state and interactions
* **React**: Required for component rendering and hooks

**Core Dependencies:**

* **GR-11 (Procedures Management)**: Primary consumer
  * Uses canvas for visual procedure editor
  * Creates procedure-specific node types (Action, Decision, Reference, Verification, System)
* **FW-06 (Forms & Workflow)**: Original implementation and source of truth
  * Advanced workflow builder uses platform layer
  * Maintains workflow engine and execution logic

**Documentation:** See `/src/platform/workflow/README.md` (to be created during GR-11 implementation) for complete implementation details, API reference, and advanced usage patterns.

***

## PF-73: Swim Lane Diagram Builder

**Location:** `/src/platform/workflow/` (extends Workflow Canvas layer)\
**Status:** ✅ Complete (Phase 1) — Phase 2 📝 Planned
**Spec Reference:** [PF-73 Workflow Builder with Swim Lane Visualization](../../../specs/pf/specs/PF-73-workflow-builder-swim-lane-visualization.md)\
**Integration Doc:** [PF-73-workflow-builder-swim-lane-INTEGRATION.md](./workflow-builder-swim-lane-integration.md)

**Purpose:** Extends the workflow layer with swim lane diagram capabilities: horizontal/vertical lanes, node-in-lane placement, manual builder UI, diagram CRUD in `pf_swim_lane_diagrams`, generation from GR-11 procedures and GR-01 policies (with optional PF-27 AI), and PDF/image export. Consumed by GR, FW, HR for process documentation—visualization only (no workflow execution; FW-06 remains the execution engine).

**Public API (when implemented):**

* **Components:** `SwimLaneCanvas` (lane-aware canvas)
* **Hooks:** `useSwimLaneDiagramList`, `useSwimLaneDiagram`, `useSwimLaneDiagramMutation`
* **Types:** `LaneDefinition`, `SwimLaneDiagramState` (lanes, nodes, edges, viewport)

**Consumer Cores:** GR (procedures/policies), FW (documentation), HR (onboarding/process docs). Permissions: `pf.swim-lane-diagrams.view`, `.create`, `.update`, `.delete`, `.export`.

**Documentation:** See [PF-73 Integration Doc](./workflow-builder-swim-lane-integration.md) for contracts, RLS, and settings.

***

## PF-65: Gusto Embedded Payroll Integration Layer

**Location:** `/src/platform/gusto/` (to be created)\
**Status:** 📝 Planned\
**Spec:** [PF-65 Gusto Embedded Payroll Integration](../../../specs/pf/specs/PF-65-gusto-embedded-payroll-integration.md)\
**Integration Doc:** [PF-65-gusto-embedded-payroll-INTEGRATION.md](./gusto-embedded-payroll-integration.md)

**Purpose:** Platform layer for the Gusto Embedded React SDK. Provides `GustoProvider`, hooks (`useGustoConfig`, `useGustoConnectionStatus`), and re-exports of SDK components (e.g. `EmployeeOnboardingFlow`, `EmployeeList`). All SDK requests go through a Supabase Edge Function proxy that adds OAuth2 and `x-gusto-client-ip`; no Gusto credentials in the frontend.

**Features:**

* Backend proxy (Supabase Edge Function) for OAuth token injection and request forwarding
* OAuth and token management via PF-35 (access/refresh tokens server-side only)
* `x-gusto-client-ip` injection from trusted proxy headers
* SDK re-exports from `@gusto/embedded-react-sdk` (GustoProvider, EmployeeOnboardingFlow, EmployeeList)
* Event handling via `componentEvents` and `onEvent` for analytics/sync

**Public API:**

```typescript theme={null}
// Components
export { GustoProviderWrapper } from './GustoProviderWrapper';

// SDK Re-exports (configured for proxy)
export { GustoApiProvider, Employee, Company, componentEvents } from '@gusto/embedded-react-sdk';

// Hooks
export { useGustoConfig, type GustoConfig } from './useGustoConfig';
export { useGustoConnectionStatus, useIsGustoConnected, type GustoConnectionStatus, type GustoConnectionInfo } from './useGustoConnectionStatus';

// OAuth Configuration
export { GUSTO_OAUTH_CONFIG, GUSTO_DEMO_OAUTH_CONFIG, GUSTO_INTEGRATION_TYPE, GUSTO_PERMISSIONS, getGustoOAuthConfig, type GustoOAuthConfig } from './gusto-oauth-config';
```

**Usage Example:**

```typescript theme={null}
// 1. Import baseline styles in route/layout
import '@gusto/embedded-react-sdk/style.css';

// 2. Use in HR route
import { GustoProviderWrapper, useGustoConfig, Employee } from '@/platform/gusto';

function GustoEmbedPage() {
  const { companyId, isConnected, isLoading } = useGustoConfig();

  if (isLoading) return <Skeleton />;
  if (!isConnected || !companyId) {
    return <EmptyState title="Connect to Gusto" />;
  }

  return (
    <GustoProviderWrapper>
      <Employee.SelfOnboardingFlow 
        companyId={companyId}
        onEvent={(event) => console.log('Gusto event:', event)}
      />
    </GustoProviderWrapper>
  );
}
```

```typescript theme={null}
// ❌ WRONG: Do not import SDK directly; bypasses proxy and OAuth
import { GustoApiProvider, Employee } from '@gusto/embedded-react-sdk';
```

**Anti-Patterns:**

* **Never import the SDK directly** – Always use `@/platform/gusto`; direct `@gusto/embedded-react-sdk` imports bypass the proxy and OAuth.
* **Never send OAuth tokens to the frontend** – Tokens are resolved server-side in the proxy only; client only receives proxy baseUrl and companyId.
* **Never set `x-gusto-client-ip` from the client** – The header must be set by the Edge Function from trusted proxy headers (X-Forwarded-For / X-Real-IP) only.
* **Never bypass the proxy** – All Gusto API traffic must go through the gusto-proxy Edge Function so tokens and client IP are injected server-side.

**Consumer Cores:**

* **HR (primary)** – Workforce routes such as `/hr/payroll/gusto` (Gusto employees list) and `/hr/me/onboarding` (Employee Onboarding). Permissions: `hr.gusto.view`, `hr.gusto.configure`.

**Internal Dependencies:**

* **PF-01 (Organizations)** – Org context and `organization_id` resolution for proxy and connection status.
* **PF-35 (Integration Hub)** – OAuth flow, credential storage (`pf_integrations`), and company mapping for Gusto Embedded.
* **PF-04 (Audit Logging)** – Audit entries for connect/disconnect and token refresh failures (no token values in logs).

**External Dependencies:**

* **@gusto/embedded-react-sdk** – Gusto Embedded React SDK; provides `GustoApiProvider`, `Employee`, `Company`, `componentEvents`. All usage must go through the platform layer so requests are proxied with OAuth and `x-gusto-client-ip`.

**Documentation:** See `/src/platform/gusto/README.md` for implementation details and API reference. See [PF-65-gusto-embedded-payroll-INTEGRATION.md](./gusto-embedded-payroll-integration.md) for the integration contract, proxy behavior, and security guidance.

***

## Planned Platform Layers (CL/PM EHR & Practice Management)

**Source:** [EHR\_PM\_PLANNING\_BUNDLE.md](../../../specs/cl/planning/EHR_PM_PLANNING_BUNDLE.md)\
**Status:** 🟡 In Progress — Consent Service ✅; Patient Context, Billing Adapter, Document Export, Scheduling layer contracts defined in `src/platform/clinical/README.md` and `src/platform/scheduling/README.md`. Shared types in `@/platform/types` (clinical-billing). **Clinical medication integrations** (e.g. CL–RH Residential MAR) use `@/platform/clinical` as the canonical layer so medication-related APIs remain colocated with clinical data; see [CL-RH-RESIDENTIAL-MAR-INTEGRATION.md](CL-RH-RESIDENTIAL-MAR-INTEGRATION.md).

### CL Consent Service

**Location:** `@/platform/clinical`
**Status:** ✅ Implemented (useConsentCheck)
**Spec Reference:** [CL-11 – Consent Management & 42 CFR Part 2](../../../specs/cl/specs/CL-11-consent-management-42cfr-part2.md)

**Purpose:** Centralized consent evaluation for 42 CFR Part 2, TPO, SUD counseling notes, and legal-proceedings consent. Policy decision point (PDP) for UI/API/export gating and disclosure logging. Consumer cores: CL, PM, FW.

**Public API (proposed):**

* **Interface:** `ConsentServiceAPI`
  * `evaluateConsent(request: ConsentCheckRequest): Promise<ConsentCheckResponse>` — Returns `{ allowed, obligations?, denial_reason?, audit_id? }`; key fields: `patient_id`, `purpose_of_use`, `resource_type?`, `organization_id`, `user_id?`.
* **Return shape:** `ConsentCheckResponse`: `allowed: boolean`, `obligations?: string[]`, `denial_reason?: string`, `audit_id?: string`.

**Example:**

```typescript theme={null}
import { evaluateConsent } from '@/platform/clinical';

const result = await evaluateConsent({
  patient_id: patientId,
  purpose_of_use: 'TPO',
  organization_id: orgId,
  user_id: userId,
});
if (result.allowed) {
  // proceed with access
} else {
  // gate UI/API; log denial via result.audit_id
}
```

***

### CL Billing Adapter

**Location:** `@/platform/clinical`\
**Status:** 📝 Planned\
**Spec Reference:** [PM-07 – Charge Capture & Fee Schedules](../../../specs/pm/specs/PM-07-charge-capture-fee-schedules.md), [CL-04 – Progress Notes & Session Documentation](../../../specs/cl/specs/CL-04-progress-notes-session-documentation.md)

**Purpose:** Map encounters and progress notes to billable events without direct CL→PM imports. Exposes encounter context (e.g. encounter type, duration) for charge capture. Consumer cores: PM, CL (read-only context).

**Public API (proposed):**

* **Interface:** `BillingAdapterAPI`
  * `mapEncounterToCharge(encounterId: string, options?: { organization_id: string }): Promise<ChargeCaptureContext>` — Returns encounter type, date, provider, duration, and suggested service codes for charge capture.
* **Return shape:** `ChargeCaptureContext`: `encounter_id: string`, `encounter_type?: string`, `service_date: string`, `provider_id?: string`, `duration_minutes?: number`, `suggested_codes?: { cpt?: string; modifier?: string }[]`.

**Example:**

```typescript theme={null}
import { mapEncounterToCharge } from '@/platform/clinical';

const context = await mapEncounterToCharge(encounterId, { organization_id: orgId });
// PM uses context.service_date, context.suggested_codes to create charge
```

***

### CL Document Export (EHI)

**Location:** `@/platform/clinical`\
**Status:** 📝 Planned\
**Spec Reference:** [CL-16 – FHIR Interoperability & Data Exchange](../../../specs/cl/specs/CL-16-fhir-interoperability-data-exchange.md)

**Purpose:** FHIR R4 / USCDI v3 export and C-CDA generation for patient access and third-party apps. Supports "full EHI access" and information blocking compliance. Consumer cores: CL, PM-12, external FHIR clients.

**Public API (proposed):**

* **Interface:** `DocumentExportAPI`
  * `exportEHI(patientId: string, options: { organization_id: string; format?: 'fhir' | 'ccda'; _since?: string }): Promise<ExportResult>` — Returns URL or FHIR Bundle for downloaded EHI.
* **Return shape:** `ExportResult`: `url?: string`, `bundle?: object`, `format: string`, `size_bytes?: number`.

**Example:**

```typescript theme={null}
import { exportEHI } from '@/platform/clinical';

const result = await exportEHI(patientId, {
  organization_id: orgId,
  format: 'fhir',
  _since: '2026-01-01',
});
if (result.url) window.open(result.url, '_blank');
```

***

### Clinical Summary / Chart Context

**Location:** `@/platform/clinical`\
**Status:** 📝 Planned\
**Spec Reference:** [CL-01 – Patient Chart & Clinical Summary](../../../specs/cl/specs/CL-01-patient-chart-clinical-summary.md), [PM-07 – Charge Capture & Fee Schedules](../../../specs/pm/specs/PM-07-charge-capture-fee-schedules.md)

**Purpose:** Read-only chart/encounter context for PM (e.g. encounter type, date, provider for billing). No direct PM→CL imports; access via platform layer only.

**Public API (proposed):**

* **Interface:** `ChartContextAPI`
  * `getChartContext(patientId: string, encounterId?: string, options?: { organization_id: string }): Promise<ChartContext>` — Read-only summary and encounter context for billing/display.
* **Return shape:** `ChartContext`: `patient_id: string`, `encounter_id?: string`, `encounter_type?: string`, `service_date?: string`, `provider_id?: string`, `summary_snapshot?: object` (diagnoses, meds, allergies per CL-01).

**Example:**

```typescript theme={null}
import { getChartContext } from '@/platform/clinical';

const context = await getChartContext(patientId, encounterId, { organization_id: orgId });
// PM uses context.encounter_type, context.service_date for charge capture
```

***

## PF-70: Medical Terminology & Code Libraries

**Location:** `/src/platform/codes/`\
**Status:** 📝 Planned\
**Spec Reference:** [PF-70-medical-terminology-code-libraries.md](../../../specs/pf/specs/PF-70-medical-terminology-code-libraries.md)\
**Integration Doc:** [PF-70-medical-terminology-code-libraries-INTEGRATION.md](./medical-terminology-code-libraries-integration.md)

**Purpose:** Centralized platform layer for ICD-10-CM, CPT, HCPCS, modifiers, and crosswalk data. Provides type-ahead search, behavioral health filtering, effective-date-aware validation, modifier-code combination validation, and optional payer-specific rules. Consumed by CL and PM cores via `@/platform/codes` — never via direct Supabase queries.

**Consumers:** CL-01, CL-04, CL-06 (NDC, future), CL-08 (ICD-10-CM, CPT, HCPCS; LOINC deferred), CL-18, CL-19, PM-07, PM-08

**Public API (planned):**

```typescript theme={null}
// Hooks
export { useCodeSearch } from './useCodeSearch';
export { useCodeFavorites } from './useCodeFavorites';
export { useCodeRecent } from './useCodeRecent';

// Functions
export { validateCode } from './validateCode';
export { searchCodes } from './searchCodes';

// Types
export type { CodeSearchParams, CodeSearchResult, CodeValidationResult } from './types';
```

**Search API — `useCodeSearch` / `searchCodes`:**

| Param            | Type                                       | Required | Description                                        |
| ---------------- | ------------------------------------------ | -------- | -------------------------------------------------- |
| `codeSet`        | `'ICD10CM' \| 'CPT' \| 'HCPCS' \| 'LOINC'` | Yes      | Code set to search                                 |
| `query`          | `string`                                   | Yes      | Min 2 chars; matches code or description prefix    |
| `effectiveDate`  | `string` (ISO date)                        | No       | Default: today                                     |
| `bhOnly`         | `boolean`                                  | No       | Filter to `is_behavioral_health = true` codes only |
| `organizationId` | `string`                                   | Yes      | Tenant isolation                                   |

**Validation API — `validateCode`:**

| Param            | Type       | Required | Description                |
| ---------------- | ---------- | -------- | -------------------------- |
| `code`           | `string`   | Yes      | Code to validate           |
| `codeSet`        | `string`   | Yes      | ICD10CM, CPT, HCPCS        |
| `modifiers`      | `string[]` | No       | Modifiers to validate      |
| `serviceDate`    | `string`   | Yes      | Effective date validation  |
| `payerId`        | `string`   | No       | Payer-specific rule lookup |
| `organizationId` | `string`   | Yes      | Tenant isolation           |

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform layer
import { useCodeSearch, validateCode } from '@/platform/codes';

// Type-ahead search for BH diagnosis codes
const { results, isLoading } = useCodeSearch({
  codeSet: 'ICD10CM',
  query: 'F32',
  bhOnly: true,
  organizationId: orgId,
});

// Validate code + modifier before claim submission
const result = await validateCode({
  code: '90837',
  codeSet: 'CPT',
  modifiers: ['GT'],
  serviceDate: '2026-02-18',
  organizationId: orgId,
});
if (!result.valid) {
  toast.error(result.errors?.join(', '));
}

// ❌ WRONG: Direct Supabase query from core
import { supabase } from '@/integrations/supabase/client';
const { data } = await supabase.from('pf_icd10_codes').select('*');
```

**Core Tables:**

* `pf_code_sets` — Code set registry (ICD10CM 2025, CPT 2025, etc.) with effective dates
* `pf_icd10_codes` — ICD-10-CM codes with `is_behavioral_health`, `is_sdoh` flags
* `pf_cpt_codes` — CPT codes with `is_behavioral_health`, `category`
* `pf_hcpcs_codes` — HCPCS Level II codes with `is_behavioral_health`, `category`
* `pf_code_modifiers` — Modifier definitions and valid code-modifier combinations (org-scoped)
* `pf_code_crosswalks` — Platform-managed CPT→revenue code mappings
* `pf_payer_code_rules` — Org-specific payer code overrides (payer\_id is a bare UUID, no FK to pm\_payers)
* `pf_code_favorites` — Per-user/org favorites
* `pf_code_recent` — Per-user/org recently used

**Permissions:** `pf.codes.read` (all clinician/billing users), `pf.codes.admin` (code set management)

**RLS Pattern:** Platform-managed code sets use `organization_id IS NULL` and are readable by all authenticated users via `pf_can_read_code_set(p_code_set_id UUID)` SECURITY DEFINER helper. Org-scoped tables (`pf_code_modifiers`, `pf_payer_code_rules`) use standard `pf_has_org_access(organization_id, auth.uid())`.

**Notes:**

* LOINC is reserved as a `codeSet` param but returns `{ loinc_unavailable: true }` until a future phase adds the LOINC table. CL-08 is partially blocked on LOINC for lab monitoring CDS rules.
* `pf_payer_code_rules.payer_id` is an unenforced UUID annotation (no FK to `pm_payers`) to preserve PF→PM boundary isolation.

***

## PF-84: Business Calendar Service

**Location:** `/src/platform/calendar/`\
**Status:** ✅ Complete (Phase 1)\
**Implemented:** 2026-03-18\
**Version:** 1.0.0\
**Spec Reference:** [PF-84-business-calendar-service.md](../../../specs/pf/specs/PF-84-business-calendar-service.md)\
**Integration Doc:** [PF-84-business-calendar-service-INTEGRATION.md](./business-calendar-service-integration.md)

**Public API:**

```typescript theme={null}
// Hooks
export { useBusinessCalendars } from './useBusinessCalendars';
export { useBusinessCalendar } from './useBusinessCalendar';
export { useDefaultCalendar } from './useDefaultCalendar';
export { useHolidays } from './useHolidays';
export { useBusinessDays } from './useBusinessDays';
export { useHolidayTemplates } from './useHolidayTemplates';
export { useApplyHolidayTemplate } from './useApplyHolidayTemplate';
export { useImportHolidaysFromCsv } from './useImportHolidaysFromCsv';

// Components
export { CalendarPicker } from './CalendarPicker';
export { HolidayTemplateSelector } from './HolidayTemplateSelector';
export { HolidayImportDialog } from './HolidayImportDialog';
export { HolidayPreviewTable } from './HolidayPreviewTable';

// Pure Utilities
export { addBusinessDays, subtractBusinessDays, isBusinessDay, isHoliday, nextBusinessDay, createDefaultBusinessHours } from './utils';

// Types
export type { BusinessCalendar, CalendarHoliday, BusinessDayUtils, HolidayTemplate, HolidayType } from './types';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { useBusinessDays, CalendarPicker, addBusinessDays } from '@/platform/calendar';

// Calculate business days
const { addBusinessDays: addDays, isBusinessDay } = useBusinessDays(calendarId);
const nextBusinessDate = addDays(new Date(), 5);

// Use calendar picker component
<CalendarPicker calendarId={calendarId} onSelect={handleDateSelect} />

// Pure utility (no hook needed)
const result = addBusinessDays(new Date(), 10, calendarId);
```

**Consumer Cores:**

* All cores can use business calendar logic via `@/platform/calendar`
* PF-83 (SLA Management) uses calendar for deadline calculations
* FW-16 (Date-Relative Triggers) integrates with calendar for business-day-aware triggers

**Implementation Notes:**

* Wraps FW-35 calendar tables (`fw_business_calendars`, `fw_calendar_holidays`) via platform layer
* Provides shared Edge Function utility (`_shared/business-calendar.ts`) for server-side calculations
* Includes 6 holiday templates (US Federal 2026/2027, CA/NY/TX/FL 2026) at `src/platform/calendar/templates/`
* CSV import support for bulk holiday management
* Edge utility uses 5-minute cache to reduce database reads

**Documentation:**

* [PF-84 Integration Doc](./business-calendar-service-integration.md)
* [PF-84 Spec](../../../specs/pf/specs/PF-84-business-calendar-service.md)

***

## PF-85: Automation Observability Dashboard

**Location:** `@/cores/fw/pages/AutomationObservabilityPage.tsx` (⚠️ Architectural Debt: Should be moved to `@/platform/automation-observability`)\
**Status:** ✅ Complete (Phase 1)\
**Implemented:** 2026-03-18\
**Version:** 1.0.0\
**Spec Reference:** [PF-85-automation-observability-dashboard.md](../../../specs/pf/specs/PF-85-automation-observability-dashboard.md)\
**Integration Doc:** [PF-85-automation-observability-dashboard-INTEGRATION.md](./automation-observability-dashboard-integration.md)

**⚠️ Architectural Note:** This feature is currently implemented in the FW core (`src/cores/fw/pages/AutomationObservabilityPage.tsx`, `src/cores/fw/hooks/`, `src/cores/fw/components/`) but is owned by Platform Foundation per spec. The hooks and components should be moved to `@/platform/automation-observability` to comply with platform layer boundaries. This is documented architectural debt.

**Public API (Current Implementation):**

```typescript theme={null}
// Types (from @/cores/fw/types/observability)
export type { ObservabilityCurrent, ObservabilityTimeseriesPoint, AutomationAlertThresholds, ObservabilityWindow } from '@/cores/fw/types/observability';

// Hooks (from @/cores/fw/hooks/)
export { useObservabilityCurrent } from '@/cores/fw/hooks/useObservabilityCurrent';
export { useObservabilityTimeseries } from '@/cores/fw/hooks/useObservabilityTimeseries';
export { useAlertThresholds } from '@/cores/fw/hooks/useAlertThresholds';

// Components (from @/cores/fw/components/)
export { ObservabilityMetricCard } from '@/cores/fw/components/ObservabilityMetricCard';
export { ObservabilityTrendChart } from '@/cores/fw/components/ObservabilityTrendChart';
export { AlertThresholdDialog } from '@/cores/fw/components/AlertThresholdDialog';
```

**Usage Example:**

```typescript theme={null}
// ⚠️ Current: Import from FW core (architectural debt)
import { useObservabilityCurrent, ObservabilityMetricCard } from '@/cores/fw/...';

// Future: Should import from platform
// import { useObservabilityCurrent, ObservabilityMetricCard } from '@/platform/automation-observability';

const { data, isLoading } = useObservabilityCurrent({ organizationId: orgId });
<ObservabilityMetricCard metric="executions_queued" value={data?.executions_queued} />
```

**Consumer Cores:**

* Platform admins and operators use the dashboard at `/settings/automation/observability`
* Integrates with PF-82 (Business Process Registry), PF-83 (SLA Management), FW-22 (Execution Monitoring), FW-47 (Dead Letter Queue)

**Implementation Notes:**

* Aggregates metrics from multiple subsystems: workflow executions, DLQ, SLA instances, process health
* Real-time counters with 30-second auto-refresh
* Trend charts for execution volume, success rate, average duration, DLQ depth
* Configurable alert thresholds stored in `pf_module_settings.custom_fields.observability_alert_thresholds`
* Permissions: `platform.automation.observability.view`, `platform.automation.observability.manage`
* DLQ metrics currently stubbed to 0 (FW-47 not yet implemented)

**Documentation:**

* [PF-85 Integration Doc](./automation-observability-dashboard-integration.md)
* [PF-85 Spec](../../../specs/pf/specs/PF-85-automation-observability-dashboard.md)

***

## PF-96: Jurisdiction Profile Integration Layer

**Location:** `@/platform/jurisdiction/`
**Status:** 📝 Planned
**Spec Reference:** [PF-96-medicaid-state-compliance-configuration.md](../../../specs/pf/specs/PF-96-medicaid-state-compliance-configuration.md)
**Integration Doc:** [PF-96-medicaid-state-compliance-configuration-INTEGRATION.md](./medicaid-state-compliance-configuration-integration.md)
**Plan:** [PF-96-medicaid-state-compliance-configuration-PLAN.md](../../../specs/pf/plans/PF-96-medicaid-state-compliance-configuration-PLAN.md)

**Purpose:** Provides state-specific Medicaid compliance rules via a four-tier jurisdiction profile system (Federal Baseline → State Profile → Org Overrides → Site Overrides). Enables multi-state deployment without code changes by externalizing AHCCCS-specific rules to configuration.

**Public API:**

```typescript theme={null}
// Types
export type {
  JurisdictionProfile,
  ClinicalRules,
  BillingRules,
  ComplianceRules,
  ModifierConvention,
  PlaceOfServiceCode
} from '@/platform/jurisdiction/types';

// Hooks
export { useJurisdictionProfile } from '@/platform/jurisdiction/useJurisdictionProfile';
export { useClinicalRules } from '@/platform/jurisdiction/useJurisdictionProfile';
export { useBillingRules } from '@/platform/jurisdiction/useJurisdictionProfile';
export { useComplianceRules } from '@/platform/jurisdiction/useJurisdictionProfile';
```

**Edge Function Helper:**

```typescript theme={null}
// supabase/functions/_shared/jurisdiction.ts
export { getJurisdictionProfile } from '../_shared/jurisdiction.ts';
```

**Usage Example:**

```typescript theme={null}
// ✅ CORRECT: Import from platform
import { useJurisdictionProfile, useClinicalRules } from '@/platform/jurisdiction';

// Frontend: Get full profile
const { data: profile, isLoading, error } = useJurisdictionProfile(siteId?);
// Access: profile?.clinical, profile?.billing, profile?.compliance

// Frontend: Convenience accessors
const clinicalRules = useClinicalRules(siteId?);
const billingRules = useBillingRules(siteId?);

// Edge function: Server-side resolution
import { getJurisdictionProfile } from '../_shared/jurisdiction.ts';
const profile = await getJurisdictionProfile(supabaseClient, orgId, siteId?);
```

**Consumer Cores:**

| Core | Spec                         | What It Reads                                                                   | Usage                                            |
| ---- | ---------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------ |
| CL   | CL-02 (Assessments)          | `clinical.assessment_required_elements`, `clinical.assessment_completion_hours` | `useClinicalRules()` hook                        |
| CL   | CL-04 (Progress Notes)       | `clinical.documentation_timeliness_hours`, `clinical.required_note_elements`    | `useClinicalRules()` hook                        |
| CL   | CL-11 (Consent)              | `clinical.minor_consent_age`, `clinical.sud_confidentiality_standard`           | `useClinicalRules()` hook                        |
| CL   | CL-40 (Intake)               | `clinical.intake_assessment_type`                                               | `useClinicalRules()` hook / edge function helper |
| PM   | PM-07 (Charge Capture)       | `billing.min_billable_minutes`, `billing.modifier_conventions`                  | `useBillingRules()` hook                         |
| PM   | PM-08 (Claims)               | `billing.filing_deadline_days`                                                  | `useBillingRules()` hook                         |
| PM   | PM-10 (Prior Auth)           | `billing.bhrf_urgent_pa_exempt_days`                                            | `useBillingRules()` hook                         |
| PM   | PM-18 (Scrub Rules)          | `billing.modifier_conventions`                                                  | `getJurisdictionProfile()` edge fn               |
| PM   | PM-41 (Compliance Reports)   | `billing.compliance_window_hours`                                               | `getJurisdictionProfile()` edge fn               |
| PF   | PF-91 (Compliance Dashboard) | All rule packs                                                                  | `useJurisdictionProfile()` hook                  |

**Integration Pattern:**

* **Resolution:** Database RPC `pf_resolve_jurisdiction_profile(org_id, site_id?)` merges federal baseline → state → org → site
* **Cache:** Client-side with 5min staleTime, 10min gcTime
* **Invalidation:** `pf_jurisdiction_profile_changed` event (see [EVENT\_CONTRACTS.md](./EVENT_CONTRACTS.md#pf-96-jurisdiction-profile-changed))
* **Fallback:** Profile resolution falls back to federal baseline if org profile unavailable

**Key Features:**

* State Medicaid profile seed data (Arizona AHCCCS, California Medi-Cal, Texas Medicaid, etc.)
* Organization-level and site-level profile assignment with override capability
* Federal baseline enforcement (HIPAA, 42 CFR Part 2, CMS-0057-F cannot be weakened)
* Admin UI for profile selection and override management

**Database Tables:**

* `pf_jurisdiction_profiles` — State profiles (shared reference data)
* `pf_org_jurisdiction_config` — Org-level assignment + overrides
* `pf_site_jurisdiction_config` — Site-level overrides for multi-state orgs

**Permissions:**

* `pf.jurisdiction.view` — View jurisdiction profile and rules (all org members)
* `pf.jurisdiction.admin` — Manage jurisdiction assignment and overrides (org admins)
* `pf.jurisdiction.profiles.manage` — Create/edit state profiles (platform admins only)

**Implementation Notes:**

* Profile versions use semver format; updates apply to all orgs using that profile
* Array fields (e.g., `assessment_required_elements`) replaced entirely on override (not appended)
* JSONB merge at rule-pack level (clinical, billing, compliance packs merged separately)
* Generic column aliases: `medicaid_member_id` ↔ `ahcccs_member_id`, `state_system_id` ↔ `ahcccs_cis_id`

**Documentation:**

* [PF-96 Spec](../../../specs/pf/specs/PF-96-medicaid-state-compliance-configuration.md)
* [PF-96 Integration Doc](./medicaid-state-compliance-configuration-integration.md)
* [PF-96 Plan](../../../specs/pf/plans/PF-96-medicaid-state-compliance-configuration-PLAN.md)
* [PF-96 Migration Plan](../../../specs/cross-cutting/PF-96-MIGRATION-PLAN-ahcccs-to-jurisdiction-profiles.md)

***

## Related Documentation

* [Integration Examples](../patterns/INTEGRATION_EXAMPLES.md) - Code examples
* [Event Contracts](./EVENT_CONTRACTS.md) - Event-based integration
* [API Contracts](./API_CONTRACTS.md) - API-based integration
* [Constitution](../../../constitution.md) - Engineering guardrails
* `docs/architecture/analysis/AI_INTEGRATION_STRATEGY_2026.md` - AI feature roadmap (not yet authored)
* [Mobile Gesture Guide](../../development/mobile-gesture-guide.md) - Gesture patterns

***

## PF-63: Entra ID Deep Integrations Layer

**Location:** `/src/platform/integrations/`\
**Status:** ✅ Complete\
**Version:** 1.0.0\
**Implemented:** 2026-02-21

**Public API:**

```typescript theme={null}
// Components
export { PresenceBadge } from '@/platform/integrations/components/PresenceBadge';
export { OOOBadge } from '@/platform/integrations/components/OOOBadge';
export { SharePointDocumentBrowser } from '@/platform/integrations/components/SharePointDocumentBrowser';

// Hooks — Presence
export { useEmployeePresence, useEmployeesPresenceBatch, useEmployeeOOOStatus } from '@/platform/integrations/hooks/useEmployeePresence';

// Hooks — SharePoint
export { useSharePointDocuments, useUploadToSharePoint, useSharePointDownloadUrl, useCreateSharePointFolder, useSearchSharePoint } from '@/platform/integrations/hooks/useSharePointDocuments';

// Hooks — Teams Notification Config
export { useTeamsNotificationConfig, useTeamsNotificationConfigMutation } from '@/platform/integrations/hooks/useTeamsNotificationConfig';

// Types
export type { PresenceData, OOOStatus } from '@/platform/integrations/hooks/useEmployeePresence';
export type { SharePointItem } from '@/platform/integrations/hooks/useSharePointDocuments';
export type { TeamsNotificationRule } from '@/platform/integrations/hooks/useTeamsNotificationConfig';
```

**Component Details:**

| Component                   | Purpose                                           | Props                                         |
| --------------------------- | ------------------------------------------------- | --------------------------------------------- |
| `PresenceBadge`             | Colored dot showing Teams availability            | `presence`, `size`, `showTooltip`             |
| `OOOBadge`                  | "OOO" badge indicator                             | `isOOO`, `endDate` (message redacted for PHI) |
| `SharePointDocumentBrowser` | File/folder browser with upload, download, search | `siteId`, `defaultFolder`, `className`        |

**Security:**

* All hooks filter by `organization_id`
* Mutation hooks include `created_by`/`updated_by` audit fields
* OOO message content redacted to prevent PHI exposure
* Edge functions enforce `verifyOrgAccess()` for cross-tenant isolation

**Consumer Cores:**

* HR: Employee detail pages (presence badge, OOO status)
* PF: Organization settings (notification config, SharePoint browser)
* All cores: Can embed presence indicators on employee references

***

**Next Review:** 2026-03-24 (Quarterly)
