Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
[issue-9519] Preserve memory graphs when legacy migration fails (#9543)
[._.]/5605552709aa
diff --git a/server/scripts/migrateMemoryToPg.db.test.js b/server/scripts/migrateMemoryToPg.db.test.jsnew file mode 100644index 0000000000..dd73f58c38--- /dev/null+++ b/server/scripts/migrateMemoryToPg.db.test.js@@ -0,0 +1,84 @@+import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { checkHealth, close, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { migrate } from './migrateMemoryToPg.js';++// This replacement workflow necessarily owns the whole memory table. The DB+// config serializes suites and db.js refuses runner writes outside a test DB.+const health = await checkHealth();+const runDb = requireDbOrSkip('scripts/migrateMemoryToPg.db.test', health.connected && health.hasSchema, health.error || 'memory schema unavailable');+const oldA = '00000000-0000-4000-8000-000000000010';+const oldB = '00000000-0000-4000-8000-000000000011';+const newA = '00000000-0000-4000-8000-000000000020';+const newB = '00000000-0000-4000-8000-000000000021';+const missing = '00000000-0000-4000-8000-000000000099';+let dir;++const snapshot = async () => ({+ memories: (await query('SELECT * FROM memories ORDER BY id')).rows,+ links: (await query('SELECT * FROM memory_links ORDER BY source_id, target_id')).rows,+});++async function writeSource(records) {+ await writeFile(join(dir, 'index.json'), JSON.stringify({ memories: records.map(({ id, type }) => ({ id, type })) }));+ for (const record of records) {+ await mkdir(join(dir, 'memories', record.id), { recursive: true });+ await writeFile(join(dir, 'memories', record.id, 'memory.json'), JSON.stringify(record));+ }+}++const records = () => [+ { id: newA, type: 'fact', content: 'First replacement', relatedMemories: [newB] },+ { id: newB, type: 'fact', content: 'Forward target', relatedMemories: [] },+];++afterAll(() => close());++describe.skipIf(!runDb)('atomic memory migration in PostgreSQL', () => {+ beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'memory-migration-db-'));+ await query('DELETE FROM memories');+ await query("INSERT INTO memories (id, type, content) VALUES ($1, 'fact', 'Previous first'), ($2, 'fact', 'Previous second')", [oldA, oldB]);+ await query('INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2)', [oldA, oldB]);+ });++ afterEach(async () => {+ await query('DELETE FROM memories');+ await rm(dir, { recursive: true, force: true });+ });++ it.each(['malformed source', 'record constraint', 'link constraint'])('preserves the previous graph on %s failure', async failure => {+ const source = records();+ if (failure === 'record constraint') source[1].content = null;+ if (failure === 'link constraint') source[0].relatedMemories = [missing];+ await writeSource(source);+ if (failure === 'malformed source') await writeFile(join(dir, 'memories', newB, 'memory.json'), '{ malformed');+ const before = await snapshot();++ const error = await migrate({ memoryDir: dir, execute: true, clearFirst: true }).then(() => null, err => err);+ // Persisted state is the rollback contract, independent of SQL-call mocks.+ expect(await snapshot()).toEqual(before);+ expect(error).toBeInstanceOf(Error);+ if (failure === 'record constraint') expect(error.code).toBe('23502');+ if (failure === 'link constraint') expect(error.code).toBe('23503');+ if (failure === 'malformed source') expect(error).toBeInstanceOf(SyntaxError);+ });++ it('replaces the graph with forward links, then replays without overwriting records', async () => {+ await writeSource(records());+ expect(await migrate({ memoryDir: dir, execute: true, clearFirst: true })).toEqual({ inserted: 2, skipped: 0, links: 1, total: 2 });+ const imported = await snapshot();+ expect(imported.memories.map(({ id, content }) => ({ id, content }))).toEqual([+ { id: newA, content: 'First replacement' }, { id: newB, content: 'Forward target' },+ ]);+ expect(imported.links.map(({ source_id, target_id }) => [source_id, target_id])).toEqual([[newA, newB]]);+ const replay = records();+ replay[0].content = null; // An incomplete replay must still skip the stored record.+ await writeSource(replay);+ expect(await migrate({ memoryDir: dir, execute: true })).toEqual({ inserted: 0, skipped: 2, links: 0, total: 2 });+ expect(await snapshot()).toEqual(imported);+ });+});diff --git a/server/scripts/migrateMemoryToPg.js b/server/scripts/migrateMemoryToPg.jsindex bf81fbd55e..a30928ff2a 100644--- a/server/scripts/migrateMemoryToPg.js+++ b/server/scripts/migrateMemoryToPg.js@@ -16,21 +16,13 @@* - Schema must be initialized (happens automatically via init-db.sql)*/-import { readFile, readdir } from 'fs/promises';+import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { query, close } from '../lib/db.js';+import { query, withTransaction, close } from '../lib/db.js';+import { isDirectlyInvoked } from '../../scripts/lib/directInvocation.js';import { PATHS } from '../lib/fileUtils.js';-const MEMORY_DIR = PATHS.memory;-const INDEX_FILE = join(MEMORY_DIR, 'index.json');-const EMBEDDINGS_FILE = join(MEMORY_DIR, 'embeddings.json');-const MEMORIES_DIR = join(MEMORY_DIR, 'memories');--const args = process.argv.slice(2);-const execute = args.includes('--execute');-const clearFirst = args.includes('--clear');-async function loadJSON(path) {const content = await readFile(path, 'utf-8');return JSON.parse(content);@@ -41,71 +33,35 @@ function arrayToPgvector(arr) {return `[${arr.join(',')}]`;}-async function migrate() {+export async function migrate({ memoryDir = PATHS.memory, execute = false, clearFirst = false } = {}) {+ const indexFile = join(memoryDir, 'index.json');+ const embeddingsFile = join(memoryDir, 'embeddings.json');+ const memoriesDir = join(memoryDir, 'memories');console.log('🧠 Memory Migration: JSON → PostgreSQL');console.log(` Mode: ${execute ? 'EXECUTE' : 'DRY RUN (add --execute to write)'}`);console.log('');// 1. Check source files exist- if (!existsSync(INDEX_FILE)) {+ if (!existsSync(indexFile)) {console.log('⚠️ No index.json found — nothing to migrate');return;}// 2. Load index and embeddings- const index = await loadJSON(INDEX_FILE);+ const index = await loadJSON(indexFile);console.log(`📋 Index: ${index.memories.length} memory entries`);let embeddings = { vectors: {} };- if (existsSync(EMBEDDINGS_FILE)) {- embeddings = await loadJSON(EMBEDDINGS_FILE);+ if (existsSync(embeddingsFile)) {+ embeddings = await loadJSON(embeddingsFile);console.log(`🧮 Embeddings: ${Object.keys(embeddings.vectors).length} vectors`);}- // 3. Load each full memory from disk- const memoryDirs = existsSync(MEMORIES_DIR)- ? await readdir(MEMORIES_DIR).catch(() => [])- : [];- console.log(`📁 Memory files: ${memoryDirs.length} directories`);- console.log('');-- // 4. Check DB connection- const dbCheck = await query('SELECT 1 AS ok').catch(err => {- console.error(`❌ Cannot connect to PostgreSQL: ${err.message}`);- console.error(' Is the database running? Try: docker compose up -d');- process.exit(1);- });- console.log('✅ PostgreSQL connected');-- // Check schema- const schemaCheck = await query(- "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'memories') AS has_table"- );- if (!schemaCheck.rows[0].has_table) {- console.error('❌ memories table not found. Run init-db.sql first.');- process.exit(1);- }- console.log('✅ Schema verified');-- // 5. Clear if requested- if (execute && clearFirst) {- await query('DELETE FROM memory_links');- await query('DELETE FROM memories');- console.log('🗑️ Cleared existing data');- }-- // 6. Check existing count- const existing = await query('SELECT COUNT(*) AS count FROM memories');- console.log(`📊 Existing DB records: ${existing.rows[0].count}`);- console.log('');-- // 7. Migrate each memory- let inserted = 0;- let skipped = 0;- let errors = 0;-+ // Read every source before opening the replacement transaction. A corrupt+ // later record must never leave an already-cleared database behind.+ const records = [];for (const meta of index.memories) {- const memoryFile = join(MEMORIES_DIR, meta.id, 'memory.json');+ const memoryFile = join(memoriesDir, meta.id, 'memory.json');let memory;if (existsSync(memoryFile)) {@@ -134,110 +90,97 @@ async function migrate() {};}- const embedding = embeddings.vectors[meta.id] || null;-- if (!execute) {- console.log(` [DRY] ${meta.id} — ${memory.type}: ${(memory.summary || '').substring(0, 60)}...`);- inserted++;- continue;+ if (memory.relatedMemories != null && !Array.isArray(memory.relatedMemories)) {+ throw new Error(`Invalid relatedMemories for ${meta.id}`);}+ const embedding = embeddings.vectors[meta.id] || null;+ records.push({ memory, embedding });+ }- // Check if already exists- const existCheck = await query('SELECT 1 FROM memories WHERE id = $1', [memory.id]);- if (existCheck.rows.length > 0) {- skipped++;- continue;- }+ await query('SELECT 1 AS ok');+ const schemaCheck = await query(+ "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'memories') AS has_table"+ );+ if (!schemaCheck.rows[0].has_table) throw new Error('memories table not found. Run init-db.sql first.');+ console.log('✅ PostgreSQL connected and schema verified');- const insertResult = await query(- `INSERT INTO memories (- id, type, content, summary, category, tags,- embedding, embedding_model, confidence, importance,- access_count, last_accessed,- source_task_id, source_agent_id, source_app_id,- expires_at, status, created_at, updated_at- ) VALUES (- $1, $2, $3, $4, $5, $6,- $7, $8, $9, $10,- $11, $12,- $13, $14, $15,- $16, $17, $18, $19- )`,- [- memory.id, memory.type, memory.content, memory.summary,- memory.category || 'other', memory.tags || [],- embedding ? arrayToPgvector(embedding) : null,- memory.embeddingModel || (embedding ? 'text-embedding-nomic-embed-text-v2-moe' : null),- memory.confidence ?? 0.8, memory.importance ?? 0.5,- memory.accessCount || 0, memory.lastAccessed || null,- memory.sourceTaskId || null, memory.sourceAgentId || null, memory.sourceAppId || null,- memory.expiresAt || null, memory.status || 'active',- memory.createdAt || new Date().toISOString(), memory.updatedAt || new Date().toISOString()- ]- ).catch(err => {- console.error(` ❌ ${meta.id}: ${err.message}`);- errors++;- return null;- });+ if (!execute) {+ console.log(`📊 Would import ${records.length} memories${clearFirst ? ' after clearing existing data' : ''}`);+ console.log('ℹ️ This was a dry run. Add --execute to perform the migration.');+ return { inserted: 0, skipped: 0, links: 0 };+ }- if (insertResult) {- inserted++;-- // Migrate related memory links- if (memory.relatedMemories?.length > 0) {- for (const relId of memory.relatedMemories) {- await query(- 'INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',- [memory.id, relId]- ).catch(() => {}); // Skip if target doesn't exist yet- }+ const result = await withTransaction(async client => {+ if (clearFirst) {+ await client.query('DELETE FROM memory_links');+ await client.query('DELETE FROM memories');+ }+ let inserted = 0;+ let skipped = 0;+ let links = 0;+ for (const { memory, embedding } of records) {+ // Preserve legacy replay semantics even when an existing record's source+ // body is incomplete; PostgreSQL checks NOT NULL before ON CONFLICT.+ const existing = await client.query('SELECT 1 FROM memories WHERE id = $1', [memory.id]);+ if (existing.rows.length > 0) {+ skipped++;+ continue;}+ const insertResult = await client.query(+ `INSERT INTO memories (+ id, type, content, summary, category, tags,+ embedding, embedding_model, confidence, importance,+ access_count, last_accessed,+ source_task_id, source_agent_id, source_app_id,+ expires_at, status, created_at, updated_at+ ) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, $10,+ $11, $12,+ $13, $14, $15,+ $16, $17, $18, $19+ ) ON CONFLICT (id) DO NOTHING`,+ [+ memory.id, memory.type, memory.content, memory.summary,+ memory.category || 'other', memory.tags || [],+ embedding ? arrayToPgvector(embedding) : null,+ memory.embeddingModel || (embedding ? 'text-embedding-nomic-embed-text-v2-moe' : null),+ memory.confidence ?? 0.8, memory.importance ?? 0.5,+ memory.accessCount || 0, memory.lastAccessed || null,+ memory.sourceTaskId || null, memory.sourceAgentId || null, memory.sourceAppId || null,+ memory.expiresAt || null, memory.status || 'active',+ memory.createdAt || new Date().toISOString(), memory.updatedAt || new Date().toISOString()+ ]+ );+ if (insertResult.rowCount > 0) inserted++;+ else skipped++;}- }-- // 8. Second pass: retry links (some targets may not have existed on first pass)- if (execute) {- let linksFixed = 0;- for (const meta of index.memories) {- const memoryFile = join(MEMORIES_DIR, meta.id, 'memory.json');- if (!existsSync(memoryFile)) continue;-- const memory = await loadJSON(memoryFile);- if (!memory.relatedMemories?.length) continue;- for (const relId of memory.relatedMemories) {- const result = await query(+ // Every record exists before links are inserted, including forward links.+ // Replay may add links but never overwrites an existing memory's content.+ for (const { memory } of records) {+ for (const relId of memory.relatedMemories || []) {+ const link = await client.query('INSERT INTO memory_links (source_id, target_id) VALUES ($1, $2) ON CONFLICT DO NOTHING',[memory.id, relId]- ).catch(() => null);- if (result?.rowCount > 0) linksFixed++;+ );+ links += link.rowCount;}}- if (linksFixed > 0) console.log(`🔗 Fixed ${linksFixed} memory links on second pass`);- }-- // 9. Report- console.log('');- console.log('📊 Migration Summary:');- console.log(` Inserted: ${inserted}`);- console.log(` Skipped (already exists): ${skipped}`);- console.log(` Errors: ${errors}`);-- if (execute) {- const finalCount = await query('SELECT COUNT(*) AS count FROM memories');- console.log(` Total in DB: ${finalCount.rows[0].count}`);- }+ const count = await client.query('SELECT COUNT(*) AS count FROM memories');+ return { inserted, skipped, links, total: Number(count.rows[0].count) };+ });- if (!execute) {- console.log('');- console.log('ℹ️ This was a dry run. Add --execute to perform the migration.');- }+ console.log(`📊 Migration Summary: inserted ${result.inserted}, skipped ${result.skipped}, links ${result.links}, total ${result.total}`);+ return result;}-migrate()- .catch(err => {- console.error(`💥 Migration failed: ${err.message}`);- console.error(err.stack);- process.exit(1);- })- .finally(() => close());+if (isDirectlyInvoked(import.meta.url)) {+ const args = process.argv.slice(2);+ migrate({ execute: args.includes('--execute'), clearFirst: args.includes('--clear') })+ .finally(() => close())+ .catch(err => {+ console.error(`💥 Migration failed: ${err.message}`);+ process.exitCode = 1;+ });+}diff --git a/server/scripts/migrateMemoryToPg.test.js b/server/scripts/migrateMemoryToPg.test.jsnew file mode 100644index 0000000000..8b7b5c95c5--- /dev/null+++ b/server/scripts/migrateMemoryToPg.test.js@@ -0,0 +1,95 @@+import { afterEach, describe, expect, it } from 'vitest';+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const execFileAsync = promisify(execFile);+const script = fileURLToPath(new URL('./migrateMemoryToPg.js', import.meta.url));+const dirs = [];+afterEach(async () => Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))));++async function fixture(failure = '') {+ const dir = await mkdtemp(join(tmpdir(), 'memory-migration-cli-'));+ dirs.push(dir);+ const id = '00000000-0000-4000-8000-000000000001';+ const target = '00000000-0000-4000-8000-000000000002';+ await mkdir(join(dir, 'memories', id), { recursive: true });+ const sources = {+ 'index.json': JSON.stringify({ memories: [{ id, type: 'fact' }, { id: target, type: 'fact', summary: 'Fallback record' }] }),+ 'embeddings.json': JSON.stringify({ vectors: {} }),+ [`memories/${id}/memory.json`]: JSON.stringify({ id, type: 'fact', content: 'Synthetic memory', relatedMemories: [target] }),+ };+ await Promise.all(Object.entries(sources).map(([name, data]) => writeFile(join(dir, name), data)));+ // Only the database and source root are doubled. Node runs the shipped CLI,+ // including its argument parsing, direct-invocation guard and exit handling.+ const dbSource = `+ export async function query(sql) {+ if (/^(DELETE|INSERT|UPDATE)/.test(sql.trim())) console.log('DB_WRITE');+ if (${JSON.stringify(failure)} === 'record' && sql.includes('INSERT INTO memories')) throw new Error('injected record failure');+ if (${JSON.stringify(failure)} === 'link' && sql.includes('INSERT INTO memory_links')) throw new Error('injected link failure');+ if (sql.includes('information_schema')) return { rows: [{ has_table: true }] };+ if (sql.includes('COUNT')) return { rows: [{ count: 0 }] };+ return { rows: [], rowCount: 1 };+ }+ export const withTransaction = fn => fn({ query });+ export async function close() { console.log('DB_CLOSED'); }+ `;+ const loader = join(dir, 'loader.mjs');+ await writeFile(loader, `+ import { registerHooks } from 'node:module';+ const modules = {+ '../lib/db.js': ${JSON.stringify(dbSource)},+ '../lib/fileUtils.js': ${JSON.stringify(`export const PATHS = { memory: ${JSON.stringify(dir)} };`)},+ };+ registerHooks({ resolve(specifier, context, nextResolve) {+ if (context.parentURL?.endsWith('/migrateMemoryToPg.js') && modules[specifier]) {+ return { url: 'data:text/javascript,' + encodeURIComponent(modules[specifier]), shortCircuit: true };+ }+ return nextResolve(specifier, context);+ } });+ `);+ const run = async (args = []) => execFileAsync(process.execPath, ['--import', pathToFileURL(loader).href, script, ...args], { timeout: 15000 })+ .then(result => ({ ...result, code: 0 }), error => ({ stdout: error.stdout, stderr: error.stderr, code: error.code }));+ const importModule = () => execFileAsync(process.execPath, ['--import', pathToFileURL(loader).href, '--input-type=module', '-e',+ `await import(${JSON.stringify(pathToFileURL(script).href)})`], { timeout: 15000 });+ return { dir, sources, run, importModule };+}++describe('memory migration CLI', () => {+ it('defaults to a dry run without writes or source changes', async () => {+ const { dir, sources, run } = await fixture();+ const result = await run(['--clear']);+ expect(result.code, result.stderr || result.stdout).toBe(0);+ expect(result.stdout).toContain('DRY RUN');+ expect(result.stdout).not.toContain('DB_WRITE');+ expect(result.stdout).toContain('DB_CLOSED');+ for (const [name, bytes] of Object.entries(sources)) expect(await readFile(join(dir, name), 'utf8')).toBe(bytes);+ });++ it('preflights malformed source before any destructive write', async () => {+ const { dir, sources, run } = await fixture();+ const memoryFile = Object.keys(sources).find(name => name.endsWith('/memory.json'));+ await writeFile(join(dir, memoryFile), '{ malformed');+ const result = await run(['--execute', '--clear']);+ expect(result.code, result.stderr || result.stdout).toBe(1);+ expect(result.stdout).not.toContain('DB_WRITE');+ expect(result.stdout).toContain('DB_CLOSED');+ });++ it('can be imported without starting the CLI or closing the caller pool', async () => {+ const { importModule } = await fixture();+ expect((await importModule()).stdout).toBe('');+ });++ it.each(['record', 'link'])('fails the process and closes the pool on a %s write failure', async failure => {+ const { run } = await fixture(failure);+ const result = await run(['--execute', '--clear']);+ expect(result.code, result.stderr || result.stdout).toBe(1);+ expect(result.stderr).toContain(`injected ${failure} failure`);+ expect(result.stdout).toContain('DB_CLOSED');+ expect(result.stdout).not.toContain('Migration Summary');+ });+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex f00bf04cae..cef6bf8fbc 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -59,6 +59,7 @@ export const DB_TEST_INCLUDE = ['services/decksSync.db.test.js','services/modelPinRecords.db.test.js','scripts/run-db-migrations.test.js',+ 'scripts/migrateMemoryToPg.db.test.js','lib/db/schema/audit.db.test.js','lib/db/schema/syncFeed.db.test.js',];