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
stamp per-record catalog payload.schemaVersion + add upgrade migration
[._.]/ Adam Eivy085795b619e9
diff --git a/scripts/migrations/049-catalog-payload-schemaversion.js b/scripts/migrations/049-catalog-payload-schemaversion.jsnew file mode 100644index 0000000000..01f13e0c01--- /dev/null+++ b/scripts/migrations/049-catalog-payload-schemaversion.js@@ -0,0 +1,28 @@+/**+ * Registration stub for the per-record catalog payload-schemaVersion+ * migration.+ *+ * The actual work — walking `catalog_ingredients` rows whose stored+ * `payload.schemaVersion` lags the registry-current and applying the per-type+ * upgrader chain — lives in `server/scripts/migrateCatalogPayload.js` and runs+ * at server boot, AFTER `ensureSchema()` (it needs Postgres tables). The+ * `scripts/migrations/` runner (`scripts/run-migrations.js`) executes BEFORE+ * the DB pool is initialized, so a DB walk cannot live here — the same reason+ * `migrateBibleToCatalog` runs at boot rather than as a file-runner migration.+ *+ * This stub exists so the migration is *registered the standard way*: it lands+ * in `data/migrations.applied.json`, so `git log` / the migration ledger show+ * the payload-versioning migration was introduced in this release, and so a+ * future audit of "which migrations has this install seen" is complete. The+ * boot-time `migrateCatalogPayload` keeps its own `data/catalog-payload.applied.json`+ * high-water marker (mirroring `migrateBibleToCatalog`'s+ * `catalog-backfill.applied.json`) for the idempotent DB walk.+ *+ * No-op + idempotent: nothing to do here.+ */++export default {+ async up() {+ console.log('🧬 catalog payload schemaVersion: per-record migration runs at boot (server/scripts/migrateCatalogPayload.js); nothing to do in the file runner');+ },+};diff --git a/server/index.js b/server/index.jsindex 9c52d86a7e..7f32c35113 100644--- a/server/index.js+++ b/server/index.js@@ -692,8 +692,14 @@ ensureSelf()await ensureSchema();const { migrateBibleToCatalog } = await import('./scripts/migrateBibleToCatalog.js');await migrateBibleToCatalog();+ // Per-record catalog payload-shape migration — walks rows whose stored+ // payload.schemaVersion lags the registry-current and applies registered+ // upgraders. No-ops via marker once an install is at the high-water+ // version, so this is free on steady-state boots.+ const { migrateCatalogPayload } = await import('./scripts/migrateCatalogPayload.js');+ await migrateCatalogPayload();} catch (err) {- console.error(`🪄 bible→catalog migration failed at boot: ${err.message}`);+ console.error(`🪄 catalog migrations failed at boot: ${err.message}`);}}).then(() => {diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 40c7056f57..8dfc112a8f 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -67,6 +67,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// their pushes; newer peers pushing to older receivers are sender-ahead// and get 412. `cat-ingredient` and `cat-scrap` record kinds map back// here via RECORD_KIND_SCHEMA_CATEGORIES.+ //+ // NOT bumped for the per-record `payload.schemaVersion` stamp added by+ // catalog-payload-schemaversion: that key is additive JSONB that both old+ // and new peers store verbatim (`upsertIngredientFromPeer` writes payload+ // as-is — no sanitizer strips it), and all types are payload-v1 today so no+ // shape actually changed on the wire. The FIRST type that bumps its+ // registry `payloadSchemaVersion` to 2 with a genuine shape change (a peer+ // ≤ that version would round-trip the new shape through an unaware+ // sanitizer) MUST bump `catalog` here in lockstep.catalog: 3,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (thediff --git a/server/scripts/migrateCatalogPayload.js b/server/scripts/migrateCatalogPayload.jsnew file mode 100644index 0000000000..56134c486a--- /dev/null+++ b/server/scripts/migrateCatalogPayload.js@@ -0,0 +1,120 @@+/**+ * Per-record catalog payload schemaVersion migration.+ *+ * Every `catalog_ingredients` row carries `payload.schemaVersion` (stamped at+ * create time by `catalogDB.createIngredient`). When a TYPE's payload shape+ * evolves, the registry (`server/lib/catalogTypes.js`) bumps that type's+ * `payloadSchemaVersion` and registers `payloadUpgraders` keyed by FROM+ * version. This script walks every row whose stored `payload.schemaVersion`+ * is below the registry-current for its type and applies the upgrader chain,+ * persisting the upgraded payload (which re-stamps `schemaVersion` to current).+ *+ * Distinct from:+ * - the cross-instance WIRE contract (`PORTOS_SCHEMA_VERSIONS.catalog`),+ * which gates whether a peer push is even accepted; and+ * - the storage-LAYOUT version (Postgres tables) handled by `ensureSchema`.+ * This is the per-record payload-SHAPE version, mirroring the+ * `data/{type}/index.json` `schemaVersion` convention documented in CLAUDE.md.+ *+ * Idempotency: a marker in `data/catalog-payload.applied.json` records the+ * highest registry payload version this install has fully migrated to, so the+ * walk only runs when a new code version actually raised a type's+ * `payloadSchemaVersion`. The per-row predicate (`stored < current`) is itself+ * idempotent, so re-running is always safe.+ *+ * Invoked from server/index.js at boot, after `ensureSchema()` (it needs the+ * tables) and alongside `migrateBibleToCatalog` — both are DB walks that can't+ * ride the pre-DB `scripts/migrations/` file runner.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { query } from '../lib/db.js';+import { CATALOG_TYPES, currentPayloadSchemaVersion, upgradePayload } from '../lib/catalogTypes.js';++const MARKER_FILENAME = 'catalog-payload.applied.json';++// The aggregate "fully-migrated-to" version is the max payloadSchemaVersion+// across all types. When code bumps any type past this, the marker is stale+// and the walk runs. (A per-type marker would be finer-grained but the walk's+// row predicate is already per-type, so a single high-water mark is enough to+// skip the no-op boot scan on an already-migrated install.)+const targetHighWater = () => Math.max(...CATALOG_TYPES.map((t) => t.payloadSchemaVersion));++async function readMarker() {+ const path = join(PATHS.data, MARKER_FILENAME);+ const raw = await readFile(path, 'utf-8').catch(() => null);+ if (!raw) return null;+ try { return JSON.parse(raw); } catch { return null; }+}++async function writeMarker(payload) {+ const path = join(PATHS.data, MARKER_FILENAME);+ await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');+}++/**+ * Walk one type's below-current rows and apply the upgrader chain. Returns the+ * number of rows upgraded. Rows whose stored `schemaVersion` is absent are+ * treated as v1 (the original shape) by `upgradePayload`.+ *+ * Only types that declare at least one upgrader are walked — a type that+ * bumped its version without registering an upgrader has nothing to apply, and+ * `upgradePayload` would only re-stamp the marker (harmless but pointless work+ * across potentially many rows), so we skip it.+ */+async function migrateType(type) {+ const current = currentPayloadSchemaVersion(type.id);+ if (current <= 1) return 0;+ if (!type.payloadUpgraders || Object.keys(type.payloadUpgraders).length === 0) return 0;++ // `payload->>'schemaVersion'` is text; a missing key yields NULL → treated as+ // below-current. `COALESCE(...,'1')::int` lets the comparison run in SQL.+ const result = await query(+ `SELECT id, payload FROM catalog_ingredients+ WHERE type = $1+ AND deleted = false+ AND COALESCE((payload->>'schemaVersion')::int, 1) < $2`,+ [type.id, current],+ );++ let upgraded = 0;+ for (const row of result.rows) {+ const next = upgradePayload(type.id, row.payload || {});+ await query(+ `UPDATE catalog_ingredients SET payload = $2::jsonb WHERE id = $1`,+ [row.id, JSON.stringify(next)],+ );+ upgraded++;+ }+ return upgraded;+}++/**+ * Public entry point. No-ops when the marker shows this install is already at+ * (or above) the current high-water version, unless `force` is set.+ */+export async function migrateCatalogPayload({ force = false } = {}) {+ const highWater = targetHighWater();+ const marker = await readMarker();+ if (!force && marker?.highWater >= highWater) {+ return { skipped: true, marker };+ }++ console.log(`🧬 catalog payload migration: starting (target v${highWater})`);+ const totals = { typesWalked: 0, upgraded: 0 };+ for (const type of CATALOG_TYPES) {+ const n = await migrateType(type);+ if (n > 0) {+ totals.typesWalked++;+ totals.upgraded += n;+ console.log(`🧬 ${type.id}: upgraded ${n} row(s) to v${currentPayloadSchemaVersion(type.id)}`);+ }+ }++ const payload = { highWater, completedAt: new Date().toISOString(), stats: totals };+ await writeMarker(payload);+ console.log(`🧬 catalog payload migration: ${totals.upgraded} row(s) upgraded across ${totals.typesWalked} type(s)`);+ return { skipped: false, ...payload };+}diff --git a/server/scripts/migrateCatalogPayload.test.js b/server/scripts/migrateCatalogPayload.test.jsnew file mode 100644index 0000000000..ffe214dfeb--- /dev/null+++ b/server/scripts/migrateCatalogPayload.test.js@@ -0,0 +1,115 @@+/**+ * Tests for the per-record catalog payload-schemaVersion migration.+ *+ * Postgres + the marker file are mocked, and the registry is mocked to inject+ * a type with a real upgrader chain (the shipped registry is all payload-v1,+ * so there is nothing to walk in production yet). This exercises:+ * - the below-current row predicate + upgrader application;+ * - the marker high-water skip on an already-migrated install;+ * - the no-walk path for types without upgraders.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { rows: [], updates: [] };+const fsState = { marker: null, written: null };++vi.mock('../lib/db.js', () => ({+ query: vi.fn(async (sql, params) => {+ if (/^\s*SELECT/i.test(sql)) return { rows: db.rows };+ if (/^\s*UPDATE/i.test(sql)) { db.updates.push({ id: params[0], payload: JSON.parse(params[1]) }); return { rows: [] }; }+ return { rows: [] };+ }),+}));++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async () => (fsState.marker == null ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) : JSON.stringify(fsState.marker))),+ writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),+}));++vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));++// Inject a synthetic registry with a v1→v2 upgrader (character) plus an all-v1+// upgrader-less type (idea). Defined inside the factory because vi.mock hoists+// above top-level consts.+vi.mock('../lib/catalogTypes.js', () => {+ const SYNTH_TYPES = [+ {+ id: 'character',+ payloadSchemaVersion: 2,+ payloadUpgraders: { 1: (p) => ({ ...p, voiceNotes: p.voiceNotes ?? '' }) },+ },+ { id: 'idea', payloadSchemaVersion: 1, payloadUpgraders: {} },+ ];+ return {+ CATALOG_TYPES: SYNTH_TYPES,+ currentPayloadSchemaVersion: (id) => SYNTH_TYPES.find((t) => t.id === id)?.payloadSchemaVersion ?? 1,+ upgradePayload: (id, payload) => {+ const t = SYNTH_TYPES.find((x) => x.id === id);+ let p = { ...payload };+ let v = Number.isInteger(p.schemaVersion) ? p.schemaVersion : 1;+ while (v < t.payloadSchemaVersion) {+ const up = t.payloadUpgraders[v];+ if (typeof up !== 'function') break;+ p = up(p) || p;+ v += 1;+ }+ p.schemaVersion = t.payloadSchemaVersion;+ return p;+ },+ };+});++import { migrateCatalogPayload } from './migrateCatalogPayload.js';++beforeEach(() => {+ db.rows = [];+ db.updates = [];+ fsState.marker = null;+ fsState.written = null;+});++describe('migrateCatalogPayload', () => {+ it('upgrades below-current rows and re-stamps schemaVersion', async () => {+ db.rows = [+ { id: 'cat-chr-1', payload: { name: 'Echo', schemaVersion: 1 } },+ { id: 'cat-chr-2', payload: { name: 'Vox' } }, // missing version → treated as v1+ ];+ const res = await migrateCatalogPayload();+ expect(res.skipped).toBe(false);+ expect(res.stats.upgraded).toBe(2);+ expect(db.updates).toHaveLength(2);+ for (const u of db.updates) {+ expect(u.payload.schemaVersion).toBe(2);+ expect(u.payload).toHaveProperty('voiceNotes');+ }+ // Marker stamped to the high-water version.+ expect(fsState.written.highWater).toBe(2);+ });++ it('skips entirely when the marker is already at the high-water version', async () => {+ fsState.marker = { highWater: 2 };+ db.rows = [{ id: 'cat-chr-1', payload: { schemaVersion: 1 } }];+ const res = await migrateCatalogPayload();+ expect(res.skipped).toBe(true);+ expect(db.updates).toHaveLength(0);+ });++ it('re-runs when forced even if the marker is current', async () => {+ fsState.marker = { highWater: 2 };+ db.rows = [{ id: 'cat-chr-1', payload: { schemaVersion: 1 } }];+ const res = await migrateCatalogPayload({ force: true });+ expect(res.skipped).toBe(false);+ expect(db.updates).toHaveLength(1);+ });++ it('does not walk types that have no upgraders', async () => {+ // Only the character type (with an upgrader) should be queried; the idea+ // type is v1 / upgrader-less. We assert nothing was upgraded when the only+ // below-current rows belong to the no-upgrader type — the migration never+ // SELECTs for it. Simulate by leaving db.rows empty (character has none).+ db.rows = [];+ const res = await migrateCatalogPayload();+ expect(res.stats.upgraded).toBe(0);+ });+});diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 1710e5ab94..0ab2d5c339 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -14,6 +14,7 @@ import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../libimport {getCatalogType,ingredientIdPrefix,+ currentPayloadSchemaVersion,} from '../lib/catalogTypes.js';import { getInstanceId } from './instances.js';@@ -196,6 +197,14 @@ export async function createIngredient({ id: explicitId, type, name, payload = {// same logical character has the same catalog id on every install. New// user-initiated creates omit it and we mint a fresh prefix:uuid.const id = explicitId || newIngredientId(type);+ // Stamp the per-record payload-shape version from the registry so a later+ // `migrateCatalogPayload` run knows which shape this row was written in.+ // An incoming payload may already carry `schemaVersion` (peer backfill) — we+ // overwrite with the LOCAL registry-current value so the stored marker+ // reflects the shape this install's code actually wrote, not a stale sender+ // claim. (The wire `PORTOS_SCHEMA_VERSIONS.catalog` gate covers cross-install+ // skew; this is the per-record payload-shape marker, distinct from that.)+ const storedPayload = { ...(payload && typeof payload === 'object' ? payload : {}), schemaVersion: currentPayloadSchemaVersion(type) };const originInstanceId = await getInstanceId();const exec = client ? client.query.bind(client) : query;const result = await exec(@@ -207,7 +216,7 @@ export async function createIngredient({ id: explicitId, type, name, payload = {id,type,String(name).trim(),- JSON.stringify(payload || {}),+ JSON.stringify(storedPayload),tags || [],embedding ? arrayToPgvector(embedding) : null,embeddingModel,@@ -282,8 +291,12 @@ export async function deleteIngredient(id, { hard = false } = {}) {* `null` if no row exists at that id (caller falls through to plain INSERT).*/export async function reviveDeletedIngredient(id, { type, name, payload = {}, tags = [] } = {}) {- if (!type || !TYPE_PREFIX[type]) throw new Error(`reviveDeletedIngredient: invalid type ${type}`);+ if (!type || !getCatalogType(type)) throw new Error(`reviveDeletedIngredient: invalid type ${type}`);if (!name || !String(name).trim()) throw new Error('reviveDeletedIngredient: name required');+ // Re-stamp the payload schemaVersion on revive — the revived row is being+ // rewritten with a fresh payload, so it gets this install's current marker+ // (mirrors createIngredient).+ const storedPayload = { ...(payload && typeof payload === 'object' ? payload : {}), schemaVersion: currentPayloadSchemaVersion(type) };const result = await query(`UPDATE catalog_ingredientsSET deleted = false, deleted_at = NULL,@@ -291,7 +304,7 @@ export async function reviveDeletedIngredient(id, { type, name, payload = {}, taupdated_at = NOW()WHERE id = $1 AND deleted = trueRETURNING *`,- [id, type, String(name).trim(), JSON.stringify(payload || {}), tags || []],+ [id, type, String(name).trim(), JSON.stringify(storedPayload), tags || []],);return result.rows.length > 0 ? rowToIngredient(result.rows[0]) : null;}diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.jsnew file mode 100644index 0000000000..5a669ed7a0--- /dev/null+++ b/server/services/catalogDB.test.js@@ -0,0 +1,103 @@+/**+ * Unit tests for the catalog DB layer's registry-driven behavior:+ * - `createIngredient` stamps `payload.schemaVersion` from the registry;+ * - it overwrites an incoming (stale/peer) schemaVersion with the LOCAL one;+ * - the minted id uses the registry's per-type prefix;+ * - an unknown type throws before touching the DB.+ *+ * Postgres is mocked — we capture the INSERT params and assert on them, so the+ * suite runs without a live database.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const captured = { sql: null, params: null };++vi.mock('../lib/db.js', () => ({+ query: vi.fn(async (sql, params) => {+ captured.sql = sql;+ captured.params = params;+ // Echo a row shaped like catalog_ingredients so rowToIngredient works.+ const [id, type, name] = params;+ const payload = JSON.parse(params[3]);+ return {+ rows: [{+ id, type, name, payload, tags: params[4] || [],+ embedding: null, embedding_model: null, origin_instance_id: params[7],+ created_at: new Date(), updated_at: new Date(),+ deleted: false, deleted_at: null, sync_sequence: 1,+ }],+ };+ }),+ withTransaction: vi.fn(),+ pgvectorToArray: vi.fn(() => null),+ arrayToPgvector: vi.fn((a) => a),+}));++vi.mock('./instances.js', () => ({+ getInstanceId: vi.fn(async () => 'inst-test'),+}));++import { createIngredient, reviveDeletedIngredient } from './catalogDB.js';+import { currentPayloadSchemaVersion } from '../lib/catalogTypes.js';++beforeEach(() => {+ captured.sql = null;+ captured.params = null;+});++describe('createIngredient — payload schemaVersion stamping', () => {+ it('stamps the registry-current payload schemaVersion', async () => {+ const ing = await createIngredient({ type: 'character', name: 'Echo', payload: { physicalDescription: 'tall' } });+ const stored = JSON.parse(captured.params[3]);+ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('character'));+ expect(stored.physicalDescription).toBe('tall');+ // The returned record carries the stamped payload too.+ expect(ing.payload.schemaVersion).toBe(currentPayloadSchemaVersion('character'));+ });++ it('overwrites an incoming (stale) schemaVersion with the local one', async () => {+ await createIngredient({ type: 'idea', name: 'Spark', payload: { summary: 'x', schemaVersion: 99 } });+ const stored = JSON.parse(captured.params[3]);+ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('idea'));+ expect(stored.schemaVersion).not.toBe(99);+ });++ it('stamps even when no payload is supplied', async () => {+ await createIngredient({ type: 'scene', name: 'Open' });+ const stored = JSON.parse(captured.params[3]);+ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('scene'));+ });+});++describe('createIngredient — registry-derived id prefix + type guard', () => {+ it('mints an id with the registry per-type prefix', async () => {+ const ing = await createIngredient({ type: 'place', name: 'Dock' });+ expect(ing.id).toMatch(/^cat-plc-/);+ });++ it('preserves an explicit id (peer backfill) without minting', async () => {+ const ing = await createIngredient({ id: 'cat-chr-bible-abc', type: 'character', name: 'Echo' });+ expect(ing.id).toBe('cat-chr-bible-abc');+ });++ it('throws on an unknown type before touching the DB', async () => {+ await expect(createIngredient({ type: 'wardrobe', name: 'Cape' })).rejects.toThrow(/Invalid ingredient type/);+ expect(captured.params).toBeNull();+ });+});++describe('reviveDeletedIngredient — registry guard + payload stamping', () => {+ it('validates the type against the registry (not a stale prefix map)', async () => {+ await expect(reviveDeletedIngredient('cat-x-1', { type: 'wardrobe', name: 'Cape' }))+ .rejects.toThrow(/invalid type/);+ expect(captured.params).toBeNull();+ });++ it('re-stamps the payload schemaVersion on revive', async () => {+ await reviveDeletedIngredient('cat-chr-1', { type: 'character', name: 'Echo', payload: { role: 'lead' } });+ const stored = JSON.parse(captured.params[3]);+ expect(stored.schemaVersion).toBe(currentPayloadSchemaVersion('character'));+ expect(stored.role).toBe('lead');+ });+});