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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# Phase 2: PostgreSQL Migration

## 🎯 Objective
Migrate from SQLite to PostgreSQL for scalability, transactional integrity, and multi-user support.

## πŸ“‹ Prerequisites
- Docker/PostgreSQL server available
- Backup of existing SQLite database
- Migration testing environment

## πŸ”§ Implementation Tasks

### Task 2.1: Database Schema Analysis & Design
**Agent**: Data Engineer
**Priority**: Critical
**Estimated Time**: 4 hours

**Deliverables**:
- [ ] Complete SQLite schema analysis
- [ ] PostgreSQL schema design document
- [ ] Data type mapping (SQLite β†’ PostgreSQL)
- [ ] Index strategy document
- [ ] Migration plan with rollback procedures

**Current Schema Analysis**:
```sql
-- From apps/backend/src/database/schema.sql
-- Tables to migrate:
- memory_entities
- memory_relations
- memory_tags
- raw_documents
- structured_facts
- evolution_kpis
- decisions
- pal_focus_windows
- pal_stress_levels
```

**PostgreSQL Equivalents**:
```sql
-- Type Mappings
INTEGER PRIMARY KEY AUTOINCREMENT β†’ SERIAL PRIMARY KEY
TEXT β†’ TEXT or VARCHAR(n)
REAL β†’ NUMERIC(precision, scale)
BLOB β†’ BYTEA
TIMESTAMP β†’ TIMESTAMP WITH TIME ZONE
```

### Task 2.2: Set Up PostgreSQL Infrastructure
**Agent**: DevOps Engineer
**Priority**: Critical
**Estimated Time**: 3 hours

**Deliverables**:
```yaml
# docker-compose.yml - Add PostgreSQL service
services:
  postgres:
    image: postgres:16-alpine
    container_name: widgettdc-postgres
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: widgettdc
    ports:
      - "5432:5432"
    volumes:
      - postgres-data:/var/lib/postgresql/data
      - ./apps/backend/src/database/init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - widgettdc-network

  pgadmin:
    image: dpage/pgadmin4
    container_name: widgettdc-pgadmin
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}
    ports:
      - "5050:80"
    networks:
      - widgettdc-network

volumes:
  postgres-data:

networks:
  widgettdc-network:
    driver: bridge
```

**Environment Configuration**:
```bash
# .env
DATABASE_TYPE=postgres
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=widgettdc_user
POSTGRES_PASSWORD=secure_password_here
POSTGRES_DB=widgettdc
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}
```

### Task 2.3: Implement ORM with Prisma
**Agent**: Backend Engineer
**Priority**: Critical
**Estimated Time**: 6 hours

**Deliverables**:
```prisma
// apps/backend/prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model MemoryEntity {
  id           Int               @id @default(autoincrement())
  orgId        String            @map("org_id") @db.VarChar(255)
  text         String
  metadata     Json?
  createdAt    DateTime          @default(now()) @map("created_at") @db.Timestamptz
  updatedAt    DateTime          @updatedAt @map("updated_at") @db.Timestamptz

  relations    MemoryRelation[]  @relation("MemoryEntityRelations")
  tags         MemoryTag[]

  @@index([orgId])
  @@index([createdAt])
  @@map("memory_entities")
}

model MemoryRelation {
  id              Int          @id @default(autoincrement())
  sourceId        Int          @map("source_id")
  targetId        Int          @map("target_id")
  relationType    String       @map("relation_type") @db.VarChar(100)
  strength        Decimal      @default(1.0) @db.Decimal(3, 2)

  sourceEntity    MemoryEntity @relation("MemoryEntityRelations", fields: [sourceId], references: [id], onDelete: Cascade)

  @@index([sourceId])
  @@index([targetId])
  @@map("memory_relations")
}

model MemoryTag {
  id        Int          @id @default(autoincrement())
  entityId  Int          @map("entity_id")
  tag       String       @db.VarChar(100)

  entity    MemoryEntity @relation(fields: [entityId], references: [id], onDelete: Cascade)

  @@index([entityId])
  @@index([tag])
  @@map("memory_tags")
}

model RawDocument {
  id          Int      @id @default(autoincrement())
  orgId       String   @map("org_id") @db.VarChar(255)
  title       String?  @db.VarChar(500)
  content     String
  source      String?  @db.VarChar(200)
  ingestedAt  DateTime @default(now()) @map("ingested_at") @db.Timestamptz

  @@index([orgId])
  @@index([ingestedAt])
  @@map("raw_documents")
}

model StructuredFact {
  id        Int      @id @default(autoincrement())
  orgId     String   @map("org_id") @db.VarChar(255)
  subject   String   @db.VarChar(500)
  predicate String   @db.VarChar(200)
  object    String
  docId     Int?     @map("doc_id")

  @@index([orgId])
  @@index([subject])
  @@map("structured_facts")
}

model EvolutionKpi {
  id            Int      @id @default(autoincrement())
  decisionId    Int      @map("decision_id")
  kpiName       String   @map("kpi_name") @db.VarChar(200)
  expectedValue Decimal  @map("expected_value") @db.Decimal(10, 2)
  actualValue   Decimal? @map("actual_value") @db.Decimal(10, 2)
  measuredAt    DateTime @map("measured_at") @db.Timestamptz

  @@index([decisionId])
  @@index([measuredAt])
  @@map("evolution_kpis")
}

model Decision {
  id          Int      @id @default(autoincrement())
  orgId       String   @map("org_id") @db.VarChar(255)
  title       String   @db.VarChar(500)
  description String?
  madeAt      DateTime @map("made_at") @db.Timestamptz

  @@index([orgId])
  @@index([madeAt])
  @@map("decisions")
}

model PalFocusWindow {
  id        Int      @id @default(autoincrement())
  userId    String   @map("user_id") @db.VarChar(255)
  startTime DateTime @map("start_time") @db.Timestamptz
  endTime   DateTime @map("end_time") @db.Timestamptz
  priority  String   @db.VarChar(50)

  @@index([userId])
  @@index([startTime])
  @@map("pal_focus_windows")
}

model PalStressLevel {
  id          Int      @id @default(autoincrement())
  userId      String   @map("user_id") @db.VarChar(255)
  level       Int      @db.SmallInt
  measuredAt  DateTime @map("measured_at") @db.Timestamptz

  @@index([userId])
  @@index([measuredAt])
  @@map("pal_stress_levels")
}
```

