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
feat([peer-sync-per-category-version-gate]): scope the cross-install schema gate to the transferred category
Adam Eivy5e2bb3154689
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex d1ff49e862..19e1f675ba 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -45,9 +45,33 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// id with LWW-on-createdAt; the merge already tolerates unknown/extra rows,// so it does not need whole-payload gating. An older peer that lacks the// `videoHistory` route simply rejects that one category request and keeps- // syncing everything else. (Generalizing the gate to be per-category —- // which would also fix the same latent issue for mediaCollections — is a- // separate follow-up tracked in PLAN.md.)+ // syncing everything else.+ //+ // The gate is now PER-CATEGORY (see `scopeVersionDiff` below + its three+ // call sites: dataSync `applyRemote`, peerSync push, sharing importer), so+ // adding a new key here or bumping one category only gates transfers of+ // THAT category — unrelated categories keep flowing. videoHistory stays+ // unlisted because it has no versioned storage layout at all, not because+ // of the old whole-payload footgun.+});++/**+ * Map a federated record KIND (the unit a peer push or share manifest moves)+ * to the `PORTOS_SCHEMA_VERSIONS` categories its storage layout touches. The+ * per-category gate uses this to block a transfer ONLY when the sender is+ * ahead on a category that record actually writes.+ *+ * Kinds absent from this map carry no versioned storage layout and are never+ * gated — media-job records (flat re-render metadata), media-annotations,+ * goals/character/digitalTwin/meatspace, videoHistory, etc. A `series` push+ * that bundles issues, or a universe/series push that bundles a linked media+ * collection, unions the additional kinds' categories at the call site.+ */+export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({+ universe: Object.freeze(['universes']),+ series: Object.freeze(['pipelineSeries']),+ issue: Object.freeze(['pipelineIssues']),+ mediaCollection: Object.freeze(['mediaCollections']),});/**@@ -134,6 +158,31 @@ export function compareSchemaVersions(senderVersions = {}, receiverVersions = POreturn { ahead, behind, compatible: ahead.length === 0 && behind.length === 0 };}+/**+ * Restrict a comparator result to the categories actually being transferred.+ *+ * `compareSchemaVersions` walks the UNION of every known category so the full+ * diff stays useful for diagnostics/UI. But the GATE decision must be+ * per-category: a sender that bumped (or added) one category should only be+ * blocked for transfers of THAT category — not for unrelated categories that+ * happen to ride a federation upgrading on independent schedules. Pass the+ * schema-version keys this transfer actually moves; categories outside the+ * set are dropped from `ahead`/`behind` so they can't block (and the scoped+ * `ahead` is what callers report, so a "pipeline" snapshot rejection never+ * mis-attributes a `universes` gap).+ *+ * `categories` non-array (null/undefined) → returns the diff unchanged+ * (whole-payload gate; the comparator's union result is used as-is). An empty+ * array → nothing can block (the transfer touches no versioned category).+ */+export function scopeVersionDiff(diff = {}, categories) {+ if (!Array.isArray(categories)) return diff;+ const allow = new Set(categories);+ const ahead = (Array.isArray(diff.ahead) ? diff.ahead : []).filter((g) => allow.has(g.category));+ const behind = (Array.isArray(diff.behind) ? diff.behind : []).filter((g) => allow.has(g.category));+ return { ahead, behind, compatible: ahead.length === 0 && behind.length === 0 };+}+/*** Human-readable explanation of a comparator result. Used both for log lines* and for the UI badge tooltip. Keeps the wording in one place so a peer-diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 95399ecbdc..fd9d3bc49f 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -1,7 +1,9 @@import { describe, it, expect } from 'vitest';import {PORTOS_SCHEMA_VERSIONS,+ RECORD_KIND_SCHEMA_CATEGORIES,compareSchemaVersions,+ scopeVersionDiff,formatVersionGap,buildPortosMeta,} from './schemaVersions.js';@@ -120,6 +122,83 @@ describe('compareSchemaVersions', () => {});});+describe('RECORD_KIND_SCHEMA_CATEGORIES', () => {+ it('maps each federated record kind to its versioned storage categories', () => {+ expect(RECORD_KIND_SCHEMA_CATEGORIES.universe).toEqual(['universes']);+ expect(RECORD_KIND_SCHEMA_CATEGORIES.series).toEqual(['pipelineSeries']);+ expect(RECORD_KIND_SCHEMA_CATEGORIES.issue).toEqual(['pipelineIssues']);+ expect(RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection).toEqual(['mediaCollections']);+ });++ it('only references keys that exist in PORTOS_SCHEMA_VERSIONS', () => {+ for (const keys of Object.values(RECORD_KIND_SCHEMA_CATEGORIES)) {+ for (const k of keys) {+ expect(PORTOS_SCHEMA_VERSIONS[k]).toBeDefined();+ }+ }+ });++ it('is frozen so a kind→category mapping change is deliberate', () => {+ expect(Object.isFrozen(RECORD_KIND_SCHEMA_CATEGORIES)).toBe(true);+ });+});++describe('scopeVersionDiff', () => {+ const diff = {+ ahead: [+ { category: 'universes', senderV: 6, receiverV: 5 },+ { category: 'mediaCollections', senderV: 2, receiverV: 1 },+ ],+ behind: [{ category: 'pipelineSeries', senderV: 1, receiverV: 2 }],+ compatible: false,+ };++ it('keeps only ahead/behind entries within the allowed categories', () => {+ const scoped = scopeVersionDiff(diff, ['universes']);+ expect(scoped.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);+ expect(scoped.behind).toEqual([]);+ expect(scoped.compatible).toBe(false);+ });++ it('drops an unrelated ahead category so it no longer blocks', () => {+ // The crux of the per-category gate: a transfer that only touches+ // `pipelineSeries` is NOT blocked by a sender that bumped `mediaCollections`.+ const scoped = scopeVersionDiff(diff, ['pipelineSeries']);+ expect(scoped.ahead).toEqual([]); // mediaCollections + universes filtered out+ expect(scoped.behind).toEqual([{ category: 'pipelineSeries', senderV: 1, receiverV: 2 }]);+ expect(scoped.compatible).toBe(false);+ });++ it('an empty allow-list makes the scoped diff compatible (no versioned category touched)', () => {+ const scoped = scopeVersionDiff(diff, []);+ expect(scoped.ahead).toEqual([]);+ expect(scoped.behind).toEqual([]);+ expect(scoped.compatible).toBe(true);+ });++ it('a non-array categories arg returns the diff unchanged (whole-payload gate)', () => {+ expect(scopeVersionDiff(diff, null)).toBe(diff);+ expect(scopeVersionDiff(diff, undefined)).toBe(diff);+ });++ it('tolerates a malformed diff (missing ahead/behind arrays)', () => {+ const scoped = scopeVersionDiff({}, ['universes']);+ expect(scoped).toEqual({ ahead: [], behind: [], compatible: true });+ });++ it('composes with compareSchemaVersions for a realistic cross-key scenario', () => {+ // Sender is ahead on mediaCollections only; a universe transfer scopes to+ // ['universes'] and stays compatible even though the union diff is not.+ const union = compareSchemaVersions(+ { universes: 5, pipelineSeries: 1, pipelineIssues: 1, mediaCollections: 2 },+ PORTOS_SCHEMA_VERSIONS,+ );+ expect(union.compatible).toBe(false); // mediaCollections 2 > 1+ expect(scopeVersionDiff(union, RECORD_KIND_SCHEMA_CATEGORIES.universe).compatible).toBe(true);+ expect(scopeVersionDiff(union, RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection).compatible).toBe(false);+ });+});+describe('formatVersionGap', () => {it('describes a single ahead gap', () => {expect(formatVersionGap({ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] }))diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex c8f883ffdf..050ae3cdba 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -13,8 +13,10 @@ import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import {PORTOS_SCHEMA_VERSIONS,+ RECORD_KIND_SCHEMA_CATEGORIES,buildPortosMeta,compareSchemaVersions,+ scopeVersionDiff,formatVersionGap,} from '../lib/schemaVersions.js';import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';@@ -719,6 +721,19 @@ const CATEGORIES = {videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote }};+// Map a snapshot CATEGORY to the `PORTOS_SCHEMA_VERSIONS` keys whose storage+// layout that category's `applyRemote` actually writes — derived from the+// canonical record-kind map so it can't drift. `applyRemote` gates only on+// these keys, so a sender that bumped/added an unrelated category (e.g. a new+// `mediaCollections` version) no longer rejects an unrelated category's+// snapshot. Categories absent here (goals/character/digitalTwin/meatspace/+// videoHistory) have no versioned layout → no gate.+const SNAPSHOT_CATEGORY_SCHEMA_KEYS = {+ universe: RECORD_KIND_SCHEMA_CATEGORIES.universe,+ pipeline: [...RECORD_KIND_SCHEMA_CATEGORIES.series, ...RECORD_KIND_SCHEMA_CATEGORIES.issue],+ mediaCollections: RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection,+};+// Per-`(category, forPeerId)` `{ fingerprints, checksum }` cache. The// orchestrator hits getChecksum every cycle — by far the hottest sync-side I/O —// so caching keyed on underlying-file `(mtime, size)` lets it stat-and-return@@ -904,7 +919,11 @@ export async function applyRemote(category, remoteData, options = {}) {const portosMeta = isPlainObject(options.portosMeta) ? options.portosMeta : null;const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;- const versionDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ // Full union diff for diagnostics; gate (and report) only on the schema+ // categories THIS snapshot category actually writes, so an ahead-mismatch on+ // an unrelated category can't reject this category's snapshot.+ const fullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ const versionDiff = scopeVersionDiff(fullDiff, SNAPSHOT_CATEGORY_SCHEMA_KEYS[category] || []);if (versionDiff.ahead.length > 0) {console.warn(`⚠️ dataSync: rejecting "${category}" snapshot — ${formatVersionGap(versionDiff)} ` +diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 0a2558772d..0c146e5cfc 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -818,3 +818,76 @@ describe('dataSync — videoHistory category', () => {expect(after.checksum).not.toBe(before.checksum);});});++describe('dataSync — per-category schema gate (cross-key isolation)', () => {+ // A sender always stamps its FULL schemaVersions map (buildPortosMeta spreads+ // PORTOS_SCHEMA_VERSIONS). The old whole-payload gate rejected EVERY category+ // when the sender was ahead on ANY one of them. These tests pin the new+ // per-category behavior: an ahead-mismatch only gates the category whose+ // storage layout that snapshot actually writes.+ const aheadOnUniverses = {+ portosVersion: '99.0.0',+ schemaVersions: { universes: 6, pipelineSeries: 1, pipelineIssues: 1, mediaCollections: 1 },+ };++ it('does NOT block a videoHistory snapshot when the sender is ahead on universes', async () => {+ // videoHistory has no versioned storage layout, so it must keep syncing+ // even from a sender on a newer universes layout. This is the exact latent+ // bug the per-category gate fixes (the old union gate rejected it).+ writeJSON(VIDEO_HISTORY_PATH, []);+ const result = await dataSync.applyRemote('videoHistory', {+ videos: [{ id: 'v1', prompt: 'p', filename: 'v1.mp4', createdAt: '2026-05-22T00:00:00Z' }],+ }, { portosMeta: aheadOnUniverses });+ expect(result.blockedBySchema).toBeUndefined();+ expect(result.applied).toBe(true);+ });++ it('does NOT block a pipeline snapshot when the sender is ahead on universes', async () => {+ writeSeriesState([]);+ writeIssueState([]);+ const result = await dataSync.applyRemote('pipeline', {+ series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],+ issues: [],+ }, { portosMeta: aheadOnUniverses });+ expect(result.blockedBySchema).toBeUndefined();+ expect(result.applied).toBe(true);+ expect(readSeriesState().find((s) => s.id === 'ser-1')).toBeTruthy();+ });++ it('does NOT block a mediaCollections snapshot when the sender is ahead on universes', async () => {+ writeJSON(MEDIA_COLLECTIONS_PATH, { collections: [] });+ const result = await dataSync.applyRemote('mediaCollections', {+ collections: [{+ id: 'c-new', name: 'New', description: '', coverKey: null, universeId: null, seriesId: null,+ items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',+ }],+ }, { portosMeta: aheadOnUniverses });+ expect(result.blockedBySchema).toBeUndefined();+ expect(result.applied).toBe(true);+ });++ it('does NOT block a universe snapshot when the sender is ahead on mediaCollections only', async () => {+ writeUniverseState({ universes: [], runs: [] });+ const result = await dataSync.applyRemote('universe', {+ universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, mediaCollections: 2 } } });+ expect(result.blockedBySchema).toBeUndefined();+ expect(result.applied).toBe(true);+ });++ it('STILL blocks a pipeline snapshot when the sender is ahead on pipelineSeries (relevant category)', async () => {+ writeSeriesState([]);+ writeIssueState([]);+ const result = await dataSync.applyRemote('pipeline', {+ series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],+ issues: [],+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 2, pipelineIssues: 1, mediaCollections: 1 } } });+ expect(result.applied).toBe(false);+ expect(result.blockedBySchema).toBeDefined();+ // The reported gap is scoped to the relevant category — NOT mis-attributed.+ expect(result.blockedBySchema.ahead).toEqual([+ { category: 'pipelineSeries', senderV: 2, receiverV: 1 },+ ]);+ expect(readSeriesState()).toEqual([]); // nothing written+ });+});diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex f53a644a5b..8c45bd2185 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -30,7 +30,7 @@ import { isSafeRecordId } from '../../lib/validation.js';import { getBucket, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName, isHexHash } from './buckets.js';import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';-import { PORTOS_SCHEMA_VERSIONS, compareSchemaVersions, formatVersionGap } from '../../lib/schemaVersions.js';+import { PORTOS_SCHEMA_VERSIONS, RECORD_KIND_SCHEMA_CATEGORIES, compareSchemaVersions, scopeVersionDiff, formatVersionGap } from '../../lib/schemaVersions.js';import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';@@ -391,6 +391,36 @@ async function readReferencedRecords(bucketPath, manifest) {return { records, missing };}+/**+ * Which `PORTOS_SCHEMA_VERSIONS` categories does this manifest actually carry?+ * Used to scope the per-category schema gate so a sender ahead on an unrelated+ * category doesn't reject an import that never touches it. Derived from the+ * manifest's declared `recordIds` + `kind` + bundled `collection` — NOT from+ * reading the record files (the gate runs before any record read, and a+ * manifest delivered ahead of its records still declares what it carries).+ *+ * Id-prefix → kind mirrors `readReferencedRecords` above (`ser-`/`iss-`/+ * bible-prefixed); a UUID is a universe record EXCEPT on a `media` manifest,+ * where UUIDs are media-job records (flat re-render metadata, unversioned).+ * `media-annotations` manifests bypass the records pipeline entirely and carry+ * no versioned layout → never gated.+ */+function relevantSchemaCategoriesForManifest(manifest) {+ if (manifest?.kind === 'media-annotations') return [];+ const categories = new Set();+ const add = (keys) => { for (const k of keys) categories.add(k); };+ const ids = Array.isArray(manifest?.recordIds) ? manifest.recordIds : [];+ for (const id of ids) {+ if (typeof id !== 'string') continue;+ if (id.startsWith('ser-')) add(RECORD_KIND_SCHEMA_CATEGORIES.series);+ else if (id.startsWith('iss-')) add(RECORD_KIND_SCHEMA_CATEGORIES.issue);+ else if (id.startsWith('chr-') || id.startsWith('set-') || id.startsWith('obj-')) add(RECORD_KIND_SCHEMA_CATEGORIES.universe);+ else if (manifest?.kind !== 'media') add(RECORD_KIND_SCHEMA_CATEGORIES.universe);+ }+ if (isPlainObject(manifest?.collection)) add(RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection);+ return [...categories];+}+/*** Auto-merge mode: apply records into live state.*@@ -812,7 +842,11 @@ export async function processManifest(bucketId, manifestFilename) {const senderSchemaVersions = isPlainObject(manifest.portosSchemaVersions)? manifest.portosSchemaVersions: {};- const portosDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ // Scope the gate to the categories this manifest actually carries, so an+ // ahead-mismatch on a category the manifest doesn't touch can't refuse the+ // import. Full union diff stays available for diagnostics.+ const portosFullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ const portosDiff = scopeVersionDiff(portosFullDiff, relevantSchemaCategoriesForManifest(manifest));if (portosDiff.ahead.length > 0) {// Mark processed so subsequent chokidar fan-outs (every asset/record// file landing under the bucket triggers a backlog scan that re-walksdiff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 129f156295..bf2fcc719d 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -2039,16 +2039,16 @@ describe('sharing round-trip', () => {expect(manifest.portosSchemaVersions.universes).toBe(5);});- it('importer rejects a manifest whose portosSchemaVersions.universes is AHEAD of local', async () => {+ it('importer rejects a manifest when the sender is AHEAD on a category the manifest CARRIES', async () => {const bucket = await buckets.createBucket({ name: 'AheadBucket', path: tempBucket, mode: 'auto-merge' });const s = await series.createSeries({ name: 'Future', logline: 'x' });const exp = await exporter.exportSeries(s.id, bucket.id);- // Mutate the written manifest to stamp a future portos schema. This- // simulates a manifest exported by a NEWER PortOS instance landing in- // an OLDER instance's bucket.+ // Stamp a future schema for pipelineSeries — the category this series+ // manifest actually carries — simulating a manifest exported by a NEWER+ // PortOS instance landing in an OLDER instance's bucket.const manifestPath = join(tempBucket, 'manifests', exp.filename);const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));- manifest.portosSchemaVersions = { universes: 99 };+ manifest.portosSchemaVersions = { universes: 5, pipelineSeries: 99, pipelineIssues: 1, mediaCollections: 1 };manifest.producedByVersion = '99.0.0';writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));// Delete the local series so the auto-merge would normally re-create it.@@ -2057,12 +2057,33 @@ describe('sharing round-trip', () => {const result = await importer.processManifest(bucket.id, exp.filename);expect(result.skipped).toBe(true);expect(result.reason).toBe('portos-schema-ahead');- expect(result.ahead).toEqual([{ category: 'universes', senderV: 99, receiverV: 5 }]);+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 1 }]);expect(result.producedByVersion).toBe('99.0.0');// Series stayed tombstoned (or absent) — apply was refused.await expect(series.getSeries(s.id)).rejects.toThrow();});+ it('importer IMPORTS a manifest when the sender is ahead only on a category the manifest does NOT carry', async () => {+ // Per-category gate: a universeless series manifest carries only+ // pipelineSeries (+ pipelineIssues for bundled issues). A sender ahead on+ // `universes` must NOT block it — the old whole-payload gate did, severing+ // sync across a federation upgrading on independent schedules.+ const bucket = await buckets.createBucket({ name: 'UnrelatedBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Unaffected', logline: 'x' });+ const exp = await exporter.exportSeries(s.id, bucket.id);+ const manifestPath = join(tempBucket, 'manifests', exp.filename);+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));+ manifest.portosSchemaVersions = { universes: 99, pipelineSeries: 1, pipelineIssues: 1, mediaCollections: 99 };+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));+ await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);+ const result = await importer.processManifest(bucket.id, exp.filename);+ expect(result.reason).not.toBe('portos-schema-ahead');+ expect(result.processed).toBe(true);+ const restored = await series.getSeries(s.id);+ expect(restored.id).toBe(s.id);+ });+it('importer falls through for manifests with no portosSchemaVersions (legacy peer)', async () => {// A manifest produced by a pre-this-PR PortOS won't have the field;// the comparator treats it as no-contract, so the merge proceeds.diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 770bed3c7f..b35ea71fe5 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -53,8 +53,10 @@ import { pullSidecarForImage } from './sidecarSync.js';import { recordEvents } from './recordEvents.js';import {PORTOS_SCHEMA_VERSIONS,+ RECORD_KIND_SCHEMA_CATEGORIES,buildPortosMeta,compareSchemaVersions,+ scopeVersionDiff,formatVersionGap,getPortosVersion,} from '../../lib/schemaVersions.js';@@ -1274,7 +1276,20 @@ export async function applyIncomingPush(payload) {// directions for that purpose.const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;- const versionDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ // Per-category gate: scope the ahead-check to the categories THIS push+ // actually writes — the record's own kind, plus pipelineIssues when issues+ // ride along on a series push, plus mediaCollections when a linked+ // collection is bundled. A sender ahead on an unrelated category no longer+ // rejects this push. The full union diff stays available for diagnostics.+ const relevantCategories = new Set(RECORD_KIND_SCHEMA_CATEGORIES[kind] || []);+ if (kind === 'series' && Array.isArray(issues) && issues.length > 0) {+ for (const c of RECORD_KIND_SCHEMA_CATEGORIES.issue) relevantCategories.add(c);+ }+ if (isPlainObject(linkedCollection)) {+ for (const c of RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection) relevantCategories.add(c);+ }+ const fullDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ const versionDiff = scopeVersionDiff(fullDiff, [...relevantCategories]);// Tombstone payloads carry only id+deleted+deletedAt+updatedAt — fields// that exist at EVERY schema version and cannot corrupt local state. Gating// them on the schema-version comparator would strand federated deletesdiff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 740cd6f9d6..ce8ad1de05 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -2012,6 +2012,7 @@ describe('peerSync', () => {vi.mocked(mergeUniversesFromSync).mockClear();vi.mocked(mergeSeriesFromSync).mockClear();vi.mocked(mergeIssuesFromSync).mockClear();+ vi.mocked(mergeMediaCollectionsFromSync).mockClear();});describe('receiver — applyIncomingPush', () => {@@ -2080,6 +2081,71 @@ describe('peerSync', () => {});expect(mergeUniversesFromSync).toHaveBeenCalled();});++ // ---- per-category gate: cross-key isolation -------------------------+ // The sender stamps its full schemaVersions map. A push must only be+ // gated on the categories THIS record actually writes.+ it('does NOT reject a universe push when the sender is ahead on mediaCollections only', async () => {+ // universes is equal; the sender bumped an unrelated category. The old+ // whole-payload gate would have rejected this universe push.+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, mediaCollections: 2 } },+ });+ expect(mergeUniversesFromSync).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'u1' }),+ ]);+ });++ it('does NOT reject a series push with NO bundled issues when the sender is ahead on pipelineIssues only', async () => {+ // No issues ride along, so pipelineIssues is not a transferred category.+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 2 } },+ });+ expect(mergeSeriesFromSync).toHaveBeenCalled();+ expect(mergeIssuesFromSync).not.toHaveBeenCalled();+ });++ it('DOES reject a series push WITH bundled issues when the sender is ahead on pipelineIssues', async () => {+ // Issues are being transferred, so a pipelineIssues ahead-mismatch must+ // gate the push — otherwise the receiver merges issues it can't parse.+ const rejection = await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'Foo' },+ issues: [{ id: 'i1', seriesId: 's1', deleted: false, deletedAt: null }],+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 2 } },+ }).catch((err) => err);+ expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');+ expect(rejection.details.ahead).toEqual([{ category: 'pipelineIssues', senderV: 2, receiverV: 1 }]);+ expect(mergeSeriesFromSync).not.toHaveBeenCalled();+ expect(mergeIssuesFromSync).not.toHaveBeenCalled();+ });++ it('DOES reject a universe push WITH a bundled linkedCollection when the sender is ahead on mediaCollections', async () => {+ // The linked collection is a transferred category, so a mediaCollections+ // ahead-mismatch must gate even though universes is equal.+ const rejection = await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ linkedCollection: { id: 'col-1', name: 'Universe: U', items: [] },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, mediaCollections: 2 } },+ }).catch((err) => err);+ expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');+ expect(rejection.details.ahead).toEqual([{ category: 'mediaCollections', senderV: 2, receiverV: 1 }]);+ expect(mergeUniversesFromSync).not.toHaveBeenCalled();+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();+ });});describe('sender — pushRecordToPeer', () => {