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: provide an isolated synthetic collection audit fixture (#8249)
[._.]/ Adam Eivy510c5e982316
diff --git a/scripts/perf/README.md b/scripts/perf/README.mdnew file mode 100644index 0000000000..8eb899048d--- /dev/null+++ b/scripts/perf/README.md@@ -0,0 +1,75 @@+# Isolated collection audit fixture++From a checkout with dependencies and portos_test already provisioned+(npm run setup:db:test), run this non-interactive command:++~~~sh+npm run build && PGDATABASE=portos_test node scripts/perf/collectionFixture.js+~~~++The command prints one JSON readiness record with a loopback URL and cardinalities.+Visit /media/history or /messages/inbox on that URL. Send SIGINT or SIGTERM to stop;+the launcher closes the child, drops its own PostgreSQL schema, and removes its+temporary directory. Initialization failures also clean up. As with any process,+SIGKILL or machine power loss cannot run cleanup; use graceful shutdown.++A future CDP runner can import startCollectionFixture() and use its returned+{ url, cardinalities, close }. Always await close() in a finally block. It is+idempotent. /__fixture/ready returns the same readiness/cardinality information+without database identifiers, credentials, paths, or record payloads. The optional+clientDist argument selects an already-built client; it defaults to client/dist.+No development proxy is started.++The fixed dataset contains 2,400 PNG images, 1,200 one-second MP4 videos and their+PNG thumbnails, and 4,000 messages across two disabled synthetic accounts. Every+tenth media record is hidden (240 images and 120 videos). Prompts and message+detail fields contain 8,192 characters. Ordering, IDs, and content are deterministic;+all addresses use example.com. Assets are generated colored rectangles. Reproduce+the checked-in clip with:++~~~sh+ffmpeg -f lavfi -i color=c=0x335577:s=640x360:r=1 -t 1 -c:v libx264 -pix_fmt yuv420p -movflags +faststart synthetic.mp4+~~~++## Isolation and measurement boundary++- Only portos_test on loopback is accepted. TEST_DB_OK cannot override this.+ The launcher verifies the connected database and creates a fresh+ collection_audit_<random> schema. The child has only that schema in search_path+ and verifies the database/schema before seeding. Canonical media table/index+ DDL and mediaAssetIndex row transforms/writes are reused. No shared table is+ truncated or cleaned. Concurrent runs use separate schemas.+- An inherited PORTOS_DATA_ROOT, production database name, remote database host,+ alternate database service/URL, or non-loopback bind is refused before server+ imports. The launcher copies tracked server/library source to a fresh temporary+ directory and links installed dependencies. It never copies runtime data,+ .env, browser profiles, or private keys. A physical source copy preserves the+ existing rule that CoS worktrees cannot redirect PATHS into a live install.+- The worker receives an explicit environment allowlist; provider keys, agent+ tokens, proxy configuration, NODE_OPTIONS, and test/file-backend switches are+ omitted. The production PostgreSQL gallery path is exercised. Message caches+ use the normal per-account JSON format below temporary PATHS.messages.+- Gallery list/facet/collection reads and inbox summary/detail reads reuse the+ production handlers and services. Pagination and projections happen server-side.+ No browser route interception or collection response mocks are used.+- The real built client and an idle Socket.IO transport are served on the fixture+ origin. Auth/settings bootstrap responses describe this synthetic environment.+ Unrelated APIs explicitly return FIXTURE_UNAVAILABLE (503); media mutations+ return 405. Record unavailable calls separately in browser reports; they are+ fixture limitations rather than production API performance evidence.+- No application boot entrypoint, scheduler, provider runner, peer connection,+ sync, or send endpoint is started. Accounts are disabled. A same-origin connect+ policy prevents the browser reaching the running install or external services.+ This covers collection loading, pagination, detail hydration, and idle+ observations; it is not a full-install end-to-end environment.++Tests, from server/:++~~~sh+npm test -- ../scripts/perf/collectionFixture.test.js+npm run test:db -- ../scripts/perf/collectionFixture.db.test.js+~~~++The first covers pre-import isolation rejection. The second covers actual HTTP+pagination, projections, unavailable actions, and success/failure cleanup against+portos_test.diff --git a/scripts/perf/assets/synthetic.mp4 b/scripts/perf/assets/synthetic.mp4new file mode 100644index 0000000000..599c5b2cc7Binary files /dev/null and b/scripts/perf/assets/synthetic.mp4 differdiff --git a/scripts/perf/collectionFixture.db.test.js b/scripts/perf/collectionFixture.db.test.jsnew file mode 100644index 0000000000..5791a57d9e--- /dev/null+++ b/scripts/perf/collectionFixture.db.test.js@@ -0,0 +1,121 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';+import { spawn } from 'node:child_process';+import { once } from 'node:events';+import { createRequire } from 'node:module';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { requireDbOrSkip } from '../../server/lib/dbTestGate.js';+import { startCollectionFixture } from './collectionFixture.js';++const { Client } = createRequire(new URL('../../server/package.json', import.meta.url))('pg');+let client;+let clientDist;+let available;+const schemas = async () => (await client.query("SELECT nspname FROM pg_namespace WHERE nspname LIKE 'collection_audit_%' ORDER BY nspname")).rows.map(row => row.nspname);+const roots = async () => (await readdir(tmpdir())).filter(name => name.startsWith('portos-collection-audit-')).sort();++beforeAll(async () => {+ if (process.env.PGDATABASE !== 'portos_test') {+ available = requireDbOrSkip('collection fixture', false, 'requires portos_test');+ return;+ }+ client = new Client({ database: 'portos_test', host: process.env.PGHOST || '127.0.0.1',+ port: Number(process.env.PGPORT || 5432), user: process.env.PGUSER || 'portos',+ password: process.env.PGPASSWORD || 'portos', options: '', connectionTimeoutMillis: 2000 });+ try { await client.connect(); available = true; } catch {+ available = requireDbOrSkip('collection fixture', false, 'test database unavailable');+ }+ if (available) {+ clientDist = await mkdtemp(join(tmpdir(), 'collection-client-test-'));+ await writeFile(join(clientDist, 'index.html'), '<!doctype html><title>Synthetic lifecycle client</title>');+ }+});+afterAll(async () => {+ await client?.end();+ if (clientDist) await rm(clientDist, { recursive: true, force: true });+});++describe('isolated fixture using real collection routes and storage', () => {+ it('pages PostgreSQL media and projected inbox data, then removes only its resources', async context => {+ if (!available) return context.skip();+ const beforeSchemas = await schemas();+ const beforeRoots = await roots();+ const fixture = await startCollectionFixture({ clientDist });+ const get = async path => {+ const response = await fetch(fixture.url + path);+ expect(response.status).toBe(200);+ return response.json();+ };+ try {+ expect((await get('/__fixture/ready')).cardinalities).toMatchObject({ images: 2400, videos: 1200, messages: 4000 });+ const page = await get('/api/image-gen/gallery?limit=7&offset=0&media=true&kind=all&summary=true&hidden=false');+ expect(page).toMatchObject({ total: 3240, hiddenTotal: 360, counts: { image: 2160, video: 1080, all: 3240 } });+ expect(page.items).toHaveLength(7);+ expect(new Set(page.items.map(item => item.kind))).toEqual(new Set(['image', 'video']));+ expect(page.items.every(item => !item.data.hidden)).toBe(true);+ const next = await get('/api/image-gen/gallery?limit=7&offset=7&media=true&kind=all&hidden=false');+ expect(next.items.map(item => item.data.filename).some(name => page.items.some(item => item.data.filename === name))).toBe(false);+ const inbox = await get('/api/messages/inbox?limit=11&offset=20&summary=true');+ expect(inbox.total).toBe(4000);+ expect(inbox.messages).toHaveLength(11);+ expect(inbox.messages[0]).not.toHaveProperty('bodyHtml');+ expect(inbox.messages[0].evaluation).not.toHaveProperty('reasoning');+ const summary = inbox.messages[0];+ const detail = await get('/api/messages/' + summary.accountId + '/' + summary.id);+ expect(detail.bodyText).toHaveLength(8192);+ expect((await fetch(fixture.url + '/api/messages/sync/' + summary.accountId, { method: 'POST' })).status).toBe(503);+ expect((await fetch(fixture.url + '/api/image-gen/generate', { method: 'POST' })).status).toBe(405);+ expect((await fetch(fixture.url + '/messages/inbox')).headers.get('content-security-policy')).toContain("connect-src 'self'");+ expect((await schemas()).length).toBe(beforeSchemas.length + 1);+ } finally {+ await fixture.close();+ await fixture.close();+ }+ expect(await schemas()).toEqual(beforeSchemas);+ expect(await roots()).toEqual(beforeRoots);+ await expect(fetch(fixture.url + '/__fixture/ready')).rejects.toThrow();+ }, 120000);++ it('cleans fixture resources on SIGTERM', async context => {+ if (!available) return context.skip();+ const beforeSchemas = await schemas();+ const beforeRoots = await roots();+ const moduleUrl = new URL('./collectionFixture.js', import.meta.url).href;+ const source = 'import { startCollectionFixture } from ' + JSON.stringify(moduleUrl)+ + '; const f = await startCollectionFixture({ clientDist: ' + JSON.stringify(clientDist)+ + ' }); console.log(JSON.stringify({ url: f.url }));';+ const child = spawn(process.execPath, ['--input-type=module', '-e', source], {+ env: process.env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ const exited = once(child, 'exit');+ child.stderr.resume();+ try {+ await new Promise((resolveReady, rejectReady) => {+ let output = '';+ child.stdout.on('data', chunk => {+ output += chunk;+ if (output.includes('\n')) resolveReady();+ });+ child.once('error', rejectReady);+ child.once('exit', code => rejectReady(new Error('Fixture exited early: ' + code)));+ });+ child.kill('SIGTERM');+ expect((await exited)[0]).toBe(0);+ } finally {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGTERM');+ await exited;+ }+ }+ expect(await schemas()).toEqual(beforeSchemas);+ expect(await roots()).toEqual(beforeRoots);+ }, 120000);++ it('cleans the temporary root when database startup fails', async context => {+ if (!available) return context.skip();+ const before = await roots();+ await expect(startCollectionFixture({ clientDist, env: { PGDATABASE: 'portos_test', PGPORT: '1' } })).rejects.toThrow();+ expect(await roots()).toEqual(before);+ }, 120000);+});diff --git a/scripts/perf/collectionFixture.js b/scripts/perf/collectionFixture.jsnew file mode 100644index 0000000000..bf3b8ac030--- /dev/null+++ b/scripts/perf/collectionFixture.js@@ -0,0 +1,145 @@+/**+ * Opt-in synthetic collection instance. Parent owns every resource; the child+ * imports application modules only after its environment has been isolated.+ */+import { execFile, fork } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { access, cp, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { promisify } from 'node:util';+import { fileURLToPath, pathToFileURL } from 'node:url';++const codeRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..');++export function validateFixtureEnvironment(env = process.env, host = '127.0.0.1') {+ if (host !== '127.0.0.1') throw new Error('Fixture bind must be 127.0.0.1');+ if (env.PORTOS_DATA_ROOT) throw new Error('Unset PORTOS_DATA_ROOT; the fixture creates its own root');+ if (env.PGDATABASE && env.PGDATABASE !== 'portos_test') throw new Error('Fixture requires portos_test');+ if (env.PGHOST && !['127.0.0.1', 'localhost', '::1'].includes(env.PGHOST)) {+ throw new Error('Fixture PostgreSQL must be on loopback');+ }+ if (env.PGSERVICE || env.PGSERVICEFILE || env.DATABASE_URL) throw new Error('Remove alternate database configuration');+}++/** Each invocation returns { url, cardinalities, close }; close is idempotent. */+export async function startCollectionFixture({+ env = process.env, host = '127.0.0.1', clientDist = join(codeRoot, 'client/dist'),+} = {}) {+ validateFixtureEnvironment(env, host);+ await access(join(clientDist, 'index.html'));+ const require = createRequire(join(codeRoot, 'server/package.json'));+ const { Client } = require('pg');+ const schema = 'collection_audit_' + randomUUID().replaceAll('-', '');+ const dbConfig = { host: env.PGHOST || '127.0.0.1', port: Number(env.PGPORT || 5432),+ database: 'portos_test', user: env.PGUSER || 'portos', password: env.PGPASSWORD || 'portos',+ options: '', connectionTimeoutMillis: 10000 };+ const db = new Client(dbConfig);+ let root;+ let child;+ let schemaCreated = false;+ let closing;+ let stopped = false;+ let finishSetup;+ const setupFinished = new Promise(resolveSetup => { finishSetup = resolveSetup; });+ const close = () => closing ||= (async () => {+ await setupFinished;+ let cleanupError;+ if (child && child.exitCode === null && child.signalCode === null) {+ const exited = new Promise(resolveExit => child.once('exit', resolveExit));+ child.kill('SIGTERM');+ const killTimer = setTimeout(() => child.kill('SIGKILL'), 5000);+ await exited;+ clearTimeout(killTimer);+ }+ // Never touch public/shared tables. This unguessable schema is created by+ // this invocation and is the only database object cleanup can drop.+ try {+ if (schemaCreated) await db.query('DROP SCHEMA "' + schema + '" CASCADE');+ } catch (error) { cleanupError = error; }+ await db.end().catch(error => { cleanupError ||= error; });+ if (root) await rm(root, { recursive: true, force: true });+ process.removeListener('SIGINT', onSignal);+ process.removeListener('SIGTERM', onSignal);+ if (cleanupError) throw cleanupError;+ })();+ const onSignal = () => { stopped = true; close().catch(() => { process.exitCode = 1; }); };+ process.once('SIGINT', onSignal);+ process.once('SIGTERM', onSignal);+ try {+ root = await realpath(await mkdtemp(join(tmpdir(), 'portos-collection-audit-')));+ // Copy code, never data, configuration, credentials, or the live checkout's+ // symlinks. A physical temp copy also preserves dataRoot's worktree guard.+ const { stdout } = await promisify(execFile)('git', ['ls-files', '-z', '--', 'server', 'lib'], { cwd: codeRoot });+ for (const file of stdout.split('\0').filter(Boolean)) {+ if (file === 'lib/slashdo' || file.endsWith('.test.js') || file.endsWith('.test.jsx')) continue;+ await mkdir(dirname(join(root, file)), { recursive: true });+ await cp(join(codeRoot, file), join(root, file), { dereference: false });+ }+ await mkdir(join(root, 'scripts/perf'), { recursive: true });+ for (const file of ['collectionFixtureWorker.js', 'collectionFixtureData.js']) {+ await cp(join(codeRoot, 'scripts/perf', file), join(root, 'scripts/perf', file));+ }+ await cp(join(codeRoot, 'scripts/perf/assets'), join(root, 'scripts/perf/assets'), { recursive: true });+ await writeFile(join(root, 'package.json'), '{"type":"module"}\n');+ await symlink(join(codeRoot, 'server/node_modules'), join(root, 'server/node_modules'), 'junction');+ await db.connect();+ const identity = await db.query('SELECT current_database() AS name');+ if (identity.rows[0].name !== 'portos_test') throw new Error('Connected database is not portos_test');+ await db.query('CREATE SCHEMA "' + schema + '"');+ schemaCreated = true;+ // An allowlist prevents API tokens, provider keys, proxy settings, NODE_OPTIONS,+ // user home configuration, and inherited test escape hatches reaching reads.+ if (stopped) throw new Error('Fixture startup interrupted');+ child = fork(join(root, 'scripts/perf/collectionFixtureWorker.js'), [], {+ cwd: root, execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'],+ env: {+ NODE_ENV: 'production', PORTOS_DATA_ROOT: root,+ HOME: root, USERPROFILE: root, TMPDIR: root,+ PGHOST: dbConfig.host, PGPORT: String(dbConfig.port), PGDATABASE: 'portos_test',+ PGUSER: dbConfig.user, PGPASSWORD: dbConfig.password,+ PGOPTIONS: '-csearch_path=' + schema, COLLECTION_FIXTURE_SCHEMA: schema,+ COLLECTION_FIXTURE_CLIENT: resolve(clientDist),+ },+ });+ // Drain diagnostics without leaking paths, payloads, or credentials into reports.+ child.stderr.resume();+ const ready = await new Promise((resolveReady, rejectReady) => {+ const timer = setTimeout(() => rejectReady(new Error('Collection fixture readiness timed out')), 30000);+ const finish = (error, value) => {+ clearTimeout(timer);+ child.removeListener('error', onError);+ child.removeListener('exit', onExit);+ child.removeListener('message', onMessage);+ error ? rejectReady(error) : resolveReady(value);+ };+ const onError = () => finish(new Error('Collection fixture child failed to start'));+ const onExit = () => finish(new Error('Collection fixture child exited before readiness'));+ const onMessage = message => {+ if (message?.type === 'ready') finish(null, message);+ if (message?.type === 'failed') finish(new Error('Collection fixture initialization failed at ' + message.phase));+ };+ child.once('error', onError);+ child.once('exit', onExit);+ child.on('message', onMessage);+ });+ if (stopped) throw new Error('Fixture startup interrupted');+ finishSetup();+ child.once('exit', () => { close().catch(() => { process.exitCode = 1; }); });+ return { url: ready.url, cardinalities: ready.cardinalities, close };+ } catch (error) {+ finishSetup();+ await close();+ throw error;+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {+ startCollectionFixture().then(fixture => {+ console.log(JSON.stringify({ ready: true, url: fixture.url, cardinalities: fixture.cardinalities }));+ }).catch(error => {+ console.error(error.message);+ process.exitCode = 1;+ });+}diff --git a/scripts/perf/collectionFixture.test.js b/scripts/perf/collectionFixture.test.jsnew file mode 100644index 0000000000..ee8bd23abd--- /dev/null+++ b/scripts/perf/collectionFixture.test.js@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';+import { startCollectionFixture, validateFixtureEnvironment } from './collectionFixture.js';++describe('collection fixture isolation gate', () => {+ it('refuses unsafe destinations before creating resources or importing server modules', async () => {+ for (const env of [+ { PGDATABASE: 'portos' }, { PGDATABASE: 'other_test', TEST_DB_OK: '1' },+ { PORTOS_DATA_ROOT: '/example/live-install' }, { PGHOST: 'example.com' },+ { DATABASE_URL: 'postgres://example.com/portos_test' }, { PGSERVICE: 'production' },+ ]) {+ await expect(startCollectionFixture({ env, clientDist: '/does-not-exist' })).rejects.toThrow(/Fixture|Unset|Remove/);+ }+ expect(() => validateFixtureEnvironment({}, '0.0.0.0')).toThrow('127.0.0.1');+ expect(() => validateFixtureEnvironment({ PGDATABASE: 'portos_test', PGHOST: 'localhost' })).not.toThrow();+ });+});diff --git a/scripts/perf/collectionFixtureData.js b/scripts/perf/collectionFixtureData.jsnew file mode 100644index 0000000000..119b4bf84c--- /dev/null+++ b/scripts/perf/collectionFixtureData.js@@ -0,0 +1,29 @@+// Fixed content and ordering make separate fixture runs comparable.+export const CARDINALITIES = Object.freeze({+ images: 2400, videos: 1200, hiddenImages: 240, hiddenVideos: 120,+ accounts: 2, messages: 4000, detailCharacters: 8192,+});+export const ACCOUNT_IDS = ['00000000-0000-4000-8000-000000000001', '00000000-0000-4000-8000-000000000002'];+const date = index => new Date(Date.UTC(2025, 0, 1) + index * 60000).toISOString();+const detail = 'Synthetic collection audit detail. '.repeat(256).slice(0, CARDINALITIES.detailCharacters);++export function mediaFixture(kind, index) {+ const id = 'synthetic-' + kind + '-' + String(index).padStart(5, '0');+ const filename = id + (kind === 'image' ? '.png' : '.mp4');+ return { id, filename, path: '/data/' + (kind === 'image' ? 'images/' : 'videos/') + filename,+ thumbnail: kind === 'video' ? id + '.png' : undefined,+ createdAt: date(index * (kind === 'video' ? 4 : 2) + (kind === 'video' ? 1 : 0)), hidden: index % 10 === 0, width: 640, height: 360,+ prompt: id + ' ' + detail, model: 'synthetic-fixture', status: 'completed',+ ...(kind === 'video' ? { duration: 1, fps: 1 } : {}),+ };+}++export function messageFixture(accountId, index) {+ return { id: 'synthetic-message-' + index, externalId: 'synthetic-external-' + index,+ accountId, threadId: 'synthetic-thread-' + Math.floor(index / 2), subject: 'Synthetic message ' + index,+ from: { name: 'Example Sender', email: '[email protected]' }, to: ['[email protected]'],+ date: date(index), source: 'gmail', isRead: index % 3 === 0, isUnread: index % 3 !== 0,+ bodyText: detail, bodyHtml: '<p>' + detail + '</p>',+ evaluation: { action: 'review', priority: 'normal', reasoning: detail },+ };+}diff --git a/scripts/perf/collectionFixtureWorker.js b/scripts/perf/collectionFixtureWorker.jsnew file mode 100644index 0000000000..695abb117a--- /dev/null+++ b/scripts/perf/collectionFixtureWorker.js@@ -0,0 +1,129 @@+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { join, resolve } from 'node:path';+import { CARDINALITIES, ACCOUNT_IDS, mediaFixture, messageFixture } from './collectionFixtureData.js';++// This is the only worker entrypoint. Validate BEFORE dynamic server imports.+const root = process.cwd();+const schema = process.env.COLLECTION_FIXTURE_SCHEMA;+if (process.env.PORTOS_DATA_ROOT !== root || !/^[\s\S]*[\\/]portos-collection-audit-[^\\/]+$/.test(root)+ || process.env.PGDATABASE !== 'portos_test' || !/^collection_audit_[a-f0-9]{32}$/.test(schema || '')+ || process.env.PGOPTIONS !== '-csearch_path=' + schema || process.env.NODE_ENV !== 'production'+ || process.env.VITEST || !process.send) {+ throw new Error('Invalid isolated collection worker environment');+}++let server;+let io;+let db;+let closing;+let phase = 'imports';+const close = () => closing ||= (async () => {+ if (server) {+ if (io) await new Promise(resolveIo => io.close(resolveIo));+ server.closeAllConnections();+ await new Promise(resolveClose => server.close(resolveClose));+ }+ await db?.close();+ if (process.connected) process.disconnect();+})();+const stop = () => { close().catch(() => { process.exitCode = 1; }); };+process.once('SIGINT', stop);+process.once('SIGTERM', stop);+process.once('disconnect', stop);++async function start() {+ const require = createRequire(join(root, 'server/package.json'));+ const express = require('express');+ const sharp = require('sharp');+ db = await import('../../server/lib/db.js');+ const { PATHS } = await import('../../server/lib/paths.js');+ if (resolve(PATHS.data) !== join(root, 'data')) throw new Error('Fixture data root mismatch');+ phase = 'database';+ const identity = await db.query('SELECT current_database() AS db, current_schema() AS schema');+ if (identity.rows[0].db !== 'portos_test' || identity.rows[0].schema !== schema) throw new Error('Fixture DB isolation mismatch');+ const { mediaDdl } = await import('../../server/lib/db/schema/media.js');+ // Reuse the canonical table/index declarations without booting other domains.+ for (const sql of mediaDdl.filter(sql => /CREATE (TABLE IF NOT EXISTS media_assets\b|INDEX IF NOT EXISTS idx_media_assets_kind_created\b)/.test(sql))) {+ await db.query(sql);+ }+ const { upsertAsset } = await import('../../server/services/mediaAssetIndex/db.js');+ const { imageToRow, videoToRow } = await import('../../server/services/mediaAssetIndex/logic.js');+ await Promise.all(['images', 'videos', 'video-thumbnails', 'messages/cache'].map(dir => mkdir(join(PATHS.data, dir), { recursive: true })));+ const png = await sharp({ create: { width: 640, height: 360, channels: 3, background: '#335577' } }).png().toBuffer();+ phase = 'media-seed';+ for (let index = 0; index < CARDINALITIES.images; index++) {+ const image = mediaFixture('image', index);+ await writeFile(join(PATHS.images, image.filename), png);+ await writeFile(join(PATHS.images, image.filename.replace('.png', '.metadata.json')), JSON.stringify(image));+ await upsertAsset(imageToRow(image));+ }+ const clip = await readFile(join(root, 'scripts/perf/assets/synthetic.mp4'));+ const videos = [];+ for (let index = 0; index < CARDINALITIES.videos; index++) {+ const video = mediaFixture('video', index);+ videos.push(video);+ await writeFile(join(PATHS.data, 'videos', video.filename), clip);+ await writeFile(join(PATHS.data, 'video-thumbnails', video.thumbnail), png);+ await upsertAsset(videoToRow(video));+ }+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify(videos));+ phase = 'inbox-seed';+ const accounts = {};+ for (const [accountIndex, id] of ACCOUNT_IDS.entries()) {+ accounts[id] = { id, name: 'Synthetic inbox ' + (accountIndex + 1), type: 'gmail', provider: 'api',+ email: 'fixture' + accountIndex + '@example.com', enabled: false, syncConfig: {}, lastSyncAt: null };+ const messages = Array.from({ length: CARDINALITIES.messages / CARDINALITIES.accounts },+ (_, index) => messageFixture(id, index + accountIndex * CARDINALITIES.messages / CARDINALITIES.accounts));+ await writeFile(join(PATHS.messages, 'cache', id + '.json'), JSON.stringify({ syncCursor: null, messages }));+ }+ await writeFile(join(PATHS.messages, 'accounts.json'), JSON.stringify(accounts));+ await writeFile(join(PATHS.data, 'settings.json'), JSON.stringify({ timezone: 'UTC', instances: [] }));++ phase = 'routes';+ const { createImageGalleryHandlers } = await import('../../server/routes/imageGalleryRead.js');+ const { messageInboxRead, messageDetailRead } = await import('../../server/routes/messageInboxRead.js');+ const { listAccounts } = await import('../../server/services/messageAccounts.js');+ const { errorMiddleware, asyncHandler } = await import('../../server/lib/errorHandler.js');+ const app = express();+ app.disable('x-powered-by');+ app.use((_req, res, next) => {+ res.set('Content-Security-Policy', "connect-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; frame-src 'none'; form-action 'none'");+ next();+ });+ app.get('/__fixture/ready', (_req, res) => res.json({ ready: true, cardinalities: CARDINALITIES }));+ app.get('/api/auth/status', (_req, res) => res.json({ enabled: false, authenticated: true }));+ app.get('/api/settings/features', (_req, res) => res.json({ features: [], groups: [] }));+ app.get('/api/settings', (_req, res) => res.json({ timezone: 'UTC' }));+ // Allow only collection reads. Mutation / provider / peer / sync endpoints+ // are absent; no server boot module or scheduler is imported.+ const gallery = express.Router();+ const galleryReads = createImageGalleryHandlers();+ gallery.get('/gallery/collections', galleryReads.collections);+ gallery.get('/gallery/facets', galleryReads.facets);+ gallery.get('/gallery', galleryReads.list);+ app.use('/api/image-gen', (req, res, next) => req.method === 'GET' ? next() : res.sendStatus(405), gallery);+ const messages = express.Router();+ messages.get('/accounts', asyncHandler(async (_req, res) => res.json(await listAccounts())));+ messages.get('/inbox', messageInboxRead);+ messages.get('/:accountId/:messageId', messageDetailRead);+ app.use('/api/messages', messages);+ app.use('/api', (_req, res) => res.status(503).json({ code: 'FIXTURE_UNAVAILABLE', error: 'Outside collection audit fixture scope' }));+ app.use('/data', express.static(PATHS.data, { index: false, dotfiles: 'deny' }));+ app.use(express.static(process.env.COLLECTION_FIXTURE_CLIENT));+ app.get(/.*/, (_req, res) => res.sendFile(join(process.env.COLLECTION_FIXTURE_CLIENT, 'index.html')));+ app.use(errorMiddleware);+ server = await new Promise((resolveListen, rejectListen) => {+ const listener = app.listen(0, '127.0.0.1', () => resolveListen(listener));+ listener.once('error', rejectListen);+ });+ const { Server } = require('socket.io');+ io = new Server(server);+ process.send({ type: 'ready', url: 'http://127.0.0.1:' + server.address().port, cardinalities: CARDINALITIES });+}++start().catch(async () => {+ if (process.connected) process.send({ type: 'failed', phase });+ await close();+ process.exitCode = 1;+});diff --git a/server/routes/imageGalleryRead.js b/server/routes/imageGalleryRead.jsnew file mode 100644index 0000000000..95b014bc12--- /dev/null+++ b/server/routes/imageGalleryRead.js@@ -0,0 +1,52 @@+// Shared production collection reads; safe to mount without generation routes.+import { z } from 'zod';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';++export function createImageGalleryHandlers(listGallery = async () => (await import('../services/imageGen/local.js')).listGallery()) {+ const galleryQuerySchema = z.object({+ limit: z.coerce.number().int().min(1).max(200).default(60),+ offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),+ q: z.string().max(500).default(''),+ hidden: z.enum(['true', 'false']).optional().transform(v => v === undefined ? undefined : v === 'true'),+ starred: z.enum(['true', 'false']).optional().transform(v => v === 'true'),+ summary: z.enum(['true', 'false']).optional().transform(v => v === 'true'),+ filename: z.string().min(1).max(255).optional(),+ kind: z.enum(['image', 'video', 'all']).default('image'),+ media: z.enum(['true', 'false']).optional().transform(v => v === 'true'),+ collectionId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),+ universeId: z.string().min(1).max(255).optional(),+ entryCategory: z.string().min(1).max(255).optional(),+ entryKind: z.string().min(1).max(255).optional(),+ });++ const collections = asyncHandler(async (_req, res) => {+ const { listGalleryCollectionSummaries } = await import('../services/mediaAssetIndex/gallery.js');+ res.json(await listGalleryCollectionSummaries(listGallery));+ });++ const facets = asyncHandler(async (_req, res) => {+ const { listGalleryFacets } = await import('../services/mediaAssetIndex/gallery.js');+ res.json(await listGalleryFacets(listGallery));+ });++ // Reference hydration is bounded independently of browsing; callers send only+ // filenames actually attached to their universe, project or export.+ const lookup = asyncHandler(async (req, res) => {+ const { filenames } = validateRequest(z.object({ filenames: z.array(z.string().min(1).max(255)).max(200) }), req.body);+ const { listGalleryPage } = await import('../services/mediaAssetIndex/gallery.js');+ res.json((await listGalleryPage({ limit: 200, mediaKeys: filenames.map(f => `image:${f}`) }, listGallery)).items);+ });++ const list = asyncHandler(async (req, res) => {+ // No paging keys preserves the full legacy array for callers not migrated yet.+ // New callers use ?limit=5 (recent strip) or ?limit=60&offset=0&q=...+ const paginated = Object.keys(galleryQuerySchema.shape).some(key => req.query[key] !== undefined);+ if (!paginated) return res.json(await listGallery());+ const options = validateRequest(galleryQuerySchema, req.query);+ const { listGalleryPage } = await import('../services/mediaAssetIndex/gallery.js');+ res.json(await listGalleryPage(options, listGallery));+ });++ return { collections, facets, lookup, list };+}diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 7345ee4658..c1a32d820f 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -9,6 +9,7 @@* (gallery, loras, models, delete) target the local module directly.*/+import { createImageGalleryHandlers } from './imageGalleryRead.js';import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';@@ -795,49 +796,11 @@ router.get('/loras', asyncHandler(async (_req, res) => {res.json(await local.listLoraFilenames());}));-const galleryQuerySchema = z.object({- limit: z.coerce.number().int().min(1).max(200).default(60),- offset: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0),- q: z.string().max(500).default(''),- hidden: z.enum(['true', 'false']).optional().transform(v => v === undefined ? undefined : v === 'true'),- starred: z.enum(['true', 'false']).optional().transform(v => v === 'true'),- summary: z.enum(['true', 'false']).optional().transform(v => v === 'true'),- filename: z.string().min(1).max(255).optional(),- kind: z.enum(['image', 'video', 'all']).default('image'),- media: z.enum(['true', 'false']).optional().transform(v => v === 'true'),- collectionId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),- universeId: z.string().min(1).max(255).optional(),- entryCategory: z.string().min(1).max(255).optional(),- entryKind: z.string().min(1).max(255).optional(),-});--router.get('/gallery/collections', asyncHandler(async (_req, res) => {- const { listGalleryCollectionSummaries } = await import('../services/mediaAssetIndex/gallery.js');- res.json(await listGalleryCollectionSummaries(local.listGallery));-}));--router.get('/gallery/facets', asyncHandler(async (_req, res) => {- const { listGalleryFacets } = await import('../services/mediaAssetIndex/gallery.js');- res.json(await listGalleryFacets(local.listGallery));-}));--// Reference hydration is bounded independently of browsing; callers send only-// filenames actually attached to their universe, project or export.-router.post('/gallery/lookup', asyncHandler(async (req, res) => {- const { filenames } = validateRequest(z.object({ filenames: z.array(z.string().min(1).max(255)).max(200) }), req.body);- const { listGalleryPage } = await import('../services/mediaAssetIndex/gallery.js');- res.json((await listGalleryPage({ limit: 200, mediaKeys: filenames.map(f => `image:${f}`) }, local.listGallery)).items);-}));--router.get('/gallery', asyncHandler(async (req, res) => {- // No paging keys preserves the full legacy array for callers not migrated yet.- // New callers use ?limit=5 (recent strip) or ?limit=60&offset=0&q=...- const paginated = Object.keys(galleryQuerySchema.shape).some(key => req.query[key] !== undefined);- if (!paginated) return res.json(await local.listGallery());- const options = validateRequest(galleryQuerySchema, req.query);- const { listGalleryPage } = await import('../services/mediaAssetIndex/gallery.js');- res.json(await listGalleryPage(options, local.listGallery));-}));+const galleryReads = createImageGalleryHandlers(local.listGallery);+router.get('/gallery/collections', galleryReads.collections);+router.get('/gallery/facets', galleryReads.facets);+router.post('/gallery/lookup', galleryReads.lookup);+router.get('/gallery', galleryReads.list);// SSE progress stream. Local renders run via the mediaJobQueue and emit// `queued` → `started` → `progress` → `complete` events; the queue owns thediff --git a/server/routes/messageInboxRead.js b/server/routes/messageInboxRead.jsnew file mode 100644index 0000000000..5b8988bef0--- /dev/null+++ b/server/routes/messageInboxRead.js@@ -0,0 +1,58 @@+// Shared production inbox route, without sync, send, browser or AI endpoints.+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { parsePagination } from '../lib/validation.js';+import { UUID_RE } from '../lib/fileUtils.js';+import * as messageSync from '../services/messageSync.js';++export const messageInboxRead = asyncHandler(async (req, res) => {+ const { accountId, search } = req.query;+ if (accountId && !UUID_RE.test(accountId)) {+ throw new ServerError('Invalid accountId format', { status: 400 });+ }+ const { limit: parsedLimit, offset: parsedOffset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 100 });+ const result = await messageSync.getMessages({+ accountId,+ search,+ limit: parsedLimit,+ offset: parsedOffset+ });+ // Summary is opt-in so older clients and automation retain the full-record+ // contract. Search and pagination above still run against the full cache.+ res.json(req.query.summary === 'true' ? {+ ...result,+ messages: result.messages.map(message => ({+ id: message.id,+ accountId: message.accountId,+ externalId: message.externalId,+ threadId: message.threadId,+ subject: message.subject,+ from: message.from && { name: message.from.name, email: message.from.email },+ date: message.date,+ source: message.source,+ isRead: message.isRead,+ isUnread: message.isUnread,+ isPinned: message.isPinned,+ isFlagged: message.isFlagged,+ preview: typeof message.bodyText === 'string' ? message.bodyText.slice(0, 100) : '',+ evaluation: message.evaluation && {+ action: message.evaluation.action,+ priority: message.evaluation.priority,+ },+ })),+ } : result);+});+++export const messageParamsSchema = z.object({+ accountId: z.string().guid(),+ messageId: z.string().min(1)+});++export const messageDetailRead = asyncHandler(async (req, res) => {+ const parsed = messageParamsSchema.safeParse(req.params);+ if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });+ const message = await messageSync.getMessage(parsed.data.accountId, parsed.data.messageId);+ if (!message) throw new ServerError('Message not found', { status: 404 });+ res.json(message);+});diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 6ba870372e..909db6decc 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -1,7 +1,8 @@+import { messageInboxRead, messageDetailRead, messageParamsSchema } from './messageInboxRead.js';import express from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, parsePagination } from '../lib/validation.js';+import { validateRequest } from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';import * as messageAccounts from '../services/messageAccounts.js';import * as messageSync from '../services/messageSync.js';@@ -142,43 +143,7 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {}));// === Inbox Routes ===-router.get('/inbox', asyncHandler(async (req, res) => {- const { accountId, search } = req.query;- if (accountId && !UUID_RE.test(accountId)) {- throw new ServerError('Invalid accountId format', { status: 400 });- }- const { limit: parsedLimit, offset: parsedOffset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 100 });- const result = await messageSync.getMessages({- accountId,- search,- limit: parsedLimit,- offset: parsedOffset- });- // Summary is opt-in so older clients and automation retain the full-record- // contract. Search and pagination above still run against the full cache.- res.json(req.query.summary === 'true' ? {- ...result,- messages: result.messages.map(message => ({- id: message.id,- accountId: message.accountId,- externalId: message.externalId,- threadId: message.threadId,- subject: message.subject,- from: message.from && { name: message.from.name, email: message.from.email },- date: message.date,- source: message.source,- isRead: message.isRead,- isUnread: message.isUnread,- isPinned: message.isPinned,- isFlagged: message.isFlagged,- preview: typeof message.bodyText === 'string' ? message.bodyText.slice(0, 100) : '',- evaluation: message.evaluation && {- action: message.evaluation.action,- priority: message.evaluation.priority,- },- })),- } : result);-}));+router.get('/inbox', messageInboxRead);// === Triage Rules Routes ===router.get('/triage-rules', asyncHandler(async (req, res) => {@@ -396,11 +361,6 @@ router.get('/thread/:accountId/:threadId', asyncHandler(async (req, res) => {}));// === Message params schema (shared by detail + refresh routes) ===-const messageParamsSchema = z.object({- accountId: z.string().guid(),- messageId: z.string().min(1)-});-// === Per-message refresh ===router.post('/:accountId/:messageId/refresh', asyncHandler(async (req, res) => {const parsed = messageParamsSchema.safeParse(req.params);@@ -513,12 +473,6 @@ router.post('/debug/clear-token', asyncHandler(async (req, res) => {// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===-router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {- const parsed = messageParamsSchema.safeParse(req.params);- if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });- const message = await messageSync.getMessage(parsed.data.accountId, parsed.data.messageId);- if (!message) throw new ServerError('Message not found', { status: 404 });- res.json(message);-}));+router.get('/:accountId/:messageId', messageDetailRead);export default router;diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 10fe339321..75da3491f2 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -15,6 +15,7 @@ process.env.NODE_ENV = 'test';* listed explicitly below (the drift guard fails the build if you forget).*/export const DB_TEST_INCLUDE = [+ '../scripts/perf/collectionFixture.db.test.js','services/appQuality.db.test.js','**/db.test.js','services/dbAdmin.db.test.js',