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([manuscript-review-sync]): sync the manuscript-review comment set across installs
[._.]/ Adam Eivy8f95834d9424
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex e5b4455434..95e4e24ea8 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -46,6 +46,25 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// the field back onto a newer peer. Per-category gate → only series sync// pauses with old peers; issues/universes keep flowing.pipelineSeries: 2,+ // NOT bumped for the manuscript-review sibling doc now bundled on series+ // pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).+ // Unlike `readerMap` (v2), the review is NOT a field inside the series+ // record — it's a separate doc that rides a dedicated `manuscriptReview`+ // payload key, so an older peer never round-trips it through the series+ // sanitizer (no silent-strip-then-LWW-back corruption — the readerMap gate's+ // whole reason to exist). It is additive + gracefully degrading: a pre-feature+ // receiver ignores the unknown key (review just doesn't reach it) and ships+ // no review back, so the newer peer's `if (manuscriptReview)` receive guard+ // is a no-op and the local review is preserved. Bumping `pipelineSeries` here+ // would be actively harmful — it would 412-reject the ENTIRE series push+ // (record + issues) to every not-yet-upgraded peer over an OPTIONAL doc that+ // degrades fine. Registering a brand-new gated category would hit the same+ // whole-payload footgun documented for `videoHistory` below. So manuscript-+ // review is intentionally UNGATED today (all peers ship review-doc shape v1).+ // The FIRST incompatible review-doc shape change (manuscriptReview.js+ // SCHEMA_VERSION 1→2, where an older peer's sanitizer would strip a field and+ // LWW it back) MUST introduce a gate then — mirroring the catalog+ // payloadSchemaVersion lockstep note below.mediaCollections: 1,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.jsindex 1f9b0bf82b..85371517f2 100644--- a/server/services/pipeline/manuscriptReview.js+++ b/server/services/pipeline/manuscriptReview.js@@ -21,6 +21,7 @@ import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';import { seriesStore } from './series.js';import { collectManuscriptSections } from './arcPlanner.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';// Storage-layout version for the review document. Bump + migrate if the// comment shape changes in a way older peers can't read.@@ -167,6 +168,13 @@ export async function seedReviewFromFindings(seriesId, findings, { runId = nullconst next = { schemaVersion: SCHEMA_VERSION, comments: [...review.comments, ...fresh] };await writeReview(seriesId, next);+ // The review is a sibling of the series record, so a review-only change+ // doesn't move the series `index.json` — emit a series `updated` event so+ // the peer-sync push + bucket re-export fire (both hash the review into+ // their payload). Only when something actually changed; a no-op seed+ // would just be short-circuited by the push hash anyway. Skipped on the+ // sync RECEIVE path (`mergeReviewFromSync`) to avoid an echo loop.+ if (fresh.length > 0) emitRecordUpdated('series', seriesId);return next;});}@@ -191,6 +199,9 @@ export async function updateComment(seriesId, commentId, patch) {merged.updatedAt = new Date().toISOString();const next = { ...review, comments: review.comments.map((c, i) => (i === idx ? sanitizeComment(merged) : c)) };await writeReview(seriesId, next);+ // Sibling-doc change → fire a series `updated` event so the review+ // propagates to peers / re-exports to subscribed buckets (see seed above).+ emitRecordUpdated('series', seriesId);return next.comments[idx];});}diff --git a/server/services/pipeline/manuscriptReview.test.js b/server/services/pipeline/manuscriptReview.test.jsnew file mode 100644index 0000000000..df2c39d775--- /dev/null+++ b/server/services/pipeline/manuscriptReview.test.js@@ -0,0 +1,66 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// In-memory file store so reads/writes round-trip without touching disk.+const fileStore = new Map();+vi.mock('../../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++// seriesStore().recordDir(id) → a stable per-series path key.+vi.mock('./series.js', () => ({+ seriesStore: () => ({ recordDir: (id) => `/mock/series/${id}` }),+}));++// No manuscript sections needed for these tests (seed resolves issueId/stageId+// from them, but we don't assert on those here).+vi.mock('./arcPlanner.js', () => ({+ collectManuscriptSections: vi.fn(async () => []),+}));++import { recordEvents } from '../sharing/recordEvents.js';+import { seedReviewFromFindings, updateComment, mergeReviewFromSync } from './manuscriptReview.js';++describe('manuscriptReview — record-event emission on write', () => {+ let updates;+ let listener;+ beforeEach(() => {+ fileStore.clear();+ updates = [];+ listener = (evt) => updates.push(evt);+ recordEvents.on('updated', listener);+ });+ afterEach(() => {+ recordEvents.off('updated', listener);+ });++ it('seedReviewFromFindings emits a series updated event when comments are added', async () => {+ await seedReviewFromFindings('ser-1', [{ problem: 'Act II sags', anchorQuote: 'the road' }]);+ expect(updates).toContainEqual({ recordKind: 'series', recordId: 'ser-1' });+ });++ it('seedReviewFromFindings does NOT emit when no fresh findings are added', async () => {+ // Seed once, then re-seed the identical finding — the second call is a no-op+ // (deduped by finding key) and must not fire a spurious push/re-export.+ await seedReviewFromFindings('ser-1', [{ problem: 'Act II sags', anchorQuote: 'the road' }]);+ updates.length = 0;+ await seedReviewFromFindings('ser-1', [{ problem: 'Act II sags', anchorQuote: 'the road' }]);+ expect(updates).toEqual([]);+ });++ it('updateComment emits a series updated event', async () => {+ const seeded = await seedReviewFromFindings('ser-2', [{ problem: 'Pacing', anchorQuote: 'q' }]);+ const commentId = seeded.comments[0].id;+ updates.length = 0;+ await updateComment('ser-2', commentId, { status: 'accepted' });+ expect(updates).toContainEqual({ recordKind: 'series', recordId: 'ser-2' });+ });++ it('mergeReviewFromSync does NOT emit (receive path — avoids an echo loop)', async () => {+ await mergeReviewFromSync('ser-3', {+ schemaVersion: 1,+ comments: [{ id: 'mrc-x', problem: 'remote note', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],+ });+ expect(updates).toEqual([]);+ });+});diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 60877d1293..1db4d4c3d9 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -25,6 +25,7 @@ import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlimport { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';import { listSeries, getSeries } from '../pipeline/series.js';import { listIssues } from '../pipeline/issues.js';+import { getReview } from '../pipeline/manuscriptReview.js';import { getUniverse } from '../universeBuilder.js';import { findCollectionByUniverseId, findCollectionBySeriesId } from '../mediaCollections.js';import { getJob } from '../mediaJobQueue/index.js';@@ -406,6 +407,17 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {const stampedSeries = stampOrigin(series, { bucket, source, sourceBio, manifestId });await atomicWrite(join(bucket.path, 'records', 'series', `${series.id}.json`), stampedSeries);+ // Bundle the manuscript-review sibling doc (the "Finish the draft" comment+ // set) so it travels with the series. It's keyed by seriesId — not a record+ // id of its own — so it lives under records/reviews/ and is NOT added to+ // `recordIds` (the importer reads it by seriesId after the series merges).+ // Skip when empty so we don't litter the bucket with no-op review files; an+ // importer that finds no file simply leaves the local review untouched.+ const review = await getReview(series.id).catch(() => null);+ if (review && Array.isArray(review.comments) && review.comments.length > 0) {+ await atomicWrite(join(bucket.path, 'records', 'reviews', `${series.id}.json`), review);+ }+for (const issue of issues) {recordIds.push(issue.id);const stamped = stampOrigin(issue, { bucket, source, sourceBio, manifestId });diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex f03bc25d65..37d4e62e9b 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -33,6 +33,7 @@ import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.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 { mergeReviewFromSync } from '../pipeline/manuscriptReview.js';import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';import { applyLegacySeriesCanonToUniverse } from '../pipeline/migrateSeriesCanon.js';import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';@@ -627,6 +628,24 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =});}+ // Merge the bundled manuscript-review sibling doc (if the sender shipped one)+ // into local state, LWW-per-comment. Keyed by seriesId under records/reviews/+ // — read by seriesId rather than via `recordIds` because the review has no+ // record id of its own. An older sender (no reviews/ folder) → null → skip;+ // a newer sender whose review LWW-loses every comment is a harmless no-op.+ // Best-effort: a review merge failure must not abort the manifest (the+ // series + issues already applied, and the next sync cycle re-attempts).+ // `mergeReviewFromSync` does not emit a record event, so no re-export loop.+ for (const s of records.series) {+ if (skipSeriesMerge.has(s.id)) continue;+ const review = await readJSONFile(join(bucket.path, 'records', 'reviews', `${s.id}.json`), null, { logError: false });+ if (review) {+ await mergeReviewFromSync(s.id, review).catch((err) => {+ console.log(`⚠️ sharing.importer: manuscript-review merge for ${s.id} failed: ${err.message}`);+ });+ }+ }+// Universe and series shares can both carry a linked media collection// payload. Items are unioned into a local "Universe: <name>" or// "Series: <name>" collection so peer-generated images appear alongsidediff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex eb44f5edf1..2a9bf0b980 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -61,6 +61,7 @@ const importer = await import('./importer.js');const series = await import('../pipeline/series.js');const issues = await import('../pipeline/issues.js');const universeSvc = await import('../universeBuilder.js');+const manuscriptReview = await import('../pipeline/manuscriptReview.js');// Rewrite a manifest's senderInstanceId on disk so the importer sees it as// coming from a remote peer. The mocked `getInstanceId` returns the same@@ -202,6 +203,39 @@ describe('sharing round-trip', () => {expect(afterOverride.name).toBe('Test Series (renamed)');});+ it('round-trips the manuscript review (Finish-the-draft comments) with a series export/import', async () => {+ const bucket = await buckets.createBucket({ name: 'ReviewBucket', path: tempBucket, mode: 'auto-merge' });++ const s = await series.createSeries({ name: 'Review Series', logline: 'A' });+ await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });+ // Author a review comment (the "Finish the draft" pass output).+ await manuscriptReview.seedReviewFromFindings(s.id, [+ { problem: 'Act II sags', severity: 'medium', anchorQuote: 'the long road', issueNumber: 1 },+ ]);+ const before = await manuscriptReview.getReview(s.id);+ expect(before.comments).toHaveLength(1);++ const exp = await exporter.exportSeries(s.id, bucket.id);+ // The review rides under records/reviews/<seriesId>.json, NOT in recordIds.+ expect(existsSync(join(tempBucket, 'records', 'reviews', `${s.id}.json`))).toBe(true);++ // Drop the local series (removes its folder + review file), then import.+ await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);+ await importer.processManifest(bucket.id, exp.filename);++ const restored = await manuscriptReview.getReview(s.id);+ expect(restored.comments).toHaveLength(1);+ expect(restored.comments[0].problem).toBe('Act II sags');+ });++ it('skips writing a review file when the series has no review comments', async () => {+ const bucket = await buckets.createBucket({ name: 'NoReviewBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Empty Review Series', logline: 'A' });+ await exporter.exportSeries(s.id, bucket.id);+ expect(existsSync(join(tempBucket, 'records', 'reviews', `${s.id}.json`))).toBe(false);+ });+it('a remote orphan series (universeId null) preserves the local universe link instead of aborting the import', async () => {const bucket = await buckets.createBucket({ name: 'OrphanLinkBucket', path: tempBucket, mode: 'auto-merge' });const u = await universeSvc.createUniverse({ name: 'Linked Universe' });diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 53a4b1ec4c..bdb4ca45a1 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -928,6 +928,7 @@ export async function pushRecordToPeer(sub, options = {}) {record: payload.record,issues: payload.issues ?? null,linkedCollection: payload.linkedCollection ?? null,+ manuscriptReview: payload.manuscriptReview ?? null,assetManifest: payload.assetManifest ?? [],});if (sub.lastPushedHash && sub.lastPushedHash === hash) {@@ -1271,6 +1272,19 @@ async function buildPushPayload(sub, sourceInstanceId) {const assetManifest = record.deleted === true? []: await buildAssetManifestForSeries(record, manifestIssues, linkedCollection);+ // Bundle the manuscript-review sibling doc (the "Finish the draft" comment+ // set) so review-only edits — which don't move the series record — still+ // propagate. Same reasoning as the linkedCollection bundle above: the+ // review rides the payload AND the push hash, defeating the lastPushedHash+ // short-circuit. Skip for tombstones (a deleted series ships no review).+ // Dynamic import keeps manuscriptReview's arcPlanner graph off peerSync's+ // boot load path (matches the catalogBundle pattern).+ const manuscriptReview = record.deleted === true+ ? null+ : await (async () => {+ const { getReview } = await import('../pipeline/manuscriptReview.js');+ return getReview(sub.recordId).catch(() => null);+ })();return {kind: 'series',record: sanitized,@@ -1279,6 +1293,7 @@ async function buildPushPayload(sub, sourceInstanceId) {sourceInstanceId,portosMeta,...(linkedCollection ? { linkedCollection } : {}),+ ...(manuscriptReview && manuscriptReview.comments?.length ? { manuscriptReview } : {}),};}if (sub.recordKind === 'mediaCollection') {@@ -1456,7 +1471,7 @@ export async function applyIncomingPush(payload) {if (!isPlainObject(payload)) {throw makeErr('payload must be an object', ERR_VALIDATION);}- const { kind, record, issues, linkedCollection, catalogBundle, assetManifest, sourceInstanceId, portosMeta } = payload;+ const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, assetManifest, sourceInstanceId, portosMeta } = payload;if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);}@@ -1594,6 +1609,18 @@ export async function applyIncomingPush(payload) {if (!localEphemeral && Array.isArray(issues) && issues.length > 0) {await mergeIssuesFromSync(issues, { source });}+ // Merge the bundled manuscript-review sibling doc, LWW-per-comment. Same+ // guards as the issue batch + linkedCollection below: skip for local-+ // ephemeral records (the user opted this series out of sync) and tombstone+ // pushes (a deleted series carries no live review). Best-effort — a review+ // merge failure must not fail the push (the series/issues already merged).+ // Dynamic import keeps the arcPlanner graph off peerSync's load path.+ if (!localEphemeral && record.deleted !== true && isPlainObject(manuscriptReview)) {+ const { mergeReviewFromSync } = await import('../pipeline/manuscriptReview.js');+ await mergeReviewFromSync(record.id, manuscriptReview).catch((err) => {+ console.log(`⚠️ peerSync: manuscriptReview merge failed: ${err.message}`);+ });+ }} else if (kind === 'mediaCollection') {await mergeMediaCollectionsFromSync([record], { source });}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 227de47b71..0408ad8e3c 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -39,6 +39,13 @@ vi.mock('../pipeline/issues.js', async () => ({mergeIssuesFromSync: vi.fn(),}));+// manuscriptReview is dynamic-imported inside the series push/receive helpers;+// mock both entry points so the review bundle path is exercisable.+vi.mock('../pipeline/manuscriptReview.js', async () => ({+ getReview: vi.fn(),+ mergeReviewFromSync: vi.fn(),+}));+vi.mock('../mediaCollections.js', async () => ({getCollection: vi.fn(),listCollections: vi.fn(),@@ -99,6 +106,7 @@ import { getInstanceId, getPeers } from '../instances.js';import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBuilder.js';import { getSeries, mergeSeriesFromSync, listSeries } from '../pipeline/series.js';import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';+import { getReview, mergeReviewFromSync } from '../pipeline/manuscriptReview.js';import {getCollection,listCollections,@@ -174,6 +182,10 @@ beforeEach(async () => {vi.mocked(getUniverse).mockReset().mockResolvedValue(undefined);vi.mocked(getSeries).mockReset().mockResolvedValue(undefined);vi.mocked(listIssues).mockReset().mockResolvedValue([]);+ // Default: no manuscript review for any series. Tests that exercise the+ // review-bundle path override getReview per-call.+ vi.mocked(getReview).mockReset().mockResolvedValue({ schemaVersion: 1, comments: [] });+ vi.mocked(mergeReviewFromSync).mockReset().mockResolvedValue({ schemaVersion: 1, comments: [] });// Default: no linked collection for any record. Tests that exercise the// bundle path override these per-call.vi.mocked(getCollection).mockReset().mockRejectedValue(Object.assign(new Error('Collection not found'), { code: 'NOT_FOUND' }));@@ -1485,6 +1497,76 @@ describe('peerSync', () => {expect(captured.issues.map((i) => i.id)).toEqual(['i1', 'i2']);});+ it('bundles the manuscript review with a series push so review-only edits propagate', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(getReview).mockResolvedValue({+ schemaVersion: 1,+ comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],+ });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1' });+ expect(captured.kind).toBe('series');+ expect(captured.manuscriptReview).toBeTruthy();+ expect(captured.manuscriptReview.comments).toHaveLength(1);+ expect(captured.manuscriptReview.comments[0].id).toBe('mrc-1');+ });++ it('omits the manuscriptReview key when the series has an empty review', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(getReview).mockResolvedValue({ schemaVersion: 1, comments: [] });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1' });+ expect(captured.manuscriptReview).toBeUndefined();+ });++ it('does not fetch a review for a tombstone series push', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series', deleted: true, deletedAt: '2026-06-02T00:00:00Z', updatedAt: '2026-06-02T00:00:00Z' });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({ id: 's', peerId: 'peer-a', recordKind: 'series', recordId: 's1' });+ expect(captured.manuscriptReview).toBeUndefined();+ expect(vi.mocked(getReview)).not.toHaveBeenCalled();+ });++ it('re-pushes when only the manuscript review changes (series record byte-identical)', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(getReview)+ .mockResolvedValueOnce({+ schemaVersion: 1,+ comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],+ })+ .mockResolvedValueOnce({+ // A comment status flip bumps updatedAt → review (and thus hash) changes.+ schemaVersion: 1,+ comments: [{ id: 'mrc-1', problem: 'pacing', status: 'accepted', updatedAt: '2026-06-02T01:00:00Z' }],+ });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });+ const sub = await subscribePeer(+ { peerId: 'peer-a', recordKind: 'series', recordId: 's1' },+ { adoptedFromReverse: true },+ );+ const first = await pushRecordToPeer(sub);+ expect(first.pushed).toBe(true);++ vi.mocked(peerFetch).mockClear();+ const refreshed = await findPeerSubscription('peer-a', 'series', 's1');+ const second = await pushRecordToPeer(refreshed);+ expect(second.pushed).toBe(true);+ expect(second.reason).not.toBe('unchanged');+ expect(peerFetch).toHaveBeenCalledTimes(1);+ });+it('bundles the linked media collection with a universe push so collection-only edits propagate', async () => {// Regression: collection items[] adds emit recordEvents.updated('universe', id)// but the universe record content itself doesn't change, so the@@ -1902,6 +1984,58 @@ describe('peerSync', () => {expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();});+ it('routes a bundled manuscriptReview through mergeReviewFromSync on a series push', async () => {+ const manuscriptReview = {+ schemaVersion: 1,+ comments: [{ id: 'mrc-1', problem: 'pacing', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }],+ };+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ manuscriptReview,+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeReviewFromSync).toHaveBeenCalledWith('s1', manuscriptReview);+ });++ it('skips mergeReviewFromSync when no manuscriptReview is bundled', async () => {+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeReviewFromSync).not.toHaveBeenCalled();+ });++ it('refuses to merge manuscriptReview when the incoming series record is a tombstone', async () => {+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', deleted: true, deletedAt: '2026-06-02T00:00:00Z', updatedAt: '2026-06-02T00:00:00Z' },+ issues: [],+ manuscriptReview: { schemaVersion: 1, comments: [{ id: 'mrc-1', problem: 'x', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }] },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeReviewFromSync).not.toHaveBeenCalled();+ });++ it('skips mergeReviewFromSync when the LOCAL series is ephemeral', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', ephemeral: true });+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ manuscriptReview: { schemaVersion: 1, comments: [{ id: 'mrc-1', problem: 'x', status: 'open', updatedAt: '2026-06-02T00:00:00Z' }] },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeReviewFromSync).not.toHaveBeenCalled();+ });+it('refuses to merge linkedCollection when the incoming record is a tombstone', async () => {// Defense in depth: the sender's buildPushPayload already skips the// bundle for tombstones, but a buggy or malicious peer could send