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
plan: mark CD/pipeline polish batch items shipped; add changelog entries
Adam Eivy3b7fafcf0f62
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a212eb3c4c..1e0b68d0d6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,10 @@## Changed+- LTX-2.3 video model dropdown now groups the legacy notapalindrome runtimes (`ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4`) under a `Legacy` `<optgroup>`, with the dgrauet `ltx23_dgrauet_*` runtimes surfaced as the active picks at the top of the list. `defaultMacos` deliberately stays on `ltx23_distilled_q4` because the dgrauet runtime requires an opt-in venv install — fresh installs need a model that works out of the box. Applies to both Video Gen and Creative Director dropdowns. New Video Gen FFLF mode also gets a one-line keyframe-pair guidance hint ("use keyframes that share scene geometry — same camera, same subject; unrelated images produce a visual cut") to prevent the "looks like two stills" complaint.+- Writers Room bible CRUD (characters / settings / objects, one file per work) now collapses onto a single `createBibleStore(...)` factory in `server/lib/storyBible.js` — each domain file shrinks to ~30 LOC of factory configuration. -281 LOC across the three domain files. Pipeline bible routes share the writers-room zod schemas under generic names (`characterBibleCreateSchema`, etc.) instead of the prior `z.record(z.string(), z.any())` loose-record validation; the canonical `sanitizeBibleList` in `storyBible.js` remains the single source-of-truth for shape enforcement on both sides. Steps 2a + 2b of the Writers Room ↔ Pipeline DRY unification.+- Pipeline stage components (`ProseStage`, `TextStagePanel`, `EpisodeVideoStage`) now share a `useAsyncAction(fn)` hook for the common "setLoading(true) → await → catch+toast → setLoading(false)" pattern. `StoryboardsStage` deliberately stays on its existing pattern because its `savingIdx`/`extractingFrom` flags are keyed loading states, not booleans. Step 4c of the Writers Room ↔ Pipeline DRY unification.+- Pipeline `POST /api/pipeline/series/:id/extract-bible` accepts a `parallel: true` flag that fans out the three bible kinds concurrently (~3× wall-clock speedup on HTTP-API providers like OpenAI / Anthropic / LM Studio HTTP). Default stays sequential so CLI-only providers (codex, claude-code, gemini-cli) — which serialize at the provider session anyway — aren't penalized.- Creative Director `GET /api/creative-director/:id` accepts a `?slim=1` query param that drops the unbounded `runs[]` history and the heavy treatment fields, returning only what a polling UI needs (`status`, `updatedAt`, per-scene `{ id, order, status }`, `finalVideoId`, `failureReason`). Pipeline EpisodeVideoStage's 4s poll now uses slim mode — keeps the UI responsive without pulling the entire render history on every tick.- Pipeline Storyboards stage gains "From TV script" + "From prose" auto-fill buttons. Once the upstream stage has output, one click runs the new shared `extractScenes()` LLM pass (sluglines parsed from the teleplay, or paragraph-grain beats lifted from the prose) and replaces `stages.storyboards.scenes[]` with the result. A two-click-arm replace guard surfaces a warning toast before clobbering hand-curated scenes. Backed by `POST /api/pipeline/issues/:id/stages/storyboards/extract-scenes` and the new `server/lib/sceneExtractor.js`, which both Pipeline AND the Writers Room evaluator's `script` analysis now route through — deleting ~25 LOC of duplicated SHAPERS.script logic and giving the Pipeline a one-click path from "TV script ready" to "all storyboards primed for image gen." Step 5 of the Writers Room ↔ Pipeline DRY unification. Side fix: the issue PATCH schema's `stages` z.union order was swapped so visual-stage payloads (`scenes` / `pages` / `cdProjectId` / `videoPath`) no longer silently strip on the way through — the union evaluated the text-only schema first, hiding the visual fields.@@ -28,3 +32,4 @@- Pipeline issues no longer get stuck in `status: 'running'` after a server restart mid auto-run. Boot now walks every issue and demotes any `running` to `needs-review` (the same terminal state a normal completion lands on) — the UI shows the issue as needing attention instead of spinning forever waiting for SSE that will never arrive.- Pipeline EpisodeVideoStage final-video render no longer breaks when the underlying mp4 is missing — both surfaces (Creative Director SegmentsTab + Pipeline EpisodeVideoStage) now route through a shared `ScenePreview` component with the onError-missing-media fallback + Retry + cache-bust pattern.- Render Queue UI now lists jobs in execution order (running first, then queue position ascending) instead of mixing a long-running job into the middle of newer queued batches. The route was sorting all jobs by `startedAt || queuedAt` DESC, which slotted an active job below a fresher batch.+- CoS agent dedup race in `spawnAgentForTask` — under sustained scheduler tick load, two parallel `task:ready` emissions for the same task id could both pass the dedup-has-check because `spawningTasks.delete(task.id)` ran BEFORE the agent was queued to the runner. A second spawn would slip through the window and produce a duplicate agent. The delete now lives inside a `try { spawnViaRunner|spawnDirectly } finally { spawningTasks.delete }` block so the guard outlives the spawn call. New behavioral race-repro test in `agentLifecycle.test.js` proves the contract.diff --git a/PLAN.md b/PLAN.mdindex dc2cfd616b..cc954908ea 100644--- a/PLAN.md+++ b/PLAN.md@@ -22,7 +22,7 @@ The pipeline now has multi-frame evaluation, auto-accept watchdog, cheap smoke f- **Stitch path change.** `server/services/creativeDirector/stitchRunner.js` after timeline render: strip per-clip audio (`-c:v copy -an`), then a second ffmpeg pass overlays the generated track. New project-level `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. PLAN today's `'per-clip'` stays the default so existing projects don't regress.- **UX.** `EpisodeVideoStage.jsx` toolbar gets an "Audio" dropdown beside aspectRatio/quality. "Generated" kicks off the audio gen as part of the stitch pipeline; "Uploaded" opens a file picker.- **Investigation needed first** — pick a generator. Suno has the cleanest UX (give it a vibe prompt + duration); MusicGen-MLX is local but needs sliding-window stitching to exceed 30s; AudioLDM2 is older. ~150 LOC for the stitcher change once the generator is picked; the bigger question is which model and how to prompt it from script-level arc metadata. Treat this as a new sub-brainstorm when we pick it up — not a same-PR fix.-- [ ] **Duplicate evaluator spawn dedup.** During the long E2E run, server logs showed `Task already being spawned, skipping duplicate` followed seconds later by a *second* agent spawning for the exact same task id. The CoS task lane logic ends up double-acquiring. Reproduce in a unit test against `taskSchedule` / `agentLifecycle` and fix the de-dup window (`agentLifecycle.js:114`).+- [x] **Duplicate evaluator spawn dedup** — shipped (2026-05-10). Root cause: `spawningTasks.delete(task.id)` ran immediately after `updateTask(in_progress)` succeeded but BEFORE the spawn call queued the agent to the runner; a concurrent `task:ready` re-emission could race past the dedup-has-check and produce a duplicate spawn. Fix wraps the spawn call in `try { spawnViaRunner|spawnDirectly } finally { spawningTasks.delete(task.id) }` (`server/services/agentLifecycle.js:536-547`). New behavioral repro + source-text regression guard in `agentLifecycle.test.js`. Full server pack green (3831 tests). Pre-existing wider issue (any throw between `spawningTasks.add` and the inner try-block also leaks the guard) noted as a separate item below.- [ ] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min (early) to 10–30 min (late) within one project — likely accumulated listeners + queue races. Profile after sustained use; the round-22 dedup work probably already helps; verify.### LTX-2.3 dgrauet runtime — wire native modes@@ -30,8 +30,8 @@ The pipeline now has multi-frame evaluation, auto-accept watchdog, cheap smoke fThe dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), audio-to-video, and native video Extend (see DONE.md 2026-05-06). Remaining gaps:- [ ] **Native FFLF deeper test on real keyframe pairs.** FFLF wiring is verified on synthetic ball-motion keyframes (commit `ef5d9081`). Validate with REAL pairs: take last frame of clip A + first frame of clip B from the same scene/camera, render an interpolation, confirm temporally-coherent transition. If it looks weak even on similar keyframes, file a follow-up to expose more pipeline knobs in the UI (cfg-scale, stg-scale, stage1-steps).-- [ ] **Add UI hint under FFLF mode.** Current advisory note says "Experimental — last frame is advisory" but doesn't guide users on *what makes a good keyframe pair*. Add: "Use keyframes that share scene geometry — same camera, same subject; the model interpolates between them. Random unrelated images produce a visual cut." Prevents the "looks like two stills" complaint that surfaced during testing. (`client/src/pages/VideoGen.jsx` ~line 917)-- [ ] **Once dgrauet is the default for everything we care about, deprecate notapalindrome models.** Mark `ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4` with `deprecated: true` in `server/lib/mediaModels.js` so the model dropdown groups them under a "Legacy" section. Eventually drop them and the `runtime: 'mlx_video'` dispatch entirely (~50 LOC removal in videoGen/local.js).+- [x] **Add UI hint under FFLF mode** — shipped (2026-05-10). `renderFramePanel` in `client/src/pages/VideoGen.jsx` gained a `hint` prop rendered as a subtle accent-coloured line below the existing experimental advisory ("Tip: use keyframes that share scene geometry — same camera, same subject…"). Visually distinct from the warning so the two categories of information don't blur.+- [x] **Deprecate notapalindrome models** — shipped (2026-05-10). `ltx2_unified`, `ltx23_unified`, `ltx23_distilled_q4` carry `deprecated: true` in both `server/lib/mediaModels.js` and the `data.sample/media-models.json` seed. VideoGen and CreativeDirector dropdowns render them under a `<optgroup label="Legacy">` below the active dgrauet models. `defaultMacos` deliberately stays on `ltx23_distilled_q4` and `getDefaultVideoModelId` does NOT auto-roll forward — the dgrauet runtime requires an opt-in venv install (`INSTALL_LTX2=1 bash scripts/setup-image-video.sh`), so fresh installs need a model that works out of the box. Comment in `mediaModels.js#getDefaultVideoModelId` documents this. Eventual full removal of `runtime: 'mlx_video'` dispatch (~50 LOC in `videoGen/local.js`) deferred until dgrauet is the install-default.### Other backlog@@ -131,15 +131,15 @@ Items below are ordered by dependency: each later item builds on earlier ones. L- [x] **1b. Mirror `composeStyledPrompt` to `server/lib/`** — shipped. `server/lib/composeStyledPrompt.js` is the verbatim mirror of `client/src/lib/composeStyledPrompt.js`. World Builder's `compileBatchPrompts` now uses it for both the variation and composite-sheet code paths. Side effect: the rendered prompts switch separator from `, ` to `. ` (the composeStyledPrompt convention shared with `scenePrompt`); semantically identical for diffusion models, two pinned test assertions updated. 6 unit tests.- [x] **1. Shared scene-prompt composer** — shipped. Canonical `server/lib/scenePrompt.js` with mirror `client/src/lib/scenePrompt.js` (Vite fs.allow doesn't reach across to `server/lib`, so we follow the project's existing manual-mirror convention). `writersRoom/settings.js#normalizeSlugline` and `sceneCardHelpers.js` both re-export from the canonical home. Pipeline `composeVisualPrompt` now routes through `buildScenePrompt` so series name + style + universal cast (series.characters[]) + scene visual all flow through the same algorithm with PROMPT_MAX-budgeted truncation. Storyboards stage UI + route schema accept an optional per-scene `slugline` so the eventual settings-bible match (item 2) is plumbed end-to-end. 18 new unit tests in `server/lib/scenePrompt.test.js`; existing 119-test pipeline + writers-room pack stays green.-- [ ] **2a. `bibleStore({ kind, idPrefix, idRegex, fileName, ... })` factory.** After items 1+2, the three writers-room files (`characters.js`/`settings.js`/`objects.js`) still share ~70% structurally — `loadFile`/`saveFile`/`listX`/`getX`/`createX`/`updateX`/`deleteX`/`mergeExtractedX` are byte-similar except for filename + idRegex + the setting-specific "name OR slugline" identifier rule + the post-update "blank-both → reject" guard. Extract into a `createBibleStore({ kind, idPrefix, idRegex, fileName, listKey, dedupKey, validateAfter })` factory in `server/lib/storyBible.js`. Each domain file shrinks to ~15 lines: `export const { list, get, create, update, delete, mergeExtracted } = createBibleStore({...})`. Setting's slugline-aware dedup goes in via the `dedupKey` callback. Estimated -250 LOC.-- [ ] **2b. Share zod bible-entry schemas between writers-room + pipeline routes.** `server/lib/validation.js` already defines `writersRoomCharacterCreateSchema` / `writersRoomSettingCreateSchema` / `writersRoomObjectCreateSchema` mirroring `BIBLE_LIMITS` shape. Pipeline `routes/pipeline.js#bibleEntrySchema = z.record(z.string(), z.any())` is strictly looser — accepts arbitrary keys, no length caps. Re-export the writers-room schemas under generic names (`characterBibleSchema` / `settingBibleSchema` / `objectBibleSchema`) and have pipeline `routes/pipeline.js` extend them with its own back-compat `description` + `imageRefs` overrides.+- [x] **2a. `createBibleStore({...})` factory** — shipped (2026-05-10). Factory lives in `server/lib/storyBible.js` and derives `fileName`/`listKey`/`idSuffix` regex internally from `kind`; callers supply `idPrefix` + `dedupKey` + `primaryFields` + `editableFields` + `requireOnCreate` + optional `validateAfterUpdate` + error strings. Each writers-room domain file collapses to ~30 LOC. -281 LOC across the three files; 12 new factory tests in `storyBible.test.js`. Settings' slugline-aware dedup and "blank-both → reject" guard go through the `dedupKey` callback and `validateAfterUpdate` respectively.+- [x] **2b. Share zod bible-entry schemas between writers-room + pipeline routes** — shipped (2026-05-10). `server/lib/validation.js` re-exports `characterBibleCreateSchema` / `settingBibleCreateSchema` / `objectBibleCreateSchema` under kind-neutral names (the writers-room name `writersRoomCharacterCreateSchema` etc. stay for the existing route's import). Pipeline `routes/pipeline.js` extends those with its own back-compat fields (`description` legacy alias, `imageRefs`, optional `id`) plus `.passthrough()` so sanitizer-emitted fields (evidence/firstAppearance/source/timestamps) round-trip without strict-mode rejection. The loose `bibleEntrySchema = z.record(z.string(), z.any())` is gone. `settingBibleCreateSchema` is the un-refined `ZodObject` (the refined `writersRoomSettingCreateSchema` is the route-layer enforcer for the WR endpoint only); the "name OR slugline" rule is enforced at the sanitizer/store layer (`storyBible.js#sanitizeSetting` drops blank-both entries) — single source of truth.- [x] **2. Unified story-bible schema** — shipped. `server/lib/storyBible.js` owns the canonical `Character` / `Setting` / `Object` shapes + `sanitizeBibleList` + `mergeExtractedBible` (with per-kind key normalizers — slugline collapsing for settings, name-key for characters/objects). Writers-room `characters.js` / `settings.js` / `objects.js` collapsed onto the shared helpers (-299 LOC of duplicated merge/sanitize logic). Pipeline `series.characters` migrates to the canonical shape via back-compat read (legacy `description` field auto-promotes to `physicalDescription`); `series.settings[]` and `series.objects[]` added with the same sanitizers. `composeVisualPrompt` now activates the slugline-matching plumbed in item 1 — pipeline storyboard scenes that reuse a setting slugline get the canonical setting baseline (description + palette + recurring details) prepended automatically. 30 new tests in `server/lib/storyBible.test.js`; full server pack 3716/3716 green.- [x] **3. Shared staged-LLM runner** — shipped. `server/lib/stageRunner.js` exposes `runStagedLLM(stageName, variables, { providerOverride, modelOverride, returnsJson, source })` plus `resolveModel` (tier-aware) and `extractJson` (lenient code-fence stripper). Both `writersRoom/evaluator.js#runAnalysis` and `pipeline/textStages.js#generateStage` route through it. Writers-room evaluator went 589 → 435 LOC; the bespoke `callApiProvider` + `callCliProvider` + `buildCliInvocation` (~150 LOC of CLI-spawn drift) deleted. Pipeline text stages went 180 → 118 LOC. Writers-room calls now persist transcripts to `data/runs/<runId>/` (which the bespoke fetch path was silently skipping) and pick up tier-name model resolution for free. Behavioral note: per-stage temperature override (format=0.2, others=0.4) was dropped — the toolkit's `executeApiRun` doesn't expose a temp parameter; if format-stage drift surfaces, plumb temperature through the toolkit. 18 new stageRunner tests; obsolete `evaluator.test.js` (only `buildCliInvocation` coverage, now redundant with `runner.test.js:48`) deleted. Server pack 3733/3733 green.- [x] **4a. `extractAndMergeIntoSeries(seriesId, { kinds, corpus, ... })`** — shipped. The bible extract → merge → patch orchestration now lives in `server/services/pipeline/series.js`; the route shrinks to a `seriesSvc.extractAndMergeIntoSeries(series.id, {...})` call and `mergeExtractedBible` / `extractBible` are no longer route-layer imports. Mirrors how writers-room exposes `mergeExtractedCharacters(workId, extracted)`. Forwards the `parallel` flag from 4b through to the service so the speedup stays available. Pure refactor — all 23 pipeline route tests green without modification.- [x] **4b. Opt-in `parallel: true` mode for `/extract-bible`** — shipped. `extractBibleSchema` accepts a `parallel: boolean`; when true the three kinds fan out via `Promise.all` (~3× wall-clock speedup on HTTP-API providers). Default stays sequential — safe for CLI providers that serialize at the provider session anyway. Merge always runs after all extractions complete; `series.<field>` is read once at the top of the route so the merge baseline doesn't race. 2 new route tests: one drives the parallel guarantee (every start fires before the first finish), one drives the sequential guarantee (events alternate start/finish/start/finish/...).-- [ ] **4c. `client/src/hooks/useAsyncAction.js`** — collapse the `setLoading(true) → await ... .catch(toast) → setLoading(false)` pattern that now duplicates across `ProseStage.jsx`, `TextStagePanel.jsx#handleGenerate`, `StoryboardsStage.jsx#handleGenerate`, `EpisodeVideoStage.jsx#handle*`. Returns `[run, running]`. Cross-cutting client cleanup, not WR↔Pipeline-specific — schedule with the next general DRY pass.+- [x] **4c. `client/src/hooks/useAsyncAction.js`** — shipped (2026-05-10). Hook returns `[run, running]`. Migrated `ProseStage.jsx#handleExtract`, `TextStagePanel.jsx#handleSave` + `#handleGenerate` (the latter OR'd with externally-synced `serverGenerating` for auto-runs), and `EpisodeVideoStage.jsx#submit`. `StoryboardsStage.jsx` deliberately stays on its existing pattern — `savingIdx` and `extractingFrom` are keyed loading states, not booleans; a keyed variant would be a bigger abstraction. Post-unmount setState guard with `mountedRef` deferred to a future general DRY pass (YAGNI for the current stable parent components).- [x] **4. Shared bible-extraction service** — shipped. `server/lib/bibleExtractor.js#extractBible({ kind, corpus, existing, context, providerOverride, source })` runs the staged LLM, pulls the `{ characters | settings | objects }` envelope, and routes through the canonical `sanitizeBibleList`. Returns the sanitized list + run metadata; the caller owns persistence (writers-room → `mergeExtractedX(workId, ...)`, pipeline → `mergeExtractedBible(series.<field>, extracted, kind)`) — splitting extraction from merge avoids the double-merge footgun. Writers-room evaluator's three bible SHAPERS (~75 LOC of duplicated field-trim) deleted; analysis path now goes `runAnalysis → extractBible → mergeExtractedX`. New pipeline route `POST /api/pipeline/series/:id/extract-bible` accepts `{ kinds, issueId, corpus, providerOverride }` and merges results into the series. New "Extract bibles" button on the Pipeline ProseStage that calls it. 12 lib tests + 4 route tests; full server pack 3746/3746 green.- [x] **5. Shared scene-list extractor** — shipped. `server/lib/sceneExtractor.js#extractScenes({ source, sourceKind, characters, settings, objects, work, series, issue, providerOverride, tag })` mirrors the bibleExtractor.js pattern: caller owns persistence, extractor owns the LLM call + sanitization. Two source modes: `prose` routes through the existing `writers-room-script` prompt; `tvScript` routes through the new `pipeline-extract-scenes` prompt (parses already-present sluglines instead of inventing them). Shared `sanitizeSceneList` is the single source of truth for the canonical scene shape (`{ id, heading, slugline, summary, characters, action, dialogue, visualPrompt, sourceSegmentIds }`) — defensive, every field has a typed fallback so a partial LLM response never crashes downstream. Writers Room evaluator's `script` kind now delegates here (~25 LOC of duplicated SHAPERS.script logic deleted); Pipeline storyboards stage gains a "From TV script" + "From prose" button pair via `POST /api/pipeline/issues/:id/stages/storyboards/extract-scenes` (with a 409 + two-click-arm replace-confirm guard so an extraction can't silently obliterate hand-curated scenes). 14 unit tests + 4 route tests; full server pack 3765/3765 green. **Side fix:** `issuePatchSchema.stages` z.union order swapped so PATCH /issues/:id with a visual stage payload (`scenes` / `pages` / `cdProjectId` / `videoPath`) no longer silently strips those fields — the union picked the strict text-only schema first, hiding the visual fields.