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

address review (codex): support per-kind sync cursors under Express 5 simple parser, always run idempotent catalog DDL

[._.]/ Adam Eivy4cf774b5bb4e
diff --git a/PLAN.md b/PLAN.md
index fc7fd7874c..bde04381ab 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -14,6 +14,7 @@ The catalog backend, schema, federation routes, ingest extraction service, and C
- [ ] [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-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-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`.
diff --git a/server/lib/db.js b/server/lib/db.js
index 241199d27e..62b4023a1e 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -103,23 +103,14 @@ export async function ensureSchema() {
await pool.query(sql);
}
- // Catalog block: probe ALL four tables. A previous boot that crashed
- // mid-DDL (network blip, OOM) could leave catalog_ingredients present but
- // catalog_ingredient_sources / _refs missing; gating only on the lead
- // table would silently freeze the install in that half-applied state.
- // Every catalogDDL statement is idempotent (CREATE IF NOT EXISTS / OR
- // REPLACE), so re-running on a fully-applied install is a no-op anyway.
- const catalogReady = await pool.query(
- `SELECT
- to_regclass('public.catalog_ingredients') IS NOT NULL
- AND to_regclass('public.catalog_scraps') IS NOT NULL
- AND to_regclass('public.catalog_ingredient_sources') IS NOT NULL
- AND to_regclass('public.catalog_ingredient_refs') IS NOT NULL AS ready`,
- );
- if (catalogReady.rows?.[0]?.ready) {
- console.log('🗄️ Database schema upgrades applied');
- return;
- }
+ // Catalog block: every statement below is idempotent (CREATE IF NOT EXISTS
+ // / CREATE OR REPLACE FUNCTION / DROP TRIGGER IF EXISTS + CREATE TRIGGER),
+ // so we run the whole list on every boot rather than gating on table
+ // presence. A previous probe that early-returned on "all four tables exist"
+ // would skip the indexes / functions / triggers if the prior boot crashed
+ // between the table CREATEs and the artifact CREATEs — leaving the schema
+ // marked ready while update triggers and HNSW indexes were never installed.
+ // Cost on a fully-applied install is ~30 Postgres no-op parses (<10ms).
const catalogDDL = [
`CREATE TABLE IF NOT EXISTS catalog_scraps (
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 3dedddcc69..415355915c 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -197,14 +197,31 @@ router.get('/sync', asyncHandler(async (req, res) => {
// The four `sync_sequence` columns are independent — accept either
// `?since=N` (uniform; only meaningful on the first pull where everyone's
// at 0) or `?since[scraps]=A&since[ingredients]=B&...` for subsequent
- // pulls. Express's `qs` parser turns the bracket form into a nested object.
+ // pulls.
+ //
+ // Express 5 defaults `query parser` to `simple` (Node's querystring),
+ // which leaves `since[scraps]=10` as a flat key `'since[scraps]': '10'`
+ // instead of nesting it. We reconstruct the per-kind object ourselves so
+ // the documented bracket protocol survives regardless of parser config —
+ // otherwise peers would silently keep pulling page 1 and loop on hasMore.
const sinceRaw = req.query.since;
- const isCursorObj = sinceRaw && typeof sinceRaw === 'object' && !Array.isArray(sinceRaw);
- // Reject arrays (`?since=1&since=2`) — coerce to '0' rather than letting
- // them silently re-pull the whole sync log.
- const since = isCursorObj
- ? sinceRaw
- : (typeof sinceRaw === 'string' && /^\d+$/.test(sinceRaw) ? sinceRaw : '0');
+ let since;
+ if (sinceRaw && typeof sinceRaw === 'object' && !Array.isArray(sinceRaw)) {
+ since = sinceRaw;
+ } else {
+ const bracket = {};
+ for (const [k, v] of Object.entries(req.query)) {
+ const m = /^since\[([a-z]+)\]$/.exec(k);
+ if (m && typeof v === 'string') bracket[m[1]] = v;
+ }
+ if (Object.keys(bracket).length > 0) {
+ since = bracket;
+ } else {
+ // Reject arrays (`?since=1&since=2`) — coerce to '0' rather than letting
+ // them silently re-pull the whole sync log.
+ since = (typeof sinceRaw === 'string' && /^\d+$/.test(sinceRaw)) ? sinceRaw : '0';
+ }
+ }
const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 100, 1), 1000);
const changes = await catalogSync.getChangesSince(since, limit);
res.json({