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
fix([render-slowness-on-long-sessions-per-scene-render]): enforce runs[] cap at saveAll and migrate legacy bloat
[._.]/ Adam Eivyfd3e8337062d
diff --git a/client/src/services/apiCreativeDirector.js b/client/src/services/apiCreativeDirector.jsindex 1179e5e1b0..b52a27f737 100644--- a/client/src/services/apiCreativeDirector.js+++ b/client/src/services/apiCreativeDirector.js@@ -3,7 +3,7 @@ import { request } from './apiCore.js';export const listCreativeDirectorProjects = () => request('/creative-director');// Pass `{ slim: true }` to receive only the fields a polling consumer needs// (status / per-scene status / finalVideoId / failureReason / updatedAt) —-// drops the unbounded `runs[]` history and the full treatment text. Useful+// drops the `runs[]` history and the full treatment text. Useful// for 4s-poll surfaces like the Pipeline EpisodeVideoStage.export const getCreativeDirectorProject = (id, { slim = false } = {}) =>request(`/creative-director/${encodeURIComponent(id)}${slim ? '?slim=1' : ''}`);diff --git a/scripts/migrations/047-trim-creative-director-runs.js b/scripts/migrations/047-trim-creative-director-runs.jsnew file mode 100644index 0000000000..3283316c9f--- /dev/null+++ b/scripts/migrations/047-trim-creative-director-runs.js@@ -0,0 +1,93 @@+/**+ * Truncate accumulated per-project `runs[]` history in+ * `data/creative-director-projects.json` so existing installs immediately shed+ * the bloat that turned per-scene orchestration into O(N²) wall-clock during+ * long sessions.+ *+ * Without this one-shot, the cap added in `server/services/creativeDirector/local.js`+ * only shrinks a project's runs[] the next time something writes that project+ * — so until that happens, every list / get / scene update still parses and+ * serializes the legacy multi-thousand-entry payload from disk.+ *+ * Trim policy mirrors `trimRuns` in `local.js`: keep every non-terminal run+ * (load-bearing for orphan / dedup detection in completionHook and the boot+ * recovery scan) plus the most-recent terminal entries, up to MAX_PERSISTED_RUNS+ * total. Skip projects whose runs[] is already under the cap.+ *+ * Idempotent: a second run finds everything already at or under the cap and+ * exits without writing.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++const REL_PATH = 'data/creative-director-projects.json';+const MAX_PERSISTED_RUNS = 200;+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed']);++function trimRuns(runs) {+ if (!Array.isArray(runs) || runs.length <= MAX_PERSISTED_RUNS) return runs;+ let inflightCount = 0;+ for (const r of runs) {+ if (!(r && TERMINAL_RUN_STATUSES.has(r.status))) inflightCount += 1;+ }+ const terminalBudget = Math.max(0, MAX_PERSISTED_RUNS - inflightCount);+ const kept = [];+ let terminalsKept = 0;+ for (let i = runs.length - 1; i >= 0; i -= 1) {+ const r = runs[i];+ const isTerminal = r && TERMINAL_RUN_STATUSES.has(r.status);+ if (!isTerminal) {+ kept.push(r);+ } else if (terminalsKept < terminalBudget) {+ kept.push(r);+ terminalsKept += 1;+ }+ }+ return kept.reverse();+}++export default {+ async up({ rootDir }) {+ const path = join(rootDir, REL_PATH);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${REL_PATH} not present — skipping (fresh install)`);+ return;+ }++ let projects;+ try {+ projects = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }+ if (!Array.isArray(projects)) {+ console.log(`⚠️ ${REL_PATH}: expected array, found ${typeof projects} — skipping`);+ return;+ }++ let trimmedCount = 0;+ let entriesDropped = 0;+ for (const p of projects) {+ if (!p || !Array.isArray(p.runs) || p.runs.length <= MAX_PERSISTED_RUNS) continue;+ const before = p.runs.length;+ p.runs = trimRuns(p.runs);+ entriesDropped += before - p.runs.length;+ trimmedCount += 1;+ }++ if (trimmedCount === 0) {+ console.log(`✅ ${REL_PATH}: all ${projects.length} project(s) already under runs[] cap of ${MAX_PERSISTED_RUNS}, nothing to migrate`);+ return;+ }++ await atomicWrite(path, `${JSON.stringify(projects, null, 2)}\n`);+ console.log(`📝 ${REL_PATH}: trimmed ${trimmedCount} project(s), dropped ${entriesDropped} stale run entries (cap ${MAX_PERSISTED_RUNS})`);+ },+};diff --git a/scripts/migrations/047-trim-creative-director-runs.test.js b/scripts/migrations/047-trim-creative-director-runs.test.jsnew file mode 100644index 0000000000..1fee76ea14--- /dev/null+++ b/scripts/migrations/047-trim-creative-director-runs.test.js@@ -0,0 +1,88 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './047-trim-creative-director-runs.js';++const FILE = 'data/creative-director-projects.json';++const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 047 — trim creative-director runs[]', () => {+ let rootDir;+ let projectsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-047-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ projectsPath = join(rootDir, FILE);+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('no-ops on a fresh install (file absent)', async () => {+ await migration.up({ rootDir });+ expect(existsSync(projectsPath)).toBe(false);+ });++ it('skips projects already under the cap', async () => {+ const projects = [+ { id: 'cd-small', runs: Array.from({ length: 20 }, (_, i) => ({ runId: `r-${i}`, status: 'completed' })) },+ ];+ writeFileSync(projectsPath, JSON.stringify(projects, null, 2));+ await migration.up({ rootDir });+ expect(readJson(projectsPath)[0].runs).toHaveLength(20);+ });++ it('trims an over-cap legacy project to MAX_PERSISTED_RUNS', async () => {+ const runs = Array.from({ length: 800 }, (_, i) => ({ runId: `r-${i}`, status: 'completed' }));+ writeFileSync(projectsPath, JSON.stringify([{ id: 'cd-huge', runs }], null, 2));+ await migration.up({ rootDir });+ const after = readJson(projectsPath)[0].runs;+ expect(after).toHaveLength(200);+ // Keeps the most-recent terminal entries.+ expect(after[0].runId).toBe('r-600');+ expect(after[199].runId).toBe('r-799');+ });++ it('preserves every in-flight run even when total is way over cap', async () => {+ const runs = [+ ...Array.from({ length: 700 }, (_, i) => ({ runId: `done-${i}`, status: 'completed' })),+ { runId: 'live-treatment', status: 'running', kind: 'treatment' },+ { runId: 'live-evaluate', status: 'queued', kind: 'evaluate', sceneId: 'scene-7' },+ ];+ writeFileSync(projectsPath, JSON.stringify([{ id: 'cd-mixed', runs }], null, 2));+ await migration.up({ rootDir });+ const after = readJson(projectsPath)[0].runs;+ expect(after).toHaveLength(200);+ expect(after.find((r) => r.runId === 'live-treatment')).toBeTruthy();+ expect(after.find((r) => r.runId === 'live-evaluate')).toBeTruthy();+ });++ it('is idempotent — running twice has no further effect', async () => {+ const runs = Array.from({ length: 400 }, (_, i) => ({ runId: `r-${i}`, status: 'completed' }));+ writeFileSync(projectsPath, JSON.stringify([{ id: 'cd-1', runs }], null, 2));+ await migration.up({ rootDir });+ const firstPass = readJson(projectsPath);+ expect(firstPass[0].runs).toHaveLength(200);+ await migration.up({ rootDir });+ const secondPass = readJson(projectsPath);+ expect(secondPass[0].runs).toHaveLength(200);+ expect(secondPass[0].runs[0].runId).toBe(firstPass[0].runs[0].runId);+ });++ it('survives invalid JSON without throwing or corrupting the file', async () => {+ writeFileSync(projectsPath, 'not json {');+ await migration.up({ rootDir });+ expect(readFileSync(projectsPath, 'utf-8')).toBe('not json {');+ });++ it('survives a non-array top-level payload without writing', async () => {+ writeFileSync(projectsPath, JSON.stringify({ projects: [] }));+ await migration.up({ rootDir });+ expect(readJson(projectsPath)).toEqual({ projects: [] });+ });+});diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 4fde32eecf..bcd0b2ecd6 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -35,8 +35,8 @@ router.get('/', asyncHandler(async (_req, res) => {}));// Slim projection of a project for polling consumers (pipeline EpisodeVideoStage-// polls every 4s; the full project carries an unbounded `runs[]` history that-// grows with every render operation). The shape covers exactly what the+// polls every 4s; the full project carries `runs[]` history and the full+// treatment text the poll doesn't need). The shape covers exactly what the// polling UI consumes: status, updatedAt (change-detect key), per-scene// sceneId/order/status, finalVideoId, failureReason. `sceneId` (not `id`) is// the canonical scene identifier per services/creativeDirector/local.js.diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex fc45cdb301..82374846bc 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -30,16 +30,30 @@ const MAX_PERSISTED_RUNS = 200;const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed']);export function trimRuns(runs) {- if (!Array.isArray(runs) || runs.length <= MAX_PERSISTED_RUNS) return runs || [];- const inflight = [];- const terminal = [];+ if (!Array.isArray(runs)) return [];+ if (runs.length <= MAX_PERSISTED_RUNS) return runs;+ let inflightCount = 0;for (const r of runs) {- if (r && TERMINAL_RUN_STATUSES.has(r.status)) terminal.push(r);- else inflight.push(r);+ if (!(r && TERMINAL_RUN_STATUSES.has(r.status))) inflightCount += 1;}- const keepTerminal = Math.max(0, MAX_PERSISTED_RUNS - inflight.length);- const trimmedTerminal = keepTerminal === 0 ? [] : terminal.slice(-keepTerminal);- return [...inflight, ...trimmedTerminal];+ const terminalBudget = Math.max(0, MAX_PERSISTED_RUNS - inflightCount);+ // Walk backwards keeping every in-flight run + the most-recent `terminalBudget`+ // terminal runs, then reverse the result so original chronological order is+ // preserved (RunsTab sorts by startedAt, but recovery scans + completionHook+ // predicates iterate runs[] directly and stay readable when it reads chronologically).+ const kept = [];+ let terminalsKept = 0;+ for (let i = runs.length - 1; i >= 0; i -= 1) {+ const r = runs[i];+ const isTerminal = r && TERMINAL_RUN_STATUSES.has(r.status);+ if (!isTerminal) {+ kept.push(r);+ } else if (terminalsKept < terminalBudget) {+ kept.push(r);+ terminalsKept += 1;+ }+ }+ return kept.reverse();}async function loadAll() {@@ -51,6 +65,12 @@ async function saveAll(projects) {// Defense for first-run on a fresh checkout where data/ may not exist yet.// Mirrors videoTimeline/local.js#saveProjects.await ensureDir(PATHS.data);+ // Enforce the runs[] cap at the single write chokepoint so every mutator+ // (recordRun, updateRun, updateProject, setTreatment, updateScene) shrinks+ // legacy over-cap arrays on first save without each having to remember.+ for (const p of projects) {+ if (Array.isArray(p?.runs)) p.runs = trimRuns(p.runs);+ }await atomicWrite(PROJECTS_FILE, projects);}@@ -181,7 +201,7 @@ export async function recordRun(id, runEntry) {if (idx < 0) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });const project = all[idx];const run = { startedAt: new Date().toISOString(), ...runEntry, runId: runEntry.runId || randomUUID() };- project.runs = trimRuns([...(project.runs || []), run]);+ project.runs = [...(project.runs || []), run];project.updatedAt = new Date().toISOString();all[idx] = project;await saveAll(all);diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 4230c4d673..aec5ddd300 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -17,7 +17,7 @@ vi.mock('../mediaCollections.js', () => ({createCollection: vi.fn(async () => ({ id: 'col-1' })),}));-const { setTreatment, recordRun, trimRuns } = await import('./local.js');+const { setTreatment, recordRun, updateRun, trimRuns } = await import('./local.js');const VALID_TREATMENT = {logline: 'A cat finds a hat.',@@ -97,6 +97,32 @@ describe('trimRuns — bound runs[] growth', () => {expect(trimmed.filter((r) => r.status === 'completed')).toHaveLength(198);});+ it('preserves chronological insertion order across mixed terminal/in-flight entries', () => {+ // Interleave terminal + in-flight so a partition-and-concat impl would+ // shuffle them. The contract: kept entries appear in the same relative+ // order as in the input — RunsTab sorts by startedAt for display, but+ // completionHook + recovery iterate runs[] directly.+ const runs = [];+ for (let i = 0; i < 150; i += 1) {+ runs.push({ runId: `t-a-${i}`, status: 'completed' });+ }+ runs.push({ runId: 'live-mid', status: 'running' });+ for (let i = 0; i < 150; i += 1) {+ runs.push({ runId: `t-b-${i}`, status: 'failed' });+ }+ runs.push({ runId: 'live-end', status: 'queued' });+ const trimmed = trimRuns(runs);+ expect(trimmed).toHaveLength(200);+ const liveMidIdx = trimmed.findIndex((r) => r.runId === 'live-mid');+ const liveEndIdx = trimmed.findIndex((r) => r.runId === 'live-end');+ expect(liveMidIdx).toBeGreaterThanOrEqual(0);+ expect(liveEndIdx).toBeGreaterThan(liveMidIdx);+ // Every retained terminal entry must keep its relative order vs. its neighbors.+ const ids = trimmed.map((r) => r.runId);+ const sorted = [...ids].sort((a, b) => runs.findIndex((r) => r.runId === a) - runs.findIndex((r) => r.runId === b));+ expect(ids).toEqual(sorted);+ });+it('treats unknown non-terminal statuses as in-flight (orphan/wedge detection load-bearing)', () => {const runs = [{ runId: 'mystery', status: 'evaluating' },@@ -106,28 +132,46 @@ describe('trimRuns — bound runs[] growth', () => {expect(trimmed.find((r) => r.runId === 'mystery')).toBeTruthy();});- it('tolerates non-array / nullish input', () => {+ it('returns [] for non-array / nullish input (including truthy non-arrays like {})', () => {expect(trimRuns(null)).toEqual([]);expect(trimRuns(undefined)).toEqual([]);+ expect(trimRuns({})).toEqual([]);+ expect(trimRuns('runs')).toEqual([]);});});-describe('recordRun — applies trim on append', () => {- it('caps persisted runs[] when recordRun would otherwise grow it past the cap', async () => {+describe('runs[] cap enforced at saveAll chokepoint', () => {+ it('recordRun caps when an append pushes the array over the limit', async () => {const existing = Array.from({ length: 200 }, (_, i) => ({ runId: `r-${i}`, status: 'completed', startedAt: new Date(2026, 0, 1, 0, i).toISOString() }));mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'rendering', name: 'Test', runs: existing }]);await recordRun('cd-1', { agentId: 'agent-x', kind: 'evaluate', sceneId: 'scene-1', status: 'running' });const saved = mockAtomicWrite.mock.calls[0][1];expect(saved[0].runs).toHaveLength(200);- // The new in-flight run must survive trim, even though it pushed total past the cap.expect(saved[0].runs.find((r) => r.kind === 'evaluate' && r.sceneId === 'scene-1' && r.status === 'running')).toBeTruthy();});- it('does not cap when total is still under the limit', async () => {+ it('recordRun leaves the array alone when total is still under the limit', async () => {const existing = Array.from({ length: 10 }, (_, i) => ({ runId: `r-${i}`, status: 'completed' }));mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'rendering', name: 'Test', runs: existing }]);await recordRun('cd-1', { agentId: 'agent-x', kind: 'evaluate', status: 'running' });const saved = mockAtomicWrite.mock.calls[0][1];expect(saved[0].runs).toHaveLength(11);});++ it('updateRun also shrinks a legacy over-cap array (not just recordRun)', async () => {+ // Legacy bloated project — 500 terminal + 1 in-flight. The in-flight one+ // is what updateRun is going to patch. Without saveAll-side trim, the+ // 500-entry terminal history would persist unchanged.+ const existing = [+ ...Array.from({ length: 500 }, (_, i) => ({ runId: `legacy-${i}`, status: 'completed' })),+ { runId: 'live-1', status: 'running', kind: 'evaluate', sceneId: 'scene-1' },+ ];+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-1', status: 'rendering', name: 'Test', runs: existing }]);+ await updateRun('cd-1', 'live-1', { status: 'completed', completedAt: '2026-05-29T12:00:00.000Z' });+ const saved = mockAtomicWrite.mock.calls[0][1];+ expect(saved[0].runs).toHaveLength(200);+ const patched = saved[0].runs.find((r) => r.runId === 'live-1');+ expect(patched).toBeTruthy();+ expect(patched.status).toBe('completed');+ });});