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(plan): prune 38 shipped checked items, reconfirm 3 open catalog TODOs
[._.]/ Adam Eivy4c507f043102
diff --git a/PLAN.md b/PLAN.mdindex f1c15893bf..0f7b188084 100644--- a/PLAN.md+++ b/PLAN.md@@ -10,52 +10,21 @@ The catalog backend, schema, federation routes, ingest extraction service, and C_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._-_Re-triaged 2026-05-30 (post-merge follow-up pass): the 6 review-surfaced follow-ups + the 4 gated items were each verified against current `main`. Being implemented now: the 4 follow-ups (`catalog-bulk-import-scrap-persistence`, `catalog-sync-apply-kind-helper`, `catalog-detail-batched-endpoint`, `browser-navigate-ssrf-guard`), the 2 review tests/tags items (`catalog-bulk-import-route-db-tests`, `catalog-friendlify-universe-tags-on-sync`), the character-sheet remainder, and the previously-gated `catalog-type-table-vs-check` + `catalog-ask-retrieval`. Staying deferred: `catalog-user-defined-types` (gated on `catalog-type-table-vs-check` landing first) and `catalog-scrap-chunking` (per its own "wait for user pain" note — confirmed still not triggered)._+_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`. Still open below (verified still-valid 2026-05-30): `catalog-character-sheet-enrichment` (deep durable-record unification + structured array-field editors remain), `catalog-user-defined-types` (precondition now resolved; deferred until deliberately picked up), and `catalog-scrap-chunking` (per its own "wait for user pain" note — confirmed still not triggered)._-New follow-ups surfaced during the 2026-05-30 review pass:--- [x] [catalog-bulk-import-route-db-tests] **Route-level DB integration tests for `/bulk-import` and `/ingredients/:id/revisions/:revisionId/restore`.** Both establish producer↔consumer contracts pinned only at the parser/unit layer today (bundle-ref → refLink recreation + role precedence; restore preserves the revision's `payload.schemaVersion`). Needs the Postgres test fixture the `catalog-tests` PR establishes. Surfaced by claude review of #554 + #558.-- [x] [catalog-bulk-import-scrap-persistence] **Persist scraps on markdown bulk-import.** `parseMarkdownBulk` now round-trips `### Scraps` into a non-enumerable `entry.scraps[]`, but the bulk-import route does NOT create `catalog_scraps`/`catalog_ingredient_sources` rows from them (lossy-but-not-corrupt per the PLAN). Wire scrap creation into the bulk-import transaction (createScrap needs a `{ client }` option). Surfaced by codex review of #554.-- [x] [catalog-sync-apply-kind-helper] **Extract an `applyKindEnvelope(kind, items, upsertFn, statsTally)` helper in `server/services/catalogSync.js`.** The 7 per-kind apply loops (scraps/ingredients/sources/refs/relations/tags/media) share a try/catch + stats-tally shape. Deferred from #558 to avoid churning tested sync code in an already-large PR. Surfaced by codex review.-- [x] [catalog-detail-batched-endpoint] **`GET /api/catalog/ingredients/:id/details` to collapse the detail page's 4 round-trips** (relations + revisions + media + missing-media) into one hydrated response. Nice-to-have; surfaced by simplify review of #558.-- [x] [browser-navigate-ssrf-guard] **Apply the catalog-ingest SSRF guard to the pre-existing `POST /api/browser/navigate` route.** `server/lib/catalogValidation.js:isSafeIngestUrl` + the DNS-resolution + post-redirect re-check from #559 should be reused by `server/routes/browser.js` (it has the same bare-`z.string().url()` gap — `file://`/loopback/link-local reachable). Surfaced by claude review of #559.-- [x] [catalog-friendlify-universe-tags-on-sync] **Friendlify late-synced legacy universe tags.** The one-time boot repair (`repairUniverseTags.js`) is marker-gated, so a catalog ingredient synced from an older/offline peer AFTER the marker is written keeps its raw `from-universe`/`universe:<uuid>` machine tags. Either run `friendlifyUniverseTags` on inbound catalog rows in the sync-apply path, or replace the one-shot marker with a periodic/high-water repair. Surfaced by codex review of #560.--- [x] [catalog-universe-builder-picker] **Add "Pick from Catalog" button to `client/src/pages/UniverseBuilder.jsx` character/place/object panels (~3736 LOC file).** When a catalog ingredient is picked, copy its `payload` into a new embedded canon entry with `ingredientId` stamped, AND post `linkCatalogIngredient(id, { refKind: 'universe', refId, role: 'canon-character'|'canon-place'|'canon-object' })`. Picker component lives at `client/src/components/IngredientPicker.jsx` (already built). Deferred from the initial PR because of the file size — needs targeted exploration of the canon-panel structure first (CanonTab / BibleTab around `UniverseBuilder.jsx:1835` + `:2945`).- [ ] [catalog-character-sheet-enrichment] **Upgrade `client/src/pages/CatalogIngredient.jsx` character detail/edit routes (for example `/catalog/character/cat-chr-224496f9-22ec-4784-b84a-f69cecdd4f01`) into a full editable DnD-style character sheet backed by the enriched universe-canon payload.** Character rows should expose and edit all enriched canon data already present in universe records: identity, role/archetype, appearance, personality, goals/fears, relationships, stats/abilities, color palette, style notes, prompt/render hints, reference images, and any future `payload.schemaVersion` fields. If a character reference sheet has already been rendered, show it in the detail page; if none exists, allow rendering one from this page using the linked universe's style data (`styleNotes`, `influences`, `styleImageRefs`, palette, and render settings) when the ingredient has an associated universe ref. Catalog ingredients and universe canon characters must become the same durable records rather than copy-on-write mirrors: editing either the Catalog detail page or the universe canon surface should update the same `catalog_ingredients` row (with the universe canon entry carrying only a stable `ingredientId`/projection cache if needed), so enriched fields cannot diverge between Catalog and Universe Builder. Migration/backfill: update universe-backfilled character tags from machine tags like `from-universe, universe:14590a09-5a49-4994-b401-395ee354528d` to friendly, user-facing universe-name tags while preserving a structured universe ref for querying; ship a one-time data repair for the current instance as part of the implementation. Pairs with `[catalog-universe-builder-picker]`, `[catalog-bundled-universe-push]`, `[catalog-ingredient-media-refs]`, and `[catalog-payload-schemaversion-per-type]`. _In review 2026-05-30 (#560): SLICE shipped — the editable grouped character/place/object sheet (registry-driven `editorSections`/`editorFields`, scalar fields keyed to mirror `sanitizeCharacter` so edits land in the same `catalog_ingredients` row the canon reads), the "Reference sheet" panel, and the friendly-universe-tag data repair (`repairUniverseTags.js`, marker `053`). REMAINING: the deep durable-record unification (collapse the embedded universe-canon entry to a pure `ingredientId` projection so the catalog row is the single store of record) and the structured array-field editors (color palette / stats / aliases, currently read-only here). Keep this item open until those land._-- [x] [catalog-pipeline-series-cast] **Add a "Cast (from Catalog)" section to `client/src/pages/PipelineSeries.jsx` that surfaces `listCatalogIngredientsForRef('series', seriesId)` and lets the user attach/detach via `IngredientPicker`.** Series records carry no embedded `characters[]` array, so this is purely additive — backed entirely by `catalog_ingredient_refs`. Same pattern applies to `client/src/pages/PipelineIssue.jsx` (refKind `'issue'`) and `client/src/pages/WritersRoom.jsx` work bibles (refKind `'work'`). _Shipped 2026-05-29: `CatalogCastPanel` reusable component wired into all three pages._-- [x] [catalog-federation-orchestrator] **Wire the catalog into `server/services/syncOrchestrator.js` (or `server/services/sharing/peerSync.js`, whichever owns memory sync orchestration) so the existing `/api/catalog/sync` + `/api/catalog/sync/apply` routes auto-replicate between peers.** Today the routes exist and are version-gated via `PORTOS_SCHEMA_VERSIONS.catalog = 1`, but no scheduler pulls from peers. Mirror how memory sync is registered (it's the only existing Postgres-backed sync category). Outbound `portosMeta.schemaVersions.catalog` is already stamped server-side. **Universe/series sync today does NOT block on catalog sync** — universes carry their full embedded canon payloads, so a peer-pushed universe still arrives complete; the receiving peer's boot-time backfill walks the freshly-arrived universe and (now, post-`[catalog-universe-builder-picker]`'s peer-reconciliation fix) creates local catalog rows with the original IDs preserved. Direct catalog sync only matters for **orphan ingredients** (idea/scene/concept rows not attached to a universe) and for **post-`[catalog-universe-builder-picker]`** universe-ingredient picker links (the `catalog_ingredient_refs` rows themselves) so the "Appears in" panel populates across peers.-- [x] [catalog-bundled-universe-push] **Bundle catalog ingredients into universe peer-push payloads.** When peer A pushes a universe to peer B, the push should include the `catalog_ingredients` rows referenced by that universe's embedded canon plus the `catalog_ingredient_refs` rows linking universe→ingredient. Today the embedded canon payloads still replicate (so universes work end-to-end across peers), but the `tags`, `embedding`, `payload.summary`-style enrichments that live ONLY in the catalog row do not — they get re-derived from the embedded entry on the receiver's first backfill, which is a strictly-lossy view. Mirror the `bundleAdditionalKinds` pattern in `server/services/sharing/peerSync.js`. Schema-version gating already covers the new bundle: `RECORD_KIND_SCHEMA_CATEGORIES.universe` would need `['universes', 'catalog']` appended OR the bundling can rely on `cat-ingredient` arriving as its own already-gated kind in the same push. Pairs with `[catalog-federation-orchestrator]`.-- [x] [catalog-tests] **Remaining tests for the catalog stack.** `server/services/catalogDB.test.js` (CRUD round-trip — bootstrap follows `server/services/memoryDB.test.js` — needs a Postgres test fixture), `server/scripts/migrateBibleToCatalog.test.js` (idempotency), `client/src/pages/Catalog.test.jsx`, `client/src/components/IngredientPicker.test.jsx`. _Pure-unit slice shipped 2026-05-29: `server/lib/catalogValidation.test.js` (Zod boundary), `server/services/catalogSync.test.js` (envelope round-trip + LWW + cursor normalization), `server/services/catalogExtraction.test.js` (mocked bibleExtractor + stage progress), and `server/lib/db.catalogDdlParity.test.js` (init-db.sql ↔ ensureSchema DDL parity)._-- [x] [catalog-writers-room-version-refs] **Phase 9 (deferred at design time): capture catalog ingredient ids per Writers Room draft version.** Extend the draft save path in `server/services/writersRoom/local.js` to accept `referencedIngredientIds[]`. Add `scanProseForIngredientRefs(text, { universeId?, seriesId?, workId? })` to `catalogExtraction.js` (substring match scoped to refs linked to the target). UI: render referenced ingredients on each version-history chip in `client/src/pages/WritersRoom.jsx`.### Creative Catalog — extensibility roadmapThe 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.-- [x] [catalog-shared-type-registry] **Lift catalog ingredient types into a single shared registry (`server/lib/catalogTypes.js` + mirrored client constants).** Today the 6 types are duplicated across `init-db.sql`, `db.js:ensureSchema`, `catalogValidation.js` (Zod enum), `catalogExtraction.js` (prompt slot + JSON schema), `Catalog.jsx` (`TYPES`/`PRIMARY_CONTENT_KEY`/`PRIMARY_CONTENT_LABEL`/`payloadSnippet`), `CatalogIngredient.jsx` (per-type editor branches), `IngredientPicker.jsx` (type chips). One registry entry per type: `{ id, label, idPrefix, badgeColor, primaryContentKey, primaryContentLabel, snippetFallbackKeys, payloadSchema, extractionPromptFragment, editorComponent }`. Server-side: validation, extraction, ID prefix, and FTS field set derive from the registry. Client-side: list, picker, editor branches, and snippet fallback all map over the same registry. Adding a new type becomes one registry entry + one editor component + one migration that loosens the CHECK constraint (or replaces it with an FK to a `catalog_ingredient_types` table — see `[catalog-type-table-vs-check]`). Surfaced 2026-05-29 during the extensibility review.-- [x] [catalog-type-table-vs-check] **Replace the `type` CHECK constraint with a `catalog_ingredient_types` table (or relax to a free-form `VARCHAR(32)` + app-layer validation).** Today `catalog_ingredients.type` is `CHECK (type IN ('character','place','object','idea','scene','concept'))`, so adding a type requires a Postgres migration that DROP/RE-ADD the constraint in both `server/scripts/init-db.sql` and `server/lib/db.js:ensureSchema`, plus a `PORTOS_SCHEMA_VERSIONS.catalog` bump. Either (a) seed a `catalog_ingredient_types(id, label, payload_schema_version, system bool, created_at)` table and FK `catalog_ingredients.type → catalog_ingredient_types.id`, letting registry-driven seeds + user-defined types coexist; OR (b) drop the constraint entirely and validate `type` against the registry at the app layer. Pairs with `[catalog-shared-type-registry]` and is the precondition for `[catalog-user-defined-types]`. Decide before adding the 7th type.-- [x] [catalog-payload-schemaversion-per-type] **Stamp `payload.schemaVersion` per ingredient row + add a migration helper.** Today the JSONB `payload` is loose — when a type's payload shape evolves (e.g. character adds a `voiceNotes` field, scene adds `beat`/`povShift`), older rows have no marker for which shape they're in, and the sanitizer must tolerate any historical key set forever. Mirror the per-record `schemaVersion` convention already documented in CLAUDE.md (separate from the storage-layout version): each `createIngredient` stamps `payload.schemaVersion: <registry-current>`, and `server/scripts/migrateCatalogPayload.js` walks rows whose `payload.schemaVersion < registry-current` and applies registered upgraders. Registry entry gains `payloadSchemaVersion: number` + `payloadUpgraders: { 1: (p) => p2, 2: ... }`. Without this, payload evolution silently mixes shapes across rows.- [ ] [catalog-user-defined-types] **Allow user-defined ingredient types in the Settings → Catalog section.** Once `[catalog-type-table-vs-check]` lands, expose a Settings UI to add a user type: `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string'|'longtext'|'tags'|'ref', maxLength? }] }`. Persisted in the new `catalog_ingredient_types` table with `system: false`; the registry merges seeded + user types at boot. Editor component for user types is a generic form renderer driven by the `fields` array (no per-type React file). Unblocks the long tail of personal creative shards (wardrobe, vehicle, faction, magic-system, voice-line, prompt-fragment, etc.) without a code change per shard. Decision needed on whether user types federate to peers (probably yes, with the type row riding the catalog sync envelope and gated by `PORTOS_SCHEMA_VERSIONS.catalog`). _Precondition resolved 2026-05-30: `[catalog-type-table-vs-check]` landed as **option (b)** (DB `CHECK` dropped + `type VARCHAR(32)`; validity gated by the `INGREDIENT_TYPES` registry + Zod enum) — so user types do NOT need a `catalog_ingredient_types` table; they can persist in settings and merge into the registry at boot, and a user-typed row already inserts at the DB layer. Still open as a larger Settings-UI + generic-form-renderer feature; remains deferred until picked up deliberately._-- [x] [catalog-ingredient-relations] **Add a `catalog_ingredient_relations` table for ingredient↔ingredient edges.** Today the only ingredient relationships are to *external* records (`catalog_ingredient_refs` → universe/series/issue/work). Within the catalog, a character has no link to its place or to scenes it appears in, a concept has no link to objects that embody it, and a scene can't enumerate its cast. Schema: `(from_id, to_id, kind, created_at, sync_sequence, deleted, deleted_at)` with `kind` from a registry (`appears-in`, `lives-in`, `created-by`, `parent-of`, `variant-of`, `references`, ...). FK both ids to `catalog_ingredients(id) ON DELETE CASCADE`. UI: a "Relations" panel on `CatalogIngredient.jsx` with picker-driven add. Federate via the existing catalog sync envelope (new `relations: [...]` block). Use `deleted/deleted_at` soft-delete from day one (don't repeat the `[catalog-ref-deletion-tombstones]` mistake). This is the seam that makes the catalog a graph instead of a flat list — required before the "Knowledge Graph Visualization" Future Idea (line 249) can include creative content.-- [x] [catalog-tag-taxonomy] **Promote tags from `TEXT[]` to a first-class `catalog_tags` table with autocomplete.** Today `catalog_ingredients.tags` is freeform (GIN-indexed, no canonical list) — `noir` / `Noir` / `noir-style` / `film noir` accumulate as separate tags and search by tag has no autocomplete. Add `catalog_tags(id, label, description?, color?, parent_id?, created_at, sync_sequence)`; keep the freeform `tags TEXT[]` column for write-path simplicity but add a normalization step that maps user input through the canonical table, creating new rows on first use. UI: tag picker autocomplete on `CatalogIngredient.jsx` and the Quick Idea form. Optional parent_id enables tag hierarchies (genre/tone vs structural vs character-trait). Pairs with `[catalog-shared-type-registry]` — the registry can also declare default tags per type.-- [x] [catalog-ingredient-revisions] **Add a `catalog_ingredient_revisions` history table.** Today `updateIngredient` overwrites `payload` + `tags` in place and only `updated_at` records that it changed — no "what changed" diff, no "restore previous version" UI, no audit trail for AI-driven refinement runs (story-builder refine, future agent edits). Schema: `(id, ingredient_id, payload, tags, name, source: 'user'|'extract'|'refine'|'sync', actor?: string, created_at)` keyed `(ingredient_id, created_at)`. Write a row inside `updateIngredient` whenever `payload`/`tags`/`name` changes. UI: revision history list on `CatalogIngredient.jsx` with inline diff + "Restore" button. Cap retention to last N revisions per ingredient (config; default 50) to avoid unbounded growth. Pairs naturally with the existing Writers-Room version-history pattern.-- [x] [catalog-ingredient-media-refs] **Add a `catalog_ingredient_media` join table for image/audio/video attachments.** Today scenes and characters can only carry text — but the natural creative workflow is "here's a generated portrait for this character, this is the voice memo I recorded for this scene, this is the reference mood image for this concept." Schema: `(ingredient_id, media_key, kind: 'portrait'|'reference'|'audio'|'video'|'document', role?, caption?, created_at, sync_sequence, deleted, deleted_at)`. `media_key` references the existing media-history sidecar (`data/history.jsonl` + generated assets); does NOT duplicate bytes. UI: drag-and-drop image into `CatalogIngredient.jsx`, voice-memo button (record → Whisper → ingredient attached audio + transcript as scrap), "set portrait" picker that scopes to existing media history. Federation: ingredient ships its media-key list; receiving peer matches against its own media library and surfaces missing entries via the existing `metadata-missing` integrity surface. Unblocks "Mood Board Canvas" (line 256) by giving creative refs a typed home.-- [x] [catalog-bulk-import] **Bulk-ingest path for markdown/CSV/JSON dumps.** _Shipped 2026-05-29: `POST /api/catalog/bulk-import` with JSON / CSV / markdown (`## <Type>: <Name>`) parsers, single-transaction insert, optional `defaults.tags` + `*Ref` stamping. UI on `CatalogIngest.jsx`._-- [x] [catalog-export-bundle] **Export a catalog slice as a portable bundle.** _Shipped 2026-05-29: `GET /api/catalog/export?refKind=&refId=&format=json|markdown|yaml` hydrates ingredients + scraps + ref-links, sets `Content-Disposition: attachment`. Relations + media-refs deferred to those PLAN items._-- [x] [catalog-cmdk-ask-voice-discovery] **Surface catalog ingredients in ⌘K / Ask / voice (cross-surface discovery).** _Partially shipped 2026-05-29: ⌘K palette renders live catalog hits under a "Catalog" group (debounced search); voice tool `catalog_lookup({ query, type?, limit? })` registered with intent-gated loading. **Ask retrieval still open — see `[catalog-ask-retrieval]`.**_-- [x] [catalog-ask-retrieval] **Wire catalog ingredients into `/api/ask` context (token-budgeted, top-K hybrid search).** Deferred from `[catalog-cmdk-ask-voice-discovery]` — needs a research pass on the existing Ask retriever + budgeter before implementing so the catalog slice shares the same scoring/budget model as memory/universe context.-- [x] [catalog-export-bundle-import-refs] **JSON export bundles don't recreate ref links on re-import.** `parseJsonBulk` (in `server/lib/catalogBulkParsers.js`) unwraps `{ ingredients }` from an export bundle, but the route only stamps refLinks from `defaults.*Ref` — so when a user re-imports a bundle through `/catalog/ingest` → "Bulk Import", new ingredients land *without* the bundle's `ref` link and each row's per-row `roleForExportedRef` is dropped. Result: the imported slice is invisible to `listIngredientsForRef` and to future slice exports. Fix: have `parseJsonBulk` attach `bundleRef = { kind, id }` (non-enumerable, like `warnings`) when it detects a bundle root; have the bulk-import route fall back to `bundleRef` for refLinks when no `defaults.*Ref` overrides it, and (separately) propagate `roleForExportedRef` per row instead of the batch-level `defaults.role || bulk-<kind>` default. Surfaced by codex iter-2 review on PR #552.-- [x] [catalog-markdown-roundtrip-fences-scraps] **Markdown export → re-import loses non-primary payload keys + scraps.** `ingredientToMarkdown` (`catalogBulkParsers.js:303`) emits a ` ```json … ``` ` fence for non-primary payload keys (e.g. character `personality`) and a `### Scraps` subsection; but `parseMarkdownBulk` only recognizes the heading + `tags:` line and appends every other line to the primary content body, so re-importing pollutes `description`/`summary` with fence text and JSON. Fix: in `parseMarkdownBulk`, recognize ` ``` ` as a fence start/end and either skip (current behavior — but cleanly) or parse the JSON fence into `payload.*`; treat `### Scraps` as a body terminator and either preserve as a sibling `scraps[]` (full round-trip) or skip cleanly (lossy but not corrupt). Pairs with `[catalog-export-bundle-import-refs]` for the broader "round-trip lossy → round-trip fidelity" pass. Surfaced by codex iter-2.-- [x] [catalog-cast-panel-multi-role-unlink] **`CatalogCastPanel` unlink removes every row with the matching ingredient id, ignoring `role`.** `client/src/components/CatalogCastPanel.jsx:99` filters `r.ingredient.id !== ingredient.id` — but the ref table key is `(ingredient_id, ref_kind, ref_id, role)`, so an ingredient linked to the same record under multiple roles (which the API allows) loses all rows from local state on a single-role unlink until reload. Fix: filter by `!(r.ingredient.id === ingredient.id && r.role === role)`. Today the panel's role-mapping always picks one role per ingredient type, so this is latent — but peer-sync or future role-aware UI can populate multi-role rows. Surfaced by codex iter-2.-- [x] [catalog-source-kinds-url-file-voice] **Expand scrap `source_kind` beyond `paste|brain-bridge|importer-handoff`.** The column is already a free `VARCHAR(32)`, but the only ingest path that hits it is the textarea paste. Add: (a) URL ingest — paste a URL, server fetches + extracts main text via the existing browser service, source_kind `url`, metadata carries the URL + fetched title. (b) File ingest — `.txt`/`.md`/`.pdf` upload, source_kind `file`, metadata carries the original filename + mime. (c) Voice ingest — record a memo, Whisper transcribes, source_kind `voice-memo`, metadata carries the audio media_key (pairs with `[catalog-ingredient-media-refs]`). Each reuses the existing extraction pipeline and emits the same `catalog:extract:progress` frames.- [ ] [catalog-scrap-chunking] **Chunk long scraps into multiple `(parent_scrap_id, chunk_index)` rows.** Today `raw_text` is a single TEXT column with no enforced cap, but a 50k-word screenplay paste lands as one row and one LLM call — context overflow is silent and extraction degrades. Add `chunk_index INT DEFAULT 0` + `parent_scrap_id TEXT REFERENCES catalog_scraps(id)` and split inputs over ~12k chars into N child rows; the extractor processes each child and unions the results, dedup by name+type. Surfaced by anticipation, not yet by user pain — defer until a long-input failure is reported._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]`)._-- [x] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails now use `MediaImage`.** Grid thumbnails show the peer-sync "Syncing" placeholder on missing assets and live-swap when `peerSync:asset-arrived` lands. Shipped 2026-05-30 with a MediaCard regression test.- [ ] [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).- [ ] [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.@@ -160,7 +129,6 @@ Surfaced while building the sync-hygiene feature (duplicate detection/merge, non- [ ] [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.- [ ] [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).-- [x] [merge-orphan-series-via-api] **DONE in v2.10.0.** `recordMerge.js:334-340` now throws `Orphan series (no universe) cannot be merged …` when both `universeId` are null, and `recordMerge.test.js:231` pins it. (Was: `mergeSeries` permitted merging two orphan series via the API because `null !== null` is false.)- [ ] [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.@@ -184,20 +152,6 @@ Surfaced while adding merge-verified worktree reaping (`isBranchMergedInto` + `r- [ ] [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.-### v2.10.0 release-review follow-ups (2026-05-25)--Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctness findings were fixed in-release (paused-agent cleanup protection, browser spawn/loadConfig guards, CLI pause-ordering double-finalize, runner immediate-fallback exit-0 race, conflict-journal `ERR_TARGET_GONE`→409, pause-route Zod). The items below were deferred as test-coverage gaps or non-blocking improvements.--- [x] [test-paused-agent-cleanup-protection] _(DONE post-v2.10.0 patch)_ **Add a test that `agentDataCleanup` excludes paused agents from worktree/data reaping.** The fix (`server/services/autonomousJobs.js` reads `data/cos/state.json` and unions `status === 'paused'` ids into the protect set) is currently unverified by tests — `agentDataCleanup` is a private (non-exported) handler and has no test today. Export it (or the `SCRIPT_HANDLERS` map), build fs (`readdir`/`stat`/`rm`) + `reapMergedWorktrees`/`cleanupOrphanedWorktrees` mocks, seed a state.json with a paused agent, and assert its worktree + data dir are NOT reaped. (Batch-1 CRITICAL review follow-up.)-- [x] [test-pause-agent-branches] _(DONE post-v2.10.0 patch)_ **Cover the non-happy-path `pauseAgent` branches.** `agentManagement.test.js` only tests the direct-mode happy path. Add: runner-branch success + `pauseAgentViaRunner` failure → `pausedAgents` rolled back and agent stays in `runnerAgents`; TUI branch (ESC + delayed `killSession`); and the close-handler skip-finalization contract (a `pausedAgents`-flagged agent hitting the CLI/TUI/runner close handler does NOT finalize the task / clean the worktree). (Batch-1 IMPROVEMENT.)-- [x] [cosrunner-orphan-paused-emit] _(DONE post-v2.10.0 patch — dropped the dead emit per YAGNI)_ **`cos-runner/index.js` emits `agent:paused` but nothing listens.** `cosRunnerClient.js` never subscribes to `agent:paused` (pause state is applied synchronously via the HTTP `/pause` path), so the emit is dead code implying a server listener that doesn't exist. Either drop the emit or wire `socket.on('agent:paused', …)` and handle it idempotently. (Batch-1 NIT.)-- [x] [merge-union-seasons-collision] _(DONE — already fixed in #505 merge-union-summary; verified `unionSeasons` gap-fills colliding loser seasons into the survivor instead of dropping them)_ **`unionSeasons` silently drops a loser season whose `number` collides with a survivor's.** `server/services/recordMerge.js` (~line 151) `continue`s past a colliding loser season, discarding its authored title/episodes/arc metadata even though the merge is documented as "no data loss" (this is a local merge, so the conflict journal never sees it). Either union the loser season's non-empty fields into the survivor, or surface a count in the `cascade` summary so the UI can warn "N loser seasons not merged." (Batch-2 NIT.)-- [x] [conflict-journal-basehash-evict] _(DONE post-v2.10.0 patch)_ **`sync_base_hashes.json` entries are never evicted on record delete.** `server/lib/conflictJournal.js#setSyncBaseHash` keys by `${kind}:${id}`; when a record is tombstoned and force-pruned its base-hash entry leaks (slow unbounded growth on a long-lived federated install — not a correctness bug). Delete the entry as part of the delete cascade / tombstone prune. (Batch-2 NIT.)-- [x] [test-merge-route-contracts] _(DONE post-v2.10.0 patch — route identical-ids returns `VALIDATION_ERROR` via Zod refine; service-level `MERGE_VALIDATION` still pinned in recordMerge.test.js)_ **Route-level tests for the merge endpoints' contracts.** `universeBuilder.test.js`/`pipeline.test.js` only assert `status === 400` for identical-ids and never pin the body `code` (`MERGE_VALIDATION`); there's no route test for a successful `POST /merge` (`{ merged, cascade }`), the `DELETE /universe-builder/:id` 409 `UNIVERSE_HAS_LIVE_SERIES` + `context.blockingSeries` body the UI depends on, nor the `POST /merge/ai-resolve` error contract (`MERGE_AI_NO_MERGEABLE_FIELDS` 422, no-provider, `LLM_INVALID_JSON` 502). Add them. (Batch-2 IMPROVEMENT.)-- [x] [share-empty-scalar-helper] _(DONE post-v2.10.0 patch — moved to `server/lib/objects.js`)_ **Move `isEmptyScalar` out of `recordMerge.js` into a shared util.** `recordMerge.js`'s `isEmptyScalar` (null/undefined/empty-string/empty-array predicate) is now used by `resolveScalars` and `unionSeasons` and is a generic enough "is this value blank" check to live in `server/lib/objects.js` (or `validation.js`) for reuse. Low priority. (Batch-3/gemini NIT.)-- [x] [test-codereview-defaults-cache-isolation] _(DONE post-v2.10.0 patch)_ **`codeReview.test.js` doesn't reset the module-level `cachedDefaults` between tests.** `getCodeReviewDefaults` memoizes into `cachedDefaults` (invalidated only by a `settings:updated` event the test stubs as a no-op); `afterEach` resets `mockedSettings.current` but never clears the cache, so a future test adding a second `getCodeReviewDefaults()` call with different settings would silently read stale data. Export a test-only `__resetCodeReviewDefaultsCache()` and call it in `afterEach`. Latent (no current failure). (Batch-1/claude NIT.)-- [x] [test-codereview-local-route] _(DONE post-v2.10.0 patch)_ **`POST /api/code-review/local` has no route-level test.** Add a supertest-style test (mocking `runLocalCodeReview`/`getSettings`): empty `diff` → 400 (Zod), unknown `backend` → 400 (`z.enum`), `model` omitted falls back to the settings model, and `{ ok: false }` service result → 502. Also add `validation.test.js` assertions that `featureProviderConfigSchema.parse({ providerId:'', model:'' })` yields `undefined`s and `codeReviewSettingsSchema` rejects unknown keys (`.strict()`). (Batch-3 IMPROVEMENT/NIT.)-### 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.