> ## Documentation Index
> Fetch the complete documentation index at: https://docs-terra.withunify.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Shared Packages

> Common infrastructure shared across all Unify applications

# Shared Packages

All Unify applications share common infrastructure through packages in the monorepo. This ensures consistency, reduces duplication, and makes cross-app features possible.

```
packages/
├── database/     # Supabase types, client, schemas
├── identity/     # Applicant management, profiles
├── extraction/   # Document extraction (OCR, AI)
├── ai/           # Shared LLM utilities
└── ui/           # React component library
```

***

## @unify/database

Shared database types and Supabase client configuration.

### What It Provides

* **TypeScript types** generated from Supabase schema
* **Supabase client** initialization with proper configuration
* **Zod schemas** for runtime validation
* **Privacy-aware patterns** for handling PII

### Key Patterns

#### Verified Fields

Track the source and evidence for every piece of applicant data:

```typescript theme={null}
interface VerifiedField<T> {
  value: T;
  verified: boolean;
  verifiedAt?: string;
  verificationSource?: 'user' | 'admin' | 'system_ocr' | 'partner_api';
  evidenceDocumentId?: string;
}
```

#### Privacy Proxy

Separate queryable metadata from encrypted sensitive values:

```typescript theme={null}
// Queryable (in applicant_profiles)
has_ssn: boolean;
citizenship_status: 'citizen' | 'permanent_resident' | 'other';

// Encrypted (in applicant_pii)
ssn_encrypted: string; // AES-256 encrypted
```

***

## @unify/identity

Unified applicant identity management across all applications.

### What It Provides

* **Applicant linking** across Terra, Pathfinder, and external systems
* **Profile management** with verification tracking
* **History tracking** for all applications and interactions

### Core Schema

```typescript theme={null}
// Core linking table
interface Applicant {
  id: string;
  workosId?: string;      // Authenticated user
  sessionId?: string;     // Anonymous session
  email?: string;
  displayName?: string;
  createdAt: string;
}

// Non-PII, fully queryable
interface ApplicantProfile {
  applicantId: string;
  householdSize: number;
  monthlyIncomeCents: number;
  needsFlags: NeedsFlags;
  citizenshipStatus: string;
  verificationScore: number; // 0-100
}

// Encrypted sensitive data
interface ApplicantPii {
  applicantId: string;
  firstName: string;
  lastName: string;
  ssnEncrypted?: string;
  dateOfBirth?: string;
}
```

### Usage

```typescript theme={null}
import { getApplicantByEmail, createApplicant } from '@unify/identity';

// Find or create applicant
const applicant = await getApplicantByEmail('user@example.com');

// Get full profile with history
const profile = await getApplicantProfile(applicant.id);
```

***

## @unify/extraction

Document extraction service for OCR and AI-powered data extraction.

<Note>
  This package is planned for the Foundation Phase. Documentation will be expanded as implementation progresses.
</Note>

### Planned Capabilities

| Document Type    | Extracted Fields                                          |
| ---------------- | --------------------------------------------------------- |
| Paystubs         | Employer name, gross pay, net pay, pay period, YTD totals |
| Government ID    | Name, date of birth, ID number, expiration, address       |
| Bank Statements  | Account holder, account number, balance, transactions     |
| Proof of Address | Name, address, date, document type                        |
| Utility Bills    | Account holder, service address, amount due, due date     |

### Planned Interface

```typescript theme={null}
import { extractDocument } from '@unify/extraction';

const result = await extractDocument(file, {
  type: 'paystub',
  options: {
    extractEmployer: true,
    extractPayPeriod: true,
    extractYtd: true,
  }
});

// Returns typed extraction result
result.data.employerName;    // "Acme Corp"
result.data.grossPay;        // 250000 (cents)
result.data.payPeriod;       // { start: "2024-01-01", end: "2024-01-15" }
result.confidence;           // 0.95
```

### Integration Points

* **Terra**: Auto-fill form fields from uploaded documents
* **Sentinel**: Analyze documents for fraud indicators
* **Airtable**: Exposed via API for external systems

***

## @unify/ai

Shared AI/LLM utilities for all applications.

<Note>
  This package is planned for the Intelligence Layer Phase. Documentation will be expanded as implementation progresses.
</Note>

### Planned Capabilities

#### Chat/Completion

```typescript theme={null}
import { chat } from '@unify/ai';

const response = await chat([
  { role: 'system', content: 'You are a benefits program expert.' },
  { role: 'user', content: 'What documentation is typically required for rental assistance?' }
], {
  model: 'claude-sonnet',
  temperature: 0.3,
});
```

#### Embeddings

```typescript theme={null}
import { embed } from '@unify/ai';

const embedding = await embed('Emergency rental assistance program for low-income families');
// Returns: number[] (1536 dimensions)
```

#### RAG (Retrieval-Augmented Generation)

```typescript theme={null}
import { rag } from '@unify/ai';

const answer = await rag({
  query: 'What income limits do similar programs use?',
  documents: existingProgramDocs,
  options: {
    maxTokens: 1000,
    citeSources: true,
  }
});
```

#### Translation

```typescript theme={null}
import { translate, translateBatch } from '@unify/ai';

// Single translation
const spanish = await translate('Your application has been approved', 'es');

// Batch translation for all program messaging
const translations = await translateBatch(messagingVariants, ['es', 'vi', 'zh', 'ko']);
```

***

## @unify/ui

Shared React component library based on Shadcn UI.

### What It Provides

* **Radix UI primitives** with Tailwind styling
* **CVA (Class Variance Authority)** for component variants
* **Consistent design system** across all applications

### Usage

```typescript theme={null}
import { Button, Card, Input, Dialog } from '@unify/ui';

function MyComponent() {
  return (
    <Card>
      <Input placeholder="Enter your email" />
      <Button variant="primary">Submit</Button>
    </Card>
  );
}
```

### Design Tokens

| Token        | Value       | Usage                |
| ------------ | ----------- | -------------------- |
| `background` | `slate-50`  | Page backgrounds     |
| `card`       | `white`     | Card backgrounds     |
| `border`     | `slate-200` | Borders and dividers |
| `primary`    | `#0F172A`   | Primary actions      |
| `muted`      | `slate-500` | Secondary text       |

***

## Package Dependencies

```mermaid theme={null}
flowchart TD
    Terra[apps/terra] --> Database[@unify/database]
    Terra --> Identity[@unify/identity]
    Terra --> Extraction[@unify/extraction]
    Terra --> UI[@unify/ui]

    Pathfinder[apps/pathfinder] --> Database
    Pathfinder --> Identity
    Pathfinder --> UI

    Forge[apps/forge] --> Database
    Forge --> AI[@unify/ai]
    Forge --> UI

    Sentinel[apps/sentinel] --> Database
    Sentinel --> Identity
    Sentinel --> Extraction
    Sentinel --> AI
    Sentinel --> UI

    Hub[apps/hub] --> Database
    Hub --> Identity
    Hub --> UI

    Extraction --> AI
```

***

## Adding a New Package

1. Create the package directory:

```bash theme={null}
mkdir -p packages/my-package/src
```

2. Add `package.json`:

```json theme={null}
{
  "name": "@unify/my-package",
  "version": "0.0.1",
  "main": "./src/index.ts",
  "types": "./src/index.ts",
  "scripts": {
    "build": "tsc",
    "test": "vitest"
  }
}
```

3. Add to app dependencies:

```json theme={null}
{
  "dependencies": {
    "@unify/my-package": "workspace:*"
  }
}
```

4. Import in your app:

```typescript theme={null}
import { myFunction } from '@unify/my-package';
```
