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: admit sprite file records before shared write queues
[._.]/ Adam Eivy17e5e36aa73e
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex f4a70383e4..79ceadb979 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -70,7 +70,7 @@ Admission inventory (`withBackupAssetPublication`):| 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 |+| 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`) | Covered (#9982 partial): shared animation/reference queues acquire admission before serialization; file-primary records and their bytes must drain together, regardless of the metadata-only sprite DB row || 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) |diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 7a28ddd268..1eae6ccbce 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -287,21 +287,14 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([],},{- // 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/walk.js', 'services/sprites/walkTrims.js',- 'services/sprites/atlas.js', 'services/sprites/assets.js', 'services/sprites/publish.js',- 'services/sprites/animationTrackWorkflow.js',- ],+ // File-primary run records, reference candidates, loop trims, selections,+ // atlas versions/current pointer and publication history also need a lease:+ // rsync can traverse their bytes before it copies a newly written pointer.+ // Shared animation/reference queues acquire before serialization; long+ // provider runs remain detached and their completion reacquires admission.+ id: 'sprite-file-record-publication',+ status: 'admitted',+ modules: ['services/sprites/animationWorkflow.js', 'services/sprites/reference.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 adiff --git a/server/services/sprites/animationWorkflow.js b/server/services/sprites/animationWorkflow.jsindex 53ec490a41..2a473aa708 100644--- a/server/services/sprites/animationWorkflow.js+++ b/server/services/sprites/animationWorkflow.js@@ -10,6 +10,7 @@* literal, and the task text — and the task text had already drifted by a clause.*/+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';import { GROK_TUI_ID } from '../../lib/grok.js';import { ServerError } from '../../lib/errorHandler.js';@@ -18,7 +19,9 @@ const animationWriteTail = createKeyCachedQueue();// Walk and every named action mutate adjacent records under one sprite. Keep// their write tail shared so a scanner approval cannot race a walk revision.-export const withAnimationWriteTail = (recordId, fn) => animationWriteTail(recordId, fn);+// File-backed run/set/atlas records are copied by the same rsync as their bytes.+// Admit before the shared queue, including callers that never update a DB row.+export const withAnimationWriteTail = (recordId, fn) => withBackupAssetPublication(() => animationWriteTail(recordId, fn));// manifest → record is the frozen chroma-key precedence for every animation// track. A run's own key is the strongest provenance rung while packaging.diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.jsindex c25ad55a48..68457cd312 100644--- a/server/services/sprites/atlas.test.js+++ b/server/services/sprites/atlas.test.js@@ -16,7 +16,7 @@ import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import sharp from 'sharp';-import { mkdir, writeFile, readFile, rm } from 'fs/promises';+import { mkdir, writeFile, readFile, readdir, rm } from 'fs/promises';import { createHash } from 'crypto';import {capSharpThreads,@@ -32,6 +32,12 @@ const restoreSharpThreads = capSharpThreads();afterAll(restoreSharpThreads);const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-atlas-test-'));+let beforeAssetWrite = async () => {};+let bypassAdmission = false;+vi.mock('../../lib/backupSnapshotBoundary.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, withBackupAssetPublication: work => bypassAdmission ? work() : actual.withBackupAssetPublication(work) };+});vi.mock('../../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();Object.assign(actual.PATHS, {@@ -39,7 +45,10 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {sprites: join(TEST_ROOT, 'sprites'),images: join(TEST_ROOT, 'images'),});- return actual;+ return { ...actual, atomicWrite: async (path, ...args) => {+ await beforeAssetWrite(path);+ return actual.atomicWrite(path, ...args);+ } };});vi.mock('../imageGen/index.js', () => ({@@ -365,6 +374,7 @@ describe('lockAllAnchors fixture materialization (#6180)', () => {});beforeEach(() => {+ beforeAssetWrite = async () => {}; bypassAdmission = false;rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });});afterAll(() => rmSync(TEST_ROOT, {@@ -965,3 +975,46 @@ it('preserves an unreadable atlas pointer until it is repaired', async () => {await writeFile(path, good);await expect(compileAtlas(id)).resolves.toMatchObject({ created: false });});++const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const backupDeferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };+const backupSettle = () => new Promise(resolve => setImmediate(resolve));++describe('atlas backup publication', () => {+ it('keeps the runtime pointer and version bytes behind an open cut', async () => {+ const id = await finalizedAmbientPlace();+ const release = await acquireBackupSnapshotCut();+ const writes = []; beforeAssetWrite = async path => { writes.push(path); };+ const work = compileAtlas(id);+ try { await backupSettle(); await backupSettle(); expect(writes).toEqual([]); }+ finally { release(); }+ const result = await work;+ expect(await readFile(join(TEST_ROOT, 'sprites', id, result.atlasPath))).toBeTruthy();+ });+ it('drains atlas bytes through the real current-pointer write', async () => {+ const id = await finalizedAmbientPlace();+ const reached = backupDeferred(); const commit = backupDeferred();+ beforeAssetWrite = async path => { if (path.endsWith('runtime/current.json')) { reached.resolve(); await commit.promise; } };+ const work = compileAtlas(id);+ await Promise.race([reached.promise, work.then(() => { throw new Error('missed pointer seam'); })]);+ let ready = false; const cut = acquireBackupSnapshotCut().then(release => { ready = true; return release; });+ try { await backupSettle(); expect(ready).toBe(false); } finally { commit.resolve(); }+ const result = await work; const release = await cut;+ try {+ const pointer = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/current.json'), 'utf8'));+ expect(pointer.atlasPath).toBe(result.atlasPath);+ expect(await readFile(join(TEST_ROOT, 'sprites', id, pointer.atlasPath))).toBeTruthy();+ } finally { release(); }+ });+ it('negative control exposes a new pointer absent from an earlier copied runtime tree', async () => {+ const id = await finalizedAmbientPlace(); bypassAdmission = true;+ const copiedAtlasPaths = await readdir(join(TEST_ROOT, 'sprites', id, 'runtime'), { recursive: true }).catch(err => { if (err.code === 'ENOENT') return []; throw err; });+ const release = await acquireBackupSnapshotCut();+ try {+ const result = await compileAtlas(id);+ const pointer = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runtime/current.json'), 'utf8'));+ expect(pointer.atlasPath).toBe(result.atlasPath);+ expect(copiedAtlasPaths).not.toContain(pointer.atlasPath.replace(/^runtime\//, ''));+ } finally { release(); }+ });+});diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 39430b5d54..b8a8f7a45a 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -92,7 +92,8 @@ const manifestRelPath = (id) => `reference/${id}-reference-set-v1.json`;// manifest and the second save would erase the first's locked state —// breaking the immutability contract. Same convention as the completion// hook's per-record queue.-const manifestWriteTail = createKeyCachedQueue();+const manifestWriteQueue = createKeyCachedQueue();+const manifestWriteTail = (recordId, fn) => withBackupAssetPublication(() => manifestWriteQueue(recordId, fn));// Phase-1 imported manifests are copied verbatim from the source pipeline// and carry repo-root paths (`art-source/sprites/<id>/reference/...`), while@@ -851,7 +852,11 @@ export async function forkSprite(sourceId, body) {* gallery into the record's reference/candidates/ with a generation sidecar.* Returns the candidate rel path (falsy result = hook logs a skip).*/-export async function attachReferenceCandidate(ctx) {+export function attachReferenceCandidate(ctx) {+ return withBackupAssetPublication(() => attachReferenceCandidateLeased(ctx));+}++async function attachReferenceCandidateLeased(ctx) {const { recordId, anchorId, filename } = ctx;const src = join(PATHS.images, filename);if (!await pathExists(src)) return null;diff --git a/server/services/sprites/spriteBackupAdmission.test.js b/server/services/sprites/spriteBackupAdmission.test.jsindex 2083612632..536d663e30 100644--- a/server/services/sprites/spriteBackupAdmission.test.js+++ b/server/services/sprites/spriteBackupAdmission.test.js@@ -456,10 +456,8 @@ describe('source-pipeline import', () => {});});-// 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.+// The DB sprite row remains metadata-only. Adjacent file-primary records still+// name bytes and are separately admitted by the shared animation/reference tails.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' });diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.jsindex 9d035e0c74..6647dac911 100644--- a/server/services/sprites/walkTrims.test.js+++ b/server/services/sprites/walkTrims.test.js@@ -10,17 +10,26 @@ import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import sharp from 'sharp';-import { writeFile, mkdir, readFile } from 'fs/promises';+import { writeFile, mkdir, readFile, readdir } from 'fs/promises';const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-trim-test-'));+let beforeAssetWrite = async () => {};+let bypassAdmission = false;+vi.mock('../../lib/backupSnapshotBoundary.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, withBackupAssetPublication: work => bypassAdmission ? work() : actual.withBackupAssetPublication(work) };+});vi.mock('../../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();Object.assign(actual.PATHS, {data: TEST_ROOT,sprites: join(TEST_ROOT, 'sprites'),});- return actual;+ return { ...actual, atomicWrite: async (path, ...args) => {+ await beforeAssetWrite(path);+ return actual.atomicWrite(path, ...args);+ } };});const runFfmpegProcess = vi.fn(async ({ args }) => {@@ -163,6 +172,7 @@ async function characterWithImportedRun(id, { manifest = 'valid', anchorPaths =}beforeEach(() => {+ beforeAssetWrite = async () => {}; bypassAdmission = false;runFfmpegProcess.mockClear();rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });});@@ -322,3 +332,46 @@ describe('saveLoopTrim', () => {.rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });});});++const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const backupDeferred = () => { let resolve; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; };+const backupSettle = () => new Promise(resolve => setImmediate(resolve));++describe('trim backup publication', () => {+ it('keeps strip, GIF and manifest behind an open cut', async () => {+ const id = await characterWithRun(newId());+ const release = await acquireBackupSnapshotCut();+ const writes = []; beforeAssetWrite = async path => { writes.push(path); };+ const work = saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });+ try { await backupSettle(); await backupSettle(); expect(writes).toEqual([]); }+ finally { release(); }+ const result = await work;+ expect(await readFile(join(TEST_ROOT, 'sprites', id, result.loop), 'utf8')).toBe('GIF89a-stub');+ });+ it('drains the real strip and GIF writes through their manifest commit', async () => {+ const id = await characterWithRun(newId());+ const reached = backupDeferred(); const commit = backupDeferred();+ beforeAssetWrite = async path => { if (path.includes('/trims/') && path.endsWith('.json')) { reached.resolve(); await commit.promise; } };+ const work = saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });+ await Promise.race([reached.promise, work.then(() => { throw new Error('missed trim seam'); })]);+ let ready = false; const cut = acquireBackupSnapshotCut().then(release => { ready = true; return release; });+ try { await backupSettle(); expect(ready).toBe(false); } finally { commit.resolve(); }+ const result = await work; const release = await cut;+ try {+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ expect(await readFile(join(TEST_ROOT, 'sprites', id, manifest.gifPath), 'utf8')).toBe('GIF89a-stub');+ expect(await readFile(join(TEST_ROOT, 'sprites', id, manifest.stripPath))).toBeTruthy();+ } finally { release(); }+ });+ it('negative control exposes a manifest absent from the earlier copied trim files', async () => {+ const id = await characterWithRun(newId()); bypassAdmission = true;+ const copiedTrimPaths = await readdir(join(TEST_ROOT, 'sprites', id, 'walk/trims')).catch(err => { if (err.code === 'ENOENT') return []; throw err; });+ const release = await acquireBackupSnapshotCut();+ try {+ const result = await saveLoopTrim(id, { runId: RUN_ID, enabledColumns: [0, 1] });+ const manifest = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, result.manifest), 'utf8'));+ expect(copiedTrimPaths).not.toContain(manifest.stripPath.split('/').at(-1));+ expect(copiedTrimPaths).not.toContain(manifest.gifPath.split('/').at(-1));+ } finally { release(); }+ });+});