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-730]): sync sync-enabled Story Builder sessions across peers
[._.]/ Adam Eivyace5d5b26f7e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 10414e847d..a9f03e52cc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **[issue-730] Story Builder sessions can sync across your machines** — a Story Builder session you mark for cross-machine resume now travels to your sync peers, so you can pick up the same wizard (its step locks, progress, and provider choice) on another machine. Sessions stay private to one machine by default; only the ones you explicitly opt in are shared, via a new "Story Builder" sync category you enable per peer on the Instances page. Local-only sessions are never pushed.- **[issue-735] AudioLDM2 long-form music backend** — the pipeline audio stage can now generate background music with a second local engine, AudioLDM2, alongside MusicGen. Pick the engine in the Generate panel: MusicGen for short clips (up to 30s) or AudioLDM2 for longer pieces (up to two minutes), each with its own model choices. Both run entirely on your machine with no API key; install AudioLDM2's runtime with `INSTALL_AUDIOLDM2=1 bash scripts/setup-image-video.sh` and the panel shows an install hint until it's ready.- **Shell arrow-key hot buttons** — the Shell page's quick-command toolbar now has touch-friendly Up / Down / Left / Right / Enter buttons that send the matching key to the terminal. Handy on phones and tablets where the on-screen keyboard hides the arrow keys, for scrolling command history, and for driving TUI apps without a hardware keyboard.- **[issue-827] Clinician export for blood and lifestyle data** — MeatSpace gains an Export tab that builds a one-page, doctor-ready summary of your blood panels and lifestyle. Each blood test is laid out as a clean table with reference ranges and out-of-range markers flagged, and your lifestyle factors (sex, smoking, exercise, sleep, diet, stress, BMI, and any chronic conditions) are summarized above them. Print it or save it as a PDF straight from the browser, or copy the whole thing as markdown to paste into a message or note. Genome and longevity context are intentionally left out of this view.diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex ecc19fdbae..11a94c6765 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -7,7 +7,7 @@ import {Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, Timer,Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,- Lock, Globe, Info, Sparkles, Film, Images, Library+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -458,6 +458,7 @@ const SYNC_CATEGORY_META = [{ key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },{ key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },{ key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },+ { key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }];diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 95e4e24ea8..41ca58291a 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -140,6 +140,21 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// receiver still accepts ≤v7 senders (sender-behind); their envelopes carry no// `catalogTypes` block and the receiver applies the other kinds as before.catalog: 8,+ // v1 = cross-machine resumable Story Builder sessions (#730). Sessions are+ // local-only by default and excluded from sync; only `sync: true` sessions+ // ride the `storyBuilder` snapshot category. This is a brand-NEW synced+ // record type (not a sibling doc on an existing bundle), so it gets its own+ // per-category gate: a sender ahead on `storyBuilder` would push a session+ // shape an older receiver's `sanitizeSession` would silently strip and then+ // LWW back, so a v1 sender pushing to a ≤v0 (pre-feature) receiver is+ // sender-ahead on `storyBuilder` and gets a 412 — only the storyBuilder+ // category pauses; every other category keeps flowing (per-category gate via+ // scopeVersionDiff). A v1 receiver still accepts a ≤v0 sender (sender-behind):+ // pre-feature peers never send a `storyBuilder` snapshot at all, so there's+ // nothing to gate. The FIRST incompatible session-shape change MUST bump this+ // to 2 then (where a v1 peer would round-trip the new shape through an+ // unaware sanitizer).+ storyBuilder: 1,// NOTE: `videoHistory` is intentionally NOT listed here. The version gate// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the// comparator walks the union of keys), so declaring a brand-new key would@@ -178,6 +193,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({mediaCollection: Object.freeze(['mediaCollections']),'cat-ingredient': Object.freeze(['catalog']),'cat-scrap': Object.freeze(['catalog']),+ storyBuilder: Object.freeze(['storyBuilder']),});/**diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 697071da18..7e9447a4bd 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -55,6 +55,7 @@ const syncCategoriesSchema = z.object({// universe + pipeline omission tracked in .changelog/NEXT.md.mediaCollections: z.boolean().optional(),videoHistory: z.boolean().optional(),+ storyBuilder: z.boolean().optional(),catalog: z.boolean().optional()}).optional();diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 3d3a2712b8..7aab74b2e9 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -23,6 +23,7 @@ import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';import { mergeIssuesFromSync, listIssues } from './pipeline/issues.js';import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';+import { listSyncableSessionsForWire, mergeStorySessionsFromSync } from './storyBuilder.js';import { sanitizeStateForWire } from '../lib/syncWire.js';// --- Category Definitions ---@@ -55,6 +56,11 @@ const MEDIA_COLLECTIONS_DIR = join(PATHS.data, 'media-collections');// CHECKSUM_PATHS below.const PEER_SUBSCRIPTIONS_FILE = join(PATHS.data, 'sharing', 'peer_subscriptions.json');const VIDEO_HISTORY_FILE = join(PATHS.data, 'video-history.json');+// Story Builder sessions live in per-record `data/story-builder/<id>/index.json`+// (collectionStore layout) with a type-level `data/story-builder/index.json`.+// Only `sync: true` sessions ride this category (#730); the fingerprint walker+// descends into the dir so a session edit invalidates the snapshot checksum.+const STORY_BUILDER_DIR = join(PATHS.data, 'story-builder');const MEATSPACE_FILES = {'daily-log.json': { arrayKey: 'entries', idField: 'date' },@@ -680,6 +686,33 @@ async function applyVideoHistoryRemote(remoteData) {return { applied: true, count: changedCount };}+// --- Category: Story Builder sessions ---++// Optional cross-machine resumable Story Builder sessions (#730). Sessions are+// LOCAL-ONLY by default and excluded from sync; only a session with+// `sync: true` participates. `listSyncableSessionsForWire` enforces that+// (returning ONLY sync-enabled sessions, wire-sanitized + sorted by id), so a+// local-only session can NEVER appear in the snapshot or its checksum — two+// peers that disagree only on local-only sessions still compute the same+// checksum and never churn. The merge is union-by-id, LWW on `updatedAt`, and+// refuses to flip a local session's sync mode (see mergeStorySessionsFromSync).+//+// No exclude-set / `{forPeerId}` scoping: sessions have no per-record push+// subscription (they ride the snapshot only), so there's nothing to exclude.++async function getStoryBuilderSnapshot() {+ const sessions = await listSyncableSessionsForWire();+ const data = { sessions };+ return { data, checksum: computeChecksum(data) };+}++async function applyStoryBuilderRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ const incoming = Array.isArray(remoteData.sessions) ? remoteData.sessions : [];+ if (incoming.length === 0) return { applied: false, count: 0 };+ return mergeStorySessionsFromSync(incoming);+}+// --- Public API ---// Files each category reads, used to keep the in-process checksum cache@@ -711,6 +744,12 @@ const CHECKSUM_PATHS = {// videoHistory is a flat history file with no parent-record dependency —// its checksum invalidates only when video-history.json itself moves.videoHistory: [VIDEO_HISTORY_FILE],+ // storyBuilder invalidates on its own per-record dir. The snapshot includes+ // ONLY sync-enabled sessions, but the fingerprint walker is content-agnostic+ // (any session file edit re-checksums) — over-invalidation is harmless: the+ // snapshot getter filters back to sync:true and the checksum is unchanged+ // when no synced session moved, so the orchestrator still skips the transfer.+ storyBuilder: [STORY_BUILDER_DIR],};const CATEGORIES = {@@ -721,7 +760,8 @@ const CATEGORIES = {universe: { getSnapshot: getUniverseSnapshot, applyRemote: applyUniverseRemote },pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote },mediaCollections: { getSnapshot: getMediaCollectionsSnapshot, applyRemote: applyMediaCollectionsRemote },- videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote }+ videoHistory: { getSnapshot: getVideoHistorySnapshot, applyRemote: applyVideoHistoryRemote },+ storyBuilder: { getSnapshot: getStoryBuilderSnapshot, applyRemote: applyStoryBuilderRemote }};// Map a snapshot CATEGORY to the `PORTOS_SCHEMA_VERSIONS` keys whose storage@@ -751,6 +791,7 @@ const SNAPSHOT_CATEGORY_SCHEMA_KEYS = {digitalTwin: [],meatspace: [],videoHistory: [],+ storyBuilder: RECORD_KIND_SCHEMA_CATEGORIES.storyBuilder,};// Exported for the boot-adjacent guard test (see dataSync.pipelineUniverse.test.js):diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 1a27ab61e6..1531569495 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -886,6 +886,111 @@ describe('dataSync — videoHistory category', () => {});});+describe('dataSync — storyBuilder category (#730)', () => {+ const STORY_BUILDER_DIR = join(tempRoot, 'story-builder');+ const session = (id, overrides = {}) => ({+ id,+ title: `Session ${id}`,+ intakeMode: 'seed',+ seedIdea: '',+ universeId: null,+ seriesId: null,+ currentStep: 'idea',+ steps: {},+ llm: { provider: null, model: null },+ sync: true,+ syncedHashes: {},+ origin: null,+ createdAt: '2026-05-22T00:00:00Z',+ updatedAt: '2026-05-22T00:00:00Z',+ ...overrides,+ });+ const writeSessions = (sessions) => writeCollectionState(STORY_BUILDER_DIR, 'storyBuilder', sessions);+ const readSessions = () => readCollectionState(STORY_BUILDER_DIR);++ it('is registered alongside the other categories', () => {+ expect(dataSync.getSupportedCategories()).toContain('storyBuilder');+ });++ it('snapshot includes ONLY sync:true sessions — local-only sessions never cross the wire', async () => {+ writeSessions([session('stb-synced'), session('stb-local', { sync: false })]);+ const snap = await dataSync.getSnapshot('storyBuilder');+ expect(snap.data.sessions.map((s) => s.id)).toEqual(['stb-synced']);+ expect(snap.checksum).toBeTruthy();+ });++ it('snapshot checksum is identical whether or not a local-only session exists (convergence)', async () => {+ writeSessions([session('stb-synced')]);+ const a = await dataSync.getSnapshot('storyBuilder');+ await new Promise((r) => setTimeout(r, 5));+ writeSessions([session('stb-synced'), session('stb-local', { sync: false })]);+ const b = await dataSync.getSnapshot('storyBuilder');+ expect(b.checksum).toBe(a.checksum);+ });++ it('applyRemote inserts a new synced session (union by id)', async () => {+ writeSessions([session('stb-a')]);+ const result = await dataSync.applyRemote('storyBuilder', {+ sessions: [session('stb-b')],+ });+ expect(result.applied).toBe(true);+ expect(readSessions().map((s) => s.id).sort()).toEqual(['stb-a', 'stb-b']);+ });++ it('applyRemote LWW: newer remote wins for the same id', async () => {+ writeSessions([session('stb-a', { title: 'old', updatedAt: '2026-05-22T00:00:00Z' })]);+ await dataSync.applyRemote('storyBuilder', {+ sessions: [session('stb-a', { title: 'new', updatedAt: '2026-05-22T05:00:00Z' })],+ });+ expect(readSessions().find((s) => s.id === 'stb-a').title).toBe('new');+ });++ it('applyRemote refuses to overwrite a LOCAL session the user turned local-only', async () => {+ writeSessions([session('stb-a', { sync: false, title: 'local wins' })]);+ const result = await dataSync.applyRemote('storyBuilder', {+ sessions: [session('stb-a', { title: 'peer wins?', updatedAt: '2030-01-01T00:00:00Z' })],+ });+ expect(result.applied).toBe(false);+ const got = readSessions().find((s) => s.id === 'stb-a');+ expect(got.sync).toBe(false);+ expect(got.title).toBe('local wins');+ });++ it('round-trips: a fresh receiver applying the wire snapshot recomputes the same checksum', async () => {+ writeSessions([session('stb-a'), session('stb-b'), session('stb-local', { sync: false })]);+ const snap = await dataSync.getSnapshot('storyBuilder');+ // Fresh receiver: empty store, apply, recompute.+ rmSync(STORY_BUILDER_DIR, { recursive: true, force: true });+ writeSessions([]);+ const applied = await dataSync.applyRemote('storyBuilder', snap.data);+ expect(applied.applied).toBe(true);+ const receiverSnap = await dataSync.getSnapshot('storyBuilder');+ expect(receiverSnap.checksum).toBe(snap.checksum);+ });++ it('does NOT block a storyBuilder snapshot when the sender is ahead on universes (per-category gate)', async () => {+ writeSessions([]);+ const result = await dataSync.applyRemote('storyBuilder', {+ sessions: [session('stb-a')],+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6, storyBuilder: 1 } } });+ expect(result.blockedBySchema).toBeUndefined();+ expect(result.applied).toBe(true);+ });++ it('STILL blocks a storyBuilder snapshot when the sender is ahead on storyBuilder', async () => {+ writeSessions([]);+ const result = await dataSync.applyRemote('storyBuilder', {+ sessions: [session('stb-a')],+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { storyBuilder: 2 } } });+ expect(result.applied).toBe(false);+ expect(result.blockedBySchema).toBeDefined();+ expect(result.blockedBySchema.ahead).toEqual([+ { category: 'storyBuilder', senderV: 2, receiverV: 1 },+ ]);+ expect(readSessions()).toEqual([]);+ });+});+describe('dataSync — per-category schema gate (cross-key isolation)', () => {// A sender always stamps its FULL schemaVersions map (buildPortosMeta spreads// PORTOS_SCHEMA_VERSIONS). The old whole-payload gate rejected EVERY categorydiff --git a/server/services/instances.js b/server/services/instances.jsindex 846d5e57f0..ba63c3b81b 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -168,6 +168,7 @@ const DEFAULT_SYNC_CATEGORIES = {pipeline: false,mediaCollections: false,videoHistory: false,+ storyBuilder: false,catalog: false};diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 6894a130c9..959a28edfe 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -306,6 +306,116 @@ export async function deleteStorySession(id) {});}+// ── Cross-machine sync (#730) ─────────────────────────────────────────────+//+// Sessions are LOCAL-ONLY by default and excluded from peer sync entirely.+// Only a session with `sync: true` participates — it rides the dedicated+// `storyBuilder` snapshot category (dataSync.js), union-merged by id with LWW+// on `updatedAt`. Sessions carry no assets and no child records, so they don't+// need the per-record push pipeline / asset-manifest / reverse-subscribe+// machinery the universe/series kinds use; the 60s snapshot loop's LWW merge+// is the whole transport.+//+// The carried `syncedHashes` baseline is exactly what makes this safe: a peer's+// universe/series edit moves the live records but NOT `syncedHashes`, so a+// session that traveled across machines doesn't false-positive-stale (the whole+// point of the #861 staleness model). The FKs (`universeId`, `seriesId`)+// reference records that sync through their own categories; if the peer hasn't+// received them yet, the session view degrades gracefully (computeCurrentHashes+// reads them best-effort and a missing record just yields empty hashes).++/**+ * Wire-safe projection of a single session for the peer snapshot. Re-runs the+ * sanitizer (canonical key order + field whitelist) and strips the local-only+ * `ephemeral` marker so a synced session can't smuggle a peer-local flag and so+ * the byte-stable checksum matches across machines. Returns null for a session+ * that isn't sync-enabled — local-only sessions must NEVER cross the wire.+ *+ * Tombstones (deleted=true) still cross: a session that was synced, then+ * deleted, needs its tombstone to converge on peers that hold the live copy.+ */+export function sanitizeSessionForWire(raw) {+ const s = sanitizeSession(raw);+ if (!s) return null;+ if (s.sync !== true) return null;+ // `ephemeral` is a peer-local "don't sync" marker analogous to the+ // universe/series flag (and #727's `importDraft`). A live ephemeral session+ // is local-only and never crosses the wire; a tombstone still does so the+ // delete converges on peers that hold the live copy.+ if (s.ephemeral === true && s.deleted !== true) return null;+ // Strip the local-only marker so the wire form is byte-stable against peers+ // that predate the flag (sanitizeSession only adds it when raw.ephemeral).+ const { ephemeral: _ephemeral, ...rest } = s; // eslint-disable-line no-unused-vars+ return rest;+}++/**+ * Every sync-enabled session in wire form, sorted by id for a deterministic+ * (checksum-stable) snapshot. Includes tombstones so deletes propagate.+ */+export async function listSyncableSessionsForWire() {+ const sessions = await store().loadAll();+ return sessions+ .map(sanitizeSessionForWire)+ .filter(Boolean)+ .sort((a, b) => a.id.localeCompare(b.id));+}++/**+ * Merge a peer's sync-enabled sessions into local state. Union by id, LWW on+ * `updatedAt`. Mirrors the bundled-record merge contract:+ * - sanitize-first: every remote row goes through `sanitizeSession` before it+ * can touch disk (drops bogus baselines, malformed steps, missing title).+ * - first-wins dedup: a duplicate id within the same batch keeps the first.+ * - throw-on-unreadable: a per-record load failure aborts (the store's+ * queueRecordWrite rejects), surfacing rather than silently dropping.+ * - local-only guard: a remote session that isn't sync-enabled is refused+ * (the sender only ships sync:true, but a malformed/hostile payload can't+ * plant a local-only session as synced).+ * - sync-flag preservation: a remote payload can't flip a LOCAL session's+ * `sync` off (or on) — sync mode is a per-machine gesture. We only ever+ * create/update sessions the remote marked sync:true; a local-only session+ * of the same id is left untouched (its `sync:false` keeps it out of the+ * wire on its own machine).+ */+export async function mergeStorySessionsFromSync(remoteSessions) {+ if (!Array.isArray(remoteSessions)) return { applied: false, count: 0 };+ // First-wins dedup within the batch (mirrors the monolithic-reader contract).+ const byId = new Map();+ for (const raw of remoteSessions) {+ const s = sanitizeSessionForWire(raw);+ if (!s || byId.has(s.id)) continue;+ byId.set(s.id, s);+ }+ let changed = 0;+ for (const remote of byId.values()) {+ const applied = await store().queueRecordWrite(remote.id, async () => {+ const local = await store().loadOne(remote.id);+ if (!local) {+ // No local counterpart — adopt the remote session verbatim. It's+ // already sync:true (sanitizeSessionForWire enforced it), so it stays+ // syncable on this machine too.+ await store().saveOneNow(remote.id, remote);+ return true;+ }+ // Don't resurrect / re-sync a session the LOCAL user opted out of. If the+ // local copy is local-only (sync:false), the user explicitly turned sync+ // off here — honor that and leave it alone rather than letting a stale+ // peer push flip it back on.+ if (local.sync !== true) return false;+ const localTs = local.updatedAt || '';+ const remoteTs = remote.updatedAt || '';+ if (remoteTs <= localTs) return false; // local wins (or tie — no churn)+ await store().saveOneNow(remote.id, remote);+ return true;+ });+ if (applied) changed += 1;+ }+ if (changed === 0) return { applied: false, count: 0 };+ console.log(`🔄 StoryBuilder sync: merged ${changed} session(s)`);+ return { applied: true, count: changed };+}+// ── Integrity (staleness) ─────────────────────────────────────────────────// Project the whitelisted SEMANTIC upstream fields per step. Never includediff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.jsindex 4b2a5b86f2..d6ba80e9bd 100644--- a/server/services/storyBuilder.test.js+++ b/server/services/storyBuilder.test.js@@ -818,3 +818,107 @@ describe('generateIssuesFromArc (issues step)', () => {.rejects.toMatchObject({ code: sb.ERR_VALIDATION });});});++describe('storyBuilder — cross-machine sync wire (#730)', () => {+ it('listSyncableSessionsForWire excludes local-only sessions and includes only sync:true', async () => {+ const local = await sb.createStorySession({ title: 'Local only' });+ const synced = await sb.createStorySession({ title: 'Synced' });+ await sb.setStorySessionSync(synced.id, true);++ const wire = await sb.listSyncableSessionsForWire();+ const ids = wire.map((s) => s.id);+ expect(ids).toContain(synced.id);+ expect(ids).not.toContain(local.id);+ // The wire form must never carry a peer-local marker.+ expect(wire.every((s) => !('ephemeral' in s))).toBe(true);+ // Deterministic ordering by id for a stable checksum.+ expect(ids).toEqual([...ids].sort((a, b) => a.localeCompare(b)));+ });++ it('sanitizeSessionForWire returns null for a non-sync session and for a non-tombstone ephemeral session', () => {+ expect(sb.sanitizeSessionForWire({ id: 'stb-x', title: 'T', sync: false })).toBeNull();+ expect(sb.sanitizeSessionForWire({ id: 'stb-y', title: 'T', sync: true, ephemeral: true })).toBeNull();+ const ok = sb.sanitizeSessionForWire({ id: 'stb-z', title: 'T', sync: true });+ expect(ok).toMatchObject({ id: 'stb-z', sync: true });+ });++ it('merge adopts a new remote sync session verbatim', async () => {+ const remote = {+ id: 'stb-remote-1', title: 'From peer', intakeMode: 'seed',+ sync: true, syncedHashes: {}, currentStep: 'idea',+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ };+ const res = await sb.mergeStorySessionsFromSync([remote]);+ expect(res).toEqual({ applied: true, count: 1 });+ const got = await sb.getStorySession('stb-remote-1');+ expect(got.title).toBe('From peer');+ expect(got.sync).toBe(true);+ });++ it('merge is LWW on updatedAt — newer remote wins, older remote is a no-op', async () => {+ const base = {+ id: 'stb-lww', title: 'v1', intakeMode: 'seed', sync: true, syncedHashes: {},+ currentStep: 'idea', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ };+ await sb.mergeStorySessionsFromSync([base]);+ // Older remote → ignored.+ const older = await sb.mergeStorySessionsFromSync([{ ...base, title: 'stale', updatedAt: '2025-12-31T00:00:00.000Z' }]);+ expect(older.applied).toBe(false);+ expect((await sb.getStorySession('stb-lww')).title).toBe('v1');+ // Newer remote → wins.+ const newer = await sb.mergeStorySessionsFromSync([{ ...base, title: 'v2', updatedAt: '2026-02-01T00:00:00.000Z' }]);+ expect(newer.applied).toBe(true);+ expect((await sb.getStorySession('stb-lww')).title).toBe('v2');+ });++ it('merge refuses to re-sync a session the local user turned local-only', async () => {+ const synced = await sb.createStorySession({ title: 'Was synced' });+ await sb.setStorySessionSync(synced.id, true);+ // User disables sync locally (now sync:false, local-only).+ await sb.setStorySessionSync(synced.id, false);+ // A stale peer push for the same id must NOT flip it back on or overwrite it.+ const res = await sb.mergeStorySessionsFromSync([{+ id: synced.id, title: 'peer wins?', intakeMode: 'seed', sync: true, syncedHashes: {},+ currentStep: 'idea', createdAt: synced.createdAt, updatedAt: '2030-01-01T00:00:00.000Z',+ }]);+ expect(res.applied).toBe(false);+ const got = await sb.getStorySession(synced.id);+ expect(got.sync).toBe(false);+ expect(got.title).toBe('Was synced');+ });++ it('merge refuses a remote session that is not sync-enabled', async () => {+ const res = await sb.mergeStorySessionsFromSync([{+ id: 'stb-not-synced', title: 'sneaky', sync: false,+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ }]);+ expect(res.applied).toBe(false);+ await expect(sb.getStorySession('stb-not-synced')).rejects.toMatchObject({ code: sb.ERR_NOT_FOUND });+ });++ it('merge is first-wins within a batch for a duplicate id', async () => {+ const dupA = {+ id: 'stb-dup', title: 'first', intakeMode: 'seed', sync: true, syncedHashes: {},+ currentStep: 'idea', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-03-01T00:00:00.000Z',+ };+ const dupB = { ...dupA, title: 'second', updatedAt: '2026-04-01T00:00:00.000Z' };+ await sb.mergeStorySessionsFromSync([dupA, dupB]);+ // first-wins dedup keeps dupA despite dupB's newer timestamp.+ expect((await sb.getStorySession('stb-dup')).title).toBe('first');+ });++ it('merge converges a tombstone for a synced session', async () => {+ const base = {+ id: 'stb-tomb', title: 'doomed', intakeMode: 'seed', sync: true, syncedHashes: {},+ currentStep: 'idea', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ };+ await sb.mergeStorySessionsFromSync([base]);+ const res = await sb.mergeStorySessionsFromSync([{+ ...base, deleted: true, deletedAt: '2026-05-01T00:00:00.000Z', updatedAt: '2026-05-01T00:00:00.000Z',+ }]);+ expect(res.applied).toBe(true);+ await expect(sb.getStorySession('stb-tomb')).rejects.toMatchObject({ code: sb.ERR_NOT_FOUND });+ const withDeleted = await sb.getStorySession('stb-tomb', { includeDeleted: true });+ expect(withDeleted.deleted).toBe(true);+ });+});