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([peer-sync-per-category-version-gate]): address codex/claude/gemini review
Adam Eivydfd82f166b00
diff --git a/server/lib/README.md b/server/lib/README.mdindex bdd6618844..05f970e36d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -84,7 +84,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` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. 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. || `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. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |-| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply on the comparator result so an upgraded sender can't corrupt a downstream peer. |+| `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. || `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. || `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 050ae3cdba..a32851988b 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -726,14 +726,37 @@ const CATEGORIES = {// 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.+// snapshot.+//+// EVERY category is listed explicitly (not via a `|| []` fallthrough) so the+// guard test below can assert completeness: a future category, or a future+// storage-layout version added to a currently-unversioned one, can't ship+// without a deliberate mapping decision here. The unversioned categories map+// to `[]` (their merges are LWW/deep-union/append-tolerant with no versioned+// on-disk layout today). KNOWN trade-off of per-category scoping: an+// already-shipped OLD receiver no longer blanket-blocks a future sender that+// bumps a category this version doesn't yet know is versioned — that's the+// inverse of the whole-payload over-blocking this change exists to fix.+// Introducing versioning for one of these must add its key to+// PORTOS_SCHEMA_VERSIONS AND here (the coverage test enforces it).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,+ goals: [],+ character: [],+ digitalTwin: [],+ meatspace: [],+ videoHistory: [],};+// Exported for the boot-adjacent guard test (see dataSync.pipelineUniverse.test.js):+// every snapshot category must have a deliberate schema-key mapping, and every+// versioned PORTOS_SCHEMA_VERSIONS key must be reachable from some category.+export function getSnapshotCategorySchemaKeys() {+ return SNAPSHOT_CATEGORY_SCHEMA_KEYS;+}+// 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-returndiff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 0c146e5cfc..11bdbf3d4a 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -22,6 +22,7 @@ vi.mock('../lib/fileUtils.js', async () => {afterAll(cleanup);const dataSync = await import('./dataSync.js');+const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');const SERIES_DIR = join(tempRoot, 'pipeline-series');const ISSUES_DIR = join(tempRoot, 'pipeline-issues');@@ -890,4 +891,23 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {]);expect(readSeriesState()).toEqual([]); // nothing written});++ // ---- gate-map completeness (fail-open guard) -------------------------+ it('every snapshot category has a deliberate schema-key mapping', () => {+ // No `|| []` fallthrough surprises: a future category must be mapped+ // explicitly (even to []) so the gate decision for it is intentional.+ const map = dataSync.getSnapshotCategorySchemaKeys();+ for (const category of dataSync.getSupportedCategories()) {+ expect(Array.isArray(map[category])).toBe(true);+ }+ });++ it('every versioned PORTOS_SCHEMA_VERSIONS key is reachable from some snapshot category', () => {+ // A newly-versioned category can't ship without being wired into the+ // per-category snapshot gate — otherwise its snapshot transfer is ungated.+ const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());+ for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {+ expect(covered.has(key)).toBe(true);+ }+ });});diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 8c45bd2185..98d7237073 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -399,11 +399,16 @@ async function readReferencedRecords(bucketPath, manifest) {* 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.+ * Id-prefix → kind mirrors `readReferencedRecords` above (`ser-` → series,+ * `iss-` → issue, `chr-`/`set-`/`obj-` → universe bible sub-records); a UUID is+ * a universe record EXCEPT on a `media` manifest, where UUIDs are media-job+ * records. Media-job records are intentionally NOT gated: they have no+ * versioned storage layout, and `mergeMediaJobRecords` is insert-only by id+ * (never overwrites, stores the record verbatim, readers use optional+ * chaining) — so a future-shape job degrades gracefully rather than corrupting,+ * exactly like the unlisted `videoHistory` category. `media-annotations`+ * manifests bypass the records pipeline entirely and carry no versioned layout+ * → never gated.*/function relevantSchemaCategoriesForManifest(manifest) {if (manifest?.kind === 'media-annotations') return [];@@ -619,7 +624,12 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =let collectionPendingUniverse = null;let collectionPendingSeries = null;let collectionTombstonedUniverse = null;- if (manifest.collection) {+ // `isPlainObject` (not bare truthiness) so this apply path agrees exactly+ // with the schema gate's `relevantSchemaCategoriesForManifest`, which only+ // counts a plain-object `collection` as carrying the mediaCollections+ // category. A truthy non-object (corrupt/hand-crafted manifest) must not+ // slip past the gate yet still reach the merge.+ if (isPlainObject(manifest.collection)) {// Suppress re-export of the owner record while the collection items// land — the items themselves drive recordEvents, which would loop// back through the receiver's own subscriptions if not gated.diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex b35ea71fe5..4f46fed79a 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -1276,28 +1276,36 @@ 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;- // 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) {+ // Per-category gate, scoped to the categories THIS push actually writes a+ // LIVE (non-tombstone) record into. A sender ahead on an unrelated category+ // no longer rejects this push; the full union diff stays for diagnostics.+ //+ // Tombstones are folded INTO the per-category scoping rather than exempted+ // wholesale. A tombstone payload carries only id+deleted+deletedAt+updatedAt+ // — fields that exist at EVERY schema version and can't corrupt local state+ // — so its category needn't gate, and exempting it keeps federated deletes+ // converging even when one peer upgrades ahead (otherwise blockedBySchema →+ // edit-push cooldown → the delete never lands). BUT a deleted `series` push+ // still bundles its LIVE child issues (deleteSeries does not cascade-+ // tombstone them; buildPushPayload ships every child so the receiver can+ // finish its cascade), and those live, full-shape issue records WOULD+ // corrupt an older receiver. So gate a category only when it carries at+ // least one live record:+ const relevantCategories = new Set();+ if (record.deleted !== true) {+ for (const c of (RECORD_KIND_SCHEMA_CATEGORIES[kind] || [])) relevantCategories.add(c);+ }+ if (kind === 'series' && Array.isArray(issues) && issues.some((i) => i?.deleted !== true)) {for (const c of RECORD_KIND_SCHEMA_CATEGORIES.issue) relevantCategories.add(c);}- if (isPlainObject(linkedCollection)) {+ // A linked collection only rides a non-deleted push (buildPushPayload drops+ // it for tombstones) and is itself a live record when present.+ if (isPlainObject(linkedCollection) && linkedCollection.deleted !== true) {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 deletes- // whenever any peer upgrades faster than another (sender writes- // blockedBySchema → edit-triggered pushes go into cooldown → delete never- // reaches receivers until both peers reconnect AND the receiver upgrades).- // Exempt tombstones from the gate so soft-deletes always converge.- if (versionDiff.ahead.length > 0 && record.deleted !== true) {+ if (versionDiff.ahead.length > 0) {console.warn(`⚠️ peerSync: rejecting push from ${sourceInstanceId} — ${formatVersionGap(versionDiff)} (sender PortOS ${senderPortosVersion || 'unknown'})`,);diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex ce8ad1de05..d86ee80f5e 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -11,6 +11,7 @@ import { tmpdir } from 'os';// runs against the real on-disk paths via the tmpdir-redirect pattern below.import { PATHS } from '../../lib/fileUtils.js';+import { RECORD_KIND_SCHEMA_CATEGORIES, PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';vi.mock('../instances.js', async () => {return {@@ -2146,6 +2147,82 @@ describe('peerSync', () => {expect(mergeUniversesFromSync).not.toHaveBeenCalled();expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();});++ // ---- tombstone-aware per-category scoping --------------------------+ it('does NOT reject a pure tombstone push even when the sender is ahead on that record kind (delete converges)', async () => {+ // A tombstone carries only id+deleted+deletedAt+updatedAt — safe at any+ // schema version. Gating it would strand federated deletes when one peer+ // upgrades ahead. The merge still runs (the delete must land).+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', deleted: true, deletedAt: '2026-05-22T03:00:00Z' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } },+ });+ expect(mergeUniversesFromSync).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'u1', deleted: true }),+ ]);+ });++ it('DOES reject a deleted-series push that bundles a LIVE issue when the sender is ahead on pipelineIssues', async () => {+ // deleteSeries does not cascade-tombstone child issues, and the push+ // bundles every child — so a deleted series can carry full-shape LIVE+ // issues. The series tombstone alone is safe, but the live issues are+ // NOT; gate pipelineIssues so they can't corrupt an older receiver.+ const rejection = await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', deleted: true, deletedAt: '2026-05-22T03:00:00Z' },+ 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 NOT reject a deleted-series push whose bundled issues are ALL tombstones (cascade delete converges)', async () => {+ // Series tombstone + issue tombstones only — no live record in any+ // category, so nothing gates and the whole delete cascade converges+ // even though the sender is ahead on both pipelineSeries and pipelineIssues.+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', deleted: true, deletedAt: '2026-05-22T03:00:00Z' },+ issues: [{ id: 'i1', seriesId: 's1', deleted: true, deletedAt: '2026-05-22T03:00:00Z' }],+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 9, pipelineIssues: 9 } },+ });+ expect(mergeSeriesFromSync).toHaveBeenCalled();+ expect(mergeIssuesFromSync).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'i1', deleted: true }),+ ]);+ });+ });++ describe('gate-map completeness (fail-open guard)', () => {+ it('every PEER_SUBSCRIBABLE_KIND resolves to a schema-category mapping', () => {+ // A new push kind that writes a versioned layout must be added to+ // RECORD_KIND_SCHEMA_CATEGORIES, or its push would bypass the gate+ // entirely (silent cross-install corruption). `mediaCollection` maps+ // via the same key; series issues are unioned at the call site.+ for (const kind of PEER_SUBSCRIBABLE_KINDS) {+ expect(Array.isArray(RECORD_KIND_SCHEMA_CATEGORIES[kind])).toBe(true);+ expect(RECORD_KIND_SCHEMA_CATEGORIES[kind].length).toBeGreaterThan(0);+ }+ });++ it('every versioned PORTOS_SCHEMA_VERSIONS key is reachable from a record kind', () => {+ // So a newly-versioned category can't ship without being wired into the+ // per-category gate (which would leave its transfers ungated).+ const covered = new Set(Object.values(RECORD_KIND_SCHEMA_CATEGORIES).flat());+ for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {+ expect(covered.has(key)).toBe(true);+ }+ });});describe('sender — pushRecordToPeer', () => {