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

feat([issue-730]): opt-in sync-safe staleness for story-builder sessions

[._.]/ Adam Eivy6ce7983cc702
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7d5db9c8d9..2a72360309 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -45,6 +45,7 @@
## Changed
+- **[issue-730] Story Builder sessions can opt into cross-machine resume** — a Story Builder session is private to one machine by default, but you can now turn on cross-machine resume per session. When it's on, the "needs another look" warnings on locked steps follow a snapshot the session carries with it, so a change another of your machines makes to the same universe no longer makes every locked step look stale the moment the session travels over. A reconcile action lets you re-baseline against the current world whenever you want.
- **[issue-738] Cross-Domain Insights Engine design** — design groundwork for narrative insights connecting genome, health, taste, and creative output, including a dismissable/acceptable insight model and a structured facts table feeding the LLM.
- **[issue-727] Abandoned imports no longer leave empty universes lying around** — starting an import and walking away before you commit it used to leave a blank universe and series behind in your library. Those scratch records are now hidden from sync and automatically cleaned up after a week if you never finish the import, while committing one keeps it for good.
- **Codex TUI runs fully bypassed** — Codex now launches in TUI mode with `--dangerously-bypass-approvals-and-sandbox` (the same full-yolo posture the headless CLI path already used), instead of only `--ask-for-approval never`. The previous flag suppressed approval prompts but kept Codex's sandbox on, so tool calls that needed real file or network writes still got blocked. Provider configs that pin their own `--ask-for-approval` / `--sandbox` policy are left untouched.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b37475c145..ce777b63df 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1930,6 +1930,13 @@ export const storySessionUpdateSchema = z.object({
}).optional(),
}).strict();
+// Cross-machine resume opt-in toggle (#730). Sessions are local-only by
+// default; flipping this on snapshots a staleness baseline that travels with
+// the session so a peer's universe edit can't false-positive-stale it.
+export const storySessionSyncSchema = z.object({
+ sync: z.boolean(),
+}).strict();
+
export const storyStepGenerateSchema = z.object({
providerId: storyProviderField,
model: storyModelField,
diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.js
index b247e5b83e..482566669a 100644
--- a/server/routes/storyBuilder.js
+++ b/server/routes/storyBuilder.js
@@ -4,6 +4,7 @@ import {
validateRequest,
storySessionCreateSchema,
storySessionUpdateSchema,
+ storySessionSyncSchema,
storyStepGenerateSchema,
storyStepRefineSchema,
storyIssueLockSchema,
@@ -22,6 +23,8 @@ import {
setCurrentStep,
setIssueLock,
generateIssuesFromArc,
+ setStorySessionSync,
+ reconcileStorySession,
ERR_NOT_FOUND,
ERR_VALIDATION,
} from '../services/storyBuilder.js';
@@ -72,6 +75,24 @@ router.delete('/:id', asyncHandler(async (req, res) => {
res.json(result);
}));
+// ── Cross-machine resume opt-in (#730) ──────────────────────────────────────
+
+// Toggle whether this session participates in cross-machine resume. Local-only
+// is the default; flipping sync on captures a staleness baseline that travels
+// with the session so a peer's universe edit can't false-positive-stale it.
+router.post('/:id/sync', asyncHandler(async (req, res) => {
+ const { sync } = validateRequest(storySessionSyncSchema, req.body || {});
+ const updated = await setStorySessionSync(req.params.id, sync).catch((err) => { throw mapServiceError(err); });
+ res.json(updated);
+}));
+
+// Re-snapshot a sync-enabled session's staleness baseline to the current live
+// records — the explicit "adopt this machine's universe/series state" gesture.
+router.post('/:id/reconcile', asyncHandler(async (req, res) => {
+ const updated = await reconcileStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(updated);
+}));
+
// ── Step state machine ─────────────────────────────────────────────────────
function assertStep(stepId) {
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index 30d24271b7..460d03ec6b 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -7,12 +7,28 @@
* `seriesId`). All real content lives in the universe and series records and is
* mutated through their existing services — this service never duplicates it.
*
- * Sessions are LOCAL-ONLY: they reference peer-syncable records by FK, but the
- * lock/integrity bookkeeping is a private workflow artifact. We deliberately do
- * NOT register a sync schema version, do NOT add the type to
- * RECORD_TYPE_CATEGORIES, and do NOT auto-subscribe peers on create — syncing a
- * session would create cross-install staleness false-positives. The
- * tombstone/origin/ephemeral fields are carried only for on-disk shape parity.
+ * Sessions are LOCAL-ONLY BY DEFAULT: they reference peer-syncable records by
+ * FK, but the lock/integrity bookkeeping is a private workflow artifact. A
+ * session opts into cross-machine resume by flipping `sync: true` (#730). The
+ * wire/push integration itself (peer push schema, manifest kind, importer
+ * apply) is a later slice; what ships here is the OPT-IN flag plus the
+ * sync-safe staleness model that makes enabling it later non-corrupting.
+ *
+ * Sync-safe staleness (#730). The default (local-only) staleness model
+ * live-diffs each locked step's frozen `upstreamHash` against the CURRENT hash
+ * recomputed from the live universe/series records — so any out-of-band edit
+ * (#731), including a peer's universe edit that arrived via universe sync, flags
+ * the locked step stale. That is correct within one install but wrong for a
+ * synced session: once the session travels to another machine, that machine's
+ * live records legitimately differ, so a live recompute would false-positive
+ * EVERY locked step stale. So a `sync: true` session instead keys staleness on a
+ * content hash CARRIED IN THE SESSION (`syncedHashes`) — the upstream hashes the
+ * session last reconciled with on whatever machine touched it. A peer's record
+ * edit moves the live records but NOT `syncedHashes`, so it can't false-positive
+ * a synced session; the user re-snapshots the baseline explicitly via reconcile.
+ *
+ * The tombstone/origin/ephemeral fields are carried only for on-disk shape
+ * parity (and forward-compat with the eventual sync wire integration).
*
* Persisted to data/story-builder/{id}/index.json.
*/
@@ -121,6 +137,21 @@ function sanitizeSteps(raw) {
return steps;
}
+// The content-hash baseline a `sync: true` session carries (#730): one
+// sha256 hex digest per step id, the upstream hash the session last reconciled
+// with. Drops unknown ids and non-hex values so a hand-edited / peer-sourced
+// record can't smuggle a bogus baseline that would mis-flag staleness.
+const HASH_RE = /^[0-9a-f]{64}$/;
+function sanitizeSyncedHashes(raw) {
+ if (!raw || typeof raw !== 'object') return {};
+ const out = {};
+ for (const id of STEP_IDS) {
+ const h = raw[id];
+ if (isStr(h) && HASH_RE.test(h)) out[id] = h;
+ }
+ return out;
+}
+
export function sanitizeSession(raw) {
if (!raw || typeof raw !== 'object') return null;
if (!isStr(raw.id) || !raw.id) return null;
@@ -143,6 +174,11 @@ export function sanitizeSession(raw) {
currentStep,
steps: sanitizeSteps(raw.steps),
llm,
+ // Cross-machine resume is OPT-IN (#730): local-only is the default. When
+ // off, `syncedHashes` is irrelevant (staleness live-diffs against records)
+ // so we drop it to keep the record minimal.
+ sync: raw.sync === true,
+ ...(raw.sync === true ? { syncedHashes: sanitizeSyncedHashes(raw.syncedHashes) } : {}),
origin: sanitizeOrigin(raw.origin),
createdAt,
updatedAt,
@@ -378,14 +414,68 @@ export async function computeCurrentHashes(session) {
* Load a session augmented with the computed `staleSteps` array (the locked
* steps whose upstream inputs have drifted since lock time). This is the shape
* the route serves to the client.
+ *
+ * Staleness baseline depends on the sync mode (#730):
+ * - local-only (default): compare each locked step's frozen `upstreamHash`
+ * against the LIVE recompute, so any out-of-band record edit flags stale
+ * (#731). Correct within one install.
+ * - sync (`session.sync === true`): compare against the session-carried
+ * `syncedHashes` baseline instead of live records. The baseline travels with
+ * the session, so a peer's universe edit that hasn't been reconciled can't
+ * false-positive-stale a session that synced across machines. The user
+ * re-snapshots the baseline to live via `reconcileStorySession`.
*/
export async function getStorySessionView(id) {
const session = await getStorySession(id);
const { hashes, universe, series } = await computeCurrentHashes(session);
- const staleSteps = computeStaleSteps(session, hashes);
+ const baseline = session.sync === true ? (session.syncedHashes || {}) : hashes;
+ const staleSteps = computeStaleSteps(session, baseline);
return { session, staleSteps, universe, series };
}
+/**
+ * Re-snapshot a sync-enabled session's `syncedHashes` baseline to the CURRENT
+ * live records. This is the explicit "adopt this machine's universe/series
+ * state as the new staleness baseline" gesture — the only thing that moves the
+ * carried baseline on a synced session. A no-op shape-wise for a local-only
+ * session (it carries no baseline), but we still allow the call so the route
+ * can offer reconcile after the user flips sync on. Returns the saved session.
+ */
+export async function reconcileStorySession(id) {
+ const session = await getStorySession(id);
+ const { hashes } = await computeCurrentHashes(session);
+ return store().queueRecordWrite(id, async () => {
+ const cur = await store().loadOne(id);
+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);
+ const next = sanitizeSession({ ...cur, sync: true, syncedHashes: hashes, updatedAt: nowIso() });
+ await store().saveOneNow(next.id, next);
+ return next;
+ });
+}
+
+/**
+ * Toggle cross-machine resume on/off for a session (#730). Turning it ON
+ * snapshots the current live hashes as the staleness baseline (so the user
+ * doesn't start out "stale against nothing"); turning it OFF drops the baseline
+ * and reverts to live-diff staleness.
+ */
+export async function setStorySessionSync(id, enabled) {
+ const session = await getStorySession(id);
+ const { hashes } = enabled ? await computeCurrentHashes(session) : { hashes: {} };
+ return store().queueRecordWrite(id, async () => {
+ const cur = await store().loadOne(id);
+ if (!cur || cur.deleted) throw makeErr(`Story Builder session not found: ${id}`, ERR_NOT_FOUND);
+ const next = sanitizeSession({
+ ...cur,
+ sync: enabled === true,
+ ...(enabled === true ? { syncedHashes: hashes } : {}),
+ updatedAt: nowIso(),
+ });
+ await store().saveOneNow(next.id, next);
+ return next;
+ });
+}
+
// ── State machine: lock / unlock ──────────────────────────────────────────
// Apply (or release) the underlying record lock that backs a step, so the
@@ -437,7 +527,16 @@ export async function lockStep(id, stepId) {
lockedAt: nowIso(),
upstreamHash: hashes[stepId],
};
- const next = sanitizeSession({ ...cur, steps, updatedAt: nowIso() });
+ // A sync-enabled session keys staleness off its carried baseline, not live
+ // records — so locking must also move the baseline to live (#730). Otherwise
+ // the just-locked step would compare its fresh `upstreamHash` against a
+ // stale `syncedHashes` entry and report itself stale on the next read.
+ const next = sanitizeSession({
+ ...cur,
+ steps,
+ ...(cur.sync === true ? { syncedHashes: { ...(cur.syncedHashes || {}), ...hashes } } : {}),
+ updatedAt: nowIso(),
+ });
await store().saveOneNow(next.id, next);
return next;
});
diff --git a/server/services/storyBuilder.test.js b/server/services/storyBuilder.test.js
index b439a65aab..169d8f5f5f 100644
--- a/server/services/storyBuilder.test.js
+++ b/server/services/storyBuilder.test.js
@@ -318,6 +318,100 @@ describe('storyBuilder — integrity / staleness', () => {
});
});
+describe('storyBuilder — sync-safe staleness (#730)', () => {
+ it('sessions are local-only (sync:false) by default and carry no baseline', async () => {
+ const s = await sb.createStorySession({ title: 'X' });
+ expect(s.sync).toBe(false);
+ expect(s.syncedHashes).toBeUndefined();
+ });
+
+ it('a peer universe edit does NOT false-positive-stale a synced session', async () => {
+ // The exact #730 case: a sync-enabled session locks a step, then a peer's
+ // universe edit lands via universe sync (modeled here as a direct
+ // out-of-band updateSeries). A LOCAL-only session would flag stale (#731);
+ // a synced session keys staleness off its carried baseline, so it does not.
+ const s = await sb.createStorySession({ title: 'X' });
+ await sb.setStorySessionSync(s.id, true);
+ await seriesSvc.updateSeries(s.seriesId, {
+ arc: { logline: 'spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },
+ });
+ await sb.lockStep(s.id, 'readerMap');
+ let view = await sb.getStorySessionView(s.id);
+ expect(view.session.sync).toBe(true);
+ expect(view.staleSteps).not.toContain('readerMap');
+ // Peer edits the upstream arc out-of-band (universe/series sync) — no
+ // session action touched the baseline, so it must NOT flag stale.
+ await seriesSvc.updateSeries(s.seriesId, {
+ arc: { logline: 'PEER-CHANGED spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },
+ locked: {},
+ });
+ view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).not.toContain('readerMap');
+ });
+
+ it('the SAME out-of-band edit DOES flag stale for a local-only session', async () => {
+ // Mirror of the case above with sync OFF — confirms we only suppressed the
+ // false-positive for synced sessions, not the genuine #731 detection.
+ const s = await sb.createStorySession({ title: 'X' });
+ await seriesSvc.updateSeries(s.seriesId, {
+ arc: { logline: 'spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },
+ });
+ await sb.lockStep(s.id, 'readerMap');
+ await seriesSvc.updateSeries(s.seriesId, {
+ arc: { logline: 'CHANGED spine', summary: 'sum', readerMap: { hooks: [{ label: 'h' }] } },
+ locked: {},
+ });
+ const view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).toContain('readerMap');
+ });
+
+ it('reconcile re-snapshots the baseline so a genuine drift surfaces', async () => {
+ const s = await sb.createStorySession({ title: 'X' });
+ await sb.setStorySessionSync(s.id, true);
+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'spine', summary: 'sum' } });
+ await sb.lockStep(s.id, 'plotArc');
+ // Drift the upstream out-of-band; synced session ignores it until reconcile.
+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'DRIFTED', summary: 'sum' }, locked: {} });
+ let view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).not.toContain('plotArc');
+ // Reconcile adopts the current live records as the new baseline. The locked
+ // step's frozen upstreamHash no longer matches → it surfaces as stale.
+ await sb.reconcileStorySession(s.id);
+ view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).toContain('plotArc');
+ });
+
+ it('turning sync OFF reverts to live-diff staleness and drops the baseline', async () => {
+ const s = await sb.createStorySession({ title: 'X' });
+ await sb.setStorySessionSync(s.id, true);
+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'spine', summary: 'sum' } });
+ await sb.lockStep(s.id, 'plotArc');
+ await seriesSvc.updateSeries(s.seriesId, { arc: { logline: 'CHANGED', summary: 'sum' }, locked: {} });
+ // Synced: not stale (baseline frozen).
+ let view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).not.toContain('plotArc');
+ // Flip sync off → baseline gone, live-diff resumes → stale.
+ const off = await sb.setStorySessionSync(s.id, false);
+ expect(off.sync).toBe(false);
+ expect(off.syncedHashes).toBeUndefined();
+ view = await sb.getStorySessionView(s.id);
+ expect(view.staleSteps).toContain('plotArc');
+ });
+
+ it('sanitizer drops bogus / unknown-step entries from a hand-edited syncedHashes', async () => {
+ const cleaned = sb.sanitizeSession({
+ id: 'stb-x', title: 'X', sync: true,
+ syncedHashes: {
+ plotArc: 'a'.repeat(64), // valid
+ readerMap: 'not-a-hash', // dropped (not 64-hex)
+ bogusStep: 'b'.repeat(64), // dropped (unknown step id)
+ },
+ });
+ expect(cleaned.sync).toBe(true);
+ expect(cleaned.syncedHashes).toEqual({ plotArc: 'a'.repeat(64) });
+ });
+});
+
describe('storyBuilder — generate delegation', () => {
it('generateStep(plotArc) persists the arc onto the series', async () => {
const s = await sb.createStorySession({ title: 'X' });