Skip to content

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

plan/changelog: prune shipped catalog items + log this batch

[._.]/ Adam Eivyee8f1a7865ac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ab4a274b41..dfe0bcbe1a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Changed
+- **[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.
- **[mediajobqueue-resolve-live-params] Media job dispatch internals.** Internal refactor: the live-settings re-resolution step that picks the current Python interpreter before each video / local-image render moves into its own helper, giving future live-resolved fields a single seam. No user-visible behavior change.
- **[patch-settings-slice-helper] Nested settings edits no longer risk clobbering sibling fields.** Saving a Python path from Video Gen, or an image-gen config from a pipeline / Writers Room stage, used to round-trip the entire current settings object — leaving unrelated top-level keys exposed to drift if the read raced a concurrent write elsewhere. These edits now scope themselves to the slice being changed.
@@ -12,6 +13,8 @@
## Added
+- **[catalog-extraction-idea-scene-concept] Catalog Ingest now extracts ideas, scenes, and concepts too.** Pasting prose into `/catalog/ingest` previously only surfaced characters / places / objects. A new LLM stage runs alongside the three existing bible passes and proposes idea, scene, and concept candidates from the same scrap — each rendered as its own review section with selectable / editable rows, then committed via the same path. One additional LLM call per ingest; failures isolate to that stage so the other three are unaffected.
+- **[catalog-quick-idea-dashboard-widget] New "Quick Idea (Catalog)" dashboard widget.** Captures a creative ingredient directly into the catalog without the scrap+extract LLM round-trip — pick a type chip (character / place / object / idea / scene / concept), name it, optionally add primary text and tags, and submit. Lands in the Quick Capture row of the seeded "Everything" layout on fresh installs. Existing installs whose `data/dashboard-layouts.json` predates this PR keep their saved layout — the new widget appears in the Layout Picker's "Edit" sheet so you can toggle it on. The "Open" link in the success toast jumps straight to the new ingredient's detail page.
- **[catalog-extensibility-roadmap] PLAN.md: Creative Catalog extensibility roadmap.** Internal: 14 new tracked items covering type-registry consolidation, types table vs CHECK constraint, per-payload `schemaVersion` + upgraders, user-defined ingredient types, ingredient↔ingredient relations, canonical tag taxonomy, revision history, media attachments, bulk import + slice export, ⌘K/Ask/voice discovery hooks, URL/file/voice-memo source kinds, scrap chunking, and a dashboard Quick Idea (Catalog) widget under Quick Capture. No user-visible behavior change yet — scopes the work required to evolve the catalog beyond the v1 six hardcoded types.
- **[creative-ingredients-catalog-upgrade-path] Catalog deployment + upgrade story.** The bible→catalog backfill is now peer-aware: when a universe arrives via federated sync carrying an `ingredientId` that doesn't exist in the receiving install's catalog, the backfill creates the local catalog row WITH that explicit id instead of minting a new one — so the same logical character keeps the same catalog id across every install in the federation, even when the catalog rows weren't in the original sync payload. A new admin endpoint `POST /api/catalog/migration/rerun` (with `{ force: true }` to ignore the applied-marker) lets users recover from a stuck backfill or fix data on a peer. Catalog DDL ships in both `server/scripts/init-db.sql` (fresh installs via docker-entrypoint-initdb.d or `setup-db.js`/`db.sh setup-native`) AND `server/lib/db.js:ensureSchema()` (idempotent runtime upgrades — runs on every server boot), so existing installs pick up the catalog tables on the first restart post-pull without needing to re-run `init-db.sql`.
- **[creative-ingredients-catalog] New "Catalog" feature under Create.** A central, Postgres-backed store of typed creative ingredients — characters, places, objects, ideas, scenes, concepts. Paste any creative scrap (a one-line story spark, a scene snippet, a rough short-story draft) into `/catalog/ingest` and the server extracts candidate characters / places / objects via LLM, streams progress as a stage checklist, and shows a review screen where you check the ones to commit. The Catalog page (`/catalog`) lists every ingredient with type-chip filters, debounced search, and a one-click "+ New" inline form for the lighter idea/scene/concept types. Each ingredient has a detail page with source-scrap provenance and an "Appears in" panel that back-links to every universe / series / issue / work referencing it. Federation routes (`GET/POST /api/catalog/sync`) are wired and version-gated via the existing `PORTOS_SCHEMA_VERSIONS` contract (`catalog: 1`); the auto-orchestrator hookup ships in a follow-up. A boot-time migration backfilled 970 ingredients across 10 existing universes (94 characters, 140 places, 736 objects) so the catalog opens populated. **Vector embeddings are provider-agnostic** — a new Embeddings settings tab lets you pick Ollama or LM Studio + a 768-dim model (e.g. `nomic-embed-text`); embeddings auto-apply at ingest when configured and a `/api/catalog/embeddings/backfill` admin endpoint fills missing rows. Per-record sanitizer carries an `ingredientId` field through the round-trip so embedded universe canon stays linked to its catalog row.
diff --git a/PLAN.md b/PLAN.md
index ffc87ab0a1..3fcb59ab2a 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -11,14 +11,8 @@ The catalog backend, schema, federation routes, ingest extraction service, and C
- [ ] [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-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'`).
- [ ] [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-ddl-drift-test] **Add a server test that diffs the catalog DDL between `server/scripts/init-db.sql` and the catalog block in `server/lib/db.js:ensureSchema()`.** Both files now duplicate the four table definitions + indexes + trigger functions; a future PR that updates one without the other will leave fresh installs and upgrading installs with different schemas. Lift the catalog DDL into a shared constant array consumed by both, or write a smoke test that parses both files and compares the relevant statements. Same risk exists for the `memories`/`memory_links` DDL but has been tolerated since the memory system landed; catalog inherits it. Surfaced when the user asked about Postgres schema upgrade management (2026-05-29).
- [ ] [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-extraction-idea-scene-concept] **Extend `server/services/catalogExtraction.js` to also extract idea / scene / concept ingredients from a scrap.** Current extractor reuses `extractBible` for character/place/object only (the three storyBible-shaped types). For the other three, ship a single LLM JSON-mode call with a custom prompt; surface the new stages on `catalog:extract:progress`. Until this lands, ideas/scenes/concepts are created manually via the Catalog list's "+ New" button.
-- [ ] [catalog-fts-character-fields] **`catalog_ingredients.search_tsv` (GENERATED ALWAYS) indexes `payload->>description|notes|background|summary` but NOT `physicalDescription` or `personality`** — so a search for "tall" or "introverted" misses bible-backfilled characters whose narrative text lives in those keys. Fix needs a schema migration: DROP COLUMN search_tsv + ADD COLUMN with the expanded expression (Postgres can't ALTER a STORED generated expression), update both `server/lib/db.js` and `server/scripts/init-db.sql`, and bump `PORTOS_SCHEMA_VERSIONS.catalog`. Surfaced by gemini review pass on the catalog PR (2026-05-29).
-- [ ] [catalog-commit-transactional] **`POST /api/catalog/scraps/:id/commit` does N `createIngredient` + N `linkIngredientToSource` writes in a sequential loop with no transaction.** A mid-loop failure (DB timeout, validation throw) leaves a partial commit — some ingredients persisted, some not, and some ingredients without source-link rows. Wrap the loop in `withTransaction` and pass the client down to `createIngredient` / `linkIngredientToSource`. Requires the catalogDB write helpers to accept an optional `client` (currently they call the pool-level `query()` directly). Surfaced by gemini review pass (2026-05-29).
-- [ ] [catalog-scrap-embedding-or-search] **Scraps embed on every create (`POST /api/catalog/scraps`), but the embedding column is never read** — no semantic-search route, no "find similar scraps" UI. Either remove the LLM round-trip on create (and keep the column for future use) OR ship the search endpoint that justifies the cost. Currently every scrap creation burns a 768-dim embedding call for zero search benefit. Surfaced by gemini review pass (2026-05-29).
-- [ ] [catalog-ref-deletion-tombstones] **`catalog_ingredient_refs` uses hard DELETE on unlink — the row vanishes with no `sync_sequence` bump and no tombstone, so peers that already pulled the ref never learn it was removed and their "Appears in" panels stay stale.** Fix needs: add `deleted boolean DEFAULT false` + `deleted_at timestamptz` to `catalog_ingredient_refs` (DDL in both `server/lib/db.js` and `server/scripts/init-db.sql`), switch `unlinkIngredientFromRef` in `server/services/catalogDB.js:430` to soft-delete with `sync_sequence` bump, teach `applyRemoteChanges` in `server/services/catalogSync.js` to apply ref-delete envelopes, and bump `PORTOS_SCHEMA_VERSIONS.catalog`. Pairs with `[catalog-federation-orchestrator]` — also re-surfaced by the codex review pass on the catalog PR (2026-05-29).
-- [ ] [catalog-tests] **Tests for the catalog stack.** `server/services/catalogDB.test.js` (CRUD round-trip — bootstrap follows `server/services/memoryDB.test.js`), `catalogExtraction.test.js` (mock aiToolkit, assert Zod conformance), `catalogSync.test.js` (envelope round-trip + LWW), `server/lib/catalogValidation.test.js` (Zod boundary tests), `server/scripts/migrateBibleToCatalog.test.js` (idempotency), `client/src/pages/Catalog.test.jsx`, `client/src/components/IngredientPicker.test.jsx`.
+- [ ] [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`.
### Creative Catalog — extensibility roadmap
@@ -38,7 +32,6 @@ The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`)
- [ ] [catalog-cmdk-ask-voice-discovery] **Surface catalog ingredients in ⌘K / Ask / voice (cross-surface discovery).** Today the catalog is only reachable via `/catalog` and the per-page Pick-from-Catalog buttons (post-`[catalog-universe-builder-picker]`). Three integrations needed: (1) `⌘K` palette — open the manifest to "search results" beyond static nav by calling `/api/catalog/ingredients?q=<query>` when the user types; show top 5 matches with type badges; selecting opens the ingredient detail. (2) Ask retrieval — let `/api/ask` pull catalog ingredients tagged or linked to the active universe/series as part of its context window (token-budgeted, top-K hybrid search). (3) Voice tool `catalog_lookup({ query, type? })` registered in `server/services/voice/tools.js` + the `palette.js` whitelist. Each integration is independent and the registry from `[catalog-shared-type-registry]` makes the type filter trivial.
- [ ] [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.
-- [ ] [catalog-quick-idea-dashboard-widget] **Add a Quick Idea (Catalog) widget under the dashboard's Quick Capture set, mirroring `QuickBrainCapture`.** New file `client/src/components/QuickIdeaCapture.jsx`; registry entry `{ id: 'quick-idea', label: 'Quick Idea (Catalog)', Component: QuickIdeaCapture, width: 'half', defaultH: 4 }` in `widgetRegistry.jsx`; add to the `default` layout in `server/services/dashboardLayouts.js`. Behavior: a single-row type chip selector (driven by `[catalog-shared-type-registry]`'s `TYPES` so adding a 7th type lights up automatically — until that lands, mirror `Catalog.jsx`'s local `TYPES` array but mark the file with a `// TODO: switch to shared registry` comment so the followup is discoverable). On type pick, render the type's primary-content key as a single textarea labeled by `PRIMARY_CONTENT_LABEL[primaryContentKey]` (e.g. "Physical Description" for character, "Summary" for idea/scene/concept, "Description" for place/object), plus a name field and optional tag input. Submit calls `createCatalogIngredient({ type, name, payload: { [primaryContentKey]: text }, tags })`. Optimistic toast + clear; "Open in Catalog" link to `/catalog/:type/:id`. No LLM extraction — this is the *fast* path for the user who already knows what shape they want (the scrap+extract path on `/catalog/ingest` is the *slow* path). Mobile-responsive (chip row wraps; full-width textarea). Pairs with `[catalog-shared-type-registry]` — without the registry the widget will need to be touched whenever a new type lands.
_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`._