# Phase 4 Plan 1: Add Linking Schema and Storage
## Objective
Extend BaseEntitySchema with `linkedEntities` field and add storage helpers for managing entity links.
## Context
From ROADMAP.md Phase 4 requirements:
- Add `linkedEntities` field to BaseEntitySchema
- Enable linking entities like persona → canvas, SWOT → competitive analysis
Current BaseEntitySchema in `src/schemas/index.ts`:
```typescript
export const BaseEntitySchema = z.object({
id: z.string(),
projectId: z.string(),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
researchMetadata: ResearchMetadataSchema.optional(),
});
```
## Tasks
### Task 1: Add LinkedEntitySchema to schemas
**File:** `src/schemas/index.ts`
Add schema for linked entity references:
```typescript
export const LinkedEntitySchema = z.object({
id: z.string(),
type: EntityTypeEnum,
relationship: z.string().optional(), // e.g., "informs", "validates", "supports"
});
export const BaseEntitySchema = z.object({
id: z.string(),
projectId: z.string(),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
researchMetadata: ResearchMetadataSchema.optional(),
linkedEntities: z.array(LinkedEntitySchema).optional(),
});
```
**Commit:** `feat(schemas): add linkedEntities field to BaseEntitySchema`
### Task 2: Add link/unlink storage helpers
**File:** `src/storage/index.ts`
Add functions:
```typescript
export async function linkEntities(
sourceId: string,
targetId: string,
relationship?: string
): Promise<boolean>
export async function unlinkEntities(
sourceId: string,
targetId: string
): Promise<boolean>
export async function getLinkedEntities(
entityId: string
): Promise<Array<{ entity: Entity; relationship?: string }>>
```
Implementation:
- `linkEntities`: Load source entity, add target to linkedEntities array, save
- `unlinkEntities`: Load source entity, remove target from linkedEntities, save
- `getLinkedEntities`: Load entity, resolve all linked entity IDs to full entities
**Commit:** `feat(storage): add link/unlink entity helper functions`
### Task 3: Add tests for linking functionality
**File:** `src/storage/linking.test.ts`
Test cases:
- Link two entities successfully
- Prevent duplicate links
- Unlink entities
- Get linked entities with resolved data
- Handle missing entities gracefully
**Commit:** `test(storage): add entity linking tests`
## Verification
```bash
npm test -- src/storage/linking.test.ts
npm run build
```
## Dependencies
None - this is foundational for 04-02 and 04-03.