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([issue-1348]): wire the reverse-outline sibling doc into cross-install peer sync
[._.]/ Adam Eivyaeaba5bf20ed
diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 6308b0d814..3511b0b7a2 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -132,11 +132,29 @@ const manuscriptReviewField = {}).passthrough()).max(5000),}).passthrough().optional(),};+// Optional bundled reverse-outline sibling doc (#1348) — a series push carries+// the scene-by-scene segmentation (data/pipeline-series/{id}/reverse-outline.json)+// so a regenerate-only change propagates via the per-record push pipeline. ONLY+// valid on series pushes. `.passthrough()` on the doc + each scene/plotline+// (same rationale as manuscriptReview) so a newer sender that adds a field+// doesn't 400 at this receiver BEFORE its merge — `sanitizeSyncedOutline`+// clamps/drops everything on apply. Arrays are bounded so the payload can't+// force unbounded work (the sanitizer caps them again at 600 scenes / 10 plotlines).+const reverseOutlineField = {+ reverseOutline: z.object({+ schemaVersion: z.number().int().min(0).max(1_000_000).optional(),+ status: z.string().max(40).optional(),+ generatedAt: z.string().max(64).optional(),+ plotlines: z.array(z.object({}).passthrough()).max(64).optional(),+ scenes: z.array(z.object({}).passthrough()).max(2000).optional(),+ }).passthrough().optional(),+};const seriesPushSchema = z.object({kind: z.literal('series'),...peerSyncPushBase,...linkedCollectionField,...manuscriptReviewField,+ ...reverseOutlineField,issues: z.array(peerWireRecordSchema).max(1000).optional(),}).strict();const mediaCollectionPushSchema = z.object({diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 50db125120..a2694f7258 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -110,6 +110,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// 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.+ // ALSO not bumped for the reverse-outline sibling doc (#1348), bundled on+ // series pushes/exports as `data/pipeline-series/{id}/reverse-outline.json`+ // via a dedicated `reverseOutline` payload key. Identical reasoning to the+ // manuscript-review note above: it's a separate doc (not a series field), so+ // an older peer never round-trips it through `sanitizeSeries`; it's additive ++ // gracefully degrading (a pre-#1348 receiver ignores the unknown key and ships+ // none back, so the newer peer's `if (reverseOutline)` receive guard is a+ // no-op and the local outline is preserved); and the sender's legacy-strip+ // retry drops the key so the record/issues still land. Whole-doc LWW on+ // `generatedAt` means there's no per-field strip-then-LWW-back corruption to+ // gate against. The FIRST incompatible outline-doc shape change (reverseOutline.js+ // SCHEMA_VERSION 1→2) MUST introduce a gate then, same as the review above.mediaCollections: 1,// v1 = author personas (PostgreSQL `authors` table) federated via the// per-record peer-sync push pipeline (record kind `author`, sync categorydiff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.jsindex f1b83b47ef..2ba863fd39 100644--- a/server/services/pipeline/reverseOutline.js+++ b/server/services/pipeline/reverseOutline.js@@ -30,6 +30,7 @@ import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/coimport { seriesStore, getSeries } from './series.js';import { getSeriesCanon } from './seriesCanon.js';import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';+import { emitRecordUpdated } from '../sharing/recordEvents.js';const STAGE = 'pipeline-reverse-outline';@@ -50,6 +51,12 @@ const ANCHOR_MAX = 240;const NAME_MAX = 80;const SETTING_MAX = 120;const PLOTLINE_ID_MAX = 40;+// Series issue ids are `iss-<uuid>`; the content hash is a 64-char hex digest.+// Used only by the peer-sync sanitizer, which trusts the sender's resolved+// refs rather than recomputing them against a manuscript the receiver may lack.+const ISSUE_ID_MAX = 64;+const HASH_MAX = 128;+const PROVIDER_MAX = 120;// Floor on manuscript chars sent to the model — scaled UP to the target model's// context window in generateReverseOutline (mirrors editorialAnalysis), so a@@ -280,6 +287,13 @@ export async function generateReverseOutline(seriesId, { providerId, model, forc...body,};await queueOutlineWrite(seriesId, () => writeOutline(seriesId, outline));+ // The outline is a sibling of the series record, so regenerating it doesn't+ // move the series `index.json` — emit a series `updated` event so the+ // peer-sync push + bucket re-export fire (both hash the outline into their+ // payload, defeating the lastPushedHash short-circuit). Skipped on the sync+ // RECEIVE path (`mergeOutlineFromSync`) to avoid an echo loop. Mirrors+ // manuscriptReview.seedReviewFromFindings.+ emitRecordUpdated('series', seriesId);console.log(`🧭 reverse outline: series=${String(seriesId).slice(0, 12)} plotlines=${body.plotlines.length} scenes=${body.scenes.length}${truncated ? ' (truncated)' : ''}`);return { ...outline, stale: false };}@@ -331,6 +345,121 @@ export async function getSceneSegmentation(seriesId) {};}+// ---------------------------------------------------------------------------+// Cross-install peer sync (#1348) — the outline rides the series push/export as+// a sibling doc (same as manuscript-review), so a regenerate-only change still+// propagates even though it doesn't move the series record. Unlike the review's+// per-comment LWW, the outline is a single regenerated document, so the merge+// is whole-doc LWW on `generatedAt`.+// ---------------------------------------------------------------------------++/**+ * Lightweight accessor for the push/export bundle: the raw stored outline doc+ * (or null when none exists), WITHOUT the staleness recompute getReverseOutline+ * does (that re-reads the whole manuscript). Only a `complete` outline is worth+ * propagating — callers gate on `status === 'complete'`.+ */+export async function getStoredOutline(seriesId) {+ assertValidSeriesId(seriesId);+ return readOutline(seriesId);+}++// Sanitize one scene arriving over peer sync. Unlike sanitizeScene (which+// rebuilds issueId/issueTitle from the LOCAL manuscript via byNumber), this+// trusts + clamps the issue refs the sender already resolved — the receiving+// peer may not hold the drafted manuscript, and the issues sync separately.+function sanitizeSyncedScene(raw, idx, plotlineIds) {+ if (!raw || typeof raw !== 'object') return null;+ const summary = clampStr(raw.summary, SUMMARY_MAX);+ const heading = clampStr(raw.heading, LABEL_MAX);+ if (!summary && !heading) return null;+ const primary = clampStr(raw.plotlineId, PLOTLINE_ID_MAX);+ const secondary = clampStr(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);+ return {+ id: `scene-${String(idx + 1).padStart(3, '0')}`,+ sequence: idx,+ issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,+ issueId: clampStr(raw.issueId, ISSUE_ID_MAX) || null,+ issueTitle: clampStr(raw.issueTitle, LABEL_MAX),+ heading: heading || summary.slice(0, LABEL_MAX),+ summary,+ anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX),+ povCharacter: clampStr(raw.povCharacter, NAME_MAX) || null,+ plotlineId: plotlineIds.has(primary) ? primary : UNASSIGNED_PLOTLINE.id,+ secondaryPlotlineId: secondary && plotlineIds.has(secondary) && secondary !== primary ? secondary : null,+ components: sanitizeComponents(raw.components),+ setting: clampStr(raw.setting, SETTING_MAX),+ charactersPresent: Array.isArray(raw.charactersPresent)+ ? raw.charactersPresent.map((n) => clampStr(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)+ : [],+ };+}++/**+ * Shape a full stored outline document arriving over peer sync into the local+ * stored shape. Returns null for anything that isn't a complete, timestamped+ * outline — only complete outlines propagate, and `generatedAt` is the LWW+ * clock. Defense-in-depth on top of the peer-sync Zod schema: never trust a+ * peer's payload past the wire shape. Exported via __testing.+ */+function sanitizeSyncedOutline(raw) {+ if (!raw || typeof raw !== 'object') return null;+ if (raw.status !== 'complete') return null;+ const generatedAt = typeof raw.generatedAt === 'string' ? raw.generatedAt : null;+ if (!generatedAt || Number.isNaN(new Date(generatedAt).getTime())) return null;+ const plotlines = sanitizePlotlines(raw.plotlines);+ const plotlineIds = new Set(plotlines.map((pl) => pl.id));+ const scenes = (Array.isArray(raw.scenes) ? raw.scenes : [])+ .slice(0, MAX_SCENES)+ .map((s, idx) => sanitizeSyncedScene(s, idx, plotlineIds))+ .filter(Boolean);+ // Re-append the synthetic catch-all only if a scene landed on it and the+ // sender didn't already include the row (mirrors sanitizeOutline).+ if (scenes.some((s) => s.plotlineId === UNASSIGNED_PLOTLINE.id) && !plotlineIds.has(UNASSIGNED_PLOTLINE.id)) {+ plotlines.push({ ...UNASSIGNED_PLOTLINE });+ }+ return {+ schemaVersion: SCHEMA_VERSION,+ status: 'complete',+ sourceContentHash: clampStr(raw.sourceContentHash, HASH_MAX) || null,+ truncated: raw.truncated === true,+ providerId: clampStr(raw.providerId, PROVIDER_MAX) || null,+ model: clampStr(raw.model, PROVIDER_MAX) || null,+ runId: clampStr(raw.runId, PROVIDER_MAX) || null,+ generatedAt,+ plotlines,+ scenes,+ };+}++/**+ * Merge a reverse outline received from a peer, whole-doc LWW on `generatedAt`+ * (strict-newer wins, so an equal-clock echo is a skip — matching+ * mergeReviewFromSync's `>` guard). Returns the doc now on disk (local kept on a+ * stale/equal push, remote adopted on a newer one) or null when the payload+ * isn't a propagatable outline. Does NOT emit a record event (the local write+ * paths do) so a received outline can't echo back into a push loop. Serializes+ * on the same per-series tail as local writes.+ */+export async function mergeOutlineFromSync(seriesId, remoteOutline) {+ assertValidSeriesId(seriesId);+ const remote = sanitizeSyncedOutline(remoteOutline);+ if (!remote) return null;+ return queueOutlineWrite(seriesId, async () => {+ const local = await readOutline(seriesId);+ const localRaw = local && typeof local.generatedAt === 'string'+ ? new Date(local.generatedAt).getTime()+ : NaN;+ // A corrupt/missing local clock sorts oldest so a valid remote always wins.+ const localTime = Number.isNaN(localRaw) ? -Infinity : localRaw;+ const remoteTime = new Date(remote.generatedAt).getTime();+ if (!(remoteTime > localTime)) return local;+ const next = { ...remote, seriesId };+ await writeOutline(seriesId, next);+ return next;+ });+}+// ---------------------------------------------------------------------------// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),// the same factory backing manuscriptCompletenessRunner + editorial/checkRunner.@@ -385,4 +514,4 @@ export function startReverseOutlineRun(seriesId, options = {}) {}// Export internals for tests.-export const __testing = { sanitizeOutline, sanitizePlotlines, sanitizeScene, isOutlineStale, contentHash, runs: runner.runs };+export const __testing = { sanitizeOutline, sanitizePlotlines, sanitizeScene, sanitizeSyncedOutline, sanitizeSyncedScene, isOutlineStale, contentHash, runs: runner.runs };diff --git a/server/services/pipeline/reverseOutline.test.js b/server/services/pipeline/reverseOutline.test.jsindex c76a80884e..dcea0c9a3f 100644--- a/server/services/pipeline/reverseOutline.test.js+++ b/server/services/pipeline/reverseOutline.test.js@@ -45,6 +45,12 @@ vi.mock('./arcPlanner.js', () => ({sectionsCorpus: (sections) => sections.map((s) => `# Issue ${s.number}\n\n${s.content}`).join('\n\n---\n\n'),}));+// Record-event emitter — spied so we can assert generate emits a series+// `updated` event (firing peer-sync) while mergeOutlineFromSync stays silent+// (the echo-loop guard).+const { emitRecordUpdatedMock } = vi.hoisted(() => ({ emitRecordUpdatedMock: vi.fn() }));+vi.mock('../sharing/recordEvents.js', () => ({ emitRecordUpdated: emitRecordUpdatedMock }));+const svc = await import('./reverseOutline.js');const SERIES_ID = 'ser-abc';@@ -70,6 +76,7 @@ function cannedOutline() {beforeEach(() => {fileStore.clear();+ emitRecordUpdatedMock.mockClear();llmQueue.length = 0;llmCalls.length = 0;sectionsFixture = [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'It was dusk on the pier.' }];@@ -185,3 +192,96 @@ describe('sanitizeOutline (pure)', () => {expect(plotlines.map((p) => p.id)).not.toContain('_unassigned');});});++describe('emits a series updated event on generate (peer-sync trigger)', () => {+ it('fires emitRecordUpdated after a successful generation', async () => {+ llmQueue.push(cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});+ expect(emitRecordUpdatedMock).toHaveBeenCalledWith('series', SERIES_ID);+ });++ it('does not emit again when returning a cached (unchanged-manuscript) outline', async () => {+ llmQueue.push(cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});+ emitRecordUpdatedMock.mockClear();+ // Same manuscript hash → cached short-circuit, no write, no emit.+ await svc.generateReverseOutline(SERIES_ID, {});+ expect(emitRecordUpdatedMock).not.toHaveBeenCalled();+ });+});++describe('sanitizeSyncedOutline (peer sync)', () => {+ const { sanitizeSyncedOutline } = svc.__testing;++ it('returns null for a non-complete or untimestamped outline', () => {+ expect(sanitizeSyncedOutline({ status: 'none', generatedAt: '2026-06-02T00:00:00Z' })).toBeNull();+ expect(sanitizeSyncedOutline({ status: 'complete' })).toBeNull();+ expect(sanitizeSyncedOutline({ status: 'complete', generatedAt: 'not-a-date' })).toBeNull();+ expect(sanitizeSyncedOutline(null)).toBeNull();+ });++ it('preserves the sender-resolved issue refs instead of recomputing them', () => {+ // Unlike sanitizeOutline (byNumber-driven), the synced sanitizer trusts the+ // issueId/issueTitle the sender already resolved — the receiver may not hold+ // the manuscript.+ const out = sanitizeSyncedOutline({+ status: 'complete', generatedAt: '2026-06-02T00:00:00Z',+ plotlines: [{ id: 'A', label: 'Main', kind: 'main' }],+ scenes: [{ summary: 'A beat.', issueNumber: 3, issueId: 'iss-xyz', issueTitle: 'Chapter Three', plotlineId: 'A' }],+ });+ expect(out.scenes[0].issueId).toBe('iss-xyz');+ expect(out.scenes[0].issueTitle).toBe('Chapter Three');+ expect(out.scenes[0].issueNumber).toBe(3);+ });++ it('drops empty scenes and maps unknown plotlines to _unassigned', () => {+ const out = sanitizeSyncedOutline({+ status: 'complete', generatedAt: '2026-06-02T00:00:00Z',+ plotlines: [{ id: 'A', label: 'Main', kind: 'main' }],+ scenes: [{ summary: 'kept', plotlineId: 'Z' }, { nonsense: true }],+ });+ expect(out.scenes).toHaveLength(1);+ expect(out.scenes[0].plotlineId).toBe('_unassigned');+ expect(out.plotlines.map((p) => p.id)).toContain('_unassigned');+ });+});++describe('mergeOutlineFromSync (whole-doc LWW)', () => {+ const remote = (generatedAt, summary = 'remote') => ({+ status: 'complete', generatedAt,+ plotlines: [{ id: 'A', label: 'Main', kind: 'main' }],+ scenes: [{ summary, plotlineId: 'A' }],+ });++ it('adopts a remote outline when none exists locally', async () => {+ const merged = await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-02T00:00:00Z'));+ expect(merged.scenes[0].summary).toBe('remote');+ expect(merged.seriesId).toBe(SERIES_ID);+ // Receive path must NOT emit (echo-loop guard).+ expect(emitRecordUpdatedMock).not.toHaveBeenCalled();+ });++ it('adopts a strictly-newer remote over an older local outline', async () => {+ await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-02T00:00:00Z', 'old'));+ const merged = await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-03T00:00:00Z', 'new'));+ expect(merged.scenes[0].summary).toBe('new');+ });++ it('keeps the local outline on an equal-clock echo (strict-newer wins)', async () => {+ await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-02T00:00:00Z', 'first'));+ const merged = await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-02T00:00:00Z', 'echo'));+ expect(merged.scenes[0].summary).toBe('first');+ });++ it('keeps the local outline when the remote is older', async () => {+ await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-03T00:00:00Z', 'newer-local'));+ const merged = await svc.mergeOutlineFromSync(SERIES_ID, remote('2026-06-01T00:00:00Z', 'stale-remote'));+ expect(merged.scenes[0].summary).toBe('newer-local');+ });++ it('returns null and writes nothing for a non-propagatable (non-complete) remote', async () => {+ const merged = await svc.mergeOutlineFromSync(SERIES_ID, { status: 'none', generatedAt: '2026-06-02T00:00:00Z' });+ expect(merged).toBeNull();+ expect(await svc.getStoredOutline(SERIES_ID)).toBeNull();+ });+});diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsindex 1ff04f4da8..b1ea194c1b 100644--- a/server/services/sharing/buckets.js+++ b/server/services/sharing/buckets.js@@ -106,8 +106,8 @@ export function bucketBlobSidecarPath(bucketPath, hash) {export function bucketBlobIndexPath(bucketPath) { return join(bucketBlobsDir(bucketPath), '.index.json'); }export function imageSidecarName(filename) { return filename.replace(IMAGE_EXT_RE, '') + '.metadata.json'; }-// Per-bucket record store — series/issues/universes/media/reviews JSON live-// under `records/<type>/<id>.json`. Unlike the blob helpers above, these do+// Per-bucket record store — series/issues/universes/media/reviews/outlines JSON+// live under `records/<type>/<id>.json`. Unlike the blob helpers above, these do// NOT validate `id`: every callsite supplies an id that's either locally// authored (the exporter) or already screened by `isSafeRecordId` (the// importer) before it reaches the path. Keeping them as plain joins preserves@@ -145,6 +145,7 @@ export async function ensureBucketLayout(bucket) {await ensureDir(bucketRecordsDir(base, 'universes'));await ensureDir(bucketRecordsDir(base, 'media'));await ensureDir(bucketRecordsDir(base, 'reviews'));+ await ensureDir(bucketRecordsDir(base, 'outlines'));await ensureDir(join(base, 'assets', 'images'));await ensureDir(join(base, 'assets', 'videos'));await ensureDir(join(base, 'assets', 'blobs'));diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 95b3a755fe..36b02869c4 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -26,6 +26,7 @@ import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.jimport { listSeries, getSeries } from '../pipeline/series.js';import { listIssues } from '../pipeline/issues.js';import { getReview } from '../pipeline/manuscriptReview.js';+import { getStoredOutline } from '../pipeline/reverseOutline.js';import { getUniverse } from '../universeBuilder.js';import { findCollectionByUniverseId, findCollectionBySeriesId } from '../mediaCollections.js';import { getJob } from '../mediaJobQueue/index.js';@@ -426,6 +427,17 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {reviewRefs.push(series.id);}+ // Bundle the reverse-outline sibling doc (#1348) on the same terms as the+ // review: keyed by seriesId under records/outlines/, NOT in `recordIds` (read+ // by seriesId after the series merges). Only a `complete` outline is shipped;+ // an importer that finds no file leaves the local outline untouched.+ const outline = await getStoredOutline(series.id).catch(() => null);+ const outlineRefs = [];+ if (outline && outline.status === 'complete') {+ await atomicWrite(bucketRecordPath(bucket.path, 'outlines', series.id), outline);+ outlineRefs.push(series.id);+ }+for (const issue of issues) {recordIds.push(issue.id);const stamped = stampOrigin(issue, { bucket, source, sourceBio, manifestId });@@ -471,7 +483,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {return [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];});- const manifest = { ...manifestStub, recordIds, assetRefs, reviewRefs };+ const manifest = { ...manifestStub, recordIds, assetRefs, reviewRefs, outlineRefs };const filename = await writeManifest(bucket.path, manifest);await pruneAfterExport(bucket, senderInstanceId);return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 40afcca1e5..9ca68363ec 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -34,6 +34,7 @@ import { PORTOS_SCHEMA_VERSIONS, RECORD_KIND_SCHEMA_CATEGORIES, compareSchemaVerimport { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';import { mergeReviewFromSync } from '../pipeline/manuscriptReview.js';+import { mergeOutlineFromSync } from '../pipeline/reverseOutline.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';@@ -378,6 +379,20 @@ async function missingDeclaredReviews(bucketPath, manifest) {return checks.filter(Boolean);}+// Declared reverse-outline files (records/outlines/<seriesId>.json) the manifest+// says are bundled but aren't yet readable on disk (#1348). Same parse-not-+// existsSync semantics as missingDeclaredReviews: a present-but-corrupt file mid-+// cloud-sync counts as "not ready" and keeps the manifest pending. Legacy+// manifests (no outlineRefs) → [].+async function missingDeclaredOutlines(bucketPath, manifest) {+ const refs = (Array.isArray(manifest.outlineRefs) ? manifest.outlineRefs : []).filter(isSafeRecordId);+ const checks = await Promise.all(refs.map(async (sid) => {+ const r = await readJSONFile(bucketRecordPath(bucketPath, 'outlines', sid), 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 = [];@@ -681,6 +696,26 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =}}+ // Merge the bundled reverse-outline sibling doc (#1348), whole-doc LWW on+ // generatedAt. Same authoritative-refs + pending-on-failure contract as the+ // review above: `outlineRefs` is authoritative (a stale lingering file from a+ // prior export is ignored unless THIS manifest declared it), and a merge+ // failure surfaces as a retryable pending condition rather than silently+ // advancing the cursor. `mergeOutlineFromSync` emits no record event → no+ // re-export loop.+ const declaredOutlines = new Set((Array.isArray(manifest.outlineRefs) ? manifest.outlineRefs : []).filter(isSafeRecordId));+ const outlineMergeFailures = [];+ for (const s of records.series) {+ if (skipSeriesMerge.has(s.id) || !declaredOutlines.has(s.id)) continue;+ const outline = await readJSONFile(bucketRecordPath(bucket.path, 'outlines', s.id), null, { logError: false });+ if (outline) {+ await mergeOutlineFromSync(s.id, outline).catch((err) => {+ console.log(`⚠️ sharing.importer: reverse-outline merge for ${s.id} failed: ${err.message}`);+ outlineMergeFailures.push(s.id);+ });+ }+ }+// 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 alongside@@ -743,6 +778,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =legacyCanonPendingFailures: legacyCanonPendingFailures.length > 0 ? legacyCanonPendingFailures : null,recordImportFailures: failedInserts.length > 0 ? failedInserts : null,reviewMergeFailures: reviewMergeFailures.length > 0 ? reviewMergeFailures : null,+ outlineMergeFailures: outlineMergeFailures.length > 0 ? outlineMergeFailures : null,adoptedSubscription: adoptedSubscription? { id: adoptedSubscription.id, bucketId: adoptedSubscription.bucketId, recordKind: adoptedSubscription.recordKind, recordId: adoptedSubscription.recordId }: null,@@ -983,6 +1019,9 @@ export async function processManifest(bucketId, manifestFilename) {// dropping the review. Mirror the missingRecords pending gate. Legacy// manifests have no `reviewRefs` → empty → no wait (back-compat).const missingReviews = await missingDeclaredReviews(bucket.path, manifest);+ // Declared reverse-outline files not yet on disk (#1348) — same out-of-order+ // cloud-delivery wait as missingReviews. Legacy manifests → empty → no wait.+ const missingOutlines = await missingDeclaredOutlines(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@@ -1013,6 +1052,7 @@ export async function processManifest(bucketId, manifestFilename) {const legacyCanonPendingFailures = outcome?.legacyCanonPendingFailures || null;const recordImportFailures = outcome?.recordImportFailures || null;const reviewMergeFailures = outcome?.reviewMergeFailures || null;+ const outlineMergeFailures = outcome?.outlineMergeFailures || 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@@ -1023,18 +1063,20 @@ 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 || missingReviews.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures || recordImportFailures || reviewMergeFailures) {+ if (assetCopy.missing.length > 0 || missingRecords.length > 0 || missingReviews.length > 0 || missingOutlines.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures || recordImportFailures || reviewMergeFailures || outlineMergeFailures) {if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;if (missingReviews.length > 0) outcome.pendingReviews = missingReviews;+ if (missingOutlines.length > 0) outcome.pendingOutlines = missingOutlines;if (collectionPendingUniverse) outcome.pendingCollectionUniverse = collectionPendingUniverse;if (collectionPendingSeries) outcome.pendingCollectionSeries = collectionPendingSeries;if (legacyCanonPendingUniverses) outcome.pendingLegacyCanonUniverses = legacyCanonPendingUniverses;if (legacyCanonPendingFailures) outcome.pendingLegacyCanonFailures = legacyCanonPendingFailures;if (recordImportFailures) outcome.pendingRecordImportFailures = recordImportFailures;if (reviewMergeFailures) outcome.pendingReviewMergeFailures = reviewMergeFailures;+ if (outlineMergeFailures) outcome.pendingOutlineMergeFailures = outlineMergeFailures;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}${missingReviews.length > 0 ? ` waitingForReviews=${missingReviews.length}` : ''}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}${legacyCanonPendingFailures ? ` legacyCanonFailures=${legacyCanonPendingFailures.join(',')}` : ''}${recordImportFailures ? ` recordImportFailures=${recordImportFailures.join(',')}` : ''}${reviewMergeFailures ? ` reviewMergeFailures=${reviewMergeFailures.join(',')}` : ''}`);+ console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${missingReviews.length > 0 ? ` waitingForReviews=${missingReviews.length}` : ''}${missingOutlines.length > 0 ? ` waitingForOutlines=${missingOutlines.length}` : ''}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}${legacyCanonPendingFailures ? ` legacyCanonFailures=${legacyCanonPendingFailures.join(',')}` : ''}${recordImportFailures ? ` recordImportFailures=${recordImportFailures.join(',')}` : ''}${reviewMergeFailures ? ` reviewMergeFailures=${reviewMergeFailures.join(',')}` : ''}${outlineMergeFailures ? ` outlineMergeFailures=${outlineMergeFailures.join(',')}` : ''}`);return { processed: true, pending: true, manifest, outcome };}await markProcessed(bucketId, manifestFilename, manifest.id);@@ -1153,6 +1195,14 @@ export async function promoteInboxItem(bucketId, manifestId) {missingReviews,});}+ // Same out-of-order delivery guard for the reverse-outline sibling doc (#1348).+ const missingOutlines = await missingDeclaredOutlines(bucket.path, manifest);+ if (missingOutlines.length > 0) {+ throw Object.assign(new Error(`Manifest outlines are still syncing (${missingOutlines.length} missing)`), {+ code: 'SHARING_OUTLINES_PENDING',+ missingOutlines,+ });+ }await mergeMediaJobRecords(bucket.path, manifest.recordIds);const availableAssetKeys = new Set(assetCopy.available.map((ref) => `${ref.kind}:${ref.ref}`));const outcome = await applyAutoMerge(bucket, manifest, records, { availableAssetKeys });diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex c83ab20c58..553a4ab9f8 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -62,6 +62,19 @@ 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');+const reverseOutline = await import('../pipeline/reverseOutline.js');++// Seed a stored reverse outline directly (generateReverseOutline needs an LLM).+// Writes the sibling doc at the same path reverseOutline.js reads/writes.+function seedOutline(seriesId, generatedAt = '2026-06-02T00:00:00Z', summary = 'Opening beat') {+ const dir = series.seriesStore().recordDir(seriesId);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'reverse-outline.json'), JSON.stringify({+ seriesId, schemaVersion: 1, status: 'complete', generatedAt,+ plotlines: [{ id: 'A', label: 'A-plot', kind: 'main', color: '#3b82f6' }],+ scenes: [{ id: 'scene-001', sequence: 0, summary, plotlineId: 'A', issueId: 'iss-1', issueTitle: 'One', issueNumber: 1 }],+ }));+}// Rewrite a manifest's senderInstanceId on disk so the importer sees it as// coming from a remote peer. The mocked `getInstanceId` returns the same@@ -236,6 +249,79 @@ describe('sharing round-trip', () => {expect(existsSync(join(tempBucket, 'records', 'reviews', `${s.id}.json`))).toBe(false);});+ it('round-trips the reverse outline with a series export/import', async () => {+ const bucket = await buckets.createBucket({ name: 'OutlineBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Outline Series', logline: 'A' });+ await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });+ seedOutline(s.id);+ expect((await reverseOutline.getStoredOutline(s.id)).status).toBe('complete');++ const exp = await exporter.exportSeries(s.id, bucket.id);+ // The outline rides under records/outlines/<seriesId>.json, NOT in recordIds.+ expect(existsSync(join(tempBucket, 'records', 'outlines', `${s.id}.json`))).toBe(true);++ await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);+ await importer.processManifest(bucket.id, exp.filename);++ const restored = await reverseOutline.getStoredOutline(s.id);+ expect(restored.status).toBe('complete');+ expect(restored.scenes[0].summary).toBe('Opening beat');+ expect(restored.scenes[0].issueId).toBe('iss-1');+ });++ it('skips writing an outline file when the series has no complete outline', async () => {+ const bucket = await buckets.createBucket({ name: 'NoOutlineBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'No Outline Series', logline: 'A' });+ await exporter.exportSeries(s.id, bucket.id);+ expect(existsSync(join(tempBucket, 'records', 'outlines', `${s.id}.json`))).toBe(false);+ });++ it('keeps a manifest pending when a declared outline file has not synced yet (out-of-order delivery)', async () => {+ const bucket = await buckets.createBucket({ name: 'OutlineLagBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Outline Lag Series', logline: 'A' });+ await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });+ seedOutline(s.id);+ const exp = await exporter.exportSeries(s.id, bucket.id);+ const outlineFile = join(tempBucket, 'records', 'outlines', `${s.id}.json`);+ expect(existsSync(outlineFile)).toBe(true);++ // Manifest + series arrive before the outline file (cloud relay reorders).+ const stashed = readFileSync(outlineFile, 'utf-8');+ rmSync(outlineFile);+ 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.pendingOutlines).toContain(s.id);++ writeFileSync(outlineFile, stashed);+ const r2 = await importer.processManifest(bucket.id, exp.filename);+ expect(r2.pending).toBeFalsy();+ expect((await reverseOutline.getStoredOutline(s.id)).status).toBe('complete');+ });++ it('keeps a manifest retryable when the bundled outline merge fails (no silent drop)', async () => {+ const bucket = await buckets.createBucket({ name: 'OutlineFailBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Outline Fail Series', logline: 'A' });+ await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });+ seedOutline(s.id);+ const exp = await exporter.exportSeries(s.id, bucket.id);+ await series.deleteSeries(s.id);++ const spy = vi.spyOn(reverseOutline, 'mergeOutlineFromSync').mockRejectedValueOnce(new Error('disk full'));+ simulateRemoteSender(tempBucket, exp.filename);+ const r1 = await importer.processManifest(bucket.id, exp.filename);+ expect(r1.pending).toBe(true);+ expect(r1.outcome.pendingOutlineMergeFailures).toContain(s.id);+ spy.mockRestore();++ const r2 = await importer.processManifest(bucket.id, exp.filename);+ expect(r2.pending).toBeFalsy();+ expect((await reverseOutline.getStoredOutline(s.id)).status).toBe('complete');+ });+it('keeps a manifest pending when a declared review file has not synced yet (out-of-order delivery)', async () => {const bucket = await buckets.createBucket({ name: 'ReviewLagBucket', path: tempBucket, mode: 'auto-merge' });const s = await series.createSeries({ name: 'Review Lag Series', logline: 'A' });diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex cca64d3d29..11ea8c74c8 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -144,7 +144,7 @@ export function hasBeenProcessed(cursor, manifestFilename, manifestId = null) {* content-changes re-process correctly.*/export function buildManifest({- kind, senderInstanceId, source, sourceBio, recordIds, assetRefs, reviewRefs,+ kind, senderInstanceId, source, sourceBio, recordIds, assetRefs, reviewRefs, outlineRefs,bucketId, bucketName, note, producedByVersion, subscription, collection,portosSchemaVersions,}) {@@ -187,6 +187,12 @@ export function buildManifest({// (cloud-relayed buckets deliver files out of order). Absent on legacy// manifests → importer treats as "no declared reviews".reviewRefs: Array.isArray(reviewRefs) ? reviewRefs : [],+ // Series ids whose reverse-outline sibling doc (records/outlines/<id>.json)+ // is bundled (#1348). Same out-of-band-by-seriesId rationale as reviewRefs:+ // the outline has no record id of its own, so the importer waits for the+ // declared file before markProcessed (cloud-relayed buckets deliver out of+ // order). Absent on legacy manifests → importer treats as "no outlines".+ outlineRefs: Array.isArray(outlineRefs) ? outlineRefs : [],// Optional payload for universe/series shares — the linked media// collection so recipients gain the same set of generated images and// the link is restored on their side. Either `universeId` (universe-diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 49e8c123df..00f9ee8caa 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -951,6 +951,7 @@ export async function pushRecordToPeer(sub, options = {}) {issues: payload.issues ?? null,linkedCollection: payload.linkedCollection ?? null,manuscriptReview: payload.manuscriptReview ?? null,+ reverseOutline: payload.reverseOutline ?? null,assetManifest: payload.assetManifest ?? [],});if (sub.lastPushedHash && sub.lastPushedHash === hash) {@@ -983,6 +984,10 @@ export async function pushRecordToPeer(sub, options = {}) {// review once that peer upgrades. Withhold the hash (like reviewSyncPending)// so the next cycle re-sends.let reviewStrippedForLegacyPeer = false;+ // Same as reviewStrippedForLegacyPeer, for the bundled reverse-outline doc —+ // a pre-#1348 peer's strict series schema rejects the `reverseOutline` key, so+ // the retry strips it and we withhold the hash to re-send once it upgrades.+ let outlineStrippedForLegacyPeer = 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@@ -1015,8 +1020,8 @@ export async function pushRecordToPeer(sub, options = {}) {const mentions = (key) => details.some((d) => new RegExp(key).test(`${d?.path || ''} ${d?.message || ''}`));if (isValidationError- && (payload.portosMeta || payload.catalogBundle || payload.manuscriptReview)- && (mentions('portosMeta') || mentions('catalogBundle') || mentions('manuscriptReview'))+ && (payload.portosMeta || payload.catalogBundle || payload.manuscriptReview || payload.reverseOutline)+ && (mentions('portosMeta') || mentions('catalogBundle') || mentions('manuscriptReview') || mentions('reverseOutline'))) {// (1) UNKNOWN ENVELOPE KEY — the peer recognizes the record `kind` but its// `.strict()` schema predates a newer top-level key we sent. Strip whichever@@ -1027,6 +1032,7 @@ export async function pushRecordToPeer(sub, options = {}) {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'); reviewStrippedForLegacyPeer = true; }+ if (mentions('reverseOutline') && 'reverseOutline' in legacyPayload) { delete legacyPayload.reverseOutline; stripped.push('reverseOutline'); outlineStrippedForLegacyPeer = true; }console.log(`ℹ️ peerSync: ${peer.name || peer.instanceId} rejected newer envelope key(s) ${stripped.join(', ')} — retrying push without them`,);@@ -1125,6 +1131,11 @@ export async function pushRecordToPeer(sub, options = {}) {// 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 || reviewStrippedForLegacyPeer;+ // OUTLINE-STRANDED GUARD: same as the review above — the receiver merged the+ // record/issues but its bundled reverse-outline merge threw (or we stripped+ // the key for a pre-#1348 peer). The outline has no independent reconciliation+ // path, so withhold lastPushedHash to re-send next cycle.+ const outlineSyncPending = body?.outlineSyncPending === true || outlineStrippedForLegacyPeer;// 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@@ -1134,7 +1145,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 || reviewSyncPending) ? null : hash, { confirmedAtMs: Date.now() });+ await persistPushSuccess(sub.id, (missingCount > 0 || reviewSyncPending || outlineSyncPending) ? null : hash, { confirmedAtMs: Date.now() });if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});}@@ -1363,6 +1374,17 @@ async function buildPushPayload(sub, sourceInstanceId) {: await import('../pipeline/manuscriptReview.js').then(({ getReview }) => getReview(sub.recordId)).catch(() => null);+ // Bundle the reverse-outline sibling doc (the scene-by-scene segmentation)+ // on the same terms as the review above: a regenerate-only change doesn't+ // move the series record, so without bundling it the per-record push would+ // short-circuit and the receiver's outline would diverge. Only a `complete`+ // outline is worth shipping. Skip for tombstones. Dynamic import keeps+ // reverseOutline's arcPlanner graph off peerSync's boot load path.+ const reverseOutline = record.deleted === true+ ? null+ : await import('../pipeline/reverseOutline.js')+ .then(({ getStoredOutline }) => getStoredOutline(sub.recordId))+ .catch(() => null);return {kind: 'series',record: sanitized,@@ -1372,6 +1394,7 @@ async function buildPushPayload(sub, sourceInstanceId) {portosMeta,...(linkedCollection ? { linkedCollection } : {}),...(manuscriptReview && manuscriptReview.comments?.length ? { manuscriptReview } : {}),+ ...(reverseOutline && reverseOutline.status === 'complete' ? { reverseOutline } : {}),};}if (sub.recordKind === 'mediaCollection') {@@ -1574,7 +1597,7 @@ export async function applyIncomingPush(payload) {if (!isPlainObject(payload)) {throw makeErr('payload must be an object', ERR_VALIDATION);}- const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, assetManifest, sourceInstanceId, portosMeta } = payload;+ const { kind, record, issues, linkedCollection, catalogBundle, manuscriptReview, reverseOutline, assetManifest, sourceInstanceId, portosMeta } = payload;if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);}@@ -1703,6 +1726,8 @@ export async function applyIncomingPush(payload) {// sender so it withholds lastPushedHash and retries (the review has no other// reconciliation path; see the merge block below).let reviewSyncPending = false;+ // Same contract as reviewSyncPending, for the bundled reverse-outline doc.+ let outlineSyncPending = false;if (kind === 'universe') {await mergeUniversesFromSync([record], { source });} else if (kind === 'series') {@@ -1733,6 +1758,18 @@ export async function applyIncomingPush(payload) {reviewSyncPending = true;});}+ // Merge the bundled reverse-outline sibling doc, whole-doc LWW on+ // generatedAt. Same ephemeral/tombstone guards + pending-signal contract as+ // the review above: a merge failure must withhold the sender's hash so the+ // outline (which has no independent reconciliation cycle) re-sends next+ // cycle. Dynamic import keeps the arcPlanner graph off peerSync's load path.+ if (!localEphemeral && record.deleted !== true && isPlainObject(reverseOutline)) {+ const { mergeOutlineFromSync } = await import('../pipeline/reverseOutline.js');+ await mergeOutlineFromSync(record.id, reverseOutline).catch((err) => {+ console.log(`⚠️ peerSync: reverseOutline merge failed: ${err.message}`);+ outlineSyncPending = true;+ });+ }} else if (kind === 'mediaCollection') {await mergeMediaCollectionsFromSync([record], { source });} else if (kind === 'author') {@@ -1835,6 +1872,7 @@ export async function applyIncomingPush(payload) {reverseSubscriptionCreated,ackedDeletesUpTo,...(reviewSyncPending ? { reviewSyncPending: true } : {}),+ ...(outlineSyncPending ? { outlineSyncPending: true } : {}),};}diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 23375a8bab..29ebd77f4d 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -49,6 +49,14 @@ vi.mock('../pipeline/manuscriptReview.js', async () => ({mergeReviewFromSync: vi.fn(),}));+// reverseOutline is dynamic-imported inside the series push/receive helpers (and+// statically by exporter.js, which peerSync.js imports) — mock both entry points+// so the outline bundle path is exercisable without loading the arcPlanner graph.+vi.mock('../pipeline/reverseOutline.js', async () => ({+ getStoredOutline: vi.fn(),+ mergeOutlineFromSync: vi.fn(),+}));+vi.mock('../mediaCollections.js', async () => ({getCollection: vi.fn(),listCollections: vi.fn(),@@ -110,6 +118,7 @@ import { getUniverse, mergeUniversesFromSync, listUniverses } from '../universeBimport { getSeries, mergeSeriesFromSync, listSeries } from '../pipeline/series.js';import { listIssues, mergeIssuesFromSync } from '../pipeline/issues.js';import { getReview, mergeReviewFromSync } from '../pipeline/manuscriptReview.js';+import { getStoredOutline, mergeOutlineFromSync } from '../pipeline/reverseOutline.js';import {getCollection,listCollections,@@ -189,6 +198,10 @@ beforeEach(async () => {// 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 stored reverse outline for any series. Tests that exercise the+ // outline-bundle path override getStoredOutline per-call.+ vi.mocked(getStoredOutline).mockReset().mockResolvedValue(null);+ vi.mocked(mergeOutlineFromSync).mockReset().mockResolvedValue(null);// 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' }));@@ -1572,6 +1585,49 @@ describe('peerSync', () => {expect(vi.mocked(getReview)).not.toHaveBeenCalled();});+ it('bundles the reverse outline with a series push so regenerate-only edits propagate', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(getStoredOutline).mockResolvedValue({+ seriesId: 's1', schemaVersion: 1, status: 'complete', generatedAt: '2026-06-02T00:00:00Z',+ plotlines: [{ id: 'a', label: 'A-plot', kind: 'main', color: '#3b82f6' }],+ scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],+ });+ 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.reverseOutline).toBeTruthy();+ expect(captured.reverseOutline.scenes).toHaveLength(1);+ expect(captured.reverseOutline.generatedAt).toBe('2026-06-02T00:00:00Z');+ });++ it('omits the reverseOutline key when no complete outline exists', async () => {+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ // A never-generated / in-progress outline (status !== 'complete') is not shipped.+ vi.mocked(getStoredOutline).mockResolvedValue({ seriesId: 's1', schemaVersion: 1, status: 'none', plotlines: [], scenes: [] });+ 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.reverseOutline).toBeUndefined();+ });++ it('does not fetch an outline 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.reverseOutline).toBeUndefined();+ expect(vi.mocked(getStoredOutline)).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)@@ -2108,6 +2164,76 @@ describe('peerSync', () => {expect(res.reviewSyncPending).toBe(true);});+ const sampleOutline = (generatedAt = '2026-06-02T00:00:00Z') => ({+ schemaVersion: 1, status: 'complete', generatedAt,+ plotlines: [{ id: 'a', label: 'A', kind: 'main' }],+ scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],+ });++ it('routes a bundled reverseOutline through mergeOutlineFromSync on a series push', async () => {+ const reverseOutline = sampleOutline();+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ reverseOutline,+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeOutlineFromSync).toHaveBeenCalledWith('s1', reverseOutline);+ });++ it('skips mergeOutlineFromSync when no reverseOutline is bundled', async () => {+ await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeOutlineFromSync).not.toHaveBeenCalled();+ });++ it('refuses to merge reverseOutline 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: [],+ reverseOutline: sampleOutline(),+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeOutlineFromSync).not.toHaveBeenCalled();+ });++ it('skips mergeOutlineFromSync 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: [],+ reverseOutline: sampleOutline(),+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeOutlineFromSync).not.toHaveBeenCalled();+ });++ it('returns outlineSyncPending when the bundled outline merge throws (so the sender retries)', async () => {+ vi.mocked(mergeOutlineFromSync).mockRejectedValueOnce(new Error('disk full'));+ const res = await applyIncomingPush({+ kind: 'series',+ record: { id: 's1', name: 'S', deleted: false, deletedAt: null },+ issues: [],+ reverseOutline: sampleOutline(),+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ // Series/issues merge still succeeded — the outline has no independent+ // reconciliation path, so the sender withholds its hash and retries.+ expect(res.outlineSyncPending).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@@ -2979,6 +3105,46 @@ describe('peerSync', () => {expect(refreshed.lastPushedHash).toBeFalsy();});+ it('falls back without reverseOutline when a pre-#1348 peer rejects the new key, keeping series + issues', async () => {+ // Same graceful-degradation contract as the manuscriptReview strip above:+ // a pre-#1348 peer's `.strict()` series schema 400-rejects the+ // reverseOutline key, so the sender strips ONLY it and retries, then+ // withholds the hash so the outline re-sends once the peer upgrades.+ vi.mocked(getSeries).mockResolvedValue({ id: 's1', name: 'Series' });+ vi.mocked(listIssues).mockResolvedValue([{ id: 'i1', seriesId: 's1', number: 1 }]);+ vi.mocked(getStoredOutline).mockResolvedValue({+ seriesId: 's1', schemaVersion: 1, status: 'complete', generatedAt: '2026-06-02T00:00:00Z',+ plotlines: [{ id: 'a', label: 'A', kind: 'main', color: '#3b82f6' }],+ scenes: [{ id: 'scene-001', sequence: 0, summary: 'opening', plotlineId: 'a' }],+ });+ const firstCallBody = { ok: false, status: 400, json: async () => ({+ code: 'VALIDATION_ERROR',+ message: 'Validation failed',+ context: { details: [{ path: '', message: "Unrecognized key(s) in object: 'reverseOutline'" }] },+ }) };+ firstCallBody.clone = () => firstCallBody;+ const retryBody = { ok: true, status: 200, json: async () => ({}) };+ vi.mocked(peerFetch).mockResolvedValueOnce(firstCallBody).mockResolvedValueOnce(retryBody);+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'series', recordId: 's1',+ }, { adoptedFromReverse: true });+ const result = await pushRecordToPeer(sub);+ expect(result.pushed).toBe(true);+ const calls = vi.mocked(peerFetch).mock.calls;+ expect(calls.length).toBe(2);+ const firstPayload = JSON.parse(calls[0][1].body);+ const retryPayload = JSON.parse(calls[1][1].body);+ expect(firstPayload.reverseOutline).toBeDefined();+ expect(retryPayload.reverseOutline).toBeUndefined();+ // Surgical strip: portosMeta + series + issues still land.+ expect(retryPayload.portosMeta).toBeDefined();+ expect(retryPayload.record.id).toBe('s1');+ expect(retryPayload.issues).toHaveLength(1);+ // Hash withheld so the outline re-sends once the peer upgrades.+ 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 () => {// The retry is keyed on the `portosMeta` mention in the validation// details — any other 400 (oversized field, unknown record key, etc.)