**Database Client Implementation**:
```typescript
// apps/backend/src/database/prisma.ts
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

export const prisma = globalForPrisma.prisma ?? new PrismaClient({
  log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma;
}

export default prisma;
```

### Task 2.4: Update Repository Layer
**Agent**: Backend Engineer
**Priority**: Critical
**Estimated Time**: 8 hours

**Deliverables**:
```typescript
// apps/backend/src/services/memory/memoryRepository.ts
import prisma from '../../database/prisma.js';
import { MemoryEntity, Prisma } from '@prisma/client';

export class MemoryRepository {
  async ingestMemory(input: MemoryIngestInput): Promise<MemoryEntity> {
    return await prisma.memoryEntity.create({
      data: {
        orgId: input.orgId,
        text: input.text,
        metadata: input.metadata,
        tags: {
          create: input.tags?.map(tag => ({ tag })) ?? [],
        },
      },
      include: {
        tags: true,
      },
    });
  }

  async searchMemories(orgId: string, query: string): Promise<MemoryEntity[]> {
    return await prisma.memoryEntity.findMany({
      where: {
        orgId,
        text: {
          contains: query,
          mode: 'insensitive',
        },
      },
      include: {
        tags: true,
        relations: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });
  }

  async getMemoryById(id: number): Promise<MemoryEntity | null> {
    return await prisma.memoryEntity.findUnique({
      where: { id },
      include: {
        tags: true,
        relations: true,
      },
    });
  }

  async updateMemory(id: number, data: Partial<MemoryIngestInput>): Promise<MemoryEntity> {
    return await prisma.memoryEntity.update({
      where: { id },
      data: {
        text: data.text,
        metadata: data.metadata,
      },
    });
  }

  async deleteMemory(id: number): Promise<void> {
    await prisma.memoryEntity.delete({
      where: { id },
    });
  }

  // Complex query example with relations
  async getMemoriesWithRelations(orgId: string): Promise<MemoryEntity[]> {
    return await prisma.memoryEntity.findMany({
      where: { orgId },
      include: {
        tags: true,
        relations: {
          include: {
            sourceEntity: {
              select: {
                id: true,
                text: true,
              },
            },
          },
        },
      },
    });
  }
}
```

### Task 2.5: Data Migration Script
**Agent**: Data Engineer
**Priority**: Critical
**Estimated Time**: 6 hours

**Deliverables**:
```typescript
// apps/backend/src/database/migrate-sqlite-to-postgres.ts
import Database from 'better-sqlite3';
import prisma from './prisma.js';

interface SQLiteRow {
  [key: string]: any;
}

async function migrateSQLiteToPostgres() {
  console.log('Starting SQLite to PostgreSQL migration...');

  // Connect to SQLite
  const sqlite = new Database('./widget-tdc.db', { readonly: true });

  try {
    // 1. Migrate memory_entities
    console.log('Migrating memory_entities...');
    const memoryEntities = sqlite.prepare('SELECT * FROM memory_entities').all() as SQLiteRow[];

    for (const entity of memoryEntities) {
      await prisma.memoryEntity.create({
        data: {
          id: entity.id,
          orgId: entity.org_id,
          text: entity.text,
          metadata: entity.metadata ? JSON.parse(entity.metadata) : null,
          createdAt: new Date(entity.created_at),
          updatedAt: new Date(entity.updated_at),
        },
      });
    }
    console.log(`Migrated ${memoryEntities.length} memory entities`);

    // 2. Migrate memory_tags
    console.log('Migrating memory_tags...');
    const tags = sqlite.prepare('SELECT * FROM memory_tags').all() as SQLiteRow[];

    for (const tag of tags) {
      await prisma.memoryTag.create({
        data: {
          id: tag.id,
          entityId: tag.entity_id,
          tag: tag.tag,
        },
      });
    }
    console.log(`Migrated ${tags.length} tags`);

    // 3. Migrate memory_relations
    console.log('Migrating memory_relations...');
    const relations = sqlite.prepare('SELECT * FROM memory_relations').all() as SQLiteRow[];

    for (const relation of relations) {
      await prisma.memoryRelation.create({
        data: {
          id: relation.id,
          sourceId: relation.source_id,
          targetId: relation.target_id,
          relationType: relation.relation_type,
          strength: relation.strength,
        },
      });
    }
    console.log(`Migrated ${relations.length} relations`);

    // 4. Migrate raw_documents
    console.log('Migrating raw_documents...');
    const documents = sqlite.prepare('SELECT * FROM raw_documents').all() as SQLiteRow[];

    for (const doc of documents) {
      await prisma.rawDocument.create({
        data: {
          id: doc.id,
          orgId: doc.org_id,
          title: doc.title,
          content: doc.content,
          source: doc.source,
          ingestedAt: new Date(doc.ingested_at),
        },
      });
    }
    console.log(`Migrated ${documents.length} documents`);

    // 5. Migrate structured_facts
    console.log('Migrating structured_facts...');
    const facts = sqlite.prepare('SELECT * FROM structured_facts').all() as SQLiteRow[];

    for (const fact of facts) {
      await prisma.structuredFact.create({
        data: {
          id: fact.id,
          orgId: fact.org_id,
          subject: fact.subject,
          predicate: fact.predicate,
          object: fact.object,
          docId: fact.doc_id,
        },
      });
    }
    console.log(`Migrated ${facts.length} facts`);

    // 6-9. Migrate remaining tables...
    // (evolution_kpis, decisions, pal_focus_windows, pal_stress_levels)

    console.log('Migration completed successfully!');

    // Verify migration
    const counts = {
      memoryEntities: await prisma.memoryEntity.count(),
      tags: await prisma.memoryTag.count(),
      relations: await prisma.memoryRelation.count(),
      documents: await prisma.rawDocument.count(),
      facts: await prisma.structuredFact.count(),
    };

    console.log('PostgreSQL record counts:', counts);
  } catch (error) {
    console.error('Migration failed:', error);
    throw error;
  } finally {
    sqlite.close();
    await prisma.$disconnect();
  }
}

// Run migration
migrateSQLiteToPostgres()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
```

**Test Cases**:
```typescript
describe('PostgreSQL Migration', () => {
  it('should migrate all memory entities', async () => {
    const sqliteCount = await getSQLiteCount('memory_entities');
    const pgCount = await prisma.memoryEntity.count();
    expect(pgCount).toBe(sqliteCount);
  });

  it('should preserve data integrity', async () => {
    // Compare sample records
    const sqliteRecord = getSQLiteRecord('memory_entities', 1);
    const pgRecord = await prisma.memoryEntity.findUnique({ where: { id: 1 } });

    expect(pgRecord?.text).toBe(sqliteRecord.text);
    expect(pgRecord?.orgId).toBe(sqliteRecord.org_id);
  });

  it('should maintain foreign key relationships', async () => {
    const memoryWithRelations = await prisma.memoryEntity.findFirst({
      include: { relations: true },
    });

    expect(memoryWithRelations?.relations).toBeDefined();
    // Verify relation integrity
  });
});
```

## πŸ“Š Success Criteria

- [ ] PostgreSQL running in Docker/production
- [ ] Prisma schema matches all SQLite tables
- [ ] All data migrated without loss
- [ ] Indexes created for performance
- [ ] Repository layer updated and tested
- [ ] Performance benchmarks show improvement
- [ ] Concurrent operations work without deadlocks
- [ ] All integration tests pass

## πŸš€ Deployment Checklist

- [ ] Backup SQLite database
- [ ] Set up PostgreSQL server
- [ ] Run Prisma migrations
- [ ] Execute data migration script
- [ ] Verify data integrity
- [ ] Update connection strings
- [ ] Test backend services
- [ ] Monitor performance
- [ ] Document rollback procedure

---

**Next Phase**: Phase 3 - Vector Embeddings & LLM Integration