Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep Writers Room drafts, image-to-3D meshes and rig pairs whole across backups (#9982)

Adam Eivy8c21bb44eb91
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index c7b7d2f01e..d5bf446ef4 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -83,7 +83,12 @@ Admission inventory (`withBackupAssetPublication`):
| Music Video final and excerpt renders, publishing-kit builds and composition document versions (`musicVideo/render.js`, `musicVideo/excerptRender.js`, `musicVideo/publishKit.js`, `musicVideo/compositionDocument.js`) | Covered (#9982 partial): the encoder or import writes the files in place; the history entry and project row that first name them commit under one lease |
| Music Video excerpt deletion (`musicVideo/excerptService.js`) | Reference-only: the project row drops the excerpt before its unreferenced video and contact sheet are unlinked |
| Music Video performance repair, MIDI transcription and the autonomous Suno song (`musicVideo/performanceRepair.js`, `audioMidiTranscription.js`, `musicVideo/autonomousService.js`) | Covered (#9982 partial): the boundary frame or `.mid` is written first; the row that first names it (repair revision, project MIDI pointer, track render) commits under one lease, and a declined MIDI result is unlinked inside it |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports |
+| Writers Room draft bodies: new work, draft save and version snapshot (`writersRoom/local.js`) | Covered (#9982 partial): each holds one lease from the `.md` write through the manifest row that names it; a draft save replaces its body in place |
+| Writers Room tombstone prune (`writersRoom/sync.js`) and polish snapshots (`writersRoom/polish.js`) | Reference-only: the prune drops the rows before it removes their directories, and polish snapshots are JSON files no row names (revert writes the draft through the admitted save) |
+| Image-to-3D mesh completion and AR export (`imageTo3d/models.js`) | Covered (#9982 partial): the runner writes `model.glb` outside admission and only the row that marks it ready takes the lease; the AR export's file write and the row stamping it are one lease |
+| Image-to-3D record deletion (`imageTo3d/models.js`) | Reference-only: the row is soft-deleted before the render directory is removed |
+| Rigging and animation retarget (`rigging/autoSkin.js`, `rigging/retarget.js`) | Covered (#9982 partial): the pair is published into its own directory and verified outside admission; the row that first names it takes the lease |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, code animation, peer and share imports, attachments and catalog media, mood boards, archive and document imports |
| Durable replacement/deletion owners not yet classified | Outstanding (#9982) |
| Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
@@ -177,6 +182,17 @@ pruning removes only version folders no row names. The in-flight
`renderPartialFilename` / excerpt `partialFilename` marks still name a file the
encoder is writing, as before; boot recovery clears them.
+Writers Room draft saves hold one lease from the in-place `.md` replacement
+through the manifest row, so a cut never copies old prose beside a row that
+describes the new text; creating a work and snapshotting a version do the same
+for the new body file. A mesh the image-to-3D runner writes in place stays
+unreferenced until the row that marks it ready commits, and that commit takes the
+lease; a cut taken mid-render dumps the `generating` row, which restore recovers
+as failed. Rig and retarget pairs are never replaced: the verified pair sits in
+its own directory and only the row naming it takes the lease. Deleted works and
+models keep their directories until tombstone GC or the render settles, after
+their rows stopped naming them.
+
**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventories
each durable owner as `admitted`, `reference-only` or `outstanding`, and its
test fails when an `admitted` entry stops taking the lease or a module that
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 078bdeb177..d5a571a9f3 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -16,7 +16,8 @@
* for a cut to land in. A deletion that commits the row that stops naming
* its bytes before it removes them belongs here too: the dump that follows a
* cut's file copy either sees no row, or sees one whose bytes were removed
- * only after the copy finished.
+ * only after the copy finished. So does a record whose bytes no row names:
+ * the copy takes it whole or not at all, and no dumped row can dangle.
* - `outstanding`: still changes bytes and rows outside admission.
*
* A snapshot claims global file-and-row consistency only when nothing is
@@ -149,6 +150,51 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
status: 'admitted',
modules: ['services/musicVideo/autonomousService.js'],
},
+ {
+ // A draft body replaces its .md in place and the manifest row records its new
+ // hash and segment index; a new work or version writes its .md before the
+ // row that names it. Each is one workflow, holding the lease across both.
+ id: 'writers-room-draft-bodies',
+ status: 'admitted',
+ modules: ['services/writersRoom/local.js'],
+ },
+ {
+ // Tombstone GC drops the work rows first and removes their directories after.
+ id: 'writers-room-tombstone-prune',
+ status: 'reference-only',
+ modules: ['services/writersRoom/sync.js'],
+ },
+ {
+ // Polish cycle snapshots are JSON files no row names; the revert and keep
+ // gates write the draft itself through the admitted `saveDraftBody`.
+ id: 'writers-room-polish-snapshots',
+ status: 'reference-only',
+ modules: ['services/writersRoom/polish.js'],
+ },
+ {
+ // The runner writes model.glb in place while the row still says `generating`,
+ // so only the commit that marks the mesh ready takes the lease. An AR export
+ // replaces model.usdz in place, so its file write and the row stamping it are
+ // one workflow.
+ id: 'image-to-3d-render-and-ar-export',
+ status: 'admitted',
+ modules: ['services/imageTo3d/models.js'],
+ },
+ {
+ // Deleting a model soft-deletes the row, then removes its render directory
+ // once the render has settled; the directory is never removed first.
+ id: 'image-to-3d-record-deletion',
+ status: 'reference-only',
+ modules: ['services/imageTo3d/models.js'],
+ },
+ {
+ // A rig or retarget pair is published into its own `rig/<id>` or
+ // `retarget/<id>` directory, never replaced, and verified; the row that first
+ // names it commits under the lease. A half-moved pair is named by no row.
+ id: 'rigging-published-pairs',
+ status: 'admitted',
+ modules: ['services/rigging/autoSkin.js', 'services/rigging/retarget.js'],
+ },
// Classified by a code sweep (#9982) but still outside admission. Each entry
// names the modules whose file-plus-record workflows are not wrapped yet, so a
// continuation can take one and move it up. Entries are per domain, not per
@@ -189,11 +235,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/imageGen/remote.js', 'services/imageGen/variants.js', 'services/mediaSketches.js',
],
},
- {
- id: 'writers-room-drafts',
- status: 'outstanding',
- modules: ['services/writersRoom/local.js', 'services/writersRoom/sync.js', 'services/writersRoom/polish.js'],
- },
{
// Generated HTML, package import and repair, run artifacts, and the final
// stage whose soundtrack mux rewrites the MP4 before the history append.
@@ -230,11 +271,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/moodBoard/xPost.js', 'services/moodBoard/localize.js',
],
},
- {
- id: 'image-to-3d-and-rigging',
- status: 'outstanding',
- modules: ['services/imageTo3d/models.js', 'services/rigging/autoSkin.js', 'services/rigging/retarget.js'],
- },
{
// ChatGPT archive import and memory-asset deletion, YouTube ingest, and the
// digital twin and genome document stores.
diff --git a/server/services/imageTo3d/models.backupAdmission.test.js b/server/services/imageTo3d/models.backupAdmission.test.js
new file mode 100644
index 0000000000..89c6b48ee7
--- /dev/null
+++ b/server/services/imageTo3d/models.backupAdmission.test.js
@@ -0,0 +1,180 @@
+/**
+ * Image-to-3D records against a backup cut (#9982). The runner writes
+ * `model.glb` in place while the row still says `generating`, so only the commit
+ * that marks the mesh ready takes the lease; an AR export replaces `model.usdz`
+ * and stamps the row in one workflow. A cut copies files before it dumps rows,
+ * so it must never land between a file write and the row that names it.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { writeFile } = vi.hoisted(() => ({ writeFile: vi.fn(() => Promise.resolve()) }));
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { imageTo3d: '/mock/data/image-to-3d' },
+ resolveGalleryImage: vi.fn((filename) => `/mock/data/images/${filename}`),
+ ensureDir: vi.fn(() => Promise.resolve()),
+ rmGuarded: vi.fn(() => Promise.resolve()),
+ writeFileGuarded: writeFile,
+}));
+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));
+vi.mock('./targets.js', () => ({
+ DEFAULT_IMAGE_TO_3D_TARGET: 'trellis2',
+ detectHostCapabilities: vi.fn(() => ({ appleSilicon: true, unifiedMemoryGb: 128, cuda: false })),
+ resolveTarget: vi.fn(() => ({ targetId: 'trellis2', target: { id: 'trellis2', label: 'TRELLIS.2' }, available: true, reason: null })),
+ renderOptionSupportFor: vi.fn(() => null),
+}));
+vi.mock('./trellis2.js', () => ({
+ isTrellis2Installed: vi.fn(() => true),
+ runTrellis2Generate: vi.fn(() => ({ promise: Promise.resolve({}), kill: vi.fn() })),
+}));
+vi.mock('../hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));
+vi.mock('./sourceKeying.js', () => ({ prepareSourceImage: vi.fn(async () => null) }));
+vi.mock('../../lib/heavyJobClaim.js', () => ({
+ claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: {}, release: vi.fn(async () => {}) })),
+}));
+vi.mock('../localMemory.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ prepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64, blockers: [] })),
+}));
+vi.mock('./db.js', () => ({
+ listModels: vi.fn(),
+ listGeneratingModelSummaries: vi.fn(),
+ getModel: vi.fn(),
+ createModel: vi.fn(),
+ mutateModel: vi.fn(),
+ deleteModel: vi.fn(),
+ recoverInterruptedModels: vi.fn(),
+}));
+
+const store = await import('./db.js');
+const { startGeneration, saveModelUsdz } = await import('./models.js');
+const { drainActivityNotesForTests } = await import('../systemActivityNotify.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
+const usdzBytes = Buffer.from([0x50, 0x4b, 0x03, 0x04, 1, 2, 3]);
+const readyRecord = () => ({
+ id: 'image3d-example',
+ name: 'Beacon',
+ target: 'trellis2',
+ sourceImage: { filename: 'example.png' },
+ status: 'ready',
+ assetPath: '/data/image-to-3d/image3d-example/model.glb',
+ generationOperationId: null,
+ runs: [],
+});
+
+let current;
+let beforeRowWrite;
+/** `mutateModel` applies its updater to `current`, after an optional test-held pause. */
+function installStore() {
+ store.getModel.mockImplementation(async () => current);
+ store.mutateModel.mockImplementation(async (_id, mutate) => {
+ await beforeRowWrite?.();
+ const next = mutate(current);
+ if (next) current = next;
+ return current;
+ });
+}
+
+function holdRow() {
+ let reached;
+ const reachedPromise = new Promise((resolve) => { reached = resolve; });
+ let release;
+ const released = new Promise((resolve) => { release = resolve; });
+ beforeRowWrite = async () => { reached(); await released; };
+ return { reached: reachedPromise, release };
+}
+
+beforeEach(() => {
+ drainActivityNotesForTests();
+ vi.clearAllMocks();
+ current = readyRecord();
+ beforeRowWrite = null;
+ installStore();
+});
+
+describe('image-to-3D AR export and a backup cut', () => {
+ it('drains a cut behind an export that wrote the file but has not stamped its row', async () => {
+ const row = holdRow();
+ const saving = saveModelUsdz('image3d-example', usdzBytes);
+ await row.reached;
+ expect(writeFile).toHaveBeenCalledOnce();
+
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady, 'cut acquired between model.usdz and its row').toBe(false);
+ row.release();
+ (await cut)();
+ } finally {
+ row.release();
+ }
+ const saved = await saving;
+ expect(saved.usdzPath).toBe('/data/image-to-3d/image3d-example/model.usdz');
+ });
+
+ it('writes nothing while a cut is held, then exports once it closes', async () => {
+ const release = await acquireBackupSnapshotCut();
+ let settled = false;
+ const saving = saveModelUsdz('image3d-example', usdzBytes).then((value) => { settled = true; return value; });
+ try {
+ await settle();
+ expect(settled).toBe(false);
+ expect(writeFile).not.toHaveBeenCalled();
+ } finally {
+ release();
+ }
+ expect((await saving).usdzPath).toBe('/data/image-to-3d/image3d-example/model.usdz');
+ expect(writeFile).toHaveBeenCalledOnce();
+ });
+});
+
+describe('image-to-3D render completion and a backup cut', () => {
+ it('drains a cut behind the commit that marks a finished render ready', async () => {
+ current = { ...readyRecord(), status: 'draft', assetPath: null };
+ // The generation start (status flip) and the failure/progress writes are not
+ // admitted; hold only the commit that carries `status: 'ready'`.
+ let reachedReady;
+ const reached = new Promise((resolve) => { reachedReady = resolve; });
+ let finishReady;
+ const readyDone = new Promise((resolve) => { finishReady = resolve; });
+ store.mutateModel.mockImplementation(async (_id, mutate) => {
+ const next = mutate(current);
+ if (next?.status === 'ready') { reachedReady(); await readyDone; }
+ if (next) current = next;
+ return current;
+ });
+
+ await startGeneration('image3d-example');
+ await reached;
+ expect(current.status).toBe('generating');
+
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady, 'cut acquired while the ready commit was in flight').toBe(false);
+ finishReady();
+ (await cut)();
+ } finally {
+ finishReady();
+ }
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+ });
+
+ it('keeps the ready commit out of a cut: the dumped row is still generating', async () => {
+ current = { ...readyRecord(), status: 'draft', assetPath: null };
+ const release = await acquireBackupSnapshotCut();
+ try {
+ await startGeneration('image3d-example');
+ await settle();
+ // The render finished, but its commit waits for the cut to close.
+ expect(current.status).toBe('generating');
+ } finally {
+ release();
+ }
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+ });
+});
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index b2d5d89b79..a6a8eaeb8b 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -1,4 +1,5 @@
import { maintenance } from '../../lib/maintenanceAdmission.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
/**
* Image-to-3D model orchestration (issue #2952) — gallery-image lineage, target
* dispatch, guarded local render, persistence, and GLB export.
@@ -281,7 +282,11 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio
// includeDeleted + `deleted` guard: if the user deleted the record while the
// render ran, complete quietly as a no-op (the GLB on disk is orphaned — full
// kill-on-delete is tracked as a follow-up) instead of throwing NOT_FOUND.
- const finished = await store.mutateModel(id, (current) => {
+ // The runner wrote model.glb before this commit, so the row that first names
+ // the mesh as ready takes a backup lease (#9982): a cut either follows the
+ // commit, with the mesh already on disk to copy, or precedes it, and the dumped
+ // row is still `generating` and never serves the file.
+ const finished = await withBackupAssetPublication(() => store.mutateModel(id, (current) => {
if (current.deleted || current.generationOperationId !== operationId) return null;
return {
...current,
@@ -300,7 +305,7 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio
completedAt,
}),
};
- }, { includeDeleted: true });
+ }, { includeDeleted: true }));
if (finished?.status === 'ready' && !finished.deleted) noteImageTo3d('completion');
await rmGuarded(usdzDiskPath(id), { force: true })
.catch((err) => console.error(`❌ Image-to-3D stale USDZ cleanup failed for ${id}: ${err.message}`));
@@ -543,14 +548,19 @@ export async function saveModelUsdz(id, bytes) {
if (!isZipArchive(bytes)) {
throw new ServerError('Payload is not a USDZ archive', { status: 400, code: 'USDZ_INVALID' });
}
- await ensureDir(recordDir(id));
- await writeFileGuarded(usdzDiskPath(id), bytes);
- console.log(`🥽 Image-to-3D stored AR export for ${id} (${bytes.length} bytes)`);
- return store.mutateModel(id, (current) => ({
- ...current,
- usdzPath: usdzUrl(id),
- usdzGeneratedAt: new Date().toISOString(),
- }));
+ // The export replaces model.usdz in place and the row stamps it, so the pair is
+ // one backup-admitted workflow (#9982): a cut never copies the old export beside
+ // a row that names the new one.
+ return withBackupAssetPublication(async () => {
+ await ensureDir(recordDir(id));
+ await writeFileGuarded(usdzDiskPath(id), bytes);
+ console.log(`🥽 Image-to-3D stored AR export for ${id} (${bytes.length} bytes)`);
+ return store.mutateModel(id, (current) => ({
+ ...current,
+ usdzPath: usdzUrl(id),
+ usdzGeneratedAt: new Date().toISOString(),
+ }));
+ });
}
/**
diff --git a/server/services/rigging/autoSkin.js b/server/services/rigging/autoSkin.js
index a3984c543d..7cf58ef088 100644
--- a/server/services/rigging/autoSkin.js
+++ b/server/services/rigging/autoSkin.js
@@ -39,6 +39,7 @@ import { basename, join } from 'node:path';
import { rm, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile, sha256File } from '../../lib/fileUtils.js';
import { moveWithoutReplace } from '../../lib/noReplaceMove.js';
import {
@@ -275,7 +276,11 @@ export async function rigImageTo3dModel(modelId, options = {}, { run = runAutoSk
skeletonHint: options.skeletonHint,
overrides: options,
});
- return await mutateModel(modelId, (current) => ({
+ // The verified pair already sits in its own `rig/<rigId>/` directory and is
+ // never replaced, so the row that first names it takes a backup lease (#9982):
+ // a cut either follows the commit, with the pair on disk to copy, or precedes
+ // it, and the dumped row still says `rigging`.
+ return await withBackupAssetPublication(() => mutateModel(modelId, (current) => ({
...current,
rig: {
status: 'ready',
@@ -290,7 +295,7 @@ export async function rigImageTo3dModel(modelId, options = {}, { run = runAutoSk
startedAt,
completedAt: now(),
},
- }));
+ })));
} catch (error) {
await mutateModel(modelId, (current) => ({
...current,
diff --git a/server/services/rigging/retarget.js b/server/services/rigging/retarget.js
index 16a84373e0..abe1b9da79 100644
--- a/server/services/rigging/retarget.js
+++ b/server/services/rigging/retarget.js
@@ -44,6 +44,7 @@ import { basename, join } from 'node:path';
import { rm, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../../lib/fileUtils.js';
import {
publishRigArtifacts,
@@ -363,7 +364,10 @@ export async function retargetImageTo3dModel(modelId, options = {}, {
mode,
overrides: options,
});
- return await mutateModel(modelId, (current) => ({
+ // The verified pair already sits in its own `retarget/<retargetId>/` directory
+ // and is never replaced, so the row that first names it takes a backup lease
+ // (#9982), exactly like the rig row.
+ return await withBackupAssetPublication(() => mutateModel(modelId, (current) => ({
...current,
retarget: {
status: 'ready',
@@ -381,7 +385,7 @@ export async function retargetImageTo3dModel(modelId, options = {}, {
startedAt,
completedAt: now(),
},
- }));
+ })));
} catch (error) {
await mutateModel(modelId, (current) => ({
...current,
diff --git a/server/services/rigging/rigging.backupAdmission.test.js b/server/services/rigging/rigging.backupAdmission.test.js
new file mode 100644
index 0000000000..1be85a59cd
--- /dev/null
+++ b/server/services/rigging/rigging.backupAdmission.test.js
@@ -0,0 +1,114 @@
+/**
+ * Rig and retarget records against a backup cut (#9982). Each run publishes a
+ * verified GLB+report pair into its own directory, which is never replaced, and
+ * only then does the image-to-3D row come to name it. A cut copies files before
+ * it dumps rows, so the row commit takes the lease: a cut either follows the
+ * commit, with the pair already on disk to copy, or precedes it, and the dumped
+ * row is still `rigging` / `retargeting`. The worker run itself stays outside.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../imageTo3d/db.js', () => ({ getModel: vi.fn(), mutateModel: vi.fn() }));
+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));
+
+const store = await import('../imageTo3d/db.js');
+const { rigImageTo3dModel } = await import('./autoSkin.js');
+const { retargetImageTo3dModel } = await import('./retarget.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
+const MODEL_ID = 'image3d-example';
+
+const rigResult = {
+ rigId: 'rig-example',
+ assetPath: `/data/image-to-3d/${MODEL_ID}/rig/rig-example/character.rigged.glb`,
+ sha256: 'a'.repeat(64),
+ bytes: 1234,
+ summary: { boneCount: 24 },
+};
+const retargetResult = {
+ retargetId: 'retarget-example',
+ rigId: 'rig-example',
+ clip: 'Walk',
+ assetPath: `/data/image-to-3d/${MODEL_ID}/retarget/retarget-example/character.animated.glb`,
+ sha256: 'b'.repeat(64),
+ bytes: 2345,
+ summary: { clip: 'Walk' },
+};
+
+let current;
+/** Pauses only the commit that first names a published pair; the in-flight marker write is never held. */
+let hold;
+function installStore(field) {
+ store.getModel.mockImplementation(async () => current);
+ store.mutateModel.mockImplementation(async (_id, mutate) => {
+ const next = mutate(current);
+ if (field(next)?.sha256) await hold?.();
+ if (next) current = next;
+ return current;
+ });
+}
+
+const rigging = () => rigImageTo3dModel(MODEL_ID, {}, { run: async () => rigResult, now: () => '2026-01-01T00:00:00.000Z' });
+const retargeting = () => retargetImageTo3dModel(MODEL_ID, { clip: 'walk.glb' }, {
+ run: async () => retargetResult,
+ resolveClip: () => '/mock/clips/walk.glb',
+ now: () => '2026-01-01T00:00:00.000Z',
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ hold = null;
+ current = {
+ id: MODEL_ID,
+ status: 'ready',
+ assetPath: `/data/image-to-3d/${MODEL_ID}/model.glb`,
+ rig: { status: 'ready', rigId: 'rig-example', skeletonHint: 'mixamo' },
+ };
+});
+
+describe.each([
+ ['rig', rigging, (record) => record?.rig],
+ ['retarget', retargeting, (record) => record?.retarget],
+])('%s record and a backup cut', (_name, start, field) => {
+ beforeEach(() => installStore(field));
+
+ it('drains a cut behind the commit that first names the published pair', async () => {
+ let reachedRow;
+ const reached = new Promise((resolve) => { reachedRow = resolve; });
+ let finishRow;
+ const rowDone = new Promise((resolve) => { finishRow = resolve; });
+ hold = async () => { reachedRow(); await rowDone; };
+
+ const pending = start();
+ await reached;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady, 'cut acquired while the ready row was committing').toBe(false);
+ finishRow();
+ (await cut)();
+ } finally {
+ finishRow();
+ }
+ await pending;
+ expect(field(current).status).toBe('ready');
+ });
+
+ it('keeps the ready row out of a cut, so the dump still shows the in-flight state', async () => {
+ const release = await acquireBackupSnapshotCut();
+ let settled = false;
+ const pending = start().then((value) => { settled = true; return value; });
+ try {
+ await settle();
+ expect(settled).toBe(false);
+ expect(field(current).status).toMatch(/^(rigging|retargeting)$/);
+ expect(field(current).sha256).toBeUndefined();
+ } finally {
+ release();
+ }
+ await pending;
+ expect(field(current)).toMatchObject({ status: 'ready', sha256: expect.stringMatching(/^[ab]{64}$/) });
+ });
+});
diff --git a/server/services/writersRoom/local.backupAdmission.test.js b/server/services/writersRoom/local.backupAdmission.test.js
new file mode 100644
index 0000000000..dd30bf1851
--- /dev/null
+++ b/server/services/writersRoom/local.backupAdmission.test.js
@@ -0,0 +1,139 @@
+/**
+ * Writers Room draft bodies against a backup cut (#9982). A draft body is a
+ * `.md` file under `data/` and its hash, word count and version history are a
+ * manifest row, so a cut that copies files before it dumps rows must never land
+ * between the two writes: it would dump a row for prose its copy missed, or copy
+ * prose its dumped row does not describe. These run the real file backend over a
+ * temp data root and hold the row write at its commit point.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+let tempRoot;
+let beforeWorkWrite = async () => {};
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tempRoot });
+});
+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));
+// Pause the manifest row write at its commit point, after the file write before it.
+vi.mock('./store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ writersRoomStore: () => {
+ const real = actual.writersRoomStore();
+ return { ...real, writeWork: async (manifest) => { await beforeWorkWrite(manifest); return real.writeWork(manifest); } };
+ },
+ };
+});
+
+const { createWork, deleteWork, getWork, saveDraftBody, snapshotDraft, contentHash } = await import('./local.js');
+const { wrDraftPath, wrWorkDir, wrWorksDir } = await import('./_shared.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
+const bodyOf = (work, draftId = work.activeDraftVersionId) => readFileSync(wrDraftPath(work.id, draftId), 'utf-8');
+
+beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-backup-admission-'));
+ beforeWorkWrite = async () => {};
+});
+afterEach(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+});
+
+/** Start `operation` while a cut is held; it must not change a store until the cut is released. */
+async function startDuringCut(operation, assertUntouched) {
+ const release = await acquireBackupSnapshotCut();
+ let settled = false;
+ const pending = operation().then((value) => { settled = true; return value; });
+ try {
+ await settle();
+ expect(settled, 'operation ran during the cut').toBe(false);
+ assertUntouched();
+ } finally {
+ release();
+ }
+ return pending;
+}
+
+describe('Writers Room draft bodies and a backup cut', () => {
+ it('drains a cut behind a draft save that replaced the body but has not committed its row', async () => {
+ const work = await createWork({ title: 'Example Work' });
+ let reachedRow;
+ const reached = new Promise((resolve) => { reachedRow = resolve; });
+ let finishRow;
+ const rowDone = new Promise((resolve) => { finishRow = resolve; });
+ beforeWorkWrite = async () => { reachedRow(); await rowDone; };
+
+ const save = saveDraftBody(work.id, 'Fresh prose for the chapter.');
+ await reached;
+ expect(bodyOf(work)).toBe('Fresh prose for the chapter.');
+
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady, 'cut acquired between the .md write and its row').toBe(false);
+ finishRow();
+ const release = await cut;
+ // The cut sees the replaced prose AND the row that describes it.
+ const stored = await getWork(work.id);
+ expect(stored.drafts[0].contentHash).toBe(contentHash('Fresh prose for the chapter.'));
+ release();
+ } finally {
+ finishRow();
+ (await cut)();
+ }
+ await save;
+ });
+
+ it('holds a draft save until the cut closes, leaving the old prose and row in the snapshot', async () => {
+ const work = await createWork({ title: 'Example Work' });
+ await saveDraftBody(work.id, 'Original prose.');
+ const saved = await startDuringCut(
+ () => saveDraftBody(work.id, 'Replacement prose.'),
+ () => expect(bodyOf(work)).toBe('Original prose.'),
+ );
+ expect(saved.body).toBe('Replacement prose.');
+ expect(bodyOf(work)).toBe('Replacement prose.');
+ expect((await getWork(work.id)).drafts[0].contentHash).toBe(contentHash('Replacement prose.'));
+ });
+
+ it('holds a new version snapshot until the cut closes', async () => {
+ const work = await createWork({ title: 'Example Work' });
+ await saveDraftBody(work.id, 'Prose to keep.');
+ const draftsDir = join(wrWorkDir(work.id), 'drafts');
+ const manifest = await startDuringCut(
+ () => snapshotDraft(work.id, { label: 'Checkpoint' }),
+ () => expect(readdirSync(draftsDir)).toHaveLength(1),
+ );
+ expect(readdirSync(draftsDir)).toHaveLength(2);
+ expect(manifest.drafts).toHaveLength(2);
+ expect(bodyOf(work, manifest.activeDraftVersionId)).toBe('Prose to keep.');
+ });
+
+ it('holds work creation until the cut closes, so no directory exists without its row', async () => {
+ const created = await startDuringCut(
+ () => createWork({ title: 'Brand New Work' }),
+ () => expect(existsSync(wrWorksDir())).toBe(false),
+ );
+ expect(bodyOf(created)).toBe('');
+ expect((await getWork(created.id)).title).toBe('Brand New Work');
+ });
+
+ it('holds the removal of a corrupted work directory until the cut closes', async () => {
+ const work = await createWork({ title: 'Broken Work' });
+ writeFileSync(join(wrWorkDir(work.id), 'manifest.json'), '{not json');
+ await startDuringCut(
+ () => deleteWork(work.id),
+ () => expect(existsSync(wrDraftPath(work.id, work.activeDraftVersionId))).toBe(true),
+ );
+ expect(existsSync(wrWorkDir(work.id))).toBe(false);
+ });
+});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 8e005f9d05..c5880c39cb 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -19,6 +19,7 @@ import { writersRoomWorksQuerySchema } from '../../lib/pipelineValidation.js';
import { randomUUID, createHash } from 'crypto';
import { readFile } from 'fs/promises';
import { atomicWrite, ensureDir, rmGuarded } from '../../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { countWords } from '../../lib/textUtils.js';
import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';
import { renderCharacterEvolutionListForPrompt } from '../../lib/characterEvolution.js';
@@ -383,8 +384,6 @@ export async function createWork({ folderId = null, title, kind = 'short-story'
const id = `wr-work-${randomUUID()}`;
const draftId = `wr-draft-${randomUUID()}`;
const now = nowIso();
- await ensureDir(`${wrWorkDir(id)}/drafts`);
- await atomicWrite(wrDraftPath(id, draftId), '');
const manifest = {
id,
folderId,
@@ -407,7 +406,13 @@ export async function createWork({ folderId = null, title, kind = 'short-story'
createdAt: now,
updatedAt: now,
};
- await saveManifest(id, manifest);
+ // The empty first draft body and the manifest naming it are one backup-admitted
+ // workflow (#9982): a snapshot never dumps a work whose draft file its copy missed.
+ await withBackupAssetPublication(async () => {
+ await ensureDir(`${wrWorkDir(id)}/drafts`);
+ await atomicWrite(wrDraftPath(id, draftId), '');
+ await saveManifest(id, manifest);
+ });
// Auto-subscribe every writersRoomWorks-enabled peer so brand-new works (and
// their later tombstones) propagate without waiting for a reconnect (#1565).
autoSubscribeRecordToAllPeers(WRITERS_ROOM_WORK_KIND, id).catch(() => {});
@@ -627,7 +632,7 @@ export async function deleteWork(id) {
// would drop it), so it was never syncable. Hard-remove the dir so the API's
// "delete a broken work to recover" path still works (the soft-delete store
// call would otherwise no-op on the unreadable manifest and strand it).
- await rmGuarded(wrWorkDir(id), { recursive: true, force: true });
+ await withBackupAssetPublication(() => rmGuarded(wrWorkDir(id), { recursive: true, force: true }));
return { ok: true };
}
// Soft-delete tombstone (#1565) so the deletion federates and an out-of-date
@@ -652,54 +657,63 @@ function buildDraftMeta(text, base = {}) {
};
}
-export async function saveDraftBody(workId, body, { referencedIngredientIds } = {}) {
- const manifest = await getWork(workId);
- const activeId = manifest.activeDraftVersionId;
- if (!activeId) throw badRequest('Work has no active draft');
- const text = String(body ?? '');
- await atomicWrite(wrDraftPath(workId, activeId), text);
- const draftIdx = manifest.drafts.findIndex((d) => d.id === activeId);
- if (draftIdx < 0) throw notFound('Active draft');
- const meta = buildDraftMeta(text, manifest.drafts[draftIdx]);
- // Distinguish "caller omitted the field" (preserve the existing snapshot of
- // referenced ids) from "caller passed an empty array" (the prose no longer
- // mentions any linked ingredient — clear it). An absent field must NOT wipe
- // a previously-computed reference list.
- if (Array.isArray(referencedIngredientIds)) {
- meta.referencedIngredientIds = referencedIngredientIds;
- }
- manifest.drafts[draftIdx] = meta;
- manifest.updatedAt = nowIso();
- await saveManifest(workId, manifest);
- console.log(`📝 wr: saved draft ${activeId.slice(0, 14)}… (${manifest.drafts[draftIdx].wordCount} words)`);
- return { manifest, body: text };
-}
-
-export async function snapshotDraft(workId, { label } = {}) {
- const { manifest, body } = await getWorkWithBody(workId);
- const newDraftId = `wr-draft-${randomUUID()}`;
- const fromId = manifest.activeDraftVersionId;
- const fromDraft = manifest.drafts.find((d) => d.id === fromId);
- const draftLabel = label || `Draft ${manifest.drafts.length + 1}`;
- await atomicWrite(wrDraftPath(workId, newDraftId), body);
- // The new draft copies the source's body verbatim, so carry its referenced
- // ingredient ids forward — otherwise the freshly-snapshotted version would
- // render no chips (despite identical prose) until the next save re-scans.
- manifest.drafts.push(buildDraftMeta(body, {
- id: newDraftId,
- label: draftLabel,
- contentFile: `drafts/${newDraftId}.md`,
- createdAt: nowIso(),
- createdFromVersionId: fromId,
- ...(Array.isArray(fromDraft?.referencedIngredientIds)
- ? { referencedIngredientIds: fromDraft.referencedIngredientIds }
- : {}),
- }));
- manifest.activeDraftVersionId = newDraftId;
- manifest.updatedAt = nowIso();
- await saveManifest(workId, manifest);
- console.log(`📚 wr: snapshot ${draftLabel} for ${manifest.title}`);
- return manifest;
+// The draft body replaces its .md in place and the manifest row records its new
+// hash, word count and segment index, so the pair is one backup-admitted workflow
+// (#9982): a cut never copies the old prose beside a row that describes the new.
+export function saveDraftBody(workId, body, { referencedIngredientIds } = {}) {
+ return withBackupAssetPublication(async () => {
+ const manifest = await getWork(workId);
+ const activeId = manifest.activeDraftVersionId;
+ if (!activeId) throw badRequest('Work has no active draft');
+ const text = String(body ?? '');
+ await atomicWrite(wrDraftPath(workId, activeId), text);
+ const draftIdx = manifest.drafts.findIndex((d) => d.id === activeId);
+ if (draftIdx < 0) throw notFound('Active draft');
+ const meta = buildDraftMeta(text, manifest.drafts[draftIdx]);
+ // Distinguish "caller omitted the field" (preserve the existing snapshot of
+ // referenced ids) from "caller passed an empty array" (the prose no longer
+ // mentions any linked ingredient — clear it). An absent field must NOT wipe
+ // a previously-computed reference list.
+ if (Array.isArray(referencedIngredientIds)) {
+ meta.referencedIngredientIds = referencedIngredientIds;
+ }
+ manifest.drafts[draftIdx] = meta;
+ manifest.updatedAt = nowIso();
+ await saveManifest(workId, manifest);
+ console.log(`📝 wr: saved draft ${activeId.slice(0, 14)}… (${manifest.drafts[draftIdx].wordCount} words)`);
+ return { manifest, body: text };
+ });
+}
+
+// The new version's body file and the manifest row that adds it are one
+// backup-admitted workflow (#9982).
+export function snapshotDraft(workId, { label } = {}) {
+ return withBackupAssetPublication(async () => {
+ const { manifest, body } = await getWorkWithBody(workId);
+ const newDraftId = `wr-draft-${randomUUID()}`;
+ const fromId = manifest.activeDraftVersionId;
+ const fromDraft = manifest.drafts.find((d) => d.id === fromId);
+ const draftLabel = label || `Draft ${manifest.drafts.length + 1}`;
+ await atomicWrite(wrDraftPath(workId, newDraftId), body);
+ // The new draft copies the source's body verbatim, so carry its referenced
+ // ingredient ids forward — otherwise the freshly-snapshotted version would
+ // render no chips (despite identical prose) until the next save re-scans.
+ manifest.drafts.push(buildDraftMeta(body, {
+ id: newDraftId,
+ label: draftLabel,
+ contentFile: `drafts/${newDraftId}.md`,
+ createdAt: nowIso(),
+ createdFromVersionId: fromId,
+ ...(Array.isArray(fromDraft?.referencedIngredientIds)
+ ? { referencedIngredientIds: fromDraft.referencedIngredientIds }
+ : {}),
+ }));
+ manifest.activeDraftVersionId = newDraftId;
+ manifest.updatedAt = nowIso();
+ await saveManifest(workId, manifest);
+ console.log(`📚 wr: snapshot ${draftLabel} for ${manifest.title}`);
+ return manifest;
+ });
}
export async function setActiveDraft(workId, draftId) {