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
fix: keep sprite reference locks, walk sets and source imports whole across backups (#9982)
Adam Eivy09d5585b74e4
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex d6a6e53f0f..8ec284b9f6 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -69,6 +69,8 @@ Admission inventory (`withBackupAssetPublication`):| Creative Director evaluation frames: render-completion sampling (`creativeDirector/sceneRunner.js`) and the resume pass that re-samples missing frames in place (`creativeDirector/completionHook.js`) | Covered from the first `${jobId}-fN.jpg` write through the scene row that names them (#9982 partial) || Creative Director render settlement (scene status and auto-accept, plan-step settle, seed-frame wait) and Music Video production step settlement (`musicVideo/productionService.js`) | Reference-only: these write no bytes, and the render they name was on disk before its admitted completion published || Sprite animation completion: clip copy, frame packaging and run record (`sprites/localAnimationJobHook.js`) | Covered from clip staging through the run record that names the packaged frames (#9982 partial) |+| Sprite reference lock and unlock, walk set finalization, unlock, reopen and anchor/turnaround revision, source-pipeline import, and the grok-TUI attach lanes for walk and named tracks (`sprites/reference.js`, `sprites/walk.js`, `sprites/importer.js`, `sprites/animationTrackWorkflow.js`) | Covered (#9982 partial): each holds one lease from its first byte through the sprite row it pairs with (or, for the attach lanes, the run record naming the packaged frames) |+| Sprite generation starts, reference uploads, candidate and run records, selections, loop trims, atlas compile, publication history, asset deletion and the publish-binding row (`sprites/walkTrims.js`, `atlas.js`, `assets.js`, `publish.js`, and the non-lock paths of `reference.js`, `walk.js`, `animationTrackWorkflow.js`) | Reference-only: the sprite row holds no path under `data/`, the versioned artifacts are write-once, and the record naming them is written last || Direct gallery upload, image prompt/visibility sidecar replacement, and image deletion (`imageGen/local.js`) | Covered as one file/sidecar/index workflow (#9982 partial) || Gallery image deletion's universe canon purge (`galleryImageDeletion.js`) and character reference sheet deletion (`universeCharacterSheet.js`) | Covered from file removal through the universe pointer purge (#9982 partial) || Video-history deletion, including downloaded-video deletion (`videoGen/historyOps.js`) | Covered through file/history/index removal (#9982 partial) |@@ -96,7 +98,7 @@ Admission inventory (`withBackupAssetPublication`):| ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease || YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease || Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails |+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation, image generation tails || 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) |@@ -230,6 +232,27 @@ lease. A browser render's history entry is written by the HTML-composition job(still outstanding with video generation), so the soundtrack mux holds the leaseacross its in-place install over that file, but not across the encode.+A sprite's row holds metadata and workflow state (status, the frozen chroma key,+the publish binding), never a path, and its bytes live under `data/sprites/<id>/`.+The workflows whose row mirrors a file state therefore hold one lease: reference+lock and unlock (manifest and row), walk set finalization (the set, then the+row that says `walk-complete`), and unlock, reopen and revision (remove the set,+then downgrade the row). A copy that predates the set paired with a row dumped+after it would advertise a finished walk with nothing behind it, which the write+order was chosen to prevent against a crash but cannot against a copy-then-dump+snapshot. A source-pipeline import holds a lease per subject, a character or a+props family, from its first copied byte through the row marking it imported, so a+multi-subject import lets a cut in between subjects. The grok-TUI lanes run the+terminal session outside admission and take the lease for the attach that packages+its frames and files the run, as the local completion hook does. The leases are+taken before the per-record write tail, so a workflow queued behind a long+reprocess holds its lease while it waits and can stretch a cut's drain by that+wait. Generation starts, uploads, run records, selections, loop trims, atlas+compiles, asset deletion and the publish binding take no lease: their row names no+bytes, versioned outputs are written once, and the record that names them lands+last. A cut can still copy part of a multi-file sprite tree written by one of those+workflows, as it can for any file-backed record in `data/`.+**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventorieseach durable owner as `admitted`, `reference-only` or `outstanding`, and itstest fails when an `admitted` entry stops taking the lease or a module thatdiff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 18bf8c7656..6f13cb5fe6 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -249,21 +249,43 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'reference-only',modules: ['services/codeAnimation/export.js', 'services/codeAnimation/acceptance.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- // function: a module listed here may also hold already-admitted workflows.{- // Reference lock, loop trim, atlas compile, asset delete and source import,- // plus the grok-TUI lane's attach, which runs outside the completion hook.- id: 'sprite-workflows',- status: 'outstanding',+ // Reference lock and the three unlocks (manifest plus the row's status and+ // frozen chroma key), walk set finalization (the walk set, then the row that+ // says walk-complete) and the unlock, reopen and anchor/turnaround revision+ // paths that remove it and downgrade the row, and each source-pipeline import+ // subject (the copied tree, then the row that marks it imported). The grok-TUI+ // lanes' attach (walk and named tracks) runs outside the completion hook, so+ // it takes its own lease. Every one takes the lease before the per-record+ // write tail, like the completion hook.+ id: 'sprite-reference-walk-and-import-commits',+ status: 'admitted',+ modules: [+ 'services/sprites/reference.js', 'services/sprites/walk.js', 'services/sprites/importer.js',+ 'services/sprites/animationTrackWorkflow.js',+ ],+ },+ {+ // The sprite row holds metadata and workflow state only, never a path under+ // data/ (`spriteBackupAdmission.test.js` pins its shape), so a dumped row+ // cannot dangle at bytes these workflows write, replace or delete: generation+ // starts and reference uploads, candidate and run records, selections, loop+ // trims, atlas compile and its runtime pointer, publication history, asset+ // deletion, and the publish-binding and chroma-key pin row writes. Their+ // versioned artifacts are write-once and the record naming them is written+ // last, so a copy that lists the record lists the files.+ id: 'sprite-file-only-records',+ status: 'reference-only',modules: [- 'services/sprites/reference.js', 'services/sprites/walkTrims.js', 'services/sprites/atlas.js',- 'services/sprites/assets.js', 'services/sprites/importer.js', 'services/sprites/walk.js',+ 'services/sprites/reference.js', 'services/sprites/walk.js', 'services/sprites/walkTrims.js',+ 'services/sprites/atlas.js', 'services/sprites/assets.js', 'services/sprites/publish.js','services/sprites/animationTrackWorkflow.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+ // function: a module listed here may also hold already-admitted workflows.{// Local, cloud and federated finalize, derived clips (stitch, upscale,// timeline, HTML composition), poster replacement, upload and download.diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.jsindex e250cc291e..c945493da9 100644--- a/server/services/sprites/animationTrackWorkflow.js+++ b/server/services/sprites/animationTrackWorkflow.js@@ -43,6 +43,7 @@ import { readdir } from 'fs/promises';import { randomUUID } from 'crypto';import { atomicWrite, ensureDir, pathExists, readJSONFile, sha256File, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { executeTuiRun } from '../tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';@@ -412,7 +413,11 @@ async function runTrackTuiRender(row, recordId, { runId, direction, generatedAbstimeout: GROK_TUI_TIMEOUT_MS,label: row.directional ? `sprite ${row.id} ${recordId}/${direction}` : `sprite ${row.id} ${recordId}`,}).catch((err) => console.error(`❌ sprite ${row.id} grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`));- await withAnimationWriteTail(recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs));+ // Lease before the tail, as in the completion hook (#9982): the clip, its decoded+ // frames and the run record naming them are one publication.+ await withBackupAssetPublication(() => withAnimationWriteTail(+ recordId, () => attachTrackTuiResult(row.id, recordId, runId, videoAbs),+ ));}export async function attachTrackTuiResult(trackId, recordId, runId, videoAbs) {diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.jsindex 522e85cdba..1682ad5d3c 100644--- a/server/services/sprites/importer.js+++ b/server/services/sprites/importer.js@@ -26,6 +26,7 @@ import { join, basename, dirname } from 'path';import { readdir } from 'fs/promises';import { PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile, expandHome, copyFileGuarded, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { upsertImportedRecord } from './records.js';import {spriteDir,@@ -532,7 +533,13 @@ async function importPropsFamily({ sourceRoot, familyId, srcFamilyDir }) {}/**- * Import approved sprite assets from `sourceRoot`. Options:+ * Import approved sprite assets from `sourceRoot`. Each subject (a character or a+ * props family) holds one backup admission lease from its first copied byte+ * through the record row that marks it imported (#9982): a re-import copies over+ * files an existing row already describes, and a snapshot taken halfway would+ * pair them with a row that says the import finished. A multi-subject import+ * releases the lease between subjects so a cut waits for one subject, not all.+ * Options:* - characters: limit to these character ids (default: all specs found)* - includeProps: also import game/assets/sprites/ prop families (default true)*@@ -583,7 +590,9 @@ export async function importFromSource({ sourceRoot, characters, includeProps =allSpecCharacterIds.add(characterId);if (wanted && !wanted.has(characterId)) continue;characterIds.add(characterId);- results.push(await importCharacter({ sourceRoot, characterId, spec, specPath, selection }));+ results.push(await withBackupAssetPublication(+ () => importCharacter({ sourceRoot, characterId, spec, specPath, selection }),+ ));}}@@ -595,7 +604,9 @@ export async function importFromSource({ sourceRoot, characters, includeProps =// spec-declared character, imported this run or not.if (allSpecCharacterIds.has(entry.name)) continue;if (!isValidSpriteId(entry.name)) continue;- results.push(await importPropsFamily({ sourceRoot, familyId: entry.name, srcFamilyDir: join(propsDir, entry.name) }));+ results.push(await withBackupAssetPublication(+ () => importPropsFamily({ sourceRoot, familyId: entry.name, srcFamilyDir: join(propsDir, entry.name) }),+ ));}}diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 509e915288..39430b5d54 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -31,6 +31,7 @@ import {} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { enqueueJob } from '../mediaJobQueue/index.js';import {IMAGE_GEN_MODE, resolveQueueImageMode,@@ -908,9 +909,15 @@ async function loadCandidateSidecar(candAbs) {* square and record it in the manifest as immutable evidence. Locking the* main also runs the dynamic chroma-key selection (unless the user already* pinned one on the record).+ *+ * Lock and unlock each pair the manifest with the record row's status and frozen+ * chroma key, so they hold one backup admission lease from the first byte through+ * the last write (#9982). A snapshot copies files and then dumps rows; without the+ * lease the dump could pair an older manifest with a newer row. The lease is taken+ * before the per-record tail, never inside it.*/export function lockReference(recordId, args) {- return manifestWriteTail(recordId, () => lockReferenceImpl(recordId, args));+ return withBackupAssetPublication(() => manifestWriteTail(recordId, () => lockReferenceImpl(recordId, args)));}/**@@ -922,7 +929,7 @@ export function lockReference(recordId, args) {* South is intentionally excluded because its anchor is the frozen main.*/export function unlockReferenceAnchor(recordId, args) {- return manifestWriteTail(recordId, () => unlockReferenceAnchorImpl(recordId, args));+ return withBackupAssetPublication(() => manifestWriteTail(recordId, () => unlockReferenceAnchorImpl(recordId, args)));}/**@@ -931,7 +938,7 @@ export function unlockReferenceAnchor(recordId, args) {* coordinates invalidating the south animations before this manifest reset.*/export function unlockReferenceMain(recordId) {- return manifestWriteTail(recordId, () => unlockReferenceMainImpl(recordId));+ return withBackupAssetPublication(() => manifestWriteTail(recordId, () => unlockReferenceMainImpl(recordId)));}/**@@ -944,7 +951,7 @@ export function unlockReferenceMain(recordId) {* than overwriting the evidence the user rejected.*/export function unlockReferenceTurnaround(recordId) {- return manifestWriteTail(recordId, () => unlockReferenceTurnaroundImpl(recordId));+ return withBackupAssetPublication(() => manifestWriteTail(recordId, () => unlockReferenceTurnaroundImpl(recordId)));}async function loadUnlockableReferenceAnchor(recordId, direction) {diff --git a/server/services/sprites/spriteBackupAdmission.test.js b/server/services/sprites/spriteBackupAdmission.test.jsnew file mode 100644index 0000000000..2083612632--- /dev/null+++ b/server/services/sprites/spriteBackupAdmission.test.js@@ -0,0 +1,471 @@+/**+ * Sprite workflows against a backup cut (#9982). A snapshot copies files and then+ * dumps rows, so the sprite row (status, frozen chroma key) must never be dumped+ * next to files from before the workflow that wrote it. Every workflow that pairs+ * a manifest, walk set or imported tree with its sprite row holds one admission+ * lease from its first byte through the row. The suites hold the row write at+ * its commit seam over real files: a cut requested mid-workflow must wait for+ * it, and a workflow requested mid-cut must not change a byte until the cut ends.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createHash } from 'crypto';+import { mkdir, readFile, stat, writeFile } from 'fs/promises';+import { capSharpThreads, lockAllAnchors, placeCandidate as placeCandidateFixture } from './spriteTestFixtures.js';++const restoreSharpThreads = capSharpThreads();+const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-backup-admission-'));+afterAll(() => {+ restoreSharpThreads();+ rmSync(TEST_ROOT, { recursive: true, force: true });+});++// The file record backend writes every row through atomicWrite, so holding that+// write holds the row commit.+let beforeRowWrite = async () => {};+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ Object.assign(actual.PATHS, {+ data: TEST_ROOT,+ sprites: join(TEST_ROOT, 'sprites'),+ images: join(TEST_ROOT, 'images'),+ videos: join(TEST_ROOT, 'videos'),+ });+ return {+ ...actual,+ atomicWrite: async (path, ...args) => {+ if (path.endsWith('sprite-records.json')) await beforeRowWrite();+ return actual.atomicWrite(path, ...args);+ },+ };+});++const executeTuiRun = vi.fn(() => new Promise(() => {}));+vi.mock('../tuiPromptRunner.js', () => ({ executeTuiRun: (...args) => executeTuiRun(...args) }));+vi.mock('../imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));+vi.mock('../settings.js', () => ({+ getSettings: async () => ({ imageGen: { mode: 'grok', grok: { enabled: true, grokPath: '/usr/local/bin/grok' } } }),+}));+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({+ ...await importOriginal(),+ probeVideoDuration: async () => null,+}));+const runWalkPostprocess = vi.fn(async ({ runRel, runAbs, recordId, direction, frameCount = 8, fps = 12 }) => {+ await mkdir(join(runAbs, 'generated'), { recursive: true });+ await writeFile(join(runAbs, 'generated', 'strip.png'), 'packaged-strip-bytes');+ await writeFile(join(runAbs, 'generated', 'manifest.json'), JSON.stringify({+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: recordId,+ direction,+ frameCount,+ frameRate: fps,+ stripPath: `${runRel}/generated/strip.png`,+ stripSha256: createHash('sha256').update(Buffer.from('packaged-strip-bytes')).digest('hex'),+ }));+ return {+ manifest: { frameCount, frameRate: fps },+ manifestPath: `${runRel}/generated/manifest.json`,+ stripPreview: { stripPath: `${runRel}/generated/strip.png`, frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0 },+ };+});+vi.mock('./walkPostprocess.js', async (importOriginal) => ({+ ...await importOriginal(),+ prepareWalkAnchorChromaInput: async (_anchorAbs, destAbs) => {+ await mkdir(join(destAbs, '..'), { recursive: true });+ await writeFile(destAbs, 'stub-chroma-anchor');+ return { preparation: 'composited-over-solid-chroma-matte', canvas: null };+ },+ runWalkPostprocess: (...args) => runWalkPostprocess(...args),+}));+vi.mock('../mediaJobQueue/index.js', async (importOriginal) => ({+ ...await importOriginal(),+ enqueueJob: () => ({ jobId: 'job-1', position: 0, status: 'queued' }),+}));++const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const records = await import('./records.js');+const { buildSpriteRecord } = await import('./recordsLogic.js');+const {+ lockReference, unlockReferenceAnchor, unlockReferenceMain, unlockReferenceTurnaround,+} = await import('./reference.js');+const {+ approveWalkDirection, unlockWalkSet, reopenWalkDirection, invalidateWalkDirectionForAnchorRevision,+ unlockTurnaroundReference, startWalkGeneration,+} = await import('./walk.js');+const { startTrackGeneration } = await import('./animationTrackWorkflow.js');+const { importFromSource } = await import('./importer.js');+const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');++const deferred = () => {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+};+const settle = () => new Promise((resolve) => setTimeout(resolve, 40));+const exists = (path) => stat(path).then(() => true, (error) => {+ if (error.code === 'ENOENT') return false;+ throw error;+});+const spritePath = (id, rel) => join(TEST_ROOT, 'sprites', id, rel);+const readJson = async (path) => JSON.parse(await readFile(path, 'utf8'));++/** Hold the next sprite row write; resolves `reached` once the workflow is parked on it. */+function holdRowWrite() {+ const reached = deferred();+ const commit = deferred();+ beforeRowWrite = async () => {+ beforeRowWrite = async () => {};+ reached.resolve();+ await commit.promise;+ };+ return { reached: reached.promise, commit: commit.resolve };+}++/** Request a cut and report whether it was granted yet. */+function requestCut() {+ const state = { granted: false, release: null };+ state.promise = acquireBackupSnapshotCut().then((release) => {+ state.granted = true;+ state.release = release;+ return release;+ });+ return state;+}++let seq = 0;+const newId = () => `sprite-${++seq}`;++async function lockedCharacter(directions = ['east']) {+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Example' }, id);+ await lockAllAnchors(TEST_ROOT, id, { lockReference, directions, records });+ return id;+}++async function makeCandidateRun(recordId, direction) {+ const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;+ const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'generated');+ await mkdir(runDir, { recursive: true });+ const stripName = `${recordId}-walk-${direction}-strip.png`;+ await writeFile(join(runDir, stripName), `strip-${direction}`);+ const manifestRel = `runs/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;+ await writeFile(spritePath(recordId, manifestRel), JSON.stringify({+ schemaVersion: 1,+ kind: 'deterministically-packaged-grok-walk-video',+ characterId: recordId,+ direction,+ frameRate: 12,+ frameCount: 8,+ stripPath: `runs/${runId}/generated/${stripName}`,+ stripSha256: createHash('sha256').update(Buffer.from(`strip-${direction}`)).digest('hex'),+ }));+ await writeFile(spritePath(recordId, `runs/${runId}/animation-run.json`), JSON.stringify({+ schemaVersion: 1,+ kind: 'grok-game-animation-frames-run',+ status: 'candidate',+ id: runId,+ characterId: recordId,+ direction,+ chromaKey: '#FF00FF',+ createdAt: new Date().toISOString(),+ postprocessManifest: manifestRel,+ sourceVideoPath: `runs/${runId}/generated/source-video.mp4`,+ stripPreview: { stripPath: `runs/${runId}/generated/${stripName}`, frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0 },+ }));+ return runId;+}++const approveDirections = async (id, directions) => {+ for (const direction of directions) {+ // eslint-disable-next-line no-await-in-loop -- each approval rewrites the shared selection file+ await approveWalkDirection(id, { direction, runId: await makeCandidateRun(id, direction) });+ }+};++async function finalizedCharacter() {+ const id = await lockedCharacter(ANCHOR_DIRECTIONS);+ await approveDirections(id, SPRITE_DIRECTIONS);+ expect((await records.getRecord(id)).status).toBe('walk-complete');+ return id;+}++beforeEach(() => {+ beforeRowWrite = async () => {};+ executeTuiRun.mockReset();+ executeTuiRun.mockImplementation(() => new Promise(() => {}));+ runWalkPostprocess.mockClear();+});++/**+ * One in-flight workflow, parked after its files changed and before its row+ * commits: a cut requested now must wait for the workflow and only then be+ * granted, so the dump that follows the file copy sees the finished pair.+ */+async function expectCutDrainsWorkflow({ start, filesChanged, committed }) {+ const hold = holdRowWrite();+ const running = start();+ running.catch(() => {}); // surfaced by the await below; never left unhandled if an assertion throws first+ let cut;+ try {+ await Promise.race([hold.reached, running.then(() => { throw new Error('workflow ended before its row write'); })]);+ await filesChanged();+ cut = requestCut();+ await settle();+ expect(cut.granted).toBe(false);+ hold.commit();+ // A workflow may take a second lease after the first (a revision, then the+ // unlock); it is admitted again only once the cut is released.+ await cut.promise;+ await committed();+ } finally {+ hold.commit();+ cut?.promise.then((release) => release(), () => {});+ }+ await running;+}++/** A workflow requested during a cut must change no byte until the cut is released. */+async function expectWorkflowWaitsOutCut({ start, untouched, applied }) {+ const release = await acquireBackupSnapshotCut();+ let running;+ try {+ running = start();+ running.catch(() => {});+ await settle();+ await untouched();+ } finally {+ release();+ }+ await running;+ await applied();+}++describe('reference lock and unlock', () => {+ it('drains an in-flight turnaround lock before a cut is granted', async () => {+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Example' }, id);+ const candidate = await placeCandidateFixture(TEST_ROOT, id, 'turnaround', 'turnaround-candidate-01.png');+ await expectCutDrainsWorkflow({+ start: () => lockReference(id, { target: 'turnaround', candidate }),+ // The lock writes the frozen sheet first; the manifest names it only after the row.+ filesChanged: async () => {+ expect(await exists(spritePath(id, `reference/${id}-turnaround-v1.png`))).toBe(true);+ expect(await exists(spritePath(id, `reference/${id}-reference-set-v1.json`))).toBe(false);+ },+ committed: async () => {+ const manifest = await readJson(spritePath(id, `reference/${id}-reference-set-v1.json`));+ expect(manifest.turnaround.locked).toBe(true);+ expect((await records.getRecord(id)).status).toBe('reference');+ },+ });+ });++ it('writes no locked sheet while a cut is active', async () => {+ const id = newId();+ await records.createRecord({ kind: 'character', name: 'Example' }, id);+ const candidate = await placeCandidateFixture(TEST_ROOT, id, 'turnaround', 'turnaround-candidate-01.png');+ await expectWorkflowWaitsOutCut({+ start: () => lockReference(id, { target: 'turnaround', candidate }),+ untouched: async () => {+ expect(await exists(spritePath(id, `reference/${id}-turnaround-v1.png`))).toBe(false);+ expect((await records.getRecord(id)).status).toBe('draft');+ },+ applied: async () => {+ expect(await exists(spritePath(id, `reference/${id}-turnaround-v1.png`))).toBe(true);+ expect((await records.getRecord(id)).status).toBe('reference');+ },+ });+ });++ // The unlocks write the row first, then the manifest, so a cut parked on the row+ // still sees a locked manifest; the lease keeps the dump from pairing that+ // manifest with the already-downgraded row.+ it.each([+ ['anchor', (id) => unlockReferenceAnchor(id, { direction: 'east' }), (m) => m.anchors.find((a) => a.direction === 'east').status],+ ['main', (id) => unlockReferenceMain(id), (m) => (m.mainReference.locked ? 'locked' : 'pending')],+ ['turnaround', (id) => unlockReferenceTurnaround(id), (m) => (m.turnaround.locked ? 'locked' : 'pending')],+ ])('keeps a %s unlock whole across a cut', async (_name, unlock, manifestState) => {+ const id = await lockedCharacter(['east']);+ const manifestPath = (recordId) => spritePath(recordId, `reference/${recordId}-reference-set-v1.json`);+ const before = (await records.getRecord(id)).updatedAt;+ await new Promise((resolve) => setTimeout(resolve, 5)); // a distinct updatedAt millisecond+ await expectCutDrainsWorkflow({+ start: () => unlock(id),+ filesChanged: async () => expect(manifestState(await readJson(manifestPath(id)))).toBe('locked'),+ committed: async () => {+ expect(manifestState(await readJson(manifestPath(id)))).toBe('pending');+ expect((await records.getRecord(id)).updatedAt).not.toBe(before);+ },+ });+ const second = await lockedCharacter(['east']);+ const secondBefore = (await records.getRecord(second)).updatedAt;+ await expectWorkflowWaitsOutCut({+ start: () => unlock(second),+ untouched: async () => {+ expect(manifestState(await readJson(manifestPath(second)))).toBe('locked');+ expect((await records.getRecord(second)).updatedAt).toBe(secondBefore);+ },+ applied: async () => expect(manifestState(await readJson(manifestPath(second)))).toBe('pending'),+ });+ });+});++describe('walk set finalization and revision', () => {+ // Finalizing writes the walk set before the row, so a snapshot could pair a copy+ // without the set with a row that says walk-complete — the state its write order+ // exists to prevent.+ it('keeps the eighth approval whole across a cut', async () => {+ const id = await lockedCharacter(ANCHOR_DIRECTIONS);+ await approveDirections(id, SPRITE_DIRECTIONS.slice(0, 7));+ const last = SPRITE_DIRECTIONS[7];+ const runId = await makeCandidateRun(id, last);+ const walkSet = spritePath(id, `walk/${id}-walk-set-v1.json`);+ await expectCutDrainsWorkflow({+ start: () => approveWalkDirection(id, { direction: last, runId }),+ filesChanged: async () => expect(await exists(walkSet)).toBe(true),+ committed: async () => expect((await records.getRecord(id)).status).toBe('walk-complete'),+ });+ });++ it('writes no walk set while a cut is active', async () => {+ const id = await lockedCharacter(ANCHOR_DIRECTIONS);+ await approveDirections(id, SPRITE_DIRECTIONS.slice(0, 7));+ const last = SPRITE_DIRECTIONS[7];+ const runId = await makeCandidateRun(id, last);+ const walkSet = spritePath(id, `walk/${id}-walk-set-v1.json`);+ await expectWorkflowWaitsOutCut({+ start: () => approveWalkDirection(id, { direction: last, runId }),+ untouched: async () => {+ expect(await exists(walkSet)).toBe(false);+ expect((await records.getRecord(id)).status).toBe('reference-complete');+ },+ applied: async () => expect(await exists(walkSet)).toBe(true),+ });+ });++ // Each of these removes the finalized set and then downgrades the row: a snapshot+ // that copied the set earlier must not dump the downgraded row.+ it.each([+ ['unlockWalkSet', (id) => unlockWalkSet(id, { acknowledgeNoClips: true })],+ ['reopenWalkDirection', (id) => reopenWalkDirection(id, { direction: 'east', acknowledgeNoClips: true })],+ ['invalidateWalkDirectionForAnchorRevision', (id) => invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' })],+ ['unlockTurnaroundReference', (id) => unlockTurnaroundReference(id)],+ ])('keeps %s whole across a cut', async (_name, workflow) => {+ const id = await finalizedCharacter();+ const walkSet = spritePath(id, `walk/${id}-walk-set-v1.json`);+ await expectCutDrainsWorkflow({+ start: () => workflow(id),+ filesChanged: async () => expect(await exists(walkSet)).toBe(false),+ committed: async () => expect((await records.getRecord(id)).status).not.toBe('walk-complete'),+ });+ const second = await finalizedCharacter();+ await expectWorkflowWaitsOutCut({+ start: () => workflow(second),+ untouched: async () => {+ expect(await exists(spritePath(second, `walk/${second}-walk-set-v1.json`))).toBe(true);+ expect((await records.getRecord(second)).status).toBe('walk-complete');+ },+ applied: async () => expect(await exists(spritePath(second, `walk/${second}-walk-set-v1.json`))).toBe(false),+ });+ });+});++describe('grok TUI attach lane', () => {+ // The terminal session runs outside admission and writes the clip itself; the+ // attach that packages its frames and files the run record is the publication.+ it.each([+ ['walk', (id) => startWalkGeneration(id, { direction: 'east' })],+ ['scanner track', (id) => startTrackGeneration('scanner', id, { direction: 'east' })],+ ])('packages a %s clip and files its run only outside a cut', async (_name, start) => {+ const id = await lockedCharacter(['east']);+ const clipWritten = deferred();+ const sessionEnds = deferred();+ executeTuiRun.mockImplementationOnce(async ({ workspacePath }) => {+ await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');+ clipWritten.resolve();+ await sessionEnds.promise;+ });+ const { runId } = await start(id);+ await clipWritten.promise;+ const runStatus = async () => (await readJson(spritePath(id, `runs/${runId}/animation-run.json`))).status;++ const release = await acquireBackupSnapshotCut();+ try {+ sessionEnds.resolve();+ await settle();+ expect(runWalkPostprocess).not.toHaveBeenCalled();+ expect(await runStatus()).toBe('rendering');+ } finally {+ release();+ }+ await vi.waitFor(async () => expect(await runStatus()).toBe('candidate'));+ expect(runWalkPostprocess).toHaveBeenCalledOnce();+ });+});++describe('source-pipeline import', () => {+ const sourceRoot = () => join(TEST_ROOT, 'source-pipeline');+ // A character subject carries a spec; a props family is a directory of atlas images.+ const SUBJECTS = [+ {+ name: 'character',+ async write(id) {+ await mkdir(join(sourceRoot(), 'art-pipeline', 'characters'), { recursive: true });+ await writeFile(+ join(sourceRoot(), 'art-pipeline', 'characters', `${id}.json`),+ JSON.stringify({ characterId: id, displayName: 'Example Importee' }),+ );+ },+ imported: (id) => spritePath(id, 'character-spec.json'),+ },+ {+ name: 'props family',+ async write(id) {+ await mkdir(join(sourceRoot(), 'game', 'assets', 'sprites', id), { recursive: true });+ await writeFile(join(sourceRoot(), 'game', 'assets', 'sprites', id, 'props.png'), 'synthetic atlas');+ },+ imported: (id) => spritePath(id, 'atlas/props.png'),+ },+ ];+ const run = (id) => importFromSource({ sourceRoot: sourceRoot(), characters: [id], includeProps: true });++ it.each(SUBJECTS)('drains an in-flight $name import before a cut is granted', async ({ write, imported }) => {+ const id = newId();+ await write(id);+ await expectCutDrainsWorkflow({+ start: () => run(id),+ filesChanged: async () => expect(await exists(imported(id))).toBe(true),+ committed: async () => expect((await records.getRecord(id)).status).toBe('imported'),+ });+ });++ it.each(SUBJECTS)('copies no $name file while a cut is active', async ({ write, imported }) => {+ const id = newId();+ await write(id);+ await expectWorkflowWaitsOutCut({+ start: () => run(id),+ untouched: async () => {+ expect(await exists(imported(id))).toBe(false);+ expect(await records.getRecord(id)).toBeNull();+ },+ applied: async () => expect((await records.getRecord(id)).status).toBe('imported'),+ });+ });+});++// The file-only sprite workflows (loop trims, atlas compile and publication history,+// asset deletion, run records and selections) are classified reference-only in+// `backupAssetOwners.js` because the sprite row names none of their bytes. This+// pins that premise: a row field that holds a data/ path forces a reclassification.+describe('sprite row contents', () => {+ it('holds metadata and workflow state only, never a data/ path', () => {+ const record = buildSpriteRecord({ name: 'Example', kind: 'character' }, { id: 'example', now: '2026-01-01T00:00:00.000Z' });+ expect(Object.keys(record).sort()).toEqual([+ 'chromaKey', 'createdAt', 'deleted', 'deletedAt', 'id', 'imageMode', 'imageModelId', 'importedFrom',+ 'kind', 'name', 'notes', 'publishBinding', 'spec', 'status', 'updatedAt',+ ]);+ });+});diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex a6ccaeb713..9f7fe53d13 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -26,6 +26,7 @@ import {ensureDir, atomicWrite, readJSONFile, pathExists, sha256File, rmGuarded,} from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { executeTuiRun } from '../tuiPromptRunner.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { getSettings } from '../settings.js';@@ -1137,7 +1138,9 @@ async function runWalkTuiRender(recordId, { runId, direction, grokPath, task, ge}).catch((err) => {console.error(`❌ sprite walk grok-tui run failed ${recordId}/${runId}: ${err?.message || err}`);});- await walkWriteTail(recordId, () => attachTuiWalkResult(recordId, runId, videoAbs));+ // The lease comes first, like the completion hook's: the clip grok wrote, the+ // decoded frames and the run record naming them are one publication (#9982).+ await withBackupAssetPublication(() => walkWriteTail(recordId, () => attachTuiWalkResult(recordId, runId, videoAbs)));}/**@@ -1608,7 +1611,7 @@ export async function getWalkSourceFrames(recordId, runId, { extract = false } =* walk-complete — after which the set is immutable.*/export function approveWalkDirection(recordId, args) {- return walkWriteTail(recordId, () => approveWalkDirectionImpl(recordId, args));+ return withBackupAssetPublication(() => walkWriteTail(recordId, () => approveWalkDirectionImpl(recordId, args)));}/**@@ -1632,7 +1635,7 @@ export function approveWalkDirection(recordId, args) {* REGENERATE the set can say so.*/export function unlockWalkSet(recordId, { acknowledgeNoClips = false } = {}) {- return walkWriteTail(recordId, () => unlockWalkSetImpl(recordId, { acknowledgeNoClips }));+ return withBackupAssetPublication(() => walkWriteTail(recordId, () => unlockWalkSetImpl(recordId, { acknowledgeNoClips })));}/**@@ -1899,7 +1902,9 @@ async function unlockWalkSetImpl(recordId, { acknowledgeNoClips = false } = {})* anchor can provide its fresh-render recovery.*/export function reopenWalkDirection(recordId, { direction, acknowledgeNoClips = false }) {- return walkWriteTail(recordId, () => reopenWalkDirectionImpl(recordId, direction, { acknowledgeNoClips }));+ return withBackupAssetPublication(() => walkWriteTail(+ recordId, () => reopenWalkDirectionImpl(recordId, direction, { acknowledgeNoClips }),+ ));}/**@@ -1911,7 +1916,9 @@ export function reopenWalkDirection(recordId, { direction, acknowledgeNoClips =* stays on disk; only its approval pointer is removed.*/export function invalidateWalkDirectionForAnchorRevision(recordId, { direction }) {- return walkWriteTail(recordId, () => invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction));+ return withBackupAssetPublication(() => walkWriteTail(+ recordId, () => invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction),+ ));}/**@@ -2005,7 +2012,7 @@ export async function unlockTurnaroundReference(recordId) {}function invalidateWalkForTurnaroundRevision(recordId) {- return walkWriteTail(recordId, async () => {+ return withBackupAssetPublication(() => walkWriteTail(recordId, async () => {const invalidated = [];for (const direction of SPRITE_DIRECTIONS) {if (await invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction)) {@@ -2013,7 +2020,7 @@ function invalidateWalkForTurnaroundRevision(recordId) {}}return invalidated;- });+ }));}async function invalidateWalkDirectionForAnchorRevisionImpl(recordId, direction) {