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
feat(media): add PostgreSQL media_assets index (#1000 phase 3.2)
Adam Eivy9b2fc8642f23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 18d64c0b9d..a616ce94aa 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@## Changed+- **Generated images & videos now have a PostgreSQL index** — every generated image and video is mirrored into a new `media_assets` table (one row per asset), so media metadata — prompt, model, dimensions, lineage, timestamps — becomes queryable from the database instead of only by scanning `data/images/*` sidecars and `data/video-history.json`. The bytes and those files stay exactly where they are and remain authoritative; the table is a *derived* index, rebuilt from disk on boot (and pruned of any asset whose file has been removed) and kept current as new media finishes rendering. Nothing about the gallery, history, or generation flows changes for you — this is the foundation (Phase 3.2 of the Postgres-first plan, #1000) that later lets media collections and catalog attachments resolve through one queryable asset index. The index is simply not maintained under the `MEMORY_BACKEND=file` dev/test escape hatch (media still serves from disk).- **Creative Director state now lives in PostgreSQL** — Creative Director projects (treatment, scenes, and run history) moved out of the single monolithic `data/creative-director-projects.json` file into a `creative_director_projects` table, one row per project. The orchestrator rewrote that whole file ≈10 times per scene render, so a long session turned every project list/read into an O(N²) reserialize; per-project rows remove that contention, and concurrent writes to the same project (render-progress + agent-run updates) are now serialized with a row lock so they can't lose each other's updates. Existing installs are migrated automatically and losslessly on first boot — the legacy file is kept (renamed `…json.imported`) as a recovery source. Behavior is unchanged; this is a storage move (Phase 3 of the Postgres-first plan, #997). The file backend remains reachable under the `MEMORY_BACKEND=file` dev/test escape hatch.- **PostgreSQL is now a required dependency** — file-based JSON storage is no longer offered as a normal setup choice. `npm run setup:db` presents only Docker and Native PostgreSQL hosting modes (and auto-selects native when a healthy local PostgreSQL is already reachable). On boot, PortOS now verifies the database is reachable with the required schema and refuses to start with an actionable message if it isn't — instead of silently falling back to file-backed memory and serving a half-broken install (the creative catalog has no file-backed equivalent). `MEMORY_BACKEND=file` survives only as an explicit, unsupported development/test escape hatch. New docs: [`docs/STORAGE.md`](../docs/STORAGE.md) (the storage-classification contract — `db-primary` / `file-primary` / `asset-file-db-indexed` / `ephemeral-file` — plus a "new data store?" review checklist) and [`docs/BACKUP.md`](../docs/BACKUP.md) (backup/restore now that the Postgres dump is required system state).- **Local model pickers now show what's actually installed** — the Fallback Model dropdown in the AI Provider editor and the provider/model selector in the manuscript editorial review previously only listed the models stored on the provider record, so models you'd pulled in Ollama later (e.g. Command R+, Gemma) never appeared. Both pickers now fold in the live list of installed Ollama / LM Studio models. Embedding-only models (e.g. `nomic-embed-text`) are filtered out of these generation pickers since they can't run a prompt.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex bc0690a271..65716e6435 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -61,11 +61,13 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](**Where it lives.** Bytes under `./data/` (`data/images/*`, `data/videos/*`, `data/audio/*`, `data/music/*`, thumbnails). Metadata in DB asset rows keyed by `asset_key` / `media_key`, with integrity metadata (SHA-256 — see `server/lib/assetHash.js`). The DB row references the file; it never embeds the bytes.**Examples.**-- Generated images — `data/images/*` bytes + `.metadata.json` sidecars today; **target:** searchable metadata, provenance, favorites, notes move to DB asset rows; bytes stay on disk.-- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes; metadata/history/lineage move to DB.-- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes.+- Generated images — `data/images/*` bytes + `.metadata.json` sidecars; indexed into the `media_assets` table (#1000) keyed `image:<filename>`. Sidecars remain authoritative; the DB row is a derived, queryable mirror. Adapter: `server/services/mediaAssetIndex/`.+- Generated videos — `data/videos/*`, `data/video-thumbnails/*` bytes, tracked in `data/video-history.json`; indexed into `media_assets` keyed `video:<jobId>`. History file remains authoritative.+- Media collections — many-to-many links over assets/universes/series/catalog media pointers (`db-primary` link tables) pointing at `asset-file-db-indexed` bytes. **Still `data/media-collections/*` JSON today** — a follow-up slice of #1000.-**Postgres-First target.** Image/video history (`data/history.jsonl`, `data/video-history.json`) is strong for metadata-in-DB; the bytes remain files. Do **not** move generated image/video/audio bytes into PostgreSQL.+**Media asset index (`media_assets`, #1000).** One row per generated image/video: `media_key` (`<kind>:<ref>`) PK, `kind`/`ref`/`created_at` mirror columns for queries, the full metadata record in `data` JSONB. It is a **derived index** — the on-disk sidecars + `video-history.json` stay authoritative — reconciled from disk at boot (upsert every asset, prune rows whose file is gone) and kept warm by a generation-`completed` hook. Local-only (rebuilt from disk), so no sync cursor/tombstone. Adapter: `server/services/mediaAssetIndex/{logic,db,index}.js`.++**Postgres-First target (remaining).** `data/history.jsonl` (action log) and the durable portions of `data/media-jobs.json` (job history / lineage) are still file-backed — follow-up slices. Do **not** move generated image/video/audio bytes into PostgreSQL.---diff --git a/server/index.js b/server/index.jsindex 75f778483c..9a99733224 100644--- a/server/index.js+++ b/server/index.js@@ -837,6 +837,12 @@ ensureSelf()// version; marker-gated in data/catalog-canon-reconcile.applied.json.const { reconcileCanonCatalog } = await import('./scripts/reconcileCanonCatalog.js');await reconcileCanonCatalog();+ // Media asset index (#1000): subscribe the generation-completed hooks ++ // reconcile the derived media_assets table against on-disk images/videos.+ // Bytes + sidecars + video-history.json stay authoritative; this builds a+ // queryable index over them. Idempotent, safe to run every boot.+ const { initMediaAssetIndex } = await import('./services/mediaAssetIndex/index.js');+ await initMediaAssetIndex();} catch (err) {console.error(`🪄 catalog migrations failed at boot: ${err.message}`);}diff --git a/server/lib/README.md b/server/lib/README.mdindex f9fafc2a73..a4b48f0304 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -188,6 +188,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. || `db.js` | PostgreSQL connection pool. |+| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. || `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). || `platform.js` | Platform/OS detection helpers. || `timezone.js` | Timezone utilities for scheduling. |diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 286763117e..2927a6a403 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -174,6 +174,21 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {.toEqual([...new Set(extractColumnNames(jsBody))].sort());});+ // Media asset index (#1000) — non-catalog table in BOTH DDL sources, plus a+ // non-`idx_catalog_`-prefixed index, so it needs its own parity assertion.+ it('media_assets has the same columns and index in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'media_assets');+ const jsBody = extractCreateTable(DB_JS, 'media_assets');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE media_assets').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE media_assets').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_media_assets_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_media_assets_');+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ expect(sqlIdx.size).toBeGreaterThan(0);+ });+it('search_tsv payload field set matches', () => {// Both files re-declare the GENERATED ALWAYS expression character-for-// character today. If one side adds a payload key (e.g. voiceNotes) anddiff --git a/server/lib/db.js b/server/lib/db.jsindex 469cb2fc85..27cdb3c8b6 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -543,6 +543,29 @@ async function ensureSchemaImpl() {created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,++ // Media asset index (Phase 3.2, issue #1000). One row per generated image+ // or video; the bytes stay on disk (data/images, data/videos) and the+ // sidecar/.json history files remain authoritative — this table is a+ // DERIVED, queryable index, reconciled from disk at boot + kept warm by a+ // generation-completed hook. `media_key` is the shared `<kind>:<ref>`+ // vocabulary (mediaItemKey.js); `kind`/`ref` are mirrored into columns for+ // queries, the full metadata record lives in `data` JSONB. created_at is+ // the asset's own timestamp; indexed_at is when this index row was written.+ // No sync_sequence/tombstone: the index is local-only (rebuilt from disk),+ // not federated — a row vanishes when its file does (prune on reconcile).+ // Mirrors the media_assets block in init-db.sql.+ `CREATE TABLE IF NOT EXISTS media_assets (+ media_key TEXT PRIMARY KEY,+ kind VARCHAR(16) NOT NULL,+ ref TEXT NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ indexed_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ // created_at DESC is the gallery/history sort order; kind narrows+ // images-vs-videos. A composite (kind, created_at DESC) serves both.+ `CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC)`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/lib/index.js b/server/lib/index.jsindex 83d1f9541d..030ccf669b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -159,6 +159,7 @@ export * from './telegramClient.js';export * from './browserConfig.js';export * from './buildId.js';export * from './db.js';+export * from './pgTimestamp.js';export * from './platform.js';export * from './ports.js';export * from './timezone.js';diff --git a/server/lib/pgTimestamp.js b/server/lib/pgTimestamp.jsnew file mode 100644index 0000000000..3c759a8097--- /dev/null+++ b/server/lib/pgTimestamp.js@@ -0,0 +1,43 @@+/**+ * PostgreSQL TIMESTAMPTZ bind-safety helper.+ *+ * A TIMESTAMPTZ column rejects a bind value that isn't a calendar-valid,+ * in-range timestamp — and when that bind happens inside boot-time schema+ * init / data import, one bad legacy value can throw and block the whole+ * backend from coming up. This helper turns any candidate into a value+ * Postgres will always accept, or falls back.+ *+ * Extracted from the Creative Director migration (#997), where it was hardened+ * across several review rounds against `Date.parse` quirks. Shared so other+ * DB-backed stores that mirror a hand-editable JSON timestamp into a typed+ * column (e.g. the media asset index, #1000) reuse the exact same guards+ * instead of re-deriving them and drifting.+ */++/**+ * Safe ISO timestamp for a TIMESTAMPTZ column, falling back to `fallback`.+ *+ * Returns the NORMALIZED canonical ISO string (`Date#toISOString`), not the raw+ * input — because `Date.parse` accepts out-of-range calendar dates by rolling+ * them over (`2026-02-31` → Mar 3), and echoing that raw string would still+ * make Postgres reject the TIMESTAMPTZ bind and throw. Normalizing guarantees a+ * value PG always accepts.+ *+ * Year-range guard: `toISOString()` emits a plain 4-digit year (`YYYY-…`) only+ * for years 0000–9999, and a SIGNED expanded form (`±YYYYYY-…`) otherwise. We+ * accept ONLY a 4-digit year 0001–9999 — those are all well inside Postgres+ * TIMESTAMPTZ range. Rejected (→ fallback): the signed expanded forms+ * (`-100000-…`, `+275760-…`, which `Date.parse` accepts but PG can't bind) AND+ * year `0000` (Postgres has no Gregorian year zero — AD 1–99 are `0001`–`0099`,+ * so a normalized `0000-…` would still be bind-rejected).+ */+export function mirrorTimestamp(value, fallback) {+ if (typeof value === 'string') {+ const ms = Date.parse(value);+ if (!Number.isNaN(ms)) {+ const iso = new Date(ms).toISOString();+ if (/^\d{4}-/.test(iso) && !iso.startsWith('0000-')) return iso;+ }+ }+ return fallback;+}diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex f0adc24900..c8752aae6f 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -592,3 +592,26 @@ CREATE TABLE IF NOT EXISTS creative_director_projects (created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW());++-- Media asset index (Phase 3.2, issue #1000). One row per generated image or+-- video. The bytes stay on disk (data/images, data/videos) and the image+-- sidecars + data/video-history.json remain authoritative — this table is a+-- DERIVED, queryable index, reconciled from disk at boot and kept warm by a+-- generation-completed hook. `media_key` is the shared `<kind>:<ref>` key+-- (mediaItemKey.js); `kind`/`ref` mirror into columns for queries while the+-- full metadata record lives in `data` JSONB. created_at is the asset's own+-- timestamp; indexed_at is when this index row was written. No+-- sync_sequence/tombstone: the index is local-only (rebuilt from disk), not+-- federated — a row vanishes when its file does (prune on reconcile). Mirrors+-- the media_assets block in db.js ensureSchema().+CREATE TABLE IF NOT EXISTS media_assets (+ media_key TEXT PRIMARY KEY,+ kind VARCHAR(16) NOT NULL,+ ref TEXT NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ indexed_at TIMESTAMPTZ DEFAULT NOW()+);+-- created_at DESC is the gallery/history sort order; kind narrows+-- images-vs-videos. A composite (kind, created_at DESC) serves both.+CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC);diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 4ffcb4b77e..e26ffe9b15 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -15,6 +15,12 @@ import { ServerError } from '../../lib/errorHandler.js';import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';+// TIMESTAMPTZ bind-safety helper, shared with the media asset index (#1000) and+// any other store that mirrors a hand-editable timestamp into a typed column.+// Re-exported here so the historical `import { mirrorTimestamp } from+// './projectsLogic.js'` call sites (projectsDB.js, the migration) keep working.+export { mirrorTimestamp } from '../../lib/pgTimestamp.js';+// Without a cap, runs[] grows unbounded and every load/save (≈10 per scene// render) parses + serializes a payload whose size scales with cumulative// renders — O(N²) wall-clock. In-flight runs are load-bearing for orphan/dedup@@ -65,36 +71,6 @@ export function mirrorStatus(status) {return (typeof status === 'string' && status ? status : 'draft').slice(0, STATUS_COLUMN_MAX);}-/**- * Safe ISO timestamp for a TIMESTAMPTZ mirror column, falling back to `fallback`.- *- * Returns the NORMALIZED canonical ISO string (`Date#toISOString`), not the raw- * input — because `Date.parse` accepts out-of-range calendar dates by rolling- * them over (`2026-02-31` → Mar 3), and echoing that raw string would still- * make Postgres reject the TIMESTAMPTZ bind and throw. Normalizing guarantees a- * value PG always accepts. The raw original is still preserved verbatim in the- * JSONB `data` (callers stringify the full record separately), so this only- * affects the queryable mirror column.- *- * Year-range guard: `toISOString()` emits a plain 4-digit year (`YYYY-…`) only- * for years 0000–9999, and a SIGNED expanded form (`±YYYYYY-…`) otherwise. We- * accept ONLY a 4-digit year 0001–9999 — those are all well inside Postgres- * TIMESTAMPTZ range. Rejected (→ fallback): the signed expanded forms- * (`-100000-…`, `+275760-…`, which `Date.parse` accepts but PG can't bind) AND- * year `0000` (Postgres has no Gregorian year zero — AD 1–99 are `0001`–`0099`,- * so a normalized `0000-…` would still be bind-rejected).- */-export function mirrorTimestamp(value, fallback) {- if (typeof value === 'string') {- const ms = Date.parse(value);- if (!Number.isNaN(ms)) {- const iso = new Date(ms).toISOString();- if (/^\d{4}-/.test(iso) && !iso.startsWith('0000-')) return iso;- }- }- return fallback;-}-/*** Build a fresh project record. The caller supplies the already-created media* collection id (collection creation is a side effect both backends performdiff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.jsnew file mode 100644index 0000000000..317f9b793a--- /dev/null+++ b/server/services/mediaAssetIndex/db.js@@ -0,0 +1,138 @@+/**+ * Media asset index — PostgreSQL row I/O + reconcile (#1000).+ *+ * Writes the `media_assets` table. This table is a DERIVED index over media+ * that lives on disk, so the write surface is small:+ * - upsertAsset(row) — index/refresh one asset (the live hook + reconcile)+ * - removeAsset(mediaKey) — drop one asset's row (delete hook, future slice)+ * - reconcileMediaAssets() — full sweep: upsert every on-disk asset, prune+ * rows whose backing file is gone. Idempotent and+ * cheap to re-run; called at boot.+ * - listAssets(...) — query helper (no consumer reads it for+ * correctness yet; here for the follow-up slices+ * that make collections/catalog resolve through it)+ *+ * The image + video disk readers are dynamically imported inside reconcile so+ * importing this module (e.g. for upsertAsset from a generation hook) never+ * pulls in the heavy media-gen stack, and so tests can run the SQL paths+ * without it.+ */++import { query } from '../../lib/db.js';+import { imageToRow, videoToRow } from './logic.js';++function rowToAsset(row) {+ if (!row) return null;+ // `data` already carries the full metadata record; return it verbatim so+ // consumers see the same shape the gallery/history gave.+ return row.data;+}++const UPSERT_CONFLICT = `ON CONFLICT (media_key) DO UPDATE SET+ kind = EXCLUDED.kind,+ ref = EXCLUDED.ref,+ data = EXCLUDED.data,+ created_at = EXCLUDED.created_at,+ indexed_at = NOW()`;++/** Upsert one index row. `row` is the shape produced by logic.js. */+export async function upsertAsset(row) {+ if (!row) return;+ await query(+ `INSERT INTO media_assets (media_key, kind, ref, data, created_at, indexed_at)+ VALUES ($1, $2, $3, $4::jsonb, $5, NOW())+ ${UPSERT_CONFLICT}`,+ [row.mediaKey, row.kind, row.ref, JSON.stringify(row.data), row.createdAt],+ );+}++// Upsert many rows in chunked multi-row INSERTs so reconcile (which runs every+// boot over the whole gallery) is a handful of round-trips, not one-per-asset.+const UPSERT_CHUNK = 500;+async function upsertAssets(rows) {+ for (let i = 0; i < rows.length; i += UPSERT_CHUNK) {+ const chunk = rows.slice(i, i + UPSERT_CHUNK);+ const values = [];+ const params = [];+ chunk.forEach((row, j) => {+ const b = j * 5;+ // NOW() for indexed_at is a literal, not a param.+ values.push(`($${b + 1}, $${b + 2}, $${b + 3}, $${b + 4}::jsonb, $${b + 5}, NOW())`);+ params.push(row.mediaKey, row.kind, row.ref, JSON.stringify(row.data), row.createdAt);+ });+ await query(+ `INSERT INTO media_assets (media_key, kind, ref, data, created_at, indexed_at)+ VALUES ${values.join(', ')}+ ${UPSERT_CONFLICT}`,+ params,+ );+ }+}++/** Remove one index row by media_key. */+export async function removeAsset(mediaKey) {+ if (typeof mediaKey !== 'string' || !mediaKey) return;+ await query(`DELETE FROM media_assets WHERE media_key = $1`, [mediaKey]);+}++/** List index rows, newest first. Optional `kind` filter ('image' | 'video'). */+export async function listAssets({ kind } = {}) {+ const result = kind+ ? await query(`SELECT data FROM media_assets WHERE kind = $1 ORDER BY created_at DESC`, [kind])+ : await query(`SELECT data FROM media_assets ORDER BY created_at DESC`);+ return result.rows.map(rowToAsset);+}++/**+ * Full reconcile: make the index match what's on disk RIGHT NOW.+ *+ * 1. Read every image (gallery scan) + every video (history file).+ * 2. Upsert a row for each — refreshing metadata for any that changed.+ * 3. Prune index rows whose media_key is no longer on disk (deleted out-of-band,+ * e.g. a file removed while the server was down, or by a path this slice+ * doesn't hook yet). This is what keeps the derived index honest without a+ * delete hook on every removal path.+ *+ * Idempotent: re-running with no disk changes is a no-op upsert per row + an+ * empty prune. Cheap enough to run unconditionally at boot.+ *+ * The disk readers are injected (defaulting to the real services) so tests can+ * drive reconcile without the media-gen stack.+ */+export async function reconcileMediaAssets(deps = {}) {+ const now = new Date().toISOString();+ const listGallery = deps.listGallery+ || (await import('../imageGen/local.js')).listGallery;+ const loadHistory = deps.loadHistory+ || (await import('../videoGen/local.js')).loadHistory;++ const [images, videos] = await Promise.all([+ listGallery().catch(() => []),+ loadHistory().catch(() => []),+ ]);++ const rows = [+ ...(Array.isArray(images) ? images : []).map((it) => imageToRow(it, { now })),+ ...(Array.isArray(videos) ? videos : []).map((v) => videoToRow(v, { now })),+ ].filter(Boolean);++ await upsertAssets(rows);++ // Prune: any row whose media_key isn't in the current on-disk set is stale.+ const liveKeys = rows.map((r) => r.mediaKey);+ let pruned = 0;+ if (liveKeys.length === 0) {+ // Nothing on disk → the whole index is stale.+ const res = await query(`DELETE FROM media_assets`);+ pruned = res.rowCount || 0;+ } else {+ const res = await query(+ `DELETE FROM media_assets WHERE media_key <> ALL($1::text[])`,+ [liveKeys],+ );+ pruned = res.rowCount || 0;+ }++ console.log(`🗂️ Media asset index reconciled: ${rows.length} on disk (${images.length || 0} img / ${videos.length || 0} vid), ${pruned} stale row(s) pruned`);+ return { ok: true, indexed: rows.length, pruned };+}diff --git a/server/services/mediaAssetIndex/db.test.js b/server/services/mediaAssetIndex/db.test.jsnew file mode 100644index 0000000000..0f390389a4--- /dev/null+++ b/server/services/mediaAssetIndex/db.test.js@@ -0,0 +1,109 @@+/**+ * Postgres-backed round-trip for the media asset index.+ *+ * Like projectsDB.test.js, this needs a live PostgreSQL with the schema applied.+ * If no DB is reachable (CI, fresh checkout), it SKIPS cleanly rather than+ * failing red. When a DB IS reachable it exercises upsert/list/remove and the+ * full reconcile (upsert-everything + prune-stale), using INJECTED disk readers+ * so it never touches the real media-gen stack, and cleaning its rows up after.+ */++import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'media_assets') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'media_assets table not present';+ }+}++if (!dbReady) console.log(`⏭️ mediaAssetIndex/db.test.js skipped: ${skipReason}`);++// Test rows use a recognizable prefix so cleanup can target them without+// touching any real indexed assets that happen to share the dev DB.+const PFX = 'test-mai-';++describe.skipIf(!dbReady)('media asset index DB round-trip', () => {+ let db;+ // reconcile is a GLOBAL sweep (it prunes every row not on disk), so it would+ // wipe any real index rows on a shared dev DB. Snapshot the table up front and+ // restore it after, leaving the developer's index exactly as we found it.+ let snapshot = [];+ beforeAll(async () => {+ db = await import('./db.js');+ const res = await query(`SELECT media_key, kind, ref, data, created_at FROM media_assets`);+ snapshot = res.rows;+ });++ afterAll(async () => {+ await query(`DELETE FROM media_assets WHERE ref LIKE $1`, [`${PFX}%`]).catch(() => {});+ // Restore any pre-existing rows the global reconcile prune removed.+ for (const r of snapshot) {+ await query(+ `INSERT INTO media_assets (media_key, kind, ref, data, created_at)+ VALUES ($1, $2, $3, $4::jsonb, $5) ON CONFLICT (media_key) DO NOTHING`,+ [r.media_key, r.kind, r.ref, JSON.stringify(r.data), r.created_at],+ ).catch(() => {});+ }+ await close();+ });++ it('upserts, lists, and removes an asset (lossless data)', async () => {+ const data = { filename: `${PFX}a.png`, prompt: 'p', createdAt: '2026-01-01T00:00:00.000Z' };+ await db.upsertAsset({ mediaKey: `image:${PFX}a.png`, kind: 'image', ref: `${PFX}a.png`, data, createdAt: data.createdAt });++ const imgs = await db.listAssets({ kind: 'image' });+ const found = imgs.find((x) => x.filename === `${PFX}a.png`);+ expect(found).toEqual(data);++ await db.removeAsset(`image:${PFX}a.png`);+ const after = await db.listAssets({ kind: 'image' });+ expect(after.some((x) => x.filename === `${PFX}a.png`)).toBe(false);+ });++ it('upsert refreshes data + created_at on conflict', async () => {+ const key = `image:${PFX}b.png`;+ await db.upsertAsset({ mediaKey: key, kind: 'image', ref: `${PFX}b.png`, data: { filename: `${PFX}b.png`, v: 1 }, createdAt: '2026-01-01T00:00:00.000Z' });+ await db.upsertAsset({ mediaKey: key, kind: 'image', ref: `${PFX}b.png`, data: { filename: `${PFX}b.png`, v: 2 }, createdAt: '2026-02-02T00:00:00.000Z' });+ const imgs = await db.listAssets({ kind: 'image' });+ const found = imgs.find((x) => x.filename === `${PFX}b.png`);+ expect(found.v).toBe(2);+ await db.removeAsset(key);+ });++ it('reconcile upserts on-disk assets and prunes stale rows (injected readers)', async () => {+ // Pre-seed a stale row that won't be in the injected "disk" set.+ await db.upsertAsset({ mediaKey: `image:${PFX}stale.png`, kind: 'image', ref: `${PFX}stale.png`, data: { filename: `${PFX}stale.png` }, createdAt: '2026-01-01T00:00:00.000Z' });++ const listGallery = async () => [+ { filename: `${PFX}live1.png`, prompt: 'one', createdAt: '2026-03-01T00:00:00.000Z' },+ { filename: `${PFX}live2.png`, prompt: 'two', createdAt: '2026-03-02T00:00:00.000Z' },+ ];+ const loadHistory = async () => [+ { id: `${PFX}vid1`, filename: `${PFX}vid1.mp4`, createdAt: '2026-03-03T00:00:00.000Z' },+ ];++ const res = await db.reconcileMediaAssets({ listGallery, loadHistory });+ expect(res.indexed).toBe(3);++ const imgs = await db.listAssets({ kind: 'image' });+ const refs = imgs.map((x) => x.filename);+ expect(refs).toContain(`${PFX}live1.png`);+ expect(refs).toContain(`${PFX}live2.png`);+ // The stale row whose backing file isn't in the disk set is pruned.+ expect(refs).not.toContain(`${PFX}stale.png`);++ const vids = await db.listAssets({ kind: 'video' });+ expect(vids.some((x) => x.id === `${PFX}vid1`)).toBe(true);+ });+});diff --git a/server/services/mediaAssetIndex/index.js b/server/services/mediaAssetIndex/index.jsnew file mode 100644index 0000000000..415d9ce485--- /dev/null+++ b/server/services/mediaAssetIndex/index.js@@ -0,0 +1,85 @@+/**+ * Media asset index — public entry / boot wiring (#1000).+ *+ * The index is a DERIVED Postgres mirror of on-disk media (see db.js). This+ * module owns its lifecycle:+ * - initMediaAssetIndex() — called once at boot (after the DB gate). Subscribes+ * to the existing image/video `completed` events so a freshly generated+ * asset is indexed immediately, then runs a full reconcile so the index+ * matches disk regardless of any events missed while the server was down.+ * - The reconcile + row I/O live in db.js; the pure transforms in logic.js.+ *+ * No hot-path generator edits: we hang off the `imageGenEvents` /+ * `videoGenEvents` 'completed' emitters that already fire on every render. The+ * handlers read the just-written sidecar / history entry and upsert one row.+ *+ * Escape hatch: under MEMORY_BACKEND=file or NODE_ENV=test there's no Postgres,+ * so the index is simply not maintained — the gallery/history still serve from+ * disk. init() no-ops in that case (mirrors how catalog features disable).+ */++import { checkHealth, ensureSchema } from '../../lib/db.js';+import { imageGenEvents } from '../imageGenEvents.js';+import { videoGenEvents } from '../videoGen/events.js';+import { upsertAsset, reconcileMediaAssets } from './db.js';+import { imageToRow, videoToRow } from './logic.js';++export { reconcileMediaAssets } from './db.js';++let subscribed = false;++function isEscapeHatch() {+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';+}++// Index a single just-generated image. The 'completed' event carries the+// filename; the full metadata is in the sidecar the generator just wrote.+async function onImageCompleted({ filename } = {}) {+ if (typeof filename !== 'string' || !filename) return;+ const { readImageSidecar } = await import('../imageGen/local.js');+ const { metadata } = await readImageSidecar(filename);+ // Match listGallery's entry shape exactly (filename + path + spread sidecar)+ // so a live-indexed row's `data` is identical to a reconcile-indexed one.+ const row = imageToRow({ filename, path: `/data/images/${filename}`, ...metadata });+ await upsertAsset(row).catch((err) => console.error(`❌ Media index image upsert failed: ${err.message}`));+}++// Index a single just-generated video. The 'completed' event carries the job+// id (generationId); the full metadata is the matching video-history entry.+async function onVideoCompleted({ generationId } = {}) {+ if (typeof generationId !== 'string' || !generationId) return;+ const { loadHistory } = await import('../videoGen/local.js');+ const history = await loadHistory().catch(() => []);+ const entry = Array.isArray(history) ? history.find((h) => h.id === generationId) : null;+ if (!entry) return;+ const row = videoToRow(entry);+ await upsertAsset(row).catch((err) => console.error(`❌ Media index video upsert failed: ${err.message}`));+}++/**+ * Boot init: subscribe the completed-hooks (once) + run a full reconcile.+ * No-op under the escape hatch or when Postgres is unreachable (the boot DB+ * gate already fail-fasts a required-but-missing DB; this just stays quiet).+ */+export async function initMediaAssetIndex() {+ if (isEscapeHatch()) {+ console.log('🗂️ Media asset index disabled (escape hatch / test) — serving from disk only');+ return { ok: false, reason: 'escape-hatch' };+ }+ const health = await checkHealth();+ if (!health.connected) return { ok: false, reason: 'db-unreachable' };+ // Self-sufficient like the CD backend: ensureSchema is idempotent + in-flight+ // deduped, so calling it here is safe regardless of boot ordering.+ await ensureSchema();++ if (!subscribed) {+ // The completed handlers run outside the request lifecycle (event emitter),+ // so an uncaught throw would crash Node — each handler is self-contained and+ // its upsert .catch()es. Wrap the dispatch too, defensively.+ imageGenEvents.on('completed', (p) => { onImageCompleted(p).catch((err) => console.error(`❌ Media index image hook: ${err.message}`)); });+ videoGenEvents.on('completed', (p) => { onVideoCompleted(p).catch((err) => console.error(`❌ Media index video hook: ${err.message}`)); });+ subscribed = true;+ }++ return reconcileMediaAssets();+}diff --git a/server/services/mediaAssetIndex/index.test.js b/server/services/mediaAssetIndex/index.test.jsnew file mode 100644index 0000000000..93df886a48--- /dev/null+++ b/server/services/mediaAssetIndex/index.test.js@@ -0,0 +1,78 @@+/**+ * Boot wiring + live-hook tests for the media asset index. No live DB — the DB+ * layer (db.js) and the disk readers are mocked, so we assert the orchestration:+ * escape-hatch no-op, reconcile-on-init, and the completed-event hooks turning a+ * generated asset into one upsert with the right key/shape.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const upsertAsset = vi.fn(async () => {});+const reconcileMediaAssets = vi.fn(async () => ({ ok: true, indexed: 0, pruned: 0 }));+const checkHealth = vi.fn(async () => ({ connected: true }));+const ensureSchema = vi.fn(async () => {});+const readImageSidecar = vi.fn(async () => ({ metadata: { prompt: 'p', createdAt: '2026-01-01T00:00:00.000Z' } }));+const loadHistory = vi.fn(async () => ([{ id: 'job-1', filename: 'job-1.mp4', createdAt: '2026-01-02T00:00:00.000Z' }]));++vi.mock('./db.js', () => ({ upsertAsset, reconcileMediaAssets, removeAsset: vi.fn() }));+vi.mock('../../lib/db.js', () => ({ checkHealth, ensureSchema }));+vi.mock('../imageGen/local.js', () => ({ readImageSidecar, listGallery: vi.fn(async () => []) }));+vi.mock('../videoGen/local.js', () => ({ loadHistory }));++import { imageGenEvents } from '../imageGenEvents.js';+import { videoGenEvents } from '../videoGen/events.js';++beforeEach(() => {+ vi.clearAllMocks();+ checkHealth.mockResolvedValue({ connected: true });+});++// A tiny tick helper so the fire-and-forget event handlers settle.+const flush = () => new Promise((r) => setTimeout(r, 0));++describe('initMediaAssetIndex', () => {+ it('no-ops under the escape hatch (no DB, no reconcile)', async () => {+ vi.stubEnv('NODE_ENV', 'test');+ const { initMediaAssetIndex } = await import('./index.js');+ const res = await initMediaAssetIndex();+ expect(res.reason).toBe('escape-hatch');+ expect(reconcileMediaAssets).not.toHaveBeenCalled();+ expect(checkHealth).not.toHaveBeenCalled();+ vi.unstubAllEnvs();+ });++ it('bails when Postgres is unreachable', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ checkHealth.mockResolvedValue({ connected: false, error: 'down' });+ const { initMediaAssetIndex } = await import('./index.js');+ const res = await initMediaAssetIndex();+ expect(res.reason).toBe('db-unreachable');+ expect(reconcileMediaAssets).not.toHaveBeenCalled();+ vi.unstubAllEnvs();+ });++ it('ensures schema + reconciles, and indexes a completed image/video via the hooks', async () => {+ vi.stubEnv('NODE_ENV', 'production');+ const { initMediaAssetIndex } = await import('./index.js');+ await initMediaAssetIndex();+ expect(ensureSchema).toHaveBeenCalled();+ expect(reconcileMediaAssets).toHaveBeenCalled();++ // A finished image render → one upsert keyed image:<filename>, sidecar merged.+ imageGenEvents.emit('completed', { generationId: 'g1', filename: 'img-1.png' });+ await flush();+ expect(upsertAsset).toHaveBeenCalledWith(expect.objectContaining({+ mediaKey: 'image:img-1.png', kind: 'image', ref: 'img-1.png',+ data: expect.objectContaining({ filename: 'img-1.png', prompt: 'p' }),+ }));++ // A finished video render → one upsert keyed video:<id>, history entry merged.+ upsertAsset.mockClear();+ videoGenEvents.emit('completed', { generationId: 'job-1', filename: 'job-1.mp4' });+ await flush();+ expect(upsertAsset).toHaveBeenCalledWith(expect.objectContaining({+ mediaKey: 'video:job-1', kind: 'video', ref: 'job-1',+ }));+ vi.unstubAllEnvs();+ });+});diff --git a/server/services/mediaAssetIndex/logic.js b/server/services/mediaAssetIndex/logic.jsnew file mode 100644index 0000000000..29c58ba4b0--- /dev/null+++ b/server/services/mediaAssetIndex/logic.js@@ -0,0 +1,57 @@+/**+ * Media asset index — pure row transforms.+ *+ * The index (#1000) is a DERIVED, queryable mirror of media that physically+ * lives on disk: generated images (data/images/*.png + .metadata.json sidecars)+ * and generated videos (data/videos/*.mp4, tracked in data/video-history.json).+ * Those files stay authoritative; this module just turns a disk record into the+ * `media_assets` row shape so the reconcile pass + the live completed-hook can+ * never drift on what a row looks like. No I/O here.+ *+ * A row is `{ mediaKey, kind, ref, data, createdAt }`:+ * - kind/ref → the shared `<kind>:<ref>` vocabulary (mediaItemKey.js)+ * - mediaKey → `<kind>:<ref>` (the PK)+ * - data → the full metadata record, stored verbatim in JSONB+ * - createdAt → bind-safe TIMESTAMPTZ for the queryable column+ */++import { itemKey } from '../../lib/mediaItemKey.js';+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';++/**+ * Build an index row for a generated image. `item` is a gallery entry as+ * produced by imageGen listGallery() — `{ filename, createdAt, ...sidecar }` —+ * or any object carrying at least a `filename`. Returns null when there's no+ * usable ref (so callers can filter).+ */+export function imageToRow(item, { now } = {}) {+ const ref = item?.filename;+ if (typeof ref !== 'string' || !ref) return null;+ const fallback = now || new Date().toISOString();+ return {+ mediaKey: itemKey({ kind: 'image', ref }),+ kind: 'image',+ ref,+ data: item,+ createdAt: mirrorTimestamp(item.createdAt, fallback),+ };+}++/**+ * Build an index row for a generated video. `entry` is a video-history record —+ * `{ id, filename, createdAt, ... }`. The video's ref in the `<kind>:<ref>`+ * vocabulary is its job id (matches how mediaCollections stores video items),+ * NOT the filename. Returns null when there's no usable id.+ */+export function videoToRow(entry, { now } = {}) {+ const ref = entry?.id;+ if (typeof ref !== 'string' || !ref) return null;+ const fallback = now || new Date().toISOString();+ return {+ mediaKey: itemKey({ kind: 'video', ref }),+ kind: 'video',+ ref,+ data: entry,+ createdAt: mirrorTimestamp(entry.createdAt, fallback),+ };+}diff --git a/server/services/mediaAssetIndex/logic.test.js b/server/services/mediaAssetIndex/logic.test.jsnew file mode 100644index 0000000000..5ecdf57eaa--- /dev/null+++ b/server/services/mediaAssetIndex/logic.test.js@@ -0,0 +1,57 @@+/**+ * Pure row-transform tests for the media asset index logic. No I/O — these lock+ * the mediaKey vocabulary, the verbatim `data` passthrough, and the bind-safe+ * createdAt mirror that the reconcile pass and the live hook both depend on.+ */++import { describe, it, expect } from 'vitest';+import { imageToRow, videoToRow } from './logic.js';++describe('imageToRow', () => {+ it('builds an image:<filename> row with the metadata stored verbatim', () => {+ const item = { filename: 'abc.png', prompt: 'a cat', createdAt: '2026-01-02T03:04:05.000Z', seed: 7 };+ const row = imageToRow(item);+ expect(row).toEqual({+ mediaKey: 'image:abc.png',+ kind: 'image',+ ref: 'abc.png',+ data: item,+ createdAt: '2026-01-02T03:04:05.000Z',+ });+ });+ it('falls back to `now` when createdAt is missing/invalid (bind-safe column)', () => {+ expect(imageToRow({ filename: 'x.png' }, { now: 'fb' }).createdAt).toBe('fb');+ expect(imageToRow({ filename: 'x.png', createdAt: 'not-a-date' }, { now: 'fb' }).createdAt).toBe('fb');+ // Out-of-range calendar date normalizes (Feb 31 → Mar 3) so PG accepts it.+ expect(imageToRow({ filename: 'x.png', createdAt: '2026-02-31T00:00:00.000Z' }, { now: 'fb' }).createdAt)+ .toBe('2026-03-03T00:00:00.000Z');+ });+ it('returns null when there is no usable filename', () => {+ expect(imageToRow(null)).toBeNull();+ expect(imageToRow({})).toBeNull();+ expect(imageToRow({ filename: '' })).toBeNull();+ expect(imageToRow({ filename: 123 })).toBeNull();+ });+});++describe('videoToRow', () => {+ it('builds a video:<id> row keyed on the job id, not the filename', () => {+ const entry = { id: 'job-1', filename: 'job-1.mp4', prompt: 'a ball', createdAt: '2026-01-02T03:04:05.000Z' };+ const row = videoToRow(entry);+ expect(row).toEqual({+ mediaKey: 'video:job-1',+ kind: 'video',+ ref: 'job-1',+ data: entry,+ createdAt: '2026-01-02T03:04:05.000Z',+ });+ });+ it('falls back to `now` for a missing/invalid createdAt', () => {+ expect(videoToRow({ id: 'job-2' }, { now: 'fb' }).createdAt).toBe('fb');+ });+ it('returns null when there is no usable id', () => {+ expect(videoToRow(null)).toBeNull();+ expect(videoToRow({ filename: 'x.mp4' })).toBeNull();+ expect(videoToRow({ id: '' })).toBeNull();+ });+});