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
fix: preserve catalog attachments across mixed-version peers (#8257)
[._.]/ Adam Eivy71788aea3511
diff --git a/server/lib/README.md b/server/lib/README.mdindex fd6bd1b285..c70493dea1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -320,7 +320,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. || `comparisonModelScope.js` | `catalogSlugForProviderModel(id)` / `providerCatalogSlugs(inventory)` — map provider model ids (Bedrock region prefixes, gateway namespaces, effort/quantization suffixes, dashed versions) onto canonical model identities for scoping shipped reference-price rows to models PortOS can dispatch. Pure. || `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and every base-hash-evicting `pruneTombstoned*` loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so those paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). The base-hash file is read STRICT (`readJSONFileStrict`): a present-but-unreadable `sync_base_hashes.json` latches `_persistBlocked` — `flushBaseHashes()` no-ops so the file is preserved, `maybeJournalBeforeOverwrite` journals every overwrite fail-closed, `detectConflict` reports `baseUnavailable`, and `isBaseHashPersistBlocked()` exposes the latch to the conflict-journal status payload (#7260). Local-only — never crosses the wire. |-| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |+| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), `catalogEnvelopeHasLiveRows()` (shared live-row versus tombstone gate for catalog transfers), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 950969aa82..f450e2cf8b 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -22,8 +22,8 @@* receivers compare incoming vs local and reject ahead-mismatches (sender too* new) or behind-mismatches (sender too old to satisfy a forward-only field).*- * Absent categories default to 0 — the comparator treats 0 as "no check"- * so historical / un-versioned data categories pass through unchanged.+ * Absent categories default to 0. Receivers choose which mismatch directions+ * to reject; live catalog rows require equality even for unversioned peers.* Future PRs that introduce a layout change for `series`, `issues`, etc.* add an entry here.*/@@ -54,15 +54,6 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// attachments-unaware `sanitizeObject` can't silently strip the field and// LWW the loss back onto the newer peer.//- // NOTE — `catalog` is intentionally NOT bumped for this field (matches the- // #1287 relationshipLinks precedent). A bible object promoted to the catalog- // carries `attachments` in `catalog_ingredients.payload`; an older peer's- // `updateIngredient` → `sanitizeObject` would drop it on a local edit and a- // catalog sync back could clobber the newer copy. We accept that graceful- // degradation rather than gate `catalog` — bumping it would pause ALL catalog- // sync with version-mismatched peers for one additive field, the heavier- // tradeoff this project has chosen against for additive bible fields. The- // `universes` gate above already protects the canonical (embedded) copy.// v8 adds shared styleReferences[]. Older peers must not sanitize the field// away and LWW-sync that loss back to a newer install.// v9 = `moodBoardId` added (#4188) — the universe's linked mood board. The@@ -312,10 +303,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// payload that would silently miss tombstones.//// Per-category gate so a new peer can sync its catalog independently of- // whether other categories are version-locked. Older peers are- // sender-behind on `catalog` (not ahead), so the receiver still accepts- // their pushes; newer peers pushing to older receivers are sender-ahead- // and get 409. `cat-ingredient` and `cat-scrap` record kinds map back+ // whether other categories are version-locked. Since v10, live catalog+ // rows require an exact version match; tombstones stay version-independent.+ // `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@@ -378,7 +368,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// and related fields). The metadata field is additive and optional on the// wire; a v9 sender must not push it to a ≤v8 receiver that would silently// drop it. A v9 receiver still accepts ≤v8 media rows without metadata.- catalog: 9,+ // v10 = protect structured object `payload.attachments[]` from older+ // sanitizers. Live catalog transfers now require equal versions in BOTH+ // directions, including legacy senders with no version. Whole-row LWW from+ // an older peer can erase fields after an unrelated edit. Tombstone-only+ // transfers remain version-independent; no local storage migration is needed.+ catalog: 10,// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are// local-only by default and excluded from sync; only `sync: true` sessions// ride the `storyBuilder` snapshot category. This is a brand-NEW synced@@ -937,10 +932,9 @@ export async function buildPortosMeta(overrides = {}) {** compatible — `true` only when neither list has entries.*- * Absent or zero entries on either side are treated as "no contract" — the- * comparator skips them. So legacy peers that don't send `portosMeta` at- * all simply pass through (treat their schemaVersions as `{}` → no- * `ahead` entries → compatible).+ * Absent or invalid entries are compared as zero. A legacy sender without+ * `portosMeta` is behind every versioned receiver category; callers decide+ * whether those behind gaps block the transfer.*/export function compareSchemaVersions(senderVersions = {}, receiverVersions = PORTOS_SCHEMA_VERSIONS) {const sender = senderVersions && typeof senderVersions === 'object' ? senderVersions : {};@@ -965,6 +959,16 @@ export function compareSchemaVersions(senderVersions = {}, receiverVersions = POreturn { ahead, behind, compatible: ahead.length === 0 && behind.length === 0 };}+/** Catalog row blocks share `deleted`, except user types use `deletedAt`.+ * Unknown blocks and malformed rows conservatively count as live so a future+ * payload cannot bypass the version gate. Envelope metadata is not a row block.+ */+export function catalogEnvelopeHasLiveRows(envelope) {+ return Object.entries(envelope).some(([kind, block]) => Array.isArray(block) && block.some(+ (row) => kind === 'catalogTypes' ? !row?.deletedAt : row?.deleted !== true,+ ));+}+/*** Restrict a comparator result to the categories actually being transferred.*diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 0e018383d1..ba49500bb2 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -44,8 +44,8 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(1);});- it('version-gates catalog media generation provenance', () => {- expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(9);+ it('version-gates catalog object attachments and media generation provenance', () => {+ expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(10);});it('version-gates the persisted FableLoom shot and reference shape', () => {diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex ad36a793a0..86ce7978e3 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -46,7 +46,7 @@ import {upsertMediaFromPeer,normalizeTags,} from './catalogDB.js';-import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';+import { compareSchemaVersions, scopeVersionDiff, formatVersionGap, catalogEnvelopeHasLiveRows, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';import { friendlifyUniverseTags, LEGACY_UNIVERSE_MARKER_TAG } from '../lib/catalogUniverseTags.js';import { canonicalTagKey, setUserCatalogTypes, INGREDIENT_TYPE_IDS } from '../lib/catalogTypes.js';import { readUserTypes as readUserTypeSlice, writeUserTypes } from './catalogUserTypes/store.js';@@ -131,8 +131,9 @@ export async function getChangesSince(since = '0', limit = 100) {export class CatalogSyncVersionMismatchError extends Error {constructor(diff) {- super(`catalog sync rejected: sender ahead on ${diff.ahead.map((g) => `${g.category} (v${g.senderV} vs v${g.receiverV})`).join(', ')}`);+ super(`catalog sync rejected: ${formatVersionGap(diff)}`);this.name = 'CatalogSyncVersionMismatchError';+ // Keep the established wire code so existing callers recognize the gap.this.code = 'CATALOG_SCHEMA_VERSION_AHEAD';this.status = 412;this.diff = diff;@@ -140,14 +141,13 @@ export class CatalogSyncVersionMismatchError extends Error {}export async function applyRemoteChanges(envelope = {}) {- // Schema-version gate: a peer running a newer `catalog` schema would push- // forward-shaped data this install can't safely interpret. Match the- // memorySync pattern — reject ahead-mismatches with a 412.+ // Whole-row LWW from an older sanitizer can erase new payload fields. Live+ // catalog rows require equal versions; tombstones and empty pages are safe+ // at any version. Scan all row blocks, including future envelope kinds.const senderVersions = envelope?.portosMeta?.schemaVersions || {};- const diff = compareSchemaVersions(senderVersions, PORTOS_SCHEMA_VERSIONS);- const aheadOnCatalog = diff.ahead.filter((g) => g.category === 'catalog');- if (aheadOnCatalog.length > 0) {- throw new CatalogSyncVersionMismatchError({ ahead: aheadOnCatalog, behind: [] });+ const diff = scopeVersionDiff(compareSchemaVersions(senderVersions, PORTOS_SCHEMA_VERSIONS), ['catalog']);+ if (catalogEnvelopeHasLiveRows(envelope) && !diff.compatible) {+ throw new CatalogSyncVersionMismatchError(diff);}const stats = {diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.jsindex 61fc949932..1231dfc3af 100644--- a/server/services/catalogSync.test.js+++ b/server/services/catalogSync.test.js@@ -52,7 +52,6 @@ const {applyRemoteChanges,getChangesSince,countAppliedFromStats,- CatalogSyncVersionMismatchError,} = await import('./catalogSync.js');const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');@@ -72,6 +71,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertMediaFromPeer.mockResolvedValueOnce(undefined);const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },scraps: [{ id: 's1', rawText: 'x', createdAt: 't', updatedAt: 't' }],ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' },@@ -104,6 +104,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertTagFromPeer.mockRejectedValueOnce(new Error('bad tag'));const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },tags: [{ id: 'cat-tag-noir', label: 'Noir', createdAt: 't', updatedAt: 't2' },{ id: 'cat-tag-pulp', label: 'Pulp', createdAt: 't', updatedAt: 't' },@@ -120,6 +121,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {it('isolates a failing relation row and records it', async () => {catalogDB.upsertRelationFromPeer.mockRejectedValueOnce(new Error('fk violation'));const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },relations: [{ fromId: 'i1', toId: 'gone', kind: 'references', createdAt: 't' }],});expect(stats.relations.failed).toBe(1);@@ -131,6 +133,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {catalogDB.upsertScrapFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },scraps: [{ id: 'bad', rawText: 'x', createdAt: 't', updatedAt: 't' },{ id: 'good', rawText: 'y', createdAt: 't', updatedAt: 't' },@@ -168,6 +171,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {});await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },relations: [{ fromId: 'i1', toId: 'i2', kind: 'lives-in', createdAt: 't' }],refs: [{ ingredientId: 'i1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: 't' }],sources: [{ ingredientId: 'i1', scrapId: 's1', extractedAt: 't' }],@@ -190,6 +194,7 @@ describe('applyRemoteChanges — dispatch + stats', () => {});await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },// Intentionally CHILD-first in the envelope — the apply path must reorder// so the parent (parentScrapId null) is upserted before its children.scraps: [@@ -205,42 +210,42 @@ describe('applyRemoteChanges — dispatch + stats', () => {});describe('applyRemoteChanges — schema-version gate', () => {- it('rejects envelopes whose sender is ahead on `catalog` with a 412', async () => {- const tooNew = PORTOS_SCHEMA_VERSIONS.catalog + 1;+ it.each([+ ['ahead', PORTOS_SCHEMA_VERSIONS.catalog + 1],+ ['behind', PORTOS_SCHEMA_VERSIONS.catalog - 1],+ ['unversioned', undefined],+ ])('rejects %s live catalog rows before replacing stored attachments', async (_direction, catalog) => {+ const stored = { payload: { attachments: [{ characterId: 'example-character', emotion: 'love' }] } };+ const before = structuredClone(stored);+ catalogDB.upsertIngredientFromPeer.mockImplementation(async (incoming) => {+ Object.assign(stored, incoming);+ return { applied: true, isInsert: false };+ });+ const gap = { category: 'catalog', senderV: catalog ?? 0, receiverV: PORTOS_SCHEMA_VERSIONS.catalog };+ const ahead = catalog > PORTOS_SCHEMA_VERSIONS.catalog;await expect(applyRemoteChanges({- portosMeta: { schemaVersions: { catalog: tooNew } },- ingredients: [],- })).rejects.toBeInstanceOf(CatalogSyncVersionMismatchError);-- // The thrown error carries the HTTP status + a structured diff.- try {- await applyRemoteChanges({- portosMeta: { schemaVersions: { catalog: tooNew } },- ingredients: [],- });- } catch (err) {- expect(err.status).toBe(412);- expect(err.code).toBe('CATALOG_SCHEMA_VERSION_AHEAD');- expect(err.diff.ahead[0].category).toBe('catalog');- }- });-- it('accepts envelopes from a sender behind on `catalog`', async () => {- catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: true });- const stats = await applyRemoteChanges({- portosMeta: { schemaVersions: { catalog: 1 } },- ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],+ portosMeta: catalog === undefined ? undefined : { schemaVersions: { catalog } },+ ingredients: [{ id: 'example-object', type: 'object', payload: { name: 'Edited on peer' }, updatedAt: '2026-09-24T12:00:00Z' }],+ })).rejects.toMatchObject({+ name: 'CatalogSyncVersionMismatchError', status: 412, code: 'CATALOG_SCHEMA_VERSION_AHEAD',+ diff: { ahead: ahead ? [gap] : [], behind: ahead ? [] : [gap] },});- expect(stats.ingredients.inserted).toBe(1);+ expect(catalogDB.upsertIngredientFromPeer).not.toHaveBeenCalled();+ expect(stored).toEqual(before);});- it('accepts envelopes with no portosMeta (legacy/forked peers)', async () => {- catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: true });- const stats = await applyRemoteChanges({- ingredients: [{ id: 'i1', type: 'character', name: 'A', createdAt: 't', updatedAt: 't' }],- });- expect(stats.ingredients.inserted).toBe(1);- });+ it.each([PORTOS_SCHEMA_VERSIONS.catalog + 1, PORTOS_SCHEMA_VERSIONS.catalog - 1, undefined])(+ 'accepts tombstone-only catalog envelopes at version %s', async (catalog) => {+ catalogDB.upsertIngredientFromPeer.mockResolvedValue({ applied: true, isInsert: false });+ const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: { catalog } },+ ingredients: [{ id: 'example-object', deleted: true, deletedAt: '2026-09-24T12:00:00Z' }],+ refs: [{ ingredientId: 'example-object', refKind: 'universe', refId: 'example-universe', deleted: true }],+ });+ expect(stats.ingredients.updated).toBe(1);+ expect(stats.refs.applied).toBe(1);+ },+ );});describe('getChangesSince — cursor normalization + per-kind advance', () => {@@ -400,6 +405,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],});@@ -417,7 +423,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);const row = ingredient(['hero', 'from-universe', 'universe:u-1']);- await applyRemoteChanges({ ingredients: [row] });+ await applyRemoteChanges({ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS }, ingredients: [row] });expect(row.tags).toEqual(['hero', 'from-universe', 'universe:u-1']);expect(tagsUpserted()).toEqual(['hero', 'My Universe']);@@ -428,6 +434,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([]); // u-2 not present locallyawait applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-2'])],});@@ -443,6 +450,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1', 'universe:u-2'])],});@@ -456,6 +464,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'catalogDB.upsertIngredientFromPeer.mockResolvedValueOnce({ applied: true, isInsert: true });await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'universe:marvel'])], // thematic user tag, no marker});@@ -469,6 +478,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],});@@ -484,6 +494,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [{ ...ingredient(['from-universe', 'universe:u-1']), id: 'i-1' },{ ...ingredient(['from-universe', 'universe:u-1']), id: 'i-2' },@@ -501,6 +512,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockResolvedValueOnce([{ id: 'u-1', name: 'My Universe' }]);await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [{ ...ingredient(['hero', 'from-universe', 'universe:u-1']), id: 'i-1' },{ ...ingredient(['hero', 'from-universe', 'universe:u-1']), id: 'i-2' },@@ -520,6 +532,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'catalogDB.normalizeTags.mockResolvedValueOnce(['My Universe']); // pre-existing row's casing winsawait applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],});@@ -532,6 +545,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'// The minted name collides with an inbound tag → nothing new to register.await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],});@@ -543,6 +557,7 @@ describe('applyRemoteChanges — legacy universe tag friendlify on inbound sync'universeBuilder.listUniverses.mockRejectedValueOnce(new Error('universe read failed'));const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: PORTOS_SCHEMA_VERSIONS },ingredients: [ingredient(['hero', 'from-universe', 'universe:u-1'])],});diff --git a/server/services/catalogSync.userTypes.test.js b/server/services/catalogSync.userTypes.test.jsindex 0fdab44115..5f530ca935 100644--- a/server/services/catalogSync.userTypes.test.js+++ b/server/services/catalogSync.userTypes.test.js@@ -129,6 +129,19 @@ describe('applyRemoteChanges — catalogTypes LWW merge', () => {expect(getActiveCatalogType('faction')?.label).toBe('Reborn');});+ it.each([PORTOS_SCHEMA_VERSIONS.catalog - 1, PORTOS_SCHEMA_VERSIONS.catalog + 1, undefined])(+ 'accepts user-type tombstones without a deleted boolean at version %s', async (catalog) => {+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'x', fields: [], updatedAt: '2026-01-01' }] };+ const stats = await applyRemoteChanges({+ portosMeta: { schemaVersions: { catalog } },+ catalogTypes: [{ id: 'faction', updatedAt: '2026-01-01', deletedAt: '2026-02-01' }],+ });+ expect(stats.catalogTypes.applied).toBe(1);+ expect(store.catalogUserTypes[0].deletedAt).toBe('2026-02-01');+ expect(getActiveCatalogType('faction')).toBeUndefined();+ },+ );+it('rejects with 412 when the sender is ahead on the catalog schema', async () => {await expect(applyRemoteChanges({portosMeta: { schemaVersions: { catalog: PORTOS_SCHEMA_VERSIONS.catalog + 1 } },diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 8c838c4019..557a748c74 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -3714,6 +3714,24 @@ describe('peerSync', () => {expect(applyCatalogRemoteChanges).not.toHaveBeenCalled();});+ it.each([PORTOS_SCHEMA_VERSIONS.catalog - 1, undefined])(+ 'rejects catalog version %s before merging the owning universe or its bundle', async (catalog) => {+ vi.mocked(getBackendName).mockReturnValue('postgres');+ vi.mocked(mergeUniversesFromSync).mockClear();+ const schemaVersions = { ...PORTOS_SCHEMA_VERSIONS, catalog };+ await expect(applyIncomingPush({+ kind: 'universe', record: liveUniverse, assetManifest: [], sourceInstanceId: 'peer-a',+ catalogBundle: { ingredients: [{ id: 'example-object', type: 'object', payload: { name: 'Edited on peer' } }] },+ portosMeta: { schemaVersions },+ })).rejects.toMatchObject({+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ details: { ahead: [], behind: [{ category: 'catalog', senderV: catalog ?? 0, receiverV: PORTOS_SCHEMA_VERSIONS.catalog }] },+ });+ expect(mergeUniversesFromSync).not.toHaveBeenCalled();+ expect(applyCatalogRemoteChanges).not.toHaveBeenCalled();+ },+ );+// #3926: the gate used to key on `ingredients` alone, so any bundle whose// live rows sat in another block (`refs` today; `relations`/`tags`/`media`/// `catalogTypes` from catalog v4–v8) slipped past it and got applied on a@@ -3758,7 +3776,7 @@ describe('peerSync', () => {expect(applyCatalogRemoteChanges).toHaveBeenCalledTimes(1);});- it('receiver does NOT gate a tombstone-only bundle from a schema-ahead sender', async () => {+ it.each([PORTOS_SCHEMA_VERSIONS.catalog + 1, PORTOS_SCHEMA_VERSIONS.catalog - 1, undefined])('receiver does NOT gate a tombstone-only bundle at catalog version %s', async (catalog) => {// Tombstone rows are id+deleted+deletedAt+updatedAt at every catalog// version, so they stay exempt — otherwise federated catalog deletes// would stall the moment one peer upgrades ahead.@@ -3772,7 +3790,7 @@ describe('peerSync', () => {relations: [{ id: 'cat-rel-1', deleted: true, deletedAt: '2026-03-01T00:00:00Z', updatedAt: '2026-03-01T00:00:00Z' }],},sourceInstanceId: 'peer-a',- portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS, catalog: PORTOS_SCHEMA_VERSIONS.catalog + 1 }, portosVersion: '99.0.0' },+ portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS, catalog }, portosVersion: '99.0.0' },});expect(applyCatalogRemoteChanges).toHaveBeenCalledTimes(1);});diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex 55e3a83b1e..11e7a01d5e 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -15,6 +15,7 @@ import {PORTOS_SCHEMA_VERSIONS,RECORD_KIND_SCHEMA_CATEGORIES,compareSchemaVersions,+ catalogEnvelopeHasLiveRows,scopeVersionDiff,formatVersionGap,getPortosVersion,@@ -65,37 +66,19 @@ async function applyCatalogBundle(catalogBundle, portosMeta) {});}-/**- * True when a catalog bundle carries at least one LIVE (non-tombstone) row in- * any of its blocks. Every block of the catalog sync envelope is an array of- * rows (`ingredients`, `refs`, `relations`, `tags`, `media`, `catalogTypes`,- * …), so we scan array-valued keys generically instead of enumerating them —- * a block added by a catalog schema version NEWER than this receiver still- * counts, which is exactly the case the version gate exists to catch. A row- * that isn't a plain object counts as live (conservative: gate rather than- * wave through something we can't classify).- */-function catalogBundleHasLiveRow(catalogBundle) {- return Object.values(catalogBundle).some(- (block) => Array.isArray(block) && block.some((row) => row?.deleted !== true),- );-}-/*** SCHEMA-VERSION GATE — runs BEFORE any merge so a sender on a newer storage- * layout can't corrupt local state. Legacy senders without `portosMeta` pass- * through (comparator treats absent as zero/no-contract; their record went- * through the same v0 → vN sanitizer chain we already run). When the sender+ * layout can't corrupt local state. Outside catalog, legacy senders without+ * `portosMeta` pass through (absent versions compare as zero, and their records+ * use the existing sanitizer backfill chain). When the sender* is AHEAD on any category, throws a structured error the route layer maps* to HTTP 409 + body so the sender can persist the gap on the subscription* and surface it in the UI. Returns `{ senderSchemaVersions }` on success —* the caller threads it into every merge call.*- * We do NOT reject on "sender behind" here — the sanitizer's existing- * backfill chain handles older inputs in-place. A future forward-only- * contract (e.g. a required field that the sanitizer can't synthesize) can- * opt into a behind-gate; the comparator already surfaces both directions- * for that purpose.+ * Live catalog rows also reject sender-behind (including absent versions):+ * their whole-row LWW payload can erase fields an older sanitizer dropped.+ * Other categories retain their existing sanitizer backfill behavior.** Extracted out of `applyIncomingPush`'s own body (#6843) — a self-contained* validate-or-throw step with one clear output, and one of the two chunks@@ -153,7 +136,7 @@ async function assertSchemaVersionGate({ kind, record, issues, linkedCollection,// name by definition. Tombstone-only bundles (every row deleted) are// id+deleted+deletedAt+updatedAt — safe at every version, so they needn't// gate (same reasoning as the tombstone-record exemption above).- if (record.deleted !== true && isPlainObject(catalogBundle) && catalogBundleHasLiveRow(catalogBundle)) {+ if (record.deleted !== true && isPlainObject(catalogBundle) && catalogEnvelopeHasLiveRows(catalogBundle)) {for (const c of (RECORD_KIND_SCHEMA_CATEGORIES['cat-ingredient'] || ['catalog'])) relevantCategories.add(c);}// A bundled linked track (#1858) ships a live, full-shape `track` record. Gate@@ -167,7 +150,8 @@ async function assertSchemaVersionGate({ kind, record, issues, linkedCollection,}const fullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);const versionDiff = scopeVersionDiff(fullDiff, [...relevantCategories]);- if (versionDiff.ahead.length > 0) {+ const catalogBehind = versionDiff.behind.some((gap) => gap.category === 'catalog');+ if (versionDiff.ahead.length > 0 || catalogBehind) {console.warn(`⚠️ peerSync: rejecting push from ${sourceInstanceId} — ${formatVersionGap(versionDiff)} (sender PortOS ${senderPortosVersion || 'unknown'})`,);@@ -177,7 +161,7 @@ async function assertSchemaVersionGate({ kind, record, issues, linkedCollection,// back to its own version, which is misleading.const receiverPortosVersion = await getPortosVersion().catch(() => null);throw makeErr(- `sender's schema is ahead — receiver cannot apply (${formatVersionGap(versionDiff)})`,+ `sender's schema is ${versionDiff.ahead.length ? 'ahead' : 'behind'} — receiver cannot apply (${formatVersionGap(versionDiff)})`,ERR_SCHEMA_VERSION_AHEAD,{ahead: versionDiff.ahead,diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 8188175909..b17aefb64a 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -321,7 +321,7 @@ function catalogSinceQuery(catalogSeqs) {* — but the catalog is a multi-table relational store, so the cursor is the* per-kind `maxSequences` object the peer returns, not a single scalar.*- * A schema-version-ahead peer (newer `catalog` schema) makes applyRemoteChanges+ * A schema-version-mismatched peer (older or newer `catalog` schema) makes applyRemoteChanges* throw CatalogSyncVersionMismatchError; we record the gap on the peer record* (same surfacing as the snapshot categories) and stop draining so we don't* loop on a payload we can't safely apply.@@ -369,7 +369,7 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {firstFetch = false;// Forward the sender's portosMeta so applyRemoteChanges runs the schema- // gate BEFORE merging — a sender ahead on `catalog` throws and we persist+ // gate BEFORE merging — a sender mismatched on `catalog` throws and we persist// the gap rather than corrupting local state.let stats;try {@@ -378,8 +378,9 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {if (err?.code === 'CATALOG_SCHEMA_VERSION_AHEAD') {blockedBySchema = err.diff;const ahead = Array.isArray(err.diff?.ahead) ? err.diff.ahead : [];+ const behind = Array.isArray(err.diff?.behind) ? err.diff.behind : [];await recordPeerSchemaGap(peerId, 'catalog', {- ahead, behind: [], senderPortosVersion: data?.portosMeta?.portosVersion ?? null,+ ahead, behind, senderPortosVersion: data?.portosMeta?.portosVersion ?? null,}).catch((e) => logFailureWithStack('⚠️ syncOrchestrator: persist catalog schema gap failed', e));break;}diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.jsindex cba9b0b449..e77d970a20 100644--- a/server/services/syncOrchestrator.test.js+++ b/server/services/syncOrchestrator.test.js@@ -639,7 +639,7 @@ describe('syncOrchestrator', () => {expect(updatePeer).toHaveBeenCalledWith('local-peer-row', { schemaGaps: null });});- it('records a schema gap and stops draining when the sender is ahead on catalog', async () => {+ it.each(['ahead', 'behind'])('records a %s catalog gap without advancing cursors, then retries', async (direction) => {mockFetch.mockResolvedValue({ok: true,json: async () => ({@@ -651,7 +651,8 @@ describe('syncOrchestrator', () => {});const mismatch = new Error('catalog ahead');mismatch.code = 'CATALOG_SCHEMA_VERSION_AHEAD';- mismatch.diff = { ahead: [{ category: 'catalog', senderV: 99, receiverV: 1 }], behind: [] };+ const gap = { category: 'catalog', senderV: direction === 'ahead' ? 99 : 0, receiverV: 10 };+ mismatch.diff = { ahead: [], behind: [], [direction]: [gap] };applyCatalogChanges.mockRejectedValueOnce(mismatch);const { updatePeer } = await import('./instances.js');@@ -662,17 +663,26 @@ describe('syncOrchestrator', () => {// Only one apply attempt — we stop draining on the block (no hasMore loop).expect(applyCatalogChanges).toHaveBeenCalledTimes(1);expect(result.catalog.blockedBySchema).toBeTruthy();+ expect(result.catalog.catalogSeqs.ingredients).toBeUndefined();// Gap persisted on the local peer row under schemaGaps.catalog.expect(updatePeer).toHaveBeenCalledWith('local-peer-row',expect.objectContaining({schemaGaps: expect.objectContaining({catalog: expect.objectContaining({- ahead: [{ category: 'catalog', senderV: 99, receiverV: 1 }],+ [direction]: [gap],}),}),}),);+ // The next cycle retries the same rows after peers upgrade.+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({+ ingredients: [{ id: 'x' }], maxSequences: { ingredients: '5' }, hasMore: false,+ }) });+ applyCatalogChanges.mockResolvedValueOnce({ ingredients: { inserted: 1 } });+ const retry = await syncWithPeer(catalogPeer);+ expect(mockFetch.mock.calls.at(-1)[0]).toContain('since[ingredients]=0');+ expect(retry.catalog.catalogSeqs.ingredients).toBe('5');});});