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
address review (claude): clean up assets on corrupt-zip import, guard embedding dimension mismatch, fix authors backend hint
Adam Eivy63805d582ca6
diff --git a/PLAN.md b/PLAN.mdindex 8de35e101c..5ee31de2e5 100644--- a/PLAN.md+++ b/PLAN.md@@ -50,6 +50,12 @@ independently.- [ ] [chatgpt-import-stream-assets-to-disk] **Stream ChatGPT-export `.dat` assets directly to disk instead of buffering them all in memory.** From claude review of the ChatGPT-ZIP-import PR (#1264). `extractChatgptZip` (`server/services/chatgptZipImport.js`) buffers every `.dat` asset into `pendingAssets` (a `Map<assetId, {buffer}>`) and holds them until the ZIP stream closes, then resolves extensions + writes them in a second loop — because the `conversation_asset_file_names.json` map can arrive *after* the `.dat` members, so the friendly-name fallback isn't known per-asset mid-stream. Peak RAM ≈ sum of all asset bytes; an aggregate `MAX_TOTAL_BUFFERED_BYTES` (1 GB) guard now fails fast rather than OOMing, but a legitimately large export (the route allows up to 2 GB) would be rejected. Proper fix: write each asset to a temp/served path as it streams (sniff the extension from the first chunk, which is enough for all current magic-byte types), recording `{assetId → tempPath}`; after the stream closes, rename/finalize using the now-complete name map (extension is already known from the sniff; the friendly NAME is metadata only, not part of the served filename). This removes the aggregate ceiling and bounds peak RAM to one chunk. Keep the magic-byte sniff (the `.dat` files have no extension). Estimated scope: medium.+- [ ] [lora-trainer-reattach-detached-child-on-boot] **Re-attach (or explicitly resume) a detached LoRA trainer that outlived a hard server restart instead of marking the run failed while its child still runs.** From claude review of the v2.21.0 release (PR #1270). `server/services/loraTraining/index.js` spawns the trainer with `detached: true` so a pm2 *group* SIGINT can't kill it mid-run — good. But if pm2 kills the server *process* (not just the group), the detached child keeps training while boot reconcile (`initLoraTraining`/`initMediaJobQueue`) marks the run `failed`; nothing reaps the child's `RESULT:` line, so a run that finishes post-restart registers no LoRA and silently discards hours of GPU work. Fix: on boot, probe whether the recorded child PID is still alive (`process.kill(pid, 0)`); if so, re-attach to its output (or at minimum leave the run `running` and let the existing checkpoint-resume path pick it up) rather than force-failing it. Edge-case (requires a process kill, not the common group SIGINT) but high cost when it hits. Estimated scope: medium.++- [ ] [db-write-guard-broaden-cte-copy-merge] **Broaden the test-DB row-write guard to catch data-modifying CTEs, COPY, MERGE, and multi-statement writes.** From claude review of the v2.21.0 release (PR #1270). `server/lib/db.js`'s row-write backstop (the hard defense against the 2026-06-13 data-loss class) is `^`-anchored on `INSERT|UPDATE|DELETE|TRUNCATE`, so `WITH … DELETE …`, `COPY … FROM`, `MERGE INTO`, and `SELECT 1; DELETE …` slip past it. Verified that no current store uses those forms, so it is **latent, not exploitable today** — but the guard is billed as the absolute backstop, so it should match those verbs anywhere after stripping a leading comment block. Add matching cases to `server/lib/db.guards.test.js` pinning the intent. Estimated scope: small.++- [ ] [videogen-close-handler-wrap-unhandled-rejection] **Wrap the `videoGen/local.js` child-process `close` handler so a `finalizeGeneratedVideo()` throw can't leak as an unhandled rejection (job stuck `running`).** From claude review of the v2.21.0 release (PR #1270); pre-existing, not introduced by the PR, but new LoRA-fused renders now flow through it. `server/services/videoGen/local.js` (~lines 1041, 1096) does `proc.on('close', async () => { … await finalizeGeneratedVideo() … })` with no try/catch; a throw there is an unhandled rejection (process-killing on Node ≥15 per the `nodejs-async-event-listener-unhandled-rejection` skill) that leaves the media job wedged `running` with no terminal SSE. Fix: wrap the handler body in try/catch and route failures through the job's `failed`/error finalizer + emoji-prefixed `console.error`. Estimated scope: small.+### Trigger-gated (waiting for a precondition)- [ ] [ref-watch-phosphene-spaced-lora-id-decode-validate] **Harden trained-character/LoRA id handling for spaced filenames + percent-encoded path segments.** From `reference-watch` review of Phosphene (commit `ce031395`, 2026-06-12). Upstream's character-id validation regex was a hard gate that ran *before* the sidecar was read, so a LoRA whose trigger/filename contained a space (e.g. `Annie Phosphene_v2.safetensors`) was misclassified as style-only and vanished from the Characters tab; the fix widened the id class to allow spaces and made the route `unquote()`-then-validate (staying traversal-safe because an encoded `../` or `/` decodes to chars the class still rejects). PortOS's equivalent is `server/services/loras.js#assertSafeLoraFilename()` plus the trained-LoRA `character` classification it surfaces. Fix (if applicable): audit whether any PortOS LoRA/character id route 404s or misclassifies spaced filenames and whether percent-encoded id segments are decoded before validation; if so, widen the allowed id class to permit spaces and decode-then-validate in the route. **Decision needed:** confirm PortOS actually exposes id-addressed character/LoRA routes (not just filename-addressed ones) and reproduces the spaced-name misclassification before investing — it may already be covered by `assertSafeLoraFilename`'s filename-only model. Estimated scope: small.diff --git a/server/services/authors/index.js b/server/services/authors/index.jsindex d7561f938d..f2a09f5008 100644--- a/server/services/authors/index.js+++ b/server/services/authors/index.js@@ -43,7 +43,7 @@ async function selectBackend() {// (idempotent) — the authors table is created on first use either way.const health = await checkHealth();if (!health.connected) {- throw new Error('Authors require PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env for the unsupported file backend)');+ throw new Error('Authors require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file in .env for the unsupported file backend)');}await ensureSchema();backend = await import('./db.js');diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.jsindex 233a009b41..cbc626fa6f 100644--- a/server/services/chatgptZipImport.js+++ b/server/services/chatgptZipImport.js@@ -34,6 +34,7 @@ import { Writable } from 'stream';import { PATHS, getMimeType } from '../lib/fileUtils.js';import { parseZip } from '../lib/zipStream.js';import { parseExport, importConversations, assetPointerId } from './chatgptImport.js';+import { ServerError } from '../lib/errorHandler.js';// Cap an individual buffered member (JSON shard or `.dat` asset). The largest// conversation shard in a real export is ~6 MB and assets run KB–few MB; 100 MB@@ -231,8 +232,21 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA}const conversationFiles = [];- for (const { buffer } of convoBuffers) {- conversationFiles.push(JSON.parse(buffer.toString('utf8')));+ for (const { path, buffer } of convoBuffers) {+ // A truncated/corrupt export (realistic for a partial download) makes+ // JSON.parse throw HERE — after the asset files were already written to the+ // served dir. Clean those orphans up before surfacing a clean 400, otherwise+ // the throw escapes extractChatgptZip and importChatgptZip never reaches its+ // cleanupExtractedAssets() path.+ try {+ conversationFiles.push(JSON.parse(buffer.toString('utf8')));+ } catch {+ await cleanupExtractedAssets(assets, assetDir);+ throw new ServerError(`${path} is not valid JSON — the ChatGPT export looks truncated or corrupt.`, {+ status: 400,+ code: 'INVALID_CHATGPT_EXPORT',+ });+ }}return {diff --git a/server/services/chatgptZipImport.test.js b/server/services/chatgptZipImport.test.jsindex 05c80164b4..555d76ace3 100644--- a/server/services/chatgptZipImport.test.js+++ b/server/services/chatgptZipImport.test.js@@ -134,6 +134,20 @@ describe('chatgptZipImport service', () => {const { assets } = await extractChatgptZip(zipPath, { assetDir: join(TMP, 'assets') });expect(assets.get('file-DOC').file).toBe('file-DOC.csv');});++ it('cleans up already-written assets and throws a 400 when a conversation shard is corrupt JSON', async () => {+ const zipPath = await writeZip([+ ['conversations-000.json', '[{ "id": "c1", "title": "A", "mapping": {} '], // truncated → JSON.parse throws+ ['conversation_asset_file_names.json', JSON.stringify({ 'file-IMG.dat': 'photo.png' })],+ ['file-IMG.dat', PNG],+ ]);+ const assetDir = join(TMP, 'assets');+ await expect(extractChatgptZip(zipPath, { assetDir }))+ .rejects.toMatchObject({ status: 400, code: 'INVALID_CHATGPT_EXPORT' });+ // The asset written before the parse failure must not be orphaned.+ const written = await readdir(assetDir).catch(() => []);+ expect(written).toEqual([]);+ });});describe('makeAssetResolver', () => {diff --git a/server/services/memoryDB.js b/server/services/memoryDB.jsindex c7f12ce8db..42b77a90b6 100644--- a/server/services/memoryDB.js+++ b/server/services/memoryDB.js@@ -63,6 +63,23 @@ function rowToMeta(row) {// CRUD Operations// =============================================================================+// The `embedding` column is a fixed-dimension pgvector (768). Now that the+// embedding provider/model is user-configurable, a mismatched model can yield a+// vector of a different length — Postgres would then throw "expected 768+// dimensions" on EVERY insert, aborting the whole bridge resync. Store NULL with+// one clear warning instead; the record stays un-searchable until it's+// re-embedded with a matching-dimension model. Returns `{ value, model }` for+// the embedding + embedding_model columns so both stay consistent.+function embeddingColumns(embedding) {+ if (!embedding) return { value: null, model: null };+ const expected = DEFAULT_MEMORY_CONFIG.embeddingDimension;+ if (embedding.length !== expected) {+ console.warn(`⚠️ Skipping memory embedding: got ${embedding.length} dims, column expects ${expected} — check the Brain embedding model`);+ return { value: null, model: null };+ }+ return { value: arrayToPgvector(embedding), model: DEFAULT_MEMORY_CONFIG.embeddingModel };+}+/*** Create a new memory*/@@ -72,6 +89,7 @@ export async function createMemory(data, embedding = null) {const now = new Date().toISOString();const originInstanceId = await getInstanceId();+ const embeddingCol = embeddingColumns(embedding);const memory = await withTransaction(async (client) => {const result = await client.query(@@ -88,8 +106,8 @@ export async function createMemory(data, embedding = null) {) RETURNING *`,[id, data.type, data.content, summary, data.category || 'other', data.tags || [],- embedding ? arrayToPgvector(embedding) : null,- embedding ? DEFAULT_MEMORY_CONFIG.embeddingModel : null,+ embeddingCol.value,+ embeddingCol.model,data.confidence ?? 0.8, data.importance ?? 0.5,data.sourceTaskId || null, data.sourceAgentId || null, data.sourceAppId || null,data.expiresAt || null, data.status || 'active', now, now, originInstanceId@@ -333,15 +351,16 @@ export async function updateMemory(id, updates) {* Update a memory's embedding*/export async function updateMemoryEmbedding(id, embedding) {+ const embeddingCol = embeddingColumns(embedding);const result = await query(`UPDATE memories SET embedding = $1, embedding_model = $2 WHERE id = $3 RETURNING *`,- [arrayToPgvector(embedding), DEFAULT_MEMORY_CONFIG.embeddingModel, id]+ [embeddingCol.value, embeddingCol.model, id]);if (result.rows.length === 0) return null;const memory = rowToMemory(result.rows[0]);- memory.embedding = embedding;+ memory.embedding = embeddingCol.value ? embedding : null;console.log(`🧠 Memory embedding updated: ${id}`);return memory;