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 — drop completed strip-malloc-ffmpeg + mediajobqueue-provider-predicate; verify ltx2-fflf bug; surface decision questions
[._.]/ Adam Eivy4af7df190b56
diff --git a/PLAN.md b/PLAN.mdindex a6d0190335..195343cae5 100644--- a/PLAN.md+++ b/PLAN.md@@ -4,32 +4,25 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up-### Creative Ingredients Catalog — follow-up slices+1. **[ltx2-fflf-skips-last-image-resize-when-both-frames-set]** **ltx2 FFLF skips last-image resize when both start and end frames are provided — CONFIRMED bug (verified 2026-05-30 this replan).** `server/services/videoGen/local.js:573` gates `lastImageWillBeUsed` on `mode === 'fflf' && !sourceImagePath`, so the ltx2 true-FFLF flow (both `sourceImagePath` AND `lastImagePath` set, passed via `--image` + `--last-image` at `buildLtx2Args` ~line 328) skips the `resizeImage` ffmpeg pass for the end frame; `scripts/generate_ltx2.py` `_resolve_keyframes` (~line 313) then passes both paths straight through with no resize/letterbox/pad. The end-frame image reaches `KeyframeInterpolationPipeline.generate_and_save()` at its ORIGINAL dimensions → dimension mismatch / degraded output (the multi-keyframe path already resizes each keyframe at `local.js` ~line 606; the two-keyframe legacy path was missed). Fix: resize the last image in the ltx2 two-keyframe FFLF path the same way multi-keyframes are resized, and correct the stale comment at `local.js` ~line 560 that wrongly assumes only mlx_video/Windows consume `--last-image`. (Was filed UNVERIFIED under blocked; verification this replan confirmed it real and moved it up.)+2. **[media-job-store-progress-on-job-record]** **mediaJobQueue: persist progress/statusMsg on the job record.** `runJob`'s progress handler in `server/services/mediaJobQueue/index.js` (~line 575) only broadcasts to SSE (`broadcastSse`) — it doesn't mutate the job object. So `GET /api/media-jobs/:id` (used by `MediaJobsQueue.jsx` and any other non-SSE consumer) always reports 0 progress for in-flight jobs. SSE-attached pages don't see this (lastPayload replay), but list-view hydration does. Add `job.progress` + `job.statusMsg` updates inside the dispatcher's `progress` handler. Cross-cutting across image/video/codex paths.+3. **[shared-bounded-concurrency-mapper]** **Extract a generic `mapWithConcurrency(items, n, fn)` to `server/lib/` and reuse it.** The worker-pool idiom (cursor + N workers draining a shared array, order-preserving result) is now hand-rolled in THREE places (verified 2026-05-30): `embedBatch` in `server/services/embeddings.js` (~line 158), the mapper in `server/services/catalogExtraction.js` (~line 317), and another in `server/routes/imageVideoModels.js`. A pure `server/lib/` helper would collapse all three onto one tested mechanism (barrel + README row per the maintenance rule).+4. **[video-resume-restore-keyframes]** **VideoGen resume: restore keyframes from the active job.** `ACTIVE_JOB_PARAM_FIELDS` in `server/routes/videoGen.js` (~line 739) intentionally omits `keyframes` (gallery filename + frame-index pairs for multi-keyframe FFLF) because the v1 resume effect doesn't repopulate the picker UI for them. A user who reloads mid-render on a keyframe job loses the keyframe-picker state even though every other form field is restored. Whitelist `keyframes` in the route AND wire a `setKeyframes()`-style setter in `client/src/pages/VideoGen.jsx`'s resume effect (~line 507). Independent of the SSE re-attach.+5. **[chrome-canary-followups]** **Hardening for the custom-Chrome-binary feature — remaining low/medium items.** _High-severity (a)–(f) are now DONE (verified 2026-05-30): (a) `browser/server.js` (~line 46) derives `macAppBundle` from `chromePath` on macOS; (b) both `spawn()` calls (~lines 221, 236) have `.on('error', …)` listeners; (d) both `loadConfig`s try/catch `JSON.parse`; (e) `setup-browser.js#loadConfig` warns + returns null and `applyCanaryToConfig` skips the save on unreadable config; (f) top-level `runCanarySetup()` is `.catch()`-wrapped. (c) headless-flag flip is tracked in `[setup-browser-canary-headless]` (now in Backlog with a decision)._ **Remaining low/medium:** (g) idempotency guard only checks `chromePath` — decliners + `macAppBundle`-only users get re-prompted every update; (h) `PORTOS_USE_CANARY` only matches literal `0/false/1/true` — `no/off/yes/on/True` fall through both branches; (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo prompt under non-TTY + `PORTOS_USE_CANARY=1`; (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write (GET /api/browser/config returns pre-update values until process restart); (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` (`server/lib/fileUtils.js`); (l) `spawnSync` status check treats `status: null` (spawn-failure/signal) like a non-zero exit and never logs `result.error`; (m) `optionalPath` Zod schema has no `.app`/`.exe` sanity check; (n) `launchBrowser`'s reuse-existing-Chrome early-return fires BEFORE `headlessMode` is set (wrong /health mode after a PM2 restart that reuses Chrome); (o) `detectCanary` on macOS only checks `/Applications/...` and misses per-user `~/Applications` installs.+6. **[ref-watch-phosphene-teacache-extend-a2v-denoise]** **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision (resolved 2026-05-30): land independently** against today's pin — the calibration helper `_build_teacache_controller` already exists at the current pin, so there's no need to couple this to the risky rename in `[ref-watch-phosphene-bump-ltx2-pin-v0148]`. Scope: small/medium.-The catalog backend, schema, federation routes, ingest extraction service, and Catalog/Ingest/Detail UI all landed in one PR (see `docs/plans/2026-05-29-creative-ingredients-catalog.md` for the design record). **All follow-up slices and the extensibility roadmap are now shipped — no Catalog items remain.**+## Backlog-_Merged 2026-05-30 (7 PRs, claude+codex reviewed): 15 items shipped to main — #554 roundtrip-and-cast bug fixes (`catalog-export-bundle-import-refs`, `catalog-markdown-roundtrip-fences-scraps`, `catalog-cast-panel-multi-role-unlink`); #555 `catalog-universe-builder-picker`; #556 `catalog-writers-room-version-refs`; #557 `catalog-tests`; #558 the combined schema stack (`catalog-shared-type-registry`, `catalog-payload-schemaversion-per-type`, `catalog-ingredient-relations`, `catalog-tag-taxonomy`, `catalog-ingredient-revisions`, `catalog-ingredient-media-refs`, `catalog-federation-orchestrator`, `catalog-bundled-universe-push`); #559 `catalog-source-kinds-url-file-voice`. #560 `catalog-character-sheet-enrichment` shipped a SLICE — kept open below for its remaining deep-unification + array-editor scope._+Claimable, well-specified, no decision needed — `/claim`-able. Unordered.-_Re-triaged then cleared 2026-05-30 (post-merge follow-up pass): the 6 review-surfaced follow-ups + the 4 previously-gated items were each verified against `main` and all shipped — `catalog-bulk-import-scrap-persistence`, `catalog-sync-apply-kind-helper`, `catalog-detail-batched-endpoint`, `browser-navigate-ssrf-guard`, `catalog-bulk-import-route-db-tests`, `catalog-friendlify-universe-tags-on-sync`, the character-sheet slice, `catalog-type-table-vs-check`, and `catalog-ask-retrieval`._+- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` ~lines 655 + resume block ~317; VideoGen `attachJobEvents` ~line 450). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites.+- [ ] [capabilities-cheap-memory-count] **Capabilities route should count active memories without sorting/paginating.** `GET /api/capabilities` calls `getMemories({ status: 'active' })` (`server/routes/capabilities.js` ~line 69) only to read `.total`, but `getMemories` loads the full index, filters, sorts, and paginates before returning `{ total, memories }` — the sort + slice is wasted work on a page polled every ~20s. Add a lightweight `countMemories({ status })` (or a `countOnly` option) to `server/services/memory.js` that returns the filtered count without the sort/paginate, and switch the route to it. Micro-opt; the index is cached via `loadIndex`, so low urgency.+- [ ] [banner-icon-aria-hidden] **Apply `aria-hidden="true"` to `<Banner>`'s rendered icon.** `client/src/components/ui/Banner.jsx` (~line 62) renders the `icon` prop as a bare `<Icon …>` — when the icon is decorative (the body text already conveys the meaning), screen readers should skip it. Either wrap the icon render in `<span aria-hidden="true">` inside Banner, or thread an `iconAriaHidden` prop. Once landed, re-migrate the `ImportTab.jsx` error row to `<Banner tone="error" size="md" icon={AlertCircle} actions={…}>` (it was reverted from `<Banner>` because the icon prop doesn't pass through a11y attributes).+- [ ] [inline-confirm-row-primitive] **Extract `<InlineConfirmRow tone="error">` primitive for inline delete-confirm rows.** Five sites (`client/src/components/brain/tabs/LinksTab.jsx:599`, `client/src/components/brain/tabs/InboxTab.jsx:387, 512, 606, 765`) share the same shape: `flex items-center gap-2 p-2 bg-port-error/10 border border-port-error/30 rounded` + `<span flex-1>{question}</span>` + Delete + Cancel buttons. They didn't migrate to `<Banner>` because `<Banner>` is shaped around "icon + content + actions" alerts, not "question + confirm/cancel" confirm rows. Build `client/src/components/ui/InlineConfirmRow.jsx` with `{ question, confirmText='Delete', cancelText='Cancel', onConfirm, onCancel, tone='error' }`, then swap the five sites. Pairs naturally with the existing confirmation-UX preference (no two-click-arm).+- [ ] [rich-text-editor-for-prose-stage-replace-plain] **Rich-text editor for prose stage.** Replace the plain textarea in `ProseStage.jsx`. **Decision (resolved 2026-05-30): reuse the existing Writers Room editor** rather than introducing a new markdown-editor dependency — it already exists, keeps the prose-editing experience consistent across surfaces, and avoids a third editor stack. Extract/share the Writers Room editor component for the prose stage.+- [ ] [scene-level-wardrobe-picking-per-scene] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with a wardrobe-picker dropdown. **Decision (resolved 2026-05-30): the user picks (no extractor guess), and wardrobe is APPENDED after `physicalDescription` (it does not substitute body fields).** Rationale: wardrobe is a deliberate creative choice — auto-guessing adds noise the user must then correct, and substituting body fields would lose canonical character description. Both are reversible if the extractor-guess path is wanted later.+- [ ] [setup-browser-canary-headless] **Managed-browser headed/headless default.** `data.reference/browser-config.json` ships `"headless": true`, but `browser/server.js`'s header comment says "Default headed" and opting into Canary at setup currently runs it invisibly. **Decision (resolved 2026-05-30): default HEADED.** The whole purpose of the custom-Chrome-binary feature is a *visible, differentiated* browser, so headless-by-default defeats it. Flip the seed to `"headless": false` AND set `config.headless = false` in `scripts/setup-browser.js#applyCanaryToConfig` (this also closes item (c) of `[chrome-canary-followups]`). Ship a one-time migration that flips the seed value only where the installed config still matches the old shipped hash; leave user-customized values alone.-_Final three cleared 2026-05-30 (see the "Creative Catalog — extensibility roadmap" clearance note below): `catalog-scrap-chunking` (#567), `catalog-user-defined-types` (#568), and `catalog-character-sheet-enrichment` deep-unification + array-editor remainder (#569), plus the `catalog-voice-tools-user-type-filter` follow-up. The Catalog feature is fully shipped._---### Creative Catalog — extensibility roadmap--The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`) in at least eight places: the Postgres CHECK constraint (`server/scripts/init-db.sql` + `server/lib/db.js:ensureSchema`), the Zod enum in `server/lib/catalogValidation.js`, the extraction prompt in `server/services/catalogExtraction.js`, the `TYPES` array + `PRIMARY_CONTENT_KEY` + `PRIMARY_CONTENT_LABEL` + `payloadSnippet` fallback chain in `client/src/pages/Catalog.jsx`, the type-specific editor branches in `client/src/pages/CatalogIngredient.jsx`, the `IngredientPicker.jsx` type filter, and the `search_tsv` generated column expression. Adding a seventh type today is an 8-file touch across server, client, and a Postgres migration. The items below collapse that surface so the catalog can grow into the long tail of creative shards (lore fragments, factions, magic systems, vehicles, wardrobe, dialogue snippets, beat cards, prompt fragments, voice-memo transcripts, mood references, etc.) without each new shard being a multi-PR effort.--_Catalog roadmap fully cleared 2026-05-30 (3 PRs, claude+codex+gemini reviewed): #567 `catalog-scrap-chunking` (long pastes split into parent + child chunks; per-chunk extraction unioned + deduped); #568 `catalog-user-defined-types` (Settings → Catalog UI + generic field renderer + runtime registry merge, federated via a catalogTypes sync block with LWW + delete tombstones); #569 `catalog-character-sheet-enrichment` remaining slice (bidirectional catalog↔canon projection with a re-entrancy guard + boot reconcile making the catalog row the single store of record, plus inline color-palette/stats/aliases editors). The follow-up `catalog-voice-tools-user-type-filter` (voice `catalog_lookup` type enum derived from the active registry so user types are voice-addressable) shipped in the same pass. No Catalog items remain._--_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._--_Batch-cleared 2026-05-29 (catalog batch 2): 4 catalog items shipped via parallel sub-agents — `catalog-pipeline-series-cast` (reusable `CatalogCastPanel` on Series/Issue/WritersRoom), `catalog-bulk-import` (JSON/CSV/markdown ingest), `catalog-export-bundle` (JSON/markdown/YAML), and the palette + voice slice of `catalog-cmdk-ask-voice-discovery` (Ask retrieval split out as `[catalog-ask-retrieval]`)._--- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).-- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).-- [ ] [shared-bounded-concurrency-mapper] **Extract a generic `mapWithConcurrency(items, n, fn)` to `server/lib/` and reuse it in `embedBatch` + the catalog chunk extractor.** The worker-pool idiom (cursor + N workers draining a shared array, order-preserving result) is now hand-rolled in at least two places: `embedBatch` in `server/services/embeddings.js` (~line 158, specialized to `embedText`) and `mapWithConcurrency` in `server/services/catalogExtraction.js` (~line 317, added by `[catalog-scrap-chunking]`). A pure `server/lib/` helper would collapse both onto one tested mechanism (barrel + README row per the maintenance rule). Deferred from the scrap-chunking PR's `/simplify` pass — extracting it cleanly touches `embeddings.js` and other call sites outside that diff's scope. Surfaced by reuse/altitude review (2026-05-30).-- [ ] [mediajobqueue-shared-provider-kind-predicate] **Share a `getJobProviderKind(job)` predicate between `getGenModuleForJob` and `resolveLiveParams` in `server/services/mediaJobQueue/index.js`.** Both now encode the same `video | image+codex | image+local` partition by hand (`getGenModuleForJob` at ~line 109, `resolveLiveParams.usesLocalPython` at ~line 122). A shared `getJobProviderKind(job) → 'video-local' | 'image-local' | 'image-codex' | null` would let both branches derive from one predicate and extend cleanly to future providers. Surfaced by reuse-review during the resolveLiveParams extract (2026-05-29); deferred because today's duplication is two lines and the seam is still small.-- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.## Deferred Architecture (human-led planning)God-file decomposition candidates — none are bugs; pick up when touching the file for unrelated reasons.@@ -59,31 +52,32 @@ God-file decomposition candidates — none are bugs; pick up when touching the f## Blocked on decision / design (skip for `/claim`)-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.+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. **Each item that is blocked on a decision the user must make carries a `❓ **Question:**` line; answer it and move the item back up to Next Up / Backlog.**### Audio / Video / Image gen- [ ] [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.+ > ❓ **Question:** Which local OSS music generator should the sidecar use? **Recommendation: MusicGen** (Meta; MLX-portable, runs locally, bounded ~30s clips, well-supported) for the first slice, with AudioLDM2 as a possible second backend and a commercial API (Suno, duration control) deferred to the 3rd-party-stub phase. Confirm MusicGen, or name a different starting generator.+- [ ] [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. New `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. Treat as a new sub-brainstorm when picked up — investigation first.+ > ❓ **Question:** Two decisions gate this: (1) which generator family — local-bounded (MusicGen-MLX, ~30s), local long-form (AudioLDM2), or commercial (Suno, real duration control)? and (2) at what granularity does episode-level audio drive — one track per episode, per-scene beds, or per-arc cues? Pick a generator + granularity and I'll scope the `audioMode` design from there.+- [ ] [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 the world-builder batch path so high-end renders are practical; let each bucket pick its own model.+ > ❓ **Question:** Is high-end external-SD-API rendering a priority now, or stay local-only for World Builder? With the 128GB machine online, local 9B–17B models may cover the quality need without adding a third-party render dependency + key management. Greenlight external providers, or defer?- [ ] [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.-- [ ] [media-job-store-progress-on-job-record] **mediaJobQueue: persist progress/statusMsg on the job record.** `runJob`'s progress handler in `server/services/mediaJobQueue/index.js` only broadcasts to SSE — it doesn't mutate the job object. So `GET /api/media-jobs/:id` (used by `MediaJobsQueue.jsx` and any other non-SSE consumer) always reports 0 progress for in-flight jobs. SSE-attached pages don't see this (lastPayload replay), but list-view hydration does. Add `job.progress` + `job.statusMsg` updates inside the dispatcher's `progress` handler. Deferred from video-reload PR — cross-cutting across image/video/codex paths.-- [ ] [video-resume-restore-keyframes] **VideoGen resume: restore keyframes from the active job.** `ACTIVE_JOB_PARAM_FIELDS` in `server/routes/videoGen.js` intentionally omits `keyframes` (gallery filename + frame-index pairs for multi-keyframe FFLF) because the v1 resume effect doesn't repopulate the picker UI for them. A user who reloads mid-render on a keyframe job loses the keyframe-picker state even though every other form field is restored. Whitelist `keyframes` in the route AND wire a `setKeyframes()`-style setter in `client/src/pages/VideoGen.jsx`'s resume effect. Deferred from video-reload PR — keyframes UI restoration is independent of the SSE re-attach.-- [ ] [unify-media-job-sse-hook-imagegen-videogen] **Unify ImageGen + VideoGen SSE attach into `useMediaJobSse` hook.** Both pages now have near-duplicate EventSource handlers (ImageGen `startLocalGeneration` lines 653-708 + resume block lines 317-328; VideoGen `attachJobEvents`). Build a hook on top of `useSseProgress` (`client/src/hooks/useSseProgress.js`) that handles the queued / started / status / progress / complete / error / canceled SSE types and consolidate both sites. Deferred from the video-reload PR — scope was just the bug fix.-- [ ] [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.-- [ ] [ltx2-fflf-skips-last-image-resize-when-both-frames-set] **ltx2 FFLF skips last-image resize when both start and end frames are provided.** `server/services/videoGen/local.js:571` gates `lastImageWillBeUsed` on `mode === 'fflf' && !sourceImagePath` so for the ltx2 runtime's true-FFLF flow (both `sourceImagePath` AND `lastImagePath` set — accepted at `buildLtx2Args` line 233 and passed via `--last-image` at line 337) the end-frame image bypasses the `resizeImage` ffmpeg pass at line 601. Either size-pad the last image (matching the start-image resize), or confirm `scripts/generate_ltx2.py` itself resizes/letterboxes its `--last-image` input before conditioning. Surfaced by gemini's `/do:review` pass against PR #526 (extract-expandhome-helper, 2026-05-29) — UNVERIFIED that this actually causes generation failures; the ltx2 helper script may already handle non-matching dimensions. Out-of-scope from PR #526 (that PR only touches the `expandHome` helper + HF download flags).+ > ❓ **Question:** This needs you to supply (or point me at) a real keyframe pair from the same scene to validate against — it can't be self-tested without representative content. Do you have a clip-A-last / clip-B-first pair I should test with, or should I synthesize a stand-in pair?+- [ ] [episode-video-provider-picker-runwayml-third-party] **Episode-video provider picker (RunwayML / third-party).** _Trigger-gated on a code precondition, not a user decision:_ once the provider abstraction lands, expose the picker on `EpisodeVideoStage`.+- [ ] [comic-book-pdf-export-once-stages-comicpages] **Comic-book PDF export.** _Trigger-gated on a code precondition, not a user decision:_ once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.### Large product / UX redesigns+These are strategic roadmap items, not single-decision blocks — they need a design pass and prioritization against GOALS.md before any can be `/claim`-ed. **Prioritization pass needed: which (if any) of these are the next milestone?**+- [ ] [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".-- [ ] [cross-domain-insights-engine-m42-p5] **M42 P5 — Cross-Domain Insights Engine.** Connect genome ↔ health ↔ taste ↔ identity ↔ creative output into narrative insights surfaced in Brain. Needs a design pass on (a) which signal pairs are worth correlating, (b) where insights land (new Insights surface vs. Brain daily/weekly digest), (c) how the user dismisses / accepts an insight, and (d) whether the LLM gets a structured "facts table" or raw stage data. GOALS.md flags this as the next milestone for "Digital Identity Modeling" but no design has been written.+- [ ] [cross-domain-insights-engine-m42-p5] **M42 P5 — Cross-Domain Insights Engine.** Connect genome ↔ health ↔ taste ↔ identity ↔ creative output into narrative insights surfaced in Brain. GOALS.md flags this as the next milestone for "Digital Identity Modeling" but no design has been written.+ > ❓ **Question (design pass — answer all four to unblock):** (a) Which signal pairs are worth correlating first (e.g. genome↔longevity, taste↔creative-output, health↔goals)? (b) Where do insights land — a new `/insights` surface, or fold into the Brain daily/weekly digest? (c) How does the user dismiss / accept an insight? (d) Does the LLM receive a structured "facts table" or raw stage data?- [ ] [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.@@ -93,126 +87,118 @@ Items here need a research / design pass, an explicit decision, or a preconditio- [ ] [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)+### Trigger-gated (waiting for a code precondition — not a user decision)++These fire on a code-side event (Nth consumer, a prior item landing, an observed perf problem), not on a human decision — leave them parked until the trigger occurs. The three phosphene items carry a `❓ **Question:**` because they additionally need a scope/product call from the user.-- [ ] [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.-- [ ] [capabilities-cheap-memory-count] **Capabilities route should count active memories without sorting/paginating.** `GET /api/capabilities` calls `getMemories({ status: 'active' })` (server/routes/capabilities.js) only to read `.total`, but `getMemories` loads the full index, filters, sorts, and paginates before returning `{ total, memories }` — the sort + slice is wasted work on a page polled every ~20s. Add a lightweight `countMemories({ status })` (or a `countOnly` option) to `server/services/memory.js` that returns the filtered count without the sort/paginate, and switch the route to it. Micro-opt; the index is cached via `loadIndex`, so low urgency. Surfaced by copilot review of `[codex5-onboarding-capability-map]` 2026-05-25.-- [ ] [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.-- [ ] [banner-icon-aria-hidden] **Apply `aria-hidden="true"` to `<Banner>`'s rendered icon.** `client/src/components/ui/Banner.jsx` renders the `icon` prop as a bare `<Icon size={s.iconSize} className="…">` — when the icon is decorative (the body text already conveys the meaning, which is the whole point of the icon-with-text Banner shape), screen readers should skip it. `client/src/components/brain/tabs/ImportTab.jsx` had `aria-hidden="true"` on its inline `<AlertCircle>` before `[warning-banner-migrate-remaining-sites]`; that site was reverted from `<Banner>` because the icon prop doesn't pass through a11y attributes. Either: (a) wrap the icon render in `<span aria-hidden="true">` inside Banner, or (b) thread an `iconAriaHidden` prop. Once landed, re-migrate the ImportTab error row to `<Banner tone="error" size="md" icon={AlertCircle} actions={…}>`.-- [ ] [inline-confirm-row-primitive] **Extract `<InlineConfirmRow tone="error">` primitive for inline delete-confirm rows.** Five sites (`client/src/components/brain/tabs/LinksTab.jsx:599`, `client/src/components/brain/tabs/InboxTab.jsx:387, 512, 606, 765`) share the same shape: `flex items-center gap-2 p-2 bg-port-error/10 border border-port-error/30 rounded` + `<span flex-1>{question}</span>` + Delete + Cancel buttons. They didn't migrate to `<Banner>` during `[warning-banner-migrate-remaining-sites]` because `<Banner>` is shaped around "icon + content + actions" alerts, not "question + confirm/cancel" confirm rows (the body is the prompt, both buttons are equal-weight actions, and `confirmText` / `cancelText` are the natural API). Build a tiny primitive at `client/src/components/ui/InlineConfirmRow.jsx` with `{ question, confirmText='Delete', cancelText='Cancel', onConfirm, onCancel, tone='error' }`, then swap the five sites. Pairs naturally with the existing confirmation UX preference (no two-click-arm).-- [ ] [pill-component-goaldetailpanel-migration] **Migrate `GoalDetailPanel.jsx`'s badges to the shared `<Pill>`.** The shared `<Pill>` (`client/src/components/ui/Pill.jsx`) shipped with `[shared-pill-chip-component]` and absorbed `WritersRoomGuide.jsx` + `Instances.jsx`'s badge family. `GoalDetailPanel.jsx`'s badges were intentionally left out: their colors are computed from data (`GOAL_TYPE_CONFIG[].bg/color` ~line 384, `CATEGORY_CONFIG`/`urgencyColor()` ~571-581, tag chips ~528/707, `CHECK_IN_STATUS_CONFIG` ~993), so they don't map to a fixed `tone`. They'd migrate via `<Pill tone="bare" bordered={false} className={`${cfg.bg} ${cfg.color}`}>` (the `bare` tone exists for exactly this data-driven case), which only consolidates the structural `rounded px-2 py-0.5 text-xs` shape — not the colors. Marginal benefit + many edits in a 1252-LOC god-component, so deferred. Do it opportunistically when next touching the file (pairs with the `GoalDetailPanel.jsx` god-component split under "Deferred Architecture").-- [ ] [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]`.+- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — **premise eroded; revisit when a 3rd caller lands.** 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.+- [ ] [pill-component-goaldetailpanel-migration] **Migrate `GoalDetailPanel.jsx`'s badges to the shared `<Pill>`.** `GoalDetailPanel.jsx`'s badges were intentionally left out of `[shared-pill-chip-component]`: their colors are computed from data (`GOAL_TYPE_CONFIG[].bg/color` ~line 384, `CATEGORY_CONFIG`/`urgencyColor()` ~571-581, tag chips ~528/707, `CHECK_IN_STATUS_CONFIG` ~993), so they don't map to a fixed `tone`. They'd migrate via `<Pill tone="bare" bordered={false} className={`${cfg.bg} ${cfg.color}`}>`, which only consolidates the structural `rounded px-2 py-0.5 text-xs` shape — not the colors. Marginal benefit + many edits in a 1252-LOC god-component, so deferred. Do it opportunistically when next touching the file (pairs with the `GoalDetailPanel.jsx` god-component split under "Deferred Architecture").+- [ ] [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 the tables by sweeping/glob-importing the migration files and removing the mirror entirely. Single source of truth, no hand sync.- [ ] [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.-- [ ] [ref-watch-phosphene-bump-ltx2-pin-v0148] **Bump `LTX2_PIN` from `f8f20c83` to v0.14.8 + adopt phosphene's frame_rate / class-rename / a2v / lora-fusion patches together.** From `reference-watch` review of phosphene (2026-05-22). Concrete upstream wins between PortOS's pin and current dgrauet HEAD: VAE auto-tiling that caps peak Metal memory on HD / long runs (#25), `_pending_loras` honored across every pipeline's `load()` override (#22, #23 — fixes silent character-LoRA-drops on Extend/HQ), `--lora` on `--low-ram` flow (#30), accurate transformer load-time markers for progress UI. Cost: in v0.14.x, `TextToVideoPipeline` / `ImageToVideoPipeline` / `ExtendPipeline` / `TwoStagePipeline` / `AudioToVideoPipeline` are all renamed (public surface becomes `TI2VidOneStagePipeline`, `RetakePipeline`, `TI2VidTwoStagesPipeline`, `A2VidPipelineTwoStage`, etc.). `generate_ltx2.py` would fail at import. Source commits: `2166d138` / `770ed0bd` (defensive imports v2), `94ae3430` (method-presence dispatch instead of class assumption), `aa235aa0` (`fps=` → `frame_rate=` shim), `681f429a` (a2v missing `frame_rate=` runtime patch), plus `[ref-watch-phosphene-lazy-eval-env-bootstrap]`. Scope: large (100–200 lines of careful Python touching every pipeline path, plus smoke test of every mode — text/image/fflf/extend/a2v — at the new pin). **Decision needed:** ship as one PR vs split per-mode; do this before or after the post-decode `os._exit(0)` lands.-- [ ] [ref-watch-phosphene-sigkill-watchdog-videogen-local] **Panel-side SIGKILL watchdog (Node layer) in `videoGen/local.js`.** From `reference-watch` review of phosphene (commit `94bd6965`, 2026-05-22). Even with helper-side `os._exit(0)` adopted (see `[ref-watch-phosphene-mlx-post-decode-os-exit]`), defense-in-depth at the Node layer is cheap insurance: watch stdout for the upstream "[Decoding video + audio + muxing] done in X.Xs" line (or the final `{"video_path": ...}` JSON), then arm a 30–45s grace timer that SIGKILLs the child if it doesn't exit. PortOS already has SIGTERM→SIGKILL escalation in `cancel()` (`server/services/videoGen/local.js:71-79`); reuse that path. **Trigger:** only do this if real users hit the hang after the pin bump and `os._exit(0)` proves insufficient (it shouldn't, in PortOS's short-lived-helper model). Scope: small/medium.-- [ ] [data-versioning-centralize-cosagents-settings] **Centralize `cosAgents.js` + `settings.js` on `atomicWrite` + `createFileWriteQueue`.** Both currently bypass the shared helpers and roll their own read/write paths — outside the scope of the data-versioning PR but worth folding into the same convention. Audit each call site, migrate to the established pattern, run the existing tests. Low-risk mechanical refactor; do it once a CoS PR happens to be open.-- [ ] [data-versioning-cache-invalidation-on-split] **Cache invalidation hooks in `brainStorage.js` / `messageSync.js` / `meatspacePostDrillCache.js` — needed only when their backing collections split.** Per the access-pattern audit during the data-versioning POC, these caches don't touch universe data so they were safe to skip for PR #458. When a future PR splits Brain or Messages collections into per-record `collectionStore` layouts, audit each cache for "cache key ↔ split-record-id" consistency: per-id writes are visible to other readers without going through the cache, so any cache that fronts the now-split file needs an invalidation event hook (or a switch to read-through against `store.loadOne`).+- [ ] [ref-watch-phosphene-bump-ltx2-pin-v0148] **Bump `LTX2_PIN` from `f8f20c83` to v0.14.8 + adopt phosphene's frame_rate / class-rename / a2v / lora-fusion patches together.** From `reference-watch` review of phosphene (2026-05-22). Concrete upstream wins between PortOS's pin and current dgrauet HEAD: VAE auto-tiling that caps peak Metal memory on HD / long runs (#25), `_pending_loras` honored across every pipeline's `load()` override (#22, #23 — fixes silent character-LoRA-drops on Extend/HQ), `--lora` on `--low-ram` flow (#30), accurate transformer load-time markers for progress UI. Cost: in v0.14.x, `TextToVideoPipeline` / `ImageToVideoPipeline` / `ExtendPipeline` / `TwoStagePipeline` / `AudioToVideoPipeline` are all renamed (public surface becomes `TI2VidOneStagePipeline`, `RetakePipeline`, `TI2VidTwoStagesPipeline`, `A2VidPipelineTwoStage`, etc.). `generate_ltx2.py` would fail at import. Source commits: `2166d138` / `770ed0bd` (defensive imports v2), `94ae3430` (method-presence dispatch instead of class assumption), `aa235aa0` (`fps=` → `frame_rate=` shim), `681f429a` (a2v missing `frame_rate=` runtime patch), plus `[ref-watch-phosphene-lazy-eval-env-bootstrap]`. Scope: large (100–200 lines of careful Python touching every pipeline path, plus smoke test of every mode — text/image/fflf/extend/a2v — at the new pin).+ > ❓ **Question:** Do you want to take on this large/risky pin bump now? My recommendation if yes: **ship it as one PR (not per-mode)** — the class renames touch every pipeline's import simultaneously, so a half-migrated state won't even import; one PR with a full five-mode smoke test is safer than partial landings. And do it **after** the post-decode `os._exit(0)` work (`[ref-watch-phosphene-mlx-post-decode-os-exit]`) so the hang-mitigation is in place first. Confirm "yes, one PR, after os._exit" or tell me to defer.+- [ ] [ref-watch-phosphene-sigkill-watchdog-videogen-local] **Panel-side SIGKILL watchdog (Node layer) in `videoGen/local.js`.** From `reference-watch` review of phosphene (commit `94bd6965`, 2026-05-22). Even with helper-side `os._exit(0)` adopted, defense-in-depth at the Node layer is cheap insurance: watch stdout for the upstream "[Decoding video + audio + muxing] done in X.Xs" line (or the final `{"video_path": ...}` JSON), then arm a 30–45s grace timer that SIGKILLs the child if it doesn't exit. PortOS already has SIGTERM→SIGKILL escalation in `cancel()` (`server/services/videoGen/local.js:71-79`); reuse that path. **Trigger:** only do this if real users hit the hang after the pin bump and `os._exit(0)` proves insufficient. Scope: small/medium.+- [ ] [data-versioning-centralize-cosagents-settings] **Centralize `cosAgents.js` + `settings.js` on `atomicWrite` + `createFileWriteQueue`.** Both currently bypass the shared helpers and roll their own read/write paths. Audit each call site, migrate to the established pattern, run the existing tests. Low-risk mechanical refactor; do it once a CoS PR happens to be open.+- [ ] [data-versioning-cache-invalidation-on-split] **Cache invalidation hooks in `brainStorage.js` / `messageSync.js` / `meatspacePostDrillCache.js` — needed only when their backing collections split.** These caches don't touch universe data so they were safe to skip for PR #458. When a future PR splits Brain or Messages collections into per-record `collectionStore` layouts, audit each cache for "cache key ↔ split-record-id" consistency: per-id writes are visible to other readers without going through the cache, so any cache that fronts the now-split file needs an invalidation event hook (or a switch to read-through against `store.loadOne`).- [ ] [data-versioning-typeindex-config-convention] **Establish a convention for the `config` slot on `data/{type}/index.json`.** `createCollectionStore` left `index.json`'s `config` open and unused — the first real consumer (probably the pipeline-issues split's history/runs analog) should pick the shape and document it in `server/lib/README.md` + the `collectionStore.js` header. Candidate shape: `{ config: { runs?: [], featureFlags?: {}, lockPolicies?: {} } }` — but defer the decision to the first real need.-- [ ] [cos-task-id-uniqueness-validation] **CoS task-ID uniqueness — validate at parse, not silently in `reorderTasks`.** Surfaced by gemini review (2026-05-23) on the data-versioning PR (out of scope at the time, captured here). Two related risks: (1) `server/lib/taskParser.js` `parseTasksMarkdown` doesn't detect duplicate task IDs — corrupted markdown propagates downstream; either throw on duplicate or warn + dedupe with a suffix. (2) `server/services/cos.js` `reorderTasks` (~line 2781) builds a `new Map(tasks.map(t => [t.id, t]))` which silently collapses duplicates — only the last wins, losing the others on the reorder write-back. Fix order: harden the parser so reorder can rely on uniqueness, then keep the Map-build as-is or assert uniqueness defensively.-- [ ] [cos-runner-client-non-json-response-handling] **`cosRunnerClient.js` fetch wrappers — handle non-JSON runner responses.** Surfaced by gemini review (2026-05-23). `spawnAgentViaRunner` and siblings (~`server/services/cosRunnerClient.js:139`) `await response.json()` unconditionally; if the runner returns a 500 HTML error page (e.g. PM2 crash mid-restart) the client crashes with `Unexpected token <` instead of surfacing the runner's actual error. Wrap each parse in `try { JSON.parse(text) } catch { { error: text } }` and propagate the synthesized error so the caller sees a useful message.-- [ ] [cos-agent-output-write-amplification] **`appendAgentOutput` write-amplification — already batched via `appendAgentOutputLines`, audit non-runner producers.** Surfaced by gemini review (2026-05-23) at `server/services/cosAgents.js:216`. CLAUDE.md already documents the streaming-producers convention (batched variant + ~250ms debounce + drain on completion); the runner path uses it. Verify every producer that calls `appendAgentOutput` directly is human-pace, not a hot loop (PTY streams, AI tool-call streams). If any hot producer is still calling the per-line variant, migrate it to `appendAgentOutputLines`. Likely a no-op audit; capture it as a check so the convention doesn't silently drift.-- [ ] [cos-on-demand-mark-app-review-started-dedupe] **`evaluateTasks` on-demand loop — dedupe `markAppReviewStarted` calls per app.** Surfaced by gemini review (2026-05-23) at `server/services/cos.js:730`. When multiple on-demand requests for the same app are queued in a single evaluation cycle, `markAppReviewStarted` is called once per request — wasted state writes (single-user / single-instance so not a correctness bug, just churn). Collect unique `appId`s before the loop and call once. Nit-level priority.-- [ ] [subagent-spawner-top-level-side-effects] **`subAgentSpawner.js` top-level side effects — move init into an explicit `initSpawner()`.** Surfaced by gemini review (2026-05-23) at `server/services/subAgentSpawner.js:153`. Module-load wires event listeners + timers, which interferes with test isolation (each test import re-arms them). Wrap the init block in `export function initSpawner()` and call it from `server/index.js` after dependencies are ready. Treat as a refactor — needs care that no consumer of the module relies on the import-time wiring.-- [ ] [ref-watch-phosphene-long-clip-temporal-boost-12fps] **"Long Clip Temporal Boost" (render at 12fps, interpolate to 24fps).** From `reference-watch` review of phosphene (commit `53585fc`, 2026-05-22). Phosphene added a 12fps render path that uses ffmpeg's `minterpolate` / RIFE downstream to fill back to 24fps, doubling the effective clip length per memory budget. PortOS doesn't have an interpolation post-step in `server/services/videoGen/local.js` — adding one is a feature decision, not a bug fix. The math helpers (`_duration_to_8k_frames`, LTX `8k+1` frame-count snapping) are useful regardless; PortOS's `DEFAULT_NUM_FRAMES = 121` is already 8k+1-aligned but UI-side validation could borrow this pattern. **Decision needed:** is this worth a feature surface? No clear user pain motivating it today.-- [ ] [ref-watch-phosphene-t2v-standard-env-gated-two-stage] **Env-gated two-stage T2V perf experiment.** From `reference-watch` review of phosphene (commit `5004b40b`, 2026-05-28). PortOS's `scripts/generate_ltx2.py#run_text` already routes through `TwoStagePipeline` *when `cfg_scale` is set* (~line 221-222) — but the default no-CFG path uses single-stage `TextToVideoPipeline`. Phosphene's experiment routes T2V Standard through `pipe.generate_two_stage()` (half-res Stage 1 + 2× latent upsample + 3-step Stage 2 refine, the same recipe HQ + I2V Standard already use) even without CFG, gated on `PHOSPHENE_T2V_TWO_STAGE=1`. Predicted ~30-35 % wall-time reduction on T2V Standard (M4 Max 7:40 → 5:15 on a 5 s clip; math: 5.0 step-equivalents + ~30 s vs 8.0 step-equivalents native). Fix: in `run_text`, when `cfg_scale is None`, branch on a new `PORTOS_T2V_TWO_STAGE` env (or settings flag) to call `pipe.generate_two_stage(...)` with stage1_steps=8, stage2_steps=3, cfg_scale=1.0. **Decision needed:** worth the A/B knob, or just flip the default to two-stage T2V universally once we've validated quality? Scope: small.+- [ ] [cos-task-id-uniqueness-validation] **CoS task-ID uniqueness — validate at parse, not silently in `reorderTasks`.** Two related risks: (1) `server/lib/taskParser.js` `parseTasksMarkdown` doesn't detect duplicate task IDs — corrupted markdown propagates downstream; either throw on duplicate or warn + dedupe with a suffix. (2) `server/services/cos.js` `reorderTasks` (~line 2781) builds a `new Map(tasks.map(t => [t.id, t]))` which silently collapses duplicates — only the last wins, losing the others on the reorder write-back. Fix order: harden the parser so reorder can rely on uniqueness, then keep the Map-build as-is or assert uniqueness defensively.+- [ ] [cos-runner-client-non-json-response-handling] **`cosRunnerClient.js` fetch wrappers — handle non-JSON runner responses.** `spawnAgentViaRunner` and siblings (~`server/services/cosRunnerClient.js:139`) `await response.json()` unconditionally; if the runner returns a 500 HTML error page (e.g. PM2 crash mid-restart) the client crashes with `Unexpected token <` instead of surfacing the runner's actual error. Wrap each parse in `try { JSON.parse(text) } catch { { error: text } }` and propagate the synthesized error so the caller sees a useful message.+- [ ] [cos-agent-output-write-amplification] **`appendAgentOutput` write-amplification — already batched via `appendAgentOutputLines`, audit non-runner producers.** CLAUDE.md documents the streaming-producers convention (batched variant + ~250ms debounce + drain on completion); the runner path uses it. Verify every producer that calls `appendAgentOutput` directly (`server/services/cosAgents.js:216`) is human-pace, not a hot loop. If any hot producer is still calling the per-line variant, migrate it. Likely a no-op audit; capture it so the convention doesn't silently drift.+- [ ] [cos-on-demand-mark-app-review-started-dedupe] **`evaluateTasks` on-demand loop — dedupe `markAppReviewStarted` calls per app.** When multiple on-demand requests for the same app are queued in a single evaluation cycle (`server/services/cos.js:730`), `markAppReviewStarted` is called once per request — wasted state writes. Collect unique `appId`s before the loop and call once. Nit-level priority.+- [ ] [subagent-spawner-top-level-side-effects] **`subAgentSpawner.js` top-level side effects — move init into an explicit `initSpawner()`.** Module-load (`server/services/subAgentSpawner.js:153`) wires event listeners + timers, which interferes with test isolation (each test import re-arms them). Wrap the init block in `export function initSpawner()` and call it from `server/index.js` after dependencies are ready. Treat as a refactor — needs care that no consumer relies on the import-time wiring.+- [ ] [ref-watch-phosphene-long-clip-temporal-boost-12fps] **"Long Clip Temporal Boost" (render at 12fps, interpolate to 24fps).** From `reference-watch` review of phosphene (commit `53585fc`, 2026-05-22). Phosphene added a 12fps render path that uses ffmpeg's `minterpolate` / RIFE downstream to fill back to 24fps, doubling the effective clip length per memory budget. PortOS doesn't have an interpolation post-step in `server/services/videoGen/local.js`. The math helpers (`_duration_to_8k_frames`, LTX `8k+1` frame-count snapping) are useful regardless.+ > ❓ **Question:** Is a 12fps-render-then-interpolate mode worth a feature surface? It doubles max clip length per memory budget, but there's no user pain motivating it today and minterpolate can introduce artifacts. Want it (I'll scope a `--target-fps` + interpolation post-step), or skip?+- [ ] [ref-watch-phosphene-t2v-standard-env-gated-two-stage] **Env-gated two-stage T2V perf experiment.** From `reference-watch` review of phosphene (commit `5004b40b`, 2026-05-28). PortOS's `run_text` already routes through `TwoStagePipeline` *when `cfg_scale` is set* (~line 221) — but the default no-CFG path uses single-stage. Phosphene's experiment routes T2V Standard through `pipe.generate_two_stage()` (half-res Stage 1 + 2× latent upsample + 3-step Stage 2 refine) even without CFG, gated on an env flag. Predicted ~30-35 % wall-time reduction on T2V Standard. Fix: in `run_text`, when `cfg_scale is None`, branch on a new `PORTOS_T2V_TWO_STAGE` env to call `pipe.generate_two_stage(...)` with stage1_steps=8, stage2_steps=3, cfg_scale=1.0. Scope: small.+ > ❓ **Question:** Land this behind an `A/B env knob` first, or — once you've eyeballed the quality on a couple of test prompts — just flip two-stage on as the universal T2V Standard default? Recommendation: ship the env knob first, validate quality on your prompts, then flip the default in a follow-up. Confirm "env knob first" or "flip default directly."### Duplicate resolution + conflict journal — deferred follow-ups (2026-05-25)-Surfaced while building the sync-hygiene feature (duplicate detection/merge, non-blocking conflict journal, Series→Universe hierarchy). Consciously scoped out of v1.+Surfaced while building the sync-hygiene feature. Consciously scoped out of v1.-- [ ] [conflict-journal-media-collections] **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ (items get unioned, so they're not actually "lost"). Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.+- [ ] [conflict-journal-media-collections] **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ. Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.- [ ] [conflict-journal-issues] **Issue-level conflict journaling.** The share-bucket importer hook (`server/services/sharing/importer.js` `applyAutoMerge`→`mergeOne`) is gated to `universe`/`series`; child issues ride LWW silently. Extend the journal to issues (needs the issue merge path to thread a `source` + call `maybeJournalBeforeOverwrite`).- [ ] [conflict-journal-deep-diff] **`diffSummary` is top-level shallow only.** `conflictJournal.diffSummary` compares top-level fields via canonicalStringify, so the UI shows "categories differ" rather than which variation/canon entry changed. Add per-field deep diffing for richer InlineDiff rendering in the Conflicts tab.-- [ ] [series-merge-season-rehoming] **Series merge re-homes issues un-grouped.** `recordMerge.mergeSeries` re-points the loser series' issues to the survivor via `issues.reassignIssuesToSeries`, which sets `seasonId: null` (seasons are series-scoped, so the loser's season ids don't exist on the survivor; seasons are unioned by number separately). The moved issues land un-grouped and the user must re-assign them to a survivor season. A smarter merge could map loser seasons → survivor seasons by number and preserve issue→season grouping.+- [ ] [series-merge-season-rehoming] **Series merge re-homes issues un-grouped.** `recordMerge.mergeSeries` re-points the loser series' issues to the survivor via `issues.reassignIssuesToSeries`, which sets `seasonId: null` (seasons are series-scoped). The moved issues land un-grouped and the user must re-assign them to a survivor season. A smarter merge could map loser seasons → survivor seasons by number and preserve issue→season grouping.- [ ] [conflict-restore-additive] **"Restore mine" is additive for keyed fields, not a faithful overwrite.** `conflictJournalResolver.resolveConflict` restore-all applies the snapshot via `updateUniverse(id, () => patch)`, which merges `categories` per-key — so a category the user deleted *after* the conflict is resurrected on restore. Acceptable for v1 (resurrect-not-lose), but the UI says "restore your whole version." Consider a true-replace path for restore-all. Surfaced in /code-review (medium).-- [ ] [merge-cascade-no-rollback] **`recordMerge.mergeUniverses`/`mergeSeries` cascade has no rollback.** Union-write survivor → re-point each child → tombstone loser runs as separate awaits; a mid-loop throw (e.g. a child concurrently tombstoned → NOT_FOUND) leaves the survivor merged but the loser un-tombstoned, and a retry trips `ERR_HAS_LIVE_SERIES` on the remaining children. Single-user/low-concurrency so low-probability, but a half-merge has no cleanup. Consider catching per-child and reporting, or finishing the loser tombstone best-effort. Surfaced in /code-review (medium).+- [ ] [merge-cascade-no-rollback] **`recordMerge.mergeUniverses`/`mergeSeries` cascade has no rollback.** Union-write survivor → re-point each child → tombstone loser runs as separate awaits; a mid-loop throw leaves the survivor merged but the loser un-tombstoned, and a retry trips `ERR_HAS_LIVE_SERIES` on the remaining children. Single-user/low-concurrency so low-probability, but a half-merge has no cleanup. Consider catching per-child and reporting, or finishing the loser tombstone best-effort. Surfaced in /code-review (medium).- [ ] [conflict-source-attribution] **Conflict-journal `source` is `via:'sync'/peerId:null` on the peer-push path.** `applyIncomingPush` calls `mergeUniversesFromSync`/`mergeSeriesFromSync` without the `{ source }` arg even though `sourceInstanceId` is in scope, so the Conflicts tab can't attribute which peer collided. Thread `{ via:'peer-push', peerId: sourceInstanceId }` from `applyIncomingPush`. Surfaced in /code-review (low, attribution only).-- [ ] [dup-detect-collection-count-undercount] **`duplicateDetection.collectionItemsByUniverse` last-wins instead of summing.** Uses `.set(universeId, length)` while `seriesByUniverse` accumulates with `+`; if two live collections share a `universeId` (partial-merge/hand-edit), `linkedCollectionItemCount` undercounts the survivor-suggestion heuristic. Sum like the series count. Surfaced in /code-review (low, display only).-- [ ] [conflict-journal-push-flush-coalesce] **Coalesce per-push base-hash flushes.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~947) stamps a base hash and calls `flushBaseHashes()` per pushed universe/series, so a large push loop rewrites `sync_base_hashes.json` once per record. Copilot (PR #489) suggested debouncing. A `setTimeout`-based debounce was tried and reverted because the real unref'd timer leaked into `peerSync.test.js`'s same-file settle-waits and made the suite flaky. A safe coalescing approach (e.g. a microtask/`queueMicrotask` batch within a single push burst, or a test-injectable scheduler) could land the optimization without the timer-leak flake. Low priority — the flush is serialized + fire-and-forget and the file is tiny.+- [ ] [dup-detect-collection-count-undercount] **`duplicateDetection.collectionItemsByUniverse` last-wins instead of summing.** Uses `.set(universeId, length)` while `seriesByUniverse` accumulates with `+`; if two live collections share a `universeId`, `linkedCollectionItemCount` undercounts the survivor-suggestion heuristic. Sum like the series count. Surfaced in /code-review (low, display only).+- [ ] [conflict-journal-push-flush-coalesce] **Coalesce per-push base-hash flushes.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~947) stamps a base hash and calls `flushBaseHashes()` per pushed universe/series, so a large push loop rewrites `sync_base_hashes.json` once per record. A `setTimeout`-based debounce was tried and reverted (the unref'd timer leaked into `peerSync.test.js`'s settle-waits and made the suite flaky). A safe coalescing approach (microtask/`queueMicrotask` batch within a single push burst, or a test-injectable scheduler) could land the optimization without the timer-leak flake. Low priority.- [ ] [conflict-journal-base-hash-prune] **`sync_base_hashes.json` grows unbounded.** `server/lib/conflictJournal.js` seeds a base hash per synced universe/series and never prunes entries for deleted/tombstoned records. Tiny per-entry, but a long-lived install accumulates dead keys. Add a sweep (drop keys whose record no longer resolves) to the tombstone GC path.### Storage scalability — deferred follow-ups (2026-05-26)-- [ ] [media-collections-per-record-store] **Migrate `media-collections.json` to the per-record `createCollectionStore` layout (like universes / issues / series).** Today all collections live in one monolithic `data/media-collections.json`; every `addItem` / `bulkUpdateCollectionItems` rewrites the *entire* file (all collections) through a single `serializeFileWrite` tail — so high-frequency render-filing (cover filer, universe/series auto-collections) serializes unrelated writes and rewrites a ~200 KB doc per image. Convert to `createCollectionStore({ dir: join(PATHS.data,'media-collections'), type: 'mediaCollections', … })` → `data/media-collections/{id}/index.json` + a type-level `index.json`, mirroring migration 034 (`universeBuilder.js`). Cross-install work (per the distribution model): needs a `scripts/migrations/0NN-split-media-collections.js` that fans the monolith out into per-record dirs, a storage `schemaVersion` + boot-time `verifySchemaVersion` hook (`server/index.js`), seed handling, and a careful rewrite of every reader/writer — especially the sync layer (`mergeMediaCollectionsFromSync`, `listCollections({ includeDeleted })`, the push/subscription pipeline in `sharing/peerSync.js`, `pruneTombstonedCollections`) which all currently assume the single-file shape. NOTE: this is **independent of** the LWW cascade duplicate bug fixed 2026-05-26 (cascade unlink no longer bumps `updatedAt`) — migrating storage neither fixes nor requires that. Human-led: large, touches federation — brainstorm/plan before coding.+- [ ] [media-collections-per-record-store] **Migrate `media-collections.json` to the per-record `createCollectionStore` layout (like universes / issues / series).** Today all collections live in one monolithic `data/media-collections.json`; every `addItem` / `bulkUpdateCollectionItems` rewrites the *entire* file through a single `serializeFileWrite` tail — so high-frequency render-filing serializes unrelated writes and rewrites a ~200 KB doc per image. Convert to `createCollectionStore({ dir: join(PATHS.data,'media-collections'), type: 'mediaCollections', … })`, mirroring migration 034 (`universeBuilder.js`). Cross-install work: needs a `scripts/migrations/0NN-split-media-collections.js`, a storage `schemaVersion` + boot-time `verifySchemaVersion` hook, seed handling, and a careful rewrite of every reader/writer — especially the sync layer (`mergeMediaCollectionsFromSync`, `listCollections({ includeDeleted })`, the push/subscription pipeline in `sharing/peerSync.js`, `pruneTombstonedCollections`).+ > ❓ **Question:** Greenlight this now, or defer? It's a large, federation-touching refactor that wants a brainstorm/plan pass before any code. It's independent of any bug (the LWW cascade dup bug was already fixed). My read: defer unless you're hitting real write-amplification pain (lots of auto-collection render-filing) — say the word and I'll start a design doc.### Browser / Chrome-variant + commands hardening (review candidates, 2026-05-25)-Surfaced by a gemini review during PR #489 (sync-hygiene) that scoped beyond that PR's diff — these are in the already-merged Chrome-variant browser feature + the commands service, NOT in #489. Verified against the actual code where noted; out of scope for #489, land them in a separate hardening PR.-- [ ] [commands-centralized-parser] **`commands.js` re-implements command parsing with a naive `split(/\s+/)` instead of the centralized quote-aware parser.** `server/services/commands.js:28` splits on whitespace (breaks quoted args) and only imports `ALLOWED_COMMANDS`/`DANGEROUS_SHELL_CHARS` from `commandSecurity.js` — not its `parseCommandArgs`/`validateCommand`. Route through `validateCommand` so allow-listing, dangerous-char checks, and quote-aware arg parsing are one verified step. Verified (gemini IMPROVEMENT).-- [ ] [setup-browser-canary-headless] **Decide the intended headed/headless default for the managed browser — seed says `true`, code comment says headed.** VERIFIED during the v2.10.0 release review: `data.reference/browser-config.json` ships `"headless": true`, but `browser/server.js`'s header comment says "Default headed" and `headlessMode = config.headless === true`. So a fresh install runs headless, which contradicts the comment AND means opting into Canary at setup runs it invisibly (defeating the "visible differentiated browser" purpose). This is a behavioral decision (intent-ambiguous), so it was deliberately NOT changed in the release: either flip the seed to `"headless": false` AND set `config.headless = false` in `scripts/setup-browser.js#applyCanaryToConfig`, or fix the code comment to say headless-by-default. (gemini IMPROVEMENT; release-review confirmed the seed value.)### Worktree cleanup — deferred follow-ups (2026-05-25)-Surfaced while adding merge-verified worktree reaping (`isBranchMergedInto` + `reapMergedWorktrees`, NEXT.md). These were intentionally left out of that change.--- [ ] [worktree-remove-helper] **Extract the repeated "worktree remove --force → on-fail rm + prune" dance into one helper.** The pattern (`git worktree remove <path> --force`, catch → `rm -rf` + `git worktree prune`) is now inlined in 4 spots in `server/services/worktreeManager.js`: `removeWorktree`, `reapMergedWorktrees`, `cleanupExternalRepoWorktrees`, and `removePersistentWorktree`. Extract `forceRemoveWorktreeDir(repo, worktreePath, label)` and route all four through it. Deferred from the `/simplify` pass on the reaper change because two of the four call sites are outside that feature's diff and the logging context differs slightly per site.-- [ ] [plan-task-prefer-merge] **Switch the `/claim` (`plan-task`) Phase-6 merge order to prefer `--merge` over `--squash`.** The live `plan-task` prompt in `server/services/taskSchedule.js` (~line 562) still tries `gh pr merge --auto || --squash || --merge || --rebase`, so `/claim` squash-merges by default — inconsistent with the new `--merge`-first default now used by the review-loop / `/do:pr` agent prompts (`agentPromptBuilder.js`) and the `pr-reviewer-review` stage prompt. Deferred because: (a) `plan-task` is a **version-migrated** prompt, so the change needs a `PROMPT_VERSIONS['plan-task']` bump (7→8) **and** the v7 default preserved in `PREVIOUS_DEFAULT_PROMPTS['plan-task']` (~190-line byte-exact copy — error-prone); (b) `/claim` self-cleans its worktree/branch in Phase 7 regardless of merge method, so it doesn't contribute to worktree accumulation; and (c) `reapMergedWorktrees` detects squash merges anyway, so cleanup is already correct. Low benefit, non-trivial migration cost — do it as a focused follow-up when touching `plan-task` prompt versioning next.+- [ ] [worktree-remove-helper] **Extract the repeated "worktree remove --force → on-fail rm + prune" dance into one helper.** The pattern is now inlined in 4 spots in `server/services/worktreeManager.js`: `removeWorktree`, `reapMergedWorktrees`, `cleanupExternalRepoWorktrees`, and `removePersistentWorktree`. Extract `forceRemoveWorktreeDir(repo, worktreePath, label)` and route all four through it.+- [ ] [plan-task-prefer-merge] **Switch the `/claim` (`plan-task`) Phase-6 merge order to prefer `--merge` over `--squash`.** The live `plan-task` prompt in `server/services/taskSchedule.js` (~line 562) still tries `gh pr merge --auto || --squash || --merge || --rebase`, so `/claim` squash-merges by default — inconsistent with the `--merge`-first default now used by the review-loop / `/do:pr` agent prompts. Deferred because: (a) `plan-task` is a **version-migrated** prompt, so the change needs a `PROMPT_VERSIONS['plan-task']` bump (7→8) **and** the v7 default preserved in `PREVIOUS_DEFAULT_PROMPTS['plan-task']` (~190-line byte-exact copy); (b) `/claim` self-cleans its worktree/branch regardless of merge method; and (c) `reapMergedWorktrees` detects squash merges anyway. Low benefit, non-trivial migration cost — do it as a focused follow-up when touching `plan-task` prompt versioning next.### Importer provider/model picker — deferred follow-ups (2026-05-26)-Surfaced by the code-review pass on the Importer AI Provider/Model picker (`client/src/pages/Importer.jsx`). Correctness was clean; these are reuse/altitude cleanups deferred to keep the PR focused.--- [ ] [shared-optional-provider-picker] **Add an optional/"Default" mode to the shared provider/model picker and migrate the inline copies.** Three pages now hand-roll the same inline two-`<select>` "Default sentinel + provider + model" picker because the shared `client/src/components/ProviderModelSelector.jsx` + `client/src/hooks/useProviderModels.js` force a selection (no empty option; `useProviderModels` auto-selects the first provider via `hasSetInitialRef`). UniverseBuilder.jsx (~2968-2992) and now Importer.jsx (~437-470, plus its `getProviders`+enabled-filter effect ~93-106 and `llmModels` memo) duplicate the logic in `FeatureProviderPicker.jsx`/`useProviderModels`. Add an `emptyOption={{ value:'', label }}` (or `allowDefault`) prop to `ProviderModelSelector` and an `allowDefault`/`includeEmpty` flag to `useProviderModels` that skips the auto-select, then refactor both Importer and UniverseBuilder to consume them — removing ~30 lines of JSX from each and the six prop-drilled values into `IntakeForm`. Note the importer's default label must stay accurate to its *per-stage* resolution (`stage.provider` → active), so a single "active provider (name)" label like UniverseBuilder's would be misleading for the importer — keep a generic "Default" label unless the picker is taught the resolved-per-stage provider. Cleanup only; no behavior change. Surfaced 2026-05-26.-- [ ] [importer-screenplay-teleplay-seed] **Mirror the comic-script verbatim-seed for screenplay imports → `stages.teleplay`.** The comic-script import now seeds the verbatim script into `stages.comicScript` (ready) instead of `stages.prose`, so the pipeline doesn't regenerate it (`commitImport` in `server/services/importer.js`, via the `CONTENT_TYPE_SEED_STAGE` table). Adding screenplay is now a one-row change: `'screenplay': 'teleplay'`. Also extend the auto-run script-first guard in `autoRunner.js` (currently checks `comicScript || teleplay` already, so likely covered) and check whether any downstream teleplay consumer parses a specific format (the comic path needed `parseComicScript` taught the bare `PAGE/PANEL` form — teleplay may or may not have an analogous parser). Deferred to keep the 2026-05-26 PR scoped to comics, which is what the user was importing. Surfaced 2026-05-26.+- [ ] [shared-optional-provider-picker] **Add an optional/"Default" mode to the shared provider/model picker and migrate the inline copies.** Three pages now hand-roll the same inline two-`<select>` "Default sentinel + provider + model" picker because the shared `ProviderModelSelector.jsx` + `useProviderModels.js` force a selection. UniverseBuilder.jsx (~2968) and Importer.jsx (~437, plus its `getProviders`+enabled-filter effect ~93 and `llmModels` memo) duplicate the logic in `FeatureProviderPicker.jsx`/`useProviderModels`. Add an `emptyOption`/`allowDefault` prop to `ProviderModelSelector` and an `allowDefault`/`includeEmpty` flag to `useProviderModels` that skips the auto-select, then refactor both. Note the importer's default label must stay accurate to its *per-stage* resolution. Cleanup only; no behavior change.+- [ ] [importer-screenplay-teleplay-seed] **Mirror the comic-script verbatim-seed for screenplay imports → `stages.teleplay`.** The comic-script import now seeds the verbatim script into `stages.comicScript` (ready) instead of `stages.prose`, via the `CONTENT_TYPE_SEED_STAGE` table. Adding screenplay is a one-row change: `'screenplay': 'teleplay'`. Also extend the auto-run script-first guard in `autoRunner.js` (currently checks `comicScript || teleplay` already) and check whether any downstream teleplay consumer parses a specific format (the comic path needed `parseComicScript` taught the bare `PAGE/PANEL` form).### Importer backport/merge code-review follow-ups (2026-05-26)-Lower-severity findings from the xhigh code-review of the importer feature; the correctness/data-loss bugs (greedy speaker-cue, dropped panels, prose-cap dead-end, header false-positives, auto-run spurious prose) were fixed inline. These were deferred:--- [ ] [importer-progress-hook] **Extract a `useImporterProgress` hook.** The `importer:progress` socket subscription is hand-rolled in `client/src/pages/Importer.jsx` (~60-86) — raw `socket.on/off` + `activeRunIdRef` runId-filter in a page `useEffect`, duplicating the lifecycle already factored into `useImageGenProgress` / `useMediaJobProgress` / `usePipelineAutoRunProgress`. Extract to `client/src/hooks/useImporterProgress.js`, register in the hooks `index.js` barrel + README (module-org rule: socket clients live in hooks, not pages). Also fold the `ImporterProgress` checklist's status→icon ternary into a shared lookup (it's the 3rd inline copy; `CreateApp.jsx` has another that already drifted Loader vs Loader2). Cleanup only. Surfaced 2026-05-26.-- [ ] [importer-progress-reconnect] **Live checklist stalls if the socket misses the `start` frame.** The `importer:progress` handler gates every `stage` frame on a runId set only by a `start` frame; a mid-analyze socket reconnect (or out-of-order delivery) means stage frames are dropped and the checklist stays on "Starting…" until analyze resolves. Degrades gracefully (falls back to the old spinner), so low priority. Fix: if a `stage` frame arrives while `analyzing` with no active runId, adopt it and lazily seed the stage list, OR have the server resend `start` on (re)subscribe. Surfaced 2026-05-26.-- [ ] [importer-retry-arcsummary-empty] **Retry's `arcSummary` uses `||` truthiness, dropping an intentionally-cleared summary.** `runRetryIssues` in `Importer.jsx` builds `arcDraft?.summary || arcDraft?.logline || ''`, so clearing the summary in Review falls back to the logline rather than sending none — violates the absent-vs-intentionally-empty rule the rest of the feature follows. Non-fatal (arcSummary is cosmetic prompt context). Fix: treat `summary === ''` as an intentional clear (`summary == null ? logline : summary`). Surfaced 2026-05-26.-- [ ] [importer-orphan-shell-gc] **An abandoned analyze leaves an empty universe/series shell on disk.** `analyzeImport` persists universe+series after canon+arc succeed (the chosen "keep review flow + retry" tradeoff), so if the user abandons after an issue-split failure (or just never commits) on a brand-new universe/series, empty shells linger in `data/`. By-design, but a periodic GC of zero-issue, zero-canon shells older than N days (or marking analyze-created shells `ephemeral` until commit promotes them) would keep `data/` clean. Surfaced 2026-05-26.+- [ ] [importer-progress-hook] **Extract a `useImporterProgress` hook.** The `importer:progress` socket subscription is hand-rolled in `client/src/pages/Importer.jsx` (~60-86) — raw `socket.on/off` + `activeRunIdRef` runId-filter in a page `useEffect`, duplicating the lifecycle already factored into `useImageGenProgress` / `useMediaJobProgress` / `usePipelineAutoRunProgress`. Extract to `client/src/hooks/useImporterProgress.js`, register in the hooks `index.js` barrel + README. Also fold the `ImporterProgress` checklist's status→icon ternary into a shared lookup.+- [ ] [importer-progress-reconnect] **Live checklist stalls if the socket misses the `start` frame.** The `importer:progress` handler gates every `stage` frame on a runId set only by a `start` frame; a mid-analyze socket reconnect means stage frames are dropped and the checklist stays on "Starting…" until analyze resolves. Degrades gracefully. Fix: if a `stage` frame arrives while `analyzing` with no active runId, adopt it and lazily seed the stage list, OR have the server resend `start` on (re)subscribe.+- [ ] [importer-retry-arcsummary-empty] **Retry's `arcSummary` uses `||` truthiness, dropping an intentionally-cleared summary.** `runRetryIssues` in `Importer.jsx` builds `arcDraft?.summary || arcDraft?.logline || ''`, so clearing the summary in Review falls back to the logline rather than sending none — violates the absent-vs-intentionally-empty rule. Non-fatal. Fix: treat `summary === ''` as an intentional clear (`summary == null ? logline : summary`).+- [ ] [importer-orphan-shell-gc] **An abandoned analyze leaves an empty universe/series shell on disk.** `analyzeImport` persists universe+series after canon+arc succeed, so if the user abandons after an issue-split failure on a brand-new universe/series, empty shells linger in `data/`. By-design, but a periodic GC of zero-issue, zero-canon shells older than N days (or marking analyze-created shells `ephemeral` until commit promotes them) would keep `data/` clean.### v2.11.0 release-review follow-ups (2026-05-27)-Surfaced by the multi-reviewer release gate for v2.11.0. The correctness/contract findings were fixed in-release (comic two-speaker-panel attribution, editorial-analysis pipe-enum prompt corruption + migration 042, `agentLifecycle` fallback-provider map shape, weather half-set-coordinate pairing, plus several comment-accuracy nits). This item was deferred as a non-blocking hardening gap.--- [ ] [comic-allcaps-continuation-vs-cue] **`normalizeBareComicScript` in `server/lib/comicScriptParser.js` (~line 193) can misread a short all-caps continuation line (e.g. a bare `STOP` on its own line, mid-balloon) as a new speaker cue.** The continuation branch's `!BARE_SPEAKER_LINE.test(t)` guard exists so a genuine second speaker (`GIANT` … `KESSA`) opens a new balloon — but an all-caps shouted continuation with no punctuation matches the same shape and gets treated as a cue instead of GIANT's next line. This is the inherent flip-side of the two-speaker fix: an all-caps line in *continuation* position is genuinely ambiguous between "shout" and "new cue," and the current heuristic favors "new cue" (the more common multi-speaker-panel case; shouts usually carry `!`/`?` which already excludes them). A proper fix needs one-line lookahead (a real cue is followed by its own dialogue line; a trailing shout is followed by a marker/EOF) — which means converting the `for…of` line loop to indexed iteration. Deferred from the v2.11.0 release review (gemini) as IMPROVEMENT: flipping the heuristic instead would regress the more-common multi-speaker case. Surfaced 2026-05-27.-- [ ] [voice-taskcomplete-announce-once-guard] **`onTaskUpdated` in `server/services/voice/proactiveTriggers.js` (~line 193) re-announces if an already-completed voice-dispatched task is updated again.** The spoken "your coding task is done" line keys on `tasks:changed action:'updated'` + terminal status (`completed`/`blocked`) + `voiceDispatch`, with no record of already-announced task ids — so any future caller that runs `updateTask` on an already-completed voice-dispatched task (e.g. attaching a PR URL or metadata *after* marking it completed) would re-fire the announcement. The comment claims it "announces once (at its terminal outcome)," which holds only because no current caller re-updates completed tasks. Fix: track announced task ids in a `Set` in the closure (clear on unwire) and skip if already announced, OR gate on the previous→terminal status *transition* if the event carries the prior status. Low severity (no current re-update path; worst case is a duplicate spoken line, not data loss) — deferred per YAGNI since the path doesn't exist today. Surfaced 2026-05-27.+- [ ] [comic-allcaps-continuation-vs-cue] **`normalizeBareComicScript` in `server/lib/comicScriptParser.js` (~line 193) can misread a short all-caps continuation line (e.g. a bare `STOP` mid-balloon) as a new speaker cue.** The continuation branch's `!BARE_SPEAKER_LINE.test(t)` guard exists so a genuine second speaker opens a new balloon — but an all-caps shouted continuation with no punctuation matches the same shape. A proper fix needs one-line lookahead (a real cue is followed by its own dialogue line; a trailing shout is followed by a marker/EOF) — which means converting the `for…of` line loop to indexed iteration. Deferred as IMPROVEMENT: flipping the heuristic instead would regress the more-common multi-speaker case.+- [ ] [voice-taskcomplete-announce-once-guard] **`onTaskUpdated` in `server/services/voice/proactiveTriggers.js` (~line 193) re-announces if an already-completed voice-dispatched task is updated again.** The spoken "your coding task is done" line keys on `tasks:changed action:'updated'` + terminal status + `voiceDispatch`, with no record of already-announced task ids — so a future caller that runs `updateTask` on an already-completed voice-dispatched task would re-fire the announcement. Fix: track announced task ids in a `Set` in the closure (clear on unwire), OR gate on the previous→terminal status *transition*. Low severity — deferred per YAGNI since the re-update path doesn't exist today.### Unified Story Builder — deferred follow-ups (2026-05-27)-The first slice shipped a working **seed-mode** conductor (`/story-builder`): create → idea → universeAesthetic → plotArc → readerMap → characters → issues (deep-link handoff) → production, with per-step lock gating and soft-flag integrity staleness. New code: `server/services/storyBuilder.js`, `server/routes/storyBuilder.js`, `server/lib/storyBuilderSteps.js`, `server/lib/storyBuilderIntegrity.js`, `client/src/pages/StoryBuilder.jsx`, `client/src/services/apiStoryBuilder.js`, plus `series.arc.readerMap` (new field + `generateReaderMap`/`refineReaderMap` in `arcPlanner.js`, prompts + migration 043, `pipelineSeries` schema → 2). These are the deliberately-deferred pieces:--- [ ] [story-builder-import-aesthetic-readermap-gaps] **Import pre-fills arc/characters/issues but NOT universe aesthetic or reader map.** `analyzeImport` creates the universe with only a name (no logline/premise/styleNotes/influences) and the importer never extracts a reader map — yet `createStorySession` import-branch marks every step `ready`. So in an imported session the universeAesthetic + readerMap steps show empty content under a misleading "Ready" badge; the user must Generate them in-wizard. Mitigations already in place: the session `seedIdea` is seeded from the extracted arc summary so the aesthetic Expand has a real starter, and generateStep's expand falls back through `seedIdea`→universe name (won't crash). Follow-up: either mark only the importer-filled steps `ready` (others `pending`), or extract a starter/aesthetic + reader-map pass during import. Surfaced building import mode (2026-05-27).-- [ ] [story-builder-issue-llm-seeding] **Seed issues from the arc inside the builder.** The `issues` step currently lists existing issues (from `listPipelineIssues`) and links out to the Pipeline to create/produce them. Add a "Generate issues from arc" action that calls `generateSeasonEpisodes` (arcPlanner) per season and persists via `createIssue`, so the user doesn't have to leave the builder to break the arc into issues. Per-issue lock + production handoff already work.-- [ ] [story-builder-sse-progress] **SSE streaming for long generations.** `generateStep`/`refineStep` are synchronous request/response (await the LLM, return the result) — fine for arc/reader-map but a long arc-overview blocks the button with only a spinner. Add a `GET /api/story-builder/:id/steps/:stepId/progress` EventSource endpoint (reuse `client/src/hooks/useSseProgress.js`) and stream stage progress like the pipeline auto-run does. The plan specced this; deferred as a v1 simplification.-- [ ] [story-builder-arc-refine-feedback] **AI refine-with-feedback for the plot-arc step.** `refineStep` supports `universeAesthetic` (via `refineWorldPrompts`), `readerMap` (`refineReaderMap`), and `characters` (`refineUniverseCharacter`), but `plotArc` only offers full regenerate (`generateArcOverview`) — there's no "refine the arc against this note" path. Add an arc-refine prompt + `refineArc` in `arcPlanner.js` and wire it into `refineStep`'s `plotArc` branch + the `StepPanel` plotArc RefineBox.-- [ ] [story-builder-embed-arccanvas] **Embed `ArcCanvas` / `StoryShapes` inline instead of read-only field blocks.** The plotArc + readerMap steps currently render read-only `FieldBlock`s + a deep-link to the Pipeline for editing. The plan called for reusing `client/src/components/pipeline/ArcCanvas.jsx` and the Vonnegut `StoryShapes` sparkline inline (and a beat timeline for the reader map). Embed them so editing happens in-builder. Deferred because `ArcCanvas` has a wide prop surface; the deep-link covers editing for v1.-- [ ] [story-builder-create-rollback] **`createStorySession` seed mode leaves an orphan universe if `createSeries` throws.** `server/services/storyBuilder.js` creates the universe shell, then the series shell, with no rollback — a `createSeries` failure (validation, disk, peer-import) leaves a stray universe (which also fired peer auto-subscribe) with no session pointing at it. Low severity under the single-user trust model, but repeated failed creates accumulate orphans. Wrap the two creates so a series failure deletes the just-created universe, or create the series first. Surfaced by the xhigh code-review (2026-05-27); deferred as non-blocking.-- [ ] [story-builder-goto-step-gate-divergence] **Two `setStoryCurrentStep` paths swallow a rejection and navigate anyway.** (a) `goToStep` in `client/src/pages/StoryBuilder.jsx` (~line 769) on a manual step click and (b) the `lock.toggle` `onSuccess` auto-advance after a successful "Lock & continue" (~line 754). If the server re-gate (fresh hashes) rejects the move while the client's `staleSteps` is stale, the UI lands on the target step but the persisted `currentStep` pointer stays behind, so reopening the session drops the user on a different step. Low severity (disabled controls prevent most cases). Either toast + revert nav on rejection, or refetch on failure. Both paths share the fix. Surfaced by the xhigh code-review (2026-05-27); auto-advance path also surfaced by the codex/gemini local-review pass (2026-05-27).-- [ ] [story-builder-import-partial-commit] **Import flow doesn't handle a partial commit.** `ImportPanel.importAndBuild` (`client/src/pages/StoryBuilder.jsx`) calls `commitImport` once; if it fails after the universe/arc/canon persist but the issue-create rolls back (`IMPORTER_PARTIAL_COMMIT_ISSUES`/`arcAlreadyPersisted`), it just toasts a generic error. Re-clicking re-sends the full payload — lower-risk than the standalone Importer (no editable preview, so arc/seasons are the same idempotent values) but a retry could duplicate issues. The standalone `Importer.jsx` guards this with the `arcAlreadyPersisted` retry (sends `arc:null, seasons:[]`). Either reuse that path or surface a "open in the Importer to recover" link. Surfaced by xhigh code-review (2026-05-27); deferred — rare, not data-corruption.-- [ ] [universe-styleImageRefs-wire-and-journal] **`styleImageRefs` is wire-synced but not version-gated, and feeds the conflict-journal content hash.** Confirmed by review: `sanitizeRecordForWire('universe')` ships `styleImageRefs` to peers; an older (field-unaware) peer drops it on receive and, after its own edit bumps `updatedAt`, LWW-strips it back off a newer peer (same class as the readerMap bug, deliberately left ungated since a probe is one-click-regenerable). Separately, `contentHashForRecord` now includes `styleImageRefs`, so a probe render can contribute to a 3-way-divergence conflict-journal entry whose diff won't mention it (`RESTORABLE_FIELDS.universe` omits it) — Conflicts-tab noise on mixed-version federations. Options if it becomes annoying: bump the `universes` schema version (gate it), make `styleImageRefs` local-only (strip from wire), or exclude it from the content hash. Surfaced 2026-05-27; deferred — low-stakes, regenerable.-- [ ] [story-builder-extract-image-render-hook] **Cleanup: the image-render lifecycle is duplicated 5×.** `StepCharacters` (StoryBuilder.jsx) + `StyleProbeImage.jsx` each re-implement `getSettings → readPipelineImageSettings → imageCfg` + a single-render jobId lifecycle, and `StepCharacters` near-verbatim copies `UniverseCanonSection`'s styled-render-and-persist routine (the `getSettings→imageCfg` block alone repeats in NounsStage/ComicScriptStage/UniverseBuilder too). Extract a `useImageRenderSettings()` + `useSingleImageRender({ buildPrompt, onComplete })` hook (home: `client/src/hooks/`) and a shared canon styled-render helper. Also: `ProviderModelPicker` (StoryBuilder.jsx) duplicates the Importer's `LlmPicker` + the `SeriesLlmPicker`/`FeatureProviderPicker`/`StagePromptModelPicker` pattern — promote one shared provider/model picker. Surfaced by xhigh code-review (2026-05-27); deferred — tech debt, not a bug.-- [ ] [story-builder-session-sync] **Optional cross-machine resumable sessions.** Sessions are intentionally local-only in v1 (excluded from peer sync — see `storyBuilder.js` header). If cross-machine resume is wanted later, key the staleness model on a content hash carried in the session (the integrity helper already produces one) rather than live-record diffing, so a peer's universe edit doesn't false-positive-stale the local session.-- [ ] [story-builder-step-content-staleness] **Upstream-hash detects when a step's INPUTS drift, not when its OUTPUTS are edited out-of-band.** A user can lock the universeAesthetic step, then mutate `universe.logline` directly in Universe Builder, and the aesthetic step lock won't flag stale (the lock is supposed to prevent mutation, but the lock is only soft — it gates the StoryBuilder UI, not the underlying universe record). Same shape for the characters step's `cast`. Either: (i) extend `buildUpstreamInputs` to fingerprint each step's *own outputs* as well as upstream inputs, treating any post-lock mutation as stale (UX over correctness — the integrity hash starts conflating "upstream drift" with "tampering"), or (ii) enforce harder locks at the underlying-record layer so out-of-band edits 400 while a story-builder step is locked. Surfaced by local-review (2026-05-27); deferred — current behavior matches the design intent of "upstream-only" hashing.-- [ ] [story-builder-refine-returns-provider] **`refineStep('readerMap')` drops `providerId`/`model` from the conductor's return.** Every other refine branch surfaces them so the route/UI can show which model ran; the readerMap branch destructures `runId` only. Two-line fix (see local-review SC-6, 2026-05-27).-- [ ] [story-builder-refine-fallback-changes] **`refineReaderMap` returns `changes`/`rationale` describing a refine attempt that was discarded in favor of the existing map.** When the LLM payload is empty, the function falls back to `arc.readerMap` but still surfaces the change list the LLM described, so the UI shows a non-empty change list describing a value that wasn't applied. Fix: when falling back, clear `changes` and `rationale`. Surfaced by local-review SC-7 (2026-05-27).-- [ ] [story-builder-hash-shape-vs-derivation-tests] **storyBuilder.test.js asserts `upstreamHash` is a 64-char hex string but never that it equals `hashUpstream(stepId, inputs)`.** A buggy implementation that always stamped `hashUpstream('idea', null)` would also pass. Import `hashUpstream` and assert exact equality so future input-set drift (the deferred staleness item above) surfaces as a test failure. Surfaced by local-review SC-8 (2026-05-27).-- [ ] [migration-043-line-ending-precedent] **Migration 043 (story-builder prompts) is first-shipment-only — no OLD_SHIPPED_MD5 hashing.** That's correct today: the prompts haven't shipped to anyone, so a hash-compare-and-update would be no-op. But the precedent matters: when a future migration AMENDS these prompts, follow migration 003's pattern — normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing, and ship both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` so existing installs whose copy still matches the prior shipped hash auto-upgrade. Add a one-line reminder comment to the migration. Surfaced by local-review SS-3 (2026-05-27).-- [ ] [style-probe-image-uses-draft-not-saved] **`<StyleProbeImage>` in Universe Builder renders against the in-memory draft but persists the resulting filename to the SERVER's saved record.** A probe image semantically built from in-progress styleNotes/influences gets pinned to a saved universe whose actual style fields are still on the prior values; once the user discards the draft, the styleImageRefs persists on a record that never had those style notes. Either gate `canRender` on `!draftDirty` (require save first — but users want to evaluate unsaved edits) or warn when the draft has uncommitted style changes. Story Builder's aesthetic step is fine because it persists before render. Surfaced by local-review C-5 (2026-05-27).+- [ ] [story-builder-import-aesthetic-readermap-gaps] **Import pre-fills arc/characters/issues but NOT universe aesthetic or reader map.** `analyzeImport` creates the universe with only a name (no logline/premise/styleNotes/influences) and the importer never extracts a reader map — yet `createStorySession` import-branch marks every step `ready`. So in an imported session the universeAesthetic + readerMap steps show empty content under a misleading "Ready" badge. Mitigations in place: the session `seedIdea` is seeded from the extracted arc summary, and generateStep's expand falls back through `seedIdea`→universe name. Follow-up: either mark only the importer-filled steps `ready` (others `pending`), or extract a starter/aesthetic + reader-map pass during import.+- [ ] [story-builder-issue-llm-seeding] **Seed issues from the arc inside the builder.** The `issues` step currently lists existing issues and links out to the Pipeline to create/produce them. Add a "Generate issues from arc" action that calls `generateSeasonEpisodes` (arcPlanner) per season and persists via `createIssue`, so the user doesn't have to leave the builder. Per-issue lock + production handoff already work.+- [ ] [story-builder-sse-progress] **SSE streaming for long generations.** `generateStep`/`refineStep` are synchronous request/response — fine for arc/reader-map but a long arc-overview blocks the button with only a spinner. Add a `GET /api/story-builder/:id/steps/:stepId/progress` EventSource endpoint (reuse `client/src/hooks/useSseProgress.js`) and stream stage progress like the pipeline auto-run does.+- [ ] [story-builder-arc-refine-feedback] **AI refine-with-feedback for the plot-arc step.** `refineStep` supports `universeAesthetic`, `readerMap`, and `characters`, but `plotArc` only offers full regenerate (`generateArcOverview`) — there's no "refine the arc against this note" path. Add an arc-refine prompt + `refineArc` in `arcPlanner.js` and wire it into `refineStep`'s `plotArc` branch + the `StepPanel` plotArc RefineBox.+- [ ] [story-builder-embed-arccanvas] **Embed `ArcCanvas` / `StoryShapes` inline instead of read-only field blocks.** The plotArc + readerMap steps currently render read-only `FieldBlock`s + a deep-link to the Pipeline for editing. Reuse `client/src/components/pipeline/ArcCanvas.jsx` and the Vonnegut `StoryShapes` sparkline inline (and a beat timeline for the reader map) so editing happens in-builder. Deferred because `ArcCanvas` has a wide prop surface; the deep-link covers editing for v1.+- [ ] [story-builder-create-rollback] **`createStorySession` seed mode leaves an orphan universe if `createSeries` throws.** `server/services/storyBuilder.js` creates the universe shell, then the series shell, with no rollback — a `createSeries` failure leaves a stray universe (which also fired peer auto-subscribe) with no session pointing at it. Wrap the two creates so a series failure deletes the just-created universe, or create the series first.+- [ ] [story-builder-goto-step-gate-divergence] **Two `setStoryCurrentStep` paths swallow a rejection and navigate anyway.** (a) `goToStep` in `client/src/pages/StoryBuilder.jsx` (~line 769) on a manual step click and (b) the `lock.toggle` `onSuccess` auto-advance (~line 754). If the server re-gate rejects the move while the client's `staleSteps` is stale, the UI lands on the target step but the persisted `currentStep` pointer stays behind. Either toast + revert nav on rejection, or refetch on failure. Both paths share the fix.+- [ ] [story-builder-import-partial-commit] **Import flow doesn't handle a partial commit.** `ImportPanel.importAndBuild` calls `commitImport` once; if it fails after the universe/arc/canon persist but the issue-create rolls back, it just toasts a generic error. Re-clicking re-sends the full payload — a retry could duplicate issues. The standalone `Importer.jsx` guards this with the `arcAlreadyPersisted` retry (sends `arc:null, seasons:[]`). Either reuse that path or surface a "open in the Importer to recover" link.+- [ ] [universe-styleImageRefs-wire-and-journal] **`styleImageRefs` is wire-synced but not version-gated, and feeds the conflict-journal content hash.** `sanitizeRecordForWire('universe')` ships `styleImageRefs` to peers; an older peer drops it on receive and, after its own edit bumps `updatedAt`, LWW-strips it back off a newer peer. Separately, `contentHashForRecord` now includes `styleImageRefs`, so a probe render can contribute to a 3-way-divergence conflict-journal entry whose diff won't mention it (`RESTORABLE_FIELDS.universe` omits it). Options if it becomes annoying: bump the `universes` schema version (gate it), make `styleImageRefs` local-only (strip from wire), or exclude it from the content hash. Deferred — low-stakes, regenerable.+- [ ] [story-builder-extract-image-render-hook] **Cleanup: the image-render lifecycle is duplicated 5×.** `StepCharacters` (StoryBuilder.jsx) + `StyleProbeImage.jsx` each re-implement `getSettings → readPipelineImageSettings → imageCfg` + a single-render jobId lifecycle, and `StepCharacters` near-verbatim copies `UniverseCanonSection`'s styled-render-and-persist routine. Extract a `useImageRenderSettings()` + `useSingleImageRender({ buildPrompt, onComplete })` hook and a shared canon styled-render helper. Also: `ProviderModelPicker` (StoryBuilder.jsx) duplicates the Importer's `LlmPicker` + `SeriesLlmPicker`/`FeatureProviderPicker`/`StagePromptModelPicker` — promote one shared provider/model picker.+- [ ] [story-builder-session-sync] **Optional cross-machine resumable sessions.** Sessions are intentionally local-only in v1 (excluded from peer sync). If cross-machine resume is wanted later, key the staleness model on a content hash carried in the session (the integrity helper already produces one) rather than live-record diffing, so a peer's universe edit doesn't false-positive-stale the local session.+- [ ] [story-builder-step-content-staleness] **Upstream-hash detects when a step's INPUTS drift, not when its OUTPUTS are edited out-of-band.** A user can lock the universeAesthetic step, then mutate `universe.logline` directly in Universe Builder, and the aesthetic step lock won't flag stale (the lock is only soft — it gates the StoryBuilder UI, not the underlying universe record). Either: (i) extend `buildUpstreamInputs` to fingerprint each step's *own outputs* as well, treating any post-lock mutation as stale, or (ii) enforce harder locks at the underlying-record layer. Deferred — current behavior matches the "upstream-only" hashing design intent.+- [ ] [story-builder-refine-returns-provider] **`refineStep('readerMap')` drops `providerId`/`model` from the conductor's return.** Every other refine branch surfaces them so the route/UI can show which model ran; the readerMap branch destructures `runId` only. Two-line fix (local-review SC-6, 2026-05-27).+- [ ] [story-builder-refine-fallback-changes] **`refineReaderMap` returns `changes`/`rationale` describing a refine attempt that was discarded in favor of the existing map.** When the LLM payload is empty, the function falls back to `arc.readerMap` but still surfaces the change list the LLM described. Fix: when falling back, clear `changes` and `rationale`. (local-review SC-7, 2026-05-27).+- [ ] [story-builder-hash-shape-vs-derivation-tests] **storyBuilder.test.js asserts `upstreamHash` is a 64-char hex string but never that it equals `hashUpstream(stepId, inputs)`.** A buggy implementation that always stamped `hashUpstream('idea', null)` would also pass. Import `hashUpstream` and assert exact equality so future input-set drift surfaces as a test failure. (local-review SC-8, 2026-05-27).+- [ ] [migration-043-line-ending-precedent] **Migration 043 (story-builder prompts) is first-shipment-only — no OLD_SHIPPED_MD5 hashing.** Correct today (the prompts haven't shipped to anyone). But the precedent matters: when a future migration AMENDS these prompts, follow migration 003's pattern — normalize line endings before hashing, and ship both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5`. Add a one-line reminder comment to the migration. (local-review SS-3, 2026-05-27).+- [ ] [style-probe-image-uses-draft-not-saved] **`<StyleProbeImage>` in Universe Builder renders against the in-memory draft but persists the resulting filename to the SERVER's saved record.** A probe image semantically built from in-progress styleNotes/influences gets pinned to a saved universe whose actual style fields are still on the prior values; once the user discards the draft, the styleImageRefs persists on a record that never had those style notes. Either gate `canRender` on `!draftDirty`, or warn when the draft has uncommitted style changes. (local-review C-5, 2026-05-27).## Deferred-- [ ] [consolidate-client-url-normalize] **Consolidate client-side URL normalization.** Three components prepend `https://` to a bare URL with near-identical logic: `normalizeUrl` in `client/src/components/brain/tabs/LinksTab.jsx`, the inline block in `client/src/components/QuickBrainCapture.jsx` (~line 34, with `URL_PATTERN`/`DOMAIN_PATTERN` regexes), and `client/src/components/brain/tabs/FeedsTab.jsx` (~line 50, no `git@` handling). Extract one `normalizeUrl`/`isUrl` pair to a shared `client/src/utils/` helper and migrate all three. Skipped during the buckets PR /simplify (2026-05-28) because a correct consolidation touches two unrelated components and must preserve each one's subtly different behavior (FeedsTab ignores `git@`; QuickBrainCapture splits detection from normalization).-- [ ] [brain-bucket-chip-reorder] **Drag-to-reorder chips *within* a bucket.** The Brain → Links bucket board (`client/src/components/brain/links/BucketBoard.jsx` + `BucketCard.jsx`) supports dragging a chip *between* buckets and reordering buckets, but not repositioning a chip within its own bucket — `bucketOrder` is only ever appended (max+1) on assign. Add intra-bucket position-aware drop (compute target index from the drop location, renumber `bucketOrder`, persist via `updateBrainLink`). Skipped in the initial buckets PR (2026-05-28) to avoid fragile drop-index math; chips currently sort by `bucketOrder` then insertion order, which is fine for the common case.-- [ ] [hidream-qwen-loras-runner-consumers] **Wire HIDREAM/QWEN through `client/src/pages/Loras.jsx`.** `imageGenResolutions.js` was extended on 2026-05-28 (`compatibilityKey` now returns HIDREAM/QWEN as their own keys; `1024×1536` / `1536×1024` / `1536×1536` plus a new Qwen-only `1328×2048` comic draft preset opened to them). Still pending: `client/src/pages/Loras.jsx` `RUNNER_LABELS` / `RUNNER_BG_COLORS` / Top-LoRA section list omit HIDREAM/QWEN so the LoRA picker shows them as unlabeled / no badge color. Surfaced by /do:review of PR #516 (2026-05-28).-- [ ] [wan22-hunyuan-setup-pin-shas] **Pin Wan22 / HunyuanVideo MLX clones to known-good commit SHAs.** `scripts/setup-image-video.sh` defaults `WAN22_PIN="${WAN22_PIN:-main}"` and `HUNYUAN_PIN="${HUNYUAN_PIN:-main}"`. Floating `main` on two community-maintained ports with unpinned CLIs (the PR description explicitly flags both as experimental — "if upstream renames args, flip the registry entry broken: true") means every new install gets whatever HEAD is on those repos that day. Replace the default with a tested SHA for each; let users override via the env var (same shape as the diffusers pin). Surfaced by /do:review of PR #516 (2026-05-28).-- [ ] [memory-mgmt-new-endpoint-tests] **Add tests for the 5 new memory-management routes.** `/api/local-llm/loaded`, `/api/local-llm/unload`, `/api/voice/whisper`, `/api/voice/tts/status`, `/api/voice/tts/unload` have no test coverage. The PR description claims "8062/8062 tests passing" — true for the existing suite, but no asserts pin the new wire contracts (response shapes, residency precondition, validation rejection). Add focused happy-path + validation-rejection tests so future regressions in the schema-parity fixes (or the `unloadModel` residency check) surface as test failures. Surfaced by /do:review of PR #516 (2026-05-28).-- [ ] [qwen-image-edit-init-image-required] **Qwen-Image-Edit dispatches without its required init image.** `qwen-image-edit` (registry `mediaModels.js:202`) loads `QwenImageEditPipeline` which requires an `image` arg; the entry is exposed in the normal image-gen model picker which permits text-only submission. Today the user picks the model, submits a text prompt, and the runner crashes deep inside the diffusers pipeline after loading the 20B-param model from disk. Options: (a) add an `editOnly: true` flag to the model + validate at `routes/imageGen.js` POST; (b) filter the model from the picker when no source image is uploaded; (c) reroute through a future `/api/image-gen/edit` endpoint. Touches the image route schema + UI gating — defer to a focused PR. Surfaced by codex review of PR #516 (2026-05-28).-- [ ] [hidream-requires-hf-token-fail-fast] **Probe HF token upfront for HiDream gated-encoder downloads.** `data.reference/media-models.json`'s HiDream entries carry `requiresHfToken: true` + a `licenseUrl` pointing at `meta-llama/Meta-Llama-3.1-8B-Instruct`, but `scripts/z_image_turbo.py` `load_external_text_encoder()` does NOT call `probe_hf_auth()` the way `flux2_macos.py:265` does for the base FLUX repo. A user without a valid HF token currently sees a multi-GB download attempt that fails with a 401 deep inside transformers instead of a clean upfront error. Mirror the FLUX.2 probe before invoking `transformers.from_pretrained()` on the gated encoder repo. Surfaced by /do:review of PR #516 (2026-05-28).-- [ ] [flux2-bf16-kv-multi-reference-support] **Lift the multi-reference gate on `flux2-klein-9b-bf16`.** `scripts/flux2_macos.py` (~line 280) refuses `--reference-images` on `quantization='none'` because the bf16 entry's `repo` is `black-forest-labs/FLUX.2-klein-9B` (the base 9B, not kv) — `Flux2KleinKVPipeline` would load fine (component init signatures match) but run K/V-cached reference attention against a transformer not tuned for the reference-editing task, producing off-task output. Either swap the bf16 entry's `repo` to `black-forest-labs/FLUX.2-klein-9B-kv` (which carries `flux-2-klein-9b-kv.safetensors` for the reference-tuned transformer) and ship a migration for existing installs, or thread an explicit `kvRepo` field through the runner so single-image and multi-reference renders can pull from different repos for the same logical model. Quality validation requires a 64+ GB machine to host the bf16 weights. Surfaced by gemini review of `[flux2-multi-reference-python-runner]` PR #524 (2026-05-28).-- [ ] [flux2-runner-sidecar-tests] **Test coverage for `generateImage`'s sidecar `meta` payload.** `server/services/imageGen/local.test.js` exercises `buildArgs` (CLI emission) but never asserts on the sidecar `meta` object built inside `generateImage` — including the `referenceImageFilenames` + `referenceImageStrengths` fields added by `[flux2-multi-reference-python-runner]` (the field was `referenceImageStrengthsRequested` before per-ref weighting was honored end-to-end on 2026-05-29). A focused test would need to either factor the meta-builder out of `generateImage` so it's callable without spawning Python, or stub the spawn + assert on the persisted sidecar JSON. Surfaced by gemini review of PR #524 (2026-05-28).-- [ ] [comic-script-generation-panel-hardening] **Harden `pipeline-comic-script.md` to prevent content-in-page-description malformation at generation time.** The `comic-structure` editorial-review category (migration 057) catches pages where all content landed in the page-level description instead of panel definitions. That's a detection layer; the root fix is in the generation prompt. Add explicit rules to `data.reference/prompts/stages/pipeline-comic-script.md`: (a) "NEVER put action, dialogue, or scene content in the page-level description — that is ONLY for layout intent (1–3 lines max)"; (b) "Every page MUST have 4–6 discrete `Panel N` blocks with `Description:`, `Caption:`, `Dialogue:`, and `SFX:` fields — if the source material doesn't break naturally into panels, expand or split it across panels, never compress it into the page description." Add a migration alongside the prompt change. Deferred from 2026-05-30 to keep the editorial-review fix scoped; this is prevention rather than detection.-- [ ] [comic-structure-finding-shape-unification] **Unify the finding-shape contract across `comic-structure` and narrative categories.** The `comic-structure` finding (migration 057) repurposes the `suggestion` field as a full replacement document (complete panel-by-panel rewrite), while all other categories use it as a delta/advice string. This implicit dual-meaning will confuse future maintainers. Consider: adding a `replacementStrategy: 'full-page' | 'delta'` field to the finding shape; or restructuring to `{ finding, fix: { find, replace } }` where the `fix` block is category-specific. Either way, update `pipeline-manuscript-completeness.md` output contract, `manuscriptReview.js` comment shape, and the `pipeline-manuscript-fix.md` prompt that consumes suggestions. Deferred from 2026-05-30 — the current approach works end-to-end (LLM uses the full-page suggestion correctly as a find-and-replace target), but the contract inconsistency should be resolved before the finding type proliferates.-- [ ] [manuscript-review-sync] **Wire the manuscript-review comment set into cross-install sync.** `data/pipeline-series/{id}/manuscript-review.json` (the "Finish the draft" comments + their status/fix) is written as a sibling of the series record but is NOT carried by `exportSeries`/`importSeries` (server/services/sharing/exporter.js) or the peer-sync path — series sync serializes the record + issues structurally, not the folder. `manuscriptReview.mergeReviewFromSync(seriesId, remoteReview)` (LWW-per-comment) already exists for this; what's missing is (a) including the review document in the series export bundle, (b) a wire-schema-version gate in `server/lib/schemaVersions.js`, and (c) calling `mergeReviewFromSync` on the receiving side. Note accepted *fixes* already sync (they write to issue stage outputs); only the comment list/status/dismissals don't propagate yet. Deferred from the manuscript-editor PR (2026-05-30) to keep that change scoped — the editor is single-install-correct without it. Skipped: defending review state against the multi-install federation is a meaningful exporter/importer surface of its own.-- [ ] [reference-watch-default-prompt-version-bump-check] **Re-audit `DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata` whenever `PROMPT_VERSIONS['reference-watch']` changes.** The schedule default was flipped from `readOnly: true` → `false` on 2026-05-28 because the v2 prompt instructs the agent to append `[ref-watch-…]` items to PLAN.md and commit them — the read-only guard silently defeated that on every weekly cron firing (the on-commit `triggerReferenceAnalysis` path was already correct). A future v3 of the prompt that returns to a propose-only flow would need to flip the default back. Pin: `server/services/taskSchedule.js#DEFAULT_TASK_INTERVALS` reference-watch entry must stay in sync with the prompt's behavior; tests in `taskSchedule.test.js` and `referenceRepos.test.js` pin the current contract.+- [ ] [consolidate-client-url-normalize] **Consolidate client-side URL normalization.** Three components prepend `https://` to a bare URL with near-identical logic: `normalizeUrl` in `client/src/components/brain/tabs/LinksTab.jsx`, the inline block in `client/src/components/QuickBrainCapture.jsx` (~line 34, with `URL_PATTERN`/`DOMAIN_PATTERN` regexes), and `client/src/components/brain/tabs/FeedsTab.jsx` (~line 50, no `git@` handling). Extract one `normalizeUrl`/`isUrl` pair to a shared `client/src/utils/` helper and migrate all three. Must preserve each one's subtly different behavior (FeedsTab ignores `git@`; QuickBrainCapture splits detection from normalization).+- [ ] [brain-bucket-chip-reorder] **Drag-to-reorder chips *within* a bucket.** The Brain → Links bucket board (`client/src/components/brain/links/BucketBoard.jsx` + `BucketCard.jsx`) supports dragging a chip *between* buckets and reordering buckets, but not repositioning a chip within its own bucket — `bucketOrder` is only ever appended (max+1) on assign. Add intra-bucket position-aware drop (compute target index from the drop location, renumber `bucketOrder`, persist via `updateBrainLink`).+- [ ] [hidream-qwen-loras-runner-consumers] **Wire HIDREAM/QWEN through `client/src/pages/Loras.jsx`.** `imageGenResolutions.js` was extended on 2026-05-28 (`compatibilityKey` now returns HIDREAM/QWEN as their own keys). Still pending: `client/src/pages/Loras.jsx` `RUNNER_LABELS` / `RUNNER_BG_COLORS` / Top-LoRA section list omit HIDREAM/QWEN so the LoRA picker shows them as unlabeled / no badge color.+- [ ] [wan22-hunyuan-setup-pin-shas] **Pin Wan22 / HunyuanVideo MLX clones to known-good commit SHAs.** `scripts/setup-image-video.sh` defaults `WAN22_PIN="${WAN22_PIN:-main}"` and `HUNYUAN_PIN="${HUNYUAN_PIN:-main}"`. Floating `main` on two community-maintained ports means every new install gets whatever HEAD is on those repos that day. Replace the default with a tested SHA for each; let users override via the env var.+- [ ] [memory-mgmt-new-endpoint-tests] **Add tests for the 5 new memory-management routes.** `/api/local-llm/loaded`, `/api/local-llm/unload`, `/api/voice/whisper`, `/api/voice/tts/status`, `/api/voice/tts/unload` have no test coverage. Add focused happy-path + validation-rejection tests so future regressions in the schema-parity fixes (or the `unloadModel` residency check) surface as test failures.+- [ ] [qwen-image-edit-init-image-required] **Qwen-Image-Edit dispatches without its required init image.** `qwen-image-edit` (registry `mediaModels.js:202`) loads `QwenImageEditPipeline` which requires an `image` arg; the entry is exposed in the normal image-gen model picker which permits text-only submission. Today the user picks the model, submits a text prompt, and the runner crashes deep inside the diffusers pipeline. Options: (a) add an `editOnly: true` flag + validate at `routes/imageGen.js` POST; (b) filter the model from the picker when no source image is uploaded; (c) reroute through a future `/api/image-gen/edit` endpoint.+- [ ] [hidream-requires-hf-token-fail-fast] **Probe HF token upfront for HiDream gated-encoder downloads.** `data.reference/media-models.json`'s HiDream entries carry `requiresHfToken: true`, but `scripts/z_image_turbo.py` `load_external_text_encoder()` does NOT call `probe_hf_auth()` the way `flux2_macos.py:265` does. A user without a valid HF token currently sees a multi-GB download attempt that fails with a 401 deep inside transformers. Mirror the FLUX.2 probe before invoking `transformers.from_pretrained()` on the gated encoder repo.+- [ ] [flux2-bf16-kv-multi-reference-support] **Lift the multi-reference gate on `flux2-klein-9b-bf16`.** `scripts/flux2_macos.py` (~line 280) refuses `--reference-images` on `quantization='none'` because the bf16 entry's `repo` is the base 9B (not kv) — `Flux2KleinKVPipeline` would load fine but run K/V-cached reference attention against a transformer not tuned for reference-editing. Either swap the bf16 entry's `repo` to `black-forest-labs/FLUX.2-klein-9B-kv` and ship a migration, or thread an explicit `kvRepo` field through the runner. Quality validation requires a 64+ GB machine.+- [ ] [flux2-runner-sidecar-tests] **Test coverage for `generateImage`'s sidecar `meta` payload.** `server/services/imageGen/local.test.js` exercises `buildArgs` but never asserts on the sidecar `meta` object built inside `generateImage` — including the `referenceImageFilenames` + `referenceImageStrengths` fields. A focused test would need to either factor the meta-builder out of `generateImage` so it's callable without spawning Python, or stub the spawn + assert on the persisted sidecar JSON.+- [ ] [comic-script-generation-panel-hardening] **Harden `pipeline-comic-script.md` to prevent content-in-page-description malformation at generation time.** The `comic-structure` editorial-review category (migration 057) catches pages where all content landed in the page-level description instead of panel definitions — that's a detection layer; the root fix is in the generation prompt. Add explicit rules to `data.reference/prompts/stages/pipeline-comic-script.md`: (a) "NEVER put action, dialogue, or scene content in the page-level description — that is ONLY for layout intent (1–3 lines max)"; (b) "Every page MUST have 4–6 discrete `Panel N` blocks with `Description:`, `Caption:`, `Dialogue:`, and `SFX:` fields." Add a migration alongside the prompt change.+- [ ] [comic-structure-finding-shape-unification] **Unify the finding-shape contract across `comic-structure` and narrative categories.** The `comic-structure` finding (migration 057) repurposes the `suggestion` field as a full replacement document (complete panel-by-panel rewrite), while all other categories use it as a delta/advice string. Consider: adding a `replacementStrategy: 'full-page' | 'delta'` field; or restructuring to `{ finding, fix: { find, replace } }` where the `fix` block is category-specific. Update `pipeline-manuscript-completeness.md`, `manuscriptReview.js`, and `pipeline-manuscript-fix.md` accordingly. The current approach works end-to-end, but the contract inconsistency should be resolved before the finding type proliferates.+- [ ] [manuscript-review-sync] **Wire the manuscript-review comment set into cross-install sync.** `data/pipeline-series/{id}/manuscript-review.json` is written as a sibling of the series record but is NOT carried by `exportSeries`/`importSeries` or the peer-sync path. `manuscriptReview.mergeReviewFromSync(seriesId, remoteReview)` (LWW-per-comment) already exists; what's missing is (a) including the review document in the series export bundle, (b) a wire-schema-version gate in `server/lib/schemaVersions.js`, and (c) calling `mergeReviewFromSync` on the receiving side. Accepted *fixes* already sync (they write to issue stage outputs); only the comment list/status/dismissals don't propagate yet.+- [ ] [reference-watch-default-prompt-version-bump-check] **Re-audit `DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata` whenever `PROMPT_VERSIONS['reference-watch']` changes.** The schedule default was flipped from `readOnly: true` → `false` on 2026-05-28 because the v2 prompt instructs the agent to append `[ref-watch-…]` items to PLAN.md and commit them. A future v3 prompt that returns to a propose-only flow would need to flip the default back. Pin: `server/services/taskSchedule.js#DEFAULT_TASK_INTERVALS` reference-watch entry must stay in sync with the prompt's behavior; tests in `taskSchedule.test.js` and `referenceRepos.test.js` pin the current contract.+- [ ] [season-continuity-extract-honors-series-llm] **Season-episodes continuity extract doesn't honor the series LLM (or a model override).** The continuity `extractCanonFromProse` call in `generateSeasonEpisodes` (`server/routes/pipeline.js`, the `if (body.commit)` block) passes only `providerOverride: body.providerOverride` — no `series.llm` fallback and no `modelOverride` — so it falls back to the global active provider instead of the series-pinned LLM. Not a correctness bug, just an inconsistency. Add the same `providerMatchesSeries`-guarded provider/model resolution used by the extract-canon and extract-scenes routes.+- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. On `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves) to the tombstone GC path.+- [ ] [coalesce-fallback-provider-failure-storm] **Coalesce duplicate fallback work during an N-way provider-failure storm.** When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two compounding fixes: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders`; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once. Surfaced by /simplify during the ai-fallback PR (2026-05-22).## Future Ideas@@ -224,9 +210,8 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr- **Legacy Export Format** — identity as portable Markdown/PDF (closes GOALS "Knowledge Legacy" gap currently at Early status). Bundle scope: autobiography, Brain notes + memories, key decisions, goals + milestones, digital-twin prompt, health summaries with source caveats, and a machine-readable manifest.- **Workspace Contexts** — project context syncing across shell, git, tasks.- **Inline Code Review Annotations** — one-click fix from self-improvement findings.+- **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.- **Major Dependency Upgrades** — React 19, Zod 4, PM2 6, Vite 8.- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides.- **Inspiration & Mood Board Canvas** — dedicated mood-board surface for collecting visual + textual references that feed into Universe Builder, Writers Room, and Creative Director (distinct from raw Media History). Items can be pinned from any media surface; canvas surfaces ref images when starting a new universe / scene / treatment. Documented as a Secondary Goal in GOALS.md but had no tracking.-- **Generative regen path for SynthID defeat (image cleaner) — research/backlog, hardware-gated.** Current `cleanImageBuffer` (`server/lib/imageClean.js`) only strips the C2PA `caBX` chunk + runs `median(3).sharpen()` — SynthID survives by design (verified 2026-05-20 against codex output: post-clean image reads as `C2PA removed, SynthID detected` on openai.com/synthid). The detector heatmap that OpenAI's verifier renders is a one-way correlation map `∫ image · template`, not the watermark template itself — so deterministic image-processing approaches (subtracting the heatmap, overlaying a second "PortOS SynthID," frequency-band cancellation) can't work without the secret key. The only honest defeat path is to round-trip pixels through a generative model: short-step img2img (low step count + low–moderate denoise, ~0.35–0.5) on a local FLUX runner so composition holds but the per-pixel watermark signal is overwritten by fresh sampling. **Scope narrowed (2026-05-20):** post-hoc, history-only. Surface as a second button next to "Clean (aggressive)" on the image-settings/lightbox modal — never auto-applied, never wired into the active gen flow, no per-render checkbox. Each run is ~5–15s on local mflux and GPU/unified-memory heavy; wants its own queue lane. Sidecar records `regenerated: true, regenSteps: N, regenStrength: 0.4, regenModelId: 'flux-v1'` so lineage stays honest. **Hardware-gated** — defer until the 128GB unified-memory machine arrives; current dev hardware can't comfortably host the local diffusion runner alongside the rest of PortOS. Pull in only after that hardware is online and the user wants to play with it. UX caveat: this is the only honest watermark-defeat path; the existing C2PA-strip-and-denoise will always be a no-op against SynthID and should never be relabeled as a watermark stripper.-- [ ] [season-continuity-extract-honors-series-llm] **Season-episodes continuity extract doesn't honor the series LLM (or a model override).** The continuity `extractCanonFromProse` call in `generateSeasonEpisodes` (`server/routes/pipeline.js`, the `if (body.commit)` block) passes only `providerOverride: body.providerOverride` — no `series.llm` fallback and no `modelOverride` — so it falls back to the global active provider instead of the series-pinned LLM the rest of the pipeline honors. Not a correctness bug (no foreign-model pairing), just an inconsistency. Add the same `providerMatchesSeries`-guarded provider/model resolution used by the extract-canon and extract-scenes routes (after confirming the season route schema carries `modelOverride`). Surfaced by the gemini reviewer during the canon-extraction-failure-retry PR (2026-05-30).-- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once. <!-- NEEDS_INPUT -->+- **Generative regen path for SynthID defeat (image cleaner) — research/backlog, hardware-gated.** Current `cleanImageBuffer` (`server/lib/imageClean.js`) only strips the C2PA `caBX` chunk + runs `median(3).sharpen()` — SynthID survives by design. The only honest defeat path is to round-trip pixels through a generative model: short-step img2img (low step count + low–moderate denoise, ~0.35–0.5) on a local FLUX runner so composition holds but the per-pixel watermark signal is overwritten by fresh sampling. **Scope narrowed (2026-05-20):** post-hoc, history-only — a second button next to "Clean (aggressive)" on the image-settings/lightbox modal; never auto-applied, never wired into the active gen flow. Each run is ~5–15s on local mflux and GPU/unified-memory heavy; wants its own queue lane. Sidecar records `regenerated: true, regenSteps: N, regenStrength: 0.4, regenModelId: 'flux-v1'` so lineage stays honest. **Hardware-gated** — the 128GB unified-memory machine is now online, so this can be pulled in when the user wants to play with it. UX caveat: this is the only honest watermark-defeat path; the existing C2PA-strip-and-denoise will always be a no-op against SynthID.