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: check off PR1 catalog items + changelog entry
[._.]/ Adam Eivy879df4efef85
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a509482366..260019bd99 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **[catalog-import-sync-hardening] Catalog bulk-import keeps scraps; legacy universe tags self-heal across peers.** Bulk-importing markdown that carries a `### Scraps` subsection now persists those scraps as `catalog_scraps` rows + source links inside the same transaction (previously the round-tripped scraps were silently dropped on import); the response reports a `scrapsCreated` count. Separately, an ingredient synced from an older or offline peer *after* the one-time boot tag-repair ran would reintroduce raw `from-universe` / `universe:<uuid>` machine tags via last-writer-wins — those are now friendlified to the universe NAME on inbound sync, so the repair self-heals on every sync instead of only at boot. Internal: the seven near-identical per-kind apply loops in `catalogSync.applyRemoteChanges` collapse into a single `applyKind` helper (pure refactor, behavior-identical), and `createScrap` gains a `{ client }` transaction option. Adds route-level Postgres integration tests for `/bulk-import` and revision `/restore`.+- **[federated-media-sync-followups] Sync integrity, local LLM, voice, and service hardening.** Federated sync badges now distinguish offline peers from peers that need a PortOS update, series integrity checks include child-issue assets, and records with images missing prompt sidecars show a dedicated "Metadata missing" status. Tombstone pushes now bypass the schema-version cooldown so deletes converge immediately. Internal cleanup: the AI toolkit receives Ollama readiness through an injected hook, Linux Ollama startup uses persistent `systemctl enable --now` / `disable --now`, migration 037 streams history conversion instead of materializing the union in memory, Local LLM backend switching writes `.env` atomically, the Voice settings UI can pin a vision model, and the LTX2 negative-prompt patch only targets namespaced constants modules.- **[catalog-tests + catalog-ddl-drift-test] Catalog stack now has unit-test coverage + a DDL parity guard.** Internal: pure unit tests for the catalog Zod validators, the peer-sync envelope apply path (per-kind dispatch, per-row isolation, schema-version gate, cursor normalization), and the extraction service (stage frames, isolation, light-shape sanitizer). A new structural parity test diffs the catalog DDL between `server/scripts/init-db.sql` (fresh-install path) and the `catalogDDL` array in `server/lib/db.js:ensureSchema()` (upgrade path) — table columns, indexes, trigger functions, triggers, the `type` CHECK list, and the `search_tsv` payload-field set must match in both files, so a future PR can't update one and forget the other.- **[pythonsetup-arch-tests] Test coverage for the arch-aware Local Python detector.** Internal: locks in the macOS arm64-vs-x86_64 preference behavior and the `/setup/check` arch fields with mocked-platform unit tests, so future edits to interpreter detection can't silently regress mlx wheel loading. No user-visible behavior change.diff --git a/PLAN.md b/PLAN.mdindex 96451fc56b..9937e5b58b 100644--- a/PLAN.md+++ b/PLAN.md@@ -8,45 +8,47 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelThe 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). Phase-7-onward slices remain:-_In review 2026-05-30 (7 PRs, claude+codex reviewed): 16 "ready" items across both catalog sections are implemented and awaiting merge — #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` (slice — see its remaining-scope note). Check items off on merge. The 4 gated items (`catalog-type-table-vs-check`, `catalog-user-defined-types`, `catalog-ask-retrieval`, `catalog-scrap-chunking`) were intentionally excluded pending a human-led decision/research pass._+_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)._New follow-ups surfaced during the 2026-05-30 review pass:-- [ ] [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.-- [ ] [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.-- [ ] [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-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.- [ ] [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.- [ ] [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.-- [ ] [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-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.-- [ ] [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`).+- [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._-- [ ] [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.-- [ ] [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]`.-- [ ] [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)._-- [ ] [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`.+- [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.-- [ ] [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-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.- [ ] [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.-- [ ] [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.+- [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`).-- [ ] [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.-- [ ] [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.-- [ ] [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.-- [ ] [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-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]`.**_- [ ] [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.-- [ ] [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.-- [ ] [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.-- [ ] [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.-- [ ] [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.+- [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`._