Skip to content

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

fix([manuscript-review-sync]): harden review sync against three more cloud-sync edge cases

[._.]/ Adam Eivyc6018fa9750a
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 58a5186093..8d589c8333 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -363,6 +363,21 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
* (chr-/set-/obj-) are sub-records of universes and never standalone, so they
* are skipped without being tracked as missing.
*/
+// Declared manuscript-review files (records/reviews/<seriesId>.json) the manifest
+// says are bundled but aren't yet readable on disk. Parses each (not just
+// existsSync) so a present-but-partial/corrupt file mid-cloud-sync counts as
+// "not ready" and keeps the manifest pending — mirroring readReferencedRecords,
+// where an unparseable record file is treated as missing. Returns the seriesIds
+// still pending; legacy manifests (no reviewRefs) → [].
+async function missingDeclaredReviews(bucketPath, manifest) {
+ const refs = (Array.isArray(manifest.reviewRefs) ? manifest.reviewRefs : []).filter(isSafeRecordId);
+ const checks = await Promise.all(refs.map(async (sid) => {
+ const r = await readJSONFile(join(bucketPath, 'records', 'reviews', `${sid}.json`), null, { logError: false });
+ return r == null ? sid : null;
+ }));
+ return checks.filter(Boolean);
+}
+
async function readReferencedRecords(bucketPath, manifest) {
const records = { series: [], issues: [], universes: [], media: [] };
const missing = [];
@@ -958,10 +973,7 @@ export async function processManifest(bucketId, manifestFilename) {
// would read null, treat it as "no review", and markProcessed — permanently
// dropping the review. Mirror the missingRecords pending gate. Legacy
// manifests have no `reviewRefs` → empty → no wait (back-compat).
- const declaredReviewRefs = Array.isArray(manifest.reviewRefs) ? manifest.reviewRefs : [];
- const missingReviews = declaredReviewRefs.filter(
- (sid) => isSafeRecordId(sid) && !existsSync(join(bucket.path, 'records', 'reviews', `${sid}.json`)),
- );
+ const missingReviews = await missingDeclaredReviews(bucket.path, manifest);
// Always copy assets + media-job records ahead of the merge so canon and
// pipeline records that reference them point at present files. Asset and
@@ -1123,10 +1135,9 @@ export async function promoteInboxItem(bucketId, manifestId) {
});
}
// Same out-of-order delivery guard as the auto-merge path: a declared review
- // file that hasn't landed yet must block the promote, or applyAutoMerge would
- // read null and silently drop the review.
- const missingReviews = (Array.isArray(manifest.reviewRefs) ? manifest.reviewRefs : [])
- .filter((sid) => isSafeRecordId(sid) && !existsSync(join(bucket.path, 'records', 'reviews', `${sid}.json`)));
+ // file that hasn't landed (or is present-but-unparseable) must block the
+ // promote, or applyAutoMerge would read null and silently drop the review.
+ const missingReviews = await missingDeclaredReviews(bucket.path, manifest);
if (missingReviews.length > 0) {
throw Object.assign(new Error(`Manifest reviews are still syncing (${missingReviews.length} missing)`), {
code: 'SHARING_REVIEWS_PENDING',
@@ -1176,6 +1187,15 @@ export async function promoteInboxItem(bucketId, manifestId) {
pendingLegacyCanonFailures: outcome.legacyCanonPendingFailures,
});
}
+ // A transient manuscript-review merge failure must also keep the inbox row —
+ // otherwise the manual promote consumes it while the bundled review silently
+ // never lands (the review has no independent reconciliation cycle).
+ if (outcome.reviewMergeFailures) {
+ throw Object.assign(new Error(`Manuscript-review merge failed for ${outcome.reviewMergeFailures.join(', ')} — retry after resolving the underlying error`), {
+ code: 'SHARING_REVIEW_MERGE_FAILED',
+ reviewMergeFailures: outcome.reviewMergeFailures,
+ });
+ }
// Drop from inbox.
inbox.items.splice(idx, 1);
await writeInbox(bucketId, inbox);
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index b8704e0528..bbd7012a53 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -289,6 +289,58 @@ describe('sharing round-trip', () => {
expect(after.comments).toHaveLength(0);
});
+ it('keeps a manifest pending when a declared review file is present but unparseable', async () => {
+ const bucket = await buckets.createBucket({ name: 'CorruptReviewBucket', path: tempBucket, mode: 'auto-merge' });
+ const s = await series.createSeries({ name: 'Corrupt Review 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);
+ const reviewFile = join(tempBucket, 'records', 'reviews', `${s.id}.json`);
+ const good = readFileSync(reviewFile, 'utf-8');
+ // Simulate a half-synced (truncated) file: present on disk but not valid JSON.
+ writeFileSync(reviewFile, good.slice(0, Math.floor(good.length / 2)));
+ await series.deleteSeries(s.id);
+ simulateRemoteSender(tempBucket, exp.filename);
+
+ const r1 = await importer.processManifest(bucket.id, exp.filename);
+ expect(r1.pending).toBe(true);
+ expect(r1.outcome.pendingReviews).toContain(s.id);
+
+ // The full file finishes syncing → reprocess → it merges.
+ writeFileSync(reviewFile, good);
+ const r2 = await importer.processManifest(bucket.id, exp.filename);
+ expect(r2.pending).toBeFalsy();
+ expect((await manuscriptReview.getReview(s.id)).comments).toHaveLength(1);
+ });
+
+ it('promoteInboxItem keeps the inbox row when the bundled review merge fails', async () => {
+ const bucket = await buckets.createBucket({ name: 'PromoteFailBucket', path: tempBucket, mode: 'inbox' });
+ const s = await series.createSeries({ name: 'Promote 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);
+ simulateRemoteSender(tempBucket, exp.filename);
+ await importer.processManifest(bucket.id, exp.filename); // queues to inbox
+ expect(await importer.listInbox(bucket.id)).toHaveLength(1);
+
+ // Force a transient review-merge failure during the manual promote.
+ const spy = vi.spyOn(manuscriptReview, 'mergeReviewFromSync').mockRejectedValueOnce(new Error('disk full'));
+ await expect(importer.promoteInboxItem(bucket.id, exp.manifestId)).rejects.toMatchObject({
+ code: 'SHARING_REVIEW_MERGE_FAILED',
+ });
+ spy.mockRestore();
+ // Inbox row preserved so the user can re-promote.
+ expect(await importer.listInbox(bucket.id)).toHaveLength(1);
+
+ // Re-promote now succeeds and the review lands.
+ await importer.promoteInboxItem(bucket.id, exp.manifestId);
+ expect((await manuscriptReview.getReview(s.id)).comments).toHaveLength(1);
+ });
+
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' });
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 736a40154a..e596966a65 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -955,6 +955,12 @@ export async function pushRecordToPeer(sub, options = {}) {
}).finally(() => clearTimeout(timeoutId));
};
let res = await postPayload(payload);
+ // Set when the older-peer retry below strips `manuscriptReview`: the retry
+ // succeeds with the review removed, so saving the full-payload hash would
+ // make the next push short-circuit as `unchanged` and never deliver the
+ // review once that peer upgrades. Withhold the hash (like reviewSyncPending)
+ // so the next cycle re-sends.
+ let reviewStrippedForLegacyPeer = false;
// MIXED-VERSION COMPAT: an older receiver's push schema is still `.strict()`
// without a `portosMeta` field, so it 400-rejects our envelope at Zod
// validation BEFORE its schema-version gate code (which doesn't exist on
@@ -986,7 +992,7 @@ export async function pushRecordToPeer(sub, options = {}) {
const stripped = [];
if (mentions('portosMeta') && 'portosMeta' in legacyPayload) { delete legacyPayload.portosMeta; stripped.push('portosMeta'); }
if (mentions('catalogBundle') && 'catalogBundle' in legacyPayload) { delete legacyPayload.catalogBundle; stripped.push('catalogBundle'); }
- if (mentions('manuscriptReview') && 'manuscriptReview' in legacyPayload) { delete legacyPayload.manuscriptReview; stripped.push('manuscriptReview'); }
+ if (mentions('manuscriptReview') && 'manuscriptReview' in legacyPayload) { delete legacyPayload.manuscriptReview; stripped.push('manuscriptReview'); reviewStrippedForLegacyPeer = true; }
// The series + issues still land; on a pre-feature peer the review simply
// doesn't propagate until it upgrades, and a re-push after it upgrades
// re-includes the stripped key(s).
@@ -1066,7 +1072,7 @@ export async function pushRecordToPeer(sub, options = {}) {
// 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;
+ const reviewSyncPending = body?.reviewSyncPending === true || reviewStrippedForLegacyPeer;
// 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
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index a6ba1f17be..0bc5ad6a2e 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2939,6 +2939,11 @@ describe('peerSync', () => {
expect(retryPayload.portosMeta).toBeDefined();
expect(retryPayload.record.id).toBe('s1');
expect(retryPayload.issues).toHaveLength(1);
+ // Hash withheld so the review re-sends once the peer upgrades (the
+ // retry landed with the review stripped, so saving the full-payload
+ // hash would short-circuit the next push as 'unchanged').
+ const refreshed = await findPeerSubscription('peer-a', 'series', 's1');
+ expect(refreshed.lastPushedHash).toBeFalsy();
});
it('does NOT retry on a 400 whose validation error is unrelated to portosMeta', async () => {