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([manuscript-review-sync]): don't silently drop a review on a transient merge failure
[._.]/ Adam Eivy6f6940ac4030
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 37d4e62e9b..ad506f0d0b 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -633,15 +633,20 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =// — 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.+ // A merge FAILURE (transient write/parse error) must NOT silently advance the+ // cursor — the review has no independent reconciliation cycle (it only rides+ // the series push/export), so a swallowed failure would drop it permanently.+ // Surface it as a pending condition (like recordImportFailures /+ // collectionPending*) so processManifest leaves the manifest retryable.+ const reviewMergeFailures = [];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}`);+ reviewMergeFailures.push(s.id);});}}@@ -707,6 +712,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =legacyCanonPendingUniverses: legacyCanonPendingUniverses.length > 0 ? legacyCanonPendingUniverses : null,legacyCanonPendingFailures: legacyCanonPendingFailures.length > 0 ? legacyCanonPendingFailures : null,recordImportFailures: failedInserts.length > 0 ? failedInserts : null,+ reviewMergeFailures: reviewMergeFailures.length > 0 ? reviewMergeFailures : null,adoptedSubscription: adoptedSubscription? { id: adoptedSubscription.id, bucketId: adoptedSubscription.bucketId, recordKind: adoptedSubscription.recordKind, recordId: adoptedSubscription.recordId }: null,@@ -967,6 +973,7 @@ export async function processManifest(bucketId, manifestFilename) {const legacyCanonPendingUniverses = outcome?.legacyCanonPendingUniverses || null;const legacyCanonPendingFailures = outcome?.legacyCanonPendingFailures || null;const recordImportFailures = outcome?.recordImportFailures || null;+ const reviewMergeFailures = outcome?.reviewMergeFailures || null;// Tombstoned universe: the collection owner IS on disk but locally deleted.// Unlike the truly-missing case this will never self-resolve via sync, so we// advance the cursor (no infinite pending loop) and emit a clear signal. The@@ -977,7 +984,7 @@ export async function processManifest(bucketId, manifestFilename) {console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} collectionUniverse=${collectionTombstonedUniverse} is deleted locally — ${outcome.collectionItemsDeferred ?? 0} item(s) skipped; restore universe to import`);return { processed: true, manifest, outcome };}- if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures || recordImportFailures) {+ if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures || recordImportFailures || reviewMergeFailures) {if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;if (collectionPendingUniverse) outcome.pendingCollectionUniverse = collectionPendingUniverse;@@ -985,8 +992,9 @@ export async function processManifest(bucketId, manifestFilename) {if (legacyCanonPendingUniverses) outcome.pendingLegacyCanonUniverses = legacyCanonPendingUniverses;if (legacyCanonPendingFailures) outcome.pendingLegacyCanonFailures = legacyCanonPendingFailures;if (recordImportFailures) outcome.pendingRecordImportFailures = recordImportFailures;+ if (reviewMergeFailures) outcome.pendingReviewMergeFailures = reviewMergeFailures;sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });- console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}${legacyCanonPendingFailures ? ` legacyCanonFailures=${legacyCanonPendingFailures.join(',')}` : ''}${recordImportFailures ? ` recordImportFailures=${recordImportFailures.join(',')}` : ''}`);+ console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}${legacyCanonPendingFailures ? ` legacyCanonFailures=${legacyCanonPendingFailures.join(',')}` : ''}${recordImportFailures ? ` recordImportFailures=${recordImportFailures.join(',')}` : ''}${reviewMergeFailures ? ` reviewMergeFailures=${reviewMergeFailures.join(',')}` : ''}`);return { processed: true, pending: true, manifest, outcome };}await markProcessed(bucketId, manifestFilename, manifest.id);diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 2a9bf0b980..c057085068 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -236,6 +236,33 @@ describe('sharing round-trip', () => {expect(existsSync(join(tempBucket, 'records', 'reviews', `${s.id}.json`))).toBe(false);});+ it('keeps a manifest retryable when the bundled review merge fails (no silent drop)', async () => {+ const bucket = await buckets.createBucket({ name: 'ReviewFailBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Review Fail Series', logline: 'A' });+ await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });+ await manuscriptReview.seedReviewFromFindings(s.id, [+ { problem: 'Act II sags', severity: 'medium', anchorQuote: 'the road', issueNumber: 1 },+ ]);+ const exp = await exporter.exportSeries(s.id, bucket.id);+ await series.deleteSeries(s.id);++ // Force a transient review-merge failure on the FIRST import attempt.+ const spy = vi.spyOn(manuscriptReview, 'mergeReviewFromSync').mockRejectedValueOnce(new Error('disk full'));+ simulateRemoteSender(tempBucket, exp.filename);+ const r1 = await importer.processManifest(bucket.id, exp.filename);+ // Manifest stays pending (cursor un-advanced) so the watcher retries —+ // the review is NOT silently dropped.+ expect(r1.pending).toBe(true);+ expect(r1.outcome.pendingReviewMergeFailures).toContain(s.id);+ spy.mockRestore();++ // Re-process (manifest was kept retryable) — now the review lands.+ const r2 = await importer.processManifest(bucket.id, exp.filename);+ expect(r2.pending).toBeFalsy();+ const restored = await manuscriptReview.getReview(s.id);+ expect(restored.comments).toHaveLength(1);+ });+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 46cb5c50e3..736a40154a 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -1061,6 +1061,12 @@ export async function pushRecordToPeer(sub, options = {}) {// merge LWW path; only cost is one redundant POST per push cycle// until the receiver finishes pulling).const missingCount = Array.isArray(body?.missingAssets) ? body.missingAssets.length : 0;+ // REVIEW-STRANDED GUARD: the receiver merged the record/issues (returned 2xx)+ // but its bundled manuscript-review merge threw. Withhold lastPushedHash like+ // the missing-assets case so the next push cycle re-sends the review instead+ // of short-circuiting on `unchanged` — the review has no independent+ // reconciliation path, so a saved hash here would strand the update.+ const reviewSyncPending = body?.reviewSyncPending === true;// This push landed (receiver returned 2xx). Stamp the per-record confirmed-// delivery water-mark so tombstoneGc won't prune THIS record's tombstone// until its delete-push has been confirmed — even if a later push for a@@ -1070,7 +1076,7 @@ export async function pushRecordToPeer(sub, options = {}) {// the tombstone's deletedAt once it lands. The `missingAssets` case still// counts as confirmed delivery of the RECORD (merge ran on the receiver);// only the asset-stranded hash is withheld, not the confirmation mark.- await persistPushSuccess(sub.id, missingCount > 0 ? null : hash, { confirmedAtMs: Date.now() });+ await persistPushSuccess(sub.id, (missingCount > 0 || reviewSyncPending) ? null : hash, { confirmedAtMs: Date.now() });if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});}@@ -1603,6 +1609,10 @@ export async function applyIncomingPush(payload) {// peer collided (without `source`, the merge fns fall back to// `{ via:'sync', peerId:null }` and the attribution is lost).const source = { via: 'peer-push', peerId: sourceInstanceId };+ // Set true when a bundled manuscript-review merge throws — returned to the+ // sender so it withholds lastPushedHash and retries (the review has no other+ // reconciliation path; see the merge block below).+ let reviewSyncPending = false;if (kind === 'universe') {await mergeUniversesFromSync([record], { source });} else if (kind === 'series') {@@ -1619,13 +1629,18 @@ export async function applyIncomingPush(payload) {// 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).+ // pushes (a deleted series carries no live review). A merge failure must+ // NOT fail the push (the series/issues already merged) — but unlike the+ // linkedCollection bundle, the review has NO independent reconciliation+ // cycle, so a swallowed failure could never resend once the sender saves+ // lastPushedHash. Signal `reviewSyncPending` so the sender withholds the+ // hash (mirrors the missing-assets guard) and retries next cycle.// 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}`);+ reviewSyncPending = true;});}} else if (kind === 'mediaCollection') {@@ -1727,6 +1742,7 @@ export async function applyIncomingPush(payload) {missingAssets,reverseSubscriptionCreated,ackedDeletesUpTo,+ ...(reviewSyncPending ? { reviewSyncPending: true } : {}),};}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 67d9800147..a6ba1f17be 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -1567,6 +1567,30 @@ describe('peerSync', () => {expect(peerFetch).toHaveBeenCalledTimes(1);});+ it('withholds lastPushedHash when the receiver reports reviewSyncPending (so the next cycle re-sends)', 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' }],+ });+ // Receiver merged the record but its review merge threw → reviewSyncPending.+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ reviewSyncPending: true }) });+ const sub = await subscribePeer(+ { peerId: 'peer-a', recordKind: 'series', recordId: 's1' },+ { adoptedFromReverse: true },+ );+ const r = await pushRecordToPeer(sub);+ expect(r.pushed).toBe(true);+ // Hash withheld → a subsequent push with identical content is NOT a no-op.+ const refreshed = await findPeerSubscription('peer-a', 'series', 's1');+ expect(refreshed.lastPushedHash).toBeFalsy();+ vi.mocked(peerFetch).mockClear();+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });+ const second = await pushRecordToPeer(refreshed);+ 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@@ -2036,6 +2060,21 @@ describe('peerSync', () => {expect(mergeReviewFromSync).not.toHaveBeenCalled();});+ it('returns reviewSyncPending when the bundled review merge throws (so the sender retries)', async () => {+ vi.mocked(mergeReviewFromSync).mockRejectedValueOnce(new Error('disk full'));+ const res = 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',+ });+ // The series/issues merge still succeeded — the push isn't failed — but+ // the sender is told to withhold its hash and retry the review.+ expect(res.reviewSyncPending).toBe(true);+ });+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