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
docs: replan — archive 7 shipped items, restructure PLAN.md
[._.]/ Adam Eivy5e4998668334
diff --git a/DONE.md b/DONE.mdindex 167893481d..b10b665943 100644--- a/DONE.md+++ b/DONE.md@@ -8,6 +8,13 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./## 2026-05+- **Sharing — auto-unsubscribe on local record delete.** `recordEvents.js` now hooks `deleteSeries` / `deleteUniverse` so orphaned `data/sharing/subscriptions.json` entries clean up automatically instead of logging errors on the next re-export attempt.+- **Pipeline — `spawningTasks` lifecycle.** Widened try/finally around `spawnAgentForTask` (`server/services/agentLifecycle.js`) so a throw in any async setup step releases the per-task spawn lock instead of stranding it forever.+- **Pipeline — `creativeDirectorPrompts.test.js` imageStrength assertions.** Test now matches the updated prompt template wording; full suite passes.+- **Importer — Create Suite reverse-engineering page.** `/importer` analyzes a finished story / novel / screenplay / comic script and produces universe canon + series arc + prose-seeded issues; three new stage prompts with Mustache content-type branching; case-insensitive find-or-create; locked-arc gating.+- **Universe-as-Canon Phase B.4 schema teardown.** Removed `series.{characters,settings,objects}` from sanitizer + Zod schemas; deleted `extractAndMergeIntoSeries` / `refineCharacterDescription` / `nounRefine.js` / `purgeImageRefFromAllSeries`; routes `POST /pipeline/series/:id/extract-bible` + `/characters/:entryId/refine` removed; `seriesCanon.js` simplified to universe-or-empty.+- **Universe Canon UX follow-ups.** Per-series filter dropdown on Universe Canon page (`?series=<id>` URL param); "Appears in" list sorted by `issueCount`; per-series `stylePromptOverride` wired through `applyWorldStyle` + NounsStage previews.+- **Sharing v1.4 — collection-aware universe shares.** `mediaCollections.universeId` links a collection to its parent universe; exporter bundles the collection + items + assets + media-job records; importer find-or-creates the local collection and unions items; item add/remove emits `recordEvents` on the linked universe so subscriptions auto-re-export.- **Sharing — route-level tests for `server/routes/sharing.js`.** New `server/routes/sharing.test.js` covers bucket CRUD, export (kinds + missing-payload refinement), inbox actions, subscriptions, activity, and error mapping (28 tests). Locks the HTTP/JSON contract (Zod rejection + 201 vs 200 + service-error code passthrough) that integration.test.js + subscriptions.test.js previously bypassed by exercising the service layer directly.- **Sharing — manifest archive pruning.** Long-lived sharing buckets no longer accumulate thousands of one-shot manifest JSONs; owned manifests over the cap are archived (peer/subscription manifests exempt).- **Sharing — display-name & bio settings tab.** Source-attribution fields now also editable under `/settings/sharing`.diff --git a/PLAN.md b/PLAN.mdindex 875a3aed3d..b278a5ca8e 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,178 +6,148 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]## Next Up-### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.4 shipped+1. **Universe-as-Canon Phase 2 UI** — fold canon into UniverseBuilder, retire the standalone Canon page + route, retire `universe.categories` on the schema. (Backbone shipped; UI still on the two-page split.)+2. **Step-by-step approval/lock UX across Universe → Series → Arc → Seasons → Episodes.** Iteration 1 shipped a single arc-level lock; extend to per-season + per-field locks, lock the bulk runners, surface stage-progress strip, enforce locks server-side before LLM invocations.+3. **Sharing v2 contracts** — per-peer subscription filenames (`sub-<kind>-<recordId>-<senderInstanceId>.json`), tombstone-based item removals, "🔄 live" badge on inbox subscription rows.+4. **Pipeline continuity gaps** — plumb character physicalDescription/personality/background into idea-stage prompt; plumb setting `palette`/`era`/`weather`/`recurringDetails` into visual stages; add `worldEntitiesSummary` to text stages; add a dedicated `voice` / speech-pattern field to the bible schema.+5. **AI Toolkit hardening** — toolkit-side Zod validation on POST/PUT providers; preserve non-sentinel codex `models[]` entries during migration; try/catch around `loadProviders` JSON.parse with `.corrupt` fallback; end-to-end test for `createProvider` field parity.-V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. V1.2: schema versioning — `SHARING_SCHEMA_VERSION` stamped on every manifest + bucket.json, `producedByVersion` (PortOS app version) on every manifest, importer refuses future-version manifests with a clear toast + cursor-mark, bucket cards warn when remote schema > local. V1.3: subscription model for series + universe — toggle on/off in ShareToButton with real state indicators, persistent (bucket, record) tuples in `data/sharing/subscriptions.json`, deterministic-filename manifests that overwrite on re-export, auto-re-export on edit via `recordEvents` (debounced 3s), `unlink` → `handleUnshare` flow that propagates "stop sharing" to recipients without reverting their local copies, content-aware cursor (`processedById` map). V1.4: collection-aware universe shares — `mediaCollections.universeId` field links a collection to its parent universe, exporter bundles the collection (record + items + assets + media-job records) when a universe is shared, importer find-or-creates the local collection and unions the items in, item-add/remove emits `recordEvents` on the linked universe so subscriptions auto-re-export when peer adds new images. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:--- [ ] **Auto-unsubscribe on local record delete.** Today if the user deletes a subscribed series/universe, the subscription in `data/sharing/subscriptions.json` becomes an orphan — next re-export attempt logs an error but the entry persists. Hook `deleteSeries` / `deleteUniverse` to call `unsubscribe()` for every subscription where `recordId === id`. Surface the unshare in the UI so the user sees "Removed from N bucket(s)" alongside the deletion toast.-- [ ] **Inbox UI: visually mark subscription items.** New inbox entries already carry `subscription: { recordKind, recordId }` when applicable, but the Sharing page renders them identically to one-shot manifest items. Add a small "🔄 live" badge to subscription rows so the user sees "this is the latest snapshot of a live share" vs "this is a one-time snapshot."-- [ ] **Per-peer subscription filenames for bidirectional collaboration.** Today both peers writing to the same subscription clobber each other's manifest because the filename is `sub-<kind>-<recordId>.json`. Change to `sub-<kind>-<recordId>-<senderInstanceId>.json` so each peer owns their own file; the recipient's importer merges every peer's payload into local state. Without this, peers receive each other's items via the import path but cannot push their own contributions back unless only one peer is the "owner."-- [ ] **Item-removal semantics across peers.** Collection items are unioned via `addItem` (additive only — `ERR_DUPLICATE` swallowed). When a peer removes an item from their local collection their re-exported manifest no longer lists it; for single-owner the recipient's collection still contains the item because no one tells it to drop. Decide whether to model removals as tombstones in the manifest, or treat the local collection as union-of-all-peer-sets. Probably tombstones — simpler mental model.-- [ ] **Same collection-export pattern for pipeline series with auto-collections.** Series renders that get auto-filed into a per-series collection (if/when that exists) should also flow through `manifest.collection`. Today only the universe → collection link is bundled.-- [ ] **Content-addressed asset dedup.** Today asset copies skip-if-filename-exists. Hash-based dedup would let multiple manifests share the same blob even when filenames differ.-- [ ] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Separate ticket from buckets — same-network peers on Tailscale should be able to sync these categories without going through a bucket.-- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; chain[] would preserve full attribution. Defer until users ask.--### Create Suite — Importer page (v1 shipped 2026-05-16)--V1 shipped — `/importer` reverse-engineers a finished story / novel / screenplay / comic script into universe canon + series arc + prose-seeded issues. See `~/.claude/plans/i-want-to-add-vivid-bear.md` for the full design and `.changelog/NEXT.md` for the shipped notes.--- [x] Page scaffold: `client/src/pages/Importer.jsx` (intake + review phases), API client `client/src/services/apiImporter.js`, lazy `<Route path="importer">` in `App.jsx`, sidebar entry in `Layout.jsx`, `nav.create.importer` in `navManifest.js`.-- [x] Server orchestrator `server/services/importer.js` — `analyzeImport` (no persistence) + `commitImport` (universe canon merge + series arc/seasons + issue creation with `stages.prose.output` seeded).-- [x] Server routes `server/routes/importer.js` + Zod schemas `importerAnalyzeSchema` / `importerCommitSchema` in `server/lib/validation.js`.-- [x] Three new stage prompts: `importer-canon-extract.md`, `importer-arc-extract.md`, `importer-issue-proposal.md` (in `data.sample/prompts/stages/`); content-type branching inside via Mustache section guards (`{{#isShortStory}}…{{/isShortStory}}`) — PortOS's template engine is Mustache-only, not Liquid. The orchestrator passes per-type booleans (`isShortStory`, `isNovel`, `isScreenplay`, `isComicScript`) alongside the contentType string. Migration `015-importer-stage-prompts.js` seeds them into existing installs.-- [x] Find-or-create logic: case-insensitive name match; series match scoped to universe; respect `series.locked.arc` (throw `ERR_LOCKED`).-- [x] Tests in `server/services/importer.test.js` — find-or-create scoping, oversize rejection, locked-arc gating, commit happy/duplicate paths, route validation (via Zod).--**Follow-ups (deferred from v1):**--- [ ] **Chunked extraction for source > 200K chars.** v1 hard-rejects with `ERR_VALIDATION`. Once a real import hits the cap, lift the limit and route through a per-chunk canon extraction + rolling synopsis for arc-extract (issue-proposal still takes the full source). Investigation needed first to pick a chunk-overlap / merge strategy that doesn't double-extract recurring characters. Touch site: `server/services/importer.js#analyzeImport` (the `source.length > IMPORTER_SOURCE_CHAR_LIMIT` guard).-- [ ] **Auto-detect content type.** Today the user picks via radio. A small `importer-classify.md` stage could run first and pre-select the radio (still user-editable). Skipped in v1 because the radio is one click.-- [ ] **Re-running an import to *replace* (not append) an existing series.** Today the second pass extends. A destructive-confirm UX with a "Replace all" toggle would let the user blow away the previous import without manually deleting the series first. Hold until a user actually asks.-- [ ] **Importer review UI: extract `<CanonCard>` once it lands.** Today `client/src/pages/Importer.jsx#CanonReviewSection` renders an inline minimal card. When the Phase 2 "Extract shared CanonCard" item below (under Universe-as-Canon refactor) ships, swap the inline card for the shared component so locked / source-badge / tag-chip affordances appear here automatically.-- [ ] **[PERF] `updateAt` re-render cost in `Importer.jsx`.** The `updateAt` helper (search the file for the function name — line drifts with edits) rebuilds the full list array on every keystroke, causing `IssuesReviewSection`/`ArcReviewSection` to re-render all sibling cards simultaneously — with up to 50 issues each carrying multi-paragraph synopses + 500K-char `proseExcerpt` displays, this can feel sluggish. Fix by either (a) wrapping issue/arc cards in `React.memo` so unchanged entries bail out, or (b) moving inline edits into per-card local state that lifts on blur. Deferred from v1 PR #253 — performance not correctness.-- [ ] **Centralise `ARC_ROLES` source-of-truth, drop client-side fallback.** `IMPORTER_ARC_ROLES_FALLBACK` in `client/src/services/apiImporter.js:14` hard-codes the arc-role enum. The server now exposes `arcRoles` via `/importer/config` + the analyze response, but the fallback will silently drift from `server/lib/storyArc.js#ARC_ROLES` if a role is added/removed and the client isn't redeployed in lockstep. The list also lives in `data.sample/prompts/stages/importer-issue-proposal.md` (hand-maintained). Pick one: (a) drop the client fallback to `[]` + show a "loading roles…" placeholder until config fetch lands, or (b) generate the prompt enum + client fallback from `storyArc.js` at build time. Deferred from PR #253 — long-term maintainability, not a current bug.-- [ ] **Expose `ARC_SHAPE_IDS` via `/importer/config` (same drift hazard as arc-roles).** `client/src/pages/Importer.jsx` arc-shape `<select>` is populated from `STORY_SHAPES` (client-side `components/pipeline/StoryShapes`), but the server's allowed enum is `ARC_SHAPE_IDS` from `server/lib/storyArc.js` (used by `importerArcShape` + `buildArcPreview`). If `STORY_SHAPES` ever diverges, the user could pick a UI-only shape that the server rejects, or miss a valid shape. Fold this into the same fix as the arc-roles centralisation above — the `/importer/config` payload should expose both. Deferred from PR #253.-- [ ] **Importer screenplay prompt — `targetIssueCount` default vs user-requested clarity.** `data.sample/prompts/stages/importer-issue-proposal.md:36` reads "If the screenplay contains ACT ONE/TWO/THREE breaks AND `targetIssueCount > 1`, split on act breaks; otherwise return one issue." But the orchestrator defaults `targetIssueCount` to 1 for screenplay (via `DEFAULT_TARGET_ISSUE_COUNT_HINT`) and only treats it as user-requested when the user explicitly passes it. The current prompt phrasing makes a 1-issue default look like a deliberate user request to NOT split, when in fact it's just the absence of intent. Either (a) pass a separate `isUserRequestedCount` flag into the template and gate the split logic on that, or (b) reword the prompt to distinguish "the user set targetIssueCount=N" from "default is 1". Deferred from PR #253 — needs prompt + orchestrator co-change.-- [ ] **Importer partial-commit retry — guard against arc re-apply.** When `commitImport` rolls back issues mid-loop (throws `ERR_PARTIAL_COMMIT_ISSUES`), the universe + series ARE updated (intentional). A naive client retry resubmits the same payload; canon + seasons merge idempotently, but the `arc` field is unconditionally re-applied via `updateSeries({ arc: sanitizedArc })` — overwriting any edits the user made server-side between the failed attempt and the retry. Touch site: `server/services/importer.js#commitImport` around line 525. Possible fixes: (a) on retry, return a tagged response from the route so the client can opt to skip arc; (b) extend `ERR_PARTIAL_COMMIT_ISSUES` so the route reply tells the client "universe + series already updated — retry can safely skip those fields"; (c) version the arc and reject the second write if `series.arc.updatedAt > original.updatedAt`. Deferred from PR #253 — needs UX + API contract decision.-- [ ] **Importer Review UI: in-place `proseExcerpt` edit affordance.** The Review phase renders the LLM-picked excerpt as a read-only char-count line. If the excerpt is wrong (overlaps a neighbor's, is empty/whitespace, includes a spurious header), the only recovery today is to abandon the flow, edit the source, and re-run Analyze — burning three heavy-tier LLM calls. Add a collapsed-by-default textarea (rendering 500K chars uncollapsed is itself a perf concern, hence collapsed) per issue card so the user can trim/correct without restarting. Touch site: `IssuesReviewSection` in `client/src/pages/Importer.jsx` (search the file for the function name — line drifts). Deferred from PR #253 — non-trivial UI + needs a "is this textarea actually editing the right thing" UX pass with the user.--### Universe-as-Canon refactor — Phase B.4 cleanup + follow-ups--The world model is now a Marvel-style **universe** carrying canonical entities (characters, places, objects) that multiple series can share for crossovers + cameos. Shipped 2026-05-14 across Phase 0 (world→universe rename), Phase A (canon arrays + Universe Canon page + cast-wide differentiate + image-delete purge sync), Phase B (render paths read via `getSeriesCanon`), Phase B.2 (Nouns page reads/writes universe canon), Phase B.3a (legacy series-side canon helpers redirect to universe when linked), Phase B.3b (Nouns page drops the orphan series fallback), and the "Appears in" cross-reference footer on every Canon card. Migration scripts: `server/scripts/migrateAll.js` (chains `migrateWorldToUniverse.js` + `migrateSeriesCanon.js`).--**Phase B.4 — schema teardown (hygiene, no functional gap).** Shipped 2026-05-16 — `series.{characters,settings,objects}` are gone from sanitizer + Zod schemas; `extractAndMergeIntoSeries` / `refineCharacterDescription` (and `nounRefine.js`) / `purgeImageRefFromAllSeries` deleted; routes `POST /pipeline/series/:id/extract-bible` + `POST /pipeline/series/:id/characters/:entryId/refine` removed; Writers Room `promoteWorkToPipeline` mints a universe per work and seeds canon there; `seriesCanon.js` simplified to universe-or-empty (`pickAllOrNothing` + `resolveSeriesCanonSync` removed); voice + dialogue extraction in `audio.js` rebased onto canon-shaped params; storyboard `extract-scenes` route reads canon via `getSeriesCanon`; post-prose extraction (`textStages.js`) calls `extractCanonFromProse(universeId)`. Test fixtures across `series.test.js`, `pipeline.test.js`, `promoteToPipeline.test.js`, `sharing/integration.test.js` updated to seed canon on a linked universe. See NEXT.md.--**Universe-Canon UX follow-ups.** Shipped 2026-05-16 — per-series filter dropdown on Universe Canon page (`?series=<id>` URL param), "Appears in" list sorted by `issueCount` desc, per-series `stylePromptOverride` field wired through `applyWorldStyle` + NounsStage client previews. See NEXT.md.--**Settings → Places kind rename (Phase 0b — deferred during the Universe rename).**--- [ ] Rename `BIBLE_KIND.SETTING` → `BIBLE_KIND.PLACE` and `BIBLE_FIELD[SETTING]: 'settings'` → `'places'`. Touches ~20 files: data (`series.places[]` / `universe.places[]`), sanitizer + Zod schemas, the `writers-room-settings.md` prompt (already renamed file; prompt body still refers to "settings"), `matchSettingsInText` → `matchPlacesInText`, `existingSettingsJson` LLM template var, the `writersRoom/settings.js` bible-handler module + its per-work data files, NounsStage's `KIND.label === 'Settings'`. Stick the rename to bible context — app settings (`services/settings.js`, settings drawer/UI, `imageGen.settings`, `pipeline.settings`) stays as "settings".--**Universe-as-Canon Phase 2 — unified Builder UI + categories retirement.**--The server-side lock + provenance + backfill foundation shipped 2026-05-14 (see NEXT.md). The UI still shows the legacy two-page split (Builder for categories/composites, separate Canon page for characters/settings/objects). Follow-up to land the user-visible piece:--- [ ] **Extract shared CanonCard.** Pull `CanonCard` + `KindSection` out of `client/src/pages/UniverseCanon.jsx` into `client/src/components/universe/CanonCard.jsx`. Add a lock-toggle icon (wired to the new `PATCH /api/universe-builder/:id/canon/:kind/:entryId/lock` route), a "from series: <name>" provenance badge when `sourceSeriesId` is set, and tag chips. Disable Refine + Render buttons when locked; show "Unlock to edit" affordance.-- [ ] **Fold canon into UniverseBuilder.jsx.** Replace the existing categories grid with three kind-sections (Characters / Settings / Objects) rendered from `universe.characters[]` / `settings[]` / `objects[]` using the shared `CanonCard`. Each section gets a "+ Add" inline modal (calls `PATCH /:id` with the new entry spliced into the kind array) + tag filter chip row that filters by `entry.tags.includes(activeTag)`. Move the "Extract from prose" button into the page header. Keep composite sheets as their own section unchanged.-- [ ] **Retire the standalone Canon page + route.** Replace `client/src/pages/UniverseCanon.jsx` with a `<Navigate to={`/world-builder/${id}#canon-characters`}>` (or delete + drop the route in `App.jsx`). Update `server/lib/navManifest.js` to drop the `nav.world-builder.canon` entry (or repoint to the Builder anchor); confirm `Layout.jsx` sidebar matches. Update `server/lib/navManifest.test.js` + `server/routes/palette.test.js`.-- [ ] **Retire `universe.categories` on the schema.** After the UI no longer reads it: drop `categories` from `sanitizeTemplate`, the route Zod schemas (`createSchema`, `patchSchema`, `expandSchema`, `refinePromptsSchema`, `selectionSchema`), the expand prompt template, `universeBuilderRefine.js`'s `mergeCategoriesWithLocks`, the `compilePrompts` `'variations'`/`'all'` branches (replaced by per-kind canon rendering), and `WORLD_CATEGORIES` + `VARIATIONS_PER_CATEGORY_MAX` + related exports in `universeBuilder.js`. The backfill helper stays as a one-time data-migration utility (move it to `server/scripts/` if/when the in-memory backfill is no longer needed).-- [ ] **Universe expand LLM contract enrichment.** Today expand emits `categories[key].variations[]` which the backfill converts to canon. Future enhancement: ask the LLM directly for `characters[]` / `settings[]` / `objects[]` with rich narrative metadata (role/personality/background for characters, slugline/era/palette for settings) alongside the visual `prompt` so the initial universe ships with usable canon depth instead of name-only stubs. Update `universeBuilderExpand.js`'s LLM prompt + the expand response normalizer. Composite sheets stay unchanged.--**Universe-Canon image-anchor follow-up (bigger).**--- [ ] Use rendered reference images as image-to-image anchors in downstream comic-page renders for models that support it. Codex can't accept image references; for SDXL / Flux pipelines, the per-character rendered ref could anchor every panel render. Touch: `composeComicPagePrompt` + the image-gen dispatcher. Related: existing PLAN item "Solidify characters before visual render" below (under Pipeline continuity gaps) — the universe-canon work already provides the storage; the "solidify" pass is the LLM step that merges accumulated evidence into one canonical description, and the new "AI: differentiate cast" button is its sibling (push apart vs. distill).--### Pipeline continuity gaps — deferred from arc-planning rollout--Captured 2026-05-13 while landing layer-1 (prior episodes in season prompt), layer-2 (post-episode-generate extraction), prose-extraction, verify episode-synopsis context, and character descriptions in visual composers. These are the remaining audit gaps from `pipeline/arcPlanner.js` + `pipeline/visualStages.js` + `pipeline/textStages.js`:--- [ ] **Idea-stage character context.** `pipeline-idea-expansion` template (called from `textStages.js:92`) sees only character `name` in `series.characters`, not `physicalDescription` / `personality` / `background`. Idea-stage LLM has no anchor when expanding a prompt that names existing characters — it can invent contradictory traits. Trim long fields, send the full character shape (matching the prose stage's context shape).-- [ ] **Setting palette/era/weather plumbed to visual stages.** `storyBible.js` setting shape carries `palette`, `era`, `weather`, `recurringDetails`, but `composeVisualPrompt` / `composeComicPagePrompt` only consult `description`. The fields exist for image renderers — wire `matchSceneSetting`'s match through into a "Setting: <era> <palette> <recurring>" prefix on the rendered prompt.-- [ ] **World-entity name validation in text stages.** Arc-verify checks world drift (factions/characters/locations the arc names that don't exist in the World Builder world), but per-issue text stages (idea → prose → script) don't reference world entities at all. New world entities introduced in volumes 2/3 of a series aren't surfaced to the prose LLM. Add a `worldEntitiesSummary` prompt var to the prose stage, similar to how arc-overview gets `worldCategoriesText`.-- [ ] **Character voice / speech-pattern field.** Current character shape has `personality` + `background` but no dedicated `voice` / `speech patterns` field. Prose and script generation can't carry voice consistency across issues without an authored anchor. Either add a `voice` field to the bible schema (and bibleExtractor stage prompt) or document that voice should land in `personality`.-- [ ] **Extraction after comicScript / teleplay stages.** Layer-2 extraction now runs after prose. Scripts derive FROM prose so most new characters should already be in the bible, but minor characters introduced only at script time (named extras, throwaway villains) still slip through. Decide whether to also run extraction post-script or accept the gap.-- [ ] **Solidify character descriptions before visual render.** User asked: as the series progresses, characters accumulate descriptions across multiple extractions but may still have gaps. Add a "Solidify characters" action in the bible sidebar that runs an LLM pass synthesizing one canonical `physicalDescription` per character from all accumulated `firstAppearance` + `evidence` + existing text. Useful before kicking off the visual render passes for an issue.-- [ ] **Resolve-issues inherits verify gaps.** Verify and resolve share `buildVerifyContext` so the new episode-synopsis context is already wired into both. But double-check the resolve LLM prompt instructs it to USE episode synopses when patching the arc — otherwise it'll just rewrite season-level synopses and leave per-episode contradictions intact.--- [ ] **Step-by-step approval UX pass across Universe + Series pipeline.** Iteration 1 shipped a single arc-level lock (`series.locked.arc`) on the Arc Canvas with an inline confirmation row on Regenerate. The broader UX pass should extend approval/locking through every stage so the workflow reads as a guided wizard:- - **Per-season locks** (`series.locked.seasons[<id>] = true`). Build the prompt context with locked seasons rendered as `[LOCKED]` constraints (mirror `universeBuilder.LOCKABLE_FIELD_LABELS`); post-merge by `id` match — preserve the locked existing season and let the LLM regenerate the unlocked ones.- - **Per-field arc locks** (`arc.logline`, `arc.summary`, `arc.protagonistArc`, `arc.themes`, `arc.shape`). Match the Universe builder's per-field LockButton pattern in `ArcCanvas.jsx#ArcContent`.- - **Lock the volume beat-sheet bulk runner** (`POST /series/:id/seasons/:seasonId/generate-beats`) when its season is locked, and the per-issue stage generators (`POST /issues/:id/stages/:stageId/generate`) when the issue is approved.- - **Approval as a first-class status.** Today `arc.status`/`season.status` carry `draft|verified|in-production|complete`. Wire "Approve this stage" buttons that set status + lock atomically, then the next regenerate-style action sees the approval as a refusal-to-overwrite signal everywhere downstream.- - **Visible "next step" guidance.** A sticky stage-progress strip showing Universe → Series → Arc → Seasons → Episodes → Beats → Prose → Script → Storyboards with approve/lock state per stage. Replaces the current "everything happens on one page in any order" mental model with a wizard the user can both follow linearly and jump around inside.- - **Server enforcement parity.** Every regenerator + auto-resolver must read locks BEFORE running the LLM, throwing `ERR_VALIDATION` like `arcPlanner.generateArcOverview` does for `locked.arc`. Tests in `arcPlanner.test.js` ("throws ERR_VALIDATION + skips the LLM call when arc is locked") are the template.+## Backlog-- [ ] **Fix `lib/creativeDirectorPrompts.test.js` imageStrength wording assertions.** 3 tests in `server/lib/creativeDirectorPrompts.test.js` (around line 210) fail on `expect(out).toContain('Image strength: default')` — the prompt template no longer emits that exact phrasing for unset/null imageStrength. Pre-existing on `main` (verified 2026-05-12 while landing world-bible → pipeline wiring; out of scope for that PR). Either re-add the wording in the prompt builder or update the test to match the new output.+### Sharing-### v1.54.0 release-review deferred items+- [ ] **Content-addressed asset dedup.** Today asset copies skip-if-filename-exists. Hash-based dedup would let multiple manifests share the same blob even when filenames differ.+- [ ] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Same-network peers should sync these categories without going through a bucket.+- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; `chain[]` would preserve full attribution. Defer until users ask.+- [ ] **Same collection-export pattern for pipeline series with auto-collections.** Series renders that get auto-filed into a per-series collection should also flow through `manifest.collection`.++### Importer++- [ ] **Chunked extraction for source > 200K chars.** Today's `IMPORTER_SOURCE_CHAR_LIMIT` hard-rejects. Once a real import hits the cap, route through per-chunk canon extraction + rolling synopsis. Investigate chunk-overlap / merge strategy first.+- [ ] **Auto-detect content type.** A small `importer-classify.md` stage runs first and pre-selects the radio (still user-editable).+- [ ] **Re-running an import to replace (not append) an existing series.** Destructive-confirm UX with a "Replace all" toggle.+- [ ] **Importer review UI: extract `<CanonCard>` once Universe-as-Canon Phase 2 lands.** Today renders an inline minimal card in `Importer.jsx#CanonReviewSection`.+- [ ] **[PERF] `updateAt` re-render cost in `Importer.jsx`.** Wrap issue/arc cards in `React.memo` or move inline edits into per-card local state that lifts on blur. ~50 issues + 500K-char `proseExcerpt` displays go sluggish.+- [ ] **Centralise `ARC_ROLES` source-of-truth + expose `ARC_SHAPE_IDS` via `/importer/config`.** Drop the client-side `IMPORTER_ARC_ROLES_FALLBACK` to avoid drift from `server/lib/storyArc.js#ARC_ROLES`.+- [ ] **Importer screenplay prompt — clarify `targetIssueCount` default vs user-requested.** Pass a separate `isUserRequestedCount` flag and gate the split logic on that.+- [ ] **Importer partial-commit retry — guard against arc re-apply.** When `commitImport` rolls back issues mid-loop, a naive retry overwrites server-side arc edits. Version the arc or return a tagged response telling the client to skip arc on retry.+- [ ] **Importer review UI: in-place `proseExcerpt` edit affordance.** Collapsed-by-default textarea per issue card so the user can trim/correct without re-running Analyze (which burns 3 heavy-tier LLM calls).++### Universe-as-Canon — Phase 2 + extensions++- [ ] **Extract shared `CanonCard`.** Pull `CanonCard` + `KindSection` out of `UniverseCanon.jsx` into `client/src/components/universe/CanonCard.jsx`. Add lock-toggle icon, "from series: <name>" provenance badge, tag chips. Disable Refine + Render when locked.+- [ ] **Fold canon into `UniverseBuilder.jsx`.** Replace the categories grid with three kind-sections (Characters / Settings / Objects) using shared `CanonCard`. Move "Extract from prose" into header. Keep composite sheets unchanged.+- [ ] **Retire the standalone Canon page + route.** Replace `UniverseCanon.jsx` with a Navigate redirect (or delete + drop the route). Update `navManifest.js` + sidebar + tests.+- [ ] **Retire `universe.categories` on the schema.** After UI no longer reads it, drop from `sanitizeTemplate`, route Zod schemas, expand prompt template, `mergeCategoriesWithLocks`, `compilePrompts`'s `'variations'`/`'all'` branches.+- [ ] **Universe expand LLM contract enrichment.** Ask the LLM directly for `characters[]` / `settings[]` / `objects[]` with rich narrative metadata alongside visual `prompt`.+- [ ] **Settings → Places kind rename.** `BIBLE_KIND.SETTING → BIBLE_KIND.PLACE`, `BIBLE_FIELD[SETTING]: 'settings' → 'places'`. Touches ~20 files. Stick the rename to bible context — app settings stays as "settings".+- [ ] **Use rendered reference images as i2i anchors in downstream comic-page renders for models that support it.** SDXL/Flux pipelines anchor every panel render on the per-character rendered ref.++### Pipeline continuity / approval++- [ ] **Extraction after comicScript / teleplay stages.** Decide whether to also run extraction post-script or accept the gap for minor characters introduced only at script time.+- [ ] **Solidify character descriptions before visual render.** "Solidify characters" action in the bible sidebar runs an LLM pass synthesizing one canonical `physicalDescription` from all accumulated evidence.+- [ ] **Resolve-issues inherits verify gaps.** Verify the resolve prompt USES episode synopses when patching the arc.++### Creative Director / Audio++- [ ] **Whole-episode audio generation strategy.** Stop relying on per-clip audio; drive audio gen from episode-level prose/script arc. Generator candidates: Suno (commercial, duration control), MusicGen-MLX (local, bounded ~30s), AudioLDM2. New `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. Treat as a new sub-brainstorm when picked up — investigation first.+- [ ] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min to 10–30 min within one project. Profile after sustained use; verify round-22 dedup helped.+- [ ] **Pipeline Audio Phase 4c.2/4c.3/4d.2.** Local OSS music gen (MusicGen sidecar; pick generator first); 3rd-party engine stubs; VO line muxing into the CD stitch with per-line offsets + music-bed ducking.+- [ ] **Voice picker on character cards.** `voiceId` binding via dropdown on `CanonCard` when `kind === 'character'`; audition button hitting `/api/pipeline/tts/preview`. Same picker re-usable as per-line override in `AudioStage.jsx`.++### Video Gen (LTX-2.3)++- [ ] **Native FFLF deeper test on real keyframe pairs.** Validate with last frame of clip A + first frame of clip B from the same scene; expose more pipeline knobs (cfg-scale, stg-scale, stage1-steps) if interpolation looks weak.++### CoS / Agent lifecycle++- [ ] **TUI providers in manual `/api/runs`.** Add a TUI-specific runner branch in `server/lib/aiToolkit/routes/runs.js` so devtools manual runs also open attachable shell sessions.+- [ ] **Extract `finalizeAgent` helper shared across spawn paths.** Completion sequence is duplicated in `agentTuiSpawning.js`, `agentCliSpawning.js`, and `agentLifecycle.js#handleAgentCompletion`. A divergence in any leg silently breaks one path.+- [ ] **Wrap `runnerAgents.delete` in `handleAgentCompletion` body with try/finally.** A throw from `completeAgent` / `completeAgentRun` / `updateTask` / `processAgentCompletion` leaks the runner-agents Map entry forever. Regression-pin tests in `agentLifecycle.test.js` document the gap.+- [ ] **Shared `isTuiProvider` helper + client palette helper.** Mirror `isClaudeCliProvider`. Add `isTuiProvider` + lift `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`.+- [ ] **`spawnTuiAgent` / `spawnDirectly` options-object refactor.** Convert 11 positional args + deps to a single options object before the surface area grows.+- [ ] **Wrap `createShellSession` for agent TUIs.** Move callback/initial-command wiring into a thin `createAgentTuiSession()` in `agentTuiSpawning.js` that registers its own `pty.onData`.++### Voice agent++- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (existing Google Calendar MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (pick API: OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js`).+- [ ] **Wire proactive CoS speech to real triggers.** Plumbing landed (`POST /api/voice/speak` + `voice:speak` socket event); hook to high-severity `errorEvents`, `task:ready`, and `notificationEvents` with per-source rate-limits.+- [ ] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.+- [ ] **Voice agent vision fallback** — `ui_describe_visually`: screenshot tab and send to a vision-capable model so "what's on this chart?" works on CyberCity / graph views.+- [ ] **Voice agent — explicit long-term memory routing.** On retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search`.++### Writers Room / CyberCity / Email++- [ ] **Writers Room Phases 4–5.** Phase 4 synced prose/script/media review; Phase 5 realtime CD feedback. Builds on the unified bible/scene model. See [writers-room.md](./docs/features/writers-room.md).+- [ ] **CyberCity v2 Phase 2+** — deeper drill-down: per-agent spatial trail, system flow lines between buildings, recent-action timeline overlay. See [cybercity-v2.md](./docs/features/cybercity-v2.md).+- [ ] **M50 P9 — CoS Automation & Rules.** Automated email classification, rule-based pre-filtering, email-to-task pipeline.+- [ ] **M50 P10 — Auto-Send with AI Review Gate.** Per-account/per-recipient trust level + dual-LLM review (drafter + reviewer). Auto-send only when both approve or trust ≥ 0.9. See [messages-security.md](./docs/features/messages-security.md).+- [ ] **M34 P5-P7 — Digital Twin.** Multi-modal capture (voice/video/image identity sources), advanced testing, personas. Ties to GOALS.md "Multi-Modal Identity Capture".++### Image / Video Gen UI++- [ ] **Multi-reference image editing for FLUX.2.** UI accepting 2+ reference images + edit prompt. Swap registry's 9B entry to `FLUX.2-klein-9B-kv` for 2.5× speedup on multi-reference workflows. Gated repo — request access.+- [ ] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** Wire Together / Replicate / Fal into world-builder batch path so high-end renders are practical; let each bucket pick its own model.+- [ ] **Unify VideoGen `RESOLUTIONS` with shared image-gen list.** Move to `client/src/lib/videoGenResolutions.js` (or extend imageGenResolutions with `media: 'image'|'video'`) so dropdown + custom-fallback live in one place.++### Code quality / dedup (from `/simplify` passes)++- [ ] **Promote `resolveGalleryImage` to `server/lib/fileUtils.js`.** Basename + `resolvePath` + `startsWith(imagesRoot)` security check reimplemented in 5 places (videoGen, imageGen, visualStages, sceneRunner, imageGen/local). Pick up the `isFile()` symlink-following defense the four non-videoGen sites are missing.+- [ ] **Route-level tests for proof/final `target` + `useProofAsBase`.** Three test cases on `comicPageRenderSchema` + `comicCoverRenderSchema`.+- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.+- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.+- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern.** `VideoGen.jsx` + `CreativeDirector.jsx` render identical blocks differing only in `m.name` vs `m.name || m.id`.+- [ ] **Extract `mockPathsDataRoot()` test helper.** 6 test files open with byte-identical PATHS mocking setup.+- [ ] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.+- [ ] **Extract `CollectionPickerShell` from `AddToCollectionMenu` + `BulkTargetPicker`.** Two near-identical portal popovers. While extracting, accept a `collections` prop so `MediaCollectionDetail` avoids per-mount `listMediaCollections` round-trip.+- [ ] **Server-side bulk endpoint for collection items.** `POST /api/media/collections/:id/items/bulk` taking `{ add, remove }` — single read-modify-write per collection. Halves wall-clock for Move; dodges N-call race window. Real use case: "select all" on world-builder collections with 50+ items.+- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`.** Migrate `series.characters[].description` → `physicalDescription`; drop `|| raw.description` at `storyBible.js:246`.+- [ ] **Migrate `worldBuilderRefine.runRefine` onto `runPromptThroughProvider`.** Last LLM-runner site still hand-rolling the createRun → branch → executeApi/CliRun → accumulate-text pattern. ~30 LOC dedup.+- [ ] **Extract `usePersistedState` hook.** Six components repeat `useState(() => localStorage.getItem(KEY) === '1')` + setter. Add `useLocalStorageBool(key, default)` + JSON-blob variant.+- [ ] **Lift `runFfmpegProcess({ args, signal, stderrTailBytes }) → { ok, reason }` into `server/lib/ffmpeg.js`.** Three sites share spawn → stderr-tail → close → SIGTERM-on-abort. Leave `videoTimeline/local.js` (broadcast complicates it).+- [ ] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with wardrobe-picker dropdown. Decide first: does the extractor guess or does the user pick? Append wardrobe after physicalDescription vs substitute body fields?+- [ ] **Extract `sanitizeListWith(raw, sanitizer, cap)` helper in `storyBible.js`.** Three array-walk + per-item sanitize + cap sites.+- [ ] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.+- [ ] **AbortSignal listener cleanup in `audioMux.js#runFfmpeg`.** `addEventListener('abort', kill, { once: true })` never removed on normal completion. Theoretical until the stitch step passes a signal.+- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })`.** Three readdir + filter + stat-per-entry sites in `fileUtils.js`.+- [ ] **Teach `request()` in `apiCore.js` about FormData.** Drop hard-coded `Content-Type: application/json` when body is FormData. Two helpers (`apiHealth#uploadAppleHealthXml`, `apiPipeline#uploadPipelineMusicTrack`) bypass `request()` today.+- [ ] **`mergeVariations` NPE guard in `UniverseBuilder.jsx`.** Add `.label?.toLowerCase()` + `.filter(Boolean)` parity to the locked variations Set (post-rename file/line drift — agent confirmed line 57 still lacks the guard).+- [ ] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).+- [ ] **`useMediaAnnotations.getCardProps(key)` helper.** Single `{ starred, hasNote, onToggleStar }` lookup at 6 sites across 4 gallery pages.+- [ ] **Cache `resolveGlobalDisplayName()` settings read.** Memoize for ~30s or invalidate on `settings:updated` event.+- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.+- [ ] **Hoist identity lookup out of `liftLegacyEntry` loop in `mediaAnnotations.js#readAll()`.** Pass `localInstanceId`, `defaultAuthorName` in once; make `liftLegacyEntry` synchronous.+- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` — one readState + N in-memory mutations + one writeState + one renumber.++### Better-audit residue++- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).+- [ ] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.+- [ ] **[HIGH][TESTS]** Add coverage for `server/services/shell.js` and `server/services/feeds.js` — both have exported functions but no sibling test. Shell drives all terminal sessions; feeds manages subscriptions. (New — surfaced 2026-05-16 replan.)+- [ ] **[MEDIUM][CLIENT]** 4 components still redefine `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally: `VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, `MortalLoomTab.jsx`, `ImportTab.jsx`.+- [ ] **[MEDIUM][PERF]** `feeds.js#getItems` (303–319) — full-sort-then-paginate on every request. Pre-sort once at write time or maintain a per-feed index.+- [ ] **[MEDIUM][CODE]** Magic numbers in `cos.js:166,357`, `lmStudioManager.js:66`; brittle `err.message.startsWith('unknown piper voice:')` in `routes/voice.js:160` and `err.message.includes('not initialized')` in `services/visionTest.js:124`.+- [ ] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — portal-with-fixed-positioning duplicated across 4 components (`AddToCollectionMenu`, `BulkTargetPicker`, `ThemeSwitcher`, `VisualStylePicker`) with near-identical rAF-coalesced scroll/resize listeners + `useLayoutEffect` measurement.-Captured 2026-05-13 during /do:release; rated below release-blocker but worth picking up. Six of the originals landed in the release PR after Copilot review — only items below remained.+### Pipeline — deferred-- [ ] **Holistic refine deletion confirmation UX.** Refine can silently delete every unlocked variation/composite if the LLM omits them — by design (`drops unlocked items the LLM omits` test pins this). The inline refine panel applies the patch immediately with no preview, so deletions land before the user sees them. Compute a deleted-items count from `result.categories`/`compositeSheets` vs the draft in `runRefine` (`client/src/pages/WorldBuilder.jsx`) and either surface it in the rationale block ("Removed N variations") or require a confirm click when N > 0.-- [ ] **`mergeVariations` NPE guard in `WorldBuilder.jsx:435-445`.** `new Set(locked.map((v) => v.label.toLowerCase()))` assumes every locked variation has a string label. Mid-edit drafts could violate this. Match the `fresh` loop's `v.label?.toLowerCase()` guard and `.filter(Boolean)`.-- [ ] **Client tests for deep routing + drag.** No React Testing Library coverage for `/world-builder/:worldId` URL state, `@dnd-kit` chip reorder, or the localStorage-backed sidebar collapse. Add smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).-- [ ] **`server/lib/aiToolkit/providers.js:25-31` — codex migration destructively drops extra `models[]` entries.** If `models` is `[sentinel, "gpt-5"]` (transitional/manual state), the migration overwrites the whole array with `[sentinel]`, silently losing extras. Either preserve non-sentinel entries or log a `console.warn` before overwrite.-- [ ] **`server/lib/aiToolkit/routes/providers.js:47-60, 62-70` — toolkit's own POST/PUT skip Zod validation.** PortOS's wrapper now validates POST through `providerSchema`, but the toolkit's own routes (used by direct toolkit consumers) still do ad-hoc `name`/`type` checks only. Wire `validate(providerSchema, req.body)` into the toolkit's routes too so any direct consumer of the toolkit gets the same input validation PortOS now has.-- [ ] **`server/lib/aiToolkit/providers.js:124-143` — `createProvider` explicit field list vs. `updateProvider` spread asymmetry.** Future fields added to the UI but not to `createProvider`'s explicit list are silently dropped on creation but preserved on update. Add an end-to-end test that creates a provider with every field from `providers.sample.json` and asserts persistence, or switch `createProvider` to spread.-- [ ] **`server/lib/aiToolkit/providers.js:70-76` — corrupt `providers.json` crashes warm-up.** Truncated JSON throws from `JSON.parse` in `loadProviders`, and every subsequent request also throws. Wrap parse in try/catch; on failure rename the bad file to `.corrupt` and fall back to the sample.+- [ ] **Wire `storyboards` scene-video rendering** as a separate path from the episode-video handoff. Add optional `sceneVideoJobId` per scene.+- [ ] **Rich-text editor for prose stage.** Replace plain textarea in `ProseStage.jsx` — reuse Writers Room editor or pick a minimal markdown editor.+- [ ] **Versioning / diff view per stage.** Persist last N `lastRunId` snapshots; offer a diff modal.+- [ ] **Episode-video provider picker (RunwayML / third-party).** Once the abstraction lands, expose picker on EpisodeVideoStage.+- [ ] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.+- [ ] **Voice-controlled stage advancement.** Register pipeline stage navigation actions in `voice/tools.js`.+- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` for a future "turn script fragment into N image-gen prompts" button.+- [ ] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift to a shared helper; next migration becomes ~15 lines.+- [ ] **Shots-aware scene-output-contract partial.** Split into `_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md` when a third shots-using stage appears.+- [ ] **Per-panel/scene image progress in the Pipeline UI.** ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview.-## Backlog+----### Creative Director follow-ups--The pipeline now has multi-frame evaluation, auto-accept watchdog, cheap smoke fixture, and per-scene `imageStrength` continuation anchoring (see DONE.md). Remaining targets surfaced by the long E2E run:--- [ ] **Whole-episode audio generation strategy.** mlx-video-with-audio generates audio per-clip and the resulting scene-level mini-soundtracks are abruptly different from each other — even a perfect xfade boundary won't fix it (it's like a DJ mixing five unrelated songs). The architectural answer is to STOP relying on per-clip audio and instead drive audio generation from the *whole-episode arc*. Scope of the eventual design:- - **Source of truth.** The episode's prose/script/storyboards (already in the pipeline data model) define the arc — beats, tone shifts, scene durations. An audio generator should consume this, not the per-clip video output.- - **Generator candidates.** Suno API (commercial, has duration control), MusicGen-MLX (local, but bounded to ~30s without stitching), AudioLDM2, or a multi-track approach (separate music + ambient + foley layers).- - **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.-- [ ] **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--The 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).--### Other backlog--- [ ] **TUI providers in manual `/api/runs`.** This PR wires `type: "tui"` providers into CoS agent spawning (`server/services/agentLifecycle.js` → `server/services/agentTuiSpawning.js`) and disables TUI execution in the AI Providers run panel, but the generic API route still lives in `server/lib/aiToolkit/routes/runs.js` and only knows `cli` and `api` execution. Add a TUI-specific runner branch there if manual devtools runs should also open attachable shell sessions. Deferred to keep the CoS-agent path focused and testable.-- [ ] **Extract `finalizeAgent` helper shared across spawn paths.** The completion sequence (`release(lane) → completeExecution → analyzeAgentFailure → persistSimplifySummaries → completeAgent → completeAgentRun → updateTask branch → markProviderUsageLimit/RateLimited → processAgentCompletion → rm BTW.md → cleanupWorktreeFn → unregisterSpawnedAgent → activeAgents.delete`) is duplicated in `server/services/agentTuiSpawning.js:finish()`, `server/services/agentCliSpawning.js:claudeProcess.on('close')`, and `server/services/agentLifecycle.js:handleAgentCompletion`. A divergence in any leg (lane release, user-terminated branch, rate-limit marking) silently breaks one path. Skipped in this PR to keep the TUI change reviewable; should be unified next.-- [ ] **Shared `isTuiProvider` helper + client palette helper.** `provider.type === 'tui'` is checked ~6 times in `server/services/agentLifecycle.js` and ~12 times across `client/src/pages/AIProviders.jsx` + `client/src/components/cos/TaskAddForm.jsx`. Mirror the existing `isClaudeCliProvider` pattern: add `isTuiProvider` next to it (or hoist both into a new `server/services/providerType.js`), plus a client mirror in `client/src/utils/providers.js`. Also lift `providerTypeClass` from `AIProviders.jsx` into the same client util so `AgentCard.jsx` can stop inlining the TUI badge palette.-- [ ] **`spawnTuiAgent` / `spawnDirectly` options-object refactor.** Both currently take 11 positional args + a deps object. Convert to a single options object now while the TUI surface is small, to avoid cementing the long positional signature.-- [ ] **Wrap `createShellSession` for agent TUIs.** The shell session contract in `server/services/shell.js` now carries agent-specific fields (`onData`, `onExit`, `initialCommand`, `initialCommandDelayMs`, `agentId`). `kind`/`label`/`command` stay generic, but the callback/initial-command wiring should move into a thin `createAgentTuiSession()` wrapper in `agentTuiSpawning.js` that registers its own `pty.onData` listener.-- [ ] **Writers Room (Phase 4–5)** — Phases 1–3 shipped (authoring core, storyboard companion, character/world/objects bibles, per-stage LLM picker, paragraph-grain Adapt, auto-queue scene image gen, Read view + render dock). Remaining: Phase 4 synced prose/script/media review, Phase 5 realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md). Phase 4 now lands on the unified bible/scene model that the DRY-unification work (DONE.md 2026-05-10) brought in.-- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (Google Calendar via existing MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (needs API choice — OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js` scheduled actions).-- [ ] **Wire proactive CoS speech to real triggers.** The plumbing landed in this PR (`POST /api/voice/speak` + `server/services/voice/proactiveSpeech.js` + `voice:speak` socket event), but nothing in the CoS calls it yet. Hook points to consider: high-severity error events from `errorEvents` (read-only suppression to high-priority alerts only), `cosEvents.emit('task:ready', ...)` for "ready to start <task>?", `notificationEvents` for whatever passes the priority bar. Each integration should keep a per-source rate-limit so a stuck loop can't spam audio. Priority field is plumbed end-to-end (low/normal/high) but currently only influences the toast icon — pick a real semantic before hooking high-volume sources.-- [ ] **Optimize `voice:ui:index` text payload.** `ui_read` works by piggy-backing visible page text on the existing UI index push (`client/src/services/domIndex.js#extractVisibleText`). For text-heavy pages this adds ~6-8 KB to every index push (route change + DOM mutation debounce), which is fine on a private network but wasteful. Switch to lazy: only run `extractVisibleText` when the server requests it via a new `voice:ui:read-request` side-effect that the client responds to. Keep the current behavior as a fallback so `ui_read` never returns "no page text".-- [ ] **Voice agent vision fallback** — `ui_describe_visually` tool: screenshot the current tab (or a named canvas/chart) and send to a vision-capable model so "what's on this chart?" works on non-DOM content (CyberCity, graph views). Depends on a vision provider in `portos-ai-toolkit`.-- [ ] **Voice agent — explicit long-term memory routing** — pipeline already routes capture verbs to `brain_capture`. Remaining: on retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search` so it's self-improving rather than ambient.-- [ ] **CyberCity v2 — Phase 2+** — Phase 1 operational legibility shipped (per-building health glyphs, attention pane, search overlay, filter chips, hover quick-actions, mobile). Remaining: deeper drill-down (per-agent spatial trail, system flow lines between buildings, recent-action timeline overlay). See [cybercity-v2.md](./docs/features/cybercity-v2.md).-- [ ] **M50 P9 — CoS Automation & Rules** — Automated email classification, rule-based pre-filtering, email-to-task pipeline.-- [ ] **M50 P10 — Auto-Send with AI Review Gate** — Per-account/per-recipient trust level + dual-LLM review (drafter + reviewer). Only auto-send when both approve or trust ≥ 0.9. See [Messages Security](./docs/features/messages-security.md).-- [ ] **M34 P5-P7 — Digital Twin** — Multi-modal capture (voice/video/image identity sources), advanced testing, personas. Ties to GOALS.md secondary "Multi-Modal Identity Capture".-- [ ] **Multi-reference image editing for FLUX.2** — UI on the Image Gen page that accepts 2+ reference images plus an edit prompt (e.g. "put the subject from image A into the scene from image B"). When this lands, swap the model registry's 9B entry to [`black-forest-labs/FLUX.2-klein-9B-kv`](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B-kv) — KV-cache optimization gives up to 2.5× speedup on multi-reference workflows. Work involves: schema for multi-image payload (`referenceImages: [...]`), client multi-uploader, server FormData parsing, and adapting `flux2_macos.py` to call the multi-reference pipeline API. Separately-gated repo on HF — user must request access.-- [ ] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** The shipped batch render only supports local mflux + Codex. Wire the existing external SD-API providers (Together, Replicate, Fal) into the world-builder batch path so high-end renders are practical, and let each bucket pick its own model (e.g. characters → SDXL portrait LoRA, environments → Flux-pro). Single touchpoint: `server/services/worldBuilder.js#compileBatchPrompts` + `worldBuilderCollectionHook.js`. (Surfaced from PR #211 follow-ups.)-- [ ] **Unify VideoGen.jsx RESOLUTIONS with the shared image-gen list** — `client/src/pages/VideoGen.jsx:54` defines its own private `RESOLUTIONS` array + finds-by-w/h block, duplicating the pattern in `client/src/lib/imageGenResolutions.js`. Move VideoGen's presets into a shared `client/src/lib/videoGenResolutions.js` (or extend `imageGenResolutions.js` with a `media: 'image' | 'video'` field) so the dropdown + custom-fallback logic only lives in one place. Surfaced during the codex hi-res / per-backend filter work — `filterResolutions(mode, runner)` is exactly the helper VideoGen will want once mlx-video models gain runner-specific size constraints.-- [ ] **Promote `resolveGalleryImage` to `server/lib/fileUtils.js`.** The basename + `resolvePath` + `startsWith(imagesRoot)` security check is reimplemented in 5 places: `server/routes/videoGen.js:169-180` (the most complete version, includes `statSync.isFile()`), `server/routes/imageGen.js:160-166`, `server/services/pipeline/visualStages.js#resolveProofInitImage`, `server/services/creativeDirector/sceneRunner.js:155`, `server/services/imageGen/local.js:279`. Promote `resolveGalleryImage(name)` into `fileUtils.js` (lives next to `PATHS`) and migrate all five sites — the new `resolveProofInitImage` becomes a thin wrapper that maps the `null` return to the `PIPELINE_COMIC_PROOF_*` ServerError variants. Bonus: pick up the `isFile()` symlink-following defense that the four non-videoGen sites are missing. Surfaced from the /simplify pass on the proof/final feature.-- [ ] **Route-level tests for `target: 'final'` and `useProofAsBase: true`.** The proof/final feature added route schema fields `target` (proof|final) and `useProofAsBase` (boolean) on `comicPageRenderSchema` + `comicCoverRenderSchema`. Existing `routes/pipeline.test.js` only exercises the default (no `target` → proof slot). Add: (1) a `target: 'final', useProofAsBase: false` test asserting `cover.finalImage.jobId` lands while `proofImage` is preserved untouched, (2) a `target: 'final', useProofAsBase: true` test with no prior proofImage asserting `PIPELINE_COMIC_PROOF_MISSING` surfaces as 400, (3) a happy-path i2i test verifying `initImagePath` reaches the enqueue mock when proofImage.filename is present. Surfaced from the /simplify pass on the proof/final feature.-- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`** — `MediaLightbox.jsx` hand-rolls touch-swipe nav (SWIPE_MIN_PX / TAP_MAX_PX / horizontal-dominant guard) and `navigator.clipboard.writeText` is inlined across 8+ call sites (`ExportTab`, `EditAppModal`, `NextActionBanner`, `JiraReports`, `RapidReader`, `Shell`, `RunsHistoryPage`, `MediaLightbox`). Extract once a second swipe consumer appears; clipboard can move now (`copy(text, label)` with the existing "insecure context" toast). Surfaced from the lightbox full-screen pass.-- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`** — In full-screen mode the lightbox renders a hand-rolled aside (`absolute top-0 right-0 bottom-0 w-full sm:w-96 z-20`) that is exactly the project's existing `Drawer` component. Skipped during the simplify pass because `Drawer`'s flat Esc handler conflicts with the lightbox's layered Escape cascade (drawer → fullscreen → close); reconcile by either lifting the cascade above `Drawer` or letting `Drawer` accept a no-op-Esc prop.-- [ ] **Extract `<ModelSelect>` component for the active+Legacy optgroup pattern** — `client/src/pages/VideoGen.jsx` and `client/src/pages/CreativeDirector.jsx` both render an identical "filter(!deprecated).map + optgroup('Legacy') + filter(deprecated).map" block (differ only in `m.name` vs `m.name || m.id`). Extract `client/src/components/ModelSelect.jsx` taking `{ models, value, onChange, labelOf?, disabled? }` and convert both sites. ~30 LOC removal, and any future model dropdown picks up the deprecated-grouping for free. Surfaced from the LTX-deprecate /simplify pass.-- [ ] **Extract `mockPathsDataRoot()` test helper** — `server/lib/storyBible.test.js`, `server/services/writersRoom/{characters,settings,objects,local,promoteToPipeline}.test.js` (6 files) all open with byte-identical setup: `let tempRoot; vi.mock('../../lib/fileUtils.js', async () => { const actual = await vi.importActual(...); return new Proxy(actual, { get(t,p){ if (p==='PATHS') return new Proxy(actual.PATHS,{get(tp,pp){ if(pp==='data') return tempRoot; ... }}); ... } }); }); beforeEach(() => { tempRoot = mkdtempSync(...) }); afterEach(() => rmSync(tempRoot, { recursive: true, force: true }))`. Extract into `server/test-utils/tempDataRoot.js` exposing `mockPathsDataRoot()` that returns a live tempRoot getter. ~20 LOC saved per file plus a single fix-point if PATHS mocking semantics ever change. Surfaced from the bibleStore-factory /simplify pass.-- [ ] **Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`** — pre-existing bug surfaced during /do:review. Today's try/finally (`server/services/agentLifecycle.js:536-547`) only wraps the spawn call itself. Between `spawningTasks.add(task.id)` (line 134) and the try-block, the function does ~400 lines of async work — `buildAgentPrompt`, `writeFile(prompt)`, `createAgentRun`, `registerAgent`, etc. — each of which can throw (ENOSPC, EACCES, network). A throw on any of those paths leaves `spawningTasks` registered FOREVER, permanently blocking future spawns of that task id. The detected-error paths call `cleanupOnError` which does delete, but an unhandled throw is the gap. Fix: hoist the try/finally up to wrap from line 134 (after `add`) through the spawn calls. `cleanupOnError`'s redundant `spawningTasks.delete` becomes a no-op (Set.delete on absent key) which is fine. Pre-existing bug, not introduced by the dedup-race fix.-- [ ] **`useAsyncAction` post-unmount setState guard** — the hook in `client/src/hooks/useAsyncAction.js` calls `setRunning(false)` after an awaited async fn resolves. If the owning component unmounts mid-action, React 18 silently warns; React 17 surfaces the warning. Add a `mountedRef` (set true in mount effect, false in cleanup) and gate `setRunning(false)` on `mountedRef.current`. YAGNI for current call sites (all stable parent components) but worth doing once the hook gains a 4th consumer or any consumer that unmounts during long-running ops. Surfaced from /do:review.-- [ ] **Extract `CollectionPickerShell` from `AddToCollectionMenu` + `BulkTargetPicker`** — both files (`client/src/components/media/AddToCollectionMenu.jsx`, `client/src/components/media/BulkTargetPicker.jsx`) own a near-identical portal popover: same `MENU_WIDTH/GAP/VIEWPORT_PADDING/SEARCH_THRESHOLD` constants, line-for-line identical reposition math, identical click-away + Esc + rAF-scroll effects, identical "new collection" footer form. The only differences are local to the list row (membership-toggle w/ check vs single-pick) and the create-success path (add-after-create vs pick-after-create). Extract `<CollectionPickerShell anchorRef, title, busy, onClose, renderRow, onCreate>` that owns positioning/portal/search/create-form; each picker becomes a ~40-line `renderRow` function. Two files isn't a fire; a third would force this. While extracting, also accept a `collections` prop (optional, falls back to internal fetch) so `MediaCollectionDetail` can pass its already-fetched list and avoid the per-mount `listMediaCollections` round-trip when the user toggles Move/Copy. Surfaced from the bulk-actions /simplify pass.-- [ ] **Server-side bulk endpoint for collection items** — `MediaCollectionDetail`'s bulk Move/Copy/Remove currently makes N sequential HTTP calls (server has no per-collection lock, so parallel writes would lose updates on the JSON read-modify-write). At ~30ms localhost RTT, 20 items ≈ 600ms; 50 items ≈ 1.5s (move = 2 × that). The user's stated use case is "select all" on a world-builder collection that could legitimately have 50+ items. Add `POST /api/media/collections/:id/items/bulk` taking `{ add: [{kind,ref}], remove: [key] }` and doing one read-modify-write per collection. Halves wall-clock for Move (single source-side commit instead of N), dodges the race window entirely. Surfaced from the bulk-actions /simplify pass.-- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`** — `server/lib/storyBible.js:130` carries an inline `TODO(item-4): drop the description fallback once pipeline characters extract natively.` Item 4 (shared bible-extraction service) shipped 2026-05-10 — extraction now writes the canonical `physicalDescription` field directly. Plan: write a one-shot migration that rewrites every `series.characters[].description` → `physicalDescription` in `data/pipeline-series.json` (idempotent: skip entries that already have `physicalDescription`), drop the `|| raw.description` fallback at `storyBible.js:137`, and remove the TODO comment. Audit `data.sample/` + tests for any remaining `description` reads before merging.-- [ ] **Migrate `worldBuilderRefine.runRefine` onto `runPromptThroughProvider`** — `server/services/worldBuilderRefine.js:131-162` still hand-rolls the createRun → branch-on-type → executeApiRun/executeCliRun → accumulate-text → reject-on-error pattern that the parent unification (PR #221) collapsed for the other four LLM-runner sites. The effective-model resolution was unified in this PR, but the full runner-wrapper migration was deferred to keep scope tight. Replace the inline `runRefine` with a single `runPromptThroughProvider({ provider, model, prompt, source: 'world-builder-refine' })` call (mirroring `worldBuilderExpand.js`). Drop the local `createRun`/`executeApiRun`/`executeCliRun` imports. ~30 LOC dedup. Surfaced from /do:review on the resolveEffectiveModel PR.-- [ ] **Extract `usePersistedState` hook for the localStorage-backed boolean pattern.** The same `useState(() => localStorage.getItem(KEY) === '1')` + setter-with-persist pattern is now duplicated across at least 6 sites: `client/src/pages/WorldBuilder.jsx:243-252` (`worldBuilder.worldsCollapsed`), `client/src/pages/WritersRoom.jsx:25-34` (`wr.libraryCollapsed`), `client/src/pages/ChiefOfStaff.jsx:65-93`, `client/src/pages/Instances.jsx:84-95`, `client/src/pages/PipelineSeries.jsx:39-68`, and Layout.jsx's collapse toggles. Extract `client/src/hooks/usePersistedState.js` exposing `useLocalStorageBool(key, defaultValue)` returning `[value, toggle]` (and a sibling `useLocalStorageState(key, default, serialize)` for the JSON-blob variant CalendarTab uses). Migrate all sites. ~50 LOC dedup + future consistency. Surfaced from /simplify pass on the WorldBuilder collapse work.--### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)--These were flagged by the post-merge code review pass on the Z-Image + Civitai LoRA work but deliberately deferred to keep the original PR scoped.--_All items in this section have shipped — see DONE.md → 2026-05-12 for the-"Civitai / Z-Image follow-ups — six post-merge cleanups", the-`scripts/_runner_common.py` extraction, the `runPromptThroughProvider`-+ `jsonExtract` unification, and the `<Modal>` + `getRenderConfigForItem`-entries._--### Better Audit follow-ups--- [ ] **[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test-specific hack in prod boot path).-- [ ] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.-- [ ] **[HIGH][CODE]** Wrap `handleAgentCompletion` body in try/finally so the terminal `runnerAgents.delete(agentId)` (`server/services/agentLifecycle.js:1146`) always runs. Today a throw from `completeAgent` (line 939), `completeAgentRun` (line 949), `updateTask` (lines 954 / 960), or `processAgentCompletion` (line 987) aborts the function and leaks the runner-agents Map entry forever, blocking any retry. Tests added 2026-05-12 in `agentLifecycle.test.js` ("regression-pin" block) document the gap — once the wrap lands, those tests' `runnerAgents.has(...)` assertions flip and need updating. Sister fix to the open Backlog item "Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`" above.-- [ ] **[MEDIUM][CLIENT]** 4 components still redefine `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally instead of importing from `client/src/utils/formatters.js`: `pages/VideoTimelineEditor.jsx`, `pages/VideoTimeline.jsx`, `components/settings/MortalLoomTab.jsx`, `components/brain/tabs/ImportTab.jsx`. (Down from 8.)-- [ ] **[MEDIUM][PERF]** `server/services/feeds.js#getItems` (lines 303–319) — full-sort-then-paginate on every request. Pre-sort once at write time or maintain a per-feed index.-- [ ] **[MEDIUM][CODE]** Magic numbers in `cos.js:166,357`, `lmStudioManager.js:66`; brittle `err.message.startsWith('unknown piper voice:')` in `routes/voice.js:160` and `err.message.includes('not initialized')` in `services/visionTest.js:124`.-- [ ] **[LOW][CLIENT]** Extract a shared `usePopoverPosition` hook (or `lib/popoverPosition.js`) — the inline portal-with-fixed-positioning pattern is now duplicated across four components with near-identical `updateMenuPosition` + rAF-coalesced scroll/resize listeners + `useLayoutEffect` measurement: `client/src/components/media/AddToCollectionMenu.jsx` (reference), `client/src/components/media/BulkTargetPicker.jsx`, `client/src/components/ThemeSwitcher.jsx`, `client/src/components/pipeline/VisualStylePicker.jsx`. Each carries its own `MENU_WIDTH` / `MENU_GAP` / `VIEWPORT_PADDING` constants. Deferred from the VisualStylePicker portal-fix /simplify pass — out of scope there, but the fourth copy is the right moment to dedup.+## Deferred Architecture (human-led planning)-### Deferred Architecture (human-led planning)+God-file decomposition candidates — none are bugs; pick up when touching the file for unrelated reasons.- `server/services/cos.js` (3115 LOC) — split into cosTaskStore / cosTaskGenerator / cosJobScheduler / cosHealthMonitor.- `server/services/agentLifecycle.js` (1446 LOC) — extract prepareAgentWorkspace / resolveProvider / processCompletion.@@ -185,13 +155,13 @@ entries._- `server/services/taskSchedule.js` (2369 LOC) — extract prompt management to `taskPromptService.js`.- `server/services/taskLearning.js` (1939 LOC) — separate metrics aggregation from heuristic routing.- `server/services/autonomousJobs.js` (1567 LOC) — extract job registry / scheduler / execution paths.-- `server/services/voice/tools.js` (1284 LOC) — group by domain (UI control / calendar / brain / media) into sibling modules.+- `server/services/voice/tools.js` (1284 LOC) — group by domain (UI / calendar / brain / media) into siblings.- `server/services/git.js` (1271 LOC) — extract command builders + parsers.- `server/cos-runner/index.js` (1076 LOC) — extract spawn / lifecycle / IPC layers.-- `server/services/memory.js` (1049 LOC) — separate retrieval, classification, and persistence.+- `server/services/memory.js` (1049 LOC) — separate retrieval, classification, persistence.- `server/services/xcodeScripts.js` (1131 LOC) — collapse repeated AppleScript builders.- `server/routes/apps.js` (1180 LOC) — extract `npm install` orchestration to `appBuilder.js`.-- `client/src/pages/VideoGen.jsx` (1361 LOC) — extract mode-specific control panels (i2v / a2v / extend / FFLF) into siblings.+- `client/src/pages/VideoGen.jsx` (1361 LOC) — extract mode-specific control panels (i2v / a2v / extend / FFLF).- `client/src/pages/ImageGen.jsx` (1182 LOC) — extract preset picker + multi-reference uploader.- `client/src/components/goals/GoalDetailPanel.jsx` (1252 LOC) — god component.- `client/src/components/meatspace/tabs/CalendarTab.jsx` (1269 LOC) — extract grid renderer + goal-link panels.@@ -202,78 +172,20 @@ entries._**Known low-severity:** pm2 ReDoS (GHSA-x5gf-qvw8-r2rm) — no upstream fix, not exploitable via PortOS routes.-### Depfree audit--All dependencies audited and justified (2026-04-28). 0 removals. See [docs/DEPS.md](./docs/DEPS.md) for the full classification table and per-package rationale.----## Future Ideas-- **Identity Context Injection** — Per-task-type digital twin preamble toggle.-- **Content Calendar** — Unified calendar across platforms.-- **Goal Decomposition Engine** — Auto-decompose goals into task sequences.-- **Knowledge Graph Visualization** — Extend BrainGraph 3D to full knowledge graph.+- **Identity Context Injection** — per-task-type digital twin preamble toggle.+- **Content Calendar** — unified calendar across platforms.+- **Goal Decomposition Engine** — auto-decompose goals into task sequences.+- **Knowledge Graph Visualization** — extend BrainGraph 3D to full knowledge graph.- **Autobiography Prompt Chains** — LLM follow-ups building on prior answers.-- **Legacy Export Format** — Identity as portable Markdown/PDF.-- **Workspace Contexts** — Project context syncing across shell, git, tasks.-- **Inline Code Review Annotations** — One-click fix from self-improvement findings.+- **Legacy Export Format** — identity as portable Markdown/PDF (closes GOALS "Knowledge Legacy" gap currently at Early status).+- **Workspace Contexts** — project context syncing across shell, git, tasks.+- **Inline Code Review Annotations** — one-click fix from self-improvement findings.- **Major Dependency Upgrades** — React 19, Zod 4, PM2 6, Vite 8.-- **Dynamic Skill Marketplace** — Self-generating skill templates from task patterns.-- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides. Builds on the new `/cos/workflow` pipeline.-------## Writers Room ↔ Pipeline DRY Unification--Steps 1–7 shipped (see DONE.md 2026-05-10). The Writers Room and Pipeline now share one scene-prompt composer, one story-bible schema + sanitizer, one staged-LLM runner, one bible-extraction service, one scene-list extractor, a one-way promote bridge, and a partials-aware prompt template engine. Remaining follow-ups live in the dedicated items above (drop legacy `description` fallback; `mockPathsDataRoot()` test helper; `useAsyncAction` post-unmount guard).-------## Pipeline — Story Arc Planning (shipped Phases 1–4)--Initiative shipped 2026-05-10 (see DONE.md). The PipelineSeries page now has a two-pane layout (sticky bible sidebar + Arc → Season → Episode canvas), the data model carries `series.arc` + `series.seasons[]` + `issue.seasonId` + `issue.arcPosition`, three LLM passes drive arc / per-season-episodes / cross-season verification, and the `ArcCanvas` UI surfaces all of it.--**Original Phase 5 (deferred — observe first):** Inject a `seasonContext` variable (current season synopsis + last 1–3 episodes' loglines) into the per-episode prose/script stage prompts via `server/services/pipeline/textStages.js#buildStageContext`. The macro continuity is already implicit in the planning artifacts (`series.arc.protagonistArc`, the season synopses generated upfront by `pipeline-arc-overview`, and the episode's idea-stage seed from `pipeline-season-episodes`), and the bible system already enforces character/setting consistency. Revisit only if executed per-episode prose starts contradicting adjacent episodes in practice.--**Out of scope (explicit non-goals):**--- Per-season independent media collections (one folder per season). The collection model is already per-series; per-season splits add UX complexity without clear value.-- Multi-series arcs (a season that spans two related series). Single-series scope keeps the data model flat and the LLM context bounded.-- Auto-promoting an existing flat list of issues into seasons. Users opt in via "Generate arc"; existing issues stay un-grouped (`seasonId: null`) until the user moves them.-- Drag-and-drop reorder of episodes within / between seasons (Phase 4b). Hover-revealed season picker on each episode covers manual cross-season moves; revisit if users hit reorder pain inside a single season.-------## Pipeline — Deferred--Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx`. The core text-to-video creative pipeline is now wired end-to-end (idea → prose → scripts → storyboards → episode video via CD handoff). Items below were scoped out and live here so they don't evaporate:--- [ ] **Wire `storyboards` scene-video rendering** as a separate path from the episode-video handoff. Currently storyboards records `imageJobId` per scene; add optional `sceneVideoJobId` so a user can render an individual scene's video without committing the full episode-video stitch.-- [ ] **Rich-text editor for prose stage.** Currently a plain `<textarea>` in `client/src/components/pipeline/stages/ProseStage.jsx`. Either reuse `client/src/components/writers-room/` editor, or pick a minimal markdown editor.-- [ ] **Versioning / diff view per stage.** No history right now — regenerating overwrites. Could persist last N `lastRunId` snapshots and offer a diff modal.-- [ ] **Episode-video provider picker (RunwayML / third-party).** Stubs are commented in `server/services/videoGen/`. Once that abstraction lands, the `episodeVideo` handoff should expose a provider picker on the EpisodeVideoStage UI (local LTX vs Runway vs …).-- [ ] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export a print-ready PDF.-- [ ] **Voice-controlled stage advancement.** "Next stage", "rerun comic script" via the existing voice agent. Register pipeline stage navigation actions in `server/services/voice/tools.js`.-- [x] **Recent-issues dynamic children under the Pipeline sidebar entry.** Shipped — Layout.jsx's `decoratePipelineChild` now hydrates Pipeline with one grandchild per series (`dynamic: 'pipelineSeries'`), focus-debounced refresh, alphabetical sort. Originally landed showing 10 recent issues; reworked 2026-05-14 to show all series so the sidebar stays coherent across many series. Recursive grandchildren render works in `renderNavItem`.-- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` template files for a future "AI: turn the script fragment into N image-gen prompts" button on the ComicPages and Storyboards stages.-- [ ] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.-- [ ] **Shots-aware scene-output-contract partial.** `data.sample/prompts/stages/pipeline-extract-scenes.md` now inlines the JSON output contract (with `shots[]`) instead of using `{{> scene-output-contract }}`. If a third shots-using stage ever appears (or a top-level scene field gets added), the partial and the inlined copy in extract-scenes will drift. Split into composable partials (`_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md`) when that third caller materializes — until then the inline copy is the smaller risk.-- [ ] **Voice picker on character cards (Pipeline Audio 4b follow-up).** AudioStage renders fine without it (per-line render falls through to the project default voice), but binding `character.voiceId` today requires hand-editing JSON or PATCHing the universe canon. The picker should live on `CanonCard` (`client/src/components/pipeline/CanonCard.jsx`) when `kind === 'character'`: chip with current voice id, dropdown reading `/api/pipeline/tts/voices`, audition button that fetches `/api/pipeline/tts/preview` and plays inline, and a Save handler that PATCHes the universe canon entry (`updateUniverseCharacter` — needs to exist in `apiUniverseBuilder.js`). Same picker re-usable on a per-line override in `AudioStage.jsx`. Local OSS (Kokoro/Piper) always included; 3rd-party engines surface through the same merged list.-- [ ] **Pipeline Audio — music generation + VO mux (Phase 4c.2 / 4d.2).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c (user-upload + library + picker) **shipped 2026-05-16**; 4d music-bed mux **shipped 2026-05-16**. Remaining:- - **4c.2: Local OSS music generation.** MusicGen via a Python sidecar mirroring the image-gen wiring; new `'gen'` source on `stages.audio.music`. Plug into the same `listMusicLibrary` so generated tracks appear alongside uploads. Investigation needed first: pick a generator. MusicGen-MLX is local but bounded ~30s without sliding-window stitching; AudioLDM2 is older; Suno is the cleanest UX but commercial. ~150 LOC for the AudioStage button + queue routing once the generator is picked.- - **4c.3: 3rd-party music engine stubs.** Same UI affordance as the VO engines — once 4c.2 lands the abstraction, 3rd-party engines plug in as sibling sources.- - **4d.2: VO line muxing into the CD stitch.** Today's mux only lays the music bed; per-line VO is unmixed. Walk `storyboards.scenes[].dialogue` to map each audio line to a scene, compute scene-start offsets from the per-clip durations (already in `buildTimelineClips`), then build an ffmpeg filter_complex that places each line at `sceneStart + lineOffsetInScene` and ducks the music bed underneath. Open question worth real-world testing: gap-between-lines heuristic (fixed 800ms? scene-length-aware? based on prose pacing?). Touch sites: `server/services/pipeline/audioMux.js` (extend `muxMusicBed` to `muxPipelineAudio` or add a sibling export), `server/services/creativeDirector/stitchRunner.js#maybeMuxPipelineAudio` (compute timing from `clips[]` + storyboards mapping).-- [ ] **Lift `runFfmpegProcess({ args, signal, stderrTailBytes }) → { ok, reason }` into `server/lib/ffmpeg.js`.** Three call sites today share the spawn → stderr-tail → close → SIGTERM-on-abort pattern: `audioMux.js#runFfmpeg`, `server/lib/ffmpeg.js#upscaleVideo2x`, `server/lib/ffmpeg.js#optimizeForStreaming`. `videoTimeline/local.js` has a fourth variant with per-line broadcast that complicates a full migration — leave that one local. The two simpler call sites collapse to one-liners. Surfaced from /simplify on Phase 4d.-- [ ] **Scene-level wardrobe picking (Cluster A2 follow-up).** The wardrobe data model + per-character editor shipped 2026-05-16, but downstream scene prompts don't yet know which outfit a character is wearing in a given panel/scene. Two design questions to settle first: (1) does the LLM scene-extractor guess from prose, or does the user pick per-scene? (2) does the prompt-composer append the wardrobe's description after `physicalDescription` (additive), or substitute the body fields the wardrobe overrides (less prone to outfit-and-physical contradicting each other)? Reasonable v1: per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes, with a wardrobe-picker dropdown next to each named character. Touch sites: `server/lib/sceneExtractor.js` (output schema + LLM prompt), `server/lib/scenePrompt.js#buildScenePrompt` (composer), `client/src/components/pipeline/stages/StoryboardsStage.jsx` (per-scene wardrobe picker chips).-- [ ] **Extract `sanitizeListWith(raw, sanitizer, cap)` helper in `server/lib/storyBible.js`.** Three sites today walk an array calling a per-item sanitizer + capping length: `sanitizeBibleList`, `sanitizeWardrobeList`, the per-kind `cleanStringArray`. Net negative LOC after extraction. Surfaced from /simplify on the Cluster A wardrobes work.-- [ ] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)` if a third caller appears.** Today `UniverseCanon.jsx#handlePatchEntry` and `NounsStage.jsx#handlePatchEntry` are 95% identical (optimistic UI update + `updateUniverse` PATCH + on-success reconcile). Extract into `client/src/hooks/useCanonPatch.js` so the third caller doesn't fork the pattern. YAGNI at two call sites today. Surfaced from /simplify on the Cluster A setting-metadata work.-- [ ] **AbortSignal listener cleanup in `audioMux.js#runFfmpeg`.** Today the `signal.addEventListener('abort', kill, { once: true })` is never removed on normal completion. Only a leak if the same `AbortController` is reused across many calls — the stitch step doesn't yet pass a signal, so this is theoretical. Fix when wiring real cancellation: capture the handler ref + `signal.removeEventListener('abort', handler)` in both `close` and `error` paths. Surfaced from /simplify on Phase 4d.-- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })` helper in `server/lib/fileUtils.js`.** Three call sites today follow the same readdir + filter-by-extension + stat-per-entry shape: `server/services/loras.js#listLoras` (sidecar reads), `server/services/imageGen/local.js#listGallery` (civitai-aware fields), `server/services/pipeline/musicLibrary.js#listMusicLibrary`. Each carries domain-specific per-entry mapping, so the shared helper takes a `mapEntry(dirent, statResult) → entry|null` callback. Saves ~15 LOC at each site plus a single fix-point for future "use `readdir(withFileTypes:true)` to skip the stat when only `.isFile()` is needed" optimization. Surfaced from the /simplify pass on Phase 4c.-- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.-- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.-- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** `server/services/pipeline/seasons.js#deleteSeason` reassigns each child issue via `issuesSvc.updateIssue(..., { skipRenumber: true })` in a loop, then runs one final `recomputeIssueNumbersForSeries`. Each `updateIssue` still calls `writeState` on `pipeline-issues.json`, so a 50-issue volume = 51 sequential `atomicWrite` calls. Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` that does one `readState` + N in-memory mutations + one `writeState` + one renumber. Surfaced from /simplify on the volume-ordered numbering fix (2026-05-16).-- [ ] **`useMediaAnnotations.getCardProps(key)` helper.** The 4 gallery pages (`VideoGen.jsx`, `ImageGen.jsx`, `MediaCollectionDetail.jsx`, `MediaHistory.jsx`) repeat `starred={!!annotations[key]?.starred} hasNote={!!annotations[key]?.anyNote}` at 6 sites total. A single `getCardProps(key) → { starred, hasNote, onToggleStar }` helper on the hook collapses each site to `{...getCardProps(item.key)}` and removes the `anyNote` vs `note` foot-gun this PR had to chase across 4 files. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).-- [ ] **Cache `resolveGlobalDisplayName()` settings read.** Every annotation write reads `data/settings.json` to resolve `sharingDisplayName`. Cheap, but called per PATCH (sharing export is debounced 2s, but `setAnnotation()` is not). Either memoize for ~30s in `server/services/sharing/annotationIdentity.js`, or invalidate on a `settings:updated` event. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).-- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** A peer's debounced annotation flush re-broadcasts even when their record's contents are byte-identical. The client's `onUpdate` always calls `setAnnotations`, re-rendering every gallery card. Add a JSON-equal short-circuit before the setState. Theoretical until observed; speculative micro-opt. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).-- [ ] **Hoist identity lookup out of `liftLegacyEntry` loop in `mediaAnnotations.js#readAll()`.** Post-migration-012 the `for (...) await liftLegacyEntry` loop is a microtask penalty per entry with no real I/O. Pre-migration it does `getInstanceId() + resolveLocalAuthorName()` per legacy entry serially. Make `liftLegacyEntry` synchronous and pass `localInstanceId, defaultAuthorName` in once. Surfaced from /simplify on the multi-author annotations PR (2026-05-16).+- **Dynamic Skill Marketplace** — self-generating skill templates from task patterns.+- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides.+- **Chronotype-Aware Scheduling** — integrate genome sleep/circadian markers into CoS task scheduling (closes GOALS secondary goal).+- **Apple Health live sync** — iOS bulk historical import + live sync (closes GOALS "Apple Health integration planned").