Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(universe-canon): inline-edit descriptions, Render All per kind, compact single-kind view
[._.]/ Adam Eivy3b6906ed11ae
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ab6fcc5d4e..fc567bf425 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -16,6 +16,12 @@- **PLAN.md — CODEX 5.5 review residue folded in.** Triaged the 2026-04-25 CODEX 5.5 product/engineering review: confirmed the six concrete bugs (Brain Feeds + Time Capsule nav coverage, `/cos/scripts` dead target, `/ask` full-height workaround, client lint, route/nav contract tests) are all shipped, and added 15 unaddressed strategic items to PLAN.md under a new `### CODEX 5.5 review residue` Backlog section (perf/bundle, polling consolidation, client error reporter, network exposure UI, unified Review Queue, health provenance chips, dashboard intent layouts, autonomy guardrails, onboarding capability map, mobile task flows, operating-loop dashboard, sidebar IA collapse, visual modes, decision/provenance pattern, teaching empty states). Enriched the existing Knowledge Legacy Future Idea with the bundle scope from the review.+- **Canon entries (characters / places / objects) now inline-edit their description.** The card body's main description (`physicalDescription` for characters, `description` for places & objects) was previously a static `<p>` with no edit affordance — locked or not. Unlocked rows now render a buffered-on-blur `<textarea>` next to the existing per-row controls; the legacy `description` field on pre-migration characters pre-fills the editor and migrates to `physicalDescription` on first save. The pipeline series view (`NounsStage`) intentionally stays read-only because its `KINDS` config omits `descField`.++- **Universe Canon section: Render All per kind + compact single-kind view + lock-indicator dedupe.** New "Render all (N)" button in each canon kind's toolbar that fires reference renders in parallel for every entry with a description and no existing image (the per-entry `renderingJobs` map already handles concurrent settle independently). When the canon section is already scoped to one kind (`?kind=places`, sidebar deep-links), the inner `<section>` wrapper + duplicate icon + "Places 25" header are dropped so the page no longer shows a nested card; the controls strip (count, Render all, bulk lock) stays as a slim toolbar above the list. The multi-kind view keeps its current chrome. Removed the redundant "🔒 LOCKED" chip from the card title — the lock toggle button on the right already conveys locked state via icon + accent color.++- **PLAN.md cleanup.** Removed 9 already-completed `[x]` items (Universe-as-Canon Phase 2, Pipeline continuity / approval, scattered Code quality / Better-audit / Deferred-from-better entries) — those sections went away or shrunk since DONE.md is the canonical archive. Reorganized the Backlog: 32 items requiring decision/design or waiting on a precondition moved to a new `## Blocked on decision / design (skip for \`/claim\`)` section at the bottom, split into Audio/Video/Image gen, Voice/agents, Large product/UX redesigns, and Trigger-gated subsections. The remaining Backlog is now items an agent can pick up cold via `/claim` — concrete file:line bugs, scoped refactors, and well-specified small features. 218 → 200 lines.+## Fixed- **Sharing/annotation-merge hardening — 5 v2.1.0 residue items.** Outgoing annotation manifests now honor per-bucket `displayNameOverride` (previously all buckets got the global name); peer payloads with missing/invalid `updatedAt` are dropped on import instead of winning LWW via a `now`-fallback; future-skewed peer timestamps are clamped to local-now to stop one bad clock from ratcheting every subsequent merge; `peerInstanceId === 'unknown'` (or empty) is refused on import to match the existing outgoing-path guard; and `exportAnnotationsToBucket` now skips both the asset-dir scan AND the record write when local has no annotations and no prior record exists, so a fresh-install annotation edit doesn't fan an empty manifest into every auto-merge bucket.diff --git a/PLAN.md b/PLAN.mdindex 59e01103f7..fa95c25c2e 100644--- a/PLAN.md+++ b/PLAN.md@@ -10,48 +10,15 @@ _Nothing currently parked — pick the next item from the Backlog._## Backlog-### Universe-as-Canon — Phase 2 + extensions--- [x] ~~**Drop the default `characters` category.**~~ Shipped via the Universe Builder redesign Phase A migration; default `characters` bucket retired, variations backfilled into `universe.characters[]`.-- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.-- [x] ~~**arcPlanner prompt context — include canon characters/places/objects.**~~ Shipped via the Universe Builder redesign Phase B (`renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up still open: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.---### Pipeline continuity / approval--- [x] ~~[season-lock-aware-arc-resolve] **Make `resolveVerifyIssues` respect per-season locks.**~~ Shipped via `mergeSeasonsWithLocks` inside `commitSeasonsWithRemap` (`server/services/pipeline/arcPlanner.js`) — auto-resolve and `/arc/generate` now restore locked seasons field-for-field over LLM rewrites and re-insert any locked season the LLM dropped from the new shape, mirroring the per-field arc-lock pattern.-- [x] ~~[pipeline-text-stages-worldentitiessummary] **Add `worldEntitiesSummary` to text stages.**~~ Shipped via `renderEntitiesSummary` in `server/lib/universePromptRenderers.js` (compact one-line-per-kind synopsis, 8 entries max per kind) + plumbed through `loadWorldContext` (arc context) and `textStages.buildStageContext` (text context) + migration 027 + prompt updates to `pipeline-prose.md` / `pipeline-teleplay.md` / `pipeline-comic-script.md`.-- [x] ~~[bible-schema-speech-pattern-field] **Add a dedicated speech-pattern field to the character bible schema.**~~ Shipped — `speechPattern` field added to `BIBLE_LIMITS`, `PROMPT_FIELDS[CHARACTER]`, `sanitizeCharacter`, `MERGE_CONFIG.character.userEditable`, `universeCharacterExpand`'s `STRING_FIELDS`, `universeCharacterSheet`'s rendered prompt, `CharacterDetailEditor.jsx` UI, the `universe-character-expand` prompt template + JSON contract, and the prose/teleplay/comic-script character render mustache. Migration 027 updates existing installs cleanly.--### Creative Director / Audio--- [ ] [render-slowness-on-long-sessions-per-scene-render] **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] **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.--### Video Gen (LTX-2.3)--- [ ] [native-fflf-deeper-test-on-real-keyframe-pairs] **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.-### Voice agent-- [ ] [voice-cos-tool-expansion-calendar-today-calendar] **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] **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] **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] **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] **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] **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] **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] **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] **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] **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- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs.-- [ ] [world-builder-phase-2-external-sd-api-per-bucket] **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] **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.### Sharing — performance follow-ups (deferred from content-addressed asset dedup, 2026-05-18)@@ -63,21 +30,14 @@ _Nothing currently parked — pick the next item from the Backlog._- [ ] [export-isplainobject-helper-from-server-lib-objects] **Export `isPlainObject` from `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` plain-object check is inlined at 14 sites across the codebase: `server/lib/objects.js:27` (private), `server/lib/mediaModels.js:183` (private), `server/services/calendarAccounts.js:11`, `messageAccounts.js:13`, `messagePlaywrightSync.js:29`, `loras.js:65`, `mortalLoomStore.js`, `updateChecker.js:93`, `meatspacePost.js:75`, `dataSync.js:112`, `featureAgents.js:108`, `taskSchedule.js:1900`, `pipeline/issues.js:673`, and (newly added 2026-05-19) `server/services/sharing/exporter.js#loadAssetHashCache`. Promote the helper to a named export in `objects.js`, add a row to `server/lib/README.md`, and migrate the call sites. Surfaced by /simplify during `[sharing-exporter-cache-sourcefile-hash-by-mtime]`; deferred to keep that PR scoped.- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.-- [x] [auto-save-after-expand-can-clobber-concurrent] ~~**Auto-save after expand can clobber concurrent canon edits.**~~ **Fixed in Phase B Copilot iteration 13** — both `handleExpand`'s auto-save and `handleSave`'s manual-save (when `canonDirty`) now refetch the server's canon via `getUniverse(selectedId)` and merge local additions with `mergeCanonByName` before the update payload is sent. Concurrent edits from NounsStage/other tabs are preserved on identity collision.-- [x] [canon-merge-can-revert-concurrent-deletions] ~~**Canon-merge can revert concurrent deletions/renames.**~~ **Fixed in Phase B Copilot iteration 15** — handleExpand records each merge's NEW canon entries in a `pendingCanonAdditionsRef` sidecar; handleSave + handleExpand auto-save + handleCanonChange now merge ONLY that ledger onto the refetched server canon (not the full stale draft). Concurrent deletions in other tabs/surfaces are preserved because the deleted entry isn't in the ledger, so the server response (which already lacks it) wins.- [ ] [extract-useswipenav-hook-lib-clipboard-js] **Extract `useSwipeNav` from `MediaLightbox`.** Clipboard half of the original entry already shipped (`client/src/lib/clipboard.js`); `client/src/hooks/useSwipeNav.js` also exists for the swipe pattern but `MediaLightbox` still inlines its own swipe state. Migrate `MediaLightbox` swipe to `useSwipeNav` so the lightbox + any future mobile-swipe surface share one hook.- [ ] [route-medialightbox-settings-drawer-through] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.-- [ ] [useasyncaction-post-unmount-setstate-guard-add] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.-- [ ] [scene-level-wardrobe-picking-per-scene] **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-usecanonpatch-universe-setuniverse] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.- [ ] [apicore-request-arraybuffer-response-type] **Add an `arraybuffer` responseType escape hatch to `apiCore.request()`.** Two TTS audition helpers (`client/src/services/apiVoice.js#testTts` and `client/src/services/apiPipeline.js#previewPipelineTtsVoice`) currently bypass `request()` and do raw `fetch` because the shared helper assumes JSON. Collapsing both onto `request(endpoint, { ..., responseType: 'arraybuffer' })` would drop ~25 LOC of duplicated error-shaping + dedupe the path. Surfaced by /simplify during `[voice-picker-on-character-cards-voiceid-binding]`; deferred to keep that PR scoped to the picker. Not blocked on anything.- [ ] [extract-usependinglistrows-hook] **Extract `usePendingListRows({ persisted, requiredColumn, idPrefix, onChange }) → { merged, isPending, addRow, updateRow, removeRow }`.** Surfaced by /simplify during `[wardroberow-migrate-to-userowdraft]`. `WardrobeSection` in `client/src/components/pipeline/CanonCard.jsx:155-211` and `CharacterDetailEditor` list-section block in `client/src/components/universe/CharacterDetailEditor.jsx:202-278` now share substantial structure: pending rows held client-side until a required column fills, then promoted to `onChange`/`patchList`, with an index space that concatenates `[...persisted, ...pending]` and an `isPending(idx)` partition. Estimated ~70 LOC savings across both call sites. Two load-bearing details to preserve in the extraction: (1) `WardrobeSection` mints `wd-<uuid>` ids that round-trip verbatim; `CharacterDetailEditor` mints `pending-<key>-<uuid>` that get stripped at promotion — pass an `idPrefix` and a `stripIdOnPromote` flag (or unify both onto server-shaped ids and drop the strip); (2) hook is per-list (one instance per `LIST_SECTION` in `CharacterDetailEditor`, one in `WardrobeSection`), NOT per-component. Deferred to keep this PR focused on the `useRowDraft` migration; revisit when a third caller appears or the parallel divergence drifts.- [ ] [client-tests-for-deep-routing-drag-smoke-tests-for] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).-- [ ] [shallow-equal-guard-in-usemediaannotations-socket] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.- [ ] [sweep-provider-type-tui-inline-checks-in-client] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.- [ ] [datasync-migrate-categories-to-atomicwrite] **Migrate all `dataSync.js` categories to `atomicWrite`.** Every category (`goals`, `character`, `digitalTwin`, `meatspace`, `universe`, `pipeline`) inlines `ensureDir + writeFile + JSON.stringify(..., null, 2)` — 6+ duplicate sites. `server/lib/fileUtils.js:124` exports `atomicWrite(path, data)` that handles all three steps as a temp+rename atomic write. One-line collapse per site + meaningful partial-write protection for the larger pipeline JSON files (which other services write concurrently). Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`; deferred to keep that PR focused on the new categories.- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.-- [x] [extract-flatten-canon-descriptor-fragments-helper] ~~**Extract `flattenCanonDescriptorFragments(fragments, { separator, trailingPeriod })` into `server/lib/canonPrompt.js` (+ client mirror).**~~ Shipped — `flattenCanonDescriptorFragments` + `mapCanonDescriptorFragments` added to `server/lib/canonPrompt.js` and mirrored to `client/src/lib/canonPrompt.js`. All 6 inline sites migrated: server `canonPrompt.js`/`scenePrompt.js`/`services/pipeline/visualStages.js`/`services/universeBuilder.js` + the two client mirrors. The `mapCanonDescriptorFragments` companion supports the scene-prompt budget-truncator that needs the array form.- [ ] [consolidate-cert-path-constants] **Consolidate `CERT_DIR`/`CERT_PATH`/`KEY_PATH`/`META_PATH` constants.** Re-declared in `scripts/setup-cert.js`, `scripts/open-ui-in-browser.js`, `server/services/certProvisioner.js`, and `server/services/certRenewer.js` (4 sites). Surfaced by `/simplify` during the first-run HTTPS-auto-flip fix (2026-05-19); deferred to keep that PR scoped. Candidate home: `lib/certPaths.js` (alongside `lib/tailscale-https.js` so both runtime + bootstrap can import).- [ ] [imagegen-local-defer-module-load-side-effects] **Defer module-load side effects in `server/services/imageGen/local.js`.** Line 32 runs `IMAGE_MODELS = Object.fromEntries(getImageModels().map(...))` at module evaluation — `getImageModels()` calls `lib/mediaModels.js#loadMediaModels` which `mkdirSync`s `dirname(REGISTRY_FILE)` and `writeFileSync`s a default registry if missing. Any importer that loads via a mocked `PATHS.data` (e.g. `routes/pipeline.test.js` → `routes/pipeline.js` → `routes/universeBuilder.js` → `services/universeBuilderCollectionHook.js` → `services/imageGen/local.js`) fails on `mkdirSync('/mock/data')`. Worked around in 2026-05-19 by lazy-importing `readImageSidecar` in `universeBuilderCollectionHook.js`; real fix is to convert `IMAGE_MODELS` + sibling top-level constants to lazy getters and audit callers. Affects every consumer of `local.js` exports today.- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.@@ -112,24 +72,15 @@ _Nothing currently parked — pick the next item from the Backlog._### Better-audit residue-- [x] [high-code-server-services-cos-js-3113-remove-node] ~~**[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).~~ **Shipped 2026-05-17** — `init()` is now exported and called explicitly from `server/index.js` (alongside the other `*.init()` calls); module-level auto-init removed entirely so the test guard is no longer needed.- [ ] [high-tests-add-coverage-for-server-services-shell] **[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.)-- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — **premise eroded; revisit when a 3rd caller lands.** Original PLAN flagged 4 components but `VisualStylePicker` no longer exists and `AddToCollectionMenu` / `BulkTargetPicker` no longer use portal positioning. Today the pattern lives in exactly two components (`client/src/components/ThemeSwitcher.jsx` and `client/src/components/media/CollectionPickerShell.jsx`) — both implement portal-with-fixed-positioning + `useLayoutEffect` measurement + rAF-coalesced scroll/resize listeners. With only 2 callers the abstraction isn't worth the indirection; extract when a third surface needs the same shape.- [ ] [extract-requiretoolkit-pattern-to-runner-js] **[MEDIUM][CODE]** Extend the `requireToolkit()` pattern from `server/services/providers.js` to `server/services/runner.js` — 13 sites of `if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized')` still inlined there (lines 27, 144, 218, 332, 343 + others). Surfaced by /simplify during the better-audit residue refactor bundle; left out of that PR to keep scope tight. Should reuse the same `ServerError({ status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` shape providers.js now throws.### Pipeline — deferred- [ ] [wire-storyboards-scene-video-rendering-as-a] **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] **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] **Versioning / diff view per stage.** Persist last N `lastRunId` snapshots; offer a diff modal.-- [ ] [episode-video-provider-picker-runwayml-third-party] **Episode-video provider picker (RunwayML / third-party).** Once the abstraction lands, expose picker on EpisodeVideoStage.-- [ ] [comic-book-pdf-export-once-stages-comicpages] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.- [ ] [voice-controlled-stage-advancement-register] **Voice-controlled stage advancement.** Register pipeline stage navigation actions in `voice/tools.js`.-- [ ] [ai-assisted-panel-scene-prompt-generation-reserve] **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.- [ ] [backport-pre-023-migrations-to-_lib] **Back-port pre-023 prompt-replace migrations onto `scripts/migrations/_lib.js`.** 003 / 004 / 005 / 006 / 010 / 013 / 019 all clone the inline `applyMigration` + per-file scan + customized-skip warning pattern that `_lib.js` now centralizes. Wrap any `OLD_SHIPPED_MD5: string` entries (003 / 004 / 006) into single-element arrays to match the `accepted[filename]: string[]` shape. Drop ~70 LOC per migration; nothing changes behaviorally so the only risk is mis-typed hashes — review each diff alongside a re-run of its test against the `_testHelpers.js` `runPromptMigrationTests`. Settled-history migrations have a higher rewrite-bar than active code, so a separate PR with focused review is appropriate. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.-- [ ] [setup-data-import-drift-tables-from-migrations] **`setup-data.js` should import drift tables from each migration file.** `SHIPPED_PROMPT_OLD_MD5` + `SHIPPED_PROMPT_NEW_MD5` in `scripts/setup-data.js:139-196` manually mirror the `ACCEPTED_OLD_MD5` + `NEW_SHIPPED_MD5` exports each migration file already maintains. The mirror is hand-edited every time a migration ships and is the most likely place to drift. After `[backport-pre-023-migrations-to-_lib]` lands, every prompt-replace migration will export those constants — `setup-data.js` can build `SHIPPED_PROMPT_OLD_MD5` / `SHIPPED_PROMPT_NEW_MD5` by `import * as m025 from './migrations/025-idea-stage-character-detail.js'`-style sweep (or by glob+dynamic import) and removing the mirror entirely. Single source of truth, no hand sync. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.-- [ ] [parallelize-applypromptreplacemigration-files] **Parallelize `applyPromptReplaceMigration` per-file scan.** Today every prompt-replace migration covers exactly one file, so the serial `for (await readFile…)` loop in `scripts/migrations/_lib.js` costs nothing. When the first multi-file migration lands, fold the loop into `Promise.all(Object.keys(accepted).map(async filename => …))` and accumulate the `{ updated, alreadyCurrent, skipped }` counters post-flight. Theoretical until needed.-- [ ] [shots-aware-scene-output-contract-partial-split] **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] **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.### CODEX 5.5 review residue (deferred from product/engineering review, 2026-04-25)@@ -145,26 +96,14 @@ The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule n**Product UX — concrete, medium scope**-- [ ] [codex5-unified-review-queue] **[P1][PRODUCT]** Cross-domain Review Queue (the "inbox zero" for PortOS). One page (`/review` or `/inbox`) that collects: Brain inbox items needing classification, Ask answers ready for promotion, CoS completed tasks pending approval, Message drafts awaiting send, Health anomalies pending acknowledgement, and failed syncs / imports / backups. Each row has accept / dismiss / drill-down. Build the surface aggregator first, then opt each producer into it.-- [ ] [codex5-health-provenance-chips] **[P1][HEALTH][TRUST]** Extend Ask's source-chip pattern to MeatSpace / genome / death clock / longevity views. Each insight tags itself as `data-backed | inferred | experimental | speculative` with a "what would change this?" explainer and a clinician-export view for blood + lifestyle data. Pairs with `[codex5-decision-provenance-everywhere]`.- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Intent-named layouts + morning default + widget suggestions. Rename built-in layouts to user-intent (`Morning Review`, `Deep Work`, `Ops`, `Health`, `Agent Watch`); update `server/services/dashboardLayouts.js` seeded built-ins. Add a "make this my morning default" toggle that activates a layout in a configured time window. Add a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.-- [ ] [codex5-autonomy-guardrails] **[P1][AUTONOMY]** Per-domain autonomy levels + dry-run + budgets + while-away briefing. Today CoS has a single global autonomy posture. Split into per-domain knobs (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) each with `off | dry-run | execute`. Add spending / time / token budgets per domain. Add a "what did agents do while I was away?" digest pulling from the existing CoS / agent run logs into a daily briefing card.- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.-- [ ] [codex5-mobile-task-flows] **[P2][MOBILE]** Five phone-native flows: (1) system health + one-tap restart of an app, (2) one-tap voice/text Brain capture, (3) "what should I do now?" Ask, (4) approve / reject a CoS result from a notification, (5) log a health/lifestyle event in ≤10 seconds. Each should be reachable in ≤2 taps from a Tailscale-launched mobile session.--**Product UX — vision / large redesigns**--- [ ] [codex5-operating-loop-dashboard] **[P0][PRODUCT]** Top-level daily command center / operating loop. Replace the homepage-equivalent dashboard with 3–5 prioritized cards: Critical System Issues, Today's Calendar Commitments, Active Agent Work, Goal Next Action, Health/Recovery Signal. Each card gets one primary action + one drill-down. Add an explicit day-mode selector (`Focus | Ops | Health | Review | Autonomous`) that re-ranks the cards. Pulls signals from Digital Twin, chronotype, calendar, goals, and CoS. Treat as a multi-PR design spike — investigation + mockups first.-- [ ] [codex5-sidebar-collapse-ia] **[P1][IA]** Collapse sidebar to 8–10 top-level domains + Pinned + Recent. Today the sidebar carries deep nested tabs at the same level as top-level domains; review recommends `Home, Ask, Apps, CoS, Brain, Calendar, Goals, Health, Dev Tools, Settings` only at the top level with deep tabs pushed into each page's local tab bar and Cmd+K. Add Pinned + Recent sections driven by the user's actual working set. Touch every consumer of `Layout.jsx`'s nav tree; expect alphabetical ordering convention to survive.-- [ ] [codex5-visual-modes] **[P2][DESIGN]** Product-specific visual modes: `Ops` (dense terminal-like, minimal animation), `Focus` (quiet, spacious, only next actions), `Health` (warmer, less cyber, more explanation), `Review` (document-like, optimized for reading + decisions). Tied to the day-mode selector from `[codex5-operating-loop-dashboard]`. Extend the existing Tailwind token system rather than introducing a parallel theming layer.-- [ ] [codex5-decision-provenance-everywhere] **[P2][DESIGN]** Decision/provenance pattern across CoS, Insights, Health, Goals, Dashboard widgets. Each AI-generated or rule-driven surface answers: "Why am I seeing this?", "What data backs this?", "What changed?", "What can I do next?" Reuse the Ask source-chip component. Pairs with `[codex5-health-provenance-chips]`.-- [ ] [codex5-empty-states-teach] **[P3][ONBOARDING]** Workflow-teaching empty states. Each "no data" state replaces "Nothing here" with a setup hint that names the next action: "Connect calendar to unlock schedule-aware goals", "Add birth date + genome file to unlock longevity estimates", "Capture 10 notes to improve Ask Yourself", "Configure one API provider to enable autonomous CoS". Inventory empty states first, then prioritize by which pages new users hit earliest.-### Design spikes / brainstorms (investigation-first)+### Deferred from better/2026-05-19-Items here need a research/design pass before any code lands — `/claim` should skip them by default.+- [ ] [move-usenextevalcountdown-to-hooks] **Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** `client/src/components/cos/useNextEvalCountdown.js` is a generic `useX` countdown hook living under `components/`, which the new "Module Organization" convention in CLAUDE.md places exclusively under `client/src/hooks/`. The other `useX`-named functions outside `hooks/` (`useThemeContext`, `useCitySettingsContext`, `useTokenEntries`) are context-consumer or pure `useMemo` helpers conventionally co-located with their providers — `useNextEvalCountdown` doesn't fit that exception. Surfaced by /simplify during the module-discovery PR; deferred to keep that PR scoped to infrastructure.-- [ ] [whole-episode-audio-generation-strategy-stop] **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.+- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.---@@ -197,13 +136,54 @@ God-file decomposition candidates — none are bugs; pick up when touching the f----## Deferred from better/2026-05-19+## Blocked on decision / design (skip for `/claim`)-- [x] ~~**Client formatter dedupe — signatures differ, skipped.**~~ Shipped — `formatTimecode`, `formatDurationSec`, and `formatDateShort` were added to `client/src/utils/formatters.js`; all 3 sites (`VideoTimelineEditor.jsx`, `VideoTimeline.jsx`, `brain/tabs/ImportTab.jsx`) now import the shared helpers.+Items here need a research / design pass, an explicit decision, or a precondition to fire before any code can land — `/claim` should skip them by default. Move an item back up to the Backlog once the gating question is answered.-- [ ] [move-usenextevalcountdown-to-hooks] **Move `useNextEvalCountdown` from `components/cos/` to `client/src/hooks/`.** `client/src/components/cos/useNextEvalCountdown.js` is a generic `useX` countdown hook living under `components/`, which the new "Module Organization" convention in CLAUDE.md places exclusively under `client/src/hooks/`. The other `useX`-named functions outside `hooks/` (`useThemeContext`, `useCitySettingsContext`, `useTokenEntries`) are context-consumer or pure `useMemo` helpers conventionally co-located with their providers — `useNextEvalCountdown` doesn't fit that exception. Surfaced by /simplify during the module-discovery PR; deferred to keep that PR scoped to infrastructure.+### Audio / Video / Image gen-- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.+- [ ] [render-slowness-on-long-sessions-per-scene-render] **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] **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.+- [ ] [native-fflf-deeper-test-on-real-keyframe-pairs] **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.+- [ ] [world-builder-phase-2-external-sd-api-per-bucket] **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.+- [ ] [rich-text-editor-for-prose-stage-replace-plain] **Rich-text editor for prose stage.** Replace plain textarea in `ProseStage.jsx` — reuse Writers Room editor or pick a minimal markdown editor.+- [ ] [episode-video-provider-picker-runwayml-third-party] **Episode-video provider picker (RunwayML / third-party).** Once the abstraction lands, expose picker on EpisodeVideoStage.+- [ ] [comic-book-pdf-export-once-stages-comicpages] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.+- [ ] [ai-assisted-panel-scene-prompt-generation-reserve] **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.+- [ ] [whole-episode-audio-generation-strategy-stop] **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.++### Voice / agents++- [ ] [voice-cos-tool-expansion-calendar-today-calendar] **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`).+- [ ] [voice-agent-vision-fallback-ui-describe-visually] **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.++### Large product / UX redesigns++- [ ] [writers-room-phases-4-5-phase-4-synced-prose] **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] **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] **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] **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] **M34 P5-P7 — Digital Twin.** Multi-modal capture (voice/video/image identity sources), advanced testing, personas. Ties to GOALS.md "Multi-Modal Identity Capture".+- [ ] [codex5-unified-review-queue] **[P1][PRODUCT]** Cross-domain Review Queue (the "inbox zero" for PortOS). One page (`/review` or `/inbox`) that collects: Brain inbox items needing classification, Ask answers ready for promotion, CoS completed tasks pending approval, Message drafts awaiting send, Health anomalies pending acknowledgement, and failed syncs / imports / backups. Each row has accept / dismiss / drill-down. Build the surface aggregator first, then opt each producer into it.+- [ ] [codex5-health-provenance-chips] **[P1][HEALTH][TRUST]** Extend Ask's source-chip pattern to MeatSpace / genome / death clock / longevity views. Each insight tags itself as `data-backed | inferred | experimental | speculative` with a "what would change this?" explainer and a clinician-export view for blood + lifestyle data. Pairs with `[codex5-decision-provenance-everywhere]`.+- [ ] [codex5-autonomy-guardrails] **[P1][AUTONOMY]** Per-domain autonomy levels + dry-run + budgets + while-away briefing. Today CoS has a single global autonomy posture. Split into per-domain knobs (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) each with `off | dry-run | execute`. Add spending / time / token budgets per domain. Add a "what did agents do while I was away?" digest pulling from the existing CoS / agent run logs into a daily briefing card.+- [ ] [codex5-mobile-task-flows] **[P2][MOBILE]** Five phone-native flows: (1) system health + one-tap restart of an app, (2) one-tap voice/text Brain capture, (3) "what should I do now?" Ask, (4) approve / reject a CoS result from a notification, (5) log a health/lifestyle event in ≤10 seconds. Each should be reachable in ≤2 taps from a Tailscale-launched mobile session.+- [ ] [codex5-operating-loop-dashboard] **[P0][PRODUCT]** Top-level daily command center / operating loop. Replace the homepage-equivalent dashboard with 3–5 prioritized cards: Critical System Issues, Today's Calendar Commitments, Active Agent Work, Goal Next Action, Health/Recovery Signal. Each card gets one primary action + one drill-down. Add an explicit day-mode selector (`Focus | Ops | Health | Review | Autonomous`) that re-ranks the cards. Pulls signals from Digital Twin, chronotype, calendar, goals, and CoS. Treat as a multi-PR design spike — investigation + mockups first.+- [ ] [codex5-sidebar-collapse-ia] **[P1][IA]** Collapse sidebar to 8–10 top-level domains + Pinned + Recent. Today the sidebar carries deep nested tabs at the same level as top-level domains; review recommends `Home, Ask, Apps, CoS, Brain, Calendar, Goals, Health, Dev Tools, Settings` only at the top level with deep tabs pushed into each page's local tab bar and Cmd+K. Add Pinned + Recent sections driven by the user's actual working set. Touch every consumer of `Layout.jsx`'s nav tree; expect alphabetical ordering convention to survive.+- [ ] [codex5-visual-modes] **[P2][DESIGN]** Product-specific visual modes: `Ops` (dense terminal-like, minimal animation), `Focus` (quiet, spacious, only next actions), `Health` (warmer, less cyber, more explanation), `Review` (document-like, optimized for reading + decisions). Tied to the day-mode selector from `[codex5-operating-loop-dashboard]`. Extend the existing Tailwind token system rather than introducing a parallel theming layer.+- [ ] [codex5-decision-provenance-everywhere] **[P2][DESIGN]** Decision/provenance pattern across CoS, Insights, Health, Goals, Dashboard widgets. Each AI-generated or rule-driven surface answers: "Why am I seeing this?", "What data backs this?", "What changed?", "What can I do next?" Reuse the Ask source-chip component. Pairs with `[codex5-health-provenance-chips]`.+- [ ] [codex5-empty-states-teach] **[P3][ONBOARDING]** Workflow-teaching empty states. Each "no data" state replaces "Nothing here" with a setup hint that names the next action: "Connect calendar to unlock schedule-aware goals", "Add birth date + genome file to unlock longevity estimates", "Capture 10 notes to improve Ask Yourself", "Configure one API provider to enable autonomous CoS". Inventory empty states first, then prioritize by which pages new users hit earliest.++### Trigger-gated (waiting for a precondition)++- [ ] [scene-level-wardrobe-picking-per-scene] **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?+- [ ] [useasyncaction-post-unmount-setstate-guard-add] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.+- [ ] [extract-usecanonpatch-universe-setuniverse] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)`.** `UniverseCanon.jsx` + `NounsStage.jsx` 95% identical optimistic-patch handlers. Extract when a 3rd caller appears.+- [ ] [shallow-equal-guard-in-usemediaannotations-socket] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.+- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — **premise eroded; revisit when a 3rd caller lands.** Original PLAN flagged 4 components but `VisualStylePicker` no longer exists and `AddToCollectionMenu` / `BulkTargetPicker` no longer use portal positioning. Today the pattern lives in exactly two components (`client/src/components/ThemeSwitcher.jsx` and `client/src/components/media/CollectionPickerShell.jsx`) — both implement portal-with-fixed-positioning + `useLayoutEffect` measurement + rAF-coalesced scroll/resize listeners. With only 2 callers the abstraction isn't worth the indirection; extract when a third surface needs the same shape.+- [ ] [setup-data-import-drift-tables-from-migrations] **`setup-data.js` should import drift tables from each migration file.** `SHIPPED_PROMPT_OLD_MD5` + `SHIPPED_PROMPT_NEW_MD5` in `scripts/setup-data.js:139-196` manually mirror the `ACCEPTED_OLD_MD5` + `NEW_SHIPPED_MD5` exports each migration file already maintains. The mirror is hand-edited every time a migration ships and is the most likely place to drift. After `[backport-pre-023-migrations-to-_lib]` lands, every prompt-replace migration will export those constants — `setup-data.js` can build `SHIPPED_PROMPT_OLD_MD5` / `SHIPPED_PROMPT_NEW_MD5` by `import * as m025 from './migrations/025-idea-stage-character-detail.js'`-style sweep (or by glob+dynamic import) and removing the mirror entirely. Single source of truth, no hand sync. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.+- [ ] [parallelize-applypromptreplacemigration-files] **Parallelize `applyPromptReplaceMigration` per-file scan.** Today every prompt-replace migration covers exactly one file, so the serial `for (await readFile…)` loop in `scripts/migrations/_lib.js` costs nothing. When the first multi-file migration lands, fold the loop into `Promise.all(Object.keys(accepted).map(async filename => …))` and accumulate the `{ updated, alreadyCurrent, skipped }` counters post-flight. Theoretical until needed.+- [ ] [shots-aware-scene-output-contract-partial-split] **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.## Future Ideasdiff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 9521e5ca6a..db147a4f6f 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -14,6 +14,7 @@ import { useEffect, useRef, useState } from 'react';import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen } from 'lucide-react';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import useRowDraft from '../../hooks/useRowDraft';+import useFieldDraft from '../../hooks/useFieldDraft';import MediaJobThumb from './MediaJobThumb';import EntryCard from '../universe/EntryCard';import EntryThumbSlot from '../universe/EntryThumbSlot';@@ -53,6 +54,39 @@ function ChipPicker({ label, value, options, onChange }) {);}+// Inline editable description for the canon card's primary descriptor field.+// Read-only `<p>` when locked or no PATCH channel; buffered textarea otherwise+// (commits on blur via `useFieldDraft`, mirroring the WardrobeRow pattern).+// The bound value falls back to the legacy field (`description` on characters,+// `significance` on objects) so pre-migration entries pre-fill on first edit+// and migrate to the canonical field on save.+function DescriptionField({ entry, descField, fallbackField, max, editable, onCommit, placeholder }) {+ const stored = entry[descField];+ const fallback = fallbackField ? entry[fallbackField] : null;+ const seed = (typeof stored === 'string' && stored)+ || (typeof fallback === 'string' ? fallback : '')+ || '';+ const draft = useFieldDraft(seed, onCommit);+ if (!editable) {+ return (+ <p className="text-xs text-gray-400 mt-1 line-clamp-3 whitespace-pre-wrap">+ {seed || <em className="text-gray-600">No description yet.</em>}+ </p>+ );+ }+ return (+ <textarea+ value={draft.value}+ onChange={draft.onChange}+ onBlur={draft.onBlur}+ placeholder={placeholder}+ rows={3}+ maxLength={max}+ className="w-full mt-1 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 whitespace-pre-wrap"+ />+ );+}+function ReadonlyChip({ children }) {return (<span className="px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider bg-port-card border border-port-border text-gray-400">@@ -322,11 +356,6 @@ export default function CanonCard({aka {entry.aliases.join(', ')}</span>) : null}- {locked ? (- <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-port-accent/15 text-port-accent text-[9px] uppercase tracking-wider">- <Lock size={9} /> Locked- </span>- ) : null}{entry.sourceSeriesId ? (<SourceSeriesChipsourceSeriesId={entry.sourceSeriesId}@@ -347,9 +376,15 @@ export default function CanonCard({))}</div>) : null}- <p className="text-xs text-gray-400 mt-1 line-clamp-3 whitespace-pre-wrap">- {description || <em className="text-gray-600">No description yet.</em>}- </p>+ <DescriptionField+ entry={entry}+ descField={kind.descField || 'description'}+ fallbackField={kind.descFieldFallback || null}+ max={kind.descFieldMax}+ editable={!!onPatchEntry && !locked && !!kind.descField}+ onCommit={(v) => onPatchEntry?.(entry.id, { [kind.descField]: v })}+ placeholder={`Describe ${entry.name} (image-gen-ready prose)`}+ />{kind.key === 'places' && onPatchEntry && !locked ? (<div className="flex flex-wrap items-center gap-2 mt-2"><ChipPickerdiff --git a/client/src/components/pipeline/CanonCard.test.jsx b/client/src/components/pipeline/CanonCard.test.jsxindex 4d1cf2a467..7582e6cc98 100644--- a/client/src/components/pipeline/CanonCard.test.jsx+++ b/client/src/components/pipeline/CanonCard.test.jsx@@ -73,6 +73,87 @@ describe('CanonCard — "from series" provenance chip', () => {});});+describe('CanonCard — inline description editor', () => {+ const editableKind = {+ key: 'characters',+ label: 'Characters',+ descFor: (e) => e.physicalDescription || e.description || '',+ descField: 'physicalDescription',+ descFieldFallback: 'description',+ descFieldMax: 2000,+ };++ it('stays read-only when locked even with onPatchEntry wired', () => {+ const onPatchEntry = vi.fn();+ render(+ <CanonCard+ kind={editableKind}+ entry={{ ...baseEntry, physicalDescription: 'Tall.', locked: true }}+ onRender={() => {}}+ onPatchEntry={onPatchEntry}+ />,+ );+ expect(screen.getByText('Tall.')).toBeInTheDocument();+ expect(screen.queryByPlaceholderText(/Describe Lyra/)).not.toBeInTheDocument();+ });++ it('renders a buffered textarea when unlocked + onPatchEntry + kind.descField is wired', () => {+ const onPatchEntry = vi.fn();+ render(+ <CanonCard+ kind={editableKind}+ entry={{ ...baseEntry, physicalDescription: 'Tall.' }}+ onRender={() => {}}+ onPatchEntry={onPatchEntry}+ />,+ );+ const textarea = screen.getByPlaceholderText(/Describe Lyra/);+ expect(textarea).toHaveValue('Tall.');+ fireEvent.change(textarea, { target: { value: 'Tall, sharp-eyed cartographer.' } });+ // Buffered — no PATCH until blur.+ expect(onPatchEntry).not.toHaveBeenCalled();+ fireEvent.blur(textarea);+ expect(onPatchEntry).toHaveBeenCalledWith('ent-1', { physicalDescription: 'Tall, sharp-eyed cartographer.' });+ });++ it('pre-fills from the legacy fallback field and migrates to the canonical field on save', () => {+ const onPatchEntry = vi.fn();+ render(+ <CanonCard+ kind={editableKind}+ // Legacy entry: only `description` (the fallback), no `physicalDescription`.+ entry={{ ...baseEntry, description: 'Cartographer-spy.' }}+ onRender={() => {}}+ onPatchEntry={onPatchEntry}+ />,+ );+ const textarea = screen.getByPlaceholderText(/Describe Lyra/);+ expect(textarea).toHaveValue('Cartographer-spy.');+ fireEvent.change(textarea, { target: { value: 'Cartographer-spy with a forged passport.' } });+ fireEvent.blur(textarea);+ // Migrates onto the canonical field — descFor will now prefer it.+ expect(onPatchEntry).toHaveBeenCalledWith('ent-1', { physicalDescription: 'Cartographer-spy with a forged passport.' });+ });++ it('falls back to read-only when kind.descField is absent (NounsStage / series view)', () => {+ const seriesKind = {+ key: 'characters', label: 'Characters',+ descFor: (e) => e.description || '',+ // No descField — series view stays read-only on canon descriptions.+ };+ render(+ <CanonCard+ kind={seriesKind}+ entry={baseEntry}+ onRender={() => {}}+ onPatchEntry={vi.fn()}+ />,+ );+ expect(screen.getByText('Cartographer-spy.')).toBeInTheDocument();+ expect(screen.queryByPlaceholderText(/Describe Lyra/)).not.toBeInTheDocument();+ });+});+describe('CanonCard — wardrobe pending-row promotion', () => {const renderEditable = (onPatchEntry) => render(<CanonCarddiff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex e6ef9ec26c..cc9d50cad9 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -14,7 +14,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import {- Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock,+ Library, Loader2, Users, MapPin, Package, Wand2, Filter, Lock, Unlock, ImagePlus,} from 'lucide-react';import toast from '../ui/Toast';import {@@ -44,18 +44,26 @@ const capImageRefs = (refs) => (: refs);+// `descField` is the writable field bound to the inline description editor in+// `CanonCard`. `descFor` (used for the render prompt + the read-only fallback+// view) prefers the primary then the legacy/sibling field — so for characters+// the editor writes `physicalDescription` while `descFor` still surfaces any+// pre-migration `description` value until the user re-saves.const KINDS = [{key: 'characters', apiKind: 'character', label: 'Characters', singular: 'character', icon: Users,descFor: (c) => descriptorForCanonEntry('characters', c),+ descField: 'physicalDescription', descFieldFallback: 'description', descFieldMax: BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,},{key: 'places', apiKind: 'place', label: 'Places', singular: 'place', icon: MapPin,descFor: (p) => descriptorForCanonEntry('places', p),+ descField: 'description', descFieldMax: BIBLE_LIMITS.PLACE_DESCRIPTION_MAX,},{key: 'objects', apiKind: 'object', label: 'Objects', singular: 'object', icon: Package,descFor: (o) => descriptorForCanonEntry('objects', o),+ descField: 'description', descFieldFallback: 'significance', descFieldMax: BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX,},];@@ -361,6 +369,36 @@ export default function UniverseCanonSection({toast.success(`Rendering reference for ${entry.name}`);};+ // Render All — fires `handleRenderRef` for every entry in the kind that+ // (a) has a non-blank descFor() prompt and (b) doesn't already carry an+ // image ref. Already-rendered entries are intentionally skipped so the+ // button is the one-shot "fill in the holes" affordance; users can still+ // re-render an individual entry from its row.+ // Parallel kickoff is safe — `renderingJobs[entry.id]` is keyed per entry+ // and the queue handler clears each independently on completion.+ const [renderAllKindKey, setRenderAllKindKey] = useState(null);+ const handleRenderAll = async (kind) => {+ const entries = Array.isArray(universe?.[kind.key]) ? universe[kind.key] : [];+ const candidates = entries.filter((e) =>+ kind.descFor(e).trim()+ && !(Array.isArray(e.imageRefs) && e.imageRefs.length > 0)+ );+ if (candidates.length === 0) {+ toast.error(`No ${kind.label.toLowerCase()} need a reference render`);+ return;+ }+ setRenderAllKindKey(kind.key);+ try {+ // Sequential await isn't necessary for correctness, but it keeps the+ // first toast from racing the spinner-state writes for many entries+ // at once. `generateImage` returns as soon as the job is queued.+ await Promise.all(candidates.map((entry) => handleRenderRef(kind, entry)));+ toast.success(`Queued ${candidates.length} reference render${candidates.length === 1 ? '' : 's'}`);+ } finally {+ if (mountedRef.current) setRenderAllKindKey(null);+ }+ };+const handleRenderCleanPlate = async (entry) => {// Match CanonCard's button-enable predicate (descFor includes palette +// recurringDetails for places) — composeCleanPlatePrompt builds a valid@@ -636,6 +674,14 @@ export default function UniverseCanonSection({bulkLocking={bulkLockingKindKey === kind.key}fullList={Array.isArray(universe[kind.key]) ? universe[kind.key] : []}externalPendingByEntryId={externalPendingByEntryId}+ // Single-kind view (`?kind=places`, sidebar deep-links) — the+ // outer canon section already supplies the h2 + description + card+ // chrome, so KindSection drops its own bordered wrapper + duplicate+ // header. Multi-kind view keeps the chrome so Characters / Places /+ // Objects stay visually separated.+ compact={!!kindFilter}+ onRenderAll={() => handleRenderAll(kind)}+ renderingAll={renderAllKindKey === kind.key}/>))}@@ -643,7 +689,7 @@ export default function UniverseCanonSection({);}-function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onSheetDeleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap, onBulkLock, bulkLocking, fullList, externalPendingByEntryId = null, compact = false, onRenderAll = null, renderingAll = false }) {// Universe-only character wiring — `null` for non-character kinds so// CanonCard's gate stays `kind === 'characters' && characterExtensions`.// Memoized so the BASE object is stable across re-renders that aren't@@ -667,6 +713,119 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende// so the next click locks the remaining holdouts.const allLocked = fullList.length > 0 && lockedCount === fullList.length;const bulkDisabled = !onBulkLock || bulkLocking || fullList.length === 0;++ // Render All — disabled when every entry already has a ref image or no entry+ // carries a renderable description. Mirrors the per-entry render button's+ // own enable predicate, just folded over the kind's full list.+ const renderableCount = fullList.filter((e) =>+ kind.descFor(e).trim()+ && !(Array.isArray(e.imageRefs) && e.imageRefs.length > 0)+ ).length;+ const renderAllDisabled = !onRenderAll || renderingAll || renderableCount === 0;++ const controls = (+ <>+ {onRenderAll ? (+ <button+ type="button"+ onClick={onRenderAll}+ disabled={renderAllDisabled}+ title={renderableCount === 0+ ? `Every ${kind.singular} already has a reference image`+ : `Queue reference renders for ${renderableCount} ${renderableCount === 1 ? kind.singular : kind.label.toLowerCase()} without an image yet`}+ aria-label={`Render all ${kind.label}`}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-gray-400 hover:text-port-accent disabled:opacity-30 disabled:cursor-not-allowed border border-port-border hover:border-port-accent/50"+ >+ {renderingAll ? <Loader2 size={11} className="animate-spin" /> : <ImagePlus size={11} />}+ Render all{renderableCount > 0 ? ` (${renderableCount})` : ''}+ </button>+ ) : null}+ {fullList.length > 0 && onBulkLock ? (+ // Single toggle button — mirrors the per-item lock-toggle visual.+ // Lock icon when every entry is already locked (click unlocks all);+ // Unlock icon for the all-unlocked + mixed cases (click locks all)+ // so "the next click locks the holdouts" is always the action.+ <button+ type="button"+ onClick={() => onBulkLock(!allLocked)}+ disabled={bulkDisabled}+ title={allLocked+ ? `Unlock all ${kind.label.toLowerCase()} — AI refine / differentiate may overwrite them`+ : `Lock all ${kind.label.toLowerCase()} — AI refine / differentiate will skip them`}+ aria-label={allLocked ? `Unlock all ${kind.label}` : `Lock all ${kind.label}`}+ aria-pressed={allLocked}+ className={`p-1 rounded disabled:opacity-30 disabled:cursor-not-allowed ${+ allLocked+ ? 'text-port-accent hover:bg-port-accent/20'+ : 'text-gray-500 hover:text-gray-300'+ }`}+ >+ {bulkLocking+ ? <Loader2 size={14} className="animate-spin" />+ : allLocked ? <Lock size={14} /> : <Unlock size={14} />}+ </button>+ ) : null}+ </>+ );++ const list = all.length === 0 ? (+ filtered && totalCount > 0+ ? <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} in the selected series. {totalCount} total in this universe — clear the filter to see them all.</p>+ : <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} yet. Use <em>Extract from prose</em> above to populate this list from an issue.</p>+ ) : (+ <ul className="space-y-2">+ {all.map((entry) => (+ <CanonCard+ key={entry.id || entry.name}+ kind={kind}+ entry={entry}+ // Merge the section-local pending map (one-off renders) with+ // the universe-page-level map (batch `/render` jobs). The+ // section's own state wins because its completion handler is+ // the one that does the optimistic imageRefs[] append for+ // canon entries (`handleRefCompleted`); the external map is+ // a presentation-only fallback so the spinner shows for+ // batch-queued canon jobs too.+ inFlightJobId={renderingJobs[entry.id] || externalPendingByEntryId?.[entry.id] || null}+ onRender={() => onRender(entry)}+ onJobCompleted={onJobCompleted}+ onJobFailed={onJobFailed}+ onPreview={onPreview}+ onRefine={onRefine}+ refining={refiningId === entry.id}+ refineDisabled={!!refiningId && refiningId !== entry.id}+ usage={usage?.[entry.id] || null}+ onToggleLock={onToggleLock}+ togglingLock={togglingLockId === entry.id}+ onPatchEntry={onPatchEntry}+ onRenderCleanPlate={onRenderCleanPlate}+ seriesNameMap={seriesNameMap}+ characterExtensions={characterExtensions+ ? { ...characterExtensions, expanding: expandingId === entry.id }+ : null}+ />+ ))}+ </ul>+ );++ // Compact mode: the outer canon section already supplies the h2 + bordered+ // card chrome, so KindSection drops its own wrapper to avoid double-nesting.+ // The duplicate icon + label header is hidden too — only the controls strip+ // (count, Render all, bulk lock) stays as a slim toolbar above the list.+ if (compact) {+ return (+ <div>+ <div className="flex items-center justify-end gap-1.5 mb-2">+ <span className="text-[10px] text-gray-500 mr-auto">+ {filtered ? `${all.length} / ${totalCount}` : all.length} {all.length === 1 ? kind.singular : kind.label.toLowerCase()}+ </span>+ {controls}+ </div>+ {list}+ </div>+ );+ }+return (<section className="rounded border border-port-border bg-port-bg/60"><div className="flex items-center gap-2 px-3 py-2 border-b border-port-border">@@ -675,73 +834,11 @@ function KindSection({ kind, universeId, all, totalCount, filtered, usage, rende<span className="text-[10px] text-gray-500">{filtered ? `${all.length} / ${totalCount}` : all.length}</span>- {fullList.length > 0 && onBulkLock ? (- // Single toggle button — mirrors the per-item lock-toggle visual.- // Lock icon when every entry is already locked (click unlocks all);- // Unlock icon for the all-unlocked + mixed cases (click locks all)- // so "the next click locks the holdouts" is always the action.- <button- type="button"- onClick={() => onBulkLock(!allLocked)}- disabled={bulkDisabled}- title={allLocked- ? `Unlock all ${kind.label.toLowerCase()} — AI refine / differentiate may overwrite them`- : `Lock all ${kind.label.toLowerCase()} — AI refine / differentiate will skip them`}- aria-label={allLocked ? `Unlock all ${kind.label}` : `Lock all ${kind.label}`}- aria-pressed={allLocked}- className={`ml-auto p-1 rounded disabled:opacity-30 disabled:cursor-not-allowed ${- allLocked- ? 'text-port-accent hover:bg-port-accent/20'- : 'text-gray-500 hover:text-gray-300'- }`}- >- {bulkLocking- ? <Loader2 size={14} className="animate-spin" />- : allLocked ? <Lock size={14} /> : <Unlock size={14} />}- </button>- ) : null}- </div>- <div className="p-3">- {all.length === 0 ? (- filtered && totalCount > 0- ? <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} in the selected series. {totalCount} total in this universe — clear the filter to see them all.</p>- : <p className="text-xs text-gray-500 italic">No {kind.label.toLowerCase()} yet. Use <em>Extract from prose</em> above to populate this list from an issue.</p>- ) : (- <ul className="space-y-2">- {all.map((entry) => (- <CanonCard- key={entry.id || entry.name}- kind={kind}- entry={entry}- // Merge the section-local pending map (one-off renders) with- // the universe-page-level map (batch `/render` jobs). The- // section's own state wins because its completion handler is- // the one that does the optimistic imageRefs[] append for- // canon entries (`handleRefCompleted`); the external map is- // a presentation-only fallback so the spinner shows for- // batch-queued canon jobs too.- inFlightJobId={renderingJobs[entry.id] || externalPendingByEntryId?.[entry.id] || null}- onRender={() => onRender(entry)}- onJobCompleted={onJobCompleted}- onJobFailed={onJobFailed}- onPreview={onPreview}- onRefine={onRefine}- refining={refiningId === entry.id}- refineDisabled={!!refiningId && refiningId !== entry.id}- usage={usage?.[entry.id] || null}- onToggleLock={onToggleLock}- togglingLock={togglingLockId === entry.id}- onPatchEntry={onPatchEntry}- onRenderCleanPlate={onRenderCleanPlate}- seriesNameMap={seriesNameMap}- characterExtensions={characterExtensions- ? { ...characterExtensions, expanding: expandingId === entry.id }- : null}- />- ))}- </ul>- )}+ <div className="ml-auto flex items-center gap-1.5">+ {controls}+ </div></div>+ <div className="p-3">{list}</div></section>);